vibeman 0.0.0 → 0.0.2

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 (230) hide show
  1. package/README.md +12 -0
  2. package/dist/index.js +114 -0
  3. package/dist/runtime/api/.tsbuildinfo +1 -0
  4. package/dist/runtime/api/agent/agent-service.d.ts +224 -0
  5. package/dist/runtime/api/agent/agent-service.js +895 -0
  6. package/dist/runtime/api/agent/ai-providers/claude-code-adapter.d.ts +61 -0
  7. package/dist/runtime/api/agent/ai-providers/claude-code-adapter.js +362 -0
  8. package/dist/runtime/api/agent/ai-providers/codex-cli-provider.d.ts +34 -0
  9. package/dist/runtime/api/agent/ai-providers/codex-cli-provider.js +315 -0
  10. package/dist/runtime/api/agent/ai-providers/index.d.ts +9 -0
  11. package/dist/runtime/api/agent/ai-providers/index.js +7 -0
  12. package/dist/runtime/api/agent/ai-providers/types.d.ts +182 -0
  13. package/dist/runtime/api/agent/ai-providers/types.js +5 -0
  14. package/dist/runtime/api/agent/codex-cli-provider.test.d.ts +1 -0
  15. package/dist/runtime/api/agent/codex-cli-provider.test.js +125 -0
  16. package/dist/runtime/api/agent/core-agent-service.d.ts +119 -0
  17. package/dist/runtime/api/agent/core-agent-service.js +267 -0
  18. package/dist/runtime/api/agent/parsers.d.ts +16 -0
  19. package/dist/runtime/api/agent/parsers.js +308 -0
  20. package/dist/runtime/api/agent/prompt-service.d.ts +30 -0
  21. package/dist/runtime/api/agent/prompt-service.js +449 -0
  22. package/dist/runtime/api/agent/prompt-service.test.d.ts +1 -0
  23. package/dist/runtime/api/agent/prompt-service.test.js +230 -0
  24. package/dist/runtime/api/agent/routing-policy.d.ts +188 -0
  25. package/dist/runtime/api/agent/routing-policy.js +246 -0
  26. package/dist/runtime/api/api/router-helpers.d.ts +32 -0
  27. package/dist/runtime/api/api/router-helpers.js +31 -0
  28. package/dist/runtime/api/api/routers/ai.d.ts +188 -0
  29. package/dist/runtime/api/api/routers/ai.js +395 -0
  30. package/dist/runtime/api/api/routers/executions.d.ts +98 -0
  31. package/dist/runtime/api/api/routers/executions.js +94 -0
  32. package/dist/runtime/api/api/routers/git.d.ts +45 -0
  33. package/dist/runtime/api/api/routers/git.js +35 -0
  34. package/dist/runtime/api/api/routers/provider-config.d.ts +165 -0
  35. package/dist/runtime/api/api/routers/provider-config.js +252 -0
  36. package/dist/runtime/api/api/routers/settings.d.ts +139 -0
  37. package/dist/runtime/api/api/routers/settings.js +113 -0
  38. package/dist/runtime/api/api/routers/tasks.d.ts +141 -0
  39. package/dist/runtime/api/api/routers/tasks.js +238 -0
  40. package/dist/runtime/api/api/routers/workflows.d.ts +267 -0
  41. package/dist/runtime/api/api/routers/workflows.js +310 -0
  42. package/dist/runtime/api/api/routers/worktrees.d.ts +101 -0
  43. package/dist/runtime/api/api/routers/worktrees.js +80 -0
  44. package/dist/runtime/api/api/trpc.d.ts +118 -0
  45. package/dist/runtime/api/api/trpc.js +34 -0
  46. package/dist/runtime/api/index.d.ts +9 -0
  47. package/dist/runtime/api/index.js +117 -0
  48. package/dist/runtime/api/lib/id-generator.d.ts +70 -0
  49. package/dist/runtime/api/lib/id-generator.js +123 -0
  50. package/dist/runtime/api/lib/image-paste-drop-extension.d.ts +26 -0
  51. package/dist/runtime/api/lib/image-paste-drop-extension.js +125 -0
  52. package/dist/runtime/api/lib/local-config.d.ts +245 -0
  53. package/dist/runtime/api/lib/local-config.js +288 -0
  54. package/dist/runtime/api/lib/logger.d.ts +11 -0
  55. package/dist/runtime/api/lib/logger.js +188 -0
  56. package/dist/runtime/api/lib/markdown-utils.d.ts +8 -0
  57. package/dist/runtime/api/lib/markdown-utils.js +282 -0
  58. package/dist/runtime/api/lib/markdown-utils.test.d.ts +1 -0
  59. package/dist/runtime/api/lib/markdown-utils.test.js +348 -0
  60. package/dist/runtime/api/lib/provider-detection.d.ts +59 -0
  61. package/dist/runtime/api/lib/provider-detection.js +244 -0
  62. package/dist/runtime/api/lib/server/agent-service-singleton.d.ts +6 -0
  63. package/dist/runtime/api/lib/server/agent-service-singleton.js +27 -0
  64. package/dist/runtime/api/lib/server/bootstrap.d.ts +38 -0
  65. package/dist/runtime/api/lib/server/bootstrap.js +197 -0
  66. package/dist/runtime/api/lib/server/git-service-singleton.d.ts +6 -0
  67. package/dist/runtime/api/lib/server/git-service-singleton.js +47 -0
  68. package/dist/runtime/api/lib/server/project-root.d.ts +2 -0
  69. package/dist/runtime/api/lib/server/project-root.js +61 -0
  70. package/dist/runtime/api/lib/server/task-service-singleton.d.ts +7 -0
  71. package/dist/runtime/api/lib/server/task-service-singleton.js +58 -0
  72. package/dist/runtime/api/lib/server/vibing-orchestrator-singleton.d.ts +7 -0
  73. package/dist/runtime/api/lib/server/vibing-orchestrator-singleton.js +57 -0
  74. package/dist/runtime/api/lib/tiptap-utils.clamp-selection.test.d.ts +1 -0
  75. package/dist/runtime/api/lib/tiptap-utils.clamp-selection.test.js +27 -0
  76. package/dist/runtime/api/lib/tiptap-utils.d.ts +130 -0
  77. package/dist/runtime/api/lib/tiptap-utils.js +327 -0
  78. package/dist/runtime/api/lib/trpc/client.d.ts +1 -0
  79. package/dist/runtime/api/lib/trpc/client.js +5 -0
  80. package/dist/runtime/api/lib/trpc/server.d.ts +915 -0
  81. package/dist/runtime/api/lib/trpc/server.js +11 -0
  82. package/dist/runtime/api/lib/trpc/ws-server.d.ts +8 -0
  83. package/dist/runtime/api/lib/trpc/ws-server.js +33 -0
  84. package/dist/runtime/api/persistence/database-service.d.ts +14 -0
  85. package/dist/runtime/api/persistence/database-service.js +74 -0
  86. package/dist/runtime/api/persistence/execution-log-persistence.d.ts +90 -0
  87. package/dist/runtime/api/persistence/execution-log-persistence.js +410 -0
  88. package/dist/runtime/api/persistence/execution-log-persistence.test.d.ts +1 -0
  89. package/dist/runtime/api/persistence/execution-log-persistence.test.js +170 -0
  90. package/dist/runtime/api/router.d.ts +918 -0
  91. package/dist/runtime/api/router.js +34 -0
  92. package/dist/runtime/api/settings-service.d.ts +110 -0
  93. package/dist/runtime/api/settings-service.js +613 -0
  94. package/dist/runtime/api/tasks/file-watcher.d.ts +23 -0
  95. package/dist/runtime/api/tasks/file-watcher.js +88 -0
  96. package/dist/runtime/api/tasks/task-file-parser.d.ts +13 -0
  97. package/dist/runtime/api/tasks/task-file-parser.js +161 -0
  98. package/dist/runtime/api/tasks/task-service.d.ts +36 -0
  99. package/dist/runtime/api/tasks/task-service.js +173 -0
  100. package/dist/runtime/api/types/index.d.ts +179 -0
  101. package/dist/runtime/api/types/index.js +1 -0
  102. package/dist/runtime/api/types/settings.d.ts +81 -0
  103. package/dist/runtime/api/types/settings.js +2 -0
  104. package/dist/runtime/api/types.d.ts +2 -0
  105. package/dist/runtime/api/types.js +1 -0
  106. package/dist/runtime/api/utils/env.d.ts +6 -0
  107. package/dist/runtime/api/utils/env.js +12 -0
  108. package/dist/runtime/api/utils/stripNextEnv.d.ts +7 -0
  109. package/dist/runtime/api/utils/stripNextEnv.js +22 -0
  110. package/dist/runtime/api/utils/title-slug.d.ts +6 -0
  111. package/dist/runtime/api/utils/title-slug.js +77 -0
  112. package/dist/runtime/api/utils/url.d.ts +2 -0
  113. package/dist/runtime/api/utils/url.js +19 -0
  114. package/dist/runtime/api/vcs/git-history-service.d.ts +57 -0
  115. package/dist/runtime/api/vcs/git-history-service.js +228 -0
  116. package/dist/runtime/api/vcs/git-service.d.ts +127 -0
  117. package/dist/runtime/api/vcs/git-service.js +284 -0
  118. package/dist/runtime/api/vcs/worktree-service.d.ts +93 -0
  119. package/dist/runtime/api/vcs/worktree-service.js +506 -0
  120. package/dist/runtime/api/vcs/worktree-service.test.d.ts +1 -0
  121. package/dist/runtime/api/vcs/worktree-service.test.js +20 -0
  122. package/dist/runtime/api/workflows/quality-pipeline.d.ts +58 -0
  123. package/dist/runtime/api/workflows/quality-pipeline.js +400 -0
  124. package/dist/runtime/api/workflows/vibing-orchestrator.d.ts +318 -0
  125. package/dist/runtime/api/workflows/vibing-orchestrator.js +1860 -0
  126. package/dist/runtime/web/.next/BUILD_ID +1 -0
  127. package/dist/runtime/web/.next/app-build-manifest.json +59 -0
  128. package/dist/runtime/web/.next/app-path-routes-manifest.json +7 -0
  129. package/dist/runtime/web/.next/build-manifest.json +33 -0
  130. package/dist/runtime/web/.next/package.json +1 -0
  131. package/dist/runtime/web/.next/prerender-manifest.json +61 -0
  132. package/dist/runtime/web/.next/react-loadable-manifest.json +39 -0
  133. package/dist/runtime/web/.next/required-server-files.json +334 -0
  134. package/dist/runtime/web/.next/routes-manifest.json +62 -0
  135. package/dist/runtime/web/.next/server/app/_not-found/page.js +2 -0
  136. package/dist/runtime/web/.next/server/app/_not-found/page.js.nft.json +1 -0
  137. package/dist/runtime/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
  138. package/dist/runtime/web/.next/server/app/_not-found.html +7 -0
  139. package/dist/runtime/web/.next/server/app/_not-found.meta +8 -0
  140. package/dist/runtime/web/.next/server/app/_not-found.rsc +22 -0
  141. package/dist/runtime/web/.next/server/app/api/health/route.js +1 -0
  142. package/dist/runtime/web/.next/server/app/api/health/route.js.nft.json +1 -0
  143. package/dist/runtime/web/.next/server/app/api/health/route_client-reference-manifest.js +1 -0
  144. package/dist/runtime/web/.next/server/app/api/images/[...path]/route.js +1 -0
  145. package/dist/runtime/web/.next/server/app/api/images/[...path]/route.js.nft.json +1 -0
  146. package/dist/runtime/web/.next/server/app/api/images/[...path]/route_client-reference-manifest.js +1 -0
  147. package/dist/runtime/web/.next/server/app/api/upload/route.js +1 -0
  148. package/dist/runtime/web/.next/server/app/api/upload/route.js.nft.json +1 -0
  149. package/dist/runtime/web/.next/server/app/api/upload/route_client-reference-manifest.js +1 -0
  150. package/dist/runtime/web/.next/server/app/index.html +7 -0
  151. package/dist/runtime/web/.next/server/app/index.meta +7 -0
  152. package/dist/runtime/web/.next/server/app/index.rsc +27 -0
  153. package/dist/runtime/web/.next/server/app/page.js +147 -0
  154. package/dist/runtime/web/.next/server/app/page.js.nft.json +1 -0
  155. package/dist/runtime/web/.next/server/app/page_client-reference-manifest.js +1 -0
  156. package/dist/runtime/web/.next/server/app-paths-manifest.json +7 -0
  157. package/dist/runtime/web/.next/server/chunks/217.js +1 -0
  158. package/dist/runtime/web/.next/server/chunks/383.js +6 -0
  159. package/dist/runtime/web/.next/server/chunks/458.js +1 -0
  160. package/dist/runtime/web/.next/server/chunks/576.js +18 -0
  161. package/dist/runtime/web/.next/server/chunks/635.js +22 -0
  162. package/dist/runtime/web/.next/server/chunks/761.js +1 -0
  163. package/dist/runtime/web/.next/server/chunks/777.js +3 -0
  164. package/dist/runtime/web/.next/server/chunks/825.js +1 -0
  165. package/dist/runtime/web/.next/server/chunks/838.js +1 -0
  166. package/dist/runtime/web/.next/server/chunks/973.js +15 -0
  167. package/dist/runtime/web/.next/server/functions-config-manifest.json +4 -0
  168. package/dist/runtime/web/.next/server/middleware-build-manifest.js +1 -0
  169. package/dist/runtime/web/.next/server/middleware-manifest.json +6 -0
  170. package/dist/runtime/web/.next/server/middleware-react-loadable-manifest.js +1 -0
  171. package/dist/runtime/web/.next/server/next-font-manifest.js +1 -0
  172. package/dist/runtime/web/.next/server/next-font-manifest.json +1 -0
  173. package/dist/runtime/web/.next/server/pages/404.html +7 -0
  174. package/dist/runtime/web/.next/server/pages/500.html +1 -0
  175. package/dist/runtime/web/.next/server/pages/_app.js +1 -0
  176. package/dist/runtime/web/.next/server/pages/_app.js.nft.json +1 -0
  177. package/dist/runtime/web/.next/server/pages/_document.js +1 -0
  178. package/dist/runtime/web/.next/server/pages/_document.js.nft.json +1 -0
  179. package/dist/runtime/web/.next/server/pages/_error.js +19 -0
  180. package/dist/runtime/web/.next/server/pages/_error.js.nft.json +1 -0
  181. package/dist/runtime/web/.next/server/pages-manifest.json +6 -0
  182. package/dist/runtime/web/.next/server/server-reference-manifest.js +1 -0
  183. package/dist/runtime/web/.next/server/server-reference-manifest.json +1 -0
  184. package/dist/runtime/web/.next/server/webpack-runtime.js +1 -0
  185. package/dist/runtime/web/.next/static/chunks/18-15c10d3288afef2e.js +1 -0
  186. package/dist/runtime/web/.next/static/chunks/1c0ca389.537bbe362e3ffbd9.js +3 -0
  187. package/dist/runtime/web/.next/static/chunks/22747d63-ad5da0c19f4cfe41.js +71 -0
  188. package/dist/runtime/web/.next/static/chunks/277-0142a939f08738c3.js +63 -0
  189. package/dist/runtime/web/.next/static/chunks/355.056c2645878a799a.js +1 -0
  190. package/dist/runtime/web/.next/static/chunks/420.a5ccf151c9e2b2f1.js +1 -0
  191. package/dist/runtime/web/.next/static/chunks/439.1be0c6242fd248d5.js +15 -0
  192. package/dist/runtime/web/.next/static/chunks/440.c52e7c0f797e22b2.js +1 -0
  193. package/dist/runtime/web/.next/static/chunks/575-e2478287c27da87b.js +1 -0
  194. package/dist/runtime/web/.next/static/chunks/691.920d88c115087314.js +1 -0
  195. package/dist/runtime/web/.next/static/chunks/765-e838910065b50c3d.js +1 -0
  196. package/dist/runtime/web/.next/static/chunks/87c73c54-09e1ba5c70e60a51.js +1 -0
  197. package/dist/runtime/web/.next/static/chunks/891cff7f.0f71fc028f87e683.js +1 -0
  198. package/dist/runtime/web/.next/static/chunks/8bb4d8db-3e2aa02b0a2384b9.js +1 -0
  199. package/dist/runtime/web/.next/static/chunks/9af238c7-271a911d4e99ab18.js +1 -0
  200. package/dist/runtime/web/.next/static/chunks/app/_not-found/page-1cb74d1cba27d0ab.js +1 -0
  201. package/dist/runtime/web/.next/static/chunks/app/api/health/route-105a61ae865ba536.js +1 -0
  202. package/dist/runtime/web/.next/static/chunks/app/api/images/[...path]/route-105a61ae865ba536.js +1 -0
  203. package/dist/runtime/web/.next/static/chunks/app/api/upload/route-105a61ae865ba536.js +1 -0
  204. package/dist/runtime/web/.next/static/chunks/app/layout-8435322f09fd0975.js +1 -0
  205. package/dist/runtime/web/.next/static/chunks/app/page-8c3ba579efc6f918.js +1 -0
  206. package/dist/runtime/web/.next/static/chunks/cac567b0-5b77dd12911823cd.js +1 -0
  207. package/dist/runtime/web/.next/static/chunks/framework-2518f1345b5b2806.js +1 -0
  208. package/dist/runtime/web/.next/static/chunks/main-17665e5e39de9a8a.js +1 -0
  209. package/dist/runtime/web/.next/static/chunks/main-app-c0b0f5ba4f7f9d75.js +1 -0
  210. package/dist/runtime/web/.next/static/chunks/pages/_app-d6f6b3bbc3d81ee1.js +1 -0
  211. package/dist/runtime/web/.next/static/chunks/pages/_error-75a96cf1997cc3b9.js +1 -0
  212. package/dist/runtime/web/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  213. package/dist/runtime/web/.next/static/chunks/webpack-c8de37305b4635cf.js +1 -0
  214. package/dist/runtime/web/.next/static/css/08c950681f1a9a92.css +1 -0
  215. package/dist/runtime/web/.next/static/css/2728291c68f99cb1.css +3 -0
  216. package/dist/runtime/web/.next/static/css/521bd69cc298cd1a.css +1 -0
  217. package/dist/runtime/web/.next/static/css/537e22821e101b87.css +1 -0
  218. package/dist/runtime/web/.next/static/mRpNgPfbYR_0wrODzlg_4/_buildManifest.js +1 -0
  219. package/dist/runtime/web/.next/static/mRpNgPfbYR_0wrODzlg_4/_ssgManifest.js +1 -0
  220. package/dist/runtime/web/.next/static/media/19cfc7226ec3afaa-s.woff2 +0 -0
  221. package/dist/runtime/web/.next/static/media/21350d82a1f187e9-s.woff2 +0 -0
  222. package/dist/runtime/web/.next/static/media/8e9860b6e62d6359-s.woff2 +0 -0
  223. package/dist/runtime/web/.next/static/media/ba9851c3c22cd980-s.woff2 +0 -0
  224. package/dist/runtime/web/.next/static/media/c5fe6dc8356a8c31-s.woff2 +0 -0
  225. package/dist/runtime/web/.next/static/media/df0a9ae256c0569c-s.woff2 +0 -0
  226. package/dist/runtime/web/.next/static/media/e4af272ccee01ff0-s.p.woff2 +0 -0
  227. package/dist/runtime/web/package.json +65 -0
  228. package/dist/runtime/web/server.js +44 -0
  229. package/dist/tsconfig.tsbuildinfo +1 -0
  230. package/package.json +84 -7
@@ -0,0 +1,1860 @@
1
+ import { EventEmitter } from 'events';
2
+ import { QualityPipeline } from './quality-pipeline.js';
3
+ import { DatabaseService } from '../persistence/database-service.js';
4
+ import { log } from '../lib/logger.js';
5
+ import { generateId } from '../lib/id-generator.js';
6
+ import path from 'path';
7
+ import { stripNextInjectedEnv } from '../utils/stripNextEnv.js';
8
+ import { spawn } from 'child_process';
9
+ import { getSettingsService } from '../settings-service.js';
10
+ import { getVibeDir } from '../lib/server/project-root.js';
11
+ // Canonical phase flow and labels for server-driven timeline and placeholders
12
+ // Action phases only; placeholders are created for these
13
+ const PHASE_FLOW = [
14
+ 'implementing',
15
+ 'validating',
16
+ 'ai-reviewing',
17
+ // Show awaiting-review explicitly in the main flow so the timeline
18
+ // reflects the human approval step in order
19
+ 'awaiting-review',
20
+ 'merging',
21
+ 'cleaning',
22
+ ];
23
+ const PHASE_LABELS = {
24
+ draft: 'Workflow started',
25
+ implementing: 'Implementation',
26
+ implemented: 'Implemented',
27
+ validating: 'Validation',
28
+ validated: 'Validated',
29
+ 'ai-reviewing': 'AI Review',
30
+ 'ai-reviewed': 'AI Reviewed',
31
+ 'awaiting-review': 'Awaiting Review',
32
+ paused: 'Paused',
33
+ approved: 'Approved',
34
+ merging: 'Merge',
35
+ merged: 'Merged',
36
+ cleaning: 'Cleaning',
37
+ cleaned: 'Cleaned',
38
+ completed: 'Completed',
39
+ failed: 'Failed',
40
+ };
41
+ // Default config
42
+ const getDefaultConfig = async () => {
43
+ try {
44
+ const settingsService = getSettingsService();
45
+ await settingsService.initialize();
46
+ const settings = settingsService.getSettings();
47
+ return {
48
+ autoQualityChecks: settings.defaultWorkflow.autoQualityChecks,
49
+ requireHumanApproval: settings.defaultWorkflow.requireHumanApproval,
50
+ aiCodeReview: settings.defaultWorkflow.aiCodeReview,
51
+ stepByStepMode: false,
52
+ retryPolicy: {
53
+ maxImplementationAttempts: settings.defaultWorkflow.maxImplementationAttempts,
54
+ },
55
+ autoCommit: settings.defaultWorkflow.autoCommit,
56
+ };
57
+ }
58
+ catch (error) {
59
+ log.warn('Failed to load settings, using fallback defaults', error, 'vibing-orchestrator');
60
+ return {
61
+ autoQualityChecks: true,
62
+ requireHumanApproval: true,
63
+ aiCodeReview: true,
64
+ stepByStepMode: false,
65
+ retryPolicy: { maxImplementationAttempts: 3 },
66
+ autoCommit: false,
67
+ };
68
+ }
69
+ };
70
+ export class VibingOrchestrator extends EventEmitter {
71
+ // Build a new, visible timeline array without mutating the input
72
+ // Correct order: remove placeholders -> add real phases -> fill missing placeholders
73
+ computeVisibleTimeline(wf) {
74
+ const base = Array.isArray(wf.timeline) ? [...wf.timeline] : [];
75
+ // Visible phases in timeline
76
+ const visible = new Set([
77
+ 'draft',
78
+ 'implementing',
79
+ 'validating',
80
+ 'ai-reviewing',
81
+ 'awaiting-review',
82
+ 'merging',
83
+ 'cleaning',
84
+ 'failed',
85
+ 'paused',
86
+ ]);
87
+ // Ensure a start marker exists (non-placeholder)
88
+ let startItem = base.find((t) => t.phase === 'draft' && !t.placeholder);
89
+ if (!startItem && wf.startTime) {
90
+ startItem = {
91
+ id: `start:${wf.startTime}`,
92
+ label: 'Workflow started',
93
+ phase: 'draft',
94
+ startTime: wf.startTime,
95
+ };
96
+ }
97
+ // Remove all placeholders and keep only visible phases
98
+ const realItems = base.filter((t) => !t.placeholder && visible.has(t.phase));
99
+ // Group real items by phase (preserve per-phase chronological order)
100
+ // TODO: retry logic is different from grouping by phase
101
+ const realByPhase = new Map();
102
+ for (const item of realItems) {
103
+ const ph = item.phase;
104
+ if (!realByPhase.has(ph))
105
+ realByPhase.set(ph, []);
106
+ realByPhase.get(ph).push(item);
107
+ }
108
+ for (const [, items] of realByPhase) {
109
+ items.sort((a, b) => {
110
+ const ta = new Date(a.startTime || wf.startTime || 0).getTime();
111
+ const tb = new Date(b.startTime || wf.startTime || 0).getTime();
112
+ return ta - tb;
113
+ });
114
+ }
115
+ // Compose final ordered list: start -> each phase in PHASE_FLOW (real items if any, else placeholder)
116
+ const out = [];
117
+ if (startItem)
118
+ out.push(startItem);
119
+ const ts = wf.metrics?.lastPhaseStartedAt ||
120
+ wf.lastUpdatedAt ||
121
+ wf.startTime ||
122
+ new Date().toISOString();
123
+ for (const ph of PHASE_FLOW) {
124
+ const items = realByPhase.get(ph) || [];
125
+ if (items.length > 0) {
126
+ out.push(...items);
127
+ }
128
+ else {
129
+ out.push({
130
+ id: `placeholder:${ph}`,
131
+ label: PHASE_LABELS[ph],
132
+ phase: ph,
133
+ startTime: ts,
134
+ placeholder: true,
135
+ });
136
+ }
137
+ }
138
+ // Append any other visible real items not in PHASE_FLOW (e.g., 'awaiting-review', 'failed', 'paused')
139
+ for (const [ph, items] of realByPhase) {
140
+ if (!PHASE_FLOW.includes(ph) && ph !== 'draft') {
141
+ out.push(...items);
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ // Build a new timeline by appending an optional item, then normalizing
147
+ buildTimeline(wf, newItem) {
148
+ const base = Array.isArray(wf.timeline) ? [...wf.timeline] : [];
149
+ if (newItem)
150
+ base.push(newItem);
151
+ const tmp = { ...wf, timeline: base };
152
+ return this.computeVisibleTimeline(tmp);
153
+ }
154
+ constructor(taskService, agentService, worktreeService, config, gitService, persistenceDataDir) {
155
+ super();
156
+ this.taskService = taskService;
157
+ this.agentService = agentService;
158
+ this.worktreeService = worktreeService;
159
+ this.config = config;
160
+ this.gitService = gitService;
161
+ this.workflows = new Map();
162
+ this.initialized = false;
163
+ this.qualityPipeline = new QualityPipeline();
164
+ // Persist workflows in a JSON file using the generic database service
165
+ const filePath = persistenceDataDir
166
+ ? path.join(persistenceDataDir, 'workflows.json')
167
+ : path.join(getVibeDir(), 'workflows.json');
168
+ this.workflowDB = new DatabaseService(filePath);
169
+ // Forward execution updates from AgentService so UIs can subscribe via orchestrator
170
+ this.agentService.on('executionUpdated', (update) => {
171
+ this.emit('executionUpdated', update);
172
+ });
173
+ // Listen for execution creation so we can associate executionId to workflows
174
+ this.agentService.on('executionCreated', async (data) => {
175
+ try {
176
+ const wfId = data.workflowId;
177
+ if (!wfId)
178
+ return;
179
+ const wf = this.workflows.get(wfId);
180
+ if (!wf)
181
+ return;
182
+ // Track execution IDs and attempts for implementing phase
183
+ const attempt = (wf.attempts?.implementing || 0) + 1;
184
+ const executionIds = (wf.executionIds ?? (wf.executionIds = {}));
185
+ const implList = (executionIds['implementing'] || []);
186
+ executionIds['implementing'] = [...implList, data.executionId];
187
+ wf.attempts = wf.attempts || {};
188
+ wf.attempts['implementing'] = attempt;
189
+ // Timeline: record implementation attempt start
190
+ wf.timeline = this.buildTimeline(wf, {
191
+ id: data.executionId,
192
+ label: attempt > 1 ? `Implementation – Retry #${attempt}` : 'Implementation',
193
+ phase: 'implementing',
194
+ attempt,
195
+ executionId: data.executionId,
196
+ startTime: new Date().toISOString(),
197
+ });
198
+ await this.saveWorkflow(wf);
199
+ // Notify listeners that an execution for this workflow has started
200
+ this.emit('workflowExecutionStarted', {
201
+ workflowId: wfId,
202
+ executionId: data.executionId,
203
+ phase: 'implementing',
204
+ workflow: wf,
205
+ });
206
+ }
207
+ catch (err) {
208
+ log.warn('Failed to handle executionCreated event', err, 'vibing-orchestrator');
209
+ }
210
+ });
211
+ }
212
+ /**
213
+ * Initialize workflow orchestrator by loading existing workflows
214
+ * Call this after construction to load persisted workflows
215
+ */
216
+ async initialize() {
217
+ try {
218
+ // Load existing workflows from database
219
+ const all = await this.workflowDB.getAll();
220
+ const map = new Map();
221
+ for (const [id, wf] of Object.entries(all)) {
222
+ map.set(id, this.normalizeWorkflow(wf));
223
+ }
224
+ this.workflows = map;
225
+ log.debug('Loaded existing workflows from disk', { count: this.workflows.size }, 'vibing-orchestrator');
226
+ log.debug('Vibing orchestrator initialized with persisted workflows', undefined, 'vibing-orchestrator');
227
+ }
228
+ catch (error) {
229
+ log.warn('Failed to load workflows from disk', error, 'vibing-orchestrator');
230
+ }
231
+ this.initialized = true;
232
+ }
233
+ // Normalize workflow shape so timeline/status writes don't throw
234
+ normalizeWorkflow(wf) {
235
+ const out = { ...wf };
236
+ if (!Array.isArray(out.phaseHistory))
237
+ out.phaseHistory = [];
238
+ if (!Array.isArray(out.timeline))
239
+ out.timeline = [];
240
+ if (!out.executionIds || typeof out.executionIds !== 'object')
241
+ out.executionIds = {};
242
+ const execPhases = ['implementing', 'validating', 'ai-reviewing', 'merging'];
243
+ for (const ph of execPhases) {
244
+ const arr = out.executionIds[ph];
245
+ if (!Array.isArray(arr))
246
+ out.executionIds[ph] = [];
247
+ }
248
+ if (!out.attempts || typeof out.attempts !== 'object')
249
+ out.attempts = {};
250
+ const metrics = (out.metrics ?? (out.metrics = { durationsMs: {} }));
251
+ if (!metrics.durationsMs)
252
+ metrics.durationsMs = {};
253
+ if (!metrics.lastPhaseStartedAt)
254
+ metrics.lastPhaseStartedAt = out.startTime;
255
+ if (!out.lastUpdatedAt)
256
+ out.lastUpdatedAt = out.startTime;
257
+ if (!out.status && out.phase === 'draft')
258
+ out.status = 'draft';
259
+ return out;
260
+ }
261
+ /**
262
+ * Execute a task once (no phase management). Optionally associates with a workflow.
263
+ */
264
+ async executeTask(taskId, workflowId) {
265
+ const t = this.taskService.getTask(taskId);
266
+ if (!t)
267
+ throw new Error(`Task ${taskId} not found`);
268
+ // Wait for the executionCreated event for this task/workflow
269
+ const createdPromise = this.waitForExecutionCreated(taskId, workflowId, 15000);
270
+ // Kick off the agent execution (do not rely on returned id)
271
+ // Attach a catch handler to avoid unhandled promise rejection crashing the process
272
+ void this.agentService
273
+ .executeTask(taskId, workflowId)
274
+ .catch((err) => log.error('Agent execution failed to start (executeTask)', err, 'vibing-orchestrator'));
275
+ const executionId = await createdPromise;
276
+ return { executionId };
277
+ }
278
+ async stopExecution(executionId) {
279
+ await this.agentService.stopExecution(executionId);
280
+ }
281
+ getExecutionStatus(executionId) {
282
+ return this.agentService.getExecutionStatus(executionId);
283
+ }
284
+ async getPersistedExecutionLogs(executionId) {
285
+ return await this.agentService.getPersistedExecutionLogs(executionId);
286
+ }
287
+ getExecutionLogs(executionId) {
288
+ return this.agentService.getExecutionLogs(executionId);
289
+ }
290
+ getTaskExecutions(taskId) {
291
+ return this.agentService.getTaskExecutions(taskId);
292
+ }
293
+ getExecutionStats() {
294
+ return this.agentService.getExecutionStats();
295
+ }
296
+ async listAllExecutions() {
297
+ return await this.agentService.listAllExecutions();
298
+ }
299
+ async improveTaskContent(taskId, data, options) {
300
+ const task = this.taskService.getTask(taskId);
301
+ if (!task)
302
+ throw new Error(`Task ${taskId} not found`);
303
+ const res = await this.agentService.improveTaskContent(task, data, options?.executionId);
304
+ if (options?.workflowId) {
305
+ const wf = this.workflows.get(options.workflowId);
306
+ if (wf) {
307
+ wf.metadata = {
308
+ ...wf.metadata,
309
+ lastTaskImprovement: { ...res, timestamp: new Date().toISOString() },
310
+ };
311
+ await this.saveWorkflow(wf);
312
+ }
313
+ }
314
+ return res;
315
+ }
316
+ async aiReviewCode(taskId, reviewContext, options) {
317
+ const res = await this.agentService.aiReviewCode(taskId, reviewContext, {
318
+ overrides: options?.overrides,
319
+ workflowId: options?.workflowId,
320
+ executionId: options?.executionId,
321
+ });
322
+ const wfId = options?.workflowId;
323
+ if (wfId) {
324
+ const wf = this.workflows.get(wfId);
325
+ if (wf) {
326
+ wf.metadata = {
327
+ ...wf.metadata,
328
+ aiReviewResult: { ...res, timestamp: new Date().toISOString() },
329
+ };
330
+ // Record execution ID under ai-reviewing for UI/observability
331
+ if (res?.executionId) {
332
+ wf.executionIds = wf.executionIds || {};
333
+ const list = wf.executionIds['ai-reviewing'] || [];
334
+ wf.executionIds['ai-reviewing'] = [...list, res.executionId];
335
+ }
336
+ await this.saveWorkflow(wf);
337
+ }
338
+ }
339
+ return res;
340
+ }
341
+ async aiMerge(taskId, options) {
342
+ const overrides = options?.provider || options?.model
343
+ ? { provider: options?.provider, model: options?.model }
344
+ : undefined;
345
+ return await this.agentService.aiMerge(taskId, {
346
+ baseBranch: options?.baseBranch,
347
+ workflowId: options?.workflowId,
348
+ executionId: options?.executionId,
349
+ overrides,
350
+ });
351
+ }
352
+ // Worktree façade
353
+ async listWorktrees() {
354
+ return await this.worktreeService.listWorktrees();
355
+ }
356
+ async syncWorktreeState() {
357
+ await this.worktreeService.syncWorktreeState();
358
+ }
359
+ getWorktreeInfo(taskId) {
360
+ const wt = this.worktreeService.getWorktree(taskId);
361
+ if (!wt)
362
+ return null;
363
+ // Remove non-serializable references before exposing to callers
364
+ const { git, ...rest } = wt;
365
+ return rest;
366
+ }
367
+ async createWorktree(taskId) {
368
+ const task = this.taskService.getTask(taskId);
369
+ if (!task)
370
+ throw new Error(`Task ${taskId} not found`);
371
+ if (task.deleted_at)
372
+ throw new Error(`Task ${taskId} is deleted`);
373
+ const wt = await this.worktreeService.createWorktree(task);
374
+ const { git, ...rest } = wt;
375
+ return rest;
376
+ }
377
+ async deleteWorktree(taskId, force) {
378
+ await this.worktreeService.deleteWorktree(taskId, !!force);
379
+ }
380
+ async cleanupWorktree(params) {
381
+ await this.worktreeService.cleanupWorktree(params);
382
+ }
383
+ async createPullRequest(taskId, baseBranch = 'main') {
384
+ return await this.worktreeService.createPullRequest(taskId, baseBranch);
385
+ }
386
+ // Open in configured code editor (from settings.development.editor.command)
387
+ async openInEditor(worktreePath) {
388
+ try {
389
+ const settingsService = getSettingsService();
390
+ await settingsService.initialize();
391
+ const editor = settingsService.getSetting([
392
+ 'development',
393
+ 'editor',
394
+ ]) || { command: 'code', args: [] };
395
+ const cmd = editor.command || 'code';
396
+ const baseArgs = Array.isArray(editor.args) ? editor.args : [];
397
+ spawn(cmd, [...baseArgs, worktreePath], {
398
+ stdio: 'ignore',
399
+ detached: true,
400
+ env: stripNextInjectedEnv(),
401
+ });
402
+ return { success: true };
403
+ }
404
+ catch {
405
+ // Fallback to cursor if settings service fails
406
+ spawn('cursor', [worktreePath], {
407
+ stdio: 'ignore',
408
+ detached: true,
409
+ env: stripNextInjectedEnv(),
410
+ });
411
+ return { success: true };
412
+ }
413
+ }
414
+ async openInTerminal(worktreePath) {
415
+ // TODO: add options to resume the session
416
+ try {
417
+ const settingsService = getSettingsService();
418
+ await settingsService.initialize();
419
+ const terminal = settingsService.getSetting([
420
+ 'development',
421
+ 'terminal',
422
+ ]) || {
423
+ command: '/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal',
424
+ args: [],
425
+ };
426
+ const cmd = terminal.command || '/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal';
427
+ const baseArgs = Array.isArray(terminal.args) ? terminal.args : [];
428
+ spawn(cmd, [...baseArgs, worktreePath], {
429
+ stdio: 'ignore',
430
+ detached: true,
431
+ env: stripNextInjectedEnv(),
432
+ });
433
+ return { success: true };
434
+ }
435
+ catch {
436
+ // Fallback to default terminal if settings service fails
437
+ spawn('/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal', [worktreePath], {
438
+ stdio: 'ignore',
439
+ detached: true,
440
+ env: stripNextInjectedEnv(),
441
+ });
442
+ return { success: true };
443
+ }
444
+ }
445
+ // Worktree status helpers used by UI gating flows
446
+ async checkWorktreeStatus(workflowId) {
447
+ const workflow = this.workflows.get(workflowId);
448
+ if (!workflow)
449
+ throw new Error(`Workflow ${workflowId} not found`);
450
+ const worktree = this.getWorktreeInfo(workflow.taskId);
451
+ if (!worktree?.path)
452
+ throw new Error('No worktree found for this task');
453
+ const status = await this.worktreeService.getGitService().getGitStatus(worktree.path);
454
+ const files = [...status.modified, ...status.staged, ...status.not_added];
455
+ return { clean: files.length === 0, uncommittedFiles: files, worktreePath: worktree.path };
456
+ }
457
+ async approveAndContinueReview(workflowId) {
458
+ const status = await this.checkWorktreeStatus(workflowId);
459
+ if (!status.clean) {
460
+ throw new Error(`Uncommitted changes found. Please commit or stash the following files:\n${status.uncommittedFiles.join('\n')}`);
461
+ }
462
+ await this.approveWorkflow(workflowId);
463
+ }
464
+ /**
465
+ * Mark workflow as completed by human decision.
466
+ * Does not perform merge/cleanup; simply finalizes the workflow and emits completion.
467
+ */
468
+ async markWorkflowCompleted(workflowId) {
469
+ const workflow = this.workflows.get(workflowId);
470
+ if (!workflow)
471
+ throw new Error(`Workflow ${workflowId} not found`);
472
+ // Record that completion was decided by human
473
+ workflow.metadata = {
474
+ ...workflow.metadata,
475
+ humanCompleted: true,
476
+ };
477
+ workflow.endTime = new Date().toISOString();
478
+ await this.transitionToPhase(workflowId, 'completed');
479
+ this.emit('workflowCompleted', workflow);
480
+ log.info('Workflow marked completed by human', { taskId: workflow.taskId }, 'vibing-orchestrator');
481
+ await this.saveWorkflow(workflow);
482
+ }
483
+ async ensureInitialized() {
484
+ if (!this.initialized) {
485
+ await this.initialize();
486
+ }
487
+ }
488
+ /**
489
+ * Start AI-assisted workflow for a task
490
+ */
491
+ async startWorkflow(taskId, customConfig) {
492
+ const task = this.taskService.getTask(taskId);
493
+ if (!task) {
494
+ throw new Error(`Task ${taskId} not found`);
495
+ }
496
+ const workflowId = generateId('workflow');
497
+ const defaultConfig = await getDefaultConfig();
498
+ // Ensure settings-derived defaults take precedence over constructor fallbacks
499
+ const finalConfig = { ...this.config, ...defaultConfig, ...customConfig };
500
+ const workflow = this.createNewWorkflow(workflowId, taskId, finalConfig);
501
+ this.workflows.set(workflowId, workflow);
502
+ // Persist the new workflow
503
+ await this.saveWorkflow(workflow);
504
+ this.emit('workflowStarted', workflow);
505
+ log.info('Starting workflow for task', { taskId, workflowId }, 'vibing-orchestrator');
506
+ await this.executeImplementation(workflowId);
507
+ return workflowId;
508
+ }
509
+ /**
510
+ * Pause a workflow execution
511
+ */
512
+ async pauseWorkflow(workflowId) {
513
+ const workflow = this.workflows.get(workflowId);
514
+ if (!workflow) {
515
+ throw new Error(`Workflow ${workflowId} not found`);
516
+ }
517
+ // Stop current execution if running
518
+ // Try to stop the most recent running execution for this task
519
+ const executions = this.agentService.getTaskExecutions(workflow.taskId) || [];
520
+ const running = executions
521
+ .filter((e) => e.status === 'running')
522
+ .sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())[0];
523
+ const latest = running ||
524
+ executions.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())[0];
525
+ if (latest?.id) {
526
+ try {
527
+ await this.agentService.stopExecution(latest.id);
528
+ }
529
+ catch (error) {
530
+ log.warn('Failed to stop execution', error, 'vibing-orchestrator');
531
+ }
532
+ }
533
+ workflow.phase = 'paused';
534
+ workflow.error = 'Paused by user';
535
+ workflow.status = 'paused';
536
+ // Persist the workflow state
537
+ await this.saveWorkflow(workflow);
538
+ this.emit('workflowPaused', workflow);
539
+ log.info('Paused workflow', { workflowId }, 'vibing-orchestrator');
540
+ }
541
+ /**
542
+ * Reset a workflow by deleting its record and optionally its worktree.
543
+ */
544
+ async resetWorkflow(workflowId, options) {
545
+ const wf = this.workflows.get(workflowId);
546
+ if (!wf)
547
+ throw new Error(`Workflow ${workflowId} not found`);
548
+ const taskId = wf.taskId;
549
+ if (options?.deleteWorktree) {
550
+ try {
551
+ await this.deleteWorktree(wf.taskId, !!options.force);
552
+ }
553
+ catch (e) {
554
+ log.warn('Failed to delete worktree during reset', e, 'vibing-orchestrator');
555
+ }
556
+ }
557
+ // Remove from memory and persistence
558
+ this.workflows.delete(workflowId);
559
+ try {
560
+ await this.workflowDB.delete(workflowId);
561
+ }
562
+ catch (e) {
563
+ log.warn('Failed to delete workflow persistence', e, 'vibing-orchestrator');
564
+ }
565
+ if (taskId) {
566
+ try {
567
+ const removed = await this.removeWorkflowsByTask(taskId);
568
+ if (removed > 0) {
569
+ log.info('Deleted additional workflows for task during reset', { taskId, removed }, 'vibing-orchestrator');
570
+ }
571
+ }
572
+ catch (e) {
573
+ log.warn('Failed to delete all workflows for task on reset', e, 'vibing-orchestrator');
574
+ }
575
+ }
576
+ this.emit('workflowDeleted', { workflowId, taskId: wf.taskId });
577
+ }
578
+ /**
579
+ * Approve workflow changes and proceed to merge
580
+ */
581
+ async approveWorkflow(workflowId) {
582
+ const workflow = this.requireWorkflow(workflowId);
583
+ this.assertPhase(workflow, 'awaiting-review', 'approve');
584
+ // Close the awaiting-review timeline item if present
585
+ try {
586
+ const tl = (workflow.timeline || []);
587
+ for (let i = tl.length - 1; i >= 0; i--) {
588
+ const t = tl[i];
589
+ if (t.phase === 'awaiting-review' && !t.placeholder && !t.endTime) {
590
+ t.endTime = new Date().toISOString();
591
+ break;
592
+ }
593
+ }
594
+ workflow.timeline = this.computeVisibleTimeline(workflow);
595
+ await this.saveWorkflow(workflow);
596
+ }
597
+ catch (err) {
598
+ log.debug('Failed to finalize awaiting-review timeline item', err, 'vibing-orchestrator');
599
+ }
600
+ workflow.status = 'approved';
601
+ workflow.lastUpdatedAt = new Date().toISOString();
602
+ await this.transitionToPhase(workflowId, 'approved');
603
+ await this.saveWorkflow(workflow);
604
+ if (workflow.metadata.stepByStepMode) {
605
+ log.info('Manual step mode – approved; waiting for Continue to run merge', { workflowId }, 'vibing-orchestrator');
606
+ }
607
+ else {
608
+ await this.executeMerge(workflowId);
609
+ }
610
+ }
611
+ /**
612
+ * Reject workflow and request changes
613
+ */
614
+ async rejectWorkflow(workflowId, feedback) {
615
+ const workflow = this.requireWorkflow(workflowId);
616
+ this.assertPhase(workflow, 'awaiting-review', 'reject');
617
+ // Close the awaiting-review timeline item if present
618
+ try {
619
+ const tl = (workflow.timeline || []);
620
+ for (let i = tl.length - 1; i >= 0; i--) {
621
+ const t = tl[i];
622
+ if (t.phase === 'awaiting-review' && !t.placeholder && !t.endTime) {
623
+ t.endTime = new Date().toISOString();
624
+ break;
625
+ }
626
+ }
627
+ workflow.timeline = this.computeVisibleTimeline(workflow);
628
+ await this.saveWorkflow(workflow);
629
+ }
630
+ catch (err) {
631
+ log.debug('Failed to finalize awaiting-review timeline item', err, 'vibing-orchestrator');
632
+ }
633
+ // Return to implementation phase with feedback
634
+ await this.transitionToPhase(workflowId, 'implementing');
635
+ await this.executeImplementation(workflowId, feedback);
636
+ }
637
+ /**
638
+ * Get workflow status
639
+ */
640
+ getWorkflow(workflowId) {
641
+ const wf = this.workflows.get(workflowId) || null;
642
+ if (wf) {
643
+ wf.timeline = this.computeVisibleTimeline(wf);
644
+ }
645
+ return wf;
646
+ }
647
+ /**
648
+ * Get all workflows for a task
649
+ */
650
+ getTaskWorkflows(taskId) {
651
+ return Array.from(this.workflows.values())
652
+ .filter((w) => w.taskId === taskId)
653
+ .map((wf) => {
654
+ wf.timeline = this.computeVisibleTimeline(wf);
655
+ return wf;
656
+ })
657
+ .sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
658
+ }
659
+ /**
660
+ * Get latest workflow for a task, preferring most recently updated.
661
+ * Falls back to newest startTime when lastUpdatedAt is unavailable.
662
+ */
663
+ getLatestWorkflowByTask(taskId) {
664
+ const list = Array.from(this.workflows.values()).filter((w) => w.taskId === taskId);
665
+ if (list.length === 0)
666
+ return null;
667
+ const sorted = list.sort((a, b) => {
668
+ const aTs = new Date(a.lastUpdatedAt || a.startTime || 0).getTime();
669
+ const bTs = new Date(b.lastUpdatedAt || b.startTime || 0).getTime();
670
+ return bTs - aTs;
671
+ });
672
+ const latest = sorted[0];
673
+ latest.timeline = this.computeVisibleTimeline(latest);
674
+ return latest;
675
+ }
676
+ /**
677
+ * Transition workflow to new phase
678
+ */
679
+ async transitionToPhase(workflowId, newPhase) {
680
+ const workflow = this.workflows.get(workflowId);
681
+ if (!workflow)
682
+ return;
683
+ const oldPhase = workflow.phase;
684
+ workflow.lastPhase = oldPhase;
685
+ workflow.phase = newPhase;
686
+ const history = workflow.phaseHistory || [];
687
+ const now = new Date().toISOString();
688
+ history.push({ from: oldPhase, to: newPhase, at: now });
689
+ workflow.phaseHistory = history;
690
+ // Metrics accumulation
691
+ const metrics = (workflow.metrics = workflow.metrics || { durationsMs: {} });
692
+ const startTs = metrics.lastPhaseStartedAt
693
+ ? new Date(metrics.lastPhaseStartedAt).getTime()
694
+ : new Date(workflow.startTime).getTime();
695
+ const nowTs = new Date(now).getTime();
696
+ const delta = Math.max(0, nowTs - startTs);
697
+ const prev = metrics.durationsMs?.[oldPhase] || 0;
698
+ metrics.durationsMs = { ...metrics.durationsMs, [oldPhase]: prev + delta };
699
+ metrics.lastPhaseStartedAt = now;
700
+ if (newPhase === 'completed') {
701
+ metrics.totalDurationMs = Object.values(metrics.durationsMs || {}).reduce((a, b) => a + (b || 0), 0);
702
+ }
703
+ workflow.lastUpdatedAt = now;
704
+ workflow.timeline = this.computeVisibleTimeline(workflow);
705
+ log.info('Workflow phase transition', { workflowId, oldPhase, newPhase }, 'vibing-orchestrator');
706
+ await this.saveWorkflow(workflow);
707
+ this.emit('workflowPhaseChanged', { workflowId, oldPhase, newPhase, workflow });
708
+ }
709
+ /**
710
+ * Save workflow to persistence layer
711
+ */
712
+ async saveWorkflow(workflow) {
713
+ try {
714
+ await this.workflowDB.set(workflow.id, serializeVibe(workflow));
715
+ }
716
+ catch (error) {
717
+ log.warn('Failed to persist workflow', error, 'vibing-orchestrator');
718
+ }
719
+ }
720
+ /**
721
+ * Execute implementation phase with AI coding
722
+ */
723
+ async executeImplementation(workflowId, feedback, providerOverride) {
724
+ const workflow = this.workflows.get(workflowId);
725
+ if (!workflow)
726
+ return;
727
+ await this.transitionToPhase(workflowId, 'implementing');
728
+ try {
729
+ log.info('Implementing task', { taskId: workflow.taskId }, 'vibing-orchestrator');
730
+ // Start task execution with enhanced prompts and workflow context
731
+ // Prepare rerun context if any
732
+ const previousExecId = (workflow.executionIds?.['implementing'] || []).slice(-1)[0];
733
+ const attempt = (workflow.attempts?.implementing || 0) + 1;
734
+ // Build rerun context automatically when available (no need to plumb reason externally)
735
+ const autoReason = feedback ||
736
+ workflow.failureContext?.error ||
737
+ (workflow.failureContext?.atPhase
738
+ ? `Retry after ${workflow.failureContext.atPhase} failure`
739
+ : undefined);
740
+ // Prepare to capture executionId from event, then start execution
741
+ const createdPromise = this.waitForExecutionCreated(workflow.taskId, workflowId, 20000);
742
+ // Fire-and-forget; attach catch to prevent unhandled rejection from crashing process
743
+ void this.agentService
744
+ .executeTask(workflow.taskId, workflowId, {
745
+ rerunContext: autoReason
746
+ ? {
747
+ reason: autoReason,
748
+ previousExecutionId: previousExecId,
749
+ failurePhase: workflow.failureContext?.atPhase,
750
+ qualityResults: workflow.qualityResults,
751
+ attempt,
752
+ }
753
+ : undefined,
754
+ providerOverride: providerOverride || workflow.metadata?.aiRoutingOverrides?.execute_task,
755
+ workflowConfig: workflow.metadata,
756
+ })
757
+ .catch((err) => log.error('Agent execution failed to start (implementation phase)', err, 'vibing-orchestrator'));
758
+ const executionId = await createdPromise;
759
+ // Maintain placeholders and wait for execution to complete
760
+ workflow.timeline = this.computeVisibleTimeline(workflow);
761
+ await this.saveWorkflow(workflow);
762
+ // Wait for execution to complete
763
+ await this.waitForExecution(executionId);
764
+ const execution = this.agentService.getExecutionStatus(executionId);
765
+ if (!execution || execution.status === 'failed') {
766
+ throw new Error(`Implementation failed: ${execution?.error || 'Unknown error'}`);
767
+ }
768
+ // Timeline: complete implementation attempt
769
+ const tImpl = workflow.timeline.find((t) => t.executionId === executionId);
770
+ if (tImpl) {
771
+ tImpl.endTime = execution.endTime || new Date().toISOString();
772
+ tImpl.usage = execution.usage;
773
+ workflow.timeline = this.computeVisibleTimeline(workflow);
774
+ await this.saveWorkflow(workflow);
775
+ }
776
+ log.info('Implementation completed', { taskId: workflow.taskId }, 'vibing-orchestrator');
777
+ // Update checkpoint status
778
+ workflow.status = 'implemented';
779
+ workflow.lastUpdatedAt = new Date().toISOString();
780
+ await this.saveWorkflow(workflow);
781
+ await this.transitionToPhase(workflowId, 'implemented');
782
+ if (workflow.metadata.stepByStepMode) {
783
+ log.info('Manual step mode – implemented; waiting for Continue to run validation', { workflowId }, 'vibing-orchestrator');
784
+ }
785
+ else {
786
+ await this.executeValidation(workflowId);
787
+ }
788
+ }
789
+ catch (error) {
790
+ await this.handlePhaseFailure(workflowId, 'implementing', error);
791
+ }
792
+ }
793
+ /**
794
+ * Public: re-run implementation phase on demand
795
+ * Forces phase to 'implementing' and executes implementation again.
796
+ */
797
+ async rerunImplementation(workflowId, feedback, providerOverride) {
798
+ const workflow = this.workflows.get(workflowId);
799
+ if (!workflow)
800
+ throw new Error(`Workflow ${workflowId} not found`);
801
+ await this.transitionToPhase(workflowId, 'implementing');
802
+ await this.executeImplementation(workflowId, feedback, providerOverride);
803
+ }
804
+ /**
805
+ * Get previous phase, preferring the phase where failure occurred
806
+ */
807
+ getPreviousPhase(workflowId) {
808
+ const wf = this.workflows.get(workflowId);
809
+ if (!wf)
810
+ return null;
811
+ return wf.failureContext?.atPhase || wf.lastPhase || null;
812
+ }
813
+ /**
814
+ * Rerun the phase that led to failure (or lastPhase if available)
815
+ */
816
+ async rerunPreviousPhase(workflowId) {
817
+ const phase = this.getPreviousPhase(workflowId);
818
+ if (!phase)
819
+ throw new Error('No previous phase recorded.');
820
+ await this.rerunPhase(workflowId, phase);
821
+ }
822
+ /**
823
+ * Rerun a specific phase programmatically
824
+ */
825
+ async rerunPhase(workflowId, phase) {
826
+ // Before rerun, reset timeline and results from the selected phase onward
827
+ await this.resetFromPhase(workflowId, phase);
828
+ switch (phase) {
829
+ case 'implementing':
830
+ await this.transitionToPhase(workflowId, 'implementing');
831
+ await this.executeImplementation(workflowId);
832
+ return;
833
+ case 'validating':
834
+ await this.executeValidation(workflowId);
835
+ return;
836
+ case 'ai-reviewing':
837
+ await this.executeAiReviewPhase(workflowId);
838
+ return;
839
+ case 'awaiting-review':
840
+ await this.executeAwaitingReview(workflowId);
841
+ return;
842
+ case 'merging':
843
+ await this.executeMerge(workflowId);
844
+ return;
845
+ case 'approved':
846
+ // Failure after approval typically means merge failed; try merging again
847
+ await this.executeMerge(workflowId);
848
+ return;
849
+ case 'cleaning':
850
+ await this.executeCleanup(workflowId);
851
+ return;
852
+ default:
853
+ // For other phases, restart implementation as a safe default
854
+ await this.executeImplementation(workflowId);
855
+ return;
856
+ }
857
+ }
858
+ /**
859
+ * Reset workflow state from a given phase onward (inclusive).
860
+ * Clears timeline entries, execution IDs, attempts, and phase results for later phases
861
+ * so that a rerun behaves like a fresh run from that step.
862
+ */
863
+ async resetFromPhase(workflowId, from) {
864
+ const workflow = this.workflows.get(workflowId);
865
+ if (!workflow)
866
+ return;
867
+ const ordered = [
868
+ 'draft',
869
+ 'implementing',
870
+ 'validating',
871
+ 'ai-reviewing',
872
+ 'awaiting-review',
873
+ 'approved',
874
+ 'merging',
875
+ 'merged',
876
+ 'cleaning',
877
+ 'completed',
878
+ ];
879
+ const idx = ordered.indexOf(from);
880
+ if (idx < 0)
881
+ return;
882
+ const toReset = ordered.slice(idx); // inclusive of `from`
883
+ // Clear execution IDs and attempts for affected phases
884
+ workflow.executionIds = workflow.executionIds || {};
885
+ workflow.attempts = workflow.attempts || {};
886
+ for (const ph of toReset) {
887
+ if (workflow.executionIds[ph])
888
+ workflow.executionIds[ph] = [];
889
+ if (workflow.attempts[ph] !== undefined)
890
+ delete workflow.attempts[ph];
891
+ }
892
+ // Trim timeline items from affected phases
893
+ if (Array.isArray(workflow.timeline)) {
894
+ workflow.timeline = workflow.timeline.filter((t) => ordered.indexOf(t.phase) < idx);
895
+ }
896
+ // Trim phase history entries from affected phases so UI does not reconstruct later steps
897
+ if (Array.isArray(workflow.phaseHistory)) {
898
+ workflow.phaseHistory = workflow.phaseHistory.filter((h) => ordered.indexOf(h.to) < idx);
899
+ // Update lastPhase to the last remaining history entry (or 'draft')
900
+ const last = workflow.phaseHistory[workflow.phaseHistory.length - 1];
901
+ workflow.lastPhase = (last ? last.to : 'draft');
902
+ }
903
+ // Clear phase-specific results when rerunning from or before them
904
+ if (idx <= ordered.indexOf('validating')) {
905
+ workflow.qualityResults = undefined;
906
+ }
907
+ if (idx <= ordered.indexOf('ai-reviewing')) {
908
+ if (workflow.metadata) {
909
+ const { aiReviewResult, ...rest } = workflow.metadata || {};
910
+ workflow.metadata = { ...rest };
911
+ }
912
+ }
913
+ // Clear any failure/error context
914
+ workflow.error = undefined;
915
+ workflow.failureContext = undefined;
916
+ // Persist reset before kicking off rerun
917
+ await this.saveWorkflow(workflow);
918
+ // Notify listeners that the workflow snapshot changed (phase change will follow)
919
+ this.emit('workflowUpdated', workflow);
920
+ }
921
+ /**
922
+ * Perform AI code review of implemented changes
923
+ */
924
+ async performAICodeReview(workflowId, providedExecutionId) {
925
+ const workflow = this.workflows.get(workflowId);
926
+ if (!workflow)
927
+ return { passed: false };
928
+ try {
929
+ log.info('Running AI code review', { taskId: workflow.taskId }, 'vibing-orchestrator');
930
+ // Get worktree info for the task
931
+ const worktree = this.agentService.getWorktreeInfo(workflow.taskId);
932
+ if (!worktree) {
933
+ log.warn('No worktree found for AI code review, skipping', undefined, 'vibing-orchestrator');
934
+ return { passed: true, executionId: providedExecutionId };
935
+ }
936
+ // Execute AI code review via agent service
937
+ const review = await this.agentService.aiReviewCode(workflow.taskId, 'Automated AI code review triggered by workflow orchestrator', {
938
+ overrides: workflow.metadata?.aiRoutingOverrides?.ai_codereview,
939
+ executionId: providedExecutionId,
940
+ workflowId,
941
+ });
942
+ // Persist review result into workflow metadata
943
+ const timestamp = new Date().toISOString();
944
+ workflow.metadata = {
945
+ ...workflow.metadata,
946
+ aiReviewResult: { ...review, timestamp },
947
+ };
948
+ // Track execution ID under ai-reviewing for observability
949
+ const executionId = providedExecutionId ?? review?.executionId;
950
+ if (executionId) {
951
+ workflow.executionIds = workflow.executionIds || {};
952
+ const list = workflow.executionIds['ai-reviewing'] || [];
953
+ if (!list.includes(executionId)) {
954
+ workflow.executionIds['ai-reviewing'] = [...list, executionId];
955
+ }
956
+ }
957
+ await this.saveWorkflow(workflow);
958
+ // Gate by minimum score from settings
959
+ const minScore = await this.getAIReviewThreshold();
960
+ if (review.qualityScore < minScore) {
961
+ const msg = `AI code review score too low (${review.qualityScore} < ${minScore})`;
962
+ log.warn('AI code review score too low', { score: review.qualityScore, minScore }, 'vibing-orchestrator');
963
+ workflow.error = msg;
964
+ return { passed: false, executionId };
965
+ }
966
+ log.info('AI code review passed', { score: review.qualityScore }, 'vibing-orchestrator');
967
+ workflow.error = undefined;
968
+ return { passed: true, executionId };
969
+ }
970
+ catch (error) {
971
+ log.warn('AI code review failed', error, 'vibing-orchestrator');
972
+ const msg = error instanceof Error ? error.message : String(error);
973
+ const workflowRef = this.workflows.get(workflowId);
974
+ if (workflowRef) {
975
+ workflowRef.error = `AI code review failed: ${msg}`;
976
+ }
977
+ return { passed: false, executionId: providedExecutionId };
978
+ }
979
+ }
980
+ /**
981
+ * Execute AI review as a dedicated phase
982
+ */
983
+ async executeAiReviewPhase(workflowId) {
984
+ const workflow = this.workflows.get(workflowId);
985
+ if (!workflow)
986
+ return;
987
+ await this.transitionToPhase(workflowId, 'ai-reviewing');
988
+ try {
989
+ const attemptList = workflow.executionIds?.['ai-reviewing'] || [];
990
+ const attempt = attemptList.length + 1;
991
+ const execId = generateId('review');
992
+ workflow.executionIds = workflow.executionIds || {};
993
+ const aiList = workflow.executionIds['ai-reviewing'] || [];
994
+ workflow.executionIds['ai-reviewing'] = [...aiList, execId];
995
+ workflow.timeline = this.buildTimeline(workflow, {
996
+ id: execId,
997
+ label: attempt > 1 ? `AI Review – Retry #${attempt}` : 'AI Review',
998
+ phase: 'ai-reviewing',
999
+ attempt,
1000
+ executionId: execId,
1001
+ startTime: new Date().toISOString(),
1002
+ });
1003
+ await this.saveWorkflow(workflow);
1004
+ this.emit('workflowExecutionStarted', {
1005
+ workflowId,
1006
+ executionId: execId,
1007
+ phase: 'ai-reviewing',
1008
+ workflow,
1009
+ });
1010
+ const { passed } = await this.performAICodeReview(workflowId, execId);
1011
+ const latest = this.workflows.get(workflowId);
1012
+ if (latest) {
1013
+ const timeline = (latest.timeline || []);
1014
+ const item = timeline.find((t) => t.executionId === execId);
1015
+ if (item) {
1016
+ item.endTime = new Date().toISOString();
1017
+ if (!passed) {
1018
+ item.reason = latest.error || 'AI review did not pass the quality threshold';
1019
+ }
1020
+ latest.timeline = this.computeVisibleTimeline(latest);
1021
+ await this.saveWorkflow(latest);
1022
+ }
1023
+ }
1024
+ if (!passed) {
1025
+ const reason = workflow.error || 'AI review did not pass the quality threshold';
1026
+ const retried = await this.maybeRetryImplementation(workflowId, reason, 'ai-reviewing');
1027
+ if (!retried) {
1028
+ await this.handlePhaseFailure(workflowId, 'ai-reviewing', workflow.error);
1029
+ }
1030
+ return;
1031
+ }
1032
+ // AI review passed → set checkpoint
1033
+ workflow.status = 'ai-reviewed';
1034
+ workflow.lastUpdatedAt = new Date().toISOString();
1035
+ workflow.timeline = this.computeVisibleTimeline(workflow);
1036
+ await this.saveWorkflow(workflow);
1037
+ workflow.status = 'awaiting-review';
1038
+ workflow.lastUpdatedAt = new Date().toISOString();
1039
+ await this.saveWorkflow(workflow);
1040
+ await this.executeAwaitingReview(workflowId);
1041
+ const wf = this.workflows.get(workflowId);
1042
+ if (wf?.metadata.stepByStepMode) {
1043
+ log.info('Manual step mode – AI review passed; waiting for Continue', { workflowId }, 'vibing-orchestrator');
1044
+ }
1045
+ }
1046
+ catch (error) {
1047
+ await this.handlePhaseFailure(workflowId, 'ai-reviewing', error);
1048
+ }
1049
+ }
1050
+ async executeAwaitingReview(workflowId) {
1051
+ const workflow = this.workflows.get(workflowId);
1052
+ if (!workflow)
1053
+ return;
1054
+ await this.transitionToPhase(workflowId, 'awaiting-review');
1055
+ const hasReal = Array.isArray(workflow.timeline)
1056
+ ? workflow.timeline.some((t) => t.phase === 'awaiting-review' && !t.placeholder)
1057
+ : false;
1058
+ if (!hasReal) {
1059
+ workflow.timeline = this.buildTimeline(workflow, {
1060
+ id: `awaiting-review:${new Date().toISOString()}`,
1061
+ label: PHASE_LABELS['awaiting-review'],
1062
+ phase: 'awaiting-review',
1063
+ startTime: new Date().toISOString(),
1064
+ });
1065
+ }
1066
+ workflow.timeline = this.computeVisibleTimeline(workflow);
1067
+ await this.saveWorkflow(workflow);
1068
+ }
1069
+ /**
1070
+ * Execute validation phase with quality checks
1071
+ */
1072
+ async executeValidation(workflowId) {
1073
+ const workflow = this.workflows.get(workflowId);
1074
+ if (!workflow)
1075
+ return;
1076
+ await this.transitionToPhase(workflowId, 'validating');
1077
+ try {
1078
+ if (!workflow.metadata.autoQualityChecks) {
1079
+ // TODO implement later
1080
+ return;
1081
+ }
1082
+ log.info('Running quality checks', { taskId: workflow.taskId }, 'vibing-orchestrator');
1083
+ // Get worktree path for quality checks
1084
+ const worktree = this.agentService.getWorktreeInfo(workflow.taskId);
1085
+ const workingDirectory = worktree?.path || process.cwd();
1086
+ // Start a generic execution for validation to unify observability
1087
+ const execId = await this.agentService.startGenericExecution(workflow.taskId, {
1088
+ workflowId,
1089
+ workingDirectory,
1090
+ });
1091
+ workflow.executionIds = workflow.executionIds || {};
1092
+ const valList = workflow.executionIds['validating'] || [];
1093
+ workflow.executionIds['validating'] = [...valList, execId];
1094
+ workflow.timeline = this.buildTimeline(workflow, {
1095
+ id: `validation:${new Date().toISOString()}`,
1096
+ label: 'Validation',
1097
+ phase: 'validating',
1098
+ startTime: new Date().toISOString(),
1099
+ executionId: execId,
1100
+ });
1101
+ await this.saveWorkflow(workflow);
1102
+ // Notify listeners that a validation execution has started
1103
+ this.emit('workflowExecutionStarted', {
1104
+ workflowId,
1105
+ executionId: execId,
1106
+ phase: 'validating',
1107
+ workflow,
1108
+ });
1109
+ // Capture quality checks used for this workflow (from settings if not already set)
1110
+ try {
1111
+ if (!workflow.metadata.qualityChecks || workflow.metadata.qualityChecks.length === 0) {
1112
+ const { getSettingsService } = await import('../settings-service.js');
1113
+ const settingsService = getSettingsService();
1114
+ await settingsService.initialize();
1115
+ const settings = settingsService.getSettings();
1116
+ if (settings.quality?.checks?.length) {
1117
+ workflow.metadata.qualityChecks = settings.quality.checks;
1118
+ await this.saveWorkflow(workflow);
1119
+ }
1120
+ }
1121
+ }
1122
+ catch (e) {
1123
+ log.warn('Failed to get quality checks from settings', e, 'vibing-orchestrator');
1124
+ }
1125
+ // Run quality pipeline with streaming logs
1126
+ const qualityResults = await this.qualityPipeline.runChecksStreaming(workingDirectory, async (line) => {
1127
+ try {
1128
+ await this.agentService.logGenericExecution(execId, String(line));
1129
+ }
1130
+ catch (err) {
1131
+ log.debug('Failed to stream validation log line', err, 'vibing-orchestrator');
1132
+ }
1133
+ });
1134
+ workflow.qualityResults = qualityResults;
1135
+ // Timeline: end validation
1136
+ const timeline = workflow.timeline;
1137
+ for (let i = timeline.length - 1; i >= 0; i--) {
1138
+ const t = timeline[i];
1139
+ if (t.phase === 'validating' && !t.endTime) {
1140
+ t.endTime = new Date().toISOString();
1141
+ break;
1142
+ }
1143
+ }
1144
+ // Mark execution complete (completed even if checks failed; workflow handles failure)
1145
+ await this.agentService.completeGenericExecution(execId, 'completed');
1146
+ workflow.timeline = this.computeVisibleTimeline(workflow);
1147
+ await this.saveWorkflow(workflow);
1148
+ if (!qualityResults.overall) {
1149
+ log.info('Quality checks failed', { taskId: workflow.taskId }, 'vibing-orchestrator');
1150
+ workflow.error = 'Quality checks failed';
1151
+ const reason = 'Quality checks failed. Please address the reported issues.';
1152
+ const retried = await this.maybeRetryImplementation(workflowId, reason, 'validating');
1153
+ if (!retried) {
1154
+ await this.handlePhaseFailure(workflowId, 'validating', workflow.error);
1155
+ }
1156
+ return;
1157
+ }
1158
+ log.info('Quality checks passed', { taskId: workflow.taskId }, 'vibing-orchestrator');
1159
+ // Update checkpoint status
1160
+ await this.transitionToPhase(workflowId, 'validated');
1161
+ workflow.status = 'validated';
1162
+ workflow.lastUpdatedAt = new Date().toISOString();
1163
+ await this.saveWorkflow(workflow);
1164
+ if (workflow.metadata.aiCodeReview) {
1165
+ if (workflow.metadata.stepByStepMode) {
1166
+ log.info('Manual step mode – waiting for Continue to run AI review', { workflowId }, 'vibing-orchestrator');
1167
+ }
1168
+ else {
1169
+ await this.executeAiReviewPhase(workflowId);
1170
+ }
1171
+ }
1172
+ }
1173
+ catch (error) {
1174
+ await this.handlePhaseFailure(workflowId, 'validating', error);
1175
+ }
1176
+ }
1177
+ /**
1178
+ * Public: run validation phase on demand
1179
+ */
1180
+ async runValidation(workflowId) {
1181
+ const workflow = this.workflows.get(workflowId);
1182
+ if (!workflow)
1183
+ throw new Error(`Workflow ${workflowId} not found`);
1184
+ await this.executeValidation(workflowId);
1185
+ }
1186
+ /**
1187
+ * Execute merge phase
1188
+ */
1189
+ async executeMerge(workflowId, providerOverride) {
1190
+ const workflow = this.workflows.get(workflowId);
1191
+ if (!workflow)
1192
+ return;
1193
+ await this.transitionToPhase(workflowId, 'merging');
1194
+ let executionId;
1195
+ try {
1196
+ log.info('AI merging changes', { taskId: workflow.taskId }, 'vibing-orchestrator');
1197
+ const mergeList = workflow.executionIds?.['merging'] || [];
1198
+ const attempt = mergeList.length + 1;
1199
+ executionId = generateId('merge');
1200
+ const startTime = new Date().toISOString();
1201
+ workflow.executionIds = workflow.executionIds || {};
1202
+ workflow.executionIds['merging'] = [...mergeList, executionId];
1203
+ workflow.timeline = this.buildTimeline(workflow, {
1204
+ id: executionId,
1205
+ label: attempt > 1 ? `Merge – Retry #${attempt}` : 'Merge',
1206
+ phase: 'merging',
1207
+ attempt,
1208
+ executionId,
1209
+ startTime,
1210
+ });
1211
+ workflow.lastUpdatedAt = startTime;
1212
+ await this.saveWorkflow(workflow);
1213
+ this.emit('workflowUpdated', workflow);
1214
+ this.emit('workflowExecutionStarted', {
1215
+ workflowId,
1216
+ executionId,
1217
+ phase: 'merging',
1218
+ workflow,
1219
+ });
1220
+ await this.agentService.aiMerge(workflow.taskId, {
1221
+ baseBranch: 'main',
1222
+ executionId,
1223
+ workflowId,
1224
+ overrides: providerOverride || workflow.metadata?.aiRoutingOverrides?.ai_merge,
1225
+ });
1226
+ const mergeExec = this.agentService.getExecutionStatus(executionId);
1227
+ if (!mergeExec || mergeExec.status !== 'completed') {
1228
+ throw new Error(`AI merge failed: ${mergeExec?.error || 'Unknown error'}`);
1229
+ }
1230
+ const latest = this.workflows.get(workflowId) || workflow;
1231
+ const timeline = (latest.timeline || []);
1232
+ const tMerge = timeline.find((t) => t.executionId === executionId);
1233
+ if (tMerge) {
1234
+ tMerge.endTime = mergeExec.endTime || new Date().toISOString();
1235
+ tMerge.usage = mergeExec.usage;
1236
+ latest.timeline = this.computeVisibleTimeline(latest);
1237
+ latest.lastUpdatedAt = new Date().toISOString();
1238
+ await this.saveWorkflow(latest);
1239
+ }
1240
+ await this.taskService.updateTask(workflow.taskId, { status: 'done' });
1241
+ await this.transitionToPhase(workflowId, 'merged');
1242
+ const mergedWorkflow = this.workflows.get(workflowId);
1243
+ if (mergedWorkflow) {
1244
+ mergedWorkflow.status = 'merged';
1245
+ mergedWorkflow.lastUpdatedAt = new Date().toISOString();
1246
+ await this.saveWorkflow(mergedWorkflow);
1247
+ }
1248
+ if (workflow.metadata.stepByStepMode) {
1249
+ log.info('Manual step mode – merge completed; waiting for Continue', { workflowId }, 'vibing-orchestrator');
1250
+ }
1251
+ else {
1252
+ await this.updateCleanupStatus(workflowId);
1253
+ }
1254
+ log.info('Merge completed, ready for cleanup', { taskId: workflow.taskId }, 'vibing-orchestrator');
1255
+ }
1256
+ catch (error) {
1257
+ const latest = this.workflows.get(workflowId) || workflow;
1258
+ if (executionId && latest) {
1259
+ const timeline = (latest.timeline || []);
1260
+ const pending = timeline.find((t) => t.executionId === executionId);
1261
+ if (pending && !pending.endTime) {
1262
+ pending.endTime = new Date().toISOString();
1263
+ if (!pending.reason) {
1264
+ pending.reason = error instanceof Error ? error.message : String(error);
1265
+ }
1266
+ latest.timeline = this.computeVisibleTimeline(latest);
1267
+ latest.lastUpdatedAt = new Date().toISOString();
1268
+ await this.saveWorkflow(latest);
1269
+ }
1270
+ }
1271
+ await this.handlePhaseFailure(workflowId, 'merging', error);
1272
+ }
1273
+ }
1274
+ async updateCleanupStatus(workflowId) {
1275
+ const workflow = this.workflows.get(workflowId);
1276
+ if (!workflow)
1277
+ return;
1278
+ await this.transitionToPhase(workflowId, 'cleaning');
1279
+ workflow.status = 'cleaning';
1280
+ workflow.lastUpdatedAt = new Date().toISOString();
1281
+ workflow.timeline = this.buildTimeline(workflow, {
1282
+ id: `cleaning:${new Date().toISOString()}`,
1283
+ label: 'Cleaning',
1284
+ phase: 'cleaning',
1285
+ startTime: new Date().toISOString(),
1286
+ });
1287
+ await this.saveWorkflow(workflow);
1288
+ this.emit('workflowUpdated', workflow);
1289
+ }
1290
+ /**
1291
+ * Public: run merge phase on demand
1292
+ * This will attempt merge regardless of current phase.
1293
+ */
1294
+ async runMerge(workflowId, options) {
1295
+ const workflow = this.workflows.get(workflowId);
1296
+ if (!workflow)
1297
+ throw new Error(`Workflow ${workflowId} not found`);
1298
+ await this.executeMerge(workflowId, { provider: options?.provider, model: options?.model });
1299
+ }
1300
+ /**
1301
+ * Execute cleanup phase: remove worktree/branch and finalize workflow
1302
+ */
1303
+ async executeCleanup(workflowId) {
1304
+ const workflow = this.workflows.get(workflowId);
1305
+ if (!workflow)
1306
+ return;
1307
+ await this.transitionToPhase(workflowId, 'cleaning');
1308
+ try {
1309
+ log.info('Cleaning up resources', { taskId: workflow.taskId }, 'vibing-orchestrator');
1310
+ // Remove worktree and local branch if present
1311
+ try {
1312
+ await this.worktreeService.deleteWorktree(workflow.taskId, true);
1313
+ }
1314
+ catch (err) {
1315
+ log.warn('Cleanup encountered an issue (continuing)', err, 'vibing-orchestrator');
1316
+ }
1317
+ // Finalize workflow
1318
+ workflow.status = 'cleaned';
1319
+ workflow.endTime = new Date().toISOString();
1320
+ await this.transitionToPhase(workflowId, 'cleaned');
1321
+ workflow.status = 'completed';
1322
+ workflow.lastUpdatedAt = new Date().toISOString();
1323
+ await this.saveWorkflow(workflow);
1324
+ this.emit('workflowCompleted', workflow);
1325
+ log.info('Workflow completed', { taskId: workflow.taskId }, 'vibing-orchestrator');
1326
+ }
1327
+ catch (error) {
1328
+ log.error('Cleanup failed', error, 'vibing-orchestrator');
1329
+ workflow.error = error instanceof Error ? error.message : String(error);
1330
+ workflow.failureContext = {
1331
+ atPhase: 'cleaning',
1332
+ error: workflow.error,
1333
+ timestamp: new Date().toISOString(),
1334
+ };
1335
+ await this.transitionToPhase(workflowId, 'failed');
1336
+ workflow.status = 'failed';
1337
+ workflow.lastUpdatedAt = new Date().toISOString();
1338
+ await this.saveWorkflow(workflow);
1339
+ this.emit('workflowFailed', workflow);
1340
+ }
1341
+ }
1342
+ /**
1343
+ * Public: run cleanup phase on demand
1344
+ */
1345
+ async runCleanup(workflowId) {
1346
+ const workflow = this.workflows.get(workflowId);
1347
+ if (!workflow)
1348
+ throw new Error(`Workflow ${workflowId} not found`);
1349
+ await this.executeCleanup(workflowId);
1350
+ }
1351
+ /**
1352
+ * Public: manually skip to next phase
1353
+ */
1354
+ async skipToNextPhase(workflowId) {
1355
+ const workflow = this.workflows.get(workflowId);
1356
+ if (!workflow)
1357
+ throw new Error(`Workflow ${workflowId} not found`);
1358
+ // If anything is currently running for this task, stop it to move on quickly
1359
+ try {
1360
+ const executions = this.agentService.getTaskExecutions(workflow.taskId) || [];
1361
+ const running = executions
1362
+ .filter((e) => e.status === 'running')
1363
+ .sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())[0];
1364
+ if (running?.id) {
1365
+ await this.agentService.stopExecution(running.id);
1366
+ }
1367
+ }
1368
+ catch (error) {
1369
+ log.warn('Failed to stop execution before skipping phase', error, 'vibing-orchestrator');
1370
+ }
1371
+ // Determine the base phase to compute the "next" from.
1372
+ // For paused/failed, use the last known operational phase.
1373
+ const lastTransitionTo = workflow.phaseHistory?.[workflow.phaseHistory.length - 1]?.to;
1374
+ const basePhase = workflow.phase === 'paused'
1375
+ ? lastTransitionTo || workflow.lastPhase || 'draft'
1376
+ : workflow.phase === 'failed'
1377
+ ? (workflow.failureContext?.atPhase ||
1378
+ workflow.lastPhase ||
1379
+ lastTransitionTo ||
1380
+ 'implementing')
1381
+ : workflow.phase;
1382
+ const ordered = [
1383
+ 'draft',
1384
+ 'implementing',
1385
+ 'validating',
1386
+ 'ai-reviewing',
1387
+ 'awaiting-review',
1388
+ 'approved',
1389
+ 'merging',
1390
+ 'merged',
1391
+ 'cleaning',
1392
+ 'completed',
1393
+ // 'failed' and 'paused' are non-linear; excluded from the sequence
1394
+ ];
1395
+ const idx = ordered.indexOf(basePhase);
1396
+ const nextPhase = idx >= 0 && idx < ordered.length - 1 ? ordered[idx + 1] : 'completed';
1397
+ if (nextPhase && nextPhase !== workflow.phase) {
1398
+ log.info('Manually skipping workflow phase', { workflowId, currentPhase: workflow.phase, basePhase, nextPhase }, 'vibing-orchestrator');
1399
+ await this.transitionToPhase(workflowId, nextPhase);
1400
+ // Immediately kick off the next phase where applicable to make skipping faster
1401
+ switch (nextPhase) {
1402
+ case 'implementing':
1403
+ await this.executeImplementation(workflowId);
1404
+ break;
1405
+ case 'validating':
1406
+ await this.executeValidation(workflowId);
1407
+ break;
1408
+ case 'ai-reviewing':
1409
+ await this.executeAiReviewPhase(workflowId);
1410
+ break;
1411
+ case 'approved':
1412
+ case 'merging':
1413
+ await this.executeMerge(workflowId);
1414
+ break;
1415
+ case 'merged':
1416
+ case 'cleaning':
1417
+ await this.executeCleanup(workflowId);
1418
+ break;
1419
+ case 'awaiting-review':
1420
+ case 'completed':
1421
+ default:
1422
+ // No immediate action; awaiting-review waits for human approval; completed is terminal
1423
+ break;
1424
+ }
1425
+ }
1426
+ }
1427
+ /**
1428
+ * Wait for an execution to complete
1429
+ */
1430
+ async waitForExecution(executionId, timeoutMs = 30 * 60 * 1000) {
1431
+ const startTime = Date.now();
1432
+ let missingStatusWarned = false;
1433
+ while (Date.now() - startTime < timeoutMs) {
1434
+ const execution = this.agentService.getExecutionStatus(executionId);
1435
+ if (!execution) {
1436
+ if (!missingStatusWarned) {
1437
+ log.debug('Execution status not yet available; waiting for agent to register', { executionId }, 'vibing-orchestrator');
1438
+ missingStatusWarned = true;
1439
+ }
1440
+ await new Promise((resolve) => setTimeout(resolve, 500));
1441
+ continue;
1442
+ }
1443
+ missingStatusWarned = false;
1444
+ if (['completed', 'failed', 'cancelled'].includes(execution.status)) {
1445
+ return;
1446
+ }
1447
+ // Wait 5 seconds before checking again
1448
+ await new Promise((resolve) => setTimeout(resolve, 5000));
1449
+ }
1450
+ throw new Error(`Execution ${executionId} timed out after ${timeoutMs}ms`);
1451
+ }
1452
+ /**
1453
+ * Wait for the AgentService to emit an executionCreated event for the given task/workflow
1454
+ */
1455
+ waitForExecutionCreated(taskId, workflowId, timeoutMs = 15000) {
1456
+ return new Promise((resolve, reject) => {
1457
+ const onCreated = (data) => {
1458
+ try {
1459
+ if (data.taskId !== taskId)
1460
+ return;
1461
+ if (workflowId && data.workflowId !== workflowId)
1462
+ return;
1463
+ cleanup();
1464
+ resolve(data.executionId);
1465
+ }
1466
+ catch (err) {
1467
+ cleanup();
1468
+ reject(err instanceof Error ? err : new Error(String(err)));
1469
+ }
1470
+ };
1471
+ const cleanup = () => {
1472
+ clearTimeout(timer);
1473
+ this.agentService.off('executionCreated', onCreated);
1474
+ };
1475
+ const timer = setTimeout(() => {
1476
+ cleanup();
1477
+ reject(new Error('Timed out waiting for executionCreated event'));
1478
+ }, timeoutMs);
1479
+ this.agentService.on('executionCreated', onCreated);
1480
+ });
1481
+ }
1482
+ /**
1483
+ * Get workflow statistics
1484
+ */
1485
+ getWorkflowStats() {
1486
+ const workflows = Array.from(this.workflows.values());
1487
+ const stats = {
1488
+ total: workflows.length,
1489
+ byPhase: {},
1490
+ active: 0,
1491
+ completed: 0,
1492
+ failed: 0,
1493
+ };
1494
+ // Initialize phase counts
1495
+ const phases = [
1496
+ 'draft',
1497
+ 'implementing',
1498
+ 'validating',
1499
+ 'ai-reviewing',
1500
+ 'awaiting-review',
1501
+ 'paused',
1502
+ 'approved',
1503
+ 'merging',
1504
+ 'merged',
1505
+ 'cleaning',
1506
+ 'completed',
1507
+ 'failed',
1508
+ ];
1509
+ phases.forEach((phase) => {
1510
+ stats.byPhase[phase] = 0;
1511
+ });
1512
+ // Count workflows by phase
1513
+ workflows.forEach((workflow) => {
1514
+ stats.byPhase[workflow.phase]++;
1515
+ if ([
1516
+ 'implementing',
1517
+ 'validating',
1518
+ 'ai-reviewing',
1519
+ 'awaiting-review',
1520
+ 'approved',
1521
+ 'merging',
1522
+ 'cleaning',
1523
+ ].includes(workflow.phase)) {
1524
+ stats.active++;
1525
+ }
1526
+ else if (['completed', 'merged'].includes(workflow.phase)) {
1527
+ stats.completed++;
1528
+ }
1529
+ else if (workflow.phase === 'failed') {
1530
+ stats.failed++;
1531
+ }
1532
+ });
1533
+ return stats;
1534
+ }
1535
+ /**
1536
+ * Get workflow persistence information
1537
+ */
1538
+ getWorkflowPersistenceInfo() {
1539
+ return {
1540
+ filePath: this.workflowDB.getFilePath(),
1541
+ workflowCount: this.workflows.size,
1542
+ };
1543
+ }
1544
+ /**
1545
+ * Force save all workflows to disk
1546
+ */
1547
+ async saveAllWorkflows() {
1548
+ const obj = {};
1549
+ for (const [id, wf] of this.workflows)
1550
+ obj[id] = serializeVibe(wf);
1551
+ await this.workflowDB.setAll(obj);
1552
+ }
1553
+ /**
1554
+ * Reload workflows from disk
1555
+ */
1556
+ async reloadWorkflows() {
1557
+ const all = await this.workflowDB.getAll();
1558
+ const map = new Map();
1559
+ for (const [id, wf] of Object.entries(all)) {
1560
+ map.set(id, this.normalizeWorkflow(wf));
1561
+ }
1562
+ this.workflows = map;
1563
+ log.info('Reloaded workflows from disk', { count: this.workflows.size }, 'vibing-orchestrator');
1564
+ }
1565
+ /**
1566
+ * Remove workflows by task ID
1567
+ */
1568
+ async removeWorkflowsByTask(taskId) {
1569
+ const all = await this.workflowDB.getAll();
1570
+ let removedCount = 0;
1571
+ for (const [id, workflow] of Object.entries(all)) {
1572
+ if (workflow.taskId === taskId) {
1573
+ delete all[id];
1574
+ removedCount++;
1575
+ }
1576
+ }
1577
+ if (removedCount > 0) {
1578
+ await this.workflowDB.setAll(all);
1579
+ }
1580
+ // Also remove from memory
1581
+ for (const [id, workflow] of this.workflows) {
1582
+ if (workflow.taskId === taskId) {
1583
+ this.workflows.delete(id);
1584
+ }
1585
+ }
1586
+ return removedCount;
1587
+ }
1588
+ /**
1589
+ * Get comprehensive workflow statistics
1590
+ */
1591
+ async getDetailedStats() {
1592
+ return {
1593
+ memoryStats: this.getWorkflowStats(),
1594
+ persistenceStats: await getDbStats(this.workflowDB),
1595
+ persistencePath: this.workflowDB.getFilePath(),
1596
+ };
1597
+ }
1598
+ /**
1599
+ * Update workflow options without changing phase
1600
+ */
1601
+ async updateWorkflowOptions(workflowId, config) {
1602
+ const workflow = this.workflows.get(workflowId);
1603
+ if (!workflow) {
1604
+ throw new Error(`Workflow ${workflowId} not found`);
1605
+ }
1606
+ // Update metadata with new config
1607
+ workflow.metadata = { ...workflow.metadata, ...config };
1608
+ // Persist the updated workflow
1609
+ await this.saveWorkflow(workflow);
1610
+ log.info('Updated workflow options', { workflowId }, 'vibing-orchestrator');
1611
+ this.emit('workflowOptionsUpdated', workflow);
1612
+ }
1613
+ /**
1614
+ * Continue workflow execution from current state
1615
+ */
1616
+ async continueWorkflow(workflowId) {
1617
+ const workflow = this.workflows.get(workflowId);
1618
+ if (!workflow) {
1619
+ throw new Error(`Workflow ${workflowId} not found`);
1620
+ }
1621
+ log.info('Continuing workflow (status-driven)', { workflowId, phase: workflow.phase, status: workflow.status }, 'vibing-orchestrator');
1622
+ // If failed, prefer immediate retry of implementation
1623
+ if (workflow.phase === 'failed' || workflow.status === 'failed') {
1624
+ if (workflow.metadata.stepByStepMode) {
1625
+ await this.rerunImplementation(workflowId);
1626
+ }
1627
+ else {
1628
+ await this.executeImplementation(workflowId);
1629
+ }
1630
+ return;
1631
+ }
1632
+ // Compute next actionable phase from status/checkpoint
1633
+ const next = this.computeNextActionPhase(workflow);
1634
+ if (!next) {
1635
+ log.info('No actionable next phase (waiting for human or already done)', { workflowId, phase: workflow.phase, status: workflow.status }, 'vibing-orchestrator');
1636
+ return;
1637
+ }
1638
+ switch (next) {
1639
+ case 'implementing':
1640
+ await this.executeImplementation(workflowId);
1641
+ return;
1642
+ case 'validating':
1643
+ await this.executeValidation(workflowId);
1644
+ return;
1645
+ case 'ai-reviewing':
1646
+ await this.executeAiReviewPhase(workflowId);
1647
+ return;
1648
+ case 'awaiting-review':
1649
+ await this.executeAwaitingReview(workflowId);
1650
+ return;
1651
+ case 'merging':
1652
+ await this.executeMerge(workflowId);
1653
+ return;
1654
+ case 'cleaning':
1655
+ await this.executeCleanup(workflowId);
1656
+ return;
1657
+ default:
1658
+ throw new Error(`Unsupported next phase computed: ${next}`);
1659
+ }
1660
+ }
1661
+ // Decide next action from status/checkpoint and configuration
1662
+ computeNextActionPhase(workflow) {
1663
+ const status = workflow.status;
1664
+ const cfg = workflow.metadata || {};
1665
+ const requireHuman = !!cfg.requireHumanApproval;
1666
+ const wantsAIReview = !!cfg.aiCodeReview;
1667
+ // If paused, compute by last checkpoint
1668
+ // If failed handling is done earlier
1669
+ switch (status) {
1670
+ case undefined:
1671
+ case 'draft':
1672
+ return 'implementing';
1673
+ case 'implemented':
1674
+ return 'validating';
1675
+ case 'validated':
1676
+ if (wantsAIReview)
1677
+ return 'ai-reviewing';
1678
+ return requireHuman ? null : 'merging';
1679
+ case 'ai-reviewed':
1680
+ return requireHuman ? null : 'merging';
1681
+ case 'awaiting-review':
1682
+ return null; // wait for approveWorkflow
1683
+ case 'approved':
1684
+ return 'merging';
1685
+ case 'merged':
1686
+ return 'cleaning';
1687
+ case 'cleaned':
1688
+ return 'completed';
1689
+ case 'completed':
1690
+ return null;
1691
+ case 'paused':
1692
+ // Map paused to next by lastPhase or default to implementing
1693
+ return workflow.lastPhase || 'implementing';
1694
+ case 'failed':
1695
+ return 'implementing';
1696
+ default:
1697
+ return null;
1698
+ }
1699
+ }
1700
+ // ============ Small helpers to reduce duplication ============
1701
+ requireWorkflow(workflowId) {
1702
+ const wf = this.workflows.get(workflowId);
1703
+ if (!wf)
1704
+ throw new Error(`Workflow ${workflowId} not found`);
1705
+ return wf;
1706
+ }
1707
+ async getAIReviewThreshold() {
1708
+ try {
1709
+ const settingsService = getSettingsService();
1710
+ await settingsService.initialize();
1711
+ const settings = settingsService.getSettings();
1712
+ return settings.agents.judgeAgent.reviewThresholdScore;
1713
+ }
1714
+ catch (error) {
1715
+ log.warn('Failed to load AI review threshold from settings, using default', error, 'vibing-orchestrator');
1716
+ return 70; // fallback default
1717
+ }
1718
+ }
1719
+ assertPhase(workflow, expected, action) {
1720
+ if (workflow.phase !== expected) {
1721
+ throw new Error(`Cannot ${action} workflow in phase ${workflow.phase}; expected ${expected}`);
1722
+ }
1723
+ }
1724
+ createNewWorkflow(workflowId, taskId, config) {
1725
+ const now = new Date().toISOString();
1726
+ const wf = {
1727
+ id: workflowId,
1728
+ taskId,
1729
+ phase: 'draft',
1730
+ startTime: now,
1731
+ endTime: undefined,
1732
+ status: 'draft',
1733
+ // Phase tracking
1734
+ lastPhase: undefined,
1735
+ phaseHistory: [],
1736
+ failureContext: undefined,
1737
+ // Execution tracking and attempts per phase
1738
+ executionIds: {
1739
+ implementing: [],
1740
+ validating: [],
1741
+ 'ai-reviewing': [],
1742
+ merging: [],
1743
+ },
1744
+ attempts: {},
1745
+ // Rerun context audit trail
1746
+ rerunContextHistory: [],
1747
+ // Quality + links placeholders
1748
+ qualityResults: undefined,
1749
+ links: {},
1750
+ // Error placeholder
1751
+ error: undefined,
1752
+ // Observability/metrics
1753
+ metrics: { durationsMs: {}, lastPhaseStartedAt: now },
1754
+ lastUpdatedAt: now,
1755
+ // Persisted workflow configuration
1756
+ metadata: config,
1757
+ // Initial timeline marker
1758
+ timeline: [
1759
+ {
1760
+ id: 'start',
1761
+ label: 'Workflow started',
1762
+ phase: 'draft',
1763
+ startTime: now,
1764
+ },
1765
+ ],
1766
+ };
1767
+ // Seed placeholders for the rest of the flow
1768
+ wf.timeline = this.computeVisibleTimeline(wf);
1769
+ return wf;
1770
+ }
1771
+ async maybeRetryImplementation(workflowId, reason, _atPhase) {
1772
+ const workflow = this.requireWorkflow(workflowId);
1773
+ // In step-by-step mode, do not auto-retry; wait for explicit Continue
1774
+ if (workflow.metadata.stepByStepMode) {
1775
+ log.info('Step-by-step mode: skipping auto-retry of implementation', { workflowId, reason }, 'vibing-orchestrator');
1776
+ return false;
1777
+ }
1778
+ const max = workflow.metadata.retryPolicy?.maxImplementationAttempts || 0;
1779
+ const implementingCount = (workflow.phaseHistory || []).filter((h) => h.to === 'implementing').length;
1780
+ if (max > 0 && implementingCount < max) {
1781
+ await this.transitionToPhase(workflowId, 'implementing');
1782
+ await this.executeImplementation(workflowId, reason);
1783
+ return true;
1784
+ }
1785
+ return false;
1786
+ }
1787
+ async handlePhaseFailure(workflowId, atPhase, error) {
1788
+ const workflow = this.requireWorkflow(workflowId);
1789
+ const msg = error instanceof Error ? error.message : String(error);
1790
+ log.error(`${atPhase} failed`, error, 'vibing-orchestrator');
1791
+ workflow.error = msg;
1792
+ workflow.failureContext = {
1793
+ atPhase,
1794
+ error: msg,
1795
+ timestamp: new Date().toISOString(),
1796
+ };
1797
+ // Attach reason to last timeline item of this phase
1798
+ const wf = this.workflows.get(workflowId);
1799
+ if (wf && Array.isArray(wf.timeline)) {
1800
+ for (let i = wf.timeline.length - 1; i >= 0; i--) {
1801
+ const t = wf.timeline[i];
1802
+ if (t.phase === atPhase) {
1803
+ t.reason = msg;
1804
+ break;
1805
+ }
1806
+ }
1807
+ await this.saveWorkflow(wf);
1808
+ }
1809
+ await this.transitionToPhase(workflowId, 'failed');
1810
+ workflow.status = 'failed';
1811
+ workflow.lastUpdatedAt = new Date().toISOString();
1812
+ await this.saveWorkflow(workflow);
1813
+ this.emit('workflowFailed', workflow);
1814
+ }
1815
+ /**
1816
+ * Get the agent service instance
1817
+ */
1818
+ getAgentService() {
1819
+ return this.agentService;
1820
+ }
1821
+ }
1822
+ // Helpers local to this module
1823
+ function serializeVibe(workflow) {
1824
+ return {
1825
+ ...workflow,
1826
+ startTime: new Date(workflow.startTime).toISOString(),
1827
+ endTime: workflow.endTime ? new Date(workflow.endTime).toISOString() : undefined,
1828
+ qualityResults: workflow.qualityResults
1829
+ ? {
1830
+ ...workflow.qualityResults,
1831
+ timestamp: new Date(workflow.qualityResults.timestamp).toISOString(),
1832
+ }
1833
+ : undefined,
1834
+ };
1835
+ }
1836
+ async function getDbStats(db) {
1837
+ const all = await db.getAll();
1838
+ const stats = {
1839
+ total: 0,
1840
+ byPhase: {},
1841
+ oldestWorkflow: undefined,
1842
+ newestWorkflow: undefined,
1843
+ };
1844
+ let oldest = null;
1845
+ let newest = null;
1846
+ for (const wf of Object.values(all)) {
1847
+ stats.total += 1;
1848
+ stats.byPhase[wf.phase] = (stats.byPhase[wf.phase] || 0) + 1;
1849
+ const start = new Date(wf.startTime);
1850
+ if (!oldest || start < oldest) {
1851
+ oldest = start;
1852
+ stats.oldestWorkflow = wf.id;
1853
+ }
1854
+ if (!newest || start > newest) {
1855
+ newest = start;
1856
+ stats.newestWorkflow = wf.id;
1857
+ }
1858
+ }
1859
+ return stats;
1860
+ }