forjajs 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/bin/create-memory-nest-kit.d.ts +11 -0
  3. package/dist/bin/create-memory-nest-kit.js +5 -5
  4. package/dist/bin/forja.js +1 -1
  5. package/dist/bin/init-project.d.ts +12 -0
  6. package/dist/bin/init-project.js +2 -2
  7. package/dist/lib/context-builder.d.ts +15 -5
  8. package/dist/lib/context-builder.js +5 -0
  9. package/dist/lib/core/checks.d.ts +3 -3
  10. package/dist/lib/core/doc-graph.js +1 -1
  11. package/dist/lib/core/health.d.ts +3 -32
  12. package/dist/lib/core/health.js +0 -14
  13. package/dist/lib/core/registry.js +12 -12
  14. package/dist/lib/core/release.d.ts +2 -14
  15. package/dist/lib/core/release.js +0 -8
  16. package/dist/lib/generators/memory-generator.d.ts +10 -6
  17. package/dist/lib/generators/memory-generator.js +1 -1
  18. package/dist/lib/generators/nest-generator.d.ts +8 -4
  19. package/dist/lib/generators/nest-generator.js +1 -1
  20. package/dist/lib/generators/readme-generator.d.ts +7 -4
  21. package/dist/lib/generators/readme-generator.js +1 -1
  22. package/dist/lib/governance-report.d.ts +1 -1
  23. package/dist/lib/utils/file-helpers.d.ts +10 -6
  24. package/dist/lib/validators/structure-validator.d.ts +49 -27
  25. package/dist/scripts/dev.d.ts +2 -2
  26. package/dist/scripts/dev.js +1 -1
  27. package/dist/scripts/query-universal-memory.js +1 -1
  28. package/dist/scripts/sprint-manager.js +1 -1
  29. package/dist/scripts/token-benchmark.js +1 -1
  30. package/package.json +1 -1
  31. package/specs/ts-migration/plan.md +9 -8
  32. package/specs/ts-migration/spec.md +1 -1
  33. package/dist/lib/templates/harness/code-intel.d.mts +0 -2
  34. package/dist/lib/templates/harness/code-intel.mjs +0 -126
package/CHANGELOG.md CHANGED
@@ -4,6 +4,39 @@ Histórico consolidado das mudanças estruturais do framework. Para decisões ar
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.3.2] — 2026-07-19 — Migração TypeScript concluída (interno)
8
+
9
+ **Sem mudança para quem instala** — o `dist/*.js` publicado é idêntico ao da 1.3.1. Fecha a SPEC-012.
10
+
11
+ ### Alterado (interno)
12
+ - **Fonte 100% TypeScript**: os 16 `.js` restantes (entries públicos `init-project`/
13
+ `create-memory-nest-kit`, generators, validators, `context-builder`, scaffolding) viraram `.ts`.
14
+ - **`noImplicitAny: true`** — o ratchet está armado: daqui pra frente todo parâmetro novo precisa de
15
+ tipo explícito. Os ~285 params existentes foram anotados (tipo real onde agrega, `any` explícito
16
+ onde o valor é dinâmico). Os checks de `health`/`release` viram `Check[]` de verdade.
17
+ - Shim `lib/vendor.d.ts` para o `better-sqlite3` (sem tipos publicados); `lib/templates` fora do
18
+ type-check (é conteúdo copiado, não código do framework).
19
+ - Correção pega pelo `release:check`: um sed havia corrompido o array de fallback do `resolveScript`
20
+ (`['.ts','.js','.mjs']`→`['.ts','.ts','.ts']`), quebrando a resolução do `dist/*.js`.
21
+
22
+ ---
23
+
24
+ ## [1.3.1] — 2026-07-19 — Migração TypeScript dos módulos do framework (interno)
25
+
26
+ **Sem mudança para quem instala** — o `dist/*.js` publicado é idêntico ao da 1.3.0. A conversão é
27
+ interna: fecha a renomeação leaf-first da SPEC-012 Fase 2.
28
+
29
+ ### Alterado (interno)
30
+ - **Todos os 21 módulos `.mjs` do framework** (`bin/forja`, `lib/{audit,governance-report,workspace}`,
31
+ todos os `scripts/` incluindo os 4 hooks) convertidos para `.ts`, com ~130 anotações de tipo. Os
32
+ typedefs JSDoc viraram `interface`; os casts-comentário `/** @type */ (x)` viraram `as`.
33
+ - Dev e CI rodam a fonte `.ts` (Node ≥22.6); o `ci.yml` invoca `bin/forja.ts`. O publicado segue
34
+ `dist/*.js` (Node ≥20), provado pelo `release-gate`.
35
+ - **Fora desta fatia** (deliberado): os 16 `.js` (entries públicos + generators + scaffolding), que
36
+ seguem no checkJs, e `noImplicitAny: true` (endurecimento final).
37
+
38
+ ---
39
+
7
40
  ## [1.3.0] — 2026-07-19 — Governança visível e o núcleo em TypeScript
8
41
 
9
42
  Duas frentes que amadurecem o framework: a governança sai do arquivo que ninguém abre para
@@ -1,2 +1,13 @@
1
1
  #!/usr/bin/env node
2
+ /**
3
+ * create-memory-nest-kit v0.6.0
4
+ * Orquestrador de geração de projetos com memória hierárquica
5
+ *
6
+ * Refatoração modular:
7
+ * - lib/generators/memory-generator.js
8
+ * - lib/generators/nest-generator.js
9
+ * - lib/generators/readme-generator.js
10
+ * - lib/validators/structure-validator.js
11
+ * - lib/utils/file-helpers.js
12
+ */
2
13
  export {};
@@ -13,11 +13,11 @@
13
13
  import path from 'node:path';
14
14
  import process from 'node:process';
15
15
  import { fileURLToPath } from 'node:url';
16
- import { generateMemoryStructure } from '../lib/generators/memory-generator.js';
17
- import { generateNestStructure } from '../lib/generators/nest-generator.js';
18
- import { generateReadme } from '../lib/generators/readme-generator.js';
19
- import { validateProjectStructure, printValidationReport } from '../lib/validators/structure-validator.js';
20
- import { ensureDir, logSuccess, logError } from '../lib/utils/file-helpers.js';
16
+ import { generateMemoryStructure } from "../lib/generators/memory-generator.js";
17
+ import { generateNestStructure } from "../lib/generators/nest-generator.js";
18
+ import { generateReadme } from "../lib/generators/readme-generator.js";
19
+ import { validateProjectStructure, printValidationReport } from "../lib/validators/structure-validator.js";
20
+ import { ensureDir, logSuccess, logError } from "../lib/utils/file-helpers.js";
21
21
  const __filename = fileURLToPath(import.meta.url);
22
22
  const __dirname = path.dirname(__filename);
23
23
  // Parse arguments
package/dist/bin/forja.js CHANGED
@@ -120,7 +120,7 @@ else {
120
120
  cwd: root,
121
121
  stdio: 'inherit',
122
122
  });
123
- if (result.error && /** @type {any} */ (result.error).code === 'ENOENT') {
123
+ if (result.error && result.error.code === 'ENOENT') {
124
124
  console.error(`Binário não encontrado no PATH: ${cmd.bin}. Veja: forja tools:doctor`);
125
125
  result.status = 127;
126
126
  }
@@ -1,2 +1,14 @@
1
1
  #!/usr/bin/env node
2
+ /**
3
+ * init-project.js
4
+ *
5
+ * Comando universal para inicializar novo projeto com agentes orquestrados.
6
+ * Puxa configuração de Copilot, Claude, Gemini, Codex e outros.
7
+ *
8
+ * Uso:
9
+ * node bin/init-project.js meu-projeto
10
+ * node bin/init-project.js meu-projeto --ai copilot,claude,gemini
11
+ * node bin/init-project.js meu-projeto --skip-backend
12
+ * node bin/init-project.js --interactive
13
+ */
2
14
  export {};
@@ -16,7 +16,7 @@ import path from 'node:path';
16
16
  import process from 'node:process';
17
17
  import { execSync } from 'node:child_process';
18
18
  import { fileURLToPath } from 'node:url';
19
- import { getWorkspaceRoot, getProjectsDir, resolveProject, initWorkspace, getWorkspaceProjectsMemoryDir, assertOutsideFrameworkRepo, } from "../lib/workspace.js";
19
+ import { getWorkspaceRoot, resolveProject, initWorkspace, getWorkspaceProjectsMemoryDir, assertOutsideFrameworkRepo, } from "../lib/workspace.js";
20
20
  const __filename = fileURLToPath(import.meta.url);
21
21
  const __dirname = path.dirname(__filename);
22
22
  const kitRoot = path.resolve(__dirname, '..');
@@ -302,7 +302,7 @@ Para trocar de IA (ex: se acabar a cota), use o arquivo [models.json](./models.j
302
302
 
303
303
  ## IAs Configuradas
304
304
 
305
- ${opts.ai.map(ai => `- [${ai.toUpperCase()}](./${ai}.md)`).join('\n')}
305
+ ${opts.ai.map((ai) => `- [${ai.toUpperCase()}](./${ai}.md)`).join('\n')}
306
306
  `;
307
307
  fs.writeFileSync(path.join(instructionsDir, 'README.md'), indexContent);
308
308
  // Criar models.json para interoperabilidade
@@ -1,10 +1,20 @@
1
- export class ContextBuilder {
2
- constructor(projectPath: any, dbPath: any);
3
- projectPath: any;
4
- dbPath: any;
1
+ /**
2
+ * Context Builder - API Reutilizável para Construção de Contexto Inteligente
3
+ *
4
+ * Suporta 3 modos de contexto:
5
+ * - 'global': Apenas contexto global (mission, standards, decisões recentes)
6
+ * - 'domain': Contexto de domínio específico + globais
7
+ * - 'task': Contexto orientado a tarefa + domain + globais (mais compacto)
8
+ *
9
+ * Usa SQLite FTS5 para busca eficiente e cache local para reutilização.
10
+ */
11
+ export declare class ContextBuilder {
12
+ projectPath: string;
13
+ dbPath: string;
5
14
  db: any;
6
15
  cache: Map<any, any>;
7
16
  maxCacheSize: number;
17
+ constructor(projectPath: any, dbPath: any);
8
18
  /**
9
19
  * Abrir conexão com banco de dados (readonly)
10
20
  */
@@ -21,7 +31,7 @@ export class ContextBuilder {
21
31
  * @param {string} keyword - Palavra-chave para busca (modo 'task')
22
32
  * @returns {string} Conteúdo do contexto em markdown
23
33
  */
24
- build(mode: string, project: string, keyword?: string): string;
34
+ build(mode: any, project: any, keyword?: string): string;
25
35
  /**
26
36
  * Obter contexto global (mission, standards, padrões)
27
37
  */
@@ -13,6 +13,11 @@ import path from 'node:path';
13
13
  import Database from 'better-sqlite3';
14
14
  import { getDbPath, ensureSchema } from "../scripts/memory-schema.js";
15
15
  export class ContextBuilder {
16
+ projectPath;
17
+ dbPath;
18
+ db;
19
+ cache;
20
+ maxCacheSize;
16
21
  constructor(projectPath, dbPath) {
17
22
  this.projectPath = projectPath;
18
23
  this.dbPath = dbPath;
@@ -68,9 +68,9 @@ export declare function asErrno(e: any): any;
68
68
  * @returns {Promise<Result[]>}
69
69
  */
70
70
  export declare function runChecks({ checks, scope, env }: {
71
- checks: any;
72
- scope?: string | undefined;
73
- env?: {} | undefined;
71
+ checks: Check[];
72
+ scope?: Scope | 'all';
73
+ env?: any;
74
74
  }): Promise<Result[]>;
75
75
  /**
76
76
  * Veredito agregado. Só `critical` reprova — um gate que trava por aquilo que não impede trabalho
@@ -201,7 +201,7 @@ export function projectCommands(env) {
201
201
  /* sem geradores — segue */
202
202
  }
203
203
  for (const entry of genEntries) {
204
- if (!/\.(mjs|js)$/.test(entry))
204
+ if (!/\.(mjs|cjs|js|ts)$/.test(entry))
205
205
  continue;
206
206
  const src = safeRead(env, path.join(genDir, entry));
207
207
  if (src == null)
@@ -27,8 +27,7 @@
27
27
  import fs from 'node:fs';
28
28
  import { getWorkspaceDbPath, getWorkspaceInfo } from '../workspace.ts';
29
29
  import { worstStatus } from './checks.ts';
30
- /** @typedef {import('./checks.ts').Check} Check */
31
- /** @typedef {import('./checks.ts').Result} Result */
30
+ import type { Check, Result } from './checks.ts';
32
31
  /** @typedef {import('./checks.ts').Status} Status */
33
32
  export { worstStatus };
34
33
  /**
@@ -57,35 +56,7 @@ export declare function defaultEnv(overrides?: {}): {
57
56
  /** Estamos dentro do repo do framework, e não numa instalação do pacote? */
58
57
  export declare function isFrameworkRepo(env: any): boolean;
59
58
  /** @type {Check[]} */
60
- export declare const CHECKS: ({
61
- id: string;
62
- title: string;
63
- severity: string;
64
- scope: string;
65
- probe(env: any): Promise<{
66
- status: string;
67
- detail: string;
68
- fix: string;
69
- } | {
70
- status: string;
71
- detail: string;
72
- fix: null;
73
- }>;
74
- } | {
75
- id: string;
76
- title: string;
77
- severity: string;
78
- scope: string;
79
- probe(env: any): {
80
- status: string;
81
- detail: string;
82
- fix: string;
83
- } | {
84
- status: string;
85
- detail: string;
86
- fix: null;
87
- };
88
- })[];
59
+ export declare const CHECKS: Check[];
89
60
  /**
90
61
  * Roda os checks do núcleo. Fachada sobre o runner de `checks.mjs`: existe só para injetar o
91
62
  * `defaultEnv` do framework, que o runner genérico não conhece nem deve conhecer.
@@ -100,4 +71,4 @@ export declare function runChecks(opts?: {
100
71
  scope?: import('./checks.ts').Scope | 'all';
101
72
  env?: any;
102
73
  checks?: import('./checks.ts').Check[];
103
- }): Promise<import("./checks.ts").Result[]>;
74
+ }): Promise<Result[]>;
@@ -39,10 +39,6 @@ import { getWorkspaceDbPath, getWorkspaceInfo } from "../workspace.js";
39
39
  import { runChecks as run, worstStatus, stripTemplateLiterals, asErrno } from "./checks.js";
40
40
  import { COMMANDS } from "./registry.js";
41
41
  import { scanCommands, scanLinks, projectCommands } from "./doc-graph.js";
42
- // Os contratos vivem em checks.mjs — importados, não redefinidos. As cópias locais eram resíduo da
43
- // extração do runner (SPEC-010) e já divergiam.
44
- /** @typedef {import('./checks.ts').Check} Check */
45
- /** @typedef {import('./checks.ts').Result} Result */
46
42
  /** @typedef {import('./checks.ts').Status} Status */
47
43
  // O runner vive em checks.mjs e é compartilhado com o catálogo de release (SPEC-010). Re-exportado
48
44
  // aqui para que `tools:doctor` e o hook SessionStart sigam importando de um lugar só.
@@ -85,7 +81,6 @@ export function defaultEnv(overrides = {}) {
85
81
  * Classificamos por `err.code`, nunca pela mensagem: o texto do erro varia entre versões do Node,
86
82
  * e este check existe precisamente para sobreviver a troca de versão do Node.
87
83
  */
88
- /** @type {Check} */
89
84
  const nativeAbi = {
90
85
  id: 'native-abi',
91
86
  title: 'better-sqlite3 carrega no Node atual',
@@ -125,7 +120,6 @@ const nativeAbi = {
125
120
  return { status: 'ok', detail: `carrega em Node v${env.process.versions.node}`, fix: null };
126
121
  },
127
122
  };
128
- /** @type {Check} */
129
123
  const memoryDb = {
130
124
  id: 'memory-db',
131
125
  title: 'universal.db acessível',
@@ -196,7 +190,6 @@ function newestMarkdownMtime(env, dir, acc = { t: 0 }) {
196
190
  *
197
191
  * É `warn`, não `critical`: responder sobre memória velha atrapalha, mas não impede trabalho.
198
192
  */
199
- /** @type {Check} */
200
193
  const memoryFresh = {
201
194
  id: 'memory-fresh',
202
195
  title: 'índice em dia com memory/',
@@ -233,7 +226,6 @@ const memoryFresh = {
233
226
  * pensa" — um FORJA_WORKSPACE esquecido no ambiente aponta o framework para o workspace errado, e
234
227
  * tudo parece funcionar.
235
228
  */
236
- /** @type {Check} */
237
229
  const workspace = {
238
230
  id: 'workspace',
239
231
  title: 'workspace resolvido',
@@ -252,7 +244,6 @@ const workspace = {
252
244
  },
253
245
  };
254
246
  /** Compara o Node em uso com o `engines.node` declarado. Abaixo do mínimo, o resto é loteria. */
255
- /** @type {Check} */
256
247
  const nodeEngines = {
257
248
  id: 'node-engines',
258
249
  title: 'Node dentro de engines',
@@ -324,7 +315,6 @@ function packageName(specifier) {
324
315
  * Conservador de propósito: só olha import **estático** de script publicado. Import dinâmico não
325
316
  * conta (é o padrão do carregamento lazy, e lazy é justamente o que o ADR-0021 pediu).
326
317
  */
327
- /** @type {Check} */
328
318
  const runtimeDeps = {
329
319
  id: 'runtime-deps',
330
320
  title: 'deps de runtime declaradas',
@@ -398,7 +388,6 @@ const runtimeDeps = {
398
388
  * repo. O codegraph indexava código morto e respondia com confiança sobre ele. O path também
399
389
  * quebrava para qualquer outro contribuidor.
400
390
  */
401
- /** @type {Check} */
402
391
  const mcpJson = {
403
392
  id: 'mcp-json',
404
393
  title: '.mcp.json sem path absoluto',
@@ -437,7 +426,6 @@ const mcpJson = {
437
426
  * quebrou. É `critical`. A allowlist do projeto gerado é **derivada** dos geradores + boilerplates
438
427
  * (nunca literal), senão `start:dev`/`test:e2e` e afins dariam falso positivo.
439
428
  */
440
- /** @type {Check} */
441
429
  const docsCommands = {
442
430
  id: 'docs-commands',
443
431
  title: 'comandos citados na doc existem',
@@ -464,7 +452,6 @@ const docsCommands = {
464
452
  * Capacidade que ninguém documenta é capacidade obscura. `warn`, não `critical`: um comando
465
453
  * não-documentado atrapalha (o operador não sabe que existe), mas não impede trabalho.
466
454
  */
467
- /** @type {Check} */
468
455
  const commandsDocumented = {
469
456
  id: 'commands-documented',
470
457
  title: 'todo comando do registry é documentado',
@@ -487,7 +474,6 @@ const commandsDocumented = {
487
474
  },
488
475
  };
489
476
  /** Link relativo para o nada é step obscuro. `warn`: atrapalha a navegação, não impede trabalho. */
490
- /** @type {Check} */
491
477
  const docsLinks = {
492
478
  id: 'docs-links',
493
479
  title: 'links relativos da doc resolvem',
@@ -29,7 +29,7 @@ export function resolveScript(root, node) {
29
29
  if (fs.existsSync(direct))
30
30
  return direct;
31
31
  const base = direct.replace(/\.(mjs|cjs|js|ts)$/, '');
32
- for (const ext of ['.ts', '.js', '.ts']) {
32
+ for (const ext of ['.ts', '.js', '.mjs']) {
33
33
  if (fs.existsSync(base + ext))
34
34
  return base + ext;
35
35
  }
@@ -132,19 +132,19 @@ export const COMMANDS = {
132
132
  'sprint:start': {
133
133
  domain: 'gsd',
134
134
  desc: 'Inicia sprint',
135
- node: 'scripts/sprint-manager.js',
135
+ node: 'scripts/sprint-manager.ts',
136
136
  args: ['start'],
137
137
  },
138
138
  'sprint:status': {
139
139
  domain: 'gsd',
140
140
  desc: 'Status da sprint atual',
141
- node: 'scripts/sprint-manager.js',
141
+ node: 'scripts/sprint-manager.ts',
142
142
  args: ['status'],
143
143
  },
144
144
  'sprint:complete': {
145
145
  domain: 'gsd',
146
146
  desc: 'Encerra sprint',
147
- node: 'scripts/sprint-manager.js',
147
+ node: 'scripts/sprint-manager.ts',
148
148
  args: ['complete'],
149
149
  },
150
150
  // --- Design ---------------------------------------------------------------
@@ -201,19 +201,19 @@ export const COMMANDS = {
201
201
  'sync:universal': {
202
202
  domain: 'memoria',
203
203
  desc: 'Reindexa a memória universal (SQLite FTS5)',
204
- node: 'scripts/sync-universal-memory.js',
204
+ node: 'scripts/sync-universal-memory.ts',
205
205
  gates: ['workspace-warn'],
206
206
  },
207
207
  'query:universal': {
208
208
  domain: 'memoria',
209
209
  desc: 'Busca FTS5 na memória universal',
210
- node: 'scripts/query-universal-memory.js',
210
+ node: 'scripts/query-universal-memory.ts',
211
211
  gates: ['workspace-warn'],
212
212
  },
213
213
  'memory:compress': {
214
214
  domain: 'memoria',
215
215
  desc: 'Arquiva runs antigos e compacta memória de projeto',
216
- node: 'scripts/compress-project-memory.js',
216
+ node: 'scripts/compress-project-memory.ts',
217
217
  },
218
218
  'memory:vacuum': {
219
219
  domain: 'memoria',
@@ -228,13 +228,13 @@ export const COMMANDS = {
228
228
  'memory:extract': {
229
229
  domain: 'memoria',
230
230
  desc: 'Extrai conhecimento global da memória',
231
- node: 'scripts/extract-global-knowledge.js',
231
+ node: 'scripts/extract-global-knowledge.ts',
232
232
  },
233
233
  // --- Contexto & token economy ---------------------------------------------
234
234
  'context:smart': {
235
235
  domain: 'contexto',
236
236
  desc: 'Gera smart-context (3 modos, ADR-0003)',
237
- node: 'scripts/build-smart-context.js',
237
+ node: 'scripts/build-smart-context.ts',
238
238
  gates: ['workspace-warn'],
239
239
  },
240
240
  'context:budget': {
@@ -276,7 +276,7 @@ export const COMMANDS = {
276
276
  'project:check': {
277
277
  domain: 'governanca',
278
278
  desc: 'Standards check do framework (pre-commit)',
279
- node: 'scripts/check-standards.js',
279
+ node: 'scripts/check-standards.ts',
280
280
  },
281
281
  'tools:doctor': {
282
282
  domain: 'governanca',
@@ -291,7 +291,7 @@ export const COMMANDS = {
291
291
  'project:dashboard': {
292
292
  domain: 'governanca',
293
293
  desc: 'Gera dashboard estático de status',
294
- node: 'scripts/generate-dashboard.js',
294
+ node: 'scripts/generate-dashboard.ts',
295
295
  },
296
296
  'audit:sync': {
297
297
  domain: 'governanca',
@@ -312,6 +312,6 @@ export const COMMANDS = {
312
312
  'init:project': {
313
313
  domain: 'geracao',
314
314
  desc: 'Gera projeto direto num path (prefira project:new)',
315
- node: 'bin/init-project.js',
315
+ node: 'bin/init-project.ts',
316
316
  },
317
317
  };
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import fs from 'node:fs';
21
21
  import { worstStatus } from './checks.ts';
22
+ import type { Check } from './checks.ts';
22
23
  export { worstStatus };
23
24
  /**
24
25
  * Empacota o repo e instala o tarball num diretório temporário isolado.
@@ -37,20 +38,7 @@ export declare function withCleanInstall(fn: any, { root }?: {
37
38
  root?: string | undefined;
38
39
  }): Promise<any>;
39
40
  /** @type {import('./checks.ts').Check[]} */
40
- export declare const RELEASE_CHECKS: {
41
- id: string;
42
- title: string;
43
- severity: string;
44
- probe(env: any): {
45
- status: string;
46
- detail: string;
47
- fix: null;
48
- } | {
49
- status: string;
50
- detail: string;
51
- fix: string;
52
- };
53
- }[];
41
+ export declare const RELEASE_CHECKS: Check[];
54
42
  export declare function defaultEnv(overrides?: {}): {
55
43
  root: string;
56
44
  fs: typeof fs;
@@ -23,7 +23,6 @@ import os from 'node:os';
23
23
  import path from 'node:path';
24
24
  import { fileURLToPath } from 'node:url';
25
25
  import { runChecks as run, worstStatus, stripTemplateLiterals } from "./checks.js";
26
- /** @typedef {import('./checks.ts').Check} Check */
27
26
  import { COMMANDS, resolveScript } from "./registry.js";
28
27
  export { worstStatus };
29
28
  const __filename = fileURLToPath(import.meta.url);
@@ -112,7 +111,6 @@ export async function withCleanInstall(fn, { root = repoRoot } = {}) {
112
111
  * Severidade depende do modo: sob `--publish` é fatal; em dev é aviso — um gate que reprova todo
113
112
  * desenvolvimento local é um gate que se contorna (a lição que o CI nos deu na SPEC-009).
114
113
  */
115
- /** @type {Check} */
116
114
  const treeClean = {
117
115
  id: 'tree-clean',
118
116
  title: 'árvore limpa (o tarball é o commit)',
@@ -135,7 +133,6 @@ const treeClean = {
135
133
  },
136
134
  };
137
135
  /** Se o pacote não instala, todo o resto é irrelevante — daí todos dependerem deste. */
138
- /** @type {Check} */
139
136
  const install = {
140
137
  id: 'install',
141
138
  title: 'o pacote instala do zero',
@@ -150,7 +147,6 @@ const install = {
150
147
  * Todo comando anunciado pelo registry precisa existir no tarball. É o bug da v1.1.3, generalizado:
151
148
  * `npm run dashboard` era publicado, a pasta `dashboard/` não.
152
149
  */
153
- /** @type {Check} */
154
150
  const registryScripts = {
155
151
  id: 'registry-scripts',
156
152
  title: 'todo comando do registry existe no tarball',
@@ -266,7 +262,6 @@ function packageName(specifier) {
266
262
  return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
267
263
  }
268
264
  /** Import relativo que não resolve dentro do tarball = arquivo fora do `files[]` (bug da v1.1.3). */
269
- /** @type {Check} */
270
265
  const importsResolve = {
271
266
  id: 'imports-resolve',
272
267
  title: 'imports relativos resolvem dentro do tarball',
@@ -296,7 +291,6 @@ const importsResolve = {
296
291
  },
297
292
  };
298
293
  /** O bug do ADR-0021 §2: importado por script publicado, mas declarado como devDependency. */
299
- /** @type {Check} */
300
294
  const depsDeclared = {
301
295
  id: 'deps-declared',
302
296
  title: 'todo import externo está em dependencies',
@@ -326,7 +320,6 @@ const depsDeclared = {
326
320
  },
327
321
  };
328
322
  /** Peso morto viaja no tarball de todo usuário. Incomoda; não quebra — por isso `warn` (D7). */
329
- /** @type {Check} */
330
323
  const depsUnused = {
331
324
  id: 'deps-unused',
332
325
  title: 'nenhuma dependency é peso morto',
@@ -367,7 +360,6 @@ const depsUnused = {
367
360
  * code reprovaria um pacote saudável — a mesma armadilha do `memory-db` na SPEC-009, um nível
368
361
  * acima.
369
362
  */
370
- /** @type {Check} */
371
363
  const smokeCommands = {
372
364
  id: 'smoke-commands',
373
365
  title: 'os comandos executam de verdade',
@@ -1,7 +1,11 @@
1
+ /**
2
+ * Memory Generator - Gera estrutura completa de memória hierárquica
3
+ * Extraído de create-memory-nest-kit.js para modularização
4
+ */
1
5
  /**
2
6
  * Retorna todos os templates combinados
3
7
  */
4
- export function getAllMemoryTemplates(): {
8
+ export declare function getAllMemoryTemplates(): {
5
9
  'scripts/build-context-pack.mjs': string;
6
10
  'scripts/append-handoff.mjs': string;
7
11
  'scripts/lib/skill-loader.mjs': string;
@@ -71,13 +75,13 @@ export function getAllMemoryTemplates(): {
71
75
  * @param {string} baseDir - Diretório base para geração
72
76
  * @param {Object} options - Opções (force, noGitkeep)
73
77
  */
74
- export function generateMemoryStructure(baseDir: string, options?: any): {
78
+ export declare function generateMemoryStructure(baseDir: any, options?: {}): {
75
79
  success: boolean;
76
80
  filesWritten: number;
77
81
  emptyDirsCreated: number;
78
82
  };
79
- declare namespace _default {
80
- export { generateMemoryStructure };
81
- export { getAllMemoryTemplates };
82
- }
83
+ declare const _default: {
84
+ generateMemoryStructure: typeof generateMemoryStructure;
85
+ getAllMemoryTemplates: typeof getAllMemoryTemplates;
86
+ };
83
87
  export default _default;
@@ -3,7 +3,7 @@
3
3
  * Extraído de create-memory-nest-kit.js para modularização
4
4
  */
5
5
  import path from 'node:path';
6
- import { writeFileSafe, ensureDir, maybeGitkeep } from '../utils/file-helpers.js';
6
+ import { writeFileSafe, ensureDir, maybeGitkeep } from "../utils/file-helpers.js";
7
7
  /**
8
8
  * Template de arquivos da estrutura de memória
9
9
  * Organizado por categorias para facilitar manutenção
@@ -1,15 +1,19 @@
1
+ /**
2
+ * Nest Generator - Gera estrutura completa NestJS
3
+ * Extraído de create-memory-nest-kit.js para modularização
4
+ */
1
5
  /**
2
6
  * Gera estrutura completa do NestJS backend
3
7
  * @param {string} baseDir - Diretório base
4
8
  * @param {string} projectName - Nome do projeto
5
9
  * @param {Object} options - Opções (force, noGitkeep)
6
10
  */
7
- export function generateNestStructure(baseDir: string, projectName: string, options?: any): {
11
+ export declare function generateNestStructure(baseDir: any, projectName: any, options?: {}): {
8
12
  success: boolean;
9
13
  filesWritten: number;
10
14
  emptyDirsCreated: number;
11
15
  };
12
- declare namespace _default {
13
- export { generateNestStructure };
14
- }
16
+ declare const _default: {
17
+ generateNestStructure: typeof generateNestStructure;
18
+ };
15
19
  export default _default;
@@ -3,7 +3,7 @@
3
3
  * Extraído de create-memory-nest-kit.js para modularização
4
4
  */
5
5
  import path from 'node:path';
6
- import { writeFileSafe, ensureDir, maybeGitkeep } from '../utils/file-helpers.js';
6
+ import { writeFileSafe, ensureDir, maybeGitkeep } from "../utils/file-helpers.js";
7
7
  /**
8
8
  * Factory de templates NestJS dinâmicos
9
9
  * Recebe projectName para interpolar em package.json
@@ -1,15 +1,18 @@
1
+ /**
2
+ * README Generator - Gera README.md para novo projeto
3
+ */
1
4
  /**
2
5
  * Escreve README.md para o projeto
3
6
  * @param {string} baseDir - Diretório base
4
7
  * @param {string} projectName - Nome do projeto
5
8
  * @param {Object} options - Opções (force)
6
9
  */
7
- export function generateReadme(baseDir: string, projectName: string, options?: any): {
10
+ export declare function generateReadme(baseDir: any, projectName: any, options?: {}): {
8
11
  success: boolean;
9
12
  path: string;
10
13
  size: number;
11
14
  };
12
- declare namespace _default {
13
- export { generateReadme };
14
- }
15
+ declare const _default: {
16
+ generateReadme: typeof generateReadme;
17
+ };
15
18
  export default _default;
@@ -2,7 +2,7 @@
2
2
  * README Generator - Gera README.md para novo projeto
3
3
  */
4
4
  import path from 'node:path';
5
- import { writeFileSafe } from '../utils/file-helpers.js';
5
+ import { writeFileSafe } from "../utils/file-helpers.js";
6
6
  /**
7
7
  * Factory para README dinâmico
8
8
  */
@@ -28,7 +28,7 @@ export declare function collect(env?: {
28
28
  state: string;
29
29
  checks: {
30
30
  id: string;
31
- severity: string;
31
+ severity: import("./core/checks.ts").Severity;
32
32
  }[];
33
33
  }[];
34
34
  specs: {
@@ -1,9 +1,13 @@
1
1
  /**
2
2
  * Funções utilitárias compartilhadas para geração de arquivos
3
3
  */
4
- export function ensureDir(dirPath: any): void;
5
- export function writeFileSafe(filePath: any, content: any, options?: {}): void;
6
- export function maybeGitkeep(dirPath: any, options?: {}): void;
7
- export function log(message: any): void;
8
- export function logError(message: any): void;
9
- export function logSuccess(message: any): void;
4
+ export declare function ensureDir(dirPath: any): void;
5
+ export declare function writeFileSafe(filePath: any, content: any, options?: {
6
+ force?: boolean;
7
+ }): void;
8
+ export declare function maybeGitkeep(dirPath: any, options?: {
9
+ noGitkeep?: boolean;
10
+ }): void;
11
+ export declare function log(message: any): void;
12
+ export declare function logError(message: any): void;
13
+ export declare function logSuccess(message: any): void;
@@ -1,48 +1,70 @@
1
+ /**
2
+ * Structure Validator - Valida integridade da estrutura gerada
3
+ * Garante que todos os diretórios e arquivos críticos foram criados
4
+ */
1
5
  /**
2
6
  * Valida estrutura de memória
3
7
  * @param {string} baseDir - Diretório base
4
8
  * @returns {Object} Resultado da validação
5
9
  */
6
- export function validateMemoryStructure(baseDir: string): any;
10
+ export declare function validateMemoryStructure(baseDir: any): {
11
+ isValid: boolean;
12
+ errors: string[];
13
+ warnings: string[];
14
+ checklist: {
15
+ memoryStructure: number;
16
+ memoryFiles: number;
17
+ };
18
+ };
7
19
  /**
8
20
  * Valida estrutura NestJS
9
21
  * @param {string} baseDir - Diretório base
10
22
  * @returns {Object} Resultado da validação
11
23
  */
12
- export function validateNestStructure(baseDir: string): any;
24
+ export declare function validateNestStructure(baseDir: any): {
25
+ isValid: boolean;
26
+ errors: string[];
27
+ warnings: string[];
28
+ checklist: {
29
+ nestDirectories: number;
30
+ nestFiles: number;
31
+ };
32
+ };
13
33
  /**
14
34
  * Valida estrutura completa do projeto
15
35
  * @param {string} baseDir - Diretório base
16
36
  * @param {Object} options - Opções { includeNest: boolean }
17
37
  * @returns {Object} Resultado completo
18
38
  */
19
- export function validateProjectStructure(baseDir: string, options?: any): any;
39
+ export declare function validateProjectStructure(baseDir: any, options?: {
40
+ includeNest?: boolean;
41
+ }): {
42
+ isValid: boolean;
43
+ errors: any[];
44
+ warnings: any[];
45
+ results: {
46
+ memory: any;
47
+ nest?: any;
48
+ };
49
+ summary: {
50
+ totalErrors: number;
51
+ hasNest: boolean;
52
+ timestamp: string;
53
+ };
54
+ };
20
55
  /**
21
56
  * Imprime relatório de validação de forma amigável
22
57
  * @param {Object} report - Resultado de validateProjectStructure
23
58
  */
24
- export function printValidationReport(report: any): void;
25
- declare namespace _default {
26
- export { validateProjectStructure };
27
- export { validateMemoryStructure };
28
- export { validateNestStructure };
29
- export { printValidationReport };
30
- export { CRITICAL_FILES };
31
- export { CRITICAL_DIRS };
32
- export { NEST_CRITICAL_FILES };
33
- export { NEST_CRITICAL_DIRS };
34
- }
59
+ export declare function printValidationReport(report: any): void;
60
+ declare const _default: {
61
+ validateProjectStructure: typeof validateProjectStructure;
62
+ validateMemoryStructure: typeof validateMemoryStructure;
63
+ validateNestStructure: typeof validateNestStructure;
64
+ printValidationReport: typeof printValidationReport;
65
+ CRITICAL_FILES: string[];
66
+ CRITICAL_DIRS: string[];
67
+ NEST_CRITICAL_FILES: string[];
68
+ NEST_CRITICAL_DIRS: string[];
69
+ };
35
70
  export default _default;
36
- /**
37
- * Lista dos arquivos críticos que devem existir
38
- */
39
- declare const CRITICAL_FILES: string[];
40
- /**
41
- * Lista de diretórios críticos
42
- */
43
- declare const CRITICAL_DIRS: string[];
44
- /**
45
- * Validações específicas do NestJS backend
46
- */
47
- declare const NEST_CRITICAL_FILES: string[];
48
- declare const NEST_CRITICAL_DIRS: string[];
@@ -76,7 +76,7 @@ declare function runScript(scriptPath: any, args?: string[]): Promise<void>;
76
76
  /**
77
77
  * Context Build Handler
78
78
  */
79
- declare function contextBuild([mode, project, keyword]?: [any?, any?, any?]): Promise<void>;
79
+ declare function contextBuild([mode, project, keyword]?: string[]): Promise<void>;
80
80
  /**
81
81
  * Memory Vacuum Handler
82
82
  */
@@ -84,7 +84,7 @@ declare function memoryVacuum(): Promise<void>;
84
84
  /**
85
85
  * Memory Sync Handler
86
86
  */
87
- declare function memorySync([project]?: [any?]): Promise<void>;
87
+ declare function memorySync([project]?: string[]): Promise<void>;
88
88
  /**
89
89
  * Project Health Check
90
90
  */
@@ -143,7 +143,7 @@ async function contextBuild([mode, project, keyword] = []) {
143
143
  console.log(`Building ${mode} context for ${project}...`);
144
144
  try {
145
145
  ensureSchema({ silent: true });
146
- const builder = (await import('../lib/context-builder.js')).default;
146
+ const builder = (await import("../lib/context-builder.js")).default;
147
147
  const dbPath = getDbPath();
148
148
  const ctx = new builder(root, dbPath);
149
149
  ctx.connect();
@@ -31,7 +31,7 @@ try {
31
31
  }
32
32
  else {
33
33
  console.log(`\nResultados para: "${query}"\n`);
34
- results.forEach(r => {
34
+ results.forEach((r) => {
35
35
  const scope = r.project ? `[Projeto: ${r.project}]` : '[Global]';
36
36
  console.log(`${scope} ${r.title} (${r.path})`);
37
37
  console.log(` > ${r.snippet.replace(/\n/g, ' ')}\n`);
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { resolveProject, initWorkspace, getWorkspaceRoot } from "../lib/workspace.js";
4
+ import { resolveProject, initWorkspace } from "../lib/workspace.js";
5
5
  const __filename = fileURLToPath(import.meta.url);
6
6
  const __dirname = path.dirname(__filename);
7
7
  const root = path.resolve(__dirname, '..');
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import ContextBuilder from '../lib/context-builder.js';
14
+ import ContextBuilder from "../lib/context-builder.js";
15
15
  import { fileURLToPath } from 'node:url';
16
16
  import { getDbPath, ensureSchema } from "./memory-schema.js";
17
17
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forjajs",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "Forja — framework CLI-first de orquestração multiagente, memória hierárquica e geração de projetos com IA",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -172,14 +172,15 @@ classe "dist mente") e ADR-0024 (o gate que ganha o `build-fresh`).
172
172
  no CI. Corrigir os erros com os arquivos ainda `.mjs`. Nada renomeado ainda.
173
173
  - [x] **Fase 1 — resolver.** Registry sem extensão (na verdade: registry mantém `.mjs` e o
174
174
  `resolveScript` faz strip + tenta `.ts/.js/.mjs`), dispatch pelo resolver. Suíte verde.
175
- - [~] **Fase 2 — renomear leaf-first.** Um módulo por vez (D5), `npm test` verde a cada um.
176
- **Entregue: todos os 21 módulos `.mjs` do framework** (`lib/core/`, `lib/{audit,governance-report,
177
- workspace}`, `bin/forja`, todos os `scripts/` incl. hooks). Os typedefs JSDoc viraram `interface`
178
- real; `allowImportingTsExtensions` no type-check (build reescreve `.ts→.js`). Dois achados
179
- recorrentes no `.ts` estrito: `[]`→`never[]` (anotação inline) e os casts-comentário
180
- `/** @type */ (x)` não narram (viram `as`). **Restam**: os 16 `.js` (entries públicos
181
- `init-project`/`create-memory-nest-kit` + generators + scaffolding), que seguem no checkJs; e o
182
- `noImplicitAny: true` (endurecimento final — hoje off, ~280 params a tipar).
175
+ - [x] **Fase 2 — renomear leaf-first + endurecer.** **Concluída.** Toda a fonte do framework é `.ts`
176
+ (21 `.mjs` + 16 `.js`), e `noImplicitAny` está ON — os ~285 params foram anotados (tipo real
177
+ onde agrega, `any` explícito onde é dinâmico). Shim `lib/vendor.d.ts` para o `better-sqlite3`
178
+ sem tipos; `lib/templates` excluído do type-check (é conteúdo). O ratchet está armado.
179
+ Achados recorrentes no `.ts` estrito: `[]`→`never[]` (anotação inline), os casts-comentário
180
+ `/** @type */ (x)` não narram (viram `as`), e os typedefs JSDoc viram `interface`/`import type`
181
+ reais. Armadilha corrigida em voo: o sed que atualizava os `node:` do registry atingiu também o
182
+ array de fallback do `resolveScript` (`['.ts','.js','.mjs']`→`['.ts','.ts','.ts']`), quebrando a
183
+ resolução do `dist/*.js` — pego pelo `release:check`, não pelo type-check nem pelos testes.
183
184
  - [x] **Fase 3 — build + publish.** `tsc` emitindo `dist/`; `package.json` apontando para `dist/`;
184
185
  `prepublishOnly` = gate (o gate builda, D4 revisado). Provado por `release:check` (#15).
185
186
  - [x] Doc/persona: governança ganha o `build-fresh`; `docs/` e `CONTRIBUTING` ganham o "dev roda
@@ -1,7 +1,7 @@
1
1
  # Spec: ts-migration
2
2
 
3
3
  - **ID**: SPEC-012
4
- - **Status**: approved
4
+ - **Status**: done
5
5
  - **Owner**: apk
6
6
  - **Criado em**: 2026-07-18
7
7
  - **Sprint alvo**: S?
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
@@ -1,126 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * code-intel — camada de code intelligence sobre o codegraph (ADR-0017).
4
- *
5
- * Auto-contido: depende apenas do binario `codegraph` no PATH. Se ausente,
6
- * degrada graciosamente (avisa e segue) — nunca trava o fluxo.
7
- *
8
- * Comandos:
9
- * check Valida indice (worktree + freshness)
10
- * impact <simbolo> [d] Chamadores e blast radius de um simbolo
11
- *
12
- * Emitido por forja/init-project.js. Veja docs do framework para o GSD completo.
13
- */
14
- import { spawnSync } from 'node:child_process';
15
- function runCodegraph(args) {
16
- const result = spawnSync('codegraph', args, { encoding: 'utf8' });
17
- if (result.error && /** @type {any} */ (result.error).code === 'ENOENT')
18
- return { missing: true };
19
- return {
20
- missing: false,
21
- status: result.status ?? 1,
22
- stdout: (result.stdout || '').trim(),
23
- stderr: (result.stderr || '').trim(),
24
- };
25
- }
26
- function codegraphStatus() {
27
- const res = runCodegraph(['status', '--json']);
28
- if (res.missing)
29
- return { missing: true };
30
- let data = null;
31
- try {
32
- data = JSON.parse(/** @type {string} */ (res.stdout));
33
- }
34
- catch {
35
- return { missing: false, parseError: true, raw: res.stdout || res.stderr };
36
- }
37
- const pending = data.pendingChanges || {};
38
- const pendingTotal = (pending.added || 0) + (pending.modified || 0) + (pending.removed || 0);
39
- return {
40
- missing: false,
41
- initialized: Boolean(data.initialized),
42
- worktreeMismatch: data.worktreeMismatch || null,
43
- fileCount: data.fileCount || 0,
44
- pendingTotal,
45
- reindexRecommended: Boolean(data.index && data.index.reindexRecommended),
46
- };
47
- }
48
- function fail(msg) {
49
- console.error(msg);
50
- process.exit(1);
51
- }
52
- function cmdCheck() {
53
- const s = codegraphStatus();
54
- if (s.missing) {
55
- console.log('Codegraph nao instalado no PATH. Code intelligence ignorado.');
56
- console.log('Instale com: npm i -g @codegraph/cli');
57
- process.exit(0);
58
- }
59
- if (s.parseError) {
60
- console.log('Codegraph respondeu, mas status --json nao pode ser lido.');
61
- fail(s.raw || 'sem saida');
62
- }
63
- const lines = [];
64
- let blocking = false;
65
- if (!s.initialized) {
66
- blocking = true;
67
- lines.push('FAIL indice ausente: rode `npm run code:index`.');
68
- }
69
- else {
70
- lines.push(`OK indice inicializado (${s.fileCount} arquivos).`);
71
- }
72
- if (s.worktreeMismatch) {
73
- blocking = true;
74
- lines.push(`FAIL indice de outro worktree: ${s.worktreeMismatch}. Rode \`codegraph init -i\`.`);
75
- }
76
- else if (s.initialized) {
77
- lines.push('OK indice pertence a este worktree.');
78
- }
79
- if (s.pendingTotal > 0 || s.reindexRecommended) {
80
- lines.push(`WARN indice defasado (${s.pendingTotal} pend.). Rode \`npm run code:sync\`.`);
81
- }
82
- else if (s.initialized) {
83
- lines.push('OK indice em dia.');
84
- }
85
- console.log('Codegraph check:\n');
86
- for (const line of lines)
87
- console.log(line);
88
- if (blocking)
89
- fail('\nResultado: gate de code intelligence reprovado.');
90
- console.log('\nResultado: code intelligence confiavel.');
91
- }
92
- function cmdImpact(symbol, depthArg) {
93
- if (!symbol)
94
- fail('Uso: code-intel impact <simbolo> [profundidade]');
95
- const probe = runCodegraph(['status', '--json']);
96
- if (probe.missing) {
97
- console.log('Codegraph nao instalado. Sem mapa de impacto automatico.');
98
- console.log(`Fallback manual: grep -rn "${symbol}" . e leia os chamadores.`);
99
- process.exit(0);
100
- }
101
- const depth = String(parseInt(depthArg, 10) || 2);
102
- console.log(`Mapa de impacto: ${symbol} (profundidade ${depth})\n`);
103
- const impact = runCodegraph(['impact', symbol, '-d', depth]);
104
- if (impact.stdout)
105
- console.log(impact.stdout);
106
- const callers = runCodegraph(['callers', symbol]);
107
- if (callers.stdout) {
108
- console.log('\n--- Chamadores diretos ---');
109
- console.log(callers.stdout);
110
- }
111
- if (!impact.stdout && !callers.stdout) {
112
- console.log('Nenhum no encontrado. Confirme o nome ou rode `npm run code:sync`.');
113
- }
114
- }
115
- const [cmd, ...rest] = process.argv.slice(2);
116
- switch (cmd) {
117
- case 'check':
118
- cmdCheck();
119
- break;
120
- case 'impact':
121
- cmdImpact(rest[0], rest[1]);
122
- break;
123
- default:
124
- console.log('Uso: node scripts/code-intel.mjs <check|impact> [args]');
125
- process.exit(cmd ? 1 : 0);
126
- }