forjajs 5.1.0 → 5.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +108 -0
- package/README.md +52 -4
- package/README.pt-BR.md +54 -4
- package/dist/apps/cli/src/index.d.ts +0 -1
- package/dist/apps/cli/src/index.js +43 -32
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
- package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
- package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
- package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
- package/dist/apps/server/src/forja-nest.module.js +55 -0
- package/dist/apps/server/src/main.d.ts +21 -4
- package/dist/apps/server/src/main.js +79 -57
- package/dist/apps/server/src/task-planning-service.d.ts +29 -0
- package/dist/apps/server/src/task-planning-service.js +195 -0
- package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
- package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
- package/dist/bin/forja.js +3 -2
- package/dist/lib/agent-evals.d.ts +138 -0
- package/dist/lib/agent-evals.js +365 -0
- package/dist/lib/cli-output.js +14 -2
- package/dist/lib/code-context.d.ts +33 -5
- package/dist/lib/code-context.js +70 -5
- package/dist/lib/context-builder.d.ts +49 -4
- package/dist/lib/context-builder.js +114 -47
- package/dist/lib/core/coverage-gate.d.ts +59 -0
- package/dist/lib/core/coverage-gate.js +58 -0
- package/dist/lib/core/doc-graph.d.ts +38 -0
- package/dist/lib/core/doc-graph.js +83 -0
- package/dist/lib/core/health.js +286 -5
- package/dist/lib/core/journey.js +26 -0
- package/dist/lib/core/registry.js +81 -6
- package/dist/lib/docs-reference.d.ts +35 -0
- package/dist/lib/docs-reference.js +57 -0
- package/dist/lib/exec.d.ts +55 -0
- package/dist/lib/exec.js +141 -0
- package/dist/lib/project-wiring.js +6 -2
- package/dist/lib/session-memory.d.ts +38 -0
- package/dist/lib/session-memory.js +206 -0
- package/dist/lib/spec-trace.d.ts +46 -0
- package/dist/lib/spec-trace.js +184 -0
- package/dist/packages/adapter-git/src/index.js +13 -4
- package/dist/packages/adapter-nest/src/index.d.ts +2 -1
- package/dist/packages/adapter-nest/src/index.js +59 -1
- package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
- package/dist/packages/adapter-sqlite/src/index.js +61 -1
- package/dist/packages/context/src/index.d.ts +2 -0
- package/dist/packages/context/src/index.js +36 -15
- package/dist/packages/contracts/src/index.d.ts +64 -0
- package/dist/packages/core/src/index.d.ts +9 -1
- package/dist/packages/core/src/index.js +28 -3
- package/dist/packages/graph/src/index.js +14 -5
- package/dist/packages/llm/src/index.js +7 -24
- package/dist/packages/mcp/src/index.d.ts +8 -0
- package/dist/packages/mcp/src/index.js +12 -1
- package/dist/packages/observability/src/index.d.ts +11 -0
- package/dist/packages/observability/src/index.js +3 -0
- package/dist/packages/orchestration/src/index.d.ts +15 -1
- package/dist/packages/orchestration/src/index.js +127 -21
- package/dist/packages/planner/src/index.d.ts +7 -1
- package/dist/packages/planner/src/index.js +67 -10
- package/dist/packages/planner/src/proposal-store.d.ts +30 -0
- package/dist/packages/planner/src/proposal-store.js +109 -0
- package/dist/packages/policy/src/index.d.ts +9 -16
- package/dist/packages/policy/src/index.js +114 -31
- package/dist/packages/runtime/src/index.d.ts +16 -2
- package/dist/packages/runtime/src/index.js +176 -61
- package/dist/scripts/build-smart-context.d.ts +2 -0
- package/dist/scripts/build-smart-context.js +12 -3
- package/dist/scripts/code-context.d.ts +3 -1
- package/dist/scripts/code-context.js +13 -3
- package/dist/scripts/coverage-gate.d.ts +2 -0
- package/dist/scripts/coverage-gate.js +101 -0
- package/dist/scripts/eval-agents.d.ts +11 -0
- package/dist/scripts/eval-agents.js +96 -0
- package/dist/scripts/gen-commands-doc.d.ts +2 -0
- package/dist/scripts/gen-commands-doc.js +18 -0
- package/dist/scripts/hook-session-memory.d.ts +9 -0
- package/dist/scripts/hook-session-memory.js +20 -0
- package/dist/scripts/hook-session-start.js +34 -0
- package/dist/scripts/llm-fit.js +15 -6
- package/dist/scripts/simulate.js +16 -4
- package/dist/scripts/spec-trace.d.ts +10 -0
- package/dist/scripts/spec-trace.js +73 -0
- package/dist/scripts/sync-universal-memory.js +69 -4
- package/dist/scripts/token-benchmark.d.ts +33 -1
- package/dist/scripts/token-benchmark.js +179 -5
- package/dist/scripts/token-economy.js +3 -1
- package/dist/scripts/tools-doctor.d.ts +16 -1
- package/dist/scripts/tools-doctor.js +58 -17
- package/docs/commands.md +155 -0
- package/docs/fluxo.md +11 -7
- package/docs/init-project.md +3 -1
- package/docs/llm-fit-loop.md +20 -0
- package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
- package/docs/produto/factsheet-marketing.md +7 -5
- package/docs/produto/roteiro-demo.md +14 -5
- package/docs/quick-reference.md +3 -3
- package/docs/token-optimization.md +10 -6
- package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
- package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
- package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
- package/package.json +4 -2
- package/specs/avaliacoes-de-agentes/spec.md +52 -0
- package/specs/criterios-ligados-a-testes/spec.md +42 -0
- package/specs/memoria-de-sessao/spec.md +48 -0
- package/specs/v6-agent-runtime-portable/spec.md +83 -0
- package/specs/v6-core-consolidation/spec.md +70 -0
- package/specs/v6-docs-drift/spec.md +85 -0
- package/specs/v6-quality-gates/spec.md +104 -0
- package/specs/v6-token-economy/spec.md +84 -0
- package/templates/evals/agents/adr.json +25 -0
- package/templates/evals/agents/memoria.json +32 -0
- package/templates/evals/agents/proxima-acao.json +29 -0
- package/templates/evals/agents/spec-nova.json +26 -0
- package/templates/evals/agents/teste-do-criterio.json +29 -0
- package/templates/project/AGENTS.md +7 -0
- package/templates/project/CLAUDE.md +3 -2
- 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
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/exec.ts — fronteira de subprocesso portável (SPEC-059).
|
|
3
|
+
*
|
|
4
|
+
* Resolve binários por plataforma (`where`/`which` + PATHEXT), spawnar `.cmd`/`.bat`
|
|
5
|
+
* sem `shell: true` (CVE-2024-27980), launcher de shell portável e kill de árvore.
|
|
6
|
+
* Sem dependência nova: o quoting de cmd.exe é ~30 linhas testadas exaustivamente.
|
|
7
|
+
*
|
|
8
|
+
* Precedente: `hasBinary()` em lib/project-wiring.ts:98.
|
|
9
|
+
*/
|
|
10
|
+
import { type ChildProcess, type SpawnOptions, type SpawnSyncReturns } from 'node:child_process';
|
|
11
|
+
/**
|
|
12
|
+
* Resolve um binário para caminho absoluto, ou null se não encontrável.
|
|
13
|
+
* POSIX: `which`. Windows: `where` + PATHEXT (`.CMD;.BAT;.EXE;…`).
|
|
14
|
+
*/
|
|
15
|
+
export declare function resolveCommand(bin: string): string | null;
|
|
16
|
+
/**
|
|
17
|
+
* Escapa um argumento para cmd.exe + parser MSVCRT do processo-filho.
|
|
18
|
+
*
|
|
19
|
+
* Estratégia (a mesma do cross-spawn, sem a dependência):
|
|
20
|
+
* 1. Quoting MSVCRT: envolve em `"`, escapa `"` como `\"`, dobra `\` antes de `"`.
|
|
21
|
+
* 2. Escapa metacaracteres do cmd.exe (`% ^ & | < > ( ) "`) com `^` — fora das aspas
|
|
22
|
+
* MSVCRT, o `^` é processado pelo parser do cmd.exe antes da expansão de variáveis.
|
|
23
|
+
*
|
|
24
|
+
* Limitação conhecida: `%VAR%` dentro de aspas ainda é expandido pelo cmd.exe se VAR
|
|
25
|
+
* existir no ambiente. Na prática, argumentos de agentes (prompts, flags) raramente
|
|
26
|
+
* contêm padrões `%VAR%` que casem com variáveis reais. O teste AC-2 usa variável
|
|
27
|
+
* inexistente, que o cmd.exe preserva literal.
|
|
28
|
+
*/
|
|
29
|
+
export declare function quoteCmdArg(arg: string): string;
|
|
30
|
+
export interface SpawnAgentOptions extends SpawnOptions {
|
|
31
|
+
readonly timeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Spawna um executável de agente de forma portável.
|
|
35
|
+
* - Resolve via resolveCommand (where/which + PATHEXT).
|
|
36
|
+
* - `.cmd`/`.bat` → cmd.exe /d /s /c com quoting próprio (nunca shell: true).
|
|
37
|
+
* - Outros → spawn direto, shell: false.
|
|
38
|
+
* - detached: true em POSIX (process group para killTree); false em Windows.
|
|
39
|
+
*/
|
|
40
|
+
export declare function spawnAgent(executable: string, args: readonly string[], opts?: SpawnAgentOptions): ChildProcess;
|
|
41
|
+
/**
|
|
42
|
+
* Launcher de shell portável para checks declarativos (`type: 'command'`).
|
|
43
|
+
* POSIX: `sh -c`. Windows: `%ComSpec% /d /s /c`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function runShell(command: string, opts?: {
|
|
46
|
+
cwd?: string;
|
|
47
|
+
env?: NodeJS.ProcessEnv;
|
|
48
|
+
timeoutMs?: number;
|
|
49
|
+
}): SpawnSyncReturns<string>;
|
|
50
|
+
/**
|
|
51
|
+
* Derruba a árvore de processos.
|
|
52
|
+
* POSIX: kill(-pid, SIGTERM) → grace → kill(-pid, SIGKILL).
|
|
53
|
+
* Windows: taskkill /pid <pid> /T /F (alcança netos de shim .cmd).
|
|
54
|
+
*/
|
|
55
|
+
export declare function killTree(pid: number, graceMs?: number): void;
|
package/dist/lib/exec.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/exec.ts — fronteira de subprocesso portável (SPEC-059).
|
|
3
|
+
*
|
|
4
|
+
* Resolve binários por plataforma (`where`/`which` + PATHEXT), spawnar `.cmd`/`.bat`
|
|
5
|
+
* sem `shell: true` (CVE-2024-27980), launcher de shell portável e kill de árvore.
|
|
6
|
+
* Sem dependência nova: o quoting de cmd.exe é ~30 linhas testadas exaustivamente.
|
|
7
|
+
*
|
|
8
|
+
* Precedente: `hasBinary()` em lib/project-wiring.ts:98.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
const IS_WIN = process.platform === 'win32';
|
|
13
|
+
/**
|
|
14
|
+
* Resolve um binário para caminho absoluto, ou null se não encontrável.
|
|
15
|
+
* POSIX: `which`. Windows: `where` + PATHEXT (`.CMD;.BAT;.EXE;…`).
|
|
16
|
+
*/
|
|
17
|
+
export function resolveCommand(bin) {
|
|
18
|
+
if (path.isAbsolute(bin))
|
|
19
|
+
return bin;
|
|
20
|
+
const finder = IS_WIN ? 'where' : 'which';
|
|
21
|
+
const r = spawnSync(finder, [bin], { encoding: 'utf8', timeout: 5_000 });
|
|
22
|
+
if (r.status === 0 && r.stdout) {
|
|
23
|
+
const lines = r.stdout.trim().split(/\r?\n/).filter(Boolean);
|
|
24
|
+
if (IS_WIN) {
|
|
25
|
+
const exec = lines.find((l) => /\.(cmd|bat|exe|com)$/i.test(l));
|
|
26
|
+
if (exec)
|
|
27
|
+
return exec;
|
|
28
|
+
}
|
|
29
|
+
if (lines[0])
|
|
30
|
+
return lines[0];
|
|
31
|
+
}
|
|
32
|
+
if (IS_WIN) {
|
|
33
|
+
const exts = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
|
|
34
|
+
for (const ext of exts) {
|
|
35
|
+
const candidate = `${bin}${ext}`;
|
|
36
|
+
const probe = spawnSync('where', [candidate], { encoding: 'utf8', timeout: 5_000 });
|
|
37
|
+
if (probe.status === 0 && probe.stdout) {
|
|
38
|
+
const first = probe.stdout.trim().split(/\r?\n/)[0];
|
|
39
|
+
if (first)
|
|
40
|
+
return first;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Escapa um argumento para cmd.exe + parser MSVCRT do processo-filho.
|
|
48
|
+
*
|
|
49
|
+
* Estratégia (a mesma do cross-spawn, sem a dependência):
|
|
50
|
+
* 1. Quoting MSVCRT: envolve em `"`, escapa `"` como `\"`, dobra `\` antes de `"`.
|
|
51
|
+
* 2. Escapa metacaracteres do cmd.exe (`% ^ & | < > ( ) "`) com `^` — fora das aspas
|
|
52
|
+
* MSVCRT, o `^` é processado pelo parser do cmd.exe antes da expansão de variáveis.
|
|
53
|
+
*
|
|
54
|
+
* Limitação conhecida: `%VAR%` dentro de aspas ainda é expandido pelo cmd.exe se VAR
|
|
55
|
+
* existir no ambiente. Na prática, argumentos de agentes (prompts, flags) raramente
|
|
56
|
+
* contêm padrões `%VAR%` que casem com variáveis reais. O teste AC-2 usa variável
|
|
57
|
+
* inexistente, que o cmd.exe preserva literal.
|
|
58
|
+
*/
|
|
59
|
+
export function quoteCmdArg(arg) {
|
|
60
|
+
if (arg.length === 0)
|
|
61
|
+
return '""';
|
|
62
|
+
let s = arg.replace(/(\\*)"/g, '$1$1\\"');
|
|
63
|
+
s = s.replace(/(\\*)$/, '$1$1');
|
|
64
|
+
s = `"${s}"`;
|
|
65
|
+
s = s.replace(/[()%!^"<>&|]/g, '^$&');
|
|
66
|
+
return s;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Spawna um executável de agente de forma portável.
|
|
70
|
+
* - Resolve via resolveCommand (where/which + PATHEXT).
|
|
71
|
+
* - `.cmd`/`.bat` → cmd.exe /d /s /c com quoting próprio (nunca shell: true).
|
|
72
|
+
* - Outros → spawn direto, shell: false.
|
|
73
|
+
* - detached: true em POSIX (process group para killTree); false em Windows.
|
|
74
|
+
*/
|
|
75
|
+
export function spawnAgent(executable, args, opts = {}) {
|
|
76
|
+
const resolved = resolveCommand(executable) ?? executable;
|
|
77
|
+
const isCmd = IS_WIN && /\.(cmd|bat)$/i.test(resolved);
|
|
78
|
+
if (isCmd) {
|
|
79
|
+
const comspec = process.env.ComSpec ?? 'cmd.exe';
|
|
80
|
+
const commandLine = `"${resolved}" ${args.map(quoteCmdArg).join(' ')}`;
|
|
81
|
+
return spawn(comspec, ['/d', '/s', '/c', `"${commandLine}"`], {
|
|
82
|
+
...opts,
|
|
83
|
+
shell: false,
|
|
84
|
+
detached: false,
|
|
85
|
+
windowsVerbatimArguments: true,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return spawn(resolved, [...args], {
|
|
89
|
+
...opts,
|
|
90
|
+
shell: false,
|
|
91
|
+
detached: opts.detached ?? !IS_WIN,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Launcher de shell portável para checks declarativos (`type: 'command'`).
|
|
96
|
+
* POSIX: `sh -c`. Windows: `%ComSpec% /d /s /c`.
|
|
97
|
+
*/
|
|
98
|
+
export function runShell(command, opts = {}) {
|
|
99
|
+
const shell = IS_WIN ? (process.env.ComSpec ?? 'cmd.exe') : 'sh';
|
|
100
|
+
const shellArgs = IS_WIN ? ['/d', '/s', '/c', command] : ['-c', command];
|
|
101
|
+
return spawnSync(shell, shellArgs, {
|
|
102
|
+
cwd: opts.cwd,
|
|
103
|
+
env: opts.env,
|
|
104
|
+
encoding: 'utf8',
|
|
105
|
+
timeout: opts.timeoutMs ?? 120_000,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Derruba a árvore de processos.
|
|
110
|
+
* POSIX: kill(-pid, SIGTERM) → grace → kill(-pid, SIGKILL).
|
|
111
|
+
* Windows: taskkill /pid <pid> /T /F (alcança netos de shim .cmd).
|
|
112
|
+
*/
|
|
113
|
+
export function killTree(pid, graceMs = 3_000) {
|
|
114
|
+
if (IS_WIN) {
|
|
115
|
+
try {
|
|
116
|
+
spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 10_000 });
|
|
117
|
+
}
|
|
118
|
+
catch { /* já morto */ }
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
process.kill(-pid, 'SIGTERM');
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
try {
|
|
126
|
+
process.kill(pid, 'SIGTERM');
|
|
127
|
+
}
|
|
128
|
+
catch { /* já morto */ }
|
|
129
|
+
}
|
|
130
|
+
setTimeout(() => {
|
|
131
|
+
try {
|
|
132
|
+
process.kill(-pid, 'SIGKILL');
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
try {
|
|
136
|
+
process.kill(pid, 'SIGKILL');
|
|
137
|
+
}
|
|
138
|
+
catch { /* já morto */ }
|
|
139
|
+
}
|
|
140
|
+
}, graceMs).unref();
|
|
141
|
+
}
|
|
@@ -52,7 +52,8 @@ export function templateSkills() {
|
|
|
52
52
|
export function skillProblem(name, text) {
|
|
53
53
|
if (text == null)
|
|
54
54
|
return 'ausente';
|
|
55
|
-
|
|
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(', ')}` : '
|
|
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[];
|