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.
Files changed (268) hide show
  1. package/CHANGELOG.md +114 -2
  2. package/README.md +40 -5
  3. package/README.pt-BR.md +42 -4
  4. package/boilerplates/02-saas-starter/README.md +58 -293
  5. package/boilerplates/02-saas-starter/backend/.env.example +13 -0
  6. package/boilerplates/02-saas-starter/backend/.oxlintrc.json +8 -0
  7. package/boilerplates/02-saas-starter/backend/nest-cli.json +6 -0
  8. package/boilerplates/02-saas-starter/backend/package.json +32 -73
  9. package/boilerplates/02-saas-starter/backend/src/app.module.ts +16 -16
  10. package/boilerplates/02-saas-starter/backend/src/billing/adapters/http/billing.controller.ts +55 -0
  11. package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/orm-entities.ts +28 -0
  12. package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/typeorm-billing.repository.ts +46 -0
  13. package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.spec.ts +58 -0
  14. package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.ts +68 -0
  15. package/boilerplates/02-saas-starter/backend/src/billing/billing.module.ts +11 -0
  16. package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.spec.ts +23 -0
  17. package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.ts +36 -0
  18. package/boilerplates/02-saas-starter/backend/src/billing/domain/ports.ts +27 -0
  19. package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.spec.ts +28 -0
  20. package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.ts +47 -0
  21. package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/auth.dto.ts +22 -0
  22. package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/identity.controller.ts +59 -0
  23. package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/orm-entities.ts +25 -0
  24. package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/typeorm-identity.repository.ts +47 -0
  25. package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.spec.ts +72 -0
  26. package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.ts +63 -0
  27. package/boilerplates/02-saas-starter/backend/src/identity/domain/model.spec.ts +19 -0
  28. package/boilerplates/02-saas-starter/backend/src/identity/domain/model.ts +42 -0
  29. package/boilerplates/02-saas-starter/backend/src/identity/domain/password.spec.ts +17 -0
  30. package/boilerplates/02-saas-starter/backend/src/identity/domain/password.ts +26 -0
  31. package/boilerplates/02-saas-starter/backend/src/identity/identity.module.ts +12 -0
  32. package/boilerplates/02-saas-starter/backend/src/main.ts +19 -19
  33. package/boilerplates/02-saas-starter/backend/src/platform/auth/jwt-auth.guard.ts +17 -0
  34. package/boilerplates/02-saas-starter/backend/src/platform/auth/principal.ts +22 -0
  35. package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.spec.ts +23 -0
  36. package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.ts +20 -0
  37. package/boilerplates/02-saas-starter/backend/src/platform/auth/token.service.ts +54 -0
  38. package/boilerplates/02-saas-starter/backend/src/platform/config.spec.ts +18 -0
  39. package/boilerplates/02-saas-starter/backend/src/platform/config.ts +33 -0
  40. package/boilerplates/02-saas-starter/backend/src/platform/platform.module.ts +14 -0
  41. package/boilerplates/02-saas-starter/backend/tsconfig.build.json +6 -0
  42. package/boilerplates/02-saas-starter/backend/tsconfig.json +16 -21
  43. package/boilerplates/02-saas-starter/backend/vitest.config.ts +7 -0
  44. package/boilerplates/02-saas-starter/boilerplate.manifest.json +19 -14
  45. package/boilerplates/02-saas-starter/docker-compose.yml +10 -24
  46. package/boilerplates/02-saas-starter/memory/30-domains/billing/context.md +15 -132
  47. package/boilerplates/02-saas-starter/memory/30-domains/identity/context.md +20 -0
  48. package/boilerplates/README.md +9 -10
  49. package/dist/apps/cli/src/index.d.ts +0 -1
  50. package/dist/apps/cli/src/index.js +43 -32
  51. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
  52. package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
  53. package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
  54. package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
  55. package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
  56. package/dist/apps/server/src/forja-nest.module.js +55 -0
  57. package/dist/apps/server/src/main.d.ts +21 -4
  58. package/dist/apps/server/src/main.js +79 -57
  59. package/dist/apps/server/src/task-planning-service.d.ts +29 -0
  60. package/dist/apps/server/src/task-planning-service.js +195 -0
  61. package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
  62. package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
  63. package/dist/bin/forja.js +3 -2
  64. package/dist/bin/init-project.js +1 -0
  65. package/dist/lib/agent-evals.d.ts +138 -0
  66. package/dist/lib/agent-evals.js +349 -0
  67. package/dist/lib/cli-output.js +14 -2
  68. package/dist/lib/code-context.d.ts +33 -5
  69. package/dist/lib/code-context.js +70 -5
  70. package/dist/lib/context-builder.d.ts +49 -4
  71. package/dist/lib/context-builder.js +114 -47
  72. package/dist/lib/core/coverage-gate.d.ts +59 -0
  73. package/dist/lib/core/coverage-gate.js +58 -0
  74. package/dist/lib/core/doc-graph.d.ts +38 -0
  75. package/dist/lib/core/doc-graph.js +83 -0
  76. package/dist/lib/core/health.js +286 -5
  77. package/dist/lib/core/journey.js +36 -0
  78. package/dist/lib/core/registry.js +81 -6
  79. package/dist/lib/docs-reference.d.ts +35 -0
  80. package/dist/lib/docs-reference.js +57 -0
  81. package/dist/lib/generators/memory-generator.d.ts +0 -11
  82. package/dist/lib/generators/memory-generator.js +5 -161
  83. package/dist/lib/generators/readme-generator.js +1 -1
  84. package/dist/lib/llm/json-output.d.ts +14 -0
  85. package/dist/lib/llm/json-output.js +77 -0
  86. package/dist/lib/project-wiring.d.ts +8 -0
  87. package/dist/lib/project-wiring.js +79 -3
  88. package/dist/lib/session-memory.d.ts +38 -0
  89. package/dist/lib/session-memory.js +206 -0
  90. package/dist/lib/spec-trace.d.ts +46 -0
  91. package/dist/lib/spec-trace.js +184 -0
  92. package/dist/lib/validators/structure-validator.js +0 -1
  93. package/dist/packages/adapter-nest/src/index.d.ts +2 -1
  94. package/dist/packages/adapter-nest/src/index.js +59 -1
  95. package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
  96. package/dist/packages/adapter-sqlite/src/index.js +61 -1
  97. package/dist/packages/context/src/index.d.ts +2 -0
  98. package/dist/packages/context/src/index.js +36 -15
  99. package/dist/packages/contracts/src/index.d.ts +64 -0
  100. package/dist/packages/core/src/index.d.ts +9 -1
  101. package/dist/packages/core/src/index.js +28 -3
  102. package/dist/packages/graph/src/index.js +14 -5
  103. package/dist/packages/llm/src/index.js +12 -2
  104. package/dist/packages/mcp/src/index.d.ts +8 -0
  105. package/dist/packages/mcp/src/index.js +12 -1
  106. package/dist/packages/observability/src/index.d.ts +11 -0
  107. package/dist/packages/observability/src/index.js +3 -0
  108. package/dist/packages/orchestration/src/index.d.ts +15 -1
  109. package/dist/packages/orchestration/src/index.js +127 -21
  110. package/dist/packages/planner/src/index.d.ts +7 -1
  111. package/dist/packages/planner/src/index.js +67 -10
  112. package/dist/packages/planner/src/proposal-store.d.ts +30 -0
  113. package/dist/packages/planner/src/proposal-store.js +109 -0
  114. package/dist/packages/policy/src/index.d.ts +9 -16
  115. package/dist/packages/policy/src/index.js +114 -31
  116. package/dist/packages/runtime/src/index.d.ts +16 -2
  117. package/dist/packages/runtime/src/index.js +176 -61
  118. package/dist/scripts/build-smart-context.d.ts +2 -0
  119. package/dist/scripts/build-smart-context.js +12 -3
  120. package/dist/scripts/code-context.d.ts +3 -1
  121. package/dist/scripts/code-context.js +13 -3
  122. package/dist/scripts/coverage-gate.d.ts +2 -0
  123. package/dist/scripts/coverage-gate.js +101 -0
  124. package/dist/scripts/eval-agents.d.ts +11 -0
  125. package/dist/scripts/eval-agents.js +96 -0
  126. package/dist/scripts/gen-commands-doc.d.ts +2 -0
  127. package/dist/scripts/gen-commands-doc.js +18 -0
  128. package/dist/scripts/hook-session-memory.d.ts +9 -0
  129. package/dist/scripts/hook-session-memory.js +20 -0
  130. package/dist/scripts/hook-session-start.js +34 -0
  131. package/dist/scripts/llm-fit.js +23 -1
  132. package/dist/scripts/spec-trace.d.ts +10 -0
  133. package/dist/scripts/spec-trace.js +73 -0
  134. package/dist/scripts/sync-universal-memory.js +69 -4
  135. package/dist/scripts/token-benchmark.d.ts +33 -1
  136. package/dist/scripts/token-benchmark.js +179 -5
  137. package/dist/scripts/token-economy.js +3 -1
  138. package/dist/scripts/tools-doctor.d.ts +16 -1
  139. package/dist/scripts/tools-doctor.js +58 -17
  140. package/docs/commands.md +155 -0
  141. package/docs/fluxo.md +11 -7
  142. package/docs/init-project.md +3 -1
  143. package/docs/llm-fit-loop.md +36 -0
  144. package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
  145. package/docs/produto/factsheet-marketing.md +7 -5
  146. package/docs/produto/roteiro-demo.md +14 -5
  147. package/docs/quick-reference.md +3 -3
  148. package/docs/token-optimization.md +10 -6
  149. package/memory/90-decisions/0088-templates-validados.md +3 -0
  150. package/memory/90-decisions/0089-skills-do-projeto.md +51 -0
  151. package/memory/90-decisions/0090-adapters-de-agente-somente-leitura.md +47 -0
  152. package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
  153. package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
  154. package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
  155. package/package.json +4 -2
  156. package/specs/avaliacoes-de-agentes/spec.md +52 -0
  157. package/specs/criterios-ligados-a-testes/spec.md +42 -0
  158. package/specs/memoria-de-sessao/spec.md +48 -0
  159. package/specs/skills-do-projeto/plan.md +40 -0
  160. package/specs/skills-do-projeto/spec.md +63 -0
  161. package/specs/skills-do-projeto/tasks.md +27 -0
  162. package/specs/v6-agent-runtime-portable/spec.md +83 -0
  163. package/specs/v6-core-consolidation/spec.md +70 -0
  164. package/specs/v6-docs-drift/spec.md +85 -0
  165. package/specs/v6-quality-gates/spec.md +99 -0
  166. package/specs/v6-token-economy/spec.md +84 -0
  167. package/templates/evals/agents/adr.json +25 -0
  168. package/templates/evals/agents/memoria.json +32 -0
  169. package/templates/evals/agents/proxima-acao.json +29 -0
  170. package/templates/evals/agents/spec-nova.json +26 -0
  171. package/templates/evals/agents/teste-do-criterio.json +29 -0
  172. package/templates/project/AGENTS.md +16 -0
  173. package/templates/project/CLAUDE.md +3 -2
  174. package/templates/project/agents/context-engineer.md +3 -0
  175. package/templates/project/agents/governance.md +3 -0
  176. package/templates/project/agents/marketing.md +3 -0
  177. package/templates/project/agents/orchestrator.md +3 -0
  178. package/templates/project/agents/product.md +3 -0
  179. package/templates/project/agents/sdd-architect.md +3 -0
  180. package/templates/project/skills/README.md +14 -0
  181. package/templates/project/skills/accessibility-review/SKILL.md +89 -0
  182. package/templates/project/skills/api-design/SKILL.md +77 -0
  183. package/templates/project/skills/architecture-decision-record/SKILL.md +92 -0
  184. package/templates/project/skills/backlog-slicing/SKILL.md +82 -0
  185. package/templates/project/skills/bounded-context-mapping/SKILL.md +88 -0
  186. package/templates/project/skills/ci-pipeline-review/SKILL.md +83 -0
  187. package/templates/project/skills/commit-message/SKILL.md +143 -0
  188. package/templates/project/skills/data-migrations/SKILL.md +88 -0
  189. package/templates/project/skills/dependency-upgrade/SKILL.md +75 -0
  190. package/templates/project/skills/docker-compose-review/SKILL.md +85 -0
  191. package/templates/project/skills/domain-modeling/SKILL.md +120 -0
  192. package/templates/project/skills/event-storming/SKILL.md +95 -0
  193. package/templates/project/skills/executive-writing/SKILL.md +99 -0
  194. package/templates/project/skills/frontend-architecture/SKILL.md +97 -0
  195. package/templates/project/skills/incident-postmortem/SKILL.md +93 -0
  196. package/templates/project/skills/lgpd-compliance/SKILL.md +108 -0
  197. package/templates/project/skills/llm-provider-routing/SKILL.md +18 -0
  198. package/templates/project/skills/observability/SKILL.md +93 -0
  199. package/templates/project/skills/product-evaluation/SKILL.md +130 -0
  200. package/templates/project/skills/prompt-spec/SKILL.md +83 -0
  201. package/templates/project/skills/pull-request/SKILL.md +101 -0
  202. package/templates/project/skills/query-performance/SKILL.md +83 -0
  203. package/templates/project/skills/release-checklist/SKILL.md +106 -0
  204. package/templates/project/skills/release-notes/SKILL.md +87 -0
  205. package/templates/project/skills/requirements-elicitation/SKILL.md +127 -0
  206. package/templates/project/skills/requirements-gathering/SKILL.md +134 -0
  207. package/templates/project/skills/technical-spike/SKILL.md +101 -0
  208. package/templates/project/skills/testing/SKILL.md +109 -0
  209. package/templates/project/skills/threat-modeling/SKILL.md +87 -0
  210. package/templates/project/skills/ts-async-patterns/SKILL.md +101 -0
  211. package/templates/project/skills/ts-code-review/SKILL.md +121 -0
  212. package/templates/project/skills/ts-module-layout/SKILL.md +104 -0
  213. package/templates/project/skills/ts-testing/SKILL.md +89 -0
  214. package/templates/project/skills/web-performance/SKILL.md +72 -0
  215. package/boilerplates/02-saas-starter/.env.example +0 -25
  216. package/boilerplates/02-saas-starter/CHECKLIST-CRIACAO.md +0 -190
  217. package/boilerplates/02-saas-starter/INFO.md +0 -252
  218. package/boilerplates/02-saas-starter/QUICK_START.md +0 -194
  219. package/boilerplates/02-saas-starter/START-HERE.md +0 -259
  220. package/boilerplates/02-saas-starter/backend/src/common/decorators/roles.decorator.ts +0 -3
  221. package/boilerplates/02-saas-starter/backend/src/common/decorators/tenant.decorator.ts +0 -6
  222. package/boilerplates/02-saas-starter/backend/src/common/middleware/roles.guard.ts +0 -23
  223. package/boilerplates/02-saas-starter/backend/src/config/database.ts +0 -26
  224. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.controller.ts +0 -46
  225. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.module.ts +0 -25
  226. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.service.ts +0 -145
  227. package/boilerplates/02-saas-starter/backend/src/modules/auth/dto/auth.dto.ts +0 -30
  228. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/jwt.strategy.ts +0 -24
  229. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/local.strategy.ts +0 -19
  230. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.controller.ts +0 -42
  231. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.module.ts +0 -13
  232. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.service.ts +0 -67
  233. package/boilerplates/02-saas-starter/backend/src/modules/billing/entities/invoice.entity.ts +0 -52
  234. package/boilerplates/02-saas-starter/backend/src/modules/organizations/entities/organization.entity.ts +0 -36
  235. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.controller.ts +0 -16
  236. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.module.ts +0 -13
  237. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.service.ts +0 -34
  238. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/entities/subscription.entity.ts +0 -40
  239. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.controller.ts +0 -36
  240. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.module.ts +0 -13
  241. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.service.ts +0 -91
  242. package/boilerplates/02-saas-starter/backend/src/modules/users/entities/user.entity.ts +0 -42
  243. package/boilerplates/02-saas-starter/backend/src/modules/users/users.controller.ts +0 -14
  244. package/boilerplates/02-saas-starter/backend/src/modules/users/users.module.ts +0 -13
  245. package/boilerplates/02-saas-starter/backend/src/modules/users/users.service.ts +0 -48
  246. package/boilerplates/02-saas-starter/memory/00-global/agent-contract.md +0 -227
  247. package/boilerplates/02-saas-starter/memory/00-global/context-policy.md +0 -141
  248. package/boilerplates/02-saas-starter/memory/00-global/index.md +0 -133
  249. package/boilerplates/02-saas-starter/memory/00-global/mission.md +0 -45
  250. package/boilerplates/02-saas-starter/memory/00-global/patterns.md +0 -223
  251. package/boilerplates/02-saas-starter/memory/10-product/business-rules.md +0 -240
  252. package/boilerplates/02-saas-starter/memory/10-product/nfrs.md +0 -239
  253. package/boilerplates/02-saas-starter/memory/10-product/personas.md +0 -195
  254. package/boilerplates/02-saas-starter/memory/10-product/vision.md +0 -63
  255. package/boilerplates/02-saas-starter/memory/20-architecture/overview.md +0 -232
  256. package/boilerplates/02-saas-starter/memory/30-domains/auth/api.md +0 -186
  257. package/boilerplates/02-saas-starter/memory/30-domains/auth/context.md +0 -85
  258. package/boilerplates/02-saas-starter/memory/30-domains/billing/api.md +0 -262
  259. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/api.md +0 -176
  260. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/context.md +0 -100
  261. package/boilerplates/02-saas-starter/memory/40-delivery/backlog.md +0 -81
  262. package/boilerplates/02-saas-starter/memory/40-delivery/roadmap.md +0 -97
  263. package/boilerplates/02-saas-starter/memory/40-delivery/sprint-atual.md +0 -57
  264. package/boilerplates/02-saas-starter/memory/50-orchestration/topology.md +0 -90
  265. package/boilerplates/02-saas-starter/memory/60-runs/index.md +0 -54
  266. package/boilerplates/02-saas-starter/memory/70-summaries/global.md +0 -50
  267. package/boilerplates/02-saas-starter/memory/80-data/schema.md +0 -185
  268. package/boilerplates/02-saas-starter/memory/90-decisions/adr-template.md +0 -75
