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