forjajs 5.1.0 → 5.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.
Files changed (113) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +37 -4
  3. package/README.pt-BR.md +39 -4
  4. package/dist/apps/cli/src/index.d.ts +0 -1
  5. package/dist/apps/cli/src/index.js +43 -32
  6. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
  7. package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
  8. package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
  9. package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
  10. package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
  11. package/dist/apps/server/src/forja-nest.module.js +55 -0
  12. package/dist/apps/server/src/main.d.ts +21 -4
  13. package/dist/apps/server/src/main.js +79 -57
  14. package/dist/apps/server/src/task-planning-service.d.ts +29 -0
  15. package/dist/apps/server/src/task-planning-service.js +195 -0
  16. package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
  17. package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
  18. package/dist/bin/forja.js +3 -2
  19. package/dist/lib/agent-evals.d.ts +138 -0
  20. package/dist/lib/agent-evals.js +349 -0
  21. package/dist/lib/cli-output.js +14 -2
  22. package/dist/lib/code-context.d.ts +33 -5
  23. package/dist/lib/code-context.js +70 -5
  24. package/dist/lib/context-builder.d.ts +49 -4
  25. package/dist/lib/context-builder.js +114 -47
  26. package/dist/lib/core/coverage-gate.d.ts +59 -0
  27. package/dist/lib/core/coverage-gate.js +58 -0
  28. package/dist/lib/core/doc-graph.d.ts +38 -0
  29. package/dist/lib/core/doc-graph.js +83 -0
  30. package/dist/lib/core/health.js +286 -5
  31. package/dist/lib/core/journey.js +26 -0
  32. package/dist/lib/core/registry.js +81 -6
  33. package/dist/lib/docs-reference.d.ts +35 -0
  34. package/dist/lib/docs-reference.js +57 -0
  35. package/dist/lib/project-wiring.js +6 -2
  36. package/dist/lib/session-memory.d.ts +38 -0
  37. package/dist/lib/session-memory.js +206 -0
  38. package/dist/lib/spec-trace.d.ts +46 -0
  39. package/dist/lib/spec-trace.js +184 -0
  40. package/dist/packages/adapter-nest/src/index.d.ts +2 -1
  41. package/dist/packages/adapter-nest/src/index.js +59 -1
  42. package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
  43. package/dist/packages/adapter-sqlite/src/index.js +61 -1
  44. package/dist/packages/context/src/index.d.ts +2 -0
  45. package/dist/packages/context/src/index.js +36 -15
  46. package/dist/packages/contracts/src/index.d.ts +64 -0
  47. package/dist/packages/core/src/index.d.ts +9 -1
  48. package/dist/packages/core/src/index.js +28 -3
  49. package/dist/packages/graph/src/index.js +14 -5
  50. package/dist/packages/mcp/src/index.d.ts +8 -0
  51. package/dist/packages/mcp/src/index.js +12 -1
  52. package/dist/packages/observability/src/index.d.ts +11 -0
  53. package/dist/packages/observability/src/index.js +3 -0
  54. package/dist/packages/orchestration/src/index.d.ts +15 -1
  55. package/dist/packages/orchestration/src/index.js +127 -21
  56. package/dist/packages/planner/src/index.d.ts +7 -1
  57. package/dist/packages/planner/src/index.js +67 -10
  58. package/dist/packages/planner/src/proposal-store.d.ts +30 -0
  59. package/dist/packages/planner/src/proposal-store.js +109 -0
  60. package/dist/packages/policy/src/index.d.ts +9 -16
  61. package/dist/packages/policy/src/index.js +114 -31
  62. package/dist/packages/runtime/src/index.d.ts +16 -2
  63. package/dist/packages/runtime/src/index.js +176 -61
  64. package/dist/scripts/build-smart-context.d.ts +2 -0
  65. package/dist/scripts/build-smart-context.js +12 -3
  66. package/dist/scripts/code-context.d.ts +3 -1
  67. package/dist/scripts/code-context.js +13 -3
  68. package/dist/scripts/coverage-gate.d.ts +2 -0
  69. package/dist/scripts/coverage-gate.js +101 -0
  70. package/dist/scripts/eval-agents.d.ts +11 -0
  71. package/dist/scripts/eval-agents.js +96 -0
  72. package/dist/scripts/gen-commands-doc.d.ts +2 -0
  73. package/dist/scripts/gen-commands-doc.js +18 -0
  74. package/dist/scripts/hook-session-memory.d.ts +9 -0
  75. package/dist/scripts/hook-session-memory.js +20 -0
  76. package/dist/scripts/hook-session-start.js +34 -0
  77. package/dist/scripts/spec-trace.d.ts +10 -0
  78. package/dist/scripts/spec-trace.js +73 -0
  79. package/dist/scripts/sync-universal-memory.js +69 -4
  80. package/dist/scripts/token-benchmark.d.ts +33 -1
  81. package/dist/scripts/token-benchmark.js +179 -5
  82. package/dist/scripts/token-economy.js +3 -1
  83. package/dist/scripts/tools-doctor.d.ts +16 -1
  84. package/dist/scripts/tools-doctor.js +58 -17
  85. package/docs/commands.md +155 -0
  86. package/docs/fluxo.md +11 -7
  87. package/docs/init-project.md +3 -1
  88. package/docs/llm-fit-loop.md +20 -0
  89. package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
  90. package/docs/produto/factsheet-marketing.md +7 -5
  91. package/docs/produto/roteiro-demo.md +14 -5
  92. package/docs/quick-reference.md +3 -3
  93. package/docs/token-optimization.md +10 -6
  94. package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
  95. package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
  96. package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
  97. package/package.json +4 -2
  98. package/specs/avaliacoes-de-agentes/spec.md +52 -0
  99. package/specs/criterios-ligados-a-testes/spec.md +42 -0
  100. package/specs/memoria-de-sessao/spec.md +48 -0
  101. package/specs/v6-agent-runtime-portable/spec.md +83 -0
  102. package/specs/v6-core-consolidation/spec.md +70 -0
  103. package/specs/v6-docs-drift/spec.md +85 -0
  104. package/specs/v6-quality-gates/spec.md +99 -0
  105. package/specs/v6-token-economy/spec.md +84 -0
  106. package/templates/evals/agents/adr.json +25 -0
  107. package/templates/evals/agents/memoria.json +32 -0
  108. package/templates/evals/agents/proxima-acao.json +29 -0
  109. package/templates/evals/agents/spec-nova.json +26 -0
  110. package/templates/evals/agents/teste-do-criterio.json +29 -0
  111. package/templates/project/AGENTS.md +7 -0
  112. package/templates/project/CLAUDE.md +3 -2
  113. package/templates/project/skills/testing/SKILL.md +1 -1
@@ -0,0 +1,57 @@
1
+ /**
2
+ * lib/docs-reference.ts — o lado "código" da coerência de documentação (SPEC-055).
3
+ *
4
+ * A leitura da doc como dado vive em `core/doc-graph.ts` (scanCommands/scanFlags/scanSkillCounts) e
5
+ * o juízo vive nos checks de `core/health.ts`. Aqui ficam só as três referências derivadas do código
6
+ * contra as quais a doc é comparada:
7
+ *
8
+ * declaredFlags o que cada comando aceita (usage + examples do registry + flags do dispatcher)
9
+ * skillsCount quantas skills existem de fato em templates/project/skills
10
+ * renderCommandsDoc a referência completa de comandos, gerada — conteúdo de docs/commands.md
11
+ *
12
+ * Não há scanner próprio de propósito: um segundo scanner de markdown diverge do primeiro com o
13
+ * tempo, e divergência entre superfícies que deveriam concordar é o defeito que a SPEC-009 matou.
14
+ */
15
+ import { flagTokens } from './core/doc-graph.js';
16
+ /** Flags tratadas pelo dispatcher (bin/forja.ts), não pelo comando — valem em qualquer linha. */
17
+ export const GLOBAL_FLAGS = new Set(['--help', '-h', '--json']);
18
+ /** Flags que um comando declara em `usage`/`examples`, mais as globais do dispatcher. */
19
+ export function declaredFlags(spec) {
20
+ const source = [spec.usage ?? '', ...(spec.examples ?? [])].join(' ');
21
+ return new Set([...GLOBAL_FLAGS, ...flagTokens(source)]);
22
+ }
23
+ /**
24
+ * Skills reais distribuídas aos projetos gerados — só diretórios (o README.md da pasta não conta).
25
+ * Recebe o diretório pronto para não impor separador de caminho nenhum (portável entre SOs).
26
+ */
27
+ export function skillsCount(fsLike, skillsDir) {
28
+ if (!fsLike.existsSync(skillsDir))
29
+ return 0;
30
+ return fsLike.readdirSync(skillsDir, { withFileTypes: true }).filter((e) => e.isDirectory()).length;
31
+ }
32
+ /** Referência completa de comandos, gerada do registry — conteúdo canônico de docs/commands.md. */
33
+ export function renderCommandsDoc(registry, skills) {
34
+ const domains = [];
35
+ for (const spec of Object.values(registry)) {
36
+ if (!domains.includes(spec.domain))
37
+ domains.push(spec.domain);
38
+ }
39
+ const cell = (v) => v.replace(/\|/g, '\\|');
40
+ const out = [
41
+ '# Referência de comandos',
42
+ '',
43
+ '> Gerado por `forja docs:gen` a partir de `lib/core/registry.ts` — **não edite à mão.**',
44
+ `> ${Object.keys(registry).length} comandos · ${skills} skills distribuídas aos projetos gerados.`,
45
+ '',
46
+ ];
47
+ for (const domain of domains) {
48
+ out.push(`## ${domain}`, '', '| Comando | O que faz | Uso | Tier | Gates |', '|---|---|---|---|---|');
49
+ for (const [name, spec] of Object.entries(registry)) {
50
+ if (spec.domain !== domain)
51
+ continue;
52
+ out.push(`| \`forja ${name}\` | ${cell(spec.desc)} | \`${cell(spec.usage ?? `forja ${name}`)}\` | ${spec.tier ?? 'advanced'} | ${spec.gates?.join(', ') ?? '—'} |`);
53
+ }
54
+ out.push('');
55
+ }
56
+ return out.join('\n');
57
+ }
@@ -52,7 +52,8 @@ export function templateSkills() {
52
52
  export function skillProblem(name, text) {
53
53
  if (text == null)
54
54
  return 'ausente';
55
- const m = text.match(/^---\nname: ([^\n]+)\ndescription: ([^\n]+)\n/);
55
+ // `\r?\n`: no Windows o checkout traz CRLF, e uma skill perfeitamente válida seria lida como inválida.
56
+ const m = text.match(/^---\r?\nname: ([^\r\n]+)\r?\ndescription: ([^\r\n]+)\r?\n/);
56
57
  if (!m)
57
58
  return 'frontmatter sem name/description';
58
59
  if (m[1].trim() !== name)
@@ -64,6 +65,9 @@ export const ROLES = ['orchestrator', 'product', 'sdd-architect', 'context-engin
64
65
  export const HOOKS = {
65
66
  SessionStart: 'hook:session-start',
66
67
  UserPromptSubmit: 'hook:user-prompt',
68
+ // SPEC-052: checkpoint da sessão ao fim de cada turno e antes de compactar.
69
+ Stop: 'hook:session-memory',
70
+ PreCompact: 'hook:session-memory',
67
71
  };
68
72
  export function hookCommand(cmd) {
69
73
  return `command -v forja >/dev/null 2>&1 && forja ${cmd} || true`;
@@ -346,7 +350,7 @@ export function checkProjectWiring(dir, { commands, ai }) {
346
350
  }
347
351
  if (settings !== undefined) {
348
352
  const missing = Object.entries(HOOKS).filter(([event, cmd]) => !(settings?.hooks?.[event] || []).some((g) => (g.hooks || []).some((h) => String(h.command || '').includes(`forja ${cmd}`))));
349
- add('claude-hooks', missing.length ? 'fail' : 'ok', missing.length ? `hooks ausentes: ${missing.map(([e]) => e).join(', ')}` : 'SessionStart + UserPromptSubmit');
353
+ add('claude-hooks', missing.length ? 'fail' : 'ok', missing.length ? `hooks ausentes: ${missing.map(([e]) => e).join(', ')}` : Object.keys(HOOKS).join(' + '));
350
354
  }
351
355
  const absent = ROLES.filter((r) => !fs.existsSync(path.join(dir, '.claude', 'agents', `${r}.md`)));
352
356
  add('claude-agents', absent.length ? 'fail' : 'ok', absent.length ? `sub-agents ausentes: ${absent.join(', ')}` : `${ROLES.length} sub-agents`);
@@ -0,0 +1,38 @@
1
+ /**
2
+ * lib/session-memory.ts — checkpoint determinístico de uma sessão do Claude Code (SPEC-052, ADR-0091).
3
+ *
4
+ * Lê o transcript JSONL que o Claude Code passa aos hooks e extrai só fatos estruturais: título da
5
+ * sessão, branch, arquivos editados, comandos `forja`, specs tocadas e assuntos de commit. Nunca o
6
+ * texto de prompts, comandos inteiros ou saídas de ferramenta: o checkpoint vai para `memory/`, que é
7
+ * commitada, e um segredo colado no chat não pode acabar no git.
8
+ *
9
+ * O formato do transcript não é contrato público: o que não for reconhecido é ignorado.
10
+ */
11
+ export interface SessionDigest {
12
+ readonly sessionId: string;
13
+ readonly title: string | null;
14
+ readonly branch: string | null;
15
+ readonly startedAt: string | null;
16
+ readonly updatedAt: string | null;
17
+ readonly files: readonly string[];
18
+ readonly forjaCommands: readonly string[];
19
+ readonly specs: readonly string[];
20
+ readonly commits: readonly string[];
21
+ }
22
+ /**
23
+ * Lê o transcript e devolve o resumo. `root` é a raiz do projeto: arquivos fora dela não entram.
24
+ * Linhas sem `tool_use` nem `ai-title` são descartadas antes do `JSON.parse` (transcripts têm MBs).
25
+ */
26
+ export declare function digestTranscript(transcriptPath: string, root: string, sessionId: string): SessionDigest;
27
+ /** Sessão sem edição, sem comando forja e sem commit não é memória: é conversa. */
28
+ export declare function hasWork(d: SessionDigest): boolean;
29
+ export declare function checkpointPath(root: string, d: Pick<SessionDigest, 'sessionId' | 'startedAt'>): string;
30
+ export declare function renderCheckpoint(d: SessionDigest, event: string): string;
31
+ /** Grava (ou reescreve) o checkpoint. Devolve o caminho, ou null quando não há trabalho a registrar. */
32
+ export declare function writeCheckpoint(root: string, transcriptPath: string, sessionId: string, event: string): string | null;
33
+ /** Checkpoint desta sessão (para o SessionStart `compact`), ou null. */
34
+ export declare function findCheckpoint(root: string, sessionId: string): string | null;
35
+ /** Checkpoint mais recente (por mtime), exceto o da sessão atual. */
36
+ export declare function latestCheckpoint(root: string, exceptSessionId?: string): string | null;
37
+ /** Uma linha sobre um checkpoint: data, título, nº de arquivos, specs. */
38
+ export declare function summarizeCheckpoint(file: string): string;
@@ -0,0 +1,206 @@
1
+ /**
2
+ * lib/session-memory.ts — checkpoint determinístico de uma sessão do Claude Code (SPEC-052, ADR-0091).
3
+ *
4
+ * Lê o transcript JSONL que o Claude Code passa aos hooks e extrai só fatos estruturais: título da
5
+ * sessão, branch, arquivos editados, comandos `forja`, specs tocadas e assuntos de commit. Nunca o
6
+ * texto de prompts, comandos inteiros ou saídas de ferramenta: o checkpoint vai para `memory/`, que é
7
+ * commitada, e um segredo colado no chat não pode acabar no git.
8
+ *
9
+ * O formato do transcript não é contrato público: o que não for reconhecido é ignorado.
10
+ */
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { COMMANDS } from './core/registry.js';
14
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
15
+ const SESSIONS_DIR = path.join('memory', '60-runs', 'sessions');
16
+ /** `forja spec:new x`, `npx forja status`, `node bin/forja.ts spec:check` → nome do subcomando. */
17
+ const FORJA_CMD = /(?:^|[\s;&|(])(?:npx\s+)?(?:forja|node\s+\S*bin\/forja\.[jt]s)\s+([a-z][\w-]*(?::[\w-]+)*)/g;
18
+ /** `forja spec:plan <slug>` e afins: o slug é a spec tocada (não é texto livre do usuário). */
19
+ const FORJA_SPEC = /forja(?:\.[jt]s)?\s+spec:[a-z]+\s+([a-z0-9][a-z0-9-]*)/g;
20
+ // O heredoc vem primeiro: `-m "$(cat <<'EOF'` também casaria a alternativa de aspas.
21
+ /** `specs/<slug>/` citado num comando (caminho, não texto livre); filtrado depois pelas specs que existem. */
22
+ const SPEC_PATH = /(?:^|[\s'"=(])(?:\.\/)?specs\/([a-z0-9][a-z0-9-]*)\//g;
23
+ const COMMIT_MSG = /git\s+commit\b[^\n]*?\s-[a-zA-Z]*m\s+(?:"?\$\(cat\s+<<-?\s*'?EOF'?\n([^\n]+)|"([^"\n]+)|'([^'\n]+))/;
24
+ function relativeTo(root, file) {
25
+ const abs = path.resolve(root, file);
26
+ const rel = path.relative(root, abs);
27
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
28
+ return null;
29
+ return rel.split(path.sep).join('/');
30
+ }
31
+ function specOf(rel) {
32
+ const m = rel.match(/^specs\/([^/_.][^/]*)\//);
33
+ return m ? m[1] : null;
34
+ }
35
+ /**
36
+ * Lê o transcript e devolve o resumo. `root` é a raiz do projeto: arquivos fora dela não entram.
37
+ * Linhas sem `tool_use` nem `ai-title` são descartadas antes do `JSON.parse` (transcripts têm MBs).
38
+ */
39
+ export function digestTranscript(transcriptPath, root, sessionId) {
40
+ const raw = fs.readFileSync(transcriptPath, 'utf8');
41
+ let title = null;
42
+ let branch = null;
43
+ let startedAt = null;
44
+ let updatedAt = null;
45
+ const files = new Set();
46
+ const commands = new Set();
47
+ const specs = new Set();
48
+ const commits = [];
49
+ // Uma ferramenta só conta quando o resultado volta sem erro: edição negada ou commit que falhou
50
+ // não é trabalho feito. Guardamos o efeito pelo id do tool_use e aplicamos no tool_result.
51
+ const pending = new Map();
52
+ for (const line of raw.split('\n')) {
53
+ if (!line)
54
+ continue;
55
+ const relevant = line.includes('"tool_use"') || line.includes('"tool_result"') || line.includes('"ai-title"')
56
+ || (!startedAt && line.includes('"timestamp"'));
57
+ if (!relevant)
58
+ continue;
59
+ let e;
60
+ try {
61
+ e = JSON.parse(line);
62
+ }
63
+ catch {
64
+ continue;
65
+ }
66
+ if (e.type === 'ai-title' && typeof e.aiTitle === 'string') {
67
+ title = e.aiTitle;
68
+ continue;
69
+ }
70
+ if (typeof e.timestamp === 'string') {
71
+ startedAt ??= e.timestamp;
72
+ updatedAt = e.timestamp;
73
+ }
74
+ if (typeof e.gitBranch === 'string' && e.gitBranch)
75
+ branch = e.gitBranch;
76
+ const content = Array.isArray(e.message?.content) ? e.message.content : [];
77
+ for (const c of content) {
78
+ if (c?.type === 'tool_result') {
79
+ const apply = pending.get(c.tool_use_id);
80
+ if (apply && c.is_error !== true)
81
+ apply();
82
+ pending.delete(c.tool_use_id);
83
+ continue;
84
+ }
85
+ if (c?.type !== 'tool_use' || !c.input || typeof c.id !== 'string')
86
+ continue;
87
+ if (EDIT_TOOLS.has(c.name)) {
88
+ const target = c.input.file_path ?? c.input.notebook_path;
89
+ const rel = typeof target === 'string' ? relativeTo(root, target) : null;
90
+ if (rel)
91
+ pending.set(c.id, () => {
92
+ files.add(rel);
93
+ const s = specOf(rel);
94
+ if (s)
95
+ specs.add(s);
96
+ });
97
+ }
98
+ else if (c.name === 'Bash' && typeof c.input.command === 'string') {
99
+ const cmd = c.input.command;
100
+ pending.set(c.id, () => {
101
+ // Só nomes do registry: texto de heredoc ("forja e ...") não vira comando.
102
+ for (const m of cmd.matchAll(FORJA_CMD))
103
+ if (m[1] in COMMANDS)
104
+ commands.add(m[1]);
105
+ for (const m of cmd.matchAll(FORJA_SPEC))
106
+ specs.add(m[1]);
107
+ for (const m of cmd.matchAll(SPEC_PATH))
108
+ specs.add(m[1]);
109
+ const cm = cmd.match(COMMIT_MSG);
110
+ const subject = cm && (cm[1] ?? cm[2] ?? cm[3])?.trim();
111
+ if (subject && !commits.includes(subject))
112
+ commits.push(subject.slice(0, 120));
113
+ });
114
+ }
115
+ }
116
+ }
117
+ // Só specs que existem no projeto: um slug citado à toa não vira memória.
118
+ const realSpecs = [...specs].filter((s) => fs.existsSync(path.join(root, 'specs', s, 'spec.md'))).sort();
119
+ return { sessionId, title, branch, startedAt, updatedAt, files: [...files].sort(), forjaCommands: [...commands].sort(), specs: realSpecs, commits };
120
+ }
121
+ /** Sessão sem edição, sem comando forja e sem commit não é memória: é conversa. */
122
+ export function hasWork(d) {
123
+ return d.files.length > 0 || d.forjaCommands.length > 0 || d.commits.length > 0;
124
+ }
125
+ export function checkpointPath(root, d) {
126
+ const day = (d.startedAt ?? new Date().toISOString()).slice(0, 10);
127
+ const id = d.sessionId.replace(/[^a-zA-Z0-9-]/g, '').slice(0, 8) || 'sessao';
128
+ return path.join(root, SESSIONS_DIR, `${day}-${id}.md`);
129
+ }
130
+ const MAX_FILES = 60;
131
+ export function renderCheckpoint(d, event) {
132
+ const lines = [`# Sessão ${d.sessionId.slice(0, 8)}${d.title ? ` — ${d.title}` : ''}`, ''];
133
+ lines.push(`- **Sessão**: ${d.sessionId}`);
134
+ if (d.branch)
135
+ lines.push(`- **Branch**: ${d.branch}`);
136
+ if (d.startedAt)
137
+ lines.push(`- **Início**: ${d.startedAt}`);
138
+ if (d.updatedAt)
139
+ lines.push(`- **Atualizado**: ${d.updatedAt} (${event})`);
140
+ lines.push(`- **Specs**: ${d.specs.length ? d.specs.join(', ') : '—'}`);
141
+ lines.push('');
142
+ if (d.commits.length) {
143
+ lines.push('## Commits', '', ...d.commits.map((c) => `- ${c}`), '');
144
+ }
145
+ if (d.files.length) {
146
+ lines.push(`## Arquivos editados (${d.files.length})`, '');
147
+ lines.push(...d.files.slice(0, MAX_FILES).map((f) => `- \`${f}\``));
148
+ if (d.files.length > MAX_FILES)
149
+ lines.push(`- … e mais ${d.files.length - MAX_FILES}`);
150
+ lines.push('');
151
+ }
152
+ if (d.forjaCommands.length) {
153
+ lines.push('## Comandos forja', '', d.forjaCommands.map((c) => `\`${c}\``).join(' · '), '');
154
+ }
155
+ lines.push('<!-- forja:session-memory — gerado pelos hooks Stop/PreCompact (ADR-0091). Sem texto de prompt. -->');
156
+ return `${lines.join('\n')}\n`;
157
+ }
158
+ /** Grava (ou reescreve) o checkpoint. Devolve o caminho, ou null quando não há trabalho a registrar. */
159
+ export function writeCheckpoint(root, transcriptPath, sessionId, event) {
160
+ if (!fs.existsSync(path.join(root, 'memory')))
161
+ return null;
162
+ const d = digestTranscript(transcriptPath, root, sessionId);
163
+ if (!hasWork(d))
164
+ return null;
165
+ const file = checkpointPath(root, d);
166
+ fs.mkdirSync(path.dirname(file), { recursive: true });
167
+ fs.writeFileSync(file, renderCheckpoint(d, event), 'utf8');
168
+ return file;
169
+ }
170
+ /** Checkpoint desta sessão (para o SessionStart `compact`), ou null. */
171
+ export function findCheckpoint(root, sessionId) {
172
+ const dir = path.join(root, SESSIONS_DIR);
173
+ const id = sessionId.replace(/[^a-zA-Z0-9-]/g, '').slice(0, 8);
174
+ if (!id)
175
+ return null;
176
+ try {
177
+ const hit = fs.readdirSync(dir).filter((n) => n.endsWith(`-${id}.md`)).sort().pop();
178
+ return hit ? path.join(dir, hit) : null;
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ }
184
+ /** Checkpoint mais recente (por mtime), exceto o da sessão atual. */
185
+ export function latestCheckpoint(root, exceptSessionId) {
186
+ const dir = path.join(root, SESSIONS_DIR);
187
+ const skip = exceptSessionId ? `-${exceptSessionId.replace(/[^a-zA-Z0-9-]/g, '').slice(0, 8)}.md` : null;
188
+ try {
189
+ const files = fs.readdirSync(dir).filter((n) => n.endsWith('.md') && (!skip || !n.endsWith(skip)))
190
+ .map((n) => ({ n, t: fs.statSync(path.join(dir, n)).mtimeMs }))
191
+ .sort((a, b) => b.t - a.t);
192
+ return files.length ? path.join(dir, files[0].n) : null;
193
+ }
194
+ catch {
195
+ return null;
196
+ }
197
+ }
198
+ /** Uma linha sobre um checkpoint: data, título, nº de arquivos, specs. */
199
+ export function summarizeCheckpoint(file) {
200
+ const text = fs.readFileSync(file, 'utf8');
201
+ const title = text.match(/^# Sessão \S+(?: — (.+))?$/m)?.[1] ?? 'sem título';
202
+ const updated = text.match(/^- \*\*Atualizado\*\*: (\S+)/m)?.[1]?.slice(0, 16).replace('T', ' ') ?? '?';
203
+ const nFiles = text.match(/^## Arquivos editados \((\d+)\)/m)?.[1] ?? '0';
204
+ const specs = text.match(/^- \*\*Specs\*\*: (.+)$/m)?.[1] ?? '—';
205
+ return `${updated} — ${title} · ${nFiles} arquivo(s) · specs: ${specs}`;
206
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * lib/spec-trace.ts — critérios de aceite ligados aos testes que os citam (SPEC-053, ADR-0092).
3
+ *
4
+ * A ligação mora no teste: `SPEC-NNN AC-N` ou `<slug> AC-N` no nome ou num comentário; `AC-N`
5
+ * sozinho vale quando o arquivo cita uma única spec. Estático (não roda testes), qualquer stack.
6
+ */
7
+ export interface Criterion {
8
+ readonly id: string;
9
+ readonly text: string;
10
+ }
11
+ export interface TestRef {
12
+ readonly file: string;
13
+ readonly line: number;
14
+ }
15
+ export interface SpecTrace {
16
+ readonly slug: string;
17
+ readonly specId: string | null;
18
+ readonly status: string;
19
+ readonly criteria: readonly {
20
+ id: string;
21
+ text: string;
22
+ tests: readonly TestRef[];
23
+ }[];
24
+ readonly uncovered: readonly string[];
25
+ readonly orphans: readonly {
26
+ ac: string;
27
+ ref: TestRef;
28
+ }[];
29
+ }
30
+ export interface TraceReport {
31
+ readonly specs: readonly SpecTrace[];
32
+ readonly testFiles: number;
33
+ /** `AC-N` sem spec identificável (arquivo cita 0 ou várias specs). */
34
+ readonly ambiguous: readonly {
35
+ ac: string;
36
+ ref: TestRef;
37
+ reason: string;
38
+ }[];
39
+ }
40
+ /** Status em que "pronto" já foi prometido: o `--strict` cobra a rastreabilidade. */
41
+ export declare const GATED_STATUSES: Set<string>;
42
+ export declare function parseCriteria(specText: string): Criterion[];
43
+ export declare function isTestFile(rel: string): boolean;
44
+ export declare function traceSpecs(root: string): TraceReport;
45
+ /** Specs que reprovam no `--strict`: status com "pronto" prometido e lacuna de rastreio. */
46
+ export declare function strictFailures(specs: readonly SpecTrace[]): SpecTrace[];
@@ -0,0 +1,184 @@
1
+ /**
2
+ * lib/spec-trace.ts — critérios de aceite ligados aos testes que os citam (SPEC-053, ADR-0092).
3
+ *
4
+ * A ligação mora no teste: `SPEC-NNN AC-N` ou `<slug> AC-N` no nome ou num comentário; `AC-N`
5
+ * sozinho vale quando o arquivo cita uma única spec. Estático (não roda testes), qualquer stack.
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { spawnSync } from 'node:child_process';
10
+ /** Status em que "pronto" já foi prometido: o `--strict` cobra a rastreabilidade. */
11
+ export const GATED_STATUSES = new Set(['approved', 'implementing', 'done']);
12
+ // `AC-1 (RF-01): …` também: agentes ligam o critério ao requisito entre parênteses.
13
+ const AC_LINE = /^\s*[-*]\s*(?:\[[ xX]\]\s*)?\**(AC-\d+)\**(?:\s*\([^)\n]*\))?\s*[:—–-]\s*(.+)$/;
14
+ const SPEC_ID = /\*\*ID\*\*:\s*(SPEC-\d+)/;
15
+ const STATUS = /-\s*\*\*Status\*\*:\s*([a-z-]+)/i;
16
+ const CODE_EXT = /\.(?:[cm]?[jt]sx?|py|go|rb|java|kt|cs|php|rs|swift|exs?)$/;
17
+ const TEST_NAME = /(?:\.(?:test|spec)\.[cm]?[jt]sx?$|^test_.+\.py$|_test\.(?:py|go)$|Tests?\.(?:java|kt|cs)$|_spec\.rb$)/;
18
+ const TEST_DIRS = new Set(['test', 'tests', '__tests__', 'spec']);
19
+ const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', '.git', 'vendor', 'target', 'fixtures', '__fixtures__', '__snapshots__']);
20
+ /** Grupo qualificado: `SPEC-029 AC-5/AC-6`, `pagamentos AC-1, AC-2`, `SPEC-053 (AC-3)`. */
21
+ const QUALIFIED = /\b(SPEC-\d+|[a-z0-9]+(?:-[a-z0-9]+)*)[\s#:(]+(AC-\d+(?:\s*(?:\/|,|&|\be\b|\band\b)?\s*AC-\d+)*)/g;
22
+ const AC_TOKEN = /\bAC-\d+\b/g;
23
+ export function parseCriteria(specText) {
24
+ const out = [];
25
+ for (const line of specText.split('\n')) {
26
+ const m = line.match(AC_LINE);
27
+ if (m && !out.some((c) => c.id === m[1]))
28
+ out.push({ id: m[1], text: m[2].trim() });
29
+ }
30
+ return out;
31
+ }
32
+ export function isTestFile(rel) {
33
+ const parts = rel.split('/');
34
+ if (parts.some((p) => SKIP_DIRS.has(p)))
35
+ return false;
36
+ const base = parts[parts.length - 1];
37
+ if (TEST_NAME.test(base))
38
+ return true;
39
+ return CODE_EXT.test(base) && parts.slice(0, -1).some((p) => TEST_DIRS.has(p));
40
+ }
41
+ function listFiles(root) {
42
+ const git = spawnSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
43
+ if (git.status === 0)
44
+ return git.stdout.split('\n').filter(Boolean);
45
+ const out = [];
46
+ const walk = (dir, rel) => {
47
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
48
+ if (e.name.startsWith('.') || SKIP_DIRS.has(e.name))
49
+ continue;
50
+ const r = rel ? `${rel}/${e.name}` : e.name;
51
+ if (e.isDirectory())
52
+ walk(path.join(dir, e.name), r);
53
+ else if (e.isFile())
54
+ out.push(r);
55
+ }
56
+ };
57
+ walk(root, '');
58
+ return out;
59
+ }
60
+ function loadSpecs(root) {
61
+ const dir = path.join(root, 'specs');
62
+ let slugs = [];
63
+ try {
64
+ slugs = fs.readdirSync(dir).filter((s) => !s.startsWith('_') && !s.startsWith('.'));
65
+ }
66
+ catch {
67
+ return [];
68
+ }
69
+ const out = [];
70
+ for (const slug of slugs.sort()) {
71
+ let text;
72
+ try {
73
+ text = fs.readFileSync(path.join(dir, slug, 'spec.md'), 'utf8');
74
+ }
75
+ catch {
76
+ continue;
77
+ }
78
+ out.push({ slug, specId: text.match(SPEC_ID)?.[1] ?? null, status: text.match(STATUS)?.[1]?.toLowerCase() ?? 'unknown', criteria: parseCriteria(text) });
79
+ }
80
+ return out;
81
+ }
82
+ export function traceSpecs(root) {
83
+ const specs = loadSpecs(root);
84
+ const bySlug = new Map(specs.map((s) => [s.slug, s]));
85
+ const byId = new Map();
86
+ for (const s of specs)
87
+ if (s.specId && !byId.has(s.specId))
88
+ byId.set(s.specId, s);
89
+ const resolve = (q) => byId.get(q) ?? bySlug.get(q) ?? null;
90
+ const hits = new Map(); // `${slug}#AC-N` → refs
91
+ const orphans = new Map();
92
+ const ambiguous = [];
93
+ const has = (spec, ac) => spec.criteria.some((c) => c.id === ac);
94
+ const cite = (spec, ac, ref) => {
95
+ if (has(spec, ac)) {
96
+ const k = `${spec.slug}#${ac}`;
97
+ const list = hits.get(k) ?? [];
98
+ if (!list.some((r) => r.file === ref.file && r.line === ref.line))
99
+ list.push(ref);
100
+ hits.set(k, list);
101
+ }
102
+ else {
103
+ const list = orphans.get(spec.slug) ?? [];
104
+ list.push({ ac, ref });
105
+ orphans.set(spec.slug, list);
106
+ }
107
+ };
108
+ const testFiles = listFiles(root).filter(isTestFile);
109
+ for (const rel of testFiles) {
110
+ let text;
111
+ try {
112
+ text = fs.readFileSync(path.join(root, rel), 'utf8');
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ if (!text.includes('AC-'))
118
+ continue;
119
+ // Specs que o arquivo cita: pelo ID, por `specs/<slug>` ou pelo slug com hífen (palavra única
120
+ // como "gates" ou "help" aparece em qualquer teste; só conta qualificada ou pelo caminho).
121
+ const live = text.replace(/spec-trace:off[\s\S]*?(?:spec-trace:on|$)/g, '');
122
+ const cited = new Set();
123
+ for (const m of live.matchAll(/\bSPEC-\d+\b/g)) {
124
+ const s = byId.get(m[0]);
125
+ if (s)
126
+ cited.add(s);
127
+ }
128
+ const base = path.basename(rel).replace(/\.(?:test|spec)\.[cm]?[jt]sx?$|\.[a-z]+$/, '').replace(/^test_|_test$/, '').replace(/_/g, '-');
129
+ for (const s of specs) {
130
+ if (base === s.slug || live.includes(`specs/${s.slug}`) || (s.slug.includes('-') && new RegExp(`\\b${s.slug}\\b`).test(live)))
131
+ cited.add(s);
132
+ }
133
+ // Fixtures que contêm citações de exemplo ficam entre `spec-trace:off` e `spec-trace:on`.
134
+ const lines = text.split('\n');
135
+ let off = false;
136
+ lines.forEach((line, i) => {
137
+ if (line.includes('spec-trace:off')) {
138
+ off = true;
139
+ return;
140
+ }
141
+ if (line.includes('spec-trace:on')) {
142
+ off = false;
143
+ return;
144
+ }
145
+ if (off || !line.includes('AC-'))
146
+ return;
147
+ const ref = { file: rel, line: i + 1 };
148
+ const consumed = [];
149
+ for (const m of line.matchAll(QUALIFIED)) {
150
+ const spec = resolve(m[1]);
151
+ if (!spec)
152
+ continue;
153
+ consumed.push([m.index, m.index + m[0].length]);
154
+ for (const ac of m[2].match(AC_TOKEN) ?? [])
155
+ cite(spec, ac, ref);
156
+ }
157
+ for (const m of line.matchAll(AC_TOKEN)) {
158
+ if (consumed.some(([a, b]) => m.index >= a && m.index < b))
159
+ continue;
160
+ // `AC-N` solto é ligação fraca: conta se o critério existe na única spec do arquivo; se não
161
+ // existe, provavelmente é de outra spec — ambíguo, não órfão (órfã é só a citação qualificada).
162
+ const only = cited.size === 1 ? [...cited][0] : null;
163
+ if (only && has(only, m[0]))
164
+ cite(only, m[0], ref);
165
+ else if (only)
166
+ ambiguous.push({ ac: m[0], ref, reason: `${m[0]} não existe em ${only.slug}, a única spec citada no arquivo` });
167
+ else
168
+ ambiguous.push({ ac: m[0], ref, reason: cited.size ? `arquivo cita ${cited.size} specs` : 'arquivo não cita nenhuma spec' });
169
+ }
170
+ });
171
+ }
172
+ return {
173
+ testFiles: testFiles.length,
174
+ ambiguous,
175
+ specs: specs.map((s) => {
176
+ const criteria = s.criteria.map((c) => ({ id: c.id, text: c.text, tests: hits.get(`${s.slug}#${c.id}`) ?? [] }));
177
+ return { slug: s.slug, specId: s.specId, status: s.status, criteria, uncovered: criteria.filter((c) => !c.tests.length).map((c) => c.id), orphans: orphans.get(s.slug) ?? [] };
178
+ }),
179
+ };
180
+ }
181
+ /** Specs que reprovam no `--strict`: status com "pronto" prometido e lacuna de rastreio. */
182
+ export function strictFailures(specs) {
183
+ return specs.filter((s) => GATED_STATUSES.has(s.status) && (s.uncovered.length > 0 || s.orphans.length > 0));
184
+ }
@@ -1,4 +1,4 @@
1
- import type { McpServer } from '../../mcp/src/index.ts';
1
+ import { type McpServer } from '../../mcp/src/index.ts';
2
2
  import type { ControlPlanePort } from '../../observability/src/index.ts';
3
3
  export interface HttpRequest {
4
4
  readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -50,6 +50,7 @@ export interface NestModuleDefinition {
50
50
  readonly routes: readonly string[];
51
51
  }
52
52
  export declare const FORJA_NEST_MODULES: readonly NestModuleDefinition[];
53
+ export declare function planningOpenApiPaths(): OpenApiDocument['paths'];
53
54
  export declare class NestAdapterError extends Error {
54
55
  constructor(message: string);
55
56
  }