oxe-cc 1.16.0 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/.github/copilot-instructions.md +177 -177
  2. package/.github/dependabot.yml +31 -31
  3. package/.github/workflows/ci.yml +159 -138
  4. package/.github/workflows/release.yml +107 -106
  5. package/AGENTS.md +97 -97
  6. package/CHANGELOG.md +1032 -856
  7. package/README.md +673 -600
  8. package/assets/readme-banner.svg +19 -19
  9. package/bin/banner.txt +13 -13
  10. package/bin/lib/oxe-agent-install.cjs +650 -650
  11. package/bin/lib/oxe-artifact-catalog.cjs +376 -376
  12. package/bin/lib/oxe-azure.cjs +1445 -1445
  13. package/bin/lib/oxe-budget.cjs +117 -0
  14. package/bin/lib/oxe-change.cjs +230 -0
  15. package/bin/lib/oxe-command-registry.cjs +31 -31
  16. package/bin/lib/oxe-commit-convention.cjs +85 -0
  17. package/bin/lib/oxe-context-engine.cjs +874 -874
  18. package/bin/lib/oxe-core-command-handlers.cjs +82 -82
  19. package/bin/lib/oxe-criterion-coverage.cjs +58 -0
  20. package/bin/lib/oxe-dashboard.cjs +737 -737
  21. package/bin/lib/oxe-dossier.cjs +281 -0
  22. package/bin/lib/oxe-install-resolve.cjs +134 -106
  23. package/bin/lib/oxe-manifest.cjs +124 -124
  24. package/bin/lib/oxe-npm-version.cjs +66 -66
  25. package/bin/lib/oxe-operational.cjs +4484 -2676
  26. package/bin/lib/oxe-phase-gates.cjs +280 -0
  27. package/bin/lib/oxe-plan-json.cjs +433 -0
  28. package/bin/lib/oxe-plugin-cli.cjs +95 -95
  29. package/bin/lib/oxe-plugins.cjs +432 -432
  30. package/bin/lib/oxe-process.cjs +56 -56
  31. package/bin/lib/oxe-program.cjs +205 -0
  32. package/bin/lib/oxe-project-env.cjs +178 -0
  33. package/bin/lib/oxe-project-health.cjs +2962 -2846
  34. package/bin/lib/oxe-rationality.cjs +73 -49
  35. package/bin/lib/oxe-release.cjs +42 -0
  36. package/bin/lib/oxe-repo-rules.cjs +108 -0
  37. package/bin/lib/oxe-runtime-semantics.cjs +514 -514
  38. package/bin/lib/oxe-scorecard.cjs +164 -0
  39. package/bin/lib/oxe-security.cjs +289 -289
  40. package/bin/lib/oxe-spike.cjs +98 -0
  41. package/bin/lib/oxe-verify-dryrun.cjs +152 -0
  42. package/bin/lib/oxe-workflows.cjs +145 -145
  43. package/bin/oxe-cc.js +6281 -5829
  44. package/docs/INTEGRATION.md +182 -182
  45. package/docs/QUALITY-GATES.md +46 -46
  46. package/docs/RELEASE-READINESS.md +87 -86
  47. package/docs/RUNTIME-SMOKE-MATRIX.md +137 -137
  48. package/docs/oxespace-1.5/BACKLOG.md +273 -0
  49. package/docs/oxevoice/BACKLOG.md +244 -0
  50. package/lib/runtime/compiler/graph-compiler.d.ts +13 -0
  51. package/lib/runtime/compiler/graph-compiler.js +40 -3
  52. package/lib/runtime/delivery/promotion-pipeline.js +6 -2
  53. package/lib/runtime/events/catalog.d.ts +1 -1
  54. package/lib/runtime/events/catalog.js +11 -0
  55. package/lib/runtime/executor/adapters/claude-cli.d.ts +63 -0
  56. package/lib/runtime/executor/adapters/claude-cli.js +250 -0
  57. package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
  58. package/lib/runtime/executor/adapters/http-openai.js +18 -0
  59. package/lib/runtime/executor/adapters/registry.d.ts +13 -0
  60. package/lib/runtime/executor/adapters/registry.js +29 -0
  61. package/lib/runtime/executor/adapters/types.d.ts +21 -0
  62. package/lib/runtime/executor/adapters/types.js +2 -0
  63. package/lib/runtime/executor/built-in-tools.d.ts +8 -0
  64. package/lib/runtime/executor/built-in-tools.js +40 -9
  65. package/lib/runtime/executor/index.d.ts +12 -2
  66. package/lib/runtime/executor/index.js +28 -1
  67. package/lib/runtime/executor/llm-task-executor.d.ts +35 -2
  68. package/lib/runtime/executor/llm-task-executor.js +97 -21
  69. package/lib/runtime/executor/node-context.d.ts +83 -0
  70. package/lib/runtime/executor/node-context.js +116 -0
  71. package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
  72. package/lib/runtime/executor/node-prompt-builder.js +2 -0
  73. package/lib/runtime/executor/shell-argv.d.ts +30 -0
  74. package/lib/runtime/executor/shell-argv.js +57 -0
  75. package/lib/runtime/executor/stream-completion.d.ts +11 -0
  76. package/lib/runtime/executor/stream-completion.js +10 -1
  77. package/lib/runtime/index.d.ts +5 -2
  78. package/lib/runtime/index.js +8 -1
  79. package/lib/runtime/program/index.d.ts +1 -0
  80. package/lib/runtime/program/index.js +17 -0
  81. package/lib/runtime/program/program-model.d.ts +74 -0
  82. package/lib/runtime/program/program-model.js +195 -0
  83. package/lib/runtime/projection/projection-engine.d.ts +10 -1
  84. package/lib/runtime/projection/projection-engine.js +25 -1
  85. package/lib/runtime/reducers/run-state-reducer.js +5 -0
  86. package/lib/runtime/scheduler/run-journal.d.ts +19 -1
  87. package/lib/runtime/scheduler/run-journal.js +40 -1
  88. package/lib/runtime/scheduler/scheduler.d.ts +30 -0
  89. package/lib/runtime/scheduler/scheduler.js +195 -19
  90. package/lib/runtime/verification/contract-exports.d.ts +24 -0
  91. package/lib/runtime/verification/contract-exports.js +201 -0
  92. package/lib/runtime/verification/index.d.ts +1 -0
  93. package/lib/runtime/verification/index.js +1 -0
  94. package/lib/runtime/verification/test-report-parsers.d.ts +37 -0
  95. package/lib/runtime/verification/test-report-parsers.js +180 -0
  96. package/lib/runtime/verification/verification-compiler.d.ts +67 -1
  97. package/lib/runtime/verification/verification-compiler.js +302 -25
  98. package/lib/runtime/verification/verification-manifest.d.ts +10 -0
  99. package/lib/runtime/verification/verification-manifest.js +18 -3
  100. package/lib/runtime/workspace/strategies/git-worktree.d.ts +9 -0
  101. package/lib/runtime/workspace/strategies/git-worktree.js +81 -0
  102. package/lib/sdk/README.md +61 -61
  103. package/lib/sdk/index.cjs +815 -810
  104. package/lib/sdk/index.d.ts +982 -982
  105. package/lib/sdk/index.types.ts +933 -933
  106. package/oxe/schemas/plan-agents.schema.json +122 -122
  107. package/oxe/schemas/plan.schema.json +85 -0
  108. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  109. package/oxe/templates/CAPABILITIES.template.md +7 -7
  110. package/oxe/templates/CAPABILITY.template.md +45 -45
  111. package/oxe/templates/CHECKPOINT.template.md +37 -37
  112. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  113. package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
  114. package/oxe/templates/CONFIG.md +105 -105
  115. package/oxe/templates/DISCUSS.template.md +44 -44
  116. package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
  117. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  118. package/oxe/templates/FIXTURE-PACK.template.json +23 -23
  119. package/oxe/templates/FIXTURE-PACK.template.md +11 -11
  120. package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
  121. package/oxe/templates/HYPOTHESES.template.md +33 -33
  122. package/oxe/templates/IMPLEMENTATION-PACK.template.json +42 -42
  123. package/oxe/templates/IMPLEMENTATION-PACK.template.md +16 -16
  124. package/oxe/templates/INVESTIGATION.template.md +38 -38
  125. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  126. package/oxe/templates/LESSONS.template.md +43 -43
  127. package/oxe/templates/MEMORY.template.md +49 -49
  128. package/oxe/templates/MILESTONES.template.md +17 -17
  129. package/oxe/templates/NOTES.template.md +16 -16
  130. package/oxe/templates/OBSERVATIONS.template.md +18 -18
  131. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  132. package/oxe/templates/PLAN.template.md +66 -66
  133. package/oxe/templates/PLUGINS.md +108 -108
  134. package/oxe/templates/REFERENCE-ANCHORS.template.md +9 -9
  135. package/oxe/templates/RESEARCH.template.md +57 -57
  136. package/oxe/templates/RESUME.template.md +49 -49
  137. package/oxe/templates/ROADMAP.template.md +44 -44
  138. package/oxe/templates/SECURITY.template.md +72 -72
  139. package/oxe/templates/SESSION.template.md +34 -34
  140. package/oxe/templates/SKILL.template.md +26 -26
  141. package/oxe/templates/SPEC.template.md +54 -54
  142. package/oxe/templates/STATE-REFERENCE.md +125 -125
  143. package/oxe/templates/STATE.md +30 -30
  144. package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
  145. package/oxe/templates/config.template.json +38 -38
  146. package/oxe/templates/plan-agent-messages-README.template.md +9 -9
  147. package/oxe/templates/plan-agents.template.json +30 -30
  148. package/oxe/templates/quick-agents.template.json +24 -24
  149. package/oxe/workflows/ask.md +96 -96
  150. package/oxe/workflows/capabilities.md +25 -25
  151. package/oxe/workflows/checkpoint.md +37 -37
  152. package/oxe/workflows/compact.md +44 -44
  153. package/oxe/workflows/dashboard.md +33 -33
  154. package/oxe/workflows/debug.md +34 -34
  155. package/oxe/workflows/discuss.md +86 -86
  156. package/oxe/workflows/execute.md +255 -255
  157. package/oxe/workflows/forensics.md +48 -48
  158. package/oxe/workflows/help.md +355 -355
  159. package/oxe/workflows/loop.md +67 -67
  160. package/oxe/workflows/milestone.md +95 -95
  161. package/oxe/workflows/next.md +45 -45
  162. package/oxe/workflows/obs.md +167 -167
  163. package/oxe/workflows/oxe.md +150 -149
  164. package/oxe/workflows/plan-agent.md +143 -143
  165. package/oxe/workflows/plan.md +525 -523
  166. package/oxe/workflows/project.md +55 -55
  167. package/oxe/workflows/quick.md +185 -185
  168. package/oxe/workflows/references/adaptive-discovery.md +27 -27
  169. package/oxe/workflows/references/flow-robustness-contract.md +80 -80
  170. package/oxe/workflows/references/legacy-brownfield.md +136 -136
  171. package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
  172. package/oxe/workflows/references/plan-json-acceptance-program.md +143 -0
  173. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  174. package/oxe/workflows/references/reasoning-execution.md +29 -29
  175. package/oxe/workflows/references/reasoning-planning.md +32 -32
  176. package/oxe/workflows/references/reasoning-review.md +29 -29
  177. package/oxe/workflows/references/reasoning-status.md +24 -24
  178. package/oxe/workflows/references/robustness-elevation.md +295 -295
  179. package/oxe/workflows/references/session-path-resolution.md +71 -71
  180. package/oxe/workflows/research.md +66 -66
  181. package/oxe/workflows/retro.md +117 -117
  182. package/oxe/workflows/review-pr.md +53 -53
  183. package/oxe/workflows/route.md +32 -32
  184. package/oxe/workflows/security.md +67 -67
  185. package/oxe/workflows/session.md +213 -213
  186. package/oxe/workflows/ship.md +142 -142
  187. package/oxe/workflows/skill.md +44 -44
  188. package/oxe/workflows/spec.md +569 -566
  189. package/oxe/workflows/ui-review.md +32 -32
  190. package/oxe/workflows/ui-spec.md +25 -25
  191. package/oxe/workflows/update.md +35 -35
  192. package/oxe/workflows/validate-gaps.md +45 -45
  193. package/oxe/workflows/verify-audit.md +73 -73
  194. package/oxe/workflows/verify.md +247 -244
  195. package/oxe/workflows/workflow-authoring.md +34 -34
  196. package/oxe/workflows/workstream.md +97 -97
  197. package/package.json +132 -129
  198. package/packages/runtime/package.json +18 -18
  199. package/packages/runtime/src/audit/audit-trail.ts +243 -243
  200. package/packages/runtime/src/audit/index.ts +2 -2
  201. package/packages/runtime/src/audit/policy-pack.ts +62 -62
  202. package/packages/runtime/src/compiler/graph-compiler.ts +336 -285
  203. package/packages/runtime/src/compiler/index.ts +1 -1
  204. package/packages/runtime/src/context/context-pack-builder.ts +339 -339
  205. package/packages/runtime/src/context/context-pack-store.ts +197 -197
  206. package/packages/runtime/src/context/context-profiles.ts +60 -60
  207. package/packages/runtime/src/context/index.ts +3 -3
  208. package/packages/runtime/src/decision/decision-engine.ts +174 -174
  209. package/packages/runtime/src/decision/decision-memo.ts +211 -211
  210. package/packages/runtime/src/decision/index.ts +2 -2
  211. package/packages/runtime/src/delivery/branch-manager.ts +91 -91
  212. package/packages/runtime/src/delivery/ci-checks.ts +285 -285
  213. package/packages/runtime/src/delivery/delivery-records.ts +75 -75
  214. package/packages/runtime/src/delivery/index.ts +5 -5
  215. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  216. package/packages/runtime/src/delivery/promotion-pipeline.ts +342 -334
  217. package/packages/runtime/src/events/bus.ts +92 -92
  218. package/packages/runtime/src/events/catalog.ts +45 -34
  219. package/packages/runtime/src/events/envelope.ts +14 -14
  220. package/packages/runtime/src/events/index.ts +3 -3
  221. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  222. package/packages/runtime/src/evidence/index.ts +1 -1
  223. package/packages/runtime/src/executor/adapters/claude-cli.ts +285 -0
  224. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
  225. package/packages/runtime/src/executor/adapters/registry.ts +33 -0
  226. package/packages/runtime/src/executor/adapters/types.ts +24 -0
  227. package/packages/runtime/src/executor/built-in-tools.ts +36 -8
  228. package/packages/runtime/src/executor/index.ts +12 -2
  229. package/packages/runtime/src/executor/llm-task-executor.ts +125 -25
  230. package/packages/runtime/src/executor/node-context.ts +210 -0
  231. package/packages/runtime/src/executor/node-prompt-builder.ts +5 -0
  232. package/packages/runtime/src/executor/shell-argv.ts +66 -0
  233. package/packages/runtime/src/executor/stream-completion.ts +16 -1
  234. package/packages/runtime/src/gate/gate-manager.ts +289 -289
  235. package/packages/runtime/src/gate/index.ts +1 -1
  236. package/packages/runtime/src/index.ts +54 -44
  237. package/packages/runtime/src/models/attempt.ts +19 -19
  238. package/packages/runtime/src/models/evidence.ts +21 -21
  239. package/packages/runtime/src/models/gate-decision.ts +25 -25
  240. package/packages/runtime/src/models/index.ts +8 -8
  241. package/packages/runtime/src/models/run.ts +24 -24
  242. package/packages/runtime/src/models/session.ts +11 -11
  243. package/packages/runtime/src/models/verification-result.ts +10 -10
  244. package/packages/runtime/src/models/work-item.ts +25 -25
  245. package/packages/runtime/src/models/workspace.ts +31 -31
  246. package/packages/runtime/src/plugins/capability-adapter.ts +313 -313
  247. package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
  248. package/packages/runtime/src/plugins/index.ts +5 -5
  249. package/packages/runtime/src/plugins/plugin-abi.ts +106 -106
  250. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
  251. package/packages/runtime/src/plugins/plugin-registry.ts +241 -241
  252. package/packages/runtime/src/policy/index.ts +1 -1
  253. package/packages/runtime/src/policy/policy-engine.ts +330 -330
  254. package/packages/runtime/src/program/index.ts +1 -0
  255. package/packages/runtime/src/program/program-model.ts +233 -0
  256. package/packages/runtime/src/projection/index.ts +1 -1
  257. package/packages/runtime/src/projection/projection-engine.ts +361 -328
  258. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  259. package/packages/runtime/src/reducers/index.ts +2 -2
  260. package/packages/runtime/src/reducers/run-state-reducer.ts +329 -326
  261. package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
  262. package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
  263. package/packages/runtime/src/scheduler/index.ts +4 -4
  264. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +1017 -1017
  265. package/packages/runtime/src/scheduler/run-journal.ts +105 -62
  266. package/packages/runtime/src/scheduler/scheduler.ts +1144 -938
  267. package/packages/runtime/src/verification/contract-exports.ts +203 -0
  268. package/packages/runtime/src/verification/index.ts +3 -2
  269. package/packages/runtime/src/verification/test-report-parsers.ts +198 -0
  270. package/packages/runtime/src/verification/verification-compiler.ts +766 -438
  271. package/packages/runtime/src/verification/verification-manifest.ts +281 -256
  272. package/packages/runtime/src/workspace/index.ts +5 -5
  273. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +126 -126
  274. package/packages/runtime/src/workspace/strategies/git-worktree.ts +150 -87
  275. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
  276. package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
  277. package/packages/runtime/tsconfig.json +23 -23
  278. package/vscode-extension/.vscodeignore +9 -9
  279. package/vscode-extension/package.json +193 -193
  280. package/vscode-extension/src/extension.js +320 -320
  281. package/vscode-extension/src/shared/contextLoader.js +137 -137
  282. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  283. package/vscode-extension/src/shared/stateReader.js +101 -101
  284. package/docs/oxe-artifact-map.html +0 -1172
@@ -1,438 +1,766 @@
1
- import crypto from 'crypto';
2
- import { spawnSync } from 'child_process';
3
- import type { EvidenceType } from '../models/evidence';
4
- import type { VerificationStatus } from '../models/verification-result';
5
- import type { VerificationResult } from '../models/verification-result';
6
- import type { EvidenceStore } from '../evidence/evidence-store';
7
- import type { PluginRegistry } from '../plugins/plugin-registry';
8
- import {
9
- buildManifest,
10
- buildRiskLedger,
11
- summarizeEvidenceCoverage,
12
- saveManifest,
13
- saveRiskLedger,
14
- saveEvidenceCoverage,
15
- type EvidenceCoverageSummary,
16
- type ResidualRiskLedger,
17
- type VerificationManifest,
18
- } from './verification-manifest';
19
-
20
- export type CheckType =
21
- | 'unit'
22
- | 'integration'
23
- | 'contract'
24
- | 'smoke'
25
- | 'policy'
26
- | 'security'
27
- | 'ux_snapshot'
28
- | 'performance_baseline'
29
- | 'custom';
30
-
31
- export interface AcceptanceCheck {
32
- id: string;
33
- type: CheckType;
34
- command: string | null;
35
- evidence_type_expected: EvidenceType;
36
- acceptance_ref: string | null;
37
- description: string;
38
- }
39
-
40
- export interface AcceptanceCheckSuite {
41
- checks: AcceptanceCheck[];
42
- compiled_at: string;
43
- spec_hash: string;
44
- plan_hash: string;
45
- }
46
-
47
- export interface CheckResult {
48
- check_id: string;
49
- acceptance_ref: string | null;
50
- status: VerificationStatus;
51
- stdout: string;
52
- stderr: string;
53
- exit_code: number | null;
54
- duration_ms: number;
55
- error: string | null;
56
- evidence_refs?: string[];
57
- }
58
-
59
- export interface ExecutedVerificationSuite {
60
- results: CheckResult[];
61
- verification_results: VerificationResult[];
62
- evidence_refs: Map<string, string[]>;
63
- manifest: VerificationManifest;
64
- risk_ledger: ResidualRiskLedger;
65
- evidence_coverage: EvidenceCoverageSummary;
66
- }
67
-
68
- export interface VerifyRunResult {
69
- status: 'passed' | 'failed' | 'partial';
70
- suite: AcceptanceCheckSuite;
71
- executed: ExecutedVerificationSuite | null;
72
- gaps: string[];
73
- verification_results: VerificationResult[];
74
- check_results: CheckResult[];
75
- manifest: VerificationManifest | null;
76
- risk_ledger: ResidualRiskLedger | null;
77
- evidence_coverage: EvidenceCoverageSummary | null;
78
- }
79
-
80
- // Mirror of ParsedSpec/ParsedPlan (same as in graph-compiler to avoid circular deps)
81
- interface Criterion {
82
- id: string;
83
- criterion: string;
84
- howToVerify: string;
85
- }
86
-
87
- interface ParsedSpecLike {
88
- objective: string | null;
89
- criteria: Criterion[];
90
- }
91
-
92
- interface ParsedTaskLike {
93
- id: string;
94
- verifyCommand: string | null;
95
- aceite: string[];
96
- }
97
-
98
- interface ParsedPlanLike {
99
- tasks: ParsedTaskLike[];
100
- }
101
-
102
- function inferCheckType(howToVerify: string): CheckType {
103
- const v = howToVerify.toLowerCase();
104
- if (v.includes('npm test') || v.includes('jest') || v.includes('vitest') || v.includes('node --test')) return 'unit';
105
- if (v.includes('postman') || v.includes('newman') || v.includes('integration')) return 'integration';
106
- if (v.includes('smoke') || v.includes('curl')) return 'smoke';
107
- if (v.includes('eslint') || v.includes('lint') || v.includes('oxe-policy')) return 'policy';
108
- if (v.includes('security') || v.includes('audit') || v.includes('trivy')) return 'security';
109
- return 'custom';
110
- }
111
-
112
- function inferEvidenceType(checkType: CheckType): EvidenceType {
113
- switch (checkType) {
114
- case 'unit': return 'junit_xml';
115
- case 'integration': return 'api_output';
116
- case 'security': return 'security_report';
117
- case 'policy': return 'log';
118
- default: return 'stdout';
119
- }
120
- }
121
-
122
- export function compile(
123
- spec: ParsedSpecLike,
124
- plan: ParsedPlanLike
125
- ): AcceptanceCheckSuite {
126
- const checks: AcceptanceCheck[] = [];
127
- const seenRefs = new Set<string>();
128
-
129
- // Generate checks from spec criteria
130
- for (const criterion of spec.criteria) {
131
- // Find the verify command from the task that references this criterion
132
- const task = plan.tasks.find((t) => t.aceite.includes(criterion.id));
133
- const command = task?.verifyCommand ?? null;
134
- const type = inferCheckType(criterion.howToVerify);
135
-
136
- checks.push({
137
- id: `check-${criterion.id.toLowerCase()}`,
138
- type,
139
- command: command ?? (criterion.howToVerify.startsWith('#') ? null : criterion.howToVerify),
140
- evidence_type_expected: inferEvidenceType(type),
141
- acceptance_ref: criterion.id,
142
- description: criterion.criterion,
143
- });
144
- seenRefs.add(criterion.id);
145
- }
146
-
147
- // Add checks for task verify commands not already covered
148
- for (const task of plan.tasks) {
149
- if (!task.verifyCommand) continue;
150
- const uncovered = task.aceite.filter((ref) => !seenRefs.has(ref));
151
- if (uncovered.length === 0 && checks.some((c) => c.command === task.verifyCommand)) continue;
152
-
153
- checks.push({
154
- id: `check-task-${task.id.toLowerCase()}`,
155
- type: inferCheckType(task.verifyCommand),
156
- command: task.verifyCommand,
157
- evidence_type_expected: 'stdout',
158
- acceptance_ref: uncovered[0] ?? null,
159
- description: `Verify command for task ${task.id}`,
160
- });
161
- }
162
-
163
- return {
164
- checks,
165
- compiled_at: new Date().toISOString(),
166
- spec_hash: hashObject(spec),
167
- plan_hash: hashObject(plan),
168
- };
169
- }
170
-
171
- export async function runCheck(
172
- check: AcceptanceCheck,
173
- cwd: string,
174
- timeoutMs = 60_000
175
- ): Promise<CheckResult> {
176
- if (!check.command) {
177
- return {
178
- check_id: check.id,
179
- acceptance_ref: check.acceptance_ref,
180
- status: 'skip',
181
- stdout: '',
182
- stderr: '',
183
- exit_code: null,
184
- duration_ms: 0,
185
- error: null,
186
- };
187
- }
188
-
189
- const start = Date.now();
190
- try {
191
- // Use shell so the full command string is interpreted (handles quotes, &&, node -e "...")
192
- const isWin = process.platform === 'win32';
193
- const shell = isWin ? 'cmd' : 'sh';
194
- const shellArgs = isWin ? ['/c', check.command] : ['-c', check.command];
195
-
196
- const result = spawnSync(shell, shellArgs, {
197
- cwd,
198
- encoding: 'utf8',
199
- timeout: timeoutMs,
200
- maxBuffer: 2 * 1024 * 1024,
201
- // On Windows, prevent Node from re-quoting the args (preserves double-quotes inside node -e "...")
202
- windowsVerbatimArguments: isWin,
203
- });
204
-
205
- const duration_ms = Date.now() - start;
206
- const status: VerificationStatus = result.status === 0 ? 'pass' : 'fail';
207
-
208
- return {
209
- check_id: check.id,
210
- acceptance_ref: check.acceptance_ref,
211
- status,
212
- stdout: result.stdout ?? '',
213
- stderr: result.stderr ?? '',
214
- exit_code: result.status ?? null,
215
- duration_ms,
216
- error: result.error ? String(result.error) : null,
217
- };
218
- } catch (err) {
219
- return {
220
- check_id: check.id,
221
- acceptance_ref: check.acceptance_ref,
222
- status: 'error',
223
- stdout: '',
224
- stderr: '',
225
- exit_code: null,
226
- duration_ms: Date.now() - start,
227
- error: String(err),
228
- };
229
- }
230
- }
231
-
232
- export async function runSuite(
233
- suite: AcceptanceCheckSuite,
234
- cwd: string,
235
- timeoutMs = 60_000
236
- ): Promise<CheckResult[]> {
237
- const results: CheckResult[] = [];
238
- for (const check of suite.checks) {
239
- results.push(await runCheck(check, cwd, timeoutMs));
240
- }
241
- return results;
242
- }
243
-
244
- export async function executeSuite(
245
- suite: AcceptanceCheckSuite,
246
- cwd: string,
247
- options: {
248
- timeoutMs?: number;
249
- runId: string;
250
- workItemId: string;
251
- attemptNumber?: number;
252
- evidenceStore?: EvidenceStore;
253
- pluginRegistry?: PluginRegistry;
254
- }
255
- ): Promise<ExecutedVerificationSuite> {
256
- const results: CheckResult[] = [];
257
- const verificationResults: VerificationResult[] = [];
258
- const evidenceRefs = new Map<string, string[]>();
259
- const timeoutMs = options.timeoutMs ?? 60_000;
260
- const attemptNumber = options.attemptNumber ?? 1;
261
-
262
- for (const check of suite.checks) {
263
- const provider = options.pluginRegistry?.verifierProviderFor(check.type);
264
- let result: CheckResult;
265
- let verificationResult: VerificationResult;
266
-
267
- if (provider) {
268
- const providerResult = await provider.execute({
269
- check_id: check.id,
270
- check_type: check.type,
271
- command: check.command,
272
- work_item_id: options.workItemId,
273
- workspace_root: cwd,
274
- evidence_dir: '',
275
- });
276
- result = {
277
- check_id: check.id,
278
- acceptance_ref: check.acceptance_ref,
279
- status: providerResult.status,
280
- stdout: providerResult.summary ?? '',
281
- stderr: '',
282
- exit_code: providerResult.status === 'pass' ? 0 : 1,
283
- duration_ms: 0,
284
- error: providerResult.status === 'error' ? providerResult.summary ?? 'provider error' : null,
285
- evidence_refs: providerResult.evidence_refs,
286
- };
287
- verificationResult = providerResult;
288
- } else {
289
- result = await runCheck(check, cwd, timeoutMs);
290
- const collectedEvidence = options.evidenceStore
291
- ? await collectCheckEvidence(options.evidenceStore, check, result, {
292
- run_id: options.runId,
293
- work_item_id: options.workItemId,
294
- attempt_number: attemptNumber,
295
- })
296
- : [];
297
- result.evidence_refs = collectedEvidence;
298
- verificationResult = {
299
- verification_id: `vr-${crypto.randomBytes(4).toString('hex')}`,
300
- work_item_id: options.workItemId,
301
- check_id: check.id,
302
- status: result.status,
303
- evidence_refs: collectedEvidence,
304
- summary: result.error || result.stderr || result.stdout || null,
305
- };
306
- }
307
-
308
- if (result.evidence_refs && result.evidence_refs.length > 0) {
309
- evidenceRefs.set(check.id, result.evidence_refs);
310
- }
311
- results.push(result);
312
- verificationResults.push(verificationResult);
313
- }
314
-
315
- const manifest = buildManifest(options.runId, results, {
316
- workItemId: options.workItemId,
317
- granularity: 'work_item',
318
- evidenceRefs,
319
- });
320
- const riskLedger = buildRiskLedger(options.runId, manifest);
321
- const evidenceCoverage = summarizeEvidenceCoverage(manifest);
322
- return {
323
- results,
324
- verification_results: verificationResults,
325
- evidence_refs: evidenceRefs,
326
- manifest,
327
- risk_ledger: riskLedger,
328
- evidence_coverage: evidenceCoverage,
329
- };
330
- }
331
-
332
- export function summarizeSuite(results: CheckResult[]): {
333
- total: number;
334
- pass: number;
335
- fail: number;
336
- skip: number;
337
- error: number;
338
- allPassed: boolean;
339
- } {
340
- const counts = { total: results.length, pass: 0, fail: 0, skip: 0, error: 0 };
341
- for (const r of results) counts[r.status]++;
342
- return { ...counts, allPassed: counts.fail === 0 && counts.error === 0 };
343
- }
344
-
345
- export async function verifyRun(input: {
346
- projectRoot: string;
347
- runId: string;
348
- workItemId: string;
349
- cwd: string;
350
- suite: AcceptanceCheckSuite;
351
- pluginRegistry?: PluginRegistry;
352
- evidenceStore?: EvidenceStore;
353
- attemptNumber?: number;
354
- timeoutMs?: number;
355
- }): Promise<VerifyRunResult> {
356
- const gaps: string[] = [];
357
- if (!input.suite || !Array.isArray(input.suite.checks) || input.suite.checks.length === 0) {
358
- gaps.push('Nenhum check executável foi compilado a partir de SPEC/PLAN.');
359
- return {
360
- status: 'partial',
361
- suite: input.suite,
362
- executed: null,
363
- gaps,
364
- verification_results: [],
365
- check_results: [],
366
- manifest: null,
367
- risk_ledger: null,
368
- evidence_coverage: null,
369
- };
370
- }
371
-
372
- const executed = await executeSuite(input.suite, input.cwd, {
373
- timeoutMs: input.timeoutMs,
374
- runId: input.runId,
375
- workItemId: input.workItemId,
376
- attemptNumber: input.attemptNumber,
377
- evidenceStore: input.evidenceStore,
378
- pluginRegistry: input.pluginRegistry,
379
- });
380
- saveManifest(input.projectRoot, input.runId, executed.manifest);
381
- saveRiskLedger(input.projectRoot, input.runId, executed.risk_ledger);
382
- saveEvidenceCoverage(input.projectRoot, input.runId, executed.evidence_coverage);
383
- const summary = summarizeSuite(executed.results);
384
- return {
385
- status: summary.total === 0 ? 'partial' : summary.allPassed ? 'passed' : 'failed',
386
- suite: input.suite,
387
- executed,
388
- gaps,
389
- verification_results: executed.verification_results,
390
- check_results: executed.results,
391
- manifest: executed.manifest,
392
- risk_ledger: executed.risk_ledger,
393
- evidence_coverage: executed.evidence_coverage,
394
- };
395
- }
396
-
397
- function hashObject(obj: unknown): string {
398
- return crypto
399
- .createHash('sha256')
400
- .update(JSON.stringify(obj))
401
- .digest('hex')
402
- .slice(0, 12);
403
- }
404
-
405
- async function collectCheckEvidence(
406
- store: EvidenceStore,
407
- check: AcceptanceCheck,
408
- result: CheckResult,
409
- options: { run_id: string; work_item_id: string; attempt_number: number }
410
- ): Promise<string[]> {
411
- const refs: string[] = [];
412
- if (result.stdout) {
413
- const evidence = await store.collect('stdout', result.stdout, options);
414
- refs.push(evidence.evidence_id);
415
- }
416
- if (result.stderr) {
417
- const evidence = await store.collect('stderr', result.stderr, options);
418
- refs.push(evidence.evidence_id);
419
- }
420
- const summaryEvidence = await store.collect(
421
- check.evidence_type_expected,
422
- JSON.stringify(
423
- {
424
- check_id: check.id,
425
- type: check.type,
426
- command: check.command,
427
- status: result.status,
428
- exit_code: result.exit_code,
429
- duration_ms: result.duration_ms,
430
- },
431
- null,
432
- 2
433
- ),
434
- options
435
- );
436
- refs.push(summaryEvidence.evidence_id);
437
- return refs;
438
- }
1
+ import crypto from 'crypto';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { spawnSync } from 'child_process';
5
+ import { parseTestReport, extractTestFileArgs, missingProofs } from './test-report-parsers';
6
+ import { shellInvocation, childProcessEnv } from '../executor/shell-argv';
7
+ import { checkExpectedExports } from './contract-exports';
8
+ import type { ExpectedExport } from './contract-exports';
9
+ import type { EvidenceType } from '../models/evidence';
10
+ import type { VerificationStatus } from '../models/verification-result';
11
+ import type { VerificationResult } from '../models/verification-result';
12
+ import type { EvidenceStore } from '../evidence/evidence-store';
13
+ import type { PluginRegistry } from '../plugins/plugin-registry';
14
+ import {
15
+ buildManifest,
16
+ buildRiskLedger,
17
+ summarizeEvidenceCoverage,
18
+ saveManifest,
19
+ saveRiskLedger,
20
+ saveEvidenceCoverage,
21
+ type EvidenceCoverageSummary,
22
+ type ResidualRiskLedger,
23
+ type VerificationManifest,
24
+ } from './verification-manifest';
25
+
26
+ export type CheckType =
27
+ | 'unit'
28
+ | 'integration'
29
+ | 'contract'
30
+ | 'smoke'
31
+ | 'policy'
32
+ | 'security'
33
+ | 'ux_snapshot'
34
+ | 'performance_baseline'
35
+ | 'custom'
36
+ /** Criterion without an executable verification — never counts as proof. */
37
+ | 'manual';
38
+
39
+ export interface AcceptanceCheck {
40
+ id: string;
41
+ type: CheckType;
42
+ command: string | null;
43
+ evidence_type_expected: EvidenceType;
44
+ acceptance_ref: string | null;
45
+ description: string;
46
+ /** Paths that must exist in the workspace (IMPLEMENTATION-PACK `exact_paths`); checked before any command. */
47
+ files_exist?: string[];
48
+ /** Symbols the pack contracts per file (`symbols`); JS/TS files are scanned statically. */
49
+ exports_expected?: ExpectedExport[];
50
+ /** Set on checks carried over from a closed program phase (regression). */
51
+ regression_phase?: string | null;
52
+ /**
53
+ * Plan-owned acceptance test files frozen by hash at compile time (1.19). Checked before the
54
+ * command: a missing or modified file fails the check — the executor cannot rewrite its proof.
55
+ */
56
+ frozen_files?: FrozenFile[];
57
+ /**
58
+ * Executed proof (1.20): names of tests (or `file › name`) that must appear as PASSED in the runner output.
59
+ * A green exit code without these named tests is `proof_not_executed`.
60
+ */
61
+ proves?: string[];
62
+ /** Own timeout (ms) for slow project gates such as a full typecheck (1.21); otherwise the suite timeout. */
63
+ timeout_ms?: number;
64
+ /** Id of the project phase gate this check runs (1.21, OXB-020). */
65
+ phase_gate?: string;
66
+ }
67
+
68
+ export interface FrozenFile {
69
+ path: string;
70
+ /** sha256 hex at freeze time; null when the file did not exist when the run was compiled. */
71
+ sha256: string | null;
72
+ }
73
+
74
+ export interface AcceptanceTestLike {
75
+ /** Own id for cross-cutting proofs (e.g. a constraint CR): check id `check-accept-<id>`. Defaults to the criterion. */
76
+ id?: string | null;
77
+ criterion: string | null;
78
+ command: string;
79
+ files: FrozenFile[];
80
+ proves?: string[];
81
+ }
82
+
83
+ export interface AcceptanceCheckSuite {
84
+ checks: AcceptanceCheck[];
85
+ compiled_at: string;
86
+ spec_hash: string;
87
+ plan_hash: string;
88
+ }
89
+
90
+ export interface CheckResult {
91
+ check_id: string;
92
+ acceptance_ref: string | null;
93
+ status: VerificationStatus;
94
+ stdout: string;
95
+ stderr: string;
96
+ exit_code: number | null;
97
+ duration_ms: number;
98
+ error: string | null;
99
+ evidence_refs?: string[];
100
+ /** Why a check was skipped (`needs_structured_check` = criterion has no executable verification). */
101
+ skip_reason?: string | null;
102
+ /** Test cases the runner reported; null when the output has no recognizable test report. */
103
+ tests_executed?: number | null;
104
+ /** Evidence id of the structured summary record (kept out of `evidence_refs` so coverage counts real output only). */
105
+ summary_evidence_ref?: string | null;
106
+ }
107
+
108
+ export interface ExecutedVerificationSuite {
109
+ results: CheckResult[];
110
+ verification_results: VerificationResult[];
111
+ evidence_refs: Map<string, string[]>;
112
+ manifest: VerificationManifest;
113
+ risk_ledger: ResidualRiskLedger;
114
+ evidence_coverage: EvidenceCoverageSummary;
115
+ }
116
+
117
+ export interface VerifyRunResult {
118
+ status: 'passed' | 'failed' | 'partial';
119
+ suite: AcceptanceCheckSuite;
120
+ executed: ExecutedVerificationSuite | null;
121
+ gaps: string[];
122
+ verification_results: VerificationResult[];
123
+ check_results: CheckResult[];
124
+ manifest: VerificationManifest | null;
125
+ risk_ledger: ResidualRiskLedger | null;
126
+ evidence_coverage: EvidenceCoverageSummary | null;
127
+ }
128
+
129
+ // Mirror of ParsedSpec/ParsedPlan (same as in graph-compiler to avoid circular deps)
130
+ interface Criterion {
131
+ id: string;
132
+ criterion: string;
133
+ howToVerify: string;
134
+ }
135
+
136
+ interface ParsedSpecLike {
137
+ objective: string | null;
138
+ criteria: Criterion[];
139
+ }
140
+
141
+ interface ParsedTaskLike {
142
+ id: string;
143
+ verifyCommand: string | null;
144
+ aceite: string[];
145
+ /** Contracted paths from the IMPLEMENTATION-PACK, attached by the caller. */
146
+ filesExist?: string[];
147
+ /** Contracted exports from the IMPLEMENTATION-PACK `symbols`. */
148
+ exportsExpected?: ExpectedExport[];
149
+ }
150
+
151
+ interface ParsedPlanLike {
152
+ tasks: ParsedTaskLike[];
153
+ /** PLAN.json `acceptance_tests` with the hashes frozen when the run was compiled. */
154
+ acceptanceTests?: AcceptanceTestLike[];
155
+ }
156
+
157
+ export function sha256File(absPath: string): string | null {
158
+ try {
159
+ return crypto.createHash('sha256').update(fs.readFileSync(absPath)).digest('hex');
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Drop quoted arguments so only invoked programs are classified: `node -e "…'node --test'…"`
167
+ * checks package.json, it does not run a test runner.
168
+ */
169
+ export function stripQuotedArgs(command: string): string {
170
+ return command.replace(/"(?:\\.|[^"\\])*"|'[^']*'/g, '""');
171
+ }
172
+
173
+ function inferCheckType(howToVerify: string): CheckType {
174
+ const v = howToVerify.toLowerCase();
175
+ if (v.includes('npm test') || v.includes('jest') || v.includes('vitest') || v.includes('node --test')) return 'unit';
176
+ if (v.includes('postman') || v.includes('newman') || v.includes('integration')) return 'integration';
177
+ if (v.includes('smoke') || v.includes('curl')) return 'smoke';
178
+ if (v.includes('eslint') || v.includes('lint') || v.includes('oxe-policy')) return 'policy';
179
+ if (v.includes('security') || v.includes('audit') || v.includes('trivy')) return 'security';
180
+ return 'custom';
181
+ }
182
+
183
+ function inferEvidenceType(checkType: CheckType): EvidenceType {
184
+ switch (checkType) {
185
+ case 'unit': return 'junit_xml';
186
+ case 'integration': return 'api_output';
187
+ case 'security': return 'security_report';
188
+ case 'policy': return 'log';
189
+ default: return 'stdout';
190
+ }
191
+ }
192
+
193
+ export const SHELL_COMMAND_RE =
194
+ /^(npm|npx|pnpm|yarn|node|deno|bun|python3?|pytest|go|cargo|make|dotnet|mvn|gradle|bash|sh|curl|git|eslint|tsc|jest|vitest|mocha|oxe-cc|oxe|docker)(\s|$)/i;
195
+
196
+ export function looksLikeShellCommand(text: string): boolean {
197
+ return SHELL_COMMAND_RE.test(String(text || '').trim());
198
+ }
199
+
200
+ /**
201
+ * Turn a SPEC "Como verificar" cell into an executable command, or null when it is prose.
202
+ * Only backtick spans that look like commands count; path-like spans (`test/api.test.js`)
203
+ * and free text are never executed.
204
+ */
205
+ export function extractCommandFromHowToVerify(howToVerify: string): string | null {
206
+ const text = String(howToVerify || '').trim();
207
+ if (!text || text.startsWith('#')) return null;
208
+ const spans = [...text.matchAll(/`([^`]+)`/g)].map((m) => m[1].trim()).filter(Boolean);
209
+ if (spans.length > 0) {
210
+ const commands = [...new Set(spans.filter(looksLikeShellCommand))];
211
+ return commands.length ? commands.join(' && ') : null;
212
+ }
213
+ return looksLikeShellCommand(text) ? text : null;
214
+ }
215
+
216
+ /** Bump when the rules that turn SPEC/PLAN into checks change (invalidates persisted suites). */
217
+ export const VERIFICATION_COMPILER_VERSION = '1.20.0';
218
+
219
+ export function compile(
220
+ spec: ParsedSpecLike,
221
+ plan: ParsedPlanLike
222
+ ): AcceptanceCheckSuite {
223
+ const checks: AcceptanceCheck[] = [];
224
+ const seenRefs = new Set<string>();
225
+
226
+ // Generate checks from spec criteria
227
+ for (const criterion of spec.criteria) {
228
+ // Find the verify command from the task that references this criterion
229
+ const task = plan.tasks.find((t) => t.aceite.includes(criterion.id));
230
+ // A criterion the SPEC declares manual (UAT, manual check) is never "proven" by some task's verify command:
231
+ // OxeVoice F1's A8 (real dictation, UAT) passed on a doc-exists check of the task that wrote the UAT script.
232
+ const declaredManual = MANUAL_CRITERION_RE.test(String(criterion.howToVerify || ''))
233
+ && !extractCommandFromHowToVerify(criterion.howToVerify);
234
+ const command = declaredManual ? null : (task?.verifyCommand ?? extractCommandFromHowToVerify(criterion.howToVerify));
235
+ // Prose that cannot be executed is a manual criterion, not a shell command. The type comes from
236
+ // the command that actually runs: prose saying "npm test" must not demand a test report from a
237
+ // task command that never runs tests (false red seen in the 1.17 linkly benchmark).
238
+ const type: CheckType = command ? inferCheckType(stripQuotedArgs(command)) : 'manual';
239
+
240
+ checks.push({
241
+ id: `check-${criterion.id.toLowerCase()}`,
242
+ type,
243
+ command,
244
+ evidence_type_expected: inferEvidenceType(type),
245
+ acceptance_ref: criterion.id,
246
+ description: criterion.criterion,
247
+ });
248
+ seenRefs.add(criterion.id);
249
+ }
250
+
251
+ // Add checks for task verify commands not already covered
252
+ for (const task of plan.tasks) {
253
+ if (!task.verifyCommand) continue;
254
+ const uncovered = task.aceite.filter((ref) => !seenRefs.has(ref));
255
+ if (uncovered.length === 0 && checks.some((c) => c.command === task.verifyCommand)) continue;
256
+
257
+ checks.push({
258
+ id: `check-task-${task.id.toLowerCase()}`,
259
+ type: inferCheckType(stripQuotedArgs(task.verifyCommand)),
260
+ command: task.verifyCommand,
261
+ evidence_type_expected: 'stdout',
262
+ acceptance_ref: uncovered[0] ?? null,
263
+ description: `Verify command for task ${task.id}`,
264
+ });
265
+ }
266
+
267
+ // The IMPLEMENTATION-PACK contract is checked, not just recorded: a task that skipped a contracted
268
+ // file must not pass because its own verify command happened to exit 0 (T3 in the 1.17 benchmark).
269
+ for (const task of plan.tasks) {
270
+ const files = [...new Set(task.filesExist ?? [])];
271
+ const exportsExpected = dedupeExports(task.exportsExpected ?? []);
272
+ if (files.length === 0 && exportsExpected.length === 0) continue;
273
+ checks.push({
274
+ id: `check-pack-${task.id.toLowerCase()}`,
275
+ type: 'contract',
276
+ command: null,
277
+ evidence_type_expected: 'stdout',
278
+ acceptance_ref: null,
279
+ description: `Implementation pack contract for task ${task.id}`,
280
+ files_exist: files,
281
+ ...(exportsExpected.length ? { exports_expected: exportsExpected } : {}),
282
+ });
283
+ }
284
+
285
+ // Plan-owned acceptance tests: the proof of A* is written before execution and frozen.
286
+ for (const entry of plan.acceptanceTests ?? []) {
287
+ if (!entry || !entry.command || !Array.isArray(entry.files) || entry.files.length === 0) continue;
288
+ const type = inferCheckType(stripQuotedArgs(entry.command));
289
+ checks.push({
290
+ id: `check-accept-${String(entry.id || entry.criterion).toLowerCase()}`,
291
+ type,
292
+ command: entry.command,
293
+ evidence_type_expected: inferEvidenceType(type),
294
+ acceptance_ref: entry.criterion || null,
295
+ description: `Teste de aceite congelado de ${entry.criterion || entry.id}`,
296
+ frozen_files: entry.files.map((f) => ({ path: f.path, sha256: f.sha256 ?? null })),
297
+ ...(Array.isArray(entry.proves) && entry.proves.length ? { proves: [...entry.proves] } : {}),
298
+ });
299
+ }
300
+
301
+ return {
302
+ checks,
303
+ compiled_at: new Date().toISOString(),
304
+ spec_hash: hashObject(spec),
305
+ // OXB-011: the compiler's own version is part of the cache key — a suite compiled by older rules is stale.
306
+ plan_hash: hashObject({ plan, compiler: VERIFICATION_COMPILER_VERSION }),
307
+ };
308
+ }
309
+
310
+ export async function runCheck(
311
+ check: AcceptanceCheck,
312
+ cwd: string,
313
+ timeoutMs = 60_000
314
+ ): Promise<CheckResult> {
315
+ if (typeof check.timeout_ms === 'number' && check.timeout_ms > 0) timeoutMs = check.timeout_ms;
316
+ const frozen = check.frozen_files ?? [];
317
+ if (frozen.length > 0) {
318
+ const missing = frozen.filter((f) => !fs.existsSync(path.resolve(cwd, f.path)));
319
+ const tampered = missing.length > 0
320
+ ? []
321
+ : frozen.filter((f) => f.sha256 !== null && sha256File(path.resolve(cwd, f.path)) !== f.sha256);
322
+ const unlocked = frozen.filter((f) => f.sha256 === null);
323
+ if (missing.length > 0 || tampered.length > 0 || unlocked.length > 0) {
324
+ return {
325
+ check_id: check.id,
326
+ acceptance_ref: check.acceptance_ref,
327
+ status: 'fail',
328
+ stdout: '',
329
+ stderr: '',
330
+ exit_code: null,
331
+ duration_ms: 0,
332
+ error: missing.length > 0
333
+ ? `acceptance_missing: ${missing.map((f) => f.path).join(', ')}`
334
+ : tampered.length > 0
335
+ ? `acceptance_tampered: ${tampered.map((f) => f.path).join(', ')}`
336
+ : `acceptance_not_frozen: ${unlocked.map((f) => f.path).join(', ')} (não existia no compile)`,
337
+ tests_executed: null,
338
+ };
339
+ }
340
+ }
341
+
342
+ const contracted = check.files_exist ?? [];
343
+ const exportsExpected = check.exports_expected ?? [];
344
+ if (contracted.length > 0 || exportsExpected.length > 0) {
345
+ const absent = contracted.filter((file) => !fs.existsSync(path.resolve(cwd, file)));
346
+ const leaks = absent.length > 0 ? [] : contracted.filter((file) => referencesOxeInternals(path.resolve(cwd, file)));
347
+ const exportOutcome = absent.length > 0 || leaks.length > 0
348
+ ? { missing: [] as ExpectedExport[], unsupported: [] as string[] }
349
+ : checkExpectedExports(cwd, exportsExpected);
350
+ const failed = absent.length > 0 || leaks.length > 0 || exportOutcome.missing.length > 0;
351
+ if (failed || !check.command) {
352
+ const okLines: string[] = [];
353
+ if (contracted.length) okLines.push(`files_exist ok: ${contracted.join(', ')}`);
354
+ const checkedExports = exportsExpected.filter((e) => !exportOutcome.unsupported.includes(e.file));
355
+ if (checkedExports.length) okLines.push(`exports ok: ${checkedExports.map((e) => `${e.file}#${e.name}`).join(', ')}`);
356
+ if (exportOutcome.unsupported.length) okLines.push(`exports_unchecked (linguagem não suportada): ${exportOutcome.unsupported.join(', ')}`);
357
+ return {
358
+ check_id: check.id,
359
+ acceptance_ref: check.acceptance_ref,
360
+ status: failed ? 'fail' : 'pass',
361
+ stdout: failed ? '' : `${okLines.join('\n')}\n`,
362
+ stderr: '',
363
+ exit_code: null,
364
+ duration_ms: 0,
365
+ error: absent.length > 0
366
+ ? `files_missing: ${absent.join(', ')}`
367
+ : leaks.length > 0
368
+ ? `oxe_internal_reference: ${leaks.join(', ')}`
369
+ : exportOutcome.missing.length > 0
370
+ ? `exports_missing: ${exportOutcome.missing.map((e) => `${e.file}#${e.name}`).join(', ')}`
371
+ : null,
372
+ tests_executed: null,
373
+ };
374
+ }
375
+ }
376
+
377
+ if (!check.command) {
378
+ return {
379
+ check_id: check.id,
380
+ acceptance_ref: check.acceptance_ref,
381
+ status: 'skip',
382
+ stdout: '',
383
+ stderr: '',
384
+ exit_code: null,
385
+ duration_ms: 0,
386
+ error: null,
387
+ skip_reason: check.type === 'manual' ? 'needs_structured_check' : 'no_command',
388
+ tests_executed: null,
389
+ };
390
+ }
391
+
392
+ // A verify command that names a test file which does not exist cannot have verified it,
393
+ // whatever the runner's exit code says.
394
+ const missingFiles = extractTestFileArgs(check.command).filter(
395
+ (file) => !fs.existsSync(path.resolve(cwd, file))
396
+ );
397
+ if (missingFiles.length > 0) {
398
+ return {
399
+ check_id: check.id,
400
+ acceptance_ref: check.acceptance_ref,
401
+ status: 'fail',
402
+ stdout: '',
403
+ stderr: '',
404
+ exit_code: null,
405
+ duration_ms: 0,
406
+ error: `test_file_missing: ${missingFiles.join(', ')}`,
407
+ tests_executed: 0,
408
+ };
409
+ }
410
+
411
+ const start = Date.now();
412
+ try {
413
+ // Use a shell so the full command string is interpreted (handles quotes, &&, node -e "...").
414
+ // The child never inherits node:test context: it would emit a serialized protocol, not TAP.
415
+ const shell = shellInvocation(check.command);
416
+ const result = spawnSync(shell.file, shell.args, {
417
+ cwd,
418
+ env: childProcessEnv(),
419
+ encoding: 'utf8',
420
+ timeout: timeoutMs,
421
+ maxBuffer: 2 * 1024 * 1024,
422
+ windowsVerbatimArguments: shell.windowsVerbatimArguments,
423
+ });
424
+
425
+ const duration_ms = Date.now() - start;
426
+ const stdout = result.stdout ?? '';
427
+ const stderr = result.stderr ?? '';
428
+ const report = parseTestReport(`${stdout}\n${stderr}`);
429
+ let status: VerificationStatus = result.status === 0 ? 'pass' : 'fail';
430
+ let error: string | null = result.error ? String(result.error) : null;
431
+
432
+ // Exit code 0 is not proof: `node --test` exits 0 when a listed file is missing, and a
433
+ // unit check that executed zero tests verified nothing.
434
+ if (status === 'pass' && report.missing_files.length > 0) {
435
+ status = 'fail';
436
+ error = `test_file_missing: ${report.missing_files.join(', ')}`;
437
+ } else if (status === 'pass' && check.type === 'unit' && report.tests_executed === 0) {
438
+ status = 'fail';
439
+ error = 'no_tests_executed';
440
+ } else if (status === 'pass' && check.type === 'unit' && report.tests_executed === null && !stdout.trim() && !stderr.trim()) {
441
+ // A unit check that printed nothing cannot have run a test runner.
442
+ status = 'fail';
443
+ error = 'no_test_report';
444
+ }
445
+ if (status === 'pass' && check.proves && check.proves.length > 0) {
446
+ const missing = missingProofs(check.proves, `${stdout}
447
+ ${stderr}`);
448
+ if (missing.length > 0) {
449
+ status = 'fail';
450
+ error = `proof_not_executed: ${missing.join(' | ')}`;
451
+ }
452
+ }
453
+
454
+ return {
455
+ check_id: check.id,
456
+ acceptance_ref: check.acceptance_ref,
457
+ status,
458
+ stdout,
459
+ stderr,
460
+ exit_code: result.status ?? null,
461
+ duration_ms,
462
+ error,
463
+ tests_executed: report.tests_executed,
464
+ };
465
+ } catch (err) {
466
+ return {
467
+ check_id: check.id,
468
+ acceptance_ref: check.acceptance_ref,
469
+ status: 'error',
470
+ stdout: '',
471
+ stderr: '',
472
+ exit_code: null,
473
+ duration_ms: Date.now() - start,
474
+ error: String(err),
475
+ };
476
+ }
477
+ }
478
+
479
+ export async function runSuite(
480
+ suite: AcceptanceCheckSuite,
481
+ cwd: string,
482
+ timeoutMs = 60_000
483
+ ): Promise<CheckResult[]> {
484
+ const results: CheckResult[] = [];
485
+ for (const check of suite.checks) {
486
+ results.push(await runCheck(check, cwd, timeoutMs));
487
+ }
488
+ return results;
489
+ }
490
+
491
+ export async function executeSuite(
492
+ suite: AcceptanceCheckSuite,
493
+ cwd: string,
494
+ options: {
495
+ timeoutMs?: number;
496
+ runId: string;
497
+ workItemId: string;
498
+ attemptNumber?: number;
499
+ evidenceStore?: EvidenceStore;
500
+ pluginRegistry?: PluginRegistry;
501
+ }
502
+ ): Promise<ExecutedVerificationSuite> {
503
+ const results: CheckResult[] = [];
504
+ const verificationResults: VerificationResult[] = [];
505
+ const evidenceRefs = new Map<string, string[]>();
506
+ const timeoutMs = options.timeoutMs ?? 60_000;
507
+ const attemptNumber = options.attemptNumber ?? 1;
508
+
509
+ for (const check of suite.checks) {
510
+ const provider = options.pluginRegistry?.verifierProviderFor(check.type);
511
+ let result: CheckResult;
512
+ let verificationResult: VerificationResult;
513
+
514
+ if (provider) {
515
+ const providerResult = await provider.execute({
516
+ check_id: check.id,
517
+ check_type: check.type,
518
+ command: check.command,
519
+ work_item_id: options.workItemId,
520
+ workspace_root: cwd,
521
+ evidence_dir: '',
522
+ });
523
+ result = {
524
+ check_id: check.id,
525
+ acceptance_ref: check.acceptance_ref,
526
+ status: providerResult.status,
527
+ stdout: providerResult.summary ?? '',
528
+ stderr: '',
529
+ exit_code: providerResult.status === 'pass' ? 0 : 1,
530
+ duration_ms: 0,
531
+ error: providerResult.status === 'error' ? providerResult.summary ?? 'provider error' : null,
532
+ evidence_refs: providerResult.evidence_refs,
533
+ };
534
+ verificationResult = providerResult;
535
+ } else {
536
+ result = await runCheck(check, cwd, timeoutMs);
537
+ const collected = options.evidenceStore
538
+ ? await collectCheckEvidence(options.evidenceStore, check, result, {
539
+ run_id: options.runId,
540
+ work_item_id: options.workItemId,
541
+ attempt_number: attemptNumber,
542
+ })
543
+ : { refs: [], summaryRef: null };
544
+ result.evidence_refs = collected.refs;
545
+ result.summary_evidence_ref = collected.summaryRef;
546
+ verificationResult = {
547
+ verification_id: `vr-${crypto.randomBytes(4).toString('hex')}`,
548
+ work_item_id: options.workItemId,
549
+ check_id: check.id,
550
+ status: result.status,
551
+ evidence_refs: collected.refs,
552
+ summary: result.error || result.stderr || result.stdout || null,
553
+ };
554
+ }
555
+
556
+ if (result.evidence_refs && result.evidence_refs.length > 0) {
557
+ evidenceRefs.set(check.id, result.evidence_refs);
558
+ }
559
+ results.push(result);
560
+ verificationResults.push(verificationResult);
561
+ }
562
+
563
+ const manifest = buildManifest(options.runId, results, {
564
+ workItemId: options.workItemId,
565
+ granularity: 'work_item',
566
+ evidenceRefs,
567
+ });
568
+ const riskLedger = buildRiskLedger(options.runId, manifest);
569
+ const evidenceCoverage = summarizeEvidenceCoverage(manifest);
570
+ return {
571
+ results,
572
+ verification_results: verificationResults,
573
+ evidence_refs: evidenceRefs,
574
+ manifest,
575
+ risk_ledger: riskLedger,
576
+ evidence_coverage: evidenceCoverage,
577
+ };
578
+ }
579
+
580
+ export function summarizeSuite(results: CheckResult[]): {
581
+ total: number;
582
+ pass: number;
583
+ fail: number;
584
+ skip: number;
585
+ error: number;
586
+ /** Skipped checks whose criterion has no executable verification. */
587
+ manual: number;
588
+ allPassed: boolean;
589
+ } {
590
+ const counts = { total: results.length, pass: 0, fail: 0, skip: 0, error: 0 };
591
+ let manual = 0;
592
+ for (const r of results) {
593
+ counts[r.status]++;
594
+ if (r.status === 'skip' && r.skip_reason === 'needs_structured_check') manual++;
595
+ }
596
+ return { ...counts, manual, allPassed: counts.fail === 0 && counts.error === 0 };
597
+ }
598
+
599
+ export async function verifyRun(input: {
600
+ projectRoot: string;
601
+ runId: string;
602
+ workItemId: string;
603
+ cwd: string;
604
+ suite: AcceptanceCheckSuite;
605
+ pluginRegistry?: PluginRegistry;
606
+ evidenceStore?: EvidenceStore;
607
+ attemptNumber?: number;
608
+ timeoutMs?: number;
609
+ }): Promise<VerifyRunResult> {
610
+ const gaps: string[] = [];
611
+ if (!input.suite || !Array.isArray(input.suite.checks) || input.suite.checks.length === 0) {
612
+ gaps.push('Nenhum check executável foi compilado a partir de SPEC/PLAN.');
613
+ return {
614
+ status: 'partial',
615
+ suite: input.suite,
616
+ executed: null,
617
+ gaps,
618
+ verification_results: [],
619
+ check_results: [],
620
+ manifest: null,
621
+ risk_ledger: null,
622
+ evidence_coverage: null,
623
+ };
624
+ }
625
+
626
+ const executed = await executeSuite(input.suite, input.cwd, {
627
+ timeoutMs: input.timeoutMs,
628
+ runId: input.runId,
629
+ workItemId: input.workItemId,
630
+ attemptNumber: input.attemptNumber,
631
+ evidenceStore: input.evidenceStore,
632
+ pluginRegistry: input.pluginRegistry,
633
+ });
634
+ saveManifest(input.projectRoot, input.runId, executed.manifest);
635
+ saveRiskLedger(input.projectRoot, input.runId, executed.risk_ledger);
636
+ saveEvidenceCoverage(input.projectRoot, input.runId, executed.evidence_coverage);
637
+ const summary = summarizeSuite(executed.results);
638
+ for (const r of executed.results) {
639
+ if (r.status === 'skip' && r.skip_reason === 'needs_structured_check') {
640
+ gaps.push(
641
+ `Critério ${r.acceptance_ref ?? r.check_id}: "Como verificar" não é executável — informe um comando ou vincule a uma tarefa com verificação.`
642
+ );
643
+ }
644
+ }
645
+ // Manual criteria leave the run `partial`: nothing failed, but nothing proved them either.
646
+ const status: VerifyRunResult['status'] = summary.total === 0
647
+ ? 'partial'
648
+ : !summary.allPassed
649
+ ? 'failed'
650
+ : summary.manual > 0
651
+ ? 'partial'
652
+ : 'passed';
653
+ return {
654
+ status,
655
+ suite: input.suite,
656
+ executed,
657
+ gaps,
658
+ verification_results: executed.verification_results,
659
+ check_results: executed.results,
660
+ manifest: executed.manifest,
661
+ risk_ledger: executed.risk_ledger,
662
+ evidence_coverage: executed.evidence_coverage,
663
+ };
664
+ }
665
+
666
+ const MANUAL_CRITERION_RE = /\b(manual|uat|homologa\w*|inspe[cç][aã]o visual|visual inspection)\b/i;
667
+
668
+ const CODE_FILE_RE = /\.(c|m)?[jt]sx?$|\.(py|go|rs|java|kt|rb|php|cs|json|ya?ml|sh)$/i;
669
+ const OXE_INTERNAL_REF_RE = /(^|[^\w.-])\.oxe[\\/]/;
670
+
671
+ /**
672
+ * Product code or tests that read `.oxe/` depend on OXE's local state, which is usually
673
+ * gitignored: they pass in the workspace and break on a clean clone or in CI. Seen in the 1.18
674
+ * benchmark (test/api.test.js loading `.oxe/investigations/fixtures/…`). Docs may mention `.oxe/`.
675
+ */
676
+ function referencesOxeInternals(absPath: string): boolean {
677
+ if (!CODE_FILE_RE.test(absPath)) return false;
678
+ try {
679
+ const stat = fs.statSync(absPath);
680
+ if (!stat.isFile() || stat.size > 1024 * 1024) return false;
681
+ const current = fs.readFileSync(absPath, 'utf8');
682
+ const added = countOxeRefs(current);
683
+ if (added === 0) return false;
684
+ // Only references the run introduced count: a product that legitimately talks about `.oxe/` (OXESpace hosts OXE)
685
+ // already had them at HEAD (false red seen in OxeVoice F1 on shared/mcp-coverage.ts).
686
+ const baseline = readCommittedVersion(absPath);
687
+ return baseline === null ? true : added > countOxeRefs(baseline);
688
+ } catch {
689
+ return false;
690
+ }
691
+ }
692
+
693
+ function countOxeRefs(text: string): number {
694
+ return (text.match(new RegExp(OXE_INTERNAL_REF_RE.source, 'g')) || []).length;
695
+ }
696
+
697
+ /** The file as committed at HEAD, or null when it is untracked / there is no git. */
698
+ function readCommittedVersion(absPath: string): string | null {
699
+ try {
700
+ const dir = path.dirname(absPath);
701
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: dir, encoding: 'utf8', windowsHide: true });
702
+ if (top.status !== 0) return null;
703
+ const rel = path.relative(top.stdout.trim(), absPath).split(path.sep).join('/');
704
+ const shown = spawnSync('git', ['show', `HEAD:${rel}`], { cwd: dir, encoding: 'utf8', windowsHide: true, maxBuffer: 4 * 1024 * 1024 });
705
+ return shown.status === 0 ? shown.stdout : null;
706
+ } catch {
707
+ return null;
708
+ }
709
+ }
710
+
711
+ function dedupeExports(list: ExpectedExport[]): ExpectedExport[] {
712
+ const seen = new Set<string>();
713
+ const out: ExpectedExport[] = [];
714
+ for (const entry of list) {
715
+ if (!entry || typeof entry.file !== 'string' || typeof entry.name !== 'string') continue;
716
+ const key = `${entry.file}#${entry.name}`;
717
+ if (seen.has(key)) continue;
718
+ seen.add(key);
719
+ out.push({ file: entry.file, name: entry.name });
720
+ }
721
+ return out;
722
+ }
723
+
724
+ function hashObject(obj: unknown): string {
725
+ return crypto
726
+ .createHash('sha256')
727
+ .update(JSON.stringify(obj))
728
+ .digest('hex')
729
+ .slice(0, 12);
730
+ }
731
+
732
+ async function collectCheckEvidence(
733
+ store: EvidenceStore,
734
+ check: AcceptanceCheck,
735
+ result: CheckResult,
736
+ options: { run_id: string; work_item_id: string; attempt_number: number }
737
+ ): Promise<{ refs: string[]; summaryRef: string }> {
738
+ const refs: string[] = [];
739
+ if (result.stdout) {
740
+ const evidence = await store.collect('stdout', result.stdout, options);
741
+ refs.push(evidence.evidence_id);
742
+ }
743
+ if (result.stderr) {
744
+ const evidence = await store.collect('stderr', result.stderr, options);
745
+ refs.push(evidence.evidence_id);
746
+ }
747
+ const summaryEvidence = await store.collect(
748
+ check.evidence_type_expected,
749
+ JSON.stringify(
750
+ {
751
+ check_id: check.id,
752
+ type: check.type,
753
+ command: check.command,
754
+ status: result.status,
755
+ exit_code: result.exit_code,
756
+ duration_ms: result.duration_ms,
757
+ },
758
+ null,
759
+ 2
760
+ ),
761
+ options
762
+ );
763
+ // The summary record is bookkeeping, not proof: it is stored but excluded from `evidence_refs`,
764
+ // otherwise every check (even a silent exit 0) counts as "covered".
765
+ return { refs, summaryRef: summaryEvidence.evidence_id };
766
+ }