{"version":3,"sources":["../src/analysis-entry.ts","../src/register-node-ts-morph.ts","../src/ts-morph-loader.ts","../src/analyze.ts","../src/types.ts","../src/static-analyzer.ts","../src/analysis-utils.ts","../src/type-extractor.ts","../src/analysis-patterns.ts","../src/path-utils.ts","../src/alias-resolution.ts","../src/program-discovery.ts","../src/core-analysis.ts","../src/effect-analysis.ts","../src/callback-summary.ts","../src/layer-initializer-resolution.ts","../src/service-type-heuristics.ts","../src/analysis-context.ts","../src/stream-channel-sink-analyzers.ts","../src/analysis-classifiers.ts","../src/retry-timeout-analyzers.ts","../src/concurrency-fiber-analyzers.ts","../src/parallel-race-analyzers.ts","../src/error-handler-analyzer.ts","../src/resource-analyzer.ts","../src/control-flow-analyzers.ts","../src/project-analyzer.ts","../src/service-registry.ts","../src/project-corpus.ts","../src/audit-assessment.ts","../src/ir.ts","../src/fidelity-findings.ts","../src/project-architecture.ts","../src/analysis-session.ts","../src/audit-policy.ts","../src/output/coverage-report.ts","../src/complexity.ts","../src/path-generator.ts","../src/data-flow.ts","../src/error-flow.ts","../src/service-flow.ts","../src/layer-graph.ts","../src/observability.ts","../src/output/test-matrix.ts","../src/scope-resource.ts","../src/state-flow.ts","../src/state-machine.ts","../src/state-machine-ast.ts","../src/state-machine-json.ts","../src/state-machine-coverage.ts","../src/output/mermaid-statechart.ts","../src/output/xstate-config.ts","../src/output/svg-statechart.ts"],"sourcesContent":["/** Full static-analysis interface for Effect v4. */\n\nexport * from './analysis-session';\nexport { analyze, type AnalyzeResult } from './analyze';\nexport { analyzeEffectFile, analyzeEffectSource } from './static-analyzer';\nexport {\n  analyzeProject,\n  analyzeProjectCorpus,\n  runCoverageAudit,\n  runCoverageAuditFromCorpus,\n  type AnalyzeProjectOptions,\n  type CoverageAuditResult,\n  type FileOutcome,\n  type ProjectAnalysisResult,\n  type ProjectFidelityFinding,\n  type ZeroProgramCategory,\n  type ZeroProgramClassification,\n} from './project-analyzer';\nexport * from './audit-assessment';\nexport * from './audit-policy';\nexport * from './output/coverage-report';\nexport {\n  scanProjectCorpus,\n  type ProjectCorpus,\n  type ProjectCorpusFile,\n  type ProjectCorpusFileStatus,\n  type ScanProjectCorpusOptions,\n} from './project-corpus';\nexport * from './ir';\nexport * from './fidelity-findings';\nexport * from './complexity';\nexport * from './path-generator';\nexport * from './data-flow';\nexport * from './error-flow';\nexport * from './service-flow';\nexport * as LayerGraph from './layer-graph';\nexport * from './observability';\nexport * from './output/test-matrix';\nexport * from './scope-resource';\nexport * from './state-flow';\n// Statechart analysis: extract from source, ingest MachineJSON, verify coverage.\nexport {\n  analyzeStateMachines,\n  type StateMachine,\n  type StateInvoke,\n  type StateTransition,\n  type StateMachineAnalysis,\n} from './state-machine';\nexport {\n  fromMachineJSON,\n  type MachineJSON,\n  type MachineJSONInvoke,\n  type MachineJSONStateNode,\n  type MachineJSONValue,\n  type MachineJSONTransition,\n  type MachineJSONGuard,\n  type MachineJSONAction,\n  type MachineJSONInitial,\n  type MachineJSONExpression,\n  type MachineJSONUnserializable,\n  type FromMachineJSONOptions,\n} from './state-machine-json';\nexport {\n  computeStateMachineCoverage,\n  type StateMachineCoverage,\n  type CoverageFinding,\n  type CoverageKind,\n} from './state-machine-coverage';\n// Statechart renderers, so MachineJSON machines (which the CLI does not\n// discover in source) can be rendered programmatically too.\nexport { renderStatechartMermaid, renderStatechartsMermaid } from './output/mermaid-statechart';\nexport { renderXStateConfig } from './output/xstate-config';\nexport { renderStatechartSVG } from './output/svg-statechart';\nexport type * from './types';\n","import { createRequire } from 'node:module';\nimport { setTsMorphLoader } from './ts-morph-loader';\n\n/** Current module location in both ESM and bundled CommonJS builds. */\nexport const nodeModuleLocation =\n  typeof __filename === 'string' ? __filename : import.meta.url;\n\nsetTsMorphLoader(() => {\n  const require = createRequire(nodeModuleLocation);\n  return require('ts-morph') as typeof import('ts-morph');\n});\n","/**\n * Runtime-configurable ts-morph loader.\n *\n * Node uses a lazy builtin-module fallback so browser bundles do not pull in\n * `node:module` at build time. Browser consumers must explicitly provide a\n * ts-morph-compatible module before calling source analysis APIs.\n */\n\nimport type { Project, SourceFile } from 'ts-morph';\n\ntype TsMorphModule = typeof import('ts-morph');\ntype TsMorphLoader = () => TsMorphModule;\n\nlet tsMorphModule: TsMorphModule | null = null;\nlet tsMorphLoader: TsMorphLoader | null = null;\nconst projectCache = new Map<string, Project>();\n\ninterface BuiltinAwareProcess {\n  readonly getBuiltinModule?: (id: string) => unknown;\n}\n\nconst getBuiltinModule = (id: string): unknown => {\n  const maybeProcess = (globalThis as { process?: BuiltinAwareProcess }).process;\n  return maybeProcess?.getBuiltinModule?.(id);\n};\n\nconst loadNodeTsMorph = (): TsMorphModule | null => {\n  const moduleBuiltin =\n    getBuiltinModule('node:module') ?? getBuiltinModule('module');\n  const createRequire =\n    moduleBuiltin &&\n    typeof moduleBuiltin === 'object' &&\n    'createRequire' in moduleBuiltin\n      ? (moduleBuiltin.createRequire as (url: string) => NodeJS.Require)\n      : undefined;\n\n  if (!createRequire) {\n    return null;\n  }\n\n  try {\n    const require = createRequire(import.meta.url);\n    return require('ts-morph') as TsMorphModule;\n  } catch {\n    return null;\n  }\n};\n\nexport const setTsMorphModule = (module: TsMorphModule): void => {\n  tsMorphModule = module;\n};\n\nexport const setTsMorphLoader = (loader: TsMorphLoader): void => {\n  tsMorphLoader = loader;\n  tsMorphModule = null;\n};\n\nexport const resetTsMorphRuntime = (): void => {\n  tsMorphModule = null;\n  tsMorphLoader = null;\n  projectCache.clear();\n};\n\nexport const loadTsMorph = (): TsMorphModule => {\n  if (tsMorphModule) {\n    return tsMorphModule;\n  }\n\n  const configuredModule =\n    tsMorphLoader?.() ?? loadNodeTsMorph();\n\n  if (!configuredModule) {\n    throw new Error(\n      'ts-morph is not configured. In Node, install ts-morph as a dependency. In browser builds, call setTsMorphModule() or setTsMorphLoader() before analysis.',\n    );\n  }\n\n  tsMorphModule = configuredModule;\n  return configuredModule;\n};\n\nexport const createProject = (tsConfigPath?: string): Project => {\n  const cacheKey = tsConfigPath ?? '__default__';\n  const cached = projectCache.get(cacheKey);\n  if (cached) {\n    return cached;\n  }\n\n  const { Project } = loadTsMorph();\n  const options: { tsConfigFilePath?: string } = {};\n  if (tsConfigPath) {\n    options.tsConfigFilePath = tsConfigPath;\n  }\n  const project = new Project(options);\n  projectCache.set(cacheKey, project);\n  return project;\n};\n\nexport const clearProjectCache = (): void => {\n  projectCache.clear();\n};\n\nexport const createProjectFromSource = (\n  code: string,\n  filePath = 'temp.ts',\n): SourceFile => {\n  const { Project } = loadTsMorph();\n  const project = new Project({\n    useInMemoryFileSystem: true,\n    compilerOptions: {\n      strict: true,\n      esModuleInterop: true,\n    },\n  });\n  return project.createSourceFile(filePath, code);\n};\n","/**\n * Fluent Builder API for Static Effect Analysis\n *\n * Provides an ergonomic API for analyzing Effect files with explicit intent.\n * Built entirely with Effect for composability.\n *\n * @known-hub Library API entry point — imported by all consumers\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { analyze } from \"effect-analyzer/analysis\";\n *\n * // Single program file\n * const ir = await Effect.runPromise(analyze(\"./program.ts\").single);\n *\n * // Multi-program file\n * const programs = await Effect.runPromise(analyze(\"./programs.ts\").all);\n *\n * // Get specific program by name\n * const program = await Effect.runPromise(analyze(\"./programs.ts\").named(\"myProgram\"));\n *\n * // From source string\n * const ir = await Effect.runPromise(analyze.source(code).single);\n * ```\n */\n\nimport './register-node-ts-morph';\nimport { Effect, Option } from 'effect';\nimport { AnalysisError } from './types';\nimport type { StaticEffectIR, AnalyzerOptions } from './types';\nimport {\n  analyzeEffectFile,\n  analyzeEffectSource,\n  resetIdCounter,\n} from './static-analyzer';\n\n/**\n * Result object from analyze() with fluent methods to retrieve programs.\n */\nexport interface AnalyzeResult {\n  /**\n   * Get single program. Fails if file has 0 or >1 programs.\n   */\n  readonly single: Effect.Effect<StaticEffectIR, AnalysisError>;\n\n  /**\n   * Get single program or None if not exactly one.\n   */\n  readonly singleOption: Effect.Effect<\n    Option.Option<StaticEffectIR>\n  >;\n\n  /**\n   * Get all programs as array.\n   */\n  readonly all: Effect.Effect<\n    readonly StaticEffectIR[],\n    AnalysisError\n  >;\n\n  /**\n   * Get program by name. Fails if not found.\n   */\n  readonly named: (\n    name: string,\n  ) => Effect.Effect<StaticEffectIR, AnalysisError>;\n\n  /**\n   * Get first program. Fails if empty.\n   */\n  readonly first: Effect.Effect<StaticEffectIR, AnalysisError>;\n\n  /**\n   * Get first program or None if empty.\n   */\n  readonly firstOption: Effect.Effect<\n    Option.Option<StaticEffectIR>\n  >;\n}\n\nconst createResult = (\n  programs: readonly StaticEffectIR[],\n): AnalyzeResult => ({\n  single: Effect.gen(function* () {\n      if (programs.length === 1) {\n        const program = programs[0];\n        if (program) {\n          return program;\n        }\n      }\n      return yield* Effect.fail(\n        new AnalysisError(\n          'NOT_SINGLE_PROGRAM',\n          `Expected exactly 1 program, found ${String(programs.length)}: ` +\n            `${programs.map((p) => p.root.programName).join(', ')}. ` +\n            'Use .named(name) to pick one, or .all for every program.',\n        ),\n      );\n    }),\n\n  singleOption: Effect.gen(function* () {\n      if (programs.length === 1) {\n        const program = programs[0];\n        if (program) {\n          return Option.some(program);\n        }\n      }\n      return Option.none<StaticEffectIR>();\n    }),\n\n  all: Effect.succeed(programs),\n\n  named: (name: string) =>\n    Effect.gen(function* () {\n      const found = programs.find((p) => p.root.programName === name);\n      if (!found) {\n        const available = programs.map((p) => p.root.programName).join(', ');\n        return yield* Effect.fail(\n          new AnalysisError(\n            'PROGRAM_NOT_FOUND',\n            `Program \"${name}\" not found. Available: ${available || '(none)'}`,\n          ),\n        );\n      }\n      return found;\n    }),\n\n  first: Effect.gen(function* () {\n      const program = programs[0];\n      if (program) {\n        return program;\n      }\n      return yield* Effect.fail(\n        new AnalysisError('NO_PROGRAMS', 'No programs found'),\n      );\n    }),\n\n  firstOption: Effect.gen(function* () {\n      const program = programs[0];\n      if (program) {\n        return Option.some(program);\n      }\n      return Option.none<StaticEffectIR>();\n    }),\n});\n\n/**\n * Analyze an Effect file and return a fluent result object.\n *\n * @param filePath - Path to the TypeScript file containing the Effect program(s)\n * @param options - Analysis options\n * @returns Fluent result object with methods to retrieve programs\n *\n * @example\n * ```typescript\n * // Single program file\n * const ir = await Effect.runPromise(analyze(\"./program.ts\").single);\n *\n * // Multiple programs - get all as array\n * const programs = await Effect.runPromise(analyze(\"./programs.ts\").all);\n *\n * // Get specific program by name\n * const program = await Effect.runPromise(analyze(\"./programs.ts\").named(\"myProgram\"));\n * ```\n */\nexport const analyze = (\n  filePath: string,\n  options?: AnalyzerOptions,\n): AnalyzeResult => {\n  // Reset ID counter for deterministic results\n  resetIdCounter();\n\n  // Lazily evaluate the analysis\n  const programsEffect = analyzeEffectFile(filePath, options);\n\n  return {\n    single: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).single;\n      }),\n\n    singleOption: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).singleOption;\n      }).pipe(Effect.orDie),\n\n    all: programsEffect,\n\n    named: (name: string) =>\n      Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).named(name);\n      }),\n\n    first: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).first;\n      }),\n\n    firstOption: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).firstOption;\n      }).pipe(Effect.orDie),\n  };\n};\n\n/**\n * Analyze Effect source code directly (for testing or dynamic analysis).\n *\n * @param code - TypeScript source code containing the Effect program(s)\n * @param options - Analysis options\n * @returns Fluent result object with methods to retrieve programs\n *\n * @example\n * ```typescript\n * const source = `\n *   const program = Effect.gen(function* () {\n *     yield* Effect.log(\"Hello\");\n *     return 42;\n *   });\n * `;\n *\n * const ir = await Effect.runPromise(analyze.source(source).single);\n * ```\n */\nanalyze.source = (code: string, options?: AnalyzerOptions): AnalyzeResult => {\n  resetIdCounter();\n\n  const programsEffect = analyzeEffectSource(code, 'temp.ts', options);\n\n  return {\n    single: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).single;\n      }),\n\n    singleOption: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).singleOption;\n      }).pipe(Effect.orDie),\n\n    all: programsEffect,\n\n    named: (name: string) =>\n      Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).named(name);\n      }),\n\n    first: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).first;\n      }),\n\n    firstOption: Effect.gen(function* () {\n        const programs = yield* programsEffect;\n        return yield* createResult(programs).firstOption;\n      }).pipe(Effect.orDie),\n  };\n};\n","/**\n * Static Effect Analysis - Type Definitions\n *\n * These types represent Effect code structure extracted through static analysis\n * (AST walking) rather than runtime execution.\n *\n * @known-hub Central IR type definitions imported by every analyzer\n */\n\nimport { Effect, Option } from 'effect';\n\n// =============================================================================\n// Static Node Types\n// =============================================================================\n\n/**\n * Source code location for tracing back to original code.\n */\nexport interface SourceLocation {\n  /** Absolute file path */\n  readonly filePath: string;\n  /** Line number (1-indexed) */\n  readonly line: number;\n  /** Column number (0-indexed) */\n  readonly column: number;\n  /** End line number */\n  readonly endLine?: number | undefined;\n  /** End column number */\n  readonly endColumn?: number | undefined;\n  /** Character offset from start of file (0-indexed) */\n  readonly offset?: number | undefined;\n  /** Character end offset from start of file (0-indexed) */\n  readonly endOffset?: number | undefined;\n}\n\n/**\n * Semantic role classification for display and styling.\n */\nexport type SemanticRole =\n  | 'constructor'\n  | 'service-call'\n  | 'environment'\n  | 'side-effect'\n  | 'transform'\n  | 'error-handler'\n  | 'concurrency'\n  | 'resource'\n  | 'control-flow'\n  | 'scheduling'\n  | 'stream'\n  | 'layer'\n  | 'fiber'\n  | 'unknown';\n\n/**\n * Structured JSDoc tag data extracted from comments.\n */\nexport interface JSDocTags {\n  readonly params: readonly { readonly name: string; readonly description?: string }[];\n  readonly returns?: string | undefined;\n  readonly throws: readonly string[];\n  readonly example?: string | undefined;\n}\n\n/**\n * Detail level for Mermaid diagram labels.\n */\nexport type MermaidDetailLevel = 'compact' | 'standard' | 'verbose';\n\n/**\n * Base properties shared by all static analysis nodes.\n */\nexport interface StaticBaseNode {\n  /** Unique identifier for this node */\n  readonly id: string;\n  /** Human-readable name */\n  readonly name?: string | undefined;\n  /** Source location */\n  readonly location?: SourceLocation | undefined;\n  /** Pre-computed human-readable display label (e.g. \"user <- UserRepo.getById\") */\n  readonly displayName?: string | undefined;\n  /** Semantic role classification for styling and filtering */\n  readonly semanticRole?: SemanticRole | undefined;\n  /** Span name from Effect.withSpan annotation */\n  readonly spanName?: string | undefined;\n  /** Runtime nesting order for multiple Effect.withSpan transformations. */\n  readonly spanNames?: readonly string[] | undefined;\n  /** True when a span name is computed and cannot be joined statically. */\n  readonly spanNameDynamic?: boolean | undefined;\n}\n\n/**\n * A single Effect operation (yield* or direct call).\n */\nexport interface StaticEffectNode extends StaticBaseNode {\n  readonly type: 'effect';\n  /** The Effect being created (e.g., \"Effect.succeed\", \"Effect.sync\") */\n  readonly callee: string;\n  /** Description of what this effect does */\n  readonly description?: string | undefined;\n  /** JSDoc description extracted from comments above the effect */\n  readonly jsdocDescription?: string | undefined;\n  /** Structured JSDoc tags extracted from comments */\n  readonly jsdocTags?: JSDocTags | undefined;\n  /** Error type if statically determinable */\n  readonly errorType?: string | undefined;\n  /** Full type signature (A, E, R) - requires type extraction */\n  readonly typeSignature?: EffectTypeSignature | undefined;\n  /** Services required by this specific effect */\n  readonly requiredServices?: ServiceRequirement[] | undefined;\n  /** If this effect is a method call on a typed service object */\n  readonly serviceCall?: {\n    /** Resolved type name of the service object (e.g. 'UserRepo') */\n    readonly serviceType: string;\n    /** Method name being called (e.g. 'getById') */\n    readonly methodName: string;\n    /** Variable/expression name used at call site (e.g. 'repo') */\n    readonly objectName: string;\n  } | undefined;\n  /** Resolved service method when call is e.g. yield* db.query() and db is bound to a service tag */\n  readonly serviceMethod?: { readonly serviceId: string; readonly methodName: string } | undefined;\n  /** Service wrapper callback pattern like `fileClient.use((client) => ...)` */\n  readonly usePattern?: {\n    readonly wrapperName: string;\n    readonly callbackKind: 'promise' | 'effect' | 'unknown';\n  } | undefined;\n  /** Inner effects from Effect.sync/promise/async callback body (one level only) */\n  readonly callbackBody?: readonly StaticFlowNode[] | undefined;\n  /** Callback-style constructors: resume/canceller patterns for Effect.callback/asyncEffect/callback. */\n  readonly asyncCallback?: {\n    readonly resumeParamName: string;\n    readonly resumeCallCount: number;\n    readonly returnsCanceller: boolean;\n  } | undefined;\n  /** Effect.provide only: whether context is provided via Layer, Context, or Runtime. */\n  readonly provideKind?: 'layer' | 'context' | 'runtime' | undefined;\n  /** Constructor subtype classification */\n  readonly constructorKind?: 'sync' | 'promise' | 'async' | 'callback' | 'never' | 'void' | 'fromNullable' | 'fn' | 'fnUntraced' | undefined;\n  /** FiberRef built-in name (e.g. currentLogLevel, currentConcurrency) */\n  readonly fiberRefName?: string | undefined;\n  /** Effect.fn traced name */\n  readonly tracedName?: string | undefined;\n}\n\n/**\n * Generator-based effect block (Effect.gen).\n */\nexport interface StaticGeneratorNode extends StaticBaseNode {\n  readonly type: 'generator';\n  /** Variables yielded in the generator */\n  readonly yields: {\n    readonly variableName?: string | undefined;\n    readonly effect: StaticFlowNode;\n  }[];\n  /** Final return value */\n  readonly returnNode?: StaticFlowNode | undefined;\n  /** JSDoc description extracted from comments above the generator function */\n  readonly jsdocDescription?: string | undefined;\n  /** Structured JSDoc tags extracted from comments */\n  readonly jsdocTags?: JSDocTags | undefined;\n}\n\n/**\n * Pipe composition chain (effect.pipe(...)).\n */\nexport interface StaticPipeNode extends StaticBaseNode {\n  readonly type: 'pipe';\n  /** The initial effect */\n  readonly initial: StaticFlowNode;\n  /** Pipe transformations in order */\n  readonly transformations: readonly StaticFlowNode[];\n  /** Type flow through the pipe chain (A, E, R at each step) */\n  readonly typeFlow?: readonly EffectTypeSignature[] | undefined;\n}\n\n/**\n * Concurrency mode for Effect.all / Effect.allWith.\n */\nexport type ConcurrencyMode = 'sequential' | 'bounded' | 'unbounded' | number;\n\n/**\n * Parallel execution (Effect.all, Effect.allPar).\n */\nexport interface StaticParallelNode extends StaticBaseNode {\n  readonly type: 'parallel';\n  /** Child effects running in parallel */\n  readonly children: readonly StaticFlowNode[];\n  /** Mode: sequential (all) or parallel (allPar) */\n  readonly mode: 'sequential' | 'parallel';\n  /** The callee (e.g., \"Effect.all\", \"Effect.allPar\") */\n  readonly callee: string;\n  /** Resolved concurrency: from options or inferred from mode (GAP 18) */\n  readonly concurrency?: ConcurrencyMode | undefined;\n  /** Request batching enabled (Effect.all with { batching: true }) */\n  readonly batching?: boolean | undefined;\n  /** Results discarded (Effect.all with { discard: true }) */\n  readonly discard?: boolean | undefined;\n  /** Labels for each parallel branch (from child displayNames) */\n  readonly branchLabels?: readonly string[] | undefined;\n}\n\n/**\n * Race execution (Effect.race, Effect.raceAll).\n */\nexport interface StaticRaceNode extends StaticBaseNode {\n  readonly type: 'race';\n  /** Child effects racing */\n  readonly children: readonly StaticFlowNode[];\n  /** The callee */\n  readonly callee: string;\n  /** Labels for each race competitor */\n  readonly raceLabels?: readonly string[] | undefined;\n}\n\n/**\n * Error handling (catch, catchTag, orElse, etc.).\n */\nexport interface StaticErrorHandlerNode extends StaticBaseNode {\n  readonly type: 'error-handler';\n  /** Type of handler: catch, catchTag, orElse, etc. */\n  readonly handlerType:\n    | 'catch'\n    | 'catchTag'\n    | 'catchCause'\n    | 'catchIf'\n    | 'catchSome'\n    | 'catchSomeCause'\n    | 'catchSomeDefect'\n    | 'catchDefect'\n    | 'catchTags'\n    // Effect 4 catch APIs\n    | 'catchReason'\n    | 'catchReasons'\n    | 'catchFilter'\n    | 'catchCauseIf'\n    | 'catchCauseFilter'\n    | 'catchNoSuchElement'\n    | 'catchEager'\n    | 'orElse'\n    | 'orElseFail'\n    | 'orElseSucceed'\n    | 'orDie'\n    | 'orDieWith'\n    | 'flip'\n    | 'mapError'\n    | 'mapErrorCause'\n    | 'mapBoth'\n    | 'sandbox'\n    | 'unsandbox'\n    | 'parallelErrors'\n    | 'filterOrDie'\n    | 'filterOrDieMessage'\n    | 'filterOrElse'\n    | 'filterOrFail'\n    | 'match'\n    | 'matchCause'\n    | 'matchEffect'\n    | 'matchCauseEffect'\n    | 'firstSuccessOf'\n    | 'ignore'\n    | 'ignoreLogged'\n    | 'eventually';\n  /** The effect being handled */\n  readonly source: StaticFlowNode;\n  /** The handler (recovery) effect */\n  readonly handler?: StaticFlowNode | undefined;\n  /** For catchTag, the error tag being caught */\n  readonly errorTag?: string | undefined;\n  /** For catchTags (object form), the error tags being caught */\n  readonly errorTags?: readonly string[] | undefined;\n  /** Edge label for the error path (e.g. \"on DatabaseError\") */\n  readonly errorEdgeLabel?: string | undefined;\n}\n\n/**\n * Schedule composition info (GAP 8).\n */\nexport interface ScheduleInfo {\n  readonly baseStrategy:\n    | 'fixed'\n    | 'exponential'\n    | 'fibonacci'\n    | 'spaced'\n    | 'linear'\n    | 'cron'\n    | 'windowed'\n    | 'duration'\n    | 'elapsed'\n    | 'delays'\n    | 'once'\n    | 'stop'\n    | 'count'\n    | 'custom';\n  readonly maxRetries?: number | 'unlimited' | undefined;\n  readonly initialDelay?: string | undefined;\n  readonly maxDelay?: string | undefined;\n  readonly jittered: boolean;\n  readonly conditions: readonly string[];\n  readonly estimatedMaxDuration?: string | undefined;\n}\n\n/**\n * Retry/Schedule operation.\n */\nexport interface StaticRetryNode extends StaticBaseNode {\n  readonly type: 'retry';\n  /** The effect being retried */\n  readonly source: StaticFlowNode;\n  /** Schedule policy if statically determinable (expression text) */\n  readonly schedule?: string | undefined;\n  /** Parsed schedule when present (GAP 8 dedicated Schedule IR) */\n  readonly scheduleNode?: StaticFlowNode | undefined;\n  /** Whether it's a retryOrElse */\n  readonly hasFallback: boolean;\n  /** Decomposed schedule (GAP 8) */\n  readonly scheduleInfo?: ScheduleInfo | undefined;\n  /** Edge label for the retry path (e.g. \"retry: exponential(100ms)\") */\n  readonly retryEdgeLabel?: string | undefined;\n}\n\n/**\n * Timeout operation.\n */\nexport interface StaticTimeoutNode extends StaticBaseNode {\n  readonly type: 'timeout';\n  /** The effect being timed out */\n  readonly source: StaticFlowNode;\n  /** Timeout duration if statically determinable */\n  readonly duration?: string | undefined;\n  /** Whether there's a fallback */\n  readonly hasFallback: boolean;\n}\n\n/**\n * Resource acquisition (acquireRelease).\n */\nexport interface StaticResourceNode extends StaticBaseNode {\n  readonly type: 'resource';\n  /** Acquisition effect */\n  readonly acquire: StaticFlowNode;\n  /** Release effect */\n  readonly release: StaticFlowNode;\n  /** Use effect */\n  readonly use?: StaticFlowNode | undefined;\n}\n\n/**\n * Conditional execution (Effect.if, when, unless).\n */\nexport interface StaticConditionalNode extends StaticBaseNode {\n  readonly type: 'conditional';\n  /** The condition as source string */\n  readonly condition: string;\n  /** Type of conditional */\n  readonly conditionalType:\n    | 'if'\n    | 'when'\n    | 'unless'\n    | 'whenEffect'\n    | 'whenFiberRef'\n    | 'whenRef'\n    | 'unlessEffect'\n    | 'option'\n    | 'either'\n    | 'exit'\n    | 'liftPredicate';\n  /** Branch when condition is true */\n  readonly onTrue: StaticFlowNode;\n  /** Branch when condition is false (if present) */\n  readonly onFalse?: StaticFlowNode | undefined;\n  /** Semantic label for the condition (e.g. \"isAdmin\") */\n  readonly conditionLabel?: string | undefined;\n  /** Label for the true branch edge */\n  readonly trueEdgeLabel?: string | undefined;\n  /** Label for the false branch edge */\n  readonly falseEdgeLabel?: string | undefined;\n}\n\n/**\n * Decision node for raw `if`, ternaries, short-circuits, and `Step.decide`.\n */\nexport interface StaticDecisionNode extends StaticBaseNode {\n  readonly type: 'decision';\n  /** Unique decision identifier */\n  readonly decisionId: string;\n  /** Human-readable label for the decision */\n  readonly label: string;\n  /** Condition expression source text */\n  readonly condition: string;\n  /** Origin of the decision construct */\n  readonly source: 'effect-flow' | 'raw-if' | 'raw-ternary' | 'raw-short-circuit';\n  /** Branch when condition is true */\n  readonly onTrue: readonly StaticFlowNode[];\n  /** Branch when condition is false (if present) */\n  readonly onFalse?: readonly StaticFlowNode[] | undefined;\n}\n\n/**\n * A single case arm in a switch node.\n */\nexport interface StaticSwitchCase {\n  /** Labels for this case (e.g. string/number literals) */\n  readonly labels: readonly string[];\n  /** Whether this is the default case */\n  readonly isDefault: boolean;\n  /** Body nodes for this case */\n  readonly body: readonly StaticFlowNode[];\n}\n\n/**\n * Switch node for raw `switch` statements and `Step.branch`.\n */\nexport interface StaticSwitchNode extends StaticBaseNode {\n  readonly type: 'switch';\n  /** Optional switch identifier */\n  readonly switchId?: string | undefined;\n  /** Expression being switched on */\n  readonly expression: string;\n  /** Case arms */\n  readonly cases: readonly StaticSwitchCase[];\n  /** Origin of the switch construct */\n  readonly source: 'effect-flow' | 'raw-js';\n  /** Whether a default case is present */\n  readonly hasDefault: boolean;\n  /** Whether any case falls through to the next */\n  readonly hasFallthrough: boolean;\n}\n\n/**\n * Try/catch/finally node for raw exception handling.\n */\nexport interface StaticTryCatchNode extends StaticBaseNode {\n  readonly type: 'try-catch';\n  /** Body of the try block */\n  readonly tryBody: readonly StaticFlowNode[];\n  /** Catch clause variable name */\n  readonly catchVariable?: string | undefined;\n  /** Body of the catch block */\n  readonly catchBody?: readonly StaticFlowNode[] | undefined;\n  /** Body of the finally block */\n  readonly finallyBody?: readonly StaticFlowNode[] | undefined;\n  /** Whether the try body contains a terminal statement (return/throw) */\n  readonly hasTerminalInTry: boolean;\n}\n\n/**\n * Terminal node for `return`, `throw`, `break`, and `continue` statements.\n */\nexport interface StaticTerminalNode extends StaticBaseNode {\n  readonly type: 'terminal';\n  /** Kind of terminal statement */\n  readonly terminalKind: 'return' | 'throw' | 'break' | 'continue';\n  /** Label for labeled break/continue */\n  readonly label?: string | undefined;\n  /** Value expression (e.g. the returned/thrown value) */\n  readonly value?: readonly StaticFlowNode[] | undefined;\n}\n\n/**\n * Opaque node for unsupported or unanalyzable constructs.\n */\nexport interface StaticOpaqueNode extends StaticBaseNode {\n  readonly type: 'opaque';\n  /** Reason why this construct could not be analyzed */\n  readonly reason: string;\n  /** Original source text of the construct */\n  readonly sourceText: string;\n}\n\n/**\n * Cause module operation — construction or inspection of Effect Cause values.\n */\nexport interface StaticCauseNode extends StaticBaseNode {\n  readonly type: 'cause';\n  /** The specific Cause operation */\n  readonly causeOp:\n    | 'fail'\n    | 'die'\n    | 'interrupt'\n    | 'parallel'\n    | 'sequential'\n    | 'empty'\n    | 'failures'\n    | 'defects'\n    | 'interruptors'\n    | 'squash'\n    | 'squashWith'\n    | 'pretty'\n    | 'flatten'\n    | 'isDie'\n    | 'isFailure'\n    | 'isInterrupted'\n    | 'isEmpty'\n    | 'map'\n    | 'filter'\n    | 'other';\n  /** Whether this is a constructor (fail/die/interrupt/parallel/sequential/empty) */\n  readonly isConstructor: boolean;\n  /** For parallel/sequential: child cause nodes (GAP Cause structural traversal). */\n  readonly children?: readonly StaticFlowNode[] | undefined;\n  /** Cause kind classification */\n  readonly causeKind?: 'fail' | 'die' | 'interrupt' | 'mixed' | undefined;\n}\n\n/**\n * Exit module operation — construction or inspection of Effect Exit values.\n */\nexport interface StaticExitNode extends StaticBaseNode {\n  readonly type: 'exit';\n  /** The specific Exit operation */\n  readonly exitOp:\n    | 'succeed'\n    | 'fail'\n    | 'die'\n    | 'interrupt'\n    | 'void'\n    | 'unit'\n    | 'match'\n    | 'isSuccess'\n    | 'isFailure'\n    | 'isInterrupted'\n    | 'when'\n    | 'whenEffect'\n    | 'exists'\n    | 'contains'\n    | 'flatten'\n    | 'map'\n    | 'mapBoth'\n    | 'mapError'\n    | 'flatMap'\n    | 'zipWith'\n    | 'tap'\n    | 'tapBoth'\n    | 'tapError'\n    | 'other';\n  /** Whether this is a constructor (succeed/fail/die/interrupt/void/unit) */\n  readonly isConstructor: boolean;\n}\n\n/**\n * Schedule module operation — construction or composition of Schedule values (GAP 8 dedicated IR).\n */\nexport interface StaticScheduleNode extends StaticBaseNode {\n  readonly type: 'schedule';\n  /** The specific Schedule operation */\n  readonly scheduleOp:\n    | 'exponential'\n    | 'fibonacci'\n    | 'spaced'\n    | 'fixed'\n    | 'linear'\n    | 'cron'\n    | 'windowed'\n    | 'duration'\n    | 'elapsed'\n    | 'delays'\n    | 'once'\n    | 'stop'\n    | 'count'\n    | 'forever'\n    | 'jittered'\n    | 'andThen'\n    | 'intersect'\n    | 'union'\n    | 'compose'\n    | 'zipWith'\n    | 'addDelay'\n    | 'modifyDelay'\n    | 'check'\n    | 'resetAfter'\n    | 'resetWhen'\n    | 'ensure'\n    | 'driver'\n    | 'mapInput'\n    | 'other';\n  /** Decomposed schedule (when parseable from expression text) */\n  readonly scheduleInfo?: ScheduleInfo | undefined;\n}\n\n/**\n * Match module operation (Match.type / Match.when / Match.exhaustive etc.).\n */\nexport interface StaticMatchNode extends StaticBaseNode {\n  readonly type: 'match';\n  /** The specific Match operation */\n  readonly matchOp:\n    | 'type'\n    | 'tag'\n    | 'value'\n    | 'when'\n    | 'whenOr'\n    | 'whenAnd'\n    | 'not'\n    | 'is'\n    | 'exhaustive'\n    | 'orElse'\n    | 'option'\n    | 'either'\n    | 'discriminator'\n    | 'discriminatorsExhaustive'\n    | 'tags'\n    | 'tagsExhaustive'\n    | 'withReturnType'\n    | 'run'\n    | 'other';\n  /** Tag names matched (for Match.tag, Match.when with tag literals, Match.tags) */\n  readonly matchedTags?: readonly string[] | undefined;\n  /** Whether this match arm makes the overall match exhaustive */\n  readonly isExhaustive: boolean;\n}\n\n/**\n * Transformation step in a pipe chain (map, flatMap, andThen, tap, zip, as, etc.).\n * These preserve the Effect channel but transform A, E, or R.\n */\nexport interface StaticTransformNode extends StaticBaseNode {\n  readonly type: 'transform';\n  /** Specific transformation operation */\n  readonly transformType:\n    | 'map'\n    | 'flatMap'\n    | 'andThen'\n    | 'tap'\n    | 'tapBoth'\n    | 'tapError'\n    | 'tapErrorTag'\n    | 'tapErrorCause'\n    | 'tapDefect'\n    | 'zipLeft'\n    | 'zipRight'\n    | 'zipWith'\n    | 'zip'\n    | 'as'\n    | 'asVoid'\n    | 'asSome'\n    | 'asSomeError'\n    | 'flatten'\n    | 'ap'\n    | 'negate'\n    | 'merge'\n    | 'other';\n  /**\n   * Whether this is an effectful transformation\n   * (e.g. flatMap/andThen produce a new Effect, map does not).\n   */\n  readonly isEffectful: boolean;\n  /** The source/input effect (if extractable from args, undefined for curried forms). */\n  readonly source?: StaticFlowNode | undefined;\n  /** The transformation function text (if simple enough to extract). */\n  readonly fn?: string | undefined;\n  /** Input type signature (before transform) */\n  readonly inputType?: EffectTypeSignature | undefined;\n  /** Output type signature (after transform) */\n  readonly outputType?: EffectTypeSignature | undefined;\n}\n\n/**\n * Loop structure (forEach, loop).\n */\nexport interface StaticLoopNode extends StaticBaseNode {\n  readonly type: 'loop';\n  /** Type of loop / collection operation */\n  readonly loopType:\n    | 'forEach'\n    | 'filter'\n    | 'filterMap'\n    | 'partition'\n    | 'reduce'\n    | 'validate'\n    | 'replicate'\n    | 'dropUntil'\n    | 'dropWhile'\n    | 'takeUntil'\n    | 'takeWhile'\n    | 'every'\n    | 'exists'\n    | 'findFirst'\n    | 'head'\n    | 'mergeAll'\n    | 'loop'\n    | 'for'\n    | 'forOf'\n    | 'forIn'\n    | 'while'\n    | 'doWhile';\n  /** The iteration source */\n  readonly iterSource?: string | undefined;\n  /** Body of the loop */\n  readonly body: StaticFlowNode;\n  /** Callback/reducer body summary for higher-order collection APIs */\n  readonly callbackBody?: readonly StaticFlowNode[] | undefined;\n  /** Whether the loop contains an early exit (break/return) */\n  readonly hasEarlyExit?: boolean | undefined;\n  /** Yield expressions in the loop header (e.g. for-of with yield* in initializer) */\n  readonly headerYields?: readonly StaticFlowNode[] | undefined;\n  /** Iteration variable name (for for-of/for-in loops) */\n  readonly iterVariable?: string | undefined;\n}\n\n/**\n * Layer lifecycle (GAP 2).\n */\nexport type LayerLifecycle = 'default' | 'fresh' | 'scoped' | 'memoized';\n\n/**\n * Layer/service provision.\n */\nexport interface StaticLayerNode extends StaticBaseNode {\n  readonly type: 'layer';\n  /** Layer operations */\n  readonly operations: readonly StaticFlowNode[];\n  /** Whether this is a merged layer */\n  readonly isMerged: boolean;\n  /** Service tags this layer provides (GAP 2) */\n  readonly provides?: readonly string[] | undefined;\n  /** Service tags this layer requires (GAP 2) */\n  readonly requires?: readonly string[] | undefined;\n  /** Lifecycle (GAP 2) */\n  readonly lifecycle?: LayerLifecycle | undefined;\n  /** True when this layer is or contains Layer.MemoMap (GAP dedicated memo-map analysis). */\n  readonly isMemoMap?: boolean | undefined;\n}\n\n/**\n * Stream operator in a pipeline (GAP 5).\n */\nexport interface StreamOperatorInfo {\n  readonly operation: string;\n  readonly isEffectful: boolean;\n  /** Callback/transformation body summary for higher-order stream operators */\n  readonly callbackBody?: readonly StaticFlowNode[] | undefined;\n  readonly estimatedCardinality?: 'same' | 'fewer' | 'more' | 'unknown' | undefined;\n  readonly category?:\n    | 'constructor'\n    | 'transform'\n    | 'filter'\n    | 'windowing'\n    | 'merge'\n    | 'broadcasting'\n    | 'halting'\n    | 'text'\n    | 'backpressure'\n    | 'error'\n    | 'resource'\n    | 'context'\n    | 'sink'\n    | 'conversion'\n    | 'channel'\n    | 'other'\n    | undefined;\n  /** Windowing: size for grouped/groupedWithin/sliding (GAP 2 windowing detail). */\n  readonly windowSize?: number | undefined;\n  /** Windowing: stride/step for sliding (GAP 2 windowing detail). */\n  readonly stride?: number | undefined;\n}\n\n/**\n * Stream pipeline (GAP 5).\n */\nexport interface StaticStreamNode extends StaticBaseNode {\n  readonly type: 'stream';\n  readonly source: StaticFlowNode;\n  readonly pipeline: readonly StreamOperatorInfo[];\n  readonly sink?: string | undefined;\n  readonly backpressureStrategy?: 'buffer' | 'drop' | 'sliding' | undefined;\n  /** Classified constructor type when this is a Stream.from* / Stream.make / etc. */\n  readonly constructorType?:\n    | 'fromIterable'\n    | 'fromArray'\n    | 'fromQueue'\n    | 'fromPubSub'\n    | 'fromEffect'\n    | 'fromAsyncIterable'\n    | 'fromReadableStream'\n    | 'fromEventListener'\n    | 'fromSchedule'\n    | 'range'\n    | 'tick'\n    | 'iterate'\n    | 'unfold'\n    | 'make'\n    | 'empty'\n    | 'never'\n    | 'succeed'\n    | 'fail'\n    | 'fromMailbox'\n    | 'fromSubscriptionRef'\n    | 'other'\n    | undefined;\n}\n\n/**\n * Concurrency primitive (Queue, PubSub, Deferred, Semaphore, Mailbox, Latch, FiberSet, FiberMap, FiberHandle, RateLimiter, SubscriptionRef) - GAP 6.\n */\nexport interface StaticConcurrencyPrimitiveNode extends StaticBaseNode {\n  readonly type: 'concurrency-primitive';\n  readonly primitive:\n    | 'queue'\n    | 'pubsub'\n    | 'deferred'\n    | 'semaphore'\n    | 'mailbox'\n    | 'latch'\n    | 'fiberHandle'\n    | 'fiberSet'\n    | 'fiberMap'\n    | 'rateLimiter'\n    | 'cache'\n    | 'scopedCache'\n    | 'rcRef'\n    | 'rcMap'\n    | 'reloadable'\n    | 'subscriptionRef';\n  readonly operation:\n    | 'create'\n    | 'offer'\n    | 'take'\n    | 'takeAll'\n    | 'publish'\n    | 'subscribe'\n    | 'await'\n    | 'succeed'\n    | 'fail'\n    | 'withPermit'\n    | 'run'\n    | 'open'\n    | 'close'\n    | 'release'\n    | 'available'\n    | 'get'\n    | 'set'\n    | 'invalidate'\n    | 'contains'\n    | 'update'\n    | 'reload'\n    | 'end'\n    | 'toStream'\n    | 'changes';\n  readonly strategy?: 'bounded' | 'unbounded' | 'sliding' | 'dropping' | undefined;\n  readonly capacity?: number | undefined;\n  /** For Semaphore take(n) / release(n): permit count when first arg is numeric literal (GAP 13). */\n  readonly permitCount?: number | undefined;\n  readonly source?: StaticFlowNode | undefined;\n  /** Lifecycle options (e.g. FiberHandle.run { onlyIfMissing: true }) */\n  readonly lifecycleOptions?: Record<string, unknown> | undefined;\n}\n\n/**\n * Fiber operation (fork, join, interrupt) - GAP 1.\n */\nexport interface StaticFiberNode extends StaticBaseNode {\n  readonly type: 'fiber';\n  readonly operation:\n    | 'fork'\n    | 'forkScoped'\n    | 'forkDaemon'\n    | 'forkAll'\n    | 'forkIn'\n    | 'forkWithErrorHandler'\n    | 'join'\n    | 'await'\n    | 'interrupt'\n    | 'interruptFork'\n    | 'poll'\n    | 'status'\n    | 'all'\n    | 'awaitAll'\n    | 'children'\n    | 'dump'\n    | 'scoped'\n    | 'inheritAll'\n    | 'map'\n    | 'mapEffect'\n    | 'mapFiber'\n    | 'roots'\n    | 'getCurrentFiber';\n  readonly fiberSource?: StaticFlowNode | undefined;\n  readonly joinPoint?: string | undefined;\n  readonly isScoped: boolean;\n  readonly isDaemon: boolean;\n  /** Scope context: 'safe' when fiber is inside Effect.scoped or after Scope.make */\n  readonly scopeContext?: string | undefined;\n}\n\n/**\n * Interruption region (interruptible/uninterruptible/mask/onInterrupt).\n */\nexport interface StaticInterruptionNode extends StaticBaseNode {\n  readonly type: 'interruption';\n  /** The interruption operation */\n  readonly interruptionType:\n    | 'interrupt'\n    | 'interruptWith'\n    | 'interruptible'\n    | 'uninterruptible'\n    | 'interruptibleMask'\n    | 'uninterruptibleMask'\n    | 'onInterrupt'\n    | 'disconnect'\n    | 'allowInterrupt';\n  /** The wrapped effect (for interruptible/uninterruptible/mask) */\n  readonly source?: StaticFlowNode | undefined;\n  /** The interrupt handler (for onInterrupt) */\n  readonly handler?: StaticFlowNode | undefined;\n}\n\n/**\n * Unknown or unanalyzable code block.\n */\nexport interface StaticUnknownNode extends StaticBaseNode {\n  readonly type: 'unknown';\n  /** Reason why this couldn't be analyzed */\n  readonly reason: string;\n  /** The source code that couldn't be analyzed */\n  readonly sourceCode?: string | undefined;\n}\n\n/** Channel operator or constructor (improve.md §8). */\nexport interface ChannelOperatorInfo {\n  readonly operation: string;\n  readonly category?: 'constructor' | 'transform' | 'pipe' | 'other' | undefined;\n}\n\n/**\n * Channel pipeline node (improve.md §8 dedicated Channel analysis).\n */\nexport interface StaticChannelNode extends StaticBaseNode {\n  readonly type: 'channel';\n  readonly source?: StaticFlowNode | undefined;\n  readonly pipeline: readonly ChannelOperatorInfo[];\n}\n\n/** Sink operator (improve.md §8). */\nexport interface SinkOperatorInfo {\n  readonly operation: string;\n  readonly category?: 'constructor' | 'transform' | 'other' | undefined;\n}\n\n/**\n * Sink pipeline node (improve.md §8 dedicated Sink analysis).\n */\nexport interface StaticSinkNode extends StaticBaseNode {\n  readonly type: 'sink';\n  readonly source?: StaticFlowNode | undefined;\n  readonly pipeline: readonly SinkOperatorInfo[];\n}\n\n/**\n * Union of all static flow node types.\n */\nexport type StaticFlowNode =\n  | StaticEffectNode\n  | StaticGeneratorNode\n  | StaticPipeNode\n  | StaticParallelNode\n  | StaticRaceNode\n  | StaticErrorHandlerNode\n  | StaticRetryNode\n  | StaticTimeoutNode\n  | StaticResourceNode\n  | StaticConditionalNode\n  | StaticLoopNode\n  | StaticCauseNode\n  | StaticExitNode\n  | StaticScheduleNode\n  | StaticMatchNode\n  | StaticTransformNode\n  | StaticLayerNode\n  | StaticStreamNode\n  | StaticChannelNode\n  | StaticSinkNode\n  | StaticConcurrencyPrimitiveNode\n  | StaticFiberNode\n  | StaticInterruptionNode\n  | StaticDecisionNode\n  | StaticSwitchNode\n  | StaticTryCatchNode\n  | StaticTerminalNode\n  | StaticOpaqueNode\n  | StaticUnknownNode;\n\n// =============================================================================\n// Static Effect IR\n// =============================================================================\n\n/**\n * Root node representing the analyzed effect program.\n */\nexport interface StaticEffectProgram extends StaticBaseNode {\n  readonly type: 'program';\n  /** Name of the program (from file name or variable) */\n  readonly programName: string;\n  /** Entry point: gen, direct, pipe, run, workflow-execute, or class */\n  readonly source: 'generator' | 'direct' | 'pipe' | 'run' | 'workflow-execute' | 'class' | 'classProperty' | 'classMethod' | 'functionDeclaration';\n  /** Discovery confidence based on alias/path resolution vs heuristics */\n  readonly discoveryConfidence?: 'high' | 'medium' | 'low';\n  /** Best-effort reason used to classify this as an Effect program */\n  readonly discoveryReason?: string | undefined;\n  /** The root effect nodes */\n  readonly children: readonly StaticFlowNode[];\n  /** Dependencies (services required) */\n  readonly dependencies: readonly DependencyInfo[];\n  /** Error types */\n  readonly errorTypes: readonly string[];\n  /** Full type signature of the program (A, E, R) */\n  readonly typeSignature?: EffectTypeSignature | undefined;\n  /** All service requirements across the program */\n  readonly requiredServices?: ServiceRequirement[] | undefined;\n  /** Description */\n  readonly description?: string | undefined;\n  /** JSDoc description extracted from comments above the program */\n  readonly jsdocDescription?: string | undefined;\n  /** Structured JSDoc tags extracted from comments */\n  readonly jsdocTags?: JSDocTags | undefined;\n}\n\n/**\n * Information about a dependency/service.\n */\nexport interface DependencyInfo {\n  readonly name: string;\n  readonly typeSignature?: string | undefined;\n  readonly isLayer: boolean;\n}\n\n/**\n * Effect Type Signature - A, E, R parameters\n */\nexport interface EffectTypeSignature {\n  /** Success type (A) */\n  readonly successType: string;\n  /** Error type (E) */\n  readonly errorType: string;\n  /** Requirements/Context type (R) */\n  readonly requirementsType: string;\n  /** Whether the type was successfully extracted */\n  readonly isInferred: boolean;\n  /** Confidence level of the type extraction */\n  readonly typeConfidence: 'declared' | 'inferred' | 'unknown';\n  /** Raw type string from TypeScript */\n  readonly rawTypeString?: string;\n  /** TaggedError `_tag` literals for E, when the checker can see them */\n  readonly errorTags?: readonly string[];\n}\n\n/** Stream type args — Stream<A, E, R> (21.3 type extraction) */\nexport interface StreamTypeSignature {\n  readonly successType: string;\n  readonly errorType: string;\n  readonly requirementsType: string;\n  readonly rawTypeString?: string;\n}\n\n/** Layer type args — Layer<ROut, E, RIn> (provides, error, requires) (21.3 type extraction) */\nexport interface LayerTypeSignature {\n  readonly providedType: string;\n  readonly errorType: string;\n  readonly requiredType: string;\n  readonly rawTypeString?: string;\n}\n\n/** Schedule type args — Schedule<Out, In, R> (21.3 type extraction) */\nexport interface ScheduleTypeSignature {\n  readonly outputType: string;\n  readonly inputType: string;\n  readonly requirementsType: string;\n  readonly rawTypeString?: string;\n}\n\n/** Cause type args — Cause<E> (21.3 type extraction) */\nexport interface CauseTypeSignature {\n  readonly errorType: string;\n  readonly rawTypeString?: string;\n}\n\n/**\n * Service requirement extracted from Context type\n */\nexport interface ServiceRequirement {\n  /** Service identifier (tag key) */\n  readonly serviceId: string;\n  /** Service type name */\n  readonly serviceType: string;\n  /** Where this requirement originates */\n  readonly requiredAt: SourceLocation;\n}\n\n// =============================================================================\n// Schema Analysis Types\n// =============================================================================\n\n/**\n * Schema validation path - represents a field that can fail validation\n */\nexport interface SchemaValidationPath {\n  /** Field path (e.g., \"user.email\" or \"items[0].name\") */\n  readonly path: string;\n  /** Schema type at this path */\n  readonly schemaType: string;\n  /** Validation constraints (e.g., minLength, pattern) */\n  readonly constraints: readonly SchemaConstraint[];\n  /** Whether this field is optional */\n  readonly isOptional: boolean;\n  /** Location in source code */\n  readonly location?: SourceLocation | undefined;\n}\n\n/**\n * Schema validation constraint\n */\nexport interface SchemaConstraint {\n  /** Constraint type (e.g., \"minLength\", \"pattern\", \"range\") */\n  readonly type: string;\n  /** Constraint value */\n  readonly value: string | number | boolean;\n  /** Human-readable description */\n  readonly description: string;\n}\n\n/**\n * Schema decode/encode operation analysis\n */\nexport interface SchemaOperation {\n  /** Operation type */\n  readonly operation: 'decode' | 'encode' | 'decodeUnknown' | 'encodeUnknown';\n  /** Schema being used */\n  readonly schemaName: string;\n  /** Source type (encoded) */\n  readonly sourceType: string;\n  /** Target type (decoded) */\n  readonly targetType: string;\n  /** Validation paths that can fail */\n  readonly validationPaths: readonly SchemaValidationPath[];\n  /** Whether error handling is present */\n  readonly hasErrorHandling: boolean;\n  /** Location in source code */\n  readonly location?: SourceLocation | undefined;\n}\n\n/**\n * Schema composition information\n */\nexport interface SchemaComposition {\n  /** Schema name */\n  readonly schemaName: string;\n  /** Composition type */\n  readonly compositionType:\n    | 'struct'\n    | 'union'\n    | 'array'\n    | 'record'\n    | 'tuple'\n    | 'class'\n    | 'recursive'\n    | 'optional'\n    | 'nullable'\n    | 'transform'\n    | 'filter'\n    | 'brand'\n    | 'literal'\n    | 'enum'\n    | 'refinement'\n    | 'datetime'\n    | 'effect-type'\n    | 'serializable';\n  /** Child schemas */\n  readonly children: readonly string[];\n  /** Validation paths */\n  readonly validationPaths: readonly SchemaValidationPath[];\n}\n\n/**\n * Complete Schema analysis result\n */\nexport interface SchemaAnalysis {\n  /** All Schema.decode/encode operations found */\n  readonly operations: readonly SchemaOperation[];\n  /** Schema compositions detected */\n  readonly compositions: readonly SchemaComposition[];\n  /** Missing error handlers for Schema operations */\n  readonly unhandledOperations: readonly SchemaOperation[];\n}\n\n/**\n * Complete static Effect IR.\n */\nexport interface StaticEffectIR {\n  readonly root: StaticEffectProgram;\n  readonly metadata: StaticAnalysisMetadata;\n  readonly references: ReadonlyMap<string, StaticEffectIR>;\n}\n\n/**\n * Service interface shape extracted from Context.Tag / Effect.Service class (GAP service interface tracking).\n */\nexport interface ServiceDefinition {\n  /** Tag/service identifier (class name or tag string). */\n  readonly tagId: string;\n  /** Method names from the service interface type. */\n  readonly methods: readonly string[];\n  /** Property names (non-callable members) from the service interface type. */\n  readonly properties: readonly string[];\n  /** Whether class implements [Equal.symbol] */\n  readonly hasCustomEquality?: boolean | undefined;\n  /** Whether class implements [Hash.symbol] */\n  readonly hasCustomHash?: boolean | undefined;\n}\n\n/**\n * Metadata about the static analysis.\n */\nexport interface StaticAnalysisMetadata {\n  readonly analyzedAt: number;\n  readonly filePath: string;\n  readonly tsVersion?: string | undefined;\n  readonly warnings: readonly AnalysisWarning[];\n  readonly stats: AnalysisStats;\n  /** Service interface shapes (methods/properties) from Context.Tag/Effect.Service in this file. */\n  readonly serviceDefinitions?: readonly ServiceDefinition[] | undefined;\n}\n\n/**\n * Warning generated during analysis.\n */\nexport interface AnalysisWarning {\n  readonly code: string;\n  readonly message: string;\n  readonly location?: SourceLocation | undefined;\n}\n\n/**\n * Statistics about the analysis.\n */\nexport interface AnalysisStats {\n  totalEffects: number;\n  parallelCount: number;\n  raceCount: number;\n  errorHandlerCount: number;\n  retryCount: number;\n  timeoutCount: number;\n  resourceCount: number;\n  loopCount: number;\n  conditionalCount: number;\n  layerCount: number;\n  interruptionCount: number;\n  unknownCount: number;\n  decisionCount: number;\n  switchCount: number;\n  tryCatchCount: number;\n  terminalCount: number;\n  opaqueCount: number;\n}\n\n// =============================================================================\n// Diagram Quality Types\n// =============================================================================\n\nexport type DiagramReadabilityBand = 'good' | 'ok' | 'noisy';\n\nexport interface DiagramQualityMetrics {\n  readonly stepCountDetailed: number;\n  readonly stepCountSummary: number;\n  readonly collapsedGroupsSummary: number;\n  readonly logRatio: number;\n  readonly sideEffectRatio: number;\n  readonly anonymousNodeCount: number;\n  readonly anonymousRatio: number;\n  readonly unknownNodeCount: number;\n  readonly serviceCallCount: number;\n  readonly namedServiceCallRatio: number;\n  readonly pipeChainCount: number;\n  readonly maxPipeChainLength: number;\n}\n\nexport interface DiagramQuality {\n  readonly score: number;\n  readonly band: DiagramReadabilityBand;\n  readonly metrics: DiagramQualityMetrics;\n  readonly reasons: readonly string[];\n  readonly tips: readonly string[];\n}\n\nexport interface DiagramTopOffenderEntry {\n  readonly filePath: string;\n  readonly metricValue: number;\n  readonly tip: string;\n}\n\nexport interface DiagramTopOffendersReport {\n  readonly largestPrograms: readonly DiagramTopOffenderEntry[];\n  readonly mostAnonymousNodes: readonly DiagramTopOffenderEntry[];\n  readonly mostUnknownNodes: readonly DiagramTopOffenderEntry[];\n  readonly highestLogRatio: readonly DiagramTopOffenderEntry[];\n}\n\nexport interface DiagramQualityWithFile {\n  readonly filePath: string;\n  readonly quality: DiagramQuality;\n}\n\n/**\n * Options for the static analyzer.\n */\nexport interface AnalyzerOptions {\n  readonly tsConfigPath?: string | undefined;\n  readonly resolveReferences?: boolean | undefined;\n  readonly maxReferenceDepth?: number | undefined;\n  readonly includeLocations?: boolean | undefined;\n  readonly assumeImported?: boolean | undefined;\n  /** Enable effect-workflow patterns (Workflow.make / Workflow.run). Use the \"effect-workflow\" entrypoint for this. */\n  readonly enableEffectWorkflow?: boolean | undefined;\n  /** Optional path to known Effect internals root; local/relative imports under this path are treated as Effect-like (improve.md §1). */\n  readonly knownEffectInternalsRoot?: string | undefined;\n  /** Optional minimum confidence threshold for discovered programs. */\n  readonly minDiscoveryConfidence?: 'low' | 'medium' | 'high' | undefined;\n  /** When true, only keep discovered programs whose roots are exported (or top-level run statements). */\n  readonly onlyExportedPrograms?: boolean | undefined;\n  /** Enable effect-flow analysis for raw control-flow constructs (if/switch/try-catch/loops). */\n  readonly enableEffectFlow?: boolean | undefined;\n}\n\n// =============================================================================\n// Effect-based Analysis Result\n// =============================================================================\n\n/**\n * Result of static analysis - wrapped in Effect for composability.\n */\nexport type AnalysisResult = Effect.Effect<StaticEffectIR, AnalysisError>;\n\n/**\n * Errors that can occur during analysis.\n */\nexport class AnalysisError extends Error {\n  readonly code: string;\n  readonly location?: SourceLocation | undefined;\n\n  constructor(\n    code: string,\n    message: string,\n    location?: SourceLocation  ,\n  ) {\n    super(message);\n    this.code = code;\n    this.location = location;\n    this.name = 'AnalysisError';\n  }\n}\n\n// =============================================================================\n// Path Analysis Types\n// =============================================================================\n\n/**\n * A single execution path through the effect program.\n */\nexport interface EffectPath {\n  readonly id: string;\n  readonly description: string;\n  readonly steps: readonly PathStepRef[];\n  readonly conditions: readonly PathCondition[];\n  readonly hasLoops: boolean;\n  readonly hasUnresolvedRefs: boolean;\n}\n\n/**\n * Reference to a step in a path.\n */\nexport interface PathStepRef {\n  readonly nodeId: string;\n  readonly name?: string | undefined;\n  readonly repeated: boolean;\n}\n\n/**\n * A condition for a path.\n */\nexport interface PathCondition {\n  readonly expression: string;\n  readonly mustBe: boolean;\n  readonly location?: SourceLocation | undefined;\n}\n\n// =============================================================================\n// Complexity Types\n// =============================================================================\n\n/**\n * Complexity metrics for an effect program.\n */\nexport interface ComplexityMetrics {\n  readonly cyclomaticComplexity: number;\n  readonly pathCount: number | 'unbounded';\n  readonly maxDepth: number;\n  readonly maxParallelBreadth: number;\n  readonly decisionPoints: number;\n  readonly cognitiveComplexity: number;\n}\n\n/**\n * Complexity thresholds.\n */\nexport interface ComplexityThresholds {\n  readonly cyclomaticWarning: number;\n  readonly cyclomaticError: number;\n  readonly pathCountWarning: number;\n  readonly maxDepthWarning: number;\n}\n\n// =============================================================================\n// Test Matrix Types\n// =============================================================================\n\n/**\n * Test coverage matrix.\n */\nexport interface TestMatrix {\n  readonly paths: readonly TestPath[];\n  readonly conditions: readonly TestCondition[];\n  readonly summary: TestMatrixSummary;\n}\n\n/**\n * A path in the test matrix.\n */\nexport interface TestPath {\n  readonly id: string;\n  readonly suggestedTestName: string;\n  readonly description: string;\n  readonly setupConditions: readonly string[];\n  readonly expectedSteps: readonly string[];\n  readonly priority: 'high' | 'medium' | 'low';\n}\n\n/**\n * A condition affecting tests.\n */\nexport interface TestCondition {\n  readonly expression: string;\n  readonly affectedPathsWhenTrue: readonly string[];\n  readonly affectedPathsWhenFalse: readonly string[];\n}\n\n/**\n * Test matrix summary.\n */\nexport interface TestMatrixSummary {\n  readonly totalPaths: number;\n  readonly highPriorityPaths: number;\n  readonly totalConditions: number;\n  readonly minTestsForCoverage: number;\n}\n\n// =============================================================================\n// Type Guards (using Effect Option)\n// =============================================================================\n\nexport const isStaticEffectNode = (\n  node: StaticFlowNode,\n): node is StaticEffectNode => node.type === 'effect';\n\nexport const isStaticGeneratorNode = (\n  node: StaticFlowNode,\n): node is StaticGeneratorNode => node.type === 'generator';\n\nexport const isStaticPipeNode = (\n  node: StaticFlowNode,\n): node is StaticPipeNode => node.type === 'pipe';\n\nexport const isStaticParallelNode = (\n  node: StaticFlowNode,\n): node is StaticParallelNode => node.type === 'parallel';\n\nexport const isStaticRaceNode = (\n  node: StaticFlowNode,\n): node is StaticRaceNode => node.type === 'race';\n\nexport const isStaticErrorHandlerNode = (\n  node: StaticFlowNode,\n): node is StaticErrorHandlerNode => node.type === 'error-handler';\n\nexport const isStaticRetryNode = (\n  node: StaticFlowNode,\n): node is StaticRetryNode => node.type === 'retry';\n\nexport const isStaticTimeoutNode = (\n  node: StaticFlowNode,\n): node is StaticTimeoutNode => node.type === 'timeout';\n\nexport const isStaticResourceNode = (\n  node: StaticFlowNode,\n): node is StaticResourceNode => node.type === 'resource';\n\nexport const isStaticConditionalNode = (\n  node: StaticFlowNode,\n): node is StaticConditionalNode => node.type === 'conditional';\n\nexport const isStaticLoopNode = (\n  node: StaticFlowNode,\n): node is StaticLoopNode => node.type === 'loop';\n\nexport const isStaticLayerNode = (\n  node: StaticFlowNode,\n): node is StaticLayerNode => node.type === 'layer';\n\nexport const isStaticCauseNode = (\n  node: StaticFlowNode,\n): node is StaticCauseNode => node.type === 'cause';\n\nexport const isStaticExitNode = (\n  node: StaticFlowNode,\n): node is StaticExitNode => node.type === 'exit';\n\nexport const isStaticScheduleNode = (\n  node: StaticFlowNode,\n): node is StaticScheduleNode => node.type === 'schedule';\n\nexport const isStaticMatchNode = (\n  node: StaticFlowNode,\n): node is StaticMatchNode => node.type === 'match';\n\nexport const isStaticTransformNode = (\n  node: StaticFlowNode,\n): node is StaticTransformNode => node.type === 'transform';\n\nexport const isStaticStreamNode = (\n  node: StaticFlowNode,\n): node is StaticStreamNode => node.type === 'stream';\n\nexport const isStaticChannelNode = (\n  node: StaticFlowNode,\n): node is StaticChannelNode => node.type === 'channel';\n\nexport const isStaticSinkNode = (\n  node: StaticFlowNode,\n): node is StaticSinkNode => node.type === 'sink';\n\n/**\n * Collect all `StreamOperatorInfo` entries from a stream node, traversing\n * nested `source` links (for curried pipe-style chains not yet flattened).\n */\nexport const collectStreamPipeline = (node: StaticStreamNode): readonly StreamOperatorInfo[] => {\n  const ops: StreamOperatorInfo[] = [];\n  const seen = new Set<string>();\n  let current: StaticFlowNode = node;\n  while (current.type === 'stream') {\n    const s: StaticStreamNode = current;\n    if (seen.has(s.id)) break;\n    seen.add(s.id);\n    // pipeline is already flattened if data-last; just collect\n    ops.unshift(...s.pipeline);\n    current = s.source;\n  }\n  return ops;\n};\n\nexport const isStaticConcurrencyPrimitiveNode = (\n  node: StaticFlowNode,\n): node is StaticConcurrencyPrimitiveNode => node.type === 'concurrency-primitive';\n\nexport const isStaticFiberNode = (\n  node: StaticFlowNode,\n): node is StaticFiberNode => node.type === 'fiber';\n\nexport const isStaticInterruptionNode = (\n  node: StaticFlowNode,\n): node is StaticInterruptionNode => node.type === 'interruption';\n\nexport const isStaticUnknownNode = (\n  node: StaticFlowNode,\n): node is StaticUnknownNode => node.type === 'unknown';\n\nexport const isStaticDecisionNode = (node: StaticFlowNode): node is StaticDecisionNode => node.type === 'decision';\nexport const isStaticSwitchNode = (node: StaticFlowNode): node is StaticSwitchNode => node.type === 'switch';\nexport const isStaticTryCatchNode = (node: StaticFlowNode): node is StaticTryCatchNode => node.type === 'try-catch';\nexport const isStaticTerminalNode = (node: StaticFlowNode): node is StaticTerminalNode => node.type === 'terminal';\nexport const isStaticOpaqueNode = (node: StaticFlowNode): node is StaticOpaqueNode => node.type === 'opaque';\n\n// =============================================================================\n// Output Types\n// =============================================================================\n\n/**\n * Options for JSON output rendering.\n */\nexport interface JSONRenderOptions {\n  readonly pretty: boolean;\n  readonly includeMetadata: boolean;\n  readonly compact: boolean;\n}\n\n/**\n * Style definitions for Mermaid diagram output.\n */\nexport interface MermaidStyles {\n  readonly effect: string;\n  readonly generator: string;\n  readonly pipe: string;\n  readonly parallel: string;\n  readonly race: string;\n  readonly errorHandler: string;\n  readonly retry: string;\n  readonly timeout: string;\n  readonly resource: string;\n  readonly conditional: string;\n  readonly loop: string;\n  readonly layer: string;\n  readonly stream?: string | undefined;\n  readonly concurrencyPrimitive?: string | undefined;\n  readonly fiber?: string | undefined;\n  readonly unknown: string;\n  /** Start node style */\n  readonly start?: string | undefined;\n  /** End node style */\n  readonly end?: string | undefined;\n  /** Decision node style */\n  readonly decision?: string | undefined;\n  /** Switch node style */\n  readonly switch?: string | undefined;\n  /** Try/catch node style */\n  readonly tryCatch?: string | undefined;\n  /** Terminal node style */\n  readonly terminal?: string | undefined;\n  /** Opaque node style */\n  readonly opaque?: string | undefined;\n  /** Cause node style */\n  readonly cause?: string | undefined;\n  /** Exit node style */\n  readonly exit?: string | undefined;\n  /** Schedule node style */\n  readonly schedule?: string | undefined;\n  /** Match node style */\n  readonly match?: string | undefined;\n  /** Transform node style */\n  readonly transform?: string | undefined;\n  /** Channel node style */\n  readonly channel?: string | undefined;\n  /** Sink node style */\n  readonly sink?: string | undefined;\n  /** Interruption node style */\n  readonly interruption?: string | undefined;\n}\n\n/**\n * Options for Mermaid diagram output.\n */\nexport interface MermaidOptions {\n  readonly direction: 'TB' | 'LR' | 'BT' | 'RL';\n  readonly includeIds: boolean;\n  readonly includeDescriptions: boolean;\n  readonly styles: MermaidStyles;\n  readonly compact: boolean;\n  readonly title?: string | undefined;\n  /** Include type signatures (A, E, R) on effect nodes */\n  readonly includeTypeSignatures?: boolean | undefined;\n  /** Wrap parallel/race blocks in subgraphs */\n  readonly useSubgraphs?: boolean | undefined;\n  /** Show condition labels on edges (e.g. true/false for conditionals) */\n  readonly showConditions?: boolean | undefined;\n  /** Level of detail in node labels: compact (callee only), standard (+ variable names), verbose (+ types + roles) */\n  readonly detail?: MermaidDetailLevel | undefined;\n  /** Overlay data-flow variable annotations on edges and warning classes on nodes */\n  readonly dataFlowOverlay?: boolean | undefined;\n  /** Overlay error-flow annotations (error types, unhandled errors) on nodes */\n  readonly errorFlowOverlay?: boolean | undefined;\n}\n\n/**\n * Get children of a node as an Option.\n * Accepts StaticFlowNode or StaticEffectProgram (root) so that walking from ir.root works.\n */\nexport const getStaticChildren = (\n  node: StaticFlowNode | StaticEffectProgram,\n): Option.Option<readonly StaticFlowNode[]> => {\n  switch (node.type) {\n    case 'program':\n      return Option.some(node.children);\n    case 'generator':\n      return Option.some(node.yields.map((y) => y.effect));\n    case 'pipe':\n      return Option.some([node.initial, ...node.transformations]);\n    case 'parallel':\n    case 'race':\n      return Option.some([...node.children]);\n    case 'error-handler':\n      return Option.some(\n        node.handler ? [node.source, node.handler] : [node.source],\n      );\n    case 'retry': {\n      const retryNode = node;\n      const list = ([retryNode.source, retryNode.scheduleNode] as (StaticFlowNode | undefined)[]).filter(\n        (n): n is StaticFlowNode => n !== undefined,\n      );\n      return list.length > 0 ? Option.some(list) : Option.none();\n    }\n    case 'timeout': {\n      const src = node.source as StaticFlowNode | undefined;\n      return src ? Option.some([src]) : Option.none();\n    }\n    case 'resource':\n      return Option.some(\n        node.use\n          ? [node.acquire, node.release, node.use]\n          : [node.acquire, node.release],\n      );\n    case 'conditional':\n      return Option.some(\n        node.onFalse ? [node.onTrue, node.onFalse] : [node.onTrue],\n      );\n    case 'loop':\n      return Option.some([node.body]);\n    case 'cause':\n      return node.children && node.children.length > 0\n        ? Option.some(node.children)\n        : Option.none();\n    case 'exit':\n    case 'schedule':\n    case 'match':\n      return Option.none();\n    case 'transform':\n      return node.source ? Option.some([node.source]) : Option.none();\n    case 'layer':\n      return Option.some([...node.operations]);\n    case 'stream':\n      return Option.some([node.source]);\n    case 'channel':\n      return node.source ? Option.some([node.source]) : Option.none();\n    case 'sink':\n      return node.source ? Option.some([node.source]) : Option.none();\n    case 'concurrency-primitive':\n      return node.source ? Option.some([node.source]) : Option.none();\n    case 'fiber':\n      return node.fiberSource ? Option.some([node.fiberSource]) : Option.none();\n    case 'interruption': {\n      const children: StaticFlowNode[] = [];\n      if (node.source) children.push(node.source);\n      if (node.handler) children.push(node.handler);\n      return children.length > 0 ? Option.some(children) : Option.none();\n    }\n    case 'effect':\n      return node.callbackBody && node.callbackBody.length > 0\n        ? Option.some([...node.callbackBody])\n        : Option.none();\n    case 'decision':\n      return Option.some([...node.onTrue, ...(node.onFalse ?? [])]);\n    case 'switch':\n      return Option.some(node.cases.flatMap(c => [...c.body]));\n    case 'try-catch':\n      return Option.some([...node.tryBody, ...(node.catchBody ?? []), ...(node.finallyBody ?? [])]);\n    case 'terminal':\n      return node.value ? Option.some([...node.value]) : Option.none();\n    case 'opaque':\n      return Option.none();\n    default:\n      return Option.none();\n  }\n};\n\n// =============================================================================\n// Service Artifact Types (whole-codebase service mapping)\n// =============================================================================\n\n/**\n * A layer implementation that provides a service.\n */\nexport interface LayerImplementation {\n  /** Name of the layer variable (e.g. 'UserRepoLive') */\n  readonly name: string;\n  /** File where the layer is defined */\n  readonly filePath: string;\n  /** Source location of the layer definition */\n  readonly location: SourceLocation;\n  /** Layer kind */\n  readonly kind: 'effect' | 'succeed' | 'sync' | 'scoped' | 'other';\n  /** Services required by this layer implementation */\n  readonly requires: readonly string[];\n  /** IR of the layer's implementation body (if analyzable) */\n  readonly bodyIR?: StaticEffectIR | undefined;\n}\n\n/**\n * A reference to a program that consumes a service.\n */\nexport interface ServiceConsumerRef {\n  /** Program name that uses this service */\n  readonly programName: string;\n  /** File containing the program */\n  readonly filePath: string;\n  /** Location of the yield* call */\n  readonly location?: SourceLocation | undefined;\n}\n\n/**\n * First-class artifact for an Effect service, deduplicated at the project level.\n */\nexport interface ServiceArtifact {\n  /** Unique service identifier (tag string, e.g. 'UserRepo') */\n  readonly serviceId: string;\n  /** Class name (may differ from serviceId if tag string differs) */\n  readonly className: string;\n  /** File where the service tag class is defined */\n  readonly definitionFilePath: string;\n  /** Source location of the class declaration */\n  readonly definitionLocation: SourceLocation;\n  /** Interface shape (methods, properties) */\n  readonly definition: ServiceDefinition;\n  /** Full type text of the service interface */\n  readonly interfaceTypeText?: string | undefined;\n  /** Layer implementations that provide this service */\n  readonly layerImplementations: readonly LayerImplementation[];\n  /** Programs that consume (yield*) this service */\n  readonly consumers: readonly ServiceConsumerRef[];\n  /** Services this service's layers depend on (transitive requirements) */\n  readonly dependencies: readonly string[];\n}\n\n/**\n * Project-level deduplicated service map.\n */\nexport interface ProjectServiceMap {\n  /** Map from serviceId to its artifact */\n  readonly services: ReadonlyMap<string, ServiceArtifact>;\n  /** Services referenced but with no tag definition found */\n  readonly unresolvedServices: readonly string[];\n  /** Topological order of services (leaves first) */\n  readonly topologicalOrder: readonly string[];\n}\n\n// =============================================================================\n// Showcase Types\n// =============================================================================\n\nexport interface ShowcaseStepDetail {\n  readonly stepId: string;\n  readonly name: string;\n  readonly callee: string;\n  // Output type\n  readonly outputType: string;\n  readonly outputTypeKind: 'declared' | 'inferred' | 'unknown';\n  readonly outputTypeDisplay: string;\n  readonly outputTypeText: string;\n  // Error type\n  readonly errorTypeDisplay: string;\n  readonly errors: readonly string[];\n  // Dependency\n  readonly depSource?: string | undefined;\n  // Step kind\n  readonly stepKind?: string | undefined;\n  // Retry/timeout/resource/loop context (optional)\n  readonly retry?: { readonly attempts: number | 'unlimited'; readonly backoff: string } | undefined;\n  readonly timeout?: { readonly ms: string } | undefined;\n  readonly kind?: 'resource' | undefined;\n  readonly acquire?: string | undefined;\n  readonly use?: string | undefined;\n  readonly release?: string | undefined;\n  readonly repeats?: 'loop' | undefined;\n  readonly loopType?: string | undefined;\n  readonly iterationSource?: string | undefined;\n}\n\nexport interface ShowcaseEntry {\n  readonly title: string;\n  readonly code: string;\n  readonly mermaid: string;\n  readonly stepDetails: readonly ShowcaseStepDetail[];\n}\n","/**\n * Static Effect Analyzer\n *\n * Uses ts-morph to walk the TypeScript AST and extract Effect structure\n * without executing the code. Built entirely with Effect for composability.\n *\n * Public API: analyzeEffectFile, analyzeEffectSource, resetIdCounter.\n * Implementation is split across analysis-utils, analysis-patterns, alias-resolution,\n * program-discovery, effect-analysis, and core-analysis.\n */\n\nimport { Effect } from 'effect';\nimport {\n  loadTsMorph,\n  createProject,\n  createProjectFromSource,\n} from './ts-morph-loader';\nimport { AnalysisError } from './types';\nimport type { StaticEffectIR, AnalyzerOptions } from './types';\nimport { DEFAULT_OPTIONS, isJsOrJsxPath } from './analysis-utils';\nimport { findEffectPrograms } from './program-discovery';\nimport { analyzeProgram } from './core-analysis';\n\nexport { resetIdCounter } from './analysis-utils';\n\nexport const analyzeEffectFile = (\n  filePath: string,\n  options?: AnalyzerOptions,\n): Effect.Effect<readonly StaticEffectIR[], AnalysisError> =>\n  Effect.gen(function* () {\n    const opts = { ...DEFAULT_OPTIONS, ...options };\n    const { ts, Project } = loadTsMorph();\n\n    const project = yield* Effect.try({\n      try: () => {\n        if (isJsOrJsxPath(filePath)) {\n          return new Project({\n            skipAddingFilesFromTsConfig: true,\n            compilerOptions: { allowJs: true },\n          });\n        }\n        return createProject(opts.tsConfigPath);\n      },\n      catch: (error) =>\n        new AnalysisError(\n          'PROJECT_CREATION_FAILED',\n          `Failed to create project: ${String(error)}`,\n        ),\n    });\n\n    const existingFile = project.getSourceFile(filePath);\n    if (existingFile) {\n      project.removeSourceFile(existingFile);\n    }\n\n    const sourceFile = yield* Effect.try({\n      try: () => project.addSourceFileAtPath(filePath),\n      catch: (error) =>\n        new AnalysisError(\n          'FILE_NOT_FOUND',\n          `Failed to load file ${filePath}: ${String(error)}`,\n        ),\n    });\n\n    const programs = findEffectPrograms(sourceFile, opts);\n\n    if (programs.length === 0) {\n      return yield* Effect.fail(\n        new AnalysisError(\n          'NO_EFFECTS_FOUND',\n          `No Effect programs found in ${filePath}`,\n        ),\n      );\n    }\n\n    return yield* Effect.forEach(\n      programs,\n      (program) =>\n        analyzeProgram(program, sourceFile, filePath, opts, ts.version),\n      { concurrency: 'unbounded' },\n    );\n  });\n\nexport const analyzeEffectSource = (\n  code: string,\n  filePath = 'temp.ts',\n  options?: AnalyzerOptions,\n): Effect.Effect<readonly StaticEffectIR[], AnalysisError> =>\n  Effect.gen(function* () {\n    const opts = { ...DEFAULT_OPTIONS, ...options };\n    const { ts } = loadTsMorph();\n\n    const sourceFile = yield* Effect.try({\n      try: () => createProjectFromSource(code, filePath),\n      catch: (error) =>\n        new AnalysisError(\n          'SOURCE_PARSE_FAILED',\n          `Failed to parse source: ${String(error)}`,\n        ),\n    });\n\n    const programs = findEffectPrograms(sourceFile, opts);\n\n    if (programs.length === 0) {\n      return yield* Effect.fail(\n        new AnalysisError(\n          'NO_EFFECTS_FOUND',\n          `No Effect programs found in source`,\n        ),\n      );\n    }\n\n    return yield* Effect.forEach(\n      programs,\n      (program) =>\n        analyzeProgram(program, sourceFile, filePath, opts, ts.version),\n      { concurrency: 'unbounded' },\n    );\n  });\n","/**\n * Shared utilities for static Effect analysis: options, ID generation,\n * location/JSDoc extraction, dependency/error aggregation, program naming.\n */\n\nimport type {\n  Node,\n  VariableDeclaration,\n  PropertyAssignment,\n  CallExpression,\n  FunctionDeclaration,\n  ClassDeclaration,\n  PropertyDeclaration,\n  MethodDeclaration,\n  GetAccessorDeclaration,\n} from 'ts-morph';\nimport { Option } from 'effect';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  AnalysisStats,\n  AnalyzerOptions,\n  DependencyInfo,\n  JSDocTags,\n  SemanticRole,\n  SourceLocation,\n  StaticFlowNode,\n} from './types';\nimport { getStaticChildren } from './types';\nimport { splitTopLevelUnion } from './type-extractor';\nimport { KNOWN_EFFECT_NAMESPACES, BUILT_IN_TYPE_NAMES } from './analysis-patterns';\n\nconst EFFECT_RUNTIME_PRIMITIVE_NAMES = new Set([\n  'Ref',\n  'SynchronizedRef',\n  'FiberRef',\n  'TxRef',\n  'TRef',\n  'Queue',\n  'TQueue',\n  'TxQueue',\n  'PubSub',\n  'TPubSub',\n  'Deferred',\n  'TDeferred',\n  'Semaphore',\n  'TSemaphore',\n  'SubscriptionRef',\n  'Mailbox',\n]);\n\nconst isRuntimePrimitiveDependency = (name: string): boolean => {\n  const firstSegment = name.split('.')[0] ?? name;\n  return EFFECT_RUNTIME_PRIMITIVE_NAMES.has(firstSegment);\n};\n\nconst CANONICAL_EFFECT_SERVICE_NAMES = new Map<string, string>([\n  ['FileSystem', 'FileSystem.FileSystem'],\n  ['Path', 'Path.Path'],\n  ['Terminal', 'Terminal.Terminal'],\n  ['Clock', 'Clock.Clock'],\n  ['Random', 'Random.Random'],\n  ['Console', 'Console.Console'],\n  ['Scope', 'Scope.Scope'],\n]);\n\nexport const canonicalizeServiceDisplayName = (name: string): string =>\n  CANONICAL_EFFECT_SERVICE_NAMES.get(name) ?? name;\n\n// =============================================================================\n// Default Options\n// =============================================================================\n\nexport const DEFAULT_OPTIONS: Required<AnalyzerOptions> = {\n  tsConfigPath: './tsconfig.json',\n  resolveReferences: true,\n  maxReferenceDepth: 5,\n  includeLocations: true,\n  assumeImported: false,\n  enableEffectWorkflow: false,\n  knownEffectInternalsRoot: undefined,\n  minDiscoveryConfidence: 'low',\n  onlyExportedPrograms: false,\n  enableEffectFlow: false,\n};\n\n// =============================================================================\n// ID Generation\n// =============================================================================\n\nlet idCounter = 0;\n\nexport const resetIdCounter = (): void => {\n  idCounter = 0;\n};\n\nexport const generateId = (): string => `effect-${++idCounter}`;\n\n// =============================================================================\n// Node text cache (reduce repeated getText() on large nodes - improve.md §7)\n// =============================================================================\n\nconst nodeTextCache = new WeakMap<Node, string>();\n\nexport function getNodeText(node: Node): string {\n  let text = nodeTextCache.get(node);\n  if (text === undefined) {\n    text = node.getText();\n    nodeTextCache.set(node, text);\n  }\n  return text;\n}\n\n// =============================================================================\n// Program-level aggregation (dependencies, error types)\n// =============================================================================\n\nexport function collectErrorTypes(nodes: readonly StaticFlowNode[]): string[] {\n  const set = new Set<string>();\n  const visit = (list: readonly StaticFlowNode[]) => {\n    for (const node of list) {\n      if (node.type === 'effect') {\n        const err = node.typeSignature?.errorType?.trim();\n        if (err && err !== 'never') {\n          for (const part of splitTopLevelUnion(err)) {\n            set.add(part);\n          }\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) visit(children);\n    }\n  };\n  visit(nodes);\n  return Array.from(set).sort();\n}\n\nexport function collectDependencies(nodes: readonly StaticFlowNode[]): DependencyInfo[] {\n  const byName = new Map<string, DependencyInfo>();\n  const visit = (list: readonly StaticFlowNode[]) => {\n    for (const node of list) {\n      if (node.type === 'effect') {\n        const reqs = (node).requiredServices;\n        if (reqs) {\n          for (const r of reqs) {\n            if (isRuntimePrimitiveDependency(r.serviceId)) continue;\n            const displayName = canonicalizeServiceDisplayName(r.serviceId);\n            if (!byName.has(displayName)) {\n              byName.set(displayName, {\n                name: displayName,\n                typeSignature: r.serviceType,\n                isLayer: false,\n              });\n            }\n          }\n        }\n\n        // Also collect from environment/service yields (yield* ServiceTag pattern)\n        // Include both 'environment' role and service-like callees (e.g., FileSystem.FileSystem, Config.string)\n        if ((node.semanticRole === 'environment' || node.semanticRole === 'side-effect') && node.callee) {\n          const callee = node.callee;\n          // Heuristic: service tags typically start with uppercase or are dotted identifiers like FileSystem.FileSystem\n          // Skip known Effect/JS namespaces and built-in types\n          const firstSegment = callee.split('.')[0] ?? callee;\n          const looksLikeService = /^[A-Z]/.test(callee)\n            && !KNOWN_EFFECT_NAMESPACES.has(firstSegment)\n            && !BUILT_IN_TYPE_NAMES.has(firstSegment);\n          if (isRuntimePrimitiveDependency(callee)) continue;\n          const displayName = canonicalizeServiceDisplayName(callee);\n          if (looksLikeService && !byName.has(displayName)) {\n            byName.set(displayName, {\n              name: displayName,\n              typeSignature: node.typeSignature?.requirementsType,\n              isLayer: false,\n            });\n          }\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) visit(children);\n    }\n  };\n  visit(nodes);\n  return Array.from(byName.values());\n}\n\n// =============================================================================\n// Source Location Extraction\n// =============================================================================\n\nexport const extractLocation = (\n  node: Node,\n  filePath: string,\n  includeLocations: boolean,\n): SourceLocation | undefined => {\n  if (!includeLocations) {\n    return undefined;\n  }\n\n  const sourceFile = node.getSourceFile();\n  const pos = node.getStart();\n  const { line, column } = sourceFile.getLineAndColumnAtPos(pos);\n  const endPos = node.getEnd();\n  const end = sourceFile.getLineAndColumnAtPos(endPos);\n\n  return {\n    filePath,\n    line,\n    column,\n    endLine: end.line,\n    endColumn: end.column,\n    offset: pos,\n    endOffset: endPos,\n  };\n};\n\n// =============================================================================\n// JSDoc Extraction\n// =============================================================================\n\n/**\n * Extract JSDoc description from a node.\n * Uses ts-morph's getJsDocs() method with fallback to leading comment ranges.\n * Extracts only the description text (before first @tag).\n */\nexport const extractJSDocDescription = (node: Node): string | undefined => {\n  // Try to get JSDoc from the node directly using ts-morph\n  const jsDocs = (\n    node as unknown as {\n      getJsDocs?: () => {\n        getText: () => string;\n        getComment?: () => string | { text: string }[];\n      }[];\n    }\n  ).getJsDocs?.();\n\n  if (jsDocs && jsDocs.length > 0) {\n    const firstJsDoc = jsDocs[0];\n    if (!firstJsDoc) return undefined;\n    const comment = firstJsDoc.getComment?.();\n\n    if (comment) {\n      // Handle both string and array comment formats\n      let description: string;\n      if (typeof comment === 'string') {\n        description = comment;\n      } else if (Array.isArray(comment)) {\n        description = comment.map((c) => c.text).join('\\n');\n      } else {\n        return undefined;\n      }\n\n      // Extract only the description (before first @tag)\n      const tagIndex = description.search(/\\n\\s*@/);\n      if (tagIndex !== -1) {\n        description = description.substring(0, tagIndex);\n      }\n\n      return description.trim() || undefined;\n    }\n\n    // Fallback to parsing the raw JSDoc text\n    const rawText = firstJsDoc.getText();\n    const descriptionMatch = /\\/\\*\\*\\s*\\n?\\s*\\*\\s*([^@]*?)(?=\\n\\s*\\*\\s*@|\\*\\/)/.exec(rawText);\n    if (descriptionMatch?.[1]) {\n      return (\n        descriptionMatch[1].replace(/\\n\\s*\\*\\s*/g, ' ').trim() || undefined\n      );\n    }\n  }\n\n  // Fallback: use leading comment ranges\n  const leadingComments = node.getLeadingCommentRanges();\n  if (leadingComments.length > 0) {\n    const lastComment = leadingComments[leadingComments.length - 1];\n    if (!lastComment) return undefined;\n\n    const commentText = lastComment.getText();\n\n    // Check if it's a JSDoc comment\n    if (commentText.startsWith('/**')) {\n      // Remove /** and */ and * prefixes\n      const cleaned = commentText\n        .replace(/^\\/\\*\\*\\s*/, '')\n        .replace(/\\s*\\*\\/\\s*$/, '')\n        .replace(/^\\s*\\*\\s?/gm, '')\n        .trim();\n\n      // Extract only the description (before first @tag)\n      const tagIndex = cleaned.search(/\\n@/);\n      if (tagIndex !== -1) {\n        return cleaned.substring(0, tagIndex).trim() || undefined;\n      }\n\n      return cleaned || undefined;\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Extract structured JSDoc tags (@param, @returns, @throws, @example) from a node.\n * Returns undefined if no structured tags are present.\n */\nexport const extractJSDocTags = (node: Node): JSDocTags | undefined => {\n  const tryGetJsDocText = (n: Node): string | undefined => {\n    const jsDocs = (\n      n as unknown as {\n        getJsDocs?: () => { getText: () => string }[];\n      }\n    ).getJsDocs?.();\n    if (jsDocs && jsDocs.length > 0) {\n      return jsDocs[0]!.getText();\n    }\n    // Fallback: leading comment ranges\n    const leadingComments = n.getLeadingCommentRanges();\n    if (leadingComments.length > 0) {\n      const lastComment = leadingComments[leadingComments.length - 1];\n      if (lastComment) {\n        const commentText = lastComment.getText();\n        if (commentText.startsWith('/**')) return commentText;\n      }\n    }\n    return undefined;\n  };\n\n  // Try the node itself first\n  let text = tryGetJsDocText(node);\n\n  // Walk up to find JSDoc on parent statement (same logic as getJSDocFromParentVariable)\n  if (!text) {\n    const { SyntaxKind } = loadTsMorph();\n    let current = node.getParent();\n    // Walk through CallExpression → ArrowFunction → VariableDeclaration → VariableDeclarationList → VariableStatement\n    while (current && !text) {\n      const kind = current.getKind();\n      if (kind === SyntaxKind.VariableStatement) {\n        text = tryGetJsDocText(current);\n        break;\n      }\n      if (kind === SyntaxKind.VariableDeclarationList) {\n        const grandparent = current.getParent();\n        if (grandparent) {\n          text = tryGetJsDocText(grandparent);\n        }\n        break;\n      }\n      // Keep walking up through CallExpression, ArrowFunction, VariableDeclaration\n      if (\n        kind === SyntaxKind.CallExpression ||\n        kind === SyntaxKind.ArrowFunction ||\n        kind === SyntaxKind.VariableDeclaration ||\n        kind === SyntaxKind.ParenthesizedExpression\n      ) {\n        current = current.getParent();\n      } else {\n        break;\n      }\n    }\n  }\n\n  if (!text) return undefined;\n  return parseJSDocTags(text);\n};\n\nfunction parseJSDocTags(rawText: string): JSDocTags | undefined {\n  const cleaned = rawText\n    .replace(/^\\/\\*\\*/, '')\n    .replace(/\\*\\/$/, '')\n    .split('\\n')\n    .map(line => line.replace(/^\\s*\\*\\s?/, ''))\n    .join('\\n');\n\n  const params: { name: string; description?: string }[] = [];\n  let returns: string | undefined;\n  const throws: string[] = [];\n  let example: string | undefined;\n\n  const tagPattern = /@(param|returns?|throws?|exception|example)\\s*(.*)/gi;\n  let match: RegExpExecArray | null;\n\n  while ((match = tagPattern.exec(cleaned)) !== null) {\n    const tag = match[1]!.toLowerCase();\n    const rest = match[2]!.trim();\n\n    if (tag === 'param') {\n      const paramMatch =\n        /^(?:\\{[^}]*\\}\\s*)?(\\[?\\w+(?:=[^\\]]*)?]?)\\s*(?:-\\s*(.*))?$/.exec(rest);\n      if (paramMatch) {\n        const name = paramMatch[1]!.replace(/^\\[|\\]$/g, '').replace(/=.*/, '');\n        const description = paramMatch[2]?.trim();\n        params.push(description ? { name, description } : { name });\n      }\n    } else if (tag === 'returns' || tag === 'return') {\n      returns = rest.replace(/^\\{[^}]*\\}\\s*/, '').trim() || undefined;\n    } else if (tag === 'throws' || tag === 'throw' || tag === 'exception') {\n      const value = rest.replace(/^\\{[^}]*\\}\\s*/, '').trim();\n      if (value) throws.push(value);\n    } else if (tag === 'example') {\n      // @example may span multiple lines until next @tag or end of comment\n      const exampleStart = match.index + match[0].length;\n      const nextTagMatch = /\\n\\s*@\\w/.exec(cleaned.slice(exampleStart));\n      if (nextTagMatch) {\n        const block = cleaned.slice(match.index + match[0].length - rest.length, exampleStart + nextTagMatch.index);\n        example = block.trim() || undefined;\n      } else {\n        const block = cleaned.slice(match.index + match[0].length - rest.length);\n        example = block.trim() || undefined;\n      }\n    }\n  }\n\n  if (params.length === 0 && !returns && throws.length === 0 && !example) {\n    return undefined;\n  }\n\n  return { params, returns, throws, example };\n}\n\n/**\n * Get JSDoc description from the parent variable declaration of a node.\n * Used to extract program-level JSDoc from the variable above an Effect program.\n */\nexport const getJSDocFromParentVariable = (node: Node): string | undefined => {\n  const parent = node.getParent();\n  const { SyntaxKind } = loadTsMorph();\n\n  if (parent) {\n    const parentKind = parent.getKind();\n\n    if (parentKind === SyntaxKind.VariableDeclaration) {\n      return extractJSDocDescription(parent);\n    }\n\n    // Check for arrow function assignment\n    if (parentKind === SyntaxKind.ArrowFunction) {\n      const grandparent = parent.getParent();\n      if (grandparent?.getKind() === SyntaxKind.VariableDeclaration) {\n        return extractJSDocDescription(grandparent);\n      }\n    }\n  }\n\n  return undefined;\n};\n\n// =============================================================================\n// Path / file helpers\n// =============================================================================\n\n/** Gap 6: .js/.jsx need allowJs and a minimal project so tsconfig does not exclude them. */\nexport function isJsOrJsxPath(path: string): boolean {\n  return path.endsWith('.js') || path.endsWith('.jsx');\n}\n\n// =============================================================================\n// EffectProgram type (used by program-discovery and core-analysis)\n// =============================================================================\n\nexport interface EffectProgram {\n  readonly name: string;\n  readonly discoveryConfidence?: 'high' | 'medium' | 'low';\n  readonly discoveryReason?: string;\n  readonly node: CallExpression | FunctionDeclaration | VariableDeclaration | ClassDeclaration\n    | PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration;\n  readonly type: 'generator' | 'direct' | 'pipe' | 'run' | 'workflow-execute' | 'class' | 'classProperty' | 'classMethod' | 'functionDeclaration';\n}\n\n// =============================================================================\n// Program / yield name extraction\n// =============================================================================\n\nexport const extractYieldVariableName = (yieldNode: Node): string | undefined => {\n  const parent = yieldNode.getParent();\n  const { SyntaxKind } = loadTsMorph();\n\n  if (parent?.getKind() === SyntaxKind.VariableDeclaration) {\n    return (parent as VariableDeclaration).getName();\n  }\n\n  return undefined;\n};\n\nexport const extractProgramName = (node: Node): string | undefined => {\n  const { SyntaxKind } = loadTsMorph();\n  const getEnclosingVariableName = (start: Node): string | undefined => {\n    let current: Node | undefined = start;\n    while (current !== undefined) {\n      if (current.getKind() === SyntaxKind.VariableDeclaration) {\n        return (current as VariableDeclaration).getName();\n      }\n      current = current.getParent();\n    }\n    return undefined;\n  };\n\n  // Try to find the variable name this is assigned to\n  const parent = node.getParent();\n  if (parent) {\n    const parentKind = parent.getKind();\n\n    if (parentKind === SyntaxKind.VariableDeclaration) {\n      return (parent as VariableDeclaration).getName();\n    }\n\n    if (parentKind === SyntaxKind.AwaitExpression) {\n      const grandparent = parent.getParent();\n      if (grandparent?.getKind() === SyntaxKind.VariableDeclaration) {\n        return (grandparent as VariableDeclaration).getName();\n      }\n    }\n\n    if (parentKind === SyntaxKind.PropertyAssignment) {\n      const property = parent as PropertyAssignment;\n      const propertyName = property.getName();\n      const containerName = getEnclosingVariableName(parent);\n      return containerName ? `${containerName}.${propertyName}` : propertyName;\n    }\n\n    // Check for arrow function assignment\n    if (parentKind === SyntaxKind.ArrowFunction) {\n      const grandparent = parent.getParent();\n      if (grandparent?.getKind() === SyntaxKind.VariableDeclaration) {\n        return (grandparent as VariableDeclaration).getName();\n      }\n      if (grandparent?.getKind() === SyntaxKind.PropertyAssignment) {\n        const property = grandparent as PropertyAssignment;\n        const propertyName = property.getName();\n        const containerName = getEnclosingVariableName(grandparent);\n        return containerName ? `${containerName}.${propertyName}` : propertyName;\n      }\n    }\n  }\n\n  // Walk further up through DIRECT wrappers (CallExpression, ArrowFunction, FunctionExpression)\n  // Stop at function boundaries we're not an argument of\n  let ancestor: Node | undefined = node;\n  for (let depth = 0; ancestor && depth < 6; depth++) {\n    ancestor = ancestor.getParent();\n    if (!ancestor) break;\n\n    const kind = ancestor.getKind();\n\n    // Found a named container — use it\n    if (kind === SyntaxKind.VariableDeclaration) {\n      return (ancestor as VariableDeclaration).getName();\n    }\n\n    if (kind === SyntaxKind.PropertyAssignment) {\n      const property = ancestor as PropertyAssignment;\n      const propertyName = property.getName();\n      const containerName = getEnclosingVariableName(ancestor);\n      return containerName ? `${containerName}.${propertyName}` : propertyName;\n    }\n\n    // Stop walking up at Block/SourceFile — we've left the expression context\n    if (kind === SyntaxKind.Block || kind === SyntaxKind.SourceFile) break;\n  }\n\n  return undefined;\n};\n\n/**\n * Walk up the AST from a node to find an enclosing Effect.fn(\"name\") call.\n * Returns the name string if found, e.g., for Effect.gen inside Effect.fn(\"getUser\").\n */\nexport const extractEnclosingEffectFnName = (node: Node): string | undefined => {\n  const { SyntaxKind } = loadTsMorph();\n  let current: Node | undefined = node.getParent();\n  for (let depth = 0; current && depth < 10; depth++) {\n    if (current.getKind() === SyntaxKind.CallExpression) {\n      const callExpr = current as CallExpression;\n      const exprText = callExpr.getExpression().getText();\n      if (exprText === 'Effect.fn' || exprText.endsWith('.fn')) {\n        const args = callExpr.getArguments();\n        if (args.length > 0) {\n          const firstArg = args[0]!.getText();\n          // Extract string literal: \"name\" or 'name'\n          const match = /^[\"'](.+)[\"']$/.exec(firstArg);\n          if (match?.[1]) return match[1];\n        }\n      }\n    }\n    current = current.getParent();\n  }\n  return undefined;\n};\n\n// =============================================================================\n// Stats Helper\n// =============================================================================\n\nexport const createEmptyStats = (): AnalysisStats => ({\n  totalEffects: 0,\n  parallelCount: 0,\n  raceCount: 0,\n  errorHandlerCount: 0,\n  retryCount: 0,\n  timeoutCount: 0,\n  resourceCount: 0,\n  loopCount: 0,\n  conditionalCount: 0,\n  layerCount: 0,\n  interruptionCount: 0,\n  unknownCount: 0,\n  decisionCount: 0,\n  switchCount: 0,\n  tryCatchCount: 0,\n  terminalCount: 0,\n  opaqueCount: 0,\n});\n\n// =============================================================================\n// Display Name & Semantic Role Computation\n// =============================================================================\n\n/** Default max length for user-visible labels (diagrams, explain, IR display names). */\nexport const DEFAULT_LABEL_MAX = 60;\n\n/**\n * Truncate a string to `max` characters, appending an ellipsis if truncated.\n * Use for any user-facing label in output renderers.\n */\nexport function truncateDisplayText(s: string, max: number = DEFAULT_LABEL_MAX): string {\n  return s.length <= max ? s : `${s.slice(0, max)}…`;\n}\n\nconst truncate = truncateDisplayText;\n\n/**\n * Escape a label for a Mermaid node. Labels come from source text that may wrap\n * across lines, so whitespace runs collapse to a single space.\n */\nexport function escapeMermaidLabel(text: string): string {\n  return text\n    .replace(/\\s+/g, ' ')\n    .replace(/\"/g, '#quot;')\n    .replace(/</g, '#lt;')\n    .replace(/>/g, '#gt;')\n    .replace(/\\(/g, '#lpar;')\n    .replace(/\\)/g, '#rpar;');\n}\n\n/**\n * Extract a clean function name from a callee expression.\n *\n * For known Effect namespaces (Effect, Schema, Layer, etc.), strips the prefix:\n *   \"Effect.tryPromise\" → \"tryPromise\"\n *   \"Schema.decodeUnknown(UserSchema)\" → \"decodeUnknown\"\n *\n * For user/service objects, keeps the receiver for context:\n *   \"deps.convertCurrency\" → \"deps.convertCurrency\"\n *   \"config.getOrDefault\" → \"config.getOrDefault\"\n */\nexport function extractFunctionName(callee: string): string {\n  // Remove anything after opening paren (arguments)\n  const withoutArgs = callee.replace(/\\(.*$/, '');\n  const parts = withoutArgs.split('.');\n  if (parts.length <= 1) return withoutArgs;\n  // Strip known Effect namespace prefixes (Effect.X → X, Schema.X → X)\n  const receiver = parts[0] ?? '';\n  if (KNOWN_EFFECT_NAMESPACES.has(receiver) || BUILT_IN_TYPE_NAMES.has(receiver)) {\n    return parts[parts.length - 1] ?? withoutArgs;\n  }\n  // Keep receiver for user objects (deps.foo, config.bar)\n  return withoutArgs;\n}\n\n/**\n * Compute a human-readable display label for a StaticFlowNode.\n *\n * @param node - The node to label.\n * @param variableName - Optional variable name the result is assigned to (e.g. from a yield).\n */\nexport function computeDisplayName(node: StaticFlowNode, variableName?: string): string {\n  switch (node.type) {\n    case 'effect': {\n      const fnName = extractFunctionName(node.callee);\n      if (node.usePattern) {\n        const wrapper = node.serviceCall?.serviceType ?? node.usePattern.wrapperName;\n        return truncate(`${wrapper}.use`, 60);\n      }\n      if (variableName) {\n        return truncate(`${variableName} <- ${fnName}`, 60);\n      }\n      if (node.name) {\n        return truncate(`${node.name} <- ${fnName}`, 60);\n      }\n      return truncate(fnName, 60);\n    }\n\n    case 'generator':\n      return `Generator (${node.yields.length} yields)`;\n\n    case 'pipe':\n      return `Pipe (${node.transformations.length} steps)`;\n\n    case 'parallel':\n      return `${node.callee} (${node.children.length})`;\n\n    case 'race':\n      return `${node.callee} (${node.children.length} racing)`;\n\n    case 'error-handler':\n      return node.name ? `${node.name}: ${node.handlerType}` : node.handlerType;\n\n    case 'retry':\n      return node.schedule ? `retry: ${node.schedule}` : 'retry';\n\n    case 'timeout':\n      return node.duration ? `timeout: ${node.duration}` : 'timeout';\n\n    case 'resource':\n      return 'Resource';\n\n    case 'conditional':\n      return truncate(node.condition, 30);\n\n    case 'loop':\n      return node.iterSource ? truncate(`${node.loopType}(${node.iterSource})`, 60) : node.loopType;\n\n    case 'layer':\n      return node.isMerged ? 'Layer (merged)' : 'Layer';\n\n    case 'stream': {\n      const ops = node.pipeline.map((op) => op.operation);\n      const parts: string[] = ['Stream', ...ops];\n      if (node.sink) parts.push(node.sink);\n      return truncate(parts.join(' → '), 60);\n    }\n\n    case 'concurrency-primitive':\n      return `${node.primitive}.${node.operation}`;\n\n    case 'fiber': {\n      const op = node.operation;\n      if (node.isDaemon) return `${op} (daemon)`;\n      if (node.isScoped) return `${op} (scoped)`;\n      return op;\n    }\n\n    case 'transform':\n      return node.transformType;\n\n    case 'match':\n      return `Match.${node.matchOp}`;\n\n    case 'cause':\n      return `Cause.${node.causeOp}`;\n\n    case 'exit':\n      return `Exit.${node.exitOp}`;\n\n    case 'schedule':\n      return `Schedule.${node.scheduleOp}`;\n\n    case 'interruption':\n      return node.interruptionType;\n\n    case 'channel': {\n      const channelOps = node.pipeline.map((op) => op.operation);\n      return channelOps.length > 0 ? `Channel: ${channelOps.join(' → ')}` : 'Channel';\n    }\n\n    case 'sink': {\n      const sinkOps = node.pipeline.map((op) => op.operation);\n      return sinkOps.length > 0 ? `Sink: ${sinkOps.join(' → ')}` : 'Sink';\n    }\n\n    case 'decision':\n      return truncate(node.condition, 30);\n\n    case 'switch':\n      return `switch(${truncate(node.expression, 25)})`;\n\n    case 'try-catch':\n      return 'try/catch';\n\n    case 'terminal':\n      return node.label ? `${node.terminalKind} ${node.label}` : node.terminalKind;\n\n    case 'opaque':\n      return `Opaque: ${truncate(node.reason, 25)}`;\n\n    case 'unknown':\n      return `Unknown: ${truncate(node.reason, 30)}`;\n  }\n}\n\n// =============================================================================\n// Node Counting\n// =============================================================================\n\n/**\n * Count non-unknown nodes in an IR tree, recursing into children.\n */\nexport const countMeaningfulNodes = (nodes: readonly StaticFlowNode[]): number => {\n  let count = 0;\n  const walk = (list: readonly StaticFlowNode[]) => {\n    for (const node of list) {\n      if (node.type !== 'unknown') count++;\n      const children = Option.getOrElse(getStaticChildren(node), () => [] as readonly StaticFlowNode[]);\n      if (children.length > 0) walk(children);\n    }\n  };\n  walk(nodes);\n  return count;\n};\n\n/**\n * Classify a StaticFlowNode into a SemanticRole for display styling and filtering.\n */\nexport function computeSemanticRole(node: StaticFlowNode): SemanticRole {\n  switch (node.type) {\n    case 'effect': {\n      // Service call detection: explicit serviceCall/serviceMethod fields\n      if (node.serviceCall || node.serviceMethod || node.usePattern) return 'service-call';\n      // Description-based heuristic: descriptions mentioning \"service\" or \"layer\"\n      const desc = node.description?.toLowerCase() ?? '';\n      if (desc.includes('service')) return 'service-call';\n      if (desc.includes('layer') || node.provideKind === 'layer') return 'layer';\n      // Callee-based classification\n      const callee = node.callee.toLowerCase();\n      // Context/service tag access (yield* UserRepo / yield* AppConfig) is environment read, not side effect.\n      if (/^[A-Z][A-Za-z0-9_]*$/.test(node.callee) && !node.constructorKind) {\n        return 'environment';\n      }\n      if (\n        callee.includes('sync') ||\n        callee.includes('promise') ||\n        callee.includes('async') ||\n        callee.includes('log') ||\n        callee.includes('console')\n      ) {\n        return 'side-effect';\n      }\n      if (\n        callee.includes('succeed') ||\n        callee.includes('fail') ||\n        callee.includes('die') ||\n        callee.includes('void') ||\n        callee.includes('never') ||\n        callee.includes('gen') ||\n        callee.includes('make') ||\n        node.constructorKind\n      ) {\n        return 'constructor';\n      }\n      return 'side-effect';\n    }\n\n    case 'generator':\n    case 'pipe':\n      return 'constructor';\n\n    case 'parallel':\n    case 'race':\n    case 'concurrency-primitive':\n      return 'concurrency';\n\n    case 'error-handler':\n    case 'cause':\n    case 'exit':\n      return 'error-handler';\n\n    case 'retry':\n    case 'timeout':\n    case 'schedule':\n      return 'scheduling';\n\n    case 'resource':\n      return 'resource';\n\n    case 'conditional':\n    case 'loop':\n    case 'match':\n    case 'decision':\n    case 'switch':\n    case 'terminal':\n      return 'control-flow';\n\n    case 'try-catch':\n      return 'error-handler';\n\n    case 'opaque':\n      return 'unknown';\n\n    case 'layer':\n      return 'layer';\n\n    case 'stream':\n    case 'channel':\n    case 'sink':\n      return 'stream';\n\n    case 'fiber':\n    case 'interruption':\n      return 'fiber';\n\n    case 'transform':\n      return 'transform';\n\n    case 'unknown':\n      return 'unknown';\n  }\n}\n\n/**\n * Unwrap TypeScript expression wrappers: parenthesized, as, non-null,\n * satisfies, type assertion.\n *\n * A type assertion is not a program. `Effect.succeed(1) as Effect.Effect<number>`\n * is the same effect as `Effect.succeed(1)`, and every analyzer that reads an\n * expression needs to look through the wrapper before deciding what it is.\n *\n * Lives here rather than in `core-analysis.ts`, where it started, because\n * `effect-analysis.ts` needs the same rule and `core-analysis` already imports\n * from it. Both import this module, and this module imports neither.\n */\nexport function unwrapExpression(expr: Node): Node {\n  const { SyntaxKind } = loadTsMorph();\n  switch (expr.getKind()) {\n    case SyntaxKind.ParenthesizedExpression:\n    case SyntaxKind.AsExpression:\n    case SyntaxKind.TypeAssertionExpression:\n    case SyntaxKind.NonNullExpression:\n    case SyntaxKind.SatisfiesExpression:\n      return unwrapExpression(\n        (expr as unknown as { getExpression(): Node }).getExpression(),\n      );\n    default:\n      return expr;\n  }\n}\n","/**\n * Type Signature Extractor\n *\n * Uses ts-morph's TypeChecker to extract Effect type parameters:\n * - A (Success type)\n * - E (Error type)\n * - R (Requirements/Context type)\n */\n\nimport type { Type, Node, TypeChecker, VariableDeclaration, CallExpression, PropertyAccessExpression } from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  EffectTypeSignature,\n  ServiceRequirement,\n  SourceLocation,\n  StreamTypeSignature,\n  LayerTypeSignature,\n  ScheduleTypeSignature,\n  CauseTypeSignature,\n} from './types';\n\n// =============================================================================\n// Type Extraction\n// =============================================================================\n\n/** Regex to parse Effect<A, E, R> from type text when Type API fails */\nconst EFFECT_TYPE_REGEX_3 = /Effect(?:\\.Effect)?<([^,]+),\\s*([^,]+),\\s*([^>]+)>/;\n/** Regex to parse Effect<A, E> (2 params, R defaults to never) */\nconst EFFECT_TYPE_REGEX_2 = /Effect(?:\\.Effect)?<([^,>]+),\\s*([^,>]+)>/;\n\n/**\n * Read `_tag` string literals off an error type (including unions).\n * `Data.TaggedError(\"NOT_FOUND\")` exposes `_tag: \"NOT_FOUND\"`.\n */\nexport function taggedErrorTagsFromType(type: Type | undefined): readonly string[] {\n  if (!type) return [];\n  if (type.isUnion()) {\n    return [...new Set(type.getUnionTypes().flatMap((part) => taggedErrorTagsFromType(part)))];\n  }\n\n  const apparent = tagsFromTagProperty(type.getApparentType());\n  if (apparent.length > 0) return apparent;\n  const own = tagsFromTagProperty(type);\n  if (own.length > 0) return own;\n\n  const symbol = type.getSymbol() ?? type.getAliasSymbol();\n  if (!symbol) return [];\n  const tags: string[] = [];\n  for (const declaration of symbol.getDeclarations()) {\n    const tagged = /TaggedError\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/.exec(declaration.getText());\n    if (tagged?.[1]) tags.push(tagged[1]);\n  }\n  return tags;\n}\n\nfunction tagsFromTagProperty(type: Type): readonly string[] {\n  const tagProperty = type.getProperty('_tag');\n  if (!tagProperty) return [];\n  const tags: string[] = [];\n  for (const declaration of tagProperty.getDeclarations()) {\n    let tagType;\n    try {\n      tagType = declaration.getType();\n    } catch {\n      continue;\n    }\n    if (tagType.isLiteral()) {\n      const value = tagType.getLiteralValue();\n      if (typeof value === 'string') tags.push(value);\n      continue;\n    }\n    const quoted = /^(?:[\"'])([^\"']+)(?:[\"'])$/.exec(tagType.getText());\n    if (quoted?.[1]) tags.push(quoted[1]);\n  }\n  return tags;\n}\n\nconst withErrorTags = (\n  signature: EffectTypeSignature,\n  errorType: Type | undefined,\n  node?: Node,\n): EffectTypeSignature => {\n  const fromType = taggedErrorTagsFromType(errorType);\n  const fromSource = node ? taggedErrorTagsFromSource(node, signature.errorType) : [];\n  const errorTags = fromType.length > 0 ? fromType : fromSource;\n  return errorTags.length > 0 ? { ...signature, errorTags } : signature;\n};\n\nfunction taggedErrorTagsFromSource(node: Node, errorTypeName: string): readonly string[] {\n  const sourceFile = node.getSourceFile();\n  const tags: string[] = [];\n  for (const name of errorTypeName.split('|').map((part) => part.trim())) {\n    const cls = sourceFile.getClass(name);\n    if (!cls) continue;\n    const text = cls.getText();\n    const tagged = /TaggedError\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/.exec(text);\n    if (tagged?.[1]) {\n      tags.push(tagged[1]);\n      continue;\n    }\n    const field = /(?:readonly\\s+)?_tag\\s*=\\s*['\"]([^'\"]+)['\"]/.exec(text);\n    if (field?.[1]) tags.push(field[1]);\n  }\n  return tags;\n}\n\n/**\n * Build EffectTypeSignature from type text using regex (fallback when Type API has no type args).\n */\nexport function effectTypeSignatureFromTypeText(\n  typeText: string,\n): EffectTypeSignature | undefined {\n  const clean = (s: string) =>\n    s\n      .replace(/import\\([^)]+\\)\\./g, '')\n      .replace(/typeof\\s+/g, '')\n      .trim()\n      .substring(0, 200);\n\n  // Try 3-param: Effect<A, E, R>\n  const match3 = EFFECT_TYPE_REGEX_3.exec(typeText);\n  if (match3) {\n    return {\n      successType: clean(match3[1]!),\n      errorType: clean(match3[2]!),\n      requirementsType: clean(match3[3]!),\n      isInferred: false,\n      typeConfidence: 'inferred',\n      rawTypeString: typeText,\n    };\n  }\n\n  // Try 2-param: Effect<A, E> (R defaults to never)\n  const match2 = EFFECT_TYPE_REGEX_2.exec(typeText);\n  if (match2) {\n    return {\n      successType: clean(match2[1]!),\n      errorType: clean(match2[2]!),\n      requirementsType: 'never',\n      isInferred: false,\n      typeConfidence: 'inferred',\n      rawTypeString: typeText,\n    };\n  }\n\n  return undefined;\n}\n\n/**\n * When an error type is a single-letter generic (e.g., \"E\"), try to resolve\n * the concrete type from the inner expression (pipe base or call argument).\n */\nfunction tryResolveGenericFromInnerExpression(\n  node: Node,\n  typeChecker: TypeChecker,\n): { errorType: string } | undefined {\n  try {\n    const { SyntaxKind } = loadTsMorph();\n    if (node.getKind() === SyntaxKind.CallExpression) {\n      const call = node as CallExpression;\n      const expr = call.getExpression();\n      // For pipe chains: base.pipe(Effect.withSpan(\"x\")) — check the base expression\n      if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n        const propAccess = expr as PropertyAccessExpression;\n        if (propAccess.getName() === 'pipe') {\n          const baseExpr = propAccess.getExpression();\n          if (baseExpr) {\n            const baseSig = extractEffectTypeSignature(baseExpr, typeChecker);\n            if (baseSig && !/^[A-Z]$/.test(baseSig.errorType)) {\n              return { errorType: baseSig.errorType };\n            }\n          }\n        }\n      }\n      // For curried calls: Effect.withSpan(\"name\")(effect) — check the argument\n      const args = call.getArguments();\n      if (args.length > 0) {\n        for (const arg of args) {\n          const argSig = extractEffectTypeSignature(arg, typeChecker);\n          if (argSig && !/^[A-Z]$/.test(argSig.errorType)) {\n            return { errorType: argSig.errorType };\n          }\n        }\n      }\n    }\n  } catch {\n    // Type resolution can fail; return undefined\n  }\n  return undefined;\n}\n\n/**\n * Extract Effect type signature from a node\n */\nexport const extractEffectTypeSignature = (\n  node: Node,\n  _typeChecker: TypeChecker,\n): EffectTypeSignature | undefined => {\n  // Get the type of the node (can throw when type checker is unavailable)\n  let nodeType;\n  try {\n    nodeType = node.getType();\n  } catch {\n    return undefined;\n  }\n\n  // Check if it's an Effect type\n  if (!isEffectType(nodeType)) {\n    return undefined;\n  }\n\n  // Extract type arguments (A, E, R)\n  const typeArgs = extractTypeArguments(nodeType);\n\n  if (typeArgs) {\n    const [aType, eType, rType] = typeArgs;\n    const errorTypeStr = typeToString(eType);\n\n    // If errorType is a single-letter type parameter (e.g. \"E\"), try to resolve\n    // from the call's inner expression type\n    if (/^[A-Z]$/.test(errorTypeStr)) {\n      const resolved = tryResolveGenericFromInnerExpression(node, _typeChecker);\n      if (resolved) {\n        return withErrorTags({\n          successType: typeToString(aType),\n          errorType: resolved.errorType,\n          requirementsType: typeToString(rType),\n          isInferred: true,\n          typeConfidence: 'inferred',\n          rawTypeString: nodeType.getText(),\n        }, eType, node);\n      }\n    }\n\n    return withErrorTags({\n      successType: typeToString(aType),\n      errorType: errorTypeStr,\n      requirementsType: typeToString(rType),\n      isInferred: true,\n      typeConfidence: 'declared',\n      rawTypeString: nodeType.getText(),\n    }, eType, node);\n  }\n\n  // Fallback: parse A, E, R from type text when Type API doesn't provide type args\n  const typeText = nodeType.getText();\n  const fromText = effectTypeSignatureFromTypeText(typeText);\n  if (fromText) {\n    const eTrim = fromText.errorType.trim();\n    if (/^[A-Z]$/.test(eTrim)) {\n      const resolved = tryResolveGenericFromInnerExpression(node, _typeChecker);\n      if (resolved) {\n        return {\n          ...fromText,\n          errorType: resolved.errorType,\n          isInferred: true,\n          typeConfidence: 'inferred',\n          rawTypeString: nodeType.getText(),\n        };\n      }\n    }\n    return withErrorTags(fromText, undefined, node);\n  }\n\n  // Fallback: resolve the callee function's return type annotation\n  const fromCallee = tryExtractFromCalleeReturnType(node);\n  if (fromCallee) return withErrorTags(fromCallee, undefined, node);\n\n  return {\n    successType: 'unknown',\n    errorType: 'never',\n    requirementsType: 'never',\n    isInferred: false,\n    typeConfidence: 'unknown',\n    rawTypeString: typeText,\n  };\n};\n\n/**\n * When a call expression's resolved type lacks type args, try to extract\n * Effect<A, E, R> from the callee function's declared return type annotation.\n *\n * For `yield* validate(input)` where `validate` is declared as:\n *   `const validate = (input: T): Effect.Effect<A, E, R> => ...`\n * We resolve `validate` → get its return type annotation text → parse Effect<A, E, R>.\n */\nfunction tryExtractFromCalleeReturnType(node: Node): EffectTypeSignature | undefined {\n  try {\n    // Only works for call expressions\n    if (!('getExpression' in node)) return undefined;\n    const call = node as CallExpression;\n    const callee = call.getExpression();\n\n    // Try to get the callee's return type from its signature\n    const calleeType = callee.getType();\n    const callSignatures = calleeType.getCallSignatures();\n    if (callSignatures.length > 0) {\n      const returnType = callSignatures[0]!.getReturnType();\n\n      // Try type arguments on the return type\n      const returnArgs = extractTypeArguments(returnType);\n      if (returnArgs) {\n        const [aType, eType, rType] = returnArgs;\n        return withErrorTags({\n          successType: typeToString(aType),\n          errorType: typeToString(eType),\n          requirementsType: typeToString(rType),\n          isInferred: true,\n          typeConfidence: 'inferred',\n          rawTypeString: returnType.getText(),\n        }, eType, node);\n      }\n\n      // Try regex on the return type text\n      const returnText = returnType.getText();\n      const fromReturnText = effectTypeSignatureFromTypeText(returnText);\n      if (fromReturnText) return fromReturnText;\n    }\n\n    // Try to resolve the callee to its declaration and read the return type annotation\n    const symbol = callee.getSymbol();\n    if (!symbol) return undefined;\n\n    for (const decl of symbol.getDeclarations()) {\n      // Get the return type annotation text from the declaration\n      let returnTypeText: string | undefined;\n\n      if ('getReturnType' in decl) {\n        // Function/method declarations\n        const declType = (decl as { getReturnType: () => Type }).getReturnType();\n        returnTypeText = declType.getText();\n      } else if ('getType' in decl) {\n        // Variable declarations: get the type of the variable, then its call signatures\n        const varType = (decl as { getType: () => Type }).getType();\n        const sigs = varType.getCallSignatures();\n        if (sigs.length > 0) {\n          const retType = sigs[0]!.getReturnType();\n          const retArgs = extractTypeArguments(retType);\n          if (retArgs) {\n            const [aType, eType, rType] = retArgs;\n            return withErrorTags({\n              successType: typeToString(aType),\n              errorType: typeToString(eType),\n              requirementsType: typeToString(rType),\n              isInferred: true,\n              typeConfidence: 'inferred',\n              rawTypeString: retType.getText(),\n            }, eType, node);\n          }\n          returnTypeText = retType.getText();\n        }\n      }\n\n      if (returnTypeText) {\n        const fromAnnotation = effectTypeSignatureFromTypeText(returnTypeText);\n        if (fromAnnotation) {\n          return { ...fromAnnotation, typeConfidence: 'inferred' };\n        }\n      }\n    }\n  } catch {\n    // Callee resolution can fail for dynamic or unresolvable expressions\n  }\n  return undefined;\n}\n\n/**\n * Check if a type is an Effect type\n */\nconst isEffectType = (type: Type): boolean => {\n  const symbol = type.getSymbol();\n  const typeText = type.getText();\n  \n  // Check by symbol name\n  if (symbol) {\n    const name = symbol.getName();\n    if (name === 'Effect' || name.includes('Effect')) {\n      return true;\n    }\n  }\n  \n  // Check by type text pattern\n  if (typeText.includes('Effect<') || typeText.startsWith('Effect.')) {\n    return true;\n  }\n  \n  // Check for Effect interface\n  const aliasSymbol = type.getAliasSymbol();\n  if (aliasSymbol) {\n    const aliasName = aliasSymbol.getName();\n    if (aliasName === 'Effect' || aliasName.includes('Effect')) {\n      return true;\n    }\n  }\n  \n  return false;\n};\n\n/**\n * Extract type arguments from an Effect type\n * Returns [A, E, R] or undefined\n */\nconst extractTypeArguments = (type: Type): [Type, Type, Type] | undefined => {\n  try {\n    const typeArgs = type.getTypeArguments?.();\n    if (!typeArgs || typeArgs.length < 3) {\n      const aliasTypeArgs = type.getAliasTypeArguments?.();\n      if (aliasTypeArgs && aliasTypeArgs.length >= 3) {\n        return [aliasTypeArgs[0]!, aliasTypeArgs[1]!, aliasTypeArgs[2]!];\n      }\n      return undefined;\n    }\n    return [typeArgs[0]!, typeArgs[1]!, typeArgs[2]!];\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Convert a Type to a readable string\n */\nconst typeToString = (type: Type): string => {\n  const text = type.getText();\n  \n  // Clean up the type string\n  return text\n    .replace(/import\\([^)]+\\)\\./g, '') // Remove import paths\n    .replace(/typeof\\s+/g, '') // Remove typeof\n    .substring(0, 200); // Limit length\n};\n\n// =============================================================================\n// Service Requirement Extraction\n// =============================================================================\n\n/**\n * Extract service requirements from a Context type\n */\nexport const extractServiceRequirements = (\n  node: Node,\n  _typeChecker: TypeChecker,\n): ServiceRequirement[] => {\n  const requirements: ServiceRequirement[] = [];\n  \n  // Try to get the type - first from the node, then from type annotation\n  let nodeType = node.getType();\n  let locationNode: Node = node;\n  \n  // If node type doesn't have the required info, try to get declared type from variable\n  let nodeTypeArgs: readonly Type[] | undefined;\n  try {\n    nodeTypeArgs = typeof nodeType.getTypeArguments === 'function' ? nodeType.getTypeArguments() : undefined;\n  } catch {\n    nodeTypeArgs = undefined;\n  }\n  if (!nodeTypeArgs || nodeTypeArgs.length < 3) {\n    const parent = node.getParent();\n    if (parent?.getKindName() === 'VariableDeclaration') {\n      const varDecl = parent as VariableDeclaration;\n      const declaredType = varDecl.getType();\n      if (declaredType) {\n        nodeType = declaredType;\n        locationNode = varDecl;\n      }\n    }\n  }\n  \n  // Check if type contains Context requirements\n  const rType = extractRequirementsType(nodeType);\n  if (!rType) return requirements;\n  \n  // Extract individual services from the Context type\n  const services = extractServicesFromContext(rType);\n  \n  for (const service of services) {\n    const sourceFile = locationNode.getSourceFile();\n    const offset = locationNode.getStart();\n    const { line, column } = sourceFile.getLineAndColumnAtPos(offset);\n    const location: SourceLocation = {\n      filePath: sourceFile.getFilePath(),\n      line,\n      column,\n      offset,\n    };\n    \n    requirements.push({\n      serviceId: service.id,\n      serviceType: service.typeName,\n      requiredAt: location,\n    });\n  }\n  \n  return requirements;\n};\n\n/**\n * Extract the R (requirements) type from an Effect type\n */\nconst extractRequirementsType = (type: Type): Type | undefined => {\n  const typeArgs = extractTypeArguments(type);\n  if (!typeArgs) return undefined;\n  \n  return typeArgs[2]; // R is the third type parameter\n};\n\n/**\n * Extract individual service types from a Context type\n */\nconst extractServicesFromContext = (contextType: Type): { id: string; typeName: string }[] => {\n  const services: { id: string; typeName: string }[] = [];\n  \n  // Check if it's Context<Tag>\n  const typeText = contextType.getText();\n  \n  // Try to extract Tag identifier from Context<Tag>\n  const contextMatch = /Context<([^>]+)>/.exec(typeText);\n  if (contextMatch) {\n    const tagType = contextMatch[1]!;\n    services.push({\n      id: extractTagIdentifier(tagType),\n      typeName: tagType,\n    });\n  }\n  \n  // Check for intersection types (Context<A> | Context<B>)\n  if (typeText.includes('|')) {\n    const parts = splitTopLevelUnion(typeText);\n    for (const part of parts) {\n      const match = /Context<([^>]+)>/.exec(part);\n      if (match) {\n        services.push({\n          id: extractTagIdentifier(match[1]!),\n          typeName: match[1]!,\n        });\n      }\n    }\n  }\n  \n  // Check for never type (no requirements)\n  if (typeText === 'never' || typeText === '{}') {\n    return [];\n  }\n  \n  return services;\n};\n\n/**\n * Extract tag identifier from a Tag type string\n */\nconst extractTagIdentifier = (tagType: string): string => {\n  // Try to extract from Tag<\"identifier\", ...>\n  const match = /Tag<[\"']([^\"']+)[\"']/.exec(tagType);\n  if (match) {\n    return match[1]!;\n  }\n  \n  // Fallback: use the type name\n  return tagType.split('<')[0]!.trim();\n};\n\n// =============================================================================\n// Type Transformation Tracking\n// =============================================================================\n\n/**\n * Track how an Effect type transforms through a pipe operation\n */\nexport const trackTypeTransformation = (\n  inputType: EffectTypeSignature,\n  operation: string,\n  outputType: EffectTypeSignature,\n): { operation: string; typeChange: string } => {\n  const changes: string[] = [];\n  \n  if (inputType.successType !== outputType.successType) {\n    changes.push(`${inputType.successType} → ${outputType.successType}`);\n  }\n  \n  if (inputType.errorType !== outputType.errorType) {\n    changes.push(`${inputType.errorType} → ${outputType.errorType}`);\n  }\n  \n  if (inputType.requirementsType !== outputType.requirementsType) {\n    changes.push(`${inputType.requirementsType} → ${outputType.requirementsType}`);\n  }\n  \n  return {\n    operation,\n    typeChange: changes.length > 0 ? changes.join(', ') : 'no change',\n  };\n};\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Split a type string on top-level `|` only, respecting angle brackets and string literals.\n * e.g. `Envelope<\"A\" | \"B\"> | FooError` → `[\"Envelope<\\\"A\\\" | \\\"B\\\">\", \"FooError\"]`\n */\nexport function splitTopLevelUnion(typeText: string): string[] {\n  const parts: string[] = [];\n  let current = '';\n  let depth = 0;      // angle bracket depth\n  let inString: string | null = null;\n\n  for (let i = 0; i < typeText.length; i++) {\n    const ch = typeText[i]!;\n\n    if (inString) {\n      current += ch;\n      if (ch === inString && typeText[i - 1] !== '\\\\') {\n        inString = null;\n      }\n      continue;\n    }\n\n    if (ch === '\"' || ch === \"'\" || ch === '`') {\n      inString = ch;\n      current += ch;\n      continue;\n    }\n\n    if (ch === '<' || ch === '(') {\n      depth++;\n      current += ch;\n      continue;\n    }\n\n    if (ch === '>' || ch === ')') {\n      depth = Math.max(0, depth - 1);\n      current += ch;\n      continue;\n    }\n\n    if (ch === '|' && depth === 0) {\n      parts.push(current.trim());\n      current = '';\n      continue;\n    }\n\n    current += ch;\n  }\n\n  const last = current.trim();\n  if (last) parts.push(last);\n\n  return parts.filter(Boolean);\n}\n\n/**\n * Format type signature for display\n */\nexport const formatTypeSignature = (sig: EffectTypeSignature): string => {\n  return `Effect<${sig.successType}, ${sig.errorType}, ${sig.requirementsType}>`;\n};\n\n// =============================================================================\n// Stream / Layer / Schedule / Cause type extraction (21.3)\n// =============================================================================\n\nconst cleanTypeArg = (s: string): string =>\n  s\n    .replace(/import\\([^)]+\\)\\./g, '')\n    .replace(/typeof\\s+/g, '')\n    .trim()\n    .substring(0, 200);\n\n/** Regexes for type args when Type API has no type arguments */\nconst STREAM_TYPE_REGEX = /Stream<([^,]+),\\s*([^,]+),\\s*([^>]+)>/;\nconst LAYER_TYPE_REGEX = /Layer<([^,]+),\\s*([^,]+),\\s*([^>]+)>/;\nconst SCHEDULE_TYPE_REGEX = /Schedule<([^,]+),\\s*([^,]+),\\s*([^>]+)>/;\nconst CAUSE_TYPE_REGEX = /Cause<([^>]+)>/;\n\n/**\n * Extract Stream<A, E, R> type args from a node's type (regex fallback).\n */\nexport function extractStreamTypeSignature(node: Node): StreamTypeSignature | undefined {\n  const typeText = node.getType().getText();\n  const match = STREAM_TYPE_REGEX.exec(typeText);\n  if (!match) return undefined;\n  return {\n    successType: cleanTypeArg(match[1]!),\n    errorType: cleanTypeArg(match[2]!),\n    requirementsType: cleanTypeArg(match[3]!),\n    rawTypeString: typeText,\n  };\n}\n\n/**\n * Extract Layer<ROut, E, RIn> type args from a node's type (regex fallback).\n */\nexport function extractLayerTypeSignature(node: Node): LayerTypeSignature | undefined {\n  const typeText = node.getType().getText();\n  const match = LAYER_TYPE_REGEX.exec(typeText);\n  if (!match) return undefined;\n  return {\n    providedType: cleanTypeArg(match[1]!),\n    errorType: cleanTypeArg(match[2]!),\n    requiredType: cleanTypeArg(match[3]!),\n    rawTypeString: typeText,\n  };\n}\n\n/**\n * Extract Schedule<Out, In, R> type args from a node's type (regex fallback).\n */\nexport function extractScheduleTypeSignature(node: Node): ScheduleTypeSignature | undefined {\n  const typeText = node.getType().getText();\n  const match = SCHEDULE_TYPE_REGEX.exec(typeText);\n  if (!match) return undefined;\n  return {\n    outputType: cleanTypeArg(match[1]!),\n    inputType: cleanTypeArg(match[2]!),\n    requirementsType: cleanTypeArg(match[3]!),\n    rawTypeString: typeText,\n  };\n}\n\n/**\n * Extract Cause<E> type arg from a node's type (regex fallback).\n */\nexport function extractCauseTypeSignature(node: Node): CauseTypeSignature | undefined {\n  const typeText = node.getType().getText();\n  const match = CAUSE_TYPE_REGEX.exec(typeText);\n  if (!match) return undefined;\n  return {\n    errorType: cleanTypeArg(match[1]!),\n    rawTypeString: typeText,\n  };\n}\n\n// =============================================================================\n// Schema\n// =============================================================================\n\n/**\n * Check if a type is a Schema type\n */\nexport const isSchemaType = (type: Type): boolean => {\n  const symbol = type.getSymbol();\n  if (symbol) {\n    const name = symbol.getName();\n    return name === 'Schema' || name.includes('Schema');\n  }\n  \n  const typeText = type.getText();\n  return typeText.includes('Schema<') || typeText.startsWith('Schema.');\n};\n\n/**\n * Extract Schema validation information\n */\nexport const extractSchemaInfo = (type: Type): { encoded: string; decoded: string } | undefined => {\n  if (!isSchemaType(type)) return undefined;\n  \n  const typeArgs = type.getTypeArguments();\n  if (typeArgs.length >= 2) {\n    return {\n      encoded: typeToString(typeArgs[1]!),\n      decoded: typeToString(typeArgs[0]!),\n    };\n  }\n  \n  return undefined;\n};\n","/**\n * Pattern maps and semantic helpers for Effect API detection and classification.\n */\n\nimport type {\n  Node,\n  CallExpression,\n  PropertyAccessExpression,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n  Block,\n  AwaitExpression,\n  ConditionalExpression,\n  PrefixUnaryExpression,\n  ArrowFunction,\n  FunctionExpression,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticTransformNode,\n  StaticMatchNode,\n  StaticCauseNode,\n  StaticExitNode,\n  StaticScheduleNode,\n} from './types';\n\n// =============================================================================\n// Error / conditional / resource / collection / fiber patterns\n// =============================================================================\n\nexport const ERROR_HANDLER_PATTERNS = [\n  '.catch',\n  '.catchTag',\n  '.catchCause',\n  '.catchIf',\n  '.catchSome',\n  '.catchSomeCause',\n  '.catchSomeDefect',\n  '.catchDefect',\n  '.catchTags',\n  '.orElse',\n  '.orElseFail',\n  '.orElseSucceed',\n  '.orDie',\n  '.orDieWith',\n  '.flip',\n  '.mapError',\n  '.mapErrorCause',\n  '.mapBoth',\n  '.sandbox',\n  '.unsandbox',\n  '.parallelErrors',\n  '.filterOrDie',\n  '.filterOrDieMessage',\n  '.filterOrElse',\n  '.filterOrFail',\n  '.match',\n  '.matchCause',\n  '.matchEffect',\n  '.matchCauseEffect',\n  '.firstSuccessOf',\n  '.ignore',\n  '.ignoreLogged',\n  '.eventually',\n];\n\nexport const CONDITIONAL_PATTERNS = [\n  '.if',\n  '.when',\n  '.whenEffect',\n  '.whenFiberRef',\n  '.whenRef',\n  '.unless',\n  '.unlessEffect',\n  '.option',\n  '.either',\n  '.exit',\n  '.liftPredicate',\n];\n\nexport const RESOURCE_PATTERNS = [\n  '.acquireRelease',\n  '.acquireUseRelease',\n  '.ensuring',\n  '.addFinalizer',\n  '.onExit',\n  '.onError',\n  '.parallelFinalizers',\n  '.sequentialFinalizers',\n  '.finalizersMask',\n  '.using',\n  '.withEarlyRelease',\n];\n\nexport const COLLECTION_PATTERNS = [\n  '.forEach',\n  '.loop',\n  '.filter',\n  '.filterMap',\n  '.partition',\n  '.reduce',\n  '.reduceRight',\n  '.reduceWhile',\n  '.reduceEffect',\n  '.dropUntil',\n  '.dropWhile',\n  '.takeUntil',\n  '.takeWhile',\n  '.every',\n  '.exists',\n  '.findFirst',\n  '.head',\n  '.mergeAll',\n  '.replicate',\n  '.replicateEffect',\n  '.validateAll',\n  '.validateFirst',\n  '.validate',\n  '.validateWith',\n];\n\nexport const FIBER_PATTERNS = [\n  'Effect.fork',\n  '.fork',\n  '.forkAll',\n  '.forkIn',\n  '.forkWithErrorHandler',\n  'Fiber.',\n];\n\n// =============================================================================\n// Transform / Match / Cause / Exit / Schedule ops\n// =============================================================================\n\nexport const TRANSFORM_OPS: Record<string, StaticTransformNode['transformType']> = {\n  'Effect.map': 'map',\n  'Effect.flatMap': 'flatMap',\n  'Effect.andThen': 'andThen',\n  'Effect.tap': 'tap',\n  'Effect.tapBoth': 'tapBoth',\n  'Effect.tapError': 'tapError',\n  'Effect.tapErrorTag': 'tapErrorTag',\n  'Effect.tapErrorCause': 'tapErrorCause',\n  'Effect.tapDefect': 'tapDefect',\n  'Effect.zipLeft': 'zipLeft',\n  'Effect.zipRight': 'zipRight',\n  'Effect.zipWith': 'zipWith',\n  'Effect.zip': 'zip',\n  'Effect.as': 'as',\n  'Effect.asVoid': 'asVoid',\n  'Effect.asSome': 'asSome',\n  'Effect.asSomeError': 'asSomeError',\n  'Effect.flatten': 'flatten',\n  'Effect.ap': 'ap',\n  'Effect.negate': 'negate',\n  'Effect.merge': 'merge',\n};\nexport const EFFECTFUL_TRANSFORMS = new Set(['flatMap', 'andThen', 'tapBoth', 'tapError', 'tapErrorTag', 'tapErrorCause', 'tapDefect', 'zipWith', 'zipLeft', 'zipRight', 'zip', 'ap', 'flatten']);\nexport const isTransformCall = (callee: string): boolean => callee in TRANSFORM_OPS;\n\nexport const MATCH_OP_MAP: Record<string, StaticMatchNode['matchOp']> = {\n  'Match.type': 'type',\n  'Match.tag': 'tag',\n  'Match.value': 'value',\n  'Match.when': 'when',\n  'Match.whenOr': 'whenOr',\n  'Match.whenAnd': 'whenAnd',\n  'Match.not': 'not',\n  'Match.is': 'is',\n  'Match.exhaustive': 'exhaustive',\n  'Match.orElse': 'orElse',\n  'Match.option': 'option',\n  'Match.either': 'either',\n  'Match.discriminator': 'discriminator',\n  'Match.discriminatorsExhaustive': 'discriminatorsExhaustive',\n  'Match.tags': 'tags',\n  'Match.tagsExhaustive': 'tagsExhaustive',\n  'Match.withReturnType': 'withReturnType',\n  'Match.run': 'run',\n};\nexport const EXHAUSTIVE_OPS = new Set(['exhaustive', 'discriminatorsExhaustive', 'tagsExhaustive']);\nexport const isMatchCall = (callee: string): boolean =>\n  callee.startsWith('Match.') && callee in MATCH_OP_MAP;\n\nexport const CAUSE_OP_MAP: Record<string, StaticCauseNode['causeOp']> = {\n  'Cause.fail': 'fail',\n  'Cause.die': 'die',\n  'Cause.interrupt': 'interrupt',\n  'Cause.parallel': 'parallel',\n  'Cause.sequential': 'sequential',\n  'Cause.empty': 'empty',\n  'Cause.failures': 'failures',\n  'Cause.defects': 'defects',\n  'Cause.interruptors': 'interruptors',\n  'Cause.squash': 'squash',\n  'Cause.squashWith': 'squashWith',\n  'Cause.pretty': 'pretty',\n  'Cause.flatten': 'flatten',\n  'Cause.isDie': 'isDie',\n  'Cause.isFailure': 'isFailure',\n  'Cause.isInterrupted': 'isInterrupted',\n  'Cause.isEmpty': 'isEmpty',\n  'Cause.map': 'map',\n  'Cause.filter': 'filter',\n};\nexport const CAUSE_CONSTRUCTORS = new Set(['fail', 'die', 'interrupt', 'parallel', 'sequential', 'empty']);\nexport const isCauseCall = (callee: string): boolean =>\n  callee.startsWith('Cause.') && callee in CAUSE_OP_MAP;\n\nexport const EXIT_OP_MAP: Record<string, StaticExitNode['exitOp']> = {\n  'Exit.succeed': 'succeed',\n  'Exit.fail': 'fail',\n  'Exit.die': 'die',\n  'Exit.interrupt': 'interrupt',\n  'Exit.void': 'void',\n  'Exit.unit': 'unit',\n  'Exit.match': 'match',\n  'Exit.isSuccess': 'isSuccess',\n  'Exit.isFailure': 'isFailure',\n  'Exit.isInterrupted': 'isInterrupted',\n  'Exit.when': 'when',\n  'Exit.whenEffect': 'whenEffect',\n  'Exit.exists': 'exists',\n  'Exit.contains': 'contains',\n  'Exit.flatten': 'flatten',\n  'Exit.map': 'map',\n  'Exit.mapBoth': 'mapBoth',\n  'Exit.mapError': 'mapError',\n  'Exit.flatMap': 'flatMap',\n  'Exit.zipWith': 'zipWith',\n  'Exit.tap': 'tap',\n  'Exit.tapBoth': 'tapBoth',\n  'Exit.tapError': 'tapError',\n};\nexport const EXIT_CONSTRUCTORS = new Set(['succeed', 'fail', 'die', 'interrupt', 'void', 'unit']);\nexport const isExitCall = (callee: string): boolean =>\n  callee.startsWith('Exit.') && (callee in EXIT_OP_MAP || /^Exit\\.\\w+$/.test(callee));\n\nexport const SCHEDULE_OP_MAP: Record<string, StaticScheduleNode['scheduleOp']> = {\n  'Schedule.exponential': 'exponential',\n  'Schedule.fibonacci': 'fibonacci',\n  'Schedule.spaced': 'spaced',\n  'Schedule.fixed': 'fixed',\n  'Schedule.linear': 'linear',\n  'Schedule.cron': 'cron',\n  'Schedule.windowed': 'windowed',\n  'Schedule.duration': 'duration',\n  'Schedule.elapsed': 'elapsed',\n  'Schedule.delays': 'delays',\n  'Schedule.once': 'once',\n  'Schedule.stop': 'stop',\n  'Schedule.count': 'count',\n  'Schedule.forever': 'forever',\n  'Schedule.jittered': 'jittered',\n  'Schedule.andThen': 'andThen',\n  'Schedule.intersect': 'intersect',\n  'Schedule.union': 'union',\n  'Schedule.compose': 'compose',\n  'Schedule.zipWith': 'zipWith',\n  'Schedule.addDelay': 'addDelay',\n  'Schedule.modifyDelay': 'modifyDelay',\n  'Schedule.check': 'check',\n  'Schedule.resetAfter': 'resetAfter',\n  'Schedule.resetWhen': 'resetWhen',\n  'Schedule.ensure': 'ensure',\n  'Schedule.driver': 'driver',\n  'Schedule.mapInput': 'mapInput',\n};\nexport const isScheduleCall = (callee: string): boolean =>\n  callee.startsWith('Schedule.') && (callee in SCHEDULE_OP_MAP || /^Schedule\\.\\w+$/.test(callee));\n\nexport const INTERRUPTION_PATTERNS = [\n  '.interruptible',\n  '.uninterruptible',\n  '.interruptibleMask',\n  '.uninterruptibleMask',\n  '.onInterrupt',\n  '.disconnect',\n  '.allowInterrupt',\n  'Effect.interrupt',\n  '.interruptWith',\n];\n\nexport const DO_NOTATION_PATTERNS = [\n  '.Do',\n  '.bind',\n  '.bindAll',\n  '.bindTo',\n];\n\nexport const CACHING_PATTERNS = [\n  '.cached',\n  '.cachedWithTTL',\n  '.cachedInvalidateWithTTL',\n  '.cachedFunction',\n  '.once',\n  'Cache.',\n  'ScopedCache.',\n];\n\n// =============================================================================\n// API prefixes and built-in / service classification\n// =============================================================================\n\nexport const API_PREFIXES = [\n  'Effect.',\n  'Layer.',\n  'Schedule.',\n  'Stream.',\n  'Queue.',\n  'PubSub.',\n  'Deferred.',\n  'Semaphore.',\n  'Mailbox.',\n  'SubscriptionRef.',\n  'Scope.',\n  'Fiber.',\n  'Runtime.',\n  'ManagedRuntime.',\n  'NodeRuntime.',\n  'BunRuntime.',\n  'DenoRuntime.',\n  'Cause.',\n  'Exit.',\n  'Data.',\n  'Option.',\n  'Either.',\n  'Chunk.',\n  'HashMap.',\n  'HashSet.',\n  'List.',\n  'SortedMap.',\n  'SortedSet.',\n  'RedBlackTree.',\n  'Trie.',\n  'Graph.',\n  'Match.',\n  'Config.',\n  'Schema.',\n  'Cache.',\n  'ScopedCache.',\n  'RcRef.',\n  'RcMap.',\n  'Reloadable.',\n  'Cache.',\n  'ScopedCache.',\n  'RateLimiter.',\n  'PartitionedSemaphore.',\n  'FiberSet.',\n  'FiberMap.',\n  'FiberHandle.',\n  'Metric.',\n  'Logger.',\n  'Tracer.',\n  'Context.',\n  'HttpClient.',\n  'HttpRouter.',\n  'HttpApi.',\n  'FileSystem.',\n  'Command.',\n  'Socket.',\n  'SocketServer.',\n  'Worker.',\n  'Terminal.',\n  'KeyValueStore.',\n  'Multipart.',\n  'Ndjson.',\n  'MsgPack.',\n  'OpenApi.',\n  'OpenApiJsonSchema.',\n  'Brand.',\n  'Encoding.',\n  'Predicate.',\n  'DateTime.',\n  'Cron.',\n  'BigDecimal.',\n  'HashRing.',\n  'Redacted.',\n  'GlobalValue.',\n  'Channel.',\n  'Sink.',\n  'CliApp.',\n  'Args.',\n  'Options.',\n  'AiModel.',\n  'AiToolkit.',\n  'Completions.',\n  'AiInput.',\n  'AiResponse.',\n  'NodeSdk.',\n  'WebSdk.',\n  'Entity.',\n  'ClusterSchema.',\n  'MessageState.',\n  'Sharding.',\n  'RpcGroup.',\n  'RpcApi.',\n  'RpcClient.',\n  'RpcRouter.',\n  'SqlResolver.',\n  'SqlMigrator.',\n  'Printer.',\n  'Doc.',\n  'DocTree.',\n  'PageWidth.',\n  'Optimize.',\n];\n\nexport const BUILT_IN_TYPE_NAMES = new Set([\n  'Array', 'ReadonlyArray', 'String', 'Number', 'Boolean', 'Object',\n  'Function', 'Promise', 'Math', 'Date', 'RegExp', 'Error', 'Map',\n  'Set', 'WeakMap', 'WeakSet', 'Symbol', 'BigInt', 'JSON', 'Console',\n  'process', 'Buffer', 'EventEmitter', 'Window', 'Document', 'AbortController',\n]);\n\nexport const KNOWN_EFFECT_NAMESPACES = new Set([\n  // Core runtime — these are never services themselves\n  'Effect', 'Layer', 'Stream', 'Queue', 'PubSub', 'Deferred', 'Semaphore',\n  'Mailbox', 'SubscriptionRef', 'Scope', 'Fiber', 'Runtime', 'ManagedRuntime', 'Cause', 'Exit',\n  // Data types\n  'Data', 'Option', 'Either', 'Chunk', 'HashMap', 'HashSet', 'List',\n  'SortedMap', 'SortedSet',\n  // Matching, config, schema (S is a common alias for Schema)\n  'Match', 'Config', 'Schema', 'Schedule', 'S',\n  // Observability\n  'Metric', 'Tracer', 'Logger',\n  // Fiber management\n  'FiberRef', 'FiberHandle', 'FiberSet', 'FiberMap',\n  // Caching\n  'Cache', 'ScopedCache', 'RateLimiter', 'Supervisor',\n  // Refs and state\n  'Ref', 'SynchronizedRef', 'Context',\n  // Pure utilities — never services\n  'Random', 'Clock', 'Duration', 'DateTime', 'Predicate', 'Tuple', 'Struct',\n  'Record', 'Encoding', 'Order', 'Equivalence', 'Brand', 'Inspectable',\n  'Equal', 'Hash', 'Differ', 'Types', 'Unify', 'Pipeable',\n  // Streams / channels / sinks\n  'Sink', 'Channel', 'GroupBy', 'Take',\n  // STM\n  'STM', 'TRef', 'TMap', 'TSet', 'TArray', 'TQueue', 'TPubSub', 'TDeferred', 'TSemaphore',\n  // HTTP request/response builders — utility namespaces, not services\n  'HttpClientRequest', 'HttpClientResponse', 'HttpClientError',\n  'HttpServerRequest', 'HttpServerResponse', 'HttpRouter', 'HttpApiEndpoint',\n  'HttpApiGroup', 'HttpApi', 'HttpApiBuilder', 'HttpApiSecurity', 'HttpMiddleware',\n  'FetchHttpClient', 'NodeHttpClient', 'BunHttpClient',\n  // Command (the Effect platform process command, not a service)\n  'Command',\n  // SQL utilities\n  'SqlSchema', 'SqlResolver', 'SqlMigrator',\n  // RPC utilities\n  'Rpc', 'RpcRouter', 'RpcGroup', 'RpcApi', 'RpcSerialization',\n  // Cluster / distributed\n  'Entity', 'ClusterSchema', 'MessageState', 'Sharding',\n  // Printer / docs\n  'Printer', 'Doc', 'DocTree', 'PageWidth', 'Optimize',\n  // AI\n  'AiToolkit', 'Completions', 'AiInput', 'AiResponse',\n  // OpenTelemetry\n  'NodeSdk', 'WebSdk',\n]);\n\nexport const isServiceTagCallee = (callee: string): boolean => {\n  if (callee.includes('.')) return false;\n  if (KNOWN_EFFECT_NAMESPACES.has(callee)) return false;\n  return /^[A-Z][A-Za-z0-9]*$/.test(callee);\n};\n\n// =============================================================================\n// Semantic description and alias-aware helpers\n// =============================================================================\n\nexport const getSemanticDescription = (callee: string): string | undefined => {\n  if (callee.startsWith('Channel.')) return 'channel';\n  if (callee.startsWith('Sink.')) return 'sink';\n  if (callee.endsWith('.never')) return 'never';\n  if (callee.endsWith('.void')) return 'void-effect';\n  if (callee.endsWith('.fromNullable')) return 'null-coalescing';\n  if (callee.endsWith('.fn')) return 'function-lift';\n  if (callee.endsWith('.fnUntraced')) return 'function-lift';\n  if (\n    callee.includes('.async') ||\n    callee.includes('.asyncEffect') ||\n    callee.includes('.promise') ||\n    callee.includes('.sync') ||\n    callee.includes('.suspend') ||\n    callee.includes('.succeed') ||\n    callee.includes('.fail') ||\n    callee.includes('.try')\n  ) return 'constructor';\n  if (INTERRUPTION_PATTERNS.some((p) => callee.includes(p))) return 'interruption';\n  if (DO_NOTATION_PATTERNS.some((p) => callee.includes(p))) return 'do-notation';\n  if (CACHING_PATTERNS.some((p) => callee.includes(p) || callee.startsWith(p))) return 'caching';\n  if (ERROR_HANDLER_PATTERNS.some((p) => callee.includes(p))) return 'error-handler';\n  if (CONDITIONAL_PATTERNS.some((p) => callee.includes(p))) return 'conditional';\n  if (RESOURCE_PATTERNS.some((p) => callee.includes(p))) return 'resource';\n  if (COLLECTION_PATTERNS.some((p) => callee.includes(p))) return 'collection';\n  if (FIBER_PATTERNS.some((p) => callee.includes(p))) return 'fiber';\n  if (callee.startsWith('Stream.')) return 'stream';\n  if (callee.startsWith('Layer.')) return 'layer';\n  if (callee.startsWith('Schema.')) return 'schema';\n  if (callee.startsWith('Config.')) return 'config';\n  if (callee.startsWith('Cause.')) return 'cause';\n  if (callee.startsWith('Exit.')) return 'exit';\n  if (callee === 'Data.tagged' || callee === 'Data.taggedEnum') return 'tagged-enum';\n  if (callee.startsWith('Data.')) return 'data';\n  if (callee.startsWith('Option.')) return 'option';\n  if (callee.startsWith('Either.')) return 'either';\n  if (callee.startsWith('Match.')) return 'match';\n  if (callee.startsWith('ManagedRuntime.')) return 'runtime';\n  if (callee.startsWith('Runtime.')) return 'runtime';\n  if (callee.startsWith('NodeRuntime.') || callee.startsWith('BunRuntime.') || callee.startsWith('DenoRuntime.')) return 'runtime';\n  if (callee.startsWith('Scope.')) return 'scope';\n  if (callee.startsWith('ScopedRef.') || callee.startsWith('RcRef.') || callee.startsWith('RcMap.')) return 'resource-ref';\n  if (callee.startsWith('Reloadable.') || callee.startsWith('Resource.')) return 'reloadable';\n  if (callee.startsWith('Micro.')) return 'micro';\n  if (callee.startsWith('Brand.')) return 'brand';\n  if (callee.startsWith('Encoding.')) return 'encoding';\n  if (callee.startsWith('Predicate.')) return 'predicate';\n  if (callee.startsWith('DateTime.')) return 'datetime';\n  if (callee.startsWith('Cron.')) return 'cron';\n  if (callee.startsWith('Redacted.')) return 'redacted';\n  if (callee.startsWith('GlobalValue.')) return 'global-value';\n  if (callee.startsWith('Supervisor.')) return 'supervisor';\n  if (\n    callee.includes('.locally') ||\n    callee.includes('.locallyWith') ||\n    callee.includes('.locallyScoped') ||\n    callee.includes('.getFiberRefs') ||\n    callee.includes('.setFiberRefs') ||\n    callee.includes('.inheritFiberRefs') ||\n    callee.includes('FiberRef.')\n  ) return 'fiberref';\n  if (\n    callee.includes('.withConcurrency') ||\n    callee.includes('.withScheduler') ||\n    callee.includes('.withSchedulingPriority') ||\n    callee.includes('.daemonChildren') ||\n    callee.includes('.awaitAllChildren') ||\n    callee.includes('.supervised')\n  ) return 'structured-concurrency';\n  if (\n    callee.startsWith('Context.pick') ||\n    callee.startsWith('Context.omit')\n  ) return 'context';\n  if (\n    callee === 'Effect.provide' ||\n    (callee.startsWith('Effect.') && callee.includes('.provide') && !callee.includes('provideService'))\n  ) return 'context';\n  if (\n    callee.includes('.serviceOption') ||\n    callee.includes('.serviceOptional') ||\n    callee.includes('.serviceFunction') ||\n    callee.includes('.serviceFunctionEffect') ||\n    callee.includes('.serviceFunctions') ||\n    callee.includes('.serviceConstants') ||\n    callee.includes('.serviceMembers') ||\n    callee.includes('.updateService')\n  ) return 'service';\n  if (\n    callee.startsWith('CliApp.') ||\n    callee.startsWith('Args.') ||\n    callee.startsWith('Options.')\n  ) return 'cli';\n  if (\n    callee.startsWith('AiModel.') ||\n    callee.startsWith('AiToolkit.') ||\n    callee.startsWith('Completions.') ||\n    callee.startsWith('AiInput.') ||\n    callee.startsWith('AiResponse.')\n  ) return 'ai';\n  if (\n    callee.startsWith('NodeSdk.') ||\n    callee.startsWith('WebSdk.') ||\n    callee.startsWith('OtelMetrics.')\n  ) return 'opentelemetry';\n  if (\n    callee.startsWith('Entity.') ||\n    callee.startsWith('ClusterSchema.') ||\n    callee.startsWith('MessageState.') ||\n    callee.startsWith('Sharding.')\n  ) return 'cluster';\n  if (\n    callee.startsWith('RpcGroup.') ||\n    callee.startsWith('RpcApi.') ||\n    callee.startsWith('RpcClient.') ||\n    callee.startsWith('RpcRouter.')\n  ) return 'rpc';\n  if (\n    callee.startsWith('SqlResolver.') ||\n    callee.startsWith('SqlMigrator.')\n  ) return 'sql';\n  if (callee.startsWith('DevTools.') || callee.startsWith('Server.')) return 'devtools';\n  if (callee.startsWith('BigDecimal.')) return 'big-decimal';\n  if (callee.startsWith('Graph.')) return 'graph';\n  if (callee.startsWith('HashRing.')) return 'hash-ring';\n  if (callee.startsWith('Chunk.')) return 'chunk';\n  if (callee.startsWith('HashMap.') || callee.startsWith('HashSet.')) return 'immutable-collection';\n  if (\n    callee.startsWith('List.') ||\n    callee.startsWith('SortedMap.') ||\n    callee.startsWith('SortedSet.') ||\n    callee.startsWith('RedBlackTree.') ||\n    callee.startsWith('Trie.')\n  ) return 'immutable-collection';\n  if (\n    callee.includes('.map') ||\n    callee.includes('.flatMap') ||\n    callee.includes('.andThen') ||\n    callee.includes('.tap') ||\n    callee.includes('.tapBoth') ||\n    callee.includes('.tapError') ||\n    callee.includes('.tapErrorTag') ||\n    callee.includes('.tapErrorCause') ||\n    callee.includes('.tapDefect') ||\n    callee.includes('.zip') ||\n    callee.includes('.zipLeft') ||\n    callee.includes('.zipRight') ||\n    callee.includes('.zipWith') ||\n    callee.includes('.as') ||\n    callee.includes('.asVoid') ||\n    callee.includes('.flatten') ||\n    callee.includes('.merge') ||\n    callee.includes('.ap') ||\n    callee.includes('.validate') ||\n    callee.includes('.negate')\n  ) return 'transformation';\n  if (\n    callee.startsWith('Printer.') ||\n    callee.startsWith('Doc.') ||\n    callee.startsWith('DocTree.') ||\n    callee.startsWith('PageWidth.') ||\n    callee.startsWith('Optimize.')\n  ) return 'printer';\n  if (\n    callee.startsWith('Http') ||\n    callee.startsWith('FileSystem.') ||\n    callee.startsWith('Command.') ||\n    callee.startsWith('Socket.') ||\n    callee.startsWith('Worker.')\n  ) return 'platform';\n  if (callee.includes('channel.') && !callee.includes('Channel')) return 'channel';\n  return undefined;\n};\n\nexport const getSemanticDescriptionWithAliases = (\n  callee: string,\n  effectAliases?: Set<string>,\n): string | undefined => {\n  const direct = getSemanticDescription(callee);\n  if (direct) return direct;\n\n  if (effectAliases) {\n    const dotIndex = callee.indexOf('.');\n    if (dotIndex > 0) {\n      const prefix = callee.substring(0, dotIndex);\n      if (effectAliases.has(prefix)) {\n        const method = callee.substring(dotIndex + 1);\n        return getSemanticDescription(`Effect.${method}`);\n      }\n    }\n  }\n  return undefined;\n};\n\nexport const isLikelyDirectEffectInitializer = (\n  initializer: Node,\n  effectImportNames: Set<string>,\n  nonProgramEffectImportNames: Set<string> = new Set(),\n): boolean => {\n  const { SyntaxKind } = loadTsMorph();\n  const isNonProgramName = (name: string): boolean => nonProgramEffectImportNames.has(name);\n  const isRunEntrypointCalleeText = (exprText: string): boolean =>\n    /\\.run(?:Promise(?:Exit)?|Sync(?:Exit)?|Fork|Callback|Main)$/.test(exprText) ||\n    /^Runtime\\.run(?:Promise|Sync|Fork)$/.test(exprText);\n  const isDirectEffectCalleeText = (exprText: string): boolean => {\n    if (isRunEntrypointCalleeText(exprText)) {\n      return false;\n    }\n    const isPipeCall = exprText === 'pipe' || exprText.endsWith('.pipe');\n    const dotIndex = exprText.indexOf('.');\n    if (dotIndex > 0 && isNonProgramName(exprText.slice(0, dotIndex))) {\n      return false;\n    }\n    return (\n      isPipeCall ||\n      [...effectImportNames].some((alias) => exprText.startsWith(`${alias}.`))\n    );\n  };\n\n  const isLikelyEffectCall = (call: CallExpression): boolean => {\n    const callee = call.getExpression();\n    const exprText = callee.getText();\n    if (isRunEntrypointCalleeText(exprText)) {\n      return false;\n    }\n    const isPipeCall = exprText === 'pipe';\n    const isMethodPipeCall =\n      callee.getKind() === SyntaxKind.PropertyAccessExpression &&\n      (callee as PropertyAccessExpression).getName() === 'pipe';\n    if (isPipeCall || isMethodPipeCall) {\n      const argsContainEffect = call.getArguments().some((arg) =>\n        isLikelyDirectEffectInitializer(arg, effectImportNames, nonProgramEffectImportNames)\n      );\n      if (argsContainEffect) {\n        return true;\n      }\n      if (isMethodPipeCall) {\n        const base = (callee as PropertyAccessExpression).getExpression();\n        return isLikelyDirectEffectInitializer(\n          base,\n          effectImportNames,\n          nonProgramEffectImportNames,\n        );\n      }\n      return false;\n    }\n    if (\n      callee.getKind() === SyntaxKind.Identifier &&\n      effectImportNames.has(exprText) &&\n      !isNonProgramName(exprText)\n    ) {\n      return true;\n    }\n    if (isDirectEffectCalleeText(exprText)) {\n      return true;\n    }\n\n    // Builder / wrapper chains: inspect call receiver and arguments for effectful callbacks,\n    // e.g. make(() => Effect.never).identified(\"Never\")\n    if (\n      callee.getKind() === SyntaxKind.PropertyAccessExpression &&\n      isLikelyDirectEffectInitializer(\n        (callee as PropertyAccessExpression).getExpression(),\n        effectImportNames,\n        nonProgramEffectImportNames,\n      )\n    ) {\n      return true;\n    }\n\n    return call.getArguments().some((arg) =>\n      isLikelyDirectEffectInitializer(arg, effectImportNames, nonProgramEffectImportNames)\n    );\n  };\n\n  /** True when `node` is NOT inside a nested function/arrow/method relative to `scope`. */\n  const isInSameScope = (node: Node, scope: Node): boolean => {\n    let current = node.getParent();\n    while (current && current !== scope) {\n      const k = current.getKind();\n      if (\n        k === SyntaxKind.FunctionDeclaration ||\n        k === SyntaxKind.FunctionExpression ||\n        k === SyntaxKind.ArrowFunction ||\n        k === SyntaxKind.MethodDeclaration ||\n        k === SyntaxKind.GetAccessor ||\n        k === SyntaxKind.SetAccessor ||\n        k === SyntaxKind.ClassDeclaration ||\n        k === SyntaxKind.ClassExpression ||\n        k === SyntaxKind.Constructor ||\n        k === SyntaxKind.ClassStaticBlockDeclaration\n      ) {\n        return false;\n      }\n      current = current.getParent();\n    }\n    return true;\n  };\n\n  const blockContainsEffectLikeUsage = (block: import('ts-morph').Block): boolean => {\n    const callExprs = block.getDescendantsOfKind(SyntaxKind.CallExpression);\n    if (callExprs.some((call) => isInSameScope(call, block) && isLikelyEffectCall(call))) {\n      return true;\n    }\n\n    const awaitedExprs = block.getDescendantsOfKind(SyntaxKind.AwaitExpression);\n    if (\n      awaitedExprs.some((awaitExpr) =>\n        isInSameScope(awaitExpr, block) &&\n        isLikelyDirectEffectInitializer(awaitExpr, effectImportNames, nonProgramEffectImportNames)\n      )\n    ) {\n      return true;\n    }\n\n    const propertyAccessExprs = block.getDescendantsOfKind(\n      SyntaxKind.PropertyAccessExpression,\n    );\n    return propertyAccessExprs.some((expr) =>\n      isInSameScope(expr, block) &&\n      isLikelyDirectEffectInitializer(expr, effectImportNames, nonProgramEffectImportNames)\n    );\n  };\n\n  const blockContainsRunEntrypointUsage = (block: import('ts-morph').Block): boolean =>\n    block\n      .getDescendantsOfKind(SyntaxKind.CallExpression)\n      .some((call) => isInSameScope(call, block) && isRunEntrypointCalleeText((call).getExpression().getText()));\n\n  if (initializer.getKind() === SyntaxKind.ObjectLiteralExpression) {\n    const obj = initializer as ObjectLiteralExpression;\n    return obj.getProperties().some((prop) => {\n      if (\n        prop.getKind() === SyntaxKind.PropertyAssignment ||\n        prop.getKind() === SyntaxKind.ShorthandPropertyAssignment\n      ) {\n        const init =\n          prop.getKind() === SyntaxKind.PropertyAssignment\n            ? (prop as PropertyAssignment).getInitializer()\n            : undefined;\n        return init\n          ? isLikelyDirectEffectInitializer(init, effectImportNames, nonProgramEffectImportNames)\n          : false;\n      }\n      if (\n        prop.getKind() === SyntaxKind.MethodDeclaration ||\n        prop.getKind() === SyntaxKind.GetAccessor ||\n        prop.getKind() === SyntaxKind.SetAccessor\n      ) {\n        const body = (\n          prop as\n            | import('ts-morph').MethodDeclaration\n            | import('ts-morph').GetAccessorDeclaration\n            | import('ts-morph').SetAccessorDeclaration\n        ).getBody();\n        return body\n          ? blockContainsEffectLikeUsage(body as Block)\n          : false;\n      }\n      return false;\n    });\n  }\n\n  if (\n    initializer.getKind() === SyntaxKind.ArrowFunction ||\n    initializer.getKind() === SyntaxKind.FunctionExpression\n  ) {\n    const fn = initializer as ArrowFunction | FunctionExpression;\n    const body = fn.getBody();\n\n    if (body.getKind() === SyntaxKind.Block) {\n      const bodyBlock = body as Block;\n      // Check return statements in the current function scope (if/else/switch branches)\n      // but NOT those inside nested functions/callbacks.\n      const returnStmts = bodyBlock.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n      const hasEffectReturn = returnStmts.some((ret) => {\n        if (!isInSameScope(ret, bodyBlock)) return false;\n        const expr = ret.getExpression();\n        return expr !== undefined && isLikelyDirectEffectInitializer(\n          expr,\n          effectImportNames,\n          nonProgramEffectImportNames,\n        );\n      });\n      if (hasEffectReturn) {\n        return true;\n      }\n      // Only fall back to body heuristic if no run* entrypoint is present —\n      // a function that merely executes an Effect (runSync/runPromise/…)\n      // without returning one is not itself an Effect program.\n      if (blockContainsRunEntrypointUsage(bodyBlock)) {\n        return false;\n      }\n      return blockContainsEffectLikeUsage(bodyBlock);\n    }\n\n    return isLikelyDirectEffectInitializer(body, effectImportNames, nonProgramEffectImportNames);\n  }\n\n  if (initializer.getKind() === SyntaxKind.CallExpression) {\n    return isLikelyEffectCall(initializer as CallExpression);\n  }\n\n  if (initializer.getKind() === SyntaxKind.AwaitExpression) {\n    const awaited = (\n      initializer as AwaitExpression\n    ).getExpression();\n    if (awaited.getKind() !== SyntaxKind.CallExpression) {\n      return false;\n    }\n    return isLikelyEffectCall(awaited as CallExpression);\n  }\n\n  if (initializer.getKind() === SyntaxKind.ConditionalExpression) {\n    const conditional = initializer as ConditionalExpression;\n    return (\n      isLikelyDirectEffectInitializer(\n        conditional.getWhenTrue(),\n        effectImportNames,\n        nonProgramEffectImportNames,\n      ) ||\n      isLikelyDirectEffectInitializer(\n        conditional.getWhenFalse(),\n        effectImportNames,\n        nonProgramEffectImportNames,\n      )\n    );\n  }\n\n  if (initializer.getKind() === SyntaxKind.PropertyAccessExpression) {\n    const text = initializer.getText();\n    const dotIndex = text.indexOf('.');\n    if (dotIndex > 0 && isNonProgramName(text.slice(0, dotIndex))) {\n      return false;\n    }\n    return [...effectImportNames].some((alias) => text.startsWith(`${alias}.`));\n  }\n\n  return false;\n};\n\nexport function isEffectPackageSpecifier(specifier: string): boolean {\n  return (\n    specifier === 'effect' ||\n    specifier.startsWith('effect/') ||\n    specifier.startsWith('@effect/')\n  );\n}\n\nexport const EFFECT_NAMESPACE_NAMES = new Set([\n  'Effect', 'Layer', 'Schedule', 'Stream', 'Queue', 'PubSub', 'Deferred',\n  'Semaphore', 'Mailbox', 'SubscriptionRef', 'Scope', 'Fiber', 'Runtime', 'ManagedRuntime',\n  'Cause', 'Exit', 'Data', 'Option', 'Either', 'Chunk', 'HashMap', 'HashSet',\n  'Match', 'Config', 'Schema', 'Cache', 'ScopedCache', 'Metric', 'Logger',\n  'Tracer', 'Context', 'Brand', 'Encoding', 'Predicate', 'DateTime', 'Cron',\n  'BigDecimal', 'Graph', 'HashRing', 'Redacted', 'GlobalValue',\n  'NodeRuntime', 'BunRuntime', 'DenoRuntime', 'Channel', 'Sink',\n]);\n\nexport const KNOWN_INTERNAL_MODULES = new Set([\n  'core', 'core-effect', 'core-stream', 'fiberRuntime', 'effectable', 'channel', 'sink', 'layer', 'schedule', 'mailbox', 'pubsub',\n]);\n\n// =============================================================================\n// Numeric literal and Context type parsing\n// =============================================================================\n\nexport function parseServiceIdsFromContextType(requiredType: string): string[] {\n  const skip = new Set(['never', 'unknown', 'any', '{}', 'object']);\n  const normalized = requiredType.trim();\n  if (!normalized || skip.has(normalized)) return [];\n  const parts = normalized.split(/[\\s|&]+/).map((s) => s.trim().split('<')[0]?.trim() ?? '');\n  return parts.filter((s) => s.length > 0 && !skip.has(s));\n}\n\nexport function getNumericLiteralFromNode(node: Node): number | undefined {\n  const { SyntaxKind } = loadTsMorph();\n  const kind = node.getKind();\n  if (kind === SyntaxKind.NumericLiteral) {\n    const text = node.getText();\n    const n = Number(text);\n    return Number.isFinite(n) ? n : undefined;\n  }\n  if (kind === SyntaxKind.PrefixUnaryExpression) {\n    const unary = node as PrefixUnaryExpression;\n    if (unary.getOperatorToken() === SyntaxKind.MinusToken) {\n      const operand = unary.getOperand();\n      const v = getNumericLiteralFromNode(operand);\n      return v !== undefined ? -v : undefined;\n    }\n  }\n  return undefined;\n}\n","/**\n * Small browser-safe path helpers for source-mode analysis.\n *\n * They intentionally normalize to forward slashes so synthetic browser paths\n * and real Node paths behave consistently for relative import lookups.\n */\n\nexport const PATH_SEPARATOR = '/';\n\nconst normalizeSlashes = (value: string): string =>\n  value.replace(/\\\\/g, PATH_SEPARATOR);\n\nexport const normalizePath = (value: string): string => {\n  const normalized = normalizeSlashes(value);\n  const isAbsolute = normalized.startsWith(PATH_SEPARATOR);\n  const parts = normalized.split(PATH_SEPARATOR);\n  const stack: string[] = [];\n\n  for (const part of parts) {\n    if (part === '' || part === '.') {\n      continue;\n    }\n    if (part === '..') {\n      if (stack.length > 0 && stack[stack.length - 1] !== '..') {\n        stack.pop();\n      } else if (!isAbsolute) {\n        stack.push(part);\n      }\n      continue;\n    }\n    stack.push(part);\n  }\n\n  if (isAbsolute) {\n    return `${PATH_SEPARATOR}${stack.join(PATH_SEPARATOR)}` || PATH_SEPARATOR;\n  }\n\n  return stack.join(PATH_SEPARATOR) || '.';\n};\n\nexport const dirnamePath = (value: string): string => {\n  const normalized = normalizePath(value);\n  if (normalized === '.' || normalized === PATH_SEPARATOR) {\n    return '.';\n  }\n  const lastSeparator = normalized.lastIndexOf(PATH_SEPARATOR);\n  if (lastSeparator <= 0) {\n    return normalized.startsWith(PATH_SEPARATOR) ? PATH_SEPARATOR : '.';\n  }\n  return normalized.slice(0, lastSeparator);\n};\n\nexport const joinPath = (...parts: readonly string[]): string =>\n  normalizePath(parts.filter((part) => part.length > 0).join(PATH_SEPARATOR));\n\nexport const resolvePath = (...parts: readonly string[]): string =>\n  normalizePath(parts.filter((part) => part.length > 0).join(PATH_SEPARATOR));\n\nexport const hasPathPrefix = (value: string, prefix: string): boolean => {\n  const normalizedValue = normalizePath(value);\n  const normalizedPrefix = normalizePath(prefix);\n  return (\n    normalizedValue === normalizedPrefix ||\n    normalizedValue.startsWith(`${normalizedPrefix}${PATH_SEPARATOR}`)\n  );\n};\n","/**\n * Alias and module resolution for Effect: file-level alias caches,\n * barrel resolution, and Effect-like call detection.\n */\n\nimport type { SourceFile, CallExpression, PropertyAccessExpression } from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport {\n  PATH_SEPARATOR,\n  dirnamePath,\n  resolvePath,\n  joinPath,\n  hasPathPrefix,\n} from './path-utils';\nimport {\n  API_PREFIXES,\n  isEffectPackageSpecifier,\n  EFFECT_NAMESPACE_NAMES,\n  KNOWN_INTERNAL_MODULES,\n} from './analysis-patterns';\n\n// =============================================================================\n// Caches\n// =============================================================================\n\n/** Per-SourceFile alias cache — avoids global mutable state and races. */\nconst effectAliasCache = new WeakMap<SourceFile, Set<string>>();\n\n/** Per-SourceFile symbol-resolution cache — avoids repeated TypeChecker lookups. */\nconst symbolResolutionCache = new WeakMap<SourceFile, Map<string, boolean>>();\n\ninterface FsModuleLike {\n  readonly existsSync?: (path: string) => boolean;\n}\n\nconst getNodeExistsSync = (): ((path: string) => boolean) | undefined => {\n  const maybeProcess = (\n    globalThis as {\n      process?: { getBuiltinModule?: (id: string) => unknown };\n    }\n  ).process;\n  const fsBuiltin =\n    maybeProcess?.getBuiltinModule?.('node:fs') ??\n    maybeProcess?.getBuiltinModule?.('fs');\n\n  if (!fsBuiltin || typeof fsBuiltin !== 'object') {\n    return undefined;\n  }\n\n  return (fsBuiltin as FsModuleLike).existsSync;\n};\n\n// =============================================================================\n// Barrel and re-export resolution\n// =============================================================================\n\n/**\n * Names that a barrel file re-exports from Effect (export { X } from 'effect' or export * from 'effect').\n * One level only; does not follow barrel → barrel.\n */\nexport function getNamesReExportedFromEffect(barrelSourceFile: SourceFile): Set<string> {\n  const out = new Set<string>();\n  for (const decl of barrelSourceFile.getExportDeclarations()) {\n    const specifier = decl.getModuleSpecifierValue();\n    if (!specifier || !isEffectPackageSpecifier(specifier)) continue;\n    if (decl.isNamespaceExport()) {\n      EFFECT_NAMESPACE_NAMES.forEach((n) => out.add(n));\n      continue;\n    }\n    for (const named of decl.getNamedExports()) {\n      out.add(named.getName());\n      const alias = named.getAliasNode()?.getText();\n      if (alias) out.add(alias);\n    }\n  }\n  return out;\n}\n\n/**\n * Resolve a relative module specifier to a SourceFile in the project (21.5 barrel).\n * Tries exact path and common extensions / index files.\n */\nexport function resolveBarrelSourceFile(\n  project: { getSourceFile: (path: string) => SourceFile | undefined },\n  currentFilePath: string,\n  specifier: string,\n): SourceFile | undefined {\n  if (!specifier.startsWith('.')) return undefined;\n  const baseDir = dirnamePath(currentFilePath);\n  const resolved = resolvePath(baseDir, specifier);\n  const candidates: string[] = [\n    resolved,\n    `${resolved}.ts`,\n    `${resolved}.tsx`,\n    `${resolved}.js`,\n    `${resolved}.jsx`,\n    joinPath(resolved, 'index.ts'),\n    joinPath(resolved, 'index.tsx'),\n    joinPath(resolved, 'index.js'),\n    joinPath(resolved, 'index.jsx'),\n  ];\n  for (const p of candidates) {\n    const f = project.getSourceFile(p);\n    if (f) return f;\n  }\n  return undefined;\n}\n\n/**\n * Resolve a relative module specifier to an absolute path (first candidate that exists).\n * Used to add a referenced file to the project when symbol resolution doesn't load it.\n */\nexport function resolveModulePath(\n  currentFilePath: string,\n  specifier: string,\n): string | undefined {\n  if (!specifier.startsWith('.')) return undefined;\n  const existsSync = getNodeExistsSync();\n  if (!existsSync) {\n    return undefined;\n  }\n\n  const baseDir = dirnamePath(currentFilePath);\n  const resolved = resolvePath(baseDir, specifier);\n  const candidates: string[] = [\n    resolved,\n    `${resolved}.ts`,\n    `${resolved}.tsx`,\n    `${resolved}.js`,\n    `${resolved}.jsx`,\n    joinPath(resolved, 'index.ts'),\n    joinPath(resolved, 'index.tsx'),\n    joinPath(resolved, 'index.js'),\n    joinPath(resolved, 'index.jsx'),\n  ];\n  return candidates.find((p) => existsSync(p));\n}\n\n/**\n * Returns true when a relative import specifier resolves to a path at or under\n * the configured Effect internals root. Extensionless resolution is intentional:\n * imports often point at `./internal/foo.js` while callers pass the folder root.\n */\nexport function isSpecifierUnderKnownEffectInternalsRoot(\n  currentFilePath: string,\n  specifier: string,\n  knownEffectInternalsRoot?: string,\n): boolean {\n  if (!knownEffectInternalsRoot || !specifier.startsWith('.')) return false;\n  const normalizedSpecifier = specifier.replace(/\\\\/g, '/');\n  const normalizedResolved = resolvePath(dirnamePath(currentFilePath), specifier);\n  const normalizedRoot = resolvePath(knownEffectInternalsRoot);\n  if (hasPathPrefix(normalizedResolved, normalizedRoot)) {\n    return true;\n  }\n\n  // `analyze.source(...)` uses an in-memory synthetic file path (e.g. `temp.ts`),\n  // so path resolution cannot be related to the caller-provided internals root.\n  // Preserve regression coverage in source-mode while keeping path resolution primary\n  // for real files.\n  const isSyntheticSourcePath =\n    currentFilePath === 'temp.ts' ||\n    currentFilePath.endsWith(`${PATH_SEPARATOR}temp.ts`);\n  if (isSyntheticSourcePath) {\n    return normalizedSpecifier.startsWith('./internal/') || normalizedSpecifier.startsWith('../internal/');\n  }\n\n  return false;\n}\n\n/** Gap 5 / 21.5: Collect names that refer to Effect (from 'effect', 'effect/*', '@effect/*', or barrel re-exports). */\nexport function getEffectImportNames(sourceFile: SourceFile): Set<string> {\n  const names = new Set<string>(EFFECT_NAMESPACE_NAMES);\n  const project = sourceFile.getProject();\n  const currentPath = sourceFile.getFilePath();\n\n  for (const decl of sourceFile.getImportDeclarations()) {\n    const specifier = decl.getModuleSpecifierValue();\n    if (isEffectPackageSpecifier(specifier)) {\n      const def = decl.getDefaultImport();\n      if (def) names.add(def.getText());\n      const ns = decl.getNamespaceImport();\n      if (ns) names.add(ns.getText());\n      for (const named of decl.getNamedImports()) {\n        const alias = named.getAliasNode()?.getText();\n        names.add(alias ?? named.getName());\n      }\n      continue;\n    }\n    if (specifier.startsWith('.')) {\n      const barrelFile = resolveBarrelSourceFile(project, currentPath, specifier);\n      if (!barrelFile) continue;\n      const reExported = getNamesReExportedFromEffect(barrelFile);\n\n      // Collect all import names to check\n      const toCheck: { name: string; localName: string }[] = [];\n      const def = decl.getDefaultImport();\n      if (def) {\n        const text = def.getText();\n        toCheck.push({ name: text, localName: text });\n      }\n      const ns = decl.getNamespaceImport();\n      if (ns) {\n        const text = ns.getText();\n        toCheck.push({ name: text, localName: text });\n      }\n      for (const named of decl.getNamedImports()) {\n        toCheck.push({\n          name: named.getName(),\n          localName: named.getAliasNode()?.getText() ?? named.getName(),\n        });\n      }\n\n      // Fast path: check one-level re-exports first\n      let needsDeepTrace = false;\n      for (const entry of toCheck) {\n        if (reExported.has(entry.name)) {\n          names.add(entry.localName);\n        } else {\n          needsDeepTrace = true;\n        }\n      }\n\n      // Slow path: only trace deeper when one-level check missed some imports\n      if (needsDeepTrace) {\n        for (const entry of toCheck) {\n          if (!reExported.has(entry.name) && traceReExportChain(barrelFile, entry.name, project, 3)) {\n            names.add(entry.localName);\n          }\n        }\n      }\n    }\n  }\n  return names;\n}\n\n/**\n * Enhanced alias set: includes standard Effect import names PLUS namespace\n * imports from known internal modules (e.g. `import * as core from \"./core\"`).\n */\nexport function getEffectLikeNamespaceAliases(\n  sourceFile: SourceFile,\n  knownEffectInternalsRoot?: string,\n): Set<string> {\n  const aliases = getEffectImportNames(sourceFile);\n\n  for (const importDecl of sourceFile.getImportDeclarations()) {\n    const moduleSpecifier = importDecl.getModuleSpecifierValue();\n    const namespaceImport = importDecl.getNamespaceImport();\n    if (!namespaceImport) continue;\n\n    const aliasName = namespaceImport.getText();\n\n    if (moduleSpecifier.startsWith('effect') || moduleSpecifier.startsWith('@effect/')) {\n      aliases.add(aliasName);\n      continue;\n    }\n\n    if (\n      isSpecifierUnderKnownEffectInternalsRoot(\n        sourceFile.getFilePath(),\n        moduleSpecifier,\n        knownEffectInternalsRoot,\n      )\n    ) {\n      aliases.add(aliasName);\n      continue;\n    }\n\n    const basename = moduleSpecifier.replace(/\\.(js|ts)$/, '').split('/').pop() ?? '';\n    if (KNOWN_INTERNAL_MODULES.has(basename)) {\n      aliases.add(aliasName);\n    }\n  }\n\n  return aliases;\n}\n\nconst NON_PROGRAM_EFFECT_MODULE_BASENAMES = new Set([\n  'BigDecimal',\n  'BigInt',\n  'Brand',\n  'Cause',\n  'Chunk',\n  'Data',\n  'Exit',\n  'Option',\n  'Either',\n  'HashMap',\n  'HashSet',\n  'List',\n  'Redacted',\n]);\n\n/**\n * Local import names that come from Effect utility/data modules we do not want to\n * treat as direct \"program\" roots (e.g. Option.some / Either.right).\n */\nexport function getNonProgramEffectImportNames(sourceFile: SourceFile): Set<string> {\n  const out = new Set<string>();\n\n  for (const importDecl of sourceFile.getImportDeclarations()) {\n    const specifier = importDecl.getModuleSpecifierValue();\n    const normalized = specifier.replace(/\\\\/g, '/').replace(/\\.(js|ts|tsx|jsx)$/, '');\n    const basename = normalized.split('/').pop() ?? '';\n    if (!NON_PROGRAM_EFFECT_MODULE_BASENAMES.has(basename)) continue;\n\n    const def = importDecl.getDefaultImport();\n    if (def) out.add(def.getText());\n    const ns = importDecl.getNamespaceImport();\n    if (ns) out.add(ns.getText());\n    for (const named of importDecl.getNamedImports()) {\n      out.add(named.getAliasNode()?.getText() ?? named.getName());\n    }\n  }\n\n  return out;\n}\n\n// =============================================================================\n// Public alias accessor (cached)\n// =============================================================================\n\nexport function getAliasesForFile(sf: SourceFile): Set<string> {\n  let aliases = effectAliasCache.get(sf);\n  if (!aliases) {\n    aliases = getEffectLikeNamespaceAliases(sf);\n    effectAliasCache.set(sf, aliases);\n  }\n  return aliases;\n}\n\n/** Cache: sourceFile -> (local alias -> canonical Effect namespace, e.g. \"L\" -> \"Layer\"). */\nconst effectSubmoduleAliasCache = new WeakMap<SourceFile, Map<string, string>>();\n\n/**\n * Derive the canonical Effect namespace from a module specifier.\n * - \"effect\" or \"effect/Effect\" -> \"Effect\"\n * - \"effect/Layer\" -> \"Layer\", \"effect/Stream\" -> \"Stream\", etc.\n */\nfunction canonicalNamespaceFromSpecifier(specifier: string): string {\n  const n = specifier.replace(/\\\\/g, '/').replace(/\\.(js|ts|mts|cts)$/, '');\n  if (n === 'effect' || n.endsWith('/Effect')) return 'Effect';\n  const segment = n.split('/').pop() ?? '';\n  return segment || 'Effect';\n}\n\n/**\n * Returns a map from local namespace alias to canonical Effect submodule name.\n * E.g. import * as L from \"effect/Layer\" => L -> \"Layer\".\n * Used to normalize callees like L.succeed to Layer.succeed for layer/stream detection.\n */\nexport function getEffectSubmoduleAliasMap(sourceFile: SourceFile): Map<string, string> {\n  let map = effectSubmoduleAliasCache.get(sourceFile);\n  if (map) return map;\n  map = new Map();\n  for (const decl of sourceFile.getImportDeclarations()) {\n    const specifier = decl.getModuleSpecifierValue();\n    if (!specifier || !isEffectPackageSpecifier(specifier)) continue;\n\n    // Handle namespace imports: import * as L from \"effect/Layer\" => L -> Layer\n    const nsImport = decl.getNamespaceImport();\n    if (nsImport) {\n      const aliasName = nsImport.getText();\n      const canonical = canonicalNamespaceFromSpecifier(specifier);\n      map.set(aliasName, canonical);\n      continue;\n    }\n\n    // Handle named imports with aliases: import { Match as M } from \"effect\" => M -> Match\n    for (const named of decl.getNamedImports()) {\n      const alias = named.getAliasNode()?.getText();\n      if (alias) {\n        const originalName = named.getName();\n        map.set(alias, originalName);\n      }\n    }\n  }\n  effectSubmoduleAliasCache.set(sourceFile, map);\n  return map;\n}\n\n/**\n * Normalize a callee string using the file's Effect submodule alias map.\n * E.g. \"L.succeed\" with L -> Layer becomes \"Layer.succeed\".\n */\nexport function normalizeEffectCallee(callee: string, sourceFile: SourceFile): string {\n  const dotIdx = callee.indexOf('.');\n  if (dotIdx <= 0) return callee;\n  const ns = callee.slice(0, dotIdx);\n  const rest = callee.slice(dotIdx + 1);\n  const aliasMap = getEffectSubmoduleAliasMap(sourceFile);\n  const canonical = aliasMap.get(ns);\n  if (!canonical) return callee;\n  return `${canonical}.${rest}`;\n}\n\n// =============================================================================\n// Module origin resolution\n// =============================================================================\n\n/**\n * Trace a re-export chain up to `maxDepth` levels to determine if a name\n * ultimately originates from an Effect package.\n */\nfunction traceReExportChain(\n  barrelFile: SourceFile,\n  name: string,\n  project: { getSourceFile: (path: string) => SourceFile | undefined },\n  maxDepth: number,\n): boolean {\n  if (maxDepth <= 0) return false;\n\n  for (const exportDecl of barrelFile.getExportDeclarations()) {\n    const specifier = exportDecl.getModuleSpecifierValue();\n    if (!specifier) continue;\n\n    // Check if this export contains the name, and resolve the original name\n    // through any alias (e.g. export { E as Fx } — name=\"Fx\", originalName=\"E\")\n    let originalName: string | undefined;\n    if (exportDecl.isNamespaceExport()) {\n      originalName = name; // namespace re-export covers all names unchanged\n    } else {\n      for (const namedExport of exportDecl.getNamedExports()) {\n        const alias = namedExport.getAliasNode()?.getText();\n        if (alias === name) {\n          // export { E as Fx } — looking for \"Fx\", original is \"E\"\n          originalName = namedExport.getName();\n          break;\n        }\n        if (namedExport.getName() === name) {\n          // export { E } — no rename\n          originalName = name;\n          break;\n        }\n      }\n    }\n\n    if (originalName === undefined) continue;\n\n    // If it re-exports from an Effect package, we found it\n    if (isEffectPackageSpecifier(specifier)) return true;\n\n    // If it re-exports from a local module, recurse with the original name\n    if (specifier.startsWith('.')) {\n      const nextBarrel = resolveBarrelSourceFile(project, barrelFile.getFilePath(), specifier);\n      if (nextBarrel) {\n        const fromEffect = getNamesReExportedFromEffect(nextBarrel);\n        if (fromEffect.has(originalName)) return true;\n        if (traceReExportChain(nextBarrel, originalName, project, maxDepth - 1)) return true;\n      }\n    }\n  }\n\n  return false;\n}\n\n/**\n * Resolve whether a callee expression originates from an Effect package\n * by tracing its import declaration. Fallback when API_PREFIXES and alias checks don't match.\n */\nfunction resolveCalleeModuleOrigin(calleeText: string, sourceFile: SourceFile): boolean {\n  let cache = symbolResolutionCache.get(sourceFile);\n  if (!cache) {\n    cache = new Map();\n    symbolResolutionCache.set(sourceFile, cache);\n  }\n\n  const dotIdx = calleeText.indexOf('.');\n  const nsText = dotIdx > 0 ? calleeText.slice(0, dotIdx) : calleeText;\n  const cached = cache.get(nsText);\n  if (cached !== undefined) return cached;\n\n  let result = false;\n  try {\n    for (const importDecl of sourceFile.getImportDeclarations()) {\n      const specifier = importDecl.getModuleSpecifierValue();\n\n      const nsImport = importDecl.getNamespaceImport();\n      if (nsImport?.getText() === nsText) {\n        result = isEffectPackageSpecifier(specifier);\n        break;\n      }\n\n      const defImport = importDecl.getDefaultImport();\n      if (defImport?.getText() === nsText) {\n        result = isEffectPackageSpecifier(specifier);\n        break;\n      }\n\n      for (const named of importDecl.getNamedImports()) {\n        const alias = named.getAliasNode()?.getText();\n        const localName = alias ?? named.getName();\n        if (localName === nsText) {\n          if (isEffectPackageSpecifier(specifier)) {\n            result = true;\n          } else if (specifier.startsWith('.')) {\n            const barrelFile = resolveBarrelSourceFile(\n              sourceFile.getProject(), sourceFile.getFilePath(), specifier\n            );\n            if (barrelFile) {\n              const reExported = getNamesReExportedFromEffect(barrelFile);\n              if (reExported.has(named.getName())) {\n                result = true;\n              } else {\n                // Multi-level: trace through barrel → barrel chains (up to 3 levels)\n                result = traceReExportChain(barrelFile, named.getName(), sourceFile.getProject(), 3);\n              }\n            }\n          }\n          break;\n        }\n      }\n      if (result) break;\n    }\n  } catch {\n    result = false;\n  }\n\n  cache.set(nsText, result);\n  return result;\n}\n\n/**\n * Resolve the module specifier for the namespace part of a property access (e.g. E in E.succeed).\n * Returns the import's module specifier string, or undefined if not found.\n */\nfunction resolveNamespaceImportModuleSpecifier(\n  expr: import('ts-morph').PropertyAccessExpression,\n  sourceFile: SourceFile,\n): string | undefined {\n  const nsExpr = expr.getExpression();\n  const nsText = nsExpr.getText();\n  for (const importDecl of sourceFile.getImportDeclarations()) {\n    const specifier = importDecl.getModuleSpecifierValue();\n    const nsImport = importDecl.getNamespaceImport();\n    if (nsImport?.getText() === nsText) return specifier;\n    const defImport = importDecl.getDefaultImport();\n    if (defImport?.getText() === nsText) return specifier;\n    for (const named of importDecl.getNamedImports()) {\n      const alias = named.getAliasNode()?.getText();\n      const localName = alias ?? named.getName();\n      if (localName === nsText) return specifier;\n    }\n  }\n  return undefined;\n}\n\n// =============================================================================\n// Effect-like call detection\n// =============================================================================\n\n/**\n * Symbol/typechecker-backed check for Effect-like call. Fast path: API_PREFIXES + file alias set;\n * fallback: resolve callee namespace to module specifier and classify by origin.\n * Optional knownEffectInternalsRoot: local paths under that root are treated as Effect-like (improve.md §1).\n */\nexport function isEffectLikeCallExpression(\n  call: CallExpression,\n  sourceFile: SourceFile,\n  effectAliases: Set<string>,\n  knownEffectInternalsRoot?: string,\n): boolean {\n  const expr = call.getExpression();\n  const text = expr.getText();\n  if (API_PREFIXES.some((p) => text.startsWith(p)) || text.startsWith('pipe(')) return true;\n  for (const alias of effectAliases) {\n    if (text.startsWith(`${alias}.`)) return true;\n  }\n  const { SyntaxKind } = loadTsMorph();\n  if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return false;\n  const propAccess = expr as PropertyAccessExpression;\n  const specifier = resolveNamespaceImportModuleSpecifier(propAccess, sourceFile);\n  if (!specifier) return false;\n  if (isEffectPackageSpecifier(specifier)) return true;\n  if (specifier.startsWith('.')) {\n    const barrelFile = resolveBarrelSourceFile(\n      sourceFile.getProject(),\n      sourceFile.getFilePath(),\n      specifier,\n    );\n    if (barrelFile) {\n      const reExported = getNamesReExportedFromEffect(barrelFile);\n      const nsText = propAccess.getExpression().getText();\n      for (const importDecl of sourceFile.getImportDeclarations()) {\n        if (importDecl.getModuleSpecifierValue() !== specifier) continue;\n        for (const named of importDecl.getNamedImports()) {\n          const localName = named.getAliasNode()?.getText() ?? named.getName();\n          if (localName === nsText && reExported.has(named.getName())) return true;\n        }\n      }\n    }\n    if (\n      isSpecifierUnderKnownEffectInternalsRoot(\n        sourceFile.getFilePath(),\n        specifier,\n        knownEffectInternalsRoot,\n      )\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * Check if callee text is an Effect API call (prefix, alias, or symbol-resolved).\n */\nexport function isEffectCallee(\n  text: string,\n  effectAliases?: Set<string>,\n  sourceFile?: SourceFile,\n): boolean {\n  if (API_PREFIXES.some((prefix) => text.startsWith(prefix)) || text.startsWith('pipe(')) {\n    return true;\n  }\n  if (effectAliases) {\n    for (const alias of effectAliases) {\n      if (text.startsWith(`${alias}.`)) return true;\n    }\n  }\n  if (sourceFile && text.includes('.')) {\n    return resolveCalleeModuleOrigin(text, sourceFile);\n  }\n  return false;\n}\n","/**\n * Effect program discovery: find Effect.gen, pipe, run, class, and class-member programs.\n */\n\nimport type {\n  SourceFile,\n  Node,\n  CallExpression,\n  VariableDeclaration,\n  PropertyAccessExpression,\n  Identifier,\n  AwaitExpression,\n  ArrowFunction,\n  FunctionExpression,\n  PropertyDeclaration,\n  MethodDeclaration,\n  GetAccessorDeclaration,\n  FunctionDeclaration,\n  ClassDeclaration,\n  ReturnStatement,\n  ExpressionStatement,\n  TypeNode,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type { AnalyzerOptions, ServiceDefinition } from './types';\nimport { extractProgramName, extractEnclosingEffectFnName } from './analysis-utils';\nimport type { EffectProgram } from './analysis-utils';\n\nexport type { EffectProgram } from './analysis-utils';\nimport { isLikelyDirectEffectInitializer } from './analysis-patterns';\nimport {\n  getEffectLikeNamespaceAliases,\n  getNonProgramEffectImportNames,\n  isSpecifierUnderKnownEffectInternalsRoot,\n  isEffectLikeCallExpression,\n} from './alias-resolution';\n\n// =============================================================================\n// Workflow (effect-workflow) helpers\n// =============================================================================\n\nconst WORKFLOW_FACTORY_NAMES = new Set([\n  'createWorkflow',\n  'createSagaWorkflow',\n  'runSaga',\n]);\n\nconst isWorkflowFactoryCall = (calleeText: string): boolean =>\n  Array.from(WORKFLOW_FACTORY_NAMES).some(\n    (name) => calleeText === name || calleeText.endsWith(`.${name}`),\n  );\n\n/** Returns true if call is X.make(name, deps?, fn, options?) with at least 3 args and 3rd is a function. */\nconst isWorkflowMakeCall = (call: CallExpression): boolean => {\n  const expr = call.getExpression();\n  if (expr.getKind() !== loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n    return false;\n  }\n  const prop = expr as PropertyAccessExpression;\n  const args = call.getArguments();\n  if (prop.getName() !== 'make' || args.length < 3 || !args[2]) {\n    return false;\n  }\n  const third = args[2].getKind();\n  const { SyntaxKind } = loadTsMorph();\n  return (\n    third === SyntaxKind.ArrowFunction || third === SyntaxKind.FunctionExpression\n  );\n};\n\n// =============================================================================\n// Effect package workflow\n// =============================================================================\n\n/** True if the module specifier refers to the workflow package. */\nfunction isWorkflowPackageSpecifier(specifier: string, _currentFilePath?: string): boolean {\n  const n = specifier.replace(/\\\\/g, '/');\n  if (n === '@effect/workflow' || n === 'effect/workflow') return true;\n  if (n.endsWith('/workflow') || n.includes('/workflow/')) return true;\n  if (n.endsWith('/Workflow.js') || n.endsWith('/Workflow.ts')) return true;\n  if (n.endsWith('/Activity.js') || n.endsWith('/Activity.ts')) return true;\n  if (n.startsWith('.') && (n.endsWith('Workflow.js') || n.endsWith('Workflow.ts') || n.endsWith('Activity.js') || n.endsWith('Activity.ts'))) return true;\n  return false;\n}\n\nfunction isWorkflowNamespaceFromPackage(\n  localName: string,\n  specifier: string,\n  _currentFilePath?: string,\n): boolean {\n  if (localName !== 'Workflow') return false;\n  return isWorkflowPackageSpecifier(specifier, _currentFilePath);\n}\n\nfunction isActivityNamespaceFromPackage(\n  localName: string,\n  specifier: string,\n  _currentFilePath?: string,\n): boolean {\n  if (localName !== 'Activity') return false;\n  return isWorkflowPackageSpecifier(specifier, _currentFilePath);\n}\n\nfunction objectArgHasAnyProperty(\n  call: CallExpression,\n  propertyNames: readonly string[],\n): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  const args = call.getArguments();\n  if (args.length !== 1 || !args[0]) return false;\n  const arg = args[0];\n  if (arg.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n  const obj = arg as ObjectLiteralExpression;\n  const props = obj.getProperties();\n  const names = new Set(propertyNames);\n  for (const p of props) {\n    if (p.getKind() === SyntaxKind.PropertyAssignment) {\n      const name = (p as PropertyAssignment).getName();\n      if (names.has(name)) return true;\n    }\n  }\n  return false;\n}\n\nfunction isWorkflowMakeOptionsCall(\n  call: CallExpression,\n  importSpecifierByLocalName: Map<string, string>,\n  currentFilePath: string,\n): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  const expr = call.getExpression();\n  if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return false;\n  const prop = expr as PropertyAccessExpression;\n  if (prop.getName() !== 'make') return false;\n  const baseText = prop.getExpression().getText();\n  const specifier = importSpecifierByLocalName.get(baseText);\n  if (!specifier || !isWorkflowNamespaceFromPackage(baseText, specifier, currentFilePath)) return false;\n  return objectArgHasAnyProperty(call, ['name', 'payload', 'idempotencyKey']);\n}\n\nfunction isActivityMakeOptionsCall(\n  call: CallExpression,\n  importSpecifierByLocalName: Map<string, string>,\n  currentFilePath: string,\n): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  const expr = call.getExpression();\n  if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return false;\n  const prop = expr as PropertyAccessExpression;\n  if (prop.getName() !== 'make') return false;\n  const baseText = prop.getExpression().getText();\n  const specifier = importSpecifierByLocalName.get(baseText);\n  if (!specifier || !isActivityNamespaceFromPackage(baseText, specifier, currentFilePath)) return false;\n  return objectArgHasAnyProperty(call, ['name', 'execute']);\n}\n\n/**\n * For X.run(singleArg) (e.g. effect-workflow Workflow.run(workflow)), resolve the single\n * argument to the workflow body (the callback passed to Workflow.make). Returns the AST\n * node for that callback or null.\n */\nexport const getWorkflowBodyNodeForRunCall = (\n  runCall: CallExpression,\n  sourceFile: SourceFile,\n): Node | null => {\n  const expr = runCall.getExpression();\n  if (expr.getKind() !== loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n    return null;\n  }\n  const prop = expr as PropertyAccessExpression;\n  if (prop.getName() !== 'run') {\n    return null;\n  }\n  const args = runCall.getArguments();\n  if (args.length < 1 || !args[0]) {\n    return null;\n  }\n  const arg = args[0];\n  const { SyntaxKind } = loadTsMorph();\n\n  if (arg.getKind() === SyntaxKind.CallExpression) {\n    const innerCall = arg as CallExpression;\n    if (isWorkflowMakeCall(innerCall)) {\n      const makeArgs = innerCall.getArguments();\n      return makeArgs[2] ?? null;\n    }\n    return null;\n  }\n\n  if (arg.getKind() !== SyntaxKind.Identifier) {\n    return null;\n  }\n  const id = arg as Identifier;\n  const name = id.getText();\n  const varDecls = sourceFile.getDescendantsOfKind(\n    SyntaxKind.VariableDeclaration,\n  );\n  for (const decl of varDecls) {\n    if ((decl).getName() !== name) {\n      continue;\n    }\n    const initializer = (decl).getInitializer();\n    if (\n      initializer?.getKind() === SyntaxKind.CallExpression &&\n      isWorkflowMakeCall(initializer as CallExpression)\n    ) {\n      const makeArgs = (initializer as CallExpression).getArguments();\n      return makeArgs[2] ?? null;\n    }\n  }\n  return null;\n};\n\n// =============================================================================\n// Scope and run detection\n// =============================================================================\n\nconst isInsideEffectGen = (node: Node): boolean => {\n  const { SyntaxKind } = loadTsMorph();\n  let current = node.getParent();\n  while (current) {\n    if (current.getKind() === SyntaxKind.CallExpression) {\n      const expr = (current as CallExpression).getExpression();\n      const text = expr.getText();\n      if (text.includes('.gen') || text === 'gen') {\n        return true;\n      }\n    }\n    current = current.getParent();\n  }\n  return false;\n};\n\nconst isTopLevelVariableDeclaration = (decl: VariableDeclaration): boolean => {\n  const { SyntaxKind } = loadTsMorph();\n  const statement = decl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n  return statement?.getParent()?.getKind() === SyntaxKind.SourceFile;\n};\n\nconst isYieldBoundDeclaration = (decl: VariableDeclaration): boolean => {\n  const { SyntaxKind } = loadTsMorph();\n  const initializer = decl.getInitializer();\n  if (!initializer) return false;\n  if (initializer.getKind() === SyntaxKind.YieldExpression) return true;\n  if (\n    initializer.getKind() === SyntaxKind.AwaitExpression &&\n    (\n      initializer as AwaitExpression\n    ).getExpression().getKind() === SyntaxKind.YieldExpression\n  ) {\n    return true;\n  }\n  return false;\n};\n\nconst getCallExpressionFromInitializer = (\n  initializer: Node,\n): CallExpression | undefined => {\n  const { SyntaxKind } = loadTsMorph();\n  if (initializer.getKind() === SyntaxKind.CallExpression) {\n    return initializer as CallExpression;\n  }\n  if (initializer.getKind() === SyntaxKind.AwaitExpression) {\n    const awaited = (\n      initializer as AwaitExpression\n    ).getExpression();\n    if (awaited.getKind() === SyntaxKind.CallExpression) {\n      return awaited as CallExpression;\n    }\n  }\n  return undefined;\n};\n\ntype DiscoveryConfidence = NonNullable<EffectProgram['discoveryConfidence']>;\n\ninterface DiscoveryInfo {\n  readonly discoveryConfidence: DiscoveryConfidence;\n  readonly discoveryReason: string;\n}\n\nconst buildDiscoveryInfo = (\n  discoveryConfidence: DiscoveryConfidence,\n  discoveryReason: string,\n): DiscoveryInfo => ({ discoveryConfidence, discoveryReason });\n\nconst EFFECT_FAMILY_TYPE_HINTS = [\n  'Effect<',\n  'Layer<',\n  'Layer.Layer<',\n  'Stream<',\n  'Stream.Stream<',\n  'Channel<',\n  'Channel.Channel<',\n  'Sink<',\n  'Sink.Sink<',\n  'STM<',\n  'STM.STM<',\n  'Schedule<',\n  'Schedule.Schedule<',\n];\n\nconst hasEffectFamilyTypeHint = (text: string | undefined): boolean =>\n  text !== undefined && EFFECT_FAMILY_TYPE_HINTS.some((hint) => text.includes(hint));\n\nconst DISCOVERY_CONFIDENCE_RANK: Record<DiscoveryConfidence, number> = {\n  low: 0,\n  medium: 1,\n  high: 2,\n};\n\nconst isRunCall = (call: CallExpression): boolean => {\n  const exprText = call.getExpression().getText();\n  return (\n    exprText.includes('.runPromise') ||\n    exprText.includes('.runPromiseExit') ||\n    exprText.includes('.runSync') ||\n    exprText.includes('.runSyncExit') ||\n    exprText.includes('.runFork') ||\n    exprText.includes('.runCallback') ||\n    exprText.includes('.runMain') ||\n    exprText.includes('Runtime.runPromise') ||\n    exprText.includes('Runtime.runSync') ||\n    exprText.includes('Runtime.runFork')\n  );\n};\n\n/**\n * Check if a function-like node's body contains runMain/runPromise/runSync/runFork.\n * Used for indirect runMain wrapper detection (improve.md §9).\n */\nfunction bodyContainsRunMainOrRunPromise(node: Node): boolean {\n  const body = (node as unknown as { getBody?: () => Node }).getBody?.();\n  if (!body) return false;\n  const text = body.getText();\n  return (\n    text.includes('.runMain') ||\n    text.includes('.runPromise') ||\n    text.includes('.runSync') ||\n    text.includes('.runFork') ||\n    text.includes('Runtime.runPromise') ||\n    text.includes('Runtime.runSync') ||\n    text.includes('NodeRuntime.runMain') ||\n    text.includes('BunRuntime.runMain') ||\n    text.includes('DenoRuntime.runMain')\n  );\n}\n\n/**\n * Resolve identifier to a function declaration/expression and check if its body contains runMain/runPromise.\n */\nfunction isIndirectRunMainWrapper(call: CallExpression, _sourceFile: SourceFile): boolean {\n  const expr = call.getExpression();\n  if (expr.getKind() !== loadTsMorph().SyntaxKind.Identifier) return false;\n  const id = expr as Identifier;\n  const sym = id.getSymbol();\n  const decl = sym?.getValueDeclaration();\n  if (!decl) return false;\n  const kind = decl.getKind();\n  const { SyntaxKind } = loadTsMorph();\n  if (\n    kind === SyntaxKind.FunctionDeclaration ||\n    kind === SyntaxKind.ArrowFunction ||\n    kind === SyntaxKind.FunctionExpression\n  ) {\n    return bodyContainsRunMainOrRunPromise(decl);\n  }\n  if (kind === SyntaxKind.VariableDeclaration) {\n    const init = (decl as VariableDeclaration).getInitializer();\n    if (init && (init.getKind() === SyntaxKind.ArrowFunction || init.getKind() === SyntaxKind.FunctionExpression)) {\n      return bodyContainsRunMainOrRunPromise(init);\n    }\n  }\n  return false;\n}\n\n/**\n * Detect curried runtime form: Runtime.runPromise(runtime)(effect) — improve.md §9.\n * The outer call has one argument (the effect); the callee is itself a call with one argument (the runtime).\n */\nexport function isRuntimeCurriedForm(call: CallExpression): boolean {\n  const expr = call.getExpression();\n  if (call.getArguments().length !== 1) return false;\n  const { SyntaxKind } = loadTsMorph();\n  if (expr.getKind() !== SyntaxKind.CallExpression) return false;\n  const innerCall = expr as CallExpression;\n  if (innerCall.getArguments().length !== 1) return false;\n  const innerExprText = innerCall.getExpression().getText();\n  return (\n    innerExprText.includes('.runPromise') ||\n    innerExprText.includes('.runSync') ||\n    innerExprText.includes('.runFork') ||\n    innerExprText.includes('.runCallback') ||\n    innerExprText.includes('Runtime.runPromise') ||\n    innerExprText.includes('Runtime.runSync') ||\n    innerExprText.includes('Runtime.runFork')\n  );\n}\n\n// =============================================================================\n// Program discovery\n// =============================================================================\n\nexport const findEffectPrograms = (\n  sourceFile: SourceFile,\n  _opts: Required<AnalyzerOptions>,\n): readonly EffectProgram[] => {\n  const programs: EffectProgram[] = [];\n  const { SyntaxKind } = loadTsMorph();\n  const seenCallStarts = new Set<number>();\n  const workflowProgramBuilders = new Set<string>();\n  const effectImportNames = getEffectLikeNamespaceAliases(\n    sourceFile,\n    _opts.knownEffectInternalsRoot,\n  );\n  const nonProgramEffectImportNames = getNonProgramEffectImportNames(sourceFile);\n  const importSpecifierByLocalName = new Map<string, string>();\n\n  for (const importDecl of sourceFile.getImportDeclarations()) {\n    const specifier = importDecl.getModuleSpecifierValue();\n    const def = importDecl.getDefaultImport();\n    if (def) importSpecifierByLocalName.set(def.getText(), specifier);\n    const ns = importDecl.getNamespaceImport();\n    if (ns) importSpecifierByLocalName.set(ns.getText(), specifier);\n    for (const named of importDecl.getNamedImports()) {\n      importSpecifierByLocalName.set(\n        named.getAliasNode()?.getText() ?? named.getName(),\n        specifier,\n      );\n    }\n  }\n\n  const inferAliasBackedDiscovery = (aliasName: string): DiscoveryInfo | undefined => {\n    const specifier = importSpecifierByLocalName.get(aliasName);\n    if (!specifier) return undefined;\n    if (specifier.startsWith('effect') || specifier.startsWith('@effect/')) {\n      return buildDiscoveryInfo('high', `imported from ${specifier}`);\n    }\n    if (\n      isSpecifierUnderKnownEffectInternalsRoot(\n        sourceFile.getFilePath(),\n        specifier,\n        _opts.knownEffectInternalsRoot,\n      )\n    ) {\n      return buildDiscoveryInfo(\n        'high',\n        'namespace import resolved under knownEffectInternalsRoot',\n      );\n    }\n    if (specifier.startsWith('.') && /(?:^|\\/)Effect(?:\\.[jt]sx?)?$/.test(specifier)) {\n      return buildDiscoveryInfo('high', `relative Effect module namespace import (${specifier})`);\n    }\n    return undefined;\n  };\n\n  const inferDirectInitializerDiscovery = (initializer: Node): DiscoveryInfo => {\n    const inferFromNestedEffectAliasUsage = (node: Node): DiscoveryInfo | undefined => {\n      const propertyAccesses = node.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression);\n      for (const expr of propertyAccesses) {\n        const base = expr.getExpression().getText();\n        if (effectImportNames.has(base) && !nonProgramEffectImportNames.has(base)) {\n          const aliasInfo = inferAliasBackedDiscovery(base);\n          if (aliasInfo?.discoveryConfidence === 'high') {\n            return buildDiscoveryInfo('high', `function body uses ${base}.* from trusted Effect alias`);\n          }\n          return buildDiscoveryInfo('medium', `function body uses Effect-like alias ${base}.*`);\n        }\n      }\n\n      const calls = node.getDescendantsOfKind(SyntaxKind.CallExpression);\n      for (const c of calls) {\n        const callee = (c).getExpression();\n        if (callee.getKind() === SyntaxKind.Identifier) {\n          const local = callee.getText();\n          if (effectImportNames.has(local) && !nonProgramEffectImportNames.has(local)) {\n            const aliasInfo = inferAliasBackedDiscovery(local);\n            if (aliasInfo?.discoveryConfidence === 'high') {\n              return buildDiscoveryInfo('high', `function body calls trusted Effect import ${local}(...)`);\n            }\n            return buildDiscoveryInfo('medium', `function body calls Effect-like import ${local}(...)`);\n          }\n        }\n      }\n\n      return undefined;\n    };\n\n    if (\n      initializer.getKind() === SyntaxKind.ArrowFunction ||\n      initializer.getKind() === SyntaxKind.FunctionExpression\n    ) {\n      const fn = initializer as\n        | ArrowFunction\n        | FunctionExpression;\n      const body = fn.getBody();\n      if (body.getKind() === SyntaxKind.Block) {\n        const nested = inferFromNestedEffectAliasUsage(body);\n        if (nested) return nested;\n      } else {\n        const nested = inferFromNestedEffectAliasUsage(body);\n        if (nested) return nested;\n      }\n    }\n\n    const call = getCallExpressionFromInitializer(initializer);\n    if (call) {\n      const callee = call.getExpression();\n      const calleeText = callee.getText();\n      if (callee.getKind() === SyntaxKind.Identifier) {\n        const local = calleeText;\n        if (\n          effectImportNames.has(local) &&\n          !nonProgramEffectImportNames.has(local)\n        ) {\n          return (\n            inferAliasBackedDiscovery(local) ??\n            buildDiscoveryInfo('high', `named import call (${local})`)\n          );\n        }\n        if (local === 'pipe') {\n          return buildDiscoveryInfo('medium', 'exact pipe() call detection');\n        }\n      }\n      if (callee.getKind() === SyntaxKind.PropertyAccessExpression) {\n        const prop = callee as PropertyAccessExpression;\n        const baseText = prop.getExpression().getText();\n        if (effectImportNames.has(baseText) && !nonProgramEffectImportNames.has(baseText)) {\n          return (\n            inferAliasBackedDiscovery(baseText) ??\n            buildDiscoveryInfo('medium', `Effect-like namespace prefix (${baseText}.*)`)\n          );\n        }\n        if (prop.getName() === 'pipe') {\n          return buildDiscoveryInfo('medium', 'exact .pipe() call detection');\n        }\n      }\n    }\n\n    if (initializer.getKind() === SyntaxKind.PropertyAccessExpression) {\n      const prop = initializer as PropertyAccessExpression;\n      const baseText = prop.getExpression().getText();\n      if (effectImportNames.has(baseText) && !nonProgramEffectImportNames.has(baseText)) {\n        return (\n          inferAliasBackedDiscovery(baseText) ??\n          buildDiscoveryInfo('medium', `Effect-like namespace property access (${baseText}.*)`)\n        );\n      }\n    }\n\n    if (initializer.getKind() === SyntaxKind.AwaitExpression) {\n      const awaited = (initializer as AwaitExpression).getExpression();\n      if (awaited.getKind() === SyntaxKind.CallExpression) {\n        return inferDirectInitializerDiscovery(awaited);\n      }\n    }\n\n    return buildDiscoveryInfo('low', 'heuristic direct initializer match');\n  };\n\n  const inferTypeAnnotatedDiscovery = (\n    node:\n      | VariableDeclaration\n      | PropertyDeclaration\n      | MethodDeclaration\n      | GetAccessorDeclaration,\n  ): DiscoveryInfo | undefined => {\n    const getTypeNodeText = (\n      n: unknown,\n    ): string | undefined => {\n      const typeNode = (\n        n as { getTypeNode?: () => { getText: () => string } | undefined }\n      ).getTypeNode?.();\n      return typeNode?.getText();\n    };\n\n    const typeText = getTypeNodeText(node);\n    if (hasEffectFamilyTypeHint(typeText)) {\n      return buildDiscoveryInfo('high', 'explicit Effect-family type annotation');\n    }\n\n    const isExportedDecl = (() => {\n      if (node.getKind() === SyntaxKind.VariableDeclaration) {\n        const stmt = (node as VariableDeclaration).getFirstAncestorByKind(\n          SyntaxKind.VariableStatement,\n        );\n        return stmt?.isExported() ?? false;\n      }\n      if (node.getKind() === SyntaxKind.PropertyDeclaration) {\n        const cls = node.getFirstAncestorByKind(SyntaxKind.ClassDeclaration);\n        return cls?.isExported() ?? false;\n      }\n      if (\n        node.getKind() === SyntaxKind.MethodDeclaration ||\n        node.getKind() === SyntaxKind.GetAccessor\n      ) {\n        const cls = node.getFirstAncestorByKind(SyntaxKind.ClassDeclaration);\n        return cls?.isExported() ?? false;\n      }\n      return false;\n    })();\n\n    if (\n      node.getKind() === SyntaxKind.VariableDeclaration ||\n      node.getKind() === SyntaxKind.PropertyDeclaration\n    ) {\n      const initializer = (\n        node as VariableDeclaration | PropertyDeclaration\n      ).getInitializer();\n      if (\n        initializer &&\n        (initializer.getKind() === SyntaxKind.ArrowFunction ||\n          initializer.getKind() === SyntaxKind.FunctionExpression)\n      ) {\n        const fn = initializer as\n          | import('ts-morph').ArrowFunction\n          | import('ts-morph').FunctionExpression;\n        const fnReturnTypeText = fn.getReturnTypeNode()?.getText();\n        if (hasEffectFamilyTypeHint(fnReturnTypeText)) {\n          return buildDiscoveryInfo('high', 'function return type annotated as Effect-family');\n        }\n        if (isExportedDecl && typeText) {\n          return buildDiscoveryInfo('medium', 'explicit exported function API type signature');\n        }\n      }\n      if (initializer?.getKind() === SyntaxKind.CallExpression) {\n        const call = initializer as CallExpression;\n        const typeArgText = call\n          .getTypeArguments()\n          .map((arg) => arg.getText())\n          .join(' ');\n        if (hasEffectFamilyTypeHint(typeArgText)) {\n          return buildDiscoveryInfo('high', 'call type arguments reference Effect-family types');\n        }\n        if (isExportedDecl && typeText) {\n          return buildDiscoveryInfo('medium', 'explicit exported call-based API type signature');\n        }\n      }\n    }\n\n    if (\n      node.getKind() === SyntaxKind.MethodDeclaration ||\n      node.getKind() === SyntaxKind.GetAccessor\n    ) {\n      const fnReturnTypeText = (\n        node as MethodDeclaration | GetAccessorDeclaration\n      ).getReturnTypeNode?.()?.getText();\n      if (hasEffectFamilyTypeHint(fnReturnTypeText)) {\n        return buildDiscoveryInfo('high', 'method/getter return type annotated as Effect-family');\n      }\n      if (isExportedDecl && typeText) {\n        return buildDiscoveryInfo('medium', 'explicit exported method/getter API type signature');\n      }\n    }\n\n    return undefined;\n  };\n\n  const isProgramRootExported = (program: EffectProgram): boolean => {\n    const node = program.node;\n    const kind = node.getKind();\n    if (kind === SyntaxKind.CallExpression) {\n      // Top-level entrypoint statements / assigned runs don't have a direct export modifier.\n      return true;\n    }\n    if (kind === SyntaxKind.VariableDeclaration) {\n      const stmt = (node as VariableDeclaration).getFirstAncestorByKind(\n        SyntaxKind.VariableStatement,\n      );\n      return stmt?.isExported() ?? false;\n    }\n    if (kind === SyntaxKind.FunctionDeclaration || kind === SyntaxKind.ClassDeclaration) {\n      return (\n        node as FunctionDeclaration | ClassDeclaration\n      ).isExported();\n    }\n    if (\n      kind === SyntaxKind.PropertyDeclaration ||\n      kind === SyntaxKind.MethodDeclaration ||\n      kind === SyntaxKind.GetAccessor\n    ) {\n      const cls = node.getFirstAncestorByKind(SyntaxKind.ClassDeclaration);\n      return cls?.isExported() ?? false;\n    }\n    return true;\n  };\n\n  const inferMethodReturnDiscovery = (\n    returnStatements: readonly ReturnStatement[],\n  ): DiscoveryInfo => {\n    for (const ret of returnStatements) {\n      const expr = ret.getExpression();\n      if (!expr) continue;\n      if (\n        isLikelyDirectEffectInitializer(\n          expr,\n          effectImportNames,\n          nonProgramEffectImportNames,\n        )\n      ) {\n        return inferDirectInitializerDiscovery(expr);\n      }\n    }\n    return buildDiscoveryInfo('low', 'heuristic method return match');\n  };\n\n  const filePath = sourceFile.getFilePath();\n  const varDeclarations = sourceFile.getDescendantsOfKind(\n    SyntaxKind.VariableDeclaration,\n  );\n  for (const decl of varDeclarations) {\n    const initializer = decl.getInitializer();\n    if (\n      initializer?.getKind() === SyntaxKind.CallExpression &&\n      isWorkflowFactoryCall(\n        (initializer as CallExpression).getExpression().getText(),\n      )\n    ) {\n      workflowProgramBuilders.add(decl.getName());\n    }\n    if (\n      _opts.enableEffectWorkflow &&\n      initializer?.getKind() === SyntaxKind.CallExpression\n    ) {\n      const initCall = initializer as CallExpression;\n      if (\n        isWorkflowMakeOptionsCall(initCall, importSpecifierByLocalName, filePath) ||\n        isActivityMakeOptionsCall(initCall, importSpecifierByLocalName, filePath)\n      ) {\n        workflowProgramBuilders.add(decl.getName());\n      }\n    }\n  }\n\n  const genCalls = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n  for (const call of genCalls) {\n    const expression = call.getExpression();\n    const exprText = expression.getText();\n    const callStart = call.getStart();\n\n    let isWorkflowInvocation = false;\n    if (expression.getKind() === SyntaxKind.Identifier) {\n      isWorkflowInvocation = workflowProgramBuilders.has(exprText);\n    } else if (expression.getKind() === SyntaxKind.PropertyAccessExpression) {\n      const propertyAccess =\n        expression as PropertyAccessExpression;\n      const objectText = propertyAccess.getExpression().getText();\n      const methodName = propertyAccess.getName();\n      isWorkflowInvocation =\n        workflowProgramBuilders.has(objectText) && methodName === 'run';\n      if (\n        _opts.enableEffectWorkflow &&\n        !isWorkflowInvocation &&\n        methodName === 'run' &&\n        call.getArguments().length === 1 &&\n        !exprText.includes('runPromise') &&\n        !exprText.includes('runSync') &&\n        !exprText.includes('runFork') &&\n        !exprText.includes('runCallback') &&\n        !seenCallStarts.has(callStart)\n      ) {\n        const name =\n          extractProgramName(call) ?? `workflow-${programs.length + 1}`;\n        programs.push({\n          name,\n          node: call,\n          type: 'run',\n          ...buildDiscoveryInfo('low', 'workflow-like .run(...) shape heuristic'),\n        });\n        seenCallStarts.add(callStart);\n        continue;\n      }\n    }\n    if (isWorkflowInvocation && !seenCallStarts.has(callStart)) {\n      const name = extractProgramName(call) ?? `workflow-${programs.length + 1}`;\n      programs.push({\n        name,\n        node: call,\n        type: 'run',\n        ...buildDiscoveryInfo('medium', 'workflow builder invocation'),\n      });\n      seenCallStarts.add(callStart);\n      continue;\n    }\n\n    if (\n      _opts.enableEffectWorkflow &&\n      expression.getKind() === SyntaxKind.PropertyAccessExpression\n    ) {\n      const propertyAccess = expression as PropertyAccessExpression;\n      const objectText = propertyAccess.getExpression().getText();\n      const methodName = propertyAccess.getName();\n      const isExecuteEntrypoint =\n        (methodName === 'execute' || methodName === 'executeEncoded') &&\n        workflowProgramBuilders.has(objectText) &&\n        !seenCallStarts.has(callStart);\n      if (isExecuteEntrypoint) {\n        const name =\n          extractProgramName(call) ?? `${objectText}.${methodName}`;\n        programs.push({\n          name,\n          node: call,\n          type: 'workflow-execute',\n          ...buildDiscoveryInfo('medium', 'workflow/activity .execute entrypoint'),\n        });\n        seenCallStarts.add(callStart);\n        continue;\n      }\n    }\n\n    if ((exprText === 'gen' || (exprText.endsWith('.gen') && isEffectLikeCallExpression(call, sourceFile, effectImportNames, _opts.knownEffectInternalsRoot))) && !seenCallStarts.has(callStart)) {\n      const name = extractProgramName(call) ?? extractEnclosingEffectFnName(call) ?? `program-${programs.length + 1}`;\n      programs.push({\n        name,\n        node: call,\n        type: 'generator',\n        ...(exprText === 'gen'\n          ? buildDiscoveryInfo('medium', 'unqualified gen(...) call')\n          : buildDiscoveryInfo('high', 'Effect-like .gen(...) call')),\n      });\n      seenCallStarts.add(callStart);\n    }\n\n    const pipeName = extractProgramName(call);\n    if (\n      exprText.includes('pipe') &&\n      hasEffectInArgs(call, effectImportNames) &&\n      !seenCallStarts.has(callStart) &&\n      expression.getKind() !== SyntaxKind.PropertyAccessExpression &&\n      pipeName !== undefined &&\n      !isInsideEffectGen(call)\n    ) {\n      programs.push({\n        name: pipeName,\n        node: call,\n        type: 'pipe',\n        ...buildDiscoveryInfo('medium', 'exact pipe(...) call with Effect-like args'),\n      });\n      seenCallStarts.add(callStart);\n    }\n\n    if ((isRunCall(call) || isRuntimeCurriedForm(call)) && !seenCallStarts.has(callStart)) {\n      const name = extractProgramName(call) ?? `run-${programs.length + 1}`;\n      programs.push({\n        name,\n        node: call,\n        type: 'run',\n        ...buildDiscoveryInfo('high', 'recognized Runtime/Effect run* entrypoint'),\n      });\n      seenCallStarts.add(callStart);\n    }\n  }\n\n  for (const decl of varDeclarations) {\n    if (!isTopLevelVariableDeclaration(decl)) continue;\n    if (isYieldBoundDeclaration(decl)) continue;\n    const initializer = decl.getInitializer();\n    if (initializer) {\n      const name = decl.getName();\n      const callInitializer = getCallExpressionFromInitializer(initializer);\n      if (callInitializer && isRunCall(callInitializer)) {\n        continue;\n      }\n      if (initializer.getKind() === SyntaxKind.ObjectLiteralExpression) {\n        continue;\n      }\n      const looksLikeEffect = isLikelyDirectEffectInitializer(\n        initializer,\n        effectImportNames,\n        nonProgramEffectImportNames,\n      );\n      if (looksLikeEffect && !programs.some((p) => p.name === name)) {\n        programs.push({\n          name,\n          node: decl,\n          type: 'direct',\n          ...(inferTypeAnnotatedDiscovery(decl) ?? inferDirectInitializerDiscovery(initializer)),\n        });\n      } else if (!looksLikeEffect && !programs.some((p) => p.name === name)) {\n        // Even if the initializer doesn't look like Effect code, check type annotations\n        // This catches arrow functions like: export const f = (args, deps): Effect.Effect<T> => deps.call(args)\n        const typeDiscovery = inferTypeAnnotatedDiscovery(decl);\n        if (typeDiscovery) {\n          programs.push({\n            name,\n            node: decl,\n            type: 'direct',\n            ...typeDiscovery,\n          });\n        }\n      }\n    }\n  }\n\n  const topLevelStatements = sourceFile.getStatements();\n  for (const stmt of topLevelStatements) {\n    if (stmt.getKind() !== SyntaxKind.ExpressionStatement) continue;\n    const expr = (stmt as ExpressionStatement).getExpression();\n    if (expr.getKind() !== SyntaxKind.CallExpression) continue;\n\n    const call = expr as CallExpression;\n    const callStart = call.getStart();\n    if (seenCallStarts.has(callStart)) continue;\n\n    const calleeExpr = call.getExpression();\n    const calleeText = calleeExpr.getText();\n\n    if (isRunCall(call)) {\n      const name = `run-${programs.length + 1}`;\n      programs.push({\n        name,\n        node: call,\n        type: 'run',\n        ...buildDiscoveryInfo('high', 'recognized top-level run* entrypoint'),\n      });\n      seenCallStarts.add(callStart);\n      continue;\n    }\n\n    if (calleeText.endsWith('.pipe') || calleeText === 'pipe') {\n      const args = call.getArguments();\n      const lastArg = args[args.length - 1];\n      if (!lastArg) continue;\n\n      const lastArgText = lastArg.getText();\n      const isRunTerminated =\n        lastArgText.includes('.runMain') ||\n        lastArgText.includes('.runPromise') ||\n        lastArgText.includes('.runSync') ||\n        lastArgText.includes('.runFork');\n\n      if (isRunTerminated) {\n        let baseName: string | undefined;\n        if (calleeExpr.getKind() === SyntaxKind.PropertyAccessExpression) {\n          const propAccess = calleeExpr as PropertyAccessExpression;\n          const baseExpr = propAccess.getExpression();\n          baseName = baseExpr.getText().split('.').pop();\n        }\n        const name = baseName && !programs.some(p => p.name === baseName)\n          ? baseName\n          : `entrypoint-${programs.length + 1}`;\n        programs.push({\n          name,\n          node: call,\n          type: 'run',\n          ...buildDiscoveryInfo('medium', 'top-level pipe(...).run* terminator pattern'),\n        });\n        seenCallStarts.add(callStart);\n      }\n    }\n\n    if (calleeExpr.getKind() === SyntaxKind.Identifier && call.getArguments().length >= 1) {\n      const name = (calleeExpr as Identifier).getText();\n      const isIndirectWrapper = isIndirectRunMainWrapper(call, sourceFile);\n      if (isIndirectWrapper && !programs.some(p => p.name === name)) {\n        programs.push({\n          name,\n          node: call,\n          type: 'run',\n          ...buildDiscoveryInfo('low', 'indirect run wrapper body heuristic'),\n        });\n        seenCallStarts.add(callStart);\n      }\n    }\n  }\n\n  const DATA_SCHEMA_CLASS_PATTERNS = [\n    'Data.TaggedError',\n    'Data.TaggedClass',\n    'Data.Class',\n    'Data.Error',\n    'Schema.Class',\n    'Schema.TaggedClass',\n    'Schema.TaggedError',\n    'Schema.TaggedRequest',\n    'Context.Tag',\n    'Context.Service',\n    'Context.Reference',\n    'Effect.Service',\n  ];\n  const classDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.ClassDeclaration);\n  for (const classDecl of classDeclarations) {\n    const name = classDecl.getName();\n    if (!name) continue;\n    if (programs.some((p) => p.name === name)) continue;\n    const heritageClauses = classDecl.getHeritageClauses();\n    const matchesPattern = heritageClauses.some((clause) => {\n      const clauseText = clause.getText();\n      return DATA_SCHEMA_CLASS_PATTERNS.some((p) => clauseText.includes(p));\n    });\n    if (matchesPattern) {\n      programs.push({\n        name,\n        node: classDecl,\n        type: 'class',\n        ...buildDiscoveryInfo('medium', 'known Data/Schema/Context class pattern'),\n      });\n    }\n  }\n\n  const topLevelClasses = classDeclarations.filter((c) => {\n    const parent = c.getParent();\n    return parent === sourceFile || parent?.getParent() === sourceFile;\n  });\n  for (const classDecl of topLevelClasses) {\n    const className = classDecl.getName() ?? 'Anonymous';\n\n    const members = classDecl.getMembers();\n    const properties = members.filter(\n      m => m.getKind() === SyntaxKind.PropertyDeclaration\n    ) as PropertyDeclaration[];\n\n    for (const prop of properties) {\n      const initializer = prop.getInitializer();\n      if (!initializer) continue;\n      const memberName = prop.getName();\n      const fullName = `${className}.${memberName}`;\n      if (programs.some(p => p.name === fullName)) continue;\n\n      if (\n        isLikelyDirectEffectInitializer(\n          initializer,\n          effectImportNames,\n          nonProgramEffectImportNames,\n        )\n      ) {\n        programs.push({\n          name: fullName,\n          node: prop,\n          type: 'classProperty',\n          ...(inferTypeAnnotatedDiscovery(prop) ?? inferDirectInitializerDiscovery(initializer)),\n        });\n      }\n    }\n\n    const methods = members.filter(\n      m => m.getKind() === SyntaxKind.MethodDeclaration\n    ) as MethodDeclaration[];\n\n    for (const method of methods) {\n      const memberName = method.getName();\n      const fullName = `${className}.${memberName}`;\n      if (programs.some(p => p.name === fullName)) continue;\n\n      const body = method.getBody();\n      if (!body) continue;\n\n      const returnStatements = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n      const hasEffectReturn = returnStatements.some(ret => {\n        const expr = (ret).getExpression();\n        return expr\n          ? isLikelyDirectEffectInitializer(\n              expr,\n              effectImportNames,\n              nonProgramEffectImportNames,\n            )\n          : false;\n      });\n\n      if (hasEffectReturn) {\n        programs.push({\n          name: fullName,\n          node: method,\n          type: 'classMethod',\n          ...(inferTypeAnnotatedDiscovery(method) ?? inferMethodReturnDiscovery(returnStatements)),\n        });\n      }\n    }\n\n    const getters = members.filter(\n      m => m.getKind() === SyntaxKind.GetAccessor\n    ) as GetAccessorDeclaration[];\n\n    for (const getter of getters) {\n      const memberName = getter.getName();\n      const fullName = `${className}.${memberName}`;\n      if (programs.some(p => p.name === fullName)) continue;\n\n      const body = getter.getBody();\n      if (!body) continue;\n\n      const returnStatements = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n      const hasEffectReturn = returnStatements.some(ret => {\n        const expr = (ret).getExpression();\n        return expr\n          ? isLikelyDirectEffectInitializer(\n              expr,\n              effectImportNames,\n              nonProgramEffectImportNames,\n            )\n          : false;\n      });\n\n      if (hasEffectReturn) {\n        programs.push({\n          name: fullName,\n          node: getter,\n          type: 'classMethod',\n          ...(inferTypeAnnotatedDiscovery(getter) ?? inferMethodReturnDiscovery(returnStatements)),\n        });\n      }\n    }\n  }\n\n  // Discover exported function declarations whose return type is Effect.Effect\n  const functionDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration);\n  for (const fnDecl of functionDeclarations) {\n    const name = fnDecl.getName();\n    if (!name) continue;\n    if (programs.some((p) => p.name === name)) continue;\n    if (!fnDecl.isExported()) continue;\n    // Skip overload signatures (no body) — only discover the implementation\n    if (!fnDecl.getBody()) continue;\n\n    const returnTypeNode = fnDecl.getReturnTypeNode();\n    if (returnTypeNode && hasEffectFamilyTypeHint(returnTypeNode.getText())) {\n      programs.push({\n        name,\n        node: fnDecl,\n        type: 'functionDeclaration',\n        ...buildDiscoveryInfo('high', 'exported function with Effect-family return type'),\n      });\n    }\n  }\n\n  return programs.filter((program) => {\n    const threshold = _opts.minDiscoveryConfidence ?? 'low';\n    const confidence = program.discoveryConfidence ?? 'low';\n    if (DISCOVERY_CONFIDENCE_RANK[confidence] < DISCOVERY_CONFIDENCE_RANK[threshold]) {\n      return false;\n    }\n    if (_opts.onlyExportedPrograms && !isProgramRootExported(program)) {\n      return false;\n    }\n    return true;\n  });\n};\n\nconst hasEffectInArgs = (\n  call: CallExpression,\n  effectImportNames: Set<string>,\n): boolean => {\n  const args = call.getArguments();\n  const argTexts = args.map((arg) => arg.getText());\n  return argTexts.some((text) =>\n    [...effectImportNames].some((alias) => text.includes(`${alias}.`)),\n  );\n};\n\n// =============================================================================\n// Service definitions\n// =============================================================================\n\nexport function extractServiceDefinitionsFromFile(sourceFile: SourceFile): ServiceDefinition[] {\n  const { SyntaxKind } = loadTsMorph();\n  const results: ServiceDefinition[] = [];\n  const typeChecker = sourceFile.getProject().getTypeChecker();\n  const classDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.ClassDeclaration);\n  for (const classDecl of classDeclarations) {\n    const name = classDecl.getName();\n    if (!name) continue;\n    const extExpr = classDecl.getExtends();\n    if (!extExpr) continue;\n    const extText = extExpr.getText();\n    if (!extText.includes('Context.Service') && !extText.includes('Context.Tag') && !extText.includes('Effect.Service')) continue;\n    let typeArgs: readonly TypeNode[] = extExpr.getTypeArguments();\n    if (typeArgs.length < 2) {\n      const inner = extExpr.getExpression();\n      if (inner && 'getTypeArguments' in inner && typeof (inner as { getTypeArguments: () => unknown[] }).getTypeArguments === 'function') {\n        typeArgs = (inner as { getTypeArguments: () => readonly TypeNode[] }).getTypeArguments();\n      }\n    }\n    if (typeArgs.length < 2) continue;\n    const interfaceTypeNode = typeArgs[1];\n    if (!interfaceTypeNode) continue;\n    try {\n      const type = typeChecker.getTypeAtLocation(interfaceTypeNode);\n      const methods: string[] = [];\n      const properties: string[] = [];\n      for (const sym of type.getProperties()) {\n        const propName = sym.getName();\n        if (propName.startsWith('_') || propName === 'constructor') continue;\n        const propType = typeChecker.getTypeOfSymbolAtLocation(sym, interfaceTypeNode);\n        const callSigs = propType.getCallSignatures();\n        if (callSigs.length > 0) methods.push(propName);\n        else properties.push(propName);\n      }\n      const classText = classDecl.getText();\n      const hasCustomEquality = classText.includes('Equal.symbol') || classText.includes('[Equal') || classText.includes('equal(');\n      const hasCustomHash = classText.includes('Hash.symbol') || classText.includes('[Hash') || classText.includes('hash(');\n      results.push({\n        tagId: name, methods, properties,\n        ...(hasCustomEquality ? { hasCustomEquality } : {}),\n        ...(hasCustomHash ? { hasCustomHash } : {}),\n      });\n    } catch {\n      // skip\n    }\n  }\n\n  for (const classDecl of classDeclarations) {\n    const name = classDecl.getName();\n    if (!name) continue;\n    const extExpr = classDecl.getExtends();\n    if (!extExpr) continue;\n    const extText = extExpr.getText();\n    if (!extText.includes('Data.Class') && !extText.includes('Data.TaggedClass')) continue;\n    if (results.some(r => r.tagId === name)) continue;\n    const classText = classDecl.getText();\n    const hasCustomEquality = classText.includes('Equal.symbol') || classText.includes('[Equal') || classText.includes('equal(');\n    const hasCustomHash = classText.includes('Hash.symbol') || classText.includes('[Hash') || classText.includes('hash(');\n    if (hasCustomEquality || hasCustomHash) {\n      results.push({ tagId: name, methods: [], properties: [], hasCustomEquality, hasCustomHash });\n    }\n  }\n\n  return results;\n}\n","/**\n * Core program analysis: analyzeProgram, analyzeProgramNode,\n * analyzeGeneratorFunction, analyzeRunEntrypointExpression.\n */\n\nimport { Effect, Option, Clock } from 'effect';\nimport type {\n  SourceFile,\n  Node,\n  CallExpression,\n  ArrowFunction,\n  FunctionDeclaration,\n  FunctionExpression,\n  VariableDeclaration,\n  ClassDeclaration,\n  PropertyDeclaration,\n  MethodDeclaration,\n  GetAccessorDeclaration,\n  StringLiteral,\n  NumericLiteral,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n  PropertyAccessExpression,\n  ArrayLiteralExpression,\n  YieldExpression,\n  ExpressionStatement,\n  VariableStatement,\n  IfStatement,\n  SwitchStatement,\n  CaseClause,\n  ForStatement,\n  ForOfStatement,\n  ForInStatement,\n  WhileStatement,\n  DoStatement,\n  TryStatement,\n  ReturnStatement,\n  ThrowStatement,\n  LabeledStatement,\n  Block,\n  ConditionalExpression,\n  BinaryExpression,\n  Identifier,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticEffectIR,\n  StaticEffectProgram,\n  StaticFlowNode,\n  StaticEffectNode,\n  StaticGeneratorNode,\n  StaticDecisionNode,\n  StaticSwitchNode,\n  StaticSwitchCase,\n  StaticTryCatchNode,\n  StaticTerminalNode,\n  StaticOpaqueNode,\n  StaticLoopNode,\n  StaticParallelNode,\n  StaticRaceNode,\n  StaticRetryNode,\n  StaticLayerNode,\n  AnalysisError,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n} from './types';\nimport {\n  extractEffectTypeSignature,\n  extractServiceRequirements,\n} from './type-extractor';\nimport type { EffectProgram } from './analysis-utils';\nimport { unwrapExpression } from './analysis-utils';\nimport {\n  createEmptyStats,\n  generateId,\n  extractLocation,\n  collectDependencies,\n  collectErrorTypes,\n  getJSDocFromParentVariable,\n  extractJSDocDescription,\n  extractJSDocTags,\n  extractYieldVariableName,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport { isServiceTagCallee } from './analysis-patterns';\nimport { getAliasesForFile, isEffectLikeCallExpression } from './alias-resolution';\nimport {\n  extractServiceDefinitionsFromFile,\n  getWorkflowBodyNodeForRunCall,\n} from './program-discovery';\nimport {\n  analyzePipeChain,\n  analyzeEffectExpression,\n  analyzeEffectCall,\n} from './effect-analysis';\n\n// =============================================================================\n// Program Analysis\n// =============================================================================\n\nexport const analyzeProgram = (\n  program: EffectProgram,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  tsVersion: string,\n): Effect.Effect<StaticEffectIR, AnalysisError> =>\n  Effect.gen(function* () {\n    const warnings: AnalysisWarning[] = [];\n    const stats = createEmptyStats();\n\n    const children = yield* analyzeProgramNode(\n      program.node,\n      program.type,\n      sourceFile,\n      filePath,\n      opts,\n      warnings,\n      stats,\n    );\n\n    const programJSDoc = getJSDocFromParentVariable(program.node);\n\n    const typeChecker = sourceFile.getProject().getTypeChecker();\n    const typeSignature = extractEffectTypeSignature(program.node, typeChecker);\n    const requiredServices = extractServiceRequirements(program.node, typeChecker);\n\n    const root: StaticEffectProgram = {\n      id: generateId(),\n      type: 'program',\n      programName: program.name,\n      source: program.type,\n      ...(program.discoveryConfidence\n        ? { discoveryConfidence: program.discoveryConfidence }\n        : {}),\n      ...(program.discoveryReason ? { discoveryReason: program.discoveryReason } : {}),\n      children,\n      dependencies: collectDependencies(children),\n      errorTypes: collectErrorTypes(children),\n      typeSignature,\n      requiredServices,\n      location: extractLocation(\n        program.node,\n        filePath,\n        opts.includeLocations ?? false,\n      ),\n      jsdocDescription: programJSDoc,\n      jsdocTags: extractJSDocTags(program.node),\n    };\n\n    const serviceDefinitions = extractServiceDefinitionsFromFile(sourceFile);\n    return {\n      root,\n      metadata: {\n        analyzedAt: yield* Clock.currentTimeMillis,\n        filePath,\n        tsVersion,\n        warnings,\n        stats,\n        ...(serviceDefinitions.length > 0 ? { serviceDefinitions } : {}),\n      },\n      references: new Map(),\n    };\n  });\n\n// =============================================================================\n// Node Analysis\n// =============================================================================\n\nexport const analyzeProgramNode = (\n  node: Node,\n  programType: EffectProgram['type'],\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<readonly StaticFlowNode[], AnalysisError> =>\n  Effect.gen(function* () {\n    switch (programType) {\n      case 'generator': {\n        const genCall = node as CallExpression;\n        const args = genCall.getArguments();\n        if (args.length === 0 || !args[0]) return [];\n        const genChildren = yield* analyzeGeneratorFunction(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n\n        // If the gen call is the base of an enclosing `.pipe(...)`, analyze the\n        // pipe's Effect-level transformations (retry/timeout/catch/etc.) so\n        // wrappers around the gen are captured in the IR and stats.\n        const outerPipe = findOuterPipeOnGen(genCall);\n        if (outerPipe) {\n          return yield* applyOuterPipeTransformsToGen(\n            genChildren,\n            outerPipe,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n        }\n        const outerLayerUnwrap = findOuterLayerUnwrapOnGen(genCall);\n        if (outerLayerUnwrap) {\n          const unwrapNode: StaticLayerNode = {\n            id: generateId(),\n            type: 'layer',\n            name: 'Layer.unwrapEffect(gen)',\n            operations: [...genChildren],\n            isMerged: false,\n            lifecycle: 'default',\n            location: extractLocation(\n              outerLayerUnwrap,\n              filePath,\n              opts.includeLocations ?? false,\n            ),\n          };\n          return [{\n            ...unwrapNode,\n            displayName: computeDisplayName(unwrapNode),\n            semanticRole: computeSemanticRole(unwrapNode),\n          }];\n        }\n        return genChildren;\n      }\n\n      case 'pipe': {\n        return yield* analyzePipeChain(\n          node as CallExpression,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      }\n\n      case 'run': {\n        const call = node as CallExpression;\n        const { SyntaxKind } = loadTsMorph();\n        const pipeResult = yield* analyzeRunEntrypointExpression(\n          call,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n        if (Option.isSome(pipeResult)) {\n          return pipeResult.value;\n        }\n\n        const args = call.getArguments();\n        const callbackInArgs = args.find(\n          (arg) =>\n            arg.getKind() === SyntaxKind.ArrowFunction ||\n            arg.getKind() === SyntaxKind.FunctionExpression,\n        );\n        const workflowBody =\n          opts.enableEffectWorkflow &&\n          callbackInArgs === undefined &&\n          args.length === 1\n            ? getWorkflowBodyNodeForRunCall(call, sourceFile)\n            : null;\n        const effect = callbackInArgs ?? workflowBody ?? args[0];\n        if (effect) {\n          const analyzed = yield* analyzeEffectExpression(\n            effect,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n          return [analyzed];\n        }\n        return [];\n      }\n\n      case 'workflow-execute': {\n        const call = node as CallExpression;\n        const exprText = call.getExpression().getText();\n        const syntheticNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee: exprText,\n          name: exprText,\n          semanticRole: 'side-effect',\n          location: extractLocation(call, filePath, opts.includeLocations ?? false),\n        };\n        return [syntheticNode];\n      }\n\n      case 'direct': {\n        const initializer = (node as VariableDeclaration).getInitializer();\n        if (initializer) {\n          // Detect Effect.fn(\"name\")(function* () { ... }) curried call pattern\n          const { SyntaxKind: SK } = loadTsMorph();\n          if (initializer.getKind() === SK.CallExpression) {\n            const outerCall = initializer as CallExpression;\n            const outerExpr = outerCall.getExpression();\n            // Check if the outer expression is itself a call to Effect.fn/Effect.fnUntraced\n            if (outerExpr.getKind() === SK.CallExpression) {\n              const innerCall = outerExpr as CallExpression;\n              const innerCallee = innerCall.getExpression().getText();\n              if (innerCallee.endsWith('.fn') || innerCallee.endsWith('.fnUntraced')) {\n                // The generator function is the first argument of the outer call\n                const outerArgs = outerCall.getArguments();\n                const genArg = outerArgs.find(\n                  (arg) =>\n                    arg.getKind() === SK.FunctionExpression ||\n                    arg.getKind() === SK.ArrowFunction,\n                );\n                if (genArg) {\n                  // Extract traced name from Effect.fn(\"name\")\n                  const fnArgs = innerCall.getArguments();\n                  let tracedName: string | undefined;\n                  if (fnArgs.length > 0) {\n                    const firstArg = fnArgs[0]?.getText() ?? '';\n                    const strMatch = /^[\"'`](.+?)[\"'`]$/.exec(firstArg);\n                    if (strMatch) tracedName = strMatch[1];\n                  }\n                  const constructorKind = innerCallee.endsWith('.fnUntraced') ? 'fnUntraced' as const : 'fn' as const;\n\n                  // Create Effect.fn metadata node preserving constructor info\n                  const fnMetaNode: StaticEffectNode = {\n                    id: generateId(),\n                    type: 'effect',\n                    callee: innerCallee,\n                    location: extractLocation(innerCall, filePath, opts.includeLocations ?? false),\n                    constructorKind,\n                    ...(tracedName ? { tracedName } : {}),\n                  };\n                  stats.totalEffects++;\n                  const enrichedFnNode: StaticEffectNode = {\n                    ...fnMetaNode,\n                    displayName: computeDisplayName(fnMetaNode),\n                    semanticRole: computeSemanticRole(fnMetaNode),\n                  };\n\n                  // Analyze the generator body\n                  const genChildren = yield* analyzeGeneratorFunction(\n                    genArg,\n                    sourceFile,\n                    filePath,\n                    opts,\n                    warnings,\n                    stats,\n                  );\n\n                  return [enrichedFnNode, ...genChildren];\n                }\n              }\n            }\n          }\n          const analyzed = yield* analyzeEffectExpression(\n            initializer,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n          return [analyzed];\n        }\n        return [];\n      }\n\n      case 'class': {\n        const classDecl = node as ClassDeclaration;\n        let callee = 'Data.Class';\n        for (const clause of classDecl.getHeritageClauses()) {\n          const clauseText = clause.getText();\n          if (clauseText.includes('Data.TaggedError')) { callee = 'Data.TaggedError'; break; }\n          if (clauseText.includes('Data.TaggedClass')) { callee = 'Data.TaggedClass'; break; }\n          if (clauseText.includes('Data.Error')) { callee = 'Data.Error'; break; }\n          if (clauseText.includes('Schema.TaggedRequest')) { callee = 'Schema.TaggedRequest'; break; }\n          if (clauseText.includes('Schema.TaggedError')) { callee = 'Schema.TaggedError'; break; }\n          if (clauseText.includes('Schema.TaggedClass')) { callee = 'Schema.TaggedClass'; break; }\n          if (clauseText.includes('Schema.Class')) { callee = 'Schema.Class'; break; }\n          if (clauseText.includes('Context.Tag')) { callee = 'Context.Tag'; break; }\n          if (clauseText.includes('Context.Service')) { callee = 'Context.Service'; break; }\n          if (clauseText.includes('Context.Reference')) { callee = 'Context.Reference'; break; }\n          if (clauseText.includes('Effect.Service')) { callee = 'Effect.Service'; break; }\n        }\n        const description =\n          callee.includes('Error') ? 'error-type' :\n          callee.includes('Schema') ? 'schema' :\n          callee === 'Context.Service' || callee === 'Context.Tag' || callee === 'Context.Reference' || callee === 'Effect.Service' ? 'service-tag' :\n          'data';\n        const classEffectNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee,\n          description,\n          location: extractLocation(node, filePath, opts.includeLocations ?? false),\n          jsdocDescription: extractJSDocDescription(classDecl),\n          jsdocTags: extractJSDocTags(classDecl),\n        };\n        stats.totalEffects++;\n        return [classEffectNode];\n      }\n\n      case 'classProperty': {\n        const prop = node as PropertyDeclaration;\n        const initializer = prop.getInitializer();\n        if (initializer) {\n          const result = yield* analyzeEffectExpression(\n            initializer, sourceFile, filePath, opts, warnings, stats,\n          );\n          return [result];\n        }\n        return [];\n      }\n\n      case 'classMethod': {\n        const method = node as MethodDeclaration | GetAccessorDeclaration;\n        const body = method.getBody();\n        if (!body) return [];\n\n        const { SyntaxKind: SK } = loadTsMorph();\n        const returnStatements = body.getDescendantsOfKind(SK.ReturnStatement);\n        const children: StaticFlowNode[] = [];\n        for (const ret of returnStatements) {\n          const expr = (ret).getExpression();\n          if (expr) {\n            const result = yield* analyzeEffectExpression(\n              expr, sourceFile, filePath, opts, warnings, stats,\n            );\n            children.push(result);\n          }\n        }\n        return children;\n      }\n\n      case 'functionDeclaration': {\n        const fnDecl = node as FunctionDeclaration;\n        const body = fnDecl.getBody();\n        if (!body) return [];\n\n        const { SyntaxKind: SK2 } = loadTsMorph();\n        const returnStatements = body.getDescendantsOfKind(SK2.ReturnStatement);\n        const children: StaticFlowNode[] = [];\n        for (const ret of returnStatements) {\n          const expr = (ret).getExpression();\n          if (expr) {\n            const result = yield* analyzeEffectExpression(\n              expr, sourceFile, filePath, opts, warnings, stats,\n            );\n            children.push(result);\n          }\n        }\n        return children;\n      }\n\n      default:\n        return [];\n    }\n  });\n\n// =============================================================================\n// Statement-Level Walker Helpers\n// =============================================================================\n\n/**\n * Check if a node is a function boundary that should NOT be descended into\n * when searching for generator yields.\n */\nfunction isFunctionBoundary(node: Node): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  const kind = node.getKind();\n  return (\n    kind === SyntaxKind.FunctionDeclaration ||\n    kind === SyntaxKind.FunctionExpression ||\n    kind === SyntaxKind.ArrowFunction ||\n    kind === SyntaxKind.MethodDeclaration ||\n    kind === SyntaxKind.ClassDeclaration ||\n    kind === SyntaxKind.ClassExpression ||\n    kind === SyntaxKind.Constructor\n  );\n}\n\n/**\n * Boundary-aware check: does `node` contain (or is itself) a YieldExpression\n * without crossing into nested function/class bodies?\n */\nfunction containsGeneratorYield(node: Node): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  // Check the node itself first\n  if (node.getKind() === SyntaxKind.YieldExpression) return true;\n  let found = false;\n  node.forEachChild((child) => {\n    if (found) return;\n    if (isFunctionBoundary(child)) return; // SKIP nested functions\n    if (child.getKind() === SyntaxKind.YieldExpression) {\n      found = true;\n      return;\n    }\n    if (containsGeneratorYield(child)) {\n      found = true;\n      return;\n    }\n  });\n  return found;\n}\n\n/**\n * Extract a literal value from an expression node if it's a simple literal.\n * Returns the string representation or undefined if not a literal.\n */\nfunction extractLiteralValue(expr: Node): string | undefined {\n  const { SyntaxKind } = loadTsMorph();\n  const kind = expr.getKind();\n  switch (kind) {\n    case SyntaxKind.StringLiteral:\n      return (expr as StringLiteral).getLiteralValue();\n    case SyntaxKind.NumericLiteral:\n      return (expr as NumericLiteral).getLiteralValue().toString();\n    case SyntaxKind.TrueKeyword:\n      return 'true';\n    case SyntaxKind.FalseKeyword:\n      return 'false';\n    case SyntaxKind.NullKeyword:\n      return 'null';\n    case SyntaxKind.NoSubstitutionTemplateLiteral:\n      return expr.getText().replace(/^`|`$/g, '');\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Resolve const values in a condition string by substituting known const identifiers.\n */\nfunction resolveConditionConsts(condition: string, constValues: Map<string, string>): string {\n  if (constValues.size === 0) return condition;\n  let resolved = condition;\n  for (const [name, value] of constValues) {\n    // Replace standalone identifier references (word boundary) with the resolved value\n    const pattern = new RegExp(`\\\\b${name}\\\\b`, 'g');\n    const replacement = /^\\d/.test(value) || value === 'true' || value === 'false' || value === 'null'\n      ? value\n      : `'${value}'`;\n    resolved = resolved.replace(pattern, replacement);\n  }\n  return resolved;\n}\n\n/**\n * Simplify boolean expressions: true && X → X, false || X → X, etc.\n */\nfunction simplifyBooleanExpression(expr: string): string {\n  let result = expr;\n  // true && X → X\n  result = result.replace(/\\btrue\\b\\s*&&\\s*/g, '');\n  result = result.replace(/\\s*&&\\s*\\btrue\\b/g, '');\n  // false || X → X\n  result = result.replace(/\\bfalse\\b\\s*\\|\\|\\s*/g, '');\n  result = result.replace(/\\s*\\|\\|\\s*\\bfalse\\b/g, '');\n  // false && X → false\n  result = result.replace(/\\bfalse\\b\\s*&&\\s*[^|&]+/g, 'false');\n  // true || X → true\n  result = result.replace(/\\btrue\\b\\s*\\|\\|\\s*[^|&]+/g, 'true');\n  return result.trim();\n}\n\n/**\n * Check if a statement has a terminator (break/return/throw/continue) at the end.\n */\nfunction hasTerminatorStatement(stmts: readonly Node[]): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  if (stmts.length === 0) return false;\n  const last = stmts[stmts.length - 1];\n  if (!last) return false;\n  const kind = last.getKind();\n  return (\n    kind === SyntaxKind.ReturnStatement ||\n    kind === SyntaxKind.ThrowStatement ||\n    kind === SyntaxKind.BreakStatement ||\n    kind === SyntaxKind.ContinueStatement\n  );\n}\n\n/**\n * Collect all yield* expressions from a node in depth-first left-to-right order,\n * respecting function boundaries.\n */\nfunction collectYieldExpressionsDF(node: Node): Node[] {\n  const { SyntaxKind } = loadTsMorph();\n  const results: Node[] = [];\n  node.forEachChild((child) => {\n    if (isFunctionBoundary(child)) return;\n    if (child.getKind() === SyntaxKind.YieldExpression) {\n      results.push(child);\n    } else {\n      results.push(...collectYieldExpressionsDF(child));\n    }\n  });\n  return results;\n}\n\nfunction collectCallExpressionsBoundaryAware(node: Node): CallExpression[] {\n  const { SyntaxKind } = loadTsMorph();\n  const calls: CallExpression[] = [];\n  const visit = (current: Node): void => {\n    current.forEachChild((child) => {\n      if (isFunctionBoundary(child)) return;\n      if (child.getKind() === SyntaxKind.CallExpression) {\n        calls.push(child as CallExpression);\n      }\n      visit(child);\n    });\n  };\n  visit(node);\n  return calls;\n}\n\n// =============================================================================\n// effect-flow Step.* Detection Helpers\n// =============================================================================\n\n/** Known Step.* function names from the effect-flow library. */\nconst STEP_FUNCTIONS = new Set([\n  'Step.run', 'Step.decide', 'Step.branch', 'Step.all',\n  'Step.forEach', 'Step.retry', 'Step.race', 'Step.sleep',\n]);\n\n/**\n * Check if a node is a CallExpression whose callee matches `Step.*` patterns.\n */\nfunction isStepCall(node: Node): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  if (node.getKind() !== SyntaxKind.CallExpression) return false;\n  const callee = (node as CallExpression).getExpression().getText();\n  return STEP_FUNCTIONS.has(callee);\n}\n\n/**\n * Extract the string literal text from a node, or undefined if not a string literal.\n */\nfunction extractStringLiteral(node: Node | undefined): string | undefined {\n  if (!node) return undefined;\n  const { SyntaxKind } = loadTsMorph();\n  if (node.getKind() === SyntaxKind.StringLiteral) {\n    return (node as StringLiteral).getLiteralText();\n  }\n  return undefined;\n}\n\n/**\n * Parse an ObjectLiteralExpression into StaticSwitchCase[] for Step.branch cases.\n */\nfunction parseBranchCases(casesObj: Node | undefined): StaticSwitchCase[] {\n  if (!casesObj) return [];\n  const { SyntaxKind } = loadTsMorph();\n  if (casesObj.getKind() !== SyntaxKind.ObjectLiteralExpression) return [];\n  const cases: StaticSwitchCase[] = [];\n  const objLit = casesObj as ObjectLiteralExpression;\n  for (const prop of objLit.getProperties()) {\n    if (prop.getKind() === SyntaxKind.PropertyAssignment) {\n      const name = (prop as PropertyAssignment).getName();\n      cases.push({\n        labels: [name],\n        isDefault: name === 'default',\n        body: [], // The effect in the property value would need deep analysis\n      });\n    }\n  }\n  return cases;\n}\n\n/**\n * Analyze a Step.* call expression and produce enriched IR nodes.\n * Only called when `ctx.opts.enableEffectFlow` is true.\n */\nfunction analyzeStepCall(\n  callExpr: CallExpression,\n  ctx: WalkerContext,\n): Effect.Effect<StaticFlowNode, AnalysisError> {\n  return Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const callee = callExpr.getExpression().getText();\n    const args = callExpr.getArguments();\n\n    switch (callee) {\n      case 'Step.run': {\n        // Step.run(id, effect) -> analyze the inner effect, enrich with step ID\n        const stepId = extractStringLiteral(args[0]);\n        const innerEffect = args[1];\n        if (!innerEffect) {\n          const node: StaticEffectNode = {\n            id: generateId(),\n            type: 'effect',\n            callee: 'Step.run',\n            name: stepId,\n            displayName: stepId,\n          };\n          ctx.stats.totalEffects++;\n          return node;\n        }\n        const analyzed = yield* analyzeEffectExpression(\n          innerEffect,\n          ctx.sourceFile,\n          ctx.filePath,\n          ctx.opts,\n          ctx.warnings,\n          ctx.stats,\n          ctx.serviceScope,\n        );\n        return {\n          ...analyzed,\n          displayName: stepId ?? analyzed.displayName,\n          name: stepId ?? analyzed.name,\n        };\n      }\n\n      case 'Step.decide': {\n        // Step.decide(id, label, conditionEffect) -> StaticDecisionNode\n        const stepId = extractStringLiteral(args[0]);\n        const label = extractStringLiteral(args[1]);\n        ctx.stats.decisionCount++;\n        const decisionNode: StaticDecisionNode = {\n          id: generateId(),\n          type: 'decision',\n          decisionId: stepId ?? generateId(),\n          label: label ?? stepId ?? 'decision',\n          condition: args[2]?.getText() ?? 'unknown',\n          source: 'effect-flow',\n          onTrue: [],   // The if/else around it captures branches\n          onFalse: undefined,\n        };\n        return decisionNode;\n      }\n\n      case 'Step.branch': {\n        // Step.branch(id, expression, cases) -> StaticSwitchNode\n        const stepId = extractStringLiteral(args[0]);\n        const expression = args[1]?.getText() ?? 'unknown';\n        const casesObj = args[2];\n        const cases = parseBranchCases(casesObj);\n        ctx.stats.switchCount++;\n        const switchNode: StaticSwitchNode = {\n          id: generateId(),\n          type: 'switch',\n          switchId: stepId,\n          expression,\n          cases,\n          source: 'effect-flow',\n          hasDefault: cases.some((c) => c.isDefault),\n          hasFallthrough: false,\n        };\n        return switchNode;\n      }\n\n      case 'Step.all': {\n        // Step.all(id, effects) -> StaticParallelNode with enriched name\n        const stepId = extractStringLiteral(args[0]);\n        const effectsArg = args[1];\n        const children: StaticFlowNode[] = [];\n        if (effectsArg?.getKind() === SyntaxKind.ArrayLiteralExpression) {\n          const arrayLit = effectsArg as ArrayLiteralExpression;\n          for (const element of arrayLit.getElements()) {\n            const analyzed = yield* analyzeEffectExpression(\n              element,\n              ctx.sourceFile,\n              ctx.filePath,\n              ctx.opts,\n              ctx.warnings,\n              ctx.stats,\n              ctx.serviceScope,\n            );\n            children.push(analyzed);\n          }\n        }\n        ctx.stats.parallelCount++;\n        const parallelNode: StaticParallelNode = {\n          id: generateId(),\n          type: 'parallel',\n          name: stepId,\n          displayName: stepId,\n          children,\n          mode: 'parallel',\n          callee: 'Step.all',\n        };\n        return parallelNode;\n      }\n\n      case 'Step.forEach': {\n        // Step.forEach(id, items, fn) -> StaticLoopNode with enriched name\n        const stepId = extractStringLiteral(args[0]);\n        const iterSource = args[1]?.getText();\n        const fn = args[2];\n        let body: StaticFlowNode = { id: generateId(), type: 'effect', callee: 'unknown' };\n        if (fn) {\n          const analyzed = yield* analyzeEffectExpression(\n            fn,\n            ctx.sourceFile,\n            ctx.filePath,\n            ctx.opts,\n            ctx.warnings,\n            ctx.stats,\n            ctx.serviceScope,\n          );\n          body = analyzed;\n        }\n        ctx.stats.loopCount++;\n        const loopNode: StaticLoopNode = {\n          id: generateId(),\n          type: 'loop',\n          name: stepId,\n          displayName: stepId,\n          loopType: 'forEach',\n          iterSource,\n          body,\n        };\n        return loopNode;\n      }\n\n      case 'Step.retry': {\n        // Step.retry(id, effect, options) -> StaticRetryNode\n        const stepId = extractStringLiteral(args[0]);\n        const innerEffect = args[1];\n        if (!innerEffect) {\n          const node: StaticEffectNode = {\n            id: generateId(),\n            type: 'effect',\n            callee: 'Step.retry',\n            name: stepId,\n            displayName: stepId,\n          };\n          ctx.stats.totalEffects++;\n          return node;\n        }\n        const analyzed = yield* analyzeEffectExpression(\n          innerEffect,\n          ctx.sourceFile,\n          ctx.filePath,\n          ctx.opts,\n          ctx.warnings,\n          ctx.stats,\n          ctx.serviceScope,\n        );\n        ctx.stats.retryCount++;\n        const retryNode: StaticRetryNode = {\n          id: generateId(),\n          type: 'retry',\n          name: stepId,\n          displayName: stepId,\n          source: analyzed,\n          hasFallback: false,\n        };\n        return retryNode;\n      }\n\n      case 'Step.race': {\n        // Step.race(id, effects) -> StaticRaceNode\n        const stepId = extractStringLiteral(args[0]);\n        const effectsArg = args[1];\n        const children: StaticFlowNode[] = [];\n        if (effectsArg?.getKind() === SyntaxKind.ArrayLiteralExpression) {\n          const arrayLit = effectsArg as ArrayLiteralExpression;\n          for (const element of arrayLit.getElements()) {\n            const analyzed = yield* analyzeEffectExpression(\n              element,\n              ctx.sourceFile,\n              ctx.filePath,\n              ctx.opts,\n              ctx.warnings,\n              ctx.stats,\n              ctx.serviceScope,\n            );\n            children.push(analyzed);\n          }\n        }\n        ctx.stats.raceCount++;\n        const raceNode: StaticRaceNode = {\n          id: generateId(),\n          type: 'race',\n          name: stepId,\n          displayName: stepId,\n          children,\n          callee: 'Step.race',\n        };\n        return raceNode;\n      }\n\n      case 'Step.sleep': {\n        // Step.sleep(id, duration) -> StaticEffectNode with scheduling role\n        const stepId = extractStringLiteral(args[0]);\n        const effectNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee: 'Step.sleep',\n          name: stepId,\n          displayName: stepId,\n          semanticRole: 'scheduling',\n        };\n        ctx.stats.totalEffects++;\n        return effectNode;\n      }\n\n      default: {\n        // Unknown Step.* call — fallback to generic effect analysis\n        const node: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee,\n          name: callee,\n          displayName: callee,\n        };\n        ctx.stats.totalEffects++;\n        return node;\n      }\n    }\n  });\n}\n\n/** Walker context threaded through statement analysis. */\ninterface WalkerContext {\n  readonly sourceFile: SourceFile;\n  readonly filePath: string;\n  readonly opts: Required<AnalyzerOptions>;\n  readonly warnings: AnalysisWarning[];\n  readonly stats: AnalysisStats;\n  readonly serviceScope: Map<string, string>;\n  /** Parameter names accepted by Effect.gen callback adapters, e.g. `_` in `Effect.gen(function*(_) {})`. */\n  readonly generatorAdapterParams: ReadonlySet<string>;\n  /** Tracks const declarations with literal initializers for condition simplification */\n  readonly constValues: Map<string, string>;\n}\n\n/**\n * Analyze a single yield expression: call analyzeEffectExpression on\n * its inner expression, enrich, and track service scope.\n */\nfunction analyzeYieldNode(\n  yieldNode: Node,\n  ctx: WalkerContext,\n): Effect.Effect<{ variableName: string | undefined; effect: StaticFlowNode }, AnalysisError> {\n  return Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const yieldExpr = yieldNode as YieldExpression;\n    const isDelegated = yieldExpr.getText().startsWith('yield*');\n    const expr = yieldExpr.getExpression();\n\n    // Plain yield (not yield*)\n    if (!isDelegated) {\n      const opaqueNode: StaticOpaqueNode = {\n        id: generateId(),\n        type: 'opaque',\n        reason: 'plain-yield',\n        sourceText: yieldNode.getText().slice(0, 80),\n      };\n      ctx.stats.opaqueCount++;\n      ctx.warnings.push({\n        code: 'PLAIN_YIELD',\n        message: `Plain yield (not yield*) detected; this is unusual in Effect generators: ${yieldNode.getText().slice(0, 60)}`,\n        location: extractLocation(yieldNode, ctx.filePath, ctx.opts.includeLocations ?? false),\n      });\n      return { variableName: extractYieldVariableName(yieldNode), effect: opaqueNode };\n    }\n\n    if (!expr) {\n      const opaqueNode: StaticOpaqueNode = {\n        id: generateId(),\n        type: 'opaque',\n        reason: 'yield-no-expression',\n        sourceText: yieldNode.getText().slice(0, 80),\n      };\n      ctx.stats.opaqueCount++;\n      return { variableName: undefined, effect: opaqueNode };\n    }\n\n    // Effect.gen adapter form: yield* _(effect)\n    // Widely used in Effect ecosystem examples and wrappers.\n    let effectExpr: Node = expr;\n    const unwrappedCall = unwrapExpression(expr);\n    if (unwrappedCall.getKind() === SyntaxKind.CallExpression) {\n      const call = unwrappedCall as CallExpression;\n      const calleeExpr = call.getExpression();\n      if (\n        calleeExpr.getKind() === SyntaxKind.Identifier &&\n        ctx.generatorAdapterParams.has((calleeExpr as Identifier).getText()) &&\n        call.getArguments().length >= 1\n      ) {\n        effectExpr = (call.getArguments()[0]) ?? expr;\n      }\n    }\n\n    // effect-flow: intercept Step.* calls when enableEffectFlow is active\n    const unwrappedExpr = unwrapExpression(effectExpr);\n    if (ctx.opts.enableEffectFlow && isStepCall(unwrappedExpr)) {\n      const stepResult = yield* analyzeStepCall(unwrappedExpr as CallExpression, ctx);\n      const variableName = extractYieldVariableName(yieldNode);\n      const enrichedStep = {\n        ...stepResult,\n        displayName: stepResult.displayName ?? computeDisplayName(stepResult, variableName),\n        semanticRole: stepResult.semanticRole ?? computeSemanticRole(stepResult),\n      };\n      return { variableName, effect: enrichedStep };\n    }\n\n    const analyzed = yield* analyzeEffectExpression(\n      effectExpr,\n      ctx.sourceFile,\n      ctx.filePath,\n      ctx.opts,\n      ctx.warnings,\n      ctx.stats,\n      ctx.serviceScope,\n    );\n    const variableName = extractYieldVariableName(yieldNode);\n    if (\n      variableName &&\n      analyzed.type === 'effect' &&\n      isServiceTagCallee((analyzed).callee)\n    ) {\n      ctx.serviceScope.set(variableName, (analyzed).callee);\n    }\n    const enrichedEffect = {\n      ...analyzed,\n      ...(variableName && analyzed.type === 'fiber' ? { name: variableName } : {}),\n      displayName: computeDisplayName(analyzed, variableName),\n      semanticRole: analyzed.semanticRole ?? computeSemanticRole(analyzed),\n    };\n    return { variableName, effect: enrichedEffect };\n  });\n}\n\n/**\n * Walk a block (or block-like body) statement-by-statement and produce structured IR.\n */\nfunction analyzeGeneratorBody(\n  block: import('ts-morph').Block,\n  ctx: WalkerContext,\n): Effect.Effect<StaticGeneratorNode['yields'], AnalysisError> {\n  return Effect.gen(function* () {\n    const stmts = block.getStatements();\n    const result: StaticGeneratorNode['yields'][number][] = [];\n    for (const stmt of stmts) {\n      const nodes = yield* analyzeStatement(stmt, ctx);\n      result.push(...nodes);\n    }\n    return result;\n  });\n}\n\n/**\n * Main statement dispatcher: analyze a single statement and return yield entries.\n */\nfunction analyzeStatement(\n  stmt: Node,\n  ctx: WalkerContext,\n): Effect.Effect<StaticGeneratorNode['yields'], AnalysisError> {\n  return Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const kind = stmt.getKind();\n\n    switch (kind) {\n      // -------------------------------------------------------------------\n      // ExpressionStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ExpressionStatement: {\n        const exprStmt = stmt as ExpressionStatement;\n        const expr = exprStmt.getExpression();\n        return yield* analyzeExpressionForYields(expr, ctx);\n      }\n\n      // -------------------------------------------------------------------\n      // VariableStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.VariableStatement: {\n        const varStmt = stmt as VariableStatement;\n        const result: StaticGeneratorNode['yields'][number][] = [];\n        const { VariableDeclarationKind } = loadTsMorph();\n        const isConst = varStmt.getDeclarationKind() === VariableDeclarationKind.Const;\n        for (const decl of varStmt.getDeclarations()) {\n          const init = decl.getInitializer();\n\n          // Track const declarations with literal initializers for condition resolution\n          if (isConst && init) {\n            const literalValue = extractLiteralValue(init);\n            if (literalValue !== undefined) {\n              ctx.constValues.set(decl.getName(), literalValue);\n            }\n          }\n\n          // Preserve Context.pick/Context.omit steps even when not yield*'d.\n          // These are pure but context-shaping and are part of intended IR coverage.\n          if (init && !containsGeneratorYield(init) && init.getKind() === SyntaxKind.CallExpression) {\n            const callExpr = init as CallExpression;\n            const calleeText = callExpr.getExpression().getText();\n            if (calleeText === 'Context.pick' || calleeText === 'Context.omit') {\n              const analyzed = yield* analyzeEffectExpression(\n                callExpr,\n                ctx.sourceFile,\n                ctx.filePath,\n                ctx.opts,\n                ctx.warnings,\n                ctx.stats,\n                ctx.serviceScope,\n              );\n              if (analyzed.type === 'effect' && analyzed.description === 'context') {\n                result.push({ variableName: decl.getName(), effect: analyzed });\n              }\n              continue;\n            }\n          }\n\n          if (init && containsGeneratorYield(init)) {\n            const yieldEntries = yield* analyzeExpressionForYields(init, ctx);\n            // Try to get variable name from the declaration for the last yield\n            if (yieldEntries.length > 0) {\n              const declName = decl.getName();\n              const lastEntry = yieldEntries[yieldEntries.length - 1];\n              if (lastEntry) {\n                yieldEntries[yieldEntries.length - 1] = {\n                  ...lastEntry,\n                  variableName: lastEntry.variableName ?? declName,\n                };\n              }\n            }\n            result.push(...yieldEntries);\n          }\n        }\n        return result;\n      }\n\n      // -------------------------------------------------------------------\n      // IfStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.IfStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const ifStmt = stmt as IfStatement;\n        const condition = ifStmt.getExpression().getText();\n\n        // Check if condition itself has yields\n        const condYields = yield* analyzeExpressionForYields(\n          ifStmt.getExpression(),\n          ctx,\n        );\n\n        const thenStmt = ifStmt.getThenStatement();\n        const elseStmt = ifStmt.getElseStatement();\n\n        const onTrue = yield* analyzeStatementBlock(thenStmt, ctx);\n        const onFalse = elseStmt\n          ? yield* analyzeStatementBlock(elseStmt, ctx)\n          : undefined;\n\n        const resolvedCondition = simplifyBooleanExpression(resolveConditionConsts(condition, ctx.constValues));\n        const decisionLabel = resolvedCondition.length > 40 ? resolvedCondition.slice(0, 40) + '...' : resolvedCondition;\n        const decisionNode: StaticDecisionNode = {\n          id: generateId(),\n          type: 'decision',\n          decisionId: generateId(),\n          label: decisionLabel,\n          condition,\n          source: 'raw-if',\n          onTrue: onTrue.map((y) => y.effect),\n          onFalse: onFalse && onFalse.length > 0 ? onFalse.map((y) => y.effect) : undefined,\n        };\n        ctx.stats.decisionCount++;\n\n        return [\n          ...condYields,\n          { effect: decisionNode },\n        ];\n      }\n\n      // -------------------------------------------------------------------\n      // SwitchStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.SwitchStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const switchStmt = stmt as SwitchStatement;\n        const expression = switchStmt.getExpression().getText();\n\n        const clauses = switchStmt.getClauses();\n        const cases: StaticSwitchCase[] = [];\n        let hasFallthrough = false;\n        let hasDefault = false;\n\n        // Build fallthrough groups\n        let currentLabels: string[] = [];\n        let currentBodyYields: StaticGeneratorNode['yields'] = [];\n        let currentIsDefault = false;\n\n        for (const clause of clauses) {\n          const isDefault = clause.getKind() === SyntaxKind.DefaultClause;\n          if (isDefault) {\n            hasDefault = true;\n            currentIsDefault = true;\n            currentLabels.push('default');\n          } else {\n            const caseClause = clause as CaseClause;\n            currentLabels.push(caseClause.getExpression().getText());\n          }\n\n          const clauseStmts = clause.getStatements();\n          if (clauseStmts.length === 0) {\n            // Empty clause body = fallthrough\n            hasFallthrough = true;\n            continue;\n          }\n\n          // Analyze clause body\n          for (const clauseStmt of clauseStmts) {\n            const yieldEntries = yield* analyzeStatement(clauseStmt, ctx);\n            currentBodyYields.push(...yieldEntries);\n          }\n\n          const hasTerminator = hasTerminatorStatement(clauseStmts);\n          if (!hasTerminator) {\n            hasFallthrough = true;\n          }\n\n          cases.push({\n            labels: currentLabels,\n            isDefault: currentIsDefault,\n            body: currentBodyYields.map((y) => y.effect),\n          });\n          currentLabels = [];\n          currentBodyYields = [];\n          currentIsDefault = false;\n        }\n\n        // Flush remaining group\n        if (currentLabels.length > 0) {\n          cases.push({\n            labels: currentLabels,\n            isDefault: currentIsDefault,\n            body: currentBodyYields.map((y) => y.effect),\n          });\n        }\n\n        const resolvedExpression = resolveConditionConsts(expression, ctx.constValues);\n        const switchNode: StaticSwitchNode = {\n          id: generateId(),\n          type: 'switch',\n          switchId: generateId(),\n          expression: resolvedExpression,\n          cases,\n          source: 'raw-js',\n          hasDefault,\n          hasFallthrough,\n        };\n        ctx.stats.switchCount++;\n\n        return [{ effect: switchNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // ForStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ForStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const forStmt = stmt as ForStatement;\n\n        // Check for yields in header (initializer / incrementor)\n        const headerYields: StaticFlowNode[] = [];\n        const initializer = forStmt.getInitializer();\n        if (initializer && containsGeneratorYield(initializer)) {\n          const entries = yield* analyzeExpressionForYields(initializer, ctx);\n          headerYields.push(...entries.map((e) => e.effect));\n        }\n        const incrementor = forStmt.getIncrementor();\n        if (incrementor && containsGeneratorYield(incrementor)) {\n          const entries = yield* analyzeExpressionForYields(incrementor, ctx);\n          headerYields.push(...entries.map((e) => e.effect));\n        }\n\n        const bodyStmt = forStmt.getStatement();\n        const bodyYields = yield* analyzeStatementBlock(bodyStmt, ctx);\n        const hasEarlyExit = checkEarlyExit(bodyStmt);\n\n        const condition = forStmt.getCondition();\n        const iterSource = condition ? condition.getText() : undefined;\n\n        const loopBody: StaticFlowNode =\n          bodyYields.length === 1 && bodyYields[0]\n            ? bodyYields[0].effect\n            : {\n                id: generateId(),\n                type: 'generator' as const,\n                yields: bodyYields,\n              };\n\n        const loopNode: StaticLoopNode = {\n          id: generateId(),\n          type: 'loop',\n          loopType: 'for',\n          iterSource,\n          body: loopBody,\n          ...(hasEarlyExit ? { hasEarlyExit } : {}),\n          ...(headerYields.length > 0 ? { headerYields } : {}),\n        };\n        ctx.stats.loopCount++;\n\n        return [{ effect: loopNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // ForOfStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ForOfStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const forOfStmt = stmt as ForOfStatement;\n\n        const iterExpr = forOfStmt.getExpression();\n        const iterSource = iterExpr.getText();\n\n        // Check for yield* in the iterable expression: `for (const x of yield* items)`\n        const headerYields: StaticFlowNode[] = [];\n        if (containsGeneratorYield(iterExpr)) {\n          const entries = yield* analyzeExpressionForYields(iterExpr, ctx);\n          headerYields.push(...entries.map((e) => e.effect));\n        }\n\n        const iterVariable = forOfStmt.getInitializer().getText();\n\n        const bodyStmt = forOfStmt.getStatement();\n        const bodyYields = yield* analyzeStatementBlock(bodyStmt, ctx);\n        const hasEarlyExit = checkEarlyExit(bodyStmt);\n\n        const loopBody: StaticFlowNode =\n          bodyYields.length === 1 && bodyYields[0]\n            ? bodyYields[0].effect\n            : {\n                id: generateId(),\n                type: 'generator' as const,\n                yields: bodyYields,\n              };\n\n        const loopNode: StaticLoopNode = {\n          id: generateId(),\n          type: 'loop',\n          loopType: 'forOf',\n          iterSource,\n          body: loopBody,\n          ...(hasEarlyExit ? { hasEarlyExit } : {}),\n          ...(headerYields.length > 0 ? { headerYields } : {}),\n          iterVariable,\n        };\n        ctx.stats.loopCount++;\n\n        return [{ effect: loopNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // ForInStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ForInStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const forInStmt = stmt as ForInStatement;\n\n        const iterSource = forInStmt.getExpression().getText();\n        const iterVariable = forInStmt.getInitializer().getText();\n\n        const bodyStmt = forInStmt.getStatement();\n        const bodyYields = yield* analyzeStatementBlock(bodyStmt, ctx);\n        const hasEarlyExit = checkEarlyExit(bodyStmt);\n\n        const loopBody: StaticFlowNode =\n          bodyYields.length === 1 && bodyYields[0]\n            ? bodyYields[0].effect\n            : {\n                id: generateId(),\n                type: 'generator' as const,\n                yields: bodyYields,\n              };\n\n        const loopNode: StaticLoopNode = {\n          id: generateId(),\n          type: 'loop',\n          loopType: 'forIn',\n          iterSource,\n          body: loopBody,\n          ...(hasEarlyExit ? { hasEarlyExit } : {}),\n          iterVariable,\n        };\n        ctx.stats.loopCount++;\n\n        return [{ effect: loopNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // WhileStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.WhileStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const whileStmt = stmt as WhileStatement;\n\n        const condition = whileStmt.getExpression().getText();\n\n        const bodyStmt = whileStmt.getStatement();\n        const bodyYields = yield* analyzeStatementBlock(bodyStmt, ctx);\n        const hasEarlyExit = checkEarlyExit(bodyStmt);\n\n        const loopBody: StaticFlowNode =\n          bodyYields.length === 1 && bodyYields[0]\n            ? bodyYields[0].effect\n            : {\n                id: generateId(),\n                type: 'generator' as const,\n                yields: bodyYields,\n              };\n\n        const loopNode: StaticLoopNode = {\n          id: generateId(),\n          type: 'loop',\n          loopType: 'while',\n          iterSource: condition,\n          body: loopBody,\n          ...(hasEarlyExit ? { hasEarlyExit } : {}),\n        };\n        ctx.stats.loopCount++;\n\n        return [{ effect: loopNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // DoStatement (do-while)\n      // -------------------------------------------------------------------\n      case SyntaxKind.DoStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const doStmt = stmt as DoStatement;\n\n        const condition = doStmt.getExpression().getText();\n\n        const bodyStmt = doStmt.getStatement();\n        const bodyYields = yield* analyzeStatementBlock(bodyStmt, ctx);\n        const hasEarlyExit = checkEarlyExit(bodyStmt);\n\n        const loopBody: StaticFlowNode =\n          bodyYields.length === 1 && bodyYields[0]\n            ? bodyYields[0].effect\n            : {\n                id: generateId(),\n                type: 'generator' as const,\n                yields: bodyYields,\n              };\n\n        const loopNode: StaticLoopNode = {\n          id: generateId(),\n          type: 'loop',\n          loopType: 'doWhile',\n          iterSource: condition,\n          body: loopBody,\n          ...(hasEarlyExit ? { hasEarlyExit } : {}),\n        };\n        ctx.stats.loopCount++;\n\n        return [{ effect: loopNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // TryStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.TryStatement: {\n        if (!containsGeneratorYield(stmt)) return [];\n        const tryStmt = stmt as TryStatement;\n\n        const tryBlock = tryStmt.getTryBlock();\n        const tryYields = yield* analyzeGeneratorBody(tryBlock, ctx);\n\n        const catchClause = tryStmt.getCatchClause();\n        let catchVariable: string | undefined;\n        let catchYields: StaticGeneratorNode['yields'] | undefined;\n        if (catchClause) {\n          const variableDecl = catchClause.getVariableDeclaration();\n          catchVariable = variableDecl?.getName();\n          const catchBlock = catchClause.getBlock();\n          catchYields = yield* analyzeGeneratorBody(catchBlock, ctx);\n        }\n\n        const finallyBlock = tryStmt.getFinallyBlock();\n        let finallyYields: StaticGeneratorNode['yields'] | undefined;\n        if (finallyBlock) {\n          finallyYields = yield* analyzeGeneratorBody(finallyBlock, ctx);\n        }\n\n        const hasTerminalInTry = hasTerminatorStatement(tryBlock.getStatements());\n\n        const tryCatchNode: StaticTryCatchNode = {\n          id: generateId(),\n          type: 'try-catch',\n          tryBody: tryYields.map((y) => y.effect),\n          ...(catchVariable ? { catchVariable } : {}),\n          ...(catchYields && catchYields.length > 0\n            ? { catchBody: catchYields.map((y) => y.effect) }\n            : {}),\n          ...(finallyYields && finallyYields.length > 0\n            ? { finallyBody: finallyYields.map((y) => y.effect) }\n            : {}),\n          hasTerminalInTry,\n        };\n        ctx.stats.tryCatchCount++;\n\n        return [{ effect: tryCatchNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // ReturnStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ReturnStatement: {\n        const retStmt = stmt as ReturnStatement;\n        const expr = retStmt.getExpression();\n\n        if (!expr) {\n          return [];\n        }\n\n        if (!containsGeneratorYield(expr)) {\n          const { SyntaxKind } = loadTsMorph();\n          const entries: StaticFlowNode[] = [];\n          if (expr.getKind() === SyntaxKind.CallExpression) {\n            const analyzed = yield* analyzeEffectExpression(\n              expr,\n              ctx.sourceFile,\n              ctx.filePath,\n              ctx.opts,\n              ctx.warnings,\n              ctx.stats,\n              ctx.serviceScope,\n            );\n            if (analyzed.type !== 'unknown') {\n              entries.push(analyzed);\n            }\n          }\n\n          const descendantCalls = expr.getDescendantsOfKind(SyntaxKind.CallExpression);\n          for (const call of descendantCalls) {\n            const analyzed = yield* analyzeEffectExpression(\n              call,\n              ctx.sourceFile,\n              ctx.filePath,\n              ctx.opts,\n              ctx.warnings,\n              ctx.stats,\n              ctx.serviceScope,\n            );\n            if (analyzed.type !== 'unknown') {\n              const duplicate = entries.some(\n                (entry) =>\n                  entry.type === analyzed.type &&\n                  'id' in entry &&\n                  ((entry as StaticFlowNode & { callee?: string }).callee ===\n                    (analyzed as StaticFlowNode & { callee?: string }).callee),\n              );\n              if (!duplicate) entries.push(analyzed);\n            }\n          }\n\n          if (entries.length === 0) return [];\n          const termNode: StaticTerminalNode = {\n            id: generateId(),\n            type: 'terminal',\n            terminalKind: 'return',\n            value: entries,\n          };\n          ctx.stats.terminalCount++;\n          return [{ effect: termNode }];\n        }\n\n        // return yield* X or return (yield* X) — analyze the yield expression\n        const yieldEntries = yield* analyzeExpressionForYields(expr, ctx);\n        const termNode: StaticTerminalNode = {\n          id: generateId(),\n          type: 'terminal',\n          terminalKind: 'return',\n          value: yieldEntries.map((y) => y.effect),\n        };\n        ctx.stats.terminalCount++;\n        return [{ effect: termNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // ThrowStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ThrowStatement: {\n        const throwStmt = stmt as ThrowStatement;\n        const expr = throwStmt.getExpression();\n        if (!containsGeneratorYield(expr)) {\n          // throw without yields — skip (not interesting for the IR at top level)\n          return [];\n        }\n\n        const valueYields = yield* analyzeExpressionForYields(expr, ctx);\n\n        const termNode: StaticTerminalNode = {\n          id: generateId(),\n          type: 'terminal',\n          terminalKind: 'throw',\n          ...(valueYields.length > 0 ? { value: valueYields.map((y) => y.effect) } : {}),\n        };\n        ctx.stats.terminalCount++;\n        return [{ effect: termNode }];\n      }\n\n      // -------------------------------------------------------------------\n      // BreakStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.BreakStatement: {\n        // Only emit break as a terminal when inside a yield-containing control flow.\n        // We always skip at the top level since it can't appear there anyway,\n        // but it may appear inside switch/loop bodies that we recurse into.\n        return [];\n      }\n\n      // -------------------------------------------------------------------\n      // ContinueStatement\n      // -------------------------------------------------------------------\n      case SyntaxKind.ContinueStatement: {\n        // Same as break — skip as a yield entry.\n        return [];\n      }\n\n      // -------------------------------------------------------------------\n      // LabeledStatement — unwrap inner statement\n      // -------------------------------------------------------------------\n      case SyntaxKind.LabeledStatement: {\n        const labeledStmt = stmt as LabeledStatement;\n        return yield* analyzeStatement(labeledStmt.getStatement(), ctx);\n      }\n\n      // -------------------------------------------------------------------\n      // Block — recurse\n      // -------------------------------------------------------------------\n      case SyntaxKind.Block: {\n        return yield* analyzeGeneratorBody(stmt as Block, ctx);\n      }\n\n      // -------------------------------------------------------------------\n      // Default — skip non-yield-containing statements\n      // -------------------------------------------------------------------\n      default:\n        return [];\n    }\n  });\n}\n\n/**\n * Analyze a statement or block-like node into yield entries.\n * If the node is a Block, delegate to analyzeGeneratorBody.\n * Otherwise, treat it as a single statement (e.g., an if-then body without braces).\n */\nfunction analyzeStatementBlock(\n  stmt: Node,\n  ctx: WalkerContext,\n): Effect.Effect<StaticGeneratorNode['yields'], AnalysisError> {\n  const { SyntaxKind } = loadTsMorph();\n  if (stmt.getKind() === SyntaxKind.Block) {\n    return analyzeGeneratorBody(stmt as Block, ctx);\n  }\n  return analyzeStatement(stmt, ctx);\n}\n\n/**\n * Check if a statement body contains an early exit (break/return) at any depth,\n * respecting function boundaries.\n */\nfunction checkEarlyExit(stmt: Node): boolean {\n  const { SyntaxKind } = loadTsMorph();\n  let found = false;\n  stmt.forEachChild((child) => {\n    if (found) return;\n    if (isFunctionBoundary(child)) return;\n    const k = child.getKind();\n    if (k === SyntaxKind.BreakStatement || k === SyntaxKind.ReturnStatement) {\n      found = true;\n      return;\n    }\n    if (checkEarlyExit(child)) {\n      found = true;\n      return;\n    }\n  });\n  return found;\n}\n\n/**\n * Analyze an expression node for yield expressions. Handles:\n * - Direct yield/yield* expressions\n * - Ternary expressions: cond ? yield* A : yield* B\n * - Short-circuit: cond && yield* A, cond || yield* B, x ?? yield* A\n * - Fallback: collect all yield* in evaluation order\n */\nfunction analyzeExpressionForYields(\n  expr: Node,\n  ctx: WalkerContext,\n): Effect.Effect<StaticGeneratorNode['yields'], AnalysisError> {\n  return Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n\n    if (!containsGeneratorYield(expr)) return [];\n\n    const unwrapped = unwrapExpression(expr);\n    const exprKind = unwrapped.getKind();\n\n    // Direct yield expression\n    if (exprKind === SyntaxKind.YieldExpression) {\n      const entry = yield* analyzeYieldNode(unwrapped, ctx);\n      return [entry];\n    }\n\n    // Ternary: cond ? (yield* A) : (yield* B)\n    if (exprKind === SyntaxKind.ConditionalExpression) {\n      const ternary = unwrapped as ConditionalExpression;\n      const condition = ternary.getCondition().getText();\n      const whenTrue = ternary.getWhenTrue();\n      const whenFalse = ternary.getWhenFalse();\n\n      const trueYields = yield* analyzeExpressionForYields(whenTrue, ctx);\n      const falseYields = yield* analyzeExpressionForYields(whenFalse, ctx);\n\n      if (trueYields.length > 0 || falseYields.length > 0) {\n        const resolvedCond = simplifyBooleanExpression(resolveConditionConsts(condition, ctx.constValues));\n        const decisionNode: StaticDecisionNode = {\n          id: generateId(),\n          type: 'decision',\n          decisionId: generateId(),\n          label: resolvedCond.length > 40 ? resolvedCond.slice(0, 40) + '...' : resolvedCond,\n          condition,\n          source: 'raw-ternary',\n          onTrue: trueYields.map((y) => y.effect),\n          onFalse: falseYields.length > 0 ? falseYields.map((y) => y.effect) : undefined,\n        };\n        ctx.stats.decisionCount++;\n        return [{ effect: decisionNode }];\n      }\n    }\n\n    // Binary expression: short-circuit (&&, ||, ??)\n    if (exprKind === SyntaxKind.BinaryExpression) {\n      const binary = unwrapped as BinaryExpression;\n      const operatorToken = binary.getOperatorToken().getKind();\n      const left = binary.getLeft();\n      const right = binary.getRight();\n\n      // && short-circuit: cond && (yield* A)\n      if (operatorToken === SyntaxKind.AmpersandAmpersandToken) {\n        const rightYields = yield* analyzeExpressionForYields(right, ctx);\n        if (rightYields.length > 0) {\n          const condition = left.getText();\n          const resolvedCond = simplifyBooleanExpression(resolveConditionConsts(condition, ctx.constValues));\n          const decisionNode: StaticDecisionNode = {\n            id: generateId(),\n            type: 'decision',\n            decisionId: generateId(),\n            label: resolvedCond.length > 40 ? resolvedCond.slice(0, 40) + '...' : resolvedCond,\n            condition,\n            source: 'raw-short-circuit',\n            onTrue: rightYields.map((y) => y.effect),\n            onFalse: [],\n          };\n          ctx.stats.decisionCount++;\n          return [{ effect: decisionNode }];\n        }\n      }\n\n      // || short-circuit: cond || (yield* B)\n      if (operatorToken === SyntaxKind.BarBarToken) {\n        const rightYields = yield* analyzeExpressionForYields(right, ctx);\n        if (rightYields.length > 0) {\n          const condition = left.getText();\n          const resolvedCond = simplifyBooleanExpression(resolveConditionConsts(condition, ctx.constValues));\n          const decisionNode: StaticDecisionNode = {\n            id: generateId(),\n            type: 'decision',\n            decisionId: generateId(),\n            label: resolvedCond.length > 40 ? resolvedCond.slice(0, 40) + '...' : resolvedCond,\n            condition,\n            source: 'raw-short-circuit',\n            onTrue: [],\n            onFalse: rightYields.map((y) => y.effect),\n          };\n          ctx.stats.decisionCount++;\n          return [{ effect: decisionNode }];\n        }\n      }\n\n      // ?? nullish coalescing: x ?? (yield* A)\n      if (operatorToken === SyntaxKind.QuestionQuestionToken) {\n        const rightYields = yield* analyzeExpressionForYields(right, ctx);\n        if (rightYields.length > 0) {\n          const condition = `${left.getText()} != null`;\n          const resolvedCond = simplifyBooleanExpression(resolveConditionConsts(condition, ctx.constValues));\n          const decisionNode: StaticDecisionNode = {\n            id: generateId(),\n            type: 'decision',\n            decisionId: generateId(),\n            label: resolvedCond.length > 40 ? resolvedCond.slice(0, 40) + '...' : resolvedCond,\n            condition,\n            source: 'raw-short-circuit',\n            onTrue: [],\n            onFalse: rightYields.map((y) => y.effect),\n          };\n          ctx.stats.decisionCount++;\n          return [{ effect: decisionNode }];\n        }\n      }\n    }\n\n    // Fallback: collect all yield expressions in depth-first order\n    const yieldExprs = collectYieldExpressionsDF(expr);\n    const result: StaticGeneratorNode['yields'] = [];\n    for (const yieldExpr of yieldExprs) {\n      const entry = yield* analyzeYieldNode(yieldExpr, ctx);\n      result.push(entry);\n    }\n    return result;\n  });\n}\n\n// =============================================================================\n// Generator Function Analysis (rewritten with statement-level walker)\n// =============================================================================\n\nexport const analyzeGeneratorFunction = (\n  node: Node,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<readonly StaticFlowNode[], AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n\n    let body: Node | undefined;\n\n    if (\n      node.getKind() === SyntaxKind.ArrowFunction ||\n      node.getKind() === SyntaxKind.FunctionExpression\n    ) {\n      body = (\n        node as\n          | import('ts-morph').ArrowFunction\n          | import('ts-morph').FunctionExpression\n      ).getBody();\n    } else if (node.getKind() === SyntaxKind.FunctionDeclaration) {\n      body = (node as FunctionDeclaration).getBody();\n    }\n\n    if (!body) {\n      return [];\n    }\n\n    const serviceScope = new Map<string, string>();\n    const constValues = new Map<string, string>();\n    const generatorAdapterParams = new Set<string>();\n    if (\n      node.getKind() === SyntaxKind.ArrowFunction ||\n      node.getKind() === SyntaxKind.FunctionExpression ||\n      node.getKind() === SyntaxKind.FunctionDeclaration\n    ) {\n      const fnLike = node as ArrowFunction | FunctionExpression | FunctionDeclaration;\n      for (const param of fnLike.getParameters()) {\n        generatorAdapterParams.add(param.getName());\n      }\n    }\n    const ctx: WalkerContext = {\n      sourceFile,\n      filePath,\n      opts,\n      warnings,\n      stats,\n      serviceScope,\n      generatorAdapterParams,\n      constValues,\n    };\n\n    let yields: StaticGeneratorNode['yields'];\n\n    // If the body is a Block (the normal case), use the statement-level walker\n    if (body.getKind() === SyntaxKind.Block) {\n      yields = yield* analyzeGeneratorBody(body as Block, ctx);\n    } else {\n      // Expression body (arrow function): analyze the expression directly\n      const entries = yield* analyzeExpressionForYields(body, ctx);\n      yields = entries;\n    }\n\n    // Also scan for non-yielded Effect-like call expressions (same as before),\n    // but skip calls that live inside statements already handled by the\n    // statement-level yield walker. This avoids duplicating callback internals,\n    // resource constructors, and return-branch subexpressions as flat siblings.\n    if (body.getKind() === SyntaxKind.Block) {\n      for (const stmt of (body as Block).getStatements()) {\n        if (containsGeneratorYield(stmt)) continue;\n        const stmtKind = stmt.getKind();\n        if (\n          stmtKind !== SyntaxKind.ExpressionStatement &&\n          stmtKind !== SyntaxKind.VariableStatement\n        ) {\n          continue;\n        }\n        const calls = collectCallExpressionsBoundaryAware(stmt);\n        for (const call of calls) {\n          const callCallee = call.getExpression().getText();\n          if (callCallee.includes('withSpan')) continue;\n          const aliases = getAliasesForFile(sourceFile);\n          if (isEffectLikeCallExpression(call, sourceFile, aliases, opts.knownEffectInternalsRoot)) {\n            const analyzed = yield* analyzeEffectCall(\n              call,\n              sourceFile,\n              filePath,\n              opts,\n              warnings,\n              stats,\n              serviceScope,\n            );\n            yields.push({\n              effect: analyzed,\n            });\n          }\n        }\n      }\n    }\n\n    const generatorJSDoc = extractJSDocDescription(node);\n\n    const generatorNode: StaticGeneratorNode = {\n      id: generateId(),\n      type: 'generator',\n      yields,\n      jsdocDescription: generatorJSDoc,\n      jsdocTags: extractJSDocTags(node),\n    };\n    const enrichedGeneratorNode: StaticGeneratorNode = {\n      ...generatorNode,\n      displayName: computeDisplayName(generatorNode),\n      semanticRole: computeSemanticRole(generatorNode),\n    };\n\n    return [enrichedGeneratorNode];\n  });\n\n// =============================================================================\n// Outer `.pipe(...)` on a gen call — wrap the analyzed gen body in retry /\n// timeout / error-handler nodes when the gen call is the base of an outer pipe.\n// =============================================================================\n\n/**\n * If `genCall` is the base of an enclosing `.pipe(...)` (i.e. the expression\n * is `genCall.pipe(...)`), return that pipe CallExpression. Otherwise undefined.\n */\nfunction findOuterPipeOnGen(genCall: CallExpression): CallExpression | undefined {\n  const { SyntaxKind } = loadTsMorph();\n  const parent = genCall.getParent();\n  if (parent?.getKind() !== SyntaxKind.PropertyAccessExpression) return undefined;\n  const pa = parent as PropertyAccessExpression;\n  if (pa.getName() !== 'pipe') return undefined;\n  if (pa.getExpression() !== genCall) return undefined;\n  const grandparent = pa.getParent();\n  if (grandparent?.getKind() !== SyntaxKind.CallExpression) return undefined;\n  const call = grandparent as CallExpression;\n  if (call.getExpression() !== pa) return undefined;\n  return call;\n}\n\n/**\n * If `genCall` is the first argument to `Layer.unwrapEffect(...)`, return\n * that enclosing call so generator analysis can preserve explicit layer semantics.\n */\nfunction findOuterLayerUnwrapOnGen(genCall: CallExpression): CallExpression | undefined {\n  const { SyntaxKind } = loadTsMorph();\n  const parent = genCall.getParent();\n  if (parent?.getKind() !== SyntaxKind.CallExpression) return undefined;\n  const outer = parent as CallExpression;\n  if ((outer.getArguments()[0] ?? undefined) !== genCall) return undefined;\n  const callee = outer.getExpression().getText();\n  if (callee === 'Layer.unwrapEffect') return outer;\n  return undefined;\n}\n\n/**\n * Apply each transformation of an outer `.pipe(...)` call to the accumulated\n * child nodes from a gen body. Known Effect-level wrappers (retry, timeout,\n * catch, catchTag, orElse*, mapError, tap, tapError, ensuring, withSpan)\n * produce corresponding IR nodes and bump the relevant stats.\n *\n * This is a targeted implementation that covers the transformations people\n * most commonly attach to a gen program. Unrecognized transforms are analyzed\n * individually and appended so nothing is silently dropped.\n */\nconst applyOuterPipeTransformsToGen = (\n  genChildren: readonly StaticFlowNode[],\n  pipeCall: CallExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<readonly StaticFlowNode[], AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const transformArgs = pipeCall.getArguments();\n\n    // Build a synthetic \"generator\" wrapper so transforms have a coherent source.\n    const wrapChildren = (\n      children: readonly StaticFlowNode[],\n    ): StaticFlowNode => {\n      if (children.length === 1 && children[0]) return children[0];\n      const gen: StaticGeneratorNode = {\n        id: generateId(),\n        type: 'generator',\n        yields: children.map((c) => ({ effect: c })),\n      };\n      return {\n        ...gen,\n        displayName: computeDisplayName(gen),\n        semanticRole: computeSemanticRole(gen),\n      };\n    };\n\n    let current: readonly StaticFlowNode[] = genChildren;\n\n    for (const arg of transformArgs) {\n      if (arg.getKind() !== SyntaxKind.CallExpression) continue;\n      const argCall = arg as CallExpression;\n      const argExpr = argCall.getExpression();\n      const argExprText = argExpr.getText();\n      const text = arg.getText().trim();\n      const argArgs = argCall.getArguments();\n      const location = extractLocation(\n        argCall,\n        filePath,\n        opts.includeLocations ?? false,\n      );\n\n      // Effect.retry(schedule)\n      if (/^Effect\\.retry\\s*\\(/.test(text)) {\n        const source = wrapChildren(current);\n        const scheduleArg = argArgs[0];\n        const schedule = scheduleArg?.getText();\n        const scheduleNode = scheduleArg\n          ? yield* analyzeEffectExpression(\n              scheduleArg,\n              sourceFile,\n              filePath,\n              opts,\n              warnings,\n              stats,\n            )\n          : undefined;\n        stats.retryCount++;\n        const retryNode: StaticRetryNode = {\n          id: generateId(),\n          type: 'retry',\n          source,\n          ...(schedule ? { schedule } : {}),\n          ...(scheduleNode ? { scheduleNode } : {}),\n          hasFallback: false,\n          retryEdgeLabel: schedule ? `retry: ${schedule}` : 'retry',\n          location,\n        };\n        current = [\n          {\n            ...retryNode,\n            displayName: computeDisplayName(retryNode),\n            semanticRole: computeSemanticRole(retryNode),\n          },\n        ];\n        continue;\n      }\n\n      // Fallback: analyze the arg as an ordinary effect expression so it\n      // appears in the IR and stats (e.g., Effect.timeout, Effect.catch,\n      // Effect.withSpan). We append rather than wrap — the structural\n      // semantics of each wrapper is specialized above only where needed.\n      const analyzed = yield* analyzeEffectCall(\n        argCall,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n      // Suppress purely annotative transforms (withSpan) from visible output\n      if (\n        argExprText === 'Effect.withSpan' ||\n        argExprText.endsWith('.withSpan')\n      ) {\n        continue;\n      }\n      current = [...current, analyzed];\n    }\n\n    return current;\n  });\n\nexport function analyzeRunEntrypointExpression(\n  call: CallExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<Option.Option<readonly StaticFlowNode[]>, AnalysisError> {\n  const calleeExpr = call.getExpression();\n  const calleeText = calleeExpr.getText();\n  const isPipeCall = calleeText.endsWith('.pipe') || calleeText === 'pipe';\n  if (!isPipeCall) return Effect.succeed(Option.none());\n  const args = call.getArguments();\n  const lastArg = args[args.length - 1];\n  if (!lastArg) return Effect.succeed(Option.none());\n  const lastArgText = lastArg.getText();\n  const isRunTerminated =\n    lastArgText.includes('.runMain') ||\n    lastArgText.includes('.runPromise') ||\n    lastArgText.includes('.runSync') ||\n    lastArgText.includes('.runFork');\n  if (!isRunTerminated) return Effect.succeed(Option.none());\n  return Effect.map(\n    analyzePipeChain(call, sourceFile, filePath, opts, warnings, stats),\n    (nodes) => Option.some(nodes),\n  );\n}\n","/**\n * Effect expression analysis: pipe chains, effect calls, and domain-specific analyzers.\n */\n\nimport { Effect, Option } from 'effect';\nimport type {\n  SourceFile,\n  Node,\n  CallExpression,\n  ArrowFunction,\n  FunctionExpression,\n  Block,\n  ReturnStatement,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n  PropertyAccessExpression,\n  ExpressionStatement,\n  Identifier,\n  ArrayLiteralExpression,\n  TaggedTemplateExpression,\n  NewExpression,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type { AnalysisError, AnalyzerOptions, AnalysisWarning, AnalysisStats } from './types';\nimport type {\n  StaticFlowNode,\n  StaticEffectNode,\n  StaticPipeNode,\n  StaticErrorHandlerNode,\n  StaticLayerNode,\n  StaticStreamNode,\n  StaticFiberNode,\n  StaticUnknownNode,\n  LayerLifecycle,\n  EffectTypeSignature,\n} from './types';\nimport { getStaticChildren } from './types';\nimport {\n  extractEffectTypeSignature,\n  extractServiceRequirements,\n  extractLayerTypeSignature,\n} from './type-extractor';\nimport {\n  generateId,\n  extractLocation,\n  extractJSDocDescription,\n  extractJSDocTags,\n  computeDisplayName,\n  computeSemanticRole,\n  unwrapExpression,\n} from './analysis-utils';\nimport {\n  ERROR_HANDLER_PATTERNS,\n  CONDITIONAL_PATTERNS,\n  COLLECTION_PATTERNS,\n  FIBER_PATTERNS,\n  INTERRUPTION_PATTERNS,\n  isTransformCall,\n  isMatchCall,\n  isCauseCall,\n  isExitCall,\n  isScheduleCall,\n  getSemanticDescriptionWithAliases,\n  parseServiceIdsFromContextType,\n  BUILT_IN_TYPE_NAMES,\n  KNOWN_EFFECT_NAMESPACES,\n} from './analysis-patterns';\nimport {\n  getAliasesForFile,\n  isEffectCallee,\n  isEffectLikeCallExpression,\n  normalizeEffectCallee,\n} from './alias-resolution';\nimport {\n  buildCallbackSummaryNodes,\n  summarizeNamedCallbackHandlers,\n} from './callback-summary';\nimport { resolveIdentifierToLayerInitializer } from './layer-initializer-resolution';\nimport {\n  isEffectRuntimePrimitive,\n  isLikelyServiceStreamProperty,\n  tryResolveServicePropertyAccess,\n  classifyUseCallbackKind,\n} from './service-type-heuristics';\nimport {\n  bindAnalysisContext,\n  createAnalysisContext,\n} from './analysis-context';\nimport {\n  analyzeStreamCall as _analyzeStreamCall,\n  analyzeChannelCall as _analyzeChannelCall,\n  analyzeSinkCall as _analyzeSinkCall,\n} from './stream-channel-sink-analyzers';\nimport {\n  analyzeRetryCall as _analyzeRetryCall,\n  analyzeTimeoutCall as _analyzeTimeoutCall,\n  analyzeScheduleCall,\n} from './retry-timeout-analyzers';\nimport {\n  analyzeConcurrencyPrimitiveCall,\n  analyzeFiberCall as _analyzeFiberCall,\n  analyzeInterruptionCall as _analyzeInterruptionCall,\n} from './concurrency-fiber-analyzers';\nimport {\n  analyzeParallelCall as _analyzeParallelCall,\n  analyzeRaceCall as _analyzeRaceCall,\n} from './parallel-race-analyzers';\nimport { analyzeErrorHandlerCall as _analyzeErrorHandlerCall, classifyErrorHandlerName } from './error-handler-analyzer';\nimport { analyzeResourceCall as _analyzeResourceCall } from './resource-analyzer';\nimport {\n  analyzeConditionalCall as _analyzeConditionalCall,\n  analyzeLoopCall as _analyzeLoopCall,\n  analyzeMatchCall,\n  analyzeCauseCall as _analyzeCauseCall,\n  analyzeExitCall,\n  analyzeTransformCall as _analyzeTransformCall,\n} from './control-flow-analyzers';\n\n/**\n * Deferred reference to `analyzeEffectExpression` used by extracted analyzers\n * (stream/channel/sink) that need to recurse. The getter resolves at call time,\n * which is after the module's top-level evaluation, so the export is in scope.\n */\nconst analysisContext = createAnalysisContext(() => analyzeEffectExpression);\n\nconst analyzeStreamCall = bindAnalysisContext(analysisContext, _analyzeStreamCall);\nconst analyzeChannelCall = bindAnalysisContext(analysisContext, _analyzeChannelCall);\nconst analyzeSinkCall = bindAnalysisContext(analysisContext, _analyzeSinkCall);\nconst analyzeRetryCall = bindAnalysisContext(analysisContext, _analyzeRetryCall);\nconst analyzeTimeoutCall = bindAnalysisContext(analysisContext, _analyzeTimeoutCall);\nconst analyzeFiberCall = bindAnalysisContext(analysisContext, _analyzeFiberCall);\nconst analyzeInterruptionCall = bindAnalysisContext(analysisContext, _analyzeInterruptionCall);\nconst analyzeParallelCall = bindAnalysisContext(analysisContext, _analyzeParallelCall);\nconst analyzeRaceCall = bindAnalysisContext(analysisContext, _analyzeRaceCall);\nconst analyzeErrorHandlerCall = bindAnalysisContext(analysisContext, _analyzeErrorHandlerCall);\nconst analyzeResourceCall = bindAnalysisContext(analysisContext, _analyzeResourceCall);\nconst analyzeConditionalCall = bindAnalysisContext(analysisContext, _analyzeConditionalCall);\nconst analyzeLoopCall = bindAnalysisContext(analysisContext, _analyzeLoopCall);\nconst analyzeCauseCall = bindAnalysisContext(analysisContext, _analyzeCauseCall);\nconst analyzeTransformCall = bindAnalysisContext(analysisContext, _analyzeTransformCall);\n\n// Schema decode/encode operations are NOT collection operations.\nconst SCHEMA_OPS = [\n  'Schema.decode',\n  'Schema.decodeUnknown',\n  'Schema.encode',\n  'Schema.validate',\n  'Schema.decodeOption',\n  'Schema.decodeEither',\n  'Schema.encodeUnknown',\n  'Schema.decodeSync',\n  'Schema.encodeSync',\n  'Schema.decodeUnknownSync',\n  'Schema.decodeUnknownOption',\n  'Schema.decodeUnknownEither',\n  'Schema.decodePromise',\n  'Schema.encodePromise',\n  'Schema.decodeUnknownPromise',\n];\n\n\n/**\n * Heuristic: does this `.pipe(...)` call apply Effect-level operations?\n *\n * Used to route pipe calls whose base is not literally `Effect.*` but whose\n * transformations are (e.g. `service.doThing().pipe(Effect.retry(...))`).\n * Matches the textual prefix of each arg against the Effect module's common\n * combinators — cheap, no type-checker needed.\n */\nconst EFFECT_PIPE_OP_REGEX =\n  /^Effect\\.(retry|retryOrElse|retryN|timeout(?:Fail|FailCause|Option|To)?|catch\\w*|orElse|orElseSucceed|orElseFail|orElseFailWith|orDie|orDieWith|ignore|ignoreLogged|sandbox|unsandbox|flip|tap|tapBoth|tapDefect|tapError|tapErrorCause|tapErrorTag|mapError|mapBoth|withSpan|annotateLogs|annotateSpans|ensuring|ensuringWith|delay|repeat|repeatN|repeatOrElse|zip|zipLeft|zipRight|matchEffect|match)\\s*(?:\\(|$)/;\n\nconst pipeArgsIncludeEffectOp = (call: CallExpression): boolean => {\n  for (const arg of call.getArguments()) {\n    if (EFFECT_PIPE_OP_REGEX.test(arg.getText())) return true;\n  }\n  return false;\n};\n\n/**\n * `Effect.orDie` and `Effect.ignore` are unary, so a pipe passes them uncalled\n * and the call-based handler analyzer never sees them.\n */\nconst asErrorHandler = (\n  analyzed: StaticFlowNode,\n  arg: Node,\n  stats: AnalysisStats,\n): StaticFlowNode => {\n  if (analyzed.type !== 'effect') return analyzed;\n  if (arg.getKind() === loadTsMorph().SyntaxKind.CallExpression) return analyzed;\n  const text = arg.getText();\n  if (!ERROR_HANDLER_PATTERNS.some((pattern) => text.includes(pattern))) {\n    return analyzed;\n  }\n  const handlerType = classifyErrorHandlerName(text);\n  stats.errorHandlerCount++;\n  const node: StaticErrorHandlerNode = {\n    id: generateId(),\n    type: 'error-handler',\n    handlerType,\n    // Uncalled combinator: the effect it applies to is the pipe's own base,\n    // which `walkPropagation` already has in hand when it reaches this node.\n    source: { id: generateId(), type: 'effect', callee: text },\n    ...(analyzed.location ? { location: analyzed.location } : {}),\n  };\n  return {\n    ...node,\n    displayName: computeDisplayName(node),\n    semanticRole: computeSemanticRole(node),\n  };\n};\n\nexport const analyzePipeChain = (\n  node: CallExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  serviceScope?: Map<string, string>,\n): Effect.Effect<readonly StaticFlowNode[], AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const args = node.getArguments();\n    const expr = node.getExpression();\n    const isMethodPipe =\n      expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n      (expr as PropertyAccessExpression).getName() === 'pipe';\n    const baseExpr = isMethodPipe\n      ? (expr as PropertyAccessExpression).getExpression()\n      : args[0];\n    const transformArgs = isMethodPipe ? args : args.slice(1);\n    if (!baseExpr) return [];\n\n    // GAP: pipe-chain when base is a variable — resolve to Layer initializer (same- or cross-file)\n    const baseNode = resolveIdentifierToLayerInitializer(baseExpr);\n    let baseSourceFile = baseNode.getSourceFile();\n    const basePath = baseSourceFile.getFilePath();\n    const project = sourceFile.getProject();\n    // Ensure the resolved file is in the project so alias resolution (e.g. L→Layer) works\n    if (!project.getSourceFile(basePath)) {\n      const added = project.addSourceFileAtPath(basePath);\n      if (added) baseSourceFile = added;\n    } else {\n      const inProject = project.getSourceFile(basePath);\n      if (inProject) baseSourceFile = inProject;\n    }\n    const initial = yield* analyzeEffectExpression(\n      baseNode,\n      baseSourceFile,\n      baseSourceFile.getFilePath(),\n      opts,\n      warnings,\n      stats,\n      serviceScope,\n    );\n\n    const transformations: StaticFlowNode[] = [];\n    for (const arg of transformArgs) {\n      if (arg) {\n        const analyzed = yield* analyzeEffectExpression(\n          arg,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n          serviceScope,\n        );\n        transformations.push(asErrorHandler(analyzed, arg, stats));\n      }\n    }\n\n    // Detect Effect.withSpan in transformations and merge as annotation\n    const sourceOrderedSpanNames: string[] = [];\n    let spanNameDynamic = false;\n    const filteredTransformations = transformations.filter((t) => {\n      if (t.type === 'effect' && t.callee.includes('withSpan')) {\n        return false; // Remove withSpan from transformations list\n      }\n      return true;\n    });\n\n    // Extract span name from the AST transform arguments\n    for (const arg of transformArgs) {\n      if (arg) {\n        const argText = arg.getText();\n        if (argText.includes('withSpan')) {\n          const match = /withSpan\\s*\\(\\s*[\"']([^\"']+)[\"']/.exec(argText);\n          if (match?.[1]) {\n            sourceOrderedSpanNames.push(match[1]);\n          } else {\n            spanNameDynamic = true;\n          }\n        }\n      }\n    }\n    const spanNames = [...sourceOrderedSpanNames].reverse();\n    const spanName = spanNames.at(-1);\n\n    // Extract type flow through pipe chain\n    let typeFlow: EffectTypeSignature[] | undefined;\n    yield* Effect.try(() => {\n      const typeChecker = sourceFile.getProject().getTypeChecker();\n      const flow: EffectTypeSignature[] = [];\n      // Extract initial type\n      const initialSig = extractEffectTypeSignature(baseExpr, typeChecker);\n      if (initialSig) flow.push(initialSig);\n      // Extract type at each transform step\n      for (const argNode of transformArgs) {\n        if (argNode) {\n          const sig = extractEffectTypeSignature(argNode, typeChecker);\n          if (sig) flow.push(sig);\n        }\n      }\n      if (flow.length > 0) typeFlow = flow;\n      // Type extraction can fail; leaving typeFlow unset is the fallback.\n    }).pipe(Effect.ignore);\n\n    // A pipe whose only transforms were annotations (Effect.withSpan) adds no\n    // step of its own. Emitting a \"Pipe (0 steps)\" node between every real call\n    // buries the flow; collapse to the base effect and carry the span across.\n    if (filteredTransformations.length === 0) {\n      // Chained annotation pipes stack: `x.pipe(withSpan('inner')).pipe(\n      // withSpan('outer'))` collapses twice onto the same base, so the names\n      // already on it are the inner ones. Concatenating keeps `spanNames`\n      // outermost-first, which is the order `indexIR` builds span paths in;\n      // overwriting would drop the inner span and lose the trace match.\n      const innerSpanNames =\n        initial.spanNames ?? (initial.spanName ? [initial.spanName] : []);\n      const mergedSpanNames = [...spanNames, ...innerSpanNames];\n      const innermost = mergedSpanNames.at(-1);\n      return [{\n        ...initial,\n        ...(innermost ? { spanName: innermost } : {}),\n        ...(mergedSpanNames.length > 0 ? { spanNames: mergedSpanNames } : {}),\n        ...(spanNameDynamic || initial.spanNameDynamic\n          ? { spanNameDynamic: true }\n          : {}),\n      }];\n    }\n\n    const pipeNode: StaticPipeNode = {\n      id: generateId(),\n      type: 'pipe',\n      initial,\n      transformations: filteredTransformations,\n      ...(typeFlow ? { typeFlow } : {}),\n      ...(spanName ? { spanName } : {}),\n      ...(spanNames.length > 0 ? { spanNames } : {}),\n      ...(spanNameDynamic ? { spanNameDynamic: true } : {}),\n    };\n    const enrichedPipeNode: StaticPipeNode = {\n      ...pipeNode,\n      displayName: computeDisplayName(pipeNode),\n      semanticRole: computeSemanticRole(pipeNode),\n    };\n\n    return [enrichedPipeNode];\n  });\n\n// =============================================================================\n// Effect Expression Analysis\n// =============================================================================\n\nexport const analyzeEffectExpression = (\n  node: Node,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  serviceScope?: Map<string, string>,\n): Effect.Effect<StaticFlowNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n\n    /**\n     * A type assertion is not a program. Look through `as`, `satisfies`, `!`,\n     * `<T>` and parentheses before deciding what this expression is, or the\n     * walker stops at the wrapper and reports an unknown node.\n     *\n     * Auditing Effect's own source found this was the analyzer's single\n     * largest resolution gap: 108 of the 141 nodes in the `Could not determine\n     * effect type` bucket were `AsExpression`.\n     */\n    node = unwrapExpression(node);\n\n    // Handle function wrappers that return an Effect (common in workflow APIs)\n    if (\n      node.getKind() === SyntaxKind.ArrowFunction ||\n      node.getKind() === SyntaxKind.FunctionExpression\n    ) {\n      const fnNode = node as ArrowFunction | FunctionExpression;\n      const body = fnNode.getBody();\n\n      if (!body) {\n        const unknownNode: StaticUnknownNode = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Function has no body',\n          sourceCode: node.getText().slice(0, 100),\n          location: extractLocation(\n            node,\n            filePath,\n            opts.includeLocations ?? false,\n          ),\n        };\n        stats.unknownCount++;\n        return unknownNode;\n      }\n\n      if (body.getKind() === SyntaxKind.Block) {\n        const statements = (\n          body as Block\n        ).getStatements();\n        const returnStmt = statements.find(\n          (stmt) => stmt.getKind() === SyntaxKind.ReturnStatement,\n        ) as ReturnStatement | undefined;\n\n        const returnedExpr = returnStmt?.getExpression();\n        if (returnedExpr) {\n          return yield* analyzeEffectExpression(\n            returnedExpr,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n            serviceScope,\n          );\n        }\n      } else {\n        return yield* analyzeEffectExpression(\n          body,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n          serviceScope,\n        );\n      }\n\n      const opaqueNode = {\n        id: generateId(),\n        type: 'opaque' as const,\n        reason: 'Function body is a non-Effect callback',\n        sourceText: node.getText().slice(0, 100),\n        location: extractLocation(node, filePath, opts.includeLocations ?? false),\n      };\n      return opaqueNode;\n    }\n\n    // Handle call expressions\n    if (node.getKind() === SyntaxKind.CallExpression) {\n      return yield* analyzeEffectCall(\n        node as CallExpression,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n        serviceScope,\n      );\n    }\n\n    // Handle property access chains (Effect.succeed(...))\n    if (node.getKind() === SyntaxKind.PropertyAccessExpression) {\n      const text = node.getText();\n      // Fiber.roots / Fiber.getCurrentFiber — property access that yields an Effect (GAP 5)\n      if (text === 'Fiber.roots' || text === 'Fiber.getCurrentFiber') {\n        const operation: StaticFiberNode['operation'] =\n          text === 'Fiber.roots' ? 'roots' : 'getCurrentFiber';\n        return {\n          id: generateId(),\n          type: 'fiber',\n          operation,\n          isScoped: false,\n          isDaemon: false,\n          location: extractLocation(\n            node,\n            filePath,\n            opts.includeLocations ?? false,\n          ),\n        };\n      }\n      const objectText = (node as PropertyAccessExpression).getExpression().getText();\n      const propertyName = (node as PropertyAccessExpression).getName();\n      const serviceId = serviceScope?.get(objectText);\n      if (serviceId) {\n        const serviceEffectNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee: text,\n          description: 'service-call',\n          requiredServices: [\n            {\n              serviceId,\n              serviceType: serviceId,\n              requiredAt: extractLocation(\n                node,\n                filePath,\n                opts.includeLocations ?? false,\n              ) ?? {\n                filePath,\n                line: 1,\n                column: 0,\n              },\n            },\n          ],\n          serviceCall: {\n            serviceType: serviceId,\n            methodName: propertyName,\n            objectName: objectText,\n          },\n          location: extractLocation(\n            node,\n            filePath,\n            opts.includeLocations ?? false,\n          ),\n        };\n        stats.totalEffects++;\n        if (isLikelyServiceStreamProperty(propertyName)) {\n          const streamNode: StaticStreamNode = {\n            id: generateId(),\n            type: 'stream',\n            source: {\n              ...serviceEffectNode,\n              displayName: computeDisplayName(serviceEffectNode),\n              semanticRole: computeSemanticRole(serviceEffectNode),\n            },\n            pipeline: [],\n            constructorType: 'other',\n            location: extractLocation(\n              node,\n              filePath,\n              opts.includeLocations ?? false,\n            ),\n          };\n          return {\n            ...streamNode,\n            displayName: computeDisplayName(streamNode),\n            semanticRole: computeSemanticRole(streamNode),\n          };\n        }\n        return {\n          ...serviceEffectNode,\n          displayName: computeDisplayName(serviceEffectNode),\n          semanticRole: computeSemanticRole(serviceEffectNode),\n        };\n      }\n\n      const inferredServiceCall = tryResolveServicePropertyAccess(\n        node as PropertyAccessExpression,\n      );\n      if (inferredServiceCall) {\n        const serviceEffectNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee: text,\n          description: 'service-call',\n          requiredServices: [\n            {\n              serviceId: inferredServiceCall.serviceType,\n              serviceType: inferredServiceCall.serviceType,\n              requiredAt: extractLocation(\n                node,\n                filePath,\n                opts.includeLocations ?? false,\n              ) ?? {\n                filePath,\n                line: 1,\n                column: 0,\n              },\n            },\n          ],\n          serviceCall: inferredServiceCall,\n          serviceMethod: {\n            serviceId: inferredServiceCall.serviceType,\n            methodName: inferredServiceCall.methodName,\n          },\n          location: extractLocation(\n            node,\n            filePath,\n            opts.includeLocations ?? false,\n          ),\n        };\n        stats.totalEffects++;\n        if (isLikelyServiceStreamProperty(propertyName)) {\n          const streamNode: StaticStreamNode = {\n            id: generateId(),\n            type: 'stream',\n            source: {\n              ...serviceEffectNode,\n              displayName: computeDisplayName(serviceEffectNode),\n              semanticRole: computeSemanticRole(serviceEffectNode),\n            },\n            pipeline: [],\n            constructorType: 'other',\n            location: extractLocation(\n              node,\n              filePath,\n              opts.includeLocations ?? false,\n            ),\n          };\n          return {\n            ...streamNode,\n            displayName: computeDisplayName(streamNode),\n            semanticRole: computeSemanticRole(streamNode),\n          };\n        }\n        return {\n          ...serviceEffectNode,\n          displayName: computeDisplayName(serviceEffectNode),\n          semanticRole: computeSemanticRole(serviceEffectNode),\n        };\n      }\n\n      if (isEffectCallee(text, getAliasesForFile(sourceFile), sourceFile)) {\n        const effectNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee: normalizeEffectCallee(text, sourceFile),\n          location: extractLocation(\n            node,\n            filePath,\n            opts.includeLocations ?? false,\n          ),\n        };\n        stats.totalEffects++;\n        return effectNode;\n      }\n    }\n\n    // Handle identifier references\n    if (node.getKind() === SyntaxKind.Identifier) {\n      const effectNode: StaticEffectNode = {\n        id: generateId(),\n        type: 'effect',\n        callee: node.getText(),\n        location: extractLocation(\n          node,\n          filePath,\n          opts.includeLocations ?? false,\n        ),\n      };\n      stats.totalEffects++;\n      return effectNode;\n    }\n\n    // Handle object literal with known Effect handler properties (match-style APIs)\n    if (node.getKind() === SyntaxKind.ObjectLiteralExpression) {\n      const objLit = node as ObjectLiteralExpression;\n      const HANDLER_PROPS = new Set(['onNone', 'onSome', 'onFailure', 'onSuccess', 'onLeft', 'onRight']);\n      const props = objLit.getProperties();\n      const handlerEntries: StaticFlowNode[] = [];\n      let hasKnownHandler = false;\n\n      for (const prop of props) {\n        if (prop.getKind() !== SyntaxKind.PropertyAssignment) continue;\n        const assignment = prop as PropertyAssignment;\n        const propName = assignment.getName();\n        if (!HANDLER_PROPS.has(propName)) continue;\n        hasKnownHandler = true;\n        const initializer = assignment.getInitializer();\n        if (initializer) {\n          const analyzed = yield* analyzeEffectExpression(\n            initializer,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n            serviceScope,\n          );\n          handlerEntries.push(analyzed);\n        }\n      }\n\n      if (hasKnownHandler && handlerEntries.length > 0) {\n        return handlerEntries.length === 1 ? handlerEntries[0]! : {\n          id: generateId(),\n          type: 'parallel',\n          callee: 'match-handlers',\n          mode: 'sequential' as const,\n          children: handlerEntries,\n          location: extractLocation(node, filePath, opts.includeLocations ?? false),\n        };\n      }\n    }\n\n    // Handle tagged template expressions (e.g. sql`CREATE TABLE...`)\n    // These are commonly used in Effect SQL clients and return Effects\n    if (node.getKind() === SyntaxKind.TaggedTemplateExpression) {\n      const taggedTemplate = node as TaggedTemplateExpression;\n      const tagText = taggedTemplate.getTag().getText();\n      const effectNode: StaticEffectNode = {\n        id: generateId(),\n        type: 'effect',\n        callee: tagText,\n        description: 'side-effect',\n        location: extractLocation(node, filePath, opts.includeLocations ?? false),\n      };\n      stats.totalEffects++;\n      return {\n        ...effectNode,\n        displayName: computeDisplayName(effectNode),\n        semanticRole: 'side-effect' as const,\n      };\n    }\n\n    // Handle yielded error instances: `yield* new SomeTaggedError(...)`\n    // Common in Effect codebases where TaggedError is yieldable.\n    if (node.getKind() === SyntaxKind.NewExpression) {\n      const newExpr = node as NewExpression;\n      const ctorText = newExpr.getExpression().getText();\n      const ctorName = ctorText.split('.').pop() ?? ctorText;\n      const typeText = newExpr.getType().getText();\n      const isErrorLike =\n        ctorName.endsWith(\"Error\") ||\n        typeText.includes('YieldableError') ||\n        typeText.includes('TaggedError');\n      if (isErrorLike) {\n        const effectNode: StaticEffectNode = {\n          id: generateId(),\n          type: 'effect',\n          callee: 'Effect.fail',\n          errorType: ctorName,\n          description: 'error-handling',\n          location: extractLocation(node, filePath, opts.includeLocations ?? false),\n        };\n        stats.totalEffects++;\n        return {\n          ...effectNode,\n          displayName: computeDisplayName(effectNode),\n          semanticRole: computeSemanticRole(effectNode),\n        };\n      }\n    }\n\n    // Default: unknown. Classify by node kind so the audit's \"unknown node\n    // reasons\" histogram is actionable instead of one opaque bucket. Most of\n    // these are non-Effect sub-expressions the walker reached in a position\n    // that isn't an Effect program (option objects, predicates, service impls).\n    const unknownReason = ((): string => {\n      switch (node.getKind()) {\n        case SyntaxKind.ObjectLiteralExpression:\n          return 'Non-Effect object literal (e.g. service impl or options argument)';\n        case SyntaxKind.BinaryExpression:\n        case SyntaxKind.PrefixUnaryExpression:\n          return 'Non-Effect predicate or boolean expression';\n        case SyntaxKind.NewExpression:\n          return 'Unrecognized constructor (not an error-like type)';\n        case SyntaxKind.PropertyAccessExpression:\n        case SyntaxKind.ElementAccessExpression:\n          return 'Unresolved property access (not tied back to an Effect)';\n        case SyntaxKind.Identifier:\n          return 'Unresolved identifier (not tied back to an Effect)';\n        case SyntaxKind.ConditionalExpression:\n          return 'Non-Effect conditional expression';\n        case SyntaxKind.ArrowFunction:\n        case SyntaxKind.FunctionExpression:\n          return 'Non-Effect function expression';\n        default:\n          return 'Could not determine effect type';\n      }\n    })();\n    const unknownNode: StaticUnknownNode = {\n      id: generateId(),\n      type: 'unknown',\n      reason: unknownReason,\n      sourceCode: node.getText().slice(0, 100),\n      location: extractLocation(node, filePath, opts.includeLocations ?? false),\n    };\n    stats.unknownCount++;\n    return unknownNode;\n  });\n\nexport const analyzeEffectCall = (\n  call: CallExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  serviceScope?: Map<string, string>,\n): Effect.Effect<StaticFlowNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    // Source text keeps the line breaks of a wrapped member chain\n    // (`deps\\n  .fetchRate`), which surfaces in every label as `deps .fetchRate`.\n    const callee = call.getExpression().getText().replace(/\\s*\\n\\s*/g, '');\n    const normalizedCallee = normalizeEffectCallee(callee, sourceFile);\n    const calleeOperation =\n      (/([A-Za-z_$][\\w$]*)$/.exec(normalizedCallee))?.[1] ?? normalizedCallee;\n    const location = extractLocation(\n      call,\n      filePath,\n      opts.includeLocations ?? false,\n    );\n\n    // pipe(base, ...fns) or <base>.pipe(...fns) inside generator → analyze as pipe chain so transformations (e.g. RcRef.update) are classified\n    // For method-style .pipe(), route Effect-based pipes, plus any pipe whose\n    // transformations include explicit Effect.* operations (e.g. retry, timeout, catch)\n    // on a non-Effect-prefixed base like `serviceCall().pipe(Effect.retry(...))`.\n    const isEffectMethodPipe =\n      callee.endsWith('.pipe') &&\n      callee !== 'pipe' &&\n      (callee.startsWith('Effect.') || pipeArgsIncludeEffectOp(call));\n    if (\n      (callee === 'pipe' || isEffectMethodPipe) &&\n      call.getArguments().length >= 1\n    ) {\n      const nodes = yield* analyzePipeChain(\n        call,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n        serviceScope,\n      );\n      if (nodes.length > 0 && nodes[0]) return nodes[0];\n    }\n\n    const isMethodPipe =\n      call.getExpression().getKind() === SyntaxKind.PropertyAccessExpression &&\n      (call.getExpression() as PropertyAccessExpression).getName() === 'pipe';\n    if (isMethodPipe) {\n      const baseExpr = (call.getExpression() as PropertyAccessExpression).getExpression();\n      const baseCallText =\n        baseExpr.getKind() === SyntaxKind.CallExpression\n          ? (baseExpr as CallExpression).getExpression().getText()\n          : '';\n      if (/\\blayerProtocol[A-Za-z0-9_]*$/.test(baseCallText)) {\n        const nodes = yield* analyzePipeChain(\n          call,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n          serviceScope,\n        );\n        if (nodes.length > 0 && nodes[0]) return nodes[0];\n      }\n      const baseText = baseExpr.getText();\n      const baseCallOrExprText = baseCallText || baseText;\n      if (baseText.startsWith('Stream.') || baseCallOrExprText.startsWith('Stream.')) {\n        return yield* analyzeStreamCall(\n          call,\n          'Stream.pipe',\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n          serviceScope,\n        );\n      }\n    }\n\n    // Context.pick / Context.omit are pure operations (not Effects) but are useful\n    // to preserve context-shaping steps inside Effect.gen bodies.\n    if (\n      normalizedCallee === 'Context.pick' ||\n      normalizedCallee === 'Context.omit'\n    ) {\n      const effectNode: StaticEffectNode = {\n        id: generateId(),\n        type: 'effect',\n        callee: normalizedCallee,\n        description: 'context',\n        location,\n      };\n      stats.totalEffects++;\n      return {\n        ...effectNode,\n        displayName: computeDisplayName(effectNode),\n        semanticRole: computeSemanticRole(effectNode),\n      };\n    }\n\n    if (normalizedCallee.startsWith('Layer.')) {\n      return yield* analyzeLayerCall(\n        call,\n        normalizedCallee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    // Protocol client factories often return layers that are then composed via Layer.provide(...)\n    // e.g. RpcClient.layerProtocolHttp(...).pipe(Layer.provide([...])).\n    if (/\\blayerProtocol[A-Za-z0-9_]*$/.test(normalizedCallee)) {\n      const layerNode: StaticLayerNode = {\n        id: generateId(),\n        type: 'layer',\n        name: normalizedCallee,\n        operations: [],\n        isMerged: false,\n        location,\n      };\n      return {\n        ...layerNode,\n        displayName: computeDisplayName(layerNode),\n        semanticRole: computeSemanticRole(layerNode),\n      };\n    }\n\n    if (normalizedCallee.startsWith('Stream.')) {\n      return yield* analyzeStreamCall(\n        call,\n        normalizedCallee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n        serviceScope,\n      );\n    }\n\n    if (normalizedCallee.startsWith('Channel.')) {\n      return yield* analyzeChannelCall(\n        call,\n        normalizedCallee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (callee.startsWith('Sink.')) {\n      return yield* analyzeSinkCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    const isConcurrencyPrimitiveCallee =\n      callee.startsWith('Queue.') ||\n      callee.startsWith('PubSub.') ||\n      callee.startsWith('Deferred.') ||\n      callee.startsWith('Semaphore.') ||\n      callee.startsWith('Mailbox.') ||\n      callee.startsWith('SubscriptionRef.') ||\n      callee.startsWith('RateLimiter.') ||\n      callee.startsWith('PartitionedSemaphore.') ||\n      callee.startsWith('FiberHandle.') ||\n      callee.startsWith('FiberSet.') ||\n      callee.startsWith('FiberMap.') ||\n      callee.startsWith('Cache.') ||\n      callee.startsWith('ScopedCache.') ||\n      callee.startsWith('RcRef.') ||\n      callee.includes('.RcRef.') ||\n      callee.startsWith('RcMap.') ||\n      callee.includes('.RcMap.') ||\n      callee.startsWith('Reloadable.') ||\n      callee.includes('.Reloadable.') ||\n      callee.includes('makeLatch') ||\n      callee.includes('Latch.');\n    if (isConcurrencyPrimitiveCallee) {\n      return yield* analyzeConcurrencyPrimitiveCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (FIBER_PATTERNS.some((p) => callee.includes(p) || callee.startsWith(p))) {\n      return yield* analyzeFiberCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (INTERRUPTION_PATTERNS.some((p) => callee.includes(p))) {\n      return yield* analyzeInterruptionCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    // Handle different Effect patterns\n    if (callee.includes('.all') || callee === 'all') {\n      return yield* analyzeParallelCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n        serviceScope,\n      );\n    }\n\n    if (callee.includes('.race') || callee === 'race') {\n      return yield* analyzeRaceCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (ERROR_HANDLER_PATTERNS.some((pattern) => callee.includes(pattern))) {\n      return yield* analyzeErrorHandlerCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (callee.includes('.retry')) {\n      return yield* analyzeRetryCall(\n        call,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (callee.includes('.timeout')) {\n      return yield* analyzeTimeoutCall(\n        call,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    const resourceOps = new Set([\n      'acquireRelease',\n      'acquireUseRelease',\n      'ensuring',\n      'addFinalizer',\n      'onExit',\n      'onError',\n      'parallelFinalizers',\n      'sequentialFinalizers',\n      'finalizersMask',\n      'using',\n      'withEarlyRelease',\n    ]);\n    const resourceOpPrefixes = ['acquireRelease', 'acquireUseRelease'] as const;\n    const isResourceOp = (op: string) =>\n      resourceOps.has(op) || resourceOpPrefixes.some((p) => op.startsWith(p));\n    if (calleeOperation === 'pipe' && call.getExpression().getKind() === SyntaxKind.PropertyAccessExpression) {\n      const propAccess = call.getExpression() as PropertyAccessExpression;\n      const baseExpr = propAccess.getExpression();\n      if (baseExpr.getKind() === SyntaxKind.CallExpression) {\n        const baseCall = baseExpr as CallExpression;\n        const baseCallee = baseCall.getExpression().getText();\n        const baseOperation = (/([A-Za-z_$][\\w$]*)$/.exec(baseCallee))?.[1] ?? baseCallee;\n        if (isResourceOp(baseOperation)) {\n          return yield* analyzeResourceCall(\n            baseCall,\n            baseOperation,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n        }\n      }\n    }\n    if (isResourceOp(calleeOperation)) {\n      return yield* analyzeResourceCall(\n        call,\n        calleeOperation,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    // Match CONDITIONAL_PATTERNS against the final method name, not the full callee text\n    const conditionalOp = `.${calleeOperation}`;\n    if (CONDITIONAL_PATTERNS.some((pattern) => conditionalOp === pattern || callee.endsWith(pattern))) {\n      return yield* analyzeConditionalCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    const isSchemaOp = SCHEMA_OPS.some((op) => callee.startsWith(op) || normalizedCallee.startsWith(op));\n\n    // Match COLLECTION_PATTERNS against the final method name (calleeOperation), not\n    // the full callee text which can contain arbitrary source code from curried functions.\n    const collectionOp = `.${calleeOperation}`;\n    if (!isSchemaOp && COLLECTION_PATTERNS.some((pattern) => collectionOp === pattern || callee.endsWith(pattern))) {\n      return yield* analyzeLoopCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (isTransformCall(callee)) {\n      return yield* analyzeTransformCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (isMatchCall(callee)) {\n      return analyzeMatchCall(call, callee, filePath, opts);\n    }\n\n    if (isCauseCall(callee)) {\n      return yield* analyzeCauseCall(\n        call,\n        callee,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (isExitCall(callee)) {\n      return analyzeExitCall(call, callee, filePath, opts);\n    }\n\n    if (isScheduleCall(callee)) {\n      return yield* analyzeScheduleCall(call, callee, filePath, opts);\n    }\n\n    // Default effect node\n    stats.totalEffects++;\n\n    // Effect.sync/promise/async callback body (one level only)\n    let callbackBody: readonly StaticFlowNode[] | undefined;\n    let usePattern: StaticEffectNode['usePattern'];\n    const CONSTRUCTOR_CALLBACK_CALLEES = [\n      'Effect.sync',\n      'Effect.promise',\n      'Effect.callback',\n      'Effect.asyncEffect',\n      'Effect.callback',\n      'Effect.tryPromise',\n      'Effect.suspend',\n    ];\n    const isConstructorWithCallback =\n      CONSTRUCTOR_CALLBACK_CALLEES.some((c) => callee.includes(c)) &&\n      call.getArguments().length > 0 &&\n      call.getArguments()[0];\n    let asyncCallback: StaticEffectNode['asyncCallback'];\n    if (isConstructorWithCallback) {\n      const firstArg = call.getArguments()[0]!;\n      const { SyntaxKind } = loadTsMorph();\n      const isFn =\n        firstArg.getKind() === SyntaxKind.ArrowFunction ||\n        firstArg.getKind() === SyntaxKind.FunctionExpression;\n      if (isFn) {\n        const fn = firstArg as\n          | ArrowFunction\n          | FunctionExpression;\n        const body = fn.getBody();\n        const innerNodes: StaticFlowNode[] = [];\n        if (body) {\n          if (body.getKind() === SyntaxKind.Block) {\n            const block = body as Block;\n            for (const stmt of block.getStatements()) {\n              if (stmt.getKind() === SyntaxKind.ReturnStatement) {\n                const retExpr = (stmt as ReturnStatement).getExpression();\n                if (retExpr && isEffectCallee(retExpr.getText(), getAliasesForFile(sourceFile), sourceFile)) {\n                  const analyzed = yield* analyzeEffectExpression(\n                    retExpr,\n                    sourceFile,\n                    filePath,\n                    opts,\n                    warnings,\n                    stats,\n                    undefined,\n                  );\n                  innerNodes.push(analyzed);\n                }\n              } else if (stmt.getKind() === SyntaxKind.ExpressionStatement) {\n                const expr = (stmt as ExpressionStatement).getExpression();\n                if (\n                  expr.getKind() === SyntaxKind.CallExpression &&\n                  isEffectLikeCallExpression(expr as CallExpression, sourceFile, getAliasesForFile(sourceFile), opts.knownEffectInternalsRoot)\n                ) {\n                  const analyzed = yield* analyzeEffectExpression(\n                    expr,\n                    sourceFile,\n                    filePath,\n                    opts,\n                    warnings,\n                    stats,\n                    undefined,\n                  );\n                  innerNodes.push(analyzed);\n                }\n              }\n            }\n          } else {\n            if (isEffectCallee(body.getText(), getAliasesForFile(sourceFile), sourceFile)) {\n              const analyzed = yield* analyzeEffectExpression(\n                body,\n                sourceFile,\n                filePath,\n                opts,\n                warnings,\n                stats,\n                undefined,\n              );\n              innerNodes.push(analyzed);\n            }\n          }\n        }\n        if (innerNodes.length > 0) callbackBody = innerNodes;\n\n        // Effect.callback/asyncEffect: resume/canceller patterns (GAP async callback interop)\n        if (\n          callee.includes('Effect.callback') ||\n          callee.includes('Effect.asyncEffect') ||\n          callee.includes('Effect.callback')\n        ) {\n          const resumeParamName =\n            fn.getParameters()[0]?.getName?.() ?? 'resume';\n          let resumeCallCount = 0;\n          const visit = (node: Node) => {\n            if (node.getKind() === SyntaxKind.CallExpression) {\n              const callNode = node as CallExpression;\n              const expr = callNode.getExpression();\n              if (\n                expr.getKind() === SyntaxKind.Identifier &&\n                (expr as Identifier).getText() === resumeParamName\n              ) {\n                resumeCallCount++;\n              }\n            }\n            node.getChildren().forEach(visit);\n          };\n          if (body) visit(body);\n          let returnsCanceller = false;\n          if (body?.getKind() === SyntaxKind.Block) {\n            const block = body as Block;\n            for (const stmt of block.getStatements()) {\n              if (stmt.getKind() === SyntaxKind.ReturnStatement) {\n                const retExpr = (stmt as ReturnStatement).getExpression();\n                if (retExpr) {\n                  const k = retExpr.getKind();\n                  if (\n                    k === SyntaxKind.ArrowFunction ||\n                    k === SyntaxKind.FunctionExpression\n                  ) {\n                    returnsCanceller = true;\n                    break;\n                  }\n                }\n              }\n            }\n          } else if (\n            body &&\n            (body.getKind() === SyntaxKind.ArrowFunction ||\n              body.getKind() === SyntaxKind.FunctionExpression)\n          ) {\n            returnsCanceller = true;\n          }\n          asyncCallback = {\n            resumeParamName,\n            resumeCallCount,\n            returnsCanceller,\n          };\n\n          if (callee.includes('Effect.callback')) {\n            const handlerSummaries = yield* summarizeNamedCallbackHandlers(\n              fn,\n              sourceFile,\n              filePath,\n              opts,\n              warnings,\n              stats,\n              resumeParamName,\n            );\n            if (handlerSummaries && handlerSummaries.length > 0) {\n              callbackBody = handlerSummaries;\n            }\n          }\n        }\n      }\n    }\n\n    if (call.getExpression().getKind() === SyntaxKind.PropertyAccessExpression) {\n      const propAccess = call.getExpression() as PropertyAccessExpression;\n      if (propAccess.getName() === 'use') {\n        const callbackArg = call.getArguments().find(\n          (arg) =>\n            arg.getKind() === SyntaxKind.ArrowFunction ||\n            arg.getKind() === SyntaxKind.FunctionExpression,\n        );\n        if (callbackArg) {\n          const callbackFn = callbackArg as ArrowFunction | FunctionExpression;\n          const callbackNodes = buildCallbackSummaryNodes(\n            callbackFn,\n            filePath,\n            opts.includeLocations ?? false,\n          );\n          if (callbackNodes) {\n            callbackBody = [...(callbackBody ?? []), ...callbackNodes];\n          }\n          const wrapperExpr = propAccess.getExpression().getText();\n          usePattern = {\n            wrapperName: serviceScope?.get(wrapperExpr) ?? wrapperExpr,\n            callbackKind: classifyUseCallbackKind(callbackFn),\n          };\n        }\n      }\n    }\n\n    // Extract JSDoc from the call statement\n    const effectJSDoc = extractJSDocDescription(call);\n\n    // Extract type signature and service requirements\n    const typeChecker = sourceFile.getProject().getTypeChecker();\n    const typeSignature = extractEffectTypeSignature(call, typeChecker);\n    const requiredServices = extractServiceRequirements(call, typeChecker);\n\n    // Try to identify service method calls\n    const serviceCall = tryResolveServiceCall(call, sourceFile);\n\n    // Resolve serviceMethod from generator scope or requiredServices fallback\n    let serviceMethod: StaticEffectNode['serviceMethod'];\n    const expr = call.getExpression();\n    if (expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n      const propAccess = expr as PropertyAccessExpression;\n      const objectText = propAccess.getExpression().getText();\n      const methodName = propAccess.getName();\n      if (serviceScope) {\n        const serviceId = serviceScope.get(objectText);\n        if (serviceId) serviceMethod = { serviceId, methodName };\n      }\n      if (!serviceMethod && requiredServices?.length === 1 && requiredServices[0]) {\n        serviceMethod = { serviceId: requiredServices[0].serviceId, methodName };\n      }\n    }\n\n    // Effect.provide: infer provideKind from context arg (GAP 6: Runtime vs Layer/Context)\n    // Two forms: Effect.provide(effect, layer) → 2 args, layer is args[1]; pipe(effect, Effect.provide(layer)) → 1 arg, layer is args[0]\n    let provideKind: StaticEffectNode['provideKind'];\n    if (\n      callee === 'Effect.provide' ||\n      (callee.startsWith('Effect.') && callee.includes('.provide') && !callee.includes('provideService'))\n    ) {\n      const args = call.getArguments();\n      const contextArgText = (args.length >= 2 ? args[1] : args[0])?.getText() ?? '';\n      if (\n        /Runtime\\.|defaultRuntime|\\.runSync|\\.runPromise|\\.runFork|\\.runCallback/.test(contextArgText) ||\n        /^\\s*runtime\\s*$|^\\s*rt\\s*$/i.test(contextArgText.trim())\n      ) {\n        provideKind = 'runtime';\n      } else if (contextArgText.includes('Layer.')) {\n        provideKind = 'layer';\n      } else {\n        provideKind = 'context';\n      }\n    }\n\n    // Determine constructorKind\n    let constructorKind: StaticEffectNode['constructorKind'];\n    if (callee.endsWith('.sync') || callee.endsWith('.succeed') || callee.endsWith('.fail') || callee.endsWith('.try') || callee.endsWith('.suspend')) constructorKind = 'sync';\n    else if (callee.endsWith('.promise')) constructorKind = 'promise';\n    else if (callee.endsWith('.async') || callee.endsWith('.asyncEffect')) constructorKind = 'async';\n    else if (callee.endsWith('.callback')) constructorKind = 'callback';\n    else if (callee.endsWith('.never')) constructorKind = 'never';\n    else if (callee.endsWith('.void')) constructorKind = 'void';\n    else if (callee.endsWith('.fromNullable')) constructorKind = 'fromNullable';\n    else if (callee.endsWith('.fn')) constructorKind = 'fn';\n    else if (callee.endsWith('.fnUntraced')) constructorKind = 'fnUntraced';\n\n    // Extract FiberRef built-in name\n    let fiberRefName: string | undefined;\n    const KNOWN_FIBER_REFS = ['currentConcurrency', 'currentLogLevel', 'currentScheduler', 'currentTracerEnabled', 'currentLogSpan', 'currentLogAnnotations', 'currentContext', 'currentRequestBatching', 'currentMaxOpsBeforeYield', 'currentSupervisor', 'currentMetricLabels', 'interruptedCause', 'unhandledLogLevel'] as const;\n    for (const refName of KNOWN_FIBER_REFS) {\n      if (callee.includes(refName)) { fiberRefName = refName; break; }\n    }\n\n    // Extract Effect.fn traced name\n    let tracedName: string | undefined;\n    if (constructorKind === 'fn' || constructorKind === 'fnUntraced') {\n      const args = call.getArguments();\n      if (args.length > 0) {\n        const firstArg = args[0]!.getText();\n        const strMatch = /^[\"'`](.+?)[\"'`]$/.exec(firstArg);\n        if (strMatch) tracedName = strMatch[1];\n      }\n    }\n\n    if (\n      constructorKind === undefined &&\n      call.getExpression().getKind() === loadTsMorph().SyntaxKind.CallExpression\n    ) {\n      const innerCall = call.getExpression() as CallExpression;\n      const innerCallee = innerCall.getExpression().getText();\n      if (innerCallee.endsWith('.fn') || innerCallee.endsWith('.fnUntraced')) {\n        constructorKind = innerCallee.endsWith('.fnUntraced') ? 'fnUntraced' : 'fn';\n        const fnArgs = innerCall.getArguments();\n        if (fnArgs.length > 0) {\n          const firstArg = fnArgs[0]!.getText();\n          const strMatch = /^[\"'`](.+?)[\"'`]$/.exec(firstArg);\n          if (strMatch) tracedName = strMatch[1];\n        }\n      }\n    }\n\n    const filteredRequiredServices = requiredServices?.filter(\n      (service) => !isEffectRuntimePrimitive(service.serviceId),\n    );\n\n    const effectNode: StaticEffectNode = {\n      id: generateId(),\n      type: 'effect',\n      callee: normalizedCallee,\n      description: usePattern\n        ? `use-pattern (${usePattern.callbackKind})`\n        : serviceCall || serviceMethod\n          ? 'service-call'\n          : getSemanticDescriptionWithAliases(normalizedCallee, getAliasesForFile(sourceFile)),\n      location,\n      jsdocDescription: effectJSDoc,\n      jsdocTags: extractJSDocTags(call),\n      typeSignature,\n      requiredServices: filteredRequiredServices,\n      serviceCall,\n      serviceMethod,\n      ...(usePattern ? { usePattern } : {}),\n      callbackBody,\n      ...(asyncCallback ? { asyncCallback } : {}),\n      ...(provideKind ? { provideKind } : {}),\n      ...(constructorKind ? { constructorKind } : {}),\n      ...(fiberRefName ? { fiberRefName } : {}),\n      ...(tracedName ? { tracedName } : {}),\n    };\n    const enrichedEffectNode: StaticEffectNode = {\n      ...effectNode,\n      displayName: computeDisplayName(effectNode),\n      semanticRole: computeSemanticRole(effectNode),\n    };\n    return enrichedEffectNode;\n  });\n\n/**\n * Try to resolve a service method call from a CallExpression.\n * Returns metadata if the callee is `obj.method()` where `obj` has a\n * known, non-built-in type — indicating a yielded service method call.\n */\nconst tryResolveServiceCall = (\n  call: CallExpression,\n  sourceFile: SourceFile,\n): StaticEffectNode['serviceCall'] => {\n  const { SyntaxKind } = loadTsMorph();\n  const expr = call.getExpression();\n\n  // Must be a property access (obj.method form)\n  if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) return undefined;\n\n  const propAccess = expr as PropertyAccessExpression;\n  const objExpr = propAccess.getExpression();\n  const methodName = propAccess.getName();\n  const objectName = objExpr.getText();\n\n  // Skip if first segment is a known Effect/JS namespace (resolve aliases first)\n  const firstSegment = objectName.split('.')[0] ?? objectName;\n  if (KNOWN_EFFECT_NAMESPACES.has(firstSegment)) return undefined;\n  // Resolve aliases: e.g. \"M\" -> \"Match\", \"S\" -> \"Schema\"\n  const normalized = normalizeEffectCallee(objectName, sourceFile);\n  const normalizedFirstSegment = normalized.split('.')[0] ?? normalized;\n  if (KNOWN_EFFECT_NAMESPACES.has(normalizedFirstSegment)) return undefined;\n\n  try {\n    const type = objExpr.getType();\n    const symbol = type.getSymbol() ?? type.getAliasSymbol();\n    if (!symbol) return undefined;\n\n    const typeName = symbol.getName();\n    // Skip anonymous structural types, built-ins, and error sentinels\n    if (\n      !typeName ||\n      typeName === '__type' ||\n      typeName === 'unknown' ||\n      typeName === 'any' ||\n      BUILT_IN_TYPE_NAMES.has(typeName)\n    ) {\n      return undefined;\n    }\n\n    return { serviceType: typeName, methodName, objectName };\n  } catch {\n    return undefined;\n  }\n};\n\n// =============================================================================\n// Specific Pattern Analysis\n// =============================================================================\n\n\nconst analyzeLayerCall = (\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticLayerNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    const operations: StaticFlowNode[] = [];\n    const { SyntaxKind } = loadTsMorph();\n\n    if (args.length > 0 && args[0]) {\n      const firstArg = args[0];\n      const isMergeAll =\n        callee.includes('mergeAll') &&\n        firstArg.getKind() === SyntaxKind.ArrayLiteralExpression;\n\n      if (isMergeAll) {\n        const elements = (\n          firstArg as ArrayLiteralExpression\n        ).getElements();\n        for (const elem of elements) {\n          const analyzed = yield* analyzeEffectExpression(\n            elem,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n          operations.push(analyzed);\n        }\n      } else {\n        for (const arg of args) {\n          if (!arg) continue;\n          const toAnalyze = resolveIdentifierToLayerInitializer(arg);\n          const argSourceFile = toAnalyze.getSourceFile();\n          const analyzed = yield* analyzeEffectExpression(\n            toAnalyze,\n            argSourceFile,\n            argSourceFile.getFilePath(),\n            opts,\n            warnings,\n            stats,\n          );\n          operations.push(analyzed);\n        }\n      }\n    }\n\n    const isMerged =\n      callee.includes('merge') || callee.includes('mergeAll');\n\n    let lifecycle: LayerLifecycle | undefined;\n    if (callee.includes('fresh')) lifecycle = 'fresh';\n    else if (callee.includes('memoize')) lifecycle = 'memoized';\n    else if (callee.includes('scoped')) lifecycle = 'scoped';\n    else lifecycle = 'default';\n\n    // Layer error-handling / utility ops — track as semantic description on the node\n    // These don't change the primitive provides/requires but are important to detect:\n    // catch, orDie, orElse, retry, tap, mapError, build, launch, toRuntime,\n    // passthrough, project, flatMap, flatten, annotateLogs, annotateSpans,\n    // setConfigProvider, setClock, setTracer, locally, withSpan\n\n    const provides: string[] = [];\n    // Helper: extract one or more tag names from an arg.\n    const extractTagNames = (node: Node): string[] => {\n      if (node.getKind() === SyntaxKind.ArrayLiteralExpression) {\n        const items = (node as ArrayLiteralExpression).getElements();\n        return items.flatMap((item) => extractTagNames(item));\n      }\n      if (node.getKind() === SyntaxKind.CallExpression) {\n        const callNode = node as CallExpression;\n        const callExpr = callNode.getExpression().getText();\n        if (callExpr.startsWith('Layer.') && callNode.getArguments().length > 0) {\n          const first = callNode.getArguments()[0];\n          if (first) return extractTagNames(first);\n        }\n      }\n      if (node.getKind() === SyntaxKind.Identifier) {\n        return [(node as Identifier).getText()];\n      }\n      if (node.getKind() === SyntaxKind.PropertyAccessExpression) {\n        // e.g. SomeService.Default → 'SomeService'\n        const pae = node as PropertyAccessExpression;\n        const obj = pae.getExpression();\n        if (obj.getKind() === SyntaxKind.Identifier) {\n          return [(obj as Identifier).getText()];\n        }\n        return [pae.getText().split('.')[0] ?? pae.getText()];\n      }\n      return [];\n    };\n\n    // Layer.succeed(Tag, value) / Layer.sync(Tag, fn) / Layer.effect(Tag, eff) / Layer.scoped(Tag, eff)\n    if (\n      (callee.includes('succeed') || callee.includes('sync') ||\n       callee.includes('effect') || callee.includes('scoped') ||\n       callee.includes('scopedDiscard') || callee.includes('effectDiscard')) &&\n      args.length > 0 && args[0]\n    ) {\n      provides.push(...extractTagNames(args[0]));\n    }\n    // Layer.provide / Layer.provideMerge — method call: outerLayer.pipe(Layer.provide(innerLayer))\n    // In this case, callee is Layer.provide or Layer.provideMerge\n    // The first arg is the layer being provided (i.e., the dependency)\n    const isProvideCall = callee.includes('provide') && !callee.includes('provideService');\n\n    const requiresSet = new Set<string>();\n    // If this is Layer.provide(dep) [1-arg curried], dep's tag is what we're injecting\n    if (isProvideCall && args.length >= 1 && args[0]) {\n      for (const depName of extractTagNames(args[0])) {\n        requiresSet.add(depName);\n      }\n    }\n    // If this is Layer.provide(base, dep) [2-arg], dep is injected into base\n    if (isProvideCall && args.length >= 2 && args[1]) {\n      for (const depName of extractTagNames(args[1])) {\n        requiresSet.add(depName);\n      }\n      // The provides of the composed layer come from base (args[0])\n      const baseArg = args[0];\n      if (baseArg) provides.push(...extractTagNames(baseArg));\n    }\n    // Layer.provideService(tag, value) — provides a service inline\n    if (callee.includes('provideService') && args.length > 0 && args[0]) {\n      provides.push(...extractTagNames(args[0]));\n    }\n    const collectRequires = (node: StaticFlowNode): void => {\n      if (node.type === 'effect') {\n        const eff = node;\n        for (const req of eff.requiredServices ?? []) {\n          requiresSet.add(req.serviceId);\n        }\n        const calleeText = eff.callee ?? '';\n        if (\n          /^[A-Z][A-Za-z0-9_]*(Service|Tag)$/.test(calleeText) ||\n          calleeText.endsWith('.Tag')\n        ) {\n          requiresSet.add(calleeText);\n        }\n      } else if (node.type === 'layer') {\n        const layer = node;\n        for (const r of layer.requires ?? []) {\n          requiresSet.add(r);\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      children.forEach(collectRequires);\n    };\n    operations.forEach(collectRequires);\n\n    // Fallback: Layer type RIn extraction when requires is empty (GAP Layer requires)\n    if (requiresSet.size === 0) {\n      // Type extraction can fail; an empty requires set is the fallback.\n      yield* Effect.try(() => {\n        const layerSig = extractLayerTypeSignature(call);\n        if (layerSig?.requiredType && layerSig.requiredType !== 'never') {\n          const ids = parseServiceIdsFromContextType(layerSig.requiredType);\n          ids.forEach((id) => requiresSet.add(id));\n        }\n      }).pipe(Effect.ignore);\n    }\n\n    // Extract a semantic name for utility Layer ops\n    const layerOpName = callee.replace(/^Layer\\./, '').replace(/^[a-zA-Z]+\\./, '');\n    const UTILITY_LAYER_OPS = new Set([\n      'catch', 'catchCause', 'orDie', 'orElse', 'retry', 'tap',\n      'mapError', 'mapErrorCause', 'build', 'launch', 'toRuntime',\n      'passthrough', 'project', 'flatMap', 'flatten', 'annotateLogs',\n      'annotateSpans', 'setConfigProvider', 'setClock', 'setTracer',\n      'locally', 'withSpan', 'withLogger', 'withTracer', 'withClock',\n      'mock', 'suspend', 'unwrapEffect', 'unwrapScoped',\n    ]);\n    let layerName = UTILITY_LAYER_OPS.has(layerOpName) ? `Layer.${layerOpName}` : undefined;\n    if (layerOpName === 'unwrapEffect' && operations.some((op) => op.type === 'generator')) {\n      layerName = 'Layer.unwrapEffect(gen)';\n    }\n\n    // GAP Layer.MemoMap: dedicated memo-map analysis\n    const isMemoMap =\n      callee.includes('MemoMap') ||\n      operations.some(\n        (op) => op.type === 'layer' && (op).isMemoMap === true,\n      );\n\n    const layerNode: StaticLayerNode = {\n      id: generateId(),\n      type: 'layer',\n      name: layerName,\n      operations,\n      isMerged,\n      provides: provides.length > 0 ? provides : undefined,\n      requires: requiresSet.size > 0 ? Array.from(requiresSet).sort() : undefined,\n      lifecycle,\n      ...(isMemoMap ? { isMemoMap: true } : {}),\n      location: extractLocation(\n        call,\n        filePath,\n        opts.includeLocations ?? false,\n      ),\n    };\n    return {\n      ...layerNode,\n      displayName: computeDisplayName(layerNode),\n      semanticRole: computeSemanticRole(layerNode),\n    };\n  });\n","/**\n * Callback body summarisation helpers.\n *\n * The static analyzer captures `Effect.callback`/`Effect.gen`/loop callbacks as\n * IR nodes, but their bodies are arbitrary JS. These helpers walk a callback\n * body and produce a compact, deduplicated summary of the calls /\n * conditionals inside it — used to render meaningful labels in diagrams and\n * keep the IR small.\n *\n * Extracted from effect-analysis.ts as part of the strangler-fig cleanup.\n * Behaviour is preserved exactly; only the module boundary moved.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  SourceFile,\n  Node,\n  CallExpression,\n  ArrowFunction,\n  FunctionExpression,\n  Block,\n  Identifier,\n  VariableStatement,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type { AnalysisError, AnalyzerOptions, AnalysisWarning, AnalysisStats } from './types';\nimport type {\n  StaticFlowNode,\n  StaticEffectNode,\n  StaticLoopNode,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\n\nconst compactCallbackCalleeLabel = (call: CallExpression): string => {\n  let expr: Node = call.getExpression();\n  const { SyntaxKind } = loadTsMorph();\n  while (expr.getKind() === SyntaxKind.CallExpression) {\n    expr = (expr as CallExpression).getExpression();\n  }\n  return expr.getText();\n};\n\nconst canonicalizeCallbackLabel = (label: string): string => {\n  const match = /^([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*)\\(/.exec(label);\n  return match?.[1] ?? label;\n};\n\nconst CALLBACK_NOISE_LABELS = new Set([\n  'Effect.sync',\n  'Effect.succeed',\n  'Effect.fail',\n  'sync',\n  'succeed',\n  'fail',\n  'tap',\n  'recurs',\n  'map',\n  'flatMap',\n]);\n\nconst shouldSkipCallbackSummaryLabel = (\n  label: string,\n  availableLabels: readonly string[],\n): boolean => {\n  if (!CALLBACK_NOISE_LABELS.has(label)) return false;\n  return availableLabels.some((candidate) => candidate !== label);\n};\n\nexport const summarizeLoopCallbackSource = (\n  loopType: StaticLoopNode['loopType'],\n  callbackBody: readonly StaticFlowNode[],\n): string => {\n  const labels = callbackBody.flatMap((node) => {\n    if (node.type === 'effect') {\n      return [canonicalizeCallbackLabel(node.callee)];\n    }\n    if (node.type === 'conditional') {\n      return [`if ${node.conditionLabel ?? node.condition}`];\n    }\n    return [];\n  });\n  const filtered = labels.filter((label, index) => {\n    if (labels.indexOf(label) !== index) return false;\n    return !shouldSkipCallbackSummaryLabel(label, labels);\n  });\n  if (filtered.length === 0) return 'callback body';\n  const joined = filtered.slice(0, 4).join(' -> ');\n  const suffix = filtered.length > 4 ? ' -> ...' : '';\n  return `${loopType} callback: ${joined}${suffix}`;\n};\n\nexport const buildCallbackSummaryNodes = (\n  fnNode: ArrowFunction | FunctionExpression,\n  filePath: string,\n  includeLocations: boolean,\n): readonly StaticFlowNode[] | undefined => {\n  const { SyntaxKind } = loadTsMorph();\n  const body = fnNode.getBody();\n  const calls: StaticFlowNode[] = [];\n  const seen = new Set<string>();\n\n  const collectFrom = (candidate: Node): void => {\n    if (candidate.getKind() === SyntaxKind.CallExpression) {\n      const call = candidate as CallExpression;\n      const callee = canonicalizeCallbackLabel(compactCallbackCalleeLabel(call));\n      if (seen.has(callee)) return;\n      seen.add(callee);\n      const callbackNode: StaticEffectNode = {\n        id: generateId(),\n        type: 'effect',\n        callee,\n        description: 'callback-call',\n        location: extractLocation(candidate, filePath, includeLocations),\n      };\n      calls.push({\n        ...callbackNode,\n        displayName: computeDisplayName(callbackNode),\n        semanticRole: computeSemanticRole(callbackNode),\n      });\n    }\n  };\n\n  if (body.getKind() === SyntaxKind.Block) {\n    for (const stmt of (body as Block).getStatements()) {\n      stmt.forEachDescendant((desc) => {\n        collectFrom(desc);\n        return undefined;\n      });\n    }\n  } else {\n    body.forEachDescendant((desc) => {\n      collectFrom(desc);\n      return undefined;\n    });\n    collectFrom(body);\n  }\n\n  const labels = calls.flatMap((node) => node.type === 'effect' ? [node.callee] : []);\n  const filtered = calls.filter((node) => {\n    if (node.type !== 'effect') return true;\n    return !shouldSkipCallbackSummaryLabel(node.callee, labels);\n  });\n\n  return filtered.length > 0 ? filtered : undefined;\n};\n\nconst isFunctionBoundaryForCallbackSummary = (node: Node): boolean => {\n  const { SyntaxKind } = loadTsMorph();\n  const kind = node.getKind();\n  return (\n    kind === SyntaxKind.FunctionDeclaration ||\n    kind === SyntaxKind.FunctionExpression ||\n    kind === SyntaxKind.ArrowFunction ||\n    kind === SyntaxKind.MethodDeclaration\n  );\n};\n\nconst summarizeResumePayloads = (\n  fnNode: ArrowFunction | FunctionExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  resumeParamName: string,\n): Effect.Effect<readonly StaticFlowNode[], AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const summaries: StaticFlowNode[] = [];\n    const seen = new Set<string>();\n    const body = fnNode.getBody();\n\n    const visit = (node: Node): void => {\n      if (node.getKind() === SyntaxKind.CallExpression) {\n        const call = node as CallExpression;\n        const expr = call.getExpression();\n        if (\n          expr.getKind() === SyntaxKind.Identifier &&\n          (expr as Identifier).getText() === resumeParamName\n        ) {\n          const payload = call.getArguments()[0];\n          if (payload) {\n            const payloadText = payload.getText();\n            const compactPayload =\n              payloadText.length > 48 ? `${payloadText.slice(0, 48)}...` : payloadText;\n            const key = compactPayload;\n            if (!seen.has(key)) {\n              seen.add(key);\n              summaries.push({\n                id: generateId(),\n                type: 'effect',\n                callee: `resume -> ${compactPayload}`,\n                description: 'callback-resume',\n                location: extractLocation(call, filePath, opts.includeLocations ?? false),\n              });\n            }\n          }\n        }\n      }\n      if (!isFunctionBoundaryForCallbackSummary(node)) {\n        node.forEachChild(visit);\n      }\n    };\n\n    if (body.getKind() === SyntaxKind.Block) {\n      for (const stmt of (body as Block).getStatements()) {\n        visit(stmt);\n      }\n    } else {\n      visit(body);\n    }\n\n    return summaries;\n  });\n\nconst filterHandlerSummaryNoise = (\n  nodes: readonly StaticFlowNode[],\n): readonly StaticFlowNode[] => {\n  const seenEffectLabels = new Set<string>();\n  return nodes.filter((node) => {\n    if (node.type !== 'effect') return true;\n    if (node.callee === 'resume') return false;\n    if (node.callee === 'fail') return false;\n    if (\n      node.callee === 'succeed' ||\n      node.callee === 'succeedSome' ||\n      node.callee === 'succeedNone' ||\n      node.callee === 'Effect.fail' ||\n      node.callee === 'Effect.succeed' ||\n      node.callee === 'Effect.succeedSome' ||\n      node.callee === 'Effect.succeedNone'\n    ) {\n      return false;\n    }\n    if (seenEffectLabels.has(node.callee)) return false;\n    seenEffectLabels.add(node.callee);\n    return true;\n  });\n};\n\nexport const summarizeNamedCallbackHandlers = (\n  fnNode: ArrowFunction | FunctionExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  resumeParamName: string,\n): Effect.Effect<readonly StaticFlowNode[] | undefined, AnalysisError> =>\n  Effect.gen(function* () {\n    const { SyntaxKind } = loadTsMorph();\n    const body = fnNode.getBody();\n    if (body.getKind() !== SyntaxKind.Block) return undefined;\n\n    const summaries: StaticFlowNode[] = [];\n    const block = body as Block;\n    for (const stmt of block.getStatements()) {\n      if (stmt.getKind() === SyntaxKind.VariableStatement) {\n        for (const decl of (stmt as VariableStatement).getDeclarations()) {\n          const init = decl.getInitializer();\n          if (\n            init &&\n            (init.getKind() === SyntaxKind.ArrowFunction ||\n              init.getKind() === SyntaxKind.FunctionExpression)\n          ) {\n            const handlerFn = init as ArrowFunction | FunctionExpression;\n            const callbackBody = [\n              ...(yield* summarizeResumePayloads(\n                handlerFn,\n                sourceFile,\n                filePath,\n                opts,\n                warnings,\n                stats,\n                resumeParamName,\n              )),\n              ...filterHandlerSummaryNoise(\n                buildPureCallbackSummaryNodes(\n                  handlerFn,\n                  filePath,\n                  opts.includeLocations ?? false,\n                ) ?? [],\n              ),\n            ];\n            if (callbackBody.length > 0) {\n              const handlerNode: StaticEffectNode = {\n                id: generateId(),\n                type: 'effect',\n                callee: decl.getName(),\n                description: 'callback-handler',\n                callbackBody,\n                location: extractLocation(decl, filePath, opts.includeLocations ?? false),\n              };\n              summaries.push({\n                ...handlerNode,\n                displayName: computeDisplayName(handlerNode),\n                semanticRole: computeSemanticRole(handlerNode),\n              });\n            }\n          }\n        }\n      }\n    }\n\n    return summaries.length > 0 ? summaries : undefined;\n  });\n\nexport const buildPureCallbackSummaryNodes = (\n  fnNode: ArrowFunction | FunctionExpression,\n  filePath: string,\n  includeLocations: boolean,\n): readonly StaticFlowNode[] | undefined => {\n  const { SyntaxKind } = loadTsMorph();\n  const body = fnNode.getBody();\n  const summaries: StaticFlowNode[] = [];\n  const seen = new Set<string>();\n\n  const addEffectSummary = (label: string, description = 'callback-transform'): void => {\n    const canonicalLabel = canonicalizeCallbackLabel(label);\n    if (seen.has(canonicalLabel)) return;\n    seen.add(canonicalLabel);\n    const node: StaticEffectNode = {\n      id: generateId(),\n      type: 'effect',\n      callee: canonicalLabel,\n      description,\n      location: extractLocation(body, filePath, includeLocations),\n    };\n    summaries.push({\n      ...node,\n      displayName: computeDisplayName(node),\n      semanticRole: computeSemanticRole(node),\n    });\n  };\n\n  const addConditionalSummary = (condition: string): void => {\n    if (seen.has(`if:${condition}`)) return;\n    seen.add(`if:${condition}`);\n    summaries.push({\n      id: generateId(),\n      type: 'conditional',\n      conditionalType: 'if',\n      condition,\n      conditionLabel: condition,\n      onTrue: {\n        id: generateId(),\n        type: 'opaque',\n        reason: 'callback-branch',\n        sourceText: condition,\n        location: extractLocation(body, filePath, includeLocations),\n      },\n      location: extractLocation(body, filePath, includeLocations),\n    });\n  };\n\n  const visit = (candidate: Node): void => {\n    if (candidate.getKind() === SyntaxKind.CallExpression) {\n      const call = candidate as CallExpression;\n      addEffectSummary(call.getExpression().getText(), 'callback-call');\n    } else if (candidate.getKind() === SyntaxKind.BinaryExpression) {\n      const text = candidate.getText();\n      if (\n        text.includes('===') ||\n        text.includes('!==') ||\n        text.includes('>') ||\n        text.includes('<') ||\n        text.includes('%') ||\n        text.includes('&&') ||\n        text.includes('||')\n      ) {\n        addConditionalSummary(text);\n      }\n    } else if (\n      candidate.getKind() === SyntaxKind.Identifier ||\n      candidate.getKind() === SyntaxKind.NumericLiteral ||\n      candidate.getKind() === SyntaxKind.StringLiteral ||\n      candidate.getKind() === SyntaxKind.TrueKeyword ||\n      candidate.getKind() === SyntaxKind.FalseKeyword\n    ) {\n      return;\n    }\n    candidate.forEachChild(visit);\n  };\n\n  if (body.getKind() === SyntaxKind.Block) {\n    for (const stmt of (body as Block).getStatements()) {\n      visit(stmt);\n    }\n  } else {\n    visit(body);\n    if (summaries.length === 0) {\n      addEffectSummary(body.getText(), 'callback-transform');\n    }\n  }\n\n  return summaries.length > 0 ? summaries : undefined;\n};\n","/**\n * Resolve identifiers to their underlying Layer/Effect initializer call.\n *\n * When a pipe chain starts with a variable (e.g. `myLayer.pipe(Layer.provide(...))`)\n * we follow the variable's declaration — including cross-file imports and\n * default imports — back to the original `Layer.*` or `Effect.*` call so the\n * analyzer can classify what's actually being piped.\n *\n * Extracted from effect-analysis.ts as part of the strangler-fig cleanup.\n * Behaviour is preserved exactly.\n */\n\nimport type {\n  CallExpression,\n  Node,\n  Identifier,\n  ImportSpecifier,\n  VariableDeclaration,\n  VariableStatement,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport {\n  normalizeEffectCallee,\n  resolveBarrelSourceFile,\n  resolveModulePath,\n} from './alias-resolution';\n\n/** Return true if the call expression text (e.g. \"Layer.succeed\" or \"L.succeed\") is a Layer or Effect initializer. */\nexport function isLayerOrEffectInitializerCallee(initCall: CallExpression): boolean {\n  const initText = initCall.getExpression().getText();\n  const srcFile = initCall.getSourceFile();\n  const normalized = normalizeEffectCallee(initText, srcFile);\n  return (\n    normalized.startsWith('Layer.') ||\n    normalized.startsWith('Effect.') ||\n    initText === 'pipe' ||\n    initText.endsWith('.pipe')\n  );\n}\n\n/**\n * Resolve a Layer initializer from a cross-file import by resolving the target module\n * and looking up the exported declaration. Used when symbol alias resolution doesn't\n * yield a VariableDeclaration (e.g. project created without tsconfig).\n */\nfunction resolveLayerInitializerFromImport(\n  ident: Identifier,\n  importSpec: ImportSpecifier,\n  isLayerInit: (call: CallExpression) => boolean,\n): CallExpression | undefined {\n  const { SyntaxKind } = loadTsMorph();\n  const sourceFile = ident.getSourceFile();\n  const project = sourceFile.getProject();\n  const currentPath = sourceFile.getFilePath();\n  const importDecl = importSpec.getImportDeclaration();\n  const specifier = importDecl.getModuleSpecifierValue();\n  if (!specifier?.startsWith('.')) return undefined;\n  let targetFile = resolveBarrelSourceFile(project, currentPath, specifier);\n  if (!targetFile) {\n    const resolvedPath = resolveModulePath(currentPath, specifier);\n    if (resolvedPath) {\n      const added = project.addSourceFileAtPath(resolvedPath);\n      if (added) targetFile = added;\n    }\n  }\n  if (!targetFile) return undefined;\n  // Ensure we use the project's instance so alias resolution sees the same file\n  targetFile = project.getSourceFile(targetFile.getFilePath()) ?? targetFile;\n  const tryDecl = (d: Node): CallExpression | undefined => {\n    if (d.getKind() === SyntaxKind.VariableDeclaration) {\n      const v = d as VariableDeclaration;\n      const init = v.getInitializer();\n      if (init?.getKind() === SyntaxKind.CallExpression && isLayerInit(init as CallExpression)) {\n        return init as CallExpression;\n      }\n    }\n    if (d.getKind() === SyntaxKind.VariableStatement) {\n      const list = (d as VariableStatement).getDeclarationList();\n      for (const v of list.getDeclarations()) {\n        const init = v.getInitializer();\n        if (init?.getKind() === SyntaxKind.CallExpression && isLayerInit(init as CallExpression)) {\n          return init as CallExpression;\n        }\n      }\n    }\n    return undefined;\n  };\n  const exportName = importSpec.getName();\n  const exported = targetFile.getExportedDeclarations();\n  const decls = exported.get(exportName) ?? [];\n  for (const d of decls) {\n    const init = tryDecl(d);\n    if (init) return init;\n  }\n  const targetName = (importSpec as { getTargetName?: () => string }).getTargetName?.();\n  if (targetName && targetName !== exportName) {\n    for (const d of exported.get(targetName) ?? []) {\n      const init = tryDecl(d);\n      if (init) return init;\n    }\n  }\n  // Fallback: scan all exports (key may differ from import name in some ts-morph versions)\n  for (const [, declList] of exported) {\n    for (const d of declList) {\n      const init = tryDecl(d);\n      if (init) return init;\n    }\n  }\n  return undefined;\n}\n\nfunction resolveLayerInitializerFromDefaultImport(\n  ident: Identifier,\n  importDecl: { getModuleSpecifierValue: () => string },\n  isLayerInit: (call: CallExpression) => boolean,\n): CallExpression | undefined {\n  const { SyntaxKind } = loadTsMorph();\n  const sourceFile = ident.getSourceFile();\n  const project = sourceFile.getProject();\n  const currentPath = sourceFile.getFilePath();\n  const specifier = importDecl.getModuleSpecifierValue();\n  if (!specifier?.startsWith('.')) return undefined;\n  let targetFile = resolveBarrelSourceFile(project, currentPath, specifier);\n  if (!targetFile) {\n    const resolvedPath = resolveModulePath(currentPath, specifier);\n    if (resolvedPath) {\n      const added = project.addSourceFileAtPath(resolvedPath);\n      if (added) targetFile = added;\n    }\n  }\n  if (!targetFile) return undefined;\n  targetFile = project.getSourceFile(targetFile.getFilePath()) ?? targetFile;\n  const tryDecl = (d: Node): CallExpression | undefined => {\n    if (d.getKind() === SyntaxKind.VariableDeclaration) {\n      const v = d as VariableDeclaration;\n      const init = v.getInitializer();\n      if (init?.getKind() === SyntaxKind.CallExpression && isLayerInit(init as CallExpression)) {\n        return init as CallExpression;\n      }\n    }\n    if (d.getKind() === SyntaxKind.VariableStatement) {\n      const list = (d as VariableStatement).getDeclarationList();\n      for (const v of list.getDeclarations()) {\n        const init = v.getInitializer();\n        if (init?.getKind() === SyntaxKind.CallExpression && isLayerInit(init as CallExpression)) {\n          return init as CallExpression;\n        }\n      }\n    }\n    return undefined;\n  };\n  for (const d of targetFile.getDefaultExportSymbol()?.getDeclarations() ?? []) {\n    const init = tryDecl(d);\n    if (init) return init;\n  }\n  for (const d of targetFile.getExportedDeclarations().get('default') ?? []) {\n    const init = tryDecl(d);\n    if (init) return init;\n  }\n  return undefined;\n}\n\n/** If node is an Identifier bound to a variable whose initializer is a Layer.* call, return that initializer; else return node. (GAP: pipe-chain base variable + cross-file.) */\nexport function resolveIdentifierToLayerInitializer(node: Node): Node {\n  const { SyntaxKind } = loadTsMorph();\n  if (node.getKind() !== SyntaxKind.Identifier) return node;\n  const ident = node as Identifier;\n  const name = ident.getText();\n  let sym = ident.getSymbol();\n  let decl = sym?.getValueDeclaration();\n  let importSpec: ImportSpecifier | undefined =\n    decl?.getKind() === SyntaxKind.ImportSpecifier ? (decl as ImportSpecifier) : undefined;\n  if (!importSpec && sym) {\n    const fromDecls = sym.getDeclarations().find((d) => d.getKind() === SyntaxKind.ImportSpecifier);\n    if (fromDecls) importSpec = fromDecls as ImportSpecifier;\n  }\n  if (!importSpec) {\n    const sf = ident.getSourceFile();\n    for (const id of sf.getImportDeclarations()) {\n      const defaultImport = id.getDefaultImport()?.getText();\n      if (defaultImport === name) {\n        const fromDefault = resolveLayerInitializerFromDefaultImport(\n          ident,\n          id,\n          isLayerOrEffectInitializerCallee,\n        );\n        if (fromDefault) return fromDefault;\n      }\n      const spec = id\n        .getNamedImports()\n        .find((n) => n.getName() === name || n.getAliasNode()?.getText() === name);\n      if (spec) {\n        importSpec = spec;\n        break;\n      }\n    }\n  }\n  // Cross-file: when the binding is an import, resolve via the target module first so we get\n  // a node in the target file (alias resolution for L->Layer needs that file's SourceFile).\n  if (importSpec) {\n    const fromImport = resolveLayerInitializerFromImport(\n      ident,\n      importSpec,\n      isLayerOrEffectInitializerCallee,\n    );\n    if (fromImport) return fromImport;\n    sym = sym?.getImmediatelyAliasedSymbol() ?? sym?.getAliasedSymbol();\n    decl = sym?.getValueDeclaration();\n  }\n  // Also follow alias if valueDeclaration is an export specifier (re-export)\n  if (decl?.getKind() === SyntaxKind.ExportSpecifier) {\n    sym = sym?.getImmediatelyAliasedSymbol() ?? sym?.getAliasedSymbol();\n    decl = sym?.getValueDeclaration();\n  }\n  // Fallback: search all declarations for a VariableDeclaration with Layer initializer (cross-module)\n  if (sym && decl?.getKind() !== SyntaxKind.VariableDeclaration) {\n    for (const d of sym.getDeclarations()) {\n      if (d.getKind() === SyntaxKind.VariableDeclaration) {\n        const v = d as VariableDeclaration;\n        const init = v.getInitializer();\n        if (init?.getKind() === SyntaxKind.CallExpression) {\n          if (isLayerOrEffectInitializerCallee(init as CallExpression)) {\n            return init;\n          }\n        }\n      }\n    }\n  }\n  if (decl?.getKind() === SyntaxKind.VariableDeclaration) {\n    const vd = decl as VariableDeclaration;\n    const init = vd.getInitializer();\n    if (init?.getKind() === SyntaxKind.CallExpression) {\n      if (isLayerOrEffectInitializerCallee(init as CallExpression)) {\n        return init;\n      }\n    }\n  }\n  return node;\n}\n","/**\n * Heuristics for inferring service / runtime-primitive types from raw AST text.\n *\n * These are best-effort guesses used to label nodes in the IR (e.g. mark a\n * call as `serviceCall` when the receiver looks like a service). They never\n * fall back to the rest of the analyzer pipeline, which is why they live in\n * their own module.\n *\n * Extracted from effect-analysis.ts as part of the strangler-fig cleanup.\n * Behaviour is preserved exactly.\n */\n\nimport type { PropertyAccessExpression, ArrowFunction, FunctionExpression } from 'ts-morph';\nimport type { StaticEffectNode } from './types';\nimport {\n  BUILT_IN_TYPE_NAMES,\n  KNOWN_EFFECT_NAMESPACES,\n} from './analysis-patterns';\n\nexport const isPromiseLikeText = (text: string): boolean =>\n  /\\bPromise(?:<.*>)?\\b/.test(text) || /\\bthen\\s*\\(/.test(text);\n\nconst EFFECT_RUNTIME_PRIMITIVE_PREFIXES = [\n  'Ref.',\n  'SynchronizedRef.',\n  'FiberRef.',\n  'TxRef.',\n  'TRef.',\n  'Queue.',\n  'TQueue.',\n  'TxQueue.',\n  'PubSub.',\n  'TPubSub.',\n  'Deferred.',\n  'TDeferred.',\n  'Semaphore.',\n  'TSemaphore.',\n  'SubscriptionRef.',\n  'Mailbox.',\n];\n\nexport const isEffectRuntimePrimitive = (text: string): boolean =>\n  EFFECT_RUNTIME_PRIMITIVE_PREFIXES.some((prefix) => text.startsWith(prefix));\n\nexport const isLikelyServiceStreamProperty = (propertyName: string): boolean =>\n  propertyName === 'stream' || propertyName.startsWith('stream');\n\nconst normalizeInferredServiceType = (typeName: string): string =>\n  typeName.endsWith('Shape') ? typeName.slice(0, -'Shape'.length) : typeName;\n\nconst inferServiceTypeFromObjectName = (objectName: string): string | undefined => {\n  if (!/^[a-zA-Z_$][\\w$]*$/.test(objectName)) return undefined;\n  if (objectName.length === 0) return undefined;\n  const inferred = objectName[0]!.toUpperCase() + objectName.slice(1);\n  if (BUILT_IN_TYPE_NAMES.has(inferred) || KNOWN_EFFECT_NAMESPACES.has(inferred)) {\n    return undefined;\n  }\n  return inferred;\n};\n\nexport const tryResolveServicePropertyAccess = (\n  node: PropertyAccessExpression,\n): StaticEffectNode['serviceCall'] => {\n  const objectName = node.getExpression().getText();\n  const methodName = node.getName();\n  const firstSegment = objectName.split('.')[0] ?? objectName;\n  const fallback = inferServiceTypeFromObjectName(objectName);\n  if (KNOWN_EFFECT_NAMESPACES.has(firstSegment)) return undefined;\n\n  try {\n    const type = node.getExpression().getType();\n    const symbol = type.getSymbol() ?? type.getAliasSymbol();\n    if (!symbol) return fallback ? { serviceType: fallback, methodName, objectName } : undefined;\n    const typeName = normalizeInferredServiceType(symbol.getName());\n    if (\n      !typeName ||\n      typeName === '__type' ||\n      typeName === 'unknown' ||\n      typeName === 'any' ||\n      BUILT_IN_TYPE_NAMES.has(typeName)\n    ) {\n      return fallback ? { serviceType: fallback, methodName, objectName } : undefined;\n    }\n    return { serviceType: typeName, methodName, objectName };\n  } catch {\n    return fallback ? { serviceType: fallback, methodName, objectName } : undefined;\n  }\n};\n\nexport const classifyUseCallbackKind = (\n  fnNode: ArrowFunction | FunctionExpression,\n): 'promise' | 'effect' | 'unknown' => {\n  const body = fnNode.getBody();\n  const bodyText = body.getText();\n  if (\n    bodyText.includes('Effect.') ||\n    bodyText.includes('yield*') ||\n    bodyText.includes('.pipe(')\n  ) {\n    return 'effect';\n  }\n\n  if (isPromiseLikeText(bodyText)) {\n    return 'promise';\n  }\n\n  try {\n    const fnTypeText = fnNode.getType().getText();\n    if (fnTypeText.includes('Effect<') || fnTypeText.includes('Effect.Effect<')) {\n      return 'effect';\n    }\n    if (isPromiseLikeText(fnTypeText)) {\n      return 'promise';\n    }\n  } catch {\n    // best-effort classification only\n  }\n\n  return 'unknown';\n};\n","/** Shared recursive context for domain-specific expression analyzers. */\n\nimport type { Effect } from 'effect';\nimport type { Node, SourceFile } from 'ts-morph';\nimport type {\n  AnalysisError,\n  AnalysisStats,\n  AnalysisWarning,\n  AnalyzerOptions,\n  StaticFlowNode,\n} from './types';\n\nexport type AnalyzeEffectExpression = (\n  node: Node,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  serviceScope?: Map<string, string>,\n) => Effect.Effect<StaticFlowNode, AnalysisError>;\n\nexport interface AnalysisContext {\n  readonly analyzeEffectExpression: AnalyzeEffectExpression;\n}\n\n/**\n * Close recursive dispatch behind one context. The getter is intentionally\n * lazy so module initialization order is not part of any analyzer interface.\n */\nexport const createAnalysisContext = (\n  getAnalyze: () => AnalyzeEffectExpression,\n): AnalysisContext => ({\n  get analyzeEffectExpression() {\n    return getAnalyze();\n  },\n});\n\nexport type BindAnalysisContext<F> = F extends (\n  context: AnalysisContext,\n  ...args: infer Args\n) => infer Output\n  ? (...args: Args) => Output\n  : never;\n\nexport const bindAnalysisContext = <\n  F extends (context: AnalysisContext, ...args: never[]) => unknown,\n>(\n  context: AnalysisContext,\n  analyzer: F,\n): BindAnalysisContext<F> =>\n  ((...args: never[]) => analyzer(context, ...args)) as BindAnalysisContext<F>;\n","/**\n * Stream / Channel / Sink call analyzers.\n *\n * These functions parse Stream.*, Channel.* and Sink.* call expressions into\n * their corresponding IR nodes. They recursively analyse argument expressions,\n * which used to create a circular import on `analyzeEffectExpression` — so the\n * dependency is now passed in via the `AnalyzerDeps` parameter, keeping the\n * module acyclic.\n *\n * Extracted from effect-analysis.ts as part of the strangler-fig cleanup.\n * Behaviour is preserved exactly; the only change is `analyzeEffectExpression`\n * is now accessed via `deps.analyzeEffectExpression` instead of a direct call.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  PropertyAccessExpression,\n  ArrowFunction,\n  FunctionExpression,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticStreamNode,\n  StaticChannelNode,\n  StaticSinkNode,\n  StreamOperatorInfo,\n  ChannelOperatorInfo,\n  SinkOperatorInfo,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport {\n  buildCallbackSummaryNodes,\n  buildPureCallbackSummaryNodes,\n} from './callback-summary';\nimport { channelOpCategory, sinkOpCategory } from './analysis-classifiers';\nimport { getNumericLiteralFromNode } from './analysis-patterns';\nimport type { AnalysisContext } from './analysis-context';\n\n/** Parse Stream.* call into StaticStreamNode (GAP 5). */\nexport function analyzeStreamCall(\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  serviceScope?: Map<string, string>,\n): Effect.Effect<StaticStreamNode, AnalysisError> {\n  return Effect.gen(function* () {\n    const args = call.getArguments();\n    const { SyntaxKind } = loadTsMorph();\n\n    if (\n      call.getExpression().getKind() === SyntaxKind.PropertyAccessExpression &&\n      (call.getExpression() as PropertyAccessExpression).getName() === 'pipe'\n    ) {\n      const propAccess = call.getExpression() as PropertyAccessExpression;\n      const baseExpr = propAccess.getExpression();\n      const analyzedBase = yield* deps.analyzeEffectExpression(\n        baseExpr,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n        serviceScope,\n      );\n\n      const effectiveSource =\n        analyzedBase.type === 'stream' ? analyzedBase.source : analyzedBase;\n      const pipeline =\n        analyzedBase.type === 'stream' ? [...analyzedBase.pipeline] : [];\n      let sink =\n        analyzedBase.type === 'stream' ? analyzedBase.sink : undefined;\n      let backpressureStrategy =\n        analyzedBase.type === 'stream'\n          ? analyzedBase.backpressureStrategy\n          : undefined;\n      let constructorType =\n        analyzedBase.type === 'stream' ? analyzedBase.constructorType : undefined;\n\n      for (const arg of args) {\n        const analyzed = yield* deps.analyzeEffectExpression(\n          arg,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n          serviceScope,\n        );\n        if (analyzed.type === 'stream') {\n          pipeline.push(...analyzed.pipeline);\n          if (!sink && analyzed.sink) sink = analyzed.sink;\n          if (!backpressureStrategy && analyzed.backpressureStrategy) {\n            backpressureStrategy = analyzed.backpressureStrategy;\n          }\n          if (!constructorType && analyzed.constructorType) {\n            constructorType = analyzed.constructorType;\n          }\n        }\n      }\n\n      const streamNode: StaticStreamNode = {\n        id: generateId(),\n        type: 'stream',\n        source: effectiveSource,\n        pipeline,\n        ...(sink ? { sink } : {}),\n        ...(backpressureStrategy ? { backpressureStrategy } : {}),\n        ...(constructorType ? { constructorType } : {}),\n        location: extractLocation(call, filePath, opts.includeLocations ?? false),\n      };\n      return {\n        ...streamNode,\n        displayName: computeDisplayName(streamNode),\n        semanticRole: computeSemanticRole(streamNode),\n      };\n    }\n\n    let source: StaticFlowNode;\n    if (args.length > 0 && args[0]) {\n      source = yield* deps.analyzeEffectExpression(\n        args[0],\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n        serviceScope,\n      );\n    } else {\n      source = {\n        id: generateId(),\n        type: 'unknown',\n        reason: 'Stream source not determined',\n      };\n    }\n    const opName = callee.replace(/^Stream\\./, '') || 'unknown';\n\n    // Classify constructor type\n    let constructorType: StaticStreamNode['constructorType'];\n    if (callee.startsWith('Stream.')) {\n      if (opName === 'fromIterable' || opName === 'fromChunk' || opName === 'fromChunkQueue') constructorType = 'fromIterable';\n      else if (opName === 'fromArray') constructorType = 'fromArray';\n      else if (opName === 'fromQueue' || opName === 'fromChunkQueue') constructorType = 'fromQueue';\n      else if (opName === 'fromPubSub' || opName === 'fromChunkPubSub') constructorType = 'fromPubSub';\n      else if (opName === 'fromEffect' || opName === 'unwrap' || opName === 'unwrapScoped') constructorType = 'fromEffect';\n      else if (opName === 'fromAsyncIterable') constructorType = 'fromAsyncIterable';\n      else if (opName === 'fromReadableStream' || opName === 'fromReadableStreamByob') constructorType = 'fromReadableStream';\n      else if (opName === 'fromEventListener') constructorType = 'fromEventListener';\n      else if (opName === 'fromSchedule') constructorType = 'fromSchedule';\n      else if (opName === 'range') constructorType = 'range';\n      else if (opName === 'tick') constructorType = 'tick';\n      else if (opName === 'iterate' || opName === 'iterateEffect') constructorType = 'iterate';\n      else if (opName === 'unfold' || opName === 'unfoldEffect' || opName === 'unfoldChunk' || opName === 'unfoldChunkEffect') constructorType = 'unfold';\n      else if (opName === 'make') constructorType = 'make';\n      else if (opName === 'empty') constructorType = 'empty';\n      else if (opName === 'never') constructorType = 'never';\n      else if (opName === 'succeed' || opName === 'sync') constructorType = 'succeed';\n      else if (opName === 'fail' || opName === 'failSync' || opName === 'failCause' || opName === 'failCauseSync') constructorType = 'fail';\n    }\n\n    // Classify operator category\n    const classifyOperator = (op: string): StreamOperatorInfo['category'] => {\n      if (constructorType !== undefined) return 'constructor';\n      if (op.startsWith('run')) return 'sink';\n      if (op === 'toQueue' || op === 'toPubSub' || op === 'toReadableStream' || op === 'toAsyncIterable' || op === 'toChannel') return 'conversion';\n      if (op.includes('pipeThroughChannel') || op.includes('Channel') || op.includes('channel') || op.includes('duplex')) return 'channel';\n      if (op.includes('grouped') || op.includes('sliding') || op.includes('groupBy') || op.includes('aggregate') || op.includes('window')) return 'windowing';\n      if (op.includes('broadcast') || op === 'share') return 'broadcasting';\n      if (op.includes('haltAfter') || op.includes('haltWhen') || op.includes('interruptAfter')) return 'halting';\n      if (op.includes('decodeText') || op.includes('encodeText') || op.includes('splitLines')) return 'text';\n      if (op.includes('merge') || op === 'concat' || op.includes('interleave') || op.includes('zip')) return 'merge';\n      if (op.includes('buffer') || op.includes('debounce') || op.includes('throttle')) return 'backpressure';\n      if (op.includes('catch') || op.includes('catchTag') || op.includes('orElse') || op.includes('orDie') || op.includes('retry')) return 'error';\n      if (op.includes('filter') || op.includes('take') || op.includes('drop') || op.includes('head') || op === 'first' || op === 'last') return 'filter';\n      if (op.includes('acquireRelease') || op.includes('scoped') || op.includes('ensuring') || op.includes('onDone') || op.includes('onError')) return 'resource';\n      if (op.includes('provide') || op.includes('withSpan') || op.includes('annotate')) return 'context';\n      if (op.includes('map') || op.includes('tap') || op.includes('flatMap') || op.includes('mapChunk') || op.includes('scan') || op.includes('transduce')) return 'transform';\n      return 'other';\n    };\n\n    const isEffectful =\n      opName.includes('Effect') ||\n      opName.startsWith('run') ||\n      opName.includes('tap');\n    const callbackArg = args.find(\n      (arg) =>\n        arg.getKind() === SyntaxKind.ArrowFunction ||\n        arg.getKind() === SyntaxKind.FunctionExpression,\n    );\n    const callbackBody = callbackArg\n      ? (\n          opName.includes('Effect') || opName.includes('tap')\n            ? buildCallbackSummaryNodes(\n                callbackArg as ArrowFunction | FunctionExpression,\n                filePath,\n                opts.includeLocations ?? false,\n              )\n            : buildPureCallbackSummaryNodes(\n                callbackArg as ArrowFunction | FunctionExpression,\n                filePath,\n                opts.includeLocations ?? false,\n              )\n        )\n      : undefined;\n    const opCategory = classifyOperator(opName);\n    const cardinality: StreamOperatorInfo['estimatedCardinality'] =\n      opCategory === 'filter' ? 'fewer' :\n      opCategory === 'merge' ? 'more' :\n      opCategory === 'broadcasting' ? 'more' :\n      opCategory === 'halting' ? 'fewer' :\n      opCategory === 'sink' ? 'fewer' :\n      opCategory === 'windowing' ? 'fewer' :\n      'unknown';\n\n    // Windowing detail (GAP 2): size/stride for grouped, groupedWithin, sliding\n    let windowSize: number | undefined;\n    let stride: number | undefined;\n    const isWindowingOp =\n      opName === 'grouped' ||\n      opName === 'groupedWithin' ||\n      opName.includes('sliding') ||\n      opName.includes('Sliding');\n    if (isWindowingOp && args.length > 0 && args[0]) {\n      windowSize = getNumericLiteralFromNode(args[0]);\n      if (\n        (opName.includes('sliding') || opName.includes('Sliding')) &&\n        args.length > 1 &&\n        args[1]\n      ) {\n        stride = getNumericLiteralFromNode(args[1]);\n      }\n    }\n\n    const thisOp: StreamOperatorInfo = {\n      operation: opName,\n      isEffectful,\n      ...(callbackBody ? { callbackBody } : {}),\n      estimatedCardinality: cardinality,\n      category: opCategory,\n      ...(windowSize !== undefined ? { windowSize } : {}),\n      ...(stride !== undefined ? { stride } : {}),\n    };\n\n    let sink: string | undefined;\n    if (opName.startsWith('run')) sink = opName;\n    let backpressureStrategy: StaticStreamNode['backpressureStrategy'];\n    if (opName.includes('buffer')) backpressureStrategy = 'buffer';\n    else if (opName.includes('drop') || opName.includes('Drop')) backpressureStrategy = 'drop';\n    else if (opName.includes('sliding') || opName.includes('Sliding')) backpressureStrategy = 'sliding';\n\n    // Flatten nested stream pipeline: if source is itself a StreamNode (data-last\n    // call pattern), merge its pipeline into ours and use its base source.\n    let effectiveSource = source;\n    let pipeline: StreamOperatorInfo[] = [thisOp];\n    let effectiveConstructorType = constructorType;\n    if (source.type === 'stream') {\n      const srcStream = source;\n      // Prepend the upstream pipeline so the full chain is visible in one node\n      pipeline = [...srcStream.pipeline, thisOp];\n      effectiveSource = srcStream.source;\n      // Inherit upstream constructorType/sink/strategy if this node doesn't override\n      if (!effectiveConstructorType && srcStream.constructorType) effectiveConstructorType = srcStream.constructorType;\n      if (!sink && srcStream.sink) sink = srcStream.sink;\n      if (!backpressureStrategy && srcStream.backpressureStrategy) backpressureStrategy = srcStream.backpressureStrategy;\n    }\n\n    const streamNode: StaticStreamNode = {\n      id: generateId(),\n      type: 'stream',\n      source: effectiveSource,\n      pipeline,\n      sink,\n      backpressureStrategy,\n      constructorType: effectiveConstructorType,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...streamNode,\n      displayName: computeDisplayName(streamNode),\n      semanticRole: computeSemanticRole(streamNode),\n    };\n  });\n}\n\n/** Parse Channel.* call into StaticChannelNode (improve.md §8). */\nexport function analyzeChannelCall(\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticChannelNode, AnalysisError> {\n  return Effect.gen(function* () {\n    const args = call.getArguments();\n    let source: StaticFlowNode | undefined;\n    if (args.length > 0 && args[0]) {\n      source = yield* deps.analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n    }\n    const opName = callee.replace(/^Channel\\./, '') || 'unknown';\n    const pipeline: ChannelOperatorInfo[] = [{ operation: opName, category: channelOpCategory(opName) }];\n    if (source?.type === 'channel') {\n      const srcChan = source;\n      pipeline.unshift(...srcChan.pipeline);\n      source = srcChan.source;\n    }\n    const channelNode: StaticChannelNode = {\n      id: generateId(),\n      type: 'channel',\n      source,\n      pipeline,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...channelNode,\n      displayName: computeDisplayName(channelNode),\n      semanticRole: computeSemanticRole(channelNode),\n    };\n  });\n}\n\n/** Parse Sink.* call into StaticSinkNode (improve.md §8). */\nexport function analyzeSinkCall(\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticSinkNode, AnalysisError> {\n  return Effect.gen(function* () {\n    const args = call.getArguments();\n    let source: StaticFlowNode | undefined;\n    if (args.length > 0 && args[0]) {\n      source = yield* deps.analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n    }\n    const opName = callee.replace(/^Sink\\./, '') || 'unknown';\n    const pipeline: SinkOperatorInfo[] = [{ operation: opName, category: sinkOpCategory(opName) }];\n    if (source?.type === 'sink') {\n      const srcSink = source;\n      pipeline.unshift(...srcSink.pipeline);\n      source = srcSink.source;\n    }\n    const sinkNode: StaticSinkNode = {\n      id: generateId(),\n      type: 'sink',\n      source,\n      pipeline,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...sinkNode,\n      displayName: computeDisplayName(sinkNode),\n      semanticRole: computeSemanticRole(sinkNode),\n    };\n  });\n}\n","/**\n * Pure classifier and parsing helpers used by the analyzer.\n *\n * These functions are intentionally side-effect-free and do not call back\n * into the rest of the analyzer pipeline, which is why they live in their\n * own module — keeping effect-analysis.ts focused on tree-walking logic.\n *\n * Extracted from effect-analysis.ts as part of the strangler-fig cleanup.\n * Behaviour is preserved exactly.\n */\n\nimport type { ObjectLiteralExpression, PropertyAssignment } from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  ConcurrencyMode,\n  ScheduleInfo,\n  ChannelOperatorInfo,\n  SinkOperatorInfo,\n} from './types';\n\n/** Classify Channel.* operation (improve.md §8). */\nexport function channelOpCategory(op: string): ChannelOperatorInfo['category'] {\n  if (\n    op === 'fromReadableStream' ||\n    op === 'fromWritableStream' ||\n    op === 'fromDuplexStream' ||\n    op === 'make' ||\n    op === 'succeed' ||\n    op === 'fail' ||\n    op === 'empty' ||\n    op === 'never'\n  )\n    return 'constructor';\n  if (\n    op.includes('map') ||\n    op.includes('flatMap') ||\n    op.includes('filter') ||\n    op.includes('concat') ||\n    op.includes('zip')\n  )\n    return 'transform';\n  if (op.includes('pipe') || op === 'pipeTo' || op === 'pipeThrough') return 'pipe';\n  return 'other';\n}\n\n/** Classify Sink.* operation (improve.md §8). */\nexport function sinkOpCategory(op: string): SinkOperatorInfo['category'] {\n  if (\n    op === 'forEach' ||\n    op === 'forEachWhile' ||\n    op === 'run' ||\n    op === 'runDrain' ||\n    op === 'runFor' ||\n    op === 'make' ||\n    op === 'fromEffect' ||\n    op === 'fromQueue'\n  )\n    return 'constructor';\n  if (\n    op.includes('map') ||\n    op.includes('contramap') ||\n    op.includes('filter') ||\n    op.includes('zip')\n  )\n    return 'transform';\n  return 'other';\n}\n\n/** Parse Effect.all options object: concurrency, batching, discard (GAP 18). */\nexport function parseEffectAllOptions(\n  optionsNode: ObjectLiteralExpression,\n): {\n  concurrency: ConcurrencyMode | undefined;\n  batching: boolean | undefined;\n  discard: boolean | undefined;\n} {\n  const { SyntaxKind } = loadTsMorph();\n  let concurrency: ConcurrencyMode | undefined;\n  let batching: boolean | undefined;\n  let discard: boolean | undefined;\n  for (const prop of optionsNode.getProperties()) {\n    if (prop.getKind() !== SyntaxKind.PropertyAssignment) continue;\n    const name = (prop as PropertyAssignment).getNameNode().getText();\n    const init = (prop as PropertyAssignment).getInitializer();\n    if (!init) continue;\n    const text = init.getText();\n    if (name === 'concurrency') {\n      if (text === '\"unbounded\"' || text === \"'unbounded'\") concurrency = 'unbounded';\n      else if (text === '\"sequential\"' || text === \"'sequential'\") concurrency = 'sequential';\n      else if (text === '\"inherit\"' || text === \"'inherit'\") concurrency = 'sequential';\n      else {\n        const n = Number.parseInt(text, 10);\n        if (!Number.isNaN(n) && n >= 0) concurrency = n;\n      }\n    } else if (name === 'batching' && (text === 'true' || text === 'false')) {\n      batching = text === 'true';\n    } else if (name === 'discard' && (text === 'true' || text === 'false')) {\n      discard = text === 'true';\n    }\n  }\n  return { concurrency, batching, discard };\n}\n\n/** Parse schedule expression text into ScheduleInfo (GAP 8). */\nexport function parseScheduleInfo(scheduleText: string): ScheduleInfo | undefined {\n  const t = scheduleText.replace(/\\s+/g, ' ');\n  let baseStrategy: ScheduleInfo['baseStrategy'] = 'custom';\n  if (t.includes('Schedule.exponential') || t.includes('exponential(')) baseStrategy = 'exponential';\n  else if (t.includes('Schedule.fibonacci') || t.includes('fibonacci(')) baseStrategy = 'fibonacci';\n  else if (t.includes('Schedule.spaced') || t.includes('spaced(')) baseStrategy = 'spaced';\n  else if (t.includes('Schedule.fixed') || t.includes('fixed(')) baseStrategy = 'fixed';\n  else if (t.includes('Schedule.linear') || t.includes('linear(')) baseStrategy = 'linear';\n  else if (t.includes('Schedule.cron') || t.includes('cron(')) baseStrategy = 'cron';\n  else if (t.includes('Schedule.windowed') || t.includes('windowed(')) baseStrategy = 'windowed';\n  else if (t.includes('Schedule.duration') || t.includes('duration(')) baseStrategy = 'duration';\n  else if (t.includes('Schedule.elapsed') || t.includes('elapsed(')) baseStrategy = 'elapsed';\n  else if (t.includes('Schedule.delays') || t.includes('delays(')) baseStrategy = 'delays';\n  else if (t.includes('Schedule.once') || t.includes('once(')) baseStrategy = 'once';\n  else if (t.includes('Schedule.stop') || t.includes('stop(')) baseStrategy = 'stop';\n  else if (t.includes('Schedule.count') || t.includes('count(')) baseStrategy = 'count';\n\n  let maxRetries: number | 'unlimited' | undefined;\n  const recursMatch = /recurs\\s*\\(\\s*(\\d+)\\s*\\)/.exec(t);\n  if (recursMatch) maxRetries = Number.parseInt(recursMatch[1]!, 10);\n  const recurUpToMatch = /recurUpTo\\s*\\(\\s*(\\d+)\\s*\\)/.exec(t);\n  if (recurUpToMatch) maxRetries = Number.parseInt(recurUpToMatch[1]!, 10);\n  else if (t.includes('forever') || t.includes('Schedule.forever')) maxRetries = 'unlimited';\n\n  const jittered = t.includes('jittered') || t.includes('Schedule.jittered');\n  const conditions: string[] = [];\n  if (t.includes('whileInput')) conditions.push('whileInput');\n  if (t.includes('whileOutput')) conditions.push('whileOutput');\n  if (t.includes('untilInput')) conditions.push('untilInput');\n  if (t.includes('untilOutput')) conditions.push('untilOutput');\n  if (t.includes('recurUntil')) conditions.push('recurUntil');\n  if (t.includes('recurWhile')) conditions.push('recurWhile');\n  if (t.includes('andThen')) conditions.push('andThen');\n  if (t.includes('intersect')) conditions.push('intersect');\n  if (t.includes('union')) conditions.push('union');\n  if (t.includes('compose')) conditions.push('compose');\n  if (t.includes('zipWith')) conditions.push('zipWith');\n  if (t.includes('addDelay')) conditions.push('addDelay');\n  if (t.includes('modifyDelay')) conditions.push('modifyDelay');\n  if (t.includes('check')) conditions.push('check');\n  if (t.includes('resetAfter')) conditions.push('resetAfter');\n  if (t.includes('resetWhen')) conditions.push('resetWhen');\n  if (t.includes('ensure')) conditions.push('ensure');\n  if (t.includes('driver')) conditions.push('driver');\n  if (t.includes('mapInput')) conditions.push('mapInput');\n\n  return {\n    baseStrategy,\n    maxRetries,\n    jittered,\n    conditions,\n  };\n}\n","/**\n * Retry / Timeout / Schedule call analyzers.\n *\n * Retry and Timeout both need to recurse into their source effect via\n * `deps.analyzeEffectExpression`. The standalone Schedule analyzer is purely\n * structural and doesn't recurse, but it lives here for cohesion with the\n * temporal-control analyzers.\n *\n * Extracted from effect-analysis.ts via the strangler-fig DI pattern —\n * behaviour is preserved exactly.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  PropertyAccessExpression,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticRetryNode,\n  StaticTimeoutNode,\n  StaticScheduleNode,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n  getNodeText,\n} from './analysis-utils';\nimport { SCHEDULE_OP_MAP } from './analysis-patterns';\nimport { parseScheduleInfo } from './analysis-classifiers';\nimport type { AnalysisContext } from './analysis-context';\n\nexport const analyzeRetryCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticRetryNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    let source: StaticFlowNode;\n    let schedule: string | undefined;\n    let scheduleNode: StaticFlowNode | undefined;\n    let hasFallback: boolean;\n\n    const expr = call.getExpression();\n    if (expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n      const propAccess = expr as PropertyAccessExpression;\n      const exprSource = propAccess.getExpression();\n      source = yield* deps.analyzeEffectExpression(\n        exprSource,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n\n      if (args.length > 0 && args[0]) {\n        schedule = args[0].getText();\n        scheduleNode = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      }\n\n      hasFallback = expr.getText().includes('retryOrElse');\n    } else {\n      if (args.length > 0 && args[0]) {\n        source = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      } else {\n        source = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Could not determine source effect',\n        };\n      }\n\n      if (args.length > 1 && args[1]) {\n        schedule = args[1].getText();\n        scheduleNode = yield* deps.analyzeEffectExpression(\n          args[1],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      }\n\n      hasFallback = args.length > 2;\n    }\n\n    stats.retryCount++;\n\n    const scheduleInfo = schedule ? parseScheduleInfo(schedule) : undefined;\n\n    const retryNode: StaticRetryNode = {\n      id: generateId(),\n      type: 'retry',\n      source,\n      schedule,\n      ...(scheduleNode !== undefined ? { scheduleNode } : {}),\n      hasFallback,\n      scheduleInfo,\n      retryEdgeLabel: schedule ? `retry: ${schedule}` : 'retry',\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...retryNode,\n      displayName: computeDisplayName(retryNode),\n      semanticRole: computeSemanticRole(retryNode),\n    };\n  });\n\nexport const analyzeTimeoutCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticTimeoutNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    let source: StaticFlowNode;\n    let duration: string | undefined;\n    let hasFallback: boolean;\n\n    const expr = call.getExpression();\n    if (expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n      const propAccess = expr as PropertyAccessExpression;\n      const exprSource = propAccess.getExpression();\n      source = yield* deps.analyzeEffectExpression(\n        exprSource,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n\n      if (args.length > 0 && args[0]) {\n        duration = getNodeText(args[0]);\n      }\n\n      const exprText = getNodeText(expr);\n      hasFallback =\n        exprText.includes('timeoutFail') ||\n        exprText.includes('timeoutTo');\n    } else {\n      if (args.length > 0 && args[0]) {\n        source = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      } else {\n        source = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Could not determine source effect',\n        };\n      }\n\n      if (args.length > 1 && args[1]) {\n        duration = getNodeText(args[1]);\n      }\n\n      hasFallback = args.length > 2;\n    }\n\n    stats.timeoutCount++;\n\n    const timeoutNode: StaticTimeoutNode = {\n      id: generateId(),\n      type: 'timeout',\n      source,\n      duration,\n      hasFallback,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...timeoutNode,\n      displayName: computeDisplayName(timeoutNode),\n      semanticRole: computeSemanticRole(timeoutNode),\n    };\n  });\n\n/** Analyze Schedule.exponential / spaced / jittered / andThen / etc. (GAP 8 dedicated IR). */\nexport const analyzeScheduleCall = (\n  call: CallExpression,\n  callee: string,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n): Effect.Effect<StaticScheduleNode, AnalysisError> =>\n  Effect.sync(() => {\n    const scheduleOp: StaticScheduleNode['scheduleOp'] =\n      SCHEDULE_OP_MAP[callee] ?? 'other';\n    const scheduleText = call.getText();\n    const scheduleInfo = parseScheduleInfo(scheduleText);\n    const scheduleNode: StaticScheduleNode = {\n      id: generateId(),\n      type: 'schedule',\n      scheduleOp,\n      ...(scheduleInfo ? { scheduleInfo } : {}),\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...scheduleNode,\n      displayName: computeDisplayName(scheduleNode),\n      semanticRole: computeSemanticRole(scheduleNode),\n    };\n  });\n","/**\n * Concurrency-primitive / Fiber / Interruption call analyzers.\n *\n * - `analyzeConcurrencyPrimitiveCall` classifies Queue/PubSub/Deferred/Semaphore/etc.\n *   It does not recurse, so it takes no deps.\n * - `analyzeFiberCall` and `analyzeInterruptionCall` recurse into source effects\n *   via `deps.analyzeEffectExpression`.\n *\n * Extracted from effect-analysis.ts via the strangler-fig DI pattern.\n * Behaviour is preserved exactly.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  PropertyAccessExpression,\n  NumericLiteral,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticConcurrencyPrimitiveNode,\n  StaticStreamNode,\n  StaticFiberNode,\n  StaticInterruptionNode,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport { getNumericLiteralFromNode } from './analysis-patterns';\nimport type { AnalysisContext } from './analysis-context';\n\n/** Parse concurrency primitive (Queue, PubSub, Deferred, etc.) - GAP 6 */\nexport function analyzeConcurrencyPrimitiveCall(\n  call: CallExpression,\n  callee: string,\n  _sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  _warnings: AnalysisWarning[],\n  _stats: AnalysisStats,\n): Effect.Effect<StaticConcurrencyPrimitiveNode | StaticStreamNode, AnalysisError> {\n  const { SyntaxKind } = loadTsMorph();\n  let primitive: StaticConcurrencyPrimitiveNode['primitive'] = 'queue';\n  let operation: StaticConcurrencyPrimitiveNode['operation'] = 'create';\n  let strategy: 'bounded' | 'unbounded' | 'sliding' | 'dropping' | undefined;\n  let capacity: number | undefined;\n  let permitCount: number | undefined;\n\n  if (callee.startsWith('Queue.')) {\n    primitive = 'queue';\n    if (callee.includes('bounded')) strategy = 'bounded';\n    else if (callee.includes('unbounded')) strategy = 'unbounded';\n    else if (callee.includes('sliding')) strategy = 'sliding';\n    else if (callee.includes('dropping')) strategy = 'dropping';\n    if (callee.includes('offer') || callee.includes('offerAll')) operation = 'offer';\n    else if (callee.includes('take') || callee.includes('takeAll') || callee.includes('poll')) operation = 'take';\n    else operation = 'create';\n  } else if (callee.startsWith('PubSub.')) {\n    primitive = 'pubsub';\n    if (callee.includes('bounded')) strategy = 'bounded';\n    else if (callee.includes('unbounded')) strategy = 'unbounded';\n    if (callee.includes('publish')) operation = 'publish';\n    else if (callee.includes('subscribe')) operation = 'subscribe';\n    else operation = 'create';\n  } else if (callee.startsWith('Deferred.')) {\n    primitive = 'deferred';\n    if (callee.includes('succeed')) operation = 'succeed';\n    else if (callee.includes('fail')) operation = 'fail';\n    else if (callee.includes('await')) operation = 'await';\n    else operation = 'create';\n  } else if (callee.startsWith('Semaphore.')) {\n    primitive = 'semaphore';\n    if (callee.includes('withPermit')) operation = 'withPermit';\n    else if (callee.includes('take')) operation = 'take';\n    else if (callee.includes('release')) operation = 'release';\n    else if (callee.includes('available')) operation = 'available';\n    else operation = 'create';\n  } else if (callee.startsWith('Mailbox.')) {\n    primitive = 'mailbox';\n    if (callee.includes('offer')) operation = 'offer';\n    else if (callee.includes('takeAll')) operation = 'takeAll';\n    else if (callee.includes('take')) operation = 'take';\n    else if (callee.includes('end')) operation = 'end';\n    else if (callee.includes('toStream')) operation = 'toStream';\n    else operation = 'create';\n  } else if (callee.startsWith('SubscriptionRef.')) {\n    primitive = 'subscriptionRef';\n    if (callee.includes('changes')) operation = 'changes';\n    else if (callee.includes('get')) operation = 'get';\n    else if (callee.includes('set')) operation = 'set';\n    else if (callee.includes('update')) operation = 'update';\n    else operation = 'create';\n  } else if (callee.includes('makeLatch') || callee.includes('Latch.')) {\n    primitive = 'latch';\n    if (callee.includes('open')) operation = 'open';\n    else if (callee.includes('close')) operation = 'close';\n    else if (callee.includes('await') || callee.includes('whenOpen')) operation = 'await';\n    else operation = 'create';\n  } else if (callee.startsWith('FiberHandle.')) {\n    primitive = 'fiberHandle';\n    if (callee.includes('run')) operation = 'run';\n    else if (callee.includes('await')) operation = 'await';\n    else operation = 'create';\n  } else if (callee.startsWith('FiberSet.')) {\n    primitive = 'fiberSet';\n    if (callee.includes('run')) operation = 'run';\n    else if (callee.includes('join')) operation = 'await';\n    else operation = 'create';\n  } else if (callee.startsWith('FiberMap.')) {\n    primitive = 'fiberMap';\n    if (callee.includes('run')) operation = 'run';\n    else if (callee.includes('join')) operation = 'await';\n    else operation = 'create';\n  } else if (callee.startsWith('RateLimiter.')) {\n    primitive = 'rateLimiter';\n    if (callee.includes('withCost')) operation = 'withPermit';\n    else operation = 'create';\n  } else if (callee.startsWith('ScopedCache.')) {\n    primitive = 'scopedCache';\n    if (callee.includes('make') || callee.includes('Make')) operation = 'create';\n    else if (callee.includes('get') && !callee.includes('getOrElse')) operation = 'get';\n    else if (callee.includes('getOrElse')) operation = 'get';\n    else if (callee.includes('set') || callee.includes('Set')) operation = 'set';\n    else if (callee.includes('invalidate')) operation = 'invalidate';\n    else if (callee.includes('contains')) operation = 'contains';\n    else operation = 'create';\n  } else if (callee.startsWith('Cache.')) {\n    primitive = 'cache';\n    if (callee.includes('make') || callee.includes('Make')) operation = 'create';\n    else if (callee.includes('get') && !callee.includes('getOrElse')) operation = 'get';\n    else if (callee.includes('getOrElse')) operation = 'get';\n    else if (callee.includes('set') || callee.includes('Set')) operation = 'set';\n    else if (callee.includes('invalidate')) operation = 'invalidate';\n    else if (callee.includes('contains')) operation = 'contains';\n    else operation = 'create';\n  } else if (callee.startsWith('Reloadable.') || callee.includes('.Reloadable.')) {\n    primitive = 'reloadable';\n    if (callee.includes('make') || callee.includes('Make')) operation = 'create';\n    else if (callee.includes('get') && !callee.includes('reload')) operation = 'get';\n    else if (callee.includes('reload')) operation = 'reload';\n    else operation = 'create';\n  } else if (callee.startsWith('RcMap.') || callee.includes('.RcMap.')) {\n    primitive = 'rcMap';\n    if (callee.includes('make') || callee.includes('Make')) operation = 'create';\n    else if (callee.includes('get')) operation = 'get';\n    else if (callee.includes('set') || callee.includes('Set')) operation = 'set';\n    else if (callee.includes('update')) operation = 'update';\n    else operation = 'create';\n  } else if (callee.startsWith('RcRef.') || callee.includes('.RcRef.')) {\n    primitive = 'rcRef';\n    if (callee.includes('make') || callee.includes('Make')) operation = 'create';\n    else if (callee.includes('get')) operation = 'get';\n    else if (callee.includes('set') || callee.includes('Set')) operation = 'set';\n    else if (callee.includes('update')) operation = 'update';\n    else operation = 'create';\n  }\n\n  const args = call.getArguments();\n  if (args.length > 0 && strategy === 'bounded') {\n    const first = args[0];\n    if (first?.getKind() === SyntaxKind.NumericLiteral) {\n      capacity = Number.parseInt((first as NumericLiteral).getText(), 10);\n    }\n  }\n  if (primitive === 'semaphore' && (operation === 'take' || operation === 'release') && args.length > 0 && args[0]) {\n    permitCount = getNumericLiteralFromNode(args[0]);\n  }\n\n  // Extract lifecycle options for FiberHandle.run({ onlyIfMissing: true })\n  let lifecycleOptions: Record<string, unknown> | undefined;\n  if (primitive === 'fiberHandle' && operation === 'run') {\n    for (const arg of args) {\n      const text = arg.getText();\n      if (text.includes('onlyIfMissing')) {\n        lifecycleOptions = { onlyIfMissing: text.includes('true') };\n      }\n    }\n  }\n\n  // Mailbox.toStream and SubscriptionRef.changes produce stream nodes\n  if (\n    (primitive === 'mailbox' && operation === 'toStream') ||\n    (primitive === 'subscriptionRef' && operation === 'changes')\n  ) {\n    const constructorType =\n      primitive === 'mailbox' ? ('fromMailbox' as const) : ('fromSubscriptionRef' as const);\n    const innerPrimNode = {\n      id: generateId(),\n      type: 'concurrency-primitive' as const,\n      primitive,\n      operation,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    const streamNode = {\n      id: generateId(),\n      type: 'stream' as const,\n      source: {\n        ...innerPrimNode,\n        displayName: computeDisplayName(innerPrimNode),\n        semanticRole: computeSemanticRole(innerPrimNode),\n      },\n      pipeline: [],\n      constructorType,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    } as StaticStreamNode;\n    return Effect.succeed({\n      ...streamNode,\n      displayName: computeDisplayName(streamNode),\n      semanticRole: computeSemanticRole(streamNode),\n    });\n  }\n\n  const concurrencyNode: StaticConcurrencyPrimitiveNode = {\n    id: generateId(),\n    type: 'concurrency-primitive',\n    primitive,\n    operation,\n    strategy,\n    capacity,\n    ...(permitCount !== undefined ? { permitCount } : {}),\n    ...(lifecycleOptions ? { lifecycleOptions } : {}),\n    location: extractLocation(call, filePath, opts.includeLocations ?? false),\n  };\n  return Effect.succeed({\n    ...concurrencyNode,\n    displayName: computeDisplayName(concurrencyNode),\n    semanticRole: computeSemanticRole(concurrencyNode),\n  });\n}\n\n/** Parse fiber operations (Effect.fork, Fiber.join, etc.) - GAP 1 */\nexport function analyzeFiberCall(\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticFiberNode, AnalysisError> {\n  return Effect.gen(function* () {\n    const args = call.getArguments();\n    const { SyntaxKind } = loadTsMorph();\n    let operation: StaticFiberNode['operation'] = 'fork';\n    let isScoped = false;\n    let isDaemon = false;\n    let fiberSource: StaticFlowNode | undefined;\n    let joinPoint: string | undefined;\n\n    if (callee.startsWith('Fiber.')) {\n      if (callee.includes('awaitAll')) operation = 'awaitAll';\n      else if (callee.includes('join')) operation = 'join';\n      else if (callee.includes('await')) operation = 'await';\n      else if (callee.includes('interruptFork')) operation = 'interruptFork';\n      else if (callee.includes('interrupt')) operation = 'interrupt';\n      else if (callee.includes('poll')) operation = 'poll';\n      else if (callee.includes('status')) operation = 'status';\n      else if (callee.includes('all')) operation = 'all';\n      else if (callee.includes('children')) operation = 'children';\n      else if (callee.includes('dump')) operation = 'dump';\n      else if (callee.includes('scoped')) { operation = 'scoped'; isScoped = true; }\n      else if (callee.includes('inheritAll')) operation = 'inheritAll';\n      else if (callee.includes('mapFiber')) operation = 'mapFiber';\n      else if (callee.includes('mapEffect')) operation = 'mapEffect';\n      else if (callee.includes('map')) operation = 'map';\n      else if (callee.includes('roots')) operation = 'roots';\n      else if (callee.includes('getCurrentFiber')) operation = 'getCurrentFiber';\n    } else if (callee.includes('forkWithErrorHandler')) {\n      operation = 'forkWithErrorHandler';\n    } else if (callee.includes('forkAll')) {\n      operation = 'forkAll';\n    } else if (callee.includes('forkIn')) {\n      operation = 'forkIn';\n    } else if (callee.includes('fork')) {\n      if (callee.includes('forkDaemon')) {\n        operation = 'forkDaemon';\n        isDaemon = true;\n      } else if (callee.includes('forkScoped')) {\n        operation = 'forkScoped';\n        isScoped = true;\n      } else {\n        operation = 'fork';\n      }\n    }\n\n    if (\n      (operation === 'fork' ||\n        operation === 'forkScoped' ||\n        operation === 'forkDaemon' ||\n        operation === 'forkAll' ||\n        operation === 'forkIn' ||\n        operation === 'forkWithErrorHandler') &&\n      args.length > 0 &&\n      args[0]\n    ) {\n      fiberSource = yield* deps.analyzeEffectExpression(\n        args[0],\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n    }\n\n    if (\n      (operation === 'join' || operation === 'await' || operation === 'interrupt' || operation === 'interruptFork') &&\n      args.length > 0 &&\n      args[0]\n    ) {\n      const firstArg = args[0];\n      if (firstArg.getKind() === SyntaxKind.Identifier) {\n        joinPoint = firstArg.getText();\n      }\n    }\n\n    // Determine scope context: 'safe' when fork is scoped or inside Effect.scoped/Scope.make\n    let scopeContext: string | undefined;\n    if (isScoped) {\n      scopeContext = 'safe';\n    } else {\n      // Walk up AST to check if inside Effect.scoped\n      let parent = call.getParent();\n      while (parent) {\n        const parentText = parent.getText?.();\n        if (parentText && (parentText.includes('Effect.scoped') || parentText.includes('Scope.make'))) {\n          scopeContext = 'safe';\n          break;\n        }\n        parent = parent.getParent();\n        // Don't walk too far\n        if (parent && parent === sourceFile) break;\n      }\n    }\n\n    const fiberNode: StaticFiberNode = {\n      id: generateId(),\n      type: 'fiber',\n      operation,\n      fiberSource,\n      isScoped,\n      isDaemon,\n      ...(joinPoint ? { joinPoint } : {}),\n      ...(scopeContext ? { scopeContext } : {}),\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...fiberNode,\n      displayName: computeDisplayName(fiberNode),\n      semanticRole: computeSemanticRole(fiberNode),\n    };\n  });\n}\n\n/** Parse interruption operations (interruptible, uninterruptible, onInterrupt, etc.) */\nexport function analyzeInterruptionCall(\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticInterruptionNode, AnalysisError> {\n  return Effect.gen(function* () {\n    const args = call.getArguments();\n    const { SyntaxKind } = loadTsMorph();\n\n    let interruptionType: StaticInterruptionNode['interruptionType'];\n    if (callee.includes('uninterruptibleMask')) interruptionType = 'uninterruptibleMask';\n    else if (callee.includes('interruptibleMask')) interruptionType = 'interruptibleMask';\n    else if (callee.includes('uninterruptible')) interruptionType = 'uninterruptible';\n    else if (callee.includes('interruptible')) interruptionType = 'interruptible';\n    else if (callee.includes('onInterrupt')) interruptionType = 'onInterrupt';\n    else if (callee.includes('disconnect')) interruptionType = 'disconnect';\n    else if (callee.includes('allowInterrupt')) interruptionType = 'allowInterrupt';\n    else if (callee.includes('interruptWith')) interruptionType = 'interruptWith';\n    else interruptionType = 'interrupt';\n\n    let source: StaticFlowNode | undefined;\n    let handler: StaticFlowNode | undefined;\n\n    // Method call form: effect.pipe(Effect.interruptible) or effect.interruptible\n    const expr = call.getExpression();\n    if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n      const propAccess = expr as PropertyAccessExpression;\n      source = yield* deps.analyzeEffectExpression(propAccess.getExpression(), sourceFile, filePath, opts, warnings, stats);\n      if (args.length > 0 && args[0]) {\n        handler = yield* deps.analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n      }\n    } else if (args.length > 0 && args[0]) {\n      source = yield* deps.analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n      if (args.length > 1 && args[1]) {\n        handler = yield* deps.analyzeEffectExpression(args[1], sourceFile, filePath, opts, warnings, stats);\n      }\n    }\n\n    stats.interruptionCount++;\n\n    const interruptionNode: StaticInterruptionNode = {\n      id: generateId(),\n      type: 'interruption',\n      interruptionType,\n      source,\n      handler,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...interruptionNode,\n      displayName: computeDisplayName(interruptionNode),\n      semanticRole: computeSemanticRole(interruptionNode),\n    };\n  });\n}\n","/**\n * Parallel and Race call analyzers (Effect.all, Effect.allPar, Effect.race, ...).\n *\n * Both recurse via `deps.analyzeEffectExpression` into each branch / child effect.\n *\n * Extracted from effect-analysis.ts via the strangler-fig DI pattern.\n * Behaviour is preserved exactly.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  ArrayLiteralExpression,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticParallelNode,\n  StaticRaceNode,\n  ConcurrencyMode,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport { parseEffectAllOptions } from './analysis-classifiers';\nimport type { AnalysisContext } from './analysis-context';\n\nexport const analyzeParallelCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n  serviceScope?: Map<string, string>,\n): Effect.Effect<StaticParallelNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    const children: StaticFlowNode[] = [];\n    const { SyntaxKind } = loadTsMorph();\n\n    // First argument: array of effects or object with effect properties\n    if (args.length > 0 && args[0]) {\n      const firstArg = args[0];\n\n      if (firstArg.getKind() === SyntaxKind.ArrayLiteralExpression) {\n        const elements = (firstArg as ArrayLiteralExpression).getElements();\n        for (const elem of elements) {\n          const analyzed = yield* deps.analyzeEffectExpression(\n            elem,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n            serviceScope,\n          );\n          children.push(analyzed);\n        }\n      } else if (firstArg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n        const props = (firstArg as ObjectLiteralExpression).getProperties();\n        for (const prop of props) {\n          if (prop.getKind() === SyntaxKind.PropertyAssignment) {\n            const initializer = (prop as PropertyAssignment).getInitializer();\n            if (initializer) {\n              const analyzed = yield* deps.analyzeEffectExpression(\n                initializer,\n                sourceFile,\n                filePath,\n                opts,\n                warnings,\n                stats,\n                serviceScope,\n              );\n              children.push(analyzed);\n            }\n          }\n        }\n      }\n    }\n\n    // Second argument: options { concurrency, batching, discard } (GAP 18)\n    let concurrency: ConcurrencyMode | undefined;\n    let batching: boolean | undefined;\n    let discard: boolean | undefined;\n    if (args.length > 1 && args[1]?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n      const parsed = parseEffectAllOptions(args[1] as ObjectLiteralExpression);\n      concurrency = parsed.concurrency;\n      batching = parsed.batching;\n      discard = parsed.discard;\n    }\n\n    const mode = callee.includes('Par') ? 'parallel' : 'sequential';\n    if (concurrency === undefined) {\n      concurrency = mode === 'parallel' ? 'unbounded' : 'sequential';\n    }\n\n    stats.parallelCount++;\n\n    const branchLabels = children.map((child) => computeDisplayName(child));\n    const parallelNode: StaticParallelNode = {\n      id: generateId(),\n      type: 'parallel',\n      callee,\n      mode,\n      children,\n      concurrency,\n      batching,\n      discard,\n      branchLabels,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...parallelNode,\n      displayName: computeDisplayName(parallelNode),\n      semanticRole: computeSemanticRole(parallelNode),\n    };\n  });\n\nexport const analyzeRaceCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticRaceNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    const children: StaticFlowNode[] = [];\n\n    for (const arg of args) {\n      if (arg) {\n        const analyzed = yield* deps.analyzeEffectExpression(\n          arg,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n        children.push(analyzed);\n      }\n    }\n\n    stats.raceCount++;\n\n    const raceLabels = children.map((child) => computeDisplayName(child));\n    const raceNode: StaticRaceNode = {\n      id: generateId(),\n      type: 'race',\n      callee,\n      children,\n      raceLabels,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...raceNode,\n      displayName: computeDisplayName(raceNode),\n      semanticRole: computeSemanticRole(raceNode),\n    };\n  });\n","/**\n * Error-handler call analyzer (catch/catchTag/catchTags/orElse/orDie/match/...).\n *\n * Recurses via `deps.analyzeEffectExpression` into the source effect and the\n * handler. Tag/tags extraction reads the first/handler argument literally.\n *\n * Extracted from effect-analysis.ts via the strangler-fig DI pattern.\n * Behaviour is preserved exactly.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  PropertyAccessExpression,\n  StringLiteral,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n  MethodDeclaration,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticErrorHandlerNode,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport type { AnalysisContext } from './analysis-context';\n\n/**\n * Which handler a callee names. Ordered longest-first: the chain is substring\n * based, so `catchReason` must be tested before `catchCause` and `catch`, or\n * Effect 4's selective catches all read as catch-everything.\n */\nexport const classifyErrorHandlerName = (\n  callee: string,\n): StaticErrorHandlerNode['handlerType'] => {\n  if (callee.includes('catchCauseFilter')) {\n    return 'catchCauseFilter';\n  }\n  if (callee.includes('catchCauseIf')) {\n    return 'catchCauseIf';\n  }\n  if (callee.includes('catchNoSuchElement')) {\n    return 'catchNoSuchElement';\n  }\n  if (callee.includes('catchReasons')) {\n    return 'catchReasons';\n  }\n  if (callee.includes('catchReason')) {\n    return 'catchReason';\n  }\n  if (callee.includes('catchFilter')) {\n    return 'catchFilter';\n  }\n  if (callee.includes('catchEager')) {\n    return 'catchEager';\n  }\n  if (callee.includes('catchCause')) {\n    return 'catchCause';\n  }\n  if (callee.includes('catchSomeCause')) {\n    return 'catchSomeCause';\n  }\n  if (callee.includes('catchSomeDefect')) {\n    return 'catchSomeDefect';\n  }\n  if (callee.includes('catchDefect')) {\n    return 'catchDefect';\n  }\n  if (callee.includes('catchTags')) {\n    return 'catchTags';\n  }\n  if (callee.includes('catchIf')) {\n    return 'catchIf';\n  }\n  if (callee.includes('catchSome')) {\n    return 'catchSome';\n  }\n  if (callee.includes('catchTag')) {\n    return 'catchTag';\n  }\n  if (callee.includes('catch')) {\n    return 'catch';\n  }\n  if (callee.includes('orElseFail')) {\n    return 'orElseFail';\n  }\n  if (callee.includes('orElseSucceed')) {\n    return 'orElseSucceed';\n  }\n  if (callee.includes('orElse')) {\n    return 'orElse';\n  }\n  if (callee.includes('orDieWith')) {\n    return 'orDieWith';\n  }\n  if (callee.includes('orDie')) {\n    return 'orDie';\n  }\n  if (callee.includes('flip')) {\n    return 'flip';\n  }\n  if (callee.includes('mapErrorCause')) {\n    return 'mapErrorCause';\n  }\n  if (callee.includes('mapBoth')) {\n    return 'mapBoth';\n  }\n  if (callee.includes('mapError')) {\n    return 'mapError';\n  }\n  if (callee.includes('unsandbox')) {\n    return 'unsandbox';\n  }\n  if (callee.includes('sandbox')) {\n    return 'sandbox';\n  }\n  if (callee.includes('parallelErrors')) {\n    return 'parallelErrors';\n  }\n  if (callee.includes('filterOrDieMessage')) {\n    return 'filterOrDieMessage';\n  }\n  if (callee.includes('filterOrDie')) {\n    return 'filterOrDie';\n  }\n  if (callee.includes('filterOrElse')) {\n    return 'filterOrElse';\n  }\n  if (callee.includes('filterOrFail')) {\n    return 'filterOrFail';\n  }\n  if (callee.includes('matchCauseEffect')) {\n    return 'matchCauseEffect';\n  }\n  if (callee.includes('matchCause')) {\n    return 'matchCause';\n  }\n  if (callee.includes('matchEffect')) {\n    return 'matchEffect';\n  }\n  if (callee.includes('match')) {\n    return 'match';\n  }\n  if (callee.includes('firstSuccessOf')) {\n    return 'firstSuccessOf';\n  }\n  if (callee.includes('ignoreLogged')) {\n    return 'ignoreLogged';\n  }\n  if (callee.includes('ignore')) {\n    return 'ignore';\n  }\n  if (callee.includes('eventually')) {\n    return 'eventually';\n  }\n  return 'catch';\n};\n\nexport const analyzeErrorHandlerCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticErrorHandlerNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n\n    const handlerType = classifyErrorHandlerName(callee);\n\n    // For methods that are called as effect.pipe(Effect.catch(handler))\n    // we need to find the source effect differently\n    let source: StaticFlowNode;\n    let handler: StaticFlowNode | undefined;\n\n    // Check if this is a method call on an effect (e.g., effect.catch(fn))\n    const expr = call.getExpression();\n    if (expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n      // This is effect.method() - the source is the object of the property access\n      const propAccess = expr as PropertyAccessExpression;\n      const exprSource = propAccess.getExpression();\n      source = yield* deps.analyzeEffectExpression(\n        exprSource,\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n\n      // Handler is the first argument\n      if (args.length > 0 && args[0]) {\n        handler = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      }\n    } else {\n      // This is Effect.method(effect, handler) - effect is first argument\n      if (args.length > 0 && args[0]) {\n        source = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      } else {\n        source = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Could not determine source effect',\n        };\n      }\n\n      if (args.length > 1 && args[1]) {\n        handler = yield* deps.analyzeEffectExpression(\n          args[1],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      }\n    }\n\n    stats.errorHandlerCount++;\n\n    // For catchTags (object form), extract the tag keys from the object literal\n    let errorTag: string | undefined;\n    let errorTags: readonly string[] | undefined;\n    if (handlerType === 'catchTag') {\n      // catchTag(\"TagName\", handler) — first arg is the tag string\n      const tagArg = args[0];\n      if (tagArg?.getKind() === loadTsMorph().SyntaxKind.StringLiteral) {\n        errorTag = (tagArg as StringLiteral).getLiteralValue();\n      }\n    } else if (handlerType === 'catchTags') {\n      // catchTags({ NotFound: handler, DatabaseError: handler })\n      // Find the object literal arg (may be args[0] for Effect.catchTags(eff, obj) or handler arg)\n      const objArg = [...args].find(\n        (a) => a?.getKind() === loadTsMorph().SyntaxKind.ObjectLiteralExpression,\n      );\n      if (objArg !== undefined) {\n        const props = (objArg as ObjectLiteralExpression).getProperties();\n        errorTags = props\n          .filter(\n            (p) =>\n              p.getKind() === loadTsMorph().SyntaxKind.PropertyAssignment ||\n              p.getKind() === loadTsMorph().SyntaxKind.MethodDeclaration,\n          )\n          .map((p) => {\n            if (p.getKind() === loadTsMorph().SyntaxKind.PropertyAssignment) {\n              return (p as PropertyAssignment).getName();\n            }\n            return (p as MethodDeclaration).getName();\n          });\n      }\n    }\n\n    const handlerNode: StaticErrorHandlerNode = {\n      id: generateId(),\n      type: 'error-handler',\n      handlerType,\n      source,\n      handler,\n      errorTag,\n      errorTags,\n      errorEdgeLabel: errorTag\n        ? `on ${errorTag}`\n        : errorTags && errorTags.length > 0\n          ? `on ${errorTags.join(' | ')}`\n          : 'on error',\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...handlerNode,\n      displayName: computeDisplayName(handlerNode),\n      semanticRole: computeSemanticRole(handlerNode),\n    };\n  });\n","/**\n * Resource (acquire/release) call analyzer.\n *\n * Covers Effect.acquireRelease, acquireUseRelease, ensuring, onExit, addFinalizer\n * and related scoped resource patterns. Recurses via `deps.analyzeEffectExpression`\n * for each effect argument.\n *\n * Extracted from effect-analysis.ts via the strangler-fig DI pattern.\n * Behaviour is preserved exactly.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  PropertyAccessExpression,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticResourceNode,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport type { AnalysisContext } from './analysis-context';\n\nexport const analyzeResourceCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticResourceNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    const resourceOperation = (/([A-Za-z_$][\\w$]*)$/.exec(callee))?.[1] ?? callee;\n    let acquire: StaticFlowNode;\n    let release: StaticFlowNode;\n    let useEffect: StaticFlowNode | undefined;\n\n    if (resourceOperation.startsWith('acquireUseRelease')) {\n      // acquireUseRelease / acquireUseReleaseInterruptible (acquire, use, release) - 3-arg form\n      if (args.length >= 3 && args[0] && args[2]) {\n        acquire = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n        release = yield* deps.analyzeEffectExpression(\n          args[2],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n        if (args[1]) {\n          useEffect = yield* deps.analyzeEffectExpression(\n            args[1],\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n        }\n      } else {\n        acquire = { id: generateId(), type: 'unknown', reason: 'Missing acquire' };\n        release = { id: generateId(), type: 'unknown', reason: 'Missing release' };\n      }\n    } else if (resourceOperation.startsWith('acquireRelease')) {\n      // acquireRelease / acquireReleaseInterruptible (acquire, release) - 2-arg form\n      if (args.length >= 2 && args[0] && args[1]) {\n        acquire = yield* deps.analyzeEffectExpression(\n          args[0],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n        release = yield* deps.analyzeEffectExpression(\n          args[1],\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      } else {\n        acquire = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Missing acquire',\n        };\n        release = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Missing release',\n        };\n      }\n    } else if (\n      resourceOperation === 'addFinalizer' ||\n      resourceOperation === 'onExit' ||\n      resourceOperation === 'onError' ||\n      resourceOperation === 'parallelFinalizers' ||\n      resourceOperation === 'sequentialFinalizers' ||\n      resourceOperation === 'finalizersMask' ||\n      resourceOperation === 'using' ||\n      resourceOperation === 'withEarlyRelease'\n    ) {\n      // Finalizer/cleanup patterns - acquire is the surrounding effect (method chain) or unknown\n      const expr = call.getExpression();\n      if (expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression) {\n        const propAccess = expr as PropertyAccessExpression;\n        acquire = yield* deps.analyzeEffectExpression(\n          propAccess.getExpression(),\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      } else {\n        acquire = { id: generateId(), type: 'unknown', reason: 'Scoped acquire' };\n      }\n      release =\n        args.length > 0 && args[0]\n          ? yield* deps.analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats)\n          : { id: generateId(), type: 'unknown', reason: 'Missing finalizer' };\n    } else if (resourceOperation === 'ensuring') {\n      // Effect.ensuring(effect, cleanup)\n      const expr = call.getExpression();\n      if (\n        expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression\n      ) {\n        const propAccess = expr as PropertyAccessExpression;\n        const exprSource = propAccess.getExpression();\n        acquire = yield* deps.analyzeEffectExpression(\n          exprSource,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n        release =\n          args.length > 0 && args[0]\n            ? yield* deps.analyzeEffectExpression(\n                args[0],\n                sourceFile,\n                filePath,\n                opts,\n                warnings,\n                stats,\n              )\n            : { id: generateId(), type: 'unknown', reason: 'Missing cleanup' };\n      } else {\n        acquire =\n          args.length > 0 && args[0]\n            ? yield* deps.analyzeEffectExpression(\n                args[0],\n                sourceFile,\n                filePath,\n                opts,\n                warnings,\n                stats,\n              )\n            : { id: generateId(), type: 'unknown', reason: 'Missing effect' };\n        release =\n          args.length > 1 && args[1]\n            ? yield* deps.analyzeEffectExpression(\n                args[1],\n                sourceFile,\n                filePath,\n                opts,\n                warnings,\n                stats,\n              )\n            : { id: generateId(), type: 'unknown', reason: 'Missing cleanup' };\n      }\n    } else {\n      acquire = {\n        id: generateId(),\n        type: 'unknown',\n        reason: 'Unknown resource pattern',\n      };\n      release = {\n        id: generateId(),\n        type: 'unknown',\n        reason: 'Unknown resource pattern',\n      };\n    }\n\n    stats.resourceCount++;\n\n    const resourceNode: StaticResourceNode = {\n      id: generateId(),\n      type: 'resource',\n      acquire,\n      release,\n      use: useEffect,\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...resourceNode,\n      displayName: computeDisplayName(resourceNode),\n      semanticRole: computeSemanticRole(resourceNode),\n    };\n  });\n","/**\n * Control-flow call analyzers: conditional, loop, match, cause, exit, transform.\n *\n * Each takes `deps.analyzeEffectExpression` so it can recurse into branches /\n * bodies / handlers / sources without depending on the parent module.\n *\n * Extracted from effect-analysis.ts via the strangler-fig DI pattern.\n * Behaviour is preserved exactly.\n */\n\nimport { Effect } from 'effect';\nimport type {\n  CallExpression,\n  SourceFile,\n  PropertyAccessExpression,\n  ObjectLiteralExpression,\n  PropertyAssignment,\n  ArrowFunction,\n  FunctionExpression,\n} from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\nimport type {\n  StaticFlowNode,\n  StaticConditionalNode,\n  StaticLoopNode,\n  StaticMatchNode,\n  StaticCauseNode,\n  StaticExitNode,\n  StaticTransformNode,\n  AnalyzerOptions,\n  AnalysisWarning,\n  AnalysisStats,\n  AnalysisError,\n} from './types';\nimport {\n  generateId,\n  extractLocation,\n  computeDisplayName,\n  computeSemanticRole,\n} from './analysis-utils';\nimport {\n  MATCH_OP_MAP,\n  EXHAUSTIVE_OPS,\n  CAUSE_OP_MAP,\n  CAUSE_CONSTRUCTORS,\n  EXIT_OP_MAP,\n  EXIT_CONSTRUCTORS,\n  TRANSFORM_OPS,\n  EFFECTFUL_TRANSFORMS,\n} from './analysis-patterns';\nimport {\n  buildCallbackSummaryNodes,\n  buildPureCallbackSummaryNodes,\n  summarizeLoopCallbackSource,\n} from './callback-summary';\nimport type { AnalysisContext } from './analysis-context';\n\nexport const analyzeConditionalCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticConditionalNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n\n    let conditionalType: StaticConditionalNode['conditionalType'];\n    if (callee.includes('.if') || callee === 'if') {\n      conditionalType = 'if';\n    } else if (callee.includes('whenEffect')) {\n      conditionalType = 'whenEffect';\n    } else if (callee.includes('whenFiberRef')) {\n      conditionalType = 'whenFiberRef';\n    } else if (callee.includes('whenRef')) {\n      conditionalType = 'whenRef';\n    } else if (callee.includes('.when') || callee === 'when') {\n      conditionalType = 'when';\n    } else if (callee.includes('unlessEffect')) {\n      conditionalType = 'unlessEffect';\n    } else if (callee.includes('.unless') || callee === 'unless') {\n      conditionalType = 'unless';\n    } else if (callee.includes('.option') || callee === 'option') {\n      conditionalType = 'option';\n    } else if (callee.includes('.either') || callee === 'either') {\n      conditionalType = 'either';\n    } else if (callee.includes('.exit') || callee === 'exit') {\n      conditionalType = 'exit';\n    } else if (callee.includes('liftPredicate')) {\n      conditionalType = 'liftPredicate';\n    } else {\n      conditionalType = 'unless';\n    }\n\n    let condition = '<dynamic>';\n    let onTrue: StaticFlowNode | undefined;\n    let onFalse: StaticFlowNode | undefined;\n\n    // Different call patterns for if vs when/unless\n    if (conditionalType === 'if') {\n      // Effect.if(condition, { onTrue, onFalse })\n      if (args.length > 0 && args[0]) {\n        condition = args[0].getText();\n      }\n\n      if (args.length > 1 && args[1]) {\n        const secondArg = args[1];\n        const { SyntaxKind } = loadTsMorph();\n\n        if (secondArg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n          const props = (secondArg as ObjectLiteralExpression).getProperties();\n          for (const prop of props) {\n            if (prop.getKind() === SyntaxKind.PropertyAssignment) {\n              const propAssign = prop as PropertyAssignment;\n              const name = propAssign.getName();\n              const init = propAssign.getInitializer();\n\n              if (init) {\n                if (name === 'onTrue') {\n                  onTrue = yield* deps.analyzeEffectExpression(\n                    init,\n                    sourceFile,\n                    filePath,\n                    opts,\n                    warnings,\n                    stats,\n                  );\n                } else if (name === 'onFalse') {\n                  onFalse = yield* deps.analyzeEffectExpression(\n                    init,\n                    sourceFile,\n                    filePath,\n                    opts,\n                    warnings,\n                    stats,\n                  );\n                }\n              }\n            }\n          }\n        }\n      }\n    } else {\n      // when/unless: effect.pipe(Effect.when(condition))\n      const expr = call.getExpression();\n      if (\n        expr.getKind() === loadTsMorph().SyntaxKind.PropertyAccessExpression\n      ) {\n        const propAccess = expr as PropertyAccessExpression;\n        const exprSource = propAccess.getExpression();\n\n        // The source effect is the object being piped\n        if (!onTrue) {\n          onTrue = yield* deps.analyzeEffectExpression(\n            exprSource,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n        }\n      }\n\n      if (args.length > 0 && args[0]) {\n        condition = args[0].getText();\n      }\n    }\n\n    if (!onTrue) {\n      onTrue = {\n        id: generateId(),\n        type: 'unknown',\n        reason: 'Could not determine true branch',\n      };\n    }\n\n    stats.conditionalCount++;\n\n    const truncatedCondition = condition.length <= 30 ? condition : `${condition.slice(0, 30)}…`;\n    const conditionalNode: StaticConditionalNode = {\n      id: generateId(),\n      type: 'conditional',\n      conditionalType,\n      condition,\n      onTrue,\n      onFalse,\n      conditionLabel: truncatedCondition,\n      trueEdgeLabel: 'true',\n      falseEdgeLabel: 'false',\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...conditionalNode,\n      displayName: computeDisplayName(conditionalNode),\n      semanticRole: computeSemanticRole(conditionalNode),\n    };\n  });\n\nexport const analyzeLoopCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticLoopNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    const { SyntaxKind } = loadTsMorph();\n\n    const loopType: StaticLoopNode['loopType'] =\n      callee.includes('forEach') ? 'forEach' :\n      callee.includes('filterMap') ? 'filterMap' :\n      callee.includes('filter') ? 'filter' :\n      callee.includes('partition') ? 'partition' :\n      callee.includes('reduce') ? 'reduce' :\n      callee.includes('validateAll') || callee.includes('validateFirst') || callee.includes('validateWith') ? 'validate' :\n      callee.includes('replicate') ? 'replicate' :\n      callee.includes('dropUntil') ? 'dropUntil' :\n      callee.includes('dropWhile') ? 'dropWhile' :\n      callee.includes('takeUntil') ? 'takeUntil' :\n      callee.includes('takeWhile') ? 'takeWhile' :\n      callee.includes('every') ? 'every' :\n      callee.includes('exists') ? 'exists' :\n      callee.includes('findFirst') ? 'findFirst' :\n      callee.includes('head') ? 'head' :\n      callee.includes('mergeAll') ? 'mergeAll' :\n      'loop';\n\n    // reduce/reduceRight/reduceEffect(iterable, initial, reducer) use body at index 2;\n    // others (forEach, filter, ...) at index 1\n    const bodyArgIndex =\n      loopType === 'reduce' ||\n      callee.includes('reduceRight') ||\n      callee.includes('reduceWhile') ||\n      callee.includes('reduceEffect')\n        ? (args.length >= 3 ? 2 : 1)\n        : 1;\n\n    let iterSource: string | undefined;\n    let body: StaticFlowNode;\n    let callbackBody: readonly StaticFlowNode[] | undefined;\n\n    if (args.length > 0 && args[0]) {\n      const rawSource = args[0].getText();\n      iterSource = rawSource.length > 30 ? rawSource.slice(0, 30) + '…' : rawSource;\n    }\n\n    if (args.length > bodyArgIndex && args[bodyArgIndex]) {\n      const bodyArg = args[bodyArgIndex];\n      const isFn =\n        bodyArg.getKind() === SyntaxKind.ArrowFunction ||\n        bodyArg.getKind() === SyntaxKind.FunctionExpression;\n      if (isFn) {\n        const fn = bodyArg as ArrowFunction | FunctionExpression;\n        const effectfulSummary = buildCallbackSummaryNodes(\n          fn,\n          filePath,\n          opts.includeLocations ?? false,\n        );\n        const pureSummary = buildPureCallbackSummaryNodes(\n          fn,\n          filePath,\n          opts.includeLocations ?? false,\n        );\n        callbackBody = effectfulSummary ?? pureSummary;\n        body =\n          callbackBody?.length === 1\n            ? callbackBody[0]!\n            : {\n                id: generateId(),\n                type: 'opaque',\n                reason: 'callback-body',\n                sourceText: summarizeLoopCallbackSource(loopType, callbackBody ?? []),\n                location: extractLocation(bodyArg, filePath, opts.includeLocations ?? false),\n              };\n      } else {\n        body = yield* deps.analyzeEffectExpression(\n          bodyArg,\n          sourceFile,\n          filePath,\n          opts,\n          warnings,\n          stats,\n        );\n      }\n    } else {\n      const predicateArg = args[0];\n      const predicateLikeLoop =\n        loopType === 'exists' ||\n        loopType === 'every' ||\n        loopType === 'findFirst' ||\n        loopType === 'head';\n      if (predicateLikeLoop && predicateArg) {\n        body = {\n          id: generateId(),\n          type: 'opaque',\n          reason: 'predicate',\n          sourceText: predicateArg.getText().slice(0, 100),\n          location: extractLocation(predicateArg, filePath, opts.includeLocations ?? false),\n        };\n      } else {\n        body = {\n          id: generateId(),\n          type: 'unknown',\n          reason: 'Could not determine loop body',\n        };\n      }\n    }\n\n    stats.loopCount++;\n\n    const loopNode: StaticLoopNode = {\n      id: generateId(),\n      type: 'loop',\n      loopType,\n      iterSource,\n      body,\n      ...(callbackBody ? { callbackBody } : {}),\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...loopNode,\n      displayName: computeDisplayName(loopNode),\n      semanticRole: computeSemanticRole(loopNode),\n    };\n  });\n\n/** Analyze Match.type / Match.when / Match.tag / Match.exhaustive etc. */\nexport const analyzeMatchCall = (\n  call: CallExpression,\n  callee: string,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n): StaticMatchNode => {\n  const matchOp: StaticMatchNode['matchOp'] = MATCH_OP_MAP[callee] ?? 'other';\n  const isExhaustive = EXHAUSTIVE_OPS.has(matchOp);\n\n  // Extract tag names for Match.tag(tag, fn), Match.tags({ tag1: fn, tag2: fn })\n  const args = call.getArguments();\n  const matchedTags: string[] = [];\n  if ((matchOp === 'when' || matchOp === 'tag') && args[0]) {\n    const arg0 = args[0].getText().replace(/[\"'`]/g, '').trim();\n    if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(arg0)) matchedTags.push(arg0);\n  }\n  if (matchOp === 'tags' || matchOp === 'tagsExhaustive') {\n    const { SyntaxKind } = loadTsMorph();\n    for (const arg of args) {\n      if (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n        const obj = arg as ObjectLiteralExpression;\n        for (const prop of obj.getProperties()) {\n          const name = prop.getKind() === SyntaxKind.PropertyAssignment\n            ? (prop as PropertyAssignment).getName()\n            : undefined;\n          if (name) matchedTags.push(name.replace(/[\"'`]/g, ''));\n        }\n      }\n    }\n  }\n\n  const matchNode: StaticMatchNode = {\n    id: generateId(),\n    type: 'match',\n    matchOp,\n    isExhaustive,\n    ...(matchedTags.length > 0 ? { matchedTags } : {}),\n    location: extractLocation(call, filePath, opts.includeLocations ?? false),\n  };\n  return {\n    ...matchNode,\n    displayName: computeDisplayName(matchNode),\n    semanticRole: computeSemanticRole(matchNode),\n  };\n};\n\n/** Analyze Cause.fail / die / interrupt / parallel / sequential / failures / etc. */\nexport const analyzeCauseCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticCauseNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const causeOp: StaticCauseNode['causeOp'] = CAUSE_OP_MAP[callee] ?? 'other';\n    const isConstructor = CAUSE_CONSTRUCTORS.has(causeOp);\n    let children: readonly StaticFlowNode[] | undefined;\n    if (causeOp === 'parallel' || causeOp === 'sequential') {\n      const args = call.getArguments();\n      const childNodes: StaticFlowNode[] = [];\n      for (const arg of args) {\n        if (arg) {\n          const child = yield* deps.analyzeEffectExpression(\n            arg,\n            sourceFile,\n            filePath,\n            opts,\n            warnings,\n            stats,\n          );\n          childNodes.push(child);\n        }\n      }\n      if (childNodes.length > 0) children = childNodes;\n    }\n    // Determine causeKind\n    let causeKind: StaticCauseNode['causeKind'];\n    if (causeOp === 'fail') causeKind = 'fail';\n    else if (causeOp === 'die') causeKind = 'die';\n    else if (causeOp === 'interrupt') causeKind = 'interrupt';\n    else if ((causeOp === 'parallel' || causeOp === 'sequential') && children && children.length > 0) {\n      const childKinds = children\n        .filter((c): c is StaticCauseNode => c.type === 'cause')\n        .map((c) => c.causeKind)\n        .filter((k): k is NonNullable<typeof k> => k !== undefined);\n      if (childKinds.length > 0) {\n        causeKind = childKinds.every((k) => k === childKinds[0]) ? childKinds[0] : 'mixed';\n      }\n    }\n\n    const causeNode: StaticCauseNode = {\n      id: generateId(),\n      type: 'cause',\n      causeOp,\n      isConstructor,\n      ...(children ? { children } : {}),\n      ...(causeKind ? { causeKind } : {}),\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...causeNode,\n      displayName: computeDisplayName(causeNode),\n      semanticRole: computeSemanticRole(causeNode),\n    };\n  });\n\n/** Analyze Exit.succeed / fail / die / interrupt / match / isSuccess / etc. */\nexport const analyzeExitCall = (\n  call: CallExpression,\n  callee: string,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n): StaticExitNode => {\n  const exitOp: StaticExitNode['exitOp'] = EXIT_OP_MAP[callee] ?? 'other';\n  const isConstructor = EXIT_CONSTRUCTORS.has(exitOp);\n  const exitNode: StaticExitNode = {\n    id: generateId(),\n    type: 'exit',\n    exitOp,\n    isConstructor,\n    location: extractLocation(call, filePath, opts.includeLocations ?? false),\n  };\n  return {\n    ...exitNode,\n    displayName: computeDisplayName(exitNode),\n    semanticRole: computeSemanticRole(exitNode),\n  };\n};\n\n/** Analyze Effect.map / flatMap / andThen / tap / zip / as / flatten etc. */\nexport const analyzeTransformCall = (\n  deps: AnalysisContext,\n  call: CallExpression,\n  callee: string,\n  sourceFile: SourceFile,\n  filePath: string,\n  opts: Required<AnalyzerOptions>,\n  warnings: AnalysisWarning[],\n  stats: AnalysisStats,\n): Effect.Effect<StaticTransformNode, AnalysisError> =>\n  Effect.gen(function* () {\n    const args = call.getArguments();\n    const transformType: StaticTransformNode['transformType'] =\n      TRANSFORM_OPS[callee] ?? 'other';\n    const isEffectful = EFFECTFUL_TRANSFORMS.has(transformType);\n\n    // For data-last forms (2 args), first arg is the source\n    // For curried forms (1 arg), the source is from the outer pipe\n    let source: StaticFlowNode | undefined;\n    let fn: string | undefined;\n\n    if (args.length >= 2 && args[0]) {\n      source = yield* deps.analyzeEffectExpression(\n        args[0],\n        sourceFile,\n        filePath,\n        opts,\n        warnings,\n        stats,\n      );\n      if (args[1]) {\n        const fnText = args[1].getText();\n        fn = fnText.length <= 120 ? fnText : fnText.slice(0, 120) + '…';\n      }\n    } else if (args.length === 1 && args[0]) {\n      // Curried - single arg is the function\n      const fnText = args[0].getText();\n      fn = fnText.length <= 120 ? fnText : fnText.slice(0, 120) + '…';\n    }\n\n    stats.totalEffects++;\n\n    const transformNode: StaticTransformNode = {\n      id: generateId(),\n      type: 'transform',\n      transformType,\n      isEffectful,\n      ...(source !== undefined ? { source } : {}),\n      ...(fn !== undefined ? { fn } : {}),\n      location: extractLocation(call, filePath, opts.includeLocations ?? false),\n    };\n    return {\n      ...transformNode,\n      displayName: computeDisplayName(transformNode),\n      semanticRole: computeSemanticRole(transformNode),\n    } satisfies StaticTransformNode;\n  });\n","/**\n * Project-wide / Cross-file Analysis (GAP 17)\n *\n * Analyzes a directory of TypeScript files and aggregates results.\n */\n\nimport { Effect } from 'effect';\nimport { readdir, readFile, stat } from 'fs/promises';\nimport { readFileSync } from 'fs';\nimport { join, extname, resolve, basename } from 'path';\nimport type { StaticEffectIR, ProjectServiceMap } from './types';\nimport { loadTsMorph } from './ts-morph-loader';\nimport { buildProjectServiceMap } from './service-registry';\nimport { scanProjectCorpus, type ProjectCorpus } from './project-corpus';\nimport { assessAudit, type AuditAssessment } from './audit-assessment';\nimport {\n  assessIRFidelity,\n  type FidelityFinding,\n} from './fidelity-findings';\nimport {\n  extractProjectArchitecture,\n  type ProjectArchitectureSummary,\n} from './project-architecture';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Per-file failure for project analysis (Gap 3: no silent drops). */\nexport interface ProjectFileFailure {\n  readonly file: string;\n  readonly error: string;\n}\n\nexport interface ProjectAnalysisResult {\n  /** File path -> list of program IRs in that file */\n  readonly byFile: Map<string, readonly StaticEffectIR[]>;\n  /** All programs across the project */\n  readonly allPrograms: readonly StaticEffectIR[];\n  /** Entry points (files that run Effect.runPromise / runSync / NodeRuntime.runMain) - heuristic + package.json */\n  readonly entryPointFiles: string[];\n  /** Total file count discovered */\n  readonly fileCount: number;\n  /** Files that failed to analyze (error message included) - Gap 3 */\n  readonly failedFiles: readonly ProjectFileFailure[];\n  /** Files that were analyzed but had zero Effect programs */\n  readonly zeroProgramFiles: readonly string[];\n  /** Project-level deduplicated service map (when --service-map is enabled) */\n  readonly serviceMap?: ProjectServiceMap | undefined;\n  /** Project-level runtime architecture summary (when enabled). */\n  readonly architecture?: ProjectArchitectureSummary | undefined;\n}\n\nexport interface AnalyzeProjectOptions {\n  readonly tsconfig?: string | undefined;\n  /** File extensions to discover; default ['.ts', '.tsx']. Include '.js'/.jsx' for best-effort JS (Gap 6). */\n  readonly extensions?: readonly string[] | undefined;\n  readonly maxDepth?: number | undefined;\n  /** When true, include per-file durationMs in outcomes (improve.md §7 optional timing). */\n  readonly includePerFileTiming?: boolean | undefined;\n  /** Optional false-positive review: paths matching any of these (substring or path segment) are excluded from suspiciousZeros (improve.md §5). */\n  readonly excludeFromSuspiciousZeros?: readonly string[] | undefined;\n  /** Optional path to known Effect internals root for per-file analysis (improve.md §1). */\n  readonly knownEffectInternalsRoot?: string | undefined;\n  /** When true, build the deduplicated project-level service map (--service-map). */\n  readonly buildServiceMap?: boolean | undefined;\n  /** When true, build a project-level runtime architecture summary. */\n  readonly buildArchitecture?: boolean | undefined;\n}\n\n/** Per-file outcome for coverage audit. */\nexport interface FileOutcome {\n  readonly file: string;\n  readonly status: 'ok' | 'fail' | 'zero';\n  readonly programCount?: number;\n  readonly error?: string;\n  /** When includePerFileTiming: analysis time in ms (improve.md §7). */\n  readonly durationMs?: number;\n}\n\nexport type ZeroProgramCategory =\n  | 'barrel_or_index'\n  | 'config_or_build'\n  | 'test_or_dtslint'\n  | 'type_only'\n  | 'suspicious'\n  | 'other';\n\nexport interface ZeroProgramClassification {\n  readonly file: string;\n  readonly category: ZeroProgramCategory;\n  readonly importsEffect: boolean;\n}\n\nexport interface ProjectFidelityFinding extends FidelityFinding {\n  readonly file: string;\n  readonly programName: string;\n}\n\n/** Coverage audit: discovered vs analyzed vs failed/zero, with per-file outcomes. */\nexport interface CoverageAuditResult {\n  readonly discovered: number;\n  readonly analyzed: number;\n  readonly zeroPrograms: number;\n  readonly failed: number;\n  readonly outcomes: readonly FileOutcome[];\n  readonly assessment: AuditAssessment;\n  /** unknownCount / totalNodes across all analyzed files (0–1). */\n  readonly unknownNodeRate: number;\n  /** Repo-level aggregate: total node count across all analyzed programs (improve.md §5). */\n  readonly totalNodes: number;\n  /** Repo-level aggregate: unknown node count across all analyzed programs (improve.md §5). */\n  readonly unknownNodes: number;\n  /** Located fidelity evidence across every analyzed program. */\n  readonly fidelityFindings: readonly ProjectFidelityFinding[];\n  /** Files that import from effect/@effect but produced zero programs. */\n  readonly suspiciousZeros: readonly string[];\n  /** Per-category zero-program counts for triage. */\n  readonly zeroProgramCategoryCounts: Readonly<Record<ZeroProgramCategory, number>>;\n  /** Per-file category for zero-program outcomes. */\n  readonly zeroProgramClassifications: readonly ZeroProgramClassification[];\n  /** Top N files by unknown node rate (highest first), for --show-top-unknown. */\n  readonly topUnknownFiles?: readonly string[];\n  /** Unknown node counts by reason. */\n  readonly unknownReasonCounts?: Readonly<Record<string, number>>;\n  /** Top unknown reasons by count (highest first), for --show-top-unknown-reasons. */\n  readonly topUnknownReasons?: readonly { reason: string; count: number }[];\n  /** Audit execution time in ms (improve.md §7 performance validation). */\n  readonly durationMs?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<Omit<AnalyzeProjectOptions, 'tsconfig'>> = {\n  extensions: ['.ts', '.tsx'],\n  maxDepth: 10,\n  knownEffectInternalsRoot: undefined,\n  includePerFileTiming: false,\n  excludeFromSuspiciousZeros: [],\n  buildServiceMap: false,\n  buildArchitecture: false,\n};\n\n\n\n/** Modules from `effect` that do NOT produce Effect programs on their own. */\nconst NON_PROGRAM_EFFECT_MODULES = new Set([\n  'Option', 'Either', 'Predicate', 'Order', 'Equivalence',\n  'Hash', 'Equal', 'Inspectable', 'Pipeable', 'Types',\n  'Brand', 'Chunk', 'HashMap', 'HashSet', 'List',\n  'SortedMap', 'SortedSet', 'Duration', 'DateTime',\n  'BigInt', 'BigDecimal', 'Number', 'String', 'Struct',\n  'Tuple', 'ReadonlyArray', 'Array', 'Record',\n  'Schema', 'ServiceMap', 'Data', 'Match', 'Function',\n]);\n\nfunction fileImportsEffect(filePath: string): boolean {\n  try {\n    const content = readFileSync(filePath, 'utf-8');\n    if (!/from\\s+[\"'](?:effect|effect\\/|@effect\\/)/.test(content)) return false;\n\n    // Check if all runtime (non-type) named imports from \"effect\" are non-program modules\n    // `import type { ... }` lines are always safe (type-only, no runtime behavior)\n    const runtimeImportMatches = content.matchAll(/import\\s+{([^}]+)}\\s+from\\s+[\"']effect[\"']/g);\n    let hasAnyRuntimeImport = false;\n    let allNonProgram = true;\n    for (const match of runtimeImportMatches) {\n      // Skip if this is actually an `import type` statement (the regex above won't match `import type {`)\n      // But we need to check for inline `type` specifiers like `import { type Effect, Schema } from \"effect\"`\n      const names = match[1]!.split(',')\n        .map(s => s.trim())\n        .filter(s => !s.startsWith('type '))  // skip inline type imports\n        .map(s => s.split(/\\s+as\\s+/)[0]!.trim())\n        .filter(Boolean);\n      for (const name of names) {\n        hasAnyRuntimeImport = true;\n        if (!NON_PROGRAM_EFFECT_MODULES.has(name)) {\n          allNonProgram = false;\n          break;\n        }\n      }\n      if (!allNonProgram) break;\n    }\n\n    if (hasAnyRuntimeImport && allNonProgram) return false;\n\n    // Check for namespace imports: import * as X from \"effect\" or \"effect/...\"\n    const hasNamespaceImport = /import\\s+\\*\\s+as\\s+\\w+\\s+from\\s+[\"'](?:effect|effect\\/|@effect\\/)/.test(content);\n    if (hasNamespaceImport) return true;\n\n    // Check for named/namespace imports from effect submodules (e.g. \"effect/Effect\", \"@effect/...\")\n    // These weren't caught by the exact \"effect\" regex above\n    const hasSubmoduleImport = /import\\s+{[^}]+}\\s+from\\s+[\"'](?:effect\\/|@effect\\/)/.test(content);\n    if (hasSubmoduleImport) return true;\n\n    // If only `import type` statements exist (no runtime imports at all), not suspicious\n    if (!hasAnyRuntimeImport) return false;\n\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction isTypeOnlyZeroCandidate(filePath: string): boolean {\n  try {\n    const content = readFileSync(filePath, 'utf-8');\n    const hasRuntimeLikeEffectUsage =\n      /\\bEffect\\./.test(content) ||\n      /\\bLayer\\./.test(content) ||\n      /\\bStream\\./.test(content) ||\n      /\\bSchema\\./.test(content) ||\n      /\\byield\\*/.test(content) ||\n      /\\bpipe\\(/.test(content) ||\n      /\\brunPromise\\b/.test(content) ||\n      /\\brunSync\\b/.test(content) ||\n      /\\brunFork\\b/.test(content) ||\n      /\\bacquireRelease\\b/.test(content);\n    if (hasRuntimeLikeEffectUsage) return false;\n\n    return (\n      /\\binterface\\b/.test(content) ||\n      /\\btype\\b/.test(content) ||\n      /\\bdeclare\\b/.test(content) ||\n      /^\\s*import\\s+type\\b/m.test(content) ||\n      /^\\s*export\\s+type\\b/m.test(content)\n    );\n  } catch {\n    return false;\n  }\n}\n\nfunction isLightweightEffectAdapterFile(filePath: string): boolean {\n  try {\n    const content = readFileSync(filePath, 'utf-8');\n    const hasProgramLikeUsage =\n      /\\byield\\*/.test(content) ||\n      /\\bEffect\\.gen\\b/.test(content) ||\n      /\\bpipe\\(/.test(content) ||\n      /\\bEffect\\.run(?:Promise|Sync|Fork|Callback)\\b/.test(content) ||\n      /\\bacquireRelease\\b/.test(content) ||\n      /\\bLayer\\.(?:effect|scoped|merge|provide)\\b/.test(content);\n    if (hasProgramLikeUsage) return false;\n\n    const effectConstructorMentions =\n      content.match(/\\bEffect\\.(?:void|succeed|fail|sync|try|promise|async)\\b/g) ?? [];\n    if (effectConstructorMentions.length === 0) return false;\n\n    const callbackPropertyMentions =\n      content.match(/(?:readonly\\s+)?[A-Za-z0-9_]+\\s*:\\s*\\([^)]*\\)\\s*=>/g) ?? [];\n\n    return callbackPropertyMentions.length > 0;\n  } catch {\n    return false;\n  }\n}\n\nfunction detectExpectedZeroCategory(filePath: string): Exclude<ZeroProgramCategory, 'suspicious' | 'other'> | undefined {\n  const normalized = filePath.replace(/\\\\/g, '/');\n  const base = basename(normalized).toLowerCase();\n\n  if (base === 'index.ts' || base === 'index.tsx' || /\\/index\\.[jt]sx?$/.test(normalized)) {\n    return 'barrel_or_index';\n  }\n\n  if (\n    /(^|\\/)(__tests__|test|tests|dtslint)(\\/|$)/.test(normalized) ||\n    /\\.(test|spec|tst)\\.[jt]sx?$/.test(normalized)\n  ) {\n    return 'test_or_dtslint';\n  }\n\n  if (\n    /(^|\\/)(vitest|vite|jest|webpack|rollup|tsup|esbuild|eslint|prettier|babel|playwright|typedoc|karma)\\.config\\.[jt]s$/.test(normalized) ||\n    /(^|\\/)vitest\\.workspace\\.[jt]s$/.test(normalized)\n  ) {\n    return 'config_or_build';\n  }\n\n  if (isTypeOnlyZeroCandidate(filePath)) {\n    return 'type_only';\n  }\n\n  return undefined;\n}\n// =============================================================================\n// Entry points from package.json (Gap 4: semantic entry-point detection)\n// =============================================================================\n\nasync function findPackageJsonDirs(\n  dir: string,\n  maxDepth: number,\n  currentDepth: number,\n): Promise<string[]> {\n  if (currentDepth >= maxDepth) return [];\n  const result: string[] = [];\n  try {\n    const entries = await readdir(dir, { withFileTypes: true });\n    const hasPkg = entries.some((e) => e.isFile() && e.name === 'package.json');\n    if (hasPkg) result.push(dir);\n    for (const ent of entries) {\n      if (ent.isDirectory() && ent.name !== 'node_modules' && ent.name !== '.git') {\n        result.push(\n          ...(await findPackageJsonDirs(join(dir, ent.name), maxDepth, currentDepth + 1)),\n        );\n      }\n    }\n  } catch {\n    // ignore\n  }\n  return result;\n}\n\nfunction resolveEntry(\n  pkgDir: string,\n  entry: string | undefined,\n  extensions: readonly string[],\n): string[] {\n  if (!entry || typeof entry !== 'string') return [];\n  const normalized = entry.replace(/^\\.\\//, '');\n  const base = join(pkgDir, normalized);\n  const ext = extname(normalized);\n  if (ext) {\n    return [resolve(base)];\n  }\n  return extensions.map((e) => resolve(base + e));\n}\n\n/** Gap 4: Detect files that have Effect.runPromise / runSync / NodeRuntime.runMain at top level. */\nasync function fileHasTopLevelRunCall(filePath: string): Promise<boolean> {\n  try {\n    const { Project, SyntaxKind } = loadTsMorph();\n    const project = new Project({ skipAddingFilesFromTsConfig: true });\n    const sourceFile = project.addSourceFileAtPath(filePath);\n    const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n    const functionKinds = [\n      SyntaxKind.FunctionDeclaration,\n      SyntaxKind.FunctionExpression,\n      SyntaxKind.ArrowFunction,\n      SyntaxKind.MethodDeclaration,\n    ];\n    for (const call of callExpressions) {\n      const parent = call.getParent();\n      if (parent?.getKind() !== SyntaxKind.ExpressionStatement) continue;\n      let current: ReturnType<typeof parent.getParent> = parent;\n      while (current) {\n        const kind = current.getKind();\n        if (kind === SyntaxKind.SourceFile) break;\n        if (functionKinds.includes(kind)) break;\n        current = current.getParent();\n      }\n      if (current?.getKind() !== SyntaxKind.SourceFile) continue;\n      const exprText = call.getExpression().getText();\n      if (\n        exprText.includes('.runPromise') ||\n        exprText.includes('.runSync') ||\n        exprText.includes('.runFork') ||\n        exprText.includes('.runCallback') ||\n        exprText.includes('NodeRuntime.runMain') ||\n        exprText.includes('BunRuntime.runMain') ||\n        exprText.includes('DenoRuntime.runMain') ||\n        exprText.includes('Runtime.runPromise') ||\n        exprText.includes('Runtime.runSync') ||\n        exprText.includes('Runtime.runFork')\n      ) {\n        return true;\n      }\n    }\n  } catch {\n    // ignore parse errors\n  }\n  return false;\n}\n\nasync function getEntryPointsFromPackageJson(\n  dirPath: string,\n  extensions: readonly string[],\n): Promise<string[]> {\n  const pkgDirs = await findPackageJsonDirs(dirPath, 10, 0);\n  const entryPaths: string[] = [];\n  for (const pkgDir of pkgDirs) {\n    try {\n      const raw = await readFile(join(pkgDir, 'package.json'), 'utf-8');\n      const pkg = JSON.parse(raw) as { main?: string; module?: string; bin?: string | Record<string, string> };\n      const dirs = [resolveEntry(pkgDir, pkg.main, extensions), resolveEntry(pkgDir, pkg.module, extensions)];\n      if (typeof pkg.bin === 'string') dirs.push(resolveEntry(pkgDir, pkg.bin, extensions));\n      else if (pkg.bin && typeof pkg.bin === 'object')\n        for (const v of Object.values(pkg.bin)) dirs.push(resolveEntry(pkgDir, typeof v === 'string' ? v : undefined, extensions));\n      for (const list of dirs) {\n        for (const p of list) {\n          try {\n            const s = await stat(p).catch(() => null);\n            if (s?.isFile()) entryPaths.push(p);\n          } catch {\n            // skip\n          }\n        }\n      }\n    } catch {\n      // skip invalid or missing package.json\n    }\n  }\n  return [...new Set(entryPaths)];\n}\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\n/**\n * Analyze all TypeScript files in a directory and return aggregated IRs.\n */\nexport function analyzeProjectCorpus(\n  corpus: ProjectCorpus,\n  options: AnalyzeProjectOptions = {},\n): Effect.Effect<ProjectAnalysisResult> {\n  const dirPath = corpus.root;\n  const extensions = (options.extensions ?? DEFAULT_OPTIONS.extensions)!;\n  return Effect.gen(function* () {\n    const files = corpus.files.map((entry) => entry.file);\n    const byFile = new Map<string, readonly StaticEffectIR[]>();\n    const allPrograms: StaticEffectIR[] = [];\n    const entryPointFiles: string[] = [];\n    const failedFiles: ProjectFileFailure[] = [];\n    const zeroProgramFiles: string[] = [];\n\n    for (const entry of corpus.files) {\n      const file = entry.file;\n      if (entry.status === 'fail') {\n        failedFiles.push({ file, error: entry.error ?? 'Unknown analysis failure' });\n        continue;\n      }\n      if (entry.status === 'zero') {\n        zeroProgramFiles.push(file);\n        continue;\n      }\n      const programs = entry.programs;\n      byFile.set(file, programs);\n      allPrograms.push(...programs);\n      for (const ir of programs) {\n        const nameLikeEntry =\n          ir.root.programName === 'main' || ir.root.programName.includes('run');\n        const isRunCall = ir.root.source === 'run';\n        if (nameLikeEntry || isRunCall) {\n          if (!entryPointFiles.includes(file)) entryPointFiles.push(file);\n        }\n      }\n    }\n\n    const packageEntryPaths = yield* Effect.promise(() =>\n      getEntryPointsFromPackageJson(dirPath, extensions),\n    );\n    for (const p of packageEntryPaths) {\n      if (files.includes(p) && !entryPointFiles.includes(p)) {\n        entryPointFiles.push(p);\n      }\n    }\n\n    for (const file of byFile.keys()) {\n      if (entryPointFiles.includes(file)) continue;\n      const hasRun = yield* Effect.promise(() => fileHasTopLevelRunCall(file));\n      if (hasRun) entryPointFiles.push(file);\n    }\n\n    // Optionally build the deduplicated service map\n    let serviceMap: ProjectServiceMap | undefined;\n    if (options.buildServiceMap) {\n      serviceMap = yield* Effect.try(() => {\n        const { Project } = loadTsMorph();\n        const project = new Project({\n          skipAddingFilesFromTsConfig: true,\n          compilerOptions: { allowJs: true },\n        });\n        // oxlint-disable-next-line typescript/no-explicit-any\n        const sourceFileMap = new Map<string, any>();\n        for (const file of byFile.keys()) {\n          // Files that cannot be loaded are skipped, not fatal. This stays a\n          // plain try/catch: it guards one synchronous ts-morph call inside an\n          // already-suspended Effect.try, so lifting it would only add a nested\n          // runtime.\n          try {\n            sourceFileMap.set(file, project.addSourceFileAtPath(file));\n          } catch {\n            continue;\n          }\n        }\n        return buildProjectServiceMap(byFile, sourceFileMap);\n      }).pipe(\n        // Fall back to IR-only service map (no AST-level extraction)\n        Effect.orElseSucceed(() => buildProjectServiceMap(byFile)),\n      );\n    }\n\n    const architecture = options.buildArchitecture\n      ? extractProjectArchitecture(files, { tsconfig: options.tsconfig })\n      : undefined;\n\n    return {\n      byFile,\n      allPrograms,\n      entryPointFiles,\n      fileCount: files.length,\n      failedFiles,\n      zeroProgramFiles,\n      serviceMap,\n      architecture,\n    };\n  });\n}\n\nexport function analyzeProject(\n  dirPath: string,\n  options: AnalyzeProjectOptions = {},\n): Effect.Effect<ProjectAnalysisResult> {\n  const extensions = options.extensions ?? DEFAULT_OPTIONS.extensions;\n  const maxDepth = options.maxDepth ?? DEFAULT_OPTIONS.maxDepth;\n  return scanProjectCorpus(dirPath, {\n    extensions,\n    maxDepth,\n    tsconfig: options.tsconfig,\n    knownEffectInternalsRoot: options.knownEffectInternalsRoot,\n  }).pipe(\n    Effect.flatMap((corpus) => analyzeProjectCorpus(corpus, options)),\n  );\n}\n\n// =============================================================================\n// Coverage audit (missing-gaps: discovered vs analyzed, failed/skipped list)\n// =============================================================================\n\n/**\n * Run a coverage audit over a directory: discover all .ts/.tsx files, analyze each,\n * and return counts plus per-file outcomes (ok / zero programs / failed with reason).\n * Does not swallow failures; every file gets an outcome.\n */\nexport function runCoverageAudit(\n  dirPath: string,\n  options: AnalyzeProjectOptions = {},\n): Effect.Effect<CoverageAuditResult> {\n  return scanProjectCorpus(dirPath, {\n    extensions: options.extensions ?? DEFAULT_OPTIONS.extensions,\n    maxDepth: options.maxDepth ?? DEFAULT_OPTIONS.maxDepth,\n    tsconfig: options.tsconfig,\n    includePerFileTiming: options.includePerFileTiming,\n    knownEffectInternalsRoot: options.knownEffectInternalsRoot,\n  }).pipe(\n    Effect.flatMap((corpus) => runCoverageAuditFromCorpus(corpus, options)),\n  );\n}\n\nexport function runCoverageAuditFromCorpus(\n  corpus: ProjectCorpus,\n  options: AnalyzeProjectOptions = {},\n): Effect.Effect<CoverageAuditResult> {\n  return Effect.sync(() => {\n    const outcomes: FileOutcome[] = [];\n    let totalNodes = 0;\n    let unknownNodes = 0;\n    let sourceUnresolvedNodes = 0;\n    const fidelityFindings: ProjectFidelityFinding[] = [];\n    const fileUnknownRates: { file: string; total: number; unknown: number }[] = [];\n    const unknownReasonsCorpus = new Map<string, number>();\n\n    for (const entry of corpus.files) {\n      const file = entry.file;\n      const durationMs = entry.durationMs;\n      if (entry.status !== 'fail') {\n        const count = entry.programs.length;\n        let fileTotal = 0;\n        let fileUnknown = 0;\n        for (const ir of entry.programs) {\n          const fidelity = assessIRFidelity(ir);\n          const unknownFindings = fidelity.findings.filter(\n            (finding) => finding.kind === 'unknown-node',\n          );\n          totalNodes += fidelity.sourceRepresentation.total;\n          unknownNodes += unknownFindings.length;\n          sourceUnresolvedNodes +=\n            fidelity.sourceRepresentation.total - fidelity.sourceRepresentation.resolved;\n          fileTotal += fidelity.sourceRepresentation.total;\n          fileUnknown += unknownFindings.length;\n          for (const finding of fidelity.findings) {\n            fidelityFindings.push({\n              ...finding,\n              file,\n              programName: ir.root.programName,\n            });\n            if (finding.kind === 'unknown-node') {\n              const reason = finding.reason ?? 'Unknown reason';\n              unknownReasonsCorpus.set(reason, (unknownReasonsCorpus.get(reason) ?? 0) + 1);\n            }\n          }\n        }\n        if (fileTotal > 0) {\n          fileUnknownRates.push({ file, total: fileTotal, unknown: fileUnknown });\n        }\n        outcomes.push(\n          count > 0\n            ? { file, status: 'ok', programCount: count, ...(durationMs !== undefined ? { durationMs } : {}) }\n            : { file, status: 'zero', programCount: 0, ...(durationMs !== undefined ? { durationMs } : {}) },\n        );\n      } else {\n        outcomes.push({\n          file,\n          status: 'fail',\n          ...(entry.error === undefined ? {} : { error: entry.error }),\n          ...(durationMs !== undefined ? { durationMs } : {}),\n        });\n      }\n    }\n\n    const discovered = corpus.files.length;\n    const analyzed = outcomes.filter((o) => o.status === 'ok').length;\n    const zeroPrograms = outcomes.filter((o) => o.status === 'zero').length;\n    const failed = outcomes.filter((o) => o.status === 'fail').length;\n    const excludePatterns = options.excludeFromSuspiciousZeros ?? [];\n    const isExcludedFromSuspicious = (filePath: string): boolean => {\n      const normalized = filePath.replace(/\\\\/g, '/');\n      return excludePatterns.some(\n        (p) => normalized.includes(p.replace(/\\\\/g, '/')) || normalized.endsWith(p.replace(/\\\\/g, '/')),\n      );\n    };\n    const zeroProgramCategoryCounts: Record<ZeroProgramCategory, number> = {\n      barrel_or_index: 0,\n      config_or_build: 0,\n      test_or_dtslint: 0,\n      type_only: 0,\n      suspicious: 0,\n      other: 0,\n    };\n    const suspiciousZeros: string[] = [];\n    const zeroProgramClassifications: ZeroProgramClassification[] = [];\n\n    const zeroOutcomes = outcomes.filter((o) => o.status === 'zero');\n    for (const o of zeroOutcomes) {\n      const importsEffect = fileImportsEffect(o.file);\n      const expectedCategory = detectExpectedZeroCategory(o.file);\n      const category: ZeroProgramCategory =\n        importsEffect &&\n        !isExcludedFromSuspicious(o.file) &&\n        expectedCategory === undefined &&\n        !isLightweightEffectAdapterFile(o.file)\n          ? 'suspicious'\n          : (expectedCategory ?? 'other');\n\n      zeroProgramCategoryCounts[category]++;\n      zeroProgramClassifications.push({ file: o.file, category, importsEffect });\n      if (category === 'suspicious') suspiciousZeros.push(o.file);\n    }\n    const unknownNodeRate = totalNodes > 0 ? unknownNodes / totalNodes : 0;\n    const assessment = assessAudit({\n      discoveredFiles: discovered,\n      effectFiles: analyzed,\n      failedFiles: failed,\n      totalNodes,\n      unresolvedNodes: sourceUnresolvedNodes,\n    });\n    const topUnknownFiles = fileUnknownRates\n      .filter((f) => f.total > 0)\n      .sort((a, b) => (b.unknown / b.total) - (a.unknown / a.total))\n      .slice(0, 10)\n      .map((f) => f.file);\n\n    const unknownReasonCounts: Record<string, number> = {};\n    for (const [reason, n] of unknownReasonsCorpus) unknownReasonCounts[reason] = n;\n    const topUnknownReasons = [...unknownReasonsCorpus.entries()]\n      .sort((a, b) => b[1] - a[1])\n      .slice(0, 20)\n      .map(([reason, count]) => ({ reason, count }));\n\n    const durationMs = corpus.durationMs;\n    return {\n      discovered,\n      analyzed,\n      zeroPrograms,\n      failed,\n      outcomes,\n      assessment,\n      unknownNodeRate,\n      totalNodes,\n      unknownNodes,\n      fidelityFindings,\n      suspiciousZeros,\n      zeroProgramCategoryCounts,\n      zeroProgramClassifications,\n      topUnknownFiles,\n      unknownReasonCounts,\n      topUnknownReasons,\n      durationMs,\n    };\n  });\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Service Registry - builds a deduplicated service map for whole-codebase analysis.\n *\n * When the analyzer encounters `yield* SomeService`, this module creates a\n * first-class ServiceArtifact for that service, including its tag definition,\n * interface shape, layer implementations, consumers, and transitive dependencies.\n */\n\nimport type {\n  StaticEffectIR,\n  ServiceArtifact,\n  LayerImplementation,\n  ServiceConsumerRef,\n  ProjectServiceMap,\n  ServiceDefinition,\n  SourceLocation,\n  StaticFlowNode,\n} from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\nimport { loadTsMorph } from './ts-morph-loader';\n\n// Minimal interfaces for ts-morph's dynamically-loaded API so that values\n// flowing through the analyzer carry concrete types instead of `any`.\ninterface TsMorphSymbol {\n  getName(): string;\n}\n\ninterface TsMorphType {\n  getProperties(): TsMorphSymbol[];\n  getCallSignatures(): unknown[];\n}\n\ninterface TsMorphTypeChecker {\n  getTypeAtLocation(node: unknown): TsMorphType;\n  getTypeOfSymbolAtLocation(symbol: unknown, node: unknown): TsMorphType;\n}\n\ninterface TsMorphProject {\n  getTypeChecker(): TsMorphTypeChecker;\n}\n\ninterface TsMorphNode {\n  getName(): string;\n  getText(): string;\n  getStart(): number;\n  getKind(): number;\n  getExtends(): TsMorphNode | undefined;\n  getExpression(): TsMorphNode | undefined;\n  getTypeArguments(): TsMorphNode[];\n  getArguments?(): TsMorphNode[];\n  getInitializer(): TsMorphNode | undefined;\n}\n\ninterface TsMorphSourceFile {\n  getDescendantsOfKind(kind: number): TsMorphNode[];\n  getFilePath(): string;\n  getProject(): TsMorphProject;\n  getLineAndColumnAtPos(pos: number): { line: number; column: number };\n}\n\n// Re-export for convenience\nexport type { ProjectServiceMap, ServiceArtifact };\n\n// =============================================================================\n// Service tag definition extraction (augmented with location + file info)\n// =============================================================================\n\ninterface ServiceTagInfo {\n  readonly tagId: string;\n  readonly className: string;\n  readonly filePath: string;\n  readonly location: SourceLocation;\n  readonly definition: ServiceDefinition;\n  readonly interfaceTypeText?: string | undefined;\n}\n\n/**\n * Extract service tag definitions from a source file, with location and file path info.\n * Augments the existing extractServiceDefinitionsFromFile pattern with richer metadata.\n */\nfunction extractServiceTagsFromFile(\n  sourceFile: TsMorphSourceFile,\n  filePath: string,\n): ServiceTagInfo[] {\n  const { SyntaxKind } = loadTsMorph();\n  const results: ServiceTagInfo[] = [];\n  const typeChecker = sourceFile.getProject().getTypeChecker();\n  const classDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.ClassDeclaration);\n\n  for (const classDecl of classDeclarations) {\n    const name = classDecl.getName();\n    if (!name) continue;\n    const extExpr = classDecl.getExtends();\n    if (!extExpr) continue;\n    const extText = extExpr.getText();\n    if (!extText.includes('Context.Service') && !extText.includes('Context.Tag') && !extText.includes('Effect.Service')) continue;\n\n    // Extract tag string from Context.Tag('TagName') if possible\n    let tagId = name;\n    const tagMatch = /Context\\.Tag\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/.exec(extText);\n    if (tagMatch?.[1]) {\n      tagId = tagMatch[1];\n    } else {\n      const serviceMatch = /Context\\.Service[\\s\\S]*?\\(\\s*\\)\\s*\\(\\s*['\"]([^'\"]+)['\"]/.exec(extText);\n      if (serviceMatch?.[1]) tagId = serviceMatch[1];\n    }\n\n    // Get type arguments for interface shape\n    let typeArgs: readonly TsMorphNode[] = extExpr.getTypeArguments();\n    let expression: TsMorphNode | undefined = extExpr;\n    while (typeArgs.length < 2) {\n      expression = expression.getExpression();\n      if (!expression) break;\n      typeArgs = expression.getTypeArguments();\n    }\n\n    let definition: ServiceDefinition = { tagId, methods: [], properties: [] };\n    let interfaceTypeText: string | undefined;\n\n    if (typeArgs.length >= 2) {\n      const interfaceTypeNode = typeArgs[1];\n      if (interfaceTypeNode) {\n        try {\n          interfaceTypeText = interfaceTypeNode.getText();\n          const type = typeChecker.getTypeAtLocation(interfaceTypeNode);\n          const methods: string[] = [];\n          const properties: string[] = [];\n          for (const sym of type.getProperties()) {\n            const propName = sym.getName();\n            if (propName.startsWith('_') || propName === 'constructor') continue;\n            const propType = typeChecker.getTypeOfSymbolAtLocation(sym, interfaceTypeNode);\n            const callSigs = propType.getCallSignatures();\n            if (callSigs.length > 0) methods.push(propName);\n            else properties.push(propName);\n          }\n          definition = { tagId, methods, properties };\n        } catch {\n          // fall through with empty definition\n        }\n      }\n    }\n\n    const pos = classDecl.getStart();\n    const lineAndCol = sourceFile.getLineAndColumnAtPos(pos);\n\n    results.push({\n      tagId,\n      className: name,\n      filePath,\n      location: {\n        filePath,\n        line: lineAndCol.line,\n        column: lineAndCol.column - 1,\n      },\n      definition,\n      interfaceTypeText,\n    });\n  }\n\n  return results;\n}\n\n// =============================================================================\n// Layer implementation extraction\n// =============================================================================\n\n/**\n * Extract layer implementations from a source file by scanning for\n * Layer.effect(Tag, ...), Layer.succeed(Tag, ...), Layer.sync(Tag, ...), etc.\n */\nfunction extractLayerImplementationsFromFile(\n  sourceFile: TsMorphSourceFile,\n  filePath: string,\n  identifierToServiceId: ReadonlyMap<string, string>,\n): { readonly providesServiceId: string; readonly implementation: LayerImplementation }[] {\n  const { SyntaxKind } = loadTsMorph();\n  const results: { providesServiceId: string; implementation: LayerImplementation }[] = [];\n\n  // Scan all variable declarations at top level for Layer.* calls\n  const varDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration);\n\n  for (const varDecl of varDeclarations) {\n    const initializer = varDecl.getInitializer();\n    if (!initializer) continue;\n\n    const initText = initializer.getText();\n\n    // Check for Layer.effect, Layer.succeed, Layer.sync, Layer.scoped patterns\n    const layerMatch = /Layer\\.(effect|succeed|sync|scoped)\\s*\\(\\s*/.exec(\n      initText,\n    );\n    if (!layerMatch) continue;\n\n    const kind = layerMatch[1] as 'effect' | 'succeed' | 'sync' | 'scoped';\n    const layerName = varDecl.getName();\n\n    // Try to find the service tag referenced as first argument\n    // Look for the first identifier in the call args that matches a known service\n    let providesServiceId: string | undefined;\n\n    // Walk call expression to find first argument\n    if ((initializer.getKind()) === (SyntaxKind.CallExpression)) {\n      const args = initializer.getArguments?.();\n      if (args && args.length > 0) {\n        const firstArg = args[0];\n        if (!firstArg) continue;\n        const firstArgText = firstArg.getText().trim();\n        providesServiceId = identifierToServiceId.get(firstArgText);\n      }\n    }\n\n    // Also try to extract from pipe chains: Layer.effect(...).pipe(Layer.provide(...))\n    // For now handle the unwrapped case and simple .pipe(Layer.provide(...))\n    if (!providesServiceId) {\n      // Try to match by text pattern: Layer.effect(ServiceName, ...)\n      for (const identifier of identifierToServiceId.keys()) {\n        if (\n          initText.includes(`Layer.${kind}(${identifier}`) ||\n          initText.includes(`Layer.${kind}(\\n${identifier}`)\n        ) {\n          providesServiceId = identifierToServiceId.get(identifier);\n          break;\n        }\n      }\n    }\n\n    if (!providesServiceId) continue;\n\n    // Extract required services from Layer.provide() in pipe chain\n    const requires: string[] = [];\n    const provideMatch = /Layer\\.provide\\s*\\(([^)]+)\\)/.exec(initText);\n    if (provideMatch?.[1]) {\n      const provideArg = provideMatch[1].trim();\n      // Could be a single layer or Layer.mergeAll(...)\n      for (const [identifier, canonicalId] of identifierToServiceId.entries()) {\n        if (canonicalId === providesServiceId) continue;\n        if (provideArg.includes(identifier) && !requires.includes(canonicalId)) {\n          requires.push(canonicalId);\n        }\n      }\n    }\n\n    // Also check for yield* inside Layer.effect body for service dependencies\n    const yieldServiceMatches = initText.matchAll(/yield\\*\\s+(\\w+)/g);\n    for (const m of yieldServiceMatches) {\n      const ident = m[1];\n      const canonical = ident ? identifierToServiceId.get(ident) : undefined;\n      if (canonical && canonical !== providesServiceId && !requires.includes(canonical)) {\n        requires.push(canonical);\n      }\n    }\n    const yieldServiceMatchesAlt = initText.matchAll(/yield\\s*\\*\\s*(\\w+)/g);\n    for (const m of yieldServiceMatchesAlt) {\n      const ident = m[1];\n      const canonical = ident ? identifierToServiceId.get(ident) : undefined;\n      if (canonical && canonical !== providesServiceId && !requires.includes(canonical)) {\n        requires.push(canonical);\n      }\n    }\n\n    const pos = varDecl.getStart();\n    const lineAndCol = sourceFile.getLineAndColumnAtPos(pos);\n\n    results.push({\n      providesServiceId,\n      implementation: {\n        name: layerName,\n        filePath,\n        location: {\n          filePath,\n          line: lineAndCol.line,\n          column: lineAndCol.column - 1,\n        },\n        kind,\n        requires,\n      },\n    });\n  }\n\n  return results;\n}\n\n// =============================================================================\n// Consumer extraction from analyzed programs\n// =============================================================================\n\nfunction collectConsumers(\n  byFile: ReadonlyMap<string, readonly StaticEffectIR[]>,\n): Map<string, ServiceConsumerRef[]> {\n  const consumers = new Map<string, ServiceConsumerRef[]>();\n\n  for (const [filePath, irs] of byFile) {\n    for (const ir of irs) {\n      const programName = ir.root.programName;\n\n      // From requiredServices on the program root\n      if (ir.root.requiredServices) {\n        for (const req of ir.root.requiredServices) {\n          const list = consumers.get(req.serviceId) ?? [];\n          list.push({\n            programName,\n            filePath,\n            location: req.requiredAt,\n          });\n          consumers.set(req.serviceId, list);\n        }\n      }\n\n      // Also walk the IR tree for service references in effect nodes\n      collectConsumersFromNodes(ir.root.children, programName, filePath, consumers);\n    }\n  }\n\n  return consumers;\n}\n\nfunction collectConsumersFromNodes(\n  nodes: readonly StaticFlowNode[],\n  programName: string,\n  filePath: string,\n  consumers: Map<string, ServiceConsumerRef[]>,\n): void {\n  for (const node of nodes) {\n    if (node.type === 'effect' && node.serviceCall) {\n      const serviceId = node.serviceCall.serviceType;\n      if (serviceId) {\n        const list = consumers.get(serviceId) ?? [];\n        // Avoid duplicates for the same program\n        if (!list.some((c) => c.programName === programName && c.filePath === filePath)) {\n          list.push({\n            programName,\n            filePath,\n            location: node.location,\n          });\n          consumers.set(serviceId, list);\n        }\n      }\n    }\n\n    const children = Option.getOrElse(getStaticChildren(node), () => []);\n    if (children.length > 0) {\n      collectConsumersFromNodes(children, programName, filePath, consumers);\n    }\n  }\n}\n\n// =============================================================================\n// Topological sort\n// =============================================================================\n\nfunction computeTopologicalOrder(\n  services: ReadonlyMap<string, ServiceArtifact>,\n): string[] {\n  const result: string[] = [];\n  const visited = new Set<string>();\n  const temp = new Set<string>();\n\n  function visit(id: string): void {\n    if (visited.has(id)) return;\n    if (temp.has(id)) return; // cycle\n    temp.add(id);\n    const artifact = services.get(id);\n    if (artifact) {\n      for (const dep of artifact.dependencies) {\n        visit(dep);\n      }\n    }\n    temp.delete(id);\n    visited.add(id);\n    result.push(id);\n  }\n\n  for (const id of services.keys()) {\n    visit(id);\n  }\n\n  return result;\n}\n\n// =============================================================================\n// Transitive dependency computation\n// =============================================================================\n\nfunction computeTransitiveDeps(\n  serviceId: string,\n  layerImpls: readonly LayerImplementation[],\n  allLayersByService: ReadonlyMap<string, readonly LayerImplementation[]>,\n  visited = new Set<string>(),\n): string[] {\n  const deps: string[] = [];\n  if (visited.has(serviceId)) return deps;\n  visited.add(serviceId);\n\n  for (const layer of layerImpls) {\n    for (const req of layer.requires) {\n      if (!deps.includes(req)) {\n        deps.push(req);\n      }\n      // Recurse into the required service's layers\n      const reqLayers = allLayersByService.get(req);\n      if (reqLayers) {\n        for (const transitive of computeTransitiveDeps(req, reqLayers, allLayersByService, visited)) {\n          if (!deps.includes(transitive)) {\n            deps.push(transitive);\n          }\n        }\n      }\n    }\n  }\n\n  return deps;\n}\n\n// =============================================================================\n// Main entry point\n// =============================================================================\n\n/**\n * Build a deduplicated project-level service map from analyzed program IRs.\n *\n * @param byFile Map of file path to analyzed programs in that file\n * @param sourceFiles Optional map of file path to ts-morph SourceFile for AST-level extraction.\n *   When not provided, only IR-level data (requiredServices, StaticLayerNode) is used.\n */\nexport function buildProjectServiceMap(\n  byFile: ReadonlyMap<string, readonly StaticEffectIR[]>,\n  sourceFiles?: ReadonlyMap<string, any>,\n): ProjectServiceMap {\n  // Step 1: Collect all service tag definitions\n  const serviceTagInfos = new Map<string, ServiceTagInfo>();\n\n  if (sourceFiles) {\n    for (const [filePath, sf] of sourceFiles) {\n      const tags = extractServiceTagsFromFile(sf as TsMorphSourceFile, filePath);\n      for (const tag of tags) {\n        // Use tagId (canonical tag string) as key, not className\n        if (!serviceTagInfos.has(tag.tagId)) {\n          serviceTagInfos.set(tag.tagId, tag);\n        }\n      }\n    }\n  }\n\n  // Also collect from IR metadata serviceDefinitions\n  for (const [filePath, irs] of byFile) {\n    for (const ir of irs) {\n      if (ir.metadata.serviceDefinitions) {\n        for (const def of ir.metadata.serviceDefinitions) {\n          if (!serviceTagInfos.has(def.tagId)) {\n            serviceTagInfos.set(def.tagId, {\n              tagId: def.tagId,\n              className: def.tagId,\n              filePath,\n              location: { filePath, line: 1, column: 0 },\n              definition: def,\n            });\n          }\n        }\n      }\n    }\n  }\n\n  const knownServiceIds = new Set(serviceTagInfos.keys());\n  const identifierToServiceId = new Map<string, string>();\n  for (const [serviceId, tagInfo] of serviceTagInfos) {\n    // Allow matching layers by either canonical tag ID or the tag class name\n    if (!identifierToServiceId.has(serviceId)) identifierToServiceId.set(serviceId, serviceId);\n    if (!identifierToServiceId.has(tagInfo.className)) {\n      identifierToServiceId.set(tagInfo.className, serviceId);\n    }\n  }\n\n  // Also collect service IDs referenced in programs but not yet in the tag map\n  // (these may come from yield* SomeService without a tag definition in scope)\n  const allReferencedServiceIds = new Set<string>();\n  for (const irs of byFile.values()) {\n    for (const ir of irs) {\n      if (ir.root.requiredServices) {\n        for (const req of ir.root.requiredServices) {\n          allReferencedServiceIds.add(req.serviceId);\n        }\n      }\n    }\n  }\n\n  // Step 2: Collect layer implementations\n  const layersByService = new Map<string, LayerImplementation[]>();\n\n  if (sourceFiles) {\n    for (const [filePath, sf] of sourceFiles) {\n      const layers = extractLayerImplementationsFromFile(sf as TsMorphSourceFile, filePath, identifierToServiceId);\n      for (const match of layers) {\n        if (!knownServiceIds.has(match.providesServiceId)) continue;\n        const list = layersByService.get(match.providesServiceId) ?? [];\n        list.push(match.implementation);\n        layersByService.set(match.providesServiceId, list);\n      }\n    }\n  }\n\n  // Also extract layers from IR (StaticLayerNode with provides)\n  for (const [filePath, irs] of byFile) {\n    for (const ir of irs) {\n      collectLayersFromIR(ir.root.children, filePath, knownServiceIds, identifierToServiceId, layersByService, ir);\n    }\n  }\n\n  // Step 3: Collect consumers\n  const consumersByService = collectConsumers(byFile);\n\n  // Step 4: Build ServiceArtifact map\n  const services = new Map<string, ServiceArtifact>();\n  const unresolvedServices: string[] = [];\n\n  // Build artifacts for known services\n  for (const [serviceId, tagInfo] of serviceTagInfos) {\n    const layerImpls = layersByService.get(serviceId) ?? [];\n    const consumers = consumersByService.get(serviceId) ?? [];\n    const dependencies = computeTransitiveDeps(serviceId, layerImpls, layersByService);\n\n    services.set(serviceId, {\n      serviceId,\n      className: tagInfo.className,\n      definitionFilePath: tagInfo.filePath,\n      definitionLocation: tagInfo.location,\n      definition: tagInfo.definition,\n      interfaceTypeText: tagInfo.interfaceTypeText,\n      layerImplementations: layerImpls,\n      consumers,\n      dependencies,\n    });\n  }\n\n  // Track unresolved services (referenced but no tag definition)\n  // Include both requiredServices and serviceCall nodes (consumersByService)\n  const allReferenced = new Set(allReferencedServiceIds);\n  for (const refId of consumersByService.keys()) {\n    allReferenced.add(refId);\n  }\n  for (const refId of allReferenced) {\n    if (!services.has(refId)) {\n      unresolvedServices.push(refId);\n    }\n  }\n\n  // Step 5: Topological sort\n  const topologicalOrder = computeTopologicalOrder(services);\n\n  return {\n    services,\n    unresolvedServices,\n    topologicalOrder,\n  };\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction collectLayersFromIR(\n  nodes: readonly StaticFlowNode[],\n  filePath: string,\n  knownServiceIds: ReadonlySet<string>,\n  identifierToServiceId: ReadonlyMap<string, string>,\n  layersByService: Map<string, LayerImplementation[]>,\n  ir: StaticEffectIR,\n): void {\n  for (const node of nodes) {\n    if (node.type === 'layer' && node.provides) {\n      for (const providedIdent of node.provides) {\n        const canonical =\n          identifierToServiceId.get(providedIdent) ??\n          (knownServiceIds.has(providedIdent) ? providedIdent : undefined);\n        if (canonical && knownServiceIds.has(canonical)) {\n          const list = layersByService.get(canonical) ?? [];\n          const requires =\n            node.requires\n              ? node.requires\n                  .map((r) => identifierToServiceId.get(r) ?? r)\n                  .filter((r) => knownServiceIds.has(r))\n              : [];\n          // Avoid duplicates\n          if (!list.some((l) => l.name === (node.name ?? ir.root.programName) && l.filePath === filePath)) {\n            list.push({\n              name: node.name ?? ir.root.programName,\n              filePath,\n              location: node.location ?? { filePath, line: 1, column: 0 },\n              kind: 'other',\n              requires,\n            });\n            layersByService.set(canonical, list);\n          }\n        }\n      }\n    }\n\n    const children = Option.getOrElse(getStaticChildren(node), () => []);\n    if (children.length > 0) {\n      collectLayersFromIR(children, filePath, knownServiceIds, identifierToServiceId, layersByService, ir);\n    }\n  }\n}\n","/** Discover and analyze a project once so every project view uses the same facts. */\n\nimport { Effect, Clock } from 'effect';\nimport { readdir } from 'fs/promises';\nimport { extname, join } from 'path';\nimport { analyze } from './analyze';\nimport type { StaticEffectIR } from './types';\n\nexport type ProjectCorpusFileStatus = 'ok' | 'zero' | 'fail';\n\nexport interface ProjectCorpusFile {\n  readonly file: string;\n  readonly status: ProjectCorpusFileStatus;\n  readonly programs: readonly StaticEffectIR[];\n  readonly error?: string | undefined;\n  readonly durationMs?: number | undefined;\n}\n\nexport interface ProjectCorpus {\n  readonly root: string;\n  readonly files: readonly ProjectCorpusFile[];\n  readonly durationMs: number;\n}\n\nexport interface ScanProjectCorpusOptions {\n  readonly tsconfig?: string | undefined;\n  readonly extensions?: readonly string[] | undefined;\n  readonly maxDepth?: number | undefined;\n  readonly includePerFileTiming?: boolean | undefined;\n  readonly knownEffectInternalsRoot?: string | undefined;\n}\n\nconst DEFAULT_EXTENSIONS = ['.ts', '.tsx'] as const;\nconst DEFAULT_MAX_DEPTH = 10;\n\nexport const discoverProjectFiles = async (\n  dir: string,\n  extensions: readonly string[] = DEFAULT_EXTENSIONS,\n  maxDepth = DEFAULT_MAX_DEPTH,\n  currentDepth = 0,\n): Promise<readonly string[]> => {\n  if (currentDepth >= maxDepth) return [];\n  const files: string[] = [];\n  try {\n    const entries = await readdir(dir, { withFileTypes: true });\n    for (const entry of entries) {\n      const fullPath = join(dir, entry.name);\n      if (entry.isDirectory()) {\n        if (entry.name !== 'node_modules' && entry.name !== '.git') {\n          files.push(...await discoverProjectFiles(\n            fullPath,\n            extensions,\n            maxDepth,\n            currentDepth + 1,\n          ));\n        }\n      } else if (entry.isFile() && extensions.includes(extname(entry.name))) {\n        files.push(fullPath);\n      }\n    }\n  } catch {\n    // An unreadable directory contributes no files. Individual analysis failures\n    // remain visible in the corpus once a file has been discovered.\n  }\n  return files.sort((left, right) => left.localeCompare(right));\n};\n\nexport const scanProjectCorpus = (\n  root: string,\n  options: ScanProjectCorpusOptions = {},\n): Effect.Effect<ProjectCorpus> =>\n  Effect.gen(function* () {\n    const startedAt = yield* Clock.currentTimeMillis;\n    const files = yield* Effect.promise(() => discoverProjectFiles(\n      root,\n      options.extensions ?? DEFAULT_EXTENSIONS,\n      options.maxDepth ?? DEFAULT_MAX_DEPTH,\n    ));\n    const corpusFiles: ProjectCorpusFile[] = [];\n\n    // Analysis remains sequential until node IDs and ts-morph projects are owned\n    // by the Analysis session instead of shared module globals.\n    for (const file of files) {\n      const fileStartedAt =\n        options.includePerFileTiming === true ? yield* Clock.currentTimeMillis : 0;\n      const result = yield* analyze(file, {\n        tsConfigPath: options.tsconfig,\n        knownEffectInternalsRoot: options.knownEffectInternalsRoot,\n      }).all.pipe(\n        Effect.map((programs) => ({ _tag: 'ok' as const, programs })),\n        Effect.catch((error) => Effect.succeed({\n          _tag: 'fail' as const,\n          error: error instanceof Error ? error.message : String(error),\n        })),\n      );\n      const durationMs =\n        options.includePerFileTiming === true\n          ? (yield* Clock.currentTimeMillis) - fileStartedAt\n          : undefined;\n\n      if (result._tag === 'ok') {\n        corpusFiles.push({\n          file,\n          status: result.programs.length > 0 ? 'ok' : 'zero',\n          programs: result.programs,\n          ...(durationMs === undefined ? {} : { durationMs }),\n        });\n        continue;\n      }\n\n      const isZero = result.error.includes('No Effect programs found') ||\n        result.error.includes('NO_EFFECTS_FOUND');\n      corpusFiles.push({\n        file,\n        status: isZero ? 'zero' : 'fail',\n        programs: [],\n        ...(isZero ? {} : { error: result.error }),\n        ...(durationMs === undefined ? {} : { durationMs }),\n      });\n    }\n\n    return {\n      root,\n      files: corpusFiles,\n      durationMs: (yield* Clock.currentTimeMillis) - startedAt,\n    };\n  });\n","/** Unambiguous measurements for a project coverage audit. */\n\nexport interface AuditDimension {\n  readonly numerator: number;\n  readonly denominator: number;\n  readonly rate: number;\n}\n\nexport interface AuditAssessment {\n  /** Files containing at least one Effect program / all discovered files. */\n  readonly effectAdoption: AuditDimension;\n  /** Successfully analyzed Effect-bearing files / analyzed plus failed files. */\n  readonly analysisSuccess: AuditDimension;\n  /** Resolved IR nodes / all IR nodes. */\n  readonly sourceResolution: AuditDimension;\n}\n\nexport interface AuditAssessmentInput {\n  readonly discoveredFiles: number;\n  readonly effectFiles: number;\n  readonly failedFiles: number;\n  readonly totalNodes: number;\n  readonly unresolvedNodes: number;\n}\n\nconst dimension = (\n  numerator: number,\n  denominator: number,\n  emptyRate: number,\n): AuditDimension => ({\n  numerator,\n  denominator,\n  rate: denominator === 0 ? emptyRate : numerator / denominator,\n});\n\nexport const assessAudit = (input: AuditAssessmentInput): AuditAssessment => ({\n  effectAdoption: dimension(input.effectFiles, input.discoveredFiles, 0),\n  analysisSuccess: dimension(\n    input.effectFiles,\n    input.effectFiles + input.failedFiles,\n    1,\n  ),\n  sourceResolution: dimension(\n    input.totalNodes - input.unresolvedNodes,\n    input.totalNodes,\n    1,\n  ),\n});\n","/** Deep operations over the Effect IR. */\n\nimport { Option } from 'effect';\nimport type { StaticEffectIR, StaticFlowNode } from './types';\nimport { getStaticChildren } from './types';\n\nexport interface IRVisit {\n  readonly node: StaticFlowNode;\n  readonly parent: StaticFlowNode | undefined;\n  readonly ancestors: readonly StaticFlowNode[];\n  readonly index: number;\n}\n\nexport interface IRIndex {\n  readonly nodes: readonly StaticFlowNode[];\n  readonly byId: ReadonlyMap<string, StaticFlowNode>;\n  readonly parentById: ReadonlyMap<string, StaticFlowNode>;\n  readonly spanPathById: ReadonlyMap<string, readonly string[]>;\n  readonly idsBySpanPath: ReadonlyMap<string, readonly string[]>;\n}\n\n/** Exhaustive child access with an empty-array identity for leaf nodes. */\nexport const childrenOf = (node: StaticFlowNode): readonly StaticFlowNode[] =>\n  Option.getOrElse(getStaticChildren(node), () => [] as const);\n\n/** Depth-first pre-order traversal of an IR forest. */\nexport const visitIR = (\n  roots: readonly StaticFlowNode[],\n  visitor: (visit: IRVisit) => void,\n): void => {\n  let index = 0;\n  const visit = (\n    nodes: readonly StaticFlowNode[],\n    parent: StaticFlowNode | undefined,\n    ancestors: readonly StaticFlowNode[],\n  ): void => {\n    for (const node of nodes) {\n      visitor({ node, parent, ancestors, index: index++ });\n      visit(childrenOf(node), node, [...ancestors, node]);\n    }\n  };\n  visit(roots, undefined, []);\n};\n\nexport const flattenIR = (\n  roots: readonly StaticFlowNode[],\n): readonly StaticFlowNode[] => {\n  const nodes: StaticFlowNode[] = [];\n  visitIR(roots, ({ node }) => nodes.push(node));\n  return nodes;\n};\n\n/** Name emitted by Effect's runtime tracer, when statically exact. */\nexport const runtimeSpanName = (\n  node: StaticFlowNode,\n): string | undefined => {\n  if (node.spanName) return node.spanName;\n  return node.type === 'effect' ? node.tracedName : undefined;\n};\n\nexport const runtimeSpanNames = (\n  node: StaticFlowNode,\n): readonly string[] => {\n  if (node.spanNames && node.spanNames.length > 0) return node.spanNames;\n  const name = runtimeSpanName(node);\n  return name ? [name] : [];\n};\n\nexport const spanPathKey = (path: readonly string[]): string =>\n  path.join('\\u001f');\n\n/** Build all common indexes once for diagnostics, renderers, and overlays. */\nexport const indexIR = (ir: StaticEffectIR): IRIndex => {\n  const nodes: StaticFlowNode[] = [];\n  const byId = new Map<string, StaticFlowNode>();\n  const parentById = new Map<string, StaticFlowNode>();\n  const spanPathById = new Map<string, readonly string[]>();\n  const mutableIdsBySpanPath = new Map<string, string[]>();\n\n  visitIR(ir.root.children, ({ node, parent, ancestors }) => {\n    nodes.push(node);\n    byId.set(node.id, node);\n    if (parent) parentById.set(node.id, parent);\n\n    const ownNames = runtimeSpanNames(node);\n    if (ownNames.length === 0) return;\n    const ancestorPath = ancestors.flatMap((ancestor) => {\n      return runtimeSpanNames(ancestor);\n    });\n    const path = [...ancestorPath, ...ownNames];\n    spanPathById.set(node.id, path);\n    for (let i = 1; i <= ownNames.length; i++) {\n      const key = spanPathKey([...ancestorPath, ...ownNames.slice(0, i)]);\n      const ids = mutableIdsBySpanPath.get(key) ?? [];\n      if (!ids.includes(node.id)) ids.push(node.id);\n      mutableIdsBySpanPath.set(key, ids);\n    }\n  });\n\n  return {\n    nodes,\n    byId,\n    parentById,\n    spanPathById,\n    idsBySpanPath: mutableIdsBySpanPath,\n  };\n};\n","/** Located facts used to assess source representation and runtime joinability. */\n\nimport type { SourceLocation, StaticEffectIR, StaticFlowNode } from './types';\nimport { indexIR, runtimeSpanName } from './ir';\n\nexport type FidelityFindingKind =\n  | 'unknown-node'\n  | 'opaque-node'\n  | 'dynamic-span-name'\n  | 'duplicate-span-path';\n\nexport interface FidelityFinding {\n  readonly kind: FidelityFindingKind;\n  readonly nodeId: string;\n  readonly message: string;\n  readonly suggestion: string;\n  readonly reason?: string | undefined;\n  readonly location?: SourceLocation | undefined;\n}\n\nexport interface FidelityDimension {\n  readonly exact: boolean;\n  readonly resolved: number;\n  readonly total: number;\n  readonly rate: number;\n}\n\nexport interface IRFidelityAssessment {\n  readonly exact: boolean;\n  readonly score: number;\n  readonly sourceRepresentation: FidelityDimension;\n  readonly runtimeJoinability: FidelityDimension;\n  readonly staticOnlyNodes: number;\n  readonly findings: readonly FidelityFinding[];\n}\n\nconst findingForNode = (node: StaticFlowNode): FidelityFinding | undefined => {\n  if (node.type === 'unknown') {\n    return {\n      kind: 'unknown-node',\n      nodeId: node.id,\n      message: `The analyzer could not resolve this expression: ${node.reason}`,\n      suggestion: 'Use a supported Effect v4 construct or extract the expression into a named Effect.fn operation.',\n      reason: node.reason,\n      location: node.location,\n    };\n  }\n  if (node.type === 'opaque') {\n    return {\n      kind: 'opaque-node',\n      nodeId: node.id,\n      message: `The analyzer intentionally treats this source as opaque: ${node.reason}`,\n      suggestion: 'Extract diagram-relevant work into a named Effect.fn operation or an explicit Effect.withSpan region.',\n      reason: node.reason,\n      location: node.location,\n    };\n  }\n  if (\n    node.spanNameDynamic === true ||\n    (node.type === 'effect' &&\n      node.callee.includes('withSpan') &&\n      runtimeSpanName(node) === undefined)\n  ) {\n    return {\n      kind: 'dynamic-span-name',\n      nodeId: node.id,\n      message: 'The runtime span name is computed, so a trace cannot be joined to this static node exactly.',\n      suggestion: 'Use a literal Effect.withSpan name and put dynamic values in span attributes.',\n      location: node.location,\n    };\n  }\n  return undefined;\n};\n\nconst rate = (resolved: number, total: number): number =>\n  total === 0 ? 1 : resolved / total;\n\nexport const assessIRFidelity = (ir: StaticEffectIR): IRFidelityAssessment => {\n  const index = indexIR(ir);\n  const findings: FidelityFinding[] = [];\n  const sourceUnresolvedIds = new Set<string>();\n  const runtimeInexactIds = new Set<string>();\n  const runtimeNodeIds = new Set(index.spanPathById.keys());\n\n  for (const node of index.nodes) {\n    const finding = findingForNode(node);\n    if (!finding) continue;\n    findings.push(finding);\n    if (finding.kind === 'unknown-node' || finding.kind === 'opaque-node') {\n      sourceUnresolvedIds.add(node.id);\n    }\n    if (finding.kind === 'dynamic-span-name') {\n      runtimeNodeIds.add(node.id);\n      runtimeInexactIds.add(node.id);\n    }\n  }\n\n  for (const [spanPath, ids] of index.idsBySpanPath) {\n    if (ids.length < 2) continue;\n    const printablePath = spanPath.split('\\u001f').join(' > ');\n    for (const nodeId of ids) {\n      runtimeInexactIds.add(nodeId);\n      const node = index.byId.get(nodeId);\n      findings.push({\n        kind: 'duplicate-span-path',\n        nodeId,\n        message: `Multiple static nodes emit the runtime span path \"${printablePath}\".`,\n        suggestion: 'Give sibling Effect.withSpan or Effect.fn regions distinct literal names.',\n        location: node?.location,\n      });\n    }\n  }\n\n  for (const nodeId of sourceUnresolvedIds) {\n    if (runtimeNodeIds.has(nodeId)) runtimeInexactIds.add(nodeId);\n  }\n\n  const sourceResolved = index.nodes.length - sourceUnresolvedIds.size;\n  const runtimeResolved = runtimeNodeIds.size - runtimeInexactIds.size;\n  const penalizedIds = new Set([...sourceUnresolvedIds, ...runtimeInexactIds]);\n  const score = index.nodes.length === 0\n    ? 100\n    : Math.round(((index.nodes.length - penalizedIds.size) / index.nodes.length) * 100);\n\n  return {\n    exact: findings.length === 0,\n    score,\n    sourceRepresentation: {\n      exact: sourceUnresolvedIds.size === 0,\n      resolved: sourceResolved,\n      total: index.nodes.length,\n      rate: rate(sourceResolved, index.nodes.length),\n    },\n    runtimeJoinability: {\n      exact: runtimeInexactIds.size === 0,\n      resolved: runtimeResolved,\n      total: runtimeNodeIds.size,\n      rate: rate(runtimeResolved, runtimeNodeIds.size),\n    },\n    staticOnlyNodes: index.nodes.length - index.spanPathById.size,\n    findings,\n  };\n};\n","/* eslint-disable @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-redundant-type-constituents */\nimport { basename, relative, resolve } from 'path';\nimport { loadTsMorph } from './ts-morph-loader';\n\nexport interface CommandDefinitionSummary {\n  readonly id: string;\n  readonly file: string;\n  readonly variableName: string;\n  readonly commandName: string;\n}\n\nexport interface RuntimeArchitectureStage {\n  readonly source: string;\n  readonly kind: 'identifier' | 'call' | 'function' | 'literal' | 'object' | 'expression';\n}\n\nexport interface RuntimeArchitectureSummary {\n  readonly id: string;\n  readonly file: string;\n  readonly runtimeName: string;\n  readonly constructor: string;\n  readonly model: RuntimeArchitectureStage | undefined;\n  readonly flagsSchema: RuntimeArchitectureStage | undefined;\n  readonly flags: RuntimeArchitectureStage | undefined;\n  readonly init: RuntimeArchitectureStage | undefined;\n  readonly update: RuntimeArchitectureStage | undefined;\n  readonly view: RuntimeArchitectureStage | undefined;\n  readonly container: RuntimeArchitectureStage | undefined;\n  readonly subscriptions: RuntimeArchitectureStage | undefined;\n  readonly resources: RuntimeArchitectureStage | undefined;\n  readonly managedResources: RuntimeArchitectureStage | undefined;\n  readonly routing: RuntimeArchitectureStage | undefined;\n  readonly routingHandlers: readonly string[];\n  readonly crash: RuntimeArchitectureStage | undefined;\n  readonly crashHandlers: readonly string[];\n  readonly slowView: RuntimeArchitectureStage | undefined;\n  readonly title: RuntimeArchitectureStage | undefined;\n  readonly devtools: RuntimeArchitectureStage | undefined;\n  readonly capabilities: readonly string[];\n  readonly relatedCommands: readonly string[];\n}\n\nexport interface ProjectArchitectureSummary {\n  readonly runtimes: readonly RuntimeArchitectureSummary[];\n  readonly commandDefinitions: readonly CommandDefinitionSummary[];\n  readonly layerAssemblies: readonly LayerAssemblySummary[];\n  readonly filesScanned: number;\n}\n\nexport interface LayerAssemblySummary {\n  readonly id: string;\n  readonly file: string;\n  readonly name: string;\n  readonly constructor: string;\n  readonly operations: readonly string[];\n  readonly references: readonly string[];\n}\n\ninterface ExtractProjectArchitectureOptions {\n  readonly tsconfig?: string | undefined;\n}\n\nconst FEATURE_ORDER = [\n  'flags',\n  'routing',\n  'subscriptions',\n  'resources',\n  'managedResources',\n  'crash',\n  'slowView',\n  'title',\n  'devtools',\n] as const;\n\nconst describeText = (text: string, fallback: string): string => {\n  const trimmed = text.replace(/\\s+/g, ' ').trim();\n  if (!trimmed) return fallback;\n  if (trimmed.length <= 80) return trimmed;\n  return `${trimmed.slice(0, 77)}...`;\n};\n\nconst detectStageKind = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  expr: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): RuntimeArchitectureStage['kind'] => {\n  if (Node.isIdentifier(expr) || Node.isPropertyAccessExpression(expr)) return 'identifier';\n  if (Node.isCallExpression(expr)) return 'call';\n  if (Node.isArrowFunction(expr) || Node.isFunctionExpression(expr) || Node.isMethodDeclaration(expr)) return 'function';\n  if (Node.isObjectLiteralExpression(expr)) return 'object';\n  if (\n    Node.isStringLiteral(expr) ||\n    Node.isNumericLiteral(expr) ||\n    expr.getKindName() === 'TrueKeyword' ||\n    expr.getKindName() === 'FalseKeyword' ||\n    expr.getKindName() === 'NullKeyword'\n  ) return 'literal';\n  return 'expression';\n};\n\nconst describeStage = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  expr: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): RuntimeArchitectureStage => ({\n  source: describeText(expr.getText(), expr.getKindName()),\n  kind: detectStageKind(expr, Node),\n});\n\nconst getPropertyExpression = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  objectLiteral: any,\n  name: string,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any | undefined => {\n  const prop = objectLiteral.getProperty(name);\n  if (!prop) return undefined;\n  if (Node.isPropertyAssignment(prop)) return prop.getInitializer();\n  if (Node.isShorthandPropertyAssignment(prop)) return prop.getNameNode();\n  if (Node.isMethodDeclaration(prop)) return prop;\n  return undefined;\n};\n\nconst extractNestedHandlers = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  expr: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): readonly string[] => {\n  if (!expr || !Node.isObjectLiteralExpression(expr)) return [];\n  return expr.getProperties().flatMap(\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    (prop: any) => {\n      if (\n        Node.isPropertyAssignment(prop) ||\n        Node.isShorthandPropertyAssignment(prop) ||\n        Node.isMethodDeclaration(prop)\n      ) {\n        return [prop.getName()];\n      }\n      return [];\n    },\n  );\n};\n\nconst inferCapabilities = (\n  summary: Omit<RuntimeArchitectureSummary, 'capabilities' | 'relatedCommands'>,\n): string[] => {\n  const features: string[] = [];\n  if (summary.flags || summary.flagsSchema) features.push('flags');\n  if (summary.routing) features.push('routing');\n  if (summary.subscriptions) features.push('subscriptions');\n  if (summary.resources) features.push('resources');\n  if (summary.managedResources) features.push('managedResources');\n  if (summary.crash) features.push('crash');\n  if (summary.slowView) features.push('slowView');\n  if (summary.title) features.push('title');\n  if (summary.devtools) features.push('devtools');\n  return FEATURE_ORDER.filter((feature) => features.includes(feature));\n};\n\nconst isMakeProgramCall = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): boolean => {\n  const expression = call.getExpression();\n  const text = expression.getText();\n  return Node.isIdentifier(expression)\n    ? text === 'makeProgram'\n    : Node.isPropertyAccessExpression(expression) && text.endsWith('.makeProgram');\n};\n\nconst isCommandDefineCall = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): boolean => {\n  const expression = call.getExpression();\n  if (!Node.isPropertyAccessExpression(expression)) return false;\n  return expression.getName() === 'define' && expression.getExpression().getText().endsWith('Command');\n};\n\nconst runtimeNameForCall = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n  filePath: string,\n  ordinal: number,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): string => {\n  const parent = call.getParent();\n  if (parent && Node.isVariableDeclaration(parent)) return parent.getName();\n  return `${basename(filePath, '.ts')}-runtime-${String(ordinal)}`;\n};\n\nconst isLayerCall = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n): boolean => {\n  const text = call.getExpression().getText();\n  return text.startsWith('Layer.');\n};\n\nconst isLayerAssemblyRoot = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): boolean => {\n  if (!isLayerCall(call)) return false;\n  const parent = call.getParent();\n  if (!parent) return false;\n  if (Node.isVariableDeclaration(parent) && parent.getInitializer() === call) return true;\n  if (Node.isReturnStatement(parent) && parent.getExpression() === call) return true;\n  return false;\n};\n\nconst getLayerAssemblyName = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n  filePath: string,\n  ordinal: number,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): string => {\n  const parent = call.getParent();\n  if (parent && Node.isVariableDeclaration(parent)) return parent.getName();\n  return `${basename(filePath, '.ts')}-layer-${String(ordinal)}`;\n};\n\nconst extractLayerAssembly = (\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: any,\n  filePath: string,\n  name: string,\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Node: any,\n): LayerAssemblySummary => {\n  const operations: string[] = [];\n  const references = new Set<string>();\n\n  const collectLayerRefs = (\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    expr: any,\n  ): void => {\n    if (!expr) return;\n    if (Node.isIdentifier(expr)) {\n      const text = expr.getText();\n      if (!['Layer', 'Effect'].includes(text)) references.add(text);\n      return;\n    }\n    if (Node.isPropertyAccessExpression(expr)) {\n      const text = expr.getText();\n      if (!text.startsWith('Layer.') && !text.startsWith('Effect.')) {\n        references.add(text);\n      }\n      return;\n    }\n    if (Node.isCallExpression(expr)) {\n      collectLayerCall(expr);\n      return;\n    }\n    if (Node.isArrayLiteralExpression(expr)) {\n      for (const element of expr.getElements()) collectLayerRefs(element);\n    }\n  };\n\n  const collectLayerCall = (\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    current: any,\n  ): void => {\n    const exprText = current.getExpression().getText();\n    if (exprText.startsWith('Layer.')) {\n      operations.push(exprText.replace(/^Layer\\./, ''));\n    } else if (exprText.endsWith('.pipe')) {\n      operations.push('pipe');\n      const pipeBase = current.getExpression().getExpression();\n      collectLayerRefs(pipeBase);\n      if (Node.isCallExpression(pipeBase)) {\n        collectLayerCall(pipeBase);\n      }\n    }\n    for (const arg of current.getArguments()) {\n      collectLayerRefs(arg);\n    }\n  };\n\n  collectLayerCall(call);\n\n  return {\n    id: `${filePath}:${name}`,\n    file: filePath,\n    name,\n    constructor: call.getExpression().getText(),\n    operations,\n    references: [...references],\n  };\n};\n\nexport function extractProjectArchitecture(\n  filePaths: readonly string[],\n  options: ExtractProjectArchitectureOptions = {},\n): ProjectArchitectureSummary {\n  try {\n    const { Project, Node } = loadTsMorph();\n    const project = options.tsconfig\n      ? new Project({ tsConfigFilePath: options.tsconfig })\n      : new Project({ skipAddingFilesFromTsConfig: true, compilerOptions: { allowJs: true } });\n\n    const sourceFiles = filePaths.flatMap((filePath) => {\n      try {\n        return [project.addSourceFileAtPath(filePath)];\n      } catch {\n        return [];\n      }\n    });\n\n    const commands: CommandDefinitionSummary[] = [];\n    const runtimes: RuntimeArchitectureSummary[] = [];\n    const layerAssemblies: LayerAssemblySummary[] = [];\n\n    for (const sourceFile of sourceFiles) {\n      const filePath = resolve(sourceFile.getFilePath());\n      let runtimeOrdinal = 0;\n      let layerOrdinal = 0;\n\n      sourceFile.forEachDescendant((node) => {\n        if (!Node.isCallExpression(node)) return undefined;\n\n        if (isCommandDefineCall(node, Node)) {\n          const parent = node.getParent();\n          const variableName =\n            parent && Node.isVariableDeclaration(parent)\n              ? parent.getName()\n              : `command-${String(commands.length + 1)}`;\n          const firstArg = node.getArguments()[0];\n          const commandName =\n            firstArg && Node.isStringLiteral(firstArg)\n              ? firstArg.getLiteralText()\n              : variableName;\n          commands.push({\n            id: `${filePath}:${variableName}`,\n            file: filePath,\n            variableName,\n            commandName,\n          });\n          return undefined;\n        }\n\n        if (isLayerAssemblyRoot(node, Node)) {\n          layerOrdinal += 1;\n          const layerName = getLayerAssemblyName(node, filePath, layerOrdinal, Node);\n          layerAssemblies.push(extractLayerAssembly(node, filePath, layerName, Node));\n          return undefined;\n        }\n\n        if (!isMakeProgramCall(node, Node)) return undefined;\n        const configArg = node.getArguments()[0];\n        if (!configArg || !Node.isObjectLiteralExpression(configArg)) return undefined;\n\n        runtimeOrdinal += 1;\n        const runtimeName = runtimeNameForCall(node, filePath, runtimeOrdinal, Node);\n        const model = getPropertyExpression(configArg, 'Model', Node);\n        const flagsSchema = getPropertyExpression(configArg, 'Flags', Node);\n        const flags = getPropertyExpression(configArg, 'flags', Node);\n        const init = getPropertyExpression(configArg, 'init', Node);\n        const update = getPropertyExpression(configArg, 'update', Node);\n        const view = getPropertyExpression(configArg, 'view', Node);\n        const container = getPropertyExpression(configArg, 'container', Node);\n        const subscriptions = getPropertyExpression(configArg, 'subscriptions', Node);\n        const resources = getPropertyExpression(configArg, 'resources', Node);\n        const managedResources = getPropertyExpression(configArg, 'managedResources', Node);\n        const routing = getPropertyExpression(configArg, 'routing', Node);\n        const crash = getPropertyExpression(configArg, 'crash', Node);\n        const slowView = getPropertyExpression(configArg, 'slowView', Node);\n        const title = getPropertyExpression(configArg, 'title', Node);\n        const devtools = getPropertyExpression(configArg, 'devtools', Node);\n\n        const baseRuntime = {\n          id: `${filePath}:${runtimeName}`,\n          file: filePath,\n          runtimeName,\n          constructor: node.getExpression().getText(),\n          model: model ? describeStage(model, Node) : undefined,\n          flagsSchema: flagsSchema ? describeStage(flagsSchema, Node) : undefined,\n          flags: flags ? describeStage(flags, Node) : undefined,\n          init: init ? describeStage(init, Node) : undefined,\n          update: update ? describeStage(update, Node) : undefined,\n          view: view ? describeStage(view, Node) : undefined,\n          container: container ? describeStage(container, Node) : undefined,\n          subscriptions: subscriptions ? describeStage(subscriptions, Node) : undefined,\n          resources: resources ? describeStage(resources, Node) : undefined,\n          managedResources: managedResources ? describeStage(managedResources, Node) : undefined,\n          routing: routing ? describeStage(routing, Node) : undefined,\n          routingHandlers: extractNestedHandlers(routing, Node),\n          crash: crash ? describeStage(crash, Node) : undefined,\n          crashHandlers: extractNestedHandlers(crash, Node),\n          slowView: slowView ? describeStage(slowView, Node) : undefined,\n          title: title ? describeStage(title, Node) : undefined,\n          devtools: devtools ? describeStage(devtools, Node) : undefined,\n        };\n\n        runtimes.push({\n          ...baseRuntime,\n          capabilities: inferCapabilities(baseRuntime),\n          relatedCommands: [],\n        });\n        return undefined;\n      });\n    }\n\n    const commandsByFile = new Map<string, string[]>();\n    for (const command of commands) {\n      const current = commandsByFile.get(command.file) ?? [];\n      if (!current.includes(command.commandName)) current.push(command.commandName);\n      commandsByFile.set(command.file, current);\n    }\n\n    return {\n      runtimes: runtimes.map((runtime) => ({\n        ...runtime,\n        relatedCommands: commandsByFile.get(runtime.file) ?? [],\n      })),\n      commandDefinitions: commands,\n      layerAssemblies,\n      filesScanned: sourceFiles.length,\n    };\n  } catch {\n    return {\n      runtimes: [],\n      commandDefinitions: [],\n      layerAssemblies: [],\n      filesScanned: 0,\n    };\n  }\n}\n\nexport function renderProjectArchitecture(\n  summary: ProjectArchitectureSummary,\n  baseDir?: string,\n): string {\n  if (summary.runtimes.length === 0 && summary.layerAssemblies.length === 0) {\n    return '(no runtime architecture detected)';\n  }\n\n  const runtimeSections = summary.runtimes.map((runtime) => {\n    const fileLabel = baseDir\n      ? relative(baseDir, runtime.file) || basename(runtime.file)\n      : runtime.file;\n    const lines: string[] = [];\n    lines.push(`${runtime.runtimeName} (${fileLabel})`);\n    lines.push(`  Constructor: ${runtime.constructor}`);\n    lines.push(\n      `  Loop: ${runtime.flags || runtime.flagsSchema ? 'Flags -> init -> Model + Commands' : 'init -> Model + Commands'}`,\n    );\n    lines.push('  Loop: Message -> update -> Model + Commands');\n    lines.push('  Loop: Model -> view -> Html');\n    if (runtime.subscriptions) {\n      lines.push(`  Subscriptions: ${runtime.subscriptions.source} -> Message stream`);\n    }\n    if (runtime.resources) {\n      lines.push(`  Resources: ${runtime.resources.source}`);\n    }\n    if (runtime.managedResources) {\n      lines.push(`  Managed resources: ${runtime.managedResources.source}`);\n    }\n    if (runtime.routing) {\n      const handlers =\n        runtime.routingHandlers.length > 0\n          ? ` (${runtime.routingHandlers.join(', ')})`\n          : '';\n      lines.push(`  Routing: ${runtime.routing.source}${handlers}`);\n    }\n    if (runtime.crash) {\n      const handlers =\n        runtime.crashHandlers.length > 0\n          ? ` (${runtime.crashHandlers.join(', ')})`\n          : '';\n      lines.push(`  Crash handling: ${runtime.crash.source}${handlers}`);\n    }\n    if (runtime.slowView) {\n      lines.push(`  Slow view: ${runtime.slowView.source}`);\n    }\n    if (runtime.title) {\n      lines.push(`  Title: ${runtime.title.source}`);\n    }\n    if (runtime.devtools) {\n      lines.push(`  Devtools: ${runtime.devtools.source}`);\n    }\n    if (runtime.relatedCommands.length > 0) {\n      lines.push(`  Commands in file: ${runtime.relatedCommands.join(', ')}`);\n    }\n    if (runtime.capabilities.length > 0) {\n      lines.push(`  Capabilities: ${runtime.capabilities.join(', ')}`);\n    }\n    return lines.join('\\n');\n  });\n\n  const commandFiles = new Map<string, string[]>();\n  for (const command of summary.commandDefinitions) {\n    const fileLabel = baseDir\n      ? relative(baseDir, command.file) || basename(command.file)\n      : command.file;\n    const current = commandFiles.get(fileLabel) ?? [];\n    if (!current.includes(command.commandName)) current.push(command.commandName);\n    commandFiles.set(fileLabel, current);\n  }\n\n  const commandSection =\n    commandFiles.size === 0\n      ? ''\n      : `\\n\\nCommand definitions:\\n${[...commandFiles.entries()]\n          .map(([file, names]) => `  ${file}: ${names.join(', ')}`)\n          .join('\\n')}`;\n\n  const isTestLayer = (layer: LayerAssemblySummary): boolean =>\n    /(?:^|\\/)__tests__\\/|(?:^|\\/)test\\/|\\.test\\.[cm]?[jt]sx?$/.test(layer.file);\n\n  const renderLayerBlock = (title: string, layers: readonly LayerAssemblySummary[]): string =>\n    layers.length === 0\n      ? ''\n      : `\\n\\n${title}:\\n${layers\n          .map((layer) => {\n            const fileLabel = baseDir\n              ? relative(baseDir, layer.file) || basename(layer.file)\n              : layer.file;\n            const refs = layer.references.length > 0 ? `\\n    References: ${layer.references.join(', ')}` : '';\n            const ops = layer.operations.length > 0 ? layer.operations.join(' -> ') : layer.constructor;\n            return `  ${layer.name} (${fileLabel})\\n    Ops: ${ops}${refs}`;\n          })\n          .join('\\n')}`;\n\n  const appLayers = summary.layerAssemblies.filter((layer) => !isTestLayer(layer));\n  const testLayers = summary.layerAssemblies.filter((layer) => isTestLayer(layer));\n  const layerSection =\n    renderLayerBlock('Layer assemblies', appLayers) +\n    renderLayerBlock('Test layer assemblies', testLayers);\n\n  return [\n    `Project architecture (${String(summary.runtimes.length)} runtime${summary.runtimes.length === 1 ? '' : 's'}, ${String(summary.layerAssemblies.length)} layer assembl${summary.layerAssemblies.length === 1 ? 'y' : 'ies'})`,\n    ...runtimeSections,\n  ].join('\\n\\n') + commandSection + layerSection;\n}\n","/**\n * Node analysis session.\n *\n * This is the single Node seam for configuring ts-morph and running file,\n * source, project, or coverage analysis. Importing internal analyzer modules is\n * deliberately not required to initialize the runtime.\n */\n\nimport './register-node-ts-morph';\n\nimport type { Effect } from 'effect';\nimport type { AnalysisError, AnalyzerOptions, StaticEffectIR } from './types';\nimport { analyze as analyzeFile } from './analyze';\nimport {\n  analyzeProject,\n  analyzeProjectCorpus,\n  runCoverageAudit,\n  runCoverageAuditFromCorpus,\n  type AnalyzeProjectOptions,\n  type CoverageAuditResult,\n  type ProjectAnalysisResult,\n} from './project-analyzer';\nimport { clearProjectCache } from './ts-morph-loader';\nimport {\n  scanProjectCorpus,\n  type ProjectCorpus,\n  type ScanProjectCorpusOptions,\n} from './project-corpus';\n\nexport interface AnalysisSession {\n  readonly file: (\n    filePath: string,\n    options?: AnalyzerOptions,\n  ) => ReturnType<typeof analyzeFile>;\n  readonly source: (\n    code: string,\n    options?: AnalyzerOptions,\n  ) => ReturnType<typeof analyzeFile.source>;\n  readonly corpus: (\n    dirPath: string,\n    options?: ScanProjectCorpusOptions,\n  ) => Effect.Effect<ProjectCorpus>;\n  readonly project: (\n    dirPath: string,\n    options?: AnalyzeProjectOptions,\n  ) => Effect.Effect<ProjectAnalysisResult>;\n  readonly projectFromCorpus: (\n    corpus: ProjectCorpus,\n    options?: AnalyzeProjectOptions,\n  ) => Effect.Effect<ProjectAnalysisResult>;\n  readonly audit: (\n    dirPath: string,\n    options?: AnalyzeProjectOptions,\n  ) => Effect.Effect<CoverageAuditResult>;\n  readonly auditFromCorpus: (\n    corpus: ProjectCorpus,\n    options?: AnalyzeProjectOptions,\n  ) => Effect.Effect<CoverageAuditResult>;\n  readonly clearCaches: () => void;\n}\n\nexport const createAnalysisSession = (): AnalysisSession => ({\n  file: analyzeFile,\n  source: analyzeFile.source,\n  corpus: scanProjectCorpus,\n  project: analyzeProject,\n  projectFromCorpus: analyzeProjectCorpus,\n  audit: runCoverageAudit,\n  auditFromCorpus: runCoverageAuditFromCorpus,\n  clearCaches: clearProjectCache,\n});\n\n/** Default session for ordinary Node callers. */\nexport const analysis = createAnalysisSession();\n\nexport type AnalysisEffect = Effect.Effect<\n  readonly StaticEffectIR[],\n  AnalysisError\n>;\n","/** Native CI policy evaluation for project coverage audits. */\n\nimport type { AuditAssessment } from './audit-assessment';\n\nexport type AuditPolicyViolationKind =\n  | 'failed-files'\n  | 'suspicious-zeros'\n  | 'effect-adoption'\n  | 'source-resolution';\n\nexport interface AuditPolicy {\n  readonly maxFailedFiles?: number | undefined;\n  readonly maxSuspiciousZeros?: number | undefined;\n  readonly minEffectAdoption?: number | undefined;\n  readonly minSourceResolution?: number | undefined;\n}\n\nexport interface AuditPolicyFacts {\n  readonly assessment: AuditAssessment;\n  readonly failedFiles: number;\n  readonly suspiciousZeros: number;\n}\n\nexport interface AuditPolicyViolation {\n  readonly kind: AuditPolicyViolationKind;\n  readonly actual: number;\n  readonly expected: number;\n  readonly message: string;\n}\n\nexport interface AuditPolicyDecision {\n  readonly passed: boolean;\n  readonly violations: readonly AuditPolicyViolation[];\n}\n\nexport const evaluateAuditPolicy = (\n  facts: AuditPolicyFacts,\n  policy: AuditPolicy,\n): AuditPolicyDecision => {\n  const violations: AuditPolicyViolation[] = [];\n\n  if (\n    policy.maxFailedFiles !== undefined &&\n    facts.failedFiles > policy.maxFailedFiles\n  ) {\n    violations.push({\n      kind: 'failed-files',\n      actual: facts.failedFiles,\n      expected: policy.maxFailedFiles,\n      message: `${String(facts.failedFiles)} analysis failures exceed the allowed ${String(policy.maxFailedFiles)}.`,\n    });\n  }\n  if (\n    policy.maxSuspiciousZeros !== undefined &&\n    facts.suspiciousZeros > policy.maxSuspiciousZeros\n  ) {\n    violations.push({\n      kind: 'suspicious-zeros',\n      actual: facts.suspiciousZeros,\n      expected: policy.maxSuspiciousZeros,\n      message: `${String(facts.suspiciousZeros)} suspicious zero-program files exceed the allowed ${String(policy.maxSuspiciousZeros)}.`,\n    });\n  }\n  if (\n    policy.minEffectAdoption !== undefined &&\n    facts.assessment.effectAdoption.rate < policy.minEffectAdoption\n  ) {\n    violations.push({\n      kind: 'effect-adoption',\n      actual: facts.assessment.effectAdoption.rate,\n      expected: policy.minEffectAdoption,\n      message: `Effect adoption ${(facts.assessment.effectAdoption.rate * 100).toFixed(1)}% is below the required ${(policy.minEffectAdoption * 100).toFixed(1)}%.`,\n    });\n  }\n  if (\n    policy.minSourceResolution !== undefined &&\n    facts.assessment.sourceResolution.rate < policy.minSourceResolution\n  ) {\n    violations.push({\n      kind: 'source-resolution',\n      actual: facts.assessment.sourceResolution.rate,\n      expected: policy.minSourceResolution,\n      message: `IR source resolution ${(facts.assessment.sourceResolution.rate * 100).toFixed(2)}% is below the required ${(policy.minSourceResolution * 100).toFixed(2)}%.`,\n    });\n  }\n\n  return { passed: violations.length === 0, violations };\n};\n","/** Stable human, quiet, and JSON rendering for coverage audits. */\n\nimport { sep } from 'path';\nimport type { AuditPolicyDecision } from '../audit-policy';\nimport type { CoverageAuditResult } from '../project-analyzer';\n\nexport type CoverageReportMode = 'human' | 'quiet' | 'json';\n\nexport interface CoverageReportOptions {\n  readonly mode: CoverageReportMode;\n  readonly root: string;\n  readonly decision?: AuditPolicyDecision | undefined;\n  readonly pretty?: boolean | undefined;\n  readonly showSuspiciousZeros?: boolean | undefined;\n  readonly showTopUnknown?: boolean | undefined;\n  readonly showTopUnknownReasons?: boolean | undefined;\n  readonly showByFolder?: boolean | undefined;\n  readonly timestamp?: string | undefined;\n}\n\nconst percent = (rate: number, digits: number): string =>\n  `${(rate * 100).toFixed(digits)}%`;\n\nconst ratio = (numerator: number, denominator: number): string =>\n  `${String(numerator)}/${String(denominator)}`;\n\nconst renderViolations = (decision: AuditPolicyDecision | undefined): string[] =>\n  decision?.violations.map((violation) => `  [${violation.kind}] ${violation.message}`) ?? [];\n\nconst renderQuiet = (\n  audit: CoverageAuditResult,\n  decision: AuditPolicyDecision | undefined,\n): string => {\n  const assessment = audit.assessment;\n  const status = decision === undefined ? '' : `${decision.passed ? 'PASS' : 'FAIL'} | `;\n  const summary = [\n    `Coverage audit: ${status}${String(audit.discovered)} files`,\n    `Effect adoption ${percent(assessment.effectAdoption.rate, 1)} (${ratio(assessment.effectAdoption.numerator, assessment.effectAdoption.denominator)})`,\n    `analysis success ${percent(assessment.analysisSuccess.rate, 1)} (${ratio(assessment.analysisSuccess.numerator, assessment.analysisSuccess.denominator)})`,\n    `source resolution ${percent(assessment.sourceResolution.rate, 2)} (${ratio(assessment.sourceResolution.numerator, assessment.sourceResolution.denominator)})`,\n    `failed ${String(audit.failed)}`,\n    `suspicious ${String(audit.suspiciousZeros.length)}`,\n  ].join(' | ');\n  const violations = renderViolations(decision);\n  return violations.length === 0 ? summary : [summary, ...violations].join('\\n');\n};\n\nconst renderHuman = (\n  audit: CoverageAuditResult,\n  options: CoverageReportOptions,\n): string => {\n  const assessment = audit.assessment;\n  const lines = [\n    `Coverage audit for ${options.root}`,\n    `Files discovered:      ${String(audit.discovered)}`,\n    `Effect-bearing files:  ${String(audit.analyzed)}`,\n    `No Effect programs:    ${String(audit.zeroPrograms)}`,\n    `Analysis failures:     ${String(audit.failed)}`,\n    `Suspicious zero files: ${String(audit.suspiciousZeros.length)}`,\n    `Effect adoption:       ${percent(assessment.effectAdoption.rate, 1)} (${ratio(assessment.effectAdoption.numerator, assessment.effectAdoption.denominator)} discovered files)`,\n    `Analysis success:      ${percent(assessment.analysisSuccess.rate, 1)} (${ratio(assessment.analysisSuccess.numerator, assessment.analysisSuccess.denominator)} relevant files)`,\n    `IR source resolution:  ${percent(assessment.sourceResolution.rate, 2)} (${ratio(assessment.sourceResolution.numerator, assessment.sourceResolution.denominator)} IR nodes)`,\n    ...(audit.durationMs === undefined ? [] : [`Duration:              ${String(audit.durationMs)}ms`]),\n    `Zero categories: barrel/index=${String(audit.zeroProgramCategoryCounts.barrel_or_index)}, config/build=${String(audit.zeroProgramCategoryCounts.config_or_build)}, test/dtslint=${String(audit.zeroProgramCategoryCounts.test_or_dtslint)}, type-only=${String(audit.zeroProgramCategoryCounts.type_only)}, suspicious=${String(audit.zeroProgramCategoryCounts.suspicious)}, other=${String(audit.zeroProgramCategoryCounts.other)}`,\n  ];\n\n  if (options.decision) {\n    lines.push('', `Policy: ${options.decision.passed ? 'PASS' : 'FAIL'}`);\n    lines.push(...renderViolations(options.decision));\n  }\n\n  if (options.showByFolder && audit.outcomes.length > 0) {\n    const byFolder = new Map<string, { ok: number; zero: number; fail: number }>();\n    for (const outcome of audit.outcomes) {\n      const relative = outcome.file.replace(options.root, '').replace(/^[/\\\\]+/, '');\n      const folder = relative.split(sep)[0] ?? '(root)';\n      const counts = byFolder.get(folder) ?? { ok: 0, zero: 0, fail: 0 };\n      counts[outcome.status]++;\n      byFolder.set(folder, counts);\n    }\n    lines.push('', 'By top-level folder:');\n    for (const [folder, counts] of [...byFolder.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n      lines.push(`  ${folder}: ok=${String(counts.ok)} zero=${String(counts.zero)} fail=${String(counts.fail)}`);\n    }\n  }\n\n  const failures = audit.outcomes.filter((outcome) => outcome.status === 'fail');\n  if (failures.length > 0) {\n    lines.push('', 'Analysis failures:');\n    for (const failure of failures) {\n      lines.push(`  ${failure.file}: ${failure.error ?? 'Unknown analysis failure'}`);\n    }\n  }\n\n  if (audit.suspiciousZeros.length > 0) {\n    const suspicious = options.showSuspiciousZeros\n      ? audit.suspiciousZeros\n      : audit.suspiciousZeros.slice(0, 10);\n    lines.push('', options.showSuspiciousZeros ? 'Suspicious zero-program files:' : 'Suspicious zero-program files (sample):');\n    lines.push(...suspicious.map((file) => `  ${file}`));\n    if (suspicious.length < audit.suspiciousZeros.length) {\n      lines.push(`  ... and ${String(audit.suspiciousZeros.length - suspicious.length)} more (use --show-suspicious-zeros)`);\n    }\n  }\n\n  if (options.showTopUnknown) {\n    const unknownNodes = audit.fidelityFindings.filter(\n      (finding) => finding.kind === 'unknown-node',\n    );\n    const findings = unknownNodes.slice(0, 10);\n    if (findings.length > 0) {\n      const header =\n        findings.length < unknownNodes.length\n          ? `Located unknown nodes (showing ${String(findings.length)} of ${String(unknownNodes.length)}):`\n          : 'Located unknown nodes:';\n      lines.push('', header);\n      for (const finding of findings) {\n        const location = finding.location\n          ? `${finding.location.filePath}:${String(finding.location.line)}:${String(finding.location.column)}`\n          : `${finding.file} (${finding.nodeId})`;\n        lines.push(`  ${location}: ${finding.reason ?? finding.message}`);\n      }\n    }\n  }\n  if (options.showTopUnknownReasons && audit.topUnknownReasons && audit.topUnknownReasons.length > 0) {\n    lines.push('', 'Top unknown node reasons:');\n    lines.push(...audit.topUnknownReasons.map(({ reason, count }) => `  ${String(count)}\\t${reason}`));\n  }\n\n  lines.push('', 'Detection is heuristic. Fidelity findings identify unresolved source explicitly.');\n  return lines.join('\\n');\n};\n\nexport const renderCoverageReport = (\n  audit: CoverageAuditResult,\n  options: CoverageReportOptions,\n): string => {\n  if (options.mode === 'quiet') return renderQuiet(audit, options.decision);\n  if (options.mode === 'json') {\n    return JSON.stringify({\n      ...audit,\n      policy: options.decision,\n      timestamp: options.timestamp ?? new Date().toISOString(),\n      dirPath: options.root,\n    }, null, options.pretty ? 2 : undefined);\n  }\n  return renderHuman(audit, options);\n};\n","/**\n * Complexity Metrics Calculator\n *\n * Calculates complexity metrics for Effect programs including:\n * - Cyclomatic complexity (McCabe)\n * - Cognitive complexity (Sonar-style)\n * - Path count (bounded or unbounded)\n * - Depth and breadth metrics\n */\n\nimport { Option } from 'effect';\nimport { getStaticChildren } from './types';\nimport type {\n  StaticEffectIR,\n  StaticFlowNode,\n  ComplexityMetrics,\n  ComplexityThresholds,\n} from './types';\n\n// =============================================================================\n// Default Thresholds\n// =============================================================================\n\nexport const DEFAULT_THRESHOLDS: ComplexityThresholds = {\n  cyclomaticWarning: 10,\n  cyclomaticError: 20,\n  pathCountWarning: 50,\n  maxDepthWarning: 5,\n};\n\n// =============================================================================\n// Main Calculator\n// =============================================================================\n\nexport function calculateComplexity(ir: StaticEffectIR): ComplexityMetrics {\n  const nodes = ir.root.children;\n\n  const cyclomatic = calculateCyclomaticComplexity(nodes);\n  const cognitive = calculateCognitiveComplexity(nodes);\n  const pathCount = calculatePathCount(nodes);\n  const maxDepth = calculateMaxDepth(nodes);\n  const maxParallelBreadth = calculateMaxParallelBreadth(nodes);\n  const decisionPoints = countDecisionPoints(nodes);\n\n  return {\n    cyclomaticComplexity: cyclomatic,\n    cognitiveComplexity: cognitive,\n    pathCount,\n    maxDepth,\n    maxParallelBreadth,\n    decisionPoints,\n  };\n}\n\n// =============================================================================\n// Cyclomatic Complexity\n// =============================================================================\n\nfunction calculateCyclomaticComplexity(\n  nodes: readonly StaticFlowNode[],\n): number {\n  let complexity = 1;\n  for (const node of nodes) {\n    complexity += countDecisionPointsInNode(node);\n  }\n  return complexity;\n}\n\nfunction countDecisionPointsInNode(node: StaticFlowNode): number {\n  const children = getStaticChildren(node);\n  const childList = Option.getOrElse(children, () => [] as readonly StaticFlowNode[]);\n\n  let count = 0;\n\n  switch (node.type) {\n    case 'conditional':\n      count += 1;\n      for (const child of childList) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'race':\n      count += Math.max(0, node.children.length - 1);\n      for (const child of node.children) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'loop':\n      count += 1;\n      count += countDecisionPointsInNode(node.body);\n      break;\n\n    case 'generator':\n    case 'pipe':\n    case 'parallel':\n    case 'error-handler':\n    case 'retry':\n    case 'timeout':\n    case 'resource':\n    case 'layer':\n      for (const child of childList) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'decision':\n      count += 1;\n      for (const child of childList) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'switch':\n      count += Math.max(0, node.cases.length - 1);\n      for (const child of childList) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'try-catch':\n      count += 1;\n      for (const child of childList) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'terminal':\n    case 'opaque':\n      for (const child of childList) {\n        count += countDecisionPointsInNode(child);\n      }\n      break;\n\n    case 'match':\n      if (node.matchedTags && node.matchedTags.length > 1) {\n        count += node.matchedTags.length - 1;\n      }\n      break;\n\n    case 'interruption':\n      if (node.handler) {\n        count += 1;\n        count += countDecisionPointsInNode(node.handler);\n      }\n      if (node.source) {\n        count += countDecisionPointsInNode(node.source);\n      }\n      break;\n\n    case 'cause':\n      if (node.children) {\n        for (const child of node.children) {\n          count += countDecisionPointsInNode(child);\n        }\n      }\n      break;\n\n    case 'transform':\n      if (node.source) {\n        count += countDecisionPointsInNode(node.source);\n      }\n      break;\n\n    case 'channel':\n    case 'sink':\n      if (node.source) {\n        count += countDecisionPointsInNode(node.source);\n      }\n      break;\n\n    case 'exit':\n    case 'schedule':\n    case 'effect':\n    case 'unknown':\n      break;\n  }\n\n  return count;\n}\n\n// =============================================================================\n// Cognitive Complexity\n// =============================================================================\n\nfunction calculateCognitiveComplexity(\n  nodes: readonly StaticFlowNode[],\n): number {\n  return calculateCognitiveForNodes(nodes, 0);\n}\n\nfunction calculateCognitiveForNodes(\n  nodes: readonly StaticFlowNode[],\n  nestingDepth: number,\n): number {\n  let complexity = 0;\n  for (const node of nodes) {\n    complexity += calculateCognitiveForNode(node, nestingDepth);\n  }\n  return complexity;\n}\n\nfunction calculateCognitiveForNode(\n  node: StaticFlowNode,\n  nestingDepth: number,\n): number {\n  const children = getStaticChildren(node);\n  const childList = Option.getOrElse(children, () => [] as readonly StaticFlowNode[]);\n\n  let complexity = 0;\n\n  switch (node.type) {\n    case 'conditional':\n      complexity += 1 + nestingDepth;\n      complexity += calculateCognitiveForNode(node.onTrue, nestingDepth + 1);\n      if (node.onFalse) {\n        complexity += calculateCognitiveForNode(node.onFalse, nestingDepth + 1);\n      }\n      break;\n\n    case 'loop':\n      complexity += 1 + nestingDepth;\n      complexity += calculateCognitiveForNode(node.body, nestingDepth + 1);\n      break;\n\n    case 'race':\n      complexity += node.children.length;\n      for (const child of node.children) {\n        complexity += calculateCognitiveForNode(child, nestingDepth + 1);\n      }\n      break;\n\n    case 'parallel':\n      complexity += Math.max(0, node.children.length - 1);\n      for (const child of node.children) {\n        complexity += calculateCognitiveForNode(child, nestingDepth);\n      }\n      break;\n\n    case 'generator':\n    case 'pipe':\n    case 'error-handler':\n    case 'retry':\n    case 'timeout':\n    case 'resource':\n    case 'layer':\n      for (const child of childList) {\n        complexity += calculateCognitiveForNode(child, nestingDepth);\n      }\n      break;\n\n    case 'decision':\n      complexity += 1 + nestingDepth;\n      for (const child of node.onTrue) {\n        complexity += calculateCognitiveForNode(child, nestingDepth + 1);\n      }\n      if (node.onFalse) {\n        for (const child of node.onFalse) {\n          complexity += calculateCognitiveForNode(child, nestingDepth + 1);\n        }\n      }\n      break;\n\n    case 'switch':\n      complexity += 1 + nestingDepth;\n      for (const caseItem of node.cases) {\n        for (const child of caseItem.body) {\n          complexity += calculateCognitiveForNode(child, nestingDepth + 1);\n        }\n      }\n      break;\n\n    case 'try-catch':\n      complexity += 1 + nestingDepth;\n      for (const child of childList) {\n        complexity += calculateCognitiveForNode(child, nestingDepth + 1);\n      }\n      break;\n\n    case 'terminal':\n      if (node.value) {\n        for (const child of node.value) {\n          complexity += calculateCognitiveForNode(child, nestingDepth);\n        }\n      }\n      break;\n\n    case 'opaque':\n      break;\n\n    case 'match':\n      if (node.matchedTags && node.matchedTags.length > 0) {\n        complexity += 1 + nestingDepth;\n      }\n      break;\n\n    case 'interruption':\n      if (node.handler) {\n        complexity += 1 + nestingDepth;\n        complexity += calculateCognitiveForNode(node.handler, nestingDepth + 1);\n      }\n      if (node.source) {\n        complexity += calculateCognitiveForNode(node.source, nestingDepth);\n      }\n      break;\n\n    case 'cause':\n      if (node.children) {\n        for (const child of node.children) {\n          complexity += calculateCognitiveForNode(child, nestingDepth);\n        }\n      }\n      break;\n\n    case 'transform':\n      if (node.source) {\n        complexity += calculateCognitiveForNode(node.source, nestingDepth);\n      }\n      break;\n\n    case 'channel':\n    case 'sink':\n      if (node.source) {\n        complexity += calculateCognitiveForNode(node.source, nestingDepth);\n      }\n      break;\n\n    case 'exit':\n    case 'schedule':\n    case 'effect':\n    case 'unknown':\n      break;\n  }\n\n  return complexity;\n}\n\n// =============================================================================\n// Path Count\n// =============================================================================\n\nfunction calculatePathCount(\n  nodes: readonly StaticFlowNode[],\n): number | 'unbounded' {\n  let pathCount = 1;\n  let hasUnbounded = false;\n\n  for (const node of nodes) {\n    const result = pathCountForNode(node);\n    if (result === 'unbounded') {\n      hasUnbounded = true;\n    } else {\n      pathCount *= result;\n    }\n  }\n\n  return hasUnbounded ? 'unbounded' : pathCount;\n}\n\nfunction pathCountForNode(node: StaticFlowNode): number | 'unbounded' {\n  const children = getStaticChildren(node);\n  const childList = Option.getOrElse(children, () => [] as readonly StaticFlowNode[]);\n\n  switch (node.type) {\n    case 'conditional': {\n      const truePaths = pathCountForNodes([node.onTrue]);\n      const falsePaths = node.onFalse\n        ? pathCountForNodes([node.onFalse])\n        : 1;\n      if (truePaths === 'unbounded' || falsePaths === 'unbounded') {\n        return 'unbounded';\n      }\n      return truePaths + falsePaths;\n    }\n\n    case 'race': {\n      let total = 0;\n      for (const child of node.children) {\n        const childPaths = pathCountForNode(child);\n        if (childPaths === 'unbounded') return 'unbounded';\n        total += childPaths;\n      }\n      return Math.max(1, total);\n    }\n\n    case 'parallel': {\n      let product = 1;\n      for (const child of node.children) {\n        const childPaths = pathCountForNode(child);\n        if (childPaths === 'unbounded') return 'unbounded';\n        product *= childPaths;\n      }\n      return product;\n    }\n\n    case 'loop':\n      return 'unbounded';\n\n    case 'generator':\n    case 'pipe':\n    case 'error-handler':\n    case 'retry':\n    case 'timeout':\n    case 'resource':\n    case 'layer':\n      return pathCountForNodes(childList);\n\n    case 'effect':\n    case 'unknown':\n    case 'opaque':\n      return 1;\n\n    case 'decision': {\n      const truePaths = pathCountForNodes([...node.onTrue]);\n      const falsePaths = node.onFalse\n        ? pathCountForNodes([...node.onFalse])\n        : 1;\n      if (truePaths === 'unbounded' || falsePaths === 'unbounded') {\n        return 'unbounded';\n      }\n      return truePaths + falsePaths;\n    }\n\n    case 'switch': {\n      let total = 0;\n      for (const c of node.cases) {\n        const casePaths = pathCountForNodes([...c.body]);\n        if (casePaths === 'unbounded') return 'unbounded';\n        total += casePaths;\n      }\n      return Math.max(1, total);\n    }\n\n    case 'try-catch':\n    case 'terminal':\n    case 'stream':\n    case 'concurrency-primitive':\n    case 'fiber':\n    case 'interruption':\n    case 'transform':\n    case 'match':\n    case 'cause':\n    case 'exit':\n    case 'schedule':\n    case 'channel':\n    case 'sink':\n      return pathCountForNodes(childList);\n  }\n}\n\nfunction pathCountForNodes(\n  nodes: readonly StaticFlowNode[],\n): number | 'unbounded' {\n  let product = 1;\n  for (const node of nodes) {\n    const paths = pathCountForNode(node);\n    if (paths === 'unbounded') return 'unbounded';\n    product *= paths;\n  }\n  return product;\n}\n\n// =============================================================================\n// Depth\n// =============================================================================\n\nfunction calculateMaxDepth(nodes: readonly StaticFlowNode[]): number {\n  let maxDepth = 0;\n  for (const node of nodes) {\n    maxDepth = Math.max(maxDepth, depthOfNode(node, 0));\n  }\n  return maxDepth;\n}\n\nfunction depthOfNode(node: StaticFlowNode, currentDepth: number): number {\n  const children = getStaticChildren(node);\n  const childList = Option.getOrElse(children, () => [] as readonly StaticFlowNode[]);\n\n  let maxChildDepth = currentDepth;\n\n  switch (node.type) {\n    case 'conditional':\n      maxChildDepth = Math.max(\n        maxChildDepth,\n        depthOfNode(node.onTrue, currentDepth + 1),\n      );\n      if (node.onFalse) {\n        maxChildDepth = Math.max(\n          maxChildDepth,\n          depthOfNode(node.onFalse, currentDepth + 1),\n        );\n      }\n      break;\n\n    case 'loop':\n      maxChildDepth = Math.max(\n        maxChildDepth,\n        depthOfNode(node.body, currentDepth + 1),\n      );\n      break;\n\n    case 'parallel':\n    case 'race':\n      for (const child of node.children) {\n        maxChildDepth = Math.max(\n          maxChildDepth,\n          depthOfNode(child, currentDepth + 1),\n        );\n      }\n      break;\n\n    case 'generator':\n    case 'pipe':\n    case 'error-handler':\n    case 'retry':\n    case 'timeout':\n    case 'resource':\n    case 'layer':\n      for (const child of childList) {\n        maxChildDepth = Math.max(\n          maxChildDepth,\n          depthOfNode(child, currentDepth),\n        );\n      }\n      break;\n\n    case 'decision':\n      for (const child of node.onTrue) {\n        maxChildDepth = Math.max(\n          maxChildDepth,\n          depthOfNode(child, currentDepth + 1),\n        );\n      }\n      if (node.onFalse) {\n        for (const child of node.onFalse) {\n          maxChildDepth = Math.max(\n            maxChildDepth,\n            depthOfNode(child, currentDepth + 1),\n          );\n        }\n      }\n      break;\n\n    case 'switch':\n      for (const caseItem of node.cases) {\n        for (const child of caseItem.body) {\n          maxChildDepth = Math.max(\n            maxChildDepth,\n            depthOfNode(child, currentDepth + 1),\n          );\n        }\n      }\n      break;\n\n    case 'try-catch':\n      for (const child of childList) {\n        maxChildDepth = Math.max(\n          maxChildDepth,\n          depthOfNode(child, currentDepth + 1),\n        );\n      }\n      break;\n\n    case 'terminal':\n      if (node.value) {\n        for (const child of node.value) {\n          maxChildDepth = Math.max(\n            maxChildDepth,\n            depthOfNode(child, currentDepth),\n          );\n        }\n      }\n      break;\n\n    case 'opaque':\n      break;\n\n    case 'match':\n      break;\n\n    case 'interruption':\n      if (node.source) {\n        maxChildDepth = Math.max(maxChildDepth, depthOfNode(node.source, currentDepth + 1));\n      }\n      if (node.handler) {\n        maxChildDepth = Math.max(maxChildDepth, depthOfNode(node.handler, currentDepth + 1));\n      }\n      break;\n\n    case 'cause':\n      if (node.children) {\n        for (const child of node.children) {\n          maxChildDepth = Math.max(maxChildDepth, depthOfNode(child, currentDepth));\n        }\n      }\n      break;\n\n    case 'transform':\n      if (node.source) {\n        maxChildDepth = Math.max(maxChildDepth, depthOfNode(node.source, currentDepth));\n      }\n      break;\n\n    case 'channel':\n    case 'sink':\n      if (node.source) {\n        maxChildDepth = Math.max(maxChildDepth, depthOfNode(node.source, currentDepth));\n      }\n      break;\n\n    case 'exit':\n    case 'schedule':\n    case 'effect':\n    case 'unknown':\n      break;\n  }\n\n  return maxChildDepth;\n}\n\n// =============================================================================\n// Parallel Breadth\n// =============================================================================\n\nfunction calculateMaxParallelBreadth(\n  nodes: readonly StaticFlowNode[],\n): number {\n  let maxBreadth = 0;\n  for (const node of nodes) {\n    maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(node));\n  }\n  return maxBreadth;\n}\n\nfunction parallelBreadthOfNode(node: StaticFlowNode): number {\n  const children = getStaticChildren(node);\n  const childList = Option.getOrElse(children, () => [] as readonly StaticFlowNode[]);\n\n  let maxBreadth = 0;\n\n  switch (node.type) {\n    case 'parallel':\n    case 'race':\n      maxBreadth = node.children.length;\n      for (const child of node.children) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n      }\n      break;\n\n    case 'conditional':\n      maxBreadth = Math.max(\n        parallelBreadthOfNode(node.onTrue),\n        node.onFalse ? parallelBreadthOfNode(node.onFalse) : 0,\n      );\n      break;\n\n    case 'loop':\n      maxBreadth = parallelBreadthOfNode(node.body);\n      break;\n\n    case 'generator':\n    case 'pipe':\n    case 'error-handler':\n    case 'retry':\n    case 'timeout':\n    case 'resource':\n    case 'layer':\n      for (const child of childList) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n      }\n      break;\n\n    case 'decision':\n      for (const child of node.onTrue) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n      }\n      if (node.onFalse) {\n        for (const child of node.onFalse) {\n          maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n        }\n      }\n      break;\n\n    case 'switch':\n      for (const caseItem of node.cases) {\n        for (const child of caseItem.body) {\n          maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n        }\n      }\n      break;\n\n    case 'try-catch':\n      for (const child of childList) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n      }\n      break;\n\n    case 'terminal':\n      if (node.value) {\n        for (const child of node.value) {\n          maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n        }\n      }\n      break;\n\n    case 'opaque':\n      break;\n\n    case 'interruption':\n      if (node.source) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(node.source));\n      }\n      if (node.handler) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(node.handler));\n      }\n      break;\n\n    case 'cause':\n      if (node.children) {\n        for (const child of node.children) {\n          maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(child));\n        }\n      }\n      break;\n\n    case 'transform':\n      if (node.source) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(node.source));\n      }\n      break;\n\n    case 'channel':\n    case 'sink':\n      if (node.source) {\n        maxBreadth = Math.max(maxBreadth, parallelBreadthOfNode(node.source));\n      }\n      break;\n\n    case 'match':\n    case 'exit':\n    case 'schedule':\n    case 'effect':\n    case 'unknown':\n      break;\n  }\n\n  return maxBreadth;\n}\n\n// =============================================================================\n// Decision Points\n// =============================================================================\n\nfunction countDecisionPoints(nodes: readonly StaticFlowNode[]): number {\n  let count = 0;\n  for (const node of nodes) {\n    count += countDecisionPointsInNode(node);\n  }\n  return count;\n}\n\n// =============================================================================\n// Assessment\n// =============================================================================\n\nexport interface ComplexityAssessment {\n  level: 'low' | 'medium' | 'high' | 'very-high';\n  warnings: ComplexityWarning[];\n  recommendations: string[];\n}\n\nexport interface ComplexityWarning {\n  type: 'cyclomatic' | 'cognitive' | 'paths' | 'depth' | 'breadth';\n  message: string;\n  severity: 'warning' | 'error';\n}\n\nexport function assessComplexity(\n  metrics: ComplexityMetrics,\n  thresholds: ComplexityThresholds = DEFAULT_THRESHOLDS,\n): ComplexityAssessment {\n  const warnings: ComplexityWarning[] = [];\n  const recommendations: string[] = [];\n\n  if (metrics.cyclomaticComplexity >= thresholds.cyclomaticError) {\n    warnings.push({\n      type: 'cyclomatic',\n      message: `Cyclomatic complexity (${metrics.cyclomaticComplexity}) exceeds error threshold (${thresholds.cyclomaticError})`,\n      severity: 'error',\n    });\n    recommendations.push(\n      'Consider breaking this program into smaller effects',\n    );\n  } else if (metrics.cyclomaticComplexity >= thresholds.cyclomaticWarning) {\n    warnings.push({\n      type: 'cyclomatic',\n      message: `Cyclomatic complexity (${metrics.cyclomaticComplexity}) exceeds warning threshold (${thresholds.cyclomaticWarning})`,\n      severity: 'warning',\n    });\n    recommendations.push(\n      'Consider simplifying conditional logic or extracting sub-effects',\n    );\n  }\n\n  if (metrics.pathCount === 'unbounded') {\n    warnings.push({\n      type: 'paths',\n      message: 'Program has unbounded paths due to loops',\n      severity: 'warning',\n    });\n    recommendations.push(\n      'Ensure loop termination conditions are well-tested',\n    );\n  } else if (metrics.pathCount >= thresholds.pathCountWarning) {\n    warnings.push({\n      type: 'paths',\n      message: `Path count (${metrics.pathCount}) exceeds threshold (${thresholds.pathCountWarning})`,\n      severity: 'warning',\n    });\n    recommendations.push(\n      'High path count makes exhaustive testing difficult - consider simplifying',\n    );\n  }\n\n  if (metrics.maxDepth >= thresholds.maxDepthWarning) {\n    warnings.push({\n      type: 'depth',\n      message: `Nesting depth (${metrics.maxDepth}) exceeds threshold (${thresholds.maxDepthWarning})`,\n      severity: 'warning',\n    });\n    recommendations.push(\n      'Deep nesting reduces readability - consider flattening or extracting',\n    );\n  }\n\n  let level: ComplexityAssessment['level'] = 'low';\n  const hasError = warnings.some((w) => w.severity === 'error');\n  const hasWarning = warnings.some((w) => w.severity === 'warning');\n\n  if (hasError) {\n    level = 'very-high';\n  } else if (hasWarning) {\n    level = warnings.length >= 2 ? 'high' : 'medium';\n  }\n\n  return {\n    level,\n    warnings,\n    recommendations,\n  };\n}\n\n// =============================================================================\n// Summary\n// =============================================================================\n\nexport function formatComplexitySummary(\n  metrics: ComplexityMetrics,\n  assessment: ComplexityAssessment,\n): string {\n  const lines: string[] = [];\n\n  lines.push('## Effect Program Complexity Report');\n  lines.push('');\n  lines.push(`**Overall Complexity:** ${assessment.level.toUpperCase()}`);\n  lines.push('');\n  lines.push('### Metrics');\n  lines.push('');\n  lines.push('| Metric | Value |');\n  lines.push('|--------|-------|');\n  lines.push(`| Cyclomatic Complexity | ${metrics.cyclomaticComplexity} |`);\n  lines.push(`| Cognitive Complexity | ${metrics.cognitiveComplexity} |`);\n  lines.push(`| Unique Paths | ${metrics.pathCount} |`);\n  lines.push(`| Max Nesting Depth | ${metrics.maxDepth} |`);\n  lines.push(`| Max Parallel Breadth | ${metrics.maxParallelBreadth} |`);\n  lines.push(`| Decision Points | ${metrics.decisionPoints} |`);\n  lines.push('');\n\n  if (assessment.warnings.length > 0) {\n    lines.push('### Warnings');\n    lines.push('');\n    for (const warning of assessment.warnings) {\n      const icon = warning.severity === 'error' ? 'ERROR' : 'WARNING';\n      lines.push(`- **${icon}:** ${warning.message}`);\n    }\n    lines.push('');\n  }\n\n  if (assessment.recommendations.length > 0) {\n    lines.push('### Recommendations');\n    lines.push('');\n    for (const rec of assessment.recommendations) {\n      lines.push(`- ${rec}`);\n    }\n    lines.push('');\n  }\n\n  return lines.join('\\n');\n}\n","/**\n * Path Generator\n *\n * Generates all possible execution paths through an Effect program based on\n * static analysis. Each path represents a unique sequence of steps that could\n * execute given certain conditions.\n */\n\nimport type {\n  StaticEffectIR,\n  StaticFlowNode,\n  StaticDecisionNode,\n  StaticSwitchNode,\n  StaticTryCatchNode,\n  StaticTerminalNode,\n  StaticCauseNode,\n  StaticMatchNode,\n  StaticTransformNode,\n  StaticChannelNode,\n  StaticSinkNode,\n  StaticInterruptionNode,\n  EffectPath,\n  PathStepRef,\n  PathCondition,\n} from './types';\n\n// =============================================================================\n// Options\n// =============================================================================\n\nexport interface PathGeneratorOptions {\n  /** Maximum paths to generate (default: 1000) */\n  maxPaths?: number;\n  /** Whether to include loop iterations as separate paths (default: false) */\n  expandLoops?: boolean;\n  /** Maximum loop iterations to expand if expandLoops is true (default: 3) */\n  maxLoopIterations?: number;\n}\n\nconst DEFAULT_OPTIONS: Required<PathGeneratorOptions> = {\n  maxPaths: 1000,\n  expandLoops: false,\n  maxLoopIterations: 3,\n};\n\n// =============================================================================\n// Path Generation\n// =============================================================================\n\nexport interface PathGenerationResult {\n  /** Generated effect paths */\n  paths: EffectPath[];\n  /** Whether the maxPaths limit was hit (truncation occurred) */\n  limitHit: boolean;\n}\n\n/**\n * Generate all possible execution paths through an Effect program.\n */\nexport function generatePaths(\n  ir: StaticEffectIR,\n  options: PathGeneratorOptions = {},\n): EffectPath[] {\n  return generatePathsWithMetadata(ir, options).paths;\n}\n\n/**\n * Generate all possible execution paths with metadata.\n */\nexport function generatePathsWithMetadata(\n  ir: StaticEffectIR,\n  options: PathGeneratorOptions = {},\n): PathGenerationResult {\n  const opts = { ...DEFAULT_OPTIONS, ...options };\n\n  const context: PathContext = {\n    opts,\n    pathCount: 0,\n    hasHitLimit: false,\n    controlStack: [],\n  };\n\n  const initialState: PathState = {\n    steps: [],\n    conditions: [],\n    hasLoops: false,\n    hasUnresolvedRefs: false,\n  };\n\n  const states = generatePathsForNodes(ir.root.children, initialState, context);\n\n  const paths: EffectPath[] = states.map((state, index) => ({\n    id: `path-${index + 1}`,\n    description: generatePathDescription(state),\n    steps: state.steps,\n    conditions: state.conditions,\n    hasLoops: state.hasLoops,\n    hasUnresolvedRefs: state.hasUnresolvedRefs,\n  }));\n\n  return {\n    paths,\n    limitHit: context.hasHitLimit,\n  };\n}\n\n// =============================================================================\n// Internal Types\n// =============================================================================\n\ninterface ControlTarget {\n  readonly kind: 'loop' | 'switch' | 'block';\n  readonly label?: string;\n  readonly breakContinuationNodeId: string;\n  readonly continueContinuationNodeId?: string; // only for loops\n}\n\ninterface PathContext {\n  opts: Required<PathGeneratorOptions>;\n  pathCount: number;\n  hasHitLimit: boolean;\n  controlStack: ControlTarget[];\n}\n\ninterface PathState {\n  steps: PathStepRef[];\n  conditions: PathCondition[];\n  hasLoops: boolean;\n  hasUnresolvedRefs: boolean;\n}\n\n// =============================================================================\n// Path Generation Logic\n// =============================================================================\n\nfunction generatePathsForNodes(\n  nodes: readonly StaticFlowNode[],\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  if (nodes.length === 0) {\n    return [currentState];\n  }\n\n  let states: PathState[] = [currentState];\n\n  for (const node of nodes) {\n    const newStates: PathState[] = [];\n    for (const state of states) {\n      newStates.push(...generatePathsForNode(node, state, context));\n    }\n    states = newStates;\n    if (node.type === 'terminal') {\n      const term = node;\n      if (term.terminalKind === 'return' || term.terminalKind === 'throw') {\n        return states;\n      }\n    }\n  }\n\n  return states;\n}\n\nfunction generatePathsForNode(\n  node: StaticFlowNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  switch (node.type) {\n    case 'effect':\n      return handleEffectNode(node, currentState);\n    case 'generator':\n      return handleGeneratorNode(node, currentState, context);\n    case 'pipe':\n      return handlePipeNode(node, currentState, context);\n    case 'parallel':\n      return handleParallelNode(node, currentState, context);\n    case 'race':\n      return handleRaceNode(node, currentState, context);\n    case 'error-handler':\n      return handleErrorHandlerNode(node, currentState, context);\n    case 'retry':\n    case 'timeout':\n      return handleSingleChildNode(node, currentState, context);\n    case 'resource':\n      return handleResourceNode(node, currentState, context);\n    case 'conditional':\n      return handleConditionalNode(node, currentState, context);\n    case 'loop':\n      return handleLoopNode(node, currentState, context);\n    case 'layer':\n      return handleLayerNode(node, currentState, context);\n    case 'stream':\n      return handleStreamNode(node, currentState, context);\n    case 'concurrency-primitive':\n    case 'fiber':\n      return handleConcurrencyOrFiberNode(node, currentState, context);\n    case 'decision':\n      return handleDecisionNode(node, currentState, context);\n    case 'switch':\n      return handleSwitchNode(node, currentState, context);\n    case 'try-catch':\n      return handleTryCatchNode(node, currentState, context);\n    case 'terminal':\n      return handleTerminalNode(node, currentState, context);\n    case 'cause':\n      return handleCauseNode(node, currentState, context);\n    case 'exit':\n    case 'schedule':\n      return handleLeafStepNode(node, currentState);\n    case 'match':\n      return handleMatchNode(node, currentState, context);\n    case 'transform':\n      return handleTransformNode(node, currentState, context);\n    case 'channel':\n      return handleChannelNode(node, currentState, context);\n    case 'sink':\n      return handleSinkNode(node, currentState, context);\n    case 'interruption':\n      return handleInterruptionNode(node, currentState, context);\n    case 'opaque':\n      return [currentState]; // treat as no-op, path continues\n    case 'unknown':\n      return [currentState];\n    default:\n      return [currentState];\n  }\n}\n\nfunction handleEffectNode(\n  node: StaticFlowNode & { type: 'effect' },\n  currentState: PathState,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? node.callee,\n    repeated: false,\n  };\n  return [\n    {\n      ...currentState,\n      steps: [...currentState.steps, stepRef],\n    },\n  ];\n}\n\nfunction handleGeneratorNode(\n  node: StaticFlowNode & { type: 'generator' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const children = node.yields.map((y) => y.effect);\n  return generatePathsForNodes(children, currentState, context);\n}\n\nfunction handlePipeNode(\n  node: StaticFlowNode & { type: 'pipe' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const children = [node.initial, ...node.transformations];\n  return generatePathsForNodes(children, currentState, context);\n}\n\nfunction handleParallelNode(\n  node: StaticFlowNode & { type: 'parallel' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  let combinedStates: PathState[] = [currentState];\n\n  for (const child of node.children) {\n    const newCombinedStates: PathState[] = [];\n    for (const state of combinedStates) {\n      const childStates = generatePathsForNode(child, state, context);\n      for (const childState of childStates) {\n        newCombinedStates.push({\n          steps: childState.steps,\n          conditions: childState.conditions,\n          hasLoops: state.hasLoops || childState.hasLoops,\n          hasUnresolvedRefs:\n            state.hasUnresolvedRefs || childState.hasUnresolvedRefs,\n        });\n      }\n    }\n    combinedStates = newCombinedStates;\n  }\n\n  return combinedStates;\n}\n\nfunction handleRaceNode(\n  node: StaticFlowNode & { type: 'race' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  if (node.children.length === 0) {\n    return [currentState];\n  }\n\n  const atLimit =\n    context.hasHitLimit ||\n    context.pathCount + node.children.length >= context.opts.maxPaths;\n  if (atLimit) {\n    context.hasHitLimit = true;\n    const first = node.children[0];\n    if (first) {\n      return generatePathsForNode(first, currentState, context);\n    }\n    return [currentState];\n  }\n\n  const allStates: PathState[] = [];\n  const maxAllowed = context.opts.maxPaths;\n\n  for (const child of node.children) {\n    if (allStates.length >= maxAllowed) {\n      context.hasHitLimit = true;\n      break;\n    }\n    const childStates = generatePathsForNode(child, currentState, context);\n    const roomLeft = maxAllowed - allStates.length;\n    const toAdd = childStates.slice(0, roomLeft);\n    allStates.push(...toAdd);\n    if (toAdd.length < childStates.length) {\n      context.hasHitLimit = true;\n    }\n  }\n\n  context.pathCount += Math.max(0, allStates.length - 1);\n  return allStates.length > 0 ? allStates : [currentState];\n}\n\nfunction handleErrorHandlerNode(\n  node: StaticFlowNode & { type: 'error-handler' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const sourceStates = generatePathsForNode(node.source, currentState, context);\n  if (!node.handler) {\n    return sourceStates;\n  }\n  const handlerStates = generatePathsForNode(\n    node.handler,\n    currentState,\n    context,\n  );\n  return [...sourceStates, ...handlerStates];\n}\n\nfunction handleSingleChildNode(\n  node: StaticFlowNode & { type: 'retry' | 'timeout' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  return generatePathsForNode(node.source, currentState, context);\n}\n\nfunction handleResourceNode(\n  node: StaticFlowNode & { type: 'resource' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const resourceNodes: StaticFlowNode[] = [node.acquire, node.release];\n  if (node.use) {\n    resourceNodes.push(node.use);\n  }\n  return generatePathsForNodes(resourceNodes, currentState, context);\n}\n\nfunction handleConditionalNode(\n  node: StaticFlowNode & { type: 'conditional' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const trueCondition: PathCondition = {\n    expression: node.condition,\n    mustBe: node.conditionalType === 'unless' ? false : true,\n    location: node.location,\n  };\n\n  const trueState: PathState = {\n    ...currentState,\n    conditions: [...currentState.conditions, trueCondition],\n  };\n\n  const trueStates = generatePathsForNode(node.onTrue, trueState, context);\n\n  const falseCondition: PathCondition = {\n    expression: node.condition,\n    mustBe: node.conditionalType === 'unless' ? true : false,\n    location: node.location,\n  };\n\n  const falseState: PathState = {\n    ...currentState,\n    conditions: [...currentState.conditions, falseCondition],\n  };\n\n  if (node.onFalse) {\n    const falseStates = generatePathsForNode(node.onFalse, falseState, context);\n    return [...trueStates, ...falseStates];\n  }\n\n  return [...trueStates, falseState];\n}\n\nfunction handleLoopNode(\n  node: StaticFlowNode & { type: 'loop' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const bodyStates = generatePathsForNode(node.body, currentState, context);\n  return bodyStates.map((state) => ({\n    ...state,\n    steps: state.steps.map((step, idx) =>\n      idx >= currentState.steps.length ? { ...step, repeated: true } : step,\n    ),\n    hasLoops: true,\n  }));\n}\n\nfunction handleLayerNode(\n  node: StaticFlowNode & { type: 'layer' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  return generatePathsForNodes(node.operations, currentState, context);\n}\n\nfunction handleStreamNode(\n  node: StaticFlowNode & { type: 'stream' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.pipeline.length > 0 ? `Stream.${node.pipeline.map((p) => p.operation).join(' → ')}` : 'Stream',\n    repeated: false,\n  };\n  const stateWithStep = {\n    ...currentState,\n    steps: [...currentState.steps, stepRef],\n  };\n  return generatePathsForNode(node.source, stateWithStep, context);\n}\n\nfunction handleConcurrencyOrFiberNode(\n  node: StaticFlowNode & { type: 'concurrency-primitive' | 'fiber' },\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name:\n      node.type === 'concurrency-primitive'\n        ? `${node.primitive}.${node.operation}`\n        : node.operation,\n    repeated: false,\n  };\n  const stateWithStep = {\n    ...currentState,\n    steps: [...currentState.steps, stepRef],\n  };\n  const child =\n    node.type === 'concurrency-primitive' ? node.source : node.fiberSource;\n  if (child) {\n    return generatePathsForNode(child, stateWithStep, context);\n  }\n  return [stateWithStep];\n}\n\nfunction handleDecisionNode(\n  node: StaticDecisionNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const trueCondition: PathCondition = {\n    expression: node.condition,\n    mustBe: true,\n    location: node.location,\n  };\n  const trueState: PathState = {\n    ...currentState,\n    conditions: [...currentState.conditions, trueCondition],\n  };\n  const trueStates = generatePathsForNodes(node.onTrue, trueState, context);\n\n  if (node.onFalse && node.onFalse.length > 0) {\n    const falseCondition: PathCondition = {\n      expression: node.condition,\n      mustBe: false,\n      location: node.location,\n    };\n    const falseState: PathState = {\n      ...currentState,\n      conditions: [...currentState.conditions, falseCondition],\n    };\n    const falseStates = generatePathsForNodes(node.onFalse, falseState, context);\n    return [...trueStates, ...falseStates];\n  }\n\n  const falseCondition: PathCondition = {\n    expression: node.condition,\n    mustBe: false,\n    location: node.location,\n  };\n  const falseState: PathState = {\n    ...currentState,\n    conditions: [...currentState.conditions, falseCondition],\n  };\n  return [...trueStates, falseState];\n}\n\nfunction handleSwitchNode(\n  node: StaticSwitchNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const allStates: PathState[] = [];\n\n  for (const caseItem of node.cases) {\n    const caseLabel = caseItem.labels.join(' / ');\n    const caseCondition: PathCondition = {\n      expression: `${node.expression} === ${caseLabel}`,\n      mustBe: true,\n      location: node.location,\n    };\n    const caseState: PathState = {\n      ...currentState,\n      conditions: [...currentState.conditions, caseCondition],\n    };\n    const caseStates = generatePathsForNodes(caseItem.body, caseState, context);\n    allStates.push(...caseStates);\n  }\n\n  return allStates.length > 0 ? allStates : [currentState];\n}\n\nfunction handleTryCatchNode(\n  node: StaticTryCatchNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  // Try path (success)\n  const tryStates = generatePathsForNodes(node.tryBody, currentState, context);\n\n  // Catch path\n  const catchStates: PathState[] = [];\n  if (node.catchBody && node.catchBody.length > 0) {\n    const catchCondition: PathCondition = {\n      expression: 'throws',\n      mustBe: true,\n      location: node.location,\n    };\n    const catchState: PathState = {\n      ...currentState,\n      conditions: [...currentState.conditions, catchCondition],\n    };\n    catchStates.push(...generatePathsForNodes(node.catchBody, catchState, context));\n  }\n\n  const combined = [...tryStates, ...catchStates];\n\n  // Finally path: if present, append to all paths\n  if (node.finallyBody && node.finallyBody.length > 0) {\n    const finalStates: PathState[] = [];\n    for (const state of combined) {\n      finalStates.push(...generatePathsForNodes(node.finallyBody, state, context));\n    }\n    return finalStates;\n  }\n\n  return combined;\n}\n\nfunction handleTerminalNode(\n  node: StaticTerminalNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  // If the terminal has value nodes (e.g., return yield* effect), process them first\n  let state = currentState;\n  if (node.value && node.value.length > 0) {\n    const valueStates = generatePathsForNodes(node.value, currentState, context);\n    // Take the first resulting state (value expressions produce sequential steps)\n    state = valueStates[0] ?? currentState;\n  }\n\n  switch (node.terminalKind) {\n    case 'return':\n    case 'throw':\n      // Path terminates — add a step marking the termination\n      return [{\n        ...state,\n        steps: [...state.steps, {\n          nodeId: node.id,\n          name: node.terminalKind,\n          repeated: false,\n        }],\n      }];\n\n    case 'break':\n    case 'continue':\n      // These are structurally captured — just continue the path\n      return [state];\n  }\n}\n\n// =============================================================================\n// New node type handlers (cause, exit, schedule, match, transform, channel, sink, interruption)\n// =============================================================================\n\nfunction handleLeafStepNode(\n  node: StaticFlowNode,\n  currentState: PathState,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? node.type,\n    repeated: false,\n  };\n  return [{\n    ...currentState,\n    steps: [...currentState.steps, stepRef],\n  }];\n}\n\nfunction handleCauseNode(\n  node: StaticCauseNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? `Cause.${node.causeOp}`,\n    repeated: false,\n  };\n  const stateWithStep: PathState = {\n    ...currentState,\n    steps: [...currentState.steps, stepRef],\n  };\n\n  if (node.children && node.children.length > 0) {\n    return generatePathsForNodes([...node.children], stateWithStep, context);\n  }\n  return [stateWithStep];\n}\n\nfunction handleMatchNode(\n  node: StaticMatchNode,\n  currentState: PathState,\n  _context: PathContext,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? `Match.${node.matchOp}`,\n    repeated: false,\n  };\n  return [{\n    ...currentState,\n    steps: [...currentState.steps, stepRef],\n  }];\n}\n\nfunction handleTransformNode(\n  node: StaticTransformNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  let state = currentState;\n  if (node.source) {\n    const sourceStates = generatePathsForNode(node.source, currentState, context);\n    state = sourceStates[0] ?? currentState;\n  }\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? node.transformType,\n    repeated: false,\n  };\n  return [{\n    ...state,\n    steps: [...state.steps, stepRef],\n  }];\n}\n\nfunction handleChannelNode(\n  node: StaticChannelNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  let state = currentState;\n  if (node.source) {\n    const sourceStates = generatePathsForNode(node.source, currentState, context);\n    state = sourceStates[0] ?? currentState;\n  }\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? `Channel${node.pipeline.length > 0 ? `.${node.pipeline.map(p => p.operation).join('.')}` : ''}`,\n    repeated: false,\n  };\n  return [{\n    ...state,\n    steps: [...state.steps, stepRef],\n  }];\n}\n\nfunction handleSinkNode(\n  node: StaticSinkNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  let state = currentState;\n  if (node.source) {\n    const sourceStates = generatePathsForNode(node.source, currentState, context);\n    state = sourceStates[0] ?? currentState;\n  }\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? `Sink${node.pipeline.length > 0 ? `.${node.pipeline.map(p => p.operation).join('.')}` : ''}`,\n    repeated: false,\n  };\n  return [{\n    ...state,\n    steps: [...state.steps, stepRef],\n  }];\n}\n\nfunction handleInterruptionNode(\n  node: StaticInterruptionNode,\n  currentState: PathState,\n  context: PathContext,\n): PathState[] {\n  const stepRef: PathStepRef = {\n    nodeId: node.id,\n    name: node.name ?? node.interruptionType,\n    repeated: false,\n  };\n  const stateWithStep: PathState = {\n    ...currentState,\n    steps: [...currentState.steps, stepRef],\n  };\n\n  if (node.source) {\n    const sourceStates = generatePathsForNode(node.source, stateWithStep, context);\n    if (node.handler) {\n      // Fork: source path + handler path (on interrupt)\n      const handlerStates = generatePathsForNode(node.handler, stateWithStep, context);\n      return [...sourceStates, ...handlerStates];\n    }\n    return sourceStates;\n  }\n  return [stateWithStep];\n}\n\n// =============================================================================\n// Path Description\n// =============================================================================\n\nfunction generatePathDescription(state: PathState): string {\n  const parts: string[] = [];\n\n  if (state.conditions.length > 0) {\n    const conditionParts = state.conditions.map((c) => {\n      const verb = c.mustBe ? 'is true' : 'is false';\n      const expr =\n        c.expression.length > 30\n          ? c.expression.slice(0, 30) + '...'\n          : c.expression;\n      return `${expr} ${verb}`;\n    });\n    parts.push(`When ${conditionParts.join(' AND ')}`);\n  }\n\n  const stepNames = state.steps\n    .map((s) => {\n      const name = s.name ?? s.nodeId;\n      return s.repeated ? `${name} (repeated)` : name;\n    })\n    .join(' → ');\n\n  if (stepNames) {\n    parts.push(`Steps: ${stepNames}`);\n  }\n\n  if (state.hasLoops) {\n    parts.push('[contains loops]');\n  }\n  if (state.hasUnresolvedRefs) {\n    parts.push('[has unresolved refs]');\n  }\n\n  return parts.join('. ') || 'Empty path';\n}\n\n// =============================================================================\n// Path Statistics\n// =============================================================================\n\nexport interface PathStatistics {\n  totalPaths: number;\n  pathLimitHit: boolean;\n  pathsWithLoops: number;\n  pathsWithUnresolvedRefs: number;\n  uniqueConditions: string[];\n  maxPathLength: number;\n  minPathLength: number;\n  avgPathLength: number;\n}\n\nexport interface PathStatisticsOptions {\n  limitHit?: boolean;\n}\n\nexport function calculatePathStatistics(\n  paths: EffectPath[],\n  options?: PathStatisticsOptions,\n): PathStatistics {\n  if (paths.length === 0) {\n    return {\n      totalPaths: 0,\n      pathLimitHit: false,\n      pathsWithLoops: 0,\n      pathsWithUnresolvedRefs: 0,\n      uniqueConditions: [],\n      maxPathLength: 0,\n      minPathLength: 0,\n      avgPathLength: 0,\n    };\n  }\n\n  const conditions = new Set<string>();\n  let pathsWithLoops = 0;\n  let pathsWithUnresolvedRefs = 0;\n  let totalLength = 0;\n  let maxLength = 0;\n  let minLength = Infinity;\n\n  for (const path of paths) {\n    if (path.hasLoops) pathsWithLoops++;\n    if (path.hasUnresolvedRefs) pathsWithUnresolvedRefs++;\n    const length = path.steps.length;\n    totalLength += length;\n    maxLength = Math.max(maxLength, length);\n    minLength = Math.min(minLength, length);\n    for (const c of path.conditions) {\n      conditions.add(c.expression);\n    }\n  }\n\n  return {\n    totalPaths: paths.length,\n    pathLimitHit: options?.limitHit ?? false,\n    pathsWithLoops,\n    pathsWithUnresolvedRefs,\n    uniqueConditions: Array.from(conditions),\n    maxPathLength: maxLength,\n    minPathLength: minLength === Infinity ? 0 : minLength,\n    avgPathLength: totalLength / paths.length,\n  };\n}\n\n// =============================================================================\n// Path Filtering\n// =============================================================================\n\nexport function filterPaths(\n  paths: EffectPath[],\n  filter: {\n    mustIncludeStep?: string;\n    mustExcludeStep?: string;\n    conditionTrue?: string;\n    conditionFalse?: string;\n    noLoops?: boolean;\n    maxLength?: number;\n  },\n): EffectPath[] {\n  return paths.filter((path) => {\n    if (filter.mustIncludeStep) {\n      const has = path.steps.some(\n        (s) => s.name === filter.mustIncludeStep || s.nodeId === filter.mustIncludeStep,\n      );\n      if (!has) return false;\n    }\n    if (filter.mustExcludeStep) {\n      const has = path.steps.some(\n        (s) =>\n          s.name === filter.mustExcludeStep ||\n          s.nodeId === filter.mustExcludeStep,\n      );\n      if (has) return false;\n    }\n    if (filter.conditionTrue) {\n      const has = path.conditions.some(\n        (c) => c.expression === filter.conditionTrue && c.mustBe,\n      );\n      if (!has) return false;\n    }\n    if (filter.conditionFalse) {\n      const has = path.conditions.some(\n        (c) => c.expression === filter.conditionFalse && !c.mustBe,\n      );\n      if (!has) return false;\n    }\n    if (filter.noLoops && path.hasLoops) return false;\n    if (filter.maxLength !== undefined && path.steps.length > filter.maxLength)\n      return false;\n    return true;\n  });\n}\n","/**\n * Data Flow Analysis for Effect IR\n *\n * Builds a graph of value and service dependencies between effect nodes:\n * - Value flow: sequential edges from one effect to the next in execution order\n * - Service reads: effect nodes that require services from Context\n */\n\nimport type { StaticEffectIR, StaticFlowNode, StaticEffectNode } from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface DataFlowNode {\n  id: string;\n  name?: string | undefined;\n  /** Success type this effect produces (writes) */\n  writes?: string | undefined;\n  /** Service IDs this effect reads from Context */\n  reads: string[];\n  location?: { line: number; column: number } | undefined;\n}\n\nexport interface DataFlowEdge {\n  from: string;\n  to: string;\n  key: string;\n}\n\nexport interface DataFlowGraph {\n  nodes: DataFlowNode[];\n  edges: DataFlowEdge[];\n  producedKeys: Set<string>;\n  undefinedReads: UndefinedRead[];\n  duplicateWrites: DuplicateWrite[];\n}\n\nexport interface UndefinedRead {\n  key: string;\n  readerId: string;\n  readerName?: string | undefined;\n}\n\nexport interface DuplicateWrite {\n  key: string;\n  writerIds: string[];\n}\n\n// =============================================================================\n// Execution-order collection (effect nodes only, sequential flow)\n// =============================================================================\n\nfunction collectEffectNodesInOrder(\n  nodes: readonly StaticFlowNode[],\n  result: StaticEffectNode[],\n): void {\n  for (const node of nodes) {\n    if (node.type === 'effect') {\n      result.push(node);\n    }\n    const children = Option.getOrElse(getStaticChildren(node), () => []);\n    if (children.length > 0) {\n      collectEffectNodesInOrder(children, result);\n    }\n  }\n}\n\n// =============================================================================\n// Graph Building\n// =============================================================================\n\nexport function buildDataFlowGraph(ir: StaticEffectIR): DataFlowGraph {\n  const nodes: DataFlowNode[] = [];\n  const edges: DataFlowEdge[] = [];\n  const producedKeys = new Set<string>();\n  const keyProducers = new Map<string, string[]>();\n  const effectNodesOrdered: StaticEffectNode[] = [];\n\n  collectEffectNodesInOrder(ir.root.children, effectNodesOrdered);\n\n  for (const eff of effectNodesOrdered) {\n    const writes = eff.typeSignature?.successType;\n    const reads = (eff.requiredServices ?? []).map((s) => s.serviceId);\n\n    if (writes) {\n      producedKeys.add(writes);\n      const producers = keyProducers.get(writes) ?? [];\n      producers.push(eff.id);\n      keyProducers.set(writes, producers);\n    }\n\n    nodes.push({\n      id: eff.id,\n      name: eff.callee,\n      writes,\n      reads,\n      location: eff.location\n        ? { line: eff.location.line, column: eff.location.column }\n        : undefined,\n    });\n  }\n\n  // Value-flow edges: consecutive effects in order\n  for (let i = 0; i < effectNodesOrdered.length - 1; i++) {\n    const from = effectNodesOrdered[i];\n    const to = effectNodesOrdered[i + 1];\n    if (from === undefined || to === undefined) continue;\n    const key = from.typeSignature?.successType ?? 'value';\n    edges.push({ from: from.id, to: to.id, key });\n  }\n\n  // Context -> effect for each required service (virtual \"context\" source)\n  const contextId = '__context__';\n  for (const node of nodes) {\n    for (const key of node.reads) {\n      edges.push({ from: contextId, to: node.id, key });\n    }\n  }\n\n  const undefinedReads: UndefinedRead[] = [];\n  for (const node of nodes) {\n    for (const key of node.reads) {\n      if (!producedKeys.has(key) && key !== contextId) {\n        undefinedReads.push({\n          key,\n          readerId: node.id,\n          readerName: node.name,\n        });\n      }\n    }\n  }\n\n  const duplicateWrites: DuplicateWrite[] = [];\n  for (const [key, writers] of keyProducers) {\n    if (writers.length > 1) {\n      duplicateWrites.push({ key, writerIds: writers });\n    }\n  }\n\n  return {\n    nodes,\n    edges,\n    producedKeys,\n    undefinedReads,\n    duplicateWrites,\n  };\n}\n\n// =============================================================================\n// Analysis Utilities\n// =============================================================================\n\nexport function getDataFlowOrder(\n  graph: DataFlowGraph,\n): string[] | undefined {\n  const inDegree = new Map<string, number>();\n  const adjacency = new Map<string, string[]>();\n\n  for (const node of graph.nodes) {\n    inDegree.set(node.id, 0);\n    adjacency.set(node.id, []);\n  }\n\n  for (const edge of graph.edges) {\n    if (edge.from === '__context__') continue;\n    const targets = adjacency.get(edge.from) ?? [];\n    targets.push(edge.to);\n    adjacency.set(edge.from, targets);\n    inDegree.set(edge.to, (inDegree.get(edge.to) ?? 0) + 1);\n  }\n\n  const queue: string[] = [];\n  for (const [id, degree] of inDegree) {\n    if (id !== '__context__' && degree === 0) {\n      queue.push(id);\n    }\n  }\n\n  const result: string[] = [];\n  while (queue.length > 0) {\n    const current = queue.shift();\n    if (current === undefined) break;\n    result.push(current);\n    for (const neighbor of adjacency.get(current) ?? []) {\n      const newDegree = (inDegree.get(neighbor) ?? 0) - 1;\n      inDegree.set(neighbor, newDegree);\n      if (newDegree === 0) {\n        queue.push(neighbor);\n      }\n    }\n  }\n\n  if (result.length !== graph.nodes.length) {\n    return undefined;\n  }\n  return result;\n}\n\nexport function getProducers(\n  graph: DataFlowGraph,\n  stepId: string,\n): DataFlowNode[] {\n  const producerIds = new Set<string>();\n  for (const edge of graph.edges) {\n    if (edge.to === stepId && edge.from !== '__context__') {\n      producerIds.add(edge.from);\n    }\n  }\n  return graph.nodes.filter((n) => producerIds.has(n.id));\n}\n\nexport function getConsumers(\n  graph: DataFlowGraph,\n  stepId: string,\n): DataFlowNode[] {\n  const consumerIds = new Set<string>();\n  for (const edge of graph.edges) {\n    if (edge.from === stepId) {\n      consumerIds.add(edge.to);\n    }\n  }\n  return graph.nodes.filter((n) => consumerIds.has(n.id));\n}\n\nexport function getTransitiveDependencies(\n  graph: DataFlowGraph,\n  stepId: string,\n): string[] {\n  const visited = new Set<string>();\n  const result: string[] = [];\n\n  function visit(id: string): void {\n    if (visited.has(id) || id === '__context__') return;\n    visited.add(id);\n    for (const edge of graph.edges) {\n      if (edge.to === id) {\n        result.push(edge.from);\n        visit(edge.from);\n      }\n    }\n  }\n\n  visit(stepId);\n  return result;\n}\n\nexport function findCycles(graph: DataFlowGraph): string[][] {\n  const cycles: string[][] = [];\n  const visited = new Set<string>();\n  const recStack = new Set<string>();\n  const adjacency = new Map<string, string[]>();\n\n  for (const node of graph.nodes) {\n    adjacency.set(node.id, []);\n  }\n  for (const edge of graph.edges) {\n    if (edge.from === '__context__') continue;\n    const targets = adjacency.get(edge.from) ?? [];\n    targets.push(edge.to);\n    adjacency.set(edge.from, targets);\n  }\n\n  function dfs(id: string, path: string[]): void {\n    visited.add(id);\n    recStack.add(id);\n    path.push(id);\n\n    for (const neighbor of adjacency.get(id) ?? []) {\n      if (!visited.has(neighbor)) {\n        dfs(neighbor, path);\n      } else if (recStack.has(neighbor)) {\n        const cycleStart = path.indexOf(neighbor);\n        cycles.push(path.slice(cycleStart));\n      }\n    }\n\n    path.pop();\n    recStack.delete(id);\n  }\n\n  for (const node of graph.nodes) {\n    if (!visited.has(node.id)) {\n      dfs(node.id, []);\n    }\n  }\n\n  return cycles;\n}\n\n// =============================================================================\n// Validation\n// =============================================================================\n\nexport interface DataFlowValidation {\n  valid: boolean;\n  issues: DataFlowIssue[];\n}\n\nexport interface DataFlowIssue {\n  severity: 'error' | 'warning';\n  type: 'undefined-read' | 'duplicate-write' | 'cycle';\n  message: string;\n  stepIds: string[];\n  key?: string;\n}\n\nexport function validateDataFlow(graph: DataFlowGraph): DataFlowValidation {\n  const issues: DataFlowIssue[] = [];\n\n  for (const read of graph.undefinedReads) {\n    issues.push({\n      severity: 'warning',\n      type: 'undefined-read',\n      message: `Effect \"${read.readerName ?? read.readerId}\" reads \"${read.key}\" which is never produced`,\n      stepIds: [read.readerId],\n      key: read.key,\n    });\n  }\n\n  for (const write of graph.duplicateWrites) {\n    issues.push({\n      severity: 'warning',\n      type: 'duplicate-write',\n      message: `Key \"${write.key}\" is written by multiple effects: ${write.writerIds.join(', ')}`,\n      stepIds: write.writerIds,\n      key: write.key,\n    });\n  }\n\n  const cycles = findCycles(graph);\n  for (const cycle of cycles) {\n    issues.push({\n      severity: 'error',\n      type: 'cycle',\n      message: `Circular data dependency: ${cycle.join(' -> ')}`,\n      stepIds: cycle,\n    });\n  }\n\n  return {\n    valid: issues.length === 0,\n    issues,\n  };\n}\n\n// =============================================================================\n// Rendering\n// =============================================================================\n\nfunction sanitizeId(id: string): string {\n  return id.replace(/[^a-zA-Z0-9_]/g, '_');\n}\n\nexport function renderDataFlowMermaid(graph: DataFlowGraph): string {\n  const lines: string[] = [];\n\n  lines.push('flowchart LR');\n  lines.push('');\n  lines.push('  %% Data Flow Graph');\n  lines.push('');\n\n  for (const node of graph.nodes) {\n    const label = node.name ?? node.id;\n    const writes = node.writes ? ` [out: ${node.writes}]` : '';\n    lines.push(`  ${sanitizeId(node.id)}[\"${label}${writes}\"]`);\n  }\n\n  lines.push('');\n\n  for (const edge of graph.edges) {\n    if (edge.from === '__context__') continue;\n    lines.push(\n      `  ${sanitizeId(edge.from)} -->|${edge.key}| ${sanitizeId(edge.to)}`,\n    );\n  }\n\n  if (graph.undefinedReads.length > 0) {\n    lines.push('');\n    lines.push('  %% Undefined Reads (warnings)');\n    for (const read of graph.undefinedReads) {\n      const warningId = `undefined_${sanitizeId(read.key)}`;\n      lines.push(`  ${warningId}[/\"${read.key} (undefined)\"/]`);\n      lines.push(`  ${warningId} -.-> ${sanitizeId(read.readerId)}`);\n    }\n    lines.push('');\n    lines.push('  classDef warning fill:#fff3cd,stroke:#856404');\n    for (const read of graph.undefinedReads) {\n      lines.push(`  class undefined_${sanitizeId(read.key)} warning`);\n    }\n  }\n\n  return lines.join('\\n');\n}\n","/**\n * Error Flow Analysis for Effect IR\n *\n * Aggregates error types from effect nodes (typeSignature.errorType) and\n * error-handler nodes (catchTag, etc.) to build an error propagation view.\n */\n\nimport type {\n  StaticEffectIR,\n  StaticFlowNode,\n  StaticCauseNode,\n  StaticErrorHandlerNode,\n} from './types';\nimport { getStaticChildren } from './types';\nimport { splitTopLevelUnion } from './type-extractor';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * What a handler does to the errors it takes off the channel. `catchTag` and\n * `orDie` both make `E` smaller, but one recovers from the error and the other\n * turns it into a defect that still crashes the fiber behind an `E` of `never`.\n */\nexport type ErrorDisposition =\n  /** Dealt with — the error is recovered from. */\n  | 'handled'\n  /** Still in `E`, under a different type (mapError, orElseFail, sandbox). */\n  | 'transformed'\n  /** Left `E` as a defect — `E` says `never`, the fiber can still die. */\n  | 'defect'\n  /** Silently became a success (ignore, orElseSucceed). */\n  | 'swallowed';\n\n/**\n * Which of the incoming errors a handler takes. `'none'` covers the `filter*`\n * operators: they test the success value, so they add to `E` (or add a defect)\n * without removing anything — `filterOrFail` is `Effect<A, E, R> => Effect<B, E2 | E, R>`.\n */\ntype HandlerScope = 'all' | 'tags' | 'partial' | 'none';\n\ninterface HandlerEntry {\n  readonly disposition: ErrorDisposition;\n  readonly scope: HandlerScope;\n  /** For operators that always take one known error, whatever `E` holds. */\n  readonly tags?: readonly string[];\n}\n\nconst HANDLER_TABLE: Record<StaticErrorHandlerNode['handlerType'], HandlerEntry> = {\n  catch: { disposition: 'handled', scope: 'all' },\n  catchCause: { disposition: 'handled', scope: 'all' },\n  catchDefect: { disposition: 'handled', scope: 'all' },\n  catchEager: { disposition: 'handled', scope: 'all' },\n  catchTag: { disposition: 'handled', scope: 'tags' },\n  catchTags: { disposition: 'handled', scope: 'tags' },\n  catchIf: { disposition: 'handled', scope: 'partial' },\n  catchSome: { disposition: 'handled', scope: 'partial' },\n  catchSomeCause: { disposition: 'handled', scope: 'partial' },\n  catchSomeDefect: { disposition: 'handled', scope: 'partial' },\n  catchFilter: { disposition: 'handled', scope: 'partial' },\n  catchCauseIf: { disposition: 'handled', scope: 'partial' },\n  catchCauseFilter: { disposition: 'handled', scope: 'partial' },\n  catchReason: { disposition: 'handled', scope: 'partial' },\n  catchReasons: { disposition: 'handled', scope: 'partial' },\n  // Exclude<E, Cause.NoSuchElementError> — one named error, never a share of\n  // whatever else `E` happens to hold. (Effect 3 spells it NoSuchElementException.)\n  catchNoSuchElement: {\n    disposition: 'handled',\n    scope: 'tags',\n    tags: ['NoSuchElementError', 'NoSuchElementException'],\n  },\n  orElse: { disposition: 'handled', scope: 'all' },\n  filterOrElse: { disposition: 'handled', scope: 'none' },\n  firstSuccessOf: { disposition: 'handled', scope: 'all' },\n  match: { disposition: 'handled', scope: 'all' },\n  matchCause: { disposition: 'handled', scope: 'all' },\n  matchEffect: { disposition: 'handled', scope: 'all' },\n  matchCauseEffect: { disposition: 'handled', scope: 'all' },\n  eventually: { disposition: 'handled', scope: 'all' },\n  mapError: { disposition: 'transformed', scope: 'all' },\n  mapErrorCause: { disposition: 'transformed', scope: 'all' },\n  mapBoth: { disposition: 'transformed', scope: 'all' },\n  orElseFail: { disposition: 'transformed', scope: 'all' },\n  filterOrFail: { disposition: 'transformed', scope: 'none' },\n  sandbox: { disposition: 'transformed', scope: 'all' },\n  unsandbox: { disposition: 'transformed', scope: 'all' },\n  parallelErrors: { disposition: 'transformed', scope: 'all' },\n  flip: { disposition: 'transformed', scope: 'all' },\n  orDie: { disposition: 'defect', scope: 'all' },\n  orDieWith: { disposition: 'defect', scope: 'all' },\n  filterOrDie: { disposition: 'defect', scope: 'none' },\n  filterOrDieMessage: { disposition: 'defect', scope: 'none' },\n  ignore: { disposition: 'swallowed', scope: 'all' },\n  ignoreLogged: { disposition: 'swallowed', scope: 'all' },\n  orElseSucceed: { disposition: 'swallowed', scope: 'all' },\n};\n\n/** What this handler does to the errors it removes from the channel. */\nexport const errorDisposition = (\n  handlerType: StaticErrorHandlerNode['handlerType'],\n): ErrorDisposition => lookupHandler(handlerType)?.disposition ?? 'handled';\n\n/** IR can arrive from JSON, so a handler type this build does not know is possible. */\nconst lookupHandler = (\n  handlerType: StaticErrorHandlerNode['handlerType'],\n): HandlerEntry | undefined =>\n  (HANDLER_TABLE as Partial<Record<string, HandlerEntry>>)[handlerType];\n\nexport interface StepErrorInfo {\n  stepId: string;\n  stepName?: string | undefined;\n  errors: string[];\n  location?: { line: number; column: number } | undefined;\n}\n\n/** Per-node error propagation: errors at this point and how handlers narrow (GAP 4) */\nexport interface ErrorPropagation {\n  atNode: string;\n  possibleErrors: string[];\n  narrowedBy?: {\n    handler: StaticErrorHandlerNode['handlerType'];\n    removedErrors: string[];\n    addedErrors: string[];\n  };\n  defects: string[];\n  interruptible: boolean;\n}\n\nexport interface ErrorPropagationAnalysis {\n  propagation: ErrorPropagation[];\n  byNodeId: Map<string, ErrorPropagation>;\n}\n\nexport interface ErrorFlowAnalysis {\n  /**\n   * Every error type raised somewhere in the body, not the declared error\n   * channel of the program's signature. A step that raises `SchemaError` and\n   * maps it to `ValidationError` before returning is reported as `SchemaError`;\n   * for the channel, use `analyzeErrorChannels`.\n   */\n  allErrors: string[];\n  stepErrors: StepErrorInfo[];\n  errorToSteps: Map<string, string[]>;\n  stepsWithoutErrors: string[];\n  allStepsDeclareErrors: boolean;\n}\n\nexport interface ErrorFlowEdge {\n  stepId: string;\n  error: string;\n}\n\nexport interface ErrorValidation {\n  valid: boolean;\n  unusedDeclared: string[];\n  undeclaredErrors: string[];\n  computedErrors: string[];\n}\n\n// =============================================================================\n// Helpers: parse error type string (e.g. \"A | B\" or \"never\")\n// =============================================================================\n\n/**\n * Does a handler's tag name this error? Tags are bare (`'NoSuchElementError'`,\n * a `catchTag` literal); the checker may print the error qualified\n * (`Cause.NoSuchElementError` — a namespace member, `import * as`, Effect 3's\n * `declare namespace Cause`). Compare with the qualifier dropped, but keep the\n * qualified name as the error's identity everywhere else: `A.Error` and\n * `B.Error` are two errors, not one.\n */\nconst matchesTag = (error: string, tag: string): boolean =>\n  error === tag ||\n  error.replace(/^(?:[A-Za-z_$][\\w$]*\\.)+(?=[A-Za-z_$])/, '') === tag;\n\nconst matchingAny = (errors: readonly string[], tags: readonly string[]): string[] =>\n  errors.filter((e) => tags.some((tag) => matchesTag(e, tag)));\n\nfunction parseErrorTypes(errorType: string): string[] {\n  const t = errorType.trim();\n  if (t === 'never' || t === 'unknown') {\n    return [];\n  }\n  return splitTopLevelUnion(t);\n}\n\n// =============================================================================\n// Collection\n// =============================================================================\n\nfunction collectEffectErrors(\n  nodes: readonly StaticFlowNode[],\n  result: StepErrorInfo[],\n): void {\n  for (const node of nodes) {\n    if (node.type === 'effect') {\n      const eff = node;\n      const errors = eff.typeSignature?.errorType\n        ? parseErrorTypes(eff.typeSignature.errorType)\n        : [];\n      result.push({\n        stepId: eff.id,\n        stepName: eff.callee,\n        errors,\n        location: eff.location\n          ? { line: eff.location.line, column: eff.location.column }\n          : undefined,\n      });\n    }\n\n    const children = Option.getOrElse(getStaticChildren(node), () => []);\n    if (children.length > 0) {\n      collectEffectErrors(children, result);\n    }\n  }\n}\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\nexport function analyzeErrorFlow(ir: StaticEffectIR): ErrorFlowAnalysis {\n  const stepErrors: StepErrorInfo[] = [];\n  const allErrorsSet = new Set<string>();\n  const errorToSteps = new Map<string, string[]>();\n  const stepsWithoutErrors: string[] = [];\n\n  collectEffectErrors(ir.root.children, stepErrors);\n\n  for (const step of stepErrors) {\n    if (step.errors.length === 0) {\n      stepsWithoutErrors.push(step.stepId);\n    }\n    for (const error of step.errors) {\n      allErrorsSet.add(error);\n      const steps = errorToSteps.get(error) ?? [];\n      steps.push(step.stepId);\n      errorToSteps.set(error, steps);\n    }\n  }\n\n  return {\n    allErrors: Array.from(allErrorsSet).sort(),\n    stepErrors,\n    errorToSteps,\n    stepsWithoutErrors,\n    allStepsDeclareErrors:\n      stepsWithoutErrors.length === 0 && stepErrors.length > 0,\n  };\n}\n\n// =============================================================================\n// Error Propagation & Narrowing (GAP 4)\n// =============================================================================\n\nfunction unionErrors(a: string[], b: string[]): string[] {\n  return Array.from(new Set([...a, ...b])).sort();\n}\n\nfunction withoutErrors(current: string[], removed: string[]): string[] {\n  const set = new Set(removed);\n  return current.filter((e) => !set.has(e));\n}\n\n/** Collect error types from a subtree (effect nodes only). */\nfunction collectErrorsFromSubtree(node: StaticFlowNode): string[] {\n  const out: string[] = [];\n  const visit = (n: StaticFlowNode) => {\n    if (n.type === 'effect') {\n      const err = (n).typeSignature?.errorType;\n      if (err) out.push(...parseErrorTypes(err));\n    }\n    const children = Option.getOrElse(getStaticChildren(n), () => []);\n    children.forEach(visit);\n  };\n  visit(node);\n  return unionErrors([], out);\n}\n\n/** Find the causeKind of the first cause node in a subtree (for cause-aware mapped-error placeholders). */\nfunction findCauseKindInSubtree(node: StaticFlowNode): StaticCauseNode['causeKind'] | undefined {\n  if (node.type === 'cause') return (node).causeKind;\n  const children = Option.getOrElse(getStaticChildren(node), () => []);\n  for (const child of children) {\n    const result = findCauseKindInSubtree(child);\n    if (result) return result;\n  }\n  return undefined;\n}\n\n/**\n * Walk IR in execution order, propagating error types and applying narrowing at handlers.\n */\nfunction walkPropagation(\n  nodes: readonly StaticFlowNode[],\n  errorsIn: string[],\n  result: ErrorPropagation[],\n): string[] {\n  let current = [...errorsIn];\n  for (const node of nodes) {\n    if (node.type === 'effect') {\n      const eff = node;\n      const own = eff.typeSignature?.errorType\n        ? parseErrorTypes(eff.typeSignature.errorType)\n        : [];\n      current = unionErrors(current, own);\n      result.push({\n        atNode: eff.id,\n        possibleErrors: [...current],\n        defects: [],\n        interruptible: false,\n      });\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) {\n        current = walkPropagation(children, current, result);\n      }\n    } else if (node.type === 'error-handler') {\n      const handler = node;\n      current = walkPropagation([handler.source], current, result);\n      const sourceErrors = [...current];\n      const removed: string[] = [];\n      const entry = lookupHandler(handler.handlerType);\n      const scope = entry?.scope ?? 'all';\n      const fixedTags = entry?.tags;\n      if (scope === 'tags') {\n        if (handler.handlerType === 'catchTag' && handler.errorTag) {\n          // Remove the error under the spelling it is carried in; fall back to\n          // the bare tag when the source's errors could not be resolved at all.\n          const matched = matchingAny(sourceErrors, [handler.errorTag]);\n          removed.push(...(matched.length > 0 ? matched : [handler.errorTag]));\n        } else if (handler.errorTags && handler.errorTags.length > 0) {\n          removed.push(...matchingAny(sourceErrors, handler.errorTags));\n        } else if (fixedTags) {\n          removed.push(...matchingAny(sourceErrors, fixedTags));\n        } else if (handler.handlerType === 'catchTags') {\n          // Object-form catchTags without extracted keys: fall back to the\n          // heuristic that error-like names are the ones being caught.\n          removed.push(...sourceErrors.filter((e) => /Error$|^[A-Z]/.test(e)));\n        }\n        // A catchTag whose tag is not a literal removes nothing rather than guessing.\n      } else if (scope === 'partial') {\n        // Predicate/reason catches remove a subset we cannot infer.\n        removed.push(...sourceErrors.slice(0, Math.ceil(sourceErrors.length / 2)));\n      } else if (scope !== 'none') {\n        removed.push(...sourceErrors);\n      }\n      const afterNarrow = withoutErrors(current, removed);\n      let handlerErrors = handler.handler\n        ? collectErrorsFromSubtree(handler.handler)\n        : [];\n      // For mapping transforms: errors are replaced, not eliminated — mark as transformed.\n      // When the source includes a cause node with a known causeKind, use a more specific placeholder.\n      if (\n        (handler.handlerType === 'mapError' ||\n          handler.handlerType === 'mapErrorCause' ||\n          handler.handlerType === 'mapBoth') &&\n        removed.length > 0 &&\n        handlerErrors.length === 0\n      ) {\n        const causeKind = findCauseKindInSubtree(handler.source);\n        if (causeKind === 'fail') handlerErrors = ['<mapped-fail>'];\n        else if (causeKind === 'die') handlerErrors = ['<mapped-defect>'];\n        else handlerErrors = ['<mapped-error>'];\n      }\n      current = unionErrors(afterNarrow, handlerErrors);\n      result.push({\n        atNode: handler.id,\n        possibleErrors: [...current],\n        narrowedBy: {\n          handler: handler.handlerType,\n          removedErrors: removed,\n          addedErrors: handlerErrors,\n        },\n        defects: [],\n        interruptible: false,\n      });\n      if (handler.handler) {\n        current = walkPropagation([handler.handler], current, result);\n      }\n    } else if (node.type === 'parallel' || node.type === 'race') {\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      let branchErrors: string[] = [];\n      for (const child of children) {\n        const fromChild = walkPropagation([child], current, result);\n        branchErrors = unionErrors(branchErrors, fromChild);\n      }\n      current = branchErrors;\n    } else {\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) {\n        current = walkPropagation(children, current, result);\n      }\n    }\n  }\n  return current;\n}\n\nexport function analyzeErrorPropagation(ir: StaticEffectIR): ErrorPropagationAnalysis {\n  const propagation: ErrorPropagation[] = [];\n  walkPropagation(ir.root.children, [], propagation);\n  const byNodeId = new Map<string, ErrorPropagation>();\n  for (const p of propagation) {\n    byNodeId.set(p.atNode, p);\n  }\n  return { propagation, byNodeId };\n}\n\n// =============================================================================\n// Error Propagation\n// =============================================================================\n\nexport function getErrorsAtPoint(\n  analysis: ErrorFlowAnalysis,\n  afterStepId: string,\n): string[] {\n  const errors = new Set<string>();\n  let found = false;\n\n  for (const step of analysis.stepErrors) {\n    for (const error of step.errors) {\n      errors.add(error);\n    }\n    if (step.stepId === afterStepId) {\n      found = true;\n      break;\n    }\n  }\n\n  if (!found) {\n    return analysis.allErrors;\n  }\n  return Array.from(errors).sort();\n}\n\nexport function getErrorProducers(\n  analysis: ErrorFlowAnalysis,\n  errorTag: string,\n): StepErrorInfo[] {\n  const stepIds = analysis.errorToSteps.get(errorTag) ?? [];\n  return analysis.stepErrors.filter((s) => stepIds.includes(s.stepId));\n}\n\n// =============================================================================\n// Validation\n// =============================================================================\n\nexport function validateWorkflowErrors(\n  analysis: ErrorFlowAnalysis,\n  declaredErrors: string[],\n): ErrorValidation {\n  const declaredSet = new Set(declaredErrors);\n  const computedSet = new Set(analysis.allErrors);\n\n  const unusedDeclared = declaredErrors.filter((e) => !computedSet.has(e));\n  const undeclaredErrors = analysis.allErrors.filter((e) => !declaredSet.has(e));\n\n  return {\n    valid:\n      unusedDeclared.length === 0 && undeclaredErrors.length === 0,\n    unusedDeclared,\n    undeclaredErrors,\n    computedErrors: analysis.allErrors,\n  };\n}\n\n// =============================================================================\n// Rendering\n// =============================================================================\n\nfunction sanitizeId(id: string): string {\n  return id.replace(/[^a-zA-Z0-9_]/g, '_');\n}\n\nexport function renderErrorFlowMermaid(analysis: ErrorFlowAnalysis): string {\n  const lines: string[] = [];\n\n  lines.push('flowchart LR');\n  lines.push('');\n  lines.push('  %% Error Flow Graph');\n  lines.push('');\n\n  lines.push('  subgraph Steps');\n  for (const step of analysis.stepErrors) {\n    const label = step.stepName ?? step.stepId;\n    lines.push(`    ${sanitizeId(step.stepId)}[\"${label}\"]`);\n  }\n  lines.push('  end');\n  lines.push('');\n\n  if (analysis.allErrors.length > 0) {\n    lines.push('  subgraph Errors');\n    for (const error of analysis.allErrors) {\n      lines.push(`    err_${sanitizeId(error)}([\"${error}\"])`);\n    }\n    lines.push('  end');\n    lines.push('');\n\n    for (const step of analysis.stepErrors) {\n      for (const error of step.errors) {\n        lines.push(\n          `  ${sanitizeId(step.stepId)} -.->|throws| err_${sanitizeId(error)}`,\n        );\n      }\n    }\n  }\n\n  lines.push('');\n  lines.push('  classDef error fill:#ffcdd2,stroke:#c62828');\n  for (const error of analysis.allErrors) {\n    lines.push(`  class err_${sanitizeId(error)} error`);\n  }\n\n  if (analysis.stepsWithoutErrors.length > 0) {\n    lines.push('');\n    lines.push('  classDef noErrors fill:#fff3cd,stroke:#856404');\n    for (const stepId of analysis.stepsWithoutErrors) {\n      lines.push(`  class ${sanitizeId(stepId)} noErrors`);\n    }\n  }\n\n  return lines.join('\\n');\n}\n\nexport function formatErrorSummary(analysis: ErrorFlowAnalysis): string {\n  const lines: string[] = [];\n\n  lines.push('## Error Flow Summary');\n  lines.push('');\n\n  lines.push(`**Total Effects:** ${analysis.stepErrors.length}`);\n  lines.push(`**Total Error Types:** ${analysis.allErrors.length}`);\n  lines.push(\n    `**Effects Without Declared Errors:** ${analysis.stepsWithoutErrors.length}`,\n  );\n  lines.push('');\n\n  if (analysis.allErrors.length > 0) {\n    lines.push('### Error Types');\n    lines.push('');\n    for (const error of analysis.allErrors) {\n      const producers = analysis.errorToSteps.get(error) ?? [];\n      lines.push(`- \\`${error}\\` - produced by: ${producers.join(', ')}`);\n    }\n    lines.push('');\n  }\n\n  if (analysis.stepsWithoutErrors.length > 0) {\n    lines.push('### Effects Without Declared Errors');\n    lines.push('');\n    lines.push(\n      'The following effects do not declare their error type (typeSignature.errorType):',\n    );\n    lines.push('');\n    for (const stepId of analysis.stepsWithoutErrors) {\n      lines.push(`- ${stepId}`);\n    }\n    lines.push('');\n  }\n\n  lines.push('### Effect Error Details');\n  lines.push('');\n  lines.push('| Effect | Errors |');\n  lines.push('|--------|--------|');\n  for (const step of analysis.stepErrors) {\n    const name = step.stepName ?? step.stepId;\n    const errors =\n      step.errors.length > 0\n        ? step.errors.map((e) => `\\`${e}\\``).join(', ')\n        : '_none_';\n    lines.push(`| ${name} | ${errors} |`);\n  }\n\n  return lines.join('\\n');\n}\n","/**\n * Service (R) Flow Analysis (GAP 3)\n *\n * Tracks which services each effect requires, where they are provided,\n * and where R is still unsatisfied.\n */\n\nimport type {\n  StaticEffectIR,\n  StaticFlowNode,\n  StaticEffectNode,\n  ServiceRequirement,\n  SourceLocation,\n} from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface ServiceProvision {\n  nodeId: string;\n  serviceId: string;\n  location?: SourceLocation;\n}\n\nexport interface UnsatisfiedService {\n  nodeId: string;\n  serviceId: string;\n  serviceType?: string;\n  location?: SourceLocation;\n}\n\nexport interface ServiceLifecycleEntry {\n  createdAt: string;\n  consumedAt: string[];\n  releasedAt?: string;\n}\n\nexport interface ServiceFlowAnalysis {\n  requiredServices: ServiceRequirement[];\n  providedServices: ServiceProvision[];\n  unsatisfiedAt: UnsatisfiedService[];\n  serviceLifecycle: Map<string, ServiceLifecycleEntry>;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction collectRequiredFromNode(\n  node: StaticFlowNode,\n  result: ServiceRequirement[],\n): void {\n  if (node.type === 'effect') {\n    const eff = node;\n    const reqs = eff.requiredServices ?? [];\n    for (const r of reqs) {\n      if (!result.some((x) => x.serviceId === r.serviceId)) {\n        result.push(r);\n      }\n    }\n  }\n  const children = Option.getOrElse(getStaticChildren(node), () => []);\n  for (const c of children) collectRequiredFromNode(c, result);\n}\n\n/** Heuristic: detect provide/provideService from effect callee and first arg. */\nfunction getProvidedServiceId(\n  node: StaticEffectNode,\n  getFirstArgText: (node: StaticEffectNode) => string | undefined,\n): string | undefined {\n  const callee = node.callee;\n  if (callee.includes('provideService') || callee.includes('provide')) {\n    return getFirstArgText(node);\n  }\n  return undefined;\n}\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\n/**\n * Build service flow analysis from IR.\n * Tracks required vs provided services and unsatisfied requirements at each node.\n */\nexport function analyzeServiceFlow(\n  ir: StaticEffectIR,\n  options?: {\n    /** Optional: resolve effect node to its AST to read first arg (for provideService). */\n    getFirstArgText?: (effectNode: StaticEffectNode) => string | undefined;\n  },\n): ServiceFlowAnalysis {\n  const requiredServices: ServiceRequirement[] = [];\n  for (const child of ir.root.children) {\n    collectRequiredFromNode(child, requiredServices);\n  }\n  const dedupedRequired = Array.from(\n    new Map(requiredServices.map((r) => [r.serviceId, r])).values(),\n  );\n\n  const providedServices: ServiceProvision[] = [];\n  const unsatisfiedAt: UnsatisfiedService[] = [];\n  const consumedBy = new Map<string, string[]>();\n\n  const available = new Set<string>();\n  const getFirstArg = options?.getFirstArgText;\n\n  function walk(nodes: readonly StaticFlowNode[]) {\n    for (const node of nodes) {\n      if (node.type === 'effect') {\n        const eff = node;\n        const providedId = getFirstArg ? getProvidedServiceId(eff, getFirstArg) : undefined;\n        if (providedId) {\n          available.add(providedId);\n          const prov: ServiceProvision = { nodeId: eff.id, serviceId: providedId };\n          if (eff.location) prov.location = eff.location;\n          providedServices.push(prov);\n        }\n        const reqs = eff.requiredServices ?? [];\n        for (const r of reqs) {\n          const list = consumedBy.get(r.serviceId) ?? [];\n          list.push(eff.id);\n          consumedBy.set(r.serviceId, list);\n          if (!available.has(r.serviceId)) {\n            const u: UnsatisfiedService = { nodeId: eff.id, serviceId: r.serviceId };\n            if (r.serviceType !== undefined) u.serviceType = r.serviceType;\n            if (r.requiredAt !== undefined) u.location = r.requiredAt;\n            unsatisfiedAt.push(u);\n          }\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) walk(children);\n    }\n  }\n  walk(ir.root.children);\n\n  const serviceLifecycle = new Map<string, ServiceLifecycleEntry>();\n  for (const p of providedServices) {\n    serviceLifecycle.set(p.serviceId, {\n      createdAt: p.nodeId,\n      consumedAt: consumedBy.get(p.serviceId) ?? [],\n    });\n  }\n  for (const r of dedupedRequired) {\n    if (!serviceLifecycle.has(r.serviceId)) {\n      serviceLifecycle.set(r.serviceId, {\n        createdAt: '',\n        consumedAt: consumedBy.get(r.serviceId) ?? [],\n      });\n    }\n  }\n\n  return {\n    requiredServices: dedupedRequired,\n    providedServices,\n    unsatisfiedAt,\n    serviceLifecycle,\n  };\n}\n","/**\n * Layer Dependency Graph (GAP 2)\n *\n * Collects StaticLayerNode from IR and builds a dependency graph\n * (provides, requires, merge/provide edges) for visualization.\n */\n\nimport type { StaticEffectIR, StaticFlowNode } from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface LayerNodeInfo {\n  id: string;\n  name?: string;\n  provides: string[];\n  requires: string[];\n  lifecycle: string;\n  isMerged: boolean;\n  operationLayerIds: string[];\n}\n\nexport interface LayerGraphEdge {\n  from: string;\n  to: string;\n  kind: 'provides' | 'requires' | 'merge';\n}\n\nexport interface LayerDependencyGraph {\n  layers: LayerNodeInfo[];\n  edges: LayerGraphEdge[];\n  serviceToLayers: Map<string, string[]>;\n}\n\n// =============================================================================\n// Collection\n// =============================================================================\n\nfunction collectLayerNodes(\n  nodes: readonly StaticFlowNode[],\n  result: LayerNodeInfo[],\n): void {\n  for (const node of nodes) {\n    if (node.type === 'layer') {\n      const layer = node;\n      const info: LayerNodeInfo = {\n        id: layer.id,\n        provides: [...(layer.provides ?? [])],\n        requires: [...(layer.requires ?? [])],\n        lifecycle: layer.lifecycle ?? 'default',\n        isMerged: layer.isMerged,\n        operationLayerIds: layer.operations\n          .filter((op) => op.type === 'layer')\n          .map((op) => op.id),\n      };\n      if (layer.name !== undefined) info.name = layer.name;\n      result.push(info);\n    }\n    const children = Option.getOrElse(getStaticChildren(node), () => []);\n    if (children.length > 0) collectLayerNodes(children, result);\n  }\n}\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\nexport function buildLayerDependencyGraph(ir: StaticEffectIR): LayerDependencyGraph {\n  const layers: LayerNodeInfo[] = [];\n  collectLayerNodes(ir.root.children, layers);\n\n  const edges: LayerGraphEdge[] = [];\n  const serviceToLayers = new Map<string, string[]>();\n\n  for (const layer of layers) {\n    for (const depLayerId of layer.operationLayerIds) {\n      edges.push({ from: layer.id, to: depLayerId, kind: 'merge' });\n    }\n    for (const svc of layer.provides) {\n      const list = serviceToLayers.get(svc) ?? [];\n      list.push(layer.id);\n      serviceToLayers.set(svc, list);\n      edges.push({ from: layer.id, to: svc, kind: 'provides' });\n    }\n    for (const req of layer.requires) {\n      edges.push({ from: layer.id, to: req, kind: 'requires' });\n    }\n  }\n\n  return { layers, edges, serviceToLayers };\n}\n\n// =============================================================================\n// Cycle Detection\n// =============================================================================\n\nexport interface LayerCycle {\n  /** Layer IDs forming the cycle (first == last to close the loop) */\n  path: string[];\n}\n\n/**\n * Detect cycles in the layer provides→requires graph.\n * Returns all unique cycles found with the full cycle path.\n */\nexport function detectLayerCycles(graph: LayerDependencyGraph): LayerCycle[] {\n  // Build adjacency: layer → layers it depends on (via requires → provider lookup)\n  const providerByService = new Map<string, string[]>();\n  for (const layer of graph.layers) {\n    for (const svc of layer.provides) {\n      const providers = providerByService.get(svc) ?? [];\n      providers.push(layer.id);\n      providerByService.set(svc, providers);\n    }\n  }\n\n  const adjacency = new Map<string, string[]>();\n  for (const layer of graph.layers) {\n    const deps: string[] = [];\n    for (const req of layer.requires) {\n      for (const provider of providerByService.get(req) ?? []) {\n        if (provider !== layer.id) deps.push(provider);\n      }\n    }\n    adjacency.set(layer.id, deps);\n  }\n\n  const cycles: LayerCycle[] = [];\n  const visiting = new Set<string>();\n  const visited = new Set<string>();\n\n  function dfs(node: string, path: string[]): void {\n    if (visited.has(node)) return;\n    if (visiting.has(node)) {\n      const cycleStart = path.indexOf(node);\n      if (cycleStart >= 0) {\n        cycles.push({ path: [...path.slice(cycleStart), node] });\n      }\n      return;\n    }\n    visiting.add(node);\n    path.push(node);\n    for (const next of adjacency.get(node) ?? []) {\n      dfs(next, path);\n    }\n    path.pop();\n    visiting.delete(node);\n    visited.add(node);\n  }\n\n  for (const layerId of adjacency.keys()) {\n    dfs(layerId, []);\n  }\n\n  return cycles;\n}\n\n// =============================================================================\n// Diamond Dependency Detection\n// =============================================================================\n\nexport interface DiamondDependency {\n  serviceId: string;\n  providers: string[];\n}\n\n/**\n * Detect diamond dependencies: services reachable through multiple provide paths.\n */\nexport function detectDiamondDependencies(graph: LayerDependencyGraph): DiamondDependency[] {\n  const diamonds: DiamondDependency[] = [];\n  for (const [serviceId, providers] of graph.serviceToLayers) {\n    if (providers.length > 1) {\n      diamonds.push({ serviceId, providers: [...providers] });\n    }\n  }\n  return diamonds;\n}\n\n// =============================================================================\n// Composition Completeness\n// =============================================================================\n\nexport interface UnsatisfiedService {\n  serviceId: string;\n  requiredBy: string[];\n}\n\n/**\n * Find services required by layers but not provided by any layer.\n */\nexport function findUnsatisfiedServices(graph: LayerDependencyGraph): UnsatisfiedService[] {\n  const allProvided = new Set<string>();\n  for (const layer of graph.layers) {\n    for (const svc of layer.provides) {\n      allProvided.add(svc);\n    }\n  }\n\n  const unsatisfied = new Map<string, string[]>();\n  for (const layer of graph.layers) {\n    for (const req of layer.requires) {\n      if (!allProvided.has(req)) {\n        const requiredBy = unsatisfied.get(req) ?? [];\n        requiredBy.push(layer.id);\n        unsatisfied.set(req, requiredBy);\n      }\n    }\n  }\n\n  return Array.from(unsatisfied.entries()).map(([serviceId, requiredBy]) => ({\n    serviceId,\n    requiredBy,\n  }));\n}\n\n// =============================================================================\n// Layer Depth Calculation\n// =============================================================================\n\nfunction computeLayerDepths(graph: LayerDependencyGraph): Map<string, number> {\n  const providerByService = new Map<string, string[]>();\n  for (const layer of graph.layers) {\n    for (const svc of layer.provides) {\n      const providers = providerByService.get(svc) ?? [];\n      providers.push(layer.id);\n      providerByService.set(svc, providers);\n    }\n  }\n\n  const depths = new Map<string, number>();\n  const visited = new Set<string>();\n\n  function computeDepth(layerId: string): number {\n    const cached = depths.get(layerId);\n    if (cached !== undefined) return cached;\n    if (visited.has(layerId)) return 0; // cycle guard\n    visited.add(layerId);\n\n    const layer = graph.layers.find(l => l.id === layerId);\n    if (!layer) return 0;\n\n    let maxDep = 0;\n    for (const req of layer.requires) {\n      for (const provider of providerByService.get(req) ?? []) {\n        if (provider !== layerId) {\n          maxDep = Math.max(maxDep, computeDepth(provider) + 1);\n        }\n      }\n    }\n    depths.set(layerId, maxDep);\n    return maxDep;\n  }\n\n  for (const layer of graph.layers) {\n    computeDepth(layer.id);\n  }\n  return depths;\n}\n\n// =============================================================================\n// Mermaid output (GAP 2)\n// =============================================================================\n\nfunction sanitizeId(id: string): string {\n  return id.replace(/[^a-zA-Z0-9_]/g, '_');\n}\n\nconst DEPTH_COLORS = [\n  '#C8E6C9', '#A5D6A7', '#81C784', '#66BB6A', '#4CAF50',\n  '#43A047', '#388E3C', '#2E7D32', '#1B5E20',\n];\n\nexport function renderLayerGraphMermaid(graph: LayerDependencyGraph): string {\n  const lines: string[] = [];\n  lines.push('graph TD');\n  lines.push('');\n\n  const cycles = detectLayerCycles(graph);\n  const cycleEdges = new Set<string>();\n  for (const cycle of cycles) {\n    for (let i = 0; i < cycle.path.length - 1; i++) {\n      cycleEdges.add(`${cycle.path[i]}→${cycle.path[i + 1]}`);\n    }\n  }\n\n  const depths = computeLayerDepths(graph);\n\n  for (const layer of graph.layers) {\n    const label = layer.name ?? layer.id;\n    lines.push(`  ${sanitizeId(layer.id)}[\"${label}\"]`);\n  }\n  lines.push('');\n\n  const provided = new Set<string>();\n  for (const e of graph.edges) {\n    if (e.kind === 'provides') provided.add(e.to);\n  }\n  for (const svc of provided) {\n    lines.push(`  ${sanitizeId(svc)}[\"${svc}\"]`);\n  }\n  lines.push('');\n\n  for (const e of graph.edges) {\n    const isCycleEdge = cycleEdges.has(`${e.from}→${e.to}`);\n    if (e.kind === 'provides') {\n      lines.push(`  ${sanitizeId(e.from)} -.->|provides| ${sanitizeId(e.to)}`);\n    } else if (e.kind === 'requires') {\n      if (isCycleEdge) {\n        lines.push(`  ${sanitizeId(e.from)} -->|⚠ CYCLE| ${sanitizeId(e.to)}`);\n      } else {\n        lines.push(`  ${sanitizeId(e.from)} --> ${sanitizeId(e.to)}`);\n      }\n    } else {\n      lines.push(`  ${sanitizeId(e.from)} -->|merge| ${sanitizeId(e.to)}`);\n    }\n  }\n\n  // Color-code layers by depth\n  lines.push('');\n  lines.push('  %% Depth-based styling');\n  const maxDepth = Math.max(...Array.from(depths.values()), 0);\n  for (let d = 0; d <= maxDepth && d < DEPTH_COLORS.length; d++) {\n    lines.push(`  classDef depth${d} fill:${DEPTH_COLORS[d]},stroke:#333`);\n  }\n  for (const layer of graph.layers) {\n    const depth = Math.min(depths.get(layer.id) ?? 0, DEPTH_COLORS.length - 1);\n    lines.push(`  class ${sanitizeId(layer.id)} depth${depth}`);\n  }\n\n  // Cycle warning styling\n  if (cycles.length > 0) {\n    lines.push('  classDef cycleNode fill:#FFCDD2,stroke:#C62828,stroke-width:3px');\n    const cycleNodes = new Set<string>();\n    for (const cycle of cycles) {\n      for (const id of cycle.path) cycleNodes.add(id);\n    }\n    for (const id of cycleNodes) {\n      lines.push(`  class ${sanitizeId(id)} cycleNode`);\n    }\n  }\n\n  return lines.join('\\n');\n}\n","/**\n * Observability Analysis (GAP 11)\n *\n * Detects Effect.withSpan, Effect.log*, Metric.*, Logger usage.\n */\n\nimport type { StaticEffectIR, StaticFlowNode } from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface SpanInfo {\n  nodeId: string;\n  name?: string;\n  parentSpanId?: string;\n  depth?: number;\n  childEffectCount?: number;\n  location?: { line: number; column: number };\n}\n\nexport interface LogPointInfo {\n  nodeId: string;\n  level: 'debug' | 'info' | 'warning' | 'error';\n  location?: { line: number; column: number };\n}\n\nexport interface MetricInfo {\n  nodeId: string;\n  type: 'counter' | 'gauge' | 'histogram' | 'summary' | 'timer';\n  /** Whether this metric uses Metric.tagged / taggedWithLabels */\n  isTagged?: boolean;\n  location?: { line: number; column: number };\n}\n\nexport interface ObservabilityAnalysis {\n  spans: SpanInfo[];\n  logPoints: LogPointInfo[];\n  metrics: MetricInfo[];\n  untracedEffects: string[];\n  coverage: {\n    effectCount: number;\n    effectsWithSpans: number;\n    effectsWithMetrics: number;\n    errorHandlersWithLogging: number;\n    errorHandlerCount: number;\n  };\n}\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\nfunction isSpanCallee(callee: string): boolean {\n  return (\n    callee.includes('withSpan') ||\n    callee.includes('Tracer.span') ||\n    callee.includes('annotateCurrentSpan') ||\n    callee.includes('annotateSpans') ||\n    callee.includes('makeSpan') ||\n    callee.includes('makeSpanScoped') ||\n    callee.includes('useSpan') ||\n    callee.includes('withParentSpan') ||\n    callee.includes('linkSpans') ||\n    callee.includes('linkSpanCurrent') ||\n    callee.includes('functionWithSpan') ||\n    callee.includes('currentSpan') ||\n    callee.includes('currentParentSpan') ||\n    callee.includes('withTracerEnabled') ||\n    callee.includes('withTracerTiming') ||\n    callee.includes('span(')\n  );\n}\n\nfunction isLogCallee(callee: string): boolean {\n  return (\n    callee.includes('Effect.log') ||\n    callee.includes('Logger.add') ||\n    callee.includes('Logger.replace') ||\n    callee.includes('Logger.batched') ||\n    callee.includes('Logger.withLeveledConsole') ||\n    callee.includes('Logger.json') ||\n    callee.includes('Logger.logFmt') ||\n    callee.includes('Logger.pretty') ||\n    callee.includes('Logger.structured')\n  );\n}\n\nfunction getLogLevel(callee: string): LogPointInfo['level'] {\n  if (callee.includes('logDebug') || callee.includes('Debug')) return 'debug';\n  if (callee.includes('logWarning') || callee.includes('Warning')) return 'warning';\n  if (callee.includes('logError') || callee.includes('Error')) return 'error';\n  return 'info';\n}\n\nfunction isMetricCallee(callee: string): boolean {\n  return callee.startsWith('Metric.') || callee.includes('.track');\n}\n\nfunction getMetricType(callee: string): MetricInfo['type'] {\n  if (callee.includes('counter') || callee.includes('increment')) return 'counter';\n  if (callee.includes('frequency')) return 'counter';\n  if (callee.includes('gauge') || callee.includes('.set')) return 'gauge';\n  if (callee.includes('histogram')) return 'histogram';\n  if (callee.includes('summary')) return 'summary';\n  if (callee.includes('timer') || callee.includes('trackDuration')) return 'timer';\n  // Metric combinators — type unknown, default to counter\n  // tagged, taggedWithLabels, trackAll, trackDefect, withConstantInput, map, mapInput\n  return 'counter';\n}\n\nexport function analyzeObservability(ir: StaticEffectIR): ObservabilityAnalysis {\n  const spans: SpanInfo[] = [];\n  const logPoints: LogPointInfo[] = [];\n  const metrics: MetricInfo[] = [];\n  const untracedEffects: string[] = [];\n  let effectCount = 0;\n  let effectsWithSpans = 0;\n  let effectsWithMetrics = 0;\n  let errorHandlersWithLogging = 0;\n  let errorHandlerCount = 0;\n\n  function visit(\n    nodes: readonly StaticFlowNode[],\n    spanStack: string[],\n    underMetric: boolean,\n  ) {\n    for (const node of nodes) {\n      const nextSpanStack = [...spanStack];\n      if (node.spanName) {\n        const span: SpanInfo = {\n          nodeId: node.id,\n          name: node.spanName,\n          depth: spanStack.length,\n          ...(spanStack.length > 0 ? { parentSpanId: spanStack[spanStack.length - 1] } : {}),\n        };\n        if (node.location) {\n          span.location = { line: node.location.line, column: node.location.column };\n        }\n        spans.push(span);\n        nextSpanStack.push(node.id);\n      }\n      if (node.type === 'effect') {\n        const eff = node;\n        const callee = eff.callee ?? '';\n        effectCount++;\n        if (isSpanCallee(callee) && !node.spanName) {\n          const s: SpanInfo = { nodeId: eff.id };\n          if (eff.location) s.location = { line: eff.location.line, column: eff.location.column };\n          spans.push(s);\n        }\n        if (nextSpanStack.length > 0) effectsWithSpans++;\n        else if (\n          !isLogCallee(callee) &&\n          !isMetricCallee(callee) &&\n          !isSpanCallee(callee) &&\n          !eff.usePattern\n        ) {\n          untracedEffects.push(eff.id);\n        }\n        if (isLogCallee(callee)) {\n          const lp: LogPointInfo = { nodeId: eff.id, level: getLogLevel(callee) };\n          if (eff.location) lp.location = { line: eff.location.line, column: eff.location.column };\n          logPoints.push(lp);\n        }\n        if (isMetricCallee(callee)) {\n          const isTagged = callee.includes('tagged') || callee.includes('taggedWith');\n          const m: MetricInfo = {\n            nodeId: eff.id,\n            type: getMetricType(callee),\n            ...(isTagged ? { isTagged: true } : {}),\n          };\n          if (eff.location) m.location = { line: eff.location.line, column: eff.location.column };\n          metrics.push(m);\n        }\n        if (underMetric) effectsWithMetrics++;\n      }\n      if (node.type === 'error-handler') {\n        errorHandlerCount++;\n        const handler = node;\n        if (handler.handler) {\n          let hasLog = false;\n          const checkLog = (n: StaticFlowNode) => {\n            if (n.type === 'effect') {\n              const c = (n).callee ?? '';\n              if (isLogCallee(c)) hasLog = true;\n            }\n            const ch = Option.getOrElse(getStaticChildren(n), () => []);\n            ch.forEach(checkLog);\n          };\n          checkLog(handler.handler);\n          if (hasLog) errorHandlersWithLogging++;\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      const thisIsMetric = node.type === 'effect' && isMetricCallee((node).callee ?? '');\n      const nextUnderMetric = underMetric || thisIsMetric;\n      if (children.length > 0) visit(children, nextSpanStack, nextUnderMetric);\n    }\n  }\n  visit(ir.root.children, [], false);\n\n  const spanChildCounts = new Map<string, number>();\n  const countEffectsInSpan = (\n    nodes: readonly StaticFlowNode[],\n    activeSpans: string[],\n  ): void => {\n    for (const node of nodes) {\n      const nextSpans = node.spanName ? [...activeSpans, node.id] : activeSpans;\n      if (node.type === 'effect' && nextSpans.length > 0) {\n        for (const spanId of nextSpans) {\n          spanChildCounts.set(spanId, (spanChildCounts.get(spanId) ?? 0) + 1);\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) countEffectsInSpan(children, nextSpans);\n    }\n  };\n  countEffectsInSpan(ir.root.children, []);\n  for (const span of spans) {\n    span.childEffectCount = spanChildCounts.get(span.nodeId) ?? 0;\n  }\n\n  return {\n    spans,\n    logPoints,\n    metrics,\n    untracedEffects,\n    coverage: {\n      effectCount,\n      effectsWithSpans,\n      effectsWithMetrics,\n      errorHandlersWithLogging,\n      errorHandlerCount,\n    },\n  };\n}\n","/**\n * Test Coverage Matrix Generator\n *\n * Generates a test coverage matrix from Effect paths, helping developers\n * ensure all paths through an Effect program are tested.\n */\n\nimport type {\n  EffectPath,\n  TestMatrix,\n  TestPath,\n  TestCondition,\n  TestMatrixSummary,\n} from '../types';\n\n// =============================================================================\n// Options\n// =============================================================================\n\nexport interface TestMatrixOptions {\n  /** Prefix for generated test names */\n  testNamePrefix?: string;\n  /** Function to customize test name generation */\n  testNameGenerator?: (path: EffectPath) => string;\n  /** Whether to include paths with loops (they may need special handling) */\n  includeLoopPaths?: boolean;\n}\n\nconst DEFAULT_OPTIONS: Required<TestMatrixOptions> = {\n  testNamePrefix: 'should',\n  testNameGenerator: defaultTestNameGenerator,\n  includeLoopPaths: true,\n};\n\n// =============================================================================\n// Main Generator\n// =============================================================================\n\nexport function generateTestMatrix(\n  paths: EffectPath[],\n  options: TestMatrixOptions = {},\n): TestMatrix {\n  const opts = { ...DEFAULT_OPTIONS, ...options };\n\n  let filteredPaths = paths;\n  if (!opts.includeLoopPaths) {\n    filteredPaths = paths.filter((p) => !p.hasLoops);\n  }\n\n  const testPaths = filteredPaths.map((path) => generateTestPath(path, opts));\n  const conditions = extractConditions(filteredPaths);\n  const summary = calculateSummary(testPaths, conditions);\n\n  return {\n    paths: testPaths,\n    conditions,\n    summary,\n  };\n}\n\n// =============================================================================\n// Test Path Generation\n// =============================================================================\n\nfunction generateTestPath(\n  path: EffectPath,\n  opts: Required<TestMatrixOptions>,\n): TestPath {\n  const testName = opts.testNameGenerator(path);\n  const priority = determinePriority(path);\n\n  const setupConditions = path.conditions.map((c) => {\n    const verb = c.mustBe ? 'be truthy' : 'be falsy';\n    return `Set up ${c.expression} to ${verb}`;\n  });\n\n  const expectedSteps = path.steps.map((s) => {\n    const name = s.name ?? s.nodeId;\n    return s.repeated ? `${name} (may repeat)` : name;\n  });\n\n  return {\n    id: path.id,\n    suggestedTestName: testName,\n    description: path.description,\n    setupConditions,\n    expectedSteps,\n    priority,\n  };\n}\n\nfunction determinePriority(path: EffectPath): 'high' | 'medium' | 'low' {\n  if (path.conditions.length === 0 && !path.hasLoops) {\n    return 'high';\n  }\n  if (path.hasLoops && path.conditions.length > 2) {\n    return 'low';\n  }\n  return 'medium';\n}\n\nfunction defaultTestNameGenerator(path: EffectPath): string {\n  const parts: string[] = ['should'];\n\n  if (path.steps.length > 0) {\n    const mainSteps = path.steps.filter((s) => !s.repeated).slice(0, 3);\n    if (mainSteps.length > 0) {\n      const stepNames = mainSteps.map((s) =>\n        camelToSpaces(s.name ?? s.nodeId),\n      );\n      parts.push(stepNames.join(' then '));\n    }\n  }\n\n  if (path.conditions.length > 0) {\n    parts.push('when');\n    const conditionDescriptions = path.conditions.slice(0, 2).map((c) => {\n      const simplified = simplifyCondition(c.expression);\n      return c.mustBe ? simplified : `not ${simplified}`;\n    });\n    parts.push(conditionDescriptions.join(' and '));\n  }\n\n  if (path.hasLoops) {\n    parts.push('(with iteration)');\n  }\n\n  return parts.join(' ');\n}\n\nfunction camelToSpaces(str: string): string {\n  return str\n    .replace(/([a-z])([A-Z])/g, '$1 $2')\n    .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')\n    .toLowerCase();\n}\n\nfunction simplifyCondition(expression: string): string {\n  return expression\n    .replace(/\\s*===\\s*true/g, '')\n    .replace(/\\s*===\\s*false/g, ' is false')\n    .replace(/\\s*===\\s*/g, ' is ')\n    .replace(/\\s*!==\\s*/g, ' is not ')\n    .replace(/\\s*>\\s*/g, ' greater than ')\n    .replace(/\\s*<\\s*/g, ' less than ')\n    .replace(/\\s*>=\\s*/g, ' at least ')\n    .replace(/\\s*<=\\s*/g, ' at most ')\n    .replace(/&&/g, ' and ')\n    .replace(/\\|\\|/g, ' or ')\n    .trim();\n}\n\n// =============================================================================\n// Condition Extraction\n// =============================================================================\n\nfunction extractConditions(paths: EffectPath[]): TestCondition[] {\n  const conditionMap = new Map<\n    string,\n    { whenTrue: string[]; whenFalse: string[] }\n  >();\n\n  for (const path of paths) {\n    for (const condition of path.conditions) {\n      const key = condition.expression;\n\n      if (!conditionMap.has(key)) {\n        conditionMap.set(key, { whenTrue: [], whenFalse: [] });\n      }\n\n      const entry = conditionMap.get(key);\n      if (entry) {\n        if (condition.mustBe) {\n          entry.whenTrue.push(path.id);\n        } else {\n          entry.whenFalse.push(path.id);\n        }\n      }\n    }\n  }\n\n  return Array.from(conditionMap.entries()).map(([expression, affected]) => ({\n    expression,\n    affectedPathsWhenTrue: affected.whenTrue,\n    affectedPathsWhenFalse: affected.whenFalse,\n  }));\n}\n\n// =============================================================================\n// Summary\n// =============================================================================\n\nfunction calculateSummary(\n  paths: TestPath[],\n  conditions: TestCondition[],\n): TestMatrixSummary {\n  const highPriorityPaths = paths.filter((p) => p.priority === 'high').length;\n  const minTestsForCoverage = Math.max(\n    1,\n    conditions.length * 2,\n  );\n\n  return {\n    totalPaths: paths.length,\n    highPriorityPaths,\n    totalConditions: conditions.length,\n    minTestsForCoverage,\n  };\n}\n\n// =============================================================================\n// Output Formatting\n// =============================================================================\n\nexport function formatTestMatrixMarkdown(matrix: TestMatrix): string {\n  const lines: string[] = [];\n\n  lines.push('# Test Coverage Matrix');\n  lines.push('');\n  lines.push('## Summary');\n  lines.push('');\n  lines.push(`- **Total Paths:** ${matrix.summary.totalPaths}`);\n  lines.push(`- **High Priority Paths:** ${matrix.summary.highPriorityPaths}`);\n  lines.push(`- **Conditions to Test:** ${matrix.summary.totalConditions}`);\n  lines.push(\n    `- **Minimum Tests for Coverage:** ${matrix.summary.minTestsForCoverage}`,\n  );\n  lines.push('');\n\n  lines.push('## Test Cases');\n  lines.push('');\n\n  const highPriority = matrix.paths.filter((p) => p.priority === 'high');\n  const mediumPriority = matrix.paths.filter((p) => p.priority === 'medium');\n  const lowPriority = matrix.paths.filter((p) => p.priority === 'low');\n\n  if (highPriority.length > 0) {\n    lines.push('### High Priority');\n    lines.push('');\n    for (const path of highPriority) {\n      lines.push(...formatTestPathLines(path));\n    }\n    lines.push('');\n  }\n\n  if (mediumPriority.length > 0) {\n    lines.push('### Medium Priority');\n    lines.push('');\n    for (const path of mediumPriority) {\n      lines.push(...formatTestPathLines(path));\n    }\n    lines.push('');\n  }\n\n  if (lowPriority.length > 0) {\n    lines.push('### Low Priority');\n    lines.push('');\n    for (const path of lowPriority) {\n      lines.push(...formatTestPathLines(path));\n    }\n    lines.push('');\n  }\n\n  if (matrix.conditions.length > 0) {\n    lines.push('## Conditions Coverage');\n    lines.push('');\n    lines.push('| Condition | Paths When True | Paths When False |');\n    lines.push('|-----------|-----------------|------------------|');\n\n    for (const condition of matrix.conditions) {\n      const truncatedExpr =\n        condition.expression.length > 40\n          ? condition.expression.slice(0, 40) + '...'\n          : condition.expression;\n      const trueCount = condition.affectedPathsWhenTrue.length;\n      const falseCount = condition.affectedPathsWhenFalse.length;\n      lines.push(`| \\`${truncatedExpr}\\` | ${trueCount} | ${falseCount} |`);\n    }\n    lines.push('');\n  }\n\n  lines.push('## Test Checklist');\n  lines.push('');\n  for (const path of matrix.paths) {\n    const priority =\n      path.priority === 'high'\n        ? 'HIGH'\n        : path.priority === 'medium'\n          ? 'MED'\n          : 'LOW';\n    lines.push(`- [ ] [${priority}] ${path.suggestedTestName}`);\n  }\n  lines.push('');\n\n  return lines.join('\\n');\n}\n\nfunction formatTestPathLines(path: TestPath): string[] {\n  const lines: string[] = [];\n  lines.push(`#### ${path.suggestedTestName}`);\n  lines.push('');\n\n  if (path.setupConditions.length > 0) {\n    lines.push('**Setup:**');\n    for (const condition of path.setupConditions) {\n      lines.push(`- ${condition}`);\n    }\n    lines.push('');\n  }\n\n  lines.push('**Expected Steps:**');\n  for (let i = 0; i < path.expectedSteps.length; i++) {\n    lines.push(`${i + 1}. ${path.expectedSteps[i]}`);\n  }\n  lines.push('');\n\n  return lines;\n}\n\nexport function formatTestMatrixAsCode(\n  matrix: TestMatrix,\n  options: {\n    testRunner?: 'vitest' | 'jest' | 'mocha';\n    programName?: string;\n  } = {},\n): string {\n  const runner = options.testRunner ?? 'vitest';\n  const programName = options.programName ?? 'program';\n\n  const lines: string[] = [];\n\n  if (runner === 'vitest') {\n    lines.push(\"import { describe, it, expect } from 'vitest';\");\n  } else if (runner === 'jest') {\n    lines.push('// Jest test file');\n  } else {\n    lines.push(\"import { describe, it } from 'mocha';\");\n    lines.push(\"import { expect } from 'chai';\");\n  }\n\n  lines.push('');\n  lines.push(`describe('${programName}', () => {`);\n\n  for (const path of matrix.paths) {\n    lines.push('');\n    lines.push(`  it('${escapeString(path.suggestedTestName)}', async () => {`);\n    lines.push('    // Setup');\n    for (const condition of path.setupConditions) {\n      lines.push(`    // TODO: ${condition}`);\n    }\n    lines.push('');\n    lines.push('    // Execute effect program');\n    lines.push(`    // const result = await Effect.runPromise(${programName});`);\n    lines.push('');\n    lines.push('    // Verify expected steps executed');\n    for (const step of path.expectedSteps) {\n      lines.push(`    // TODO: Verify ${step} was executed`);\n    }\n    lines.push('  });');\n  }\n\n  lines.push('});');\n  lines.push('');\n\n  return lines.join('\\n');\n}\n\nfunction escapeString(str: string): string {\n  return str.replace(/'/g, \"\\\\'\").replace(/\"/g, '\\\\\"');\n}\n\nexport function formatTestChecklist(matrix: TestMatrix): string {\n  const lines: string[] = [];\n\n  lines.push('Test Coverage Checklist');\n  lines.push('=======================');\n  lines.push('');\n  lines.push(`Total: ${matrix.summary.totalPaths} tests needed`);\n  lines.push(`High Priority: ${matrix.summary.highPriorityPaths}`);\n  lines.push('');\n\n  for (const path of matrix.paths) {\n    const marker =\n      path.priority === 'high'\n        ? '***'\n        : path.priority === 'medium'\n          ? '**'\n          : '*';\n    lines.push(`[ ] ${marker} ${path.suggestedTestName}`);\n    if (path.setupConditions.length > 0) {\n      lines.push(`    Conditions: ${path.setupConditions.join(', ')}`);\n    }\n  }\n\n  return lines.join('\\n');\n}\n","/**\n * Scope & Resource Lifecycle Analysis (GAP 10)\n *\n * Detects acquireRelease, Scope.*, Pool.*, Effect.scoped and tracks\n * resource ordering and potential leaks.\n */\n\nimport type { StaticEffectIR, StaticFlowNode } from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface ResourceAcquisition {\n  nodeId: string;\n  type: 'acquireRelease' | 'acquireUseRelease' | 'scoped' | 'pool' | 'keyedPool';\n  acquireNodeId?: string;\n  releaseNodeId?: string;\n  location?: { line: number; column: number };\n}\n\nexport interface ScopeBoundary {\n  nodeId: string;\n  type: 'scoped' | 'scopeMake' | 'scopeUse' | 'scopeFork' | 'scopeAddFinalizer' | 'scopeExtend';\n  location?: { line: number; column: number };\n}\n\nexport interface ScopeResourceAnalysis {\n  acquisitions: ResourceAcquisition[];\n  scopeBoundaries: ScopeBoundary[];\n  poolCreations: string[];\n  potentialLeaks: string[];\n}\n\n// =============================================================================\n// Detection\n// =============================================================================\n\nfunction _isResourceCallee(callee: string): boolean {\n  return (\n    callee.includes('acquireRelease') ||\n    callee.includes('acquireUseRelease') ||\n    callee.includes('Effect.scoped') ||\n    callee.startsWith('Scope.') ||\n    callee.startsWith('Pool.') ||\n    callee.startsWith('KeyedPool.')\n  );\n}\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\nexport function analyzeScopeResource(ir: StaticEffectIR): ScopeResourceAnalysis {\n  const acquisitions: ResourceAcquisition[] = [];\n  const scopeBoundaries: ScopeBoundary[] = [];\n  const poolCreations: string[] = [];\n  const potentialLeaks: string[] = [];\n\n  function visit(nodes: readonly StaticFlowNode[]) {\n    for (const node of nodes) {\n      if (node.type === 'effect') {\n        const eff = node;\n        const callee = eff.callee;\n        if (callee.includes('acquireRelease') || callee.includes('acquireUseRelease')) {\n          const acq: ResourceAcquisition = {\n            nodeId: eff.id,\n            type: callee.includes('acquireUseRelease') ? 'acquireUseRelease' : 'acquireRelease',\n          };\n          if (eff.location) acq.location = { line: eff.location.line, column: eff.location.column };\n          acquisitions.push(acq);\n        } else if (callee.includes('Effect.scoped')) {\n          const sb: ScopeBoundary = { nodeId: eff.id, type: 'scoped' };\n          if (eff.location) sb.location = { line: eff.location.line, column: eff.location.column };\n          scopeBoundaries.push(sb);\n        } else if (callee.startsWith('Scope.')) {\n          if (callee.includes('make')) {\n            const sb: ScopeBoundary = { nodeId: eff.id, type: 'scopeMake' };\n            if (eff.location) sb.location = { line: eff.location.line, column: eff.location.column };\n            scopeBoundaries.push(sb);\n          } else if (callee.includes('use')) {\n            const sb: ScopeBoundary = { nodeId: eff.id, type: 'scopeUse' };\n            if (eff.location) sb.location = { line: eff.location.line, column: eff.location.column };\n            scopeBoundaries.push(sb);\n          } else if (callee.includes('fork')) {\n            const sb: ScopeBoundary = { nodeId: eff.id, type: 'scopeFork' };\n            if (eff.location) sb.location = { line: eff.location.line, column: eff.location.column };\n            scopeBoundaries.push(sb);\n          } else if (callee.includes('addFinalizer')) {\n            const sb: ScopeBoundary = { nodeId: eff.id, type: 'scopeAddFinalizer' };\n            if (eff.location) sb.location = { line: eff.location.line, column: eff.location.column };\n            scopeBoundaries.push(sb);\n          } else if (callee.includes('extend')) {\n            const sb: ScopeBoundary = { nodeId: eff.id, type: 'scopeExtend' };\n            if (eff.location) sb.location = { line: eff.location.line, column: eff.location.column };\n            scopeBoundaries.push(sb);\n          }\n        } else if (callee.startsWith('Pool.') || callee.startsWith('KeyedPool.')) {\n          poolCreations.push(eff.id);\n        }\n      } else if (node.type === 'resource') {\n        const res = node;\n        const acq: ResourceAcquisition = {\n          nodeId: node.id,\n          type: 'acquireRelease',\n          acquireNodeId: res.acquire.id,\n          releaseNodeId: res.release.id,\n        };\n        if (node.location) acq.location = { line: node.location.line, column: node.location.column };\n        acquisitions.push(acq);\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) visit(children);\n    }\n  }\n  visit(ir.root.children);\n\n  return {\n    acquisitions,\n    scopeBoundaries,\n    poolCreations,\n    potentialLeaks,\n  };\n}\n","/**\n * Ref / State Management Analysis (GAP 7)\n *\n * Detects Ref, FiberRef, SynchronizedRef usage and potential race conditions.\n */\n\nimport type { StaticEffectIR, StaticFlowNode } from './types';\nimport { getStaticChildren } from './types';\nimport { Option } from 'effect';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface RefInfo {\n  refId: string;\n  operation: 'make' | 'get' | 'set' | 'update' | 'modify' | 'getAndSet' | 'getAndUpdate';\n  nodeId: string;\n  location?: { line: number; column: number };\n}\n\nexport interface RefMutation {\n  refId: string;\n  nodeId: string;\n  operation: 'set' | 'update' | 'modify' | 'getAndSet' | 'getAndUpdate';\n}\n\nexport interface RaceCondition {\n  refId: string;\n  readerIds: string[];\n  writerIds: string[];\n  message: string;\n}\n\nexport interface StateFlowAnalysis {\n  refs: RefInfo[];\n  mutations: RefMutation[];\n  potentialRaces: RaceCondition[];\n  stateGraph: {\n    refId: string;\n    readers: string[];\n    writers: string[];\n  }[];\n}\n\n// =============================================================================\n// Detection\n// =============================================================================\n\nfunction isRefCallee(callee: string): boolean {\n  return (\n    callee.startsWith('Ref.') ||\n    callee.startsWith('FiberRef.') ||\n    callee.startsWith('SynchronizedRef.')\n  );\n}\n\nfunction getRefOperation(callee: string): RefInfo['operation'] {\n  if (callee.includes('getAndUpdate')) return 'getAndUpdate';\n  if (callee.includes('getAndSet')) return 'getAndSet';\n  if (callee.includes('modify')) return 'modify';\n  if (callee.includes('update')) return 'update';\n  if (callee.includes('.set')) return 'set';\n  if (callee.includes('.get')) return 'get';\n  if (callee.includes('make') || callee.includes('unsafeMake')) return 'make';\n  return 'get';\n}\n\nfunction getRefId(callee: string): string {\n  if (callee.startsWith('Ref.')) return 'Ref';\n  if (callee.startsWith('FiberRef.')) return 'FiberRef';\n  if (callee.startsWith('SynchronizedRef.')) return 'SynchronizedRef';\n  return 'Ref';\n}\n\nconst WRITE_OPS = new Set<RefInfo['operation']>(['set', 'update', 'modify', 'getAndSet', 'getAndUpdate']);\n\n// =============================================================================\n// Analysis\n// =============================================================================\n\nexport function analyzeStateFlow(ir: StaticEffectIR): StateFlowAnalysis {\n  const refs: RefInfo[] = [];\n  const mutations: RefMutation[] = [];\n  const readersByRef = new Map<string, string[]>();\n  const writersByRef = new Map<string, string[]>();\n\n  function visit(nodes: readonly StaticFlowNode[]) {\n    for (const node of nodes) {\n      if (node.type === 'effect') {\n        const eff = node;\n        const callee = eff.callee;\n        if (isRefCallee(callee)) {\n          const refId = getRefId(callee);\n          const operation = getRefOperation(callee);\n          const info: RefInfo = {\n            refId,\n            operation,\n            nodeId: eff.id,\n          };\n          if (eff.location) info.location = { line: eff.location.line, column: eff.location.column };\n          refs.push(info);\n          if (WRITE_OPS.has(operation)) {\n            mutations.push({\n              refId,\n              nodeId: eff.id,\n              operation: operation as RefMutation['operation'],\n            });\n            const w = writersByRef.get(refId) ?? [];\n            w.push(eff.id);\n            writersByRef.set(refId, w);\n          } else if (operation === 'get') {\n            const r = readersByRef.get(refId) ?? [];\n            r.push(eff.id);\n            readersByRef.set(refId, r);\n          }\n        }\n      }\n      const children = Option.getOrElse(getStaticChildren(node), () => []);\n      if (children.length > 0) visit(children);\n    }\n  }\n  visit(ir.root.children);\n\n  const stateGraph = Array.from(\n    new Set([...readersByRef.keys(), ...writersByRef.keys()]),\n  ).map((refId) => ({\n    refId,\n    readers: readersByRef.get(refId) ?? [],\n    writers: writersByRef.get(refId) ?? [],\n  }));\n\n  const potentialRaces: RaceCondition[] = [];\n  for (const { refId, readers, writers } of stateGraph) {\n    if (readers.length > 0 && writers.length > 0) {\n      potentialRaces.push({\n        refId,\n        readerIds: readers,\n        writerIds: writers,\n        message: `Ref \"${refId}\" has concurrent readers and writers - consider Ref.modify for atomic updates`,\n      });\n    }\n  }\n\n  return {\n    refs,\n    mutations,\n    potentialRaces,\n    stateGraph,\n  };\n}\n","/**\n * State machine analysis.\n *\n * Recognizes machines written with `@typeonce/effect-machine` — the\n * schema-first Machine API from Effect PR #6429 — and extracts the state tree\n * plus (fromState, event, toState) transition triples so they can be rendered\n * as an XState statechart.\n *\n * Shape detected:\n *   Machine.make({ states, events, initial }).handle({ ... })\n *\n * The state tree comes from `Machine.defineStates({...})` (or an inline\n * `states:` literal): a leaf is a tagged schema, a node is\n * `{ schema, type?, initial?, states }`. Nesting becomes dotted paths\n * ('workspace.document.Clean'), `type: 'parallel'` carries through, and a\n * compound `initial` becomes an `initial`-triggered edge. Final states can be\n * declared in either the state tree or the handler tree.\n *\n * Transitions come from the `.handle({...})` tree: `on` (events), `always`\n * (eventless), and `onDone` (compound completion). Targets are read from the\n * `target.full` / `target.local` / `target.branch` builders, including\n * `target.local.with(value, child => ...)` and nested region builders.\n */\n\nimport { statSync } from 'node:fs';\nimport {\n  Node,\n  Project,\n  SyntaxKind,\n  type CallExpression,\n  type ObjectLiteralExpression,\n} from 'ts-morph';\nimport {\n  isFunctionLike,\n  isMachineCall,\n  join,\n  locOf,\n  propEntries,\n  propValue,\n  stringValue,\n  unwrap,\n  type SourceFile,\n} from './state-machine-ast';\nimport type { SourceLocation } from './types';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface StateTransition {\n  readonly from: string;\n  readonly event: string;\n  readonly to: string;\n  /** Guard condition text when the transition is conditional (best-effort). */\n  readonly guard?: string;\n  /**\n   * Named action labels attached to the transition. Labels only: the analyzer\n   * renders and exports them but never runs anything.\n   */\n  readonly actions?: readonly string[];\n  /**\n   * Present when the transition fires automatically rather than on a user\n   * event: `initial`, `always` (eventless), `after` (delayed), or\n   * `done`/`error` (invoke completion). Automatic transitions are\n   * reachability edges but are excluded from event-coverage accounting.\n   * Absent for ordinary event transitions.\n   */\n  readonly trigger?: 'initial' | 'always' | 'after' | 'done' | 'error';\n  /** Zero-based index of the invoke that owns a done/error transition. */\n  readonly invokeIndex?: number;\n}\n\nexport interface StateInvoke {\n  readonly src: string;\n  readonly id?: string;\n}\n\nexport interface StateMachine {\n  readonly name: string;\n  readonly source: 'effect-machine' | 'machine-json';\n  readonly initial: string | undefined;\n  /** Every state path in the machine, parents included. */\n  readonly states: readonly string[];\n  readonly transitions: readonly StateTransition[];\n  readonly location: SourceLocation | undefined;\n  /**\n   * The declared alphabet — the full set of states/events the machine declares.\n   * `undefined` when it could not be resolved (e.g. an imported state tree).\n   * Used to check the machine for completeness.\n   */\n  readonly declaredStates: readonly string[] | undefined;\n  readonly declaredEvents: readonly string[] | undefined;\n  readonly alphabetSource: 'schema' | 'tagged-union' | 'config' | undefined;\n  /**\n   * States the source explicitly marks final (`type: 'final'`). `undefined`\n   * means the source has no final marker, and renderers fall back to\n   * no-outgoing-transition inference.\n   */\n  readonly finalStates?: readonly string[];\n  /** States marked `type: 'parallel'`: every child region is entered. */\n  readonly parallelStates?: readonly string[];\n  /** Entry action labels per state. Labels only — never executed. */\n  readonly entryActions?: Readonly<Record<string, readonly string[]>>;\n  /** Exit action labels per state. Labels only — never executed. */\n  readonly exitActions?: Readonly<Record<string, readonly string[]>>;\n  /** Invoked-child metadata per state (`invoke:` in the handler tree). */\n  readonly invokes?: Readonly<Record<string, readonly StateInvoke[]>>;\n}\n\n/** Explicit finals when the source declares them; else no-outgoing inference. */\nexport function finalStatesOf(machine: StateMachine): ReadonlySet<string> {\n  if (machine.finalStates !== undefined) return new Set(machine.finalStates);\n  const hasOutgoing = new Set(machine.transitions.map((t) => t.from));\n  return new Set(machine.states.filter((s) => !hasOutgoing.has(s)));\n}\n\nexport interface StateMachineAnalysis {\n  readonly machines: readonly StateMachine[];\n}\n\n/**\n * The object literal behind a value, following a local `const` binding.\n * `undefined` when the value is imported or computed.\n */\nfunction objectLiteral(\n  node: Node | undefined,\n  sf: SourceFile,\n  depth = 0,\n): ObjectLiteralExpression | undefined {\n  if (!node || depth > 8) return undefined;\n  const u = unwrap(node);\n  if (Node.isObjectLiteralExpression(u)) return u;\n  if (Node.isIdentifier(u)) {\n    return objectLiteral(sf.getVariableDeclaration(u.getText())?.getInitializer(), sf, depth + 1);\n  }\n  return undefined;\n}\n\n/**\n * The object literal behind a `states:` value: an inline tree, a\n * `Machine.defineStates({...})` / `Machine.states({...})` call, or the `.states`\n * of one. `undefined` when\n * the tree is declared in another file.\n */\nfunction stateTree(\n  node: Node | undefined,\n  sf: SourceFile,\n  depth = 0,\n): ObjectLiteralExpression | undefined {\n  if (!node || depth > 8) return undefined;\n  const u = unwrap(node);\n  // `Machine.defineStates` (<= 0.5) and `Machine.states` (>= 0.6) both take the\n  // tree as their sole argument.\n  if (isMachineCall(u, 'defineStates') || isMachineCall(u, 'states')) {\n    return objectLiteral(u.getArguments()[0], sf);\n  }\n  if (Node.isPropertyAccessExpression(u) && u.getName() === 'states') {\n    return stateTree(u.getExpression(), sf, depth + 1);\n  }\n  if (Node.isIdentifier(u)) {\n    return stateTree(sf.getVariableDeclaration(u.getText())?.getInitializer(), sf, depth + 1);\n  }\n  return objectLiteral(u, sf);\n}\n\n/**\n * The tag of a `Schema.TaggedClass<X>()('Tag', ...)`-style class declared in\n * this file, read syntactically from its extends clause. `undefined` when the\n * class is absent, imported, or not a Schema tagged class.\n */\nfunction classTag(name: string, sf: SourceFile): string | undefined {\n  const extendsText = sf.getClass(name)?.getExtends()?.getText() ?? '';\n  return /Tagged(?:Class|Request|Error)[\\s\\S]*?\\)\\s*\\(\\s*[\"'`]([^\"'`]+)[\"'`]/.exec(\n    extendsText,\n  )?.[1];\n}\n\n// =============================================================================\n// State tree\n// =============================================================================\n\ntype NodeKind = 'atomic' | 'compound' | 'parallel' | 'final';\n\ninterface TreeNode {\n  readonly path: string;\n  readonly kind: NodeKind;\n  /** Declared initial child key of a compound node. */\n  readonly initial: string | undefined;\n  readonly parent: string | undefined;\n  /** Full paths of the direct children, in declaration order. */\n  readonly children: string[];\n}\n\nconst NODE_CONFIG_KEYS = ['schema', 'type', 'initial', 'states'] as const;\n\n/**\n * The node config behind a state tree entry. A schema (an identifier, or a\n * `Union.cases.X` access) and the schema-less `{}` leaf of the 0.6+ API are\n * atomic; an object carrying any of `schema` / `type` / `initial` / `states`\n * configures a node.\n */\nfunction nodeConfig(node: Node | undefined): ObjectLiteralExpression | undefined {\n  if (!node || !Node.isObjectLiteralExpression(node)) return undefined;\n  return NODE_CONFIG_KEYS.some((key) => node.getProperty(key)) ? node : undefined;\n}\n\n/**\n * Flatten a state tree literal into dotted paths, keeping the parent/child\n * links so nothing downstream has to re-derive them from the path strings.\n */\nfunction readStateTree(\n  obj: ObjectLiteralExpression,\n  parent: TreeNode | undefined,\n  out: Map<string, TreeNode>,\n  sf: SourceFile,\n): void {\n  for (const { name: key, value } of propEntries(obj)) {\n    const inner = value ? unwrap(value) : undefined;\n    const config = nodeConfig(inner);\n    const type = config ? stringValue(propValue(config, 'type')) : undefined;\n    const children = config ? stateTree(propValue(config, 'states'), sf) : undefined;\n    const node: TreeNode = {\n      path: join(parent?.path ?? '', key),\n      kind:\n        type === 'parallel'\n          ? 'parallel'\n          : type === 'final'\n            ? 'final'\n            : children\n              ? 'compound'\n              : 'atomic',\n      initial: config ? stringValue(propValue(config, 'initial')) : undefined,\n      parent: parent?.path,\n      children: [],\n    };\n    out.set(node.path, node);\n    parent?.children.push(node.path);\n    if (children) readStateTree(children, node, out, sf);\n  }\n}\n\n/** Nearest self-or-ancestor compound node — the scope of `target.local`. */\nfunction localScope(path: string, tree: ReadonlyMap<string, TreeNode>): string {\n  let node = tree.get(path);\n  while (node) {\n    if (node.kind === 'compound') return node.path;\n    node = node.parent === undefined ? undefined : tree.get(node.parent);\n  }\n  return '';\n}\n\n// =============================================================================\n// Target builders\n// =============================================================================\n\n/**\n * Walk a nested region builder: `parent(value, child => child.Leaf(...))`\n * appends `.Leaf`. Stops when the callback chains more than one region\n * (a parallel entry) — the parent path is then the sound target.\n */\nfunction descendBuilder(call: CallExpression, path: string, depth = 0): string {\n  if (depth > 8) return path;\n  const arrows = call.getArguments().map(unwrap).filter(isFunctionLike);\n  const arrow = arrows[0];\n  if (arrows.length !== 1 || !arrow) return path;\n  const param = arrow.getParameters()[0]?.getName();\n  const body = unwrap(arrow.getBody());\n  if (param === undefined || !Node.isCallExpression(body)) return path;\n  const expr = body.getExpression();\n  if (!Node.isPropertyAccessExpression(expr)) return path;\n  const base = expr.getExpression();\n  // A chained base (`region.a(...).b(...)`) enters several regions at once.\n  if (!Node.isIdentifier(base) || base.getText() !== param) return path;\n  return descendBuilder(body, join(path, expr.getName()), depth + 1);\n}\n\n/**\n * Resolve one `<builder>.<mode>.<state>(...)` call to a full state path.\n * The builder is `target` in the 0.5-era destructured handler\n * (`({ target }) => target.full.X()`) and the handler's own parameter in the\n * 0.6+ shape (`(to) => to.full.X()`), so `builders` carries the parameter\n * names bound inside the handler.\n * `full` and `branch` are absolute; `local` is relative to the nearest\n * compound ancestor, and `local.with(...)` re-enters that scope itself.\n */\nfunction targetPath(\n  call: CallExpression,\n  from: string,\n  tree: ReadonlyMap<string, TreeNode>,\n  builders: ReadonlySet<string> = new Set(),\n): string | undefined {\n  const expr = call.getExpression();\n  if (!Node.isPropertyAccessExpression(expr)) return undefined;\n  const mode = expr.getExpression();\n  if (!Node.isPropertyAccessExpression(mode)) return undefined;\n  const modeName = mode.getName();\n  if (modeName !== 'full' && modeName !== 'local' && modeName !== 'branch') {\n    return undefined;\n  }\n  const receiver = mode.getExpression().getText();\n  if (!/(^|\\.)target$/.test(receiver) && !builders.has(receiver)) return undefined;\n\n  const segment = expr.getName();\n  const base = modeName === 'local' ? localScope(from, tree) : '';\n  const start =\n    modeName === 'local' && segment === 'with' ? base : join(base, segment);\n  return descendBuilder(call, start);\n}\n\n/** A call to `<anything>.<name>(...)` — a builder step, whatever the receiver. */\nfunction isCallTo(node: Node | undefined, name: string): boolean {\n  if (!node || !Node.isCallExpression(node)) return false;\n  const expr = node.getExpression();\n  return Node.isPropertyAccessExpression(expr) && expr.getName() === name;\n}\n\n/**\n * The branch condition guarding a target, as source text. A handler picks its\n * target with an ordinary `if` or ternary, so the nearest enclosing condition\n * is the guard label — negated when the target sits in the else branch.\n */\nfunction guardOf(call: Node, handler: Node): string | undefined {\n  let child = call;\n  let cur: Node | undefined = call.getParent();\n  while (cur && cur !== handler) {\n    // `to.branches({ accepted: { target: ... } })` names its own conditions, so\n    // the branch key is a better label than any surrounding expression.\n    if (\n      Node.isPropertyAssignment(cur) &&\n      Node.isObjectLiteralExpression(cur.getParent()) &&\n      isCallTo(cur.getParent().getParent(), 'branches')\n    ) {\n      return cur.getName();\n    }\n    if (Node.isConditionalExpression(cur)) {\n      const cond = cur.getCondition().getText();\n      return cur.getWhenTrue() === child ? cond : `!(${cond})`;\n    }\n    if (Node.isIfStatement(cur)) {\n      const cond = cur.getExpression().getText();\n      const then = cur.getThenStatement();\n      const inThen =\n        call.getStart() >= then.getStart() && call.getEnd() <= then.getEnd();\n      return inThen ? cond : `!(${cond})`;\n    }\n    child = cur;\n    cur = cur.getParent();\n  }\n  return undefined;\n}\n\ninterface HandlerTarget {\n  readonly to: string;\n  readonly guard?: string;\n}\n\n/**\n * Identifier parameters bound anywhere inside a handler. In the 0.6+ API the\n * target builder arrives as the handler's own parameter (`(to) => ...`), so its\n * name is whatever the author picked and has to be read from the source.\n */\nfunction builderNames(handler: Node): Set<string> {\n  const names = new Set<string>();\n  const fns = [\n    ...(isFunctionLike(handler) ? [handler] : []),\n    ...handler.getDescendantsOfKind(SyntaxKind.ArrowFunction),\n    ...handler.getDescendantsOfKind(SyntaxKind.FunctionExpression),\n  ];\n  for (const fn of fns) {\n    for (const param of fn.getParameters()) {\n      const nameNode = param.getNameNode();\n      if (Node.isIdentifier(nameNode)) names.add(nameNode.getText());\n    }\n  }\n  return names;\n}\n\n/** Every distinct state path a handler body can transition to. */\nfunction targetsOf(\n  handler: Node,\n  from: string,\n  tree: ReadonlyMap<string, TreeNode>,\n): HandlerTarget[] {\n  const out: HandlerTarget[] = [];\n  const seen = new Set<string>();\n  const builders = builderNames(handler);\n  const calls = [\n    ...(Node.isCallExpression(handler) ? [handler] : []),\n    ...handler.getDescendantsOfKind(SyntaxKind.CallExpression),\n  ];\n  for (const call of calls) {\n    const to = targetPath(call, from, tree, builders);\n    if (to === undefined) continue;\n    const guard = guardOf(call, handler);\n    const key = `${to}|${guard ?? ''}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    out.push(guard === undefined ? { to } : { to, guard });\n  }\n  return out;\n}\n\n// =============================================================================\n// Handler tree\n// =============================================================================\n\n/**\n * The id an invoked child was registered under: `Machine.child('selection', M)`\n * declares `'selection'`. Falls back to the reference's own text.\n */\nfunction childId(node: Node | undefined, sf: SourceFile): string | undefined {\n  if (!node) return undefined;\n  const u = unwrap(node);\n  if (!Node.isIdentifier(u)) return u.getText();\n  const decl = sf.getVariableDeclaration(u.getText())?.getInitializer();\n  const call = decl ? unwrap(decl) : undefined;\n  return (\n    (call && isMachineCall(call, 'child')\n      ? stringValue(call.getArguments()[0])\n      : undefined) ?? u.getText()\n  );\n}\n\n/**\n * Completion handlers on a 0.6+ invoke builder, mapped onto the IR triggers the\n * XState exporter already understands.\n */\nconst INVOKE_COMPLETIONS: Readonly<Record<string, 'done' | 'error'>> = {\n  onDone: 'done',\n  onFailure: 'error',\n  onError: 'error',\n};\n\n/** Verbs that start a 0.6+ invoke builder chain — the root of the chain. */\nconst INVOKE_SOURCES = new Set(['effect', 'stream', 'timer', 'logic', 'child']);\n\ninterface InvokeBuilder {\n  readonly invoke: StateInvoke;\n  /** Completion handlers in source order, for `trigger` + `invokeIndex`. */\n  readonly completions: readonly {\n    readonly trigger: 'done' | 'error';\n    readonly handler: Node;\n  }[];\n}\n\n/**\n * Read a 0.6+ invoke builder chain:\n * `from.effect('load', ...).onDone(to => ...).onFailure(to => ...)`.\n * `undefined` when the node is not such a chain — the 0.5 `Machine.invoke({...})`\n * object form is read by `invokesOf` instead.\n */\nfunction invokeBuilder(node: Node, sf: SourceFile): InvokeBuilder | undefined {\n  const completions: { trigger: 'done' | 'error'; handler: Node }[] = [];\n  let cur: Node = unwrap(node);\n  for (let depth = 0; Node.isCallExpression(cur) && depth <= 8; depth += 1) {\n    const expr = cur.getExpression();\n    if (!Node.isPropertyAccessExpression(expr)) return undefined;\n    const name = expr.getName();\n    const trigger = INVOKE_COMPLETIONS[name];\n    if (trigger !== undefined) {\n      const handler = cur.getArguments()[0];\n      if (handler) completions.unshift({ trigger, handler: unwrap(handler) });\n      cur = expr.getExpression();\n      continue;\n    }\n    if (!INVOKE_SOURCES.has(name)) return undefined;\n    const first = cur.getArguments()[0];\n    const id = stringValue(first) ?? (name === 'child' ? childId(first, sf) : undefined);\n    return {\n      invoke: { src: id ?? name, ...(id !== undefined ? { id } : {}) },\n      completions,\n    };\n  }\n  return undefined;\n}\n\n/**\n * Every invoke declared on a state, in source order. The 0.5 forms\n * (`Machine.invoke({...})`, a factory call) carry no completion handlers; the\n * 0.6+ builder chain carries its `onDone` / `onFailure` targets with it.\n */\nfunction invokesOf(node: Node | undefined, sf: SourceFile, depth = 0): InvokeBuilder[] {\n  if (!node || depth > 8) return [];\n  const u = unwrap(node);\n  if (isFunctionLike(u)) return invokesOf(u.getBody(), sf, depth + 1);\n  if (Node.isArrayLiteralExpression(u)) {\n    return u.getElements().flatMap((element) => invokesOf(element, sf, depth + 1));\n  }\n  if (Node.isIdentifier(u)) {\n    return invokesOf(\n      sf.getVariableDeclaration(u.getText())?.getInitializer(),\n      sf,\n      depth + 1,\n    );\n  }\n  if (!Node.isCallExpression(u)) return [];\n  const builder = invokeBuilder(u, sf);\n  if (builder) return [builder];\n  const callee = u.getExpression().getText();\n  if (isMachineCall(u, 'invoke') || isMachineCall(u, 'invokeMachine')) {\n    const config = objectLiteral(u.getArguments()[0], sf);\n    const id = config ? stringValue(propValue(config, 'id')) : undefined;\n    const src = id ?? childId(config ? propValue(config, 'child') : undefined, sf);\n    return src === undefined\n      ? []\n      : [{ invoke: { src, ...(id !== undefined ? { id } : {}) }, completions: [] }];\n  }\n  // `invoke: () => SearchMachine({...})` — a local factory whose body builds the\n  // invoke, so the declared id is one hop away.\n  const factory = sf.getVariableDeclaration(callee)?.getInitializer();\n  if (factory && isFunctionLike(unwrap(factory))) {\n    return invokesOf(factory, sf, depth + 1);\n  }\n  return [{ invoke: { src: callee.split('.').pop() ?? callee }, completions: [] }];\n}\n\n/**\n * Label for an `entry` / `exit` action. A named reference (`entry: logStart`)\n * carries its own name; an inline anonymous effect has none, so the state gets\n * a bare marker recording that an action runs there.\n */\nfunction actionLabel(node: Node, kind: 'entry' | 'exit'): string {\n  const u = unwrap(node);\n  return Node.isIdentifier(u) ? u.getText() : kind;\n}\n\ninterface HandlerScan {\n  readonly transitions: StateTransition[];\n  readonly finalStates: string[];\n  readonly entry: Record<string, readonly string[]>;\n  readonly exit: Record<string, readonly string[]>;\n  readonly invokes: Record<string, readonly StateInvoke[]>;\n}\n\n/** Read one state's handler config: transitions, final marker, actions, invokes, children. */\nfunction readHandlerNode(\n  config: ObjectLiteralExpression,\n  path: string,\n  tree: ReadonlyMap<string, TreeNode>,\n  sf: SourceFile,\n  out: HandlerScan,\n): void {\n  const push = (\n    event: string,\n    handler: Node,\n    trigger?: StateTransition['trigger'],\n    invokeIndex?: number,\n  ): void => {\n    for (const { to, guard } of targetsOf(handler, path, tree)) {\n      out.transitions.push({\n        from: path,\n        event,\n        to,\n        ...(guard !== undefined ? { guard } : {}),\n        ...(trigger !== undefined ? { trigger } : {}),\n        ...(invokeIndex !== undefined ? { invokeIndex } : {}),\n      });\n    }\n  };\n\n  const on = objectLiteral(propValue(config, 'on'), sf);\n  for (const { name: event, value } of on ? propEntries(on) : []) {\n    if (!value) continue;\n    const handler = unwrap(value);\n    // `{ reenter: true, transition: handler }` is the long form of a handler.\n    push(\n      event,\n      Node.isObjectLiteralExpression(handler)\n        ? (propValue(handler, 'transition') ?? handler)\n        : handler,\n    );\n  }\n\n  const always = propValue(config, 'always');\n  if (always) push('always', always, 'always');\n\n  const onDone = propValue(config, 'onDone');\n  if (onDone) push('onDone', onDone, 'done');\n\n  if (stringValue(propValue(config, 'type')) === 'final') {\n    out.finalStates.push(path);\n  }\n\n  const entry = propValue(config, 'entry');\n  if (entry) out.entry[path] = [actionLabel(entry, 'entry')];\n  const exit = propValue(config, 'exit');\n  if (exit) out.exit[path] = [actionLabel(exit, 'exit')];\n\n  const invoke = propValue(config, 'invoke');\n  if (invoke) {\n    const found = invokesOf(invoke, sf);\n    if (found.length > 0) out.invokes[path] = found.map((f) => f.invoke);\n    for (const [invokeIndex, { completions }] of found.entries()) {\n      for (const { trigger, handler } of completions) {\n        push(\n          trigger === 'done' ? 'onDone' : 'onError',\n          handler,\n          trigger,\n          invokeIndex,\n        );\n      }\n    }\n  }\n\n  const children = objectLiteral(propValue(config, 'states'), sf);\n  for (const { name: key, value } of children ? propEntries(children) : []) {\n    const child = objectLiteral(value, sf);\n    if (child) readHandlerNode(child, join(path, key), tree, sf, out);\n  }\n}\n\n// =============================================================================\n// Machine assembly\n// =============================================================================\n\n/** One `.handle({...})` implementation of a machine definition. */\ninterface Implementation {\n  readonly handlers: ObjectLiteralExpression | undefined;\n  /** The `.handle(...)` call itself, or the `make` call when unimplemented. */\n  readonly anchor: Node;\n}\n\n/** The `.handle({...})` call chained directly onto an expression, if any. */\nfunction handleCallOn(node: Node): CallExpression | undefined {\n  const parent = node.getParent();\n  if (!parent || !Node.isPropertyAccessExpression(parent)) return undefined;\n  if (parent.getName() !== 'handle') return undefined;\n  const call = parent.getParent();\n  return call && Node.isCallExpression(call) ? call : undefined;\n}\n\n/**\n * Every implementation of a `Machine.make(...)` definition. Usually one, chained\n * directly. A definition stored in a `const` can be handled more than once —\n * production and testing variants of the same model — and each is its own\n * machine.\n */\nfunction implementationsOf(\n  makeCall: CallExpression,\n  sf: SourceFile,\n): Implementation[] {\n  const asImplementation = (call: CallExpression): Implementation => ({\n    handlers: objectLiteral(call.getArguments()[0], sf),\n    anchor: call,\n  });\n\n  const chained = handleCallOn(makeCall);\n  if (chained) return [asImplementation(chained)];\n\n  const definition = ownerOf(makeCall)?.name;\n  const found: Implementation[] = [];\n  if (definition !== undefined) {\n    for (const identifier of sf.getDescendantsOfKind(SyntaxKind.Identifier)) {\n      if (identifier.getText() !== definition) continue;\n      const call = handleCallOn(identifier);\n      if (call) found.push(asImplementation(call));\n    }\n  }\n  return found.length > 0 ? found : [{ handlers: undefined, anchor: makeCall }];\n}\n\n/** `{ path, state: { path, ... } }` — the deepest path of a snapshot literal. */\nfunction snapshotPath(\n  obj: ObjectLiteralExpression,\n  depth = 0,\n): string | undefined {\n  if (depth > 8) return undefined;\n  const path = stringValue(propValue(obj, 'path'));\n  if (path === undefined) return undefined;\n  const child = objectLiteral(propValue(obj, 'state'), obj.getSourceFile());\n  return (child ? snapshotPath(child, depth + 1) : undefined) ?? path;\n}\n\n/**\n * The longest prefix of a `to.a.b.c` property chain that names a real state.\n * The 0.6+ initial builder mixes state segments with verbs\n * (`to.workspace.initial.resolve(...)`, `to.Idle()`), and only the tree can say\n * where the path stops.\n */\nfunction chainPath(\n  node: Node,\n  tree: ReadonlyMap<string, TreeNode>,\n): string | undefined {\n  const segments: string[] = [];\n  let cur: Node = node;\n  while (Node.isPropertyAccessExpression(cur)) {\n    segments.unshift(cur.getName());\n    cur = cur.getExpression();\n  }\n  if (!Node.isIdentifier(cur)) return undefined;\n  let path = '';\n  for (const segment of segments) {\n    const next = join(path, segment);\n    if (!tree.has(next)) break;\n    path = next;\n  }\n  return path === '' ? undefined : path;\n}\n\n/**\n * The initial state path from the `initial:` value — a\n * `States.initial.<state>(...)` builder chain (<= 0.5), a `(to) => to.<state>`\n * builder chain (>= 0.6), or a `{ path }` snapshot literal.\n */\nfunction initialPath(\n  node: Node | undefined,\n  tree: ReadonlyMap<string, TreeNode>,\n): string | undefined {\n  if (!node) return undefined;\n  for (const call of node.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n    const expr = call.getExpression();\n    if (!Node.isPropertyAccessExpression(expr)) continue;\n    const owner = expr.getExpression();\n    // `States.initial.<state>(...)`. The 0.6+ builder also has an `initial`\n    // segment (`to.workspace.initial.resolve(...)`), so the name after it only\n    // counts when the tree agrees it is a state.\n    if (\n      Node.isPropertyAccessExpression(owner) &&\n      owner.getName() === 'initial' &&\n      tree.has(expr.getName())\n    ) {\n      return descendBuilder(call, expr.getName());\n    }\n  }\n  for (const access of node.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression)) {\n    const path = chainPath(access, tree);\n    if (path !== undefined) return path;\n  }\n  for (const obj of node.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression)) {\n    const path = snapshotPath(obj);\n    if (path !== undefined) return path;\n  }\n  return undefined;\n}\n\n/** The declaration a `Machine.make(...)` chain is assigned to. */\nfunction ownerOf(node: Node): { readonly name: string; readonly anchor: Node } | undefined {\n  let cur: Node | undefined = node.getParent();\n  while (cur) {\n    if (Node.isVariableDeclaration(cur)) {\n      return { name: cur.getName(), anchor: cur.getNameNode() };\n    }\n    cur = cur.getParent();\n  }\n  return undefined;\n}\n\nfunction arrayLiteral(\n  node: Node | undefined,\n  sf: SourceFile,\n  depth = 0,\n): Node | undefined {\n  if (!node || depth > 8) return undefined;\n  const unwrapped = unwrap(node);\n  if (Node.isArrayLiteralExpression(unwrapped)) return unwrapped;\n  if (Node.isIdentifier(unwrapped)) {\n    return arrayLiteral(\n      sf.getVariableDeclaration(unwrapped.getText())?.getInitializer(),\n      sf,\n      depth + 1,\n    );\n  }\n  return undefined;\n}\n\n/**\n * Tags of a `Machine.events(...)` descriptor — the 0.6+ event alphabet. The\n * argument is a `Schema.TaggedUnion({ Tag: {...} })` whose keys are the tags, or\n * tagged classes passed directly. `Machine.events()` declares an empty alphabet.\n */\nfunction eventsDescriptor(\n  node: Node | undefined,\n  sf: SourceFile,\n  depth = 0,\n): string[] | undefined {\n  if (!node || depth > 8) return undefined;\n  const u = unwrap(node);\n  if (Node.isIdentifier(u)) {\n    return eventsDescriptor(\n      sf.getVariableDeclaration(u.getText())?.getInitializer(),\n      sf,\n      depth + 1,\n    );\n  }\n  if (!isMachineCall(u, 'events')) return undefined;\n  const tags: string[] = [];\n  for (const argument of u.getArguments().map(unwrap)) {\n    const union = Node.isCallExpression(argument)\n      ? objectLiteral(argument.getArguments()[0], sf)\n      : undefined;\n    if (union) {\n      tags.push(...propEntries(union).map(({ name }) => name));\n      continue;\n    }\n    if (!Node.isIdentifier(argument)) return undefined;\n    tags.push(classTag(argument.getText(), sf) ?? argument.getText());\n  }\n  return tags;\n}\n\n/**\n * The declared event alphabet: an `events: [A, B]` array (<= 0.5) or a\n * `Machine.events(...)` descriptor (>= 0.6).\n */\nfunction declaredEventsOf(\n  config: ObjectLiteralExpression,\n  sf: SourceFile,\n): string[] | undefined {\n  const events = propValue(config, 'events');\n  const array = arrayLiteral(events, sf);\n  if (!array || !Node.isArrayLiteralExpression(array)) {\n    return eventsDescriptor(events, sf);\n  }\n  const elements = array.getElements().map(unwrap);\n  if (!elements.every(Node.isIdentifier)) return undefined;\n  return elements.map((element) => classTag(element.getText(), sf) ?? element.getText());\n}\n\nfunction extractMachine(\n  makeCall: CallExpression,\n  implementation: Implementation,\n  filePath: string,\n  sf: SourceFile,\n): StateMachine | undefined {\n  const config = objectLiteral(makeCall.getArguments()[0], sf);\n  if (!config) return undefined;\n  const statesObj = stateTree(propValue(config, 'states'), sf);\n  if (!statesObj) return undefined;\n\n  const tree = new Map<string, TreeNode>();\n  readStateTree(statesObj, undefined, tree, sf);\n  if (tree.size === 0) return undefined;\n\n  const scan: HandlerScan = {\n    transitions: [],\n    finalStates: [],\n    entry: {},\n    exit: {},\n    invokes: {},\n  };\n  const { handlers } = implementation;\n  for (const { name: key, value } of handlers ? propEntries(handlers) : []) {\n    const nodeConfig = objectLiteral(value, sf);\n    if (nodeConfig) readHandlerNode(nodeConfig, key, tree, sf, scan);\n  }\n\n  const declaredStates: string[] = [];\n  const finals: string[] = [];\n  const parallels: string[] = [];\n  const transitions: StateTransition[] = [];\n  for (const node of tree.values()) {\n    declaredStates.push(node.path);\n    if (node.kind === 'final') finals.push(node.path);\n    if (node.kind === 'parallel') parallels.push(node.path);\n    // Entering a state implies entering its initial child — a compound's\n    // declared `initial`, and every region of a parallel node.\n    const entered =\n      node.kind === 'parallel'\n        ? node.children\n        : node.initial !== undefined\n          ? [join(node.path, node.initial)]\n          : [];\n    for (const to of entered) {\n      transitions.push({ from: node.path, event: '', to, trigger: 'initial' });\n    }\n  }\n  for (const finalState of scan.finalStates) {\n    if (!finals.includes(finalState)) finals.push(finalState);\n  }\n  transitions.push(...scan.transitions);\n\n  // A target that is not in the tree (a typo, or a state added to a handler but\n  // not to `defineStates`) still gets drawn, and coverage flags it as undeclared.\n  const states = [...new Set([...declaredStates, ...transitions.map((t) => t.to)])];\n  const declaredEvents = declaredEventsOf(config, sf);\n  const owner = ownerOf(implementation.anchor) ?? ownerOf(makeCall);\n\n  return {\n    name: owner?.name ?? stringValue(propValue(config, 'id')) ?? 'Machine',\n    source: 'effect-machine',\n    initial: initialPath(propValue(config, 'initial'), tree) ?? declaredStates[0],\n    states,\n    transitions,\n    location: locOf(owner?.anchor ?? makeCall, filePath),\n    declaredStates,\n    declaredEvents,\n    alphabetSource: 'config',\n    // Always set, even when empty: the state tree and handler config declare\n    // finals explicitly, so no-outgoing inference would mark ordinary leaves.\n    finalStates: finals,\n    ...(parallels.length > 0 ? { parallelStates: parallels } : {}),\n    ...(Object.keys(scan.entry).length > 0 ? { entryActions: scan.entry } : {}),\n    ...(Object.keys(scan.exit).length > 0 ? { exitActions: scan.exit } : {}),\n    ...(Object.keys(scan.invokes).length > 0 ? { invokes: scan.invokes } : {}),\n  };\n}\n\n// =============================================================================\n// Entry point\n// =============================================================================\n\n/**\n * State and event counts for a one-line summary. Events are the declared\n * alphabet — automatic triggers (`initial`, `always`, an invoke's `onDone` /\n * `onError`) are not events anyone can send, so they must not inflate it.\n */\nexport function summarizeAlphabet(machine: StateMachine): {\n  readonly states: number;\n  readonly events: number;\n} {\n  const observed = new Set(\n    machine.transitions.filter((t) => t.trigger === undefined).map((t) => t.event),\n  );\n  return {\n    states: machine.states.length,\n    events: machine.declaredEvents?.length ?? observed.size,\n  };\n}\n\nconst analysisCache = new Map<\n  string,\n  { readonly mtimeMs: number; readonly analysis: StateMachineAnalysis }\n>();\n\nexport function analyzeStateMachines(\n  filePath: string,\n  source?: string,\n): StateMachineAnalysis {\n  const mtimeMs =\n    source === undefined\n      ? (() => {\n          try {\n            return statSync(filePath).mtimeMs;\n          } catch {\n            return undefined;\n          }\n        })()\n      : undefined;\n  // Only trust the cache when the mtime is known; a failed stat must re-analyze.\n  if (source === undefined && mtimeMs !== undefined) {\n    const cached = analysisCache.get(filePath);\n    if (cached?.mtimeMs === mtimeMs) return cached.analysis;\n  }\n  const project = new Project({ useInMemoryFileSystem: !!source });\n  const sf = source\n    ? project.createSourceFile(filePath, source, { overwrite: true })\n    : project.addSourceFileAtPath(filePath);\n\n  const machines: StateMachine[] = [];\n  for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {\n    if (!isMachineCall(call, 'make')) continue;\n    for (const implementation of implementationsOf(call, sf)) {\n      const machine = extractMachine(call, implementation, filePath, sf);\n      if (machine) machines.push(machine);\n    }\n  }\n\n  const analysis = { machines };\n  if (source === undefined && mtimeMs !== undefined) {\n    analysisCache.set(filePath, { mtimeMs, analysis });\n  }\n  return analysis;\n}\n","/**\n * ts-morph helpers for reading `@typeonce/effect-machine` source.\n *\n * Generic AST plumbing only — unwrapping expressions, reading object literals,\n * and resolving whether an identifier is really the package's `Machine`. It\n * knows nothing about states, transitions, or coverage, so both the extractor\n * and the diagnostics scanner can sit on top of it.\n */\n\nimport {\n  Node,\n  SyntaxKind,\n  type ArrowFunction,\n  type CallExpression,\n  type FunctionExpression,\n  type ObjectLiteralExpression,\n  type Project,\n} from 'ts-morph';\nimport type { SourceLocation } from './types';\n\nexport type SourceFile = ReturnType<Project['createSourceFile']>;\n\n/**\n * Strip `as const`, `satisfies`, parentheses, `!` and `<T>` assertions.\n *\n * The same rule the program walker uses, so a wrapper cannot be transparent in\n * one analyzer and opaque in the other. This copy also missed `!`.\n */\nimport { unwrapExpression as unwrap } from './analysis-utils';\nexport { unwrap };\n\n/** Read a string-literal value (after unwrapping `as const`), or undefined. */\nexport function stringValue(node: Node | undefined): string | undefined {\n  if (!node) return undefined;\n  const u = unwrap(node);\n  if (Node.isStringLiteral(u)) return u.getLiteralValue();\n  if (Node.isNoSubstitutionTemplateLiteral(u)) return u.getLiteralText();\n  return undefined;\n}\n\nexport interface PropEntry {\n  readonly name: string;\n  /** `undefined` for a shorthand property (`{ Idle }`). */\n  readonly value: Node | undefined;\n}\n\n/** Named properties of an object literal, shorthand included. */\nexport function propEntries(obj: ObjectLiteralExpression): PropEntry[] {\n  const out: PropEntry[] = [];\n  for (const prop of obj.getProperties()) {\n    if (Node.isShorthandPropertyAssignment(prop)) {\n      out.push({ name: prop.getName(), value: undefined });\n      continue;\n    }\n    if (!Node.isPropertyAssignment(prop)) continue;\n    const nameNode = prop.getNameNode();\n    const name = Node.isStringLiteral(nameNode)\n      ? nameNode.getLiteralValue()\n      : Node.isIdentifier(nameNode)\n        ? nameNode.getText()\n        : undefined;\n    if (name !== undefined) out.push({ name, value: prop.getInitializer() });\n  }\n  return out;\n}\n\nexport function propValue(obj: ObjectLiteralExpression, name: string): Node | undefined {\n  return obj.getProperty(name)?.asKind(SyntaxKind.PropertyAssignment)?.getInitializer();\n}\n\nexport function locOf(node: Node, filePath: string): SourceLocation {\n  const sf = node.getSourceFile();\n  const offset = node.getStart();\n  const { line, column } = sf.getLineAndColumnAtPos(offset);\n  return { filePath, line, column, offset };\n}\n\nexport const join = (parent: string, child: string): string =>\n  parent === '' ? child : `${parent}.${child}`;\n\nexport function isFunctionLike(node: Node): node is ArrowFunction | FunctionExpression {\n  return Node.isArrowFunction(node) || Node.isFunctionExpression(node);\n}\n\nexport function isEffectMachineBinding(name: string, sf: SourceFile): boolean {\n  return sf.getImportDeclarations().some((declaration) => {\n    if (declaration.getModuleSpecifierValue() !== '@typeonce/effect-machine') {\n      return false;\n    }\n    return declaration.getNamedImports().some((namedImport) => {\n      if (namedImport.getName() !== 'Machine') return false;\n      return (namedImport.getAliasNode()?.getText() ?? 'Machine') === name;\n    });\n  });\n}\n\nexport function isEffectMachineNamespace(name: string, sf: SourceFile): boolean {\n  return sf.getImportDeclarations().some(\n    (declaration) =>\n      declaration.getModuleSpecifierValue() === '@typeonce/effect-machine' &&\n      declaration.getNamespaceImport()?.getText() === name,\n  );\n}\n\n/** A call to a method on the imported `Machine` namespace. */\nexport function isMachineCall(node: Node, name: string): node is CallExpression {\n  if (!Node.isCallExpression(node)) return false;\n  const expr = node.getExpression();\n  if (!Node.isPropertyAccessExpression(expr) || expr.getName() !== name) {\n    return false;\n  }\n  const owner = expr.getExpression();\n  if (Node.isIdentifier(owner)) {\n    return isEffectMachineBinding(owner.getText(), node.getSourceFile());\n  }\n  return (\n    Node.isPropertyAccessExpression(owner) &&\n    owner.getName() === 'Machine' &&\n    Node.isIdentifier(owner.getExpression()) &&\n    isEffectMachineNamespace(owner.getExpression().getText(), node.getSourceFile())\n  );\n}\n","/**\n * MachineJSON ingestion.\n *\n * Turns an XState v6 `MachineJSON` (the canonical machine-as-data shape) into\n * the analyzer's {@link StateMachine} IR, so a machine authored *anywhere* can\n * be run through the same coverage / reachability / diagnostics engine and the\n * same statechart renderers as machines extracted from source.\n *\n * `MachineJSON` is a standard data format (XState / Stately, hand-written\n * configs, or any library that emits it). This module deliberately takes **no\n * dependency** on any authoring library — it only reads the format's shape.\n * The declared alphabet is exact here: states come from the recursive config\n * tree and events come from `schemas.events` when available (falling back to\n * `on` keys), so coverage can use `alphabetSource: 'config'`.\n *\n * `on` (event), `always` (eventless), and `after` (delayed) transitions are all\n * ingested. Automatic initial/always/after transitions carry a `trigger` tag\n * so coverage counts them as reachability edges without treating them as events.\n */\n\nimport type { StateInvoke, StateMachine, StateTransition } from './state-machine';\n\n// =============================================================================\n// MachineJSON shape (structural — the XState v6 machine-as-data format)\n// =============================================================================\n\nexport interface MachineJSONUnserializable {\n  readonly $unserializable: 'function' | 'actor' | 'schema' | 'value';\n  readonly id?: string;\n}\n\nexport type MachineJSONExpression =\n  | { readonly '@expr': string; readonly '@lang'?: string }\n  | { readonly '@code': string; readonly '@lang'?: string };\n\nexport type MachineJSONGuard =\n  | { readonly type: string; readonly params?: Readonly<Record<string, unknown>> }\n  | MachineJSONUnserializable\n  | MachineJSONExpression;\n\nexport type MachineJSONAction =\n  | { readonly type: string; readonly [key: string]: unknown }\n  | MachineJSONUnserializable\n  | MachineJSONExpression;\n\nexport interface MachineJSONTransition {\n  readonly target?: string | readonly string[];\n  readonly guard?: MachineJSONGuard;\n  readonly actions?: readonly MachineJSONAction[];\n}\n\ntype MachineJSONSingleValue = string | MachineJSONTransition | MachineJSONUnserializable;\n\nexport type MachineJSONValue =\n  | MachineJSONSingleValue\n  | readonly MachineJSONSingleValue[];\n\nexport type MachineJSONInitial =\n  | string\n  | { readonly target: string; readonly input?: unknown };\n\nexport interface MachineJSONInvoke {\n  readonly id?: string;\n  readonly src: string | MachineJSONUnserializable;\n  readonly onDone?: MachineJSONValue;\n  readonly onError?: MachineJSONValue;\n}\n\nexport interface MachineJSONStateNode {\n  readonly id?: string;\n  readonly type?: 'atomic' | 'compound' | 'parallel' | 'final' | 'history' | 'choice';\n  readonly initial?: MachineJSONInitial;\n  readonly states?: Record<string, MachineJSONStateNode>;\n  readonly entry?: readonly MachineJSONAction[];\n  readonly exit?: readonly MachineJSONAction[];\n  readonly invoke?: MachineJSONInvoke | readonly MachineJSONInvoke[];\n  readonly on?: Record<string, MachineJSONValue>;\n  readonly always?: MachineJSONValue;\n  readonly after?: Record<string, MachineJSONValue>;\n}\n\nexport interface MachineJSON {\n  readonly id?: string;\n  readonly version?: string;\n  readonly initial: MachineJSONInitial;\n  readonly states: Record<string, MachineJSONStateNode>;\n  readonly schemas?: {\n    readonly events?: Record<string, unknown> | MachineJSONUnserializable;\n  };\n}\n\nexport interface FromMachineJSONOptions {\n  /** Overrides the machine name (defaults to `json.id`, then `'machine'`). */\n  readonly name?: string;\n}\n\n// =============================================================================\n// Validation (trust boundary — MachineJSON is often parsed from untrusted text)\n// =============================================================================\n\n/** Non-null, non-array object — used only to check genuinely `unknown` input. */\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Throw a uniform, located error unless `value` is a plain object. */\nfunction requireObject(value: unknown, what: string): void {\n  if (!isPlainObject(value)) {\n    throw new Error(`fromMachineJSON: ${what} must be an object`);\n  }\n}\n\nfunction markerLabel(value: MachineJSONUnserializable): string {\n  return value.id ?? `$unserializable:${value.$unserializable}`;\n}\n\nfunction invokeSource(\n  value: unknown,\n  where: string,\n): StateInvoke {\n  if (typeof value === 'string') return { src: value };\n  if (!isPlainObject(value)) {\n    throw new Error(\n      `fromMachineJSON: ${where}.src must be a string or $unserializable object`,\n    );\n  }\n  const marker = value;\n  const kind = marker.$unserializable;\n  if (\n    kind !== 'function' &&\n    kind !== 'actor' &&\n    kind !== 'schema' &&\n    kind !== 'value'\n  ) {\n    throw new Error(\n      `fromMachineJSON: ${where}.src must contain a valid $unserializable marker`,\n    );\n  }\n  if (marker.id !== undefined && typeof marker.id !== 'string') {\n    throw new Error(`fromMachineJSON: ${where}.src.id must be a string`);\n  }\n  return {\n    src: marker.id ?? `$unserializable:${kind}`,\n  };\n}\n\nfunction guardLabel(value: MachineJSONGuard, where: string): string {\n  if (!isPlainObject(value)) {\n    throw new Error(`fromMachineJSON: ${where}.guard must be an object`);\n  }\n  const record = value as unknown as Record<string, unknown>;\n  if (typeof record.type === 'string') return record.type;\n  if (typeof record['@expr'] === 'string') return record['@expr'];\n  if (typeof record['@code'] === 'string') return record['@code'];\n  if (typeof record.$unserializable === 'string') {\n    return markerLabel(record as unknown as MachineJSONUnserializable);\n  }\n  throw new Error(\n    `fromMachineJSON: ${where}.guard must contain type, @expr, @code, or $unserializable`,\n  );\n}\n\n/** Best-effort label for an action: its type, expression text, or marker. */\nfunction actionLabel(value: MachineJSONAction): string | undefined {\n  if (!isPlainObject(value)) return undefined;\n  const record = value as unknown as Record<string, unknown>;\n  if (typeof record.type === 'string') return record.type;\n  if (typeof record['@expr'] === 'string') return record['@expr'];\n  if (typeof record['@code'] === 'string') return record['@code'];\n  if (typeof record.$unserializable === 'string') {\n    return markerLabel(record as unknown as MachineJSONUnserializable);\n  }\n  return undefined;\n}\n\nfunction actionLabels(\n  value: readonly MachineJSONAction[] | undefined,\n): string[] | undefined {\n  if (value === undefined) return undefined;\n  const labels = value.map(actionLabel).filter((x): x is string => x !== undefined);\n  return labels.length > 0 ? labels : undefined;\n}\n\n/** Normalize a transition value to one record per target/branch. */\nfunction normalizeValue(\n  value: MachineJSONValue,\n  where: string,\n): readonly { target?: string; guard?: string; actions?: readonly string[] }[] {\n  const one = (\n    v: MachineJSONSingleValue,\n  ): readonly { target?: string; guard?: string; actions?: readonly string[] }[] => {\n    if (typeof v === 'string') return [{ target: v }];\n    if (!isPlainObject(v)) {\n      throw new Error(`fromMachineJSON: ${where} must be a string or object, got ${typeof v}`);\n    }\n    if (typeof v.$unserializable === 'string') {\n      return [{ guard: markerLabel(v as unknown as MachineJSONUnserializable) }];\n    }\n\n    const transition = v as unknown as MachineJSONTransition;\n    const target: unknown = transition.target;\n    let targets: readonly (string | undefined)[];\n    if (target === undefined) {\n      targets = [undefined];\n    } else if (typeof target === 'string') {\n      targets = [target];\n    } else if (Array.isArray(target) && target.every((candidate) => typeof candidate === 'string')) {\n      targets = target;\n    } else {\n      throw new Error(`fromMachineJSON: ${where}.target must be a string or string array`);\n    }\n    const guard = transition.guard === undefined ? undefined : guardLabel(transition.guard, where);\n    const actions = actionLabels(transition.actions);\n    return targets.map((candidate) => ({\n      ...(candidate !== undefined ? { target: candidate } : {}),\n      ...(guard !== undefined ? { guard } : {}),\n      ...(actions !== undefined ? { actions } : {}),\n    }));\n  };\n\n  if (Array.isArray(value)) return value.flatMap(one);\n  return one(value as MachineJSONSingleValue);\n}\n\nfunction initialTarget(value: MachineJSONInitial, where: string): string {\n  if (typeof value === 'string') return value;\n  requireObject(value, where);\n  if (typeof value.target !== 'string') {\n    throw new Error(`fromMachineJSON: ${where}.target must be a string`);\n  }\n  return value.target;\n}\n\n// =============================================================================\n// Ingestion\n// =============================================================================\n\n/** Label an `after` delay key readably: `after 500ms` / `after PT1M`. */\nfunction afterLabel(delayKey: string): string {\n  return /^\\d+$/.test(delayKey) ? `after ${delayKey}ms` : `after ${delayKey}`;\n}\n\n/**\n * Build a {@link StateMachine} from an XState v6 `MachineJSON`.\n *\n * @throws if the input is not a well-formed MachineJSON (malformed `initial`,\n *   non-object `states`, or a malformed transition target/guard).\n */\nexport function fromMachineJSON(\n  json: MachineJSON,\n  options?: FromMachineJSONOptions,\n): StateMachine {\n  requireObject(json, 'input');\n  const rootInitial = initialTarget(json.initial, '`initial`');\n  const states = json.states;\n  requireObject(states, '`states`');\n\n  const entries: {\n    readonly path: string;\n    readonly parentPath: string | undefined;\n    readonly node: MachineJSONStateNode;\n  }[] = [];\n  const idToPath = new Map<string, string>();\n\n  const collectStates = (\n    children: Record<string, MachineJSONStateNode>,\n    parentPath?: string,\n  ): void => {\n    for (const [key, node] of Object.entries(children)) {\n      requireObject(node, `state '${parentPath === undefined ? key : `${parentPath}.${key}`}'`);\n      const path = parentPath === undefined ? key : `${parentPath}.${key}`;\n      entries.push({ path, parentPath, node });\n      idToPath.set(path, path);\n      if (node.id !== undefined) {\n        if (typeof node.id !== 'string') {\n          throw new Error(`fromMachineJSON: state '${path}'.id must be a string`);\n        }\n        idToPath.set(node.id, path);\n      }\n      if (node.states !== undefined) {\n        requireObject(node.states, `state '${path}'.states`);\n        collectStates(node.states, path);\n      }\n    }\n  };\n  collectStates(states);\n\n  const declaredStates = entries.map(({ path }) => path);\n  const transitions: StateTransition[] = [];\n  const observedEvents: string[] = [];\n  const seenEvents = new Set<string>();\n\n  const resolveTarget = (\n    target: string,\n    from: string,\n    parentPath: string | undefined,\n  ): string => {\n    if (target.startsWith('#')) return idToPath.get(target.slice(1)) ?? target.slice(1);\n    if (target.startsWith('.')) return `${from}${target}`;\n    return parentPath === undefined ? target : `${parentPath}.${target}`;\n  };\n\n  const resolveInitialTarget = (target: string, from?: string): string => {\n    if (target.startsWith('#')) return idToPath.get(target.slice(1)) ?? target.slice(1);\n    if (from === undefined) return target.startsWith('.') ? target.slice(1) : target;\n    return `${from}.${target.startsWith('.') ? target.slice(1) : target}`;\n  };\n\n  // Emit one transition per normalized branch of a value, self-edging on a\n  // targetless (internal / automatic-without-target) transition.\n  const emit = (\n    from: string,\n    event: string,\n    value: MachineJSONValue,\n    where: string,\n    parentPath: string | undefined,\n    trigger?: 'always' | 'after' | 'done' | 'error',\n    invokeIndex?: number,\n  ): void => {\n    for (const norm of normalizeValue(value, where)) {\n      transitions.push({\n        from,\n        event,\n        to: norm.target === undefined ? from : resolveTarget(norm.target, from, parentPath),\n        ...(norm.guard !== undefined ? { guard: norm.guard } : {}),\n        ...(norm.actions !== undefined ? { actions: norm.actions } : {}),\n        ...(trigger !== undefined ? { trigger } : {}),\n        ...(invokeIndex !== undefined ? { invokeIndex } : {}),\n      });\n    }\n  };\n\n  const entryActions: Record<string, readonly string[]> = {};\n  const exitActions: Record<string, readonly string[]> = {};\n  const invokes: Record<string, readonly StateInvoke[]> = {};\n\n  for (const { path: from, parentPath, node } of entries) {\n    const entry = actionLabels(node.entry);\n    if (entry !== undefined) entryActions[from] = entry;\n    const exit = actionLabels(node.exit);\n    if (exit !== undefined) exitActions[from] = exit;\n\n    // Invoked effects: preserve every invoke and associate its completion\n    // transitions by index so the XState exporter can rebuild the array.\n    const invokeValues: readonly MachineJSONInvoke[] =\n      node.invoke === undefined\n        ? []\n        : Array.isArray(node.invoke)\n          ? node.invoke\n          : [node.invoke];\n    if (invokeValues.length > 0) {\n      const metadata: StateInvoke[] = [];\n      for (const [invokeIndex, invoke] of invokeValues.entries()) {\n        const where = `state '${from}'.invoke[${invokeIndex}]`;\n        requireObject(invoke, where);\n        if (invoke.id !== undefined && typeof invoke.id !== 'string') {\n          throw new Error(`fromMachineJSON: ${where}.id must be a string`);\n        }\n        metadata.push({\n          ...invokeSource(invoke.src, where),\n          ...(invoke.id !== undefined ? { id: invoke.id } : {}),\n        });\n        if (invoke.onDone !== undefined) {\n          emit(\n            from,\n            'onDone',\n            invoke.onDone,\n            `${where}.onDone`,\n            parentPath,\n            'done',\n            invokeIndex,\n          );\n        }\n        if (invoke.onError !== undefined) {\n          emit(\n            from,\n            'onError',\n            invoke.onError,\n            `${where}.onError`,\n            parentPath,\n            'error',\n            invokeIndex,\n          );\n        }\n      }\n      invokes[from] = metadata;\n    }\n    if (node.initial !== undefined) {\n      transitions.push({\n        from,\n        event: 'initial',\n        to: resolveInitialTarget(initialTarget(node.initial, `state '${from}'.initial`), from),\n        trigger: 'initial',\n      });\n    } else if (node.type === 'parallel' && node.states !== undefined) {\n      for (const child of Object.keys(node.states)) {\n        transitions.push({ from, event: 'initial', to: `${from}.${child}`, trigger: 'initial' });\n      }\n    }\n\n    const on = node.on;\n    if (on !== undefined) {\n      requireObject(on, `state '${from}'.on`);\n      for (const [event, value] of Object.entries(on)) {\n        if (!seenEvents.has(event)) {\n          seenEvents.add(event);\n          observedEvents.push(event);\n        }\n        emit(from, event, value, `state '${from}' event '${event}'`, parentPath);\n      }\n    }\n\n    // Eventless: fires automatically when the state is entered and its guard\n    // passes. A reachability edge, not an event.\n    if (node.always !== undefined) {\n      emit(from, 'always', node.always, `state '${from}'.always`, parentPath, 'always');\n    }\n\n    // Delayed: fires automatically after the given delay. Also reachability.\n    const after = node.after;\n    if (after !== undefined) {\n      requireObject(after, `state '${from}'.after`);\n      for (const [delayKey, value] of Object.entries(after)) {\n        emit(\n          from,\n          afterLabel(delayKey),\n          value,\n          `state '${from}'.after['${delayKey}']`,\n          parentPath,\n          'after',\n        );\n      }\n    }\n  }\n\n  const schemaEvents = json.schemas?.events;\n  if (schemaEvents !== undefined) {\n    requireObject(schemaEvents, '`schemas.events`');\n  }\n  const declaredEvents =\n    schemaEvents !== undefined && !('$unserializable' in schemaEvents)\n      ? Object.keys(schemaEvents)\n      : observedEvents;\n\n  return {\n    name: options?.name ?? json.id ?? 'machine',\n    source: 'machine-json',\n    initial: resolveInitialTarget(rootInitial),\n    // The full config state set (not just states appearing in transitions) so\n    // final/orphan states still render and are judged for reachability.\n    states: declaredStates,\n    transitions,\n    location: undefined,\n    declaredStates,\n    declaredEvents,\n    alphabetSource: 'config',\n    // Explicit finals only: a transitionless `{}` node is active, not final.\n    finalStates: entries\n      .filter(({ node }) => node.type === 'final')\n      .map(({ path }) => path),\n    ...(entries.some(({ node }) => node.type === 'parallel')\n      ? {\n          parallelStates: entries\n            .filter(({ node }) => node.type === 'parallel')\n            .map(({ path }) => path),\n        }\n      : {}),\n    ...(Object.keys(entryActions).length > 0 ? { entryActions } : {}),\n    ...(Object.keys(exitActions).length > 0 ? { exitActions } : {}),\n    ...(Object.keys(invokes).length > 0 ? { invokes } : {}),\n  };\n}\n","/**\n * State machine coverage / completeness analysis.\n *\n * Cross-checks a machine's extracted transitions against its declared alphabet\n * (the full set of states/events from its types — a tagged union or a\n * Schema-derived type). This turns the statechart from \"a drawing\" into\n * \"a verified machine\": it reports events nothing handles, states nothing\n * reaches, and symbols that drifted away from the declared types.\n */\n\nimport type { StateMachine } from './state-machine';\n\nexport type CoverageKind =\n  | 'unhandled-event'\n  | 'unreachable-state'\n  | 'undeclared-state'\n  | 'undeclared-event'\n  | 'dead-end-state';\n\nexport interface CoverageFinding {\n  readonly kind: CoverageKind;\n  readonly severity: 'warning' | 'info';\n  readonly symbol: string;\n  readonly message: string;\n}\n\nexport interface StateMachineCoverage {\n  readonly machine: string;\n  readonly file: string | undefined;\n  /** True when both declared alphabets were resolvable from the types. */\n  readonly alphabetKnown: boolean;\n  readonly alphabetSource: 'schema' | 'tagged-union' | 'config' | undefined;\n  readonly declaredStates: readonly string[];\n  readonly declaredEvents: readonly string[];\n  readonly usedStates: readonly string[];\n  readonly usedEvents: readonly string[];\n  /** Declared events that no transition uses. */\n  readonly unhandledEvents: readonly string[];\n  /** States not reachable from the initial state (and not the initial itself). */\n  readonly unreachableStates: readonly string[];\n  /** Used states/events absent from the declared alphabet (drift / typo). */\n  readonly undeclaredStates: readonly string[];\n  readonly undeclaredEvents: readonly string[];\n  /** Reachable states with no outgoing transition (treated as final). */\n  readonly deadEndStates: readonly string[];\n  readonly handledPairs: number;\n  readonly totalPairs: number;\n  /** handledPairs / totalPairs in [0,1]; 1 when there is nothing to cover. */\n  readonly coverageRatio: number;\n  readonly findings: readonly CoverageFinding[];\n}\n\nfunction unique(xs: Iterable<string>): string[] {\n  const seen = new Set<string>();\n  const out: string[] = [];\n  for (const x of xs) {\n    if (!seen.has(x)) {\n      seen.add(x);\n      out.push(x);\n    }\n  }\n  return out;\n}\n\n/** States reachable from `initial` by following transitions. */\nfunction reachableFrom(\n  initial: string | undefined,\n  adjacency: Map<string, Set<string>>,\n): Set<string> {\n  const reachable = new Set<string>();\n  if (!initial) return reachable;\n  const queue = [initial];\n  reachable.add(initial);\n  let head = 0;\n  while (head < queue.length) {\n    const u = queue[head++];\n    if (u === undefined) continue;\n    for (const v of adjacency.get(u) ?? []) {\n      if (!reachable.has(v)) {\n        reachable.add(v);\n        queue.push(v);\n      }\n    }\n  }\n  return reachable;\n}\n\nexport function computeStateMachineCoverage(\n  machine: StateMachine,\n): StateMachineCoverage {\n  const usedStates = machine.states;\n  // Event-coverage is about transitions a user event triggers; automatic\n  // (`initial`/`always`/`after`) transitions are reachability edges only.\n  const eventTransitions = machine.transitions.filter(\n    (t) => t.trigger === undefined,\n  );\n  const usedEvents = unique(eventTransitions.map((t) => t.event));\n\n  const alphabetKnown =\n    machine.declaredStates !== undefined && machine.declaredEvents !== undefined;\n  // Fall back to observed symbols when the alphabet couldn't be resolved.\n  const declaredStates = machine.declaredStates ?? usedStates;\n  const declaredEvents = machine.declaredEvents ?? usedEvents;\n  const stateSet = new Set(declaredStates);\n  const eventSet = new Set(declaredEvents);\n\n  // Reachability follows every edge (event + automatic). Outgoing bookkeeping\n  // is split: `hasAnyOutgoing` for dead-end detection (a state that\n  // auto-advances is not a dead end); `hasEventOutgoing` for coverage (only\n  // states that handle events contribute (state,event) pairs).\n  const adjacency = new Map<string, Set<string>>();\n  const hasAnyOutgoing = new Set<string>();\n  const hasEventOutgoing = new Set<string>();\n  for (const t of machine.transitions) {\n    hasAnyOutgoing.add(t.from);\n    if (t.trigger === undefined) hasEventOutgoing.add(t.from);\n    const set = adjacency.get(t.from) ?? new Set<string>();\n    set.add(t.to);\n    adjacency.set(t.from, set);\n  }\n  const reachable = reachableFrom(machine.initial, adjacency);\n\n  // The universe of states to judge reachability against: declared ∪ used.\n  const allStates = unique([...declaredStates, ...usedStates]);\n\n  const unhandledEvents = alphabetKnown\n    ? declaredEvents.filter((e) => !usedEvents.includes(e))\n    : [];\n  const unreachableStates = allStates.filter(\n    (s) => s !== machine.initial && !reachable.has(s),\n  );\n  const undeclaredStates = alphabetKnown\n    ? usedStates.filter((s) => !stateSet.has(s))\n    : [];\n  const undeclaredEvents = alphabetKnown\n    ? usedEvents.filter((e) => !eventSet.has(e))\n    : [];\n  // A dead end has no outgoing edge of any kind (no event, no auto-advance).\n  // States explicitly marked final are intentional, not dead ends.\n  const explicitFinals = new Set(machine.finalStates ?? []);\n  const deadEndStates = [...reachable].filter(\n    (s) => !hasAnyOutgoing.has(s) && !explicitFinals.has(s),\n  );\n\n  // Coverage = handled (state,event) pairs over reachable states that actually\n  // handle events. States whose only exit is automatic expect no events.\n  const activeStates = [...reachable].filter((s) => hasEventOutgoing.has(s));\n  const handledPerState = new Map<string, Set<string>>();\n  for (const t of eventTransitions) {\n    const set = handledPerState.get(t.from) ?? new Set<string>();\n    set.add(t.event);\n    handledPerState.set(t.from, set);\n  }\n  const totalPairs = activeStates.length * declaredEvents.length;\n  let handledPairs = 0;\n  for (const s of activeStates) {\n    const handled = handledPerState.get(s);\n    if (!handled) continue;\n    for (const e of declaredEvents) if (handled.has(e)) handledPairs++;\n  }\n  const coverageRatio = totalPairs === 0 ? 1 : handledPairs / totalPairs;\n\n  const findings: CoverageFinding[] = [];\n  for (const e of unhandledEvents) {\n    findings.push({\n      kind: 'unhandled-event',\n      severity: 'warning',\n      symbol: e,\n      message: `Event \"${e}\" is declared but no state handles it.`,\n    });\n  }\n  for (const s of unreachableStates) {\n    findings.push({\n      kind: 'unreachable-state',\n      severity: 'warning',\n      symbol: s,\n      message: `State \"${s}\" is not reachable from the initial state.`,\n    });\n  }\n  for (const s of undeclaredStates) {\n    findings.push({\n      kind: 'undeclared-state',\n      severity: 'warning',\n      symbol: s,\n      message: `State \"${s}\" is used in a transition but not in the declared states.`,\n    });\n  }\n  for (const e of undeclaredEvents) {\n    findings.push({\n      kind: 'undeclared-event',\n      severity: 'warning',\n      symbol: e,\n      message: `Event \"${e}\" is used in a transition but not in the declared events.`,\n    });\n  }\n  for (const s of deadEndStates) {\n    findings.push({\n      kind: 'dead-end-state',\n      severity: 'info',\n      symbol: s,\n      message: `State \"${s}\" has no outgoing transitions (treated as final).`,\n    });\n  }\n\n  return {\n    machine: machine.name,\n    file: machine.location?.filePath,\n    alphabetKnown,\n    alphabetSource: machine.alphabetSource,\n    declaredStates,\n    declaredEvents,\n    usedStates,\n    usedEvents,\n    unhandledEvents,\n    unreachableStates,\n    undeclaredStates,\n    undeclaredEvents,\n    deadEndStates,\n    handledPairs,\n    totalPairs,\n    coverageRatio,\n    findings,\n  };\n}\n","/**\n * Mermaid `stateDiagram-v2` renderer for plain-Effect state machines.\n *\n * Turns the (from, event, to) triples extracted by `analyzeStateMachines`\n * into an XState-style statechart: states are nodes, events label the edges.\n *\n * When a `StateMachineCoverage` is supplied, the diagram is annotated:\n * unreachable states (including declared-but-orphaned ones) are highlighted,\n * and unhandled events are listed in a note.\n */\n\nimport { finalStatesOf } from '../state-machine';\nimport type { StateMachine, StateMachineAnalysis } from '../state-machine';\nimport type { StateMachineCoverage } from '../state-machine-coverage';\n\n/** Mermaid state ids must be identifier-safe; remember the display label. */\nfunction sanitizeId(text: string): string {\n  const id = text.replace(/[^a-zA-Z0-9_]/g, '_');\n  return /^[0-9]/.test(id) ? `s_${id}` : id;\n}\n\nfunction escapeLabel(text: string): string {\n  return text.replace(/\"/g, '#quot;');\n}\n\n/** Render a single state machine as a `stateDiagram-v2`. */\nexport function renderStatechartMermaid(\n  machine: StateMachine,\n  coverage?: StateMachineCoverage,\n): string {\n  const lines: string[] = ['stateDiagram-v2'];\n  lines.push(`  %% ${machine.name} (${machine.source})`);\n\n  const usedStates = new Set(machine.states);\n  // Unreachable states that actually appear in a transition can be styled\n  // inline; fully-orphaned declared states (no edges) are surfaced in a note,\n  // since mermaid's layout drops disconnected nodes.\n  const unreachableUsed = (coverage?.unreachableStates ?? []).filter((s) =>\n    usedStates.has(s),\n  );\n  const orphanStates = (coverage?.unreachableStates ?? []).filter(\n    (s) => !usedStates.has(s),\n  );\n  const undeclared = new Set(coverage?.undeclaredStates ?? []);\n\n  const idOf = (s: string): string => sanitizeId(s);\n\n  // Hierarchy: a dotted state name ('Playing.Paused') nests under its parent\n  // segments, which become composite states. Flat machines have no dots and\n  // render exactly as before.\n  const childrenOf = new Map<string, string[]>(); // parent path ('' = root) → child paths\n  const known = new Set<string>();\n  for (const state of machine.states) {\n    let path = '';\n    for (const seg of state.split('.')) {\n      const parent = path;\n      path = path === '' ? seg : `${path}.${seg}`;\n      if (known.has(path)) continue;\n      known.add(path);\n      childrenOf.set(parent, [...(childrenOf.get(parent) ?? []), path]);\n    }\n  }\n\n  // Compound-initial edges (trigger 'initial') render as [*] markers inside\n  // their parent's block, not as labeled edges.\n  const initialsOf = new Map<string, string[]>();\n  for (const t of machine.transitions) {\n    if (t.trigger !== 'initial') continue;\n    initialsOf.set(t.from, [...(initialsOf.get(t.from) ?? []), t.to]);\n  }\n\n  const emitState = (path: string, indent: string): void => {\n    const id = idOf(path);\n    const kids = childrenOf.get(path) ?? [];\n    const label = path.includes('.') ? (path.split('.').pop() ?? path) : path;\n    if (kids.length === 0) {\n      if (id !== path || label !== path) {\n        lines.push(`${indent}state \"${escapeLabel(label)}\" as ${id}`);\n      }\n      return;\n    }\n    lines.push(\n      id === label\n        ? `${indent}state ${id} {`\n        : `${indent}state \"${escapeLabel(label)}\" as ${id} {`,\n    );\n    for (const to of initialsOf.get(path) ?? []) {\n      lines.push(`${indent}  [*] --> ${idOf(to)}`);\n    }\n    for (const kid of kids) emitState(kid, `${indent}  `);\n    lines.push(`${indent}}`);\n  };\n  for (const top of childrenOf.get('') ?? []) emitState(top, '  ');\n\n  if (machine.initial) {\n    lines.push(`  [*] --> ${idOf(machine.initial)}`);\n  }\n\n  // Entry/exit action and invoke labels as state description lines.\n  for (const state of machine.states) {\n    const entry = machine.entryActions?.[state];\n    const exit = machine.exitActions?.[state];\n    const invokes = machine.invokes?.[state];\n    if (entry) lines.push(`  ${idOf(state)} : entry / ${escapeLabel(entry.join(', '))}`);\n    if (exit) lines.push(`  ${idOf(state)} : exit / ${escapeLabel(exit.join(', '))}`);\n    for (const invoke of invokes ?? []) {\n      const label = invoke.id === undefined\n        ? invoke.src\n        : `${invoke.src} (${invoke.id})`;\n      lines.push(`  ${idOf(state)} : invoke ${escapeLabel(label)}`);\n    }\n  }\n\n  for (const t of machine.transitions) {\n    if (t.trigger === 'initial' && (childrenOf.get(t.from)?.length ?? 0) > 0) {\n      continue; // rendered as a [*] marker inside the parent block\n    }\n    let label = escapeLabel(t.event);\n    if (t.guard) label += ` [${escapeLabel(t.guard)}]`;\n    if (t.actions && t.actions.length > 0) {\n      label += ` / ${escapeLabel(t.actions.join(', '))}`;\n    }\n    lines.push(`  ${idOf(t.from)} --> ${idOf(t.to)}: ${label}`);\n  }\n\n  const finals = finalStatesOf(machine);\n  for (const state of machine.states) {\n    if (finals.has(state)) {\n      lines.push(`  ${idOf(state)} --> [*]`);\n    }\n  }\n\n  if (coverage) {\n    if (unreachableUsed.length > 0 || undeclared.size > 0) {\n      lines.push('  classDef unreachable fill:#5b1a1a,stroke:#e53e3e,color:#fff');\n      lines.push('  classDef undeclared fill:#5b431a,stroke:#dd6b20,color:#fff');\n      for (const s of unreachableUsed) lines.push(`  class ${idOf(s)} unreachable`);\n      for (const s of undeclared) lines.push(`  class ${idOf(s)} undeclared`);\n    }\n    const noteParts: string[] = [];\n    if (coverage.unhandledEvents.length > 0) {\n      noteParts.push(`Unhandled events: ${coverage.unhandledEvents.join(', ')}`);\n    }\n    if (orphanStates.length > 0) {\n      noteParts.push(`Unreachable states: ${orphanStates.join(', ')}`);\n    }\n    if (noteParts.length > 0 && machine.initial) {\n      lines.push(`  note right of ${idOf(machine.initial)}`);\n      for (const part of noteParts) lines.push(`    ${part}`);\n      lines.push('  end note');\n    }\n  }\n\n  return lines.join('\\n');\n}\n\n/** Render every machine found in a file, one diagram each. */\nexport function renderStatechartsMermaid(\n  analysis: StateMachineAnalysis,\n  coverages?: readonly StateMachineCoverage[],\n): string {\n  if (analysis.machines.length === 0) {\n    return 'stateDiagram-v2\\n  %% No state machines detected';\n  }\n  const byName = new Map(coverages?.map((c) => [c.machine, c]));\n  return analysis.machines\n    .map((m) => renderStatechartMermaid(m, byName.get(m.name)))\n    .join('\\n\\n');\n}\n","/**\n * XState config emitter.\n *\n * Turns an extracted plain-Effect state machine into an XState v5/v6\n * `createMachine({...})` config. The point: you write deterministic\n * Effect code (no XState), and this gives you a config you can paste\n * straight into the Stately visualizer (stately.ai/viz) to get the real\n * interactive statechart — for free.\n *\n * Dotted state names ('Playing.Paused') emit nested `states`, automatic\n * transitions emit `always` / `after` keys, and hierarchical machines use\n * absolute `#id.path` targets so cross-level transitions resolve.\n */\n\nimport { finalStatesOf } from '../state-machine';\nimport type { StateMachine, StateTransition } from '../state-machine';\n\n/** A single-quoted string literal, escaping backslashes and apostrophes. */\nconst str = (value: string): string =>\n  `'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`;\n\n/** A safe JS identifier stays bare; anything else becomes a quoted string. */\nfunction key(name: string): string {\n  return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : str(name);\n}\n\n/** Turn a display name or machine id into a valid generated binding name. */\nfunction identifier(name: string): string {\n  const sanitized = name.replace(/[^A-Za-z0-9_$]/g, '_');\n  const prefixed = /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;\n  return prefixed === '' ? 'Machine' : prefixed;\n}\n\ninterface Target {\n  readonly to: string;\n  readonly guard?: string;\n  readonly actions?: readonly string[];\n}\n\nfunction sameActions(\n  left: readonly string[] | undefined,\n  right: readonly string[] | undefined,\n): boolean {\n  if (left === undefined || right === undefined) return left === right;\n  return left.length === right.length && left.every((value, i) => value === right[i]);\n}\n\nfunction dedupe(ts: readonly StateTransition[]): Target[] {\n  const out: Target[] = [];\n  for (const t of ts) {\n    if (\n      !out.some(\n        (x) => x.to === t.to && x.guard === t.guard && sameActions(x.actions, t.actions),\n      )\n    ) {\n      out.push({\n        to: t.to,\n        ...(t.guard !== undefined ? { guard: t.guard } : {}),\n        ...(t.actions !== undefined ? { actions: t.actions } : {}),\n      });\n    }\n  }\n  return out;\n}\n\nexport function renderXStateConfig(machine: StateMachine): string {\n  const finals = finalStatesOf(machine);\n  const hierarchical = machine.states.some((s) => s.includes('.'));\n  const ref = (to: string): string =>\n    hierarchical ? str(`#${machine.name}.${to}`) : str(to);\n  const strList = (xs: readonly string[]): string => `[${xs.map(str).join(', ')}]`;\n  const transitionObj = (x: Target): string => {\n    const fields = [`target: ${ref(x.to)}`];\n    if (x.guard !== undefined) fields.push(`guard: ${str(x.guard)}`);\n    if (x.actions !== undefined) fields.push(`actions: ${strList(x.actions)}`);\n    return `{ ${fields.join(', ')} }`;\n  };\n  /** String shorthand for a single bare target, else an array of objects. */\n  const targetValue = (targets: readonly Target[]): string => {\n    const first = targets[0];\n    return targets.length === 1 &&\n      first &&\n      first.guard === undefined &&\n      first.actions === undefined\n      ? ref(first.to)\n      : `[${targets.map(transitionObj).join(', ')}]`;\n  };\n\n  // Build the state tree: dotted names nest, ancestor segments are implied.\n  const childrenOf = new Map<string, string[]>(); // parent path ('' = root) → child paths\n  const known = new Set<string>();\n  for (const state of machine.states) {\n    let path = '';\n    for (const seg of state.split('.')) {\n      const parent = path;\n      path = path === '' ? seg : `${path}.${seg}`;\n      if (known.has(path)) continue;\n      known.add(path);\n      childrenOf.set(parent, [...(childrenOf.get(parent) ?? []), path]);\n    }\n  }\n\n  const byFrom = new Map<string, StateTransition[]>();\n  for (const path of known) byFrom.set(path, []);\n  const compoundInitial = new Map<string, string>(); // parent path → initial child path\n  for (const t of machine.transitions) {\n    if (t.trigger === 'initial') {\n      if (!compoundInitial.has(t.from)) compoundInitial.set(t.from, t.to);\n      continue;\n    }\n    byFrom.get(t.from)?.push(t);\n  }\n  // A dotted machine.initial implies the initial child at every level it passes.\n  if (machine.initial?.includes('.')) {\n    const segs = machine.initial.split('.');\n    let path = segs[0] ?? '';\n    for (const seg of segs.slice(1)) {\n      const child = `${path}.${seg}`;\n      if (!compoundInitial.has(path)) compoundInitial.set(path, child);\n      path = child;\n    }\n  }\n  /** Direct child key on the way from `path` to the full path `target`. */\n  const childKeyToward = (path: string, target: string): string | undefined =>\n    target.startsWith(`${path}.`)\n      ? target.slice(path.length + 1).split('.')[0]\n      : undefined;\n\n  const parallel = new Set(machine.parallelStates ?? []);\n\n  const renderNode = (path: string, indent: string): string => {\n    const label = path.includes('.') ? (path.split('.').pop() ?? path) : path;\n    const kids = childrenOf.get(path) ?? [];\n    const outs = byFrom.get(path) ?? [];\n    const events = outs.filter((t) => t.trigger === undefined);\n    const always = outs.filter((t) => t.trigger === 'always');\n    const afters = outs.filter((t) => t.trigger === 'after');\n    const dones = outs.filter((t) => t.trigger === 'done');\n    const errors = outs.filter((t) => t.trigger === 'error');\n    const parts: string[] = [];\n\n    const entry = machine.entryActions?.[path];\n    if (entry) parts.push(`entry: ${strList(entry)}`);\n    const exit = machine.exitActions?.[path];\n    if (exit) parts.push(`exit: ${strList(exit)}`);\n    const invokes = machine.invokes?.[path] ?? [];\n    if (invokes.length > 0) {\n      const configs = invokes.map((invoke, invokeIndex) => {\n        const belongsToInvoke = (t: StateTransition): boolean =>\n          t.invokeIndex === invokeIndex ||\n          (t.invokeIndex === undefined && invokes.length === 1);\n        const invokeDones = dones.filter(belongsToInvoke);\n        const invokeErrors = errors.filter(belongsToInvoke);\n        const fields = [`src: ${str(invoke.src)}`];\n        if (invoke.id !== undefined) fields.push(`id: ${str(invoke.id)}`);\n        if (invokeDones.length > 0) {\n          fields.push(`onDone: ${targetValue(dedupe(invokeDones))}`);\n        }\n        if (invokeErrors.length > 0) {\n          fields.push(`onError: ${targetValue(dedupe(invokeErrors))}`);\n        }\n        return `{ ${fields.join(', ')} }`;\n      });\n      parts.push(\n        invokes.length === 1\n          ? `invoke: ${configs[0]}`\n          : `invoke: [${configs.join(', ')}]`,\n      );\n    }\n\n    if (events.length > 0) {\n      const byEvent = new Map<string, StateTransition[]>();\n      for (const t of events) {\n        byEvent.set(t.event, [...(byEvent.get(t.event) ?? []), t]);\n      }\n      const on = [...byEvent]\n        .map(([event, ts]) => `${key(event)}: ${targetValue(dedupe(ts))}`)\n        .join(', ');\n      parts.push(`on: { ${on} }`);\n    }\n    if (always.length > 0) {\n      parts.push(`always: ${targetValue(dedupe(always))}`);\n    }\n    if (afters.length > 0) {\n      // Event labels are `after 5000ms` / `after PT1M`; the delay becomes the key.\n      const byDelay = new Map<string, StateTransition[]>();\n      for (const t of afters) {\n        const raw = t.event.replace(/^after\\s+/, '');\n        const ms = /^(\\d+)ms$/.exec(raw)?.[1] ?? (/^\\d+$/.test(raw) ? raw : undefined);\n        const delay = ms ?? raw;\n        byDelay.set(delay, [...(byDelay.get(delay) ?? []), t]);\n      }\n      const after = [...byDelay]\n        .map(([delay, ts]) => `${key(delay)}: ${targetValue(dedupe(ts))}`)\n        .join(', ');\n      parts.push(`after: { ${after} }`);\n    }\n    if (kids.length > 0) {\n      if (parallel.has(path)) {\n        // Every region is entered; parallel nodes carry no initial.\n        parts.push(`type: 'parallel'`);\n      } else {\n        const target = compoundInitial.get(path);\n        const initKey =\n          (target !== undefined ? childKeyToward(path, target) : undefined) ??\n          childKeyToward(path, kids[0] ?? '') ??\n          (kids[0] ?? '').split('.').pop() ??\n          '';\n        parts.push(`initial: ${str(initKey)}`);\n      }\n      const inner = kids.map((kid) => renderNode(kid, `${indent}    `)).join(',\\n');\n      parts.push(`states: {\\n${inner}\\n${indent}  }`);\n      return `${indent}${key(label)}: {\\n${parts.map((p) => `${indent}  ${p}`).join(',\\n')}\\n${indent}}`;\n    }\n    if (finals.has(path)) parts.push(`type: 'final'`);\n    if (parts.length === 0) return `${indent}${key(label)}: {}`;\n    return `${indent}${key(label)}: { ${parts.join(', ')} }`;\n  };\n\n  const stateLines = (childrenOf.get('') ?? []).map((top) => renderNode(top, '    '));\n\n  const lines = [\n    \"import { createMachine } from 'xstate';\",\n    '',\n    `export const ${identifier(machine.name)}Machine = createMachine({`,\n    `  id: ${str(machine.name)},`,\n  ];\n  if (machine.initial) {\n    const rootInitial = hierarchical\n      ? (machine.initial.split('.')[0] ?? machine.initial)\n      : machine.initial;\n    lines.push(`  initial: ${str(rootInitial)},`);\n  }\n  lines.push('  states: {');\n  lines.push(stateLines.join(',\\n'));\n  lines.push('  }');\n  lines.push('});');\n  return lines.join('\\n');\n}\n","/**\n * Self-contained SVG statechart renderer, styled after the XState/Stately\n * visualizer: dark canvas, a machine-container box, an initial-state dot,\n * blue event \"pills\" on the edges, and a final-state marker.\n *\n * No external tooling — emits a standalone <svg> (optionally wrapped in HTML).\n * Layout is a layered left-to-right BFS from the initial state. Edges leaving\n * a hub fan out to separate lanes so their pills never overlap a node.\n */\n\nimport { finalStatesOf } from '../state-machine';\nimport type { StateMachine } from '../state-machine';\nimport type { StateMachineCoverage } from '../state-machine-coverage';\n\ninterface Box {\n  readonly state: string;\n  readonly layer: number;\n  readonly x: number;\n  readonly y: number;\n  readonly w: number;\n  readonly h: number;\n}\n\nconst C = {\n  bg: '#16191f',\n  container: '#3a414d',\n  title: '#e2e8f0',\n  node: '#222831',\n  nodeStroke: '#4a5568',\n  initStroke: '#4299e1',\n  text: '#e2e8f0',\n  edge: '#8a93a2',\n  pill: '#2b6cb0',\n  pillText: '#ffffff',\n  dot: '#cbd5e0',\n  unreachable: '#e53e3e',\n  undeclared: '#dd6b20',\n  warnText: '#feb2b2',\n} as const;\n\nconst NODE_H = 44;\nconst V_GAP = 30;\nconst MARGIN_X = 84;\nconst MARGIN_TOP = 58;\nconst MARGIN_BOTTOM = 70;\n\nfunction esc(text: string): string {\n  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\nconst nodeWidth = (label: string): number =>\n  Math.max(76, Math.round(label.length * 7.6) + 30);\n\nconst pillWidth = (label: string): number => label.length * 6.6 + 18;\n\n/** Event label, with a (truncated) guard condition appended when present. */\nconst eventLabel = (event: string, guard?: string): string => {\n  if (!guard) return event;\n  const g = guard.length > 18 ? `${guard.slice(0, 17)}…` : guard;\n  return `${event} [${g}]`;\n};\n\nfunction assignLayers(\n  machine: StateMachine,\n  states: readonly string[],\n): Map<string, number> {\n  const layer = new Map<string, number>();\n  const adj = new Map<string, string[]>();\n  for (const s of states) adj.set(s, []);\n  for (const t of machine.transitions) adj.get(t.from)?.push(t.to);\n\n  const init = machine.initial ?? states[0];\n  const queue: string[] = [];\n  if (init) {\n    layer.set(init, 0);\n    queue.push(init);\n  }\n  let head = 0;\n  while (head < queue.length) {\n    const u = queue[head++];\n    if (u === undefined) continue;\n    const lu = layer.get(u) ?? 0;\n    for (const v of adj.get(u) ?? []) {\n      if (!layer.has(v)) {\n        layer.set(v, lu + 1);\n        queue.push(v);\n      }\n    }\n  }\n  let maxLayer = 0;\n  for (const l of layer.values()) maxLayer = Math.max(maxLayer, l);\n  for (const s of states) {\n    if (!layer.has(s)) layer.set(s, ++maxLayer);\n  }\n  return layer;\n}\n\nfunction pill(cx: number, cy: number, label: string): string {\n  const w = pillWidth(label);\n  const h = 19;\n  return (\n    `<rect x=\"${(cx - w / 2).toFixed(1)}\" y=\"${(cy - h / 2).toFixed(1)}\" width=\"${w.toFixed(1)}\" height=\"${h}\" rx=\"9.5\" fill=\"${C.pill}\"/>` +\n    `<text x=\"${cx.toFixed(1)}\" y=\"${(cy + 4).toFixed(1)}\" text-anchor=\"middle\" font-size=\"11\" font-weight=\"600\" fill=\"${C.pillText}\">${esc(label)}</text>`\n  );\n}\n\nexport function renderStatechartSVG(\n  machine: StateMachine,\n  coverage?: StateMachineCoverage,\n): string {\n  const unreachableSet = new Set(coverage?.unreachableStates ?? []);\n  const undeclaredSet = new Set(coverage?.undeclaredStates ?? []);\n  // Include declared-but-orphaned states so coverage gaps are visible.\n  const states = [\n    ...machine.states,\n    ...(coverage?.unreachableStates ?? []).filter(\n      (s) => !machine.states.includes(s),\n    ),\n  ];\n\n  const layer = assignLayers(machine, states);\n  let maxLayer = 0;\n  for (const l of layer.values()) maxLayer = Math.max(maxLayer, l);\n\n  const byLayer: string[][] = Array.from({ length: maxLayer + 1 }, () => []);\n  for (const s of states) byLayer[layer.get(s) ?? 0]?.push(s);\n\n  // Horizontal gap must fit the widest event pill plus routing slack.\n  const widestPill = Math.max(\n    40,\n    ...machine.transitions.map((t) => pillWidth(eventLabel(t.event, t.guard))),\n  );\n  const hGap = Math.round(widestPill + 56);\n\n  const colW = byLayer.map((states) => Math.max(76, ...states.map(nodeWidth)));\n  const colX: number[] = [];\n  let cx = MARGIN_X;\n  for (let i = 0; i <= maxLayer; i++) {\n    colX[i] = cx;\n    cx += (colW[i] ?? 76) + hGap;\n  }\n\n  const boxes = new Map<string, Box>();\n  for (let l = 0; l <= maxLayer; l++) {\n    (byLayer[l] ?? []).forEach((s, idx) => {\n      const w = nodeWidth(s);\n      const x = (colX[l] ?? MARGIN_X) + ((colW[l] ?? 76) - w) / 2;\n      const y = MARGIN_TOP + idx * (NODE_H + V_GAP);\n      boxes.set(s, { state: s, layer: l, x, y, w, h: NODE_H });\n    });\n  }\n\n  const maxRows = Math.max(1, ...byLayer.map((s) => s.length));\n  const contentW = (colX[maxLayer] ?? MARGIN_X) + (colW[maxLayer] ?? 76) + MARGIN_X;\n  const contentH =\n    MARGIN_TOP + maxRows * (NODE_H + V_GAP) - V_GAP + MARGIN_BOTTOM;\n  const dipY = contentH - 32;\n\n  const finals = finalStatesOf(machine);\n  const edges: string[] = [];\n  const pills: string[] = [];\n\n  // Forward edges fan out by source so lanes/pills don't collide.\n  const forwardBySource = new Map<\n    string,\n    { event: string; to: string; guard: string | undefined }[]\n  >();\n  const otherEdges: {\n    from: string;\n    event: string;\n    to: string;\n    guard: string | undefined;\n  }[] = [];\n  for (const t of machine.transitions) {\n    const from = boxes.get(t.from);\n    const to = boxes.get(t.to);\n    if (!from || !to) continue;\n    if (to.layer > from.layer) {\n      const arr = forwardBySource.get(t.from) ?? [];\n      arr.push({ event: t.event, to: t.to, guard: t.guard });\n      forwardBySource.set(t.from, arr);\n    } else {\n      otherEdges.push({ from: t.from, event: t.event, to: t.to, guard: t.guard });\n    }\n  }\n\n  for (const [fromState, outs] of forwardBySource) {\n    const from = boxes.get(fromState);\n    if (!from) continue;\n    const sx = from.x + from.w;\n    const scy = from.y + from.h / 2;\n    const k = outs.length;\n    // sort by target vertical position for tidy fan\n    outs.sort(\n      (a, b) => (boxes.get(a.to)?.y ?? 0) - (boxes.get(b.to)?.y ?? 0),\n    );\n    outs.forEach((o, i) => {\n      const to = boxes.get(o.to);\n      if (!to) return;\n      const label = eventLabel(o.event, o.guard);\n      const exitY = scy + (i - (k - 1) / 2) * 19;\n      const pillW = pillWidth(label);\n      const pillCx = sx + pillW / 2 + 16;\n      const bendX = sx + widestPill + 30 + i * 8; // staggered vertical lane\n      const tx = to.x;\n      const ty = to.y + to.h / 2;\n      edges.push(\n        `<path d=\"M ${sx} ${scy} L ${(sx + 10).toFixed(1)} ${exitY.toFixed(1)} ` +\n          `L ${bendX.toFixed(1)} ${exitY.toFixed(1)} L ${bendX.toFixed(1)} ${ty} L ${tx} ${ty}\" ` +\n          `fill=\"none\" stroke=\"${C.edge}\" stroke-width=\"1.5\" marker-end=\"url(#arrow)\"/>`,\n      );\n      pills.push(pill(pillCx, exitY, label));\n    });\n  }\n\n  // Edges that don't go to a later layer: route downward ones on the right\n  // side (own lane each) and true back-edges under the diagram.\n  let rightLane = 0;\n  let backLane = 0;\n  for (const o of otherEdges) {\n    const from = boxes.get(o.from);\n    const to = boxes.get(o.to);\n    if (!from || !to) continue;\n    if (to.y > from.y) {\n      // downward (often same column): hug the right side in its own lane\n      const sx = from.x + from.w;\n      const sy = from.y + from.h / 2;\n      const tx = to.x + to.w;\n      const ty = to.y + to.h / 2;\n      const laneX = Math.max(sx, tx) + 22 + rightLane * 20;\n      rightLane++;\n      edges.push(\n        `<path d=\"M ${sx} ${sy} L ${laneX.toFixed(1)} ${sy} L ${laneX.toFixed(1)} ${ty} L ${tx} ${ty}\" ` +\n          `fill=\"none\" stroke=\"${C.edge}\" stroke-width=\"1.5\" marker-end=\"url(#arrow)\"/>`,\n      );\n      pills.push(pill(laneX, (sy + ty) / 2, eventLabel(o.event, o.guard)));\n    } else {\n      // back-edge: route under the diagram\n      const sx = from.x + from.w / 2;\n      const sy = from.y + from.h;\n      const tx = to.x + to.w / 2;\n      const ty = to.y + to.h;\n      const lane = dipY - backLane * 18;\n      backLane++;\n      edges.push(\n        `<path d=\"M ${sx} ${sy} L ${sx} ${lane} L ${tx} ${lane} L ${tx} ${ty}\" ` +\n          `fill=\"none\" stroke=\"${C.edge}\" stroke-width=\"1.5\" stroke-dasharray=\"4 3\" marker-end=\"url(#arrow)\"/>`,\n      );\n      pills.push(pill((sx + tx) / 2, lane, eventLabel(o.event, o.guard)));\n    }\n  }\n\n  const nodes: string[] = [];\n  for (const box of boxes.values()) {\n    const isInitial = box.state === machine.initial;\n    const isFinal = finals.has(box.state);\n    const isUnreachable = unreachableSet.has(box.state);\n    const isUndeclared = undeclaredSet.has(box.state);\n    const stroke = isUnreachable\n      ? C.unreachable\n      : isUndeclared\n        ? C.undeclared\n        : isInitial\n          ? C.initStroke\n          : C.nodeStroke;\n    const sw = isInitial || isUnreachable || isUndeclared ? 2 : 1.4;\n    const dash = isUnreachable ? ' stroke-dasharray=\"5 3\"' : '';\n    nodes.push(\n      `<rect x=\"${box.x.toFixed(1)}\" y=\"${box.y}\" width=\"${box.w}\" height=\"${box.h}\" rx=\"8\" fill=\"${C.node}\" stroke=\"${stroke}\" stroke-width=\"${sw}\"${dash}/>`,\n    );\n    if (isFinal) {\n      nodes.push(\n        `<rect x=\"${(box.x + 4).toFixed(1)}\" y=\"${box.y + 4}\" width=\"${box.w - 8}\" height=\"${box.h - 8}\" rx=\"6\" fill=\"none\" stroke=\"${C.nodeStroke}\" stroke-width=\"1.2\"/>`,\n      );\n    }\n    nodes.push(\n      `<text x=\"${(box.x + box.w / 2).toFixed(1)}\" y=\"${(box.y + box.h / 2 + 4).toFixed(1)}\" text-anchor=\"middle\" font-size=\"13\" font-weight=\"600\" fill=\"${C.text}\">${esc(box.state)}</text>`,\n    );\n  }\n\n  let initialMarker = '';\n  const initBox = machine.initial ? boxes.get(machine.initial) : undefined;\n  if (initBox) {\n    const cyN = initBox.y + initBox.h / 2;\n    const dotX = initBox.x - 30;\n    initialMarker =\n      `<circle cx=\"${dotX}\" cy=\"${cyN}\" r=\"6.5\" fill=\"${C.dot}\"/>` +\n      `<path d=\"M ${dotX + 7} ${cyN} L ${initBox.x} ${cyN}\" stroke=\"${C.edge}\" stroke-width=\"1.5\" marker-end=\"url(#arrow)\"/>`;\n  }\n\n  const unhandled = coverage?.unhandledEvents ?? [];\n  const footerH = unhandled.length > 0 ? 26 : 0;\n\n  const W = Math.round(contentW);\n  const boxH = Math.round(contentH);\n  const H = boxH + footerH;\n  const footer =\n    footerH > 0\n      ? `<text x=\"26\" y=\"${boxH + 16}\" font-size=\"12\" font-weight=\"600\" fill=\"${C.warnText}\">⚠ Unhandled events: ${esc(unhandled.join(', '))}</text>`\n      : '';\n  return [\n    `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${W}\" height=\"${H}\" viewBox=\"0 0 ${W} ${H}\" font-family=\"system-ui, sans-serif\">`,\n    `  <defs><marker id=\"arrow\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"${C.edge}\"/></marker></defs>`,\n    `  <rect x=\"0\" y=\"0\" width=\"${W}\" height=\"${H}\" fill=\"${C.bg}\"/>`,\n    `  <rect x=\"12\" y=\"26\" width=\"${W - 24}\" height=\"${boxH - 38}\" rx=\"10\" fill=\"none\" stroke=\"${C.container}\" stroke-width=\"1.5\"/>`,\n    `  <text x=\"26\" y=\"20\" font-size=\"13\" font-weight=\"700\" fill=\"${C.title}\">${esc(machine.name)}</text>`,\n    ...edges.map((e) => '  ' + e),\n    initialMarker ? '  ' + initialMarker : '',\n    ...nodes.map((n) => '  ' + n),\n    ...pills.map((p) => '  ' + p),\n    footer ? '  ' + footer : '',\n    '</svg>',\n  ]\n    .filter(Boolean)\n    .join('\\n');\n}\n\n/** Wrap one or more SVG diagrams in a minimal dark HTML page (for viewing). */\nexport function renderStatechartHTML(svgs: readonly string[]): string {\n  return [\n    '<!doctype html><html><head><meta charset=\"utf-8\">',\n    `<style>body{margin:0;background:${C.bg};display:flex;flex-direction:column;gap:24px;padding:24px;}</style>`,\n    '</head><body>',\n    ...svgs,\n    '</body></html>',\n  ].join('\\n');\n}\n"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,wBAAAE,GAAA,eAAAC,GAAA,aAAAC,GAAA,YAAAC,GAAA,sBAAAC,GAAA,wBAAAC,GAAA,qBAAAC,GAAA,4BAAAC,GAAA,yBAAAC,GAAA,mBAAAC,GAAA,yBAAAC,GAAA,yBAAAC,GAAA,uBAAAC,GAAA,qBAAAC,GAAA,yBAAAC,GAAA,gBAAAC,GAAA,qBAAAC,GAAA,qBAAAC,GAAA,uBAAAC,GAAA,wBAAAC,GAAA,4BAAAC,GAAA,eAAAC,GAAA,gCAAAC,GAAA,0BAAAC,GAAA,qBAAAC,GAAA,wBAAAC,GAAA,gBAAAC,GAAA,eAAAC,GAAA,cAAAC,GAAA,4BAAAC,GAAA,uBAAAC,GAAA,wBAAAC,GAAA,2BAAAC,GAAA,6BAAAC,GAAA,oBAAAC,GAAA,kBAAAC,GAAA,8BAAAC,GAAA,uBAAAC,GAAA,iBAAAC,GAAA,qBAAAC,GAAA,sBAAAC,GAAA,qBAAAC,GAAA,iBAAAC,GAAA,8BAAAC,GAAA,YAAAC,GAAA,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MACA,QACA,WACA,SACF,EAEaC,GAAmB,CAC9B,UACA,iBACA,2BACA,kBACA,QACA,SACA,cACF,EAMaC,GAAe,CAC1B,UACA,SACA,YACA,UACA,SACA,UACA,YACA,aACA,WACA,mBACA,SACA,SACA,WACA,kBACA,eACA,cACA,eACA,SACA,QACA,QACA,UACA,UACA,SACA,WACA,WACA,QACA,aACA,aACA,gBACA,QACA,SACA,SACA,UACA,UACA,SACA,eACA,SACA,SACA,cACA,SACA,eACA,eACA,wBACA,YACA,YACA,eACA,UACA,UACA,UACA,WACA,cACA,cACA,WACA,cACA,WACA,UACA,gBACA,UACA,YACA,iBACA,aACA,UACA,WACA,WACA,qBACA,SACA,YACA,aACA,YACA,QACA,cACA,YACA,YACA,eACA,WACA,QACA,UACA,QACA,WACA,WACA,aACA,eACA,WACA,cACA,WACA,UACA,UACA,iBACA,gBACA,YACA,YACA,UACA,aACA,aACA,eACA,eACA,WACA,OACA,WACA,aACA,WACF,EAEaC,GAAsB,IAAI,IAAI,CACzC,QAAS,gBAAiB,SAAU,SAAU,UAAW,SACzD,WAAY,UAAW,OAAQ,OAAQ,SAAU,QAAS,MAC1D,MAAO,UAAW,UAAW,SAAU,SAAU,OAAQ,UACzD,UAAW,SAAU,eAAgB,SAAU,WAAY,iBAC7D,CAAC,EAEYC,GAA0B,IAAI,IAAI,CAE7C,SAAU,QAAS,SAAU,QAAS,SAAU,WAAY,YAC5D,UAAW,kBAAmB,QAAS,QAAS,UAAW,iBAAkB,QAAS,OAEtF,OAAQ,SAAU,SAAU,QAAS,UAAW,UAAW,OAC3D,YAAa,YAEb,QAAS,SAAU,SAAU,WAAY,IAEzC,SAAU,SAAU,SAEpB,WAAY,cAAe,WAAY,WAEvC,QAAS,cAAe,cAAe,aAEvC,MAAO,kBAAmB,UAE1B,SAAU,QAAS,WAAY,WAAY,YAAa,QAAS,SACjE,SAAU,WAAY,QAAS,cAAe,QAAS,cACvD,QAAS,OAAQ,SAAU,QAAS,QAAS,WAE7C,OAA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,EAAQ,EAAI,GACzBD,EACE,eAAeG,CAAI,SAASD,CAAG,mBAAmB5F,GAAE,GAAG,iBACzC6F,EAAO,CAAC,IAAID,CAAG,MAAMD,EAAQ,CAAC,IAAIC,CAAG,aAAa5F,GAAE,IAAI,iDAC1E,CAEA,IAAM8F,EAAY1D,GAAU,iBAAmB,CAAC,EAC1C2D,EAAUD,EAAU,OAAS,EAAI,GAAK,EAEtCE,EAAI,KAAK,MAAM9C,CAAQ,EACvB+C,EAAO,KAAK,MAAM9C,CAAQ,EAC1B+C,EAAID,EAAOF,EACXI,EACJJ,EAAU,EACN,mBAAmBE,EAAO,EAAE,4CAA4CjG,GAAE,QAAQ,8BAAyBM,GAAIwF,EAAU,KAAK,IAAI,CAAC,CAAC,UACpI,GACN,MAAO,CACL,kDAAkDE,CAAC,aAAaE,CAAC,kBAAkBF,CAAC,IAAIE,CAAC,yCACzF,uKAAuKlG,GAAE,IAAI,sBAC7K,8BAA8BgG,CAAC,aAAaE,CAAC,WAAWlG,GAAE,EAAE,MAC5D,gCAAgCgG,EAAI,EAAE,aAAaC,EAAO,EAAE,iCAAiCjG,GAAE,SAAS,yBACxG,gEAAgEA,GAAE,KAAK,KAAKM,GAAIU,EAAQ,IAAI,CAAC,UAC7F,GAAGuC,EAAM,IAAK6C,GAAM,KAAOA,CAAC,EAC5BV,EAAgB,KAAOA,EAAgB,GACvC,GAAGT,EAAM,IAAKoB,GAAM,KAAOA,CAAC,EAC5B,GAAG7C,EAAM,IAAK8C,GAAM,KAAOA,CAAC,EAC5BH,EAAS,KAAOA,EAAS,GACzB,QACF,EACG,OAAO,OAAO,EACd,KAAK;AAAA,CAAI,CACd","names":["analysis_entry_exports","__export","DEFAULT_THRESHOLDS","layer_graph_exports","analysis","analyze","analyzeEffectFile","analyzeEffectSource","analyzeErrorFlow","analyzeErrorPropagation","analyzeObservability","analyzeProject","analyzeProjectCorpus","analyzeScopeResource","analyzeServiceFlow","analyzeStateFlow","analyzeStateMachines","assessAudit","assessComplexity","assessIRFidelity","buildDataFlowGraph","calculateComplexity","calculatePathStatistics","childrenOf","computeStateMachineCoverage","createAnalysisSession","errorDisposition","evaluateAuditPolicy","filterPaths","findCycles","flattenIR","formatComplexitySummary","formatErrorSummary","formatTestChecklist","formatTestMatrixAsCode","formatTestMatrixMarkdown","fromMachineJSON","generatePaths","generatePathsWithMetadata","generateTestMatrix","getConsumers","getDataFlowOrder","getErrorProducers","getErrorsAtPoint","getProducers","getTransitiveDependencies","indexIR","renderCoverageReport","renderDataFlowMermaid","renderErrorFlowMermaid","renderStatechartMermaid","renderStatechartSVG","renderStatechartsMermaid","renderXStateConfig","runCoverageAudit","runCoverageAuditFromCorpus","runtimeSpanName","runtimeSpanNames","scanProjectCorpus","spanPathKey","validateDataFlow","validateWorkflowErrors","visitIR","__toCommonJS","import_node_module","import_meta","tsMorphModule","tsMorphLoader","projectCache","getBuiltinModule","id","loadNodeTsMorph","moduleBuiltin","createRequire","setTsMorphLoader","loader","tsMorphLoader","tsMorphModule","loadTsMorph","tsMorphModule","configuredModule","tsMorphLoader","loadNodeTsMorph","createProject","tsConfigPath","cacheKey","cached","projectCache","Project","options","project","clearProjectCache","createProjectFromSource","code","filePath","import_meta","nodeModuleLocation","setTsMorphLoader","import_effect","import_effect","AnalysisError","code","message","location","getStaticChildren","node","y","retryNode","list","n","src","children","c","import_effect","import_effect","EFFECT_TYPE_REGEX_3","EFFECT_TYPE_REGEX_2","taggedErrorTagsFromType","type","part","apparent","tagsFromTagProperty","own","symbol","tags","declaration","tagged","tagProperty","tagType","value","quoted","withErrorTags","signature","errorType","node","fromType","fromSource","taggedErrorTagsFromSource","errorTags","errorTypeName","sourceFile","name","cls","text","field","effectTypeSignatureFromTypeText","typeText","clean","s","match3","match2","tryResolveGenericFromInnerExpression","typeChecker","SyntaxKind","loadTsMorph","call","expr","propAccess","baseExpr","baseSig","extractEffectTypeSignature","args","arg","argSig","_typeChecker","nodeType","isEffectType","typeArgs","extractTypeArguments","aType","eType","rType","errorTypeStr","typeToString","resolved","fromText","eTrim","fromCallee","tryExtractFromCalleeReturnType","callee","callSignatures","returnType","returnArgs","returnText","fromReturnText","decl","returnTypeText","sigs","retType","retArgs","fromAnnotation","aliasSymbol","aliasName","aliasTypeArgs","extractServiceRequirements","requirements","locationNode","nodeTypeArgs","parent","varDecl","declaredType","extractRequirementsType","services","extractServicesFromContext","service","offset","line","column","location","contextType","contextMatch","extractTagIdentifier","parts","splitTopLevelUnion","match","splitTopLevelUnion","typeText","parts","current","depth","inString","i","ch","last","cleanTypeArg","s","LAYER_TYPE_REGEX","extractLayerTypeSignature","node","typeText","match","LAYER_TYPE_REGEX","cleanTypeArg","ERROR_HANDLER_PATTERNS","CONDITIONAL_PATTERNS","RESOURCE_PATTERNS","COLLECTION_PATTERNS","FIBER_PATTERNS","TRANSFORM_OPS","EFFECTFUL_TRANSFORMS","isTransformCall","callee","MATCH_OP_MAP","EXHAUSTIVE_OPS","isMatchCall","CAUSE_OP_MAP","CAUSE_CONSTRUCTORS","isCauseCall","EXIT_OP_MAP","EXIT_CONSTRUCTORS","isExitCall","SCHEDULE_OP_MAP","isScheduleCall","INTERRUPTION_PATTERNS","DO_NOTATION_PATTERNS","CACHING_PATTERNS","API_PREFIXES","BUILT_IN_TYPE_NAMES","KNOWN_EFFECT_NAMESPACES","isServiceTagCallee","getSemanticDescription","p","getSemanticDescriptionWithAliases","effectAliases","direct","dotIndex","prefix","method","isLikelyDirectEffectInitializer","initializer","effectImportNames","nonProgramEffectImportNames","SyntaxKind","loadTsMorph","isNonProgramName","name","isRunEntrypointCalleeText","exprText","isDirectEffectCalleeText","isPipeCall","alias","isLikelyEffectCall","call","isMethodPipeCall","arg","base","isInSameScope","node","scope","current","k","blockContainsEffectLikeUsage","block","awaitExpr","expr","blockContainsRunEntrypointUsage","prop","init","body","bodyBlock","ret","awaited","conditional","text","isEffectPackageSpecifier","specifier","EFFECT_NAMESPACE_NAMES","KNOWN_INTERNAL_MODULES","parseServiceIdsFromContextType","requiredType","skip","normalized","s","getNumericLiteralFromNode","kind","n","unary","operand","v","EFFECT_RUNTIME_PRIMITIVE_NAMES","isRuntimePrimitiveDependency","name","firstSegment","CANONICAL_EFFECT_SERVICE_NAMES","canonicalizeServiceDisplayName","DEFAULT_OPTIONS","idCounter","resetIdCounter","generateId","nodeTextCache","getNodeText","node","text","collectErrorTypes","nodes","set","visit","list","err","part","splitTopLevelUnion","children","getStaticChildren","collectDependencies","byName","reqs","r","displayName","callee","looksLikeService","KNOWN_EFFECT_NAMESPACES","BUILT_IN_TYPE_NAMES","extractLocation","filePath","includeLocations","sourceFile","pos","line","column","endPos","end","extractJSDocDescription","jsDocs","firstJsDoc","comment","description","c","tagIndex","rawText","descriptionMatch","leadingComments","lastComment","commentText","cleaned","extractJSDocTags","tryGetJsDocText","n","SyntaxKind","loadTsMorph","current","kind","grandparent","parseJSDocTags","params","returns","throws","example","tagPattern","match","tag","rest","paramMatch","value","exampleStart","nextTagMatch","getJSDocFromParentVariable","parent","parentKind","isJsOrJsxPath","path","extractYieldVariableName","yieldNode","extractProgramName","getEnclosingVariableName","start","propertyName","containerName","ancestor","depth","extractEnclosingEffectFnName","callExpr","exprText","args","firstArg","createEmptyStats","DEFAULT_LABEL_MAX","truncateDisplayText","s","max","truncate","extractFunctionName","callee","withoutArgs","parts","receiver","KNOWN_EFFECT_NAMESPACES","BUILT_IN_TYPE_NAMES","computeDisplayName","node","variableName","fnName","wrapper","truncate","op","channelOps","sinkOps","computeSemanticRole","node","desc","callee","unwrapExpression","expr","SyntaxKind","loadTsMorph","normalizeSlashes","value","normalizePath","normalized","isAbsolute","parts","stack","part","dirnamePath","lastSeparator","joinPath","resolvePath","hasPathPrefix","prefix","normalizedValue","normalizedPrefix","effectAliasCache","symbolResolutionCache","getNodeExistsSync","maybeProcess","fsBuiltin","getNamesReExportedFromEffect","barrelSourceFile","out","decl","specifier","isEffectPackageSpecifier","EFFECT_NAMESPACE_NAMES","n","named","alias","resolveBarrelSourceFile","project","currentFilePath","baseDir","dirnamePath","resolved","resolvePath","candidates","joinPath","p","f","resolveModulePath","existsSync","isSpecifierUnderKnownEffectInternalsRoot","knownEffectInternalsRoot","normalizedSpecifier","normalizedResolved","normalizedRoot","hasPathPrefix","getEffectImportNames","sourceFile","names","currentPath","def","ns","barrelFile","reExported","toCheck","text","needsDeepTrace","entry","traceReExportChain","getEffectLikeNamespaceAliases","aliases","importDecl","moduleSpecifier","namespaceImport","aliasName","basename","KNOWN_INTERNAL_MODULES","NON_PROGRAM_EFFECT_MODULE_BASENAMES","getNonProgramEffectImportNames","getAliasesForFile","sf","effectSubmoduleAliasCache","canonicalNamespaceFromSpecifier","getEffectSubmoduleAliasMap","map","nsImport","canonical","originalName","normalizeEffectCallee","callee","dotIdx","rest","name","maxDepth","exportDecl","namedExport","nextBarrel","resolveCalleeModuleOrigin","calleeText","cache","nsText","cached","result","resolveNamespaceImportModuleSpecifier","expr","isEffectLikeCallExpression","call","effectAliases","API_PREFIXES","SyntaxKind","loadTsMorph","propAccess","isEffectCallee","prefix","WORKFLOW_FACTORY_NAMES","isWorkflowFactoryCall","calleeText","name","isWorkflowMakeCall","call","expr","loadTsMorph","prop","args","third","SyntaxKind","isWorkflowPackageSpecifier","specifier","_currentFilePath","isWorkflowNamespaceFromPackage","localName","isActivityNamespaceFromPackage","objectArgHasAnyProperty","propertyNames","arg","props","names","p","isWorkflowMakeOptionsCall","importSpecifierByLocalName","currentFilePath","baseText","isActivityMakeOptionsCall","getWorkflowBodyNodeForRunCall","runCall","sourceFile","innerCall","varDecls","decl","initializer","isInsideEffectGen","node","current","text","isTopLevelVariableDeclaration","isYieldBoundDeclaration","getCallExpressionFromInitializer","awaited","buildDiscoveryInfo","discoveryConfidence","discoveryReason","EFFECT_FAMILY_TYPE_HINTS","hasEffectFamilyTypeHint","hint","DISCOVERY_CONFIDENCE_RANK","isRunCall","exprText","bodyContainsRunMainOrRunPromise","body","isIndirectRunMainWrapper","_sourceFile","kind","init","isRuntimeCurriedForm","innerExprText","findEffectPrograms","_opts","programs","seenCallStarts","workflowProgramBuilders","effectImportNames","getEffectLikeNamespaceAliases","nonProgramEffectImportNames","getNonProgramEffectImportNames","importDecl","def","ns","named","inferAliasBackedDiscovery","aliasName","isSpecifierUnderKnownEffectInternalsRoot","inferDirectInitializerDiscovery","inferFromNestedEffectAliasUsage","propertyAccesses","base","calls","c","callee","local","nested","inferTypeAnnotatedDiscovery","typeText","n","isExportedDecl","fnReturnTypeText","typeArgText","isProgramRootExported","program","inferMethodReturnDiscovery","returnStatements","ret","isLikelyDirectEffectInitializer","filePath","varDeclarations","initCall","genCalls","expression","callStart","isWorkflowInvocation","propertyAccess","objectText","methodName","extractProgramName","isEffectLikeCallExpression","extractEnclosingEffectFnName","pipeName","hasEffectInArgs","callInitializer","looksLikeEffect","typeDiscovery","topLevelStatements","stmt","calleeExpr","lastArg","lastArgText","baseName","DATA_SCHEMA_CLASS_PATTERNS","classDeclarations","classDecl","clause","clauseText","topLevelClasses","parent","className","members","properties","m","memberName","fullName","methods","method","getters","getter","functionDeclarations","fnDecl","returnTypeNode","threshold","confidence","alias","extractServiceDefinitionsFromFile","results","typeChecker","extExpr","extText","typeArgs","inner","interfaceTypeNode","type","sym","propName","classText","hasCustomEquality","hasCustomHash","r","import_effect","import_effect","import_effect","compactCallbackCalleeLabel","call","expr","SyntaxKind","loadTsMorph","canonicalizeCallbackLabel","label","CALLBACK_NOISE_LABELS","shouldSkipCallbackSummaryLabel","availableLabels","candidate","summarizeLoopCallbackSource","loopType","callbackBody","labels","node","filtered","index","joined","suffix","buildCallbackSummaryNodes","fnNode","filePath","includeLocations","body","calls","seen","collectFrom","callee","callbackNode","generateId","extractLocation","computeDisplayName","computeSemanticRole","stmt","desc","isFunctionBoundaryForCallbackSummary","kind","summarizeResumePayloads","sourceFile","opts","warnings","stats","resumeParamName","summaries","visit","payload","payloadText","compactPayload","key","filterHandlerSummaryNoise","nodes","seenEffectLabels","summarizeNamedCallbackHandlers","block","decl","init","handlerFn","buildPureCallbackSummaryNodes","handlerNode","addEffectSummary","description","canonicalLabel","addConditionalSummary","condition","text","isLayerOrEffectInitializerCallee","initCall","initText","srcFile","normalized","normalizeEffectCallee","resolveLayerInitializerFromImport","ident","importSpec","isLayerInit","SyntaxKind","loadTsMorph","sourceFile","project","currentPath","specifier","targetFile","resolveBarrelSourceFile","resolvedPath","resolveModulePath","added","tryDecl","d","init","list","v","exportName","exported","decls","targetName","declList","resolveLayerInitializerFromDefaultImport","importDecl","resolveIdentifierToLayerInitializer","node","name","sym","decl","fromDecls","sf","id","fromDefault","spec","n","fromImport","isPromiseLikeText","text","EFFECT_RUNTIME_PRIMITIVE_PREFIXES","isEffectRuntimePrimitive","prefix","isLikelyServiceStreamProperty","propertyName","normalizeInferredServiceType","typeName","inferServiceTypeFromObjectName","objectName","inferred","BUILT_IN_TYPE_NAMES","KNOWN_EFFECT_NAMESPACES","tryResolveServicePropertyAccess","node","methodName","firstSegment","fallback","type","symbol","classifyUseCallbackKind","fnNode","bodyText","fnTypeText","createAnalysisContext","getAnalyze","bindAnalysisContext","context","analyzer","args","import_effect","channelOpCategory","op","sinkOpCategory","parseEffectAllOptions","optionsNode","SyntaxKind","loadTsMorph","concurrency","batching","discard","prop","name","init","text","n","parseScheduleInfo","scheduleText","baseStrategy","maxRetries","recursMatch","recurUpToMatch","jittered","conditions","analyzeStreamCall","deps","call","callee","sourceFile","filePath","opts","warnings","stats","serviceScope","args","SyntaxKind","loadTsMorph","baseExpr","analyzedBase","effectiveSource","pipeline","sink","backpressureStrategy","constructorType","arg","analyzed","streamNode","generateId","extractLocation","computeDisplayName","computeSemanticRole","source","opName","classifyOperator","op","isEffectful","callbackArg","callbackBody","buildCallbackSummaryNodes","buildPureCallbackSummaryNodes","opCategory","cardinality","windowSize","stride","getNumericLiteralFromNode","thisOp","effectiveConstructorType","srcStream","analyzeChannelCall","channelOpCategory","srcChan","channelNode","analyzeSinkCall","sinkOpCategory","srcSink","sinkNode","import_effect","analyzeRetryCall","deps","call","sourceFile","filePath","opts","warnings","stats","args","source","schedule","scheduleNode","hasFallback","expr","loadTsMorph","exprSource","generateId","scheduleInfo","parseScheduleInfo","retryNode","extractLocation","computeDisplayName","computeSemanticRole","analyzeTimeoutCall","duration","getNodeText","exprText","timeoutNode","analyzeScheduleCall","callee","scheduleOp","SCHEDULE_OP_MAP","scheduleText","import_effect","analyzeConcurrencyPrimitiveCall","call","callee","_sourceFile","filePath","opts","_warnings","_stats","SyntaxKind","loadTsMorph","primitive","operation","strategy","capacity","permitCount","args","first","getNumericLiteralFromNode","lifecycleOptions","arg","text","constructorType","innerPrimNode","generateId","extractLocation","streamNode","computeDisplayName","computeSemanticRole","concurrencyNode","analyzeFiberCall","deps","sourceFile","warnings","stats","isScoped","isDaemon","fiberSource","joinPoint","firstArg","scopeContext","parent","parentText","fiberNode","analyzeInterruptionCall","interruptionType","source","handler","expr","propAccess","interruptionNode","import_effect","analyzeParallelCall","deps","call","callee","sourceFile","filePath","opts","warnings","stats","serviceScope","args","children","SyntaxKind","loadTsMorph","firstArg","elements","elem","analyzed","props","prop","initializer","concurrency","batching","discard","parsed","parseEffectAllOptions","mode","branchLabels","child","computeDisplayName","parallelNode","generateId","extractLocation","computeSemanticRole","analyzeRaceCall","arg","raceLabels","raceNode","import_effect","classifyErrorHandlerName","callee","analyzeErrorHandlerCall","deps","call","sourceFile","filePath","opts","warnings","stats","args","handlerType","source","handler","expr","loadTsMorph","exprSource","generateId","errorTag","errorTags","tagArg","objArg","a","p","handlerNode","extractLocation","computeDisplayName","computeSemanticRole","import_effect","analyzeResourceCall","deps","call","callee","sourceFile","filePath","opts","warnings","stats","args","resourceOperation","acquire","release","useEffect","generateId","expr","loadTsMorph","propAccess","exprSource","resourceNode","extractLocation","computeDisplayName","computeSemanticRole","import_effect","analyzeConditionalCall","deps","call","callee","sourceFile","filePath","opts","warnings","stats","args","conditionalType","condition","onTrue","onFalse","secondArg","SyntaxKind","loadTsMorph","props","prop","propAssign","name","init","expr","exprSource","generateId","truncatedCondition","conditionalNode","extractLocation","computeDisplayName","computeSemanticRole","analyzeLoopCall","loopType","bodyArgIndex","iterSource","body","callbackBody","rawSource","bodyArg","fn","effectfulSummary","buildCallbackSummaryNodes","pureSummary","buildPureCallbackSummaryNodes","summarizeLoopCallbackSource","predicateArg","loopNode","analyzeMatchCall","matchOp","MATCH_OP_MAP","isExhaustive","EXHAUSTIVE_OPS","matchedTags","arg0","arg","obj","matchNode","analyzeCauseCall","causeOp","CAUSE_OP_MAP","isConstructor","CAUSE_CONSTRUCTORS","children","childNodes","child","causeKind","childKinds","c","k","causeNode","analyzeExitCall","exitOp","EXIT_OP_MAP","EXIT_CONSTRUCTORS","exitNode","analyzeTransformCall","transformType","TRANSFORM_OPS","isEffectful","EFFECTFUL_TRANSFORMS","source","fnText","transformNode","analysisContext","createAnalysisContext","analyzeEffectExpression","analyzeStreamCall","bindAnalysisContext","analyzeChannelCall","analyzeSinkCall","analyzeRetryCall","analyzeTimeoutCall","analyzeFiberCall","analyzeInterruptionCall","analyzeParallelCall","analyzeRaceCall","analyzeErrorHandlerCall","analyzeResourceCall","analyzeConditionalCall","analyzeLoopCall","analyzeCauseCall","analyzeTransformCall","SCHEMA_OPS","EFFECT_PIPE_OP_REGEX","pipeArgsIncludeEffectOp","call","arg","asErrorHandler","analyzed","stats","loadTsMorph","text","ERROR_HANDLER_PATTERNS","pattern","handlerType","classifyErrorHandlerName","node","generateId","computeDisplayName","computeSemanticRole","analyzePipeChain","sourceFile","filePath","opts","warnings","serviceScope","SyntaxKind","args","expr","isMethodPipe","baseExpr","transformArgs","baseNode","resolveIdentifierToLayerInitializer","baseSourceFile","basePath","project","inProject","added","initial","transformations","sourceOrderedSpanNames","spanNameDynamic","filteredTransformations","t","argText","match","spanNames","spanName","typeFlow","typeChecker","flow","initialSig","extractEffectTypeSignature","argNode","sig","innerSpanNames","mergedSpanNames","innermost","pipeNode","unwrapExpression","body","unknownNode","extractLocation","returnedExpr","stmt","analyzeEffectCall","operation","objectText","propertyName","serviceId","serviceEffectNode","isLikelyServiceStreamProperty","streamNode","inferredServiceCall","tryResolveServicePropertyAccess","isEffectCallee","getAliasesForFile","effectNode","normalizeEffectCallee","objLit","HANDLER_PROPS","props","handlerEntries","hasKnownHandler","prop","assignment","propName","initializer","tagText","newExpr","ctorText","ctorName","typeText","unknownReason","callee","normalizedCallee","calleeOperation","location","isEffectMethodPipe","nodes","baseCallText","baseText","baseCallOrExprText","analyzeLayerCall","layerNode","analyzeConcurrencyPrimitiveCall","FIBER_PATTERNS","p","INTERRUPTION_PATTERNS","resourceOps","resourceOpPrefixes","isResourceOp","op","baseCall","baseCallee","baseOperation","conditionalOp","CONDITIONAL_PATTERNS","isSchemaOp","collectionOp","COLLECTION_PATTERNS","isTransformCall","isMatchCall","analyzeMatchCall","isCauseCall","isExitCall","analyzeExitCall","isScheduleCall","analyzeScheduleCall","callbackBody","usePattern","isConstructorWithCallback","c","asyncCallback","firstArg","fn","innerNodes","block","retExpr","isEffectLikeCallExpression","resumeParamName","resumeCallCount","visit","returnsCanceller","k","handlerSummaries","summarizeNamedCallbackHandlers","propAccess","callbackArg","callbackFn","callbackNodes","buildCallbackSummaryNodes","wrapperExpr","classifyUseCallbackKind","effectJSDoc","extractJSDocDescription","typeSignature","requiredServices","extractServiceRequirements","serviceCall","tryResolveServiceCall","serviceMethod","methodName","provideKind","contextArgText","constructorKind","fiberRefName","KNOWN_FIBER_REFS","refName","tracedName","strMatch","innerCall","innerCallee","fnArgs","filteredRequiredServices","service","isEffectRuntimePrimitive","getSemanticDescriptionWithAliases","extractJSDocTags","objExpr","objectName","firstSegment","KNOWN_EFFECT_NAMESPACES","normalized","normalizedFirstSegment","type","symbol","typeName","BUILT_IN_TYPE_NAMES","operations","elements","elem","toAnalyze","argSourceFile","isMerged","lifecycle","provides","extractTagNames","item","callNode","first","pae","obj","isProvideCall","requiresSet","depName","baseArg","collectRequires","eff","req","calleeText","layer","r","getStaticChildren","layerSig","extractLayerTypeSignature","parseServiceIdsFromContextType","id","layerOpName","layerName","isMemoMap","analyzeProgram","program","sourceFile","filePath","opts","tsVersion","warnings","stats","createEmptyStats","children","analyzeProgramNode","programJSDoc","getJSDocFromParentVariable","typeChecker","typeSignature","extractEffectTypeSignature","requiredServices","extractServiceRequirements","root","generateId","collectDependencies","collectErrorTypes","extractLocation","extractJSDocTags","serviceDefinitions","extractServiceDefinitionsFromFile","node","programType","genCall","args","genChildren","analyzeGeneratorFunction","outerPipe","findOuterPipeOnGen","applyOuterPipeTransformsToGen","outerLayerUnwrap","findOuterLayerUnwrapOnGen","unwrapNode","computeDisplayName","computeSemanticRole","analyzePipeChain","call","SyntaxKind","loadTsMorph","pipeResult","analyzeRunEntrypointExpression","callbackInArgs","arg","workflowBody","getWorkflowBodyNodeForRunCall","effect","analyzeEffectExpression","exprText","initializer","SK","outerCall","outerExpr","innerCall","innerCallee","genArg","fnArgs","tracedName","firstArg","strMatch","constructorKind","fnMetaNode","enrichedFnNode","classDecl","callee","clause","clauseText","description","classEffectNode","extractJSDocDescription","body","returnStatements","ret","expr","result","SK2","isFunctionBoundary","kind","containsGeneratorYield","found","child","extractLiteralValue","resolveConditionConsts","condition","constValues","resolved","name","value","pattern","replacement","simplifyBooleanExpression","hasTerminatorStatement","stmts","last","collectYieldExpressionsDF","results","collectCallExpressionsBoundaryAware","calls","visit","current","STEP_FUNCTIONS","isStepCall","extractStringLiteral","parseBranchCases","casesObj","cases","objLit","prop","analyzeStepCall","callExpr","ctx","stepId","innerEffect","analyzed","label","expression","c","effectsArg","arrayLit","element","iterSource","fn","effectNode","analyzeYieldNode","yieldNode","yieldExpr","isDelegated","opaqueNode","extractYieldVariableName","effectExpr","unwrappedCall","unwrapExpression","calleeExpr","unwrappedExpr","stepResult","variableName","enrichedStep","isServiceTagCallee","enrichedEffect","analyzeGeneratorBody","block","stmt","nodes","analyzeStatement","analyzeExpressionForYields","varStmt","VariableDeclarationKind","isConst","decl","init","literalValue","calleeText","yieldEntries","declName","lastEntry","ifStmt","condYields","thenStmt","elseStmt","onTrue","analyzeStatementBlock","onFalse","resolvedCondition","decisionLabel","decisionNode","y","switchStmt","clauses","hasFallthrough","hasDefault","currentLabels","currentBodyYields","currentIsDefault","caseClause","clauseStmts","clauseStmt","resolvedExpression","switchNode","forStmt","headerYields","entries","e","incrementor","bodyStmt","bodyYields","hasEarlyExit","checkEarlyExit","loopBody","loopNode","forOfStmt","iterExpr","iterVariable","forInStmt","whileStmt","doStmt","tryStmt","tryBlock","tryYields","catchClause","catchVariable","catchYields","catchBlock","finallyBlock","finallyYields","hasTerminalInTry","tryCatchNode","descendantCalls","entry","termNode","valueYields","k","unwrapped","exprKind","ternary","whenTrue","whenFalse","trueYields","falseYields","resolvedCond","binary","operatorToken","left","right","rightYields","yieldExprs","serviceScope","generatorAdapterParams","fnLike","param","yields","stmtKind","aliases","getAliasesForFile","isEffectLikeCallExpression","analyzeEffectCall","generatorJSDoc","generatorNode","parent","pa","grandparent","outer","pipeCall","transformArgs","wrapChildren","gen","argCall","argExprText","text","argArgs","location","source","scheduleArg","schedule","scheduleNode","retryNode","lastArg","lastArgText","analyzeEffectFile","filePath","options","opts","DEFAULT_OPTIONS","ts","Project","loadTsMorph","project","isJsOrJsxPath","createProject","error","AnalysisError","existingFile","sourceFile","programs","findEffectPrograms","program","analyzeProgram","analyzeEffectSource","code","createProjectFromSource","createResult","programs","program","AnalysisError","p","name","found","available","analyze","filePath","options","resetIdCounter","programsEffect","analyzeEffectFile","code","analyzeEffectSource","import_effect","import_promises","import_fs","import_path","import_effect","extractServiceTagsFromFile","sourceFile","filePath","SyntaxKind","loadTsMorph","results","typeChecker","classDeclarations","classDecl","name","extExpr","extText","tagId","tagMatch","serviceMatch","typeArgs","expression","definition","interfaceTypeText","interfaceTypeNode","type","methods","properties","sym","propName","pos","lineAndCol","extractLayerImplementationsFromFile","identifierToServiceId","varDeclarations","varDecl","initializer","initText","layerMatch","kind","layerName","providesServiceId","args","firstArg","firstArgText","identifier","requires","provideMatch","provideArg","canonicalId","yieldServiceMatches","m","ident","canonical","yieldServiceMatchesAlt","collectConsumers","byFile","consumers","irs","ir","programName","req","list","collectConsumersFromNodes","nodes","node","serviceId","c","children","getStaticChildren","computeTopologicalOrder","services","result","visited","temp","visit","id","artifact","dep","computeTransitiveDeps","layerImpls","allLayersByService","deps","layer","reqLayers","transitive","buildProjectServiceMap","sourceFiles","serviceTagInfos","sf","tags","tag","def","knownServiceIds","tagInfo","allReferencedServiceIds","layersByService","layers","match","collectLayersFromIR","consumersByService","unresolvedServices","dependencies","allReferenced","refId","topologicalOrder","providedIdent","r","l","import_effect","import_promises","import_path","DEFAULT_EXTENSIONS","DEFAULT_MAX_DEPTH","discoverProjectFiles","dir","extensions","maxDepth","currentDepth","files","entries","entry","fullPath","left","right","scanProjectCorpus","root","options","startedAt","corpusFiles","file","fileStartedAt","result","analyze","programs","error","durationMs","isZero","dimension","numerator","denominator","emptyRate","assessAudit","input","import_effect","childrenOf","node","getStaticChildren","visitIR","roots","visitor","index","visit","nodes","parent","ancestors","flattenIR","runtimeSpanName","runtimeSpanNames","name","spanPathKey","path","indexIR","ir","byId","parentById","spanPathById","mutableIdsBySpanPath","ownNames","ancestorPath","ancestor","i","key","ids","findingForNode","node","runtimeSpanName","rate","resolved","total","assessIRFidelity","ir","index","indexIR","findings","sourceUnresolvedIds","runtimeInexactIds","runtimeNodeIds","finding","spanPath","ids","printablePath","nodeId","sourceResolved","runtimeResolved","penalizedIds","score","import_path","FEATURE_ORDER","describeText","text","fallback","trimmed","detectStageKind","expr","Node","describeStage","getPropertyExpression","objectLiteral","name","prop","extractNestedHandlers","inferCapabilities","summary","features","feature","isMakeProgramCall","call","expression","isCommandDefineCall","runtimeNameForCall","filePath","ordinal","parent","isLayerCall","isLayerAssemblyRoot","getLayerAssemblyName","extractLayerAssembly","operations","references","collectLayerRefs","collectLayerCall","element","current","exprText","pipeBase","arg","extractProjectArchitecture","filePaths","options","Project","loadTsMorph","project","sourceFiles","commands","runtimes","layerAssemblies","sourceFile","runtimeOrdinal","layerOrdinal","node","variableName","firstArg","commandName","layerName","configArg","runtimeName","model","flagsSchema","flags","init","update","view","container","subscriptions","resources","managedResources","routing","crash","slowView","title","devtools","baseRuntime","commandsByFile","command","runtime","DEFAULT_OPTIONS","NON_PROGRAM_EFFECT_MODULES","fileImportsEffect","filePath","content","runtimeImportMatches","hasAnyRuntimeImport","allNonProgram","match","names","s","name","isTypeOnlyZeroCandidate","isLightweightEffectAdapterFile","detectExpectedZeroCategory","normalized","base","findPackageJsonDirs","dir","maxDepth","currentDepth","result","entries","e","ent","resolveEntry","pkgDir","entry","extensions","fileHasTopLevelRunCall","Project","SyntaxKind","loadTsMorph","callExpressions","functionKinds","call","parent","current","kind","exprText","getEntryPointsFromPackageJson","dirPath","pkgDirs","entryPaths","raw","pkg","dirs","v","list","p","analyzeProjectCorpus","corpus","options","files","byFile","allPrograms","entryPointFiles","failedFiles","zeroProgramFiles","file","programs","ir","nameLikeEntry","isRunCall","packageEntryPaths","serviceMap","project","sourceFileMap","buildProjectServiceMap","architecture","extractProjectArchitecture","analyzeProject","scanProjectCorpus","runCoverageAudit","runCoverageAuditFromCorpus","outcomes","totalNodes","unknownNodes","sourceUnresolvedNodes","fidelityFindings","fileUnknownRates","unknownReasonsCorpus","durationMs","count","fileTotal","fileUnknown","fidelity","assessIRFidelity","unknownFindings","finding","reason","discovered","analyzed","o","zeroPrograms","failed","excludePatterns","isExcludedFromSuspicious","zeroProgramCategoryCounts","suspiciousZeros","zeroProgramClassifications","zeroOutcomes","importsEffect","expectedCategory","category","unknownNodeRate","assessment","assessAudit","topUnknownFiles","f","a","b","unknownReasonCounts","n","topUnknownReasons","createAnalysisSession","analyze","scanProjectCorpus","analyzeProject","analyzeProjectCorpus","runCoverageAudit","runCoverageAuditFromCorpus","clearProjectCache","analysis","evaluateAuditPolicy","facts","policy","violations","import_path","percent","rate","digits","ratio","numerator","denominator","renderViolations","decision","violation","renderQuiet","audit","assessment","summary","violations","renderHuman","options","lines","byFolder","outcome","folder","counts","b","failures","failure","suspicious","file","unknownNodes","finding","findings","header","location","reason","count","renderCoverageReport","import_effect","DEFAULT_THRESHOLDS","calculateComplexity","ir","nodes","cyclomatic","calculateCyclomaticComplexity","cognitive","calculateCognitiveComplexity","pathCount","calculatePathCount","maxDepth","calculateMaxDepth","maxParallelBreadth","calculateMaxParallelBreadth","decisionPoints","countDecisionPoints","complexity","node","countDecisionPointsInNode","children","getStaticChildren","childList","count","child","calculateCognitiveForNodes","nestingDepth","calculateCognitiveForNode","caseItem","hasUnbounded","result","pathCountForNode","truePaths","pathCountForNodes","falsePaths","total","childPaths","product","c","casePaths","paths","depthOfNode","currentDepth","maxChildDepth","maxBreadth","parallelBreadthOfNode","assessComplexity","metrics","thresholds","warnings","recommendations","level","hasError","w","hasWarning","formatComplexitySummary","assessment","lines","warning","icon","rec","DEFAULT_OPTIONS","generatePaths","ir","options","generatePathsWithMetadata","context","initialState","generatePathsForNodes","state","index","generatePathDescription","nodes","currentState","states","node","newStates","generatePathsForNode","term","handleEffectNode","handleGeneratorNode","handlePipeNode","handleParallelNode","handleRaceNode","handleErrorHandlerNode","handleSingleChildNode","handleResourceNode","handleConditionalNode","handleLoopNode","handleLayerNode","handleStreamNode","handleConcurrencyOrFiberNode","handleDecisionNode","handleSwitchNode","handleTryCatchNode","handleTerminalNode","handleCauseNode","handleLeafStepNode","handleMatchNode","handleTransformNode","handleChannelNode","handleSinkNode","handleInterruptionNode","stepRef","children","y","combinedStates","child","newCombinedStates","childStates","childState","first","allStates","maxAllowed","roomLeft","toAdd","sourceStates","handlerStates","resourceNodes","trueCondition","trueState","trueStates","falseCondition","falseState","falseStates","step","idx","p","stateWithStep","caseItem","caseLabel","caseCondition","caseState","caseStates","tryStates","catchStates","catchCondition","catchState","combined","finalStates","_context","parts","conditionParts","c","verb","stepNames","s","name","calculatePathStatistics","paths","conditions","pathsWithLoops","pathsWithUnresolvedRefs","totalLength","maxLength","minLength","path","length","filterPaths","filter","import_effect","collectEffectNodesInOrder","nodes","result","node","children","getStaticChildren","buildDataFlowGraph","ir","edges","producedKeys","keyProducers","effectNodesOrdered","eff","writes","reads","s","producers","i","from","to","key","contextId","undefinedReads","duplicateWrites","writers","getDataFlowOrder","graph","inDegree","adjacency","edge","targets","queue","id","degree","current","neighbor","newDegree","getProducers","stepId","producerIds","n","getConsumers","consumerIds","getTransitiveDependencies","visited","visit","findCycles","cycles","recStack","dfs","path","cycleStart","validateDataFlow","issues","read","write","cycle","sanitizeId","renderDataFlowMermaid","lines","label","warningId","import_effect","HANDLER_TABLE","errorDisposition","handlerType","lookupHandler","matchesTag","error","tag","matchingAny","errors","tags","e","parseErrorTypes","errorType","splitTopLevelUnion","collectEffectErrors","nodes","result","node","eff","children","getStaticChildren","analyzeErrorFlow","ir","stepErrors","allErrorsSet","errorToSteps","stepsWithoutErrors","step","steps","unionErrors","a","b","withoutErrors","current","removed","set","collectErrorsFromSubtree","out","visit","n","err","findCauseKindInSubtree","child","walkPropagation","errorsIn","own","handler","sourceErrors","entry","scope","fixedTags","matched","afterNarrow","handlerErrors","causeKind","branchErrors","fromChild","analyzeErrorPropagation","propagation","byNodeId","p","getErrorsAtPoint","analysis","afterStepId","found","getErrorProducers","errorTag","stepIds","s","validateWorkflowErrors","declaredErrors","declaredSet","computedSet","unusedDeclared","undeclaredErrors","sanitizeId","id","renderErrorFlowMermaid","lines","label","stepId","formatErrorSummary","producers","name","import_effect","collectRequiredFromNode","node","result","reqs","r","x","children","getStaticChildren","c","getProvidedServiceId","getFirstArgText","callee","analyzeServiceFlow","ir","options","requiredServices","child","dedupedRequired","providedServices","unsatisfiedAt","consumedBy","available","getFirstArg","walk","nodes","eff","providedId","prov","list","u","serviceLifecycle","p","layer_graph_exports","__export","buildLayerDependencyGraph","detectDiamondDependencies","detectLayerCycles","findUnsatisfiedServices","renderLayerGraphMermaid","import_effect","collectLayerNodes","nodes","result","node","layer","info","op","children","getStaticChildren","buildLayerDependencyGraph","ir","layers","edges","serviceToLayers","depLayerId","svc","list","req","detectLayerCycles","graph","providerByService","providers","adjacency","deps","provider","cycles","visiting","visited","dfs","path","cycleStart","next","layerId","detectDiamondDependencies","diamonds","serviceId","findUnsatisfiedServices","allProvided","unsatisfied","requiredBy","computeLayerDepths","depths","computeDepth","cached","maxDep","sanitizeId","id","DEPTH_COLORS","renderLayerGraphMermaid","lines","cycleEdges","cycle","i","label","provided","e","isCycleEdge","maxDepth","d","depth","cycleNodes","import_effect","isSpanCallee","callee","isLogCallee","getLogLevel","isMetricCallee","getMetricType","analyzeObservability","ir","spans","logPoints","metrics","untracedEffects","effectCount","effectsWithSpans","effectsWithMetrics","errorHandlersWithLogging","errorHandlerCount","visit","nodes","spanStack","underMetric","node","nextSpanStack","span","eff","s","lp","isTagged","m","handler","hasLog","checkLog","n","c","getStaticChildren","children","thisIsMetric","nextUnderMetric","spanChildCounts","countEffectsInSpan","activeSpans","nextSpans","spanId","DEFAULT_OPTIONS","defaultTestNameGenerator","generateTestMatrix","paths","options","opts","filteredPaths","p","testPaths","path","generateTestPath","conditions","extractConditions","summary","calculateSummary","testName","priority","determinePriority","setupConditions","verb","expectedSteps","s","name","parts","mainSteps","stepNames","camelToSpaces","conditionDescriptions","c","simplified","simplifyCondition","str","expression","conditionMap","condition","key","entry","affected","highPriorityPaths","minTestsForCoverage","formatTestMatrixMarkdown","matrix","lines","highPriority","mediumPriority","lowPriority","formatTestPathLines","truncatedExpr","trueCount","falseCount","i","formatTestMatrixAsCode","runner","programName","escapeString","step","formatTestChecklist","marker","import_effect","analyzeScopeResource","ir","acquisitions","scopeBoundaries","poolCreations","potentialLeaks","visit","nodes","node","eff","callee","acq","sb","res","children","getStaticChildren","import_effect","isRefCallee","callee","getRefOperation","getRefId","WRITE_OPS","analyzeStateFlow","ir","refs","mutations","readersByRef","writersByRef","visit","nodes","node","eff","refId","operation","info","w","r","children","getStaticChildren","stateGraph","potentialRaces","readers","writers","import_node_fs","import_ts_morph","import_ts_morph","stringValue","node","u","unwrapExpression","propEntries","obj","out","prop","nameNode","name","propValue","locOf","filePath","sf","offset","line","column","join","parent","child","isFunctionLike","isEffectMachineBinding","declaration","namedImport","isEffectMachineNamespace","isMachineCall","expr","owner","finalStatesOf","machine","hasOutgoing","t","s","objectLiteral","node","sf","depth","u","unwrapExpression","stateTree","isMachineCall","classTag","name","extendsText","NODE_CONFIG_KEYS","nodeConfig","key","readStateTree","obj","parent","out","value","propEntries","inner","config","type","stringValue","propValue","children","join","localScope","path","tree","descendBuilder","call","arrows","isFunctionLike","arrow","param","body","expr","base","targetPath","from","builders","mode","modeName","receiver","segment","start","isCallTo","guardOf","handler","child","cur","cond","then","builderNames","names","fns","fn","nameNode","targetsOf","seen","calls","to","guard","childId","decl","INVOKE_COMPLETIONS","INVOKE_SOURCES","invokeBuilder","completions","trigger","first","id","invokesOf","element","builder","callee","src","factory","actionLabel","kind","readHandlerNode","push","event","invokeIndex","on","always","onDone","entry","exit","invoke","found","f","handleCallOn","implementationsOf","makeCall","asImplementation","chained","definition","ownerOf","identifier","snapshotPath","chainPath","segments","next","initialPath","owner","access","arrayLiteral","unwrapped","eventsDescriptor","tags","argument","union","declaredEventsOf","events","array","elements","extractMachine","implementation","filePath","statesObj","scan","handlers","declaredStates","finals","parallels","transitions","entered","finalState","states","declaredEvents","locOf","analysisCache","analyzeStateMachines","filePath","source","mtimeMs","cached","project","sf","machines","call","isMachineCall","implementation","implementationsOf","machine","extractMachine","analysis","isPlainObject","v","requireObject","value","what","markerLabel","invokeSource","where","marker","kind","guardLabel","record","actionLabel","actionLabels","labels","x","normalizeValue","one","transition","target","targets","candidate","guard","actions","initialTarget","afterLabel","delayKey","fromMachineJSON","json","options","rootInitial","states","entries","idToPath","collectStates","children","parentPath","key","node","path","declaredStates","transitions","observedEvents","seenEvents","resolveTarget","from","resolveInitialTarget","emit","event","trigger","invokeIndex","norm","entryActions","exitActions","invokes","entry","exit","invokeValues","metadata","invoke","child","on","after","schemaEvents","declaredEvents","unique","xs","seen","out","x","reachableFrom","initial","adjacency","reachable","queue","head","u","v","computeStateMachineCoverage","machine","usedStates","eventTransitions","t","usedEvents","alphabetKnown","declaredStates","declaredEvents","stateSet","eventSet","hasAnyOutgoing","hasEventOutgoing","set","allStates","unhandledEvents","e","unreachableStates","s","undeclaredStates","undeclaredEvents","explicitFinals","deadEndStates","activeStates","handledPerState","totalPairs","handledPairs","handled","coverageRatio","findings","sanitizeId","text","id","escapeLabel","renderStatechartMermaid","machine","coverage","lines","usedStates","unreachableUsed","s","orphanStates","undeclared","idOf","childrenOf","known","state","path","seg","parent","initialsOf","t","emitState","indent","kids","label","to","kid","top","entry","exit","invokes","invoke","finals","finalStatesOf","noteParts","part","renderStatechartsMermaid","analysis","coverages","byName","c","m","str","value","key","name","identifier","sanitized","prefixed","sameActions","left","right","i","dedupe","ts","out","t","x","renderXStateConfig","machine","finals","finalStatesOf","hierarchical","s","ref","to","strList","xs","transitionObj","fields","targetValue","targets","first","childrenOf","known","state","path","seg","parent","byFrom","compoundInitial","segs","child","childKeyToward","target","parallel","renderNode","indent","label","kids","outs","events","always","afters","dones","errors","parts","entry","exit","invokes","configs","invoke","invokeIndex","belongsToInvoke","invokeDones","invokeErrors","byEvent","on","event","byDelay","raw","delay","after","initKey","inner","kid","p","stateLines","top","lines","rootInitial","C","NODE_H","V_GAP","MARGIN_X","MARGIN_TOP","MARGIN_BOTTOM","esc","text","nodeWidth","label","pillWidth","eventLabel","event","guard","g","assignLayers","machine","states","layer","adj","s","t","init","queue","head","u","lu","v","maxLayer","l","pill","cx","cy","w","h","renderStatechartSVG","coverage","unreachableSet","undeclaredSet","byLayer","widestPill","hGap","colW","colX","i","boxes","idx","x","y","maxRows","contentW","contentH","dipY","finals","finalStatesOf","edges","pills","forwardBySource","otherEdges","from","to","arr","fromState","outs","sx","scy","k","a","b","o","exitY","pillW","pillCx","bendX","tx","ty","rightLane","backLane","sy","laneX","lane","nodes","box","isInitial","isFinal","isUnreachable","isUndeclared","stroke","sw","dash","initialMarker","initBox","cyN","dotX","unhandled","footerH","W","boxH","H","footer","e","n","p"]}