@@ -1,4 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { assertExecutionTransition } from '../../orchestration/src/index.js';
3
+ import { assertPlanningCreate, assertPlanningReview, clonePlanningValue } from '../../planner/src/proposal-store.js';
2
4
  export const MIGRATIONS = [
3
5
  {
4
6
  version: 1,
@@ -82,7 +84,24 @@ export class SqliteJsonRepository {
82
84
  }
83
85
  export class SqliteOrchestrationStore {
84
86
  repository;
85
- constructor(db) { this.repository = new SqliteJsonRepository(db); }
87
+ db;
88
+ constructor(db) { this.db = db; this.repository = new SqliteJsonRepository(db); }
89
+ transitionExecution(input) {
90
+ // A savepoint also works inside an existing transaction. No handlers or awaits here.
91
+ this.db.exec('SAVEPOINT forja_execution_transition');
92
+ try {
93
+ assertExecutionTransition(input, this.getTask(input.beforeTask.id), input.beforeHandoff === undefined ? undefined : this.getHandoff(input.beforeHandoff.id));
94
+ this.saveTask(input.task);
95
+ if (input.handoff !== undefined)
96
+ this.saveHandoff(input.handoff);
97
+ this.db.exec('RELEASE SAVEPOINT forja_execution_transition');
98
+ }
99
+ catch (error) {
100
+ this.db.exec('ROLLBACK TO SAVEPOINT forja_execution_transition');
101
+ this.db.exec('RELEASE SAVEPOINT forja_execution_transition');
102
+ throw error;
103
+ }
104
+ }
86
105
  saveSprint(value) { this.repository.put('sprint', value.id, value, value.updatedAt); }
87
106
  getSprint(id) { return this.repository.get('sprint', id); }
88
107
  listSprints() { return this.repository.list('sprint'); }
@@ -93,6 +112,47 @@ export class SqliteOrchestrationStore {
93
112
  getHandoff(id) { return this.repository.get('handoff', id); }
94
113
  listHandoffs() { return this.repository.list('handoff'); }
95
114
  }
115
+ export class SqlitePlanningStore {
116
+ db;
117
+ repository;
118
+ reader;
119
+ constructor(db) {
120
+ this.db = db;
121
+ this.repository = new SqliteJsonRepository(db);
122
+ this.reader = new SqliteOrchestrationStore(db);
123
+ }
124
+ create(proposal) {
125
+ const next = clonePlanningValue(proposal);
126
+ this.transaction(() => {
127
+ assertPlanningCreate(next, this.get(next.id), this.reader);
128
+ this.repository.put('planning_proposal', next.id, next, next.updatedAt);
129
+ });
130
+ }
131
+ get(id) { return this.repository.get('planning_proposal', id); }
132
+ review(before, after, expectedSnapshot) {
133
+ const previous = clonePlanningValue(before);
134
+ const next = clonePlanningValue(after);
135
+ const expected = clonePlanningValue(expectedSnapshot);
136
+ this.transaction(() => {
137
+ if (assertPlanningReview(previous, next, this.get(previous.id), expected, this.reader)) {
138
+ this.repository.put('planning_proposal', next.id, next, next.updatedAt);
139
+ }
140
+ });
141
+ }
142
+ transaction(write) {
143
+ // Snapshot reads, CAS and proposal write share the same short, synchronous transaction.
144
+ this.db.exec('SAVEPOINT forja_planning_proposal');
145
+ try {
146
+ write();
147
+ this.db.exec('RELEASE SAVEPOINT forja_planning_proposal');
148
+ }
149
+ catch (error) {
150
+ this.db.exec('ROLLBACK TO SAVEPOINT forja_planning_proposal');
151
+ this.db.exec('RELEASE SAVEPOINT forja_planning_proposal');
152
+ throw error;
153
+ }
154
+ }
155
+ }
96
156
  export class SqliteSandboxStore {
97
157
  repository;
98
158
  constructor(db) { this.repository = new SqliteJsonRepository(db); }
@@ -21,6 +21,7 @@ export interface ContextBuildRequest {
21
21
  readonly objective: string;
22
22
  readonly budget: TokenBudget;
23
23
  readonly includeContent?: boolean;
24
+ readonly includeProvenanceInBudget?: boolean;
24
25
  readonly maxItems?: number;
25
26
  readonly requireEvidence?: boolean;
26
27
  readonly correlationId?: string;
@@ -53,6 +54,7 @@ export declare class ContextEngine {
53
54
  build(request: ContextBuildRequest): Promise<ContextPackage>;
54
55
  expand(checksum: string): string;
55
56
  private isUsable;
57
+ private contextItem;
56
58
  private estimateTokens;
57
59
  private checksum;
58
60
  private uniqueEvidence;
@@ -42,30 +42,38 @@ export class ContextEngine {
42
42
  if (candidates.length === 0 && (request.requireEvidence ?? true))
43
43
  throw new ContextEngineError('INSUFFICIENT_EVIDENCE', 'No current evidence matches the context objective');
44
44
  const ranked = candidates
45
- .map((candidate) => ({ candidate, checksum: candidate.checksum ?? this.checksum(candidate.content) }))
46
- .sort((left, right) => right.candidate.relevance - left.candidate.relevance || left.candidate.locator.localeCompare(right.candidate.locator) || left.checksum.localeCompare(right.checksum));
45
+ .map((candidate) => ({ candidate, item: this.contextItem(candidate, request.includeContent !== false) }))
46
+ .sort((left, right) => right.candidate.relevance - left.candidate.relevance
47
+ || left.item.locator.localeCompare(right.item.locator)
48
+ || left.item.checksum.localeCompare(right.item.checksum)
49
+ || JSON.stringify(left.item).localeCompare(JSON.stringify(right.item)));
47
50
  const unique = new Map();
48
- for (const item of ranked)
49
- if (!unique.has(item.checksum))
50
- unique.set(item.checksum, item);
51
+ for (const entry of ranked)
52
+ if (!unique.has(entry.item.checksum))
53
+ unique.set(entry.item.checksum, entry);
51
54
  const availableTokens = request.budget.totalTokens - request.budget.usedTokens;
52
55
  let usedTokens = 0;
53
56
  let cacheHits = 0;
54
57
  const selected = [];
55
- for (const item of [...unique.values()].slice(0, maxItems)) {
56
- const tokens = this.estimateTokens(item.candidate.content);
58
+ for (const entry of [...unique.values()].slice(0, maxItems)) {
59
+ const { candidate, item } = entry;
60
+ const tokens = this.estimateTokens(request.includeProvenanceInBudget ? JSON.stringify(item) : candidate.content);
57
61
  if (usedTokens + tokens > availableTokens)
58
62
  continue;
59
- if (this.dependencies.cache?.get(item.checksum) !== undefined)
63
+ // Supplied keys remain valid for expand(), but never establish content freshness.
64
+ const cacheKey = candidate.checksum ?? item.checksum;
65
+ if (this.dependencies.cache?.get(cacheKey) === candidate.content)
60
66
  cacheHits += 1;
61
- else
62
- this.dependencies.cache?.set(item.checksum, item.candidate.content);
63
- selected.push({ ...item, tokens });
67
+ this.dependencies.cache?.set(cacheKey, candidate.content);
68
+ if (cacheKey !== item.checksum)
69
+ this.dependencies.cache?.set(item.checksum, candidate.content);
70
+ selected.push(entry);
64
71
  usedTokens += tokens;
65
72
  }
66
73
  if (selected.length === 0 && (request.requireEvidence ?? true))
67
74
  throw new ContextEngineError('CONTEXT_BUDGET_EXCEEDED', 'Context budget cannot fit any evidence');
68
- const references = this.uniqueEvidence(selected.flatMap((item) => item.candidate.evidence));
75
+ const items = selected.map((entry) => entry.item);
76
+ const references = this.uniqueEvidence(items.flatMap((item) => item.evidence));
69
77
  const content = request.includeContent === false ? [] : selected.map((item) => item.candidate.content);
70
78
  const metrics = {
71
79
  candidateCount: candidates.length,
@@ -81,8 +89,9 @@ export class ContextEngine {
81
89
  id: randomUUID(),
82
90
  references,
83
91
  content,
92
+ items,
84
93
  budget: { ...request.budget, usedTokens: request.budget.usedTokens + usedTokens },
85
- checksum: this.checksum(JSON.stringify({ objective: request.objective, refs: selected.map((item) => item.checksum), includeContent: request.includeContent !== false })),
94
+ checksum: this.checksum(JSON.stringify({ objective: request.objective, items, includeContent: request.includeContent !== false })),
86
95
  metrics,
87
96
  };
88
97
  }
@@ -93,7 +102,18 @@ export class ContextEngine {
93
102
  return content;
94
103
  }
95
104
  isUsable(candidate) {
96
- return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0;
105
+ return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0 && candidate.evidence.every((item) => item.status !== 'contradicted');
106
+ }
107
+ contextItem(candidate, includeContent) {
108
+ return {
109
+ id: candidate.id,
110
+ source: candidate.source,
111
+ locator: candidate.locator,
112
+ ...(includeContent ? { content: candidate.content } : {}),
113
+ checksum: this.checksum(candidate.content),
114
+ status: candidate.status,
115
+ evidence: [...candidate.evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right))),
116
+ };
97
117
  }
98
118
  estimateTokens(content) {
99
119
  return Math.max(1, Math.ceil(Buffer.byteLength(content, 'utf8') / 4));
@@ -103,7 +123,8 @@ export class ContextEngine {
103
123
  }
104
124
  uniqueEvidence(evidence) {
105
125
  const unique = new Map();
106
- for (const item of evidence)
126
+ const sorted = [...evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right)));
127
+ for (const item of sorted)
107
128
  if (!unique.has(item.id))
108
129
  unique.set(item.id, item);
109
130
  return [...unique.values()];
@@ -72,6 +72,7 @@ export interface ExecutionError {
72
72
  readonly details?: Readonly<Record<string, string>>;
73
73
  }
74
74
  export interface ExecutionResult extends AuditFields {
75
+ readonly operationId?: string;
75
76
  readonly runId: RunId;
76
77
  readonly status: 'succeeded' | 'failed' | 'blocked' | 'cancelled';
77
78
  readonly output?: CapabilityOutput;
@@ -118,6 +119,8 @@ export interface PolicyDecision {
118
119
  readonly approvalRequestId?: EntityId;
119
120
  }
120
121
  export interface ApprovalRequest extends AuditFields {
122
+ readonly operationId?: string;
123
+ readonly fingerprint?: string;
121
124
  readonly id: EntityId;
122
125
  readonly action: string;
123
126
  readonly justification: string;
@@ -147,6 +150,10 @@ export interface Sprint extends AuditFields {
147
150
  }
148
151
  export interface Task extends AuditFields {
149
152
  readonly id: EntityId;
153
+ readonly runtimeRunId?: RunId;
154
+ readonly handoffId?: EntityId;
155
+ readonly executionScopeHash?: string;
156
+ readonly executionError?: ExecutionError;
150
157
  readonly sprintId: EntityId;
151
158
  readonly objective: string;
152
159
  readonly acceptanceCriteria: readonly string[];
@@ -158,6 +165,9 @@ export interface Task extends AuditFields {
158
165
  }
159
166
  export interface Handoff extends AuditFields {
160
167
  readonly id: EntityId;
168
+ readonly taskId?: EntityId;
169
+ readonly runId?: RunId;
170
+ readonly status?: 'pending' | 'in_progress' | 'blocked' | 'completed' | 'cancelled';
161
171
  readonly from: string;
162
172
  readonly to: string;
163
173
  readonly intent: string;
@@ -192,6 +202,7 @@ export interface RuntimeRun extends AuditFields {
192
202
  readonly agent: AgentIdentity;
193
203
  readonly sprintId?: EntityId;
194
204
  readonly taskId?: EntityId;
205
+ readonly handoffId?: EntityId;
195
206
  readonly policy: PolicyDecision;
196
207
  readonly budget: TokenBudget;
197
208
  readonly state: ExecutionState;
@@ -251,10 +262,20 @@ export interface ContextMetrics {
251
262
  readonly selectedTokens: number;
252
263
  readonly unusedTokens: number;
253
264
  }
265
+ export interface ContextItem {
266
+ readonly id: EntityId;
267
+ readonly source: 'memory' | 'graph';
268
+ readonly locator: string;
269
+ readonly content?: string;
270
+ readonly checksum: string;
271
+ readonly status: KnowledgeStatus;
272
+ readonly evidence: readonly Evidence[];
273
+ }
254
274
  export interface ContextPackage extends AuditFields {
255
275
  readonly id: EntityId;
256
276
  readonly references: readonly Evidence[];
257
277
  readonly content: readonly string[];
278
+ readonly items?: readonly ContextItem[];
258
279
  readonly budget: TokenBudget;
259
280
  readonly checksum: string;
260
281
  readonly metrics: ContextMetrics;
@@ -275,6 +296,10 @@ export interface PlanStep extends AuditFields {
275
296
  readonly acceptanceCriteria: readonly string[];
276
297
  readonly allowedFiles: readonly string[];
277
298
  readonly dependencyIds: readonly EntityId[];
299
+ readonly externalDependencyIds?: readonly EntityId[];
300
+ readonly contextItemId?: EntityId;
301
+ readonly rationale?: string;
302
+ readonly constraints?: readonly string[];
278
303
  readonly evidenceIds: readonly EntityId[];
279
304
  readonly risk: RiskLevel;
280
305
  readonly budget: TokenBudget;
@@ -286,8 +311,47 @@ export interface ExecutionPlan extends AuditFields {
286
311
  readonly steps: readonly PlanStep[];
287
312
  readonly budget: TokenBudget;
288
313
  readonly risk: RiskLevel;
314
+ readonly constraints?: readonly string[];
315
+ readonly decisions?: readonly string[];
289
316
  readonly evidenceIds: readonly EntityId[];
290
317
  }
318
+ export interface PlanningSnapshot {
319
+ readonly task: Task;
320
+ readonly sprint: Sprint;
321
+ readonly dependencies: readonly Task[];
322
+ readonly handoff?: Handoff;
323
+ }
324
+ export interface PlanningBudget {
325
+ readonly limit: TokenBudget;
326
+ readonly briefingTokens: number;
327
+ readonly contextTokens: number;
328
+ readonly allocation: TokenBudget;
329
+ }
330
+ export interface PlanningReview {
331
+ readonly decision: 'approved' | 'rejected';
332
+ readonly reviewerId: EntityId;
333
+ readonly reason: string;
334
+ readonly digest: string;
335
+ readonly decidedAt: ISO8601;
336
+ readonly sourcesVerifiedAt?: ISO8601;
337
+ }
338
+ export interface PlanningProposal extends AuditFields {
339
+ readonly id: EntityId;
340
+ readonly version: 1;
341
+ readonly digest: string;
342
+ readonly executor: AgentIdentity;
343
+ readonly snapshot: PlanningSnapshot;
344
+ readonly plan?: ExecutionPlan;
345
+ readonly context?: ContextPackage;
346
+ readonly status: 'draft' | 'approved' | 'rejected' | 'blocked';
347
+ readonly blockers: readonly {
348
+ readonly code: string;
349
+ readonly message: string;
350
+ }[];
351
+ readonly budget: PlanningBudget;
352
+ readonly declaredEvidenceIds: readonly EntityId[];
353
+ readonly review?: PlanningReview;
354
+ }
291
355
  export interface EvaluationResult extends AuditFields {
292
356
  readonly status: 'accepted' | 'rejected' | 'inconclusive' | 'blocked';
293
357
  readonly checks: readonly {
@@ -1,4 +1,4 @@
1
- import { type AgentIdentity, type AgentProfile, type CapabilityDefinition, type CapabilityInput, type CapabilityOutput, type ExecutionResult, type PolicyDecision, type RunId, type ISO8601, type TokenBudget } from '../../contracts/src/index.ts';
1
+ import { type AgentIdentity, type AgentProfile, type CapabilityDefinition, type CapabilityInput, type CapabilityOutput, type ExecutionError, type ExecutionResult, type PolicyDecision, type RunId, type ISO8601, type TokenBudget } from '../../contracts/src/index.ts';
2
2
  export interface CapabilityExecutionContext {
3
3
  readonly runId: RunId;
4
4
  readonly agent: AgentIdentity;
@@ -6,6 +6,7 @@ export interface CapabilityExecutionContext {
6
6
  }
7
7
  export interface CapabilityRegistration<Input, Output> {
8
8
  readonly definition: CapabilityDefinition;
9
+ readonly categories?: readonly string[];
9
10
  readonly validateInput: (value: unknown) => Input;
10
11
  readonly validateOutput: (value: unknown) => Output;
11
12
  readonly handler: (input: Input, context: CapabilityExecutionContext) => CapabilityOutput | Promise<CapabilityOutput>;
@@ -15,6 +16,7 @@ export interface CapabilityAuthorizationRequest {
15
16
  readonly input: CapabilityInput;
16
17
  readonly agent: AgentIdentity;
17
18
  readonly correlationId?: string;
19
+ readonly operationId?: string;
18
20
  readonly projectId?: string;
19
21
  readonly environment: string;
20
22
  readonly categories: readonly string[];
@@ -42,6 +44,7 @@ export interface CapabilityExecutionRequest {
42
44
  readonly agent: AgentIdentity;
43
45
  readonly policy: CapabilityPolicy;
44
46
  readonly correlationId?: string;
47
+ readonly operationId?: string;
45
48
  readonly projectId?: string;
46
49
  readonly environment?: string;
47
50
  readonly categories?: readonly string[];
@@ -62,6 +65,11 @@ export interface CapabilityExecutionRequest {
62
65
  export declare class CapabilityRegistryError extends Error {
63
66
  constructor(message: string);
64
67
  }
68
+ export declare class CapabilityExecutionFailure extends Error {
69
+ readonly executionError: ExecutionError;
70
+ readonly output?: CapabilityOutput;
71
+ constructor(error: ExecutionError, output?: CapabilityOutput);
72
+ }
65
73
  export declare class CapabilityRegistry {
66
74
  private readonly registrations;
67
75
  private readonly aliases;
@@ -6,6 +6,16 @@ export class CapabilityRegistryError extends Error {
6
6
  this.name = 'CapabilityRegistryError';
7
7
  }
8
8
  }
9
+ export class CapabilityExecutionFailure extends Error {
10
+ executionError;
11
+ output;
12
+ constructor(error, output) {
13
+ super(error.message);
14
+ this.name = 'CapabilityExecutionFailure';
15
+ this.executionError = error;
16
+ this.output = output;
17
+ }
18
+ }
9
19
  export class CapabilityRegistry {
10
20
  registrations = new Map();
11
21
  aliases = new Map();
@@ -24,6 +34,7 @@ export class CapabilityRegistry {
24
34
  }
25
35
  const stored = {
26
36
  definition,
37
+ categories: [...(registration.categories ?? definition.permissions)],
27
38
  validateInput: registration.validateInput,
28
39
  validateOutput: registration.validateOutput,
29
40
  handler: registration.handler,
@@ -47,7 +58,7 @@ export class CapabilityRegistry {
47
58
  }
48
59
  async execute(request) {
49
60
  const runId = this.createRunId();
50
- const timestamps = this.auditFields(request.correlationId ?? runId);
61
+ const timestamps = { ...this.auditFields(request.correlationId ?? runId), operationId: request.operationId ?? request.correlationId ?? runId };
51
62
  const resolved = this.tryResolve(request.input.capabilityId);
52
63
  if (resolved.error !== undefined) {
53
64
  return this.failure(runId, timestamps, resolved.error);
@@ -64,12 +75,13 @@ export class CapabilityRegistry {
64
75
  try {
65
76
  decision = request.policy.authorize({
66
77
  definition: registration.definition,
67
- input: request.input,
78
+ input: { capabilityId: registration.definition.id, payload: input },
68
79
  agent: request.agent,
69
80
  correlationId: request.correlationId ?? runId,
81
+ operationId: timestamps.operationId,
70
82
  projectId: request.projectId,
71
83
  environment: request.environment ?? 'local',
72
- categories: request.categories ?? [],
84
+ categories: registration.categories ?? registration.definition.permissions,
73
85
  files: request.files ?? [],
74
86
  budget: request.budget,
75
87
  now: timestamps.createdAt,
@@ -108,6 +120,19 @@ export class CapabilityRegistry {
108
120
  return { ...timestamps, runId, status: 'succeeded', output, evidence: output.evidence };
109
121
  }
110
122
  catch (error) {
123
+ if (error instanceof CapabilityExecutionFailure) {
124
+ if (error.output !== undefined) {
125
+ try {
126
+ registration.validateOutput(error.output.payload);
127
+ if (error.output.capabilityId !== registration.definition.id)
128
+ throw new Error('Handler output capabilityId does not match definition');
129
+ }
130
+ catch (invalidOutput) {
131
+ return this.failure(runId, timestamps, this.toExecutionError('HANDLER_FAILED', invalidOutput, false));
132
+ }
133
+ }
134
+ return { ...timestamps, runId, status: 'failed', error: error.executionError, output: error.output, evidence: error.output?.evidence ?? [] };
135
+ }
111
136
  return this.failure(runId, timestamps, this.toExecutionError('HANDLER_FAILED', error, true));
112
137
  }
113
138
  }
@@ -169,21 +169,30 @@ export class GraphLoop {
169
169
  }
170
170
  contextRecords(objective) {
171
171
  const terms = objective.toLowerCase().split(/[^a-z0-9_./-]+/).filter((term) => term.length > 1);
172
- const records = this.activeEdges()
172
+ const at = new Date().toISOString();
173
+ const records = this.activeEdges(at)
173
174
  .map((edge) => {
174
175
  const from = this.store.getNode(edge.from);
175
176
  const to = this.store.getNode(edge.to);
176
177
  if (from === undefined || to === undefined)
177
178
  return undefined;
178
- const content = `${from.label} ${edge.type} ${to.label}`;
179
- const haystack = content.toLowerCase();
179
+ if ([from, to].some((node) => node.status === 'contradicted' || !this.active(node.validFrom, node.validTo, at)))
180
+ return undefined;
181
+ const relation = `${from.label} ${edge.type} ${to.label}`;
182
+ const haystack = relation.toLowerCase();
180
183
  const matches = terms.filter((term) => haystack.includes(term)).length;
181
184
  if (matches === 0)
182
185
  return undefined;
183
186
  const evidence = edge.evidenceIds.map((id) => this.store.getEvidence(id)).filter((item) => item !== undefined);
184
- if (evidence.length === 0)
187
+ if (evidence.length !== edge.evidenceIds.length || evidence.length === 0 || evidence.some((item) => item.status === 'contradicted'))
185
188
  return undefined;
186
- return { id: edge.id, locator: `graph:${edge.id}`, content, relevance: matches / Math.max(1, terms.length), status: edge.status, evidence: evidence, checksum: createHash('sha256').update(`${edge.id}:${edge.updatedAt}:${content}`).digest('hex') };
189
+ evidence.sort((left, right) => left.id.localeCompare(right.id));
190
+ const content = from.type === 'Execution' || to.type === 'Execution'
191
+ ? `${relation} [Execution memory: handler attempt/result, not independent acceptance of the task.]`
192
+ : relation;
193
+ const statuses = [edge.status, from.status, to.status, ...evidence.map((item) => item.status)];
194
+ const status = ['unknown', 'hypothesis', 'inferred'].find((value) => statuses.includes(value)) ?? 'verified';
195
+ return { id: edge.id, locator: `graph:${edge.id}`, content, relevance: matches / Math.max(1, terms.length), status, evidence, checksum: createHash('sha256').update(`${edge.id}:${edge.updatedAt}:${content}`).digest('hex') };
187
196
  });
188
197
  return records
189
198
  .filter((record) => record !== undefined)
@@ -7,6 +7,9 @@ export const DEFAULT_LLM_PROFILES = {
7
7
  claude: { provider: 'claude', model: 'default', command: 'claude', roles: ['sdd-architect', 'product'], taskTypes: ['architecture', 'specification', 'analysis'], privacy: 'external', enabled: true },
8
8
  gemini: { provider: 'gemini-cli', model: 'default', command: 'gemini', roles: ['context-engineer', 'marketing'], taskTypes: ['research', 'context', 'writing'], privacy: 'external', enabled: true },
9
9
  ollama: { provider: 'ollama', model: 'llama3.3', command: 'ollama', roles: [], taskTypes: ['offline', 'sensitive'], privacy: 'local', enabled: false },
10
+ copilot: { provider: 'copilot', model: 'default', command: 'copilot', roles: ['worker'], taskTypes: ['implementation', 'review'], privacy: 'external', enabled: false },
11
+ cursor: { provider: 'cursor-agent', model: 'default', command: 'cursor-agent', roles: ['worker', 'sdd-architect'], taskTypes: ['implementation', 'analysis', 'review'], privacy: 'external', enabled: false },
12
+ opencode: { provider: 'opencode', model: 'default', command: 'opencode', roles: ['worker'], taskTypes: ['implementation', 'analysis'], privacy: 'external', enabled: false },
10
13
  },
11
14
  };
12
15
  export class LlmProfileError extends Error {
@@ -52,12 +55,19 @@ export function buildLlmExecution(profile, prompt, options = {}) {
52
55
  args: [...base, ...(profile.model === 'default' ? [] : ['--model', profile.model]), '-p', prompt,
53
56
  '--output-format', 'json', ...(options.resume ? ['--resume', options.resume] : [])],
54
57
  };
58
+ // Todos os adapters de agente rodam em modo somente leitura/planejamento: o llm:run é supervisionado
59
+ // e quem aplica mudanças é o fluxo do Forja, não o provedor (ADR-0090).
55
60
  if (profile.provider === 'gemini-cli')
56
- return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['-m', profile.model]), '-p', prompt] };
61
+ return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['-m', profile.model]), '--approval-mode', 'plan', '-o', 'json', '-p', prompt] };
57
62
  if (profile.provider === 'ollama')
58
63
  return { executable: profile.command, args: [...base, 'run', profile.model, prompt] };
64
+ // GitHub Copilot CLI (`copilot`): sem --allow-*, ferramentas que pedem aprovação ficam negadas no modo -p.
59
65
  if (profile.provider === 'copilot')
60
- return { executable: profile.command, args: [...base, 'copilot', 'suggest', '-t', 'shell', prompt] };
66
+ return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['--model', profile.model]), '-s', '-p', prompt] };
67
+ if (profile.provider === 'cursor-agent')
68
+ return { executable: profile.command, args: [...base, '-p', '--mode', 'plan', '--output-format', 'json', ...(profile.model === 'default' ? [] : ['--model', profile.model]), prompt] };
69
+ if (profile.provider === 'opencode')
70
+ return { executable: profile.command, args: ['run', ...base, '--agent', 'plan', ...(profile.model === 'default' ? [] : ['-m', profile.model]), prompt] };
61
71
  return { executable: profile.command, args: [...base, prompt] };
62
72
  }
63
73
  /** Grace period after SIGTERM before a timed-out LLM subprocess (and anything it spawned) gets SIGKILLed. */
@@ -39,6 +39,10 @@ export interface McpAgentContext {
39
39
  readonly permissions: readonly string[];
40
40
  readonly capabilities: readonly CapabilityId[];
41
41
  }
42
+ export interface McpPlanning {
43
+ propose(input: unknown): unknown | Promise<unknown>;
44
+ get(id: string): unknown | Promise<unknown>;
45
+ }
42
46
  export interface McpMemoryQuery {
43
47
  query(objective: string): unknown | Promise<unknown>;
44
48
  }
@@ -76,6 +80,7 @@ export interface McpServerDependencies {
76
80
  readonly policy: CapabilityPolicy;
77
81
  readonly agent: McpAgentContext;
78
82
  readonly context?: ContextEngine;
83
+ readonly planning?: McpPlanning;
79
84
  readonly graph?: GraphLoop;
80
85
  readonly memory?: McpMemoryQuery;
81
86
  readonly taskEngine?: TaskEngine;
@@ -91,6 +96,8 @@ export interface McpServerDependencies {
91
96
  export declare class McpAdapterError extends Error {
92
97
  constructor(message: string);
93
98
  }
99
+ export declare const PLANNING_PROPOSE_SCHEMA: McpInputSchema;
100
+ export declare const PLANNING_REVIEW_SCHEMA: McpInputSchema;
94
101
  export declare const MCP_TOOLS: readonly McpToolDefinition[];
95
102
  export declare class McpServer {
96
103
  private readonly dependencies;
@@ -119,6 +126,7 @@ export declare class McpServer {
119
126
  private entities;
120
127
  private number;
121
128
  private optionalStatus;
129
+ private requirePlanning;
122
130
  private requireContext;
123
131
  private requireGraph;
124
132
  private requireMemory;
@@ -10,7 +10,11 @@ export const MCP_RESOURCE_URIS = [
10
10
  export class McpAdapterError extends Error {
11
11
  constructor(message) { super(message); this.name = 'McpAdapterError'; }
12
12
  }
13
+ export const PLANNING_PROPOSE_SCHEMA = { type: 'object', properties: { taskId: { type: 'string', minLength: 1 }, handoffId: { type: 'string', minLength: 1 }, correlationId: { type: 'string', minLength: 1 }, budget: { type: 'object', properties: Object.fromEntries(['inputTokens', 'outputTokens', 'totalTokens', 'usedTokens'].map((field) => [field, { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }])), required: ['inputTokens', 'outputTokens', 'totalTokens', 'usedTokens'], additionalProperties: false } }, required: ['taskId'], additionalProperties: false };
14
+ export const PLANNING_REVIEW_SCHEMA = { type: 'object', properties: { decision: { type: 'string', enum: ['approved', 'rejected'] }, expectedDigest: { type: 'string', minLength: 1 }, reason: { type: 'string', minLength: 1 } }, required: ['decision', 'expectedDigest', 'reason'], additionalProperties: false };
13
15
  export const MCP_TOOLS = [
16
+ { name: 'forja_plan_propose', description: 'Gera proposta descritiva revisável sem executar capabilities.', inputSchema: PLANNING_PROPOSE_SCHEMA },
17
+ tool('forja_plan_get', 'Consulta uma proposta de planejamento persistida.', ['id']),
14
18
  tool('forja_workspace_status', 'Retorna o estado operacional mínimo do workspace.', []),
15
19
  tool('forja_capabilities_list', 'Lista capabilities visíveis para a identidade MCP.', []),
16
20
  tool('forja_capability_describe', 'Descreve uma capability pelo Registry.', ['capabilityId']),
@@ -79,6 +83,11 @@ export class McpServer {
79
83
  }
80
84
  async dispatch(name, input) {
81
85
  switch (name) {
86
+ case 'forja_plan_propose': return this.requirePlanning().propose(input);
87
+ case 'forja_plan_get':
88
+ if (Object.keys(input).some((key) => key !== 'id'))
89
+ throw new McpAdapterError('Unexpected planning input fields');
90
+ return this.requirePlanning().get(this.string(input, 'id'));
82
91
  case 'forja_workspace_status': return { agent: this.dependencies.agent, capabilities: this.dependencies.registry.list({ agent: this.dependencies.agent }), resources: this.listResources().map((resource) => resource.uri) };
83
92
  case 'forja_capabilities_list': return this.dependencies.registry.list({ agent: this.dependencies.agent, policy: this.dependencies.policy });
84
93
  case 'forja_capability_describe': return this.dependencies.registry.describe(this.string(input, 'capabilityId'), { agent: this.dependencies.agent, policy: this.dependencies.policy });
@@ -125,7 +134,7 @@ export class McpServer {
125
134
  this.authorize('forja_handoff_create', 'write', 'medium', []);
126
135
  return this.requireHandoffs().create({
127
136
  from: this.string(input, 'from'), to: this.string(input, 'to'), intent: this.string(input, 'intent'), objective: this.string(input, 'objective'),
128
- completedWork: this.strings(input, 'completedWork'), decisions: this.strings(input, 'decisions'), constraints: this.strings(input, 'constraints'), pending: this.strings(input, 'pending'), evidenceIds: this.entities(input, 'evidenceIds'), acceptance: this.strings(input, 'acceptance'), blockers: this.strings(input, 'blockers'), nextAgent: this.string(input, 'nextAgent'), correlationId: this.optionalString(input, 'correlationId'),
137
+ completedWork: this.strings(input, 'completedWork'), decisions: this.strings(input, 'decisions'), constraints: this.strings(input, 'constraints'), pending: this.strings(input, 'pending'), evidenceIds: this.entities(input, 'evidenceIds'), acceptance: this.strings(input, 'acceptance'), blockers: this.strings(input, 'blockers'), nextAgent: this.string(input, 'nextAgent'), correlationId: this.optionalString(input, 'correlationId'), taskId: input.taskId === undefined ? undefined : this.entity(input, 'taskId'),
129
138
  });
130
139
  }
131
140
  executeCapability(input) {
@@ -170,6 +179,8 @@ export class McpServer {
170
179
  optionalStatus(input, field) { const value = input[field]; if (value === undefined)
171
180
  return undefined; if (value !== 'verified' && value !== 'inferred' && value !== 'hypothesis' && value !== 'contradicted' && value !== 'unknown')
172
181
  throw new McpAdapterError(`${field} is an invalid knowledge status`); return value; }
182
+ requirePlanning() { if (this.dependencies.planning === undefined)
183
+ throw new McpAdapterError('Planning service is not configured'); return this.dependencies.planning; }
173
184
  requireContext() { if (this.dependencies.context === undefined)
174
185
  throw new McpAdapterError('Context Engine is not configured'); return this.dependencies.context; }
175
186
  requireGraph() { if (this.dependencies.graph === undefined)
@@ -29,6 +29,9 @@ export interface ObservationStore {
29
29
  export interface ControlPlanePort {
30
30
  metrics(): ControlPlaneMetrics | Promise<ControlPlaneMetrics>;
31
31
  observations(): readonly Observation[] | Promise<readonly Observation[]>;
32
+ planPropose?(input: unknown): unknown | Promise<unknown>;
33
+ planGet?(id: string): unknown | Promise<unknown>;
34
+ planReview?(id: string, input: unknown): unknown | Promise<unknown>;
32
35
  runtimeStart?(input: unknown): unknown | Promise<unknown>;
33
36
  runtimeGet?(id: string): unknown | Promise<unknown>;
34
37
  runtimeExecute?(id: string): unknown | Promise<unknown>;
@@ -57,6 +60,11 @@ export interface ControlPlaneEventSink {
57
60
  publish(event: ControlPlaneEvent): void;
58
61
  }
59
62
  export interface ControlPlaneServices {
63
+ readonly planning?: {
64
+ readonly propose: (input: unknown) => unknown | Promise<unknown>;
65
+ readonly get: (id: string) => unknown | Promise<unknown>;
66
+ readonly review: (id: string, input: unknown) => unknown | Promise<unknown>;
67
+ };
60
68
  readonly runtime?: {
61
69
  readonly start: (input: unknown) => unknown | Promise<unknown>;
62
70
  readonly get: (input: unknown) => unknown | Promise<unknown>;
@@ -110,6 +118,9 @@ export declare class ControlPlane implements ControlPlanePort {
110
118
  metrics(): Promise<ControlPlaneMetrics>;
111
119
  observations(): Promise<readonly Observation[]>;
112
120
  record(input: ObservationInput): Promise<Observation>;
121
+ planPropose(input: unknown): Promise<unknown>;
122
+ planGet(id: string): Promise<unknown>;
123
+ planReview(id: string, input: unknown): Promise<unknown>;
113
124
  runtimeStart(input: unknown): Promise<unknown>;
114
125
  runtimeGet(id: string): Promise<unknown>;
115
126
  runtimeExecute(id: string): Promise<unknown>;
@@ -47,6 +47,9 @@ export class ControlPlane {
47
47
  metrics() { return this.recorder.metrics(); }
48
48
  observations() { return this.recorder.observations(); }
49
49
  async record(input) { const observation = await this.recorder.record(input); this.services.events?.publish({ id: observation.id, type: 'observation.recorded', aggregateId: observation.runId ?? observation.traceId, data: observation, correlationId: observation.correlationId }); return observation; }
50
+ planPropose(input) { return this.delegate(this.services.planning?.propose, input, 'planPropose'); }
51
+ planGet(id) { const service = this.services.planning; return this.delegate(service === undefined ? undefined : () => service.get(id), id, 'planGet'); }
52
+ planReview(id, input) { const service = this.services.planning; return this.delegate(service === undefined ? undefined : () => service.review(id, input), input, 'planReview'); }
50
53
  runtimeStart(input) { return this.delegate(this.services.runtime?.start, input, 'runtimeStart'); }
51
54
  runtimeGet(id) { return this.delegate(this.services.runtime?.get, id, 'runtimeGet'); }
52
55
  runtimeExecute(id) { return this.delegate(this.services.runtime?.execute, id, 'runtimeExecute'); }