effect-analyzer 0.1.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/effect-workflow.ts","../src/analyze.ts","../src/types.ts","../src/static-analyzer.ts","../src/ts-morph-loader.ts","../src/analysis-utils.ts","../src/type-extractor.ts","../src/analysis-patterns.ts","../src/alias-resolution.ts","../src/program-discovery.ts","../src/core-analysis.ts","../src/effect-analysis.ts"],"sourcesContent":["/**\n * effect-workflow analyzer entrypoint\n *\n * Same API as the main analyzer but with effect-workflow patterns enabled\n * (Workflow.make / Workflow.run). Use this when analyzing code that uses\n * the effect-workflow library.\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { analyze } from \"effect-analyzer/effect-workflow\";\n *\n * const ir = await Effect.runPromise(\n * analyze.source(source).named(\"runCheckout\")\n * );\n * ```\n */\n\nimport { analyze as baseAnalyze } from './analyze';\nimport type { AnalyzerOptions } from './types';\n\nconst workflowOptions: AnalyzerOptions = { enableEffectWorkflow: true };\n\n/**\n * Analyze a file with effect-workflow patterns enabled (Workflow.make / Workflow.run).\n */\nexport const analyze = (\n filePath: string,\n options?: AnalyzerOptions,\n): ReturnType<typeof baseAnalyze> =>\n baseAnalyze(filePath, { ...workflowOptions, ...options });\n\nanalyze.source = (\n code: string,\n options?: AnalyzerOptions,\n): ReturnType<typeof baseAnalyze.source> =>\n baseAnalyze.source(code, { ...workflowOptions, ...options });\n\nexport type { AnalyzeResult } from './analyze';\nexport type { StaticEffectIR, AnalyzerOptions } from './types';\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 * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { analyze } from \"effect-analyzer\";\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 { 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: () =>\n 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 ),\n );\n }),\n\n singleOption: () =>\n 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: () =>\n 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: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).single();\n }),\n\n singleOption: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).first();\n }),\n\n firstOption: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).single();\n }),\n\n singleOption: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).first();\n }),\n\n firstOption: () =>\n 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\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}\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}\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 /** Inner effects from Effect.sync/promise/async callback body (one level only) */\n readonly callbackBody?: readonly StaticFlowNode[] | undefined;\n /** Effect.async/asyncEffect only: resume/canceller callback patterns (GAP async callback interop). */\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' | '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 (catchAll, catchTag, orElse, etc.).\n */\nexport interface StaticErrorHandlerNode extends StaticBaseNode {\n readonly type: 'error-handler';\n /** Type of handler: catchAll, catchTag, orElse, etc. */\n readonly handlerType:\n | 'catchAll'\n | 'catchTag'\n | 'catchAllCause'\n | 'catchIf'\n | 'catchSome'\n | 'catchSomeCause'\n | 'catchSomeDefect'\n | 'catchAllDefect'\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 /** 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 /** 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 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';\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}\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 * Dynamic ts-morph loader to avoid direct dependency issues\n */\n\nimport { createRequire } from 'node:module';\nimport type { Project, SourceFile } from 'ts-morph';\n\nlet tsMorphModule: typeof import('ts-morph') | null = null;\nconst projectCache = new Map<string, Project>();\n\n/**\n * Load ts-morph dynamically (peer dependency)\n */\nexport const loadTsMorph = (): typeof import('ts-morph') => {\n if (!tsMorphModule) {\n try {\n const require = createRequire(import.meta.url);\n tsMorphModule = require('ts-morph');\n } catch {\n throw new Error(\n 'ts-morph is required but not installed. Please install it as a peer dependency: npm install ts-morph',\n );\n }\n }\n return tsMorphModule!;\n};\n\n/**\n * Create a ts-morph project\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\n/**\n * Clear cached ts-morph projects.\n */\nexport const clearProjectCache = (): void => {\n projectCache.clear();\n};\n\n/**\n * Create a project from source code (for testing)\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 * 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';\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 (!byName.has(r.serviceId)) {\n byName.set(r.serviceId, {\n name: r.serviceId,\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 const looksLikeService = /^[A-Z]/.test(callee)\n && !callee.startsWith('Effect.')\n && !callee.startsWith('Schema.')\n && !callee.startsWith('Data.')\n && !callee.startsWith('Config.')\n && !callee.startsWith('Command.')\n && !callee.startsWith('Stream.')\n && !callee.startsWith('Option.')\n && !callee.startsWith('Either.')\n && !callee.startsWith('Cause.')\n && !callee.startsWith('Exit.');\n if (looksLikeService && !byName.has(callee)) {\n byName.set(callee, {\n name: callee,\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 };\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';\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/**\n * Truncate a string to `max` characters, appending an ellipsis if truncated.\n */\nconst truncate = (s: string, max: number): string =>\n s.length <= max ? s : `${s.slice(0, max)}…`;\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 prefix = variableName ?? node.name;\n return prefix ? `${prefix} <- ${node.callee}` : node.callee;\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 ? `${node.loopType}(${node.iterSource})` : 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 parts.join(' → ');\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 * 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) 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 * 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 } from 'ts-morph';\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 in Effect v3) */\nconst EFFECT_TYPE_REGEX_2 = /Effect(?:\\.Effect)?<([^,>]+),\\s*([^,>]+)>/;\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 in Effect v3)\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 * 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 return {\n successType: typeToString(aType),\n errorType: typeToString(eType),\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'declared',\n rawTypeString: nodeType.getText(),\n };\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) return fromText;\n\n // Fallback: resolve the callee function's return type annotation\n const fromCallee = tryExtractFromCalleeReturnType(node);\n if (fromCallee) return fromCallee;\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 {\n successType: typeToString(aType),\n errorType: typeToString(eType),\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'inferred',\n rawTypeString: returnType.getText(),\n };\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 {\n successType: typeToString(aType),\n errorType: typeToString(eType),\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'inferred',\n rawTypeString: retType.getText(),\n };\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 { line, column } = sourceFile.getLineAndColumnAtPos(locationNode.getStart());\n const location: SourceLocation = {\n filePath: sourceFile.getFilePath(),\n line,\n column,\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 '.catchAll',\n '.catchTag',\n '.catchAllCause',\n '.catchIf',\n '.catchSome',\n '.catchSomeCause',\n '.catchSomeDefect',\n '.catchAllDefect',\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 'Effect', 'Layer', 'Stream', 'Queue', 'PubSub', 'Deferred', 'Semaphore',\n 'Mailbox', 'SubscriptionRef', 'Scope', 'Fiber', 'Runtime', 'ManagedRuntime', 'Cause', 'Exit',\n 'Data', 'Option', 'Either', 'Chunk', 'HashMap', 'HashSet', 'List',\n 'SortedMap', 'SortedSet', 'Match', 'Config', 'Schema', 'Schedule',\n 'Metric', 'Tracer', 'Logger', 'FiberRef', 'FiberHandle', 'FiberSet',\n 'FiberMap', 'Cache', 'ScopedCache', 'RateLimiter', 'Supervisor',\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 * Alias and module resolution for Effect: file-level alias caches,\n * barrel resolution, and Effect-like call detection.\n */\n\nimport { existsSync } from 'fs';\nimport { dirname, resolve, join, sep } from 'path';\nimport type { SourceFile, CallExpression, PropertyAccessExpression } from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\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\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 = dirname(currentFilePath);\n const resolved = resolve(baseDir, specifier);\n const candidates: string[] = [\n resolved,\n `${resolved}.ts`,\n `${resolved}.tsx`,\n `${resolved}.js`,\n `${resolved}.jsx`,\n join(resolved, 'index.ts'),\n join(resolved, 'index.tsx'),\n join(resolved, 'index.js'),\n join(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 baseDir = dirname(currentFilePath);\n const resolved = resolve(baseDir, specifier);\n const candidates: string[] = [\n resolved,\n `${resolved}.ts`,\n `${resolved}.tsx`,\n `${resolved}.js`,\n `${resolved}.jsx`,\n join(resolved, 'index.ts'),\n join(resolved, 'index.tsx'),\n join(resolved, 'index.js'),\n join(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 resolvedPath = resolve(dirname(currentFilePath), specifier);\n const normalizedResolved = resolve(resolvedPath);\n const normalizedRoot = resolve(knownEffectInternalsRoot);\n if (\n normalizedResolved === normalizedRoot ||\n normalizedResolved.startsWith(normalizedRoot + sep)\n ) {\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' || currentFilePath.endsWith(`${sep}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 if (reExported.size === 0) continue;\n const def = decl.getDefaultImport();\n if (def) {\n const text = def.getText();\n if (reExported.has(text)) names.add(text);\n }\n const ns = decl.getNamespaceImport();\n if (ns) {\n const text = ns.getText();\n if (reExported.has(text)) names.add(text);\n }\n for (const named of decl.getNamedImports()) {\n if (reExported.has(named.getName())) {\n names.add(named.getAliasNode()?.getText() ?? named.getName());\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 const nsImport = decl.getNamespaceImport();\n if (!nsImport) continue;\n const aliasName = nsImport.getText();\n const canonical = canonicalNamespaceFromSpecifier(specifier);\n map.set(aliasName, canonical);\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 * 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 result = reExported.has(named.getName());\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 Block,\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 as Block);\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.includes('.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 }\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.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 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.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 } from 'effect';\nimport type {\n SourceFile,\n Node,\n CallExpression,\n FunctionDeclaration,\n VariableDeclaration,\n ClassDeclaration,\n PropertyDeclaration,\n MethodDeclaration,\n GetAccessorDeclaration,\n StringLiteral,\n NumericLiteral,\n ParenthesizedExpression,\n ObjectLiteralExpression,\n PropertyAssignment,\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} 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 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 {\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: Date.now(),\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 args = (node as CallExpression).getArguments();\n if (args.length > 0 && args[0]) {\n const genFn = args[0];\n return yield* analyzeGeneratorFunction(\n genFn,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n }\n return [];\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 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.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.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 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 * Unwrap TypeScript expression wrappers: parenthesized, as, non-null, satisfies, type assertion.\n */\nfunction unwrapExpression(expr: Node): Node {\n const { SyntaxKind } = loadTsMorph();\n const kind = expr.getKind();\n switch (kind) {\n case SyntaxKind.ParenthesizedExpression:\n case SyntaxKind.AsExpression:\n case SyntaxKind.TypeAssertionExpression:\n case SyntaxKind.NonNullExpression:\n case SyntaxKind.SatisfiesExpression: {\n const inner = (expr as ParenthesizedExpression).getExpression();\n return unwrapExpression(inner);\n }\n default:\n return expr;\n }\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\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' } as StaticEffectNode;\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 /** 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 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-flow: intercept Step.* calls when enableEffectFlow is active\n const unwrappedExpr = unwrapExpression(expr);\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 expr,\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 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 || !containsGeneratorYield(expr)) {\n // return with no yield — skip (not interesting for the IR)\n return [];\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 ctx: WalkerContext = {\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n serviceScope,\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 // This intentionally includes calls nested inside yield* arguments — the existing\n // behavior produces additional entries for sub-expressions like Effect.provide()\n // inside pipe chains, which tests and downstream consumers rely on.\n const calls = body.getDescendantsOfKind(SyntaxKind.CallExpression);\n for (const call of calls) {\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 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\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 VariableDeclaration,\n ArrayLiteralExpression,\n NumericLiteral,\n StringLiteral,\n MethodDeclaration,\n ImportSpecifier,\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 StaticPipeNode,\n StaticParallelNode,\n StaticRaceNode,\n StaticErrorHandlerNode,\n StaticRetryNode,\n StaticTimeoutNode,\n StaticResourceNode,\n StaticConditionalNode,\n StaticLoopNode,\n StaticMatchNode,\n StaticCauseNode,\n StaticExitNode,\n StaticScheduleNode,\n StaticTransformNode,\n StaticLayerNode,\n StaticStreamNode,\n StaticChannelNode,\n StaticSinkNode,\n StaticConcurrencyPrimitiveNode,\n StaticFiberNode,\n StaticInterruptionNode,\n StaticUnknownNode,\n ConcurrencyMode,\n LayerLifecycle,\n StreamOperatorInfo,\n ChannelOperatorInfo,\n SinkOperatorInfo,\n ScheduleInfo,\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 getNodeText,\n computeDisplayName,\n computeSemanticRole,\n} from './analysis-utils';\nimport {\n ERROR_HANDLER_PATTERNS,\n CONDITIONAL_PATTERNS,\n COLLECTION_PATTERNS,\n FIBER_PATTERNS,\n INTERRUPTION_PATTERNS,\n TRANSFORM_OPS,\n EFFECTFUL_TRANSFORMS,\n isTransformCall,\n MATCH_OP_MAP,\n EXHAUSTIVE_OPS,\n isMatchCall,\n CAUSE_OP_MAP,\n CAUSE_CONSTRUCTORS,\n isCauseCall,\n EXIT_OP_MAP,\n EXIT_CONSTRUCTORS,\n isExitCall,\n SCHEDULE_OP_MAP,\n isScheduleCall,\n getSemanticDescriptionWithAliases,\n parseServiceIdsFromContextType,\n getNumericLiteralFromNode,\n BUILT_IN_TYPE_NAMES,\n KNOWN_EFFECT_NAMESPACES,\n} from './analysis-patterns';\nimport {\n getAliasesForFile,\n isEffectCallee,\n isEffectLikeCallExpression,\n normalizeEffectCallee,\n resolveBarrelSourceFile,\n resolveModulePath,\n} from './alias-resolution';\nexport const analyzePipeChain = (\n node: 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 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 );\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 );\n transformations.push(analyzed);\n }\n }\n\n // Extract type flow through pipe chain\n let typeFlow: EffectTypeSignature[] | undefined;\n 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 } catch {\n // Type extraction can fail; skip type flow\n }\n\n const pipeNode: StaticPipeNode = {\n id: generateId(),\n type: 'pipe',\n initial,\n transformations,\n ...(typeFlow ? { typeFlow } : {}),\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 // 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 unknownNode: StaticUnknownNode = {\n id: generateId(),\n type: 'unknown',\n reason: 'Function does not return an Effect expression',\n sourceCode: node.getText().slice(0, 100),\n location: extractLocation(node, filePath, opts.includeLocations ?? false),\n };\n stats.unknownCount++;\n return unknownNode;\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 if (isEffectCallee(text, getAliasesForFile(sourceFile), sourceFile)) {\n const effectNode: StaticEffectNode = {\n id: generateId(),\n type: 'effect',\n callee: text,\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\n // Default: unknown\n const unknownNode: StaticUnknownNode = {\n id: generateId(),\n type: 'unknown',\n reason: 'Could not determine effect type',\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 const callee = call.getExpression().getText();\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) inside generator → analyze as pipe chain so transformations (e.g. RcRef.update) are classified\n if (callee === 'pipe' && call.getArguments().length >= 1) {\n const nodes = yield* analyzePipeChain(\n call,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n if (nodes.length > 0 && nodes[0]) return nodes[0];\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 if (normalizedCallee.startsWith('Stream.')) {\n return yield* analyzeStreamCall(\n call,\n normalizedCallee,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\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 );\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 if (CONDITIONAL_PATTERNS.some((pattern) => callee.includes(pattern))) {\n return yield* analyzeConditionalCall(\n call,\n callee,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n }\n\n if (COLLECTION_PATTERNS.some((pattern) => callee.includes(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 const CONSTRUCTOR_CALLBACK_CALLEES = [\n 'Effect.sync',\n 'Effect.promise',\n 'Effect.async',\n 'Effect.asyncEffect',\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.async/asyncEffect: resume/canceller patterns (GAP async callback interop)\n if (callee.includes('Effect.async') || callee.includes('Effect.asyncEffect')) {\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 }\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('.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 const effectNode: StaticEffectNode = {\n id: generateId(),\n type: 'effect',\n callee,\n description: serviceCall ? 'service-call' : getSemanticDescriptionWithAliases(callee, getAliasesForFile(sourceFile)),\n location,\n jsdocDescription: effectJSDoc,\n jsdocTags: extractJSDocTags(call),\n typeSignature,\n requiredServices,\n serviceCall,\n serviceMethod,\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\n const firstSegment = objectName.split('.')[0] ?? objectName;\n if (KNOWN_EFFECT_NAMESPACES.has(firstSegment)) 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/** Return true if the call expression text (e.g. \"Layer.succeed\" or \"L.succeed\") is a Layer or Effect initializer. */\nfunction 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.) */\nfunction 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\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 // catchAll, 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 a tag name from an arg (Identifier or PropertyAccessExpression)\n const extractTagName = (node: Node): string | undefined => {\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];\n }\n return undefined;\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 const tag = extractTagName(args[0]);\n if (tag) provides.push(tag);\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 const depName = extractTagName(args[0]);\n if (depName) requiresSet.add(depName);\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 const depName = extractTagName(args[1]);\n if (depName) requiresSet.add(depName);\n // The provides of the composed layer come from base (args[0])\n const baseName = extractTagName(args[0]!);\n if (baseName) provides.push(baseName);\n }\n // Layer.provideService(tag, value) — provides a service inline\n if (callee.includes('provideService') && args.length > 0 && args[0]) {\n const tag = extractTagName(args[0]);\n if (tag) provides.push(tag);\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 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 } catch {\n // type extraction can fail\n }\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 'catchAll', 'catchAllCause', '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 const layerName = UTILITY_LAYER_OPS.has(layerOpName) ? `Layer.${layerOpName}` : undefined;\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/** Parse Stream.* call into StaticStreamNode (GAP 5). */\nfunction analyzeStreamCall(\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<StaticStreamNode, AnalysisError> {\n return Effect.gen(function* () {\n const args = call.getArguments();\n let source: StaticFlowNode;\n if (args.length > 0 && args[0]) {\n source = yield* 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: '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('catchAll') || 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 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 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/** Classify Channel.* operation (improve.md §8). */\nfunction channelOpCategory(op: string): ChannelOperatorInfo['category'] {\n if (op === 'fromReadableStream' || op === 'fromWritableStream' || op === 'fromDuplexStream' || op === 'make' || op === 'succeed' || op === 'fail' || op === 'empty' || op === 'never') return 'constructor';\n if (op.includes('map') || op.includes('flatMap') || op.includes('filter') || op.includes('concat') || op.includes('zip')) return 'transform';\n if (op.includes('pipe') || op === 'pipeTo' || op === 'pipeThrough') return 'pipe';\n return 'other';\n}\n\n/** Parse Channel.* call into StaticChannelNode (improve.md §8). */\nfunction analyzeChannelCall(\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* 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/** Classify Sink.* operation (improve.md §8). */\nfunction sinkOpCategory(op: string): SinkOperatorInfo['category'] {\n if (op === 'forEach' || op === 'forEachWhile' || op === 'run' || op === 'runDrain' || op === 'runFor' || op === 'make' || op === 'fromEffect' || op === 'fromQueue') return 'constructor';\n if (op.includes('map') || op.includes('contramap') || op.includes('filter') || op.includes('zip')) return 'transform';\n return 'other';\n}\n\n/** Parse Sink.* call into StaticSinkNode (improve.md §8). */\nfunction analyzeSinkCall(\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* 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/** Parse concurrency primitive (Queue, PubSub, Deferred, etc.) - GAP 6 */\nfunction 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 ((primitive === 'mailbox' && operation === 'toStream') ||\n (primitive === 'subscriptionRef' && operation === 'changes')) {\n const constructorType = 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 as StaticConcurrencyPrimitiveNode),\n semanticRole: computeSemanticRole(innerPrimNode as StaticConcurrencyPrimitiveNode),\n } as StaticConcurrencyPrimitiveNode,\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 } as StaticStreamNode);\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 */\nfunction analyzeFiberCall(\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 let operation: StaticFiberNode['operation'] = 'fork';\n let isScoped = false;\n let isDaemon = false;\n let fiberSource: StaticFlowNode | 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 ((operation === 'fork' || operation === 'forkScoped' || operation === 'forkDaemon' || operation === 'forkAll' || operation === 'forkIn' || operation === 'forkWithErrorHandler') && args.length > 0 && args[0]) {\n fiberSource = yield* analyzeEffectExpression(\n args[0],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\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 ...(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.) */\nfunction analyzeInterruptionCall(\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* analyzeEffectExpression(propAccess.getExpression(), sourceFile, filePath, opts, warnings, stats);\n if (args.length > 0 && args[0]) {\n handler = yield* analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n }\n } else if (args.length > 0 && args[0]) {\n source = yield* analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n if (args.length > 1 && args[1]) {\n handler = yield* 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/** Parse Effect.all options object: concurrency, batching, discard (GAP 18) */\nfunction 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)\n .getNameNode()\n .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\nconst analyzeParallelCall = (\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<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 = (\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 children.push(analyzed);\n }\n } else if (firstArg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const props = (\n firstArg as ObjectLiteralExpression\n ).getProperties();\n for (const prop of props) {\n if (prop.getKind() === SyntaxKind.PropertyAssignment) {\n const initializer = (\n prop as PropertyAssignment\n ).getInitializer();\n if (initializer) {\n const analyzed = yield* analyzeEffectExpression(\n initializer,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\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(\n args[1] as ObjectLiteralExpression,\n );\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\nconst analyzeRaceCall = (\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* 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\nconst analyzeErrorHandlerCall = (\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 let handlerType: StaticErrorHandlerNode['handlerType'];\n if (callee.includes('catchAllCause')) {\n handlerType = 'catchAllCause';\n } else if (callee.includes('catchSomeCause')) {\n handlerType = 'catchSomeCause';\n } else if (callee.includes('catchSomeDefect')) {\n handlerType = 'catchSomeDefect';\n } else if (callee.includes('catchAllDefect')) {\n handlerType = 'catchAllDefect';\n } else if (callee.includes('catchTags')) {\n handlerType = 'catchTags';\n } else if (callee.includes('catchIf')) {\n handlerType = 'catchIf';\n } else if (callee.includes('catchSome')) {\n handlerType = 'catchSome';\n } else if (callee.includes('catchTag')) {\n handlerType = 'catchTag';\n } else if (callee.includes('catchAll')) {\n handlerType = 'catchAll';\n } else if (callee.includes('orElseFail')) {\n handlerType = 'orElseFail';\n } else if (callee.includes('orElseSucceed')) {\n handlerType = 'orElseSucceed';\n } else if (callee.includes('orElse')) {\n handlerType = 'orElse';\n } else if (callee.includes('orDieWith')) {\n handlerType = 'orDieWith';\n } else if (callee.includes('orDie')) {\n handlerType = 'orDie';\n } else if (callee.includes('flip')) {\n handlerType = 'flip';\n } else if (callee.includes('mapErrorCause')) {\n handlerType = 'mapErrorCause';\n } else if (callee.includes('mapBoth')) {\n handlerType = 'mapBoth';\n } else if (callee.includes('mapError')) {\n handlerType = 'mapError';\n } else if (callee.includes('unsandbox')) {\n handlerType = 'unsandbox';\n } else if (callee.includes('sandbox')) {\n handlerType = 'sandbox';\n } else if (callee.includes('parallelErrors')) {\n handlerType = 'parallelErrors';\n } else if (callee.includes('filterOrDieMessage')) {\n handlerType = 'filterOrDieMessage';\n } else if (callee.includes('filterOrDie')) {\n handlerType = 'filterOrDie';\n } else if (callee.includes('filterOrElse')) {\n handlerType = 'filterOrElse';\n } else if (callee.includes('filterOrFail')) {\n handlerType = 'filterOrFail';\n } else if (callee.includes('matchCauseEffect')) {\n handlerType = 'matchCauseEffect';\n } else if (callee.includes('matchCause')) {\n handlerType = 'matchCause';\n } else if (callee.includes('matchEffect')) {\n handlerType = 'matchEffect';\n } else if (callee.includes('match')) {\n handlerType = 'match';\n } else if (callee.includes('firstSuccessOf')) {\n handlerType = 'firstSuccessOf';\n } else if (callee.includes('ignoreLogged')) {\n handlerType = 'ignoreLogged';\n } else if (callee.includes('ignore')) {\n handlerType = 'ignore';\n } else if (callee.includes('eventually')) {\n handlerType = 'eventually';\n } else {\n handlerType = 'catchAll';\n }\n\n // For methods that are called as effect.pipe(Effect.catchAll(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.catchAll(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* 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* 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* 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* 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) {\n const props = (objArg as ObjectLiteralExpression).getProperties();\n errorTags = props\n .filter((p) => p.getKind() === loadTsMorph().SyntaxKind.PropertyAssignment || p.getKind() === loadTsMorph().SyntaxKind.MethodDeclaration)\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 ? `on ${errorTag}` : errorTags && errorTags.length > 0 ? `on ${errorTags.join(' | ')}` : '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\nconst analyzeRetryCall = (\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 // Similar logic to error handlers for determining source\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* 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* 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* 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* 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\n/** Parse schedule expression text into ScheduleInfo (GAP 8). */\nfunction 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\nconst analyzeTimeoutCall = (\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* 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* 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\nconst analyzeResourceCall = (\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* analyzeEffectExpression(\n args[0],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n release = yield* analyzeEffectExpression(\n args[2],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n if (args[1]) {\n useEffect = yield* 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* analyzeEffectExpression(\n args[0],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n release = yield* 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* 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 = args.length > 0 && args[0]\n ? yield* 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* analyzeEffectExpression(\n exprSource,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n release =\n args.length > 0 && args[0]\n ? yield* 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* 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* 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\nconst analyzeConditionalCall = (\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 = (\n secondArg as ObjectLiteralExpression\n ).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* analyzeEffectExpression(\n init,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n } else if (name === 'onFalse') {\n onFalse = yield* 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* 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\nconst analyzeLoopCall = (\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\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; 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 ? 2\n : 1;\n\n let iterSource: string | undefined;\n let body: StaticFlowNode;\n\n if (args.length > 0 && args[0]) {\n iterSource = args[0].getText();\n }\n\n if (args.length > bodyArgIndex && args[bodyArgIndex]) {\n body = yield* analyzeEffectExpression(\n args[bodyArgIndex],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n } else {\n body = {\n id: generateId(),\n type: 'unknown',\n reason: 'Could not determine loop body',\n };\n }\n\n stats.loopCount++;\n\n const loopNode: StaticLoopNode = {\n id: generateId(),\n type: 'loop',\n loopType,\n iterSource,\n body,\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. */\nconst 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. */\nconst analyzeCauseCall = (\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* 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. */\nconst 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 Schedule.exponential / spaced / jittered / andThen / etc. (GAP 8 dedicated IR). */\nconst 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/** Analyze Effect.map / flatMap / andThen / tap / zip / as / flatten etc. */\nconst analyzeTransformCall = (\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* 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"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,aAAAE,KAAA,eAAAC,GAAAH,ICyBA,IAAAI,EAA+B,kBClB/B,IAAAC,EAA+B,kBA+wClBC,EAAN,cAA4B,KAAM,CAC9B,KACA,SAET,YACEC,EACAC,EACAC,EACA,CACA,MAAMD,CAAO,EACb,KAAK,KAAOD,EACZ,KAAK,SAAWE,EAChB,KAAK,KAAO,eACd,CACF,EAoUO,IAAMC,GACXC,GAC6C,CAC7C,OAAQA,EAAK,KAAM,CACjB,IAAK,UACH,OAAO,SAAO,KAAKA,EAAK,QAAQ,EAClC,IAAK,YACH,OAAO,SAAO,KAAKA,EAAK,OAAO,IAAKC,GAAMA,EAAE,MAAM,CAAC,EACrD,IAAK,OACH,OAAO,SAAO,KAAK,CAACD,EAAK,QAAS,GAAGA,EAAK,eAAe,CAAC,EAC5D,IAAK,WACL,IAAK,OACH,OAAO,SAAO,KAAK,CAAC,GAAGA,EAAK,QAAQ,CAAC,EACvC,IAAK,gBACH,OAAO,SAAO,KACZA,EAAK,QAAU,CAACA,EAAK,OAAQA,EAAK,OAAO,EAAI,CAACA,EAAK,MAAM,CAC3D,EACF,IAAK,QAAS,CACZ,IAAME,EAAYF,EACZG,EAAQ,CAACD,EAAU,OAAQA,EAAU,YAAY,EAAqC,OACzFE,GAA2BA,IAAM,MACpC,EACA,OAAOD,EAAK,OAAS,EAAI,SAAO,KAAKA,CAAI,EAAI,SAAO,KAAK,CAC3D,CAC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MAAM,GACtBA,EAAO,SAAS,KAAK,GACrBA,EAAO,SAAS,MAAM,GACtBA,EAAO,SAAS,OAAO,GACvBA,EAAO,SAAS,KAAK,GACrBA,EAAO,SAAS,MAAM,GACtBhB,EAAK,gBAEE,cAEF,aACT,CAEA,IAAK,YACL,IAAK,OACH,MAAO,cAET,IAAK,WACL,IAAK,OACL,IAAK,wBACH,MAAO,cAET,IAAK,gBACL,IAAK,QACL,IAAK,OACH,MAAO,gBAET,IAAK,QACL,IAAK,UACL,IAAK,WACH,MAAO,aAET,IAAK,WACH,MAAO,WAET,IAAK,cACL,IAAK,OACL,IAAK,QACL,IAAK,WACL,IAAK,SACL,IAAK,WACH,MAAO,eAET,IAAK,YACH,MAAO,gBAET,IAAK,SACH,MAAO,UAET,IAAK,QACH,MAAO,QAET,IAAK,SACL,IAAK,UACL,IAAK,OACH,MAAO,SAET,IAAK,QACL,IAAK,eACH,MAAO,QAET,IAAK,YACH,MAAO,YAET,IAAK,UACH,MAAO,SACX,CACF,CEzvBO,IAAM6F,GAAyB,CACpC,YACA,YACA,iBACA,WACA,aACA,kBACA,mBACA,kBACA,aACA,UACA,cACA,iBACA,SACA,aACA,QACA,YACA,iBACA,WACA,WACA,aACA,kBACA,eACA,sBACA,gBACA,gBACA,SACA,cACA,eACA,oBACA,kBACA,UACA,gBACA,aACF,EAEaC,GAAuB,CAClC,MACA,QACA,cACA,gBACA,WACA,UACA,gBACA,UACA,UACA,QACA,gBACF,EAEaC,GAAoB,CAC/B,kBACA,qBACA,YACA,gBACA,UACA,WACA,sBACA,wBACA,kBACA,SACA,mBACF,EAEaC,GAAsB,CACjC,WACA,QACA,UACA,aACA,aACA,UACA,eACA,eACA,gBACA,aACA,aACA,aACA,aACA,SACA,UACA,aACA,QACA,YACA,aACA,mBACA,eACA,iBACA,YACA,eACF,EAEaC,GAAiB,CAC5B,cACA,QACA,WACA,UACA,wBACA,QACF,EAMaC,GAAsE,CACjF,aAAc,MACd,iBAAkB,UAClB,iBAAk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OW,EACxB,OAAO,MAAOZ,GAAaC,CAAQ,EAAE,YAAY,CACnD,CAAC,EAAE,KAAK,SAAO,KAAK,CACxB,CACF,EDtPA,IAAMe,GAAmC,CAAE,qBAAsB,EAAK,EAKzDC,GAAU,CACrBC,EACAC,IAEAF,GAAYC,EAAU,CAAE,GAAGF,GAAiB,GAAGG,CAAQ,CAAC,EAE1DF,GAAQ,OAAS,CACfG,EACAD,IAEAF,GAAY,OAAOG,EAAM,CAAE,GAAGJ,GAAiB,GAAGG,CAAQ,CAAC","names":["effect_workflow_exports","__export","analyze","__toCommonJS","import_effect","import_effect","AnalysisError","code","message","location","getStaticChildren","node","y","retryNode","list","n","src","children","c","import_effect","import_node_module","import_meta","tsMorphModule","projectCache","loadTsMorph","createProject","tsConfigPath","cacheKey","cached","Project","options","project","createProjectFromSource","code","filePath","Project","loadTsMorph","import_effect","EFFECT_TYPE_REGEX_3","EFFECT_TYPE_REGEX_2","effectTypeSignatureFromTypeText","typeText","clean","match3","match2","extractEffectTypeSignature","node","_typeChecker","nodeType","isEffectType","typeArgs","extractTypeArguments","aType","eType","rType","typeToString","fromText","fromCallee","tryExtractFromCalleeReturnType","callee","callSignatures","returnType","returnArgs","returnText","fromReturnText","symbol","decl","returnTypeText","sigs","retType","retArgs","fromAnnotation","type","name","aliasSymbol","aliasName","aliasTypeArgs","extractServiceRequirements","requirements","locationNode","nodeTypeArgs","parent","varDecl","declaredType","extractRequirementsType","services","extractServicesFromContext","service","sourceFile","line","column","location","contextType","contextMatch","tagType","extractTagIdentifier","parts","splitTopLevelUnion","part","match","splitTopLevelUnion","typeText","parts","current","depth","inString","i","ch","last","cleanTypeArg","s","LAYER_TYPE_REGEX","extractLayerTypeSignature","node","typeText","match","LAYER_TYPE_REGEX","cleanTypeArg","DEFAULT_OPTIONS","idCounter","resetIdCounter","generateId","nodeTextCache","getNodeText","node","text","collectErrorTypes","nodes","set","visit","list","err","part","splitTopLevelUnion","children","getStaticChildren","collectDependencies","byName","reqs","r","callee","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","name","value","exampleStart","nextTagMatch","getJSDocFromParentVariable","parent","parentKind","isJsOrJsxPath","path","extractYieldVariableName","yieldNode","extractProgramName","getEnclosingVariableName","start","propertyName","containerName","ancestor","depth","extractEnclosingEffectFnName","callExpr","exprText","args","firstArg","createEmptyStats","truncate","s","max","computeDisplayName","variableName","prefix","parts","op","channelOps","sinkOps","computeSemanticRole","desc","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","getNumericLiteralFromNode","kind","n","unary","operand","v","import_fs","import_path","effectAliasCache","symbolResolutionCache","getNamesReExportedFromEffect","barrelSourceFile","out","decl","specifier","isEffectPackageSpecifier","EFFECT_NAMESPACE_NAMES","n","named","alias","resolveBarrelSourceFile","project","currentFilePath","baseDir","resolved","candidates","p","f","resolveModulePath","isSpecifierUnderKnownEffectInternalsRoot","knownEffectInternalsRoot","normalizedSpecifier","resolvedPath","normalizedResolved","normalizedRoot","getEffectImportNames","sourceFile","names","currentPath","def","ns","barrelFile","reExported","text","getEffectLikeNamespaceAliases","aliases","importDecl","moduleSpecifier","namespaceImport","aliasName","basename","KNOWN_INTERNAL_MODULES","NON_PROGRAM_EFFECT_MODULE_BASENAMES","getNonProgramEffectImportNames","getAliasesForFile","sf","effectSubmoduleAliasCache","canonicalNamespaceFromSpecifier","getEffectSubmoduleAliasMap","map","nsImport","canonical","normalizeEffectCallee","callee","dotIdx","rest","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","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","threshold","confidence","alias","extractServiceDefinitionsFromFile","results","typeChecker","extExpr","extText","typeArgs","inner","interfaceTypeNode","type","sym","propName","classText","hasCustomEquality","hasCustomHash","r","import_effect","import_effect","analyzePipeChain","node","sourceFile","filePath","opts","warnings","stats","SyntaxKind","loadTsMorph","args","expr","isMethodPipe","baseExpr","transformArgs","baseNode","resolveIdentifierToLayerInitializer","baseSourceFile","basePath","project","inProject","added","initial","analyzeEffectExpression","transformations","arg","analyzed","typeFlow","typeChecker","flow","initialSig","extractEffectTypeSignature","argNode","sig","pipeNode","generateId","computeDisplayName","computeSemanticRole","serviceScope","body","unknownNode","extractLocation","returnedExpr","stmt","analyzeEffectCall","text","operation","isEffectCallee","getAliasesForFile","effectNode","objLit","HANDLER_PROPS","props","handlerEntries","hasKnownHandler","prop","assignment","propName","initializer","call","callee","normalizedCallee","normalizeEffectCallee","calleeOperation","location","nodes","analyzeLayerCall","analyzeStreamCall","analyzeChannelCall","analyzeSinkCall","analyzeConcurrencyPrimitiveCall","FIBER_PATTERNS","p","analyzeFiberCall","INTERRUPTION_PATTERNS","analyzeInterruptionCall","analyzeParallelCall","analyzeRaceCall","ERROR_HANDLER_PATTERNS","pattern","analyzeErrorHandlerCall","analyzeRetryCall","analyzeTimeoutCall","resourceOps","resourceOpPrefixes","isResourceOp","op","baseCall","baseCallee","baseOperation","analyzeResourceCall","CONDITIONAL_PATTERNS","analyzeConditionalCall","COLLECTION_PATTERNS","analyzeLoopCall","isTransformCall","analyzeTransformCall","isMatchCall","analyzeMatchCall","isCauseCall","analyzeCauseCall","isExitCall","analyzeExitCall","isScheduleCall","analyzeScheduleCall","callbackBody","isConstructorWithCallback","c","asyncCallback","firstArg","fn","innerNodes","block","retExpr","isEffectLikeCallExpression","resumeParamName","resumeCallCount","visit","returnsCanceller","k","effectJSDoc","extractJSDocDescription","typeSignature","requiredServices","extractServiceRequirements","serviceCall","tryResolveServiceCall","serviceMethod","propAccess","objectText","methodName","serviceId","provideKind","contextArgText","constructorKind","fiberRefName","KNOWN_FIBER_REFS","refName","tracedName","strMatch","getSemanticDescriptionWithAliases","extractJSDocTags","_sourceFile","objExpr","objectName","firstSegment","KNOWN_EFFECT_NAMESPACES","type","symbol","typeName","BUILT_IN_TYPE_NAMES","isLayerOrEffectInitializerCallee","initCall","initText","srcFile","normalized","resolveLayerInitializerFromImport","ident","importSpec","isLayerInit","currentPath","specifier","targetFile","resolveBarrelSourceFile","resolvedPath","resolveModulePath","tryDecl","d","init","list","v","exportName","exported","decls","targetName","declList","resolveLayerInitializerFromDefaultImport","importDecl","name","sym","decl","fromDecls","sf","id","fromDefault","spec","n","fromImport","operations","elements","elem","toAnalyze","argSourceFile","isMerged","lifecycle","provides","extractTagName","pae","obj","tag","isProvideCall","requiresSet","depName","baseName","collectRequires","eff","req","calleeText","layer","r","getStaticChildren","layerSig","extractLayerTypeSignature","parseServiceIdsFromContextType","layerOpName","layerName","isMemoMap","layerNode","source","opName","constructorType","classifyOperator","isEffectful","opCategory","cardinality","windowSize","stride","getNumericLiteralFromNode","thisOp","sink","backpressureStrategy","effectiveSource","pipeline","effectiveConstructorType","srcStream","streamNode","channelOpCategory","srcChan","channelNode","sinkOpCategory","srcSink","sinkNode","_warnings","_stats","primitive","strategy","capacity","permitCount","first","lifecycleOptions","innerPrimNode","concurrencyNode","isScoped","isDaemon","fiberSource","scopeContext","parent","parentText","fiberNode","interruptionType","handler","interruptionNode","parseEffectAllOptions","optionsNode","concurrency","batching","discard","children","parsed","mode","branchLabels","child","parallelNode","raceLabels","raceNode","handlerType","exprSource","errorTag","errorTags","tagArg","objArg","a","handlerNode","schedule","scheduleNode","hasFallback","scheduleInfo","parseScheduleInfo","retryNode","scheduleText","t","baseStrategy","maxRetries","recursMatch","recurUpToMatch","jittered","conditions","duration","getNodeText","exprText","timeoutNode","resourceOperation","acquire","release","useEffect","resourceNode","conditionalType","condition","onTrue","onFalse","secondArg","propAssign","truncatedCondition","conditionalNode","loopType","bodyArgIndex","iterSource","loopNode","matchOp","MATCH_OP_MAP","isExhaustive","EXHAUSTIVE_OPS","matchedTags","arg0","matchNode","causeOp","CAUSE_OP_MAP","isConstructor","CAUSE_CONSTRUCTORS","childNodes","causeKind","childKinds","causeNode","exitOp","EXIT_OP_MAP","EXIT_CONSTRUCTORS","exitNode","scheduleOp","SCHEDULE_OP_MAP","transformType","TRANSFORM_OPS","EFFECTFUL_TRANSFORMS","fnText","transformNode","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","args","genFn","analyzeGeneratorFunction","analyzePipeChain","call","SyntaxKind","loadTsMorph","pipeResult","analyzeRunEntrypointExpression","callbackInArgs","arg","workflowBody","getWorkflowBodyNodeForRunCall","effect","analyzeEffectExpression","exprText","initializer","classDecl","callee","clause","clauseText","description","classEffectNode","extractJSDocDescription","body","SK","returnStatements","ret","expr","result","isFunctionBoundary","kind","containsGeneratorYield","found","child","extractLiteralValue","resolveConditionConsts","condition","constValues","resolved","name","value","pattern","replacement","simplifyBooleanExpression","unwrapExpression","inner","hasTerminatorStatement","stmts","last","collectYieldExpressionsDF","results","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","unwrappedExpr","stepResult","variableName","enrichedStep","computeDisplayName","computeSemanticRole","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","termNode","valueYields","k","unwrapped","exprKind","ternary","whenTrue","whenFalse","trueYields","falseYields","resolvedCond","binary","operatorToken","left","right","rightYields","yieldExprs","entry","serviceScope","yields","calls","aliases","getAliasesForFile","isEffectLikeCallExpression","analyzeEffectCall","generatorJSDoc","generatorNode","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","name","found","p","available","analyze","filePath","options","resetIdCounter","programsEffect","analyzeEffectFile","code","analyzeEffectSource","workflowOptions","analyze","filePath","options","code"]}
1
+ {"version":3,"sources":["../src/effect-workflow.ts","../src/analyze.ts","../src/types.ts","../src/static-analyzer.ts","../src/ts-morph-loader.ts","../src/analysis-utils.ts","../src/type-extractor.ts","../src/analysis-patterns.ts","../src/alias-resolution.ts","../src/program-discovery.ts","../src/core-analysis.ts","../src/effect-analysis.ts"],"sourcesContent":["/**\n * effect-workflow analyzer entrypoint\n *\n * Same API as the main analyzer but with effect-workflow patterns enabled\n * (Workflow.make / Workflow.run). Use this when analyzing code that uses\n * the effect-workflow library.\n *\n * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { analyze } from \"effect-analyzer/effect-workflow\";\n *\n * const ir = await Effect.runPromise(\n * analyze.source(source).named(\"runCheckout\")\n * );\n * ```\n */\n\nimport { analyze as baseAnalyze } from './analyze';\nimport type { AnalyzerOptions } from './types';\n\nconst workflowOptions: AnalyzerOptions = { enableEffectWorkflow: true };\n\n/**\n * Analyze a file with effect-workflow patterns enabled (Workflow.make / Workflow.run).\n */\nexport const analyze = (\n filePath: string,\n options?: AnalyzerOptions,\n): ReturnType<typeof baseAnalyze> =>\n baseAnalyze(filePath, { ...workflowOptions, ...options });\n\nanalyze.source = (\n code: string,\n options?: AnalyzerOptions,\n): ReturnType<typeof baseAnalyze.source> =>\n baseAnalyze.source(code, { ...workflowOptions, ...options });\n\nexport type { AnalyzeResult } from './analyze';\nexport type { StaticEffectIR, AnalyzerOptions } from './types';\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 * @example\n * ```typescript\n * import { Effect } from \"effect\";\n * import { analyze } from \"effect-analyzer\";\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 { 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: () =>\n 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 ),\n );\n }),\n\n singleOption: () =>\n 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: () =>\n 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: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).single();\n }),\n\n singleOption: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).first();\n }),\n\n firstOption: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).single();\n }),\n\n singleOption: () =>\n 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: () =>\n Effect.gen(function* () {\n const programs = yield* programsEffect;\n return yield* createResult(programs).first();\n }),\n\n firstOption: () =>\n 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\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}\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}\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 /** Inner effects from Effect.sync/promise/async callback body (one level only) */\n readonly callbackBody?: readonly StaticFlowNode[] | undefined;\n /** Effect.async/asyncEffect only: resume/canceller callback patterns (GAP async callback interop). */\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' | '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 (catchAll, catchTag, orElse, etc.).\n */\nexport interface StaticErrorHandlerNode extends StaticBaseNode {\n readonly type: 'error-handler';\n /** Type of handler: catchAll, catchTag, orElse, etc. */\n readonly handlerType:\n | 'catchAll'\n | 'catchTag'\n | 'catchAllCause'\n | 'catchIf'\n | 'catchSome'\n | 'catchSomeCause'\n | 'catchSomeDefect'\n | 'catchAllDefect'\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 /** 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 /** 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 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';\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}\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 * Dynamic ts-morph loader to avoid direct dependency issues\n */\n\nimport { createRequire } from 'node:module';\nimport type { Project, SourceFile } from 'ts-morph';\n\nlet tsMorphModule: typeof import('ts-morph') | null = null;\nconst projectCache = new Map<string, Project>();\n\n/**\n * Load ts-morph dynamically (peer dependency)\n */\nexport const loadTsMorph = (): typeof import('ts-morph') => {\n if (!tsMorphModule) {\n try {\n const require = createRequire(import.meta.url);\n tsMorphModule = require('ts-morph');\n } catch {\n throw new Error(\n 'ts-morph is required but not installed. Please install it as a peer dependency: npm install ts-morph',\n );\n }\n }\n return tsMorphModule!;\n};\n\n/**\n * Create a ts-morph project\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\n/**\n * Clear cached ts-morph projects.\n */\nexport const clearProjectCache = (): void => {\n projectCache.clear();\n};\n\n/**\n * Create a project from source code (for testing)\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 * 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\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 (!byName.has(r.serviceId)) {\n byName.set(r.serviceId, {\n name: r.serviceId,\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 const looksLikeService = /^[A-Z]/.test(callee)\n && !callee.startsWith('Effect.')\n && !callee.startsWith('Schema.')\n && !callee.startsWith('Data.')\n && !callee.startsWith('Config.')\n && !callee.startsWith('Command.')\n && !callee.startsWith('Stream.')\n && !callee.startsWith('Option.')\n && !callee.startsWith('Either.')\n && !callee.startsWith('Cause.')\n && !callee.startsWith('Exit.');\n if (looksLikeService && !byName.has(callee)) {\n byName.set(callee, {\n name: callee,\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 };\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';\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 * 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 (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 * 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) 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 * 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 in Effect v3) */\nconst EFFECT_TYPE_REGEX_2 = /Effect(?:\\.Effect)?<([^,>]+),\\s*([^,>]+)>/;\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 in Effect v3)\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 {\n successType: typeToString(aType),\n errorType: resolved.errorType,\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'inferred',\n rawTypeString: nodeType.getText(),\n };\n }\n }\n\n return {\n successType: typeToString(aType),\n errorType: errorTypeStr,\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'declared',\n rawTypeString: nodeType.getText(),\n };\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 fromText;\n }\n\n // Fallback: resolve the callee function's return type annotation\n const fromCallee = tryExtractFromCalleeReturnType(node);\n if (fromCallee) return fromCallee;\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 {\n successType: typeToString(aType),\n errorType: typeToString(eType),\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'inferred',\n rawTypeString: returnType.getText(),\n };\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 {\n successType: typeToString(aType),\n errorType: typeToString(eType),\n requirementsType: typeToString(rType),\n isInferred: true,\n typeConfidence: 'inferred',\n rawTypeString: retType.getText(),\n };\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 { line, column } = sourceFile.getLineAndColumnAtPos(locationNode.getStart());\n const location: SourceLocation = {\n filePath: sourceFile.getFilePath(),\n line,\n column,\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 '.catchAll',\n '.catchTag',\n '.catchAllCause',\n '.catchIf',\n '.catchSome',\n '.catchSomeCause',\n '.catchSomeDefect',\n '.catchAllDefect',\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 'Effect', 'Layer', 'Stream', 'Queue', 'PubSub', 'Deferred', 'Semaphore',\n 'Mailbox', 'SubscriptionRef', 'Scope', 'Fiber', 'Runtime', 'ManagedRuntime', 'Cause', 'Exit',\n 'Data', 'Option', 'Either', 'Chunk', 'HashMap', 'HashSet', 'List',\n 'SortedMap', 'SortedSet', 'Match', 'Config', 'Schema', 'Schedule',\n 'Metric', 'Tracer', 'Logger', 'FiberRef', 'FiberHandle', 'FiberSet',\n 'FiberMap', 'Cache', 'ScopedCache', 'RateLimiter', 'Supervisor',\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 * Alias and module resolution for Effect: file-level alias caches,\n * barrel resolution, and Effect-like call detection.\n */\n\nimport { existsSync } from 'fs';\nimport { dirname, resolve, join, sep } from 'path';\nimport type { SourceFile, CallExpression, PropertyAccessExpression } from 'ts-morph';\nimport { loadTsMorph } from './ts-morph-loader';\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\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 = dirname(currentFilePath);\n const resolved = resolve(baseDir, specifier);\n const candidates: string[] = [\n resolved,\n `${resolved}.ts`,\n `${resolved}.tsx`,\n `${resolved}.js`,\n `${resolved}.jsx`,\n join(resolved, 'index.ts'),\n join(resolved, 'index.tsx'),\n join(resolved, 'index.js'),\n join(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 baseDir = dirname(currentFilePath);\n const resolved = resolve(baseDir, specifier);\n const candidates: string[] = [\n resolved,\n `${resolved}.ts`,\n `${resolved}.tsx`,\n `${resolved}.js`,\n `${resolved}.jsx`,\n join(resolved, 'index.ts'),\n join(resolved, 'index.tsx'),\n join(resolved, 'index.js'),\n join(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 resolvedPath = resolve(dirname(currentFilePath), specifier);\n const normalizedResolved = resolve(resolvedPath);\n const normalizedRoot = resolve(knownEffectInternalsRoot);\n if (\n normalizedResolved === normalizedRoot ||\n normalizedResolved.startsWith(normalizedRoot + sep)\n ) {\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' || currentFilePath.endsWith(`${sep}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 const nsImport = decl.getNamespaceImport();\n if (!nsImport) continue;\n const aliasName = nsImport.getText();\n const canonical = canonicalNamespaceFromSpecifier(specifier);\n map.set(aliasName, canonical);\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 Block,\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 as Block);\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 }\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.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 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.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 } from 'effect';\nimport type {\n SourceFile,\n Node,\n CallExpression,\n FunctionDeclaration,\n VariableDeclaration,\n ClassDeclaration,\n PropertyDeclaration,\n MethodDeclaration,\n GetAccessorDeclaration,\n StringLiteral,\n NumericLiteral,\n ParenthesizedExpression,\n ObjectLiteralExpression,\n PropertyAssignment,\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} 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 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 {\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: Date.now(),\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 args = (node as CallExpression).getArguments();\n if (args.length > 0 && args[0]) {\n const genFn = args[0];\n return yield* analyzeGeneratorFunction(\n genFn,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n }\n return [];\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 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.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.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 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 * Unwrap TypeScript expression wrappers: parenthesized, as, non-null, satisfies, type assertion.\n */\nfunction unwrapExpression(expr: Node): Node {\n const { SyntaxKind } = loadTsMorph();\n const kind = expr.getKind();\n switch (kind) {\n case SyntaxKind.ParenthesizedExpression:\n case SyntaxKind.AsExpression:\n case SyntaxKind.TypeAssertionExpression:\n case SyntaxKind.NonNullExpression:\n case SyntaxKind.SatisfiesExpression: {\n const inner = (expr as ParenthesizedExpression).getExpression();\n return unwrapExpression(inner);\n }\n default:\n return expr;\n }\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\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' } as StaticEffectNode;\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 /** 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 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-flow: intercept Step.* calls when enableEffectFlow is active\n const unwrappedExpr = unwrapExpression(expr);\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 expr,\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 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 || !containsGeneratorYield(expr)) {\n // return with no yield — skip (not interesting for the IR)\n return [];\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 ctx: WalkerContext = {\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n serviceScope,\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 // This intentionally includes calls nested inside yield* arguments — the existing\n // behavior produces additional entries for sub-expressions like Effect.provide()\n // inside pipe chains, which tests and downstream consumers rely on.\n const calls = body.getDescendantsOfKind(SyntaxKind.CallExpression);\n for (const call of calls) {\n // Skip Effect.withSpan calls — they are merged as annotations on pipe nodes\n const callCallee = call.getExpression().getText();\n if (callCallee.includes('withSpan')) continue;\n\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 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\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 VariableDeclaration,\n ArrayLiteralExpression,\n NumericLiteral,\n StringLiteral,\n MethodDeclaration,\n ImportSpecifier,\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 StaticPipeNode,\n StaticParallelNode,\n StaticRaceNode,\n StaticErrorHandlerNode,\n StaticRetryNode,\n StaticTimeoutNode,\n StaticResourceNode,\n StaticConditionalNode,\n StaticLoopNode,\n StaticMatchNode,\n StaticCauseNode,\n StaticExitNode,\n StaticScheduleNode,\n StaticTransformNode,\n StaticLayerNode,\n StaticStreamNode,\n StaticChannelNode,\n StaticSinkNode,\n StaticConcurrencyPrimitiveNode,\n StaticFiberNode,\n StaticInterruptionNode,\n StaticUnknownNode,\n ConcurrencyMode,\n LayerLifecycle,\n StreamOperatorInfo,\n ChannelOperatorInfo,\n SinkOperatorInfo,\n ScheduleInfo,\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 getNodeText,\n computeDisplayName,\n computeSemanticRole,\n} from './analysis-utils';\nimport {\n ERROR_HANDLER_PATTERNS,\n CONDITIONAL_PATTERNS,\n COLLECTION_PATTERNS,\n FIBER_PATTERNS,\n INTERRUPTION_PATTERNS,\n TRANSFORM_OPS,\n EFFECTFUL_TRANSFORMS,\n isTransformCall,\n MATCH_OP_MAP,\n EXHAUSTIVE_OPS,\n isMatchCall,\n CAUSE_OP_MAP,\n CAUSE_CONSTRUCTORS,\n isCauseCall,\n EXIT_OP_MAP,\n EXIT_CONSTRUCTORS,\n isExitCall,\n SCHEDULE_OP_MAP,\n isScheduleCall,\n getSemanticDescriptionWithAliases,\n parseServiceIdsFromContextType,\n getNumericLiteralFromNode,\n BUILT_IN_TYPE_NAMES,\n KNOWN_EFFECT_NAMESPACES,\n} from './analysis-patterns';\nimport {\n getAliasesForFile,\n isEffectCallee,\n isEffectLikeCallExpression,\n normalizeEffectCallee,\n resolveBarrelSourceFile,\n resolveModulePath,\n} from './alias-resolution';\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\nexport const analyzePipeChain = (\n node: 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 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 );\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 );\n transformations.push(analyzed);\n }\n }\n\n // Detect Effect.withSpan in transformations and merge as annotation\n let spanName: string | undefined;\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 if (!spanName) {\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 spanName = match[1];\n }\n }\n }\n }\n }\n\n // Extract type flow through pipe chain\n let typeFlow: EffectTypeSignature[] | undefined;\n 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 } catch {\n // Type extraction can fail; skip type flow\n }\n\n const pipeNode: StaticPipeNode = {\n id: generateId(),\n type: 'pipe',\n initial,\n transformations: filteredTransformations,\n ...(typeFlow ? { typeFlow } : {}),\n ...(spanName ? { spanName } : {}),\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 // 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 unknownNode: StaticUnknownNode = {\n id: generateId(),\n type: 'unknown',\n reason: 'Function does not return an Effect expression',\n sourceCode: node.getText().slice(0, 100),\n location: extractLocation(node, filePath, opts.includeLocations ?? false),\n };\n stats.unknownCount++;\n return unknownNode;\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 if (isEffectCallee(text, getAliasesForFile(sourceFile), sourceFile)) {\n const effectNode: StaticEffectNode = {\n id: generateId(),\n type: 'effect',\n callee: text,\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\n // Default: unknown\n const unknownNode: StaticUnknownNode = {\n id: generateId(),\n type: 'unknown',\n reason: 'Could not determine effect type',\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 const callee = call.getExpression().getText();\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 Effect.*.pipe(...fns) inside generator → analyze as pipe chain so transformations (e.g. RcRef.update) are classified\n // For method-style .pipe(), only route Effect-based pipes (not Schedule, Stream, etc.)\n const isEffectMethodPipe =\n callee.endsWith('.pipe') &&\n callee !== 'pipe' &&\n callee.startsWith('Effect.');\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 );\n if (nodes.length > 0 && nodes[0]) return nodes[0];\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 if (normalizedCallee.startsWith('Stream.')) {\n return yield* analyzeStreamCall(\n call,\n normalizedCallee,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\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 );\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 const CONSTRUCTOR_CALLBACK_CALLEES = [\n 'Effect.sync',\n 'Effect.promise',\n 'Effect.async',\n 'Effect.asyncEffect',\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.async/asyncEffect: resume/canceller patterns (GAP async callback interop)\n if (callee.includes('Effect.async') || callee.includes('Effect.asyncEffect')) {\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 }\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('.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 const effectNode: StaticEffectNode = {\n id: generateId(),\n type: 'effect',\n callee,\n description: serviceCall ? 'service-call' : getSemanticDescriptionWithAliases(callee, getAliasesForFile(sourceFile)),\n location,\n jsdocDescription: effectJSDoc,\n jsdocTags: extractJSDocTags(call),\n typeSignature,\n requiredServices,\n serviceCall,\n serviceMethod,\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\n const firstSegment = objectName.split('.')[0] ?? objectName;\n if (KNOWN_EFFECT_NAMESPACES.has(firstSegment)) 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/** Return true if the call expression text (e.g. \"Layer.succeed\" or \"L.succeed\") is a Layer or Effect initializer. */\nfunction 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.) */\nfunction 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\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 // catchAll, 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 a tag name from an arg (Identifier or PropertyAccessExpression)\n const extractTagName = (node: Node): string | undefined => {\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];\n }\n return undefined;\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 const tag = extractTagName(args[0]);\n if (tag) provides.push(tag);\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 const depName = extractTagName(args[0]);\n if (depName) requiresSet.add(depName);\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 const depName = extractTagName(args[1]);\n if (depName) requiresSet.add(depName);\n // The provides of the composed layer come from base (args[0])\n const baseName = extractTagName(args[0]!);\n if (baseName) provides.push(baseName);\n }\n // Layer.provideService(tag, value) — provides a service inline\n if (callee.includes('provideService') && args.length > 0 && args[0]) {\n const tag = extractTagName(args[0]);\n if (tag) provides.push(tag);\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 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 } catch {\n // type extraction can fail\n }\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 'catchAll', 'catchAllCause', '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 const layerName = UTILITY_LAYER_OPS.has(layerOpName) ? `Layer.${layerOpName}` : undefined;\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/** Parse Stream.* call into StaticStreamNode (GAP 5). */\nfunction analyzeStreamCall(\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<StaticStreamNode, AnalysisError> {\n return Effect.gen(function* () {\n const args = call.getArguments();\n let source: StaticFlowNode;\n if (args.length > 0 && args[0]) {\n source = yield* 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: '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('catchAll') || 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 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 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/** Classify Channel.* operation (improve.md §8). */\nfunction channelOpCategory(op: string): ChannelOperatorInfo['category'] {\n if (op === 'fromReadableStream' || op === 'fromWritableStream' || op === 'fromDuplexStream' || op === 'make' || op === 'succeed' || op === 'fail' || op === 'empty' || op === 'never') return 'constructor';\n if (op.includes('map') || op.includes('flatMap') || op.includes('filter') || op.includes('concat') || op.includes('zip')) return 'transform';\n if (op.includes('pipe') || op === 'pipeTo' || op === 'pipeThrough') return 'pipe';\n return 'other';\n}\n\n/** Parse Channel.* call into StaticChannelNode (improve.md §8). */\nfunction analyzeChannelCall(\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* 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/** Classify Sink.* operation (improve.md §8). */\nfunction sinkOpCategory(op: string): SinkOperatorInfo['category'] {\n if (op === 'forEach' || op === 'forEachWhile' || op === 'run' || op === 'runDrain' || op === 'runFor' || op === 'make' || op === 'fromEffect' || op === 'fromQueue') return 'constructor';\n if (op.includes('map') || op.includes('contramap') || op.includes('filter') || op.includes('zip')) return 'transform';\n return 'other';\n}\n\n/** Parse Sink.* call into StaticSinkNode (improve.md §8). */\nfunction analyzeSinkCall(\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* 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/** Parse concurrency primitive (Queue, PubSub, Deferred, etc.) - GAP 6 */\nfunction 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 ((primitive === 'mailbox' && operation === 'toStream') ||\n (primitive === 'subscriptionRef' && operation === 'changes')) {\n const constructorType = 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 as StaticConcurrencyPrimitiveNode),\n semanticRole: computeSemanticRole(innerPrimNode as StaticConcurrencyPrimitiveNode),\n } as StaticConcurrencyPrimitiveNode,\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 } as StaticStreamNode);\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 */\nfunction analyzeFiberCall(\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 let operation: StaticFiberNode['operation'] = 'fork';\n let isScoped = false;\n let isDaemon = false;\n let fiberSource: StaticFlowNode | 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 ((operation === 'fork' || operation === 'forkScoped' || operation === 'forkDaemon' || operation === 'forkAll' || operation === 'forkIn' || operation === 'forkWithErrorHandler') && args.length > 0 && args[0]) {\n fiberSource = yield* analyzeEffectExpression(\n args[0],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\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 ...(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.) */\nfunction analyzeInterruptionCall(\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* analyzeEffectExpression(propAccess.getExpression(), sourceFile, filePath, opts, warnings, stats);\n if (args.length > 0 && args[0]) {\n handler = yield* analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n }\n } else if (args.length > 0 && args[0]) {\n source = yield* analyzeEffectExpression(args[0], sourceFile, filePath, opts, warnings, stats);\n if (args.length > 1 && args[1]) {\n handler = yield* 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/** Parse Effect.all options object: concurrency, batching, discard (GAP 18) */\nfunction 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)\n .getNameNode()\n .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\nconst analyzeParallelCall = (\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<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 = (\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 children.push(analyzed);\n }\n } else if (firstArg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const props = (\n firstArg as ObjectLiteralExpression\n ).getProperties();\n for (const prop of props) {\n if (prop.getKind() === SyntaxKind.PropertyAssignment) {\n const initializer = (\n prop as PropertyAssignment\n ).getInitializer();\n if (initializer) {\n const analyzed = yield* analyzeEffectExpression(\n initializer,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\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(\n args[1] as ObjectLiteralExpression,\n );\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\nconst analyzeRaceCall = (\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* 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\nconst analyzeErrorHandlerCall = (\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 let handlerType: StaticErrorHandlerNode['handlerType'];\n if (callee.includes('catchAllCause')) {\n handlerType = 'catchAllCause';\n } else if (callee.includes('catchSomeCause')) {\n handlerType = 'catchSomeCause';\n } else if (callee.includes('catchSomeDefect')) {\n handlerType = 'catchSomeDefect';\n } else if (callee.includes('catchAllDefect')) {\n handlerType = 'catchAllDefect';\n } else if (callee.includes('catchTags')) {\n handlerType = 'catchTags';\n } else if (callee.includes('catchIf')) {\n handlerType = 'catchIf';\n } else if (callee.includes('catchSome')) {\n handlerType = 'catchSome';\n } else if (callee.includes('catchTag')) {\n handlerType = 'catchTag';\n } else if (callee.includes('catchAll')) {\n handlerType = 'catchAll';\n } else if (callee.includes('orElseFail')) {\n handlerType = 'orElseFail';\n } else if (callee.includes('orElseSucceed')) {\n handlerType = 'orElseSucceed';\n } else if (callee.includes('orElse')) {\n handlerType = 'orElse';\n } else if (callee.includes('orDieWith')) {\n handlerType = 'orDieWith';\n } else if (callee.includes('orDie')) {\n handlerType = 'orDie';\n } else if (callee.includes('flip')) {\n handlerType = 'flip';\n } else if (callee.includes('mapErrorCause')) {\n handlerType = 'mapErrorCause';\n } else if (callee.includes('mapBoth')) {\n handlerType = 'mapBoth';\n } else if (callee.includes('mapError')) {\n handlerType = 'mapError';\n } else if (callee.includes('unsandbox')) {\n handlerType = 'unsandbox';\n } else if (callee.includes('sandbox')) {\n handlerType = 'sandbox';\n } else if (callee.includes('parallelErrors')) {\n handlerType = 'parallelErrors';\n } else if (callee.includes('filterOrDieMessage')) {\n handlerType = 'filterOrDieMessage';\n } else if (callee.includes('filterOrDie')) {\n handlerType = 'filterOrDie';\n } else if (callee.includes('filterOrElse')) {\n handlerType = 'filterOrElse';\n } else if (callee.includes('filterOrFail')) {\n handlerType = 'filterOrFail';\n } else if (callee.includes('matchCauseEffect')) {\n handlerType = 'matchCauseEffect';\n } else if (callee.includes('matchCause')) {\n handlerType = 'matchCause';\n } else if (callee.includes('matchEffect')) {\n handlerType = 'matchEffect';\n } else if (callee.includes('match')) {\n handlerType = 'match';\n } else if (callee.includes('firstSuccessOf')) {\n handlerType = 'firstSuccessOf';\n } else if (callee.includes('ignoreLogged')) {\n handlerType = 'ignoreLogged';\n } else if (callee.includes('ignore')) {\n handlerType = 'ignore';\n } else if (callee.includes('eventually')) {\n handlerType = 'eventually';\n } else {\n handlerType = 'catchAll';\n }\n\n // For methods that are called as effect.pipe(Effect.catchAll(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.catchAll(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* 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* 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* 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* 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) {\n const props = (objArg as ObjectLiteralExpression).getProperties();\n errorTags = props\n .filter((p) => p.getKind() === loadTsMorph().SyntaxKind.PropertyAssignment || p.getKind() === loadTsMorph().SyntaxKind.MethodDeclaration)\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 ? `on ${errorTag}` : errorTags && errorTags.length > 0 ? `on ${errorTags.join(' | ')}` : '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\nconst analyzeRetryCall = (\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 // Similar logic to error handlers for determining source\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* 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* 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* 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* 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\n/** Parse schedule expression text into ScheduleInfo (GAP 8). */\nfunction 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\nconst analyzeTimeoutCall = (\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* 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* 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\nconst analyzeResourceCall = (\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* analyzeEffectExpression(\n args[0],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n release = yield* analyzeEffectExpression(\n args[2],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n if (args[1]) {\n useEffect = yield* 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* analyzeEffectExpression(\n args[0],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n release = yield* 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* 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 = args.length > 0 && args[0]\n ? yield* 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* analyzeEffectExpression(\n exprSource,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n release =\n args.length > 0 && args[0]\n ? yield* 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* 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* 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\nconst analyzeConditionalCall = (\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 = (\n secondArg as ObjectLiteralExpression\n ).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* analyzeEffectExpression(\n init,\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n } else if (name === 'onFalse') {\n onFalse = yield* 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* 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\nconst analyzeLoopCall = (\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\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; 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 ? 2\n : 1;\n\n let iterSource: string | undefined;\n let body: StaticFlowNode;\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 body = yield* analyzeEffectExpression(\n args[bodyArgIndex],\n sourceFile,\n filePath,\n opts,\n warnings,\n stats,\n );\n } else {\n body = {\n id: generateId(),\n type: 'unknown',\n reason: 'Could not determine loop body',\n };\n }\n\n stats.loopCount++;\n\n const loopNode: StaticLoopNode = {\n id: generateId(),\n type: 'loop',\n loopType,\n iterSource,\n body,\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. */\nconst 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. */\nconst analyzeCauseCall = (\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* 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. */\nconst 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 Schedule.exponential / spaced / jittered / andThen / etc. (GAP 8 dedicated IR). */\nconst 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/** Analyze Effect.map / flatMap / andThen / tap / zip / as / flatten etc. */\nconst analyzeTransformCall = (\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* 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"],"mappings":"ubAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,aAAAE,KAAA,eAAAC,GAAAH,ICyBA,IAAAI,EAA+B,kBClB/B,IAAAC,EAA+B,kBAixClBC,EAAN,cAA4B,KAAM,CAC9B,KACA,SAET,YACEC,EACAC,EACAC,EACA,CACA,MAAMD,CAAO,EACb,KAAK,KAAOD,EACZ,KAAK,SAAWE,EAChB,KAAK,KAAO,eACd,CACF,EAoUO,IAAMC,GACXC,GAC6C,CAC7C,OAAQA,EAAK,KAAM,CACjB,IAAK,UACH,OAAO,SAAO,KAAKA,EAAK,QAAQ,EAClC,IAAK,YACH,OAAO,SAAO,KAAKA,EAAK,OAAO,IAAKC,GAAMA,EAAE,MAAM,CAAC,EACrD,IAAK,OACH,OAAO,SAAO,KAAK,CAACD,EAAK,QAAS,GAAGA,EAAK,eAAe,CAAC,EAC5D,IAAK,WACL,IAAK,OACH,OAAO,SAAO,KAAK,CAAC,GAAGA,EAAK,QAAQ,CAAC,EACvC,IAAK,gBACH,OAAO,SAAO,KACZA,EAAK,QAAU,CAACA,EAAK,OAAQA,EAAK,OAAO,EAAI,CAACA,EAAK,MAAM,CAC3D,EACF,IAAK,QAAS,CACZ,IAAME,EAAYF,EACZG,EAAQ,CAACD,EAAU,OAAQA,EAAU,YAAY,EAAqC,OACzFE,GAA2BA,IAAM,MACpC,EACA,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AO,KAAK,EAEtB,IAAK,IAAMW,EAEX,MAAQR,GACN,SAAO,IAAI,WAAa,CACtB,IAAMH,EAAW,MAAOW,EACxB,OAAO,MAAOZ,GAAaC,CAAQ,EAAE,MAAMG,CAAI,CACjD,CAAC,EAEH,MAAO,IACL,SAAO,IAAI,WAAa,CACtB,IAAMH,EAAW,MAAOW,EACxB,OAAO,MAAOZ,GAAaC,CAAQ,EAAE,MAAM,CAC7C,CAAC,EAEH,YAAa,IACX,SAAO,IAAI,WAAa,CACtB,IAAMA,EAAW,MAAOW,EACxB,OAAO,MAAOZ,GAAaC,CAAQ,EAAE,YAAY,CACnD,CAAC,EAAE,KAAK,SAAO,KAAK,CACxB,CACF,EDtPA,IAAMe,GAAmC,CAAE,qBAAsB,EAAK,EAKzDC,GAAU,CACrBC,EACAC,IAEAF,GAAYC,EAAU,CAAE,GAAGF,GAAiB,GAAGG,CAAQ,CAAC,EAE1DF,GAAQ,OAAS,CACfG,EACAD,IAEAF,GAAY,OAAOG,EAAM,CAAE,GAAGJ,GAAiB,GAAGG,CAAQ,CAAC","names":["effect_workflow_exports","__export","analyze","__toCommonJS","import_effect","import_effect","AnalysisError","code","message","location","getStaticChildren","node","y","retryNode","list","n","src","children","c","import_effect","import_node_module","import_meta","tsMorphModule","projectCache","loadTsMorph","createProject","tsConfigPath","cacheKey","cached","Project","options","project","createProjectFromSource","code","filePath","Project","loadTsMorph","import_effect","EFFECT_TYPE_REGEX_3","EFFECT_TYPE_REGEX_2","effectTypeSignatureFromTypeText","typeText","clean","match3","match2","tryResolveGenericFromInnerExpression","node","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","symbol","decl","returnTypeText","sigs","retType","retArgs","fromAnnotation","type","name","aliasSymbol","aliasName","aliasTypeArgs","extractServiceRequirements","requirements","locationNode","nodeTypeArgs","parent","varDecl","declaredType","extractRequirementsType","services","extractServicesFromContext","service","sourceFile","line","column","location","contextType","contextMatch","tagType","extractTagIdentifier","parts","splitTopLevelUnion","part","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","getNumericLiteralFromNode","kind","n","unary","operand","v","DEFAULT_OPTIONS","idCounter","resetIdCounter","generateId","nodeTextCache","getNodeText","node","text","collectErrorTypes","nodes","set","visit","list","err","part","splitTopLevelUnion","children","getStaticChildren","collectDependencies","byName","reqs","r","callee","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","name","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","withoutArgs","parts","receiver","KNOWN_EFFECT_NAMESPACES","BUILT_IN_TYPE_NAMES","computeDisplayName","variableName","fnName","op","channelOps","sinkOps","computeSemanticRole","desc","import_fs","import_path","effectAliasCache","symbolResolutionCache","getNamesReExportedFromEffect","barrelSourceFile","out","decl","specifier","isEffectPackageSpecifier","EFFECT_NAMESPACE_NAMES","n","named","alias","resolveBarrelSourceFile","project","currentFilePath","baseDir","resolved","candidates","p","f","resolveModulePath","isSpecifierUnderKnownEffectInternalsRoot","knownEffectInternalsRoot","normalizedSpecifier","resolvedPath","normalizedResolved","normalizedRoot","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","normalizeEffectCallee","callee","dotIdx","rest","name","maxDepth","exportDecl","originalName","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","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","threshold","confidence","alias","extractServiceDefinitionsFromFile","results","typeChecker","extExpr","extText","typeArgs","inner","interfaceTypeNode","type","sym","propName","classText","hasCustomEquality","hasCustomHash","r","import_effect","import_effect","SCHEMA_OPS","analyzePipeChain","node","sourceFile","filePath","opts","warnings","stats","SyntaxKind","loadTsMorph","args","expr","isMethodPipe","baseExpr","transformArgs","baseNode","resolveIdentifierToLayerInitializer","baseSourceFile","basePath","project","inProject","added","initial","analyzeEffectExpression","transformations","arg","analyzed","spanName","filteredTransformations","t","argText","match","typeFlow","typeChecker","flow","initialSig","extractEffectTypeSignature","argNode","sig","pipeNode","generateId","computeDisplayName","computeSemanticRole","serviceScope","body","unknownNode","extractLocation","returnedExpr","stmt","analyzeEffectCall","text","operation","isEffectCallee","getAliasesForFile","effectNode","objLit","HANDLER_PROPS","props","handlerEntries","hasKnownHandler","prop","assignment","propName","initializer","call","callee","normalizedCallee","normalizeEffectCallee","calleeOperation","location","isEffectMethodPipe","nodes","analyzeLayerCall","analyzeStreamCall","analyzeChannelCall","analyzeSinkCall","analyzeConcurrencyPrimitiveCall","FIBER_PATTERNS","p","analyzeFiberCall","INTERRUPTION_PATTERNS","analyzeInterruptionCall","analyzeParallelCall","analyzeRaceCall","ERROR_HANDLER_PATTERNS","pattern","analyzeErrorHandlerCall","analyzeRetryCall","analyzeTimeoutCall","resourceOps","resourceOpPrefixes","isResourceOp","op","baseCall","baseCallee","baseOperation","analyzeResourceCall","conditionalOp","CONDITIONAL_PATTERNS","analyzeConditionalCall","isSchemaOp","collectionOp","COLLECTION_PATTERNS","analyzeLoopCall","isTransformCall","analyzeTransformCall","isMatchCall","analyzeMatchCall","isCauseCall","analyzeCauseCall","isExitCall","analyzeExitCall","isScheduleCall","analyzeScheduleCall","callbackBody","isConstructorWithCallback","c","asyncCallback","firstArg","fn","innerNodes","block","retExpr","isEffectLikeCallExpression","resumeParamName","resumeCallCount","visit","returnsCanceller","k","effectJSDoc","extractJSDocDescription","typeSignature","requiredServices","extractServiceRequirements","serviceCall","tryResolveServiceCall","serviceMethod","propAccess","objectText","methodName","serviceId","provideKind","contextArgText","constructorKind","fiberRefName","KNOWN_FIBER_REFS","refName","tracedName","strMatch","getSemanticDescriptionWithAliases","extractJSDocTags","_sourceFile","objExpr","objectName","firstSegment","KNOWN_EFFECT_NAMESPACES","type","symbol","typeName","BUILT_IN_TYPE_NAMES","isLayerOrEffectInitializerCallee","initCall","initText","srcFile","normalized","resolveLayerInitializerFromImport","ident","importSpec","isLayerInit","currentPath","specifier","targetFile","resolveBarrelSourceFile","resolvedPath","resolveModulePath","tryDecl","d","init","list","v","exportName","exported","decls","targetName","declList","resolveLayerInitializerFromDefaultImport","importDecl","name","sym","decl","fromDecls","sf","id","fromDefault","spec","n","fromImport","operations","elements","elem","toAnalyze","argSourceFile","isMerged","lifecycle","provides","extractTagName","pae","obj","tag","isProvideCall","requiresSet","depName","baseName","collectRequires","eff","req","calleeText","layer","r","getStaticChildren","layerSig","extractLayerTypeSignature","parseServiceIdsFromContextType","layerOpName","layerName","isMemoMap","layerNode","source","opName","constructorType","classifyOperator","isEffectful","opCategory","cardinality","windowSize","stride","getNumericLiteralFromNode","thisOp","sink","backpressureStrategy","effectiveSource","pipeline","effectiveConstructorType","srcStream","streamNode","channelOpCategory","srcChan","channelNode","sinkOpCategory","srcSink","sinkNode","_warnings","_stats","primitive","strategy","capacity","permitCount","first","lifecycleOptions","innerPrimNode","concurrencyNode","isScoped","isDaemon","fiberSource","scopeContext","parent","parentText","fiberNode","interruptionType","handler","interruptionNode","parseEffectAllOptions","optionsNode","concurrency","batching","discard","children","parsed","mode","branchLabels","child","parallelNode","raceLabels","raceNode","handlerType","exprSource","errorTag","errorTags","tagArg","objArg","a","handlerNode","schedule","scheduleNode","hasFallback","scheduleInfo","parseScheduleInfo","retryNode","scheduleText","baseStrategy","maxRetries","recursMatch","recurUpToMatch","jittered","conditions","duration","getNodeText","exprText","timeoutNode","resourceOperation","acquire","release","useEffect","resourceNode","conditionalType","condition","onTrue","onFalse","secondArg","propAssign","truncatedCondition","conditionalNode","loopType","bodyArgIndex","iterSource","rawSource","loopNode","matchOp","MATCH_OP_MAP","isExhaustive","EXHAUSTIVE_OPS","matchedTags","arg0","matchNode","causeOp","CAUSE_OP_MAP","isConstructor","CAUSE_CONSTRUCTORS","childNodes","causeKind","childKinds","causeNode","exitOp","EXIT_OP_MAP","EXIT_CONSTRUCTORS","exitNode","scheduleOp","SCHEDULE_OP_MAP","transformType","TRANSFORM_OPS","EFFECTFUL_TRANSFORMS","fnText","transformNode","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","args","genFn","analyzeGeneratorFunction","analyzePipeChain","call","SyntaxKind","loadTsMorph","pipeResult","analyzeRunEntrypointExpression","callbackInArgs","arg","workflowBody","getWorkflowBodyNodeForRunCall","effect","analyzeEffectExpression","exprText","initializer","classDecl","callee","clause","clauseText","description","classEffectNode","extractJSDocDescription","body","SK","returnStatements","ret","expr","result","isFunctionBoundary","kind","containsGeneratorYield","found","child","extractLiteralValue","resolveConditionConsts","condition","constValues","resolved","name","value","pattern","replacement","simplifyBooleanExpression","unwrapExpression","inner","hasTerminatorStatement","stmts","last","collectYieldExpressionsDF","results","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","unwrappedExpr","stepResult","variableName","enrichedStep","computeDisplayName","computeSemanticRole","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","termNode","valueYields","k","unwrapped","exprKind","ternary","whenTrue","whenFalse","trueYields","falseYields","resolvedCond","binary","operatorToken","left","right","rightYields","yieldExprs","entry","serviceScope","yields","calls","aliases","getAliasesForFile","isEffectLikeCallExpression","analyzeEffectCall","generatorJSDoc","generatorNode","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","name","found","p","available","analyze","filePath","options","resetIdCounter","programsEffect","analyzeEffectFile","code","analyzeEffectSource","workflowOptions","analyze","filePath","options","code"]}