workflow-live-acceptance.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import assert from 'node:assert/strict'
  2. import { createHash, randomUUID } from 'node:crypto'
  3. import { createServer, type Server } from 'node:http'
  4. import { homedir, tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs'
  7. import { DatabaseSync } from 'node:sqlite'
  8. const PRODUCTION_TABLES = [
  9. 'workflows',
  10. 'workflow_runs',
  11. 'workflow_run_node_sessions',
  12. 'workflow_run_edge_evaluations',
  13. 'workflow_run_loop_epochs',
  14. ]
  15. function productionWorkflowSnapshot(path: string): Record<string, { count: number; sha256: string } | { missing: true }> {
  16. if (!existsSync(path)) return Object.fromEntries(PRODUCTION_TABLES.map(table => [table, { missing: true }]))
  17. const db = new DatabaseSync(path, { readOnly: true })
  18. try {
  19. return Object.fromEntries(PRODUCTION_TABLES.map(table => {
  20. try {
  21. const rows = db.prepare(`SELECT * FROM ${table} ORDER BY rowid`).all()
  22. return [table, {
  23. count: rows.length,
  24. sha256: createHash('sha256').update(JSON.stringify(rows)).digest('hex'),
  25. }]
  26. } catch (error) {
  27. if (String(error).includes('no such table')) return [table, { missing: true }]
  28. throw error
  29. }
  30. }))
  31. } finally {
  32. db.close()
  33. }
  34. }
  35. function stringifyInput(value: unknown): string {
  36. if (typeof value === 'string') return value
  37. if (!Array.isArray(value)) return JSON.stringify(value)
  38. return value.map(item => {
  39. if (!item || typeof item !== 'object') return String(item)
  40. const record = item as Record<string, unknown>
  41. return String(record.text ?? record.content ?? '')
  42. }).join('\n')
  43. }
  44. function agent(id: string, input = id): Record<string, unknown> {
  45. return { id, type: 'agent', position: { x: 0, y: 0 }, data: { title: id, agent: 'hermes', input, skills: [], approvalRequired: false } }
  46. }
  47. function feedback(id: string, source: string, target: string, maxIterations?: number, loopId?: string): Record<string, unknown> {
  48. const value = maxIterations === undefined && loopId === undefined
  49. ? true
  50. : { ...(maxIterations === undefined ? {} : { maxIterations }), ...(loopId ? { loopId } : {}) }
  51. return { id, source, target, data: { orchestration: { route: 'success', feedback: value } } }
  52. }
  53. async function closeServer(server: Server | null): Promise<void> {
  54. if (!server?.listening) return
  55. await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
  56. }
  57. async function main(): Promise<void> {
  58. const originalCwd = process.cwd()
  59. const productionDb = process.env.WORKFLOW_LIVE_PRODUCTION_DB || join(homedir(), '.hermes-web-ui', 'hermes-web-ui.db')
  60. const productionBefore = productionWorkflowSnapshot(productionDb)
  61. const tempRoot = mkdtempSync(join(tmpdir(), 'hermes-studio-workflow-live-'))
  62. const cleanupTempRoot = () => rmSync(tempRoot, { recursive: true, force: true })
  63. process.once('exit', cleanupTempRoot)
  64. const evidencePath = process.env.WORKFLOW_LIVE_EVIDENCE || '/tmp/hermes-studio-workflow-live-evidence.json'
  65. const prefix = `live-${Date.now()}-${randomUUID().slice(0, 8)}`
  66. let server: Server | null = null
  67. let baseUrl = ''
  68. const createdWorkflowIds: string[] = []
  69. const requests: Array<{ sessionId: string; input: string }> = []
  70. const aborted: Array<{ sessionId: string; reason: string }> = []
  71. const held = new Map<string, (result: { ok: true; output: string }) => void>()
  72. const scenarios: Record<string, unknown> = {}
  73. process.env.NODE_ENV = 'test'
  74. process.env.VITEST = 'true'
  75. process.env.HERMES_WEB_UI_HOME = join(tempRoot, 'webui')
  76. process.env.HERMES_WEBUI_STATE_DIR = process.env.HERMES_WEB_UI_HOME
  77. process.env.HERMES_HOME = join(tempRoot, 'hermes')
  78. process.env.PROFILE = 'default'
  79. process.chdir(tempRoot)
  80. const [{ default: Koa }, bodyParserModule, routesModule, chatRunModule, initModule, managerModule, runStoreModule, dbModule] = await Promise.all([
  81. import('koa'),
  82. import('@koa/bodyparser'),
  83. import('../packages/server/src/routes/hermes/workflows'),
  84. import('../packages/server/src/routes/hermes/chat-run'),
  85. import('../packages/server/src/db/hermes/init'),
  86. import('../packages/server/src/services/workflow-manager'),
  87. import('../packages/server/src/db/hermes/workflow-run-store'),
  88. import('../packages/server/src/db'),
  89. ])
  90. const bodyParser = bodyParserModule.default
  91. const manager = managerModule.getWorkflowManager()
  92. const runner = {
  93. runAndWait: async (request: any, options?: { timeoutMs?: number }) => {
  94. const input = stringifyInput(request.input)
  95. requests.push({ sessionId: request.session_id, input })
  96. if (input.includes('HOLD_SOURCE')) {
  97. return await new Promise<{ ok: true; output: string }>(resolve => held.set(request.session_id, resolve))
  98. }
  99. if (input.includes('TIMEOUT_SOURCE')) return { ok: false, error: `chat-run timed out after ${options?.timeoutMs}ms` }
  100. if (input.includes('FAIL_SOURCE')) return { ok: false, error: 'deterministic source failure' }
  101. if (input.includes('PASS_SOURCE')) return { ok: true, output: 'PASS' }
  102. return { ok: true, output: 'continue' }
  103. },
  104. abortSession: async (sessionId: string, reason: string) => {
  105. aborted.push({ sessionId, reason })
  106. },
  107. }
  108. chatRunModule.setChatRunServer(runner as any)
  109. initModule.initAllStores()
  110. const app = new Koa()
  111. app.use(async (ctx: any, next: any) => {
  112. try { await next() } catch (error) {
  113. ctx.status = Number((error as any)?.status) || 500
  114. ctx.body = { error: error instanceof Error ? error.message : String(error) }
  115. }
  116. })
  117. app.use(bodyParser())
  118. app.use(async (ctx: any, next: any) => {
  119. ctx.state.user = { id: 'workflow-live-acceptance', role: 'super_admin' }
  120. ctx.state.profile = { name: 'default' }
  121. await next()
  122. })
  123. app.use(routesModule.workflowRoutes.routes())
  124. app.use(routesModule.workflowRoutes.allowedMethods())
  125. server = createServer(app.callback())
  126. await new Promise<void>((resolve, reject) => {
  127. server!.once('error', reject)
  128. server!.listen(0, '127.0.0.1', () => resolve())
  129. })
  130. const address = server.address()
  131. if (!address || typeof address === 'string') throw new Error('disposable HTTP server has no TCP address')
  132. baseUrl = `http://127.0.0.1:${address.port}`
  133. async function api(method: string, path: string, body?: unknown, expected?: number): Promise<any> {
  134. const response = await fetch(`${baseUrl}${path}`, {
  135. method,
  136. headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
  137. body: body === undefined ? undefined : JSON.stringify(body),
  138. })
  139. const text = await response.text()
  140. const payload = text ? JSON.parse(text) : null
  141. if (expected !== undefined) assert.equal(response.status, expected, `${method} ${path}: ${text}`)
  142. return { status: response.status, body: payload }
  143. }
  144. async function createWorkflow(name: string, nodes: unknown[], edges: unknown[]): Promise<any> {
  145. const response = await api('POST', '/api/hermes/workflows', { name: `${prefix}-${name}`, profile: 'default', workspace: null, nodes, edges, viewport: null }, 201)
  146. createdWorkflowIds.push(response.body.workflow.id)
  147. return response.body.workflow
  148. }
  149. async function listRuns(workflowId: string): Promise<any[]> {
  150. return (await api('GET', `/api/hermes/workflows/${workflowId}/runs`, undefined, 200)).body.runs
  151. }
  152. async function waitForRun(workflowId: string, runId?: string, terminal = true): Promise<any> {
  153. const deadline = Date.now() + 10_000
  154. while (Date.now() < deadline) {
  155. const runs = await listRuns(workflowId)
  156. const run = runId ? runs.find(item => item.id === runId) : runs[0]
  157. if (run && (!terminal || !['queued', 'running'].includes(run.status))) return run
  158. await new Promise(resolve => setTimeout(resolve, 10))
  159. }
  160. throw new Error(`timed out waiting for workflow ${workflowId} run ${runId || '<latest>'}`)
  161. }
  162. async function startAndWait(workflowId: string, body: Record<string, unknown> = {}): Promise<any> {
  163. await api('POST', `/api/hermes/workflows/${workflowId}/run`, body, 202)
  164. return waitForRun(workflowId)
  165. }
  166. try {
  167. // Real persisted branch decisions, true skipped state, and append-only evidence.
  168. const branch = await createWorkflow('branch', [
  169. agent('source', 'PASS_SOURCE'), agent('matched'), agent('unmatched'), agent('always'),
  170. ], [
  171. { id: 'yes', source: 'source', target: 'matched', data: { orchestration: { route: 'success', condition: { path: 'output', operator: 'equals', value: 'PASS' } } } },
  172. { id: 'no', source: 'source', target: 'unmatched', data: { orchestration: { route: 'success', condition: { path: 'output', operator: 'equals', value: 'RETRY' } } } },
  173. { id: 'always', source: 'source', target: 'always', data: { orchestration: { route: 'always' } } },
  174. ])
  175. const branchRun = await startAndWait(branch.id)
  176. assert.equal(branchRun.status, 'completed')
  177. assert.deepEqual(branchRun.node_sessions.map((item: any) => item.node_id).sort(), ['always', 'matched', 'source'])
  178. assert.deepEqual(Object.fromEntries(branchRun.edge_evaluations.map((item: any) => [item.edge_id, item.status])), { yes: 'taken', no: 'not_taken', always: 'taken' })
  179. assert.equal(manager.getRuntimeStatus(branch.id).nodeStatuses.unmatched, 'skipped')
  180. scenarios.branch = { runStatus: branchRun.status, nodes: manager.getRuntimeStatus(branch.id).nodeStatuses, edges: branchRun.edge_evaluations.map((item: any) => [item.edge_id, item.status]) }
  181. // Failure and always continue, while success is truly skipped and the Run remains failed.
  182. const failure = await createWorkflow('failure', [agent('source', 'FAIL_SOURCE'), agent('success'), agent('failure'), agent('always')], [
  183. { id: 'success-edge', source: 'source', target: 'success', data: { orchestration: { route: 'success' } } },
  184. { id: 'failure-edge', source: 'source', target: 'failure', data: { orchestration: { route: 'failure' } } },
  185. { id: 'always-edge', source: 'source', target: 'always', data: { orchestration: { route: 'always' } } },
  186. ])
  187. const failureRun = await startAndWait(failure.id)
  188. assert.equal(failureRun.status, 'failed')
  189. assert.deepEqual(failureRun.node_sessions.map((item: any) => item.node_id).sort(), ['always', 'failure', 'source'])
  190. assert.equal(manager.getRuntimeStatus(failure.id).nodeStatuses.success, 'skipped')
  191. scenarios.failure = { runStatus: failureRun.status, nodes: manager.getRuntimeStatus(failure.id).nodeStatuses }
  192. // Default three iterations and custom two iterations.
  193. const defaultLoop = await createWorkflow('loop-default', [agent('header'), agent('latch')], [
  194. { id: 'forward', source: 'header', target: 'latch' }, feedback('retry', 'latch', 'header'),
  195. ])
  196. const defaultRun = await startAndWait(defaultLoop.id)
  197. assert.equal(defaultRun.node_sessions.length, 6)
  198. assert.equal(defaultRun.loop_epochs.length, 3)
  199. assert.equal(defaultRun.edge_evaluations.filter((item: any) => item.edge_id === 'retry').at(-1).reason, 'iteration_limit_reached')
  200. const customLoop = await createWorkflow('loop-custom', [agent('header'), agent('latch')], [
  201. { id: 'forward', source: 'header', target: 'latch' }, feedback('retry', 'latch', 'header', 2, 'custom-loop'),
  202. ])
  203. const customRun = await startAndWait(customLoop.id)
  204. assert.equal(customRun.node_sessions.length, 4)
  205. assert.equal(customRun.loop_epochs.length, 2)
  206. scenarios.loops = { defaultExecutions: defaultRun.node_sessions.length, defaultEpochs: defaultRun.loop_epochs.length, customExecutions: customRun.node_sessions.length, customEpochs: customRun.loop_epochs.length }
  207. // Rerun appends a separate execution scope to the same Run instead of overwriting history.
  208. await api('POST', `/api/hermes/workflows/${customLoop.id}/runs/${customRun.id}/rerun-from-node`, { node_id: 'header' }, 202)
  209. const rerun = await waitForRun(customLoop.id, customRun.id)
  210. assert.equal(rerun.status, 'completed')
  211. const rerunSessions = rerun.node_sessions.filter((item: any) => item.execution_id.includes('@rerun:'))
  212. assert.equal(rerunSessions.length, 4)
  213. assert.equal(rerun.node_sessions.length, 8)
  214. assert.equal(new Set(rerun.node_sessions.map((item: any) => item.execution_id)).size, 8)
  215. scenarios.rerun = { totalExecutions: rerun.node_sessions.length, scopedExecutions: rerunSessions.length, scope: rerunSessions[0].iteration_path[0].executionScope }
  216. // Nested 2x2 loop preserves canonical outer/inner iteration history.
  217. const nested = await createWorkflow('nested', ['outer-h', 'inner-h', 'inner-l', 'outer-l'].map(id => agent(id)), [
  218. { id: 'outer-inner', source: 'outer-h', target: 'inner-h' },
  219. { id: 'inner-forward', source: 'inner-h', target: 'inner-l' },
  220. { id: 'inner-outer', source: 'inner-l', target: 'outer-l' },
  221. feedback('inner-retry', 'inner-l', 'inner-h', 2, 'inner-loop'),
  222. feedback('outer-retry', 'outer-l', 'outer-h', 2, 'outer-loop'),
  223. ])
  224. const nestedRun = await startAndWait(nested.id)
  225. assert.equal(nestedRun.node_sessions.length, 12)
  226. assert.equal(nestedRun.loop_epochs.length, 6)
  227. const deepest = nestedRun.node_sessions.find((item: any) => item.node_id === 'inner-h' && item.iteration_path.length === 2 && item.iteration_path[0].iteration === 1 && item.iteration_path[1].iteration === 1)
  228. assert.ok(deepest)
  229. const timeline = [...nestedRun.node_sessions, ...nestedRun.edge_evaluations, ...nestedRun.loop_epochs].sort((a: any, b: any) => a.sequence - b.sequence)
  230. assert.equal(new Set(timeline.map((item: any) => item.sequence)).size, timeline.length)
  231. scenarios.nested = { executions: nestedRun.node_sessions.length, epochs: nestedRun.loop_epochs.length, deepestPath: deepest.iteration_path, timelineEntries: timeline.length }
  232. // Static budget rejection occurs before durable Run acceptance/persistence.
  233. const budgetNodes = Array.from({ length: 11 }, (_, index) => agent(`n${index}`))
  234. const budgetEdges = Array.from({ length: 10 }, (_, index) => ({ id: `e${index}`, source: `n${index}`, target: `n${index + 1}` }))
  235. budgetEdges.push(feedback('budget-retry', 'n10', 'n0', 100) as any)
  236. const budget = await createWorkflow('budget', budgetNodes, budgetEdges)
  237. const budgetResponse = await api('POST', `/api/hermes/workflows/${budget.id}/run`, {}, 400)
  238. assert.match(budgetResponse.body.error, /execution bound 1100 exceeds run budget 1000/)
  239. assert.equal((await listRuns(budget.id)).length, 0)
  240. scenarios.budget = { status: budgetResponse.status, error: budgetResponse.body.error, persistedRuns: 0 }
  241. // Exact runner timeout is classified as the Run-level absolute deadline failure.
  242. const timeout = await createWorkflow('timeout', [agent('source', 'TIMEOUT_SOURCE')], [])
  243. const timeoutRun = await startAndWait(timeout.id, { timeout_ms: 250 })
  244. assert.equal(timeoutRun.status, 'failed')
  245. assert.equal(timeoutRun.error, 'workflow run timed out after 250ms')
  246. assert.equal(timeoutRun.node_sessions[0].status, 'failed')
  247. scenarios.timeout = { runStatus: timeoutRun.status, error: timeoutRun.error, nodeStatus: timeoutRun.node_sessions[0].status }
  248. // Stop persists canceled before abort; a late success cannot overwrite or dispatch target.
  249. const cancel = await createWorkflow('cancel', [agent('source', 'HOLD_SOURCE'), agent('target')], [{ id: 'next', source: 'source', target: 'target' }])
  250. await api('POST', `/api/hermes/workflows/${cancel.id}/run`, {}, 202)
  251. const running = await waitForRun(cancel.id, undefined, false)
  252. assert.equal(running.status, 'running')
  253. const stop = await api('POST', `/api/hermes/workflows/${cancel.id}/runs/${running.id}/stop`, {}, 200)
  254. assert.equal(stop.body.run.status, 'canceled')
  255. for (const release of held.values()) release({ ok: true, output: 'late success' })
  256. held.clear()
  257. await new Promise(resolve => setTimeout(resolve, 30))
  258. const canceledRun = await waitForRun(cancel.id, running.id)
  259. assert.equal(canceledRun.status, 'canceled')
  260. assert.deepEqual(canceledRun.node_sessions.map((item: any) => item.node_id), ['source'])
  261. assert.equal(canceledRun.edge_evaluations.length, 0)
  262. assert.ok(aborted.some(item => item.reason === 'Workflow run canceled by user'))
  263. scenarios.cancel = { runStatus: canceledRun.status, sessions: canceledRun.node_sessions.map((item: any) => item.node_id), edges: canceledRun.edge_evaluations.length, aborts: aborted.length }
  264. // Restart recovery fails every active execution closed, then HTTP delete removes all evidence.
  265. const recovery = await createWorkflow('recovery', [agent('node')], [])
  266. const orphan = runStoreModule.createWorkflowRun({ workflow_id: recovery.id, profile: 'default', status: 'running', snapshot_nodes: recovery.nodes, snapshot_edges: [], compiled_loops: [], started_at: Date.now() })
  267. runStoreModule.createWorkflowRunNodeSession({ run_id: orphan.id, workflow_id: recovery.id, node_id: 'node', execution_id: 'node@orphan', session_id: `orphan-${randomUUID()}`, profile: 'default', agent: 'hermes', status: 'running', sequence: 0, started_at: Date.now() })
  268. const recovered = await manager.recoverActiveRuns(recovery.id)
  269. assert.deepEqual(recovered, { runs: 1, sessions: 1 })
  270. const recoveredRun = (await api('GET', `/api/hermes/workflows/${recovery.id}/runs/${orphan.id}`, undefined, 200)).body.run
  271. assert.equal(recoveredRun.status, 'failed')
  272. assert.equal(recoveredRun.node_sessions[0].status, 'failed')
  273. await api('DELETE', `/api/hermes/workflows/${recovery.id}/runs/${orphan.id}`, undefined, 200)
  274. await api('GET', `/api/hermes/workflows/${recovery.id}/runs/${orphan.id}`, undefined, 404)
  275. assert.equal(runStoreModule.getWorkflowRun(orphan.id), null)
  276. scenarios.recoveryDelete = { recovered, status: recoveredRun.status, nodeStatus: recoveredRun.node_sessions[0].status, deleted: true }
  277. // Delete a completed Run and verify Node/Edge/Loop history is removed together.
  278. await api('DELETE', `/api/hermes/workflows/${nested.id}/runs/${nestedRun.id}`, undefined, 200)
  279. assert.equal(runStoreModule.getWorkflowRun(nestedRun.id), null)
  280. assert.deepEqual(runStoreModule.listWorkflowRunNodeSessions(nestedRun.id), [])
  281. assert.deepEqual(runStoreModule.listWorkflowRunEdgeEvaluations(nestedRun.id), [])
  282. assert.deepEqual(runStoreModule.listWorkflowRunLoopEpochs(nestedRun.id), [])
  283. scenarios.deleteCleanup = { run: 0, node: 0, edge: 0, loop: 0 }
  284. } finally {
  285. for (const release of held.values()) release({ ok: true, output: 'cleanup' })
  286. held.clear()
  287. for (const workflowId of [...createdWorkflowIds].reverse()) {
  288. try { await api('DELETE', `/api/hermes/workflows/${workflowId}`, undefined) } catch {}
  289. }
  290. await closeServer(server)
  291. chatRunModule.setChatRunServer(null as any)
  292. dbModule.closeDb()
  293. process.chdir(originalCwd)
  294. }
  295. const productionAfter = productionWorkflowSnapshot(productionDb)
  296. assert.deepEqual(productionAfter, productionBefore, `production Workflow tables changed during disposable acceptance: ${productionDb}`)
  297. const evidence = {
  298. ok: true,
  299. prefix,
  300. isolatedRoot: tempRoot,
  301. isolatedDatabase: join(tempRoot, 'packages/server/data/test-runtime/hermes-web-ui.db'),
  302. productionDatabase: productionDb,
  303. productionWorkflowTablesUnchanged: true,
  304. productionSnapshot: productionAfter,
  305. deterministicRunnerRequests: requests.length,
  306. scenarios,
  307. }
  308. writeFileSync(evidencePath, JSON.stringify(evidence, null, 2))
  309. cleanupTempRoot()
  310. process.removeListener('exit', cleanupTempRoot)
  311. console.log(JSON.stringify({ ...evidence, isolatedRoot: '<removed>', isolatedDatabase: '<removed>' }, null, 2))
  312. console.log(`Evidence: ${evidencePath}`)
  313. }
  314. main().then(
  315. () => process.exit(0),
  316. error => {
  317. console.error(error)
  318. process.exit(1)
  319. },
  320. )
粤ICP备19079148号