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.
- package/.claude/settings.json +7 -7
- package/CHANGELOG.md +25 -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,108 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Hook SessionStart — imprime status do framework no início da sessão.
|
|
4
|
+
*
|
|
5
|
+
* Roda uma vez por sessão. Lê specs em aberto + handoffs pendentes do universal.db.
|
|
6
|
+
* Output vai para additionalContext (carregado pelo Claude no system).
|
|
7
|
+
*
|
|
8
|
+
* Regra de ouro: este hook nunca pode derrubar a sessão. Todo acesso a SQLite é
|
|
9
|
+
* lazy e envolto em try/catch — sem `node_modules`, degrada para o modo só-specs
|
|
10
|
+
* em vez de abortar (ADR-0021).
|
|
11
|
+
*
|
|
12
|
+
* A saúde do núcleo vem de `lib/core/health.mjs` — zero heurística local (SPEC-009). O hook tinha
|
|
13
|
+
* a sua, e ela mentia: um `catch { return null }` colapsava "sem node_modules", "ABI incompatível"
|
|
14
|
+
* e "banco ausente" no mesmo `null`, e então prescrevia `npm install` — que não recompila binário
|
|
15
|
+
* nativo. Quem seguisse o conselho do próprio framework não consertava nada.
|
|
16
|
+
*/
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
import { runChecks } from "../lib/core/health.js";
|
|
21
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
22
|
+
const __dirname = path.dirname(__filename);
|
|
23
|
+
const root = path.resolve(__dirname, '..');
|
|
24
|
+
function safeReadDir(p) { try {
|
|
25
|
+
return fs.readdirSync(p);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return [];
|
|
29
|
+
} }
|
|
30
|
+
function listSpecs() {
|
|
31
|
+
const specsDir = path.join(root, 'specs');
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const slug of safeReadDir(specsDir)) {
|
|
34
|
+
if (slug.startsWith('_') || slug.startsWith('.'))
|
|
35
|
+
continue;
|
|
36
|
+
const specPath = path.join(specsDir, slug, 'spec.md');
|
|
37
|
+
if (!fs.existsSync(specPath))
|
|
38
|
+
continue;
|
|
39
|
+
const c = fs.readFileSync(specPath, 'utf8');
|
|
40
|
+
const m = c.match(/-\s*\*\*Status\*\*:\s*([a-z]+)/i);
|
|
41
|
+
out.push({ slug, status: m ? m[1] : 'unknown' });
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
/** Handoffs só fazem sentido com a memória de pé — daí o `memoriaOk` do caller. */
|
|
46
|
+
async function openHandoffs() {
|
|
47
|
+
try {
|
|
48
|
+
const { getWorkspaceDbPath } = await import("../lib/workspace.js");
|
|
49
|
+
const { default: Database } = await import('better-sqlite3');
|
|
50
|
+
const db = new Database(getWorkspaceDbPath(), { readonly: true });
|
|
51
|
+
const rows = db.prepare(`SELECT id, from_agent, to_agent, intent, spec_slug FROM handoffs WHERE status='open' ORDER BY id DESC LIMIT 10`).all();
|
|
52
|
+
db.close();
|
|
53
|
+
return rows;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Nunca lança e nunca trava a sessão: o hook reporta, o `tools:doctor` é que é gate. Se a própria
|
|
61
|
+
* lib de health não carregar, seguimos com o resto do briefing em vez de abortar (ADR-0021).
|
|
62
|
+
*/
|
|
63
|
+
async function coreHealth() {
|
|
64
|
+
try {
|
|
65
|
+
return await runChecks({ scope: 'runtime' });
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
(async function main() {
|
|
72
|
+
const specs = listSpecs();
|
|
73
|
+
const health = await coreHealth();
|
|
74
|
+
const problemas = health.filter((c) => c.status === 'fail' || c.status === 'warn');
|
|
75
|
+
const memoriaOk = !health.some((c) => c.status === 'fail');
|
|
76
|
+
const handoffs = memoriaOk ? await openHandoffs() : [];
|
|
77
|
+
const lines = ['<framework-status>'];
|
|
78
|
+
lines.push(`Framework: forja (SDD + orquestração)`);
|
|
79
|
+
if (problemas.length) {
|
|
80
|
+
lines.push('');
|
|
81
|
+
for (const p of problemas) {
|
|
82
|
+
const icone = p.status === 'fail' ? '✖' : '⚠';
|
|
83
|
+
lines.push(`${icone} ${p.title}: ${p.detail}`);
|
|
84
|
+
if (p.fix)
|
|
85
|
+
lines.push(` corrigir: ${p.fix}`);
|
|
86
|
+
}
|
|
87
|
+
lines.push(' raio-x completo: `npm run tools:doctor`');
|
|
88
|
+
}
|
|
89
|
+
if (specs.length) {
|
|
90
|
+
lines.push('\nSpecs ativas:');
|
|
91
|
+
for (const s of specs)
|
|
92
|
+
lines.push(` - ${s.slug} [${s.status}]`);
|
|
93
|
+
}
|
|
94
|
+
if (handoffs.length) {
|
|
95
|
+
lines.push('\nHandoffs em aberto:');
|
|
96
|
+
for (const h of handoffs)
|
|
97
|
+
lines.push(` - #${h.id} ${h.from_agent} → ${h.to_agent} (${h.intent}) ${h.spec_slug || ''}`);
|
|
98
|
+
}
|
|
99
|
+
lines.push('\nFluxo SDD: `npm run spec:new|plan|tasks|check`');
|
|
100
|
+
lines.push('Handoff: `node scripts/agent-router.mjs append <json>`');
|
|
101
|
+
lines.push('</framework-status>');
|
|
102
|
+
process.stdout.write(JSON.stringify({
|
|
103
|
+
hookSpecificOutput: {
|
|
104
|
+
hookEventName: 'SessionStart',
|
|
105
|
+
additionalContext: lines.join('\n'),
|
|
106
|
+
},
|
|
107
|
+
}));
|
|
108
|
+
})();
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Hook UserPromptSubmit — injeção opcional de smart-context.
|
|
4
|
+
*
|
|
5
|
+
* Protocolo:
|
|
6
|
+
* - stdin: JSON com { prompt, session_id, ... }
|
|
7
|
+
* - stdout: JSON com { hookSpecificOutput: { hookEventName, additionalContext } } ou vazio
|
|
8
|
+
*
|
|
9
|
+
* Dois caminhos de injeção:
|
|
10
|
+
* 1. Slug de spec detectado no prompt (specs/<slug>/ existe) → injeta pack
|
|
11
|
+
* task-mode montado do filesystem (spec + plan + tasks + runbook GSD).
|
|
12
|
+
* Ligado por padrão; desligue com FRAMEWORK_HOOK_INJECT=0. A economia não
|
|
13
|
+
* depende da IA obedecer a instrução: o contexto certo chega sozinho.
|
|
14
|
+
* 2. TRIGGER_KEYWORDS genéricos → pack global (mission/standards/ADRs).
|
|
15
|
+
* Continua opt-in via FRAMEWORK_HOOK_INJECT=1.
|
|
16
|
+
*
|
|
17
|
+
* Defaults conservadores (não bloqueia, não atrasa):
|
|
18
|
+
* - Limite duro de bytes (configurável em .memoryrc.json -> hooks.userPromptCap)
|
|
19
|
+
* - Cache por hash do prompt em /tmp/framework-hook-cache/
|
|
20
|
+
* - Sem SQLite no hot path (o Context Engineer faz FTS5 quando convocado)
|
|
21
|
+
*/
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Hook UserPromptSubmit — injeção opcional de smart-context.
|
|
4
|
+
*
|
|
5
|
+
* Protocolo:
|
|
6
|
+
* - stdin: JSON com { prompt, session_id, ... }
|
|
7
|
+
* - stdout: JSON com { hookSpecificOutput: { hookEventName, additionalContext } } ou vazio
|
|
8
|
+
*
|
|
9
|
+
* Dois caminhos de injeção:
|
|
10
|
+
* 1. Slug de spec detectado no prompt (specs/<slug>/ existe) → injeta pack
|
|
11
|
+
* task-mode montado do filesystem (spec + plan + tasks + runbook GSD).
|
|
12
|
+
* Ligado por padrão; desligue com FRAMEWORK_HOOK_INJECT=0. A economia não
|
|
13
|
+
* depende da IA obedecer a instrução: o contexto certo chega sozinho.
|
|
14
|
+
* 2. TRIGGER_KEYWORDS genéricos → pack global (mission/standards/ADRs).
|
|
15
|
+
* Continua opt-in via FRAMEWORK_HOOK_INJECT=1.
|
|
16
|
+
*
|
|
17
|
+
* Defaults conservadores (não bloqueia, não atrasa):
|
|
18
|
+
* - Limite duro de bytes (configurável em .memoryrc.json -> hooks.userPromptCap)
|
|
19
|
+
* - Cache por hash do prompt em /tmp/framework-hook-cache/
|
|
20
|
+
* - Sem SQLite no hot path (o Context Engineer faz FTS5 quando convocado)
|
|
21
|
+
*/
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
import process from 'node:process';
|
|
25
|
+
import crypto from 'node:crypto';
|
|
26
|
+
import { fileURLToPath } from 'node:url';
|
|
27
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
28
|
+
const __dirname = path.dirname(__filename);
|
|
29
|
+
const root = path.resolve(__dirname, '..');
|
|
30
|
+
const TRIGGER_KEYWORDS = [
|
|
31
|
+
'implement', 'implementa', 'implementar',
|
|
32
|
+
'refator', 'refactor',
|
|
33
|
+
'criar feature', 'nova feature',
|
|
34
|
+
'spec:', 'plan:', 'tasks:',
|
|
35
|
+
'arquitet', 'architect',
|
|
36
|
+
];
|
|
37
|
+
const DEFAULT_CAP_BYTES = 4000;
|
|
38
|
+
function exitSilent() {
|
|
39
|
+
process.exit(0);
|
|
40
|
+
}
|
|
41
|
+
function readStdin() {
|
|
42
|
+
try {
|
|
43
|
+
return fs.readFileSync(0, 'utf8');
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return '';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function loadConfig() {
|
|
50
|
+
try {
|
|
51
|
+
const cfg = JSON.parse(fs.readFileSync(path.join(root, '.memoryrc.json'), 'utf8'));
|
|
52
|
+
return cfg.hooks || {};
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return {};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function keywordTriggered(prompt) {
|
|
59
|
+
if (process.env.FRAMEWORK_HOOK_INJECT !== '1')
|
|
60
|
+
return false;
|
|
61
|
+
if (!prompt)
|
|
62
|
+
return false;
|
|
63
|
+
const lower = prompt.toLowerCase();
|
|
64
|
+
return TRIGGER_KEYWORDS.some(kw => lower.includes(kw));
|
|
65
|
+
}
|
|
66
|
+
// Slugs de spec do framework (specs/<slug>/spec.md). Slugs curtos (<4 chars)
|
|
67
|
+
// ficam de fora para evitar falso positivo em palavras comuns.
|
|
68
|
+
function listSpecSlugs() {
|
|
69
|
+
const dir = path.join(root, 'specs');
|
|
70
|
+
try {
|
|
71
|
+
return fs.readdirSync(dir, { withFileTypes: true })
|
|
72
|
+
.filter(e => e.isDirectory() && !e.name.startsWith('_') && e.name.length >= 4)
|
|
73
|
+
.filter(e => fs.existsSync(path.join(dir, e.name, 'spec.md')))
|
|
74
|
+
.map(e => e.name);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function detectSlug(prompt) {
|
|
81
|
+
if (!prompt || process.env.FRAMEWORK_HOOK_INJECT === '0')
|
|
82
|
+
return null;
|
|
83
|
+
const lower = prompt.toLowerCase();
|
|
84
|
+
// Slug mais longo primeiro: "forja-core-v2" ganha de "forja-core".
|
|
85
|
+
const slugs = listSpecSlugs().sort((a, b) => b.length - a.length);
|
|
86
|
+
return slugs.find(s => lower.includes(s)) || null;
|
|
87
|
+
}
|
|
88
|
+
function cacheKey(prompt) {
|
|
89
|
+
return crypto.createHash('sha1').update(prompt).digest('hex').slice(0, 16);
|
|
90
|
+
}
|
|
91
|
+
function getCached(key) {
|
|
92
|
+
const f = path.join('/tmp/framework-hook-cache', `${key}.txt`);
|
|
93
|
+
if (!fs.existsSync(f))
|
|
94
|
+
return null;
|
|
95
|
+
const stat = fs.statSync(f);
|
|
96
|
+
if (Date.now() - stat.mtimeMs > 30 * 60 * 1000)
|
|
97
|
+
return null; // 30min TTL
|
|
98
|
+
return fs.readFileSync(f, 'utf8');
|
|
99
|
+
}
|
|
100
|
+
function setCached(key, content) {
|
|
101
|
+
const dir = '/tmp/framework-hook-cache';
|
|
102
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
103
|
+
fs.writeFileSync(path.join(dir, `${key}.txt`), content);
|
|
104
|
+
}
|
|
105
|
+
// Pack task-mode de uma spec: o contexto mínimo-suficiente para trabalhar
|
|
106
|
+
// naquela feature, sem carregar memory/ inteira.
|
|
107
|
+
function buildTaskContext(slug, capBytes) {
|
|
108
|
+
const pieces = [];
|
|
109
|
+
const candidates = [
|
|
110
|
+
[`specs/${slug}/spec.md`, 4000],
|
|
111
|
+
[`specs/${slug}/plan.md`, 2500],
|
|
112
|
+
[`specs/${slug}/tasks.md`, 2500],
|
|
113
|
+
[`.context/gsd-${slug}.md`, 1500],
|
|
114
|
+
];
|
|
115
|
+
for (const [rel, sliceCap] of candidates) {
|
|
116
|
+
try {
|
|
117
|
+
const c = fs.readFileSync(path.join(root, rel), 'utf8');
|
|
118
|
+
pieces.push(`### ${rel}\n\n${c.slice(0, sliceCap)}`);
|
|
119
|
+
}
|
|
120
|
+
catch { /* arquivo ainda não existe nesta fase do pipeline */ }
|
|
121
|
+
}
|
|
122
|
+
if (!pieces.length)
|
|
123
|
+
return null;
|
|
124
|
+
const header = `Spec detectada no prompt: **${slug}**. Pack task-mode injetado ` +
|
|
125
|
+
`(ADR-0009). Para mais contexto: \`npm run query:universal -- "<termo>"\`.`;
|
|
126
|
+
let out = `<forja-task-context slug="${slug}">\n${header}\n\n` +
|
|
127
|
+
pieces.join('\n\n---\n\n') + '\n</forja-task-context>';
|
|
128
|
+
if (out.length > capBytes)
|
|
129
|
+
out = out.slice(0, capBytes) + '\n[…truncado…]';
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
function buildContext(prompt, capBytes) {
|
|
133
|
+
// Estratégia simples: cabeça das ADRs + index global. FTS5 dirigido por prompt seria ideal,
|
|
134
|
+
// mas evitamos abrir SQLite no hot path do hook. O Context Engineer faz isso quando convocado.
|
|
135
|
+
const pieces = [];
|
|
136
|
+
const candidates = [
|
|
137
|
+
'memory/00-global/mission.md',
|
|
138
|
+
'memory/00-global/standards.md',
|
|
139
|
+
'AGENTS.md',
|
|
140
|
+
'specs/README.md',
|
|
141
|
+
];
|
|
142
|
+
for (const rel of candidates) {
|
|
143
|
+
try {
|
|
144
|
+
const c = fs.readFileSync(path.join(root, rel), 'utf8');
|
|
145
|
+
pieces.push(`### ${rel}\n\n${c}`);
|
|
146
|
+
}
|
|
147
|
+
catch { /* ignore */ }
|
|
148
|
+
}
|
|
149
|
+
// ADRs mais recentes
|
|
150
|
+
const adrDir = path.join(root, 'memory/90-decisions');
|
|
151
|
+
if (fs.existsSync(adrDir)) {
|
|
152
|
+
const adrs = fs.readdirSync(adrDir).filter(f => f.match(/^\d{4}-/)).sort().slice(-3);
|
|
153
|
+
for (const a of adrs) {
|
|
154
|
+
try {
|
|
155
|
+
const c = fs.readFileSync(path.join(adrDir, a), 'utf8');
|
|
156
|
+
pieces.push(`### memory/90-decisions/${a}\n\n${c.slice(0, 800)}`);
|
|
157
|
+
}
|
|
158
|
+
catch { /* ignore */ }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
let out = '<framework-context>\n' + pieces.join('\n\n---\n\n') + '\n</framework-context>';
|
|
162
|
+
if (out.length > capBytes)
|
|
163
|
+
out = out.slice(0, capBytes) + '\n[…truncado…]';
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
(function main() {
|
|
167
|
+
const raw = readStdin();
|
|
168
|
+
let payload = {};
|
|
169
|
+
try {
|
|
170
|
+
payload = raw ? JSON.parse(raw) : {};
|
|
171
|
+
}
|
|
172
|
+
catch { /* tolerância */ }
|
|
173
|
+
const prompt = payload.prompt || payload.user_prompt || '';
|
|
174
|
+
const slug = detectSlug(prompt);
|
|
175
|
+
if (!slug && !keywordTriggered(prompt))
|
|
176
|
+
exitSilent();
|
|
177
|
+
const cfg = loadConfig();
|
|
178
|
+
const cap = cfg.userPromptCap || DEFAULT_CAP_BYTES;
|
|
179
|
+
const key = cacheKey(`${slug || 'kw'}:${prompt}`);
|
|
180
|
+
let ctx = getCached(key);
|
|
181
|
+
if (!ctx) {
|
|
182
|
+
ctx = (slug && buildTaskContext(slug, cap)) || (keywordTriggered(prompt) ? buildContext(prompt, cap) : null);
|
|
183
|
+
if (!ctx)
|
|
184
|
+
exitSilent();
|
|
185
|
+
setCached(key, ctx);
|
|
186
|
+
}
|
|
187
|
+
process.stdout.write(JSON.stringify({
|
|
188
|
+
hookSpecificOutput: {
|
|
189
|
+
hookEventName: 'UserPromptSubmit',
|
|
190
|
+
additionalContext: ctx,
|
|
191
|
+
},
|
|
192
|
+
}));
|
|
193
|
+
})();
|
|
@@ -1,27 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
2
|
import fs from 'node:fs';
|
|
4
3
|
import path from 'node:path';
|
|
5
4
|
import Database from 'better-sqlite3';
|
|
6
5
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { getWorkspaceDbPath, initWorkspace } from
|
|
8
|
-
|
|
6
|
+
import { getWorkspaceDbPath, initWorkspace } from "../lib/workspace.js";
|
|
9
7
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
8
|
const root = path.resolve(__dirname, '..');
|
|
11
|
-
|
|
12
9
|
function getDbPath() {
|
|
13
|
-
|
|
10
|
+
return getWorkspaceDbPath();
|
|
14
11
|
}
|
|
15
|
-
|
|
16
12
|
function ensureSchema({ silent = false } = {}) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
db.exec(`
|
|
13
|
+
initWorkspace();
|
|
14
|
+
const dbPath = getDbPath();
|
|
15
|
+
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
16
|
+
const db = new Database(dbPath, { timeout: 5000 });
|
|
17
|
+
db.pragma('busy_timeout = 5000');
|
|
18
|
+
db.pragma('journal_mode = WAL');
|
|
19
|
+
db.exec(`
|
|
25
20
|
CREATE TABLE IF NOT EXISTS spec_summaries (
|
|
26
21
|
slug TEXT PRIMARY KEY,
|
|
27
22
|
status TEXT,
|
|
@@ -53,16 +48,28 @@ function ensureSchema({ silent = false } = {}) {
|
|
|
53
48
|
updated_at TEXT NOT NULL
|
|
54
49
|
);
|
|
55
50
|
|
|
51
|
+
-- Projecao consultavel do audit trail (.context/forja-runs.jsonl), SPEC-014. O jsonl e a
|
|
52
|
+
-- fonte de verdade append-only; esta tabela e reconstruivel por audit:sync. line_hash (hash
|
|
53
|
+
-- do conteudo da linha) da idempotencia: re-sync nao duplica.
|
|
54
|
+
CREATE TABLE IF NOT EXISTS audit_runs (
|
|
55
|
+
line_hash TEXT PRIMARY KEY,
|
|
56
|
+
ts TEXT,
|
|
57
|
+
cmd TEXT,
|
|
58
|
+
args TEXT,
|
|
59
|
+
exit_code INTEGER,
|
|
60
|
+
duration_ms INTEGER
|
|
61
|
+
);
|
|
62
|
+
|
|
56
63
|
CREATE INDEX IF NOT EXISTS idx_context_runs_kind_slug ON context_runs(kind, slug);
|
|
57
64
|
CREATE INDEX IF NOT EXISTS idx_asset_catalog_type_name ON asset_catalog(type, name);
|
|
65
|
+
CREATE INDEX IF NOT EXISTS idx_audit_runs_cmd ON audit_runs(cmd);
|
|
66
|
+
CREATE INDEX IF NOT EXISTS idx_audit_runs_ts ON audit_runs(ts);
|
|
58
67
|
`);
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
68
|
+
db.close();
|
|
69
|
+
if (!silent)
|
|
70
|
+
console.log(`Schema auxiliar OK: ${getDbPath()}`);
|
|
62
71
|
}
|
|
63
|
-
|
|
64
72
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
65
|
-
|
|
73
|
+
ensureSchema();
|
|
66
74
|
}
|
|
67
|
-
|
|
68
75
|
export { ensureSchema, getDbPath };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import Database from 'better-sqlite3';
|
|
2
|
+
import { getDbPath, ensureSchema } from "./memory-schema.js";
|
|
3
|
+
ensureSchema({ silent: true });
|
|
4
|
+
const dbPath = getDbPath();
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
const query = args[0] || '';
|
|
7
|
+
const limit = Number(args[1] || 5);
|
|
8
|
+
if (!query) {
|
|
9
|
+
console.log('Uso: node scripts/query-universal-memory.js "termo de busca" [limite]');
|
|
10
|
+
process.exit(0);
|
|
11
|
+
}
|
|
12
|
+
const db = new Database(dbPath, { readonly: true });
|
|
13
|
+
const search = db.prepare(`
|
|
14
|
+
SELECT
|
|
15
|
+
n.path,
|
|
16
|
+
n.kind,
|
|
17
|
+
n.title,
|
|
18
|
+
p.name as project,
|
|
19
|
+
snippet(search_idx, 2, '>', '<', '...', 20) as snippet
|
|
20
|
+
FROM search_idx
|
|
21
|
+
JOIN memory_nodes n ON n.id = search_idx.node_id
|
|
22
|
+
LEFT JOIN projects p ON p.id = n.project_id
|
|
23
|
+
WHERE search_idx MATCH ?
|
|
24
|
+
ORDER BY rank
|
|
25
|
+
LIMIT ?
|
|
26
|
+
`);
|
|
27
|
+
try {
|
|
28
|
+
const results = search.all(query, limit);
|
|
29
|
+
if (results.length === 0) {
|
|
30
|
+
console.log(`Nenhum resultado encontrado para: "${query}"`);
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
console.log(`\nResultados para: "${query}"\n`);
|
|
34
|
+
results.forEach(r => {
|
|
35
|
+
const scope = r.project ? `[Projeto: ${r.project}]` : '[Global]';
|
|
36
|
+
console.log(`${scope} ${r.title} (${r.path})`);
|
|
37
|
+
console.log(` > ${r.snippet.replace(/\n/g, ' ')}\n`);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
catch (e) {
|
|
42
|
+
console.error('Erro na busca:', e.message);
|
|
43
|
+
}
|
|
44
|
+
db.close();
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* release-check — o gate do tarball (SPEC-010, ADR-0024).
|
|
4
|
+
*
|
|
5
|
+
* Responde a uma pergunta com evidência: **o pacote funciona na máquina de quem instala?**
|
|
6
|
+
* Empacota, instala num diretório isolado, executa os comandos e reprova se algo só funcionava
|
|
7
|
+
* porque o repo estava por perto.
|
|
8
|
+
*
|
|
9
|
+
* npm run release:check árvore suja = aviso (smoke local)
|
|
10
|
+
* npm run release:check -- --publish árvore suja = falha (prepublishOnly, CI de release)
|
|
11
|
+
*
|
|
12
|
+
* Diagnostica e autoriza; nunca publica. `npm publish` continua sendo um ato humano.
|
|
13
|
+
*/
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* release-check — o gate do tarball (SPEC-010, ADR-0024).
|
|
4
|
+
*
|
|
5
|
+
* Responde a uma pergunta com evidência: **o pacote funciona na máquina de quem instala?**
|
|
6
|
+
* Empacota, instala num diretório isolado, executa os comandos e reprova se algo só funcionava
|
|
7
|
+
* porque o repo estava por perto.
|
|
8
|
+
*
|
|
9
|
+
* npm run release:check árvore suja = aviso (smoke local)
|
|
10
|
+
* npm run release:check -- --publish árvore suja = falha (prepublishOnly, CI de release)
|
|
11
|
+
*
|
|
12
|
+
* Diagnostica e autoriza; nunca publica. `npm publish` continua sendo um ato humano.
|
|
13
|
+
*/
|
|
14
|
+
import { runReleaseChecks, worstStatus } from "../lib/core/release.js";
|
|
15
|
+
const TAG = { ok: 'OK ', warn: 'AVISO', fail: 'FALHA', skipped: '— ' };
|
|
16
|
+
async function main() {
|
|
17
|
+
const publish = process.argv.includes('--publish');
|
|
18
|
+
console.log(`\nForja release gate${publish ? ' (modo publish)' : ''}\n`);
|
|
19
|
+
console.log('Empacotando e instalando num diretório isolado — isto leva alguns instantes.\n');
|
|
20
|
+
const results = await runReleaseChecks({ publish });
|
|
21
|
+
for (const r of results) {
|
|
22
|
+
console.log(`${TAG[r.status]} ${r.id.padEnd(17)} ${r.detail}`);
|
|
23
|
+
if (r.fix)
|
|
24
|
+
console.log(` corrigir: ${r.fix}`);
|
|
25
|
+
console.log('');
|
|
26
|
+
}
|
|
27
|
+
const verdict = worstStatus(results);
|
|
28
|
+
if (verdict === 'fail') {
|
|
29
|
+
const raiz = results.filter((r) => r.status === 'fail' && r.severity === 'critical');
|
|
30
|
+
console.log(`REPROVADO — ${raiz.length} falha(s) crítica(s). O pacote não deve ser publicado.`);
|
|
31
|
+
for (const r of raiz)
|
|
32
|
+
console.log(` ${r.id}: ${r.fix || 'sem correção automática'}`);
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
if (verdict === 'warn') {
|
|
36
|
+
console.log('Aprovado com ressalvas. Nada impede o pacote de funcionar.');
|
|
37
|
+
if (!publish)
|
|
38
|
+
console.log('Para o parecer de publicação, rode com --publish.');
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
console.log('APROVADO — instalação limpa funciona.');
|
|
42
|
+
console.log('O parecer é perecível: vale para este disco, neste instante. Qualquer npm install ou');
|
|
43
|
+
console.log('edição posterior o invalida.');
|
|
44
|
+
}
|
|
45
|
+
main().catch((err) => {
|
|
46
|
+
console.error(`\nrelease-check falhou: ${err.message}`);
|
|
47
|
+
process.exit(1);
|
|
48
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* spec-cli — pipeline SDD
|
|
4
|
+
*
|
|
5
|
+
* Comandos:
|
|
6
|
+
* spec:new <feature> cria specs/<feature>/spec.md a partir do template
|
|
7
|
+
* spec:plan <feature> cria plan.md (exige spec.md aprovada)
|
|
8
|
+
* spec:tasks <feature> cria tasks.md (exige plan.md aprovado)
|
|
9
|
+
* spec:check [feature] valida 1 feature ou todas
|
|
10
|
+
*
|
|
11
|
+
* Convenções:
|
|
12
|
+
* - feature-slug em kebab-case
|
|
13
|
+
* - status na frontmatter-like "- **Status**: ..." linha 3
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* `.gitignore` ignora `/specs/*` e libera as specs do framework por allow-list. Uma spec nova
|
|
17
|
+
* nascia invisível ao git: criada, aprovada pelo check, e descartada em silêncio. A regra existia
|
|
18
|
+
* só como convenção — e convenção que depende de memória não é regra. Passa a viver no harness
|
|
19
|
+
* (ADR-0021).
|
|
20
|
+
*
|
|
21
|
+
* Puro de propósito: recebe e devolve conteúdo, para ser testável sem tocar no .gitignore real.
|
|
22
|
+
*
|
|
23
|
+
* @returns {{ changed: boolean, content: string, reason: 'added'|'already-present'|'no-block' }}
|
|
24
|
+
*/
|
|
25
|
+
export declare function addSpecToAllowlist(content: any, slug: any): {
|
|
26
|
+
changed: boolean;
|
|
27
|
+
content: any;
|
|
28
|
+
reason: string;
|
|
29
|
+
};
|