forjajs 5.0.1 → 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.
- package/CHANGELOG.md +114 -2
- package/README.md +40 -5
- package/README.pt-BR.md +42 -4
- package/boilerplates/02-saas-starter/README.md +58 -293
- package/boilerplates/02-saas-starter/backend/.env.example +13 -0
- package/boilerplates/02-saas-starter/backend/.oxlintrc.json +8 -0
- package/boilerplates/02-saas-starter/backend/nest-cli.json +6 -0
- package/boilerplates/02-saas-starter/backend/package.json +32 -73
- package/boilerplates/02-saas-starter/backend/src/app.module.ts +16 -16
- package/boilerplates/02-saas-starter/backend/src/billing/adapters/http/billing.controller.ts +55 -0
- package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/orm-entities.ts +28 -0
- package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/typeorm-billing.repository.ts +46 -0
- package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.spec.ts +58 -0
- package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.ts +68 -0
- package/boilerplates/02-saas-starter/backend/src/billing/billing.module.ts +11 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.spec.ts +23 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.ts +36 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/ports.ts +27 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.spec.ts +28 -0
- package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.ts +47 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/auth.dto.ts +22 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/identity.controller.ts +59 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/orm-entities.ts +25 -0
- package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/typeorm-identity.repository.ts +47 -0
- package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.spec.ts +72 -0
- package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.ts +63 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/model.spec.ts +19 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/model.ts +42 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/password.spec.ts +17 -0
- package/boilerplates/02-saas-starter/backend/src/identity/domain/password.ts +26 -0
- package/boilerplates/02-saas-starter/backend/src/identity/identity.module.ts +12 -0
- package/boilerplates/02-saas-starter/backend/src/main.ts +19 -19
- package/boilerplates/02-saas-starter/backend/src/platform/auth/jwt-auth.guard.ts +17 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/principal.ts +22 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.spec.ts +23 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.ts +20 -0
- package/boilerplates/02-saas-starter/backend/src/platform/auth/token.service.ts +54 -0
- package/boilerplates/02-saas-starter/backend/src/platform/config.spec.ts +18 -0
- package/boilerplates/02-saas-starter/backend/src/platform/config.ts +33 -0
- package/boilerplates/02-saas-starter/backend/src/platform/platform.module.ts +14 -0
- package/boilerplates/02-saas-starter/backend/tsconfig.build.json +6 -0
- package/boilerplates/02-saas-starter/backend/tsconfig.json +16 -21
- package/boilerplates/02-saas-starter/backend/vitest.config.ts +7 -0
- package/boilerplates/02-saas-starter/boilerplate.manifest.json +19 -14
- package/boilerplates/02-saas-starter/docker-compose.yml +10 -24
- package/boilerplates/02-saas-starter/memory/30-domains/billing/context.md +15 -132
- package/boilerplates/02-saas-starter/memory/30-domains/identity/context.md +20 -0
- package/boilerplates/README.md +9 -10
- 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/bin/init-project.js +1 -0
- package/dist/lib/agent-evals.d.ts +138 -0
- package/dist/lib/agent-evals.js +349 -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 +36 -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/generators/memory-generator.d.ts +0 -11
- package/dist/lib/generators/memory-generator.js +5 -161
- package/dist/lib/generators/readme-generator.js +1 -1
- package/dist/lib/llm/json-output.d.ts +14 -0
- package/dist/lib/llm/json-output.js +77 -0
- package/dist/lib/project-wiring.d.ts +8 -0
- package/dist/lib/project-wiring.js +79 -3
- 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/lib/validators/structure-validator.js +0 -1
- 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 +12 -2
- 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 +23 -1
- 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 +36 -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/0088-templates-validados.md +3 -0
- package/memory/90-decisions/0089-skills-do-projeto.md +51 -0
- package/memory/90-decisions/0090-adapters-de-agente-somente-leitura.md +47 -0
- 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/skills-do-projeto/plan.md +40 -0
- package/specs/skills-do-projeto/spec.md +63 -0
- package/specs/skills-do-projeto/tasks.md +27 -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 +99 -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 +16 -0
- package/templates/project/CLAUDE.md +3 -2
- package/templates/project/agents/context-engineer.md +3 -0
- package/templates/project/agents/governance.md +3 -0
- package/templates/project/agents/marketing.md +3 -0
- package/templates/project/agents/orchestrator.md +3 -0
- package/templates/project/agents/product.md +3 -0
- package/templates/project/agents/sdd-architect.md +3 -0
- package/templates/project/skills/README.md +14 -0
- package/templates/project/skills/accessibility-review/SKILL.md +89 -0
- package/templates/project/skills/api-design/SKILL.md +77 -0
- package/templates/project/skills/architecture-decision-record/SKILL.md +92 -0
- package/templates/project/skills/backlog-slicing/SKILL.md +82 -0
- package/templates/project/skills/bounded-context-mapping/SKILL.md +88 -0
- package/templates/project/skills/ci-pipeline-review/SKILL.md +83 -0
- package/templates/project/skills/commit-message/SKILL.md +143 -0
- package/templates/project/skills/data-migrations/SKILL.md +88 -0
- package/templates/project/skills/dependency-upgrade/SKILL.md +75 -0
- package/templates/project/skills/docker-compose-review/SKILL.md +85 -0
- package/templates/project/skills/domain-modeling/SKILL.md +120 -0
- package/templates/project/skills/event-storming/SKILL.md +95 -0
- package/templates/project/skills/executive-writing/SKILL.md +99 -0
- package/templates/project/skills/frontend-architecture/SKILL.md +97 -0
- package/templates/project/skills/incident-postmortem/SKILL.md +93 -0
- package/templates/project/skills/lgpd-compliance/SKILL.md +108 -0
- package/templates/project/skills/llm-provider-routing/SKILL.md +18 -0
- package/templates/project/skills/observability/SKILL.md +93 -0
- package/templates/project/skills/product-evaluation/SKILL.md +130 -0
- package/templates/project/skills/prompt-spec/SKILL.md +83 -0
- package/templates/project/skills/pull-request/SKILL.md +101 -0
- package/templates/project/skills/query-performance/SKILL.md +83 -0
- package/templates/project/skills/release-checklist/SKILL.md +106 -0
- package/templates/project/skills/release-notes/SKILL.md +87 -0
- package/templates/project/skills/requirements-elicitation/SKILL.md +127 -0
- package/templates/project/skills/requirements-gathering/SKILL.md +134 -0
- package/templates/project/skills/technical-spike/SKILL.md +101 -0
- package/templates/project/skills/testing/SKILL.md +109 -0
- package/templates/project/skills/threat-modeling/SKILL.md +87 -0
- package/templates/project/skills/ts-async-patterns/SKILL.md +101 -0
- package/templates/project/skills/ts-code-review/SKILL.md +121 -0
- package/templates/project/skills/ts-module-layout/SKILL.md +104 -0
- package/templates/project/skills/ts-testing/SKILL.md +89 -0
- package/templates/project/skills/web-performance/SKILL.md +72 -0
- package/boilerplates/02-saas-starter/.env.example +0 -25
- package/boilerplates/02-saas-starter/CHECKLIST-CRIACAO.md +0 -190
- package/boilerplates/02-saas-starter/INFO.md +0 -252
- package/boilerplates/02-saas-starter/QUICK_START.md +0 -194
- package/boilerplates/02-saas-starter/START-HERE.md +0 -259
- package/boilerplates/02-saas-starter/backend/src/common/decorators/roles.decorator.ts +0 -3
- package/boilerplates/02-saas-starter/backend/src/common/decorators/tenant.decorator.ts +0 -6
- package/boilerplates/02-saas-starter/backend/src/common/middleware/roles.guard.ts +0 -23
- package/boilerplates/02-saas-starter/backend/src/config/database.ts +0 -26
- package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.controller.ts +0 -46
- package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.module.ts +0 -25
- package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.service.ts +0 -145
- package/boilerplates/02-saas-starter/backend/src/modules/auth/dto/auth.dto.ts +0 -30
- package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/jwt.strategy.ts +0 -24
- package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/local.strategy.ts +0 -19
- package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.controller.ts +0 -42
- package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.service.ts +0 -67
- package/boilerplates/02-saas-starter/backend/src/modules/billing/entities/invoice.entity.ts +0 -52
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/entities/organization.entity.ts +0 -36
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.controller.ts +0 -16
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.service.ts +0 -34
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/entities/subscription.entity.ts +0 -40
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.controller.ts +0 -36
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.service.ts +0 -91
- package/boilerplates/02-saas-starter/backend/src/modules/users/entities/user.entity.ts +0 -42
- package/boilerplates/02-saas-starter/backend/src/modules/users/users.controller.ts +0 -14
- package/boilerplates/02-saas-starter/backend/src/modules/users/users.module.ts +0 -13
- package/boilerplates/02-saas-starter/backend/src/modules/users/users.service.ts +0 -48
- package/boilerplates/02-saas-starter/memory/00-global/agent-contract.md +0 -227
- package/boilerplates/02-saas-starter/memory/00-global/context-policy.md +0 -141
- package/boilerplates/02-saas-starter/memory/00-global/index.md +0 -133
- package/boilerplates/02-saas-starter/memory/00-global/mission.md +0 -45
- package/boilerplates/02-saas-starter/memory/00-global/patterns.md +0 -223
- package/boilerplates/02-saas-starter/memory/10-product/business-rules.md +0 -240
- package/boilerplates/02-saas-starter/memory/10-product/nfrs.md +0 -239
- package/boilerplates/02-saas-starter/memory/10-product/personas.md +0 -195
- package/boilerplates/02-saas-starter/memory/10-product/vision.md +0 -63
- package/boilerplates/02-saas-starter/memory/20-architecture/overview.md +0 -232
- package/boilerplates/02-saas-starter/memory/30-domains/auth/api.md +0 -186
- package/boilerplates/02-saas-starter/memory/30-domains/auth/context.md +0 -85
- package/boilerplates/02-saas-starter/memory/30-domains/billing/api.md +0 -262
- package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/api.md +0 -176
- package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/context.md +0 -100
- package/boilerplates/02-saas-starter/memory/40-delivery/backlog.md +0 -81
- package/boilerplates/02-saas-starter/memory/40-delivery/roadmap.md +0 -97
- package/boilerplates/02-saas-starter/memory/40-delivery/sprint-atual.md +0 -57
- package/boilerplates/02-saas-starter/memory/50-orchestration/topology.md +0 -90
- package/boilerplates/02-saas-starter/memory/60-runs/index.md +0 -54
- package/boilerplates/02-saas-starter/memory/70-summaries/global.md +0 -50
- package/boilerplates/02-saas-starter/memory/80-data/schema.md +0 -185
- package/boilerplates/02-saas-starter/memory/90-decisions/adr-template.md +0 -75
|
@@ -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
|
|
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
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { PLANNING_PROPOSE_SCHEMA, PLANNING_REVIEW_SCHEMA } from '../../mcp/src/index.js';
|
|
3
|
+
import { PlanningError } from '../../planner/src/proposal-store.js';
|
|
2
4
|
/**
|
|
3
5
|
* True for 127.0.0.0/8 and ::1 (with the common ::ffff:-mapped IPv4 form normalized first).
|
|
4
6
|
* `address === undefined` returns false — "unknown" is not "trusted" — but callers that only have
|
|
@@ -26,6 +28,7 @@ export const FORJA_NEST_MODULES = [
|
|
|
26
28
|
{ name: 'WorkspaceModule', routes: ['/health', '/api/workspace/status'] },
|
|
27
29
|
{ name: 'CapabilityModule', routes: ['/api/capabilities', '/api/capabilities/:id/execute'] },
|
|
28
30
|
{ name: 'RuntimeModule', routes: ['/api/executions/:id'] },
|
|
31
|
+
{ name: 'PlanningModule', routes: ['/api/plans', '/api/plans/:id', '/api/plans/:id/review'] },
|
|
29
32
|
{ name: 'GraphModule', routes: ['/api/graph/query', '/api/graph/impact'] },
|
|
30
33
|
{ name: 'ContextModule', routes: ['/api/context/build'] },
|
|
31
34
|
{ name: 'PolicyModule', routes: ['/api/policies'] },
|
|
@@ -38,6 +41,44 @@ export const FORJA_NEST_MODULES = [
|
|
|
38
41
|
{ name: 'ControlPlaneModule', routes: ['/api/control-plane/metrics'] },
|
|
39
42
|
{ name: 'McpModule', routes: ['/mcp/tools', '/mcp/resources'] },
|
|
40
43
|
];
|
|
44
|
+
export function planningOpenApiPaths() {
|
|
45
|
+
const string = { type: 'string' };
|
|
46
|
+
const strings = { type: 'array', items: string };
|
|
47
|
+
const timestamp = { type: 'string', format: 'date-time' };
|
|
48
|
+
const tokens = { type: 'integer', minimum: 0 };
|
|
49
|
+
const tokenBudget = PLANNING_PROPOSE_SCHEMA.properties.budget;
|
|
50
|
+
const knowledge = { type: 'string', enum: ['verified', 'inferred', 'hypothesis', 'contradicted', 'unknown'] };
|
|
51
|
+
const evidence = { type: 'object', required: ['id', 'source', 'locator', 'capturedAt', 'status'], properties: { id: string, source: string, locator: string, capturedAt: timestamp, status: knowledge, checksum: string } };
|
|
52
|
+
const evidenceItems = { type: 'array', items: evidence };
|
|
53
|
+
const contextItem = { type: 'object', required: ['id', 'source', 'locator', 'checksum', 'status', 'evidence'], properties: { id: string, source: { enum: ['memory', 'graph'] }, locator: string, content: string, checksum: string, status: knowledge, evidence: evidenceItems } };
|
|
54
|
+
const task = { type: 'object', required: ['id', 'sprintId', 'objective', 'acceptanceCriteria', 'allowedFiles', 'dependencyIds', 'budget', 'status'], properties: { id: string, sprintId: string, objective: string, acceptanceCriteria: strings, allowedFiles: strings, dependencyIds: strings, evidenceIds: strings, budget: tokenBudget, status: string } };
|
|
55
|
+
const step = { type: 'object', required: ['id', 'objective', 'acceptanceCriteria', 'allowedFiles', 'dependencyIds', 'evidenceIds', 'budget', 'status'], properties: { id: string, objective: string, acceptanceCriteria: strings, allowedFiles: strings, dependencyIds: strings, externalDependencyIds: strings, contextItemId: string, rationale: string, constraints: strings, evidenceIds: strings, risk: string, budget: tokenBudget, status: string } };
|
|
56
|
+
const proposal = {
|
|
57
|
+
type: 'object', required: ['id', 'version', 'digest', 'status', 'snapshot', 'budget', 'blockers'],
|
|
58
|
+
properties: {
|
|
59
|
+
id: string, version: { const: 1 }, digest: string, status: { type: 'string', enum: ['draft', 'blocked', 'approved', 'rejected'] },
|
|
60
|
+
schemaVersion: string, createdAt: timestamp, updatedAt: timestamp, correlationId: string, declaredEvidenceIds: strings,
|
|
61
|
+
executor: { type: 'object', required: ['id', 'name', 'role', 'autonomy'], properties: { id: string, name: string, role: string, autonomy: string } },
|
|
62
|
+
snapshot: { type: 'object', required: ['task', 'sprint', 'dependencies'], properties: {
|
|
63
|
+
task, dependencies: { type: 'array', items: task },
|
|
64
|
+
sprint: { type: 'object', properties: { id: string, objective: string, status: string, budget: tokenBudget, includedScope: strings, excludedScope: strings, completionCriteria: strings, taskIds: strings } },
|
|
65
|
+
handoff: { type: 'object', properties: { id: string, taskId: string, from: string, to: string, nextAgent: string, intent: string, objective: string, completedWork: strings, decisions: strings, constraints: strings, pending: strings, acceptance: strings, blockers: strings, evidenceIds: strings, status: string } },
|
|
66
|
+
} },
|
|
67
|
+
plan: { type: 'object', properties: { id: string, objective: string, steps: { type: 'array', items: step }, budget: tokenBudget, constraints: strings, decisions: strings, evidenceIds: strings } },
|
|
68
|
+
context: { type: 'object', properties: { id: string, checksum: string, references: evidenceItems, content: strings, items: { type: 'array', items: contextItem }, budget: tokenBudget } },
|
|
69
|
+
budget: { type: 'object', description: 'Conservative token estimates, not billed usage', required: ['limit', 'briefingTokens', 'contextTokens', 'allocation'], properties: { limit: tokenBudget, briefingTokens: tokens, contextTokens: tokens, allocation: tokenBudget } },
|
|
70
|
+
blockers: { type: 'array', items: { type: 'object', required: ['code', 'message'], properties: { code: string, message: string } } },
|
|
71
|
+
review: { type: 'object', required: ['decision', 'reviewerId', 'reason', 'digest', 'decidedAt'], properties: { decision: { enum: ['approved', 'rejected'] }, reviewerId: string, reason: string, digest: string, decidedAt: timestamp, sourcesVerifiedAt: timestamp } },
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
const responses = { '200': { description: 'Persisted planning proposal; never an execution', content: { 'application/json': { schema: proposal } } }, ...Object.fromEntries([400, 401, 403, 404, 409, 500, 503].map((status) => [String(status), { description: 'Planning error', content: { 'application/json': { schema: { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string' }, message: { type: 'string' } } } } } } } }])) };
|
|
75
|
+
const parameters = [{ name: 'id', in: 'path', required: true, schema: { type: 'string', minLength: 1 } }];
|
|
76
|
+
return {
|
|
77
|
+
'/api/plans': { post: { operationId: 'planPropose', requestBody: { required: true, content: { 'application/json': { schema: PLANNING_PROPOSE_SCHEMA } } }, responses } },
|
|
78
|
+
'/api/plans/{id}': { get: { operationId: 'planGet', parameters, responses } },
|
|
79
|
+
'/api/plans/{id}/review': { post: { operationId: 'planReview', parameters, requestBody: { required: true, content: { 'application/json': { schema: PLANNING_REVIEW_SCHEMA } } }, responses } },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
41
82
|
export class NestAdapterError extends Error {
|
|
42
83
|
constructor(message) { super(message); this.name = 'NestAdapterError'; }
|
|
43
84
|
}
|
|
@@ -56,6 +97,10 @@ export class ForjaNestAdapter {
|
|
|
56
97
|
return this.result(correlationId, result);
|
|
57
98
|
}
|
|
58
99
|
catch (error) {
|
|
100
|
+
if (request.path === '/api/plans' || request.path.startsWith('/api/plans/')) {
|
|
101
|
+
const status = error instanceof PlanningError ? { PLANNING_INVALID_INPUT: 400, PLANNING_NOT_FOUND: 404, PLANNING_DENIED: 403, PLANNING_CONFLICT: 409, PLANNING_STALE: 409, PLANNING_INVALID_SCOPE: 409, PLANNING_INVALID_REVIEW: 409, PLANNING_REVIEWER_UNAVAILABLE: 503 }[error.code] ?? 500 : 500;
|
|
102
|
+
return { status, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId }, body: { error: { code: status === 500 ? 'PLANNING_UNAVAILABLE' : error.code, message: status === 500 ? 'Planning service unavailable' : error.message } }, correlationId };
|
|
103
|
+
}
|
|
59
104
|
return this.error(correlationId, error instanceof Error ? error.message : 'Unknown HTTP adapter error');
|
|
60
105
|
}
|
|
61
106
|
}
|
|
@@ -79,10 +124,23 @@ export class ForjaNestAdapter {
|
|
|
79
124
|
}
|
|
80
125
|
modules() { return FORJA_NEST_MODULES; }
|
|
81
126
|
openApi() {
|
|
82
|
-
const paths = Object.fromEntries(FORJA_NEST_MODULES.flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }])));
|
|
127
|
+
const paths = { ...Object.fromEntries(FORJA_NEST_MODULES.filter((module) => module.name !== 'PlanningModule').flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }]))), ...planningOpenApiPaths() };
|
|
83
128
|
return { openapi: '3.1.0', info: { title: 'ForjaJS 2.0 API', version: '2.0.0' }, paths };
|
|
84
129
|
}
|
|
85
130
|
async dispatch(request) {
|
|
131
|
+
if (request.method === 'POST' && request.path === '/api/plans') {
|
|
132
|
+
if (typeof request.body !== 'object' || request.body === null || Array.isArray(request.body))
|
|
133
|
+
throw new PlanningError('PLANNING_INVALID_INPUT', 'Planning body must be an object');
|
|
134
|
+
const body = request.body;
|
|
135
|
+
return this.requireControlPlane().planPropose?.({ ...body, correlationId: request.correlationId ?? request.headers['x-correlation-id'] ?? body.correlationId }) ?? this.missing('planPropose');
|
|
136
|
+
}
|
|
137
|
+
const planRoute = /^\/api\/plans\/([^/]+)(\/review)?$/.exec(request.path);
|
|
138
|
+
if (planRoute !== null && request.method === 'GET' && planRoute[2] === undefined)
|
|
139
|
+
return this.requireControlPlane().planGet?.(planRoute[1]) ?? this.missing('planGet');
|
|
140
|
+
if (planRoute !== null && request.method === 'POST' && planRoute[2] !== undefined)
|
|
141
|
+
return this.requireControlPlane().planReview?.(planRoute[1], request.body) ?? this.missing('planReview');
|
|
142
|
+
if (request.path === '/api/plans' || request.path.startsWith('/api/plans/'))
|
|
143
|
+
throw new PlanningError('PLANNING_NOT_FOUND', 'Planning route not found');
|
|
86
144
|
if (request.method === 'GET' && request.path === '/health')
|
|
87
145
|
return { status: 'ok', service: 'forja-server', offline: true };
|
|
88
146
|
if (request.method === 'GET' && request.path === '/api/workspace/status')
|
|
@@ -4,12 +4,14 @@ import type { ProvenanceRecord } from '../../engineering/provenance/src/index.ts
|
|
|
4
4
|
import type { ApprovalStore } from '../../policy/src/index.ts';
|
|
5
5
|
import type { CheckpointStore, RuntimePersistence, RuntimePlanStep } from '../../runtime/src/index.ts';
|
|
6
6
|
import type { McpAuditEvent, McpAuditSink } from '../../mcp/src/index.ts';
|
|
7
|
-
import type
|
|
7
|
+
import { type ExecutionTransition, type OrchestrationStore } from '../../orchestration/src/index.ts';
|
|
8
8
|
import type { SandboxStore } from '../../sandbox/src/index.ts';
|
|
9
9
|
import type { ObservationStore } from '../../observability/src/index.ts';
|
|
10
10
|
import type { GraphStore } from '../../graph/src/index.ts';
|
|
11
11
|
import type { Evidence, GraphEdge, GraphNode } from '../../contracts/src/index.ts';
|
|
12
12
|
import type { ContextCache } from '../../context/src/index.ts';
|
|
13
|
+
import type { PlanningProposal, PlanningSnapshot } from '../../contracts/src/index.ts';
|
|
14
|
+
import { type PlanningStore } from '../../planner/src/proposal-store.ts';
|
|
13
15
|
export interface SqliteStatement {
|
|
14
16
|
run(...parameters: readonly unknown[]): {
|
|
15
17
|
readonly changes?: number;
|
|
@@ -47,7 +49,9 @@ export declare class SqliteJsonRepository {
|
|
|
47
49
|
}
|
|
48
50
|
export declare class SqliteOrchestrationStore implements OrchestrationStore {
|
|
49
51
|
private readonly repository;
|
|
52
|
+
private readonly db;
|
|
50
53
|
constructor(db: SqliteConnection);
|
|
54
|
+
transitionExecution(input: ExecutionTransition): void;
|
|
51
55
|
saveSprint(value: Sprint): void;
|
|
52
56
|
getSprint(id: EntityId): Sprint | undefined;
|
|
53
57
|
listSprints(): readonly Sprint[];
|
|
@@ -58,6 +62,16 @@ export declare class SqliteOrchestrationStore implements OrchestrationStore {
|
|
|
58
62
|
getHandoff(id: EntityId): Handoff | undefined;
|
|
59
63
|
listHandoffs(): readonly Handoff[];
|
|
60
64
|
}
|
|
65
|
+
export declare class SqlitePlanningStore implements PlanningStore {
|
|
66
|
+
private readonly db;
|
|
67
|
+
private readonly repository;
|
|
68
|
+
private readonly reader;
|
|
69
|
+
constructor(db: SqliteConnection);
|
|
70
|
+
create(proposal: PlanningProposal): void;
|
|
71
|
+
get(id: EntityId): PlanningProposal | undefined;
|
|
72
|
+
review(before: PlanningProposal, after: PlanningProposal, expectedSnapshot?: PlanningSnapshot): void;
|
|
73
|
+
private transaction;
|
|
74
|
+
}
|
|
61
75
|
export declare class SqliteSandboxStore implements SandboxStore {
|
|
62
76
|
private readonly repository;
|
|
63
77
|
constructor(db: SqliteConnection);
|