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