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,4 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { CONTRACT_VERSION, isPathWithinRoot, } from '../../contracts/src/index.js';
3
3
  export class PolicyError extends Error {
4
4
  constructor(message) {
@@ -6,6 +6,72 @@ export class PolicyError extends Error {
6
6
  this.name = 'PolicyError';
7
7
  }
8
8
  }
9
+ // Round-trip the calendar to reject Date.parse's normalization of impossible dates.
10
+ function approvalInstant(value) {
11
+ const parts = typeof value === 'string' ? /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value) : null;
12
+ if (parts === null)
13
+ throw new PolicyError('Approval date must be an unambiguous ISO timestamp');
14
+ const calendar = `${parts[1]}.${(parts[2] ?? '').padEnd(3, '0')}Z`;
15
+ const local = Date.parse(calendar);
16
+ const instant = Date.parse(value);
17
+ if (!Number.isFinite(local) || !Number.isFinite(instant) || new Date(local).toISOString() !== calendar) {
18
+ throw new PolicyError('Invalid approval date');
19
+ }
20
+ return instant;
21
+ }
22
+ // Tags distinguish absent/undefined/null; descriptors prevent executing getters or toJSON.
23
+ function canonicalApprovalValue(value, ancestors = new Set()) {
24
+ if (value === undefined)
25
+ return '["undefined"]';
26
+ if (value === null)
27
+ return '["null"]';
28
+ if (typeof value === 'string' || typeof value === 'boolean')
29
+ return JSON.stringify([typeof value, value]);
30
+ if (typeof value === 'number') {
31
+ if (!Number.isFinite(value))
32
+ throw new PolicyError('Non-finite approval value');
33
+ return JSON.stringify(['number', Object.is(value, -0) ? '-0' : value]);
34
+ }
35
+ if (typeof value !== 'object')
36
+ throw new PolicyError('Unsupported approval value');
37
+ if (ancestors.has(value))
38
+ throw new PolicyError('Cyclic approval value');
39
+ const array = Array.isArray(value);
40
+ const prototype = Object.getPrototypeOf(value);
41
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
42
+ throw new PolicyError('Approval values must be plain objects or arrays');
43
+ }
44
+ ancestors.add(value);
45
+ try {
46
+ const keys = Reflect.ownKeys(value);
47
+ for (const key of keys) {
48
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
49
+ if (typeof key !== 'string' || descriptor === undefined || !('value' in descriptor) || (!descriptor.enumerable && !(array && key === 'length'))) {
50
+ throw new PolicyError('Ambiguous approval property');
51
+ }
52
+ }
53
+ if (array) {
54
+ if (keys.length !== value.length + 1)
55
+ throw new PolicyError('Sparse or extended approval array');
56
+ const entries = [];
57
+ for (let index = 0; index < value.length; index += 1) {
58
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
59
+ if (descriptor === undefined)
60
+ throw new PolicyError('Sparse approval array');
61
+ entries.push(canonicalApprovalValue(descriptor.value, ancestors));
62
+ }
63
+ return `["array",[${entries.join(',')}]]`;
64
+ }
65
+ const entries = Object.keys(value).sort().map((key) => {
66
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
67
+ return `[${JSON.stringify(key)},${canonicalApprovalValue(descriptor?.value, ancestors)}]`;
68
+ });
69
+ return `["object",[${entries.join(',')}]]`;
70
+ }
71
+ finally {
72
+ ancestors.delete(value);
73
+ }
74
+ }
9
75
  export class ApprovalLedger {
10
76
  requests = new Map();
11
77
  store;
@@ -17,6 +83,8 @@ export class ApprovalLedger {
17
83
  throw new PolicyError('Approval justification is required');
18
84
  if (input.impact.trim().length === 0)
19
85
  throw new PolicyError('Approval impact is required');
86
+ if (approvalInstant(input.expiresAt) <= approvalInstant(now))
87
+ throw new PolicyError('Approval expiry must be in the future');
20
88
  const request = {
21
89
  schemaVersion: CONTRACT_VERSION,
22
90
  id: randomUUID(),
@@ -26,6 +94,8 @@ export class ApprovalLedger {
26
94
  expectedDiff: input.expectedDiff,
27
95
  expiresAt: input.expiresAt,
28
96
  correlationId: input.correlationId,
97
+ operationId: input.operationId,
98
+ fingerprint: input.fingerprint,
29
99
  createdAt: now,
30
100
  updatedAt: now,
31
101
  };
@@ -42,7 +112,7 @@ export class ApprovalLedger {
42
112
  const current = this.get(id);
43
113
  if (current.decision !== undefined)
44
114
  throw new PolicyError(`Approval already decided: ${id}`);
45
- if (current.expiresAt <= decision.decidedAt)
115
+ if (approvalInstant(current.expiresAt) <= approvalInstant(decision.decidedAt))
46
116
  throw new PolicyError(`Approval expired: ${id}`);
47
117
  const updated = { ...current, decision: decision.decision, approverId: decision.approverId, updatedAt: decision.decidedAt };
48
118
  this.requests.set(id, updated);
@@ -50,9 +120,10 @@ export class ApprovalLedger {
50
120
  return updated;
51
121
  }
52
122
  expire(now) {
123
+ const instant = approvalInstant(now);
53
124
  const expired = [];
54
- for (const current of this.requests.values()) {
55
- if (current.decision === undefined && current.expiresAt <= now) {
125
+ for (const current of this.list()) {
126
+ if ((current.decision === undefined || current.decision === 'approved') && approvalInstant(current.expiresAt) <= instant) {
56
127
  const updated = { ...current, decision: 'expired', updatedAt: now };
57
128
  this.requests.set(current.id, updated);
58
129
  void this.store?.save(updated);
@@ -61,20 +132,14 @@ export class ApprovalLedger {
61
132
  }
62
133
  return expired;
63
134
  }
64
- /** Most recent approval request recorded for this correlationId, if any. */
65
- findByCorrelationId(correlationId) {
66
- const matches = this.list().filter((request) => request.correlationId === correlationId);
135
+ /** Descriptive/historical records without both binding fields cannot authorize execution. */
136
+ findByOperation(operationId, fingerprint) {
137
+ const matches = this.list().filter((request) => request.operationId === operationId && request.fingerprint === fingerprint && request.decision !== 'expired');
67
138
  return matches.at(-1);
68
139
  }
69
140
  get(id) {
70
- const request = this.requests.get(id);
71
- if (request === undefined && this.store !== undefined) {
72
- const persisted = this.store.get(id);
73
- if (persisted !== undefined) {
74
- this.requests.set(id, persisted);
75
- return persisted;
76
- }
77
- }
141
+ // A persistent store is authoritative, including deletion and decisions by another ledger.
142
+ const request = this.store === undefined ? this.requests.get(id) : this.store.get(id);
78
143
  if (request === undefined)
79
144
  throw new PolicyError(`Approval not found: ${id}`);
80
145
  return request;
@@ -99,25 +164,44 @@ export class PolicyEngine {
99
164
  // approval just because a rule chose to bound it with limits instead of an unconditional ALLOW.
100
165
  const isGranting = decision.effect === 'ALLOW' || decision.effect === 'ALLOW_WITH_LIMITS';
101
166
  if (this.approvalRequiredRisks.includes(request.definition.risk) && isGranting) {
102
- return this.withApproval(request, decision, 'Risk requires explicit approval');
167
+ return this.withApproval(request, decision, 'Risk requires explicit approval', match);
103
168
  }
104
169
  if (decision.effect === 'REQUIRE_APPROVAL')
105
- return this.withApproval(request, decision, decision.reason);
170
+ return this.withApproval(request, decision, decision.reason, match);
106
171
  return decision;
107
172
  }
108
173
  get approvals() {
109
174
  return this.approvalLedger;
110
175
  }
111
- /**
112
- * Resolves approval state for `request` instead of unconditionally demanding a fresh one.
113
- * Keyed by `request.correlationId` (falling back to the agent id) so that resuming/retrying
114
- * the same run recognizes a decision a human already made, rather than re-issuing an
115
- * unresolvable `REQUIRE_APPROVAL` on every attempt — see ADR/finding on approval resume.
116
- */
117
- withApproval(request, decision, reason) {
118
- const correlationId = request.correlationId ?? request.agent.id;
119
- const existing = this.approvalLedger.findByCorrelationId(correlationId);
120
- if (existing !== undefined) {
176
+ withApproval(request, decision, reason, rule) {
177
+ const now = approvalInstant(request.now);
178
+ if (request.approval !== undefined)
179
+ approvalInstant(request.approval.expiresAt);
180
+ const operationId = request.operationId ?? request.correlationId ?? randomUUID();
181
+ const correlationId = request.correlationId ?? operationId;
182
+ const { definition, agent, budget, approval } = request;
183
+ const fingerprint = `v1:${createHash('sha256').update(canonicalApprovalValue({
184
+ operationId,
185
+ agent: { id: agent.id, role: agent.role, autonomy: agent.autonomy },
186
+ capability: { id: definition.id, version: definition.version, risk: definition.risk, permissions: definition.permissions, sideEffects: definition.sideEffects },
187
+ payload: request.input?.payload,
188
+ projectId: request.projectId,
189
+ environment: request.environment,
190
+ files: [...new Set(request.files)].sort(),
191
+ categories: [...new Set(request.categories)].sort(),
192
+ approval: approval === undefined ? undefined : {
193
+ action: approval.action, justification: approval.justification, impact: approval.impact,
194
+ expectedDiff: approval.expectedDiff, expiresAt: approval.expiresAt,
195
+ },
196
+ decision,
197
+ rule,
198
+ approvalRequiredRisks: this.approvalRequiredRisks,
199
+ riskScore: request.riskScore,
200
+ anomalyScore: request.anomalyScore,
201
+ budget: budget === undefined ? undefined : { inputTokens: budget.inputTokens, outputTokens: budget.outputTokens, totalTokens: budget.totalTokens },
202
+ })).digest('hex')}`;
203
+ const existing = this.approvalLedger.findByOperation(operationId, fingerprint);
204
+ if (existing !== undefined && approvalInstant(existing.expiresAt) > now) {
121
205
  if (existing.decision === 'approved') {
122
206
  // `decision.effect` may already be ALLOW/ALLOW_WITH_LIMITS (gated only by the risk-level
123
207
  // approval requirement) — keep it as-is. But when the *rule itself* is REQUIRE_APPROVAL,
@@ -130,12 +214,11 @@ export class PolicyEngine {
130
214
  return { ...decision, effect: 'DENY', reason: `Approval rejected: ${existing.id}`, approvalRequestId: existing.id };
131
215
  if (existing.decision === undefined)
132
216
  return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: existing.id };
133
- // existing.decision === 'expired': falls through to issue a fresh request below.
134
217
  }
135
- if (request.approval === undefined)
218
+ if (approval === undefined)
136
219
  return { ...decision, effect: 'REQUIRE_APPROVAL', reason };
137
- const approval = this.approvalLedger.create({ ...request.approval, correlationId }, request.now);
138
- return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: approval.id };
220
+ const created = this.approvalLedger.create({ ...approval, correlationId, operationId, fingerprint }, request.now);
221
+ return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: created.id };
139
222
  }
140
223
  matches(scope, request) {
141
224
  if (scope.agentIds !== undefined && !scope.agentIds.includes(request.agent.id))
@@ -51,6 +51,9 @@ export interface RuntimeMemory {
51
51
  remember(run: RuntimeRun, result: ExecutionResult): void | Promise<void>;
52
52
  }
53
53
  export interface RuntimeStartRequest {
54
+ readonly runId?: RunId;
55
+ readonly handoffId?: EntityId;
56
+ readonly context?: unknown;
54
57
  readonly objective: string;
55
58
  readonly agent: AgentIdentity;
56
59
  readonly budget: TokenBudget;
@@ -68,9 +71,11 @@ export interface RuntimeDependencies {
68
71
  readonly checkpointStore?: CheckpointStore;
69
72
  readonly persistence?: RuntimePersistence;
70
73
  readonly memory?: RuntimeMemory;
74
+ readonly beforeExecution?: (run: RuntimeRun) => void | Promise<void>;
71
75
  }
72
76
  export declare class RuntimeError extends Error {
73
- constructor(message: string);
77
+ readonly code: string;
78
+ constructor(message: string, code?: string);
74
79
  }
75
80
  export declare class InMemoryCheckpointStore implements CheckpointStore {
76
81
  private readonly checkpoints;
@@ -87,18 +92,27 @@ export declare class RuntimeEngine {
87
92
  private readonly policies;
88
93
  private readonly requestedPauses;
89
94
  private readonly startedAt;
95
+ private readonly starts;
96
+ private readonly executions;
97
+ private readonly recoveries;
98
+ private readonly requestedCancels;
99
+ private readonly executionErrors;
90
100
  constructor(dependencies: RuntimeDependencies, limits?: Partial<RuntimeLimits>);
91
101
  start(request: RuntimeStartRequest): Promise<RuntimeRun>;
102
+ private prepare;
92
103
  execute(runId: RunId): Promise<RuntimeRun>;
104
+ private singleFlight;
105
+ private executeRun;
93
106
  recover(runId: RunId, policy: CapabilityExecutionRequest['policy']): Promise<RuntimeRun>;
107
+ private load;
94
108
  resume(runId: RunId, policy?: CapabilityExecutionRequest['policy']): Promise<RuntimeRun>;
95
109
  pause(runId: RunId): RuntimeRun;
96
110
  cancel(runId: RunId): Promise<RuntimeRun>;
111
+ has(runId: RunId): boolean;
97
112
  get(runId: RunId): RuntimeRun;
98
113
  private validateAndFinish;
99
114
  private stop;
100
115
  private update;
101
- private persist;
102
116
  private saveCheckpoint;
103
117
  private metrics;
104
118
  private auditFields;
@@ -1,4 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
2
3
  import { CONTRACT_VERSION, validateTokenBudget, } from '../../contracts/src/index.js';
3
4
  const DEFAULT_LIMITS = {
4
5
  maxSteps: 20,
@@ -9,9 +10,11 @@ const DEFAULT_LIMITS = {
9
10
  maxParallel: 1,
10
11
  };
11
12
  export class RuntimeError extends Error {
12
- constructor(message) {
13
+ code;
14
+ constructor(message, code = 'RUNTIME_ERROR') {
13
15
  super(message);
14
16
  this.name = 'RuntimeError';
17
+ this.code = code;
15
18
  }
16
19
  }
17
20
  export class InMemoryCheckpointStore {
@@ -33,16 +36,39 @@ export class RuntimeEngine {
33
36
  policies = new Map();
34
37
  requestedPauses = new Set();
35
38
  startedAt = new Map();
39
+ starts = new Map();
40
+ executions = new Map();
41
+ recoveries = new Map();
42
+ requestedCancels = new Set();
43
+ // An interrupted write leaves execution ambiguous; retrying must not replay effects.
44
+ executionErrors = new Map();
36
45
  constructor(dependencies, limits = {}) {
37
46
  this.dependencies = dependencies;
38
47
  this.limits = { ...DEFAULT_LIMITS, ...limits };
39
48
  this.validateLimits(this.limits);
40
49
  }
41
- async start(request) {
42
- validateTokenBudget(request.budget);
43
- if (request.objective.trim().length === 0)
44
- throw new RuntimeError('Runtime objective is required');
45
- const runId = randomUUID();
50
+ start(request) {
51
+ const runId = request.runId ?? randomUUID();
52
+ if (this.has(runId) || this.starts.has(runId) || this.recoveries.has(runId)) {
53
+ return Promise.reject(new RuntimeError(`Run already exists: ${runId}`, 'RUN_ID_COLLISION'));
54
+ }
55
+ const starting = Promise.resolve().then(async () => {
56
+ validateTokenBudget(request.budget);
57
+ if (request.objective.trim().length === 0)
58
+ throw new RuntimeError('Runtime objective is required');
59
+ if (await this.dependencies.persistence?.getRun(runId) !== undefined) {
60
+ throw new RuntimeError(`Run already exists: ${runId}`, 'RUN_ID_COLLISION');
61
+ }
62
+ return this.prepare(runId, request);
63
+ }).catch((error) => {
64
+ if (this.has(runId))
65
+ this.executionErrors.set(runId, error);
66
+ throw error;
67
+ }).finally(() => { this.starts.delete(runId); });
68
+ this.starts.set(runId, starting);
69
+ return starting;
70
+ }
71
+ async prepare(runId, request) {
46
72
  const fields = this.auditFields(request.correlationId ?? runId);
47
73
  const run = {
48
74
  ...fields,
@@ -51,6 +77,7 @@ export class RuntimeEngine {
51
77
  agent: request.agent,
52
78
  sprintId: request.sprintId,
53
79
  taskId: request.taskId,
80
+ handoffId: request.handoffId,
54
81
  policy: { effect: 'ALLOW_WITH_LIMITS', reason: 'Policy is evaluated per capability', policyId: 'runtime-per-capability', limits: { maxTokens: this.limits.maxTokens, maxFiles: this.limits.maxFiles, maxRetries: this.limits.maxRetries } },
55
82
  budget: request.budget,
56
83
  state: 'created',
@@ -66,32 +93,65 @@ export class RuntimeEngine {
66
93
  this.startedAt.set(runId, Date.now());
67
94
  await this.dependencies.persistence?.saveRun(run);
68
95
  await this.dependencies.persistence?.saveCursor(runId, 0, this.startedAt.get(runId));
96
+ await this.update(runId, { state: 'planning' });
97
+ let plan;
69
98
  try {
70
- this.update(runId, { state: 'planning' });
71
- const context = this.dependencies.contextBuilder === undefined ? undefined : await this.dependencies.contextBuilder.build(request.objective);
72
- const plan = [...await this.dependencies.planner.plan(request.objective, context)];
73
- if (plan.length > this.limits.maxSteps)
74
- return this.stop(runId, 'blocked', this.error('MAX_STEPS_EXCEEDED', 'Plan exceeds maximum steps', false));
75
- this.plans.set(runId, plan);
76
- await this.dependencies.persistence?.savePlan(runId, plan);
77
- await this.persist(runId);
78
- await this.saveCheckpoint(runId, 'planning', 0);
79
- return this.get(runId);
99
+ const context = Object.hasOwn(request, 'context') ? request.context : await this.dependencies.contextBuilder?.build(request.objective);
100
+ plan = [...await this.dependencies.planner.plan(request.objective, context)];
101
+ if (this.dependencies.persistence !== undefined) {
102
+ // JSON persistence must not change the input bound to an approval on recovery.
103
+ for (const step of plan) {
104
+ if (step.payload !== undefined && !isDeepStrictEqual(step.payload, JSON.parse(JSON.stringify(step.payload)))) {
105
+ throw new RuntimeError('Persisted step payload must round-trip through JSON without changes');
106
+ }
107
+ }
108
+ }
80
109
  }
81
110
  catch (error) {
82
111
  return this.stop(runId, 'failed', this.error('PLANNING_FAILED', this.message(error), false));
83
112
  }
113
+ if (this.requestedCancels.has(runId))
114
+ return this.stop(runId, 'cancelled');
115
+ if (plan.length > this.limits.maxSteps)
116
+ return this.stop(runId, 'blocked', this.error('MAX_STEPS_EXCEEDED', 'Plan exceeds maximum steps', false));
117
+ await this.dependencies.persistence?.savePlan(runId, plan);
118
+ this.plans.set(runId, plan);
119
+ await this.saveCheckpoint(runId, 'planning', 0);
120
+ return this.get(runId);
121
+ }
122
+ execute(runId) {
123
+ return this.singleFlight(runId, async () => {
124
+ await this.starts.get(runId);
125
+ return this.executeRun(runId);
126
+ });
84
127
  }
85
- async execute(runId) {
128
+ singleFlight(runId, work) {
129
+ const existing = this.executions.get(runId);
130
+ if (existing !== undefined)
131
+ return existing;
132
+ if (this.executionErrors.has(runId))
133
+ return Promise.reject(this.executionErrors.get(runId));
134
+ const executing = Promise.resolve().then(work).catch((error) => {
135
+ if (this.has(runId) && !(error instanceof RuntimeError && error.code === 'RUN_NOT_RESUMABLE'))
136
+ this.executionErrors.set(runId, error);
137
+ throw error;
138
+ }).finally(() => { this.executions.delete(runId); });
139
+ this.executions.set(runId, executing);
140
+ return executing;
141
+ }
142
+ async executeRun(runId) {
86
143
  const current = this.get(runId);
87
144
  if (this.isTerminal(current.state))
88
145
  return current;
89
146
  const plan = this.plans.get(runId);
90
147
  if (plan === undefined)
91
148
  return this.stop(runId, 'failed', this.error('PLAN_NOT_FOUND', 'Runtime plan is missing', false));
92
- this.update(runId, { state: 'running' });
149
+ await this.update(runId, { state: 'running' });
150
+ await this.dependencies.beforeExecution?.(this.get(runId));
93
151
  while (true) {
94
152
  const run = this.get(runId);
153
+ if (this.requestedCancels.has(runId))
154
+ return this.stop(runId, 'cancelled');
95
155
  if (this.requestedPauses.has(runId)) {
96
156
  this.requestedPauses.delete(runId);
97
157
  return this.stop(runId, 'paused');
@@ -118,14 +178,15 @@ export class RuntimeEngine {
118
178
  const projectedTokens = beforeAttempt.budget.usedTokens + estimatedTokens;
119
179
  if (projectedTokens > beforeAttempt.budget.totalTokens || projectedTokens > this.limits.maxTokens)
120
180
  return this.stop(runId, 'blocked', this.error('TOKEN_BUDGET_EXCEEDED', 'Runtime token budget reached', false));
121
- this.update(runId, { steps: beforeAttempt.steps + 1, budget: { ...beforeAttempt.budget, usedTokens: projectedTokens }, metrics: this.metrics(beforeAttempt, { attempts: beforeAttempt.metrics.attempts + 1, inputTokens: beforeAttempt.metrics.inputTokens + estimatedTokens }) });
181
+ await this.update(runId, { steps: beforeAttempt.steps + 1, budget: { ...beforeAttempt.budget, usedTokens: projectedTokens }, metrics: this.metrics(beforeAttempt, { attempts: beforeAttempt.metrics.attempts + 1, inputTokens: beforeAttempt.metrics.inputTokens + estimatedTokens }) });
182
+ if (this.requestedCancels.has(runId))
183
+ return this.stop(runId, 'cancelled');
122
184
  result = await this.dependencies.registry.execute({
123
185
  input: { capabilityId: step.capabilityId, payload: step.payload },
124
186
  agent: run.agent,
125
187
  policy: this.policies.get(runId) ?? (() => { throw new RuntimeError('Runtime policy is missing'); })(),
126
- // Stable across retries/resume of the same run — without it every attempt looks like a
127
- // brand-new approval request and a human's decision can never be recognized on retry.
128
188
  correlationId: runId,
189
+ operationId: `${runId}:${index}`,
129
190
  projectId: step.projectId,
130
191
  environment: step.environment,
131
192
  categories: step.categories,
@@ -135,49 +196,78 @@ export class RuntimeEngine {
135
196
  });
136
197
  this.results.get(runId)?.push(result);
137
198
  await this.dependencies.persistence?.saveResults(runId, this.results.get(runId) ?? []);
199
+ if (this.requestedCancels.has(runId))
200
+ return this.stop(runId, 'cancelled');
138
201
  if (result.status === 'succeeded')
139
202
  break;
140
203
  if (!result.error?.retryable || attempt > this.limits.maxRetries)
141
204
  break;
142
205
  const afterAttempt = this.get(runId);
143
- this.update(runId, { metrics: this.metrics(afterAttempt, { retries: afterAttempt.metrics.retries + 1 }) });
206
+ await this.update(runId, { metrics: this.metrics(afterAttempt, { retries: afterAttempt.metrics.retries + 1 }) });
144
207
  } while (attempt <= this.limits.maxRetries);
145
208
  if (result.status !== 'succeeded') {
146
209
  const state = result.error?.code === 'APPROVAL_REQUIRED' ? 'awaiting_approval' : result.error?.code === 'POLICY_DENIED' ? 'blocked' : 'failed';
147
210
  return this.stop(runId, state, result.error);
148
211
  }
149
- this.update(runId, { evidence: [...this.get(runId).evidence, ...result.evidence], changedFiles: files });
212
+ await this.update(runId, { evidence: [...this.get(runId).evidence, ...result.evidence], changedFiles: files });
150
213
  await this.dependencies.memory?.remember(this.get(runId), result);
151
- this.nextSteps.set(runId, index + 1);
152
214
  await this.dependencies.persistence?.saveCursor(runId, index + 1, this.startedAt.get(runId) ?? Date.now());
215
+ this.nextSteps.set(runId, index + 1);
153
216
  await this.saveCheckpoint(runId, 'running', index + 1);
154
217
  }
155
218
  }
156
- async recover(runId, policy) {
219
+ recover(runId, policy) {
220
+ const starting = this.starts.get(runId);
221
+ if (starting !== undefined)
222
+ return starting;
223
+ if (this.has(runId))
224
+ return Promise.resolve(this.get(runId));
225
+ const existing = this.recoveries.get(runId);
226
+ if (existing !== undefined)
227
+ return existing;
228
+ const recovering = this.load(runId, policy).finally(() => { this.recoveries.delete(runId); });
229
+ this.recoveries.set(runId, recovering);
230
+ return recovering;
231
+ }
232
+ async load(runId, policy) {
157
233
  const persistence = this.dependencies.persistence;
158
234
  if (persistence === undefined)
159
235
  throw new RuntimeError('Runtime persistence is not configured');
160
236
  const run = await persistence.getRun(runId);
237
+ if (run === undefined)
238
+ throw new RuntimeError(`Run not found: ${runId}`, 'RUN_NOT_FOUND');
239
+ if (this.isTerminal(run.state)) {
240
+ if (this.has(runId))
241
+ return this.get(runId);
242
+ this.runs.set(runId, run);
243
+ return run;
244
+ }
161
245
  const plan = await persistence.getPlan(runId);
162
- if (run === undefined || plan === undefined)
163
- throw new RuntimeError(`Persisted runtime is incomplete: ${runId}`);
164
246
  const results = await persistence.getResults(runId);
165
247
  const cursor = await persistence.getCursor(runId);
248
+ if (this.has(runId))
249
+ return this.get(runId);
250
+ if (plan === undefined || cursor === undefined || !Number.isInteger(cursor.nextStep) || cursor.nextStep < 0 || cursor.nextStep > plan.length || !Number.isFinite(cursor.startedAt)) {
251
+ throw new RuntimeError(`Persisted runtime is incomplete: ${runId}`, 'RECOVERY_INCOMPLETE');
252
+ }
166
253
  this.runs.set(runId, run);
167
254
  this.plans.set(runId, plan);
168
255
  this.results.set(runId, [...(results ?? [])]);
169
- this.nextSteps.set(runId, cursor?.nextStep ?? run.steps);
256
+ this.nextSteps.set(runId, cursor.nextStep);
170
257
  this.policies.set(runId, policy);
171
- this.startedAt.set(runId, cursor?.startedAt ?? Date.parse(run.createdAt));
258
+ this.startedAt.set(runId, cursor.startedAt);
172
259
  return run;
173
260
  }
174
- async resume(runId, policy) {
175
- if (!this.runs.has(runId) && policy !== undefined)
176
- await this.recover(runId, policy);
177
- const run = this.get(runId);
178
- if (run.state !== 'paused' && run.state !== 'awaiting_approval')
179
- throw new RuntimeError(`Run is not resumable: ${run.state}`);
180
- return this.execute(runId);
261
+ resume(runId, policy) {
262
+ return this.singleFlight(runId, async () => {
263
+ await this.starts.get(runId);
264
+ if (!this.has(runId) && policy !== undefined)
265
+ await this.recover(runId, policy);
266
+ const run = this.get(runId);
267
+ if (run.state !== 'paused' && run.state !== 'awaiting_approval')
268
+ throw new RuntimeError(`Run is not resumable: ${run.state}`, 'RUN_NOT_RESUMABLE');
269
+ return this.executeRun(runId);
270
+ });
181
271
  }
182
272
  pause(runId) {
183
273
  const run = this.get(runId);
@@ -185,53 +275,78 @@ export class RuntimeEngine {
185
275
  this.requestedPauses.add(runId);
186
276
  return run;
187
277
  }
188
- async cancel(runId) {
189
- const run = this.get(runId);
190
- if (this.isTerminal(run.state))
191
- return run;
278
+ cancel(runId) {
279
+ if (!this.has(runId) && !this.starts.has(runId))
280
+ return Promise.reject(new RuntimeError(`Run not found: ${runId}`, 'RUN_NOT_FOUND'));
281
+ const run = this.runs.get(runId);
282
+ if (run !== undefined && this.isTerminal(run.state))
283
+ return Promise.resolve(run);
192
284
  this.requestedPauses.delete(runId);
193
- return this.stop(runId, 'cancelled');
285
+ this.requestedCancels.add(runId);
286
+ return this.singleFlight(runId, async () => {
287
+ await this.starts.get(runId);
288
+ return this.stop(runId, 'cancelled');
289
+ });
290
+ }
291
+ has(runId) {
292
+ return this.runs.has(runId);
194
293
  }
195
294
  get(runId) {
196
295
  const run = this.runs.get(runId);
197
296
  if (run === undefined)
198
- throw new RuntimeError(`Run not found: ${runId}`);
297
+ throw new RuntimeError(`Run not found: ${runId}`, 'RUN_NOT_FOUND');
199
298
  return run;
200
299
  }
201
300
  async validateAndFinish(runId) {
202
- this.update(runId, { state: 'validating' });
301
+ await this.update(runId, { state: 'validating' });
302
+ if (this.requestedCancels.has(runId))
303
+ return this.stop(runId, 'cancelled');
304
+ let validation;
203
305
  try {
204
306
  const run = this.get(runId);
205
- const validation = await this.dependencies.validator.validate(run, this.results.get(runId) ?? []);
206
- const state = validation.status === 'accepted' ? 'completed' : validation.status === 'blocked' ? 'blocked' : 'failed';
207
- return this.stop(runId, state, undefined, validation);
307
+ const plan = this.plans.get(runId) ?? [];
308
+ const history = this.results.get(runId) ?? [];
309
+ const operationIds = new Set(plan.map((_, index) => `${runId}:${index}`));
310
+ const latest = new Map(history.map((result) => [result.operationId, result]));
311
+ const results = [...operationIds].flatMap((id) => { const result = latest.get(id); return result === undefined ? [] : [result]; });
312
+ const complete = plan.length > 0 && results.length === plan.length && history.every((result) => result.operationId !== undefined && operationIds.has(result.operationId));
313
+ const consistent = results.every((result) => result.status === 'succeeded' && !result.evidence.some((item) => item.status === 'contradicted'));
314
+ validation = !complete || !consistent
315
+ ? { ...this.auditFields(run.correlationId), status: !complete ? 'inconclusive' : 'rejected', checks: [{ name: 'final-step-results', passed: complete && consistent, evidenceIds: results.flatMap((result) => result.evidence.map((item) => item.id)) }], summary: !complete ? 'Final step results cannot be established' : 'Final step results failed or contain contradicted evidence' }
316
+ : await this.dependencies.validator.validate(run, results);
208
317
  }
209
318
  catch (error) {
210
319
  return this.stop(runId, 'failed', this.error('VALIDATION_FAILED', this.message(error), false));
211
320
  }
321
+ const state = validation.status === 'accepted' ? 'completed' : validation.status === 'blocked' ? 'blocked' : 'failed';
322
+ return this.stop(runId, state, undefined, validation);
212
323
  }
213
- stop(runId, state, error, validation) {
324
+ async stop(runId, state, error, validation) {
325
+ if (this.requestedCancels.has(runId)) {
326
+ state = 'cancelled';
327
+ error = undefined;
328
+ validation = undefined;
329
+ }
214
330
  const run = this.get(runId);
215
331
  const durationMs = Date.now() - (this.startedAt.get(runId) ?? Date.now());
216
- this.update(runId, { state, error, validation, metrics: this.metrics(run, { durationMs }) });
217
- void this.saveCheckpoint(runId, state, this.nextSteps.get(runId) ?? 0);
218
- return this.get(runId);
332
+ const stopped = { ...run, state, error, validation, metrics: this.metrics(run, { durationMs }), updatedAt: new Date().toISOString() };
333
+ await this.dependencies.persistence?.saveRun(stopped);
334
+ await this.saveCheckpoint(runId, state, this.nextSteps.get(runId) ?? 0, stopped);
335
+ if (state !== 'cancelled' && this.requestedCancels.has(runId))
336
+ return this.stop(runId, 'cancelled');
337
+ this.runs.set(runId, stopped);
338
+ this.requestedCancels.delete(runId);
339
+ return stopped;
219
340
  }
220
- update(runId, patch) {
221
- this.runs.set(runId, { ...this.get(runId), ...patch, updatedAt: new Date().toISOString() });
222
- void this.persist(runId);
341
+ async update(runId, patch) {
342
+ const updated = { ...this.get(runId), ...patch, updatedAt: new Date().toISOString() };
343
+ await this.dependencies.persistence?.saveRun(updated);
344
+ this.runs.set(runId, updated);
223
345
  }
224
- async persist(runId) {
225
- const persistence = this.dependencies.persistence;
226
- if (persistence === undefined)
227
- return;
228
- await persistence.saveRun(this.get(runId));
229
- }
230
- async saveCheckpoint(runId, state, step) {
346
+ async saveCheckpoint(runId, state, step, run = this.get(runId)) {
231
347
  const store = this.dependencies.checkpointStore;
232
348
  if (store === undefined)
233
349
  return;
234
- const run = this.get(runId);
235
350
  const checkpoint = { ...this.auditFields(run.correlationId), id: randomUUID(), runId, step, state, checksum: createHash('sha256').update(JSON.stringify({ runId, step, state, files: run.changedFiles })).digest('hex'), resumable: state === 'paused' || state === 'awaiting_approval' || state === 'running' };
236
351
  await store.save(checkpoint);
237
352
  }
@@ -4,6 +4,7 @@
4
4
  * forja context:smart global (missão, padrões, ADRs)
5
5
  * forja context:smart --mode domain + visão/design/regras do projeto
6
6
  * forja context:smart --mode task --task pix + nós do projeto que casam com a tarefa (FTS5)
7
+ * forja context:smart --full-context nós inteiros, sem trecho (opt-out da SPEC-057)
7
8
  * forja context:smart <projeto> [keyword] forma posicional antiga (studio) — ainda aceita
8
9
  *
9
10
  * O projeto é inferido de onde o comando roda: no modo embedded é o próprio projeto; no studio,
@@ -15,5 +16,6 @@ export declare function parseArgs(argv: readonly string[]): {
15
16
  mode?: string;
16
17
  task?: string;
17
18
  project?: string;
19
+ full?: boolean;
18
20
  positional: string[];
19
21
  };