Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 4338x 794x 794x 794x 794x 794x 794x 794x 794x 4338x 4338x 770x 770x 770x 770x 770x 770x 770x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 1540x 770x 770x 770x 4338x 4338x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 728x 4338x 4338x 4338x 4338x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 2046x 4338x 4338x 24x 24x 24x 1x 1x 1x 1x 2774x 2774x 2774x 2774x 2774x 2774x 264x 264x 2774x 2508x 2774x 2774x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 580x 580x 108x 108x 580x 128x 128x 580x 20x 20x 580x 580x 20x 20x 20x 20x 580x 580x 108x 580x 452x 452x 580x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x | /**
* Flowchart Path Analysis
*
* Enumerates all possible paths through a flowchart and computes structural metrics.
* Used by the example generator to ensure coverage of all decision branches.
*
* @module flowcharts/path-analysis
*/
import type { ExecutableFlowchart } from './schema'
// =============================================================================
// Types
// =============================================================================
/**
* A constraint that must hold for a path to be taken
*/
export interface PathConstraint {
nodeId: string
/** The decision expression (correctAnswer) */
expression: string
/** For boolean decisions: what the expression must evaluate to */
requiredOutcome: boolean
/** For string decisions: the value the expression must equal */
requiredValue?: string
/** The option that was selected */
optionValue: string
}
/**
* A complete path through the flowchart from entry to terminal
*/
export interface FlowchartPath {
/** Sequence of node IDs */
nodeIds: string[]
/** Constraints that must be satisfied for this path */
constraints: PathConstraint[]
/** Number of decision nodes in this path */
decisions: number
/** Number of checkpoint nodes in this path */
checkpoints: number
}
/**
* Analysis of a flowchart's structure and paths
*/
export interface FlowchartAnalysis {
/** All unique paths through the flowchart */
paths: FlowchartPath[]
/** Whether path enumeration hit the safety limit (flowchart has more paths than enumerated) */
pathsLimitReached: boolean
/** Structural statistics */
stats: {
totalNodes: number
decisionNodes: number
checkpointNodes: number
terminalNodes: number
/** Total unique paths from entry to any terminal */
totalPaths: number
/** Minimum path length (in nodes) */
minPathLength: number
/** Maximum path length (in nodes) */
maxPathLength: number
/** Minimum number of decisions on any path */
minDecisions: number
/** Maximum number of decisions on any path */
maxDecisions: number
/** Minimum number of checkpoints on any path */
minCheckpoints: number
/** Maximum number of checkpoints on any path */
maxCheckpoints: number
/** Cyclomatic complexity: E - N + 2P (edges - nodes + 2*connected components) */
cyclomaticComplexity: number
}
/** Recommended Monte Carlo iterations for good coverage */
recommendedIterations: number
}
// =============================================================================
// Path Enumeration
// =============================================================================
/**
* Enumerate all paths through a flowchart using DFS.
* Returns all unique paths from entry node to terminal nodes.
* Handles cycles by tracking visited nodes within each path.
*/
export function enumerateAllPaths(flowchart: ExecutableFlowchart): {
paths: FlowchartPath[]
hitLimit: boolean
} {
const paths: FlowchartPath[] = []
const entryNode = flowchart.definition.entryNode
interface DFSFrame {
nodeId: string
pathSoFar: string[]
visitedInPath: Set<string> // Track visited nodes within THIS path to detect cycles
constraints: PathConstraint[]
decisions: number
checkpoints: number
}
// DFS with explicit stack to avoid recursion limits
const stack: DFSFrame[] = [
{
nodeId: entryNode,
pathSoFar: [],
visitedInPath: new Set(),
constraints: [],
decisions: 0,
checkpoints: 0,
},
]
const MAX_PATHS = 200 // Safety limit
const MAX_ITERATIONS = 10000 // Prevent infinite loops
let iterations = 0
while (stack.length > 0 && paths.length < MAX_PATHS && iterations < MAX_ITERATIONS) {
iterations++
const frame = stack.pop()!
const { nodeId, pathSoFar, visitedInPath, constraints, decisions, checkpoints } = frame
// Skip if we've already visited this node in the current path (cycle detection)
if (visitedInPath.has(nodeId)) {
continue
}
const currentPath = [...pathSoFar, nodeId]
const currentVisited = new Set(visitedInPath)
currentVisited.add(nodeId)
const node = flowchart.nodes[nodeId]
if (!node) continue
const def = node.definition
switch (def.type) {
case 'terminal':
// Found a complete path
paths.push({
nodeIds: currentPath,
constraints: [...constraints],
decisions,
checkpoints,
})
break
case 'decision': {
// If this decision has a skipIf/skipTo, enumerate both:
// 1. The skip path (when skipIf is true)
// 2. The regular option paths (when skipIf is false or not present)
if (def.skipIf && def.skipTo) {
// Push option paths FIRST (so they're explored LAST with LIFO stack)
// This ensures shorter skip paths are explored first
for (let optIdx = 0; optIdx < def.options.length; optIdx++) {
const option = def.options[optIdx]
const isFirstOption = optIdx === 0
const optionConstraints: PathConstraint[] = [
// skipIf must be false to reach this option
{
nodeId,
expression: def.skipIf,
requiredOutcome: false,
optionValue: '__not_skipped__',
},
]
if (def.correctAnswer) {
optionConstraints.push({
nodeId,
expression: def.correctAnswer,
requiredOutcome: isFirstOption,
requiredValue: option.value, // Always use string matching
optionValue: option.value,
})
}
stack.push({
nodeId: option.next,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: [...constraints, ...optionConstraints],
decisions: decisions + 1,
checkpoints,
})
}
// Push skip path LAST (so it's explored FIRST with LIFO stack)
// Skip paths are shorter, so we want to enumerate them first
const skipConstraint: PathConstraint = {
nodeId,
expression: def.skipIf,
requiredOutcome: true, // skipIf must be true for this path
optionValue: '__skip__',
}
stack.push({
nodeId: def.skipTo,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: [...constraints, skipConstraint],
decisions, // Don't increment - decision is skipped
checkpoints,
})
} else if (!def.excludeFromExampleStructure) {
// No skipIf - branch into all options normally (unless excluded)
for (let optIdx = 0; optIdx < def.options.length; optIdx++) {
const option = def.options[optIdx]
// Always use requiredValue for string matching - this handles both:
// - Multi-option decisions (3+ options) with string values like "a", "b", "c"
// - Binary decisions (2 options) with string values like "statement", "request"
// The boolean requiredOutcome is kept for backward compatibility but requiredValue takes precedence
const isFirstOption = optIdx === 0
const constraint: PathConstraint | undefined = def.correctAnswer
? {
nodeId,
expression: def.correctAnswer,
requiredOutcome: isFirstOption,
requiredValue: option.value, // Always use string matching
optionValue: option.value,
}
: undefined
stack.push({
nodeId: option.next,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: constraint ? [...constraints, constraint] : constraints,
decisions: decisions + 1,
checkpoints,
})
}
} else {
// Decision is excluded from example structure - just take first option
const option = def.options[0]
if (option) {
stack.push({
nodeId: option.next,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints,
decisions,
checkpoints,
})
}
}
break
}
case 'checkpoint': {
// Checkpoints with skipIf can create branching paths by default,
// unless excludeSkipFromPaths is true (for optional steps that
// don't represent different problem types).
if (def.skipIf && def.skipTo && !def.excludeSkipFromPaths) {
// Create two paths: skip path and non-skip path
// Push non-skip path first (so skip path is explored first with LIFO)
const nextNode = getNextNodeForAnalysis(flowchart, nodeId, def)
if (nextNode && !currentVisited.has(nextNode)) {
const notSkippedConstraint: PathConstraint = {
nodeId,
expression: def.skipIf,
requiredOutcome: false, // skipIf must be false
optionValue: '__not_skipped__',
}
stack.push({
nodeId: nextNode,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: [...constraints, notSkippedConstraint],
decisions,
checkpoints: checkpoints + 1,
})
}
// Push skip path last (explored first with LIFO)
if (!currentVisited.has(def.skipTo)) {
const skipConstraint: PathConstraint = {
nodeId,
expression: def.skipIf,
requiredOutcome: true, // skipIf must be true
optionValue: '__skip__',
}
stack.push({
nodeId: def.skipTo,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: [...constraints, skipConstraint],
decisions,
checkpoints,
})
}
} else {
// No skipIf, or excludeSkipFromPaths is true - just continue
const nextNode = getNextNodeForAnalysis(flowchart, nodeId, def)
if (nextNode) {
stack.push({
nodeId: nextNode,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints,
decisions,
checkpoints: checkpoints + 1,
})
}
}
break
}
case 'instruction':
case 'milestone':
case 'embellishment': {
// Check if this node has skipIf/skipTo (creates branching)
if ('skipIf' in def && 'skipTo' in def && def.skipIf && def.skipTo) {
const skipIfExpr = def.skipIf as string
const skipToNode = def.skipTo as string
// Push normal path first (so skip path is explored first with LIFO)
// Add constraint that skipIf is FALSE for normal path
const nextNode = getNextNodeForAnalysis(flowchart, nodeId, def)
if (nextNode && !currentVisited.has(nextNode)) {
const notSkippedConstraint: PathConstraint = {
nodeId,
expression: skipIfExpr,
requiredOutcome: false, // skipIf must be false
optionValue: '__not_skipped__',
}
stack.push({
nodeId: nextNode,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: [...constraints, notSkippedConstraint],
decisions,
checkpoints,
})
}
// Push skip path last (explored first with LIFO)
// Add constraint that skipIf is TRUE for skip path
if (!currentVisited.has(skipToNode)) {
const skipConstraint: PathConstraint = {
nodeId,
expression: skipIfExpr,
requiredOutcome: true, // skipIf must be true
optionValue: '__skip__',
}
stack.push({
nodeId: skipToNode,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints: [...constraints, skipConstraint],
decisions,
checkpoints,
})
}
} else {
// No skipIf - just continue to next node
const nextNode = getNextNodeForAnalysis(flowchart, nodeId, def)
if (nextNode) {
stack.push({
nodeId: nextNode,
pathSoFar: currentPath,
visitedInPath: currentVisited,
constraints,
decisions,
checkpoints,
})
}
}
break
}
}
}
return { paths, hitLimit: paths.length >= MAX_PATHS }
}
/**
* Helper to get the next node for path analysis
*/
function getNextNodeForAnalysis(
flowchart: ExecutableFlowchart,
nodeId: string,
def: { next?: string; type: string }
): string | undefined {
if ((def.type === 'milestone' || def.type === 'embellishment') && 'next' in def) {
return def.next as string
}
if (def.next) return def.next
const edges = flowchart.definition.edges?.[nodeId]
if (edges && edges.length > 0) return edges[0]
const mermaidEdges = flowchart.mermaid.edges.filter((e) => e.from === nodeId)
return mermaidEdges[0]?.to
}
// =============================================================================
// Flowchart Analysis
// =============================================================================
/**
* Analyze a flowchart's structure and compute metrics
*/
export function analyzeFlowchart(flowchart: ExecutableFlowchart): FlowchartAnalysis {
const { paths, hitLimit } = enumerateAllPaths(flowchart)
// Count node types
let decisionNodes = 0
let checkpointNodes = 0
let terminalNodes = 0
const totalNodes = Object.keys(flowchart.nodes).length
for (const node of Object.values(flowchart.nodes)) {
switch (node.definition.type) {
case 'decision':
decisionNodes++
break
case 'checkpoint':
checkpointNodes++
break
case 'terminal':
terminalNodes++
break
}
}
// Compute edge count for cyclomatic complexity
let edgeCount = 0
for (const node of Object.values(flowchart.nodes)) {
const def = node.definition
if (def.type === 'decision') {
edgeCount += def.options.length
} else if (def.type !== 'terminal') {
edgeCount += 1
}
}
// Path statistics
const pathLengths = paths.map((p) => p.nodeIds.length)
const pathDecisions = paths.map((p) => p.decisions)
const pathCheckpoints = paths.map((p) => p.checkpoints)
const stats = {
totalNodes,
decisionNodes,
checkpointNodes,
terminalNodes,
totalPaths: paths.length,
minPathLength: paths.length > 0 ? Math.min(...pathLengths) : 0,
maxPathLength: paths.length > 0 ? Math.max(...pathLengths) : 0,
minDecisions: paths.length > 0 ? Math.min(...pathDecisions) : 0,
maxDecisions: paths.length > 0 ? Math.max(...pathDecisions) : 0,
minCheckpoints: paths.length > 0 ? Math.min(...pathCheckpoints) : 0,
maxCheckpoints: paths.length > 0 ? Math.max(...pathCheckpoints) : 0,
cyclomaticComplexity: edgeCount - totalNodes + 2,
}
// Calculate recommended iterations using coupon collector problem
// Expected iterations to see all N unique items: N * (ln(N) + 0.5772)
// But paths aren't equally likely, so we multiply by a safety factor
const n = paths.length
const couponCollectorExpected = n > 0 ? n * (Math.log(n) + 0.5772) : 10
// Add extra iterations for path probability skew (some paths are rare)
const skewFactor = 3 // Assume some paths are 3x less likely
// Also factor in the number of decision nodes (more decisions = more branching = need more samples)
const branchingFactor = 2 ** Math.min(decisionNodes, 5)
const recommendedIterations = Math.max(
50, // Minimum
Math.ceil(couponCollectorExpected * skewFactor),
branchingFactor * 10
)
return { paths, pathsLimitReached: hitLimit, stats, recommendedIterations }
}
|