awaitly 1.0.0

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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1278 -0
  3. package/dist/batch.cjs +2 -0
  4. package/dist/batch.cjs.map +1 -0
  5. package/dist/batch.d.cts +197 -0
  6. package/dist/batch.d.ts +197 -0
  7. package/dist/batch.js +2 -0
  8. package/dist/batch.js.map +1 -0
  9. package/dist/circuit-breaker.cjs +2 -0
  10. package/dist/circuit-breaker.cjs.map +1 -0
  11. package/dist/circuit-breaker.d.cts +208 -0
  12. package/dist/circuit-breaker.d.ts +208 -0
  13. package/dist/circuit-breaker.js +2 -0
  14. package/dist/circuit-breaker.js.map +1 -0
  15. package/dist/conditional.cjs +2 -0
  16. package/dist/conditional.cjs.map +1 -0
  17. package/dist/conditional.d.cts +249 -0
  18. package/dist/conditional.d.ts +249 -0
  19. package/dist/conditional.js +2 -0
  20. package/dist/conditional.js.map +1 -0
  21. package/dist/core-BuTBsR0x.d.cts +2325 -0
  22. package/dist/core-BuTBsR0x.d.ts +2325 -0
  23. package/dist/core.cjs +2 -0
  24. package/dist/core.cjs.map +1 -0
  25. package/dist/core.d.cts +3 -0
  26. package/dist/core.d.ts +3 -0
  27. package/dist/core.js +2 -0
  28. package/dist/core.js.map +1 -0
  29. package/dist/devtools.cjs +11 -0
  30. package/dist/devtools.cjs.map +1 -0
  31. package/dist/devtools.d.cts +176 -0
  32. package/dist/devtools.d.ts +176 -0
  33. package/dist/devtools.js +11 -0
  34. package/dist/devtools.js.map +1 -0
  35. package/dist/duration.cjs +2 -0
  36. package/dist/duration.cjs.map +1 -0
  37. package/dist/duration.d.cts +246 -0
  38. package/dist/duration.d.ts +246 -0
  39. package/dist/duration.js +2 -0
  40. package/dist/duration.js.map +1 -0
  41. package/dist/hitl.cjs +2 -0
  42. package/dist/hitl.cjs.map +1 -0
  43. package/dist/hitl.d.cts +337 -0
  44. package/dist/hitl.d.ts +337 -0
  45. package/dist/hitl.js +2 -0
  46. package/dist/hitl.js.map +1 -0
  47. package/dist/index.cjs +2 -0
  48. package/dist/index.cjs.map +1 -0
  49. package/dist/index.d.cts +4 -0
  50. package/dist/index.d.ts +4 -0
  51. package/dist/index.js +2 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/match.cjs +2 -0
  54. package/dist/match.cjs.map +1 -0
  55. package/dist/match.d.cts +209 -0
  56. package/dist/match.d.ts +209 -0
  57. package/dist/match.js +2 -0
  58. package/dist/match.js.map +1 -0
  59. package/dist/otel.cjs +2 -0
  60. package/dist/otel.cjs.map +1 -0
  61. package/dist/otel.d.cts +185 -0
  62. package/dist/otel.d.ts +185 -0
  63. package/dist/otel.js +2 -0
  64. package/dist/otel.js.map +1 -0
  65. package/dist/persistence.cjs +2 -0
  66. package/dist/persistence.cjs.map +1 -0
  67. package/dist/persistence.d.cts +572 -0
  68. package/dist/persistence.d.ts +572 -0
  69. package/dist/persistence.js +2 -0
  70. package/dist/persistence.js.map +1 -0
  71. package/dist/policies.cjs +2 -0
  72. package/dist/policies.cjs.map +1 -0
  73. package/dist/policies.d.cts +378 -0
  74. package/dist/policies.d.ts +378 -0
  75. package/dist/policies.js +2 -0
  76. package/dist/policies.js.map +1 -0
  77. package/dist/ratelimit.cjs +2 -0
  78. package/dist/ratelimit.cjs.map +1 -0
  79. package/dist/ratelimit.d.cts +279 -0
  80. package/dist/ratelimit.d.ts +279 -0
  81. package/dist/ratelimit.js +2 -0
  82. package/dist/ratelimit.js.map +1 -0
  83. package/dist/reliability.cjs +2 -0
  84. package/dist/reliability.cjs.map +1 -0
  85. package/dist/reliability.d.cts +5 -0
  86. package/dist/reliability.d.ts +5 -0
  87. package/dist/reliability.js +2 -0
  88. package/dist/reliability.js.map +1 -0
  89. package/dist/resource.cjs +2 -0
  90. package/dist/resource.cjs.map +1 -0
  91. package/dist/resource.d.cts +171 -0
  92. package/dist/resource.d.ts +171 -0
  93. package/dist/resource.js +2 -0
  94. package/dist/resource.js.map +1 -0
  95. package/dist/retry.cjs +2 -0
  96. package/dist/retry.cjs.map +1 -0
  97. package/dist/retry.d.cts +2 -0
  98. package/dist/retry.d.ts +2 -0
  99. package/dist/retry.js +2 -0
  100. package/dist/retry.js.map +1 -0
  101. package/dist/saga.cjs +2 -0
  102. package/dist/saga.cjs.map +1 -0
  103. package/dist/saga.d.cts +231 -0
  104. package/dist/saga.d.ts +231 -0
  105. package/dist/saga.js +2 -0
  106. package/dist/saga.js.map +1 -0
  107. package/dist/schedule.cjs +2 -0
  108. package/dist/schedule.cjs.map +1 -0
  109. package/dist/schedule.d.cts +387 -0
  110. package/dist/schedule.d.ts +387 -0
  111. package/dist/schedule.js +2 -0
  112. package/dist/schedule.js.map +1 -0
  113. package/dist/tagged-error.cjs +2 -0
  114. package/dist/tagged-error.cjs.map +1 -0
  115. package/dist/tagged-error.d.cts +252 -0
  116. package/dist/tagged-error.d.ts +252 -0
  117. package/dist/tagged-error.js +2 -0
  118. package/dist/tagged-error.js.map +1 -0
  119. package/dist/testing.cjs +2 -0
  120. package/dist/testing.cjs.map +1 -0
  121. package/dist/testing.d.cts +228 -0
  122. package/dist/testing.d.ts +228 -0
  123. package/dist/testing.js +2 -0
  124. package/dist/testing.js.map +1 -0
  125. package/dist/visualize.cjs +1573 -0
  126. package/dist/visualize.cjs.map +1 -0
  127. package/dist/visualize.d.cts +1415 -0
  128. package/dist/visualize.d.ts +1415 -0
  129. package/dist/visualize.js +1573 -0
  130. package/dist/visualize.js.map +1 -0
  131. package/dist/webhook.cjs +2 -0
  132. package/dist/webhook.cjs.map +1 -0
  133. package/dist/webhook.d.cts +469 -0
  134. package/dist/webhook.d.ts +469 -0
  135. package/dist/webhook.js +2 -0
  136. package/dist/webhook.js.map +1 -0
  137. package/dist/workflow-entry-C6nH8ByN.d.ts +858 -0
  138. package/dist/workflow-entry-RRTlSg_4.d.cts +858 -0
  139. package/dist/workflow.cjs +2 -0
  140. package/dist/workflow.cjs.map +1 -0
  141. package/dist/workflow.d.cts +2 -0
  142. package/dist/workflow.d.ts +2 -0
  143. package/dist/workflow.js +2 -0
  144. package/dist/workflow.js.map +1 -0
  145. package/docs/advanced.md +1548 -0
  146. package/docs/api.md +513 -0
  147. package/docs/coming-from-neverthrow.md +1013 -0
  148. package/docs/match.md +417 -0
  149. package/docs/pino-logging-example.md +396 -0
  150. package/docs/policies.md +508 -0
  151. package/docs/resource-management.md +509 -0
  152. package/docs/schedule.md +467 -0
  153. package/docs/tagged-error.md +785 -0
  154. package/docs/visualization.md +430 -0
  155. package/docs/visualize-examples.md +330 -0
  156. package/package.json +227 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/devtools-entry.ts","../src/visualize/utils/timing.ts","../src/visualize/parallel-detector.ts","../src/visualize/ir-builder.ts","../src/visualize/types.ts","../src/visualize/renderers/colors.ts","../src/visualize/renderers/ascii.ts","../src/visualize/performance-analyzer.ts","../src/visualize/renderers/mermaid.ts","../src/visualize/renderers/flowchart.ts","../src/visualize/renderers/logger.ts","../src/visualize/dev-server.ts","../src/visualize/index.ts","../src/devtools.ts"],"sourcesContent":["/**\n * awaitly/devtools\n *\n * Debugging and development tools: timeline visualization, run comparison,\n * and console logging for workflow execution.\n *\n * @example\n * ```typescript\n * import { createDevtools, quickVisualize, createConsoleLogger } from 'awaitly/devtools';\n *\n * const devtools = createDevtools();\n * const workflow = createWorkflow(deps, {\n * onEvent: devtools.handleEvent,\n * });\n *\n * await workflow(async (step) => { ... });\n *\n * // View timeline\n * console.log(devtools.getTimeline());\n *\n * // Quick visualization\n * quickVisualize(events);\n * ```\n */\n\nexport {\n // Types\n type WorkflowRun,\n type RunDiff,\n type StepDiff,\n type TimelineEntry,\n type DevtoolsOptions,\n type Devtools,\n\n // Factory\n createDevtools,\n\n // Helpers\n renderDiff,\n quickVisualize,\n createConsoleLogger,\n} from \"./devtools\";\n","/**\n * Timing utilities for workflow visualization.\n */\n\n/**\n * Format duration in milliseconds to a human-readable string.\n *\n * @example\n * formatDuration(23) // \"23ms\"\n * formatDuration(1500) // \"1.5s\"\n * formatDuration(65000) // \"1m 5s\"\n */\nexport function formatDuration(ms: number): string {\n if (ms < 1000) {\n return `${Math.round(ms)}ms`;\n }\n\n if (ms < 60000) {\n const seconds = ms / 1000;\n // Show one decimal for seconds\n return `${seconds.toFixed(1).replace(/\\.0$/, \"\")}s`;\n }\n\n const minutes = Math.floor(ms / 60000);\n const seconds = Math.round((ms % 60000) / 1000);\n\n if (seconds === 0) {\n return `${minutes}m`;\n }\n\n return `${minutes}m ${seconds}s`;\n}\n\n/**\n * Generate a unique ID for nodes.\n */\nexport function generateId(): string {\n return `node_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n","/**\n * Parallel Detection - Heuristic detection of parallel execution from timing.\n *\n * When steps overlap in time (one starts before another ends), they are\n * likely running in parallel. This module detects such patterns and\n * groups overlapping steps into ParallelNode structures.\n */\n\nimport type { FlowNode, ParallelNode, StepNode } from \"./types\";\n\n/**\n * Options for parallel detection.\n */\nexport interface ParallelDetectorOptions {\n /**\n * Minimum overlap in milliseconds to consider steps parallel.\n * Default: 0 (any overlap counts)\n */\n minOverlapMs?: number;\n\n /**\n * Maximum gap in milliseconds to still consider steps as part of same parallel group.\n * Default: 5 (steps starting within 5ms are grouped)\n */\n maxGapMs?: number;\n}\n\n/**\n * Step timing information for overlap detection.\n */\ninterface StepTiming {\n node: StepNode;\n startTs: number;\n endTs: number;\n}\n\n/**\n * Check if nodes contain real scope nodes (from scope_start/scope_end events).\n * When real scope nodes exist, heuristic detection should be skipped to avoid\n * duplicating or conflicting with the explicit structure.\n */\nfunction hasRealScopeNodes(nodes: FlowNode[]): boolean {\n for (const node of nodes) {\n // Real scope nodes are parallel/race/sequence that came from scope events\n // (not from heuristic detection, which uses ids starting with \"detected_\")\n if (\n (node.type === \"parallel\" || node.type === \"race\" || node.type === \"sequence\") &&\n !node.id.startsWith(\"detected_\")\n ) {\n return true;\n }\n // Also check for decision nodes if present\n if (\"decisionId\" in node) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Group overlapping steps into parallel nodes.\n *\n * Algorithm:\n * 1. Sort steps by start time\n * 2. For each step, check if it overlaps with existing parallel groups\n * 3. If it overlaps, add to group; otherwise start new sequence\n * 4. Merge overlapping groups when step bridges them\n *\n * Note: If real scope nodes (from scope_start/scope_end) are present,\n * heuristic detection is skipped to avoid conflicts.\n */\nexport function detectParallelGroups(\n nodes: FlowNode[],\n options: ParallelDetectorOptions = {}\n): FlowNode[] {\n // If real scope nodes exist, skip heuristic detection\n // The explicit scope events provide accurate structure\n if (hasRealScopeNodes(nodes)) {\n return nodes;\n }\n\n const { minOverlapMs = 0, maxGapMs = 5 } = options;\n\n // Extract step nodes with timing info, preserving indices for position restoration\n const stepsWithTiming: (StepTiming & { originalIndex: number })[] = [];\n const nonStepNodes: { node: FlowNode; originalIndex: number }[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n if (node.type === \"step\" && node.startTs !== undefined) {\n stepsWithTiming.push({\n node,\n startTs: node.startTs,\n endTs: node.endTs ?? node.startTs + (node.durationMs ?? 0),\n originalIndex: i,\n });\n } else {\n // Keep non-step nodes with their original position\n nonStepNodes.push({ node, originalIndex: i });\n }\n }\n\n if (stepsWithTiming.length <= 1) {\n return nodes; // Nothing to group\n }\n\n // Sort by start time\n stepsWithTiming.sort((a, b) => a.startTs - b.startTs);\n\n // Group overlapping steps\n type StepTimingWithIndex = StepTiming & { originalIndex: number };\n const groups: StepTimingWithIndex[][] = [];\n let currentGroup: StepTimingWithIndex[] = [stepsWithTiming[0]];\n\n for (let i = 1; i < stepsWithTiming.length; i++) {\n const step = stepsWithTiming[i];\n const groupStart = Math.min(...currentGroup.map((s) => s.startTs));\n const groupEnd = Math.max(...currentGroup.map((s) => s.endTs));\n\n // Two ways steps can be parallel:\n // 1. They started together (within maxGapMs) - handles timing jitter\n // 2. They genuinely overlap (step starts before group ends)\n const startedTogether = step.startTs <= groupStart + maxGapMs;\n const hasTrueOverlap = step.startTs < groupEnd;\n\n if (!startedTogether && !hasTrueOverlap) {\n // Sequential: step started after group ended AND not with the group\n groups.push(currentGroup);\n currentGroup = [step];\n continue;\n }\n\n // Check minOverlapMs threshold for overlap duration\n // For steps that started together, overlap is measured from step start to group end\n // For steps with true overlap, it's from step start to min(step end, group end)\n const overlapDuration = hasTrueOverlap\n ? Math.min(step.endTs, groupEnd) - step.startTs\n : 0;\n\n // Started together bypasses minOverlapMs (they're parallel by definition)\n // True overlap must meet the minOverlapMs threshold\n if (startedTogether || overlapDuration >= minOverlapMs) {\n currentGroup.push(step);\n } else {\n // Overlap too small - treat as sequential\n groups.push(currentGroup);\n currentGroup = [step];\n }\n }\n groups.push(currentGroup);\n\n // Convert groups to nodes with position tracking\n const groupedNodes: { node: FlowNode; position: number }[] = [];\n\n for (const group of groups) {\n // Use the minimum original index as the position for the group\n const position = Math.min(...group.map((s) => s.originalIndex));\n\n if (group.length === 1) {\n // Single step - no parallel grouping needed\n groupedNodes.push({ node: group[0].node, position });\n } else {\n // Multiple overlapping steps - create parallel node\n const children = group.map((s) => s.node);\n const startTs = Math.min(...group.map((s) => s.startTs));\n const endTs = Math.max(...group.map((s) => s.endTs));\n\n const parallelNode: ParallelNode = {\n type: \"parallel\",\n id: `detected_parallel_${startTs}`,\n name: `${children.length} parallel steps`,\n state: deriveGroupState(children),\n mode: \"all\",\n children,\n startTs,\n endTs,\n durationMs: endTs - startTs,\n };\n\n groupedNodes.push({ node: parallelNode, position });\n }\n }\n\n // Add non-step nodes with their original positions\n for (const { node, originalIndex } of nonStepNodes) {\n groupedNodes.push({ node, position: originalIndex });\n }\n\n // Sort by original position to preserve ordering\n groupedNodes.sort((a, b) => a.position - b.position);\n\n return groupedNodes.map((g) => g.node);\n}\n\n/**\n * Derive the state of a group from its children.\n */\nfunction deriveGroupState(\n children: FlowNode[]\n): \"pending\" | \"running\" | \"success\" | \"error\" | \"aborted\" | \"cached\" {\n const hasError = children.some((c) => c.state === \"error\");\n if (hasError) return \"error\";\n\n const hasRunning = children.some((c) => c.state === \"running\");\n if (hasRunning) return \"running\";\n\n const hasPending = children.some((c) => c.state === \"pending\");\n if (hasPending) return \"pending\";\n\n const allSuccess = children.every(\n (c) => c.state === \"success\" || c.state === \"cached\"\n );\n if (allSuccess) return \"success\";\n\n return \"success\";\n}\n\n/**\n * Create a parallel detector that processes nodes.\n */\nexport function createParallelDetector(options: ParallelDetectorOptions = {}) {\n return {\n /**\n * Process nodes and group overlapping ones into parallel nodes.\n */\n detect: (nodes: FlowNode[]) => detectParallelGroups(nodes, options),\n };\n}\n","/**\n * IR Builder - Converts workflow events to Intermediate Representation.\n *\n * The builder maintains state as events arrive, constructing a tree\n * representation of the workflow execution that can be rendered.\n */\n\nimport type { WorkflowEvent } from \"../core\";\nimport type {\n FlowNode,\n ScopeEndEvent,\n ScopeStartEvent,\n ScopeType,\n StepNode,\n StepState,\n WorkflowIR,\n WorkflowNode,\n ParallelNode,\n RaceNode,\n DecisionNode,\n DecisionStartEvent,\n DecisionBranchEvent,\n DecisionEndEvent,\n DecisionBranch,\n IRSnapshot,\n ActiveStepSnapshot,\n WorkflowHooks,\n HookExecution,\n} from \"./types\";\nimport { generateId } from \"./utils/timing\";\nimport { detectParallelGroups, type ParallelDetectorOptions } from \"./parallel-detector\";\n\n// =============================================================================\n// Builder Options\n// =============================================================================\n\n/**\n * Options for the IR builder.\n */\nexport interface IRBuilderOptions {\n /**\n * Enable heuristic parallel detection based on timing.\n * When true, overlapping steps are grouped into ParallelNodes.\n * Default: true\n */\n detectParallel?: boolean;\n\n /**\n * Options for parallel detection.\n */\n parallelDetection?: ParallelDetectorOptions;\n\n /**\n * Enable snapshot recording for time-travel debugging.\n * When true, the builder captures IR state after each event.\n * Default: false\n */\n enableSnapshots?: boolean;\n\n /**\n * Maximum number of snapshots to keep (ring buffer behavior).\n * When exceeded, oldest snapshots are discarded.\n * Default: 1000\n */\n maxSnapshots?: number;\n}\n\n// =============================================================================\n// Builder State\n// =============================================================================\n\ninterface ActiveStep {\n id: string;\n name?: string;\n key?: string;\n startTs: number;\n retryCount: number;\n timedOut: boolean;\n timeoutMs?: number;\n}\n\ninterface ActiveScope {\n id: string;\n name?: string;\n type: ScopeType;\n startTs: number;\n children: FlowNode[];\n}\n\ninterface ActiveDecision {\n id: string;\n name?: string;\n condition?: string;\n decisionValue?: unknown;\n startTs: number;\n branches: Map<string, DecisionBranch>;\n branchTaken?: string | boolean;\n}\n\n// =============================================================================\n// IR Builder\n// =============================================================================\n\n/**\n * Creates an IR builder that processes workflow events.\n */\nexport function createIRBuilder(options: IRBuilderOptions = {}) {\n const {\n detectParallel = true,\n parallelDetection,\n enableSnapshots = false,\n maxSnapshots = 1000,\n } = options;\n\n // Current workflow state\n let workflowId: string | undefined;\n let workflowStartTs: number | undefined;\n let workflowState: StepState = \"pending\";\n let workflowError: unknown;\n let workflowDurationMs: number | undefined;\n\n // Active steps (currently running)\n const activeSteps = new Map<string, ActiveStep>();\n\n // Active scopes (parallel/race blocks)\n const scopeStack: ActiveScope[] = [];\n\n // Active decisions (conditional branches)\n const decisionStack: ActiveDecision[] = [];\n\n // Completed nodes at the current scope level\n let currentNodes: FlowNode[] = [];\n\n // Metadata\n let createdAt = Date.now();\n let lastUpdatedAt = createdAt;\n\n // Hook executions\n let hookState: WorkflowHooks = {\n onAfterStep: new Map(),\n };\n\n // Snapshot state for time-travel debugging\n const snapshots: IRSnapshot[] = [];\n let eventIndex = 0;\n\n /**\n * Get the step ID from an event.\n * Uses stepId if available (new events), then falls back to stepKey or name,\n * and finally generates a random ID for backwards compatibility.\n */\n function getStepId(event: { stepId?: string; stepKey?: string; name?: string }): string {\n return event.stepId ?? event.stepKey ?? event.name ?? generateId();\n }\n\n /**\n * Add a completed node to the current scope or decision branch.\n */\n function addNode(node: FlowNode): void {\n // If we're in a decision, add to the taken branch\n if (decisionStack.length > 0) {\n const decision = decisionStack[decisionStack.length - 1];\n // Find the taken branch\n for (const branch of decision.branches.values()) {\n if (branch.taken) {\n branch.children.push(node);\n lastUpdatedAt = Date.now();\n return;\n }\n }\n // If no branch is marked as taken yet, add to the first branch\n // (this handles cases where steps execute before branch is marked)\n const firstBranch = Array.from(decision.branches.values())[0];\n if (firstBranch) {\n firstBranch.children.push(node);\n lastUpdatedAt = Date.now();\n return;\n }\n }\n\n // If we're in a scope, add to the scope\n if (scopeStack.length > 0) {\n // Add to the innermost scope\n scopeStack[scopeStack.length - 1].children.push(node);\n } else {\n // Add to the root level\n currentNodes.push(node);\n }\n lastUpdatedAt = Date.now();\n }\n\n /**\n * Capture a snapshot of the current IR state (for time-travel debugging).\n * Called after each event is processed.\n */\n function captureSnapshot(event: WorkflowEvent<unknown>): void {\n if (!enableSnapshots) return;\n\n // Deep clone the current IR state\n const ir = getIR();\n\n // Clone active steps for debugging\n const activeStepsCopy = new Map<string, ActiveStepSnapshot>();\n for (const [id, step] of activeSteps) {\n activeStepsCopy.set(id, {\n id: step.id,\n name: step.name,\n key: step.key,\n startTs: step.startTs,\n retryCount: step.retryCount,\n timedOut: step.timedOut,\n timeoutMs: step.timeoutMs,\n });\n }\n\n const snapshot: IRSnapshot = {\n id: `snapshot_${eventIndex}`,\n eventIndex,\n event: structuredClone(event),\n ir: structuredClone(ir),\n timestamp: Date.now(),\n activeSteps: activeStepsCopy,\n };\n\n snapshots.push(snapshot);\n\n // Ring buffer: remove oldest if we exceed max\n if (snapshots.length > maxSnapshots) {\n snapshots.shift();\n }\n\n eventIndex++;\n }\n\n /**\n * Handle a workflow event and update the IR.\n */\n function handleEvent(event: WorkflowEvent<unknown>): void {\n switch (event.type) {\n case \"workflow_start\":\n workflowId = event.workflowId;\n workflowStartTs = event.ts;\n workflowState = \"running\";\n createdAt = Date.now();\n lastUpdatedAt = createdAt;\n // Note: Don't clear hookState here - shouldRun and onBeforeStart\n // events are emitted BEFORE workflow_start. Only clear onAfterStep\n // since those are per-step and should reset for each workflow run.\n hookState.onAfterStep = new Map();\n break;\n\n case \"workflow_success\":\n workflowState = \"success\";\n workflowDurationMs = event.durationMs;\n lastUpdatedAt = Date.now();\n break;\n\n case \"workflow_error\":\n workflowState = \"error\";\n workflowError = event.error;\n workflowDurationMs = event.durationMs;\n lastUpdatedAt = Date.now();\n break;\n\n case \"step_start\": {\n const id = getStepId(event);\n activeSteps.set(id, {\n id,\n name: event.name,\n key: event.stepKey,\n startTs: event.ts,\n retryCount: 0,\n timedOut: false,\n });\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"step_success\": {\n const id = getStepId(event);\n const active = activeSteps.get(id);\n if (active) {\n const node: StepNode = {\n type: \"step\",\n id: active.id,\n name: active.name,\n key: active.key,\n state: \"success\",\n startTs: active.startTs,\n endTs: event.ts,\n durationMs: event.durationMs,\n ...(active.retryCount > 0 && { retryCount: active.retryCount }),\n ...(active.timedOut && { timedOut: true, timeoutMs: active.timeoutMs }),\n };\n addNode(node);\n activeSteps.delete(id);\n }\n break;\n }\n\n case \"step_error\": {\n const id = getStepId(event);\n const active = activeSteps.get(id);\n if (active) {\n const node: StepNode = {\n type: \"step\",\n id: active.id,\n name: active.name,\n key: active.key,\n state: \"error\",\n startTs: active.startTs,\n endTs: event.ts,\n durationMs: event.durationMs,\n error: event.error,\n ...(active.retryCount > 0 && { retryCount: active.retryCount }),\n ...(active.timedOut && { timedOut: true, timeoutMs: active.timeoutMs }),\n };\n addNode(node);\n activeSteps.delete(id);\n }\n break;\n }\n\n case \"step_aborted\": {\n const id = getStepId(event);\n const active = activeSteps.get(id);\n if (active) {\n const node: StepNode = {\n type: \"step\",\n id: active.id,\n name: active.name,\n key: active.key,\n state: \"aborted\",\n startTs: active.startTs,\n endTs: event.ts,\n durationMs: event.durationMs,\n ...(active.retryCount > 0 && { retryCount: active.retryCount }),\n ...(active.timedOut && { timedOut: true, timeoutMs: active.timeoutMs }),\n };\n addNode(node);\n activeSteps.delete(id);\n }\n break;\n }\n\n case \"step_cache_hit\": {\n const id = getStepId(event);\n const node: StepNode = {\n type: \"step\",\n id,\n name: event.name,\n key: event.stepKey,\n state: \"cached\",\n startTs: event.ts,\n endTs: event.ts,\n durationMs: 0,\n };\n addNode(node);\n break;\n }\n\n case \"step_cache_miss\":\n // Cache miss just means the step will execute normally\n // We'll get a step_start event next\n break;\n\n case \"step_complete\":\n // step_complete is for state persistence, not visualization\n // We already handled the step via step_success/step_error\n break;\n\n case \"step_timeout\": {\n // Timeout is an intermediate event - step may retry or will get step_error\n // Track timeout info on the active step\n const id = getStepId(event);\n const active = activeSteps.get(id);\n if (active) {\n active.timedOut = true;\n active.timeoutMs = event.timeoutMs;\n }\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"step_retry\": {\n // Retry is an intermediate event - increment retry counter\n const id = getStepId(event);\n const active = activeSteps.get(id);\n if (active) {\n active.retryCount = (event.attempt ?? 1) - 1; // attempt is 1-indexed, retryCount is 0-indexed\n }\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"step_retries_exhausted\":\n // All retries exhausted - step_error will follow\n // The error state will be set by step_error handler\n lastUpdatedAt = Date.now();\n break;\n\n case \"step_skipped\": {\n const id = getStepId(event);\n const node: StepNode = {\n type: \"step\",\n id,\n name: event.name,\n key: event.stepKey,\n state: \"skipped\",\n startTs: event.ts,\n endTs: event.ts,\n durationMs: 0,\n };\n addNode(node);\n break;\n }\n\n // Hook events\n case \"hook_should_run\": {\n const hookExec: HookExecution = {\n type: \"shouldRun\",\n state: \"success\",\n ts: event.ts,\n durationMs: event.durationMs,\n context: {\n result: event.result,\n skipped: event.skipped,\n },\n };\n hookState.shouldRun = hookExec;\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"hook_should_run_error\": {\n const hookExec: HookExecution = {\n type: \"shouldRun\",\n state: \"error\",\n ts: event.ts,\n durationMs: event.durationMs,\n error: event.error,\n };\n hookState.shouldRun = hookExec;\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"hook_before_start\": {\n const hookExec: HookExecution = {\n type: \"onBeforeStart\",\n state: \"success\",\n ts: event.ts,\n durationMs: event.durationMs,\n context: {\n result: event.result,\n skipped: event.skipped,\n },\n };\n hookState.onBeforeStart = hookExec;\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"hook_before_start_error\": {\n const hookExec: HookExecution = {\n type: \"onBeforeStart\",\n state: \"error\",\n ts: event.ts,\n durationMs: event.durationMs,\n error: event.error,\n };\n hookState.onBeforeStart = hookExec;\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"hook_after_step\": {\n const hookExec: HookExecution = {\n type: \"onAfterStep\",\n state: \"success\",\n ts: event.ts,\n durationMs: event.durationMs,\n context: {\n stepKey: event.stepKey,\n },\n };\n hookState.onAfterStep.set(event.stepKey, hookExec);\n lastUpdatedAt = Date.now();\n break;\n }\n\n case \"hook_after_step_error\": {\n const hookExec: HookExecution = {\n type: \"onAfterStep\",\n state: \"error\",\n ts: event.ts,\n durationMs: event.durationMs,\n error: event.error,\n context: {\n stepKey: event.stepKey,\n },\n };\n hookState.onAfterStep.set(event.stepKey, hookExec);\n lastUpdatedAt = Date.now();\n break;\n }\n }\n\n // Capture snapshot after processing event (for time-travel)\n captureSnapshot(event);\n }\n\n /**\n * Handle a scope event (parallel/race start/end).\n */\n function handleScopeEvent(event: ScopeStartEvent | ScopeEndEvent): void {\n if (event.type === \"scope_start\") {\n scopeStack.push({\n id: event.scopeId,\n name: event.name,\n type: event.scopeType,\n startTs: event.ts,\n children: [],\n });\n lastUpdatedAt = Date.now();\n } else if (event.type === \"scope_end\") {\n const scope = scopeStack.pop();\n if (scope) {\n const node: ParallelNode | RaceNode =\n scope.type === \"race\"\n ? {\n type: \"race\",\n id: scope.id,\n name: scope.name,\n state: deriveState(scope.children),\n startTs: scope.startTs,\n endTs: event.ts,\n durationMs: event.durationMs,\n children: scope.children,\n winnerId: event.winnerId,\n }\n : {\n type: \"parallel\",\n id: scope.id,\n name: scope.name,\n state: deriveState(scope.children),\n startTs: scope.startTs,\n endTs: event.ts,\n durationMs: event.durationMs,\n children: scope.children,\n mode: scope.type === \"allSettled\" ? \"allSettled\" : \"all\",\n };\n addNode(node);\n }\n }\n }\n\n /**\n * Handle a decision event (conditional branch start/branch/end).\n */\n function handleDecisionEvent(\n event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent\n ): void {\n if (event.type === \"decision_start\") {\n decisionStack.push({\n id: event.decisionId,\n name: event.name,\n condition: event.condition,\n decisionValue: event.decisionValue,\n startTs: event.ts,\n branches: new Map(),\n });\n lastUpdatedAt = Date.now();\n } else if (event.type === \"decision_branch\") {\n const decision = decisionStack[decisionStack.length - 1];\n if (decision && decision.id === event.decisionId) {\n // Find or create branch\n const branchKey = event.branchLabel;\n const existing = decision.branches.get(branchKey);\n if (existing) {\n // Update existing branch\n existing.taken = event.taken;\n } else {\n // Create new branch\n decision.branches.set(branchKey, {\n label: event.branchLabel,\n condition: event.condition,\n taken: event.taken,\n children: [],\n });\n }\n lastUpdatedAt = Date.now();\n }\n } else if (event.type === \"decision_end\") {\n const decision = decisionStack.pop();\n if (decision && decision.id === event.decisionId) {\n // Convert branches map to array\n const branches: DecisionBranch[] = Array.from(decision.branches.values());\n\n const node: DecisionNode = {\n type: \"decision\",\n id: decision.id,\n name: decision.name,\n state: deriveState(\n branches.flatMap((b) => (b.taken ? b.children : []))\n ),\n startTs: decision.startTs,\n endTs: event.ts,\n durationMs: event.durationMs,\n condition: decision.condition,\n decisionValue: decision.decisionValue,\n branchTaken: event.branchTaken ?? decision.branchTaken,\n branches,\n };\n addNode(node);\n }\n }\n }\n\n /**\n * Derive the state of a parent node from its children.\n */\n function deriveState(children: FlowNode[]): StepState {\n if (children.length === 0) return \"success\";\n\n const hasError = children.some((c) => c.state === \"error\");\n if (hasError) return \"error\";\n\n const allSuccess = children.every(\n (c) => c.state === \"success\" || c.state === \"cached\"\n );\n if (allSuccess) return \"success\";\n\n const hasRunning = children.some((c) => c.state === \"running\");\n if (hasRunning) return \"running\";\n\n return \"pending\";\n }\n\n /**\n * Get the current nodes including any active (running) steps.\n */\n function getCurrentNodes(): FlowNode[] {\n const nodes = [...currentNodes];\n\n // Add active steps as running nodes\n for (const [, active] of activeSteps) {\n nodes.push({\n type: \"step\",\n id: active.id,\n name: active.name,\n key: active.key,\n state: \"running\",\n startTs: active.startTs,\n ...(active.retryCount > 0 && { retryCount: active.retryCount }),\n ...(active.timedOut && { timedOut: true, timeoutMs: active.timeoutMs }),\n });\n }\n\n return nodes;\n }\n\n /**\n * Build and return the current IR state.\n */\n function getIR(): WorkflowIR {\n let children = getCurrentNodes();\n\n // Apply parallel detection if enabled\n if (detectParallel) {\n children = detectParallelGroups(children, parallelDetection);\n }\n\n const root: WorkflowNode = {\n type: \"workflow\",\n id: workflowId ?? generateId(),\n workflowId: workflowId ?? \"unknown\",\n state: workflowState,\n startTs: workflowStartTs,\n durationMs: workflowDurationMs,\n children,\n error: workflowError,\n };\n\n // Include hooks if any have been recorded\n const hasHooks =\n hookState.shouldRun !== undefined ||\n hookState.onBeforeStart !== undefined ||\n hookState.onAfterStep.size > 0;\n\n return {\n root,\n metadata: {\n createdAt,\n lastUpdatedAt,\n },\n ...(hasHooks && { hooks: hookState }),\n };\n }\n\n /**\n * Reset the builder state.\n */\n function reset(): void {\n workflowId = undefined;\n workflowStartTs = undefined;\n workflowState = \"pending\";\n workflowError = undefined;\n workflowDurationMs = undefined;\n activeSteps.clear();\n scopeStack.length = 0;\n decisionStack.length = 0;\n currentNodes = [];\n createdAt = Date.now();\n lastUpdatedAt = createdAt;\n // Clear hooks\n hookState = {\n onAfterStep: new Map(),\n };\n // Clear snapshots\n snapshots.length = 0;\n eventIndex = 0;\n }\n\n /**\n * Get all recorded snapshots.\n */\n function getSnapshots(): IRSnapshot[] {\n return [...snapshots];\n }\n\n /**\n * Get a snapshot at a specific index.\n */\n function getSnapshotAt(index: number): IRSnapshot | undefined {\n return snapshots[index];\n }\n\n /**\n * Get the IR state at a specific snapshot index.\n */\n function getIRAt(index: number): WorkflowIR | undefined {\n return snapshots[index]?.ir;\n }\n\n /**\n * Clear all recorded snapshots.\n */\n function clearSnapshots(): void {\n snapshots.length = 0;\n eventIndex = 0;\n }\n\n return {\n handleEvent,\n handleScopeEvent,\n handleDecisionEvent,\n getIR,\n reset,\n // Snapshot methods for time-travel\n getSnapshots,\n getSnapshotAt,\n getIRAt,\n clearSnapshots,\n /** Check if there are active (running) steps */\n get hasActiveSteps() {\n return activeSteps.size > 0;\n },\n /** Get the current workflow state */\n get state() {\n return workflowState;\n },\n /** Get the number of recorded snapshots */\n get snapshotCount() {\n return snapshots.length;\n },\n /** Check if snapshot recording is enabled */\n get snapshotsEnabled() {\n return enableSnapshots;\n },\n };\n}\n\n/**\n * Type for the IR builder instance.\n */\nexport type IRBuilder = ReturnType<typeof createIRBuilder>;\n","/**\n * Workflow Visualization - Intermediate Representation Types\n *\n * The IR (Intermediate Representation) is a DSL that represents workflow\n * execution structure. Events are converted to IR, which can then be\n * rendered to various output formats (ASCII, Mermaid, JSON, etc.).\n */\n\n// =============================================================================\n// Step States\n// =============================================================================\n\n/**\n * Execution state of a step with semantic meaning for visualization.\n *\n * Color mapping:\n * - pending → white/clear (not started)\n * - running → yellow (currently executing)\n * - success → green (completed successfully)\n * - error → red (failed with error)\n * - aborted → gray (cancelled, e.g., in race)\n * - cached → blue (served from cache)\n * - skipped → dim gray (not executed due to conditional logic)\n */\nexport type StepState =\n | \"pending\"\n | \"running\"\n | \"success\"\n | \"error\"\n | \"aborted\"\n | \"cached\"\n | \"skipped\";\n\n// =============================================================================\n// Node Types\n// =============================================================================\n\n/**\n * Base properties shared by all IR nodes.\n */\nexport interface BaseNode {\n /** Unique identifier for this node */\n id: string;\n /** Human-readable name (from step options or inferred) */\n name?: string;\n /** Cache key if this is a keyed step */\n key?: string;\n /** Current execution state */\n state: StepState;\n /** Timestamp when execution started */\n startTs?: number;\n /** Timestamp when execution ended */\n endTs?: number;\n /** Duration in milliseconds */\n durationMs?: number;\n /** Error value if state is 'error' */\n error?: unknown;\n /** Input value that triggered this step (for decision understanding) */\n input?: unknown;\n /** Output value from this step (for decision understanding) */\n output?: unknown;\n /** Number of retry attempts made (0 = no retries, 1 = one retry, etc.) */\n retryCount?: number;\n /** Whether this step experienced a timeout (may have retried after) */\n timedOut?: boolean;\n /** Timeout duration in ms (if timed out) */\n timeoutMs?: number;\n}\n\n/**\n * A single step execution node.\n */\nexport interface StepNode extends BaseNode {\n type: \"step\";\n}\n\n/**\n * Sequential execution - steps run one after another.\n * This is the implicit structure when steps are awaited in sequence.\n */\nexport interface SequenceNode extends BaseNode {\n type: \"sequence\";\n children: FlowNode[];\n}\n\n/**\n * Parallel execution - all branches run simultaneously.\n * Created by allAsync() or allSettledAsync().\n */\nexport interface ParallelNode extends BaseNode {\n type: \"parallel\";\n children: FlowNode[];\n /**\n * Execution mode:\n * - 'all': Fails on first error (allAsync)\n * - 'allSettled': Collects all results (allSettledAsync)\n */\n mode: \"all\" | \"allSettled\";\n}\n\n/**\n * Race execution - first to complete wins.\n * Created by anyAsync().\n */\nexport interface RaceNode extends BaseNode {\n type: \"race\";\n children: FlowNode[];\n /** ID of the winning branch (first to succeed) */\n winnerId?: string;\n}\n\n/**\n * Decision point - conditional branch (if/switch).\n * Shows which branch was taken and why.\n */\nexport interface DecisionNode extends BaseNode {\n type: \"decision\";\n /** Condition that was evaluated (e.g., \"user.role === 'admin'\") */\n condition?: string;\n /** Value that was evaluated (the input to the decision) */\n decisionValue?: unknown;\n /** Which branch was taken (true/false, or the matched case) */\n branchTaken?: string | boolean;\n /** All possible branches (including skipped ones) */\n branches: DecisionBranch[];\n}\n\n/**\n * A branch in a decision node.\n */\nexport interface DecisionBranch {\n /** Label for this branch (e.g., \"if\", \"else\", \"case 'admin'\") */\n label: string;\n /** Condition that would trigger this branch */\n condition?: string;\n /** Whether this branch was taken */\n taken: boolean;\n /** Steps in this branch */\n children: FlowNode[];\n}\n\n/**\n * Union of all flow node types.\n */\nexport type FlowNode = StepNode | SequenceNode | ParallelNode | RaceNode | DecisionNode;\n\n/**\n * Root node representing the entire workflow.\n */\nexport interface WorkflowNode extends BaseNode {\n type: \"workflow\";\n /** Correlation ID from the workflow execution */\n workflowId: string;\n /** Child nodes (steps, parallel blocks, etc.) */\n children: FlowNode[];\n}\n\n// =============================================================================\n// Workflow IR\n// =============================================================================\n\n/**\n * Complete workflow intermediate representation.\n * This is the main data structure produced by the IR builder.\n */\nexport interface WorkflowIR {\n /** Root workflow node */\n root: WorkflowNode;\n /** Metadata about the IR */\n metadata: {\n /** When the IR was first created */\n createdAt: number;\n /** When the IR was last updated */\n lastUpdatedAt: number;\n };\n /** Hook executions (if any hooks are configured) */\n hooks?: WorkflowHooks;\n}\n\n// =============================================================================\n// Scope Events (for parallel/race detection)\n// =============================================================================\n\n// Re-export ScopeType from core for consistency\nexport type { ScopeType } from \"../core\";\nimport type { ScopeType } from \"../core\";\n\n/**\n * Event emitted when entering a parallel/race scope.\n * This matches the scope_start event in WorkflowEvent.\n */\nexport interface ScopeStartEvent {\n type: \"scope_start\";\n workflowId: string;\n scopeId: string;\n scopeType: ScopeType;\n name?: string;\n ts: number;\n}\n\n/**\n * Event emitted when exiting a parallel/race scope.\n */\nexport interface ScopeEndEvent {\n type: \"scope_end\";\n workflowId: string;\n scopeId: string;\n ts: number;\n durationMs: number;\n /** For race scopes, the ID of the winning branch */\n winnerId?: string;\n}\n\n/**\n * Event emitted when a decision point is encountered.\n * Use this to track conditional logic (if/switch).\n */\nexport interface DecisionStartEvent {\n type: \"decision_start\";\n workflowId: string;\n decisionId: string;\n /** Condition being evaluated (e.g., \"user.role === 'admin'\") */\n condition?: string;\n /** Value being evaluated */\n decisionValue?: unknown;\n /** Name/label for this decision point */\n name?: string;\n ts: number;\n}\n\n/**\n * Event emitted when a decision branch is taken.\n */\nexport interface DecisionBranchEvent {\n type: \"decision_branch\";\n workflowId: string;\n decisionId: string;\n /** Label for this branch (e.g., \"if\", \"else\", \"case 'admin'\") */\n branchLabel: string;\n /** Condition for this branch */\n condition?: string;\n /** Whether this branch was taken */\n taken: boolean;\n ts: number;\n}\n\n/**\n * Event emitted when a decision point completes.\n */\nexport interface DecisionEndEvent {\n type: \"decision_end\";\n workflowId: string;\n decisionId: string;\n /** Which branch was taken */\n branchTaken?: string | boolean;\n ts: number;\n durationMs: number;\n}\n\n/**\n * Event emitted when a step is skipped due to conditional logic.\n */\nexport interface StepSkippedEvent {\n type: \"step_skipped\";\n workflowId: string;\n stepKey?: string;\n name?: string;\n /** Reason why this step was skipped (e.g., \"condition was false\") */\n reason?: string;\n /** The decision that caused this skip */\n decisionId?: string;\n ts: number;\n}\n\n/**\n * Union of scope-related events.\n */\nexport type ScopeEvent = ScopeStartEvent | ScopeEndEvent;\n\n/**\n * Union of decision-related events.\n */\nexport type DecisionEvent = DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent;\n\n// =============================================================================\n// Renderer Types\n// =============================================================================\n\n/**\n * Color scheme for rendering step states.\n */\nexport interface ColorScheme {\n pending: string;\n running: string;\n success: string;\n error: string;\n aborted: string;\n cached: string;\n skipped: string;\n}\n\n/**\n * Options passed to renderers.\n */\nexport interface RenderOptions {\n /** Show timing information (duration) */\n showTimings: boolean;\n /** Show step cache keys */\n showKeys: boolean;\n /** Terminal width for ASCII renderer */\n terminalWidth?: number;\n /** Color scheme */\n colors: ColorScheme;\n}\n\n/**\n * Extended options for Mermaid renderer.\n * Controls how edges are displayed for retries, errors, and timeouts.\n */\nexport interface MermaidRenderOptions extends RenderOptions {\n /** Show retry as self-loop edge (default: true) */\n showRetryEdges?: boolean;\n /** Show error flow to error node (default: true) */\n showErrorEdges?: boolean;\n /** Show timeout as alternative path (default: true) */\n showTimeoutEdges?: boolean;\n}\n\n/**\n * Renderer interface - transforms IR to output format.\n */\nexport interface Renderer {\n /** Unique identifier for this renderer */\n readonly name: string;\n /** Render IR to string output */\n render(ir: WorkflowIR, options: RenderOptions): string;\n /** Whether this renderer supports live (incremental) updates */\n supportsLive?: boolean;\n /** Render incremental update (optional) */\n renderUpdate?(\n ir: WorkflowIR,\n changedNodes: FlowNode[],\n options: RenderOptions\n ): string;\n}\n\n// =============================================================================\n// Visualizer Types\n// =============================================================================\n\n/**\n * Output format for rendering.\n */\nexport type OutputFormat = \"ascii\" | \"mermaid\" | \"json\" | \"logger\" | \"flowchart\";\n\n/**\n * Options for creating a visualizer.\n */\nexport interface VisualizerOptions {\n /** Name for the workflow in visualizations */\n workflowName?: string;\n /** Enable parallel detection heuristics (default: true) */\n detectParallel?: boolean;\n /** Show timing information (default: true) */\n showTimings?: boolean;\n /** Show step keys (default: false) */\n showKeys?: boolean;\n /** Custom color scheme */\n colors?: Partial<ColorScheme>;\n}\n\n/**\n * Options for live visualization.\n */\nexport interface LiveVisualizerOptions extends VisualizerOptions {\n /** Output stream (default: process.stdout) */\n stream?: NodeJS.WriteStream;\n /** Update interval in ms (default: 100) */\n updateInterval?: number;\n}\n\n// =============================================================================\n// Type Guards\n// =============================================================================\n\n/**\n * Check if a node is a StepNode.\n */\nexport function isStepNode(node: FlowNode): node is StepNode {\n return node.type === \"step\";\n}\n\n/**\n * Check if a node is a SequenceNode.\n */\nexport function isSequenceNode(node: FlowNode): node is SequenceNode {\n return node.type === \"sequence\";\n}\n\n/**\n * Check if a node is a ParallelNode.\n */\nexport function isParallelNode(node: FlowNode): node is ParallelNode {\n return node.type === \"parallel\";\n}\n\n/**\n * Check if a node is a RaceNode.\n */\nexport function isRaceNode(node: FlowNode): node is RaceNode {\n return node.type === \"race\";\n}\n\n/**\n * Check if a node is a DecisionNode.\n */\nexport function isDecisionNode(node: FlowNode): node is DecisionNode {\n return node.type === \"decision\";\n}\n\n/**\n * Check if a node has children.\n */\nexport function hasChildren(\n node: FlowNode\n): node is SequenceNode | ParallelNode | RaceNode | DecisionNode {\n return \"children\" in node || (node.type === \"decision\" && \"branches\" in node);\n}\n\n// =============================================================================\n// Time Travel Types\n// =============================================================================\n\n/**\n * Snapshot of an active step's state at a point in time.\n */\nexport interface ActiveStepSnapshot {\n id: string;\n name?: string;\n key?: string;\n startTs: number;\n retryCount: number;\n timedOut: boolean;\n timeoutMs?: number;\n}\n\n/**\n * A snapshot of the complete IR state at a specific point in time.\n * Used for time-travel debugging - each event creates a snapshot.\n */\nexport interface IRSnapshot {\n /** Unique identifier for this snapshot */\n id: string;\n /** Index in the event sequence (0-based) */\n eventIndex: number;\n /** The event that triggered this snapshot */\n event: unknown; // WorkflowEvent - avoid circular import\n /** Complete IR state at this moment */\n ir: WorkflowIR;\n /** Timestamp when snapshot was taken */\n timestamp: number;\n /** Active step states at this moment (for debugging) */\n activeSteps: Map<string, ActiveStepSnapshot>;\n}\n\n/**\n * State of the time-travel controller.\n */\nexport interface TimeTravelState {\n /** All recorded snapshots */\n snapshots: IRSnapshot[];\n /** Current snapshot index (for playback position) */\n currentIndex: number;\n /** Whether playback is active */\n isPlaying: boolean;\n /** Playback speed multiplier (1.0 = realtime, 2.0 = 2x speed) */\n playbackSpeed: number;\n /** Whether recording is active */\n isRecording: boolean;\n}\n\n// =============================================================================\n// Performance Analysis Types\n// =============================================================================\n\n/**\n * Performance metrics for a single node across multiple runs.\n */\nexport interface NodePerformance {\n /** Node identifier (name or step ID) */\n nodeId: string;\n /** Average duration across all samples */\n avgDurationMs: number;\n /** Minimum duration observed */\n minDurationMs: number;\n /** Maximum duration observed */\n maxDurationMs: number;\n /** Standard deviation of durations */\n stdDevMs: number;\n /** Number of timing samples collected */\n samples: number;\n /** Retry frequency (0-1, where 1 = always retries) */\n retryRate: number;\n /** Timeout frequency (0-1) */\n timeoutRate: number;\n /** Error rate (0-1) */\n errorRate: number;\n /** Percentile data for distribution analysis */\n percentiles: {\n p50: number;\n p90: number;\n p95: number;\n p99: number;\n };\n}\n\n/**\n * Heatmap data for visualizing performance across nodes.\n */\nexport interface HeatmapData {\n /** Map of node ID to heat level (0-1, where 1 is hottest/slowest) */\n heat: Map<string, number>;\n /** The metric used for heat calculation */\n metric: \"duration\" | \"retryRate\" | \"errorRate\";\n /** Statistics used to compute heat values */\n stats: {\n /** Minimum value in the dataset */\n min: number;\n /** Maximum value in the dataset */\n max: number;\n /** Mean value */\n mean: number;\n /** Threshold above which a node is considered \"hot\" */\n threshold: number;\n };\n}\n\n/**\n * Heat level for visual styling.\n */\nexport type HeatLevel = \"cold\" | \"cool\" | \"neutral\" | \"warm\" | \"hot\" | \"critical\";\n\n// =============================================================================\n// HTML Renderer Types\n// =============================================================================\n\n/**\n * Theme for the HTML visualizer.\n */\nexport type HTMLTheme = \"light\" | \"dark\" | \"auto\";\n\n/**\n * Layout direction for the workflow diagram.\n */\nexport type LayoutDirection = \"TB\" | \"LR\" | \"BT\" | \"RL\";\n\n/**\n * Options for the HTML renderer.\n */\nexport interface HTMLRenderOptions extends RenderOptions {\n /** Enable interactive features (click to inspect, zoom/pan) */\n interactive: boolean;\n /** Include time-travel controls */\n timeTravel: boolean;\n /** Include performance heatmap overlay */\n heatmap: boolean;\n /** Animation duration for transitions (ms) */\n animationDuration: number;\n /** Color theme */\n theme: HTMLTheme;\n /** Diagram layout direction */\n layout: LayoutDirection;\n /** Heatmap data (if heatmap is enabled) */\n heatmapData?: HeatmapData;\n /** WebSocket URL for live updates (if streaming) */\n wsUrl?: string;\n}\n\n/**\n * Message sent from the web visualizer to the dev server.\n */\nexport interface WebVisualizerMessage {\n type:\n | \"time_travel_seek\"\n | \"time_travel_play\"\n | \"time_travel_pause\"\n | \"time_travel_step_forward\"\n | \"time_travel_step_backward\"\n | \"request_snapshots\"\n | \"toggle_heatmap\"\n | \"set_heatmap_metric\";\n payload?: unknown;\n}\n\n/**\n * Message sent from the dev server to the web visualizer.\n */\nexport interface ServerMessage {\n type:\n | \"ir_update\"\n | \"snapshot\"\n | \"snapshots_list\"\n | \"performance_data\"\n | \"workflow_complete\"\n | \"time_travel_state\";\n payload: unknown;\n}\n\n// =============================================================================\n// Enhanced ASCII Renderer Types\n// =============================================================================\n\n/**\n * Extended render options for the enhanced ASCII renderer.\n */\nexport interface EnhancedRenderOptions extends RenderOptions {\n /** Show performance heatmap coloring */\n showHeatmap?: boolean;\n /** Heatmap data for coloring nodes */\n heatmapData?: HeatmapData;\n /** Show timing sparklines (requires historical data) */\n showSparklines?: boolean;\n /** Historical timing data for sparklines: nodeId → array of durations */\n timingHistory?: Map<string, number[]>;\n}\n\n/**\n * Options for the flowchart ASCII renderer.\n * Renders workflow as a proper flowchart with boxes and arrows.\n */\nexport interface FlowchartRenderOptions extends EnhancedRenderOptions {\n /** Show start and end nodes (default: true) */\n showStartEnd?: boolean;\n /** Reduce vertical spacing between nodes (default: false) */\n compact?: boolean;\n /** Box border style (default: 'single') */\n boxStyle?: \"single\" | \"double\" | \"rounded\";\n}\n\n// =============================================================================\n// Hook Execution Types\n// =============================================================================\n\n/**\n * State of a hook execution.\n */\nexport type HookState = \"pending\" | \"running\" | \"success\" | \"error\";\n\n/**\n * Execution record for a workflow hook.\n */\nexport interface HookExecution {\n /** Hook type identifier */\n type: \"shouldRun\" | \"onBeforeStart\" | \"onAfterStep\";\n /** Execution state */\n state: HookState;\n /** Timestamp when hook started */\n ts: number;\n /** Duration in milliseconds */\n durationMs?: number;\n /** Error if hook failed */\n error?: unknown;\n /** Additional context (e.g., stepKey for onAfterStep) */\n context?: {\n /** Step key for onAfterStep hooks */\n stepKey?: string;\n /** Result of shouldRun hook */\n result?: boolean;\n /** Whether workflow was skipped due to shouldRun returning false */\n skipped?: boolean;\n };\n}\n\n/**\n * Hook execution summary for the workflow.\n */\nexport interface WorkflowHooks {\n /** shouldRun hook execution (if configured) */\n shouldRun?: HookExecution;\n /** onBeforeStart hook execution (if configured) */\n onBeforeStart?: HookExecution;\n /** onAfterStep hook executions (keyed by stepKey) */\n onAfterStep: Map<string, HookExecution>;\n}\n","/**\n * ANSI color utilities for terminal output.\n */\n\nimport type { ColorScheme, StepState } from \"../types\";\n\n// =============================================================================\n// ANSI Escape Codes\n// =============================================================================\n\nconst RESET = \"\\x1b[0m\";\nconst BOLD = \"\\x1b[1m\";\nconst DIM = \"\\x1b[2m\";\n\n// Foreground colors\nconst FG_RED = \"\\x1b[31m\";\nconst FG_GREEN = \"\\x1b[32m\";\nconst FG_YELLOW = \"\\x1b[33m\";\nconst FG_BLUE = \"\\x1b[34m\";\nconst FG_GRAY = \"\\x1b[90m\";\nconst FG_WHITE = \"\\x1b[37m\";\n\n// =============================================================================\n// Color Functions\n// =============================================================================\n\n/**\n * Apply ANSI color to text.\n */\nexport function colorize(text: string, color: string): string {\n if (!color) return text;\n return `${color}${text}${RESET}`;\n}\n\n/**\n * Make text bold.\n */\nexport function bold(text: string): string {\n return `${BOLD}${text}${RESET}`;\n}\n\n/**\n * Make text dim.\n */\nexport function dim(text: string): string {\n return `${DIM}${text}${RESET}`;\n}\n\n// =============================================================================\n// Default Color Scheme\n// =============================================================================\n\n/**\n * Default ANSI color scheme for step states.\n */\nexport const defaultColorScheme: ColorScheme = {\n pending: FG_WHITE,\n running: FG_YELLOW,\n success: FG_GREEN,\n error: FG_RED,\n aborted: FG_GRAY,\n cached: FG_BLUE,\n skipped: DIM + FG_GRAY, // Dim gray for skipped steps\n};\n\n// =============================================================================\n// State Symbols\n// =============================================================================\n\n/**\n * Get the symbol for a step state.\n */\nexport function getStateSymbol(state: StepState): string {\n switch (state) {\n case \"pending\":\n return \"○\"; // Empty circle\n case \"running\":\n return \"⟳\"; // Rotating arrows\n case \"success\":\n return \"✓\"; // Check mark\n case \"error\":\n return \"✗\"; // X mark\n case \"aborted\":\n return \"⊘\"; // Circled slash\n case \"cached\":\n return \"↺\"; // Cached/replay\n case \"skipped\":\n return \"⊘\"; // Circled slash (same as aborted, but different color)\n }\n}\n\n/**\n * Get the colored symbol for a step state.\n */\nexport function getColoredSymbol(state: StepState, colors: ColorScheme): string {\n const symbol = getStateSymbol(state);\n return colorize(symbol, colors[state]);\n}\n\n/**\n * Get colored text based on step state.\n */\nexport function colorByState(\n text: string,\n state: StepState,\n colors: ColorScheme\n): string {\n return colorize(text, colors[state]);\n}\n\n// =============================================================================\n// Strip ANSI\n// =============================================================================\n\n/**\n * Strip ANSI escape codes from a string.\n * Useful for calculating visible string length.\n */\nexport function stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\n\n/**\n * Get the visible length of a string (without ANSI codes).\n */\nexport function visibleLength(str: string): string {\n return stripAnsi(str);\n}\n","/**\n * ASCII Terminal Renderer\n *\n * Renders the workflow IR as ASCII art with box-drawing characters\n * and ANSI colors for terminal display.\n */\n\nimport type {\n FlowNode,\n ParallelNode,\n RaceNode,\n DecisionNode,\n Renderer,\n RenderOptions,\n StepNode,\n WorkflowIR,\n EnhancedRenderOptions,\n HeatLevel,\n WorkflowHooks,\n HookExecution,\n} from \"../types\";\nimport { isParallelNode, isRaceNode, isStepNode, isDecisionNode } from \"../types\";\nimport { formatDuration } from \"../utils/timing\";\nimport {\n bold,\n colorByState,\n colorize,\n defaultColorScheme,\n dim,\n getColoredSymbol,\n stripAnsi,\n} from \"./colors\";\n\n// =============================================================================\n// Box Drawing Characters\n// =============================================================================\n\nconst BOX = {\n topLeft: \"┌\",\n topRight: \"┐\",\n bottomLeft: \"└\",\n bottomRight: \"┘\",\n horizontal: \"─\",\n vertical: \"│\",\n teeRight: \"├\",\n teeLeft: \"┤\",\n teeDown: \"┬\",\n teeUp: \"┴\",\n cross: \"┼\",\n} as const;\n\n// =============================================================================\n// Heatmap Colors (ANSI)\n// =============================================================================\n\n/**\n * ANSI color codes for heatmap visualization.\n */\nconst HEAT_COLORS: Record<HeatLevel, string> = {\n cold: \"\\x1b[34m\", // Blue\n cool: \"\\x1b[36m\", // Cyan\n neutral: \"\", // Default (no color)\n warm: \"\\x1b[33m\", // Yellow\n hot: \"\\x1b[31m\", // Red\n critical: \"\\x1b[41m\", // Red background\n};\n\nconst RESET = \"\\x1b[0m\";\n\n/**\n * Get ANSI color code for a heat level.\n */\nfunction getHeatColor(heat: number): string {\n if (heat < 0.2) return HEAT_COLORS.cold;\n if (heat < 0.4) return HEAT_COLORS.cool;\n if (heat < 0.6) return HEAT_COLORS.neutral;\n if (heat < 0.8) return HEAT_COLORS.warm;\n if (heat < 0.95) return HEAT_COLORS.hot;\n return HEAT_COLORS.critical;\n}\n\n/**\n * Apply heat coloring to a string.\n */\nfunction applyHeatColor(text: string, heat: number): string {\n const color = getHeatColor(heat);\n if (!color) return text;\n return `${color}${text}${RESET}`;\n}\n\n// =============================================================================\n// Sparkline Characters\n// =============================================================================\n\nconst SPARK_CHARS = \"▁▂▃▄▅▆▇█\";\n\n/**\n * Render a sparkline from an array of values.\n *\n * @param values Array of numeric values\n * @param width Maximum characters to use (default: 10)\n * @returns Sparkline string\n */\nexport function renderSparkline(values: number[], width = 10): string {\n if (values.length === 0) return \"\";\n\n // Take last N values\n const subset = values.slice(-width);\n const min = Math.min(...subset);\n const max = Math.max(...subset);\n const range = max - min || 1;\n\n return subset\n .map((v) => {\n const normalized = (v - min) / range;\n const index = Math.floor(normalized * (SPARK_CHARS.length - 1));\n return SPARK_CHARS[index];\n })\n .join(\"\");\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Pad a string to a fixed width, accounting for ANSI codes.\n */\nfunction padEnd(str: string, width: number): string {\n const visibleLen = stripAnsi(str).length;\n const padding = Math.max(0, width - visibleLen);\n return str + \" \".repeat(padding);\n}\n\n/**\n * Create a horizontal line with optional title.\n */\nfunction horizontalLine(width: number, title?: string): string {\n if (!title) {\n return BOX.horizontal.repeat(width);\n }\n\n const titleText = ` ${title} `;\n const remainingWidth = width - titleText.length;\n if (remainingWidth < 4) {\n return BOX.horizontal.repeat(width);\n }\n\n const leftPad = 2;\n const rightPad = remainingWidth - leftPad;\n\n return (\n BOX.horizontal.repeat(leftPad) + titleText + BOX.horizontal.repeat(rightPad)\n );\n}\n\n// =============================================================================\n// Hook Rendering\n// =============================================================================\n\n/**\n * Render a single hook execution.\n */\nfunction renderHookExecution(\n hook: HookExecution,\n label: string,\n colors: ReturnType<typeof Object.assign>\n): string {\n const symbol = hook.state === \"success\"\n ? colorize(\"⚙\", colors.success)\n : colorize(\"⚠\", colors.error);\n\n const timing = hook.durationMs !== undefined\n ? dim(` [${formatDuration(hook.durationMs)}]`)\n : \"\";\n\n let context = \"\";\n if (hook.type === \"shouldRun\" && hook.context?.skipped) {\n context = dim(\" → workflow skipped\");\n } else if (hook.type === \"shouldRun\" && hook.context?.result === true) {\n context = dim(\" → proceed\");\n } else if (hook.type === \"onBeforeStart\" && hook.context?.skipped) {\n context = dim(\" → workflow skipped\");\n } else if (hook.type === \"onAfterStep\" && hook.context?.stepKey) {\n context = dim(` (${hook.context.stepKey})`);\n }\n\n const error = hook.state === \"error\" && hook.error\n ? dim(` error: ${String(hook.error)}`)\n : \"\";\n\n return `${symbol} ${dim(label)}${context}${timing}${error}`;\n}\n\n/**\n * Render workflow hooks section.\n */\nfunction renderHooks(\n hooks: WorkflowHooks,\n colors: ReturnType<typeof Object.assign>\n): string[] {\n const lines: string[] = [];\n\n // Render shouldRun hook\n if (hooks.shouldRun) {\n lines.push(renderHookExecution(hooks.shouldRun, \"shouldRun\", colors));\n }\n\n // Render onBeforeStart hook\n if (hooks.onBeforeStart) {\n lines.push(renderHookExecution(hooks.onBeforeStart, \"onBeforeStart\", colors));\n }\n\n // We don't render onAfterStep hooks here - they're shown inline with steps\n // But if there are any, add a separator\n if (lines.length > 0) {\n lines.push(dim(\"────────────────────\")); // Separator between hooks and steps\n }\n\n return lines;\n}\n\n// =============================================================================\n// ASCII Renderer\n// =============================================================================\n\n/**\n * Create the ASCII terminal renderer.\n */\nexport function asciiRenderer(): Renderer {\n return {\n name: \"ascii\",\n supportsLive: true,\n\n render(ir: WorkflowIR, options: RenderOptions): string {\n const colors = { ...defaultColorScheme, ...options.colors };\n const width = options.terminalWidth ?? 60;\n const innerWidth = width - 4; // Account for borders\n\n const lines: string[] = [];\n\n // Header\n const workflowName = ir.root.name ?? \"workflow\";\n const headerTitle = bold(workflowName);\n lines.push(\n `${BOX.topLeft}${horizontalLine(width - 2, headerTitle)}${BOX.topRight}`\n );\n lines.push(`${BOX.vertical}${\" \".repeat(width - 2)}${BOX.vertical}`);\n\n // Render hooks (if any)\n if (ir.hooks) {\n const hookLines = renderHooks(ir.hooks, colors);\n for (const line of hookLines) {\n lines.push(\n `${BOX.vertical} ${padEnd(line, innerWidth)}${BOX.vertical}`\n );\n }\n }\n\n // Render children\n const childLines = renderNodes(ir.root.children, options, colors, 0, ir.hooks);\n for (const line of childLines) {\n lines.push(\n `${BOX.vertical} ${padEnd(line, innerWidth)}${BOX.vertical}`\n );\n }\n\n // Footer with timing\n lines.push(`${BOX.vertical}${\" \".repeat(width - 2)}${BOX.vertical}`);\n\n if (ir.root.durationMs !== undefined && options.showTimings) {\n const status = ir.root.state === \"success\" ? \"Completed\" : \"Failed\";\n const statusColored = colorByState(status, ir.root.state, colors);\n const footer = `${statusColored} in ${formatDuration(ir.root.durationMs)}`;\n lines.push(\n `${BOX.vertical} ${padEnd(footer, innerWidth)}${BOX.vertical}`\n );\n lines.push(`${BOX.vertical}${\" \".repeat(width - 2)}${BOX.vertical}`);\n }\n\n lines.push(\n `${BOX.bottomLeft}${BOX.horizontal.repeat(width - 2)}${BOX.bottomRight}`\n );\n\n return lines.join(\"\\n\");\n },\n };\n}\n\n/**\n * Render a list of nodes.\n */\nfunction renderNodes(\n nodes: FlowNode[],\n options: RenderOptions,\n colors: ReturnType<typeof Object.assign>,\n depth: number,\n hooks?: WorkflowHooks\n): string[] {\n const lines: string[] = [];\n\n for (const node of nodes) {\n if (isStepNode(node)) {\n lines.push(renderStepNode(node, options, colors, hooks));\n } else if (isParallelNode(node)) {\n lines.push(...renderParallelNode(node, options, colors, depth, hooks));\n } else if (isRaceNode(node)) {\n lines.push(...renderRaceNode(node, options, colors, depth, hooks));\n } else if (isDecisionNode(node)) {\n lines.push(...renderDecisionNode(node, options, colors, depth, hooks));\n }\n }\n\n return lines;\n}\n\n/**\n * Render a single step node.\n */\nfunction renderStepNode(\n node: StepNode,\n options: RenderOptions,\n colors: ReturnType<typeof Object.assign>,\n hooks?: WorkflowHooks\n): string {\n const symbol = getColoredSymbol(node.state, colors);\n const name = node.name ?? node.key ?? \"step\";\n\n // Check for enhanced options\n const enhanced = options as EnhancedRenderOptions;\n const nodeId = node.name ?? node.id;\n\n // Get heat value for this node (if heatmap is enabled)\n const heat = enhanced.showHeatmap && enhanced.heatmapData\n ? enhanced.heatmapData.heat.get(node.id) ?? enhanced.heatmapData.heat.get(nodeId)\n : undefined;\n\n // Apply heat coloring or default state coloring\n let nameColored: string;\n if (heat !== undefined) {\n nameColored = applyHeatColor(name, heat);\n } else {\n nameColored = colorByState(name, node.state, colors);\n }\n\n let line = `${symbol} ${nameColored}`;\n\n // Add key if requested\n if (options.showKeys && node.key) {\n line += dim(` [key: ${node.key}]`);\n }\n\n // Add input/output if available (for decision understanding)\n if (node.input !== undefined) {\n const inputStr = typeof node.input === \"string\"\n ? node.input\n : JSON.stringify(node.input).slice(0, 30);\n line += dim(` [in: ${inputStr}${inputStr.length >= 30 ? \"...\" : \"\"}]`);\n }\n if (node.output !== undefined && node.state === \"success\") {\n const outputStr = typeof node.output === \"string\"\n ? node.output\n : JSON.stringify(node.output).slice(0, 30);\n line += dim(` [out: ${outputStr}${outputStr.length >= 30 ? \"...\" : \"\"}]`);\n }\n\n // Add timing if available and requested\n if (options.showTimings && node.durationMs !== undefined) {\n // Apply heat coloring to timing if enabled\n const timingStr = formatDuration(node.durationMs);\n const timingDisplay = heat !== undefined\n ? applyHeatColor(`[${timingStr}]`, heat)\n : dim(`[${timingStr}]`);\n line += ` ${timingDisplay}`;\n }\n\n // Add sparkline if enabled and history available\n if (enhanced.showSparklines && enhanced.timingHistory) {\n const history = enhanced.timingHistory.get(nodeId);\n if (history && history.length > 1) {\n line += ` ${dim(renderSparkline(history))}`;\n }\n }\n\n // Add retry indicator if retries occurred\n if (node.retryCount !== undefined && node.retryCount > 0) {\n line += dim(` [${node.retryCount} ${node.retryCount === 1 ? \"retry\" : \"retries\"}]`);\n }\n\n // Add timeout indicator if step timed out\n if (node.timedOut) {\n const timeoutInfo = node.timeoutMs !== undefined ? ` ${node.timeoutMs}ms` : \"\";\n line += dim(` [timeout${timeoutInfo}]`);\n }\n\n // Add onAfterStep hook indicator if present\n if (hooks && node.key && hooks.onAfterStep.has(node.key)) {\n const hookExec = hooks.onAfterStep.get(node.key)!;\n const hookSymbol = hookExec.state === \"success\"\n ? colorize(\"⚙\", colors.success)\n : colorize(\"⚠\", colors.error);\n const hookTiming = hookExec.durationMs !== undefined\n ? dim(` ${formatDuration(hookExec.durationMs)}`)\n : \"\";\n line += ` ${hookSymbol}${hookTiming}`;\n }\n\n return line;\n}\n\n/**\n * Render a parallel node (allAsync).\n */\nfunction renderParallelNode(\n node: ParallelNode,\n options: RenderOptions,\n colors: ReturnType<typeof Object.assign>,\n depth: number,\n hooks?: WorkflowHooks\n): string[] {\n const lines: string[] = [];\n const indent = \" \".repeat(depth);\n\n // Header\n const symbol = getColoredSymbol(node.state, colors);\n const name = node.name ?? \"parallel\";\n const mode = node.mode === \"allSettled\" ? \" (allSettled)\" : \"\";\n lines.push(`${indent}${BOX.teeRight}${BOX.teeDown}${BOX.horizontal} ${symbol} ${bold(name)}${mode}`);\n\n // Children\n if (node.children.length === 0) {\n // Empty parallel scope - operations inside allAsync/anyAsync weren't tracked as steps\n lines.push(`${indent}${BOX.vertical} ${dim(\"(operations not individually tracked)\")}`);\n lines.push(`${indent}${BOX.vertical} ${dim(\"(wrap each operation with step() to see individual steps)\")}`);\n } else {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const isLast = i === node.children.length - 1;\n const prefix = isLast ? `${indent}${BOX.vertical} ${BOX.bottomLeft}` : `${indent}${BOX.vertical} ${BOX.teeRight}`;\n\n if (isStepNode(child)) {\n lines.push(`${prefix} ${renderStepNode(child, options, colors, hooks)}`);\n } else {\n // Nested structure - recurse\n const nestedLines = renderNodes([child], options, colors, depth + 1, hooks);\n for (const line of nestedLines) {\n lines.push(`${indent}${BOX.vertical} ${line}`);\n }\n }\n }\n }\n\n // Timing footer\n if (options.showTimings && node.durationMs !== undefined) {\n lines.push(`${indent}${BOX.bottomLeft}${BOX.horizontal}${BOX.horizontal} ${dim(`[${formatDuration(node.durationMs)}]`)}`);\n }\n\n return lines;\n}\n\n/**\n * Render a race node (anyAsync).\n */\nfunction renderRaceNode(\n node: RaceNode,\n options: RenderOptions,\n colors: ReturnType<typeof Object.assign>,\n depth: number,\n hooks?: WorkflowHooks\n): string[] {\n const lines: string[] = [];\n const indent = \" \".repeat(depth);\n\n // Header with lightning bolt for race\n const symbol = getColoredSymbol(node.state, colors);\n const name = node.name ?? \"race\";\n lines.push(`${indent}${BOX.teeRight}⚡ ${symbol} ${bold(name)}`);\n\n // Children\n if (node.children.length === 0) {\n // Empty race scope - operations inside anyAsync weren't tracked as steps\n lines.push(`${indent}${BOX.vertical} ${dim(\"(operations not individually tracked)\")}`);\n lines.push(`${indent}${BOX.vertical} ${dim(\"(wrap each operation with step() to see individual steps)\")}`);\n } else {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const isLast = i === node.children.length - 1;\n const prefix = isLast ? `${indent}${BOX.vertical} ${BOX.bottomLeft}` : `${indent}${BOX.vertical} ${BOX.teeRight}`;\n\n // Mark winner\n const isWinner = node.winnerId && child.id === node.winnerId;\n const winnerSuffix = isWinner ? dim(\" (winner)\") : \"\";\n\n if (isStepNode(child)) {\n lines.push(`${prefix} ${renderStepNode(child, options, colors, hooks)}${winnerSuffix}`);\n } else {\n const nestedLines = renderNodes([child], options, colors, depth + 1, hooks);\n for (const line of nestedLines) {\n lines.push(`${indent}${BOX.vertical} ${line}`);\n }\n }\n }\n }\n\n // Timing footer\n if (options.showTimings && node.durationMs !== undefined) {\n lines.push(`${indent}${BOX.bottomLeft}${BOX.horizontal}${BOX.horizontal} ${dim(`[${formatDuration(node.durationMs)}]`)}`);\n }\n\n return lines;\n}\n\n/**\n * Render a decision node (conditional branch).\n */\nfunction renderDecisionNode(\n node: DecisionNode,\n options: RenderOptions,\n colors: ReturnType<typeof Object.assign>,\n depth: number,\n hooks?: WorkflowHooks\n): string[] {\n const lines: string[] = [];\n const indent = \" \".repeat(depth);\n\n // Header with decision info\n const symbol = getColoredSymbol(node.state, colors);\n const name = node.name ?? \"decision\";\n const condition = node.condition\n ? dim(` (${node.condition})`)\n : \"\";\n const decisionValue = node.decisionValue !== undefined\n ? dim(` = ${String(node.decisionValue)}`)\n : \"\";\n const branchTaken = node.branchTaken !== undefined\n ? dim(` → ${String(node.branchTaken)}`)\n : \"\";\n\n lines.push(\n `${indent}${BOX.teeRight}${BOX.teeDown}${BOX.horizontal} ${symbol} ${bold(name)}${condition}${decisionValue}${branchTaken}`\n );\n\n // Render branches\n for (let i = 0; i < node.branches.length; i++) {\n const branch = node.branches[i];\n const isLast = i === node.branches.length - 1;\n const prefix = isLast\n ? `${indent}${BOX.vertical} ${BOX.bottomLeft}`\n : `${indent}${BOX.vertical} ${BOX.teeRight}`;\n\n // Branch label with taken/skipped indicator\n const branchSymbol = branch.taken ? \"✓\" : \"⊘\";\n const branchColor = branch.taken ? colors.success : colors.skipped;\n const branchLabel = colorize(\n `${branchSymbol} ${branch.label}`,\n branchColor\n );\n const branchCondition = branch.condition\n ? dim(` (${branch.condition})`)\n : \"\";\n\n lines.push(`${prefix} ${branchLabel}${branchCondition}`);\n\n // Render children of this branch\n if (branch.children.length > 0) {\n const childLines = renderNodes(branch.children, options, colors, depth + 1, hooks);\n for (const line of childLines) {\n lines.push(`${indent}${BOX.vertical} ${line}`);\n }\n } else if (!branch.taken) {\n // Show that this branch was skipped\n lines.push(\n `${indent}${BOX.vertical} ${dim(\"(skipped)\")}`\n );\n }\n }\n\n // Timing footer\n if (options.showTimings && node.durationMs !== undefined) {\n lines.push(\n `${indent}${BOX.bottomLeft}${BOX.horizontal}${BOX.horizontal} ${dim(`[${formatDuration(node.durationMs)}]`)}`\n );\n }\n\n return lines;\n}\n\nexport { defaultColorScheme };\n","/**\n * Performance Analyzer\n *\n * Analyzes workflow execution data to identify:\n * - Slow steps (bottlenecks)\n * - Retry patterns\n * - Error-prone steps\n * - Timing anomalies\n *\n * Aggregates metrics across multiple workflow runs to provide\n * statistical insights and heatmap visualization data.\n */\n\nimport type { WorkflowEvent } from \"../core\";\nimport type {\n NodePerformance,\n HeatmapData,\n WorkflowIR,\n FlowNode,\n HeatLevel,\n} from \"./types\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * A recorded workflow run for analysis.\n */\nexport interface WorkflowRun {\n /** Unique identifier for this run */\n id: string;\n /** Workflow start timestamp */\n startTime: number;\n /** All events from the workflow execution */\n events: WorkflowEvent<unknown>[];\n}\n\n/**\n * Performance analyzer interface.\n */\nexport interface PerformanceAnalyzer {\n /** Add a completed workflow run for analysis */\n addRun: (run: WorkflowRun) => void;\n\n /** Add events incrementally (alternative to addRun) */\n addEvent: (event: WorkflowEvent<unknown>) => void;\n\n /** Finalize current run (when using addEvent) */\n finalizeRun: (runId: string) => void;\n\n /** Get performance stats for a specific node */\n getNodePerformance: (nodeId: string) => NodePerformance | undefined;\n\n /** Get heatmap data for an IR */\n getHeatmap: (\n ir: WorkflowIR,\n metric?: \"duration\" | \"retryRate\" | \"errorRate\"\n ) => HeatmapData;\n\n /** Get slowest nodes */\n getSlowestNodes: (limit?: number) => NodePerformance[];\n\n /** Get error-prone nodes */\n getErrorProneNodes: (limit?: number) => NodePerformance[];\n\n /** Get retry-prone nodes */\n getRetryProneNodes: (limit?: number) => NodePerformance[];\n\n /** Get all performance data */\n getAllPerformance: () => Map<string, NodePerformance>;\n\n /** Export performance data as JSON */\n exportData: () => string;\n\n /** Import performance data from JSON */\n importData: (json: string) => void;\n\n /** Clear all collected data */\n clear: () => void;\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Flatten all nodes from an IR tree.\n */\nfunction flattenNodes(nodes: FlowNode[]): FlowNode[] {\n const result: FlowNode[] = [];\n for (const node of nodes) {\n result.push(node);\n if (\"children\" in node && Array.isArray(node.children)) {\n result.push(...flattenNodes(node.children));\n }\n if (\"branches\" in node) {\n for (const branch of node.branches) {\n result.push(...flattenNodes(branch.children));\n }\n }\n }\n return result;\n}\n\n/**\n * Calculate percentile value from sorted array.\n */\nfunction percentile(sortedValues: number[], p: number): number {\n if (sortedValues.length === 0) return 0;\n const index = Math.floor(sortedValues.length * p);\n return sortedValues[Math.min(index, sortedValues.length - 1)];\n}\n\n/**\n * Get heat level from normalized value (0-1).\n */\nexport function getHeatLevel(heat: number): HeatLevel {\n if (heat < 0.2) return \"cold\";\n if (heat < 0.4) return \"cool\";\n if (heat < 0.6) return \"neutral\";\n if (heat < 0.8) return \"warm\";\n if (heat < 0.95) return \"hot\";\n return \"critical\";\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/**\n * Create a performance analyzer for workflow metrics.\n *\n * @example\n * ```typescript\n * const analyzer = createPerformanceAnalyzer();\n *\n * // Add completed runs\n * analyzer.addRun({ id: 'run-1', startTime: Date.now(), events });\n *\n * // Get insights\n * const slowest = analyzer.getSlowestNodes(5);\n * const heatmap = analyzer.getHeatmap(ir, 'duration');\n * ```\n */\nexport function createPerformanceAnalyzer(): PerformanceAnalyzer {\n // Timing data: nodeId → array of durations (ms)\n const timingData = new Map<string, number[]>();\n\n // Retry data: nodeId → { retried runs, total runs }\n const retryData = new Map<string, { retried: number; total: number }>();\n\n // Error data: nodeId → { error runs, total runs }\n const errorData = new Map<string, { errors: number; total: number }>();\n\n // Timeout data: nodeId → { timed out, total }\n const timeoutData = new Map<string, { timedOut: number; total: number }>();\n\n // Current run state (for incremental event adding)\n let currentRunEvents: WorkflowEvent<unknown>[] = [];\n\n /**\n * Get node ID from event (uses name or stepId).\n */\n function getNodeId(event: {\n stepId?: string;\n stepKey?: string;\n name?: string;\n }): string {\n return event.name ?? event.stepKey ?? event.stepId ?? \"unknown\";\n }\n\n /**\n * Process events from a workflow run.\n */\n function processEvents(events: WorkflowEvent<unknown>[]): void {\n // Track step state during processing\n const stepState = new Map<\n string,\n {\n retried: boolean;\n timedOut: boolean;\n }\n >();\n\n for (const event of events) {\n switch (event.type) {\n case \"step_start\": {\n const id = getNodeId(event);\n stepState.set(id, { retried: false, timedOut: false });\n break;\n }\n\n case \"step_retry\": {\n const id = getNodeId(event);\n const state = stepState.get(id);\n if (state) {\n state.retried = true;\n }\n break;\n }\n\n case \"step_timeout\": {\n const id = getNodeId(event);\n const state = stepState.get(id);\n if (state) {\n state.timedOut = true;\n }\n // Track timeout stats\n const timeout = timeoutData.get(id) ?? { timedOut: 0, total: 0 };\n timeout.timedOut++;\n timeout.total++;\n timeoutData.set(id, timeout);\n break;\n }\n\n case \"step_success\": {\n const id = getNodeId(event);\n const state = stepState.get(id);\n\n // Record timing\n const timings = timingData.get(id) ?? [];\n timings.push(event.durationMs);\n timingData.set(id, timings);\n\n // Record retry status\n const retry = retryData.get(id) ?? { retried: 0, total: 0 };\n retry.total++;\n if (state?.retried) retry.retried++;\n retryData.set(id, retry);\n\n // Record success (no error)\n const error = errorData.get(id) ?? { errors: 0, total: 0 };\n error.total++;\n errorData.set(id, error);\n\n stepState.delete(id);\n break;\n }\n\n case \"step_error\": {\n const id = getNodeId(event);\n const state = stepState.get(id);\n\n // Record timing\n const timings = timingData.get(id) ?? [];\n timings.push(event.durationMs);\n timingData.set(id, timings);\n\n // Record retry status\n const retry = retryData.get(id) ?? { retried: 0, total: 0 };\n retry.total++;\n if (state?.retried) retry.retried++;\n retryData.set(id, retry);\n\n // Record error\n const error = errorData.get(id) ?? { errors: 0, total: 0 };\n error.total++;\n error.errors++;\n errorData.set(id, error);\n\n stepState.delete(id);\n break;\n }\n }\n }\n }\n\n /**\n * Add a completed workflow run.\n */\n function addRun(run: WorkflowRun): void {\n processEvents(run.events);\n }\n\n /**\n * Add an event incrementally.\n */\n function addEvent(event: WorkflowEvent<unknown>): void {\n currentRunEvents.push(event);\n }\n\n /**\n * Finalize current run (process accumulated events).\n */\n function finalizeRun(_runId: string): void {\n if (currentRunEvents.length > 0) {\n processEvents(currentRunEvents);\n currentRunEvents = [];\n }\n }\n\n /**\n * Compute performance metrics for a node.\n */\n function computePerformance(nodeId: string): NodePerformance | undefined {\n const timings = timingData.get(nodeId);\n if (!timings || timings.length === 0) return undefined;\n\n const sorted = [...timings].sort((a, b) => a - b);\n const sum = sorted.reduce((a, b) => a + b, 0);\n const mean = sum / sorted.length;\n const variance =\n sorted.reduce((acc, t) => acc + (t - mean) ** 2, 0) / sorted.length;\n\n const retry = retryData.get(nodeId) ?? { retried: 0, total: 1 };\n const error = errorData.get(nodeId) ?? { errors: 0, total: 1 };\n const timeout = timeoutData.get(nodeId) ?? { timedOut: 0, total: 1 };\n\n return {\n nodeId,\n avgDurationMs: mean,\n minDurationMs: sorted[0],\n maxDurationMs: sorted[sorted.length - 1],\n stdDevMs: Math.sqrt(variance),\n samples: sorted.length,\n retryRate: retry.total > 0 ? retry.retried / retry.total : 0,\n timeoutRate: timeout.total > 0 ? timeout.timedOut / timeout.total : 0,\n errorRate: error.total > 0 ? error.errors / error.total : 0,\n percentiles: {\n p50: percentile(sorted, 0.5),\n p90: percentile(sorted, 0.9),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n },\n };\n }\n\n /**\n * Get performance stats for a specific node.\n */\n function getNodePerformance(nodeId: string): NodePerformance | undefined {\n return computePerformance(nodeId);\n }\n\n /**\n * Get heatmap data for an IR.\n */\n function getHeatmap(\n ir: WorkflowIR,\n metric: \"duration\" | \"retryRate\" | \"errorRate\" = \"duration\"\n ): HeatmapData {\n const heat = new Map<string, number>();\n const allNodes = flattenNodes(ir.root.children);\n\n // Compute values for all nodes\n const values: Array<{ id: string; value: number }> = [];\n for (const node of allNodes) {\n // Try node.name first, then node.id\n const nodeId = node.name ?? node.id;\n const perf = computePerformance(nodeId);\n if (perf) {\n let value: number;\n switch (metric) {\n case \"duration\":\n value = perf.avgDurationMs;\n break;\n case \"retryRate\":\n value = perf.retryRate;\n break;\n case \"errorRate\":\n value = perf.errorRate;\n break;\n }\n values.push({ id: node.id, value });\n }\n }\n\n if (values.length === 0) {\n return {\n heat,\n metric,\n stats: { min: 0, max: 0, mean: 0, threshold: 0 },\n };\n }\n\n // Compute statistics\n const vals = values.map((v) => v.value);\n const min = Math.min(...vals);\n const max = Math.max(...vals);\n const mean = vals.reduce((a, b) => a + b, 0) / vals.length;\n const range = max - min || 1;\n\n // Normalize to 0-1 heat values\n for (const { id, value } of values) {\n heat.set(id, (value - min) / range);\n }\n\n return {\n heat,\n metric,\n stats: {\n min,\n max,\n mean,\n threshold: mean + (max - mean) * 0.5, // 50% above mean is \"hot\"\n },\n };\n }\n\n /**\n * Get all performance data.\n */\n function getAllPerformance(): Map<string, NodePerformance> {\n const result = new Map<string, NodePerformance>();\n for (const nodeId of timingData.keys()) {\n const perf = computePerformance(nodeId);\n if (perf) result.set(nodeId, perf);\n }\n return result;\n }\n\n /**\n * Get slowest nodes by average duration.\n */\n function getSlowestNodes(limit = 10): NodePerformance[] {\n const all = getAllPerformance();\n return [...all.values()]\n .sort((a, b) => b.avgDurationMs - a.avgDurationMs)\n .slice(0, limit);\n }\n\n /**\n * Get error-prone nodes by error rate.\n */\n function getErrorProneNodes(limit = 10): NodePerformance[] {\n const all = getAllPerformance();\n return [...all.values()]\n .filter((p) => p.errorRate > 0)\n .sort((a, b) => b.errorRate - a.errorRate)\n .slice(0, limit);\n }\n\n /**\n * Get retry-prone nodes by retry rate.\n */\n function getRetryProneNodes(limit = 10): NodePerformance[] {\n const all = getAllPerformance();\n return [...all.values()]\n .filter((p) => p.retryRate > 0)\n .sort((a, b) => b.retryRate - a.retryRate)\n .slice(0, limit);\n }\n\n /**\n * Export performance data as JSON.\n */\n function exportData(): string {\n return JSON.stringify({\n timingData: Object.fromEntries(timingData),\n retryData: Object.fromEntries(retryData),\n errorData: Object.fromEntries(errorData),\n timeoutData: Object.fromEntries(timeoutData),\n });\n }\n\n /**\n * Import performance data from JSON.\n */\n function importData(json: string): void {\n const data = JSON.parse(json) as {\n timingData?: Record<string, number[]>;\n retryData?: Record<string, { retried: number; total: number }>;\n errorData?: Record<string, { errors: number; total: number }>;\n timeoutData?: Record<string, { timedOut: number; total: number }>;\n };\n\n // Clear existing data\n timingData.clear();\n retryData.clear();\n errorData.clear();\n timeoutData.clear();\n\n // Import timing data\n for (const [k, v] of Object.entries(data.timingData ?? {})) {\n timingData.set(k, v);\n }\n\n // Import retry data\n for (const [k, v] of Object.entries(data.retryData ?? {})) {\n retryData.set(k, v);\n }\n\n // Import error data\n for (const [k, v] of Object.entries(data.errorData ?? {})) {\n errorData.set(k, v);\n }\n\n // Import timeout data\n for (const [k, v] of Object.entries(data.timeoutData ?? {})) {\n timeoutData.set(k, v);\n }\n }\n\n /**\n * Clear all collected data.\n */\n function clear(): void {\n timingData.clear();\n retryData.clear();\n errorData.clear();\n timeoutData.clear();\n currentRunEvents = [];\n }\n\n return {\n addRun,\n addEvent,\n finalizeRun,\n getNodePerformance,\n getHeatmap,\n getSlowestNodes,\n getErrorProneNodes,\n getRetryProneNodes,\n getAllPerformance,\n exportData,\n importData,\n clear,\n };\n}\n","/**\n * Mermaid Diagram Renderer\n *\n * Renders the workflow IR as a Mermaid flowchart diagram.\n * Supports sequential flows, parallel (subgraph), and race patterns.\n */\n\nimport type {\n FlowNode,\n ParallelNode,\n RaceNode,\n DecisionNode,\n Renderer,\n RenderOptions,\n MermaidRenderOptions,\n StepNode,\n StepState,\n WorkflowIR,\n EnhancedRenderOptions,\n HeatLevel,\n WorkflowHooks,\n} from \"../types\";\nimport { isParallelNode, isRaceNode, isStepNode, isDecisionNode } from \"../types\";\nimport { formatDuration } from \"../utils/timing\";\nimport { getHeatLevel } from \"../performance-analyzer\";\n\n// =============================================================================\n// Mermaid Style Definitions\n// =============================================================================\n\n/**\n * Get Mermaid class definition for step states.\n * Colors inspired by AWS Step Functions and XState visualizers for professional appearance.\n */\nfunction getStyleDefinitions(): string[] {\n return [\n // Pending - light gray, subtle\n \" classDef pending fill:#f3f4f6,stroke:#9ca3af,stroke-width:2px,color:#374151\",\n // Running - amber/yellow, indicates active execution\n \" classDef running fill:#fef3c7,stroke:#f59e0b,stroke-width:3px,color:#92400e\",\n // Success - green, clear positive indicator\n \" classDef success fill:#d1fae5,stroke:#10b981,stroke-width:3px,color:#065f46\",\n // Error - red, clear negative indicator\n \" classDef error fill:#fee2e2,stroke:#ef4444,stroke-width:3px,color:#991b1b\",\n // Aborted - gray, indicates cancellation\n \" classDef aborted fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#4b5563,stroke-dasharray: 5 5\",\n // Cached - blue, indicates cache hit\n \" classDef cached fill:#dbeafe,stroke:#3b82f6,stroke-width:3px,color:#1e40af\",\n // Skipped - light gray with dashed border\n \" classDef skipped fill:#f9fafb,stroke:#d1d5db,stroke-width:2px,color:#6b7280,stroke-dasharray: 5 5\",\n ];\n}\n\n/**\n * Get Mermaid class definitions for heatmap visualization.\n */\nfunction getHeatmapStyleDefinitions(): string[] {\n return [\n // Heatmap colors - cold to hot\n \" classDef heat_cold fill:#dbeafe,stroke:#3b82f6,stroke-width:2px,color:#1e40af\",\n \" classDef heat_cool fill:#ccfbf1,stroke:#14b8a6,stroke-width:2px,color:#0f766e\",\n \" classDef heat_neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#374151\",\n \" classDef heat_warm fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#92400e\",\n \" classDef heat_hot fill:#fed7aa,stroke:#f97316,stroke-width:3px,color:#c2410c\",\n \" classDef heat_critical fill:#fecaca,stroke:#ef4444,stroke-width:3px,color:#b91c1c\",\n ];\n}\n\n/**\n * Get the Mermaid class name for a heat level.\n */\nfunction getHeatClass(level: HeatLevel): string {\n return `heat_${level}`;\n}\n\n/**\n * Get the Mermaid class name for a step state.\n */\nfunction getStateClass(state: StepState): string {\n return state;\n}\n\n/**\n * Get Mermaid class definitions for hook visualization.\n */\nfunction getHookStyleDefinitions(): string[] {\n return [\n // Hook styles - gear icon aesthetic\n \" classDef hook_success fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e\",\n \" classDef hook_error fill:#fef2f2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d\",\n ];\n}\n\n/**\n * Render hooks as nodes before the workflow starts.\n * Returns the ID of the last hook node (to connect to workflow start).\n */\nfunction renderHooks(\n hooks: WorkflowHooks,\n lines: string[],\n options: RenderOptions\n): { lastHookId: string | undefined } {\n let lastHookId: string | undefined;\n\n // Render shouldRun hook\n if (hooks.shouldRun) {\n const hookId = \"hook_shouldRun\";\n const state = hooks.shouldRun.state === \"success\" ? \"hook_success\" : \"hook_error\";\n const icon = hooks.shouldRun.state === \"success\" ? \"⚙\" : \"⚠\";\n const timing = options.showTimings && hooks.shouldRun.durationMs !== undefined\n ? ` ${formatDuration(hooks.shouldRun.durationMs)}`\n : \"\";\n const context = hooks.shouldRun.context?.skipped\n ? \"\\\\nskipped workflow\"\n : hooks.shouldRun.context?.result === true\n ? \"\\\\nproceed\"\n : \"\";\n\n lines.push(` ${hookId}[[\"${icon} shouldRun${context}${timing}\"]]:::${state}`);\n lastHookId = hookId;\n }\n\n // Render onBeforeStart hook\n if (hooks.onBeforeStart) {\n const hookId = \"hook_beforeStart\";\n const state = hooks.onBeforeStart.state === \"success\" ? \"hook_success\" : \"hook_error\";\n const icon = hooks.onBeforeStart.state === \"success\" ? \"⚙\" : \"⚠\";\n const timing = options.showTimings && hooks.onBeforeStart.durationMs !== undefined\n ? ` ${formatDuration(hooks.onBeforeStart.durationMs)}`\n : \"\";\n const context = hooks.onBeforeStart.context?.skipped\n ? \"\\\\nskipped workflow\"\n : \"\";\n\n lines.push(` ${hookId}[[\"${icon} onBeforeStart${context}${timing}\"]]:::${state}`);\n\n // Connect from previous hook if exists\n if (lastHookId) {\n lines.push(` ${lastHookId} --> ${hookId}`);\n }\n lastHookId = hookId;\n }\n\n return { lastHookId };\n}\n\n// =============================================================================\n// Node ID Generation\n// =============================================================================\n\nlet nodeCounter = 0;\n\nfunction generateNodeId(prefix: string = \"node\"): string {\n return `${prefix}_${++nodeCounter}`;\n}\n\nfunction resetNodeCounter(): void {\n nodeCounter = 0;\n}\n\n// =============================================================================\n// Mermaid Text Escaping\n// =============================================================================\n\n/**\n * Escape text for use in Mermaid diagrams.\n * Removes characters that break Mermaid parsing.\n * \n * Characters removed:\n * - {}[]() - Brackets and parentheses break parsing in labels\n * - <> - Angle brackets can cause issues\n * - \" - Double quotes replaced with single quotes\n * \n * @param text - Text to escape\n * @returns Escaped text safe for Mermaid\n */\nfunction escapeMermaidText(text: string): string {\n return text\n .replace(/[{}[\\]()]/g, \"\") // Remove brackets and parentheses (they break parsing)\n .replace(/[<>]/g, \"\") // Remove angle brackets\n .replace(/\"/g, \"'\") // Replace double quotes with single\n .trim();\n}\n\n/**\n * Escape text for use in Mermaid subgraph names.\n * Subgraph names in brackets need special handling.\n * \n * @param text - Text to escape for subgraph name\n * @returns Escaped text safe for subgraph names\n */\nfunction escapeSubgraphName(text: string): string {\n return escapeMermaidText(text)\n .replace(/[[\\]]/g, \"\"); // Also remove brackets from subgraph names\n}\n\n// =============================================================================\n// Mermaid Renderer\n// =============================================================================\n\n/**\n * Create the Mermaid diagram renderer.\n */\nexport function mermaidRenderer(): Renderer {\n return {\n name: \"mermaid\",\n supportsLive: false,\n\n render(ir: WorkflowIR, options: RenderOptions): string {\n resetNodeCounter();\n const lines: string[] = [];\n\n // Check for enhanced options (heatmap)\n const enhanced = options as EnhancedRenderOptions;\n\n // Diagram header\n lines.push(\"flowchart TD\");\n\n // Render hooks first (if any)\n let hookExitId: string | undefined;\n if (ir.hooks) {\n const hookResult = renderHooks(ir.hooks, lines, options);\n hookExitId = hookResult.lastHookId;\n }\n\n // Start node - more visually distinctive\n const startId = \"start\";\n lines.push(` ${startId}((\"▶ Start\"))`);\n\n // Connect hooks to start node\n if (hookExitId) {\n lines.push(` ${hookExitId} --> ${startId}`);\n }\n\n // Track the last node for connections\n let prevNodeId = startId;\n\n // Render children (passing hooks for onAfterStep annotations)\n for (const child of ir.root.children) {\n const result = renderNode(child, options, lines, enhanced, ir.hooks);\n lines.push(` ${prevNodeId} --> ${result.entryId}`);\n prevNodeId = result.exitId;\n }\n\n // End node (if workflow completed) - more visually distinctive\n if (ir.root.state === \"success\" || ir.root.state === \"error\") {\n const endId = \"finish\";\n const endIcon = ir.root.state === \"success\" ? \"✓\" : \"✗\";\n const endLabel = ir.root.state === \"success\" ? \"Done\" : \"Failed\";\n const endShape = `((\"${endIcon} ${endLabel}\"))`;\n const endClass =\n ir.root.state === \"success\" ? \":::success\" : \":::error\";\n lines.push(` ${endId}${endShape}${endClass}`);\n lines.push(` ${prevNodeId} --> ${endId}`);\n }\n\n // Add style definitions\n lines.push(\"\");\n lines.push(...getStyleDefinitions());\n\n // Add heatmap styles if enabled\n if (enhanced.showHeatmap) {\n lines.push(...getHeatmapStyleDefinitions());\n }\n\n // Add hook styles if hooks were rendered\n if (ir.hooks) {\n lines.push(...getHookStyleDefinitions());\n }\n\n return lines.join(\"\\n\");\n },\n };\n}\n\n/**\n * Render result with entry and exit node IDs.\n */\ninterface RenderResult {\n entryId: string;\n exitId: string;\n}\n\n/**\n * Render a node and return its entry/exit IDs.\n */\nfunction renderNode(\n node: FlowNode,\n options: RenderOptions,\n lines: string[],\n enhanced?: EnhancedRenderOptions,\n hooks?: WorkflowHooks\n): RenderResult {\n if (isStepNode(node)) {\n return renderStepNode(node, options, lines, enhanced, hooks);\n } else if (isParallelNode(node)) {\n return renderParallelNode(node, options, lines, enhanced, hooks);\n } else if (isRaceNode(node)) {\n return renderRaceNode(node, options, lines, enhanced, hooks);\n } else if (isDecisionNode(node)) {\n return renderDecisionNode(node, options, lines, enhanced, hooks);\n }\n\n // Fallback for sequence or unknown nodes\n const id = generateNodeId(\"unknown\");\n lines.push(` ${id}[Unknown Node]`);\n return { entryId: id, exitId: id };\n}\n\n/**\n * Render a step node.\n */\nfunction renderStepNode(\n node: StepNode,\n options: RenderOptions,\n lines: string[],\n enhanced?: EnhancedRenderOptions,\n hooks?: WorkflowHooks\n): RenderResult {\n // Cast to MermaidRenderOptions to access extended options\n const mermaidOpts = options as MermaidRenderOptions;\n const showRetryEdges = mermaidOpts.showRetryEdges ?? true;\n const showErrorEdges = mermaidOpts.showErrorEdges ?? true;\n const showTimeoutEdges = mermaidOpts.showTimeoutEdges ?? true;\n\n const id = node.key\n ? `step_${node.key.replace(/[^a-zA-Z0-9]/g, \"_\")}`\n : generateNodeId(\"step\");\n\n const label = escapeMermaidText(node.name ?? node.key ?? \"Step\");\n\n // Format timing - use space instead of parentheses to avoid Mermaid parse errors\n const timing =\n options.showTimings && node.durationMs !== undefined\n ? ` ${formatDuration(node.durationMs)}`\n : \"\";\n\n // Add visual indicators based on state (like XState/AWS Step Functions)\n let stateIcon = \"\";\n switch (node.state) {\n case \"success\":\n stateIcon = \"✓ \";\n break;\n case \"error\":\n stateIcon = \"✗ \";\n break;\n case \"cached\":\n stateIcon = \"💾 \";\n break;\n case \"running\":\n stateIcon = \"⏳ \";\n break;\n case \"skipped\":\n stateIcon = \"⊘ \";\n break;\n }\n\n // Add input/output info if available\n // Use newlines for multi-line labels, but escape special characters\n let ioInfo = \"\";\n if (node.input !== undefined) {\n const inputStr = typeof node.input === \"string\"\n ? escapeMermaidText(node.input)\n : escapeMermaidText(JSON.stringify(node.input).slice(0, 20));\n ioInfo += `\\\\nin: ${inputStr}`;\n }\n if (node.output !== undefined && node.state === \"success\") {\n const outputStr = typeof node.output === \"string\"\n ? escapeMermaidText(node.output)\n : escapeMermaidText(JSON.stringify(node.output).slice(0, 20));\n ioInfo += `\\\\nout: ${outputStr}`;\n }\n\n // Add onAfterStep hook info if present\n let hookInfo = \"\";\n if (hooks && node.key && hooks.onAfterStep.has(node.key)) {\n const hookExec = hooks.onAfterStep.get(node.key)!;\n const hookIcon = hookExec.state === \"success\" ? \"⚙\" : \"⚠\";\n const hookTiming = options.showTimings && hookExec.durationMs !== undefined\n ? ` ${formatDuration(hookExec.durationMs)}`\n : \"\";\n hookInfo = `\\\\n${hookIcon} hook${hookTiming}`;\n }\n\n // Combine all label parts with icon (retry/timeout info moved to edges)\n const escapedLabel = (stateIcon + label + ioInfo + hookInfo + timing).trim();\n\n // Determine class: use heatmap if enabled and data available, otherwise use state\n let nodeClass: string;\n const nodeId = node.name ?? node.id;\n const heat = enhanced?.showHeatmap && enhanced.heatmapData\n ? enhanced.heatmapData.heat.get(node.id) ?? enhanced.heatmapData.heat.get(nodeId)\n : undefined;\n\n if (heat !== undefined) {\n const level = getHeatLevel(heat);\n nodeClass = getHeatClass(level);\n } else {\n nodeClass = getStateClass(node.state);\n }\n\n // Use different shapes based on state (like AWS Step Functions)\n let shape: string;\n switch (node.state) {\n case \"error\":\n // Hexagon for errors (more distinctive)\n shape = `{{${escapedLabel}}}`;\n break;\n case \"cached\":\n // Rounded rectangle with double border for cached\n shape = `[(${escapedLabel})]`;\n break;\n case \"skipped\":\n // Dashed border for skipped\n shape = `[${escapedLabel}]:::skipped`;\n break;\n default:\n // Standard rectangle for normal steps\n shape = `[${escapedLabel}]`;\n }\n\n lines.push(` ${id}${shape}:::${nodeClass}`);\n\n // NEW: Add retry loop edge (self-loop showing retries)\n if (showRetryEdges && node.retryCount !== undefined && node.retryCount > 0) {\n const retryLabel = `↻ ${node.retryCount} retr${node.retryCount === 1 ? \"y\" : \"ies\"}`;\n lines.push(` ${id} -.->|\"${retryLabel}\"| ${id}`);\n }\n\n // NEW: Add error path edge (flow to error node)\n if (showErrorEdges && node.state === \"error\" && node.error !== undefined) {\n const errorNodeId = `ERR_${id}`;\n const errorLabel = escapeMermaidText(String(node.error)).slice(0, 30);\n lines.push(` ${errorNodeId}{{${errorLabel}}}`);\n lines.push(` ${id} -->|error| ${errorNodeId}`);\n lines.push(` style ${errorNodeId} fill:#fee2e2,stroke:#dc2626`);\n }\n\n // NEW: Add timeout edge (alternative timeout path)\n if (showTimeoutEdges && node.timedOut) {\n const timeoutNodeId = `TO_${id}`;\n const timeoutMs = node.timeoutMs !== undefined ? `${node.timeoutMs}ms` : \"\";\n lines.push(` ${timeoutNodeId}{{⏱ Timeout ${timeoutMs}}}`);\n lines.push(` ${id} -.->|timeout| ${timeoutNodeId}`);\n lines.push(` style ${timeoutNodeId} fill:#fef3c7,stroke:#f59e0b`);\n }\n\n return { entryId: id, exitId: id };\n}\n\n/**\n * Render a parallel node as a subgraph with fork/join.\n */\nfunction renderParallelNode(\n node: ParallelNode,\n options: RenderOptions,\n lines: string[],\n enhanced?: EnhancedRenderOptions,\n hooks?: WorkflowHooks\n): RenderResult {\n const subgraphId = generateNodeId(\"parallel\");\n const forkId = `${subgraphId}_fork`;\n const joinId = `${subgraphId}_join`;\n const name = escapeSubgraphName(node.name ?? \"Parallel\");\n const modeLabel = node.mode === \"allSettled\" ? \" (allSettled)\" : \"\";\n\n // If no children, render as a simple step-like node with note\n if (node.children.length === 0) {\n const id = subgraphId;\n const label = escapeMermaidText(`${name}${modeLabel}`);\n const note = \"operations not individually tracked\";\n const timing = options.showTimings && node.durationMs !== undefined\n ? ` ${formatDuration(node.durationMs)}`\n : \"\";\n \n // Use a rounded rectangle to indicate it's a parallel operation\n lines.push(` ${id}[${label}${timing}\\\\n${note}]:::${getStateClass(node.state)}`);\n return { entryId: id, exitId: id };\n }\n\n // Subgraph for parallel block with proper visual hierarchy\n lines.push(` subgraph ${subgraphId}[\"${name}${modeLabel}\"]`);\n lines.push(` direction TB`);\n\n // Fork node (diamond) - more visually distinct\n lines.push(` ${forkId}{\"⚡ Fork\"}`);\n\n // Child branches - render in parallel columns\n const childExitIds: string[] = [];\n for (const child of node.children) {\n const result = renderNode(child, options, lines, enhanced, hooks);\n lines.push(` ${forkId} --> ${result.entryId}`);\n childExitIds.push(result.exitId);\n }\n\n // Join node (diamond) - visually distinct\n lines.push(` ${joinId}{\"✓ Join\"}`);\n for (const exitId of childExitIds) {\n lines.push(` ${exitId} --> ${joinId}`);\n }\n\n lines.push(` end`);\n\n // Apply state styling to subgraph\n const stateClass = getStateClass(node.state);\n lines.push(` class ${subgraphId} ${stateClass}`);\n\n return { entryId: forkId, exitId: joinId };\n}\n\n/**\n * Render a race node as a subgraph with racing indicator.\n */\nfunction renderRaceNode(\n node: RaceNode,\n options: RenderOptions,\n lines: string[],\n enhanced?: EnhancedRenderOptions,\n hooks?: WorkflowHooks\n): RenderResult {\n const subgraphId = generateNodeId(\"race\");\n const startId = `${subgraphId}_start`;\n const endId = `${subgraphId}_end`;\n const name = escapeSubgraphName(node.name ?? \"Race\");\n\n // If no children, render as a simple step-like node with note\n if (node.children.length === 0) {\n const id = subgraphId;\n const label = escapeMermaidText(name);\n const note = \"operations not individually tracked\";\n const timing = options.showTimings && node.durationMs !== undefined\n ? ` ${formatDuration(node.durationMs)}`\n : \"\";\n \n lines.push(` ${id}[⚡ ${label}${timing}\\\\n${note}]:::${getStateClass(node.state)}`);\n return { entryId: id, exitId: id };\n }\n\n // Subgraph for race block - escape name and emoji is safe in quoted strings\n lines.push(` subgraph ${subgraphId}[\"⚡ ${name}\"]`);\n lines.push(` direction TB`);\n\n // Start node - use a more distinctive shape\n lines.push(` ${startId}((\"🏁 Start\"))`);\n\n // Child branches\n const childExitIds: Array<{ exitId: string; isWinner: boolean }> = [];\n let winnerExitId: string | undefined;\n\n for (const child of node.children) {\n const result = renderNode(child, options, lines, enhanced, hooks);\n const isWinner = isStepNode(child) && node.winnerId === child.id;\n lines.push(` ${startId} --> ${result.entryId}`);\n\n if (isWinner) {\n winnerExitId = result.exitId;\n }\n childExitIds.push({ exitId: result.exitId, isWinner });\n }\n\n // End node - more distinctive\n lines.push(` ${endId}((\"✓ First\"))`);\n \n // Connect winner with thick line, others with dashed (cancelled)\n for (const { exitId, isWinner } of childExitIds) {\n if (isWinner && winnerExitId) {\n lines.push(` ${exitId} ==>|🏆 Winner| ${endId}`);\n } else if (node.winnerId) {\n // Non-winner: show as cancelled\n lines.push(` ${exitId} -. cancelled .-> ${endId}`);\n } else {\n // No winner determined, normal connection\n lines.push(` ${exitId} --> ${endId}`);\n }\n }\n\n lines.push(` end`);\n\n const stateClass = getStateClass(node.state);\n lines.push(` class ${subgraphId} ${stateClass}`);\n\n return { entryId: startId, exitId: endId };\n}\n\n/**\n * Render a decision node as a diamond with branches.\n */\nfunction renderDecisionNode(\n node: DecisionNode,\n options: RenderOptions,\n lines: string[],\n enhanced?: EnhancedRenderOptions,\n hooks?: WorkflowHooks\n): RenderResult {\n const decisionId = node.key\n ? `decision_${node.key.replace(/[^a-zA-Z0-9]/g, \"_\")}`\n : generateNodeId(\"decision\");\n\n // Escape condition and decision value - remove characters that break Mermaid\n const condition = escapeMermaidText(node.condition ?? \"condition\");\n const decisionValue = node.decisionValue !== undefined\n ? ` = ${escapeMermaidText(String(node.decisionValue)).slice(0, 30)}`\n : \"\";\n\n // Decision diamond - ensure no invalid characters\n const decisionLabel = `${condition}${decisionValue}`.trim();\n lines.push(` ${decisionId}{${decisionLabel}}`);\n\n // Render branches\n const branchExitIds: string[] = [];\n let takenBranchExitId: string | undefined;\n\n for (const branch of node.branches) {\n const branchId = `${decisionId}_${branch.label.replace(/[^a-zA-Z0-9]/g, \"_\")}`;\n // Escape branch label - remove parentheses and other special chars\n const branchLabelText = escapeMermaidText(branch.label);\n const branchLabel = branch.taken\n ? `${branchLabelText} ✓`\n : `${branchLabelText} skipped`;\n const branchClass = branch.taken ? \":::success\" : \":::skipped\";\n\n // Branch label node\n lines.push(` ${branchId}[${branchLabel}]${branchClass}`);\n\n // Connect decision to branch\n // Mermaid edge labels must be simple text - escape special characters\n // Also remove pipe character as it's used for edge label syntax\n const edgeLabel = branch.condition \n ? `|${escapeMermaidText(branch.condition).replace(/\\|/g, \"\")}|` \n : \"\";\n lines.push(` ${decisionId} -->${edgeLabel} ${branchId}`);\n\n // Render children of this branch\n if (branch.children.length > 0) {\n let prevId = branchId;\n for (const child of branch.children) {\n const result = renderNode(child, options, lines, enhanced, hooks);\n lines.push(` ${prevId} --> ${result.entryId}`);\n prevId = result.exitId;\n }\n branchExitIds.push(prevId);\n if (branch.taken) {\n takenBranchExitId = prevId;\n }\n } else {\n branchExitIds.push(branchId);\n if (branch.taken) {\n takenBranchExitId = branchId;\n }\n }\n }\n\n // Join point (if we have a taken branch)\n if (takenBranchExitId) {\n return { entryId: decisionId, exitId: takenBranchExitId };\n }\n\n // If no branch was taken, return decision as exit\n return { entryId: decisionId, exitId: decisionId };\n}\n\nexport { mermaidRenderer as default };\n","/**\n * Flowchart ASCII Renderer\n *\n * Renders workflow IR as a proper flowchart with boxes and arrows.\n * Uses a 2D canvas approach for spatial layout with proper fork/join patterns.\n */\n\nimport type {\n FlowNode,\n ParallelNode,\n RaceNode,\n DecisionNode,\n Renderer,\n RenderOptions,\n StepNode,\n WorkflowIR,\n FlowchartRenderOptions,\n EnhancedRenderOptions,\n HeatLevel,\n} from \"../types\";\nimport { isParallelNode, isRaceNode, isStepNode, isDecisionNode } from \"../types\";\nimport { formatDuration } from \"../utils/timing\";\nimport {\n defaultColorScheme,\n stripAnsi,\n} from \"./colors\";\nimport { renderSparkline } from \"./ascii\";\nimport { getHeatLevel } from \"../performance-analyzer\";\n\n// =============================================================================\n// Box Drawing Characters\n// =============================================================================\n\nconst CHARS = {\n topLeft: \"┌\",\n topRight: \"┐\",\n bottomLeft: \"└\",\n bottomRight: \"┘\",\n horizontal: \"─\",\n vertical: \"│\",\n teeDown: \"┬\",\n teeUp: \"┴\",\n teeRight: \"├\",\n teeLeft: \"┤\",\n cross: \"┼\",\n arrowDown: \"▼\",\n arrowUp: \"▲\",\n} as const;\n\n// =============================================================================\n// Heatmap Colors\n// =============================================================================\n\nconst HEAT_COLORS: Record<HeatLevel, string> = {\n cold: \"\\x1b[34m\",\n cool: \"\\x1b[36m\",\n neutral: \"\",\n warm: \"\\x1b[33m\",\n hot: \"\\x1b[31m\",\n critical: \"\\x1b[41m\",\n};\n\nconst RESET = \"\\x1b[0m\";\n\n// =============================================================================\n// Canvas Module\n// =============================================================================\n\ninterface Canvas {\n cells: string[][];\n colors: (string | undefined)[][];\n width: number;\n height: number;\n}\n\nfunction createCanvas(width: number, height: number): Canvas {\n const cells: string[][] = [];\n const colors: (string | undefined)[][] = [];\n for (let y = 0; y < height; y++) {\n cells.push(Array(width).fill(\" \"));\n colors.push(Array(width).fill(undefined));\n }\n return { cells, colors, width, height };\n}\n\nfunction setChar(canvas: Canvas, x: number, y: number, char: string, color?: string): void {\n if (x >= 0 && x < canvas.width && y >= 0 && y < canvas.height) {\n canvas.cells[y][x] = char;\n if (color) canvas.colors[y][x] = color;\n }\n}\n\nfunction getChar(canvas: Canvas, x: number, y: number): string {\n if (x >= 0 && x < canvas.width && y >= 0 && y < canvas.height) {\n return canvas.cells[y][x];\n }\n return \" \";\n}\n\nfunction drawBox(canvas: Canvas, x: number, y: number, width: number, height: number): void {\n setChar(canvas, x, y, CHARS.topLeft);\n for (let i = 1; i < width - 1; i++) setChar(canvas, x + i, y, CHARS.horizontal);\n setChar(canvas, x + width - 1, y, CHARS.topRight);\n\n for (let j = 1; j < height - 1; j++) {\n setChar(canvas, x, y + j, CHARS.vertical);\n setChar(canvas, x + width - 1, y + j, CHARS.vertical);\n }\n\n setChar(canvas, x, y + height - 1, CHARS.bottomLeft);\n for (let i = 1; i < width - 1; i++) setChar(canvas, x + i, y + height - 1, CHARS.horizontal);\n setChar(canvas, x + width - 1, y + height - 1, CHARS.bottomRight);\n}\n\nfunction drawText(canvas: Canvas, x: number, y: number, text: string, color?: string): void {\n const chars = stripAnsi(text).split(\"\");\n for (let i = 0; i < chars.length; i++) {\n setChar(canvas, x + i, y, chars[i], color);\n }\n}\n\nfunction drawVerticalLine(canvas: Canvas, x: number, startY: number, endY: number): void {\n const minY = Math.min(startY, endY);\n const maxY = Math.max(startY, endY);\n for (let y = minY; y <= maxY; y++) {\n const existing = getChar(canvas, x, y);\n if (existing === CHARS.horizontal) {\n setChar(canvas, x, y, CHARS.cross);\n } else if (existing === \" \" || existing === CHARS.vertical) {\n setChar(canvas, x, y, CHARS.vertical);\n }\n }\n}\n\nfunction drawHorizontalLine(canvas: Canvas, y: number, startX: number, endX: number): void {\n const minX = Math.min(startX, endX);\n const maxX = Math.max(startX, endX);\n for (let x = minX; x <= maxX; x++) {\n const existing = getChar(canvas, x, y);\n if (existing === CHARS.vertical) {\n setChar(canvas, x, y, CHARS.cross);\n } else if (existing === \" \" || existing === CHARS.horizontal) {\n setChar(canvas, x, y, CHARS.horizontal);\n }\n }\n}\n\nfunction drawArrow(canvas: Canvas, x: number, y: number): void {\n setChar(canvas, x, y, CHARS.arrowDown);\n}\n\nfunction canvasToString(canvas: Canvas): string {\n const lines: string[] = [];\n for (let y = 0; y < canvas.height; y++) {\n let line = \"\";\n for (let x = 0; x < canvas.width; x++) {\n const color = canvas.colors[y][x];\n const char = canvas.cells[y][x];\n if (color) {\n line += color + char + RESET;\n } else {\n line += char;\n }\n }\n lines.push(line.trimEnd());\n }\n while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n return lines.join(\"\\n\");\n}\n\n// =============================================================================\n// Layout Types\n// =============================================================================\n\ninterface LayoutNode {\n id: string;\n type: \"step\" | \"parallel\" | \"race\" | \"decision\" | \"start\" | \"end\";\n label: string[];\n state: string;\n x: number;\n y: number;\n width: number;\n height: number;\n centerX: number; // Center X for connections\n bottomY: number; // Bottom Y for outgoing connections\n children?: LayoutNode[];\n metadata?: {\n isWinner?: boolean;\n heat?: number;\n verticalLayout?: boolean;\n };\n}\n\n// =============================================================================\n// Text Wrapping & Measurement\n// =============================================================================\n\nconst MIN_BOX_WIDTH = 11;\nconst BOX_PADDING = 2;\nconst VERTICAL_GAP = 2;\nconst HORIZONTAL_GAP = 3;\n\nfunction wrapText(text: string, maxWidth: number): string[] {\n if (text.length <= maxWidth) return [text];\n const words = text.split(\" \");\n const lines: string[] = [];\n let current = \"\";\n for (const word of words) {\n if (!current) {\n current = word;\n } else if (current.length + 1 + word.length <= maxWidth) {\n current += \" \" + word;\n } else {\n lines.push(current);\n current = word;\n }\n }\n if (current) lines.push(current);\n if (lines.length === 0) {\n for (let i = 0; i < text.length; i += maxWidth) {\n lines.push(text.slice(i, i + maxWidth));\n }\n }\n return lines;\n}\n\nfunction getSymbol(state: string): string {\n switch (state) {\n case \"success\": return \"✓\";\n case \"error\": return \"✗\";\n case \"running\": return \"⟳\";\n case \"pending\": return \"○\";\n case \"aborted\":\n case \"skipped\": return \"⊘\";\n case \"cached\": return \"↺\";\n default: return \"○\";\n }\n}\n\n// =============================================================================\n// Layout Algorithm\n// =============================================================================\n\nfunction layoutWorkflow(\n ir: WorkflowIR,\n options: RenderOptions,\n canvasWidth: number\n): { nodes: LayoutNode[]; totalHeight: number } {\n const showStartEnd = (options as FlowchartRenderOptions).showStartEnd ?? true;\n const enhanced = options as EnhancedRenderOptions;\n const centerX = Math.floor(canvasWidth / 2);\n const nodes: LayoutNode[] = [];\n let currentY = 0;\n\n // Start node\n if (showStartEnd) {\n const startNode = createSimpleNode(\"start\", \"start\", [\"▶ Start\"], \"success\", centerX, currentY);\n nodes.push(startNode);\n currentY = startNode.bottomY + VERTICAL_GAP;\n }\n\n // Layout workflow children sequentially\n for (const child of ir.root.children) {\n const layoutResult = layoutFlowNode(child, centerX, currentY, canvasWidth - 4, options, enhanced);\n nodes.push(layoutResult.node);\n currentY = layoutResult.bottomY + VERTICAL_GAP;\n }\n\n // End node\n if (showStartEnd && (ir.root.state === \"success\" || ir.root.state === \"error\")) {\n const endLabel = ir.root.state === \"success\" ? \"✓ Done\" : \"✗ Failed\";\n const endNode = createSimpleNode(\"end\", \"end\", [endLabel], ir.root.state, centerX, currentY);\n nodes.push(endNode);\n currentY = endNode.bottomY;\n }\n\n return { nodes, totalHeight: currentY + 2 };\n}\n\nfunction createSimpleNode(\n id: string,\n type: LayoutNode[\"type\"],\n label: string[],\n state: string,\n centerX: number,\n y: number\n): LayoutNode {\n const maxLabelLen = Math.max(...label.map(l => stripAnsi(l).length));\n const width = Math.max(MIN_BOX_WIDTH, maxLabelLen + BOX_PADDING * 2);\n const height = label.length + 2;\n const x = centerX - Math.floor(width / 2);\n return {\n id,\n type,\n label,\n state,\n x,\n y,\n width,\n height,\n centerX,\n bottomY: y + height - 1,\n };\n}\n\ninterface LayoutFlowResult {\n node: LayoutNode;\n bottomY: number;\n}\n\nfunction layoutFlowNode(\n node: FlowNode,\n centerX: number,\n startY: number,\n maxWidth: number,\n options: RenderOptions,\n enhanced?: EnhancedRenderOptions\n): LayoutFlowResult {\n if (isStepNode(node)) {\n return layoutStepNode(node, centerX, startY, maxWidth, options, enhanced);\n }\n if (isParallelNode(node) || isRaceNode(node)) {\n return layoutBranchingNode(node, centerX, startY, maxWidth, options, enhanced);\n }\n if (isDecisionNode(node)) {\n return layoutDecisionNode(node, centerX, startY, maxWidth, options, enhanced);\n }\n // Fallback\n const fallback = createSimpleNode(node.id, \"step\", [\"?\"], node.state, centerX, startY);\n return { node: fallback, bottomY: fallback.bottomY };\n}\n\nfunction layoutStepNode(\n node: StepNode,\n centerX: number,\n startY: number,\n maxWidth: number,\n options: RenderOptions,\n enhanced?: EnhancedRenderOptions\n): LayoutFlowResult {\n const name = node.name ?? node.key ?? \"step\";\n const symbol = getSymbol(node.state);\n const lines: string[] = [];\n\n // Main label\n const mainLabel = `${symbol} ${name}`;\n const innerWidth = Math.min(maxWidth - BOX_PADDING * 2, 40);\n lines.push(...wrapText(mainLabel, innerWidth));\n\n // Timing\n if (options.showTimings && node.durationMs !== undefined) {\n lines.push(`[${formatDuration(node.durationMs)}]`);\n }\n\n // Retry/timeout\n if (node.retryCount && node.retryCount > 0) {\n lines.push(`${node.retryCount}x retry`);\n }\n if (node.timedOut) {\n lines.push(\"timeout\");\n }\n\n // Sparkline\n if (enhanced?.showSparklines && enhanced.timingHistory) {\n const nodeId = node.name ?? node.id;\n const history = enhanced.timingHistory.get(nodeId);\n if (history && history.length > 1) {\n lines.push(renderSparkline(history, 8));\n }\n }\n\n const labelWidth = Math.max(...lines.map(l => stripAnsi(l).length));\n const width = Math.max(MIN_BOX_WIDTH, labelWidth + BOX_PADDING * 2);\n const height = lines.length + 2;\n const x = centerX - Math.floor(width / 2);\n\n // Heat\n let heat: number | undefined;\n if (enhanced?.showHeatmap && enhanced.heatmapData) {\n const nodeId = node.name ?? node.id;\n heat = enhanced.heatmapData.heat.get(node.id) ?? enhanced.heatmapData.heat.get(nodeId);\n }\n\n const layoutNode: LayoutNode = {\n id: node.id,\n type: \"step\",\n label: lines,\n state: node.state,\n x,\n y: startY,\n width,\n height,\n centerX,\n bottomY: startY + height - 1,\n metadata: heat !== undefined ? { heat } : undefined,\n };\n\n return { node: layoutNode, bottomY: layoutNode.bottomY };\n}\n\nfunction layoutBranchingNode(\n node: ParallelNode | RaceNode,\n centerX: number,\n startY: number,\n maxWidth: number,\n options: RenderOptions,\n enhanced?: EnhancedRenderOptions\n): LayoutFlowResult {\n const isRace = isRaceNode(node);\n const name = node.name ?? (isRace ? \"race\" : \"parallel\");\n const symbol = isRace ? \"⚡\" : \"⫘\";\n const headerLabel = `${symbol} ${name}`;\n\n // No children - simple box\n if (node.children.length === 0) {\n const lines = [headerLabel, \"(not tracked)\"];\n const result = createSimpleNode(node.id, isRace ? \"race\" : \"parallel\", lines, node.state, centerX, startY);\n return { node: result, bottomY: result.bottomY };\n }\n\n // Calculate child widths first\n const childMaxWidth = Math.floor((maxWidth - HORIZONTAL_GAP * (node.children.length - 1)) / node.children.length);\n const childWidths: number[] = [];\n\n for (const child of node.children) {\n const measured = measureFlowNode(child, Math.max(childMaxWidth, MIN_BOX_WIDTH), options, enhanced);\n childWidths.push(measured.width);\n }\n\n const totalChildWidth = childWidths.reduce((a, b) => a + b, 0) + HORIZONTAL_GAP * (node.children.length - 1);\n\n // Check if horizontal layout would overflow - fall back to vertical\n const useVerticalLayout = totalChildWidth > maxWidth && node.children.length > 1;\n\n // Header\n const headerWidth = Math.max(MIN_BOX_WIDTH, headerLabel.length + BOX_PADDING * 2);\n const headerHeight = 3;\n const headerX = centerX - Math.floor(headerWidth / 2);\n\n let currentY = startY;\n\n // Header node (we won't add it as separate node, integrate into parent)\n currentY += headerHeight;\n currentY += 1; // Fork line row\n currentY += 1; // Arrow row\n\n // Position children\n const children: LayoutNode[] = [];\n\n if (useVerticalLayout) {\n // Vertical layout - stack children sequentially\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const result = layoutFlowNode(child, centerX, currentY, maxWidth, options, enhanced);\n\n // Mark winner\n if (isRace && isRaceNode(node) && node.winnerId === child.id) {\n result.node.metadata = { ...result.node.metadata, isWinner: true };\n }\n\n children.push(result.node);\n currentY = result.bottomY + VERTICAL_GAP;\n }\n } else {\n // Horizontal layout - spread children side by side\n let childX = centerX - Math.floor(totalChildWidth / 2);\n\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const childCenterX = childX + Math.floor(childWidths[i] / 2);\n const result = layoutFlowNode(child, childCenterX, currentY, childWidths[i], options, enhanced);\n\n // Mark winner\n if (isRace && isRaceNode(node) && node.winnerId === child.id) {\n result.node.metadata = { ...result.node.metadata, isWinner: true };\n }\n\n children.push(result.node);\n childX += childWidths[i] + HORIZONTAL_GAP;\n }\n }\n\n // Calculate bottom after all children\n const childrenBottomY = Math.max(...children.map(c => c.bottomY));\n\n // For single child or vertical layout, no join line needed\n // For multiple children in horizontal layout, we have: child bottom -> join line -> vertical segment\n const needsJoinLine = !useVerticalLayout && children.length > 1;\n const totalBottomY = needsJoinLine\n ? childrenBottomY + 2 // Horizontal multi-child: join line + one row below\n : childrenBottomY; // Single child or vertical: no join line\n\n // Create parent node with children\n const parentNode: LayoutNode = {\n id: node.id,\n type: isRace ? \"race\" : \"parallel\",\n label: [headerLabel],\n state: node.state,\n x: headerX,\n y: startY,\n width: headerWidth,\n height: headerHeight,\n centerX,\n bottomY: totalBottomY,\n children,\n metadata: { verticalLayout: useVerticalLayout },\n };\n\n return { node: parentNode, bottomY: totalBottomY };\n}\n\nfunction layoutDecisionNode(\n node: DecisionNode,\n centerX: number,\n startY: number,\n maxWidth: number,\n options: RenderOptions,\n enhanced?: EnhancedRenderOptions\n): LayoutFlowResult {\n const name = node.name ?? \"decision\";\n const condition = node.condition ? ` (${node.condition.slice(0, 20)})` : \"\";\n const headerLabel = `◇ ${name}${condition}`;\n\n // Wrap header label properly\n const innerWidth = Math.min(maxWidth - BOX_PADDING * 2, 40);\n const labelLines = wrapText(headerLabel, innerWidth);\n const labelWidth = Math.max(...labelLines.map(l => stripAnsi(l).length));\n const headerWidth = Math.max(MIN_BOX_WIDTH, labelWidth + BOX_PADDING * 2);\n const headerHeight = labelLines.length + 2; // Dynamic height based on wrapped lines\n const headerX = centerX - Math.floor(headerWidth / 2);\n\n // Find taken branch\n const takenBranch = node.branches.find(b => b.taken);\n\n if (!takenBranch || takenBranch.children.length === 0) {\n // No children - just show header\n const result: LayoutNode = {\n id: node.id,\n type: \"decision\",\n label: labelLines,\n state: node.state,\n x: headerX,\n y: startY,\n width: headerWidth,\n height: headerHeight,\n centerX,\n bottomY: startY + headerHeight - 1,\n };\n return { node: result, bottomY: result.bottomY };\n }\n\n // Layout children of taken branch\n let currentY = startY + headerHeight + VERTICAL_GAP;\n const children: LayoutNode[] = [];\n\n for (const child of takenBranch.children) {\n const result = layoutFlowNode(child, centerX, currentY, maxWidth, options, enhanced);\n children.push(result.node);\n currentY = result.bottomY + VERTICAL_GAP;\n }\n\n const bottomY = children.length > 0 ? children[children.length - 1].bottomY : startY + headerHeight - 1;\n\n const parentNode: LayoutNode = {\n id: node.id,\n type: \"decision\",\n label: labelLines,\n state: node.state,\n x: headerX,\n y: startY,\n width: headerWidth,\n height: headerHeight,\n centerX,\n bottomY,\n children,\n };\n\n return { node: parentNode, bottomY };\n}\n\nfunction measureFlowNode(\n node: FlowNode,\n maxWidth: number,\n options: RenderOptions,\n enhanced?: EnhancedRenderOptions\n): { width: number; height: number } {\n if (isStepNode(node)) {\n const name = node.name ?? node.key ?? \"step\";\n const symbol = getSymbol(node.state);\n let lineCount = 1;\n if (options.showTimings && node.durationMs !== undefined) lineCount++;\n if (node.retryCount && node.retryCount > 0) lineCount++;\n if (node.timedOut) lineCount++;\n if (enhanced?.showSparklines && enhanced.timingHistory?.has(node.name ?? node.id)) lineCount++;\n\n const width = Math.min(maxWidth, Math.max(MIN_BOX_WIDTH, (`${symbol} ${name}`).length + BOX_PADDING * 2));\n const height = lineCount + 2;\n return { width, height };\n }\n\n if (isParallelNode(node) || isRaceNode(node)) {\n if (node.children.length === 0) {\n return { width: MIN_BOX_WIDTH + 4, height: 4 };\n }\n const childMaxWidth = Math.floor(maxWidth / node.children.length);\n let totalWidth = 0;\n let maxHeight = 0;\n for (const child of node.children) {\n const m = measureFlowNode(child, childMaxWidth, options, enhanced);\n totalWidth += m.width;\n maxHeight = Math.max(maxHeight, m.height);\n }\n totalWidth += HORIZONTAL_GAP * (node.children.length - 1);\n return { width: Math.max(totalWidth, MIN_BOX_WIDTH), height: 3 + 2 + maxHeight + 2 };\n }\n\n if (isDecisionNode(node)) {\n const takenBranch = node.branches.find(b => b.taken);\n let childHeight = 0;\n if (takenBranch) {\n for (const child of takenBranch.children) {\n const m = measureFlowNode(child, maxWidth, options, enhanced);\n childHeight += m.height + VERTICAL_GAP;\n }\n }\n return { width: Math.min(maxWidth, 30), height: 3 + childHeight };\n }\n\n return { width: MIN_BOX_WIDTH, height: 3 };\n}\n\n// =============================================================================\n// Rendering - Hierarchical with proper connections\n// =============================================================================\n\nfunction renderNodes(\n canvas: Canvas,\n nodes: LayoutNode[],\n options: RenderOptions\n): void {\n const colors = { ...defaultColorScheme, ...options.colors };\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n const isLast = i === nodes.length - 1;\n\n // Render this node and its children\n renderNode(canvas, node, colors);\n\n // Draw connection to next sibling node\n if (!isLast) {\n const nextNode = nodes[i + 1];\n const fromX = node.centerX;\n const fromY = node.bottomY + 1;\n const toX = nextNode.centerX;\n const toY = nextNode.y - 1;\n\n // Vertical line\n drawVerticalLine(canvas, fromX, fromY, toY - 1);\n // Arrow\n drawArrow(canvas, toX, toY);\n }\n }\n}\n\nfunction renderNode(\n canvas: Canvas,\n node: LayoutNode,\n colors: Record<string, string>\n): void {\n // Draw the box\n const hasTopConnector = node.type !== \"start\";\n const hasBottomConnector = node.type !== \"end\" && (!node.children || node.children.length === 0);\n\n drawBox(canvas, node.x, node.y, node.width, node.height);\n\n // Add connector points\n if (hasTopConnector) {\n setChar(canvas, node.centerX, node.y, CHARS.teeUp);\n }\n if (hasBottomConnector || (node.children && node.children.length > 0)) {\n setChar(canvas, node.centerX, node.y + node.height - 1, CHARS.teeDown);\n }\n\n // Draw label\n const innerWidth = node.width - BOX_PADDING * 2;\n const color = getNodeColor(node, colors);\n\n for (let j = 0; j < node.label.length; j++) {\n const line = node.label[j];\n const lineX = node.x + 1 + Math.floor((innerWidth - stripAnsi(line).length) / 2);\n const lineY = node.y + 1 + j;\n drawText(canvas, lineX, lineY, line, color);\n }\n\n // Winner indicator\n if (node.metadata?.isWinner) {\n drawText(canvas, node.x + node.width - 2, node.y, \"🏆\");\n }\n\n // Render children with proper fork/join connections\n if (node.children && node.children.length > 0) {\n if (node.type === \"parallel\" || node.type === \"race\") {\n renderBranchingChildren(canvas, node, colors);\n } else {\n // Sequential children (e.g., decision taken branch)\n renderSequentialChildren(canvas, node, colors);\n }\n }\n}\n\nfunction renderBranchingChildren(\n canvas: Canvas,\n parent: LayoutNode,\n colors: Record<string, string>\n): void {\n const children = parent.children!;\n if (children.length === 0) return;\n\n const forkY = parent.y + parent.height;\n const forkX = parent.centerX;\n\n // Check if using vertical layout (fallback for overflow)\n const useVerticalLayout = parent.metadata?.verticalLayout === true;\n\n if (useVerticalLayout) {\n // Vertical layout - render as sequential children\n // Draw connection from parent header to first child\n const firstChild = children[0];\n drawVerticalLine(canvas, forkX, forkY, firstChild.y - 2);\n drawArrow(canvas, firstChild.centerX, firstChild.y - 1);\n\n // Render children and connections between them\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n renderNode(canvas, child, colors);\n\n if (i < children.length - 1) {\n const nextChild = children[i + 1];\n drawVerticalLine(canvas, child.centerX, child.bottomY + 1, nextChild.y - 2);\n drawArrow(canvas, nextChild.centerX, nextChild.y - 1);\n }\n }\n return;\n }\n\n // Horizontal layout - draw fork/join pattern\n if (children.length === 1) {\n // Single child - just vertical line\n drawVerticalLine(canvas, forkX, forkY, children[0].y - 2);\n drawArrow(canvas, children[0].centerX, children[0].y - 1);\n } else {\n // Multiple children - fork pattern\n const childCenters = children.map(c => c.centerX);\n const minX = Math.min(...childCenters);\n const maxX = Math.max(...childCenters);\n\n // Vertical line down from parent\n drawVerticalLine(canvas, forkX, forkY, forkY + 1);\n\n // Horizontal fork line\n drawHorizontalLine(canvas, forkY + 1, minX, maxX);\n\n // Set proper junction at center\n setChar(canvas, forkX, forkY + 1, CHARS.teeUp);\n\n // Vertical lines down to each child and arrows\n for (const child of children) {\n const cx = child.centerX;\n if (cx === minX) {\n setChar(canvas, cx, forkY + 1, CHARS.topLeft);\n } else if (cx === maxX) {\n setChar(canvas, cx, forkY + 1, CHARS.topRight);\n } else if (cx !== forkX) {\n setChar(canvas, cx, forkY + 1, CHARS.teeDown);\n }\n drawVerticalLine(canvas, cx, forkY + 2, child.y - 2);\n drawArrow(canvas, cx, child.y - 1);\n }\n }\n\n // Render each child\n for (const child of children) {\n renderNode(canvas, child, colors);\n }\n\n // Draw join - gather all children back together (only for horizontal multi-child)\n if (children.length > 1) {\n const childBottoms = children.map(c => c.bottomY);\n const maxChildBottom = Math.max(...childBottoms);\n const joinY = maxChildBottom + 1;\n\n const childCenters = children.map(c => c.centerX);\n const minX = Math.min(...childCenters);\n const maxX = Math.max(...childCenters);\n\n // Vertical lines up from each child bottom to join line\n for (const child of children) {\n if (child.bottomY < maxChildBottom) {\n drawVerticalLine(canvas, child.centerX, child.bottomY + 1, joinY - 1);\n }\n }\n\n // Horizontal join line\n drawHorizontalLine(canvas, joinY, minX, maxX);\n\n // Set proper junction characters\n for (const child of children) {\n const cx = child.centerX;\n if (cx === minX) {\n setChar(canvas, cx, joinY, CHARS.bottomLeft);\n } else if (cx === maxX) {\n setChar(canvas, cx, joinY, CHARS.bottomRight);\n } else {\n setChar(canvas, cx, joinY, CHARS.teeUp);\n }\n }\n\n // Tee down at join center and vertical segment below\n setChar(canvas, parent.centerX, joinY, CHARS.teeDown);\n // Draw vertical line from join to parent's bottomY for next sibling connection\n setChar(canvas, parent.centerX, joinY + 1, CHARS.vertical);\n }\n}\n\nfunction renderSequentialChildren(\n canvas: Canvas,\n parent: LayoutNode,\n colors: Record<string, string>\n): void {\n const children = parent.children!;\n if (children.length === 0) return;\n\n // Draw connection from parent to first child\n const fromY = parent.y + parent.height;\n const firstChild = children[0];\n drawVerticalLine(canvas, parent.centerX, fromY, firstChild.y - 2);\n drawArrow(canvas, firstChild.centerX, firstChild.y - 1);\n\n // Render children and connections between them\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n renderNode(canvas, child, colors);\n\n if (i < children.length - 1) {\n const nextChild = children[i + 1];\n drawVerticalLine(canvas, child.centerX, child.bottomY + 1, nextChild.y - 2);\n drawArrow(canvas, nextChild.centerX, nextChild.y - 1);\n }\n }\n}\n\nfunction getNodeColor(node: LayoutNode, colors: Record<string, string>): string | undefined {\n if (node.metadata?.heat !== undefined) {\n const level = getHeatLevel(node.metadata.heat);\n return HEAT_COLORS[level] || undefined;\n }\n return colors[node.state] || undefined;\n}\n\n// =============================================================================\n// Main Renderer\n// =============================================================================\n\nexport function flowchartRenderer(): Renderer {\n return {\n name: \"flowchart\",\n supportsLive: false,\n\n render(ir: WorkflowIR, options: RenderOptions): string {\n const width = options.terminalWidth ?? 80;\n const { nodes, totalHeight } = layoutWorkflow(ir, options, width);\n const canvas = createCanvas(width, totalHeight);\n renderNodes(canvas, nodes, options);\n return canvasToString(canvas);\n },\n };\n}\n","/**\n * Logger Renderer - Outputs structured JSON optimized for logging systems.\n *\n * Works with any structured logger (Pino, Winston, Bunyan, console).\n * Includes workflow summary, step details, and optional ASCII diagram.\n *\n * @example\n * ```typescript\n * const logData = JSON.parse(viz.renderAs('logger'));\n * logger.info(logData, 'Workflow completed');\n * ```\n */\n\nimport type {\n Renderer,\n RenderOptions,\n WorkflowIR,\n FlowNode,\n StepNode,\n WorkflowHooks,\n} from \"../types\";\nimport { isStepNode, isSequenceNode, isParallelNode, isRaceNode, isDecisionNode } from \"../types\";\nimport { asciiRenderer } from \"./ascii\";\nimport { flowchartRenderer } from \"./flowchart\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Step log entry with execution details.\n */\nexport interface StepLog {\n id: string;\n name: string;\n key?: string;\n state: string;\n durationMs?: number;\n startTs?: number;\n endTs?: number;\n retryCount?: number;\n timedOut?: boolean;\n timeoutMs?: number;\n error?: string;\n}\n\n/**\n * Hook execution log entry.\n */\nexport interface HookLog {\n shouldRun?: {\n result?: boolean;\n durationMs?: number;\n error?: string;\n };\n onBeforeStart?: {\n durationMs?: number;\n error?: string;\n };\n onAfterStep?: Array<{\n stepKey: string;\n durationMs?: number;\n error?: string;\n }>;\n}\n\n/**\n * Summary statistics for the workflow.\n */\nexport interface WorkflowSummary {\n totalSteps: number;\n successCount: number;\n errorCount: number;\n cacheHits: number;\n skippedCount: number;\n totalRetries: number;\n slowestStep?: { name: string; durationMs: number };\n}\n\n/**\n * Complete logger output structure.\n */\nexport interface LoggerOutput {\n workflow: {\n id: string;\n name?: string;\n state: string;\n durationMs?: number;\n startedAt?: number;\n completedAt?: number;\n };\n steps: StepLog[];\n summary: WorkflowSummary;\n hooks?: HookLog;\n diagram?: string;\n}\n\n/**\n * Extended render options for logger renderer.\n */\nexport interface LoggerRenderOptions extends RenderOptions {\n /** Include ASCII diagram in output (default: true) */\n includeDiagram?: boolean;\n /** Strip ANSI color codes from diagram (default: true) */\n stripAnsiColors?: boolean;\n /** Diagram format: 'ascii' (tree-style) or 'flowchart' (boxes/arrows) (default: 'ascii') */\n diagramFormat?: \"ascii\" | \"flowchart\";\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Strip ANSI escape codes from a string.\n */\nfunction stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\n\n/**\n * Collect all step nodes from the IR tree.\n */\nfunction collectSteps(nodes: FlowNode[]): StepNode[] {\n const steps: StepNode[] = [];\n\n function walk(nodeList: FlowNode[]): void {\n for (const node of nodeList) {\n if (isStepNode(node)) {\n steps.push(node);\n } else if (isSequenceNode(node)) {\n walk(node.children);\n } else if (isParallelNode(node) || isRaceNode(node)) {\n walk(node.children);\n } else if (isDecisionNode(node)) {\n for (const branch of node.branches) {\n walk(branch.children);\n }\n }\n }\n }\n\n walk(nodes);\n return steps;\n}\n\n/**\n * Convert a step node to a log entry.\n */\nfunction stepToLog(step: StepNode): StepLog {\n const log: StepLog = {\n id: step.id,\n name: step.name ?? step.key ?? step.id,\n state: step.state,\n };\n\n if (step.key) log.key = step.key;\n if (step.durationMs !== undefined) log.durationMs = step.durationMs;\n if (step.startTs !== undefined) log.startTs = step.startTs;\n if (step.endTs !== undefined) log.endTs = step.endTs;\n if (step.retryCount !== undefined && step.retryCount > 0) log.retryCount = step.retryCount;\n if (step.timedOut) {\n log.timedOut = true;\n if (step.timeoutMs !== undefined) log.timeoutMs = step.timeoutMs;\n }\n if (step.error !== undefined) {\n log.error = typeof step.error === \"string\" ? step.error : String(step.error);\n }\n\n return log;\n}\n\n/**\n * Calculate summary statistics from steps.\n */\nfunction calculateSummary(steps: StepNode[]): WorkflowSummary {\n let successCount = 0;\n let errorCount = 0;\n let cacheHits = 0;\n let skippedCount = 0;\n let totalRetries = 0;\n let slowestStep: { name: string; durationMs: number } | undefined;\n\n for (const step of steps) {\n if (step.state === \"success\") successCount++;\n if (step.state === \"error\") errorCount++;\n if (step.state === \"cached\") cacheHits++;\n if (step.state === \"skipped\") skippedCount++;\n if (step.retryCount !== undefined) totalRetries += step.retryCount;\n\n if (step.durationMs !== undefined) {\n if (!slowestStep || step.durationMs > slowestStep.durationMs) {\n slowestStep = {\n name: step.name ?? step.key ?? step.id,\n durationMs: step.durationMs,\n };\n }\n }\n }\n\n return {\n totalSteps: steps.length,\n successCount,\n errorCount,\n cacheHits,\n skippedCount,\n totalRetries,\n slowestStep,\n };\n}\n\n/**\n * Convert hooks to log format.\n */\nfunction hooksToLog(hooks: WorkflowHooks): HookLog {\n const log: HookLog = {};\n\n if (hooks.shouldRun) {\n log.shouldRun = {\n result: hooks.shouldRun.context?.result,\n durationMs: hooks.shouldRun.durationMs,\n };\n if (hooks.shouldRun.error) {\n log.shouldRun.error = String(hooks.shouldRun.error);\n }\n }\n\n if (hooks.onBeforeStart) {\n log.onBeforeStart = {\n durationMs: hooks.onBeforeStart.durationMs,\n };\n if (hooks.onBeforeStart.error) {\n log.onBeforeStart.error = String(hooks.onBeforeStart.error);\n }\n }\n\n if (hooks.onAfterStep.size > 0) {\n log.onAfterStep = [];\n for (const [stepKey, hook] of hooks.onAfterStep) {\n const entry: { stepKey: string; durationMs?: number; error?: string } = { stepKey };\n if (hook.durationMs !== undefined) entry.durationMs = hook.durationMs;\n if (hook.error) entry.error = String(hook.error);\n log.onAfterStep.push(entry);\n }\n }\n\n return log;\n}\n\n/**\n * Build the complete logger output from IR.\n */\nfunction buildLoggerOutput(ir: WorkflowIR, options: LoggerRenderOptions): LoggerOutput {\n const root = ir.root;\n const steps = collectSteps(root.children);\n const includeDiagram = options.includeDiagram ?? true;\n const stripColors = options.stripAnsiColors ?? true;\n\n const output: LoggerOutput = {\n workflow: {\n id: root.workflowId,\n name: root.name,\n state: root.state,\n durationMs: root.durationMs,\n startedAt: root.startTs,\n completedAt: root.endTs,\n },\n steps: steps.map(stepToLog),\n summary: calculateSummary(steps),\n };\n\n // Add hooks if present\n if (ir.hooks) {\n const hookLog = hooksToLog(ir.hooks);\n if (Object.keys(hookLog).length > 0) {\n output.hooks = hookLog;\n }\n }\n\n // Add diagram if requested\n if (includeDiagram) {\n const diagramFormat = options.diagramFormat ?? \"ascii\";\n const renderer = diagramFormat === \"flowchart\"\n ? flowchartRenderer()\n : asciiRenderer();\n let diagram = renderer.render(ir, options);\n if (stripColors) {\n diagram = stripAnsi(diagram);\n }\n output.diagram = diagram;\n }\n\n return output;\n}\n\n// =============================================================================\n// Renderer\n// =============================================================================\n\n/**\n * Create a logger renderer that outputs structured JSON.\n *\n * @example\n * ```typescript\n * const viz = createVisualizer({ workflowName: 'checkout' });\n * // ... run workflow ...\n *\n * const logData = JSON.parse(viz.renderAs('logger'));\n * logger.info(logData, 'Workflow completed');\n * ```\n */\nexport function loggerRenderer(): Renderer {\n return {\n name: \"logger\",\n supportsLive: false,\n render(ir: WorkflowIR, options: RenderOptions): string {\n const loggerOptions = options as LoggerRenderOptions;\n const output = buildLoggerOutput(ir, loggerOptions);\n return JSON.stringify(output);\n },\n };\n}\n","/**\n * Development Server\n *\n * Provides a local HTTP server with WebSocket support for:\n * - Serving the HTML visualizer\n * - Live streaming workflow events\n * - Time-travel control from the browser\n * - Performance data broadcasting\n *\n * The `ws` package is an optional peer dependency.\n * Install it with: npm install ws\n */\n\nimport type { Server as HTTPServer, IncomingMessage, ServerResponse } from \"node:http\";\nimport { createServer } from \"node:http\";\nimport { execFile } from \"node:child_process\";\nimport type { WorkflowEvent } from \"../core\";\nimport type { WorkflowIR, ServerMessage, WebVisualizerMessage, HeatmapData } from \"./types\";\nimport { createTimeTravelController, type TimeTravelController } from \"./time-travel\";\nimport { createPerformanceAnalyzer, type PerformanceAnalyzer } from \"./performance-analyzer\";\nimport { renderToHTML } from \"./renderers/html\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * WebSocket interface (matches `ws` package).\n */\ninterface WebSocketLike {\n send(data: string): void;\n on(event: \"message\", listener: (data: Buffer | string) => void): void;\n on(event: \"close\", listener: () => void): void;\n on(event: \"error\", listener: (error: Error) => void): void;\n readyState: number;\n OPEN: number;\n}\n\n/**\n * WebSocket server interface (matches `ws` package).\n */\ninterface WebSocketServerLike {\n clients: Set<WebSocketLike>;\n on(event: \"connection\", listener: (ws: WebSocketLike, req: IncomingMessage) => void): void;\n close(): void;\n}\n\n/**\n * Options for the dev server.\n */\nexport interface DevServerOptions {\n /** Port to listen on (default: 3377) */\n port?: number;\n /** Hostname to bind to (default: localhost) */\n host?: string;\n /** Auto-open browser when starting (default: true) */\n autoOpen?: boolean;\n /** Workflow name for the visualizer title */\n workflowName?: string;\n /** Enable time-travel debugging (default: true) */\n timeTravel?: boolean;\n /** Enable performance heatmap (default: true) */\n heatmap?: boolean;\n /** Max snapshots for time-travel (default: 1000) */\n maxSnapshots?: number;\n}\n\n/**\n * Dev server interface.\n */\nexport interface DevServer {\n /** Start the server */\n start(): Promise<{ port: number; url: string }>;\n /** Stop the server */\n stop(): Promise<void>;\n /** Handle a workflow event (forwards to time-travel and broadcasts) */\n handleEvent(event: WorkflowEvent<unknown>): void;\n /** Push an IR update to all clients */\n pushUpdate(ir: WorkflowIR): void;\n /** Push heatmap data to all clients */\n pushHeatmap(data: HeatmapData): void;\n /** Mark workflow as complete */\n complete(): void;\n /** Get the time-travel controller */\n getTimeTravel(): TimeTravelController;\n /** Get the performance analyzer */\n getAnalyzer(): PerformanceAnalyzer;\n /** Get current IR */\n getCurrentIR(): WorkflowIR;\n}\n\n// =============================================================================\n// Implementation\n// =============================================================================\n\n/**\n * Create a development server for the workflow visualizer.\n *\n * @example\n * ```typescript\n * const server = createDevServer({ port: 3377 });\n * await server.start();\n *\n * // Forward events from workflow execution\n * workflow.onEvent(event => server.handleEvent(event));\n *\n * // When done\n * server.complete();\n * await server.stop();\n * ```\n */\nexport async function createDevServer(\n options: DevServerOptions = {}\n): Promise<DevServer> {\n const {\n port = 3377,\n host = \"localhost\",\n autoOpen = true,\n workflowName = \"Workflow\",\n timeTravel = true,\n heatmap = true,\n maxSnapshots = 1000,\n } = options;\n\n // Suppress unused variable warning - workflowName reserved for future use\n void workflowName;\n\n // Create time-travel controller and performance analyzer\n const ttController = createTimeTravelController({ maxSnapshots });\n const analyzer = createPerformanceAnalyzer();\n\n // Server state\n let httpServer: HTTPServer | null = null;\n let wsServer: WebSocketServerLike | null = null;\n let actualPort = port;\n let isRunning = false;\n\n /**\n * Broadcast a message to all connected WebSocket clients.\n */\n function broadcast(message: ServerMessage): void {\n if (!wsServer) return;\n const data = JSON.stringify(message);\n for (const client of wsServer.clients) {\n if (client.readyState === client.OPEN) {\n client.send(data);\n }\n }\n }\n\n /**\n * Handle incoming WebSocket message.\n */\n function handleClientMessage(ws: WebSocketLike, raw: Buffer | string): void {\n try {\n const msg = JSON.parse(\n typeof raw === \"string\" ? raw : raw.toString()\n ) as WebVisualizerMessage;\n\n switch (msg.type) {\n case \"time_travel_seek\": {\n const payload = msg.payload as { index: number };\n const ir = ttController.seek(payload.index);\n if (ir) {\n ws.send(JSON.stringify({ type: \"ir_update\", payload: ir }));\n }\n break;\n }\n case \"time_travel_play\": {\n const payload = msg.payload as { speed?: number } | undefined;\n ttController.play(payload?.speed);\n break;\n }\n case \"time_travel_pause\":\n ttController.pause();\n break;\n case \"time_travel_step_forward\": {\n const ir = ttController.stepForward();\n if (ir) {\n ws.send(JSON.stringify({ type: \"ir_update\", payload: ir }));\n }\n break;\n }\n case \"time_travel_step_backward\": {\n const ir = ttController.stepBackward();\n if (ir) {\n ws.send(JSON.stringify({ type: \"ir_update\", payload: ir }));\n }\n break;\n }\n case \"request_snapshots\": {\n const snapshots = ttController.getSnapshots().map((s) => ({\n id: s.id,\n eventIndex: s.eventIndex,\n timestamp: s.timestamp,\n }));\n ws.send(JSON.stringify({ type: \"snapshots_list\", payload: snapshots }));\n break;\n }\n case \"toggle_heatmap\":\n case \"set_heatmap_metric\": {\n // Client handles these locally, but we can use to sync state\n break;\n }\n }\n } catch (e) {\n console.error(\"[DevServer] Failed to handle message:\", e);\n }\n }\n\n /**\n * Generate HTML for the current state.\n */\n function generatePage(): string {\n const ir = ttController.getCurrentIR();\n const wsUrl = `ws://${host}:${actualPort}`;\n\n return renderToHTML(ir, {\n interactive: true,\n timeTravel,\n heatmap,\n theme: \"auto\",\n layout: \"TB\",\n wsUrl,\n });\n }\n\n /**\n * Handle HTTP requests.\n */\n function handleRequest(req: IncomingMessage, res: ServerResponse): void {\n const url = req.url ?? \"/\";\n\n if (url === \"/\" || url === \"/index.html\") {\n res.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n res.end(generatePage());\n return;\n }\n\n if (url === \"/api/snapshots\") {\n const snapshots = ttController.getSnapshots().map((s) => ({\n id: s.id,\n eventIndex: s.eventIndex,\n timestamp: s.timestamp,\n }));\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(snapshots));\n return;\n }\n\n if (url === \"/api/performance\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(analyzer.exportData());\n return;\n }\n\n if (url === \"/api/ir\") {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(ttController.getCurrentIR()));\n return;\n }\n\n // 404\n res.writeHead(404, { \"Content-Type\": \"text/plain\" });\n res.end(\"Not Found\");\n }\n\n /**\n * Try to dynamically import `ws` package.\n */\n async function loadWebSocketServer(): Promise<WebSocketServerLike | null> {\n try {\n // Dynamic import of optional peer dependency (ws is optional)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore - ws is an optional peer dependency\n const wsModule = await import(\"ws\");\n const ws = wsModule as {\n WebSocketServer?: new (options: { noServer: boolean }) => WebSocketServerLike;\n default?: {\n WebSocketServer?: new (options: { noServer: boolean }) => WebSocketServerLike;\n };\n };\n const WebSocketServer = ws.WebSocketServer ?? ws.default?.WebSocketServer;\n if (!WebSocketServer) {\n console.warn(\"[DevServer] WebSocket server class not found in ws module\");\n return null;\n }\n return new WebSocketServer({ noServer: true });\n } catch {\n console.warn(\n \"[DevServer] ws package not installed. Live updates disabled.\\n\" +\n \"Install with: npm install ws\"\n );\n return null;\n }\n }\n\n /**\n * Open URL in browser using platform-specific command.\n * Uses execFile for safety (no shell injection possible).\n */\n function openBrowser(url: string): void {\n const platform = process.platform;\n\n // Validate URL format to ensure it's a localhost URL\n if (!url.startsWith(\"http://localhost:\") && !url.startsWith(\"http://127.0.0.1:\")) {\n console.warn(\"[DevServer] Refusing to open non-localhost URL\");\n return;\n }\n\n if (platform === \"darwin\") {\n execFile(\"open\", [url], (err) => {\n if (err) console.warn(\"[DevServer] Failed to open browser:\", err.message);\n });\n } else if (platform === \"win32\") {\n // On Windows, use cmd.exe with /c start to handle URLs properly\n execFile(\"cmd.exe\", [\"/c\", \"start\", \"\", url], (err) => {\n if (err) console.warn(\"[DevServer] Failed to open browser:\", err.message);\n });\n } else {\n // Linux and other Unix-like systems\n execFile(\"xdg-open\", [url], (err) => {\n if (err) console.warn(\"[DevServer] Failed to open browser:\", err.message);\n });\n }\n }\n\n // =============================================================================\n // Public Interface\n // =============================================================================\n\n async function start(): Promise<{ port: number; url: string }> {\n if (isRunning) {\n return { port: actualPort, url: `http://${host}:${actualPort}` };\n }\n\n // Create HTTP server\n httpServer = createServer(handleRequest);\n\n // Try to load WebSocket server\n wsServer = await loadWebSocketServer();\n\n if (wsServer) {\n // Handle WebSocket upgrade\n httpServer.on(\"upgrade\", (request, socket, head) => {\n if (!wsServer) return;\n\n // Manual WebSocket handshake\n const ws = wsServer as unknown as {\n handleUpgrade: (\n req: IncomingMessage,\n socket: unknown,\n head: Buffer,\n callback: (ws: WebSocketLike) => void\n ) => void;\n };\n\n ws.handleUpgrade(request, socket, head, (client) => {\n // Send initial state\n client.send(\n JSON.stringify({\n type: \"ir_update\",\n payload: ttController.getCurrentIR(),\n })\n );\n\n // Handle messages\n client.on(\"message\", (data) => handleClientMessage(client, data));\n client.on(\"error\", (err) => console.error(\"[DevServer] WS error:\", err));\n });\n });\n\n // Subscribe to time-travel state changes\n ttController.onStateChange((state) => {\n broadcast({ type: \"time_travel_state\", payload: state });\n });\n }\n\n // Start listening\n return new Promise((resolve, reject) => {\n if (!httpServer) {\n reject(new Error(\"HTTP server not initialized\"));\n return;\n }\n\n httpServer.on(\"error\", (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\") {\n // Try next port\n actualPort++;\n httpServer?.listen(actualPort, host);\n } else {\n reject(err);\n }\n });\n\n httpServer.on(\"listening\", () => {\n isRunning = true;\n const url = `http://${host}:${actualPort}`;\n console.log(`[DevServer] Visualizer running at ${url}`);\n\n if (autoOpen) {\n openBrowser(url);\n }\n\n resolve({ port: actualPort, url });\n });\n\n httpServer.listen(actualPort, host);\n });\n }\n\n async function stop(): Promise<void> {\n if (!isRunning) return;\n\n return new Promise((resolve) => {\n if (wsServer) {\n wsServer.close();\n wsServer = null;\n }\n\n if (httpServer) {\n httpServer.close(() => {\n httpServer = null;\n isRunning = false;\n resolve();\n });\n } else {\n resolve();\n }\n });\n }\n\n function handleEvent(event: WorkflowEvent<unknown>): void {\n // Forward to time-travel controller\n ttController.handleEvent(event);\n\n // Forward to performance analyzer\n analyzer.addEvent(event);\n\n // Broadcast IR update\n broadcast({ type: \"ir_update\", payload: ttController.getCurrentIR() });\n }\n\n function pushUpdate(ir: WorkflowIR): void {\n broadcast({ type: \"ir_update\", payload: ir });\n }\n\n function pushHeatmap(data: HeatmapData): void {\n // Convert Map to object for JSON serialization\n const heat: Record<string, number> = {};\n for (const [k, v] of data.heat) {\n heat[k] = v;\n }\n broadcast({\n type: \"performance_data\",\n payload: { ...data, heat },\n });\n }\n\n function complete(): void {\n // Finalize analyzer run\n analyzer.finalizeRun(\"current\");\n broadcast({ type: \"workflow_complete\", payload: null });\n }\n\n function getTimeTravel(): TimeTravelController {\n return ttController;\n }\n\n function getAnalyzer(): PerformanceAnalyzer {\n return analyzer;\n }\n\n function getCurrentIR(): WorkflowIR {\n return ttController.getCurrentIR();\n }\n\n return {\n start,\n stop,\n handleEvent,\n pushUpdate,\n pushHeatmap,\n complete,\n getTimeTravel,\n getAnalyzer,\n getCurrentIR,\n };\n}\n","/**\n * Workflow Visualization Module\n *\n * Provides tools for visualizing workflow execution with color-coded\n * step states and support for parallel/race operations.\n *\n * @example\n * ```typescript\n * import { createVisualizer } from 'awaitly/visualize';\n *\n * const viz = createVisualizer({ workflowName: 'checkout' });\n * const workflow = createWorkflow(deps, { onEvent: viz.handleEvent });\n *\n * await workflow(async (step) => {\n * await step(() => validateCart(cart), 'Validate cart');\n * await step(() => processPayment(payment), 'Process payment');\n * });\n *\n * console.log(viz.render());\n * ```\n */\n\nimport type { WorkflowEvent } from \"../core\";\nimport type {\n OutputFormat,\n RenderOptions,\n ScopeEndEvent,\n ScopeStartEvent,\n DecisionStartEvent,\n DecisionBranchEvent,\n DecisionEndEvent,\n VisualizerOptions,\n WorkflowIR,\n} from \"./types\";\nimport { createIRBuilder } from \"./ir-builder\";\nimport { asciiRenderer, mermaidRenderer, loggerRenderer, flowchartRenderer, defaultColorScheme } from \"./renderers\";\n\n// =============================================================================\n// Re-exports\n// =============================================================================\n\nexport * from \"./types\";\nexport { createIRBuilder, type IRBuilderOptions } from \"./ir-builder\";\nexport { asciiRenderer, mermaidRenderer, loggerRenderer, flowchartRenderer, defaultColorScheme } from \"./renderers\";\nexport type { LoggerOutput, LoggerRenderOptions, StepLog, HookLog, WorkflowSummary } from \"./renderers\";\nexport { htmlRenderer, renderToHTML } from \"./renderers/html\";\nexport { detectParallelGroups, createParallelDetector, type ParallelDetectorOptions } from \"./parallel-detector\";\nexport { createLiveVisualizer, type LiveVisualizer } from \"./live-visualizer\";\nexport { trackDecision, trackIf, trackSwitch, type DecisionTracker, type IfTracker, type SwitchTracker } from \"./decision-tracker\";\n\n// Time-travel debugging\nexport {\n createTimeTravelController,\n type TimeTravelController,\n type TimeTravelOptions,\n} from \"./time-travel\";\n\n// Performance analysis\nexport {\n createPerformanceAnalyzer,\n getHeatLevel,\n type PerformanceAnalyzer,\n type WorkflowRun,\n} from \"./performance-analyzer\";\n\n// Dev server (WebSocket-based live visualization)\n// Note: ws is an optional peer dependency\nexport {\n createDevServer,\n type DevServer,\n type DevServerOptions,\n} from \"./dev-server\";\n\n// =============================================================================\n// Visualizer Interface\n// =============================================================================\n\n/**\n * Workflow visualizer that processes events and renders output.\n */\nexport interface WorkflowVisualizer {\n /** Process a workflow event */\n handleEvent: (event: WorkflowEvent<unknown>) => void;\n\n /** Process a scope event (parallel/race) */\n handleScopeEvent: (event: ScopeStartEvent | ScopeEndEvent) => void;\n\n /** Process a decision event (conditional branches) */\n handleDecisionEvent: (event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent) => void;\n\n /** Get current IR state */\n getIR: () => WorkflowIR;\n\n /** Render current state using the default renderer */\n render: () => string;\n\n /** Render to a specific format */\n renderAs: (format: OutputFormat) => string;\n\n /** Reset state for a new workflow */\n reset: () => void;\n\n /** Subscribe to IR updates (for live visualization) */\n onUpdate: (callback: (ir: WorkflowIR) => void) => () => void;\n}\n\n// =============================================================================\n// Create Visualizer\n// =============================================================================\n\n/**\n * Create a workflow visualizer.\n *\n * @example\n * ```typescript\n * const viz = createVisualizer({ workflowName: 'my-workflow' });\n *\n * const workflow = createWorkflow(deps, {\n * onEvent: viz.handleEvent,\n * });\n *\n * await workflow(async (step) => { ... });\n *\n * console.log(viz.render());\n * ```\n */\nexport function createVisualizer(\n options: VisualizerOptions = {}\n): WorkflowVisualizer {\n const {\n workflowName,\n detectParallel = true,\n showTimings = true,\n showKeys = false,\n colors: customColors,\n } = options;\n\n const builder = createIRBuilder({ detectParallel });\n const updateCallbacks: Set<(ir: WorkflowIR) => void> = new Set();\n\n // Renderers\n const ascii = asciiRenderer();\n const mermaid = mermaidRenderer();\n const logger = loggerRenderer();\n const flowchart = flowchartRenderer();\n\n // Build render options\n const renderOptions: RenderOptions = {\n showTimings,\n showKeys,\n terminalWidth: process.stdout?.columns ?? 80,\n colors: { ...defaultColorScheme, ...customColors },\n };\n\n function notifyUpdate(): void {\n if (updateCallbacks.size > 0) {\n const ir = builder.getIR();\n for (const callback of updateCallbacks) {\n callback(ir);\n }\n }\n }\n\n function handleEvent(event: WorkflowEvent<unknown>): void {\n // Route scope events to handleScopeEvent for proper IR building\n if (event.type === \"scope_start\" || event.type === \"scope_end\") {\n handleScopeEvent(event as ScopeStartEvent | ScopeEndEvent);\n return;\n }\n\n builder.handleEvent(event);\n\n // Set workflow name if provided\n if (event.type === \"workflow_start\" && workflowName) {\n // Note: We'd need to extend the builder to support setting name\n // For now, the name is passed in render options\n }\n\n notifyUpdate();\n }\n\n function handleScopeEvent(event: ScopeStartEvent | ScopeEndEvent): void {\n builder.handleScopeEvent(event);\n notifyUpdate();\n }\n\n function handleDecisionEvent(\n event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent\n ): void {\n builder.handleDecisionEvent(event);\n notifyUpdate();\n }\n\n function getIR(): WorkflowIR {\n const ir = builder.getIR();\n // Apply workflow name if provided\n if (workflowName && !ir.root.name) {\n ir.root.name = workflowName;\n }\n return ir;\n }\n\n function render(): string {\n const ir = getIR();\n return ascii.render(ir, renderOptions);\n }\n\n function renderAs(format: OutputFormat): string {\n const ir = getIR();\n\n switch (format) {\n case \"ascii\":\n return ascii.render(ir, renderOptions);\n\n case \"mermaid\":\n return mermaid.render(ir, renderOptions);\n\n case \"json\":\n return JSON.stringify(ir, null, 2);\n\n case \"logger\":\n return logger.render(ir, renderOptions);\n\n case \"flowchart\":\n return flowchart.render(ir, renderOptions);\n\n default:\n throw new Error(`Unknown format: ${format}`);\n }\n }\n\n function reset(): void {\n builder.reset();\n notifyUpdate();\n }\n\n function onUpdate(callback: (ir: WorkflowIR) => void): () => void {\n updateCallbacks.add(callback);\n return () => updateCallbacks.delete(callback);\n }\n\n return {\n handleEvent,\n handleScopeEvent,\n handleDecisionEvent,\n getIR,\n render,\n renderAs,\n reset,\n onUpdate,\n };\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * Union type for all collectable/visualizable events (workflow + decision).\n */\nexport type CollectableEvent =\n | WorkflowEvent<unknown>\n | DecisionStartEvent\n | DecisionBranchEvent\n | DecisionEndEvent;\n\n/**\n * Visualize collected events (post-execution).\n *\n * Supports both workflow events (from onEvent) and decision events\n * (from trackDecision/trackIf/trackSwitch).\n *\n * @example\n * ```typescript\n * const events: CollectableEvent[] = [];\n * const workflow = createWorkflow(deps, {\n * onEvent: (e) => events.push(e),\n * });\n *\n * await workflow(async (step) => {\n * const decision = trackIf('check', condition, {\n * emit: (e) => events.push(e),\n * });\n * // ...\n * });\n *\n * console.log(visualizeEvents(events));\n * ```\n */\nexport function visualizeEvents(\n events: CollectableEvent[],\n options: VisualizerOptions = {}\n): string {\n const viz = createVisualizer(options);\n\n for (const event of events) {\n if (event.type.startsWith(\"decision_\")) {\n viz.handleDecisionEvent(event as DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent);\n } else {\n viz.handleEvent(event as WorkflowEvent<unknown>);\n }\n }\n\n return viz.render();\n}\n\n/**\n * Create an event collector for later visualization.\n *\n * Supports both workflow events (from onEvent) and decision events\n * (from trackDecision/trackIf/trackSwitch).\n *\n * @example\n * ```typescript\n * const collector = createEventCollector();\n *\n * const workflow = createWorkflow(deps, {\n * onEvent: collector.handleEvent,\n * });\n *\n * await workflow(async (step) => {\n * // Decision events can also be collected\n * const decision = trackIf('check', condition, {\n * emit: collector.handleDecisionEvent,\n * });\n * // ...\n * });\n *\n * console.log(collector.visualize());\n * ```\n */\nexport function createEventCollector(options: VisualizerOptions = {}) {\n const events: CollectableEvent[] = [];\n\n return {\n /** Handle a workflow event */\n handleEvent: (event: WorkflowEvent<unknown>) => {\n events.push(event);\n },\n\n /** Handle a decision event */\n handleDecisionEvent: (event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent) => {\n events.push(event);\n },\n\n /** Get all collected events */\n getEvents: () => [...events],\n\n /** Get workflow events only */\n getWorkflowEvents: () => events.filter((e): e is WorkflowEvent<unknown> =>\n !e.type.startsWith(\"decision_\")\n ),\n\n /** Get decision events only */\n getDecisionEvents: () => events.filter((e): e is DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent =>\n e.type.startsWith(\"decision_\")\n ),\n\n /** Clear collected events */\n clear: () => {\n events.length = 0;\n },\n\n /** Visualize collected events */\n visualize: () => {\n const viz = createVisualizer(options);\n for (const event of events) {\n if (event.type.startsWith(\"decision_\")) {\n viz.handleDecisionEvent(event as DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent);\n } else {\n viz.handleEvent(event as WorkflowEvent<unknown>);\n }\n }\n return viz.render();\n },\n\n /** Visualize in a specific format */\n visualizeAs: (format: OutputFormat) => {\n const viz = createVisualizer(options);\n for (const event of events) {\n if (event.type.startsWith(\"decision_\")) {\n viz.handleDecisionEvent(event as DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent);\n } else {\n viz.handleEvent(event as WorkflowEvent<unknown>);\n }\n }\n return viz.renderAs(format);\n },\n };\n}\n\n","/**\n * awaitly/devtools\n *\n * Developer tools for workflow debugging, visualization, and analysis.\n * Provides timeline rendering, run diffing, and live visualization.\n */\n\nimport type { WorkflowEvent } from \"./core\";\nimport type {\n OutputFormat,\n VisualizerOptions,\n DecisionStartEvent,\n DecisionBranchEvent,\n DecisionEndEvent,\n CollectableEvent,\n} from \"./visualize\";\nimport { createVisualizer } from \"./visualize\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * A recorded workflow run with events and metadata.\n */\nexport interface WorkflowRun {\n /** Unique identifier for this run */\n id: string;\n /** Workflow name */\n name?: string;\n /** Start timestamp */\n startTime: number;\n /** End timestamp (undefined if still running) */\n endTime?: number;\n /** Duration in milliseconds */\n durationMs?: number;\n /** Whether the workflow succeeded */\n success?: boolean;\n /** Error if the workflow failed */\n error?: unknown;\n /** All events from this run */\n events: CollectableEvent[];\n /** Custom metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Difference between two workflow runs.\n */\nexport interface RunDiff {\n /** Steps that were added in the new run */\n added: StepDiff[];\n /** Steps that were removed from the new run */\n removed: StepDiff[];\n /** Steps that changed between runs */\n changed: StepDiff[];\n /** Steps that are identical */\n unchanged: string[];\n /** Overall status change */\n statusChange?: {\n from: \"success\" | \"error\" | \"running\";\n to: \"success\" | \"error\" | \"running\";\n };\n /** Duration change in milliseconds */\n durationChange?: number;\n}\n\n/**\n * Information about a step difference.\n */\nexport interface StepDiff {\n /** Step name or key */\n step: string;\n /** Type of change */\n type: \"added\" | \"removed\" | \"status\" | \"duration\" | \"error\";\n /** Previous value (for changes) */\n from?: unknown;\n /** New value (for changes) */\n to?: unknown;\n}\n\n/**\n * Timeline entry for a step.\n */\nexport interface TimelineEntry {\n /** Step name */\n name: string;\n /** Step key (if any) */\n key?: string;\n /** Start time (relative to workflow start) */\n startMs: number;\n /** End time (relative to workflow start) */\n endMs?: number;\n /** Duration in milliseconds */\n durationMs?: number;\n /** Step status */\n status: \"pending\" | \"running\" | \"success\" | \"error\" | \"skipped\" | \"cached\";\n /** Error if failed */\n error?: unknown;\n /** Parent scope (for nested steps) */\n parent?: string;\n /** Retry attempt number */\n attempt?: number;\n}\n\n/**\n * Devtools configuration options.\n */\nexport interface DevtoolsOptions extends VisualizerOptions {\n /** Enable console logging of events */\n logEvents?: boolean;\n /** Maximum number of runs to keep in history */\n maxHistory?: number;\n /** Custom logger function */\n logger?: (message: string) => void;\n}\n\n// =============================================================================\n// Devtools Interface\n// =============================================================================\n\n/**\n * Devtools instance for workflow debugging.\n */\nexport interface Devtools {\n /** Handle a workflow event */\n handleEvent: (event: WorkflowEvent<unknown>) => void;\n\n /** Handle a decision event */\n handleDecisionEvent: (event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent) => void;\n\n /** Get the current run */\n getCurrentRun: () => WorkflowRun | undefined;\n\n /** Get run history */\n getHistory: () => WorkflowRun[];\n\n /** Get a specific run by ID */\n getRun: (id: string) => WorkflowRun | undefined;\n\n /** Compare two runs */\n diff: (runId1: string, runId2: string) => RunDiff | undefined;\n\n /** Compare current run with a previous run */\n diffWithPrevious: () => RunDiff | undefined;\n\n /** Render current state */\n render: () => string;\n\n /** Render to a specific format */\n renderAs: (format: OutputFormat) => string;\n\n /** Render as Mermaid diagram */\n renderMermaid: () => string;\n\n /** Render as ASCII timeline */\n renderTimeline: () => string;\n\n /** Get timeline data for current run */\n getTimeline: () => TimelineEntry[];\n\n /** Clear all history */\n clearHistory: () => void;\n\n /** Reset current run */\n reset: () => void;\n\n /** Export run data as JSON */\n exportRun: (runId?: string) => string;\n\n /** Import run data from JSON */\n importRun: (json: string) => WorkflowRun;\n}\n\n// =============================================================================\n// Create Devtools\n// =============================================================================\n\n/**\n * Create a devtools instance for workflow debugging.\n *\n * @example\n * ```typescript\n * const devtools = createDevtools({ workflowName: 'checkout' });\n *\n * const workflow = createWorkflow(deps, {\n * onEvent: devtools.handleEvent,\n * });\n *\n * await workflow(async (step) => { ... });\n *\n * // Visualize\n * console.log(devtools.render());\n * console.log(devtools.renderMermaid());\n *\n * // Compare with previous run\n * const diff = devtools.diffWithPrevious();\n * ```\n */\nexport function createDevtools(options: DevtoolsOptions = {}): Devtools {\n const { logEvents = false, maxHistory = 10, logger = console.log } = options;\n\n const visualizer = createVisualizer(options);\n const history: WorkflowRun[] = [];\n let currentRun: WorkflowRun | undefined;\n let workflowStartTime = 0;\n\n function startNewRun(workflowId: string): void {\n // Save current run to history if it exists\n if (currentRun) {\n history.push(currentRun);\n // Trim history if needed\n while (history.length > maxHistory) {\n history.shift();\n }\n }\n\n workflowStartTime = Date.now();\n currentRun = {\n id: workflowId,\n name: options.workflowName,\n startTime: workflowStartTime,\n events: [],\n };\n\n visualizer.reset();\n }\n\n function endCurrentRun(success: boolean, error?: unknown): void {\n if (currentRun) {\n currentRun.endTime = Date.now();\n currentRun.durationMs = currentRun.endTime - currentRun.startTime;\n currentRun.success = success;\n currentRun.error = error;\n }\n }\n\n function handleEvent(event: WorkflowEvent<unknown>): void {\n if (logEvents) {\n logger(`[devtools] ${event.type}: ${JSON.stringify(event)}`);\n }\n\n // Start new run on workflow_start\n if (event.type === \"workflow_start\") {\n startNewRun(event.workflowId);\n }\n\n // Record event\n if (currentRun) {\n currentRun.events.push(event);\n }\n\n // Forward to visualizer\n visualizer.handleEvent(event);\n\n // End run on workflow_success or workflow_error\n if (event.type === \"workflow_success\") {\n endCurrentRun(true);\n } else if (event.type === \"workflow_error\") {\n endCurrentRun(false, event.error);\n }\n }\n\n function handleDecisionEvent(\n event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent\n ): void {\n if (logEvents) {\n logger(`[devtools] ${event.type}: ${JSON.stringify(event)}`);\n }\n\n if (currentRun) {\n currentRun.events.push(event);\n }\n\n visualizer.handleDecisionEvent(event);\n }\n\n function getCurrentRun(): WorkflowRun | undefined {\n return currentRun;\n }\n\n function getHistory(): WorkflowRun[] {\n return [...history];\n }\n\n function getRun(id: string): WorkflowRun | undefined {\n if (currentRun?.id === id) return currentRun;\n return history.find((run) => run.id === id);\n }\n\n function diff(runId1: string, runId2: string): RunDiff | undefined {\n const run1 = getRun(runId1);\n const run2 = getRun(runId2);\n\n if (!run1 || !run2) return undefined;\n\n return diffRuns(run1, run2);\n }\n\n function diffWithPrevious(): RunDiff | undefined {\n if (!currentRun || history.length === 0) return undefined;\n const previousRun = history[history.length - 1];\n return diffRuns(previousRun, currentRun);\n }\n\n function render(): string {\n return visualizer.render();\n }\n\n function renderAs(format: OutputFormat): string {\n return visualizer.renderAs(format);\n }\n\n function renderMermaid(): string {\n return visualizer.renderAs(\"mermaid\");\n }\n\n function renderTimeline(): string {\n const timeline = getTimeline();\n return formatTimeline(timeline);\n }\n\n function getTimeline(): TimelineEntry[] {\n if (!currentRun) return [];\n return buildTimeline(currentRun.events, workflowStartTime);\n }\n\n function clearHistory(): void {\n history.length = 0;\n }\n\n function reset(): void {\n currentRun = undefined;\n visualizer.reset();\n }\n\n function exportRun(runId?: string): string {\n const run = runId ? getRun(runId) : currentRun;\n if (!run) return \"{}\";\n return JSON.stringify(run, null, 2);\n }\n\n function importRun(json: string): WorkflowRun {\n const run = JSON.parse(json) as WorkflowRun;\n history.push(run);\n return run;\n }\n\n return {\n handleEvent,\n handleDecisionEvent,\n getCurrentRun,\n getHistory,\n getRun,\n diff,\n diffWithPrevious,\n render,\n renderAs,\n renderMermaid,\n renderTimeline,\n getTimeline,\n clearHistory,\n reset,\n exportRun,\n importRun,\n };\n}\n\n// =============================================================================\n// Diff Helpers\n// =============================================================================\n\nfunction diffRuns(run1: WorkflowRun, run2: WorkflowRun): RunDiff {\n const steps1 = extractSteps(run1.events);\n const steps2 = extractSteps(run2.events);\n\n const added: StepDiff[] = [];\n const removed: StepDiff[] = [];\n const changed: StepDiff[] = [];\n const unchanged: string[] = [];\n\n // Find added and changed steps\n for (const [name, step2] of steps2) {\n const step1 = steps1.get(name);\n\n if (!step1) {\n added.push({ step: name, type: \"added\", to: step2.status });\n } else if (step1.status !== step2.status) {\n changed.push({\n step: name,\n type: \"status\",\n from: step1.status,\n to: step2.status,\n });\n } else if (step1.durationMs !== step2.durationMs) {\n changed.push({\n step: name,\n type: \"duration\",\n from: step1.durationMs,\n to: step2.durationMs,\n });\n } else {\n unchanged.push(name);\n }\n }\n\n // Find removed steps\n for (const [name] of steps1) {\n if (!steps2.has(name)) {\n removed.push({ step: name, type: \"removed\", from: steps1.get(name)?.status });\n }\n }\n\n // Calculate status change\n let statusChange: RunDiff[\"statusChange\"];\n const status1 = run1.success === undefined ? \"running\" : run1.success ? \"success\" : \"error\";\n const status2 = run2.success === undefined ? \"running\" : run2.success ? \"success\" : \"error\";\n\n if (status1 !== status2) {\n statusChange = { from: status1, to: status2 };\n }\n\n // Calculate duration change\n let durationChange: number | undefined;\n if (run1.durationMs !== undefined && run2.durationMs !== undefined) {\n durationChange = run2.durationMs - run1.durationMs;\n }\n\n return {\n added,\n removed,\n changed,\n unchanged,\n statusChange,\n durationChange,\n };\n}\n\ninterface StepInfo {\n name: string;\n key?: string;\n status: string;\n durationMs?: number;\n error?: unknown;\n}\n\nfunction extractSteps(events: CollectableEvent[]): Map<string, StepInfo> {\n const steps = new Map<string, StepInfo>();\n\n for (const event of events) {\n if (event.type === \"step_start\") {\n const e = event as WorkflowEvent<unknown> & { stepId: string; name?: string; stepKey?: string };\n const name = e.name || e.stepKey || e.stepId;\n steps.set(name, {\n name,\n key: e.stepKey,\n status: \"running\",\n });\n } else if (event.type === \"step_success\") {\n const e = event as WorkflowEvent<unknown> & { stepId: string; name?: string; stepKey?: string; durationMs: number };\n const name = e.name || e.stepKey || e.stepId;\n const existing = steps.get(name);\n if (existing) {\n existing.status = \"success\";\n existing.durationMs = e.durationMs;\n }\n } else if (event.type === \"step_error\") {\n const e = event as WorkflowEvent<unknown> & { stepId: string; name?: string; stepKey?: string; durationMs: number; error: unknown };\n const name = e.name || e.stepKey || e.stepId;\n const existing = steps.get(name);\n if (existing) {\n existing.status = \"error\";\n existing.durationMs = e.durationMs;\n existing.error = e.error;\n }\n } else if (event.type === \"step_cache_hit\") {\n const e = event as WorkflowEvent<unknown> & { stepKey: string; name?: string };\n const name = e.name || e.stepKey;\n steps.set(name, {\n name,\n key: e.stepKey,\n status: \"cached\",\n });\n } else if (event.type === \"step_skipped\") {\n const e = event as WorkflowEvent<unknown> & { stepKey?: string; name?: string };\n const name = e.name || e.stepKey || \"unknown\";\n steps.set(name, {\n name,\n key: e.stepKey,\n status: \"skipped\",\n });\n }\n }\n\n return steps;\n}\n\n// =============================================================================\n// Timeline Helpers\n// =============================================================================\n\nfunction buildTimeline(events: CollectableEvent[], startTime: number): TimelineEntry[] {\n const timeline: TimelineEntry[] = [];\n const stepStarts = new Map<string, number>();\n\n for (const event of events) {\n if (event.type === \"step_start\") {\n const e = event as WorkflowEvent<unknown> & { stepId: string; name?: string; stepKey?: string; ts: number };\n const name = e.name || e.stepKey || e.stepId;\n stepStarts.set(name, e.ts);\n timeline.push({\n name,\n key: e.stepKey,\n startMs: e.ts - startTime,\n status: \"running\",\n });\n } else if (event.type === \"step_success\") {\n const e = event as WorkflowEvent<unknown> & { stepId: string; name?: string; stepKey?: string; ts: number; durationMs: number };\n const name = e.name || e.stepKey || e.stepId;\n const entry = timeline.find((t) => t.name === name && t.status === \"running\");\n if (entry) {\n entry.endMs = e.ts - startTime;\n entry.durationMs = e.durationMs;\n entry.status = \"success\";\n }\n } else if (event.type === \"step_error\") {\n const e = event as WorkflowEvent<unknown> & { stepId: string; name?: string; stepKey?: string; ts: number; durationMs: number; error: unknown };\n const name = e.name || e.stepKey || e.stepId;\n const entry = timeline.find((t) => t.name === name && t.status === \"running\");\n if (entry) {\n entry.endMs = e.ts - startTime;\n entry.durationMs = e.durationMs;\n entry.status = \"error\";\n entry.error = e.error;\n }\n } else if (event.type === \"step_cache_hit\") {\n const e = event as WorkflowEvent<unknown> & { stepKey: string; name?: string; ts: number };\n const name = e.name || e.stepKey;\n timeline.push({\n name,\n key: e.stepKey,\n startMs: e.ts - startTime,\n endMs: e.ts - startTime,\n durationMs: 0,\n status: \"cached\",\n });\n } else if (event.type === \"step_skipped\") {\n const e = event as WorkflowEvent<unknown> & { stepKey?: string; name?: string; ts: number };\n const name = e.name || e.stepKey || \"unknown\";\n timeline.push({\n name,\n key: e.stepKey,\n startMs: e.ts - startTime,\n endMs: e.ts - startTime,\n durationMs: 0,\n status: \"skipped\",\n });\n }\n }\n\n return timeline;\n}\n\nfunction formatTimeline(timeline: TimelineEntry[]): string {\n if (timeline.length === 0) return \"No timeline data\";\n\n const lines: string[] = [];\n lines.push(\"Timeline:\");\n lines.push(\"─\".repeat(60));\n\n // Find max duration for scaling\n const maxEnd = Math.max(...timeline.map((t) => t.endMs ?? t.startMs + 100));\n const barWidth = 40;\n\n for (const entry of timeline) {\n const startPos = Math.floor((entry.startMs / maxEnd) * barWidth);\n const endPos = Math.floor(((entry.endMs ?? entry.startMs + 10) / maxEnd) * barWidth);\n const width = Math.max(1, endPos - startPos);\n\n const statusChar = getStatusChar(entry.status);\n const bar = \" \".repeat(startPos) + statusChar.repeat(width);\n\n const duration = entry.durationMs !== undefined ? `${entry.durationMs}ms` : \"?\";\n lines.push(`${entry.name.padEnd(20)} |${bar.padEnd(barWidth)}| ${duration}`);\n }\n\n lines.push(\"─\".repeat(60));\n return lines.join(\"\\n\");\n}\n\nfunction getStatusChar(status: TimelineEntry[\"status\"]): string {\n switch (status) {\n case \"success\":\n return \"█\";\n case \"error\":\n return \"░\";\n case \"running\":\n return \"▒\";\n case \"cached\":\n return \"▓\";\n case \"skipped\":\n return \"·\";\n default:\n return \"?\";\n }\n}\n\n// =============================================================================\n// Diff Renderer\n// =============================================================================\n\n/**\n * Render a run diff as a string.\n */\nexport function renderDiff(diff: RunDiff): string {\n const lines: string[] = [];\n\n if (diff.statusChange) {\n lines.push(`Status: ${diff.statusChange.from} → ${diff.statusChange.to}`);\n }\n\n if (diff.durationChange !== undefined) {\n const sign = diff.durationChange >= 0 ? \"+\" : \"\";\n lines.push(`Duration: ${sign}${diff.durationChange}ms`);\n }\n\n if (diff.added.length > 0) {\n lines.push(\"\\nAdded steps:\");\n for (const step of diff.added) {\n lines.push(` + ${step.step}`);\n }\n }\n\n if (diff.removed.length > 0) {\n lines.push(\"\\nRemoved steps:\");\n for (const step of diff.removed) {\n lines.push(` - ${step.step}`);\n }\n }\n\n if (diff.changed.length > 0) {\n lines.push(\"\\nChanged steps:\");\n for (const step of diff.changed) {\n lines.push(` ~ ${step.step}: ${step.from} → ${step.to}`);\n }\n }\n\n if (diff.unchanged.length > 0) {\n lines.push(`\\nUnchanged: ${diff.unchanged.length} steps`);\n }\n\n return lines.join(\"\\n\");\n}\n\n// =============================================================================\n// Quick Visualization Helpers\n// =============================================================================\n\n/**\n * Quick visualization helper for a single workflow run.\n */\nexport function quickVisualize(\n workflowFn: (handleEvent: (event: WorkflowEvent<unknown>) => void) => Promise<unknown>,\n options: DevtoolsOptions = {}\n): Promise<string> {\n const devtools = createDevtools(options);\n\n return workflowFn(devtools.handleEvent).then(() => devtools.render());\n}\n\n/**\n * Create an event handler that logs to console with pretty formatting.\n */\nexport function createConsoleLogger(options: { prefix?: string; colors?: boolean } = {}): (\n event: WorkflowEvent<unknown>\n) => void {\n const { prefix = \"[workflow]\", colors = true } = options;\n\n const colorize = colors\n ? {\n reset: \"\\x1b[0m\",\n dim: \"\\x1b[2m\",\n green: \"\\x1b[32m\",\n red: \"\\x1b[31m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n cyan: \"\\x1b[36m\",\n }\n : { reset: \"\", dim: \"\", green: \"\", red: \"\", yellow: \"\", blue: \"\", cyan: \"\" };\n\n return (event: WorkflowEvent<unknown>) => {\n const timestamp = new Date().toISOString().slice(11, 23);\n let message = \"\";\n\n switch (event.type) {\n case \"workflow_start\":\n message = `${colorize.blue}⏵ Workflow started${colorize.reset}`;\n break;\n case \"workflow_success\":\n message = `${colorize.green}✓ Workflow completed${colorize.reset} ${colorize.dim}(${event.durationMs}ms)${colorize.reset}`;\n break;\n case \"workflow_error\":\n message = `${colorize.red}✗ Workflow failed${colorize.reset}`;\n break;\n case \"step_start\":\n message = `${colorize.cyan}→ ${event.name || event.stepKey || event.stepId}${colorize.reset}`;\n break;\n case \"step_success\":\n message = `${colorize.green}✓ ${event.name || event.stepKey || event.stepId}${colorize.reset} ${colorize.dim}(${event.durationMs}ms)${colorize.reset}`;\n break;\n case \"step_error\":\n message = `${colorize.red}✗ ${event.name || event.stepKey || event.stepId}${colorize.reset}`;\n break;\n case \"step_cache_hit\":\n message = `${colorize.yellow}⚡ ${event.name || event.stepKey} (cached)${colorize.reset}`;\n break;\n case \"step_retry\":\n message = `${colorize.yellow}↻ ${event.name || event.stepKey || event.stepId} retry ${event.attempt}/${event.maxAttempts}${colorize.reset}`;\n break;\n default:\n message = `${colorize.dim}${event.type}${colorize.reset}`;\n }\n\n console.log(`${colorize.dim}${timestamp}${colorize.reset} ${prefix} ${message}`);\n };\n}\n"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,yBAAAE,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,eAAAC,KAAA,eAAAC,GAAAN,ICYO,SAASO,EAAeC,EAAoB,CACjD,GAA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AS,KAAK,4BAAuBA,EAAS,KAAK,IAAIA,EAAS,GAAG,IAAIxE,EAAM,UAAU,MAAMwE,EAAS,KAAK,GACxH,MACF,IAAK,iBACHE,EAAU,GAAGF,EAAS,GAAG,yBAAoBA,EAAS,KAAK,GAC3D,MACF,IAAK,aACHE,EAAU,GAAGF,EAAS,IAAI,UAAKxE,EAAM,MAAQA,EAAM,SAAWA,EAAM,MAAM,GAAGwE,EAAS,KAAK,GAC3F,MACF,IAAK,eACHE,EAAU,GAAGF,EAAS,KAAK,UAAKxE,EAAM,MAAQA,EAAM,SAAWA,EAAM,MAAM,GAAGwE,EAAS,KAAK,IAAIA,EAAS,GAAG,IAAIxE,EAAM,UAAU,MAAMwE,EAAS,KAAK,GACpJ,MACF,IAAK,aACHE,EAAU,GAAGF,EAAS,GAAG,UAAKxE,EAAM,MAAQA,EAAM,SAAWA,EAAM,MAAM,GAAGwE,EAAS,KAAK,GAC1F,MACF,IAAK,iBACHE,EAAU,GAAGF,EAAS,MAAM,UAAKxE,EAAM,MAAQA,EAAM,OAAO,YAAYwE,EAAS,KAAK,GACtF,MACF,IAAK,aACHE,EAAU,GAAGF,EAAS,MAAM,UAAKxE,EAAM,MAAQA,EAAM,SAAWA,EAAM,MAAM,UAAUA,EAAM,OAAO,IAAIA,EAAM,WAAW,GAAGwE,EAAS,KAAK,GACzI,MACF,QACEE,EAAU,GAAGF,EAAS,GAAG,GAAGxE,EAAM,IAAI,GAAGwE,EAAS,KAAK,EAC3D,CAEA,QAAQ,IAAI,GAAGA,EAAS,GAAG,GAAGC,CAAS,GAAGD,EAAS,KAAK,IAAIF,CAAM,IAAII,CAAO,EAAE,CACjF,CACF","names":["devtools_entry_exports","__export","createConsoleLogger","createDevtools","quickVisualize","renderDiff","__toCommonJS","formatDuration","ms","minutes","seconds","generateId","hasRealScopeNodes","nodes","node","detectParallelGroups","options","minOverlapMs","maxGapMs","stepsWithTiming","nonStepNodes","i","a","b","groups","currentGroup","step","groupStart","s","groupEnd","startedTogether","hasTrueOverlap","overlapDuration","groupedNodes","group","position","children","startTs","endTs","parallelNode","deriveGroupState","originalIndex","g","c","createIRBuilder","options","detectParallel","parallelDetection","enableSnapshots","maxSnapshots","workflowId","workflowStartTs","workflowState","workflowError","workflowDurationMs","activeSteps","scopeStack","decisionStack","currentNodes","createdAt","lastUpdatedAt","hookState","snapshots","eventIndex","getStepId","event","generateId","addNode","node","decision","branch","firstBranch","captureSnapshot","ir","getIR","activeStepsCopy","id","step","snapshot","handleEvent","active","hookExec","handleScopeEvent","scope","deriveState","handleDecisionEvent","branchKey","existing","branches","b","children","c","getCurrentNodes","nodes","detectParallelGroups","root","hasHooks","reset","getSnapshots","getSnapshotAt","index","getIRAt","clearSnapshots","isStepNode","node","isSequenceNode","isParallelNode","isRaceNode","isDecisionNode","RESET","BOLD","DIM","FG_RED","FG_GREEN","FG_YELLOW","FG_BLUE","FG_GRAY","FG_WHITE","colorize","text","color","bold","dim","defaultColorScheme","getStateSymbol","state","getColoredSymbol","colors","symbol","colorByState","stripAnsi","str","BOX","HEAT_COLORS","RESET","getHeatColor","heat","applyHeatColor","text","color","SPARK_CHARS","renderSparkline","values","width","subset","min","range","v","normalized","index","padEnd","str","visibleLen","stripAnsi","padding","horizontalLine","title","titleText","remainingWidth","leftPad","rightPad","renderHookExecution","hook","label","colors","symbol","colorize","timing","dim","formatDuration","context","error","renderHooks","hooks","lines","asciiRenderer","ir","options","defaultColorScheme","innerWidth","workflowName","headerTitle","bold","hookLines","line","childLines","renderNodes","status","footer","colorByState","nodes","depth","node","isStepNode","renderStepNode","isParallelNode","renderParallelNode","isRaceNode","renderRaceNode","isDecisionNode","renderDecisionNode","getColoredSymbol","name","enhanced","nodeId","nameColored","inputStr","outputStr","timingStr","timingDisplay","history","timeoutInfo","hookExec","hookSymbol","hookTiming","indent","mode","i","child","prefix","nestedLines","winnerSuffix","condition","decisionValue","branchTaken","branch","branchSymbol","branchColor","branchLabel","branchCondition","getHeatLevel","heat","getStyleDefinitions","getHeatmapStyleDefinitions","getHeatClass","level","getHookStyleDefinitions","renderHooks","hooks","lines","options","lastHookId","hookId","state","icon","timing","formatDuration","context","nodeCounter","generateNodeId","prefix","resetNodeCounter","escapeMermaidText","text","escapeSubgraphName","mermaidRenderer","ir","enhanced","hookExitId","startId","prevNodeId","child","result","renderNode","endId","endIcon","endLabel","endShape","endClass","getStyleDefinitions","getHeatmapStyleDefinitions","node","isStepNode","renderStepNode","isParallelNode","renderParallelNode","isRaceNode","renderRaceNode","isDecisionNode","renderDecisionNode","id","mermaidOpts","showRetryEdges","showErrorEdges","showTimeoutEdges","label","stateIcon","ioInfo","inputStr","outputStr","hookInfo","hookExec","hookIcon","hookTiming","escapedLabel","nodeClass","nodeId","heat","level","getHeatLevel","getHeatClass","shape","retryLabel","errorNodeId","errorLabel","timeoutNodeId","timeoutMs","subgraphId","forkId","joinId","name","modeLabel","note","childExitIds","exitId","stateClass","winnerExitId","isWinner","decisionId","condition","decisionValue","decisionLabel","branchExitIds","takenBranchExitId","branch","branchId","branchLabelText","branchLabel","branchClass","edgeLabel","prevId","CHARS","HEAT_COLORS","RESET","createCanvas","width","height","cells","colors","y","setChar","canvas","x","char","color","getChar","drawBox","i","j","drawText","text","chars","stripAnsi","drawVerticalLine","startY","endY","minY","maxY","existing","drawHorizontalLine","startX","endX","minX","maxX","drawArrow","canvasToString","lines","line","MIN_BOX_WIDTH","BOX_PADDING","VERTICAL_GAP","HORIZONTAL_GAP","wrapText","maxWidth","words","current","word","getSymbol","state","layoutWorkflow","ir","options","canvasWidth","showStartEnd","enhanced","centerX","nodes","currentY","startNode","createSimpleNode","child","layoutResult","layoutFlowNode","endLabel","endNode","id","type","label","maxLabelLen","l","node","isStepNode","layoutStepNode","isParallelNode","isRaceNode","layoutBranchingNode","isDecisionNode","layoutDecisionNode","fallback","name","symbol","mainLabel","innerWidth","formatDuration","nodeId","history","renderSparkline","labelWidth","heat","layoutNode","isRace","headerLabel","result","childMaxWidth","childWidths","measured","measureFlowNode","totalChildWidth","a","b","useVerticalLayout","headerWidth","headerHeight","headerX","children","childX","childCenterX","childrenBottomY","c","totalBottomY","condition","labelLines","takenBranch","bottomY","lineCount","totalWidth","maxHeight","m","childHeight","renderNodes","defaultColorScheme","isLast","renderNode","nextNode","fromX","fromY","toX","toY","hasTopConnector","hasBottomConnector","getNodeColor","lineX","lineY","renderBranchingChildren","renderSequentialChildren","parent","forkY","forkX","firstChild","nextChild","childCenters","cx","childBottoms","maxChildBottom","joinY","level","getHeatLevel","flowchartRenderer","totalHeight","stripAnsi","str","collectSteps","nodes","steps","walk","nodeList","node","isStepNode","isSequenceNode","isParallelNode","isRaceNode","isDecisionNode","branch","stepToLog","step","log","calculateSummary","successCount","errorCount","cacheHits","skippedCount","totalRetries","slowestStep","hooksToLog","hooks","stepKey","hook","entry","buildLoggerOutput","ir","options","root","includeDiagram","stripColors","output","hookLog","diagram","flowchartRenderer","asciiRenderer","loggerRenderer","import_node_http","import_node_child_process","createVisualizer","options","workflowName","detectParallel","showTimings","showKeys","customColors","builder","createIRBuilder","updateCallbacks","ascii","asciiRenderer","mermaid","mermaidRenderer","logger","loggerRenderer","flowchart","flowchartRenderer","renderOptions","defaultColorScheme","notifyUpdate","ir","callback","handleEvent","event","handleScopeEvent","handleDecisionEvent","getIR","render","renderAs","format","reset","onUpdate","createDevtools","options","logEvents","maxHistory","logger","visualizer","createVisualizer","history","currentRun","workflowStartTime","startNewRun","workflowId","endCurrentRun","success","error","handleEvent","event","handleDecisionEvent","getCurrentRun","getHistory","getRun","id","run","diff","runId1","runId2","run1","run2","diffRuns","diffWithPrevious","previousRun","render","renderAs","format","renderMermaid","renderTimeline","timeline","getTimeline","formatTimeline","buildTimeline","clearHistory","reset","exportRun","runId","importRun","json","steps1","extractSteps","steps2","added","removed","changed","unchanged","name","step2","step1","statusChange","status1","status2","durationChange","events","steps","e","existing","startTime","stepStarts","entry","t","lines","maxEnd","barWidth","startPos","endPos","width","statusChar","getStatusChar","bar","duration","status","renderDiff","sign","step","quickVisualize","workflowFn","devtools","createConsoleLogger","prefix","colors","colorize","timestamp","message"]}