forjajs 1.1.6 → 1.2.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/CHANGELOG.md +37 -0
- package/README.en.md +28 -5
- package/README.md +30 -4
- package/bin/forja.mjs +3 -3
- package/boilerplates/06-clean-arch/README.md +48 -0
- package/boilerplates/06-clean-arch/WHEN-CLEAN-WHEN-LEAN.md +42 -0
- package/boilerplates/06-clean-arch/backend/package.json +43 -0
- package/boilerplates/06-clean-arch/backend/src/app.module.ts +20 -0
- package/boilerplates/06-clean-arch/backend/src/main.ts +10 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/place-order.usecase.ts +47 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/ship-order.usecase.ts +28 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/money.vo.ts +30 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order-status.vo.ts +36 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.entity.ts +85 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.repository.ts +17 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/order.orm-entity.ts +24 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/typeorm-order.repository.ts +57 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/orders.module.ts +28 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts +31 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.http.dto.ts +30 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/product.entity.ts +20 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.controller.ts +43 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.module.ts +11 -0
- package/boilerplates/06-clean-arch/backend/src/shared/result.ts +32 -0
- package/boilerplates/06-clean-arch/backend/test/orders/place-order.spec.ts +46 -0
- package/boilerplates/06-clean-arch/backend/tsconfig.json +16 -0
- package/boilerplates/06-clean-arch/boilerplate.manifest.json +43 -0
- package/boilerplates/06-clean-arch/memory/30-domains/orders/context.md +39 -0
- package/boilerplates/06-clean-arch/memory/30-domains/products/context.md +23 -0
- package/boilerplates/README.md +20 -0
- package/docs/personas/architect/README.md +4 -4
- package/docs/personas/developer/README.md +3 -3
- package/docs/personas/qa/README.md +3 -3
- package/docs/quick-reference.md +9 -9
- package/docs/structure.md +3 -3
- package/lib/core/checks.mjs +20 -3
- package/lib/core/doc-graph.mjs +231 -0
- package/lib/core/health.mjs +131 -29
- package/lib/core/registry.mjs +23 -0
- package/lib/core/release.mjs +48 -8
- package/lib/templates/harness/code-intel.mjs +2 -2
- package/memory/90-decisions/0025-coerencia-da-documentacao.md +95 -0
- package/memory/90-decisions/0027-clean-arch-calibrada.md +96 -0
- package/package.json +7 -1
- package/scripts/agent-harness.mjs +7 -5
- package/scripts/context-ops.mjs +7 -4
- package/scripts/dev.mjs +2 -2
- package/scripts/hook-guard-paths.mjs +1 -0
- package/scripts/hook-user-prompt.mjs +1 -1
- package/scripts/spec-cli.mjs +4 -3
- package/scripts/tools-doctor.mjs +1 -1
- package/specs/clean-arch-boilerplate/plan.md +137 -0
- package/specs/clean-arch-boilerplate/spec.md +121 -0
- package/specs/clean-arch-boilerplate/tasks.md +70 -0
- package/specs/coerencia-do-sistema/plan.md +155 -0
- package/specs/coerencia-do-sistema/spec.md +15 -14
- package/specs/coerencia-do-sistema/tasks.md +115 -0
- package/specs/ts-migration/plan.md +188 -0
- package/specs/ts-migration/spec.md +119 -0
- package/specs/ts-migration/tasks.md +110 -0
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/doc-graph.mjs — a documentação lida como dado.
|
|
3
|
+
*
|
|
4
|
+
* O `health.mjs` já lê código (imports, package.json, .mcp.json). Este módulo lê os `.md` que
|
|
5
|
+
* **instruem** o agente e extrai o que é verificável contra o código: comandos citados e links
|
|
6
|
+
* relativos. Leitura pura — nenhum juízo de severidade mora aqui; os checks de `health.mjs` é que
|
|
7
|
+
* julgam (SPEC-011, ADR-0025).
|
|
8
|
+
*
|
|
9
|
+
* Por que existir: o Forja é operado por agentes que executam o que a doc manda. Quando a doc e o
|
|
10
|
+
* registry divergem, o agente não erra por burrice — erra por obediência. Em 2026-07-14 uma
|
|
11
|
+
* auditoria manual achou quatro comandos fantasma no doc que ensina a economia de tokens. Nada
|
|
12
|
+
* quebrou um teste. É a classe do ADR-0021 — erra sem avisar — na camada de instrução.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Superfícies de instrução. Escaneia o que orienta o agente **agora** — não o histórico.
|
|
20
|
+
*
|
|
21
|
+
* Fora de propósito (plano §D3): `docs/archive/` (legado), `boilerplates/` (conteúdo do projeto
|
|
22
|
+
* gerado — cita comandos do projeto, não do Forja), `specs/` e `memory/` (registro histórico: uma
|
|
23
|
+
* spec ou ADR pode legitimamente citar um comando proposto ou já removido).
|
|
24
|
+
*/
|
|
25
|
+
export const DOC_SURFACES = [
|
|
26
|
+
'docs',
|
|
27
|
+
'prompts',
|
|
28
|
+
'.claude/agents',
|
|
29
|
+
'AGENTS.md',
|
|
30
|
+
'CLAUDE.md',
|
|
31
|
+
'README.md',
|
|
32
|
+
'README.en.md',
|
|
33
|
+
'DOC-MAP.md',
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
const EXCLUDED_DIRS = new Set(['archive', 'node_modules']);
|
|
37
|
+
|
|
38
|
+
/** Um comando do Forja: `forja x:y` ou `npm run x:y`, com ao menos um `:` (o discriminador, §D4). */
|
|
39
|
+
const COMMAND_RE = /(?:\bforja\s+|npm run\s+)([a-z][a-z0-9]*(?::[a-z0-9-]+)+)/g;
|
|
40
|
+
|
|
41
|
+
/** Link markdown relativo. Ignora http(s):// e âncoras puras; a âncora de um path é descartada. */
|
|
42
|
+
const LINK_RE = /\]\(([^)]+)\)/g;
|
|
43
|
+
|
|
44
|
+
function safeRead(env, file) {
|
|
45
|
+
try {
|
|
46
|
+
return env.fs.readFileSync(file, 'utf8');
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Coleta os `.md` sob uma superfície (arquivo direto ou diretório varrido, menos EXCLUDED_DIRS). */
|
|
53
|
+
function collectMarkdown(env, surface) {
|
|
54
|
+
const abs = path.join(env.root, surface);
|
|
55
|
+
const out = [];
|
|
56
|
+
|
|
57
|
+
const walk = (p) => {
|
|
58
|
+
let st;
|
|
59
|
+
try {
|
|
60
|
+
st = env.fs.statSync(p);
|
|
61
|
+
} catch {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (st.isDirectory()) {
|
|
65
|
+
let entries;
|
|
66
|
+
try {
|
|
67
|
+
entries = env.fs.readdirSync(p);
|
|
68
|
+
} catch {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
for (const entry of entries) {
|
|
72
|
+
if (EXCLUDED_DIRS.has(entry)) continue;
|
|
73
|
+
walk(path.join(p, entry));
|
|
74
|
+
}
|
|
75
|
+
} else if (p.endsWith('.md')) {
|
|
76
|
+
out.push(p);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
walk(abs);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Todos os `.md` das superfícies de instrução, caminhos relativos à raiz. */
|
|
85
|
+
export function docFiles(env) {
|
|
86
|
+
const seen = new Set();
|
|
87
|
+
for (const surface of DOC_SURFACES) {
|
|
88
|
+
for (const file of collectMarkdown(env, surface)) {
|
|
89
|
+
seen.add(path.relative(env.root, file));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return [...seen];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Comandos citados nas superfícies de instrução.
|
|
97
|
+
* @returns {{ file: string, line: number, command: string }[]}
|
|
98
|
+
*/
|
|
99
|
+
export function scanCommands(env) {
|
|
100
|
+
const hits = [];
|
|
101
|
+
for (const rel of docFiles(env)) {
|
|
102
|
+
const src = safeRead(env, path.join(env.root, rel));
|
|
103
|
+
if (src == null) continue;
|
|
104
|
+
const lines = src.split('\n');
|
|
105
|
+
lines.forEach((text, i) => {
|
|
106
|
+
for (const m of text.matchAll(COMMAND_RE)) {
|
|
107
|
+
hits.push({ file: rel, line: i + 1, command: m[1] });
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
return hits;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Links markdown relativos nas superfícies de instrução, com o alvo já resolvido à raiz.
|
|
116
|
+
* @returns {{ file: string, line: number, target: string, resolved: string }[]}
|
|
117
|
+
*/
|
|
118
|
+
export function scanLinks(env) {
|
|
119
|
+
const hits = [];
|
|
120
|
+
for (const rel of docFiles(env)) {
|
|
121
|
+
const src = safeRead(env, path.join(env.root, rel));
|
|
122
|
+
if (src == null) continue;
|
|
123
|
+
const dir = path.dirname(rel);
|
|
124
|
+
const lines = src.split('\n');
|
|
125
|
+
lines.forEach((text, i) => {
|
|
126
|
+
for (const m of text.matchAll(LINK_RE)) {
|
|
127
|
+
const raw = m[1].trim();
|
|
128
|
+
if (!raw || raw.startsWith('#')) continue; // âncora pura
|
|
129
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) continue; // http:, mailto:, etc. — externo
|
|
130
|
+
const target = raw.split('#')[0]; // descarta âncora do path
|
|
131
|
+
if (!target) continue;
|
|
132
|
+
hits.push({
|
|
133
|
+
file: rel,
|
|
134
|
+
line: i + 1,
|
|
135
|
+
target,
|
|
136
|
+
resolved: path.normalize(path.join(dir, target)),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return hits;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Extrai as keys de todo bloco `"scripts": { … }` de um fonte de gerador. */
|
|
145
|
+
function scriptKeys(source) {
|
|
146
|
+
const keys = new Set();
|
|
147
|
+
const block = source.match(/"scripts"\s*:\s*\{([\s\S]*?)\}/g);
|
|
148
|
+
if (!block) return keys;
|
|
149
|
+
for (const b of block) {
|
|
150
|
+
for (const m of b.matchAll(/"([a-z][a-z0-9]*(?::[a-z0-9-]+)+)"\s*:/g)) {
|
|
151
|
+
keys.add(m[1]);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return keys;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Todo `package.json` sob um diretório (boilerplates têm vários, aninhados). */
|
|
158
|
+
function findPackageJsons(env, dir, acc = []) {
|
|
159
|
+
let entries;
|
|
160
|
+
try {
|
|
161
|
+
entries = env.fs.readdirSync(dir);
|
|
162
|
+
} catch {
|
|
163
|
+
return acc;
|
|
164
|
+
}
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
if (EXCLUDED_DIRS.has(entry)) continue;
|
|
167
|
+
const p = path.join(dir, entry);
|
|
168
|
+
let st;
|
|
169
|
+
try {
|
|
170
|
+
st = env.fs.statSync(p);
|
|
171
|
+
} catch {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (st.isDirectory()) findPackageJsons(env, p, acc);
|
|
175
|
+
else if (entry === 'package.json') acc.push(p);
|
|
176
|
+
}
|
|
177
|
+
return acc;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Allowlist **derivada** dos comandos que pertencem ao projeto que o Forja *gera* (`start:dev`,
|
|
182
|
+
* `test:cov`, `test:e2e`, `memory:db:*`), não ao Forja. Nunca uma lista literal — uma lista manual
|
|
183
|
+
* mente no primeiro comando novo do boilerplate (a lição do `.gitignore`, SPEC-009).
|
|
184
|
+
*
|
|
185
|
+
* Duas fontes, porque o projeto gerado tem duas: os `"scripts"` inline que os **geradores** escrevem
|
|
186
|
+
* e os `package.json` dos **boilerplates**. Derivar de só uma delas produz falso positivo na outra —
|
|
187
|
+
* foi `test:e2e` (vive no boilerplate, não no gerador) que revelou isso.
|
|
188
|
+
*
|
|
189
|
+
* @returns {Set<string>}
|
|
190
|
+
*/
|
|
191
|
+
export function projectCommands(env) {
|
|
192
|
+
const commands = new Set();
|
|
193
|
+
|
|
194
|
+
// Fonte 1: blocos "scripts" inline dos geradores.
|
|
195
|
+
const genDir = path.join(env.root, 'lib', 'generators');
|
|
196
|
+
let genEntries = [];
|
|
197
|
+
try {
|
|
198
|
+
genEntries = env.fs.readdirSync(genDir);
|
|
199
|
+
} catch {
|
|
200
|
+
/* sem geradores — segue */
|
|
201
|
+
}
|
|
202
|
+
for (const entry of genEntries) {
|
|
203
|
+
if (!/\.(mjs|js)$/.test(entry)) continue;
|
|
204
|
+
const src = safeRead(env, path.join(genDir, entry));
|
|
205
|
+
if (src == null) continue;
|
|
206
|
+
for (const key of scriptKeys(src)) commands.add(key);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Fonte 2: package.json dos boilerplates.
|
|
210
|
+
for (const pkgPath of findPackageJsons(env, path.join(env.root, 'boilerplates'))) {
|
|
211
|
+
const src = safeRead(env, pkgPath);
|
|
212
|
+
if (src == null) continue;
|
|
213
|
+
try {
|
|
214
|
+
const scripts = JSON.parse(src).scripts || {};
|
|
215
|
+
for (const key of Object.keys(scripts)) commands.add(key);
|
|
216
|
+
} catch {
|
|
217
|
+
/* package.json inválido no boilerplate — ignora */
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return commands;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Ambiente padrão para uso fora do runner de checks (o CLI, testes de integração). */
|
|
225
|
+
export function defaultEnv(overrides = {}) {
|
|
226
|
+
return {
|
|
227
|
+
root: path.resolve(path.dirname(new URL(import.meta.url).pathname), '..', '..'),
|
|
228
|
+
fs,
|
|
229
|
+
...overrides,
|
|
230
|
+
};
|
|
231
|
+
}
|
package/lib/core/health.mjs
CHANGED
|
@@ -30,7 +30,15 @@ import path from 'node:path';
|
|
|
30
30
|
import { fileURLToPath } from 'node:url';
|
|
31
31
|
|
|
32
32
|
import { getWorkspaceDbPath, getWorkspaceInfo } from '../workspace.mjs';
|
|
33
|
-
import { runChecks as run, worstStatus, stripTemplateLiterals } from './checks.mjs';
|
|
33
|
+
import { runChecks as run, worstStatus, stripTemplateLiterals, asErrno } from './checks.mjs';
|
|
34
|
+
import { COMMANDS } from './registry.mjs';
|
|
35
|
+
import { scanCommands, scanLinks, projectCommands } from './doc-graph.mjs';
|
|
36
|
+
|
|
37
|
+
// Os contratos vivem em checks.mjs — importados, não redefinidos. As cópias locais eram resíduo da
|
|
38
|
+
// extração do runner (SPEC-010) e já divergiam.
|
|
39
|
+
/** @typedef {import('./checks.mjs').Check} Check */
|
|
40
|
+
/** @typedef {import('./checks.mjs').Result} Result */
|
|
41
|
+
/** @typedef {import('./checks.mjs').Status} Status */
|
|
34
42
|
|
|
35
43
|
// O runner vive em checks.mjs e é compartilhado com o catálogo de release (SPEC-010). Re-exportado
|
|
36
44
|
// aqui para que `tools:doctor` e o hook SessionStart sigam importando de um lugar só.
|
|
@@ -39,29 +47,6 @@ export { worstStatus };
|
|
|
39
47
|
const __filename = fileURLToPath(import.meta.url);
|
|
40
48
|
const repoRoot = path.resolve(path.dirname(__filename), '..', '..');
|
|
41
49
|
|
|
42
|
-
/** @typedef {'critical'|'warn'} Severity */
|
|
43
|
-
/** @typedef {'runtime'|'repo'} Scope */
|
|
44
|
-
/** @typedef {'ok'|'warn'|'fail'|'skipped'} Status */
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* @typedef {object} Check
|
|
48
|
-
* @property {string} id
|
|
49
|
-
* @property {string} title
|
|
50
|
-
* @property {Severity} severity `critical` trava o gate; `warn` informa.
|
|
51
|
-
* @property {Scope} scope `repo` só roda dentro do repo do framework.
|
|
52
|
-
* @property {string=} dependsOn Id de outro check. Se ele falhar, este vira `skipped`.
|
|
53
|
-
* @property {(env: Env) => Promise<Probe>|Probe} probe
|
|
54
|
-
*/
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* @typedef {object} Probe
|
|
58
|
-
* @property {Status} status
|
|
59
|
-
* @property {string} detail O que foi observado, em uma linha.
|
|
60
|
-
* @property {string|null=} fix Comando exato que corrige. `null` quando não há o que corrigir.
|
|
61
|
-
*/
|
|
62
|
-
|
|
63
|
-
/** @typedef {{ id, title, severity: Severity, scope: Scope, status: Status, detail: string, fix: string|null }} Result */
|
|
64
|
-
|
|
65
50
|
/**
|
|
66
51
|
* Ambiente injetável. Existe para que os probes sejam testáveis sem mockar o loader de módulos
|
|
67
52
|
* do Node nem corromper `node_modules` de verdade — simular um ABI quebrado é passar um
|
|
@@ -101,6 +86,7 @@ export function defaultEnv(overrides = {}) {
|
|
|
101
86
|
* Classificamos por `err.code`, nunca pela mensagem: o texto do erro varia entre versões do Node,
|
|
102
87
|
* e este check existe precisamente para sobreviver a troca de versão do Node.
|
|
103
88
|
*/
|
|
89
|
+
/** @type {Check} */
|
|
104
90
|
const nativeAbi = {
|
|
105
91
|
id: 'native-abi',
|
|
106
92
|
title: 'better-sqlite3 carrega no Node atual',
|
|
@@ -111,7 +97,7 @@ const nativeAbi = {
|
|
|
111
97
|
try {
|
|
112
98
|
({ default: Database } = await env.importModule('better-sqlite3'));
|
|
113
99
|
} catch (err) {
|
|
114
|
-
if (err
|
|
100
|
+
if (asErrno(err).code === 'ERR_MODULE_NOT_FOUND') {
|
|
115
101
|
return {
|
|
116
102
|
status: 'fail',
|
|
117
103
|
detail: 'better-sqlite3 não está instalado — toda a memória universal fica indisponível',
|
|
@@ -124,7 +110,7 @@ const nativeAbi = {
|
|
|
124
110
|
try {
|
|
125
111
|
new Database(':memory:').close();
|
|
126
112
|
} catch (err) {
|
|
127
|
-
if (err
|
|
113
|
+
if (asErrno(err).code === 'ERR_DLOPEN_FAILED') {
|
|
128
114
|
const node = env.process.versions.node;
|
|
129
115
|
return {
|
|
130
116
|
status: 'fail',
|
|
@@ -142,6 +128,7 @@ const nativeAbi = {
|
|
|
142
128
|
},
|
|
143
129
|
};
|
|
144
130
|
|
|
131
|
+
/** @type {Check} */
|
|
145
132
|
const memoryDb = {
|
|
146
133
|
id: 'memory-db',
|
|
147
134
|
title: 'universal.db acessível',
|
|
@@ -173,7 +160,7 @@ const memoryDb = {
|
|
|
173
160
|
} catch (err) {
|
|
174
161
|
return {
|
|
175
162
|
status: 'fail',
|
|
176
|
-
detail: `banco existe mas não abre (${err
|
|
163
|
+
detail: `banco existe mas não abre (${asErrno(err).code || asErrno(err).message}) — provavelmente corrompido`,
|
|
177
164
|
fix: 'npm run sync:universal',
|
|
178
165
|
};
|
|
179
166
|
}
|
|
@@ -211,6 +198,7 @@ function newestMarkdownMtime(env, dir, acc = { t: 0 }) {
|
|
|
211
198
|
*
|
|
212
199
|
* É `warn`, não `critical`: responder sobre memória velha atrapalha, mas não impede trabalho.
|
|
213
200
|
*/
|
|
201
|
+
/** @type {Check} */
|
|
214
202
|
const memoryFresh = {
|
|
215
203
|
id: 'memory-fresh',
|
|
216
204
|
title: 'índice em dia com memory/',
|
|
@@ -253,6 +241,7 @@ const memoryFresh = {
|
|
|
253
241
|
* pensa" — um FORJA_WORKSPACE esquecido no ambiente aponta o framework para o workspace errado, e
|
|
254
242
|
* tudo parece funcionar.
|
|
255
243
|
*/
|
|
244
|
+
/** @type {Check} */
|
|
256
245
|
const workspace = {
|
|
257
246
|
id: 'workspace',
|
|
258
247
|
title: 'workspace resolvido',
|
|
@@ -274,6 +263,7 @@ const workspace = {
|
|
|
274
263
|
};
|
|
275
264
|
|
|
276
265
|
/** Compara o Node em uso com o `engines.node` declarado. Abaixo do mínimo, o resto é loteria. */
|
|
266
|
+
/** @type {Check} */
|
|
277
267
|
const nodeEngines = {
|
|
278
268
|
id: 'node-engines',
|
|
279
269
|
title: 'Node dentro de engines',
|
|
@@ -347,6 +337,7 @@ function packageName(specifier) {
|
|
|
347
337
|
* Conservador de propósito: só olha import **estático** de script publicado. Import dinâmico não
|
|
348
338
|
* conta (é o padrão do carregamento lazy, e lazy é justamente o que o ADR-0021 pediu).
|
|
349
339
|
*/
|
|
340
|
+
/** @type {Check} */
|
|
350
341
|
const runtimeDeps = {
|
|
351
342
|
id: 'runtime-deps',
|
|
352
343
|
title: 'deps de runtime declaradas',
|
|
@@ -425,6 +416,7 @@ const runtimeDeps = {
|
|
|
425
416
|
* repo. O codegraph indexava código morto e respondia com confiança sobre ele. O path também
|
|
426
417
|
* quebrava para qualquer outro contribuidor.
|
|
427
418
|
*/
|
|
419
|
+
/** @type {Check} */
|
|
428
420
|
const mcpJson = {
|
|
429
421
|
id: 'mcp-json',
|
|
430
422
|
title: '.mcp.json sem path absoluto',
|
|
@@ -456,8 +448,118 @@ const mcpJson = {
|
|
|
456
448
|
},
|
|
457
449
|
};
|
|
458
450
|
|
|
451
|
+
// ---------------------------------------------------------------------------
|
|
452
|
+
// Coerência da documentação (SPEC-011, ADR-0025)
|
|
453
|
+
//
|
|
454
|
+
// O Forja é operado por agentes que executam o que a doc manda. Quando a doc e o registry divergem,
|
|
455
|
+
// o agente erra por obediência. Estes três checks trazem a classe "erra sem avisar" (ADR-0021) para
|
|
456
|
+
// a camada de instrução — a fronteira mais barata de corromper e a mais cara de perceber.
|
|
457
|
+
// ---------------------------------------------------------------------------
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Comando fantasma na doc faz o agente executar o que não existe e concluir que o ambiente
|
|
461
|
+
* quebrou. É `critical`. A allowlist do projeto gerado é **derivada** dos geradores + boilerplates
|
|
462
|
+
* (nunca literal), senão `start:dev`/`test:e2e` e afins dariam falso positivo.
|
|
463
|
+
*/
|
|
464
|
+
/** @type {Check} */
|
|
465
|
+
const docsCommands = {
|
|
466
|
+
id: 'docs-commands',
|
|
467
|
+
title: 'comandos citados na doc existem',
|
|
468
|
+
severity: 'critical',
|
|
469
|
+
scope: 'repo',
|
|
470
|
+
probe(env) {
|
|
471
|
+
if (!isFrameworkRepo(env)) {
|
|
472
|
+
return { status: 'ok', detail: 'fora do repo do framework — não se aplica', fix: null };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const known = new Set([...Object.keys(COMMANDS), ...projectCommands(env)]);
|
|
476
|
+
const ghosts = scanCommands(env).filter((c) => !known.has(c.command));
|
|
477
|
+
|
|
478
|
+
if (ghosts.length) {
|
|
479
|
+
const amostra = ghosts.slice(0, 5).map((g) => `${g.command} (${g.file}:${g.line})`).join(', ');
|
|
480
|
+
return {
|
|
481
|
+
status: 'fail',
|
|
482
|
+
detail: `${ghosts.length} citação(ões) de comando inexistente: ${amostra}`,
|
|
483
|
+
fix: 'renomeie para um comando do registry ou remova a citação no arquivo:linha indicado',
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
return { status: 'ok', detail: 'toda citação de comando resolve no registry', fix: null };
|
|
488
|
+
},
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Capacidade que ninguém documenta é capacidade obscura. `warn`, não `critical`: um comando
|
|
493
|
+
* não-documentado atrapalha (o operador não sabe que existe), mas não impede trabalho.
|
|
494
|
+
*/
|
|
495
|
+
/** @type {Check} */
|
|
496
|
+
const commandsDocumented = {
|
|
497
|
+
id: 'commands-documented',
|
|
498
|
+
title: 'todo comando do registry é documentado',
|
|
499
|
+
severity: 'warn',
|
|
500
|
+
scope: 'repo',
|
|
501
|
+
probe(env) {
|
|
502
|
+
if (!isFrameworkRepo(env)) {
|
|
503
|
+
return { status: 'ok', detail: 'fora do repo do framework — não se aplica', fix: null };
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
const citados = new Set(scanCommands(env).map((c) => c.command));
|
|
507
|
+
const orfaos = Object.keys(COMMANDS).filter((c) => !citados.has(c));
|
|
508
|
+
|
|
509
|
+
if (orfaos.length) {
|
|
510
|
+
return {
|
|
511
|
+
status: 'warn',
|
|
512
|
+
detail: `${orfaos.length} comando(s) do registry sem menção em doc/prompt/agente: ${orfaos.join(', ')}`,
|
|
513
|
+
fix: 'documente cada um numa superfície de instrução, ou remova do registry se morto',
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
return { status: 'ok', detail: 'todos os comandos do registry aparecem na doc', fix: null };
|
|
518
|
+
},
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
/** Link relativo para o nada é step obscuro. `warn`: atrapalha a navegação, não impede trabalho. */
|
|
522
|
+
/** @type {Check} */
|
|
523
|
+
const docsLinks = {
|
|
524
|
+
id: 'docs-links',
|
|
525
|
+
title: 'links relativos da doc resolvem',
|
|
526
|
+
severity: 'warn',
|
|
527
|
+
scope: 'repo',
|
|
528
|
+
probe(env) {
|
|
529
|
+
if (!isFrameworkRepo(env)) {
|
|
530
|
+
return { status: 'ok', detail: 'fora do repo do framework — não se aplica', fix: null };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const quebrados = scanLinks(env).filter(
|
|
534
|
+
(l) => !env.fs.existsSync(path.join(env.root, l.resolved))
|
|
535
|
+
);
|
|
536
|
+
|
|
537
|
+
if (quebrados.length) {
|
|
538
|
+
const amostra = quebrados.slice(0, 5).map((q) => `${q.target} (${q.file}:${q.line})`).join(', ');
|
|
539
|
+
return {
|
|
540
|
+
status: 'warn',
|
|
541
|
+
detail: `${quebrados.length} link(s) relativo(s) sem alvo: ${amostra}`,
|
|
542
|
+
fix: 'crie o alvo ou corrija o link no arquivo:linha indicado',
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
return { status: 'ok', detail: 'todo link relativo resolve', fix: null };
|
|
547
|
+
},
|
|
548
|
+
};
|
|
549
|
+
|
|
459
550
|
/** @type {Check[]} */
|
|
460
|
-
export const CHECKS = [
|
|
551
|
+
export const CHECKS = [
|
|
552
|
+
nativeAbi,
|
|
553
|
+
memoryDb,
|
|
554
|
+
memoryFresh,
|
|
555
|
+
workspace,
|
|
556
|
+
nodeEngines,
|
|
557
|
+
runtimeDeps,
|
|
558
|
+
mcpJson,
|
|
559
|
+
docsCommands,
|
|
560
|
+
commandsDocumented,
|
|
561
|
+
docsLinks,
|
|
562
|
+
];
|
|
461
563
|
|
|
462
564
|
/**
|
|
463
565
|
* Roda os checks do núcleo. Fachada sobre o runner de `checks.mjs`: existe só para injetar o
|
|
@@ -466,7 +568,7 @@ export const CHECKS = [nativeAbi, memoryDb, memoryFresh, workspace, nodeEngines,
|
|
|
466
568
|
* `scope: 'runtime'` roda só os checks baratos e portáveis — é o que o hook SessionStart usa, onde
|
|
467
569
|
* há orçamento de 5s e nenhuma tolerância a travar a sessão.
|
|
468
570
|
*
|
|
469
|
-
* @param {{ scope?: Scope|'all', env?: Partial<Env>, checks?: Check[] }} [opts]
|
|
571
|
+
* @param {{ scope?: import('./checks.mjs').Scope|'all', env?: Partial<Env>, checks?: Check[] }} [opts]
|
|
470
572
|
* @returns {Promise<Result[]>}
|
|
471
573
|
*/
|
|
472
574
|
export async function runChecks(opts = {}) {
|
package/lib/core/registry.mjs
CHANGED
|
@@ -13,6 +13,29 @@
|
|
|
13
13
|
* - workspace-warn avisa se o workspace não existir, mas segue
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Resolve o `node:` de um comando para o arquivo real, **agnóstico de extensão** (SPEC-012 D2).
|
|
21
|
+
* Tenta `.ts → .js → .mjs`: em dev acha a fonte `.ts`; no pacote publicado, o `.js` sob `dist/`.
|
|
22
|
+
* Desacopla o registry do runtime — a entrada pode manter `.mjs` que este resolver ainda acha o
|
|
23
|
+
* `.ts` renomeado. Sem isto, renomear um script quebraria o dispatch.
|
|
24
|
+
*
|
|
25
|
+
* @param {string} root Raiz onde os scripts vivem (repo em dev, `dist/` no publicado).
|
|
26
|
+
* @param {string} node Caminho do registry, com ou sem extensão.
|
|
27
|
+
* @returns {string} Caminho absoluto do arquivo que existe (ou o candidato original, que falha visível).
|
|
28
|
+
*/
|
|
29
|
+
export function resolveScript(root, node) {
|
|
30
|
+
const direct = path.join(root, node);
|
|
31
|
+
if (fs.existsSync(direct)) return direct;
|
|
32
|
+
const base = direct.replace(/\.(mjs|cjs|js|ts)$/, '');
|
|
33
|
+
for (const ext of ['.ts', '.js', '.mjs']) {
|
|
34
|
+
if (fs.existsSync(base + ext)) return base + ext;
|
|
35
|
+
}
|
|
36
|
+
return direct;
|
|
37
|
+
}
|
|
38
|
+
|
|
16
39
|
export const DOMAINS = {
|
|
17
40
|
workspace: 'Workspace & projetos',
|
|
18
41
|
sdd: 'Pipeline SDD (spec → plan → tasks → check)',
|
package/lib/core/release.mjs
CHANGED
|
@@ -25,7 +25,9 @@ import path from 'node:path';
|
|
|
25
25
|
import { fileURLToPath } from 'node:url';
|
|
26
26
|
|
|
27
27
|
import { runChecks as run, worstStatus, stripTemplateLiterals } from './checks.mjs';
|
|
28
|
-
|
|
28
|
+
|
|
29
|
+
/** @typedef {import('./checks.mjs').Check} Check */
|
|
30
|
+
import { COMMANDS, resolveScript } from './registry.mjs';
|
|
29
31
|
|
|
30
32
|
export { worstStatus };
|
|
31
33
|
|
|
@@ -48,6 +50,7 @@ function git(args, cwd = repoRoot) {
|
|
|
48
50
|
*
|
|
49
51
|
* Limpa o temporário **sempre**, inclusive quando o callback lança.
|
|
50
52
|
*
|
|
53
|
+
* @template T
|
|
51
54
|
* @param {(ctx: { pkgDir: string, installDir: string }) => Promise<T>|T} fn
|
|
52
55
|
* @returns {Promise<T>}
|
|
53
56
|
*/
|
|
@@ -74,8 +77,9 @@ export async function withCleanInstall(fn, { root = repoRoot } = {}) {
|
|
|
74
77
|
return execFileSync('npm', args, { cwd, encoding: 'utf8', env, stdio: 'pipe' });
|
|
75
78
|
} catch (err) {
|
|
76
79
|
// Engolir o stderr aqui cega o diagnóstico exatamente quando ele importa.
|
|
77
|
-
const
|
|
78
|
-
|
|
80
|
+
const e = /** @type {any} */ (err);
|
|
81
|
+
const saida = `${e.stdout || ''}${e.stderr || ''}`.trim();
|
|
82
|
+
throw new Error(`npm ${args[0]} falhou em ${cwd}:\n${saida || e.message}`);
|
|
79
83
|
}
|
|
80
84
|
};
|
|
81
85
|
|
|
@@ -84,6 +88,7 @@ export async function withCleanInstall(fn, { root = repoRoot } = {}) {
|
|
|
84
88
|
.trim()
|
|
85
89
|
.split('\n')
|
|
86
90
|
.pop();
|
|
91
|
+
if (!tgz) throw new Error('npm pack não produziu um tarball');
|
|
87
92
|
|
|
88
93
|
npm(['init', '-y'], dir);
|
|
89
94
|
npm(['install', path.join(dir, tgz)], dir);
|
|
@@ -109,6 +114,7 @@ export async function withCleanInstall(fn, { root = repoRoot } = {}) {
|
|
|
109
114
|
* Severidade depende do modo: sob `--publish` é fatal; em dev é aviso — um gate que reprova todo
|
|
110
115
|
* desenvolvimento local é um gate que se contorna (a lição que o CI nos deu na SPEC-009).
|
|
111
116
|
*/
|
|
117
|
+
/** @type {Check} */
|
|
112
118
|
const treeClean = {
|
|
113
119
|
id: 'tree-clean',
|
|
114
120
|
title: 'árvore limpa (o tarball é o commit)',
|
|
@@ -133,6 +139,7 @@ const treeClean = {
|
|
|
133
139
|
};
|
|
134
140
|
|
|
135
141
|
/** Se o pacote não instala, todo o resto é irrelevante — daí todos dependerem deste. */
|
|
142
|
+
/** @type {Check} */
|
|
136
143
|
const install = {
|
|
137
144
|
id: 'install',
|
|
138
145
|
title: 'o pacote instala do zero',
|
|
@@ -148,6 +155,7 @@ const install = {
|
|
|
148
155
|
* Todo comando anunciado pelo registry precisa existir no tarball. É o bug da v1.1.3, generalizado:
|
|
149
156
|
* `npm run dashboard` era publicado, a pasta `dashboard/` não.
|
|
150
157
|
*/
|
|
158
|
+
/** @type {Check} */
|
|
151
159
|
const registryScripts = {
|
|
152
160
|
id: 'registry-scripts',
|
|
153
161
|
title: 'todo comando do registry existe no tarball',
|
|
@@ -161,7 +169,10 @@ const registryScripts = {
|
|
|
161
169
|
const rel = def.node || def.script;
|
|
162
170
|
if (!rel) continue;
|
|
163
171
|
total += 1;
|
|
164
|
-
|
|
172
|
+
// Resolve extensão no tarball (SPEC-012 D2): o script pode ter sido renomeado para .ts em dev
|
|
173
|
+
// e compilado para .js em dist/. O resolver acha o que existe, não crava a extensão.
|
|
174
|
+
const resolved = resolveScript(pkgCodeRoot(env), rel);
|
|
175
|
+
if (!env.fs.existsSync(resolved)) faltando.push(`${name} → ${rel}`);
|
|
165
176
|
}
|
|
166
177
|
|
|
167
178
|
if (faltando.length) {
|
|
@@ -189,11 +200,31 @@ const registryScripts = {
|
|
|
189
200
|
*/
|
|
190
201
|
const CODE_DIRS = ['bin', 'lib', 'scripts'];
|
|
191
202
|
|
|
203
|
+
/**
|
|
204
|
+
* A raiz onde `bin/lib/scripts` vivem **no tarball**, derivada do campo `bin` do package.json.
|
|
205
|
+
*
|
|
206
|
+
* Fonte-na-raiz (`bin: 'bin/forja.mjs'`) → a raiz é o próprio pacote. Publicando `dist/`
|
|
207
|
+
* (`bin: 'dist/bin/forja.mjs'`, SPEC-012) → a raiz é `dist/`. É a mesma conta que o dispatch faz em
|
|
208
|
+
* runtime (`root = dirname(bin)/..`); os checks de release precisam olhar no mesmo lugar, senão
|
|
209
|
+
* procuram o código onde ele não está mais.
|
|
210
|
+
*/
|
|
211
|
+
function pkgCodeRoot(env) {
|
|
212
|
+
try {
|
|
213
|
+
const pkg = JSON.parse(env.fs.readFileSync(path.join(env.pkgDir, 'package.json'), 'utf8'));
|
|
214
|
+
const binRel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.forja;
|
|
215
|
+
if (binRel) return path.join(env.pkgDir, path.dirname(path.dirname(binRel)));
|
|
216
|
+
} catch {
|
|
217
|
+
/* sem package.json legível — cai no default */
|
|
218
|
+
}
|
|
219
|
+
return env.pkgDir;
|
|
220
|
+
}
|
|
221
|
+
|
|
192
222
|
function publishedSources(env) {
|
|
193
223
|
const out = [];
|
|
224
|
+
const root = pkgCodeRoot(env);
|
|
194
225
|
|
|
195
226
|
for (const dir of CODE_DIRS) {
|
|
196
|
-
const full = path.join(
|
|
227
|
+
const full = path.join(root, dir);
|
|
197
228
|
if (env.fs.existsSync(full)) walkDir(env, full, out);
|
|
198
229
|
}
|
|
199
230
|
|
|
@@ -241,6 +272,7 @@ function packageName(specifier) {
|
|
|
241
272
|
}
|
|
242
273
|
|
|
243
274
|
/** Import relativo que não resolve dentro do tarball = arquivo fora do `files[]` (bug da v1.1.3). */
|
|
275
|
+
/** @type {Check} */
|
|
244
276
|
const importsResolve = {
|
|
245
277
|
id: 'imports-resolve',
|
|
246
278
|
title: 'imports relativos resolvem dentro do tarball',
|
|
@@ -272,6 +304,7 @@ const importsResolve = {
|
|
|
272
304
|
};
|
|
273
305
|
|
|
274
306
|
/** O bug do ADR-0021 §2: importado por script publicado, mas declarado como devDependency. */
|
|
307
|
+
/** @type {Check} */
|
|
275
308
|
const depsDeclared = {
|
|
276
309
|
id: 'deps-declared',
|
|
277
310
|
title: 'todo import externo está em dependencies',
|
|
@@ -304,6 +337,7 @@ const depsDeclared = {
|
|
|
304
337
|
};
|
|
305
338
|
|
|
306
339
|
/** Peso morto viaja no tarball de todo usuário. Incomoda; não quebra — por isso `warn` (D7). */
|
|
340
|
+
/** @type {Check} */
|
|
307
341
|
const depsUnused = {
|
|
308
342
|
id: 'deps-unused',
|
|
309
343
|
title: 'nenhuma dependency é peso morto',
|
|
@@ -347,20 +381,25 @@ const depsUnused = {
|
|
|
347
381
|
* code reprovaria um pacote saudável — a mesma armadilha do `memory-db` na SPEC-009, um nível
|
|
348
382
|
* acima.
|
|
349
383
|
*/
|
|
384
|
+
/** @type {Check} */
|
|
350
385
|
const smokeCommands = {
|
|
351
386
|
id: 'smoke-commands',
|
|
352
387
|
title: 'os comandos executam de verdade',
|
|
353
388
|
severity: 'critical',
|
|
354
389
|
dependsOn: 'install',
|
|
355
390
|
probe(env) {
|
|
356
|
-
|
|
391
|
+
// Lê o entry point do campo `bin` do package.json, não de um path fixo — o publicado aponta
|
|
392
|
+
// para dist/ (SPEC-012). Cravar `bin/forja.mjs` quebraria o smoke assim que o bin mudasse.
|
|
393
|
+
const pkg = JSON.parse(env.fs.readFileSync(path.join(env.pkgDir, 'package.json'), 'utf8'));
|
|
394
|
+
const binRel = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.forja;
|
|
395
|
+
const bin = path.join(env.pkgDir, binRel);
|
|
357
396
|
const quebrados = [];
|
|
358
397
|
|
|
359
398
|
for (const args of env.smokeCommands) {
|
|
360
399
|
const res = env.spawn(process.execPath, [bin, ...args], { cwd: env.installDir });
|
|
361
400
|
const saida = `${res.stdout || ''}${res.stderr || ''}`;
|
|
362
401
|
if (LOADER_ERRORS.test(saida)) {
|
|
363
|
-
const causa = saida.match(LOADER_ERRORS)[0];
|
|
402
|
+
const causa = saida.match(LOADER_ERRORS)?.[0] ?? 'erro de carregamento';
|
|
364
403
|
quebrados.push(`${args[0] || '(help)'}: ${causa}`);
|
|
365
404
|
}
|
|
366
405
|
}
|
|
@@ -409,7 +448,8 @@ export function defaultEnv(overrides = {}) {
|
|
|
409
448
|
stderr: '',
|
|
410
449
|
};
|
|
411
450
|
} catch (err) {
|
|
412
|
-
|
|
451
|
+
const e = /** @type {any} */ (err);
|
|
452
|
+
return { stdout: e.stdout || '', stderr: e.stderr || String(err) };
|
|
413
453
|
}
|
|
414
454
|
},
|
|
415
455
|
...overrides,
|