oxe-cc 1.14.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 -0
  3. package/.github/workflows/ci.yml +115 -9
  4. package/.github/workflows/release.yml +72 -46
  5. package/AGENTS.md +97 -97
  6. package/CHANGELOG.md +263 -0
  7. package/README.md +474 -537
  8. package/assets/readme-banner.svg +19 -19
  9. package/bin/banner.txt +13 -13
  10. package/bin/lib/oxe-agent-install.cjs +401 -386
  11. package/bin/lib/oxe-artifact-catalog.cjs +376 -0
  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 -0
  16. package/bin/lib/oxe-commit-convention.cjs +85 -0
  17. package/bin/lib/oxe-context-engine.cjs +863 -863
  18. package/bin/lib/oxe-core-command-handlers.cjs +82 -0
  19. package/bin/lib/oxe-criterion-coverage.cjs +58 -0
  20. package/bin/lib/oxe-dashboard.cjs +597 -597
  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 +104 -104
  24. package/bin/lib/oxe-npm-version.cjs +66 -64
  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 -0
  29. package/bin/lib/oxe-plugins.cjs +432 -341
  30. package/bin/lib/oxe-process.cjs +67 -0
  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 +127 -21
  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 +446 -447
  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 -5975
  44. package/docs/INTEGRATION.md +32 -2
  45. package/docs/QUALITY-GATES.md +46 -0
  46. package/docs/RELEASE-READINESS.md +31 -5
  47. package/docs/RUNTIME-SMOKE-MATRIX.md +2 -0
  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 -792
  104. package/lib/sdk/index.d.ts +982 -913
  105. package/lib/sdk/index.types.ts +933 -0
  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 -101
  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 -0
  143. package/oxe/templates/STATE.md +30 -140
  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 -353
  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 +35 -11
  198. package/packages/runtime/package.json +1 -1
  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 +128 -128
  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 +291 -291
  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 +126 -63
  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 -17
  278. package/vscode-extension/.vscodeignore +9 -7
  279. package/vscode-extension/package.json +10 -2
  280. package/vscode-extension/src/extension.js +320 -310
  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,938 +1,1144 @@
1
- import path from 'path';
2
- import fs from 'fs';
3
- import { appendEvent } from '../events/bus';
4
- import type { OxeEvent } from '../events/envelope';
5
- import type { EventInput } from '../events/bus';
6
- import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
7
- import type { WorkspaceManager, WorkspaceRequest } from '../workspace/workspace-manager';
8
- import type { WorkspaceLease } from '../models/workspace';
9
- import type { GateManager } from '../gate/gate-manager';
10
- import type { PolicyEngine, PersistedPolicyDecision, PolicyContext } from '../policy/policy-engine';
11
- import { savePolicyDecision } from '../policy/policy-engine';
12
- import type { PluginRegistry } from '../plugins/plugin-registry';
13
- import type { AuditTrail } from '../audit/audit-trail';
14
- import type { RunQuota, QuotaViolation } from '../audit/audit-trail';
15
- import { checkQuota, consumeQuota } from '../audit/audit-trail';
16
- import {
17
- saveJournal,
18
- loadJournal,
19
- deleteJournal,
20
- createJournal,
21
- } from './run-journal';
22
- import type { RunJournal } from './run-journal';
23
- import type { FailureClass } from '../models/failure';
24
- import { listMemos } from '../decision/decision-memo';
25
- import type { RollbackPlan } from '../decision/decision-memo';
26
- import { runCapabilityAsync } from '../plugins/capability-adapter';
27
- import { verifyRun } from '../verification/verification-compiler';
28
- import type { AcceptanceCheckSuite } from '../verification/verification-compiler';
29
-
30
- export interface TaskResult {
31
- success: boolean;
32
- failure_class: FailureClass;
33
- evidence: string[];
34
- output: string;
35
- completed_by?: string;
36
- }
37
-
38
- export interface TaskExecutor {
39
- execute(
40
- node: GraphNode,
41
- lease: WorkspaceLease,
42
- runId: string,
43
- attemptNumber: number,
44
- options?: { previousError?: string | null }
45
- ): Promise<TaskResult>;
46
- }
47
-
48
- export interface SchedulerOptions {
49
- maxRunDurationMs?: number; // default: 30 min
50
- staleProgressMs?: number; // default: 5 min without any task completing
51
- }
52
-
53
- export interface SchedulerContext {
54
- projectRoot: string;
55
- sessionId: string | null;
56
- runId: string;
57
- executor: TaskExecutor;
58
- workspaceManager: WorkspaceManager;
59
- gateManager?: GateManager;
60
- policyEngine?: PolicyEngine;
61
- pluginRegistry?: PluginRegistry;
62
- auditTrail?: AuditTrail;
63
- quota?: RunQuota;
64
- policyActor?: string;
65
- onEvent?: (event: OxeEvent) => void;
66
- options?: SchedulerOptions;
67
- }
68
-
69
- export interface RunResult {
70
- run_id: string;
71
- status: 'completed' | 'failed' | 'blocked' | 'cancelled' | 'paused' | 'aborted';
72
- completed: string[];
73
- failed: string[];
74
- blocked: string[];
75
- pending_gates?: string[];
76
- reason?: string;
77
- }
78
-
79
- type NodeStatus = 'pending' | 'ready' | 'running' | 'completed' | 'failed' | 'blocked';
80
-
81
- export class Scheduler {
82
- private cancelled = false;
83
- private paused = false;
84
- private journal: RunJournal | null = null;
85
- private ctx: SchedulerContext | null = null;
86
- private runStartMs = 0;
87
- private lastProgressMs = 0;
88
-
89
- private recordProgress(): void {
90
- this.lastProgressMs = Date.now();
91
- }
92
-
93
- private async executeRollback(plan: RollbackPlan, ctx: SchedulerContext): Promise<void> {
94
- try {
95
- switch (plan.strategy) {
96
- case 'revert_commit':
97
- await runCapabilityAsync('git', ['revert', 'HEAD', '--no-edit'], {}, ctx.projectRoot, 30_000);
98
- break;
99
- case 'restore_workspace':
100
- await runCapabilityAsync('git', ['checkout', '.'], {}, ctx.projectRoot, 30_000);
101
- break;
102
- case 'undo_patch':
103
- for (const p of plan.steps) {
104
- await runCapabilityAsync('git', ['checkout', 'HEAD', '--', p], {}, ctx.projectRoot, 10_000);
105
- }
106
- break;
107
- case 'no_rollback':
108
- default:
109
- break;
110
- }
111
- this.emit(ctx, { type: 'RollbackExecuted', payload: { strategy: plan.strategy } });
112
- } catch (err) {
113
- this.emit(ctx, { type: 'RollbackFailed', payload: { strategy: plan.strategy, error: String(err) } });
114
- }
115
- }
116
-
117
- async run(graph: ExecutionGraph, ctx: SchedulerContext): Promise<RunResult> {
118
- this.cancelled = false;
119
- this.paused = false;
120
- this.ctx = ctx;
121
- this.runStartMs = Date.now();
122
- this.lastProgressMs = Date.now();
123
-
124
- const status = new Map<string, NodeStatus>();
125
- for (const id of graph.nodes.keys()) status.set(id, 'pending');
126
-
127
- const completed: string[] = [];
128
- const failed: string[] = [];
129
- const blocked: string[] = [];
130
-
131
- // Plan hash drift detection: abort if the graph was recompiled since ACTIVE-RUN was saved
132
- const activeRunPath = ctx.sessionId
133
- ? path.join(ctx.projectRoot, '.oxe', ctx.sessionId, 'execution', 'ACTIVE-RUN.json')
134
- : path.join(ctx.projectRoot, '.oxe', 'ACTIVE-RUN.json');
135
- if (fs.existsSync(activeRunPath)) {
136
- try {
137
- const activeRun = JSON.parse(fs.readFileSync(activeRunPath, 'utf8')) as Record<string, unknown>;
138
- const savedHash = activeRun.plan_hash as string | undefined;
139
- const currentHash = graph.metadata.plan_hash;
140
- if (savedHash && savedHash !== currentHash) {
141
- return {
142
- run_id: ctx.runId,
143
- status: 'aborted',
144
- completed: [],
145
- failed: [],
146
- blocked: [],
147
- reason: `plan_drift: graph recompiled (${savedHash} → ${currentHash}). Run /oxe-plan --replan to realign.`,
148
- };
149
- }
150
- } catch {
151
- // ACTIVE-RUN not parseable — continue without drift check
152
- }
153
- }
154
-
155
- this.journal = createJournal(ctx.runId);
156
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
157
-
158
- this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId } });
159
- ctx.auditTrail?.record('run_started', ctx.policyActor ?? 'runtime', {
160
- runId: ctx.runId,
161
- detail: { session_id: ctx.sessionId ?? null },
162
- });
163
-
164
- const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60_000;
165
- const staleMs = ctx.options?.staleProgressMs ?? 5 * 60_000;
166
-
167
- for (const wave of graph.waves) {
168
- if (this.cancelled) break;
169
-
170
- // Global run timeout
171
- if (Date.now() - this.runStartMs > maxRunMs) {
172
- this.emit(ctx, { type: 'RunAborted', payload: { reason: 'global_timeout' } });
173
- return { run_id: ctx.runId, status: 'aborted', completed: [], failed: [], blocked: [], reason: 'global_timeout' };
174
- }
175
-
176
- // Stale progress timeout (no task completed in staleMs)
177
- if (Date.now() - this.lastProgressMs > staleMs) {
178
- this.emit(ctx, { type: 'RunAborted', payload: { reason: 'no_progress_timeout' } });
179
- return { run_id: ctx.runId, status: 'aborted', completed: [], failed: [], blocked: [], reason: 'no_progress_timeout' };
180
- }
181
-
182
- // Respect pause: persist journal and return paused result
183
- if (this.paused) {
184
- this.journal.scheduler_state = 'paused';
185
- this.journal.paused_at = new Date().toISOString();
186
- this.journal.completed_work_items = completed.slice();
187
- this.journal.failed_work_items = failed.slice();
188
- this.journal.blocked_work_items = blocked.slice();
189
- this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
190
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
191
- ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
192
- runId: ctx.runId,
193
- detail: { completed, failed, blocked },
194
- });
195
- return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
196
- }
197
-
198
- const waveFailed = await this.runWave(
199
- wave.node_ids,
200
- graph,
201
- ctx,
202
- status,
203
- completed,
204
- failed,
205
- blocked
206
- );
207
-
208
- // Sync journal after each wave
209
- this.journal.completed_work_items = completed.slice();
210
- this.journal.failed_work_items = failed.slice();
211
- this.journal.blocked_work_items = blocked.slice();
212
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
213
-
214
- if (waveFailed) {
215
- // Execute rollback plan if one was created for this run
216
- const memos = listMemos(ctx.projectRoot, ctx.runId);
217
- for (const memo of memos) {
218
- if (memo.rollback_plan.strategy !== 'no_rollback') {
219
- await this.executeRollback(memo.rollback_plan, ctx);
220
- break; // apply at most one rollback plan per wave failure
221
- }
222
- }
223
- break;
224
- }
225
- }
226
-
227
- // Any remaining pending nodes become blocked
228
- for (const [id, s] of status) {
229
- if (s === 'pending') {
230
- status.set(id, 'blocked');
231
- blocked.push(id);
232
- this.emit(ctx, {
233
- type: 'WorkItemBlocked',
234
- work_item_id: id,
235
- payload: { reason: 'upstream_wave_failed' },
236
- });
237
- }
238
- }
239
-
240
- const finalStatus: RunResult['status'] = this.cancelled
241
- ? 'cancelled'
242
- : failed.length > 0
243
- ? 'failed'
244
- : blocked.length > 0
245
- ? 'blocked'
246
- : 'completed';
247
-
248
- this.emit(ctx, {
249
- type: 'RunCompleted',
250
- payload: { run_id: ctx.runId, status: finalStatus },
251
- });
252
- ctx.auditTrail?.record('run_completed', ctx.policyActor ?? 'runtime', {
253
- runId: ctx.runId,
254
- detail: {
255
- status: finalStatus,
256
- completed: completed.length,
257
- failed: failed.length,
258
- blocked: blocked.length,
259
- pending_gates: this.journal.pending_gates.slice(),
260
- },
261
- });
262
-
263
- this.journal.scheduler_state = this.cancelled ? 'cancelled' : finalStatus === 'blocked' ? 'blocked' : 'completed';
264
- this.journal.completed_work_items = completed.slice();
265
- this.journal.failed_work_items = failed.slice();
266
- this.journal.blocked_work_items = blocked.slice();
267
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
268
-
269
- return {
270
- run_id: ctx.runId,
271
- status: finalStatus,
272
- completed,
273
- failed,
274
- blocked,
275
- pending_gates: this.journal.pending_gates.slice(),
276
- };
277
- }
278
-
279
- /**
280
- * Recover a previously paused run by loading its journal and re-running
281
- * only the work items that haven't completed yet.
282
- */
283
- async recover(runId: string, ctx: SchedulerContext, graph: ExecutionGraph): Promise<RunResult | null> {
284
- const journal = loadJournal(ctx.projectRoot, runId);
285
- if (!journal || journal.scheduler_state !== 'paused') return null;
286
-
287
- // Restore state from journal
288
- this.cancelled = false;
289
- this.paused = false;
290
- this.ctx = ctx;
291
- this.journal = { ...journal, scheduler_state: 'running', paused_at: null };
292
-
293
- const restoredCompleted = new Set(journal.completed_work_items);
294
- const restoredFailed = new Set(journal.failed_work_items);
295
- const restoredBlocked = new Set(journal.blocked_work_items);
296
-
297
- const status = new Map<string, NodeStatus>();
298
- for (const id of graph.nodes.keys()) {
299
- if (restoredCompleted.has(id)) status.set(id, 'completed');
300
- else if (restoredFailed.has(id)) status.set(id, 'failed');
301
- else if (restoredBlocked.has(id)) status.set(id, 'blocked');
302
- else status.set(id, 'pending');
303
- }
304
-
305
- const completed = [...restoredCompleted];
306
- const failed = [...restoredFailed];
307
- const blocked = [...restoredBlocked];
308
-
309
- saveJournal(ctx.projectRoot, runId, this.journal);
310
-
311
- this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId, recovered: true } });
312
-
313
- for (const wave of graph.waves) {
314
- if (this.cancelled) break;
315
- if (this.paused) {
316
- this.journal.scheduler_state = 'paused';
317
- this.journal.paused_at = new Date().toISOString();
318
- this.journal.completed_work_items = completed.slice();
319
- this.journal.failed_work_items = failed.slice();
320
- this.journal.blocked_work_items = blocked.slice();
321
- this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
322
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
323
- ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
324
- runId: ctx.runId,
325
- detail: { recovered: true, completed, failed, blocked },
326
- });
327
- return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
328
- }
329
-
330
- // Skip waves fully completed
331
- const allDone = wave.node_ids.every(
332
- (id) => restoredCompleted.has(id) || restoredFailed.has(id) || restoredBlocked.has(id)
333
- );
334
- if (allDone) continue;
335
-
336
- const waveFailed = await this.runWave(
337
- wave.node_ids,
338
- graph,
339
- ctx,
340
- status,
341
- completed,
342
- failed,
343
- blocked
344
- );
345
-
346
- this.journal.completed_work_items = completed.slice();
347
- this.journal.failed_work_items = failed.slice();
348
- this.journal.blocked_work_items = blocked.slice();
349
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
350
-
351
- if (waveFailed) break;
352
- }
353
-
354
- for (const [id, s] of status) {
355
- if (s === 'pending') {
356
- status.set(id, 'blocked');
357
- blocked.push(id);
358
- this.emit(ctx, {
359
- type: 'WorkItemBlocked',
360
- work_item_id: id,
361
- payload: { reason: 'upstream_wave_failed' },
362
- });
363
- }
364
- }
365
-
366
- const finalStatus: RunResult['status'] = this.cancelled
367
- ? 'cancelled'
368
- : failed.length > 0
369
- ? 'failed'
370
- : blocked.length > 0
371
- ? 'blocked'
372
- : 'completed';
373
-
374
- this.emit(ctx, {
375
- type: 'RunCompleted',
376
- payload: { run_id: ctx.runId, status: finalStatus, recovered: true },
377
- });
378
- ctx.auditTrail?.record('run_recovered', ctx.policyActor ?? 'runtime', {
379
- runId: ctx.runId,
380
- detail: {
381
- status: finalStatus,
382
- completed: completed.length,
383
- failed: failed.length,
384
- blocked: blocked.length,
385
- pending_gates: this.journal.pending_gates.slice(),
386
- },
387
- });
388
-
389
- this.journal.scheduler_state = this.cancelled ? 'cancelled' : finalStatus === 'blocked' ? 'blocked' : 'completed';
390
- this.journal.completed_work_items = completed.slice();
391
- this.journal.failed_work_items = failed.slice();
392
- this.journal.blocked_work_items = blocked.slice();
393
- saveJournal(ctx.projectRoot, ctx.runId, this.journal);
394
- deleteJournal(ctx.projectRoot, ctx.runId);
395
-
396
- return {
397
- run_id: ctx.runId,
398
- status: finalStatus,
399
- completed,
400
- failed,
401
- blocked,
402
- pending_gates: this.journal.pending_gates.slice(),
403
- };
404
- }
405
-
406
- private isConcurrentSafe(nodeId: string, graph: ExecutionGraph, ctx: SchedulerContext): boolean {
407
- const node = graph.nodes.get(nodeId)!;
408
- if (node.mutation_scope.length > 0) return false;
409
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
410
- if (!primaryAction) return true;
411
- const provider = ctx.pluginRegistry?.toolProviderFor(primaryAction.type);
412
- return provider?.idempotent ?? true;
413
- }
414
-
415
- private async runWave(
416
- nodeIds: string[],
417
- graph: ExecutionGraph,
418
- ctx: SchedulerContext,
419
- status: Map<string, NodeStatus>,
420
- completed: string[],
421
- failed: string[],
422
- blocked: string[]
423
- ): Promise<boolean> {
424
- const eligible: string[] = [];
425
- const depsNotMet: string[] = [];
426
-
427
- for (const id of nodeIds) {
428
- if (status.get(id) === 'completed') continue; // already done in recovery
429
- const node = graph.nodes.get(id)!;
430
- const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
431
- if (depsMet) {
432
- eligible.push(id);
433
- } else {
434
- depsNotMet.push(id);
435
- }
436
- }
437
-
438
- for (const id of depsNotMet) {
439
- status.set(id, 'blocked');
440
- blocked.push(id);
441
- this.emit(ctx, {
442
- type: 'WorkItemBlocked',
443
- work_item_id: id,
444
- payload: { reason: 'dependency_not_met' },
445
- });
446
- }
447
-
448
- const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
449
- const mutations = eligible.filter((id) => !readOnly.includes(id));
450
-
451
- if (readOnly.length > 0) {
452
- await Promise.all(
453
- readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked))
454
- );
455
- }
456
-
457
- for (const id of mutations) {
458
- if (this.cancelled) break;
459
- await this.runNode(id, graph, ctx, status, completed, failed, blocked);
460
- }
461
-
462
- return failed.length > 0;
463
- }
464
-
465
- private async runNode(
466
- nodeId: string,
467
- graph: ExecutionGraph,
468
- ctx: SchedulerContext,
469
- status: Map<string, NodeStatus>,
470
- completed: string[],
471
- failed: string[],
472
- blocked: string[]
473
- ): Promise<void> {
474
- const node = graph.nodes.get(nodeId)!;
475
- status.set(nodeId, 'running');
476
- this.emit(ctx, {
477
- type: 'WorkItemReady',
478
- work_item_id: nodeId,
479
- payload: { title: node.title, wave: node.wave },
480
- });
481
-
482
- let lease: WorkspaceLease | null = null;
483
- let lastResult: TaskResult | null = null;
484
- let lastError: string | null = null;
485
- const maxAttempts = node.policy.max_retries + 1;
486
- const quotaBlocked = this.consumeQuotaForNode(ctx, node);
487
- if (quotaBlocked) {
488
- this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
489
- return;
490
- }
491
-
492
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
493
- const attemptId = `${nodeId}-a${attempt}`;
494
-
495
- this.emit(ctx, {
496
- type: 'AttemptStarted',
497
- work_item_id: nodeId,
498
- attempt_id: attemptId,
499
- payload: { attempt_number: attempt },
500
- });
501
-
502
- try {
503
- const policyDecision = this.evaluatePolicyForNode(node, ctx);
504
- if (policyDecision && !policyDecision.allowed) {
505
- this.emit(ctx, {
506
- type: 'PolicyEvaluated',
507
- work_item_id: nodeId,
508
- attempt_id: attemptId,
509
- payload: { ...policyDecision },
510
- });
511
- ctx.auditTrail?.record('policy_denied', ctx.policyActor ?? 'runtime', {
512
- runId: ctx.runId,
513
- workItemId: nodeId,
514
- detail: { reason: policyDecision.reason, rule_id: policyDecision.rule_id },
515
- });
516
- this.blockNode(nodeId, ctx, status, blocked, 'policy_denied', policyDecision.reason);
517
- return;
518
- }
519
-
520
- if (policyDecision) {
521
- this.emit(ctx, {
522
- type: 'PolicyEvaluated',
523
- work_item_id: nodeId,
524
- attempt_id: attemptId,
525
- payload: { ...policyDecision },
526
- });
527
- }
528
-
529
- if (policyDecision?.gate_required || node.policy.requires_human_approval) {
530
- const gateId = await this.requestGateForNode(node, ctx, policyDecision);
531
- this.blockNode(nodeId, ctx, status, blocked, 'pending_gate', gateId);
532
- return;
533
- }
534
-
535
- const wsReq: WorkspaceRequest = {
536
- work_item_id: nodeId,
537
- attempt_number: attempt,
538
- strategy: node.workspace_strategy,
539
- mutation_scope: node.mutation_scope,
540
- };
541
- const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
542
- lease = await workspaceManager.allocate(wsReq);
543
- this.emit(ctx, {
544
- type: 'WorkspaceAllocated',
545
- work_item_id: nodeId,
546
- attempt_id: attemptId,
547
- payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
548
- });
549
-
550
- lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, { previousError: lastError });
551
-
552
- if (lastResult.success) {
553
- const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
554
- if (verifyResult && verifyResult.status === 'failed') {
555
- lastResult = {
556
- success: false,
557
- failure_class: 'verify',
558
- evidence: lastResult.evidence,
559
- output: `Verification failed: ${(verifyResult.gaps || []).join('; ') || 'checks did not pass'}`,
560
- };
561
- } else {
562
- this.emit(ctx, {
563
- type: 'WorkItemCompleted',
564
- work_item_id: nodeId,
565
- attempt_id: attemptId,
566
- payload: { attempt_number: attempt, evidence: lastResult.evidence },
567
- });
568
- status.set(nodeId, 'completed');
569
- completed.push(nodeId);
570
- this.recordProgress();
571
- return;
572
- }
573
- }
574
-
575
- lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
576
-
577
- if (lastResult.failure_class === 'policy') break;
578
-
579
- if (attempt < maxAttempts) {
580
- const retryBlocked = this.consumeRetryQuota(ctx);
581
- if (retryBlocked) {
582
- this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
583
- return;
584
- }
585
- // Exponential backoff with jitter: 1s * 2^(attempt-1) + [0, 500ms], capped at 30s
586
- const backoffMs = Math.min(
587
- 1_000 * Math.pow(2, attempt - 1) + Math.random() * 500,
588
- 30_000
589
- );
590
- await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
591
- this.emit(ctx, {
592
- type: 'RetryScheduled',
593
- work_item_id: nodeId,
594
- payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs },
595
- });
596
- }
597
- } catch (err: unknown) {
598
- // Error boundary: isolate task failure, emit structured event, do not crash scheduler
599
- const message = err instanceof Error ? err.message : String(err);
600
- const stack = err instanceof Error ? err.stack : undefined;
601
- this.emit(ctx, {
602
- type: 'TaskErrorBoundaryTripped',
603
- work_item_id: nodeId,
604
- payload: { message, stack, attempt },
605
- });
606
- lastResult = {
607
- success: false,
608
- failure_class: 'env',
609
- evidence: [],
610
- output: `[error_boundary] ${message}`,
611
- };
612
- lastError = lastResult.output;
613
- if (attempt < maxAttempts) {
614
- const backoffMs = Math.min(1_000 * Math.pow(2, attempt - 1) + Math.random() * 500, 30_000);
615
- await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
616
- this.emit(ctx, {
617
- type: 'RetryScheduled',
618
- work_item_id: nodeId,
619
- payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs },
620
- });
621
- }
622
- } finally {
623
- if (lease) {
624
- await ctx.workspaceManager.dispose(lease.workspace_id).catch((e: unknown) =>
625
- this.emit(ctx!, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } })
626
- );
627
- lease = null;
628
- }
629
- }
630
- }
631
-
632
- this.emit(ctx, {
633
- type: 'WorkItemBlocked',
634
- work_item_id: nodeId,
635
- payload: { failure_class: lastResult?.failure_class ?? 'env', max_attempts: maxAttempts },
636
- });
637
- status.set(nodeId, 'failed');
638
- failed.push(nodeId);
639
- }
640
-
641
- pause(): void {
642
- this.paused = true;
643
- if (this.journal && this.ctx) {
644
- this.journal.scheduler_state = 'paused';
645
- this.journal.paused_at = new Date().toISOString();
646
- saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
647
- }
648
- }
649
-
650
- resume(): void {
651
- this.paused = false;
652
- if (this.journal && this.ctx) {
653
- this.journal.scheduler_state = 'running';
654
- this.journal.paused_at = null;
655
- saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
656
- }
657
- }
658
-
659
- cancel(): void {
660
- this.cancelled = true;
661
- if (this.journal && this.ctx) {
662
- this.journal.cancelled = true;
663
- this.journal.scheduler_state = 'cancelled';
664
- saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
665
- }
666
- }
667
-
668
- getJournal(): RunJournal | null {
669
- return this.journal;
670
- }
671
-
672
- static loadJournal(projectRoot: string, runId: string): RunJournal | null {
673
- return loadJournal(projectRoot, runId);
674
- }
675
-
676
- private async executeNode(
677
- node: GraphNode,
678
- lease: WorkspaceLease,
679
- ctx: SchedulerContext,
680
- attempt: number,
681
- attemptId: string,
682
- options: { previousError?: string | null } = {},
683
- ): Promise<TaskResult> {
684
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
685
- const provider = primaryAction ? ctx.pluginRegistry?.toolProviderFor(primaryAction.type) : null;
686
- if (!provider || !primaryAction) {
687
- return ctx.executor.execute(node, lease, ctx.runId, attempt, options);
688
- }
689
-
690
- ctx.auditTrail?.record('plugin_invoked', ctx.policyActor ?? 'runtime', {
691
- runId: ctx.runId,
692
- workItemId: node.id,
693
- resource: provider.name,
694
- detail: { action_type: primaryAction.type, attempt_id: attemptId },
695
- });
696
- this.emit(ctx, {
697
- type: 'ToolInvoked',
698
- work_item_id: node.id,
699
- attempt_id: attemptId,
700
- payload: { provider: provider.name, action_type: primaryAction.type },
701
- });
702
-
703
- const invocationInput = {
704
- action_type: primaryAction.type,
705
- work_item_id: node.id,
706
- run_id: ctx.runId,
707
- attempt_id: attemptId,
708
- params: {
709
- command: primaryAction.command ?? null,
710
- targets: primaryAction.targets ?? [],
711
- },
712
- workspace_root: lease.root_path,
713
- };
714
-
715
- if (provider.preInvoke) {
716
- const preCheck = await provider.preInvoke(invocationInput);
717
- if (!preCheck.allowed) {
718
- this.emit(ctx, {
719
- type: 'ToolFailed',
720
- work_item_id: node.id,
721
- attempt_id: attemptId,
722
- payload: { provider: provider.name, action_type: primaryAction.type, error: preCheck.reason ?? 'pre_invoke blocked', evidence_paths: [], side_effects_applied: [] },
723
- });
724
- return { success: false, failure_class: 'policy', evidence: [], output: preCheck.reason ?? 'pre_invoke blocked' };
725
- }
726
- }
727
-
728
- const result = await provider.invoke(invocationInput);
729
-
730
- if (provider.postInvoke) {
731
- await provider.postInvoke(invocationInput, result).catch(() => {});
732
- }
733
-
734
- this.emit(ctx, {
735
- type: result.success ? 'ToolCompleted' : 'ToolFailed',
736
- work_item_id: node.id,
737
- attempt_id: attemptId,
738
- payload: {
739
- provider: provider.name,
740
- action_type: primaryAction.type,
741
- evidence_paths: result.evidence_paths,
742
- side_effects_applied: result.side_effects_applied,
743
- error: result.error ?? null,
744
- },
745
- });
746
-
747
- return {
748
- success: result.success,
749
- failure_class: result.success ? null : provider.kind === 'external_operation' ? 'policy' : 'env',
750
- evidence: result.evidence_paths,
751
- output: result.output,
752
- };
753
- }
754
-
755
- private async verifyNode(
756
- node: GraphNode,
757
- lease: WorkspaceLease,
758
- ctx: SchedulerContext,
759
- attemptId: string,
760
- attempt: number,
761
- ): Promise<{ status: string; gaps?: string[] } | null> {
762
- if (!node.verify?.command) return null;
763
- this.emit(ctx, {
764
- type: 'VerificationStarted',
765
- work_item_id: node.id,
766
- payload: { command: node.verify.command, attempt_number: attempt },
767
- });
768
- const suite: AcceptanceCheckSuite = {
769
- checks: [{
770
- id: `inline-${node.id}`,
771
- type: 'custom',
772
- command: node.verify.command,
773
- evidence_type_expected: 'stdout',
774
- acceptance_ref: null,
775
- description: `Verify ${node.id}`,
776
- }],
777
- compiled_at: new Date().toISOString(),
778
- spec_hash: '',
779
- plan_hash: '',
780
- };
781
- let result: { status: string; gaps?: string[] };
782
- try {
783
- result = await verifyRun({
784
- suite,
785
- cwd: lease.root_path,
786
- timeoutMs: (ctx.options as Record<string, unknown>)?.verifyTimeoutMs as number ?? 60_000,
787
- runId: ctx.runId,
788
- workItemId: node.id,
789
- attemptNumber: attempt,
790
- projectRoot: ctx.projectRoot,
791
- pluginRegistry: ctx.pluginRegistry,
792
- });
793
- } catch (err) {
794
- this.emit(ctx, {
795
- type: 'VerificationCompleted',
796
- work_item_id: node.id,
797
- attempt_id: attemptId,
798
- payload: { status: 'error', error: String(err) },
799
- });
800
- return null;
801
- }
802
- this.emit(ctx, {
803
- type: 'VerificationCompleted',
804
- work_item_id: node.id,
805
- attempt_id: attemptId,
806
- payload: { status: result.status },
807
- });
808
- return result;
809
- }
810
-
811
- private evaluatePolicyForNode(node: GraphNode, ctx: SchedulerContext): PersistedPolicyDecision | null {
812
- if (!ctx.policyEngine) return null;
813
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
814
- const decisionContext: PolicyContext = {
815
- tool: primaryAction?.type ?? 'custom',
816
- kind: node.workspace_strategy,
817
- mutation_scope: node.mutation_scope,
818
- affected_paths: node.mutation_scope,
819
- side_effect_class: inferSideEffectClass(node),
820
- mutation_count: node.mutation_scope.length,
821
- node_policy: {
822
- max_retries: node.policy.max_retries,
823
- },
824
- };
825
- const evaluated = ctx.policyEngine.evaluate(decisionContext);
826
- const persisted: PersistedPolicyDecision = {
827
- ...evaluated,
828
- run_id: ctx.runId,
829
- work_item_id: node.id,
830
- action: primaryAction?.type ?? 'custom',
831
- actor: ctx.policyActor ?? 'runtime',
832
- override: false,
833
- rationale: null,
834
- context: decisionContext,
835
- };
836
- savePolicyDecision(ctx.projectRoot, persisted);
837
- return persisted;
838
- }
839
-
840
- private async requestGateForNode(
841
- node: GraphNode,
842
- ctx: SchedulerContext,
843
- decision: PersistedPolicyDecision | null
844
- ): Promise<string> {
845
- if (!ctx.gateManager) {
846
- console.warn('[scheduler] ctx.gateManager not configured — gates will not be persisted');
847
- return 'gate-missing-manager';
848
- }
849
- const scope = inferGateScope(node);
850
- const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
851
- const gate = await ctx.gateManager.request(scope, {
852
- run_id: ctx.runId,
853
- work_item_id: node.id,
854
- action: primaryAction?.type ?? 'custom',
855
- description: `Gate required before executing ${node.id}`,
856
- evidence_refs: [],
857
- risks: [decision?.reason ?? 'human approval required'],
858
- rationale: decision?.reason ?? 'node policy requires approval',
859
- policy_decision_id: decision?.decision_id ?? null,
860
- });
861
- if (this.journal && !this.journal.pending_gates.includes(gate.gate_id)) {
862
- this.journal.pending_gates.push(gate.gate_id);
863
- }
864
- ctx.auditTrail?.record('gate_requested', ctx.policyActor ?? 'runtime', {
865
- runId: ctx.runId,
866
- workItemId: node.id,
867
- detail: { gate_id: gate.gate_id, scope: gate.scope, action: gate.action },
868
- });
869
- return gate.gate_id;
870
- }
871
-
872
- private blockNode(
873
- nodeId: string,
874
- ctx: SchedulerContext,
875
- status: Map<string, NodeStatus>,
876
- blocked: string[],
877
- reason: string,
878
- detail: string | QuotaViolation | null = null
879
- ): void {
880
- this.emit(ctx, {
881
- type: 'WorkItemBlocked',
882
- work_item_id: nodeId,
883
- payload: { reason, detail },
884
- });
885
- status.set(nodeId, 'blocked');
886
- if (!blocked.includes(nodeId)) blocked.push(nodeId);
887
- }
888
-
889
- private consumeQuotaForNode(ctx: SchedulerContext, node: GraphNode): string | null {
890
- if (!ctx.quota) return null;
891
- let quota = consumeQuota(ctx.quota, 'work_items', 1);
892
- if (node.mutation_scope.length > 0) {
893
- quota = consumeQuota(quota, 'mutations', 1);
894
- }
895
- const violation = checkQuota(quota);
896
- ctx.quota = quota;
897
- return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
898
- }
899
-
900
- private consumeRetryQuota(ctx: SchedulerContext): string | null {
901
- if (!ctx.quota) return null;
902
- ctx.quota = consumeQuota(ctx.quota, 'retries', 1);
903
- const violation = checkQuota(ctx.quota);
904
- return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
905
- }
906
-
907
- private emit(
908
- ctx: SchedulerContext,
909
- input: EventInput
910
- ): void {
911
- const event = appendEvent(ctx.projectRoot, ctx.sessionId, {
912
- run_id: ctx.runId,
913
- ...input,
914
- });
915
- ctx.onEvent?.(event);
916
- }
917
- }
918
-
919
- function inferSideEffectClass(node: GraphNode): PolicyContext['side_effect_class'] {
920
- if (node.mutation_scope.length > 0) return 'write_fs';
921
- if (node.actions.some((action) => action.type === 'run_tests' || action.type === 'run_lint')) return 'spawn_process';
922
- return 'read_fs';
923
- }
924
-
925
- function pickPrimaryAction(node: GraphNode, pluginRegistry?: PluginRegistry): GraphNode['actions'][number] | undefined {
926
- const candidateActions = node.actions.filter((action) => action.type !== 'collect_evidence');
927
- const preferredMutation = candidateActions.find((action) => action.type === 'generate_patch')
928
- || candidateActions.find((action) => action.type === 'run_tests')
929
- || candidateActions[0];
930
- if (!pluginRegistry) return preferredMutation;
931
- return candidateActions.find((action) => pluginRegistry.toolProviderFor(action.type)) || preferredMutation;
932
- }
933
-
934
- function inferGateScope(node: GraphNode): 'critical_mutation' | 'security' | 'plan_approval' {
935
- if (node.mutation_scope.length > 0) return 'critical_mutation';
936
- if (node.actions.some((action) => action.type === 'collect_evidence')) return 'security';
937
- return 'plan_approval';
938
- }
1
+ import path from 'path';
2
+ import fs from 'fs';
3
+ import { appendEvent } from '../events/bus';
4
+ import type { OxeEvent } from '../events/envelope';
5
+ import type { EventInput } from '../events/bus';
6
+ import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
7
+ import type { WorkspaceManager, WorkspaceRequest } from '../workspace/workspace-manager';
8
+ import type { WorkspaceLease } from '../models/workspace';
9
+ import type { GateManager } from '../gate/gate-manager';
10
+ import type { PolicyEngine, PersistedPolicyDecision, PolicyContext } from '../policy/policy-engine';
11
+ import { savePolicyDecision } from '../policy/policy-engine';
12
+ import type { PluginRegistry } from '../plugins/plugin-registry';
13
+ import type { AuditTrail } from '../audit/audit-trail';
14
+ import type { RunQuota, QuotaViolation } from '../audit/audit-trail';
15
+ import { checkQuota, consumeQuota } from '../audit/audit-trail';
16
+ import {
17
+ saveJournal,
18
+ loadJournal,
19
+ deleteJournal,
20
+ createJournal,
21
+ } from './run-journal';
22
+ import type { RunJournal } from './run-journal';
23
+ import type { FailureClass } from '../models/failure';
24
+ import { listMemos } from '../decision/decision-memo';
25
+ import type { RollbackPlan } from '../decision/decision-memo';
26
+ import { runCapabilityAsync } from '../plugins/capability-adapter';
27
+ import { verifyRun } from '../verification/verification-compiler';
28
+ import type { AcceptanceCheckSuite, CheckResult } from '../verification/verification-compiler';
29
+
30
+ export interface TaskResult {
31
+ success: boolean;
32
+ failure_class: FailureClass;
33
+ evidence: string[];
34
+ output: string;
35
+ completed_by?: string;
36
+ }
37
+
38
+ export interface TaskExecutor {
39
+ execute(
40
+ node: GraphNode,
41
+ lease: WorkspaceLease,
42
+ runId: string,
43
+ attemptNumber: number,
44
+ options?: { previousError?: string | null; maxTurns?: number | null }
45
+ ): Promise<TaskResult>;
46
+ }
47
+
48
+ /**
49
+ * Turn/cost ceiling of a run (1.21, OXB-023), kept by the caller from the executor's usage. The scheduler checks it
50
+ * between attempts — never killing one mid-way — and caps the next attempt to the turns that are left, so the run
51
+ * cannot go past the turn ceiling.
52
+ */
53
+ export interface RunBudget {
54
+ /** Why no further attempt may start, or null while there is budget. */
55
+ exhausted(): string | null;
56
+ /** Turns still allowed (the next attempt's cap), or null when turns are unlimited. */
57
+ remainingTurns(): number | null;
58
+ }
59
+
60
+ export interface SchedulerOptions {
61
+ maxRunDurationMs?: number; // default: 30 min
62
+ staleProgressMs?: number; // default: 5 min without any task completing
63
+ }
64
+
65
+ export interface SchedulerContext {
66
+ projectRoot: string;
67
+ sessionId: string | null;
68
+ runId: string;
69
+ executor: TaskExecutor;
70
+ workspaceManager: WorkspaceManager;
71
+ gateManager?: GateManager;
72
+ policyEngine?: PolicyEngine;
73
+ pluginRegistry?: PluginRegistry;
74
+ auditTrail?: AuditTrail;
75
+ quota?: RunQuota;
76
+ budget?: RunBudget;
77
+ policyActor?: string;
78
+ onEvent?: (event: OxeEvent) => void;
79
+ options?: SchedulerOptions;
80
+ }
81
+
82
+ export interface RunResult {
83
+ run_id: string;
84
+ status: 'completed' | 'failed' | 'blocked' | 'cancelled' | 'paused' | 'aborted';
85
+ completed: string[];
86
+ failed: string[];
87
+ blocked: string[];
88
+ pending_gates?: string[];
89
+ reason?: string;
90
+ }
91
+
92
+ type NodeStatus = 'pending' | 'ready' | 'running' | 'completed' | 'failed' | 'blocked';
93
+
94
+ export class Scheduler {
95
+ private cancelled = false;
96
+ private paused = false;
97
+ private journal: RunJournal | null = null;
98
+ private ctx: SchedulerContext | null = null;
99
+ private runStartMs = 0;
100
+ private lastProgressMs = 0;
101
+
102
+ private recordProgress(): void {
103
+ this.lastProgressMs = Date.now();
104
+ }
105
+
106
+ private async executeRollback(plan: RollbackPlan, ctx: SchedulerContext): Promise<void> {
107
+ try {
108
+ switch (plan.strategy) {
109
+ case 'revert_commit':
110
+ await runCapabilityAsync('git', ['revert', 'HEAD', '--no-edit'], {}, ctx.projectRoot, 30_000);
111
+ break;
112
+ case 'restore_workspace':
113
+ await runCapabilityAsync('git', ['checkout', '.'], {}, ctx.projectRoot, 30_000);
114
+ break;
115
+ case 'undo_patch':
116
+ for (const p of plan.steps) {
117
+ await runCapabilityAsync('git', ['checkout', 'HEAD', '--', p], {}, ctx.projectRoot, 10_000);
118
+ }
119
+ break;
120
+ case 'no_rollback':
121
+ default:
122
+ break;
123
+ }
124
+ this.emit(ctx, { type: 'RollbackExecuted', payload: { strategy: plan.strategy } });
125
+ } catch (err) {
126
+ this.emit(ctx, { type: 'RollbackFailed', payload: { strategy: plan.strategy, error: String(err) } });
127
+ }
128
+ }
129
+
130
+ async run(graph: ExecutionGraph, ctx: SchedulerContext): Promise<RunResult> {
131
+ this.cancelled = false;
132
+ this.paused = false;
133
+ this.ctx = ctx;
134
+ this.runStartMs = Date.now();
135
+ this.lastProgressMs = Date.now();
136
+
137
+ const status = new Map<string, NodeStatus>();
138
+ for (const id of graph.nodes.keys()) status.set(id, 'pending');
139
+
140
+ const completed: string[] = [];
141
+ const failed: string[] = [];
142
+ const blocked: string[] = [];
143
+
144
+ // Plan hash drift detection: abort if the graph was recompiled since ACTIVE-RUN was saved
145
+ const activeRunPath = ctx.sessionId
146
+ ? path.join(ctx.projectRoot, '.oxe', ctx.sessionId, 'execution', 'ACTIVE-RUN.json')
147
+ : path.join(ctx.projectRoot, '.oxe', 'ACTIVE-RUN.json');
148
+ if (fs.existsSync(activeRunPath)) {
149
+ try {
150
+ const activeRun = JSON.parse(fs.readFileSync(activeRunPath, 'utf8')) as Record<string, unknown>;
151
+ const savedHash = activeRun.plan_hash as string | undefined;
152
+ const currentHash = graph.metadata.plan_hash;
153
+ if (savedHash && savedHash !== currentHash) {
154
+ return {
155
+ run_id: ctx.runId,
156
+ status: 'aborted',
157
+ completed: [],
158
+ failed: [],
159
+ blocked: [],
160
+ reason: `plan_drift: graph recompiled (${savedHash} → ${currentHash}). Run /oxe-plan --replan to realign.`,
161
+ };
162
+ }
163
+ } catch {
164
+ // ACTIVE-RUN not parseable — continue without drift check
165
+ }
166
+ }
167
+
168
+ this.journal = createJournal(ctx.runId);
169
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
170
+
171
+ this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId } });
172
+ ctx.auditTrail?.record('run_started', ctx.policyActor ?? 'runtime', {
173
+ runId: ctx.runId,
174
+ detail: { session_id: ctx.sessionId ?? null },
175
+ });
176
+
177
+ const maxRunMs = ctx.options?.maxRunDurationMs ?? 30 * 60_000;
178
+ const staleMs = ctx.options?.staleProgressMs ?? 5 * 60_000;
179
+
180
+ for (const wave of graph.waves) {
181
+ if (this.cancelled) break;
182
+
183
+ // Global run timeout
184
+ if (Date.now() - this.runStartMs > maxRunMs) {
185
+ return this.abortRun(ctx, 'global_timeout', completed, failed, blocked);
186
+ }
187
+
188
+ // Stale progress timeout (no task completed in staleMs)
189
+ if (Date.now() - this.lastProgressMs > staleMs) {
190
+ return this.abortRun(ctx, 'no_progress_timeout', completed, failed, blocked);
191
+ }
192
+
193
+ // Respect pause: persist journal and return paused result
194
+ if (this.paused) {
195
+ this.journal.scheduler_state = 'paused';
196
+ this.journal.paused_at = new Date().toISOString();
197
+ this.journal.completed_work_items = completed.slice();
198
+ this.journal.failed_work_items = failed.slice();
199
+ this.journal.blocked_work_items = blocked.slice();
200
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
201
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
202
+ ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
203
+ runId: ctx.runId,
204
+ detail: { completed, failed, blocked },
205
+ });
206
+ return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
207
+ }
208
+
209
+ const waveFailed = await this.runWave(
210
+ wave.node_ids,
211
+ graph,
212
+ ctx,
213
+ status,
214
+ completed,
215
+ failed,
216
+ blocked
217
+ );
218
+
219
+ // Sync journal after each wave
220
+ this.journal.completed_work_items = completed.slice();
221
+ this.journal.failed_work_items = failed.slice();
222
+ this.journal.blocked_work_items = blocked.slice();
223
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
224
+
225
+ if (waveFailed) {
226
+ // Execute rollback plan if one was created for this run
227
+ const memos = listMemos(ctx.projectRoot, ctx.runId);
228
+ for (const memo of memos) {
229
+ if (memo.rollback_plan.strategy !== 'no_rollback') {
230
+ await this.executeRollback(memo.rollback_plan, ctx);
231
+ break; // apply at most one rollback plan per wave failure
232
+ }
233
+ }
234
+ break;
235
+ }
236
+ }
237
+
238
+ // Any remaining pending nodes become blocked
239
+ for (const [id, s] of status) {
240
+ if (s === 'pending') {
241
+ status.set(id, 'blocked');
242
+ blocked.push(id);
243
+ this.emit(ctx, {
244
+ type: 'WorkItemBlocked',
245
+ work_item_id: id,
246
+ payload: { reason: 'upstream_wave_failed' },
247
+ });
248
+ }
249
+ }
250
+
251
+ const finalStatus: RunResult['status'] = this.cancelled
252
+ ? 'cancelled'
253
+ : failed.length > 0
254
+ ? 'failed'
255
+ : blocked.length > 0
256
+ ? 'blocked'
257
+ : 'completed';
258
+
259
+ this.emit(ctx, {
260
+ type: 'RunCompleted',
261
+ payload: { run_id: ctx.runId, status: finalStatus },
262
+ });
263
+ ctx.auditTrail?.record('run_completed', ctx.policyActor ?? 'runtime', {
264
+ runId: ctx.runId,
265
+ detail: {
266
+ status: finalStatus,
267
+ completed: completed.length,
268
+ failed: failed.length,
269
+ blocked: blocked.length,
270
+ pending_gates: this.journal.pending_gates.slice(),
271
+ },
272
+ });
273
+
274
+ this.journal.scheduler_state = this.cancelled
275
+ ? 'cancelled'
276
+ : finalStatus === 'blocked' || finalStatus === 'failed'
277
+ ? finalStatus
278
+ : 'completed';
279
+ this.journal.completed_work_items = completed.slice();
280
+ this.journal.failed_work_items = failed.slice();
281
+ this.journal.blocked_work_items = blocked.slice();
282
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
283
+
284
+ return {
285
+ run_id: ctx.runId,
286
+ status: finalStatus,
287
+ completed,
288
+ failed,
289
+ blocked,
290
+ pending_gates: this.journal.pending_gates.slice(),
291
+ };
292
+ }
293
+
294
+ /**
295
+ * Recover a previously paused run by loading its journal and re-running
296
+ * only the work items that haven't completed yet.
297
+ */
298
+ async recover(runId: string, ctx: SchedulerContext, graph: ExecutionGraph): Promise<RunResult | null> {
299
+ const journal = loadJournal(ctx.projectRoot, runId);
300
+ // Paused, blocked (gates since approved), aborted (timeout) and failed runs can all be resumed;
301
+ // only completed/cancelled runs have nothing left to do.
302
+ if (!journal || !RECOVERABLE_JOURNAL_STATES.has(journal.scheduler_state)) return null;
303
+
304
+ // Restore state from journal
305
+ this.cancelled = false;
306
+ this.paused = false;
307
+ this.ctx = ctx;
308
+ this.journal = { ...journal, scheduler_state: 'running', paused_at: null };
309
+
310
+ const restoredCompleted = new Set(journal.completed_work_items);
311
+ const restoredFailed = new Set(journal.failed_work_items);
312
+ const restoredBlocked = new Set(journal.blocked_work_items);
313
+
314
+ const status = new Map<string, NodeStatus>();
315
+ for (const id of graph.nodes.keys()) {
316
+ if (restoredCompleted.has(id)) status.set(id, 'completed');
317
+ else if (restoredFailed.has(id)) status.set(id, 'failed');
318
+ else if (restoredBlocked.has(id)) status.set(id, 'blocked');
319
+ else status.set(id, 'pending');
320
+ }
321
+
322
+ const completed = [...restoredCompleted];
323
+ const failed = [...restoredFailed];
324
+ const blocked = [...restoredBlocked];
325
+
326
+ saveJournal(ctx.projectRoot, runId, this.journal);
327
+
328
+ this.emit(ctx, { type: 'RunStarted', payload: { run_id: ctx.runId, recovered: true } });
329
+
330
+ for (const wave of graph.waves) {
331
+ if (this.cancelled) break;
332
+ if (this.paused) {
333
+ this.journal.scheduler_state = 'paused';
334
+ this.journal.paused_at = new Date().toISOString();
335
+ this.journal.completed_work_items = completed.slice();
336
+ this.journal.failed_work_items = failed.slice();
337
+ this.journal.blocked_work_items = blocked.slice();
338
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
339
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
340
+ ctx.auditTrail?.record('run_paused', ctx.policyActor ?? 'runtime', {
341
+ runId: ctx.runId,
342
+ detail: { recovered: true, completed, failed, blocked },
343
+ });
344
+ return { run_id: ctx.runId, status: 'paused', completed, failed, blocked, pending_gates: this.journal.pending_gates.slice() };
345
+ }
346
+
347
+ // Skip waves fully completed
348
+ const allDone = wave.node_ids.every(
349
+ (id) => restoredCompleted.has(id) || restoredFailed.has(id) || restoredBlocked.has(id)
350
+ );
351
+ if (allDone) continue;
352
+
353
+ const waveFailed = await this.runWave(
354
+ wave.node_ids,
355
+ graph,
356
+ ctx,
357
+ status,
358
+ completed,
359
+ failed,
360
+ blocked
361
+ );
362
+
363
+ this.journal.completed_work_items = completed.slice();
364
+ this.journal.failed_work_items = failed.slice();
365
+ this.journal.blocked_work_items = blocked.slice();
366
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
367
+
368
+ if (waveFailed) break;
369
+ }
370
+
371
+ for (const [id, s] of status) {
372
+ if (s === 'pending') {
373
+ status.set(id, 'blocked');
374
+ blocked.push(id);
375
+ this.emit(ctx, {
376
+ type: 'WorkItemBlocked',
377
+ work_item_id: id,
378
+ payload: { reason: 'upstream_wave_failed' },
379
+ });
380
+ }
381
+ }
382
+
383
+ const finalStatus: RunResult['status'] = this.cancelled
384
+ ? 'cancelled'
385
+ : failed.length > 0
386
+ ? 'failed'
387
+ : blocked.length > 0
388
+ ? 'blocked'
389
+ : 'completed';
390
+
391
+ this.emit(ctx, {
392
+ type: 'RunCompleted',
393
+ payload: { run_id: ctx.runId, status: finalStatus, recovered: true },
394
+ });
395
+ ctx.auditTrail?.record('run_recovered', ctx.policyActor ?? 'runtime', {
396
+ runId: ctx.runId,
397
+ detail: {
398
+ status: finalStatus,
399
+ completed: completed.length,
400
+ failed: failed.length,
401
+ blocked: blocked.length,
402
+ pending_gates: this.journal.pending_gates.slice(),
403
+ },
404
+ });
405
+
406
+ this.journal.scheduler_state = this.cancelled
407
+ ? 'cancelled'
408
+ : finalStatus === 'blocked' || finalStatus === 'failed'
409
+ ? finalStatus
410
+ : 'completed';
411
+ this.journal.completed_work_items = completed.slice();
412
+ this.journal.failed_work_items = failed.slice();
413
+ this.journal.blocked_work_items = blocked.slice();
414
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
415
+ deleteJournal(ctx.projectRoot, ctx.runId);
416
+
417
+ return {
418
+ run_id: ctx.runId,
419
+ status: finalStatus,
420
+ completed,
421
+ failed,
422
+ blocked,
423
+ pending_gates: this.journal.pending_gates.slice(),
424
+ };
425
+ }
426
+
427
+ private isConcurrentSafe(nodeId: string, graph: ExecutionGraph, ctx: SchedulerContext): boolean {
428
+ const node = graph.nodes.get(nodeId)!;
429
+ if (node.mutation_scope.length > 0) return false;
430
+ // A node that may write files but declares no scope is not provably safe to run in parallel
431
+ // (an empty scope used to mean "run everything in parallel, in place").
432
+ if (nodeMayMutate(node)) return false;
433
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
434
+ if (!primaryAction) return true;
435
+ const provider = ctx.pluginRegistry?.toolProviderFor(primaryAction.type);
436
+ return provider?.idempotent ?? true;
437
+ }
438
+
439
+ private async runWave(
440
+ nodeIds: string[],
441
+ graph: ExecutionGraph,
442
+ ctx: SchedulerContext,
443
+ status: Map<string, NodeStatus>,
444
+ completed: string[],
445
+ failed: string[],
446
+ blocked: string[]
447
+ ): Promise<boolean> {
448
+ const eligible: string[] = [];
449
+ const depsNotMet: string[] = [];
450
+
451
+ for (const id of nodeIds) {
452
+ if (status.get(id) === 'completed') continue; // already done in recovery
453
+ const node = graph.nodes.get(id)!;
454
+ const depsMet = node.depends_on.every((dep) => status.get(dep) === 'completed');
455
+ if (depsMet) {
456
+ eligible.push(id);
457
+ } else {
458
+ depsNotMet.push(id);
459
+ }
460
+ }
461
+
462
+ for (const id of depsNotMet) {
463
+ status.set(id, 'blocked');
464
+ blocked.push(id);
465
+ this.emit(ctx, {
466
+ type: 'WorkItemBlocked',
467
+ work_item_id: id,
468
+ payload: { reason: 'dependency_not_met' },
469
+ });
470
+ }
471
+
472
+ for (const id of eligible) {
473
+ const node = graph.nodes.get(id)!;
474
+ if (node.mutation_scope.length === 0 && nodeMayMutate(node)) {
475
+ this.emit(ctx, {
476
+ type: 'PolicyWarning',
477
+ work_item_id: id,
478
+ payload: {
479
+ reason: 'empty_mutation_scope',
480
+ detail: 'node may write files but declares no mutation_scope; running serially and without scope checks',
481
+ },
482
+ });
483
+ }
484
+ }
485
+
486
+ const readOnly = eligible.filter((id) => this.isConcurrentSafe(id, graph, ctx));
487
+ const mutations = eligible.filter((id) => !readOnly.includes(id));
488
+
489
+ if (readOnly.length > 0) {
490
+ await Promise.all(
491
+ readOnly.map((id) => this.runNode(id, graph, ctx, status, completed, failed, blocked))
492
+ );
493
+ }
494
+
495
+ for (const id of mutations) {
496
+ if (this.cancelled) break;
497
+ await this.runNode(id, graph, ctx, status, completed, failed, blocked);
498
+ }
499
+
500
+ return failed.length > 0;
501
+ }
502
+
503
+ private async runNode(
504
+ nodeId: string,
505
+ graph: ExecutionGraph,
506
+ ctx: SchedulerContext,
507
+ status: Map<string, NodeStatus>,
508
+ completed: string[],
509
+ failed: string[],
510
+ blocked: string[]
511
+ ): Promise<void> {
512
+ const node = graph.nodes.get(nodeId)!;
513
+ status.set(nodeId, 'running');
514
+ this.emit(ctx, {
515
+ type: 'WorkItemReady',
516
+ work_item_id: nodeId,
517
+ payload: { title: node.title, wave: node.wave },
518
+ });
519
+
520
+ let lease: WorkspaceLease | null = null;
521
+ // Dispose through the manager that allocated the lease (plugin provider or default).
522
+ let leaseManager: WorkspaceManager | null = null;
523
+ let lastResult: TaskResult | null = null;
524
+ let lastError: string | null = null;
525
+ // 1.20c: the same verify failure twice (normalized output) = suspect ruler or stuck executor: stop paying retries.
526
+ let lastVerifySignature: string | null = null;
527
+ let verifySuspect = false;
528
+ const maxAttempts = node.policy.max_retries + 1;
529
+ // 1.21.1 (OXB-047): work that arrives by another path never pays an agent and never becomes a human gate.
530
+ // An explicit human gate (PLAN.json `gate`) still comes first: the attempt loop requests it as before.
531
+ const humanGatePending = node.policy.requires_human_approval && !this.hasApprovedGate(node, ctx);
532
+ if (!humanGatePending && (node.policy.verify_only || (node.policy.external_dependency?.length ?? 0) > 0)) {
533
+ await this.runExternalNode(node, ctx, status, completed, failed, blocked);
534
+ return;
535
+ }
536
+ const quotaBlocked = this.consumeQuotaForNode(ctx, node);
537
+ if (quotaBlocked) {
538
+ this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', quotaBlocked);
539
+ return;
540
+ }
541
+
542
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
543
+ const attemptId = `${nodeId}-a${attempt}`;
544
+
545
+ this.emit(ctx, {
546
+ type: 'AttemptStarted',
547
+ work_item_id: nodeId,
548
+ attempt_id: attemptId,
549
+ payload: { attempt_number: attempt },
550
+ });
551
+
552
+ try {
553
+ const policyDecision = this.evaluatePolicyForNode(node, ctx);
554
+ if (policyDecision && !policyDecision.allowed) {
555
+ this.emit(ctx, {
556
+ type: 'PolicyEvaluated',
557
+ work_item_id: nodeId,
558
+ attempt_id: attemptId,
559
+ payload: { ...policyDecision },
560
+ });
561
+ ctx.auditTrail?.record('policy_denied', ctx.policyActor ?? 'runtime', {
562
+ runId: ctx.runId,
563
+ workItemId: nodeId,
564
+ detail: { reason: policyDecision.reason, rule_id: policyDecision.rule_id },
565
+ });
566
+ this.blockNode(nodeId, ctx, status, blocked, 'policy_denied', policyDecision.reason);
567
+ return;
568
+ }
569
+
570
+ if (policyDecision) {
571
+ this.emit(ctx, {
572
+ type: 'PolicyEvaluated',
573
+ work_item_id: nodeId,
574
+ attempt_id: attemptId,
575
+ payload: { ...policyDecision },
576
+ });
577
+ }
578
+
579
+ if ((policyDecision?.gate_required || node.policy.requires_human_approval) && !this.hasApprovedGate(node, ctx)) {
580
+ const gateId = await this.requestGateForNode(node, ctx, policyDecision);
581
+ this.blockNode(nodeId, ctx, status, blocked, 'pending_gate', gateId);
582
+ return;
583
+ }
584
+
585
+ // OXB-023: the run's turn/cost ceiling is checked before every attempt, never in the middle of one.
586
+ const budgetReason = ctx.budget?.exhausted() ?? null;
587
+ if (budgetReason) {
588
+ this.emit(ctx, {
589
+ type: 'BudgetExhausted',
590
+ work_item_id: nodeId,
591
+ attempt_id: attemptId,
592
+ payload: { reason: budgetReason, attempt_number: attempt },
593
+ });
594
+ this.blockNode(nodeId, ctx, status, blocked, 'budget_exhausted', budgetReason);
595
+ return;
596
+ }
597
+ const turnsLeft = ctx.budget?.remainingTurns() ?? null;
598
+
599
+ const wsReq: WorkspaceRequest = {
600
+ work_item_id: nodeId,
601
+ attempt_number: attempt,
602
+ strategy: node.workspace_strategy,
603
+ mutation_scope: node.mutation_scope,
604
+ };
605
+ const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
606
+ leaseManager = workspaceManager;
607
+ lease = await workspaceManager.allocate(wsReq);
608
+ this.emit(ctx, {
609
+ type: 'WorkspaceAllocated',
610
+ work_item_id: nodeId,
611
+ attempt_id: attemptId,
612
+ payload: { workspace_id: lease.workspace_id, strategy: lease.strategy },
613
+ });
614
+
615
+ lastResult = await this.executeNode(node, lease, ctx, attempt, attemptId, {
616
+ previousError: lastError,
617
+ ...(turnsLeft != null ? { maxTurns: turnsLeft } : {}),
618
+ });
619
+
620
+ // OXB-026: the verify judges the work, not the end of the LLM conversation. An attempt that ran out of turns
621
+ // after writing in its scope is verified before it is classified: green completes the task, red goes to the
622
+ // informed retry. Discarding it unverified paid a whole second attempt for finished work.
623
+ const turnLimitWithWork = !lastResult.success
624
+ && lastResult.completed_by === 'turn_limit_exhausted'
625
+ && Boolean(node.verify?.command)
626
+ && (lastResult.evidence?.length ?? 0) > 0;
627
+
628
+ if (lastResult.success || turnLimitWithWork) {
629
+ const verifyResult = await this.verifyNode(node, lease, ctx, attemptId, attempt);
630
+ if (verifyResult && verifyResult.status === 'failed') {
631
+ // Informed retry: the next attempt sees the command, the reason and the output — not just "failed".
632
+ lastResult = {
633
+ success: false,
634
+ failure_class: 'verify',
635
+ evidence: lastResult.evidence,
636
+ output: describeVerifyFailure(node.verify.command, verifyResult.check, verifyResult.gaps),
637
+ };
638
+ const signature = verifyFailureSignature(verifyResult.check);
639
+ if (signature && signature === lastVerifySignature) {
640
+ verifySuspect = true;
641
+ this.emit(ctx, {
642
+ type: 'VerifyCommandSuspect',
643
+ work_item_id: nodeId,
644
+ attempt_id: attemptId,
645
+ payload: {
646
+ attempt_number: attempt,
647
+ command: node.verify.command,
648
+ excerpt: tailLines(`${verifyResult.check?.error ?? ''}\n${verifyResult.check?.stderr ?? ''}\n${verifyResult.check?.stdout ?? ''}`, 12),
649
+ reason: 'identical_verify_failure',
650
+ },
651
+ });
652
+ break;
653
+ }
654
+ lastVerifySignature = signature;
655
+ } else {
656
+ this.emit(ctx, {
657
+ type: 'WorkItemCompleted',
658
+ work_item_id: nodeId,
659
+ attempt_id: attemptId,
660
+ payload: {
661
+ attempt_number: attempt,
662
+ evidence: lastResult.evidence,
663
+ ...(turnLimitWithWork ? { completed_by: 'verify_after_turn_limit' } : {}),
664
+ },
665
+ });
666
+ status.set(nodeId, 'completed');
667
+ completed.push(nodeId);
668
+ this.recordProgress();
669
+ return;
670
+ }
671
+ }
672
+
673
+ lastError = lastResult.output || (lastResult.failure_class ?? 'unknown error');
674
+
675
+ if (lastResult.failure_class === 'policy') break;
676
+
677
+ if (attempt < maxAttempts) {
678
+ const retryBlocked = this.consumeRetryQuota(ctx);
679
+ if (retryBlocked) {
680
+ this.blockNode(nodeId, ctx, status, blocked, 'quota_exceeded', retryBlocked);
681
+ return;
682
+ }
683
+ // Exponential backoff with jitter: 1s * 2^(attempt-1) + [0, 500ms], capped at 30s
684
+ const backoffMs = Math.min(
685
+ 1_000 * Math.pow(2, attempt - 1) + Math.random() * 500,
686
+ 30_000
687
+ );
688
+ await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
689
+ this.emit(ctx, {
690
+ type: 'RetryScheduled',
691
+ work_item_id: nodeId,
692
+ payload: { next_attempt: attempt + 1, reason: lastResult.failure_class, backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
693
+ });
694
+ }
695
+ } catch (err: unknown) {
696
+ // Error boundary: isolate task failure, emit structured event, do not crash scheduler
697
+ const message = err instanceof Error ? err.message : String(err);
698
+ const stack = err instanceof Error ? err.stack : undefined;
699
+ this.emit(ctx, {
700
+ type: 'TaskErrorBoundaryTripped',
701
+ work_item_id: nodeId,
702
+ payload: { message, stack, attempt },
703
+ });
704
+ lastResult = {
705
+ success: false,
706
+ failure_class: 'env',
707
+ evidence: [],
708
+ output: `[error_boundary] ${message}`,
709
+ };
710
+ lastError = lastResult.output;
711
+ if (attempt < maxAttempts) {
712
+ const backoffMs = Math.min(1_000 * Math.pow(2, attempt - 1) + Math.random() * 500, 30_000);
713
+ await new Promise<void>(resolve => setTimeout(resolve, backoffMs));
714
+ this.emit(ctx, {
715
+ type: 'RetryScheduled',
716
+ work_item_id: nodeId,
717
+ payload: { next_attempt: attempt + 1, reason: 'env', backoff_ms: backoffMs, output_tail: tailLines(lastResult.output || '', 60) },
718
+ });
719
+ }
720
+ } finally {
721
+ if (lease) {
722
+ await (leaseManager ?? ctx.workspaceManager).dispose(lease.workspace_id).catch((e: unknown) =>
723
+ this.emit(ctx!, { type: 'WorkspaceDisposeFailed', payload: { workspace_id: lease?.workspace_id, error: String(e) } })
724
+ );
725
+ lease = null;
726
+ leaseManager = null;
727
+ }
728
+ }
729
+ }
730
+
731
+ this.emit(ctx, {
732
+ type: 'WorkItemBlocked',
733
+ work_item_id: nodeId,
734
+ payload: { failure_class: verifySuspect ? 'verify_suspect' : lastResult?.failure_class ?? 'env', max_attempts: maxAttempts, output_tail: tailLines(lastResult?.output || '', 60) },
735
+ });
736
+ status.set(nodeId, 'failed');
737
+ failed.push(nodeId);
738
+ }
739
+
740
+ /** Abort keeps the progress made so far: an aborted run is recoverable, not a blank slate. */
741
+ private abortRun(
742
+ ctx: SchedulerContext,
743
+ reason: string,
744
+ completed: string[],
745
+ failed: string[],
746
+ blocked: string[]
747
+ ): RunResult {
748
+ this.emit(ctx, { type: 'RunAborted', payload: { reason, completed: completed.slice(), failed: failed.slice(), blocked: blocked.slice() } });
749
+ if (this.journal) {
750
+ this.journal.scheduler_state = 'aborted';
751
+ this.journal.completed_work_items = completed.slice();
752
+ this.journal.failed_work_items = failed.slice();
753
+ this.journal.blocked_work_items = blocked.slice();
754
+ this.journal.partial_result = { run_id: ctx.runId, completed, failed, blocked };
755
+ saveJournal(ctx.projectRoot, ctx.runId, this.journal);
756
+ }
757
+ return { run_id: ctx.runId, status: 'aborted', completed, failed, blocked, reason };
758
+ }
759
+
760
+ pause(): void {
761
+ this.paused = true;
762
+ if (this.journal && this.ctx) {
763
+ this.journal.scheduler_state = 'paused';
764
+ this.journal.paused_at = new Date().toISOString();
765
+ saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
766
+ }
767
+ }
768
+
769
+ resume(): void {
770
+ this.paused = false;
771
+ if (this.journal && this.ctx) {
772
+ this.journal.scheduler_state = 'running';
773
+ this.journal.paused_at = null;
774
+ saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
775
+ }
776
+ }
777
+
778
+ cancel(): void {
779
+ this.cancelled = true;
780
+ if (this.journal && this.ctx) {
781
+ this.journal.cancelled = true;
782
+ this.journal.scheduler_state = 'cancelled';
783
+ saveJournal(this.ctx.projectRoot, this.ctx.runId, this.journal);
784
+ }
785
+ }
786
+
787
+ getJournal(): RunJournal | null {
788
+ return this.journal;
789
+ }
790
+
791
+ static loadJournal(projectRoot: string, runId: string): RunJournal | null {
792
+ return loadJournal(projectRoot, runId);
793
+ }
794
+
795
+ private async executeNode(
796
+ node: GraphNode,
797
+ lease: WorkspaceLease,
798
+ ctx: SchedulerContext,
799
+ attempt: number,
800
+ attemptId: string,
801
+ options: { previousError?: string | null; maxTurns?: number | null } = {},
802
+ ): Promise<TaskResult> {
803
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
804
+ const provider = primaryAction ? ctx.pluginRegistry?.toolProviderFor(primaryAction.type) : null;
805
+ if (!provider || !primaryAction) {
806
+ return ctx.executor.execute(node, lease, ctx.runId, attempt, options);
807
+ }
808
+
809
+ ctx.auditTrail?.record('plugin_invoked', ctx.policyActor ?? 'runtime', {
810
+ runId: ctx.runId,
811
+ workItemId: node.id,
812
+ resource: provider.name,
813
+ detail: { action_type: primaryAction.type, attempt_id: attemptId },
814
+ });
815
+ this.emit(ctx, {
816
+ type: 'ToolInvoked',
817
+ work_item_id: node.id,
818
+ attempt_id: attemptId,
819
+ payload: { provider: provider.name, action_type: primaryAction.type },
820
+ });
821
+
822
+ const invocationInput = {
823
+ action_type: primaryAction.type,
824
+ work_item_id: node.id,
825
+ run_id: ctx.runId,
826
+ attempt_id: attemptId,
827
+ params: {
828
+ command: primaryAction.command ?? null,
829
+ targets: primaryAction.targets ?? [],
830
+ },
831
+ workspace_root: lease.root_path,
832
+ };
833
+
834
+ if (provider.preInvoke) {
835
+ const preCheck = await provider.preInvoke(invocationInput);
836
+ if (!preCheck.allowed) {
837
+ this.emit(ctx, {
838
+ type: 'ToolFailed',
839
+ work_item_id: node.id,
840
+ attempt_id: attemptId,
841
+ payload: { provider: provider.name, action_type: primaryAction.type, error: preCheck.reason ?? 'pre_invoke blocked', evidence_paths: [], side_effects_applied: [] },
842
+ });
843
+ return { success: false, failure_class: 'policy', evidence: [], output: preCheck.reason ?? 'pre_invoke blocked' };
844
+ }
845
+ }
846
+
847
+ const result = await provider.invoke(invocationInput);
848
+
849
+ if (provider.postInvoke) {
850
+ await provider.postInvoke(invocationInput, result).catch(() => {});
851
+ }
852
+
853
+ this.emit(ctx, {
854
+ type: result.success ? 'ToolCompleted' : 'ToolFailed',
855
+ work_item_id: node.id,
856
+ attempt_id: attemptId,
857
+ payload: {
858
+ provider: provider.name,
859
+ action_type: primaryAction.type,
860
+ evidence_paths: result.evidence_paths,
861
+ side_effects_applied: result.side_effects_applied,
862
+ error: result.error ?? null,
863
+ },
864
+ });
865
+
866
+ return {
867
+ success: result.success,
868
+ failure_class: result.success ? null : provider.kind === 'external_operation' ? 'policy' : 'env',
869
+ evidence: result.evidence_paths,
870
+ output: result.output,
871
+ };
872
+ }
873
+
874
+ private async verifyNode(
875
+ node: GraphNode,
876
+ lease: WorkspaceLease,
877
+ ctx: SchedulerContext,
878
+ attemptId: string,
879
+ attempt: number,
880
+ ): Promise<{ status: string; gaps?: string[]; check?: CheckResult } | null> {
881
+ if (!node.verify?.command) return null;
882
+ this.emit(ctx, {
883
+ type: 'VerificationStarted',
884
+ work_item_id: node.id,
885
+ payload: { command: node.verify.command, attempt_number: attempt },
886
+ });
887
+ const suite: AcceptanceCheckSuite = {
888
+ checks: [{
889
+ id: `inline-${node.id}`,
890
+ type: 'custom',
891
+ command: node.verify.command,
892
+ evidence_type_expected: 'stdout',
893
+ acceptance_ref: null,
894
+ description: `Verify ${node.id}`,
895
+ }],
896
+ compiled_at: new Date().toISOString(),
897
+ spec_hash: '',
898
+ plan_hash: '',
899
+ };
900
+ let result: { status: string; gaps?: string[]; check_results?: CheckResult[] };
901
+ try {
902
+ result = await verifyRun({
903
+ suite,
904
+ cwd: lease.root_path,
905
+ timeoutMs: (ctx.options as Record<string, unknown>)?.verifyTimeoutMs as number ?? 60_000,
906
+ runId: ctx.runId,
907
+ workItemId: node.id,
908
+ attemptNumber: attempt,
909
+ projectRoot: ctx.projectRoot,
910
+ pluginRegistry: ctx.pluginRegistry,
911
+ });
912
+ } catch (err) {
913
+ this.emit(ctx, {
914
+ type: 'VerificationCompleted',
915
+ work_item_id: node.id,
916
+ attempt_id: attemptId,
917
+ payload: { status: 'error', error: String(err) },
918
+ });
919
+ return null;
920
+ }
921
+ this.emit(ctx, {
922
+ type: 'VerificationCompleted',
923
+ work_item_id: node.id,
924
+ attempt_id: attemptId,
925
+ payload: { status: result.status },
926
+ });
927
+ return { status: result.status, gaps: result.gaps, check: result.check_results?.[0] };
928
+ }
929
+
930
+ private evaluatePolicyForNode(node: GraphNode, ctx: SchedulerContext): PersistedPolicyDecision | null {
931
+ if (!ctx.policyEngine) return null;
932
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
933
+ const decisionContext: PolicyContext = {
934
+ tool: primaryAction?.type ?? 'custom',
935
+ kind: node.workspace_strategy,
936
+ mutation_scope: node.mutation_scope,
937
+ affected_paths: node.mutation_scope,
938
+ side_effect_class: inferSideEffectClass(node),
939
+ mutation_count: node.mutation_scope.length,
940
+ node_policy: {
941
+ max_retries: node.policy.max_retries,
942
+ },
943
+ };
944
+ const evaluated = ctx.policyEngine.evaluate(decisionContext);
945
+ const persisted: PersistedPolicyDecision = {
946
+ ...evaluated,
947
+ run_id: ctx.runId,
948
+ work_item_id: node.id,
949
+ action: primaryAction?.type ?? 'custom',
950
+ actor: ctx.policyActor ?? 'runtime',
951
+ override: false,
952
+ rationale: null,
953
+ context: decisionContext,
954
+ };
955
+ savePolicyDecision(ctx.projectRoot, persisted);
956
+ return persisted;
957
+ }
958
+
959
+ /** An approval already granted for this node in this run must not be requested again on re-execution. */
960
+ private hasApprovedGate(node: GraphNode, ctx: SchedulerContext): boolean {
961
+ if (!ctx.gateManager) return false;
962
+ return ctx.gateManager
963
+ .listResolved()
964
+ .some((gate) => gate.work_item_id === node.id && gate.decision === 'approved' && (gate.run_id == null || gate.run_id === ctx.runId));
965
+ }
966
+
967
+ private async requestGateForNode(
968
+ node: GraphNode,
969
+ ctx: SchedulerContext,
970
+ decision: PersistedPolicyDecision | null
971
+ ): Promise<string> {
972
+ if (!ctx.gateManager) {
973
+ console.warn('[scheduler] ctx.gateManager not configured — gates will not be persisted');
974
+ return 'gate-missing-manager';
975
+ }
976
+ const scope = inferGateScope(node);
977
+ const primaryAction = pickPrimaryAction(node, ctx.pluginRegistry);
978
+ const gate = await ctx.gateManager.request(scope, {
979
+ run_id: ctx.runId,
980
+ work_item_id: node.id,
981
+ action: primaryAction?.type ?? 'custom',
982
+ description: `Gate required before executing ${node.id}`,
983
+ evidence_refs: [],
984
+ risks: [decision?.reason ?? node.policy.gate_reason ?? 'human approval required'],
985
+ rationale: decision?.reason ?? node.policy.gate_reason ?? 'node policy requires approval',
986
+ policy_decision_id: decision?.decision_id ?? null,
987
+ });
988
+ if (this.journal && !this.journal.pending_gates.includes(gate.gate_id)) {
989
+ this.journal.pending_gates.push(gate.gate_id);
990
+ }
991
+ ctx.auditTrail?.record('gate_requested', ctx.policyActor ?? 'runtime', {
992
+ runId: ctx.runId,
993
+ workItemId: node.id,
994
+ detail: { gate_id: gate.gate_id, scope: gate.scope, action: gate.action },
995
+ });
996
+ return gate.gate_id;
997
+ }
998
+
999
+ /**
1000
+ * A node delivered by another path (`verify_only`) or waiting on external work (`external_dependency`): no agent.
1001
+ * verify_only runs only the node's verify — green completes it; red (or no verify) leaves it waiting. A node with an
1002
+ * external dependency and no verify_only waits without a gate, so the rest of the run (and the next preflight) goes on.
1003
+ */
1004
+ private async runExternalNode(
1005
+ node: GraphNode,
1006
+ ctx: SchedulerContext,
1007
+ status: Map<string, NodeStatus>,
1008
+ completed: string[],
1009
+ failed: string[],
1010
+ blocked: string[]
1011
+ ): Promise<void> {
1012
+ const deps = node.policy.external_dependency ?? [];
1013
+ if (node.policy.verify_only && node.verify?.command) {
1014
+ const attemptId = `${node.id}-verify-only`;
1015
+ const workspaceManager = ctx.pluginRegistry?.workspaceProviderFor(node.workspace_strategy) ?? ctx.workspaceManager;
1016
+ const lease = await workspaceManager.allocate({ work_item_id: node.id, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope });
1017
+ try {
1018
+ const verdict = await this.verifyNode(node, lease, ctx, attemptId, 1);
1019
+ if (verdict && verdict.status !== 'failed') {
1020
+ this.emit(ctx, {
1021
+ type: 'WorkItemCompleted',
1022
+ work_item_id: node.id,
1023
+ attempt_id: attemptId,
1024
+ payload: { attempt_number: 1, evidence: [], completed_by: 'verify_only', external_dependency: deps },
1025
+ });
1026
+ status.set(node.id, 'completed');
1027
+ completed.push(node.id);
1028
+ this.recordProgress();
1029
+ return;
1030
+ }
1031
+ } finally {
1032
+ await workspaceManager.dispose(lease.workspace_id).catch(() => undefined);
1033
+ }
1034
+ }
1035
+ this.blockNode(node.id, ctx, status, blocked, 'external_dependency', deps.length ? deps.join(', ') : 'verify_only: entrega externa ainda não verificada');
1036
+ void failed;
1037
+ }
1038
+
1039
+ private blockNode(
1040
+ nodeId: string,
1041
+ ctx: SchedulerContext,
1042
+ status: Map<string, NodeStatus>,
1043
+ blocked: string[],
1044
+ reason: string,
1045
+ detail: string | QuotaViolation | null = null
1046
+ ): void {
1047
+ this.emit(ctx, {
1048
+ type: 'WorkItemBlocked',
1049
+ work_item_id: nodeId,
1050
+ payload: { reason, detail },
1051
+ });
1052
+ status.set(nodeId, 'blocked');
1053
+ if (!blocked.includes(nodeId)) blocked.push(nodeId);
1054
+ }
1055
+
1056
+ private consumeQuotaForNode(ctx: SchedulerContext, node: GraphNode): string | null {
1057
+ if (!ctx.quota) return null;
1058
+ let quota = consumeQuota(ctx.quota, 'work_items', 1);
1059
+ if (node.mutation_scope.length > 0) {
1060
+ quota = consumeQuota(quota, 'mutations', 1);
1061
+ }
1062
+ const violation = checkQuota(quota);
1063
+ ctx.quota = quota;
1064
+ return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
1065
+ }
1066
+
1067
+ private consumeRetryQuota(ctx: SchedulerContext): string | null {
1068
+ if (!ctx.quota) return null;
1069
+ ctx.quota = consumeQuota(ctx.quota, 'retries', 1);
1070
+ const violation = checkQuota(ctx.quota);
1071
+ return violation ? `${violation.quota_type}:${violation.consumed}/${violation.limit}` : null;
1072
+ }
1073
+
1074
+ private emit(
1075
+ ctx: SchedulerContext,
1076
+ input: EventInput
1077
+ ): void {
1078
+ const event = appendEvent(ctx.projectRoot, ctx.sessionId, {
1079
+ run_id: ctx.runId,
1080
+ ...input,
1081
+ });
1082
+ ctx.onEvent?.(event);
1083
+ }
1084
+ }
1085
+
1086
+ const RECOVERABLE_JOURNAL_STATES = new Set<RunJournal['scheduler_state']>(['paused', 'interrupted', 'blocked', 'aborted', 'failed']);
1087
+
1088
+ /** Nodes whose actions may write to the workspace (anything beyond reading and collecting evidence). */
1089
+ function nodeMayMutate(node: GraphNode): boolean {
1090
+ return node.actions.some((action) => action.type !== 'read_code' && action.type !== 'collect_evidence');
1091
+ }
1092
+
1093
+ function inferSideEffectClass(node: GraphNode): PolicyContext['side_effect_class'] {
1094
+ if (node.mutation_scope.length > 0) return 'write_fs';
1095
+ if (node.actions.some((action) => action.type === 'run_tests' || action.type === 'run_lint')) return 'spawn_process';
1096
+ return 'read_fs';
1097
+ }
1098
+
1099
+ function pickPrimaryAction(node: GraphNode, pluginRegistry?: PluginRegistry): GraphNode['actions'][number] | undefined {
1100
+ const candidateActions = node.actions.filter((action) => action.type !== 'collect_evidence');
1101
+ const preferredMutation = candidateActions.find((action) => action.type === 'generate_patch')
1102
+ || candidateActions.find((action) => action.type === 'run_tests')
1103
+ || candidateActions[0];
1104
+ if (!pluginRegistry) return preferredMutation;
1105
+ return candidateActions.find((action) => pluginRegistry.toolProviderFor(action.type)) || preferredMutation;
1106
+ }
1107
+
1108
+ function inferGateScope(node: GraphNode): 'critical_mutation' | 'security' | 'plan_approval' {
1109
+ if (node.mutation_scope.length > 0) return 'critical_mutation';
1110
+ if (node.actions.some((action) => action.type === 'collect_evidence')) return 'security';
1111
+ return 'plan_approval';
1112
+ }
1113
+
1114
+ /** Last `n` non-empty lines of a text. */
1115
+ export function tailLines(text: string, n: number): string {
1116
+ return String(text || '').split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim()).slice(-n).join('\n');
1117
+ }
1118
+
1119
+ /** What the next attempt needs to know about a failed task verify (1.20c informed retry). */
1120
+ export function describeVerifyFailure(command: string | null | undefined, check: CheckResult | undefined, gaps?: string[]): string {
1121
+ const reason = check?.error || (check?.exit_code != null ? `exit code ${check.exit_code}` : (gaps || []).join('; ') || 'checks did not pass');
1122
+ const output = tailLines(`${check?.stdout ?? ''}\n${check?.stderr ?? ''}`, 40);
1123
+ return [
1124
+ 'Verification failed after your previous attempt.',
1125
+ `Command: ${command ?? '(none)'}`,
1126
+ `Reason: ${reason}`,
1127
+ output ? `Output (last lines):\n${output.slice(-4000)}` : 'Output: (empty)',
1128
+ 'Fix the code so this exact command passes. If you are certain the command itself is wrong (not the code), stop and call finish_task explaining why — do not work around it.',
1129
+ ].join('\n');
1130
+ }
1131
+
1132
+ /** Normalized failure fingerprint: timings, timestamps, hashes and temp paths removed. */
1133
+ export function verifyFailureSignature(check: CheckResult | undefined): string | null {
1134
+ if (!check) return null;
1135
+ const raw = `${check.error ?? ''}\n${check.stderr ?? ''}\n${check.stdout ?? ''}`;
1136
+ const normalized = raw
1137
+ .replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z?/g, '<ts>')
1138
+ .replace(/\b\d+(\.\d+)?\s?(ms|s)\b/g, '<t>')
1139
+ .replace(/\b[0-9a-f]{7,64}\b/gi, '<hash>')
1140
+ .replace(/[A-Za-z]:\\[^\s'"]*|\/tmp\/[^\s'"]*/g, '<path>')
1141
+ .replace(/\s+/g, ' ')
1142
+ .trim();
1143
+ return normalized ? normalized.slice(-1200) : null;
1144
+ }