forjajs 1.2.0 → 1.3.1

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 +41 -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,286 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import crypto from 'node:crypto';
4
- import Database from 'better-sqlite3';
5
- import { fileURLToPath } from 'node:url';
6
- import { ensureSchema, getDbPath } from './memory-schema.mjs';
7
- import {
8
- initWorkspace,
9
- getProjectsDir,
10
- getWorkspaceSpecsDir,
11
- getWorkspaceProjectsMemoryDir,
12
- } from '../lib/workspace.mjs';
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = path.dirname(__filename);
16
- const root = path.resolve(__dirname, '..');
17
-
18
- initWorkspace();
19
- const dbPath = getDbPath();
20
- const args = process.argv.slice(2);
21
- const projectArgIndex = args.indexOf('--project');
22
- const onlyProject = projectArgIndex >= 0 ? args[projectArgIndex + 1] : null;
23
- const syncGlobal = !onlyProject || args.includes('--global');
24
- const syncProjects = !args.includes('--global') || Boolean(onlyProject);
25
-
26
- // Schema simplificado para a Memória Universal
27
- const schema = `
28
- CREATE TABLE IF NOT EXISTS projects (
29
- id INTEGER PRIMARY KEY AUTOINCREMENT,
30
- name TEXT NOT NULL UNIQUE,
31
- path TEXT NOT NULL,
32
- created_at TEXT NOT NULL
33
- );
34
-
35
- CREATE TABLE IF NOT EXISTS memory_nodes (
36
- id INTEGER PRIMARY KEY AUTOINCREMENT,
37
- project_id INTEGER, -- NULL se for global
38
- path TEXT NOT NULL UNIQUE,
39
- kind TEXT NOT NULL, -- 'global', 'project', 'domain', 'adr', 'summary'
40
- title TEXT,
41
- content TEXT NOT NULL,
42
- content_hash TEXT NOT NULL,
43
- updated_at TEXT NOT NULL,
44
- FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE
45
- );
46
-
47
- CREATE VIRTUAL TABLE IF NOT EXISTS search_idx USING fts5(
48
- node_id UNINDEXED,
49
- title,
50
- content,
51
- tokenize='porter'
52
- );
53
- `;
54
-
55
- function log(msg, level = 'info') {
56
- const prefix = { info: 'INFO', success: 'OK', warn: 'WARN', error: 'ERROR' }[level] || 'INFO';
57
- console.log(`${prefix} ${msg}`);
58
- }
59
-
60
- function ensureDir(dir) {
61
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
62
- }
63
-
64
- function walk(dir, out = []) {
65
- if (!fs.existsSync(dir)) return out;
66
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
67
- if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.memory') continue;
68
- const abs = path.join(dir, entry.name);
69
- if (entry.isDirectory()) walk(abs, out);
70
- else if (entry.isFile() && entry.name.endsWith('.md')) out.push(abs);
71
- }
72
- return out;
73
- }
74
-
75
- const dbDir = path.dirname(dbPath);
76
- ensureDir(dbDir);
77
- ensureSchema({ silent: true });
78
- const db = new Database(dbPath);
79
- db.exec(schema);
80
-
81
- const upsertProject = db.prepare('INSERT INTO projects (name, path, created_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET path=excluded.path');
82
- // RETURNING id devolve a linha realmente afetada, inserida ou atualizada.
83
- // Sem ele restaria `lastInsertRowid`, que num upsert-que-atualizou guarda o id do
84
- // último INSERT da conexão — um id alheio, e o FTS acabava indexando o conteúdo de
85
- // um documento sob o node_id de outro (ADR-0021).
86
- const upsertNode = db.prepare('INSERT INTO memory_nodes (project_id, path, kind, title, content, content_hash, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title=excluded.title, content=excluded.content, content_hash=excluded.content_hash, updated_at=excluded.updated_at RETURNING id');
87
- const getProjectId = db.prepare('SELECT id FROM projects WHERE name = ?');
88
- const deleteFts = db.prepare('DELETE FROM search_idx WHERE node_id = ?');
89
- const insertFts = db.prepare('INSERT INTO search_idx (node_id, title, content) VALUES (?, ?, ?)');
90
- const purgeFtsOrphans = db.prepare('DELETE FROM search_idx WHERE node_id NOT IN (SELECT id FROM memory_nodes)');
91
- const upsertSpecSummary = db.prepare(`
92
- INSERT INTO spec_summaries (slug, status, title, summary, source_path, updated_at)
93
- VALUES (?, ?, ?, ?, ?, ?)
94
- ON CONFLICT(slug) DO UPDATE SET
95
- status=excluded.status,
96
- title=excluded.title,
97
- summary=excluded.summary,
98
- source_path=excluded.source_path,
99
- updated_at=excluded.updated_at
100
- `);
101
- const upsertAsset = db.prepare(`
102
- INSERT INTO asset_catalog (type, name, path, summary, tags, updated_at)
103
- VALUES (?, ?, ?, ?, ?, ?)
104
- ON CONFLICT(path) DO UPDATE SET
105
- type=excluded.type,
106
- name=excluded.name,
107
- summary=excluded.summary,
108
- tags=excluded.tags,
109
- updated_at=excluded.updated_at
110
- `);
111
-
112
- const now = new Date().toISOString();
113
-
114
- function getKind(relPath) {
115
- if (relPath.startsWith('memory/00-global')) return 'global';
116
- if (relPath.includes('/design-md/') || relPath.startsWith('design-md/')) return 'design';
117
- if (relPath.includes('90-decisions')) return 'adr';
118
- if (relPath.includes('70-summaries')) return 'summary';
119
- if (relPath.includes('30-domains')) return 'domain';
120
- return 'general';
121
- }
122
-
123
- function firstHeading(content, fallback) {
124
- const match = content.match(/^#\s+(.+)$/m);
125
- return match ? match[1].trim() : fallback;
126
- }
127
-
128
- function specStatus(content) {
129
- const match = content.match(/-\s+\*\*Status\*\*:\s+([^\n]+)/);
130
- return match ? match[1].trim() : 'unknown';
131
- }
132
-
133
- function extractSection(content, heading, maxChars = 1200) {
134
- const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
135
- const re = new RegExp(`^##\\s+${escaped}\\s*\\n([\\s\\S]*?)(?=^##\\s+|$)`, 'm');
136
- const match = content.match(re);
137
- return match ? match[1].trim().slice(0, maxChars) : '';
138
- }
139
-
140
- function summarizeReadme(relPath) {
141
- const full = path.join(root, relPath);
142
- if (!fs.existsSync(full)) return null;
143
- const content = fs.readFileSync(full, 'utf8');
144
- return content.split('\n')
145
- .filter((line) => line.trim() && !line.startsWith('```'))
146
- .slice(0, 10)
147
- .join(' ')
148
- .replace(/\s+/g, ' ')
149
- .slice(0, 450);
150
- }
151
-
152
- function readJson(relPath) {
153
- const full = path.join(root, relPath);
154
- if (!fs.existsSync(full)) return null;
155
- try {
156
- return JSON.parse(fs.readFileSync(full, 'utf8'));
157
- } catch {
158
- return null;
159
- }
160
- }
161
-
162
- function syncSpecSummaries() {
163
- const specsDir = path.join(root, 'specs');
164
- if (!fs.existsSync(specsDir)) return;
165
- let count = 0;
166
- for (const entry of fs.readdirSync(specsDir, { withFileTypes: true })) {
167
- if (!entry.isDirectory() || entry.name.startsWith('_')) continue;
168
- const slug = entry.name;
169
- const rel = path.join('specs', slug, 'spec.md');
170
- const full = path.join(root, rel);
171
- if (!fs.existsSync(full)) continue;
172
- const content = fs.readFileSync(full, 'utf8');
173
- const title = firstHeading(content, slug);
174
- const status = specStatus(content);
175
- const summary = [
176
- `## Problema\n${extractSection(content, '1. Problema', 900)}`,
177
- `## Valor\n${extractSection(content, '2. Proposta de valor', 700)}`,
178
- `## AC\n${extractSection(content, '4. Criterios de aceite', 1200) || extractSection(content, '4. Critérios de aceite', 1200)}`,
179
- ].join('\n\n').slice(0, 3500);
180
- upsertSpecSummary.run(slug, status, title, summary, rel, now);
181
- count++;
182
- }
183
- log(`Spec summaries sincronizados: ${count}`, 'info');
184
- }
185
-
186
- function syncAssetCatalog() {
187
- const assets = [];
188
- const boilerRoot = path.join(root, 'boilerplates');
189
- if (fs.existsSync(boilerRoot)) {
190
- for (const entry of fs.readdirSync(boilerRoot, { withFileTypes: true })) {
191
- if (!entry.isDirectory()) continue;
192
- const rel = path.join('boilerplates', entry.name, 'README.md');
193
- const summary = summarizeReadme(rel);
194
- if (!summary) continue;
195
- const manifest = readJson(path.join('boilerplates', entry.name, 'boilerplate.manifest.json'));
196
- const tags = manifest ? [...(manifest.stack || []), ...(manifest.useCases || [])].join(',') : firstHeading(summary, entry.name);
197
- assets.push({ type: 'boilerplate', name: entry.name, path: rel, summary, tags });
198
- }
199
- }
200
- const designRoot = path.join(root, 'design-md');
201
- if (fs.existsSync(designRoot)) {
202
- for (const entry of fs.readdirSync(designRoot, { withFileTypes: true })) {
203
- if (!entry.isDirectory()) continue;
204
- const rel = path.join('design-md', entry.name, 'README.md');
205
- const summary = summarizeReadme(rel);
206
- if (!summary) continue;
207
- const manifest = readJson(path.join('design-md', entry.name, 'design.manifest.json'));
208
- const tags = manifest ? [...(manifest.surfaces || []), ...(manifest.traits || [])].join(',') : entry.name;
209
- assets.push({ type: 'design-reference', name: entry.name, path: rel, summary, tags });
210
- }
211
- }
212
- for (const asset of assets) {
213
- upsertAsset.run(asset.type, asset.name, asset.path, asset.summary, asset.tags, now);
214
- }
215
- log(`Asset catalog sincronizado: ${assets.length}`, 'info');
216
- }
217
-
218
- function syncFiles(files, projectId = null) {
219
- for (const abs of files) {
220
- const rel = path.relative(root, abs);
221
- const raw = fs.readFileSync(abs, 'utf8');
222
- const hash = crypto.createHash('sha256').update(raw).digest('hex');
223
- const titleMatch = raw.match(/^#\s+(.+)$/m);
224
- const title = titleMatch ? titleMatch[1].trim() : path.basename(rel, '.md');
225
-
226
- try {
227
- const { id: nodeId } = upsertNode.get(projectId, rel, getKind(rel), title, raw, hash, now);
228
-
229
- deleteFts.run(nodeId);
230
- insertFts.run(nodeId, title, raw);
231
- } catch (e) {
232
- log(`Erro sincronizando ${rel}: ${e.message}`, 'error');
233
- }
234
- }
235
- }
236
-
237
- // 1. Sincronizar Memória/Docs/Prompts Globais
238
- if (syncGlobal) {
239
- log('Sincronizando Memória Global...', 'info');
240
- const globalFiles = [
241
- ...walk(path.join(root, 'memory')),
242
- ...walk(path.join(root, 'docs')),
243
- ...walk(path.join(root, 'prompts')),
244
- ];
245
- syncFiles(globalFiles);
246
- syncSpecSummaries();
247
- syncAssetCatalog();
248
- }
249
-
250
- // 2. Sincronizar Projetos do Workspace
251
- const projectsDir = getProjectsDir();
252
- if (syncProjects && fs.existsSync(projectsDir)) {
253
- const projects = fs.readdirSync(projectsDir, { withFileTypes: true })
254
- .filter(e => e.isDirectory())
255
- .filter(e => !onlyProject || e.name === onlyProject);
256
- if (onlyProject && projects.length === 0) {
257
- log(`Projeto nao encontrado para sync: ${onlyProject}`, 'warn');
258
- }
259
- for (const p of projects) {
260
- log(`Sincronizando Projeto: ${p.name}...`, 'info');
261
- const projectPath = path.join(projectsDir, p.name);
262
- upsertProject.run(p.name, projectPath, now);
263
- const pid = getProjectId.get(p.name).id;
264
-
265
- // Indexa memória, documentação, spec SDD e referências de design do projeto (somente .md)
266
- const projectMemFiles = walk(path.join(projectPath, 'memory'));
267
- const projectDocsFiles = walk(path.join(projectPath, 'docs'));
268
- const projectSpecFiles = walk(path.join(getWorkspaceSpecsDir(), p.name));
269
- const projectDesignFiles = walk(path.join(projectPath, 'design-md'));
270
- syncFiles([...projectMemFiles, ...projectDocsFiles, ...projectSpecFiles, ...projectDesignFiles], pid);
271
- }
272
- }
273
-
274
- // 3. Sincronizar fichas de projetos no workspace memory/30-projects
275
- const workspaceProjectsMemoryDir = getWorkspaceProjectsMemoryDir();
276
- if (fs.existsSync(workspaceProjectsMemoryDir)) {
277
- const fichaFiles = walk(workspaceProjectsMemoryDir);
278
- syncFiles(fichaFiles);
279
- }
280
-
281
- // Nós removidos deixam linhas órfãs no FTS: matches que apontam para nada.
282
- const orphans = purgeFtsOrphans.run().changes;
283
- if (orphans) log(`Índice FTS: ${orphans} linhas órfãs removidas`, 'info');
284
-
285
- db.close();
286
- log('Sincronização Universal Concluída!', 'success');
@@ -1,203 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Token Economy Benchmark - Measure token savings from smart context
5
- *
6
- * Compara:
7
- * 1. Full context (antes) vs 3 modos (depois)
8
- * 2. Mede tamanho, tokens, tempo de geração
9
- * 3. Calcula redução %
10
- *
11
- * Uso: npm run token:benchmark
12
- */
13
-
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import ContextBuilder from '../lib/context-builder.js';
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
- /**
24
- * Estimar tokens (1KB ≈ 250 tokens, aproximação)
25
- */
26
- function estimateTokens(content) {
27
- const size = typeof content === 'number' ? content : content.length;
28
- return Math.round(size / 4); // 1 token ~= 4 bytes
29
- }
30
-
31
- /**
32
- * Formatar bytes em legível
33
- */
34
- function formatBytes(bytes) {
35
- if (bytes === 0) return '0 B';
36
- const k = 1024;
37
- const sizes = ['B', 'KB', 'MB'];
38
- const i = Math.floor(Math.log(bytes) / Math.log(k));
39
- return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
40
- }
41
-
42
- function walkMarkdown(dir, out = []) {
43
- if (!fs.existsSync(dir)) return out;
44
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
45
- if (['node_modules', '.git', '.memory', 'archive'].includes(entry.name)) continue;
46
- const abs = path.join(dir, entry.name);
47
- if (entry.isDirectory()) walkMarkdown(abs, out);
48
- else if (entry.isFile() && entry.name.endsWith('.md')) out.push(abs);
49
- }
50
- return out;
51
- }
52
-
53
- /**
54
- * Executar benchmark
55
- */
56
- async function benchmark() {
57
- console.log('Token Economy Benchmark\n');
58
-
59
- ensureSchema({ silent: true });
60
- const dbPath = getDbPath();
61
- const project = 'benchmark-project';
62
-
63
- if (!fs.existsSync(dbPath)) {
64
- console.warn('Database not found at:', dbPath);
65
- console.log(' Run: npm run memory:db:init');
66
- process.exit(1);
67
- }
68
-
69
- const builder = new ContextBuilder(root, dbPath);
70
-
71
- try {
72
- // 1. Simular contexto "antigo" (sem smart context)
73
- console.log('Scenario 1: Full Context (Baseline - No Optimization)\n');
74
-
75
- const baselineStart = Date.now();
76
- let fullContext = '';
77
-
78
- const baselineRoots = ['AGENTS.md', 'README.md', 'DOC-MAP.md', 'memory', 'docs', 'prompts', 'specs'];
79
- const baselineFiles = [];
80
- for (const rel of baselineRoots) {
81
- const abs = path.join(root, rel);
82
- if (!fs.existsSync(abs)) continue;
83
- const stat = fs.statSync(abs);
84
- if (stat.isDirectory()) walkMarkdown(abs, baselineFiles);
85
- else if (stat.isFile() && abs.endsWith('.md')) baselineFiles.push(abs);
86
- }
87
-
88
- for (const filePath of baselineFiles) {
89
- const rel = path.relative(root, filePath);
90
- const content = fs.readFileSync(filePath, 'utf8');
91
- fullContext += `\n\n## ${rel}\n${content}`;
92
- }
93
-
94
- const baselineDuration = Date.now() - baselineStart;
95
- const baselineSize = fullContext.length;
96
- const baselineTokens = estimateTokens(fullContext);
97
- const baselineCost = (baselineTokens * 0.00001).toFixed(5);
98
-
99
- console.log(` Size: ${formatBytes(baselineSize)}`);
100
- console.log(` Tokens: ${baselineTokens.toLocaleString()}`);
101
- console.log(` Files: ${baselineFiles.length}`);
102
- console.log(` Time: ${baselineDuration}ms`);
103
- console.log(` Cost: $${baselineCost}\n`);
104
-
105
- // 2. Testar 3 modos de contexto inteligente
106
- const modes = ['global', 'domain', 'task'];
107
- const results = [];
108
-
109
- for (const mode of modes) {
110
- console.log(`Scenario: ${mode.toUpperCase()} Mode\n`);
111
-
112
- const keyword = mode === 'task' ? 'architecture implementation' : '';
113
- const start = Date.now();
114
-
115
- let context = '';
116
- try {
117
- context = builder.build(mode, project, keyword);
118
- } catch (e) {
119
- console.warn(` Error building context: ${e.message}`);
120
- console.log(' Skipping this mode.\n');
121
- continue;
122
- }
123
-
124
- const duration = Date.now() - start;
125
- const size = context.length;
126
- const tokens = estimateTokens(size);
127
- const cost = (tokens * 0.00001).toFixed(5);
128
- const savings = (((baselineTokens - tokens) / baselineTokens) * 100).toFixed(1);
129
-
130
- console.log(` Size: ${formatBytes(size)}`);
131
- console.log(` Tokens: ${tokens.toLocaleString()}`);
132
- console.log(` Time: ${duration}ms`);
133
- console.log(` Cost: $${cost}`);
134
- console.log(` Savings: ${savings}% (vs baseline)\n`);
135
-
136
- results.push({
137
- mode,
138
- size,
139
- tokens,
140
- time: duration,
141
- cost: parseFloat(cost),
142
- savings: parseFloat(savings),
143
- });
144
- }
145
-
146
- // 3. Sumário
147
- console.log('Summary\n');
148
-
149
- const avgSavings =
150
- results.reduce((sum, r) => sum + r.savings, 0) / results.length;
151
- const avgTokens = results.reduce((sum, r) => sum + r.tokens, 0) / results.length;
152
- const avgCost = results.reduce((sum, r) => sum + r.cost, 0) / results.length;
153
- const bestMode = results.reduce((best, r) => (r.tokens < best.tokens ? r : best));
154
-
155
- console.log(`Baseline (Full Context)`);
156
- console.log(` Tokens: ${baselineTokens.toLocaleString()}`);
157
- console.log(` Cost: $${baselineCost}\n`);
158
-
159
- console.log(`Smart Context Average`);
160
- console.log(` Tokens: ${avgTokens.toLocaleString()}`);
161
- console.log(` Cost: $${avgCost.toFixed(5)}`);
162
- console.log(` Savings: ${avgSavings.toFixed(1)}%\n`);
163
-
164
- console.log(`Best Mode: ${bestMode.mode.toUpperCase()}`);
165
- console.log(` Tokens: ${bestMode.tokens.toLocaleString()}`);
166
- console.log(` Cost: $${bestMode.cost.toFixed(5)}`);
167
- console.log(` Savings: ${bestMode.savings.toFixed(1)}%\n`);
168
-
169
- // 4. Cálculo de ROI
170
- const monthlyRequests = 1000;
171
- const savedCostPerMonth = (baselineTokens - avgTokens) * 0.00001 * monthlyRequests;
172
-
173
- console.log('ROI Analysis (1000 requests/month)');
174
- console.log(` Baseline cost: $${(baselineTokens * 0.00001 * monthlyRequests).toFixed(2)}`);
175
- console.log(` Smart cost: $${(avgTokens * 0.00001 * monthlyRequests).toFixed(2)}`);
176
- console.log(` Monthly savings: $${savedCostPerMonth.toFixed(2)}`);
177
- console.log(` Annual savings: $${(savedCostPerMonth * 12).toFixed(2)}\n`);
178
-
179
- // 5. Recomendação
180
- console.log('Recommendation');
181
- if (avgSavings > 40) {
182
- console.log(` Deploy: ${avgSavings.toFixed(1)}% savings exceeds 40% target.`);
183
- } else if (avgSavings > 20) {
184
- console.log(` Good savings (${avgSavings.toFixed(1)}%) but optimize further.`);
185
- } else {
186
- console.log(` Savings too low (${avgSavings.toFixed(1)}%). Review strategy.`);
187
- }
188
-
189
- console.log('\nBenchmark complete.\n');
190
- } catch (e) {
191
- console.error('Benchmark error:', e.message);
192
- process.exit(1);
193
- } finally {
194
- builder.close();
195
- }
196
- }
197
-
198
- // Run if called via CLI
199
- if (import.meta.url === `file://${process.argv[1]}`) {
200
- benchmark().catch(console.error);
201
- }
202
-
203
- export { benchmark, estimateTokens };
@@ -1,132 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * tools-doctor — raio-x do núcleo (SPEC-009) e das ferramentas de processo (ADR-0018).
4
- *
5
- * Duas seções, dois contratos distintos:
6
- *
7
- * Núcleo O que impede o framework de trabalhar. Falha crítica → exit 1.
8
- * Ferramentas Binários opcionais que potencializam o harness. Ausência nunca trava.
9
- *
10
- * A separação é o ponto. Este comando auditava só as ferramentas — sobre as quais ele mesmo
11
- * dizia "o fluxo nunca trava por elas" — e era cego para tudo que trava. Quando o better-sqlite3
12
- * ficou com ABI de outra major do Node e a memória universal morreu inteira, o doctor reportou
13
- * "2/5 ferramentas disponíveis" e saiu com 0.
14
- *
15
- * Diagnostica e prescreve; não conserta. Rodar `npm rebuild` sem consentimento é a classe de
16
- * risco oposta à que este comando existe para fechar.
17
- *
18
- * Uso: node scripts/tools-doctor.mjs
19
- */
20
-
21
- import { spawnSync } from 'node:child_process';
22
-
23
- import { runChecks, worstStatus } from '../lib/core/health.mjs';
24
-
25
- const TOOLS = [
26
- {
27
- name: 'codegraph',
28
- probe: ['codegraph', ['--version']],
29
- role: 'Code intelligence: chamadores, blast radius, mapa de impacto (ADR-0017).',
30
- install: 'npm i -g @codegraph/cli',
31
- gate: 'npm run code:check / code:impact',
32
- },
33
- {
34
- name: 'gitleaks',
35
- probe: ['gitleaks', ['version']],
36
- role: 'Varredura de segredos antes de merge/release.',
37
- install: 'https://github.com/gitleaks/gitleaks (binario) ou: brew install gitleaks',
38
- gate: 'gitleaks detect --no-banner (gate de Governance)',
39
- },
40
- {
41
- name: 'ast-grep',
42
- probe: ['ast-grep', ['--version']],
43
- role: 'Busca e codemod estrutural por AST — refactor seguro do Worker.',
44
- install: 'npm i -g @ast-grep/cli (binarios: ast-grep / sg)',
45
- gate: 'ast-grep run -p "<pattern>" -r "<rewrite>"',
46
- },
47
- {
48
- name: 'lefthook',
49
- probe: ['lefthook', ['version']],
50
- role: 'Pre-commit rodando project:check / spec:check automaticamente.',
51
- install: 'npm i -g lefthook (depois: lefthook install)',
52
- gate: '.lefthook.yml (pre-commit)',
53
- },
54
- {
55
- name: 'markdownlint',
56
- probe: ['markdownlint-cli2', ['--version']],
57
- role: 'Lint da documentacao (docs e memory sao centrais aqui).',
58
- install: 'npm i -g markdownlint-cli2',
59
- gate: 'markdownlint-cli2 "docs/**/*.md"',
60
- },
61
- ];
62
-
63
- function detect(cmd, args) {
64
- const res = spawnSync(cmd, args, { encoding: 'utf8' });
65
- if (res.error && /** @type {any} */ (res.error).code === 'ENOENT') return { ok: false };
66
- const version = (res.stdout || res.stderr || '').trim().split('\n')[0] || 'instalado';
67
- return { ok: true, version };
68
- }
69
-
70
- const TAG = {
71
- ok: 'OK ',
72
- warn: 'AVISO',
73
- fail: 'FALHA',
74
- skipped: '— ',
75
- };
76
-
77
- function printCore(results) {
78
- console.log('Núcleo — o que impede o framework de trabalhar (SPEC-009)\n');
79
-
80
- for (const r of results) {
81
- console.log(`${TAG[r.status]} ${r.id.padEnd(13)} ${r.detail}`);
82
- if (r.fix) console.log(` corrigir: ${r.fix}`);
83
- console.log('');
84
- }
85
- }
86
-
87
- function printTools() {
88
- console.log('Ferramentas de processo — opcionais (ADR-0018)\n');
89
-
90
- let installed = 0;
91
- for (const tool of TOOLS) {
92
- const [cmd, args] = tool.probe;
93
- const { ok, version } = detect(cmd, args);
94
- if (ok) installed += 1;
95
- console.log(`${ok ? TAG.ok : 'FALTA'} ${tool.name.padEnd(13)} ${ok ? version : '(ausente)'}`);
96
- console.log(` papel: ${tool.role}`);
97
- console.log(` gate: ${tool.gate}`);
98
- if (!ok) console.log(` instalar: ${tool.install}`);
99
- console.log('');
100
- }
101
-
102
- console.log(`${installed}/${TOOLS.length} ferramentas disponíveis.`);
103
- console.log('Ferramentas ausentes apenas desativam seus gates — o fluxo nunca trava por elas.\n');
104
- }
105
-
106
- async function main() {
107
- console.log('\nForja doctor\n');
108
-
109
- const core = await runChecks();
110
- printCore(core);
111
- printTools();
112
-
113
- // Só o núcleo decide o exit code. Ferramenta ausente nunca reprova — o contrato do ADR-0018
114
- // é preservado à risca.
115
- const verdict = worstStatus(core);
116
-
117
- if (verdict === 'fail') {
118
- const raiz = core.filter((r) => r.status === 'fail' && r.severity === 'critical');
119
- console.log(`Núcleo quebrado — ${raiz.length} ${raiz.length === 1 ? 'falha' : 'falhas'} crítica(s).`);
120
- for (const r of raiz) console.log(` ${r.id}: ${r.fix || 'sem correção automática'}`);
121
- process.exit(1);
122
- }
123
-
124
- if (verdict === 'warn') {
125
- console.log('Núcleo operante, com ressalvas. Nada trava o fluxo.');
126
- return;
127
- }
128
-
129
- console.log('Núcleo saudável.');
130
- }
131
-
132
- main();