@atrim/instrument-node 0.8.1-dev.ae570af.20260116212440 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../core/src/instrumentation-schema.ts","../../../../../../core/src/errors.ts","../../../../../../core/src/services/config-loader.ts","../../../../../../core/src/logger.ts","../../../../../src/core/config-loader.ts","../../../../../src/integrations/effect/auto/config.ts","../../../../../src/integrations/effect/auto/traced-fork.ts","../../../../../src/integrations/effect/auto/patch-fork.ts","../../../../../src/integrations/effect/auto/naming.ts","../../../../../src/integrations/effect/auto/supervisor.ts","../../../../../src/integrations/effect/auto/effect-tracing.ts","../../../../../src/integrations/effect/auto/source-capture-supervisor.ts","../../../../../src/integrations/effect/auto/operation-tracing-supervisor.ts"],"names":["parseYaml","parseYAML","fs","path","__publicField","existsSync","join","Context","Effect","Layer","basename","FiberRef","EffectTracer","exporterConfig","SimpleSpanProcessor","ConsoleSpanExporter","OTLPTraceExporter","BatchSpanProcessor","BasicTracerProvider","resourceFromAttributes","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","OtelApi2","OtelTracer","Supervisor","fs2","AutoTracingEnabled","AutoTracingSpanName","Option","OtelApi3","FiberRefs","Exit","trace","applyTemplate","OtelApi4","EffectTracer3"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAMO,IAAM,mBAAA,GAAsB,EAAE,MAAA,CAAO;AAC1C,EAAA,OAAA,EAAS,EAAE,MAAA,EAAA;EACX,OAAA,EAAS,CAAA,CAAE,OAAA,EAAA,CAAU,QAAA,EAAA;EACrB,WAAA,EAAa,CAAA,CAAE,MAAA,EAAA,CAAS,QAAA;AAC1B,CAAC,CAAA;AAQM,IAAM,yBAAA,GAA4B,EAAE,MAAA,CAAO;;AAEhD,EAAA,OAAA,EAAS,CAAA,CAAE,OAAA,EAAA,CAAU,OAAA,CAAQ,KAAK,CAAA;;AAGlC,EAAA,SA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W,QAAQ,CAAA,CAAA;AAAA,KACzH;AAGA,IAAA,MAAM,aAAgC,eAAA,EAAiB,UAAA,GACnD,gBAAgB,UAAA,CAAW,GAAA,CAAI,CAAC,EAAA,MAAQ;AAAA,MACtC,MAAM,EAAA,CAAG,IAAA;AAAA,MACT,GAAI,EAAA,CAAG,SAAA,IAAa,EAAE,gBAAA,EAAkB,GAAG,SAAA,EAAU;AAAA,MACrD,YAAA,EAAc,GAAG,aAAA,IAAiB,IAAA;AAAA,MAClC,YAAA,EAAc,GAAG,aAAA,IAAiB;AAAA,MAClC,CAAA,GACF,iBAAA;AAEJ,IAAA,MAAM,MAAA,GAAS,eAAA,EAAiB,UAAA,GAAa,sBAAA,GAAyB,UAAA;AACtE,IAAA,MAAA,CAAO,GAAA;AAAA,MACL,CAAA,iCAAA,EAAoC,UAAA,CAAW,MAAM,CAAA,wBAAA,EAA2B,MAAM,CAAA;AAAA,KACxF;AAEA,IAAA,OAAO,yBAAA,CAA0B,YAAY,UAAU,CAAA;AAAA,EACzD,CAAC;AACH,CAAA;AA2BK,IAAM,uBAAuB,yBAAA;AAiB7B,IAAM,oBAAA,GAAuB,CAClC,MAAA,KAC2B,MAAA,CAAO,KAAK,mBAAA,EAAqBD,MAAAA,CAAO,OAAA,CAAQ,oBAAoB,CAAC","file":"index.js","sourcesContent":["/**\n * Configuration schema using Zod\n */\nimport { z } from 'zod'\nimport { parse as parseYaml } from 'yaml'\n\nexport const PatternConfigSchema = z.object({\n pattern: z.string(),\n enabled: z.boolean().optional(),\n description: z.string().optional()\n})\n\n/**\n * Configuration for automatic span isolation in Effect operations\n *\n * This prevents context leakage when using FiberSet.run, Effect.fork, etc.\n * while maintaining logical parent relationships via span links.\n */\nexport const AutoIsolationConfigSchema = z.object({\n // Global enable/disable for auto-isolation\n enabled: z.boolean().default(false),\n\n // Which operators to auto-isolate\n operators: z\n .object({\n fiberset_run: z.boolean().default(true),\n effect_fork: z.boolean().default(true),\n effect_fork_daemon: z.boolean().default(true),\n effect_fork_in: z.boolean().default(false)\n })\n .default({}),\n\n // Virtual parent tracking configuration\n tracking: z\n .object({\n use_span_links: z.boolean().default(true),\n use_attributes: z.boolean().default(true),\n capture_logical_parent: z.boolean().default(true)\n })\n .default({}),\n\n // Span categorization\n attributes: z\n .object({\n category: z.string().default('background_task'),\n add_metadata: z.boolean().default(true)\n })\n .default({})\n})\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\n/**\n * Span naming rule for auto-instrumentation\n *\n * Allows matching fibers based on file path, function name, etc.\n * and applying custom span names with template variables.\n */\nexport const SpanNamingRuleSchema = z.object({\n // Match criteria (all specified criteria must match)\n match: z.object({\n // Regex pattern to match file path\n file: z.string().optional(),\n // Regex pattern to match function name\n function: z.string().optional(),\n // Regex pattern to match module name\n module: z.string().optional()\n }),\n // Span name template with variables:\n // {fiber_id} - Fiber ID\n // {function} - Function name\n // {module} - Module name\n // {file} - File path\n // {line} - Line number\n // {operator} - Effect operator (gen, all, forEach, etc.)\n // {match:field:N} - Captured regex group from match\n name: z.string()\n})\n\n/**\n * Auto-instrumentation configuration for Effect operations\n *\n * Enables automatic tracing of all Effect fibers without manual\n * Effect.withSpan() calls. Configuration-driven via instrumentation.yaml.\n */\nexport const AutoInstrumentationConfigSchema = z.object({\n // Enable/disable auto-instrumentation\n enabled: z.boolean().default(false),\n\n // Tracing granularity\n // - 'fiber': Trace at fiber creation (recommended, lower overhead)\n // - 'operator': Trace each Effect operator (higher granularity, more overhead)\n granularity: z.enum(['fiber', 'operator']).default('fiber'),\n\n // Smart span naming configuration\n span_naming: z\n .object({\n // Default span name template when no rules match\n default: z.string().default('effect.fiber.{fiber_id}'),\n\n // Infer span names from source code (requires stack trace parsing)\n // Adds ~50-100μs overhead per fiber\n infer_from_source: z.boolean().default(true),\n\n // Naming rules (first match wins)\n rules: z.array(SpanNamingRuleSchema).default([])\n })\n .default({}),\n\n // Span relationship configuration for forked fibers\n // Controls how child fiber spans relate to their parent/forking context\n span_relationships: z\n .object({\n // Relationship type between forked fiber spans and their parent context\n // - 'parent-child': Use parent-child relationship (default, traditional tracing)\n // Parent span shows child as nested. Works well with most observability tools.\n // - 'span-links': Use span links (semantically correct for async forks per OTel spec)\n // Fibers get independent traces linked to parent. Better for long-running fibers.\n // - 'both': Create parent-child AND add span links\n // Maximum visibility but may create redundant data.\n type: z.enum(['parent-child', 'span-links', 'both']).default('parent-child'),\n\n // Custom attributes to add to span links (only used when type includes links)\n link_attributes: z\n .object({\n // Link type identifier\n 'link.type': z.string().default('fork'),\n // Custom attributes (key-value pairs)\n custom: z.record(z.string()).optional()\n })\n .optional()\n })\n .default({}),\n\n // Pattern-based filtering\n filter: z\n .object({\n // Only trace spans matching these patterns (empty = trace all)\n include: z.array(z.string()).default([]),\n\n // Never trace spans matching these patterns\n exclude: z.array(z.string()).default([])\n })\n .default({}),\n\n // Performance controls\n performance: z\n .object({\n // Sample rate (0.0 - 1.0)\n sampling_rate: z.number().min(0).max(1).default(1.0),\n\n // Skip fibers shorter than this duration (e.g., \"10ms\", \"100 millis\")\n min_duration: z.string().default('0ms'),\n\n // Maximum concurrent traced fibers (0 = unlimited)\n max_concurrent: z.number().default(0)\n })\n .default({}),\n\n // Automatic metadata extraction\n metadata: z\n .object({\n // Extract Effect fiber information\n fiber_info: z.boolean().default(true),\n\n // Extract source location (file:line)\n source_location: z.boolean().default(true),\n\n // Extract parent fiber information\n parent_fiber: z.boolean().default(true)\n })\n .default({})\n})\n\nexport type AutoInstrumentationConfig = z.infer<typeof AutoInstrumentationConfigSchema>\nexport type SpanNamingRule = z.infer<typeof SpanNamingRuleSchema>\n\n/**\n * Operation tracing configuration for Effect.all, Effect.forEach, etc.\n *\n * Enables automatic tracing of high-level Effect operations without manual\n * Effect.withSpan() calls. Uses OpSupervision to hook into every operation.\n */\nexport const OperationTracingConfigSchema = z.object({\n // Enable/disable operation tracing\n enabled: z.boolean().default(false),\n\n // Global span naming settings\n span_naming: z\n .object({\n // Include source location (file:line) in span name\n // Default: true - produces \"effect.all (index.ts:42)\"\n // When false - produces \"effect.all\"\n include_location: z.boolean().default(true),\n\n // Span name template with variables:\n // {op} - Operation name (all, forEach, retry, etc.)\n // {file} - Full file path\n // {filename} - Just the filename (basename)\n // {line} - Line number\n // {column} - Column number\n // Default: \"effect.{op} ({filename}:{line})\"\n template: z.string().default('effect.{op} ({filename}:{line})')\n })\n .default({}),\n\n // Operations to trace\n operations: z\n .array(\n z.object({\n // Operation name: 'all', 'forEach', 'retry', etc.\n name: z.string(),\n // Custom span name template (overrides global span_naming.template)\n // Supports same variables: {op}, {file}, {filename}, {line}, {column}\n span_name: z.string().optional(),\n // Include item count in span attributes\n include_count: z.boolean().default(true),\n // Include stack trace in span attributes\n include_stack: z.boolean().default(true)\n })\n )\n .default([])\n})\n\nexport type OperationTracingConfig = z.infer<typeof OperationTracingConfigSchema>\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\nexport const HttpFilteringConfigSchema = z.object({\n // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)\n ignore_outgoing_urls: z.array(z.string()).optional(),\n\n // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)\n ignore_incoming_paths: z.array(z.string()).optional(),\n\n // Require parent span for outgoing requests (prevents root spans for HTTP calls)\n require_parent_for_outgoing_spans: z.boolean().optional(),\n\n // Trace context propagation configuration\n // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)\n propagate_trace_context: z\n .object({\n // Strategy for trace propagation\n // - \"all\": Propagate to all cross-origin requests (may cause CORS errors)\n // - \"none\": Never propagate trace headers\n // - \"same-origin\": Only propagate to same-origin requests (default, safe)\n // - \"patterns\": Propagate based on include_urls patterns\n strategy: z.enum(['all', 'none', 'same-origin', 'patterns']).default('same-origin'),\n\n // URL patterns to include when strategy is \"patterns\"\n // Supports regex patterns (e.g., \"^https://api\\\\.myapp\\\\.com\")\n include_urls: z.array(z.string()).optional()\n })\n .optional()\n})\n\n/**\n * Exporter configuration for OpenTelemetry tracing\n *\n * Allows configuring how traces are exported via instrumentation.yaml\n */\nexport const ExporterConfigSchema = z.object({\n // Exporter type: 'otlp' | 'console' | 'none'\n // - 'otlp': Export to OTLP endpoint (production)\n // - 'console': Log spans to console (development)\n // - 'none': No export (disable tracing)\n type: z.enum(['otlp', 'console', 'none']).default('otlp'),\n\n // OTLP endpoint URL (for type: otlp)\n // Defaults to OTEL_EXPORTER_OTLP_ENDPOINT env var or http://localhost:4318\n endpoint: z.string().optional(),\n\n // Custom headers to send with OTLP requests (for type: otlp)\n // Useful for authentication (x-api-key, Authorization, etc.)\n headers: z.record(z.string()).optional(),\n\n // Span processor type\n // - 'batch': Batch spans for export (production, lower overhead)\n // - 'simple': Export immediately (development, no batching delay)\n processor: z.enum(['batch', 'simple']).default('batch'),\n\n // Batch processor settings (for processor: batch)\n batch: z\n .object({\n // Max time to wait before exporting (milliseconds)\n scheduled_delay_millis: z.number().default(1000),\n // Max batch size\n max_export_batch_size: z.number().default(100)\n })\n .optional()\n})\n\nexport type ExporterConfig = z.infer<typeof ExporterConfigSchema>\n\nexport const InstrumentationConfigSchema = z.object({\n version: z.string(),\n instrumentation: z.object({\n enabled: z.boolean(),\n description: z.string().optional(),\n logging: z.enum(['on', 'off', 'minimal']).optional().default('on'),\n instrument_patterns: z.array(PatternConfigSchema),\n ignore_patterns: z.array(PatternConfigSchema)\n }),\n effect: z\n .object({\n // Enable/disable Effect tracing entirely\n // When false, EffectInstrumentationLive returns Layer.empty\n enabled: z.boolean().default(true),\n // Exporter mode (legacy - use exporter.type instead):\n // - \"unified\": Use global TracerProvider from Node SDK (recommended, enables filtering)\n // - \"standalone\": Use Effect's own OTLP exporter (bypasses Node SDK filtering)\n exporter: z.enum(['unified', 'standalone']).default('unified'),\n // Exporter configuration (for auto-instrumentation)\n exporter_config: ExporterConfigSchema.optional(),\n auto_extract_metadata: z.boolean(),\n auto_isolation: AutoIsolationConfigSchema.optional(),\n // Auto-instrumentation: automatic tracing of all Effect fibers\n auto_instrumentation: AutoInstrumentationConfigSchema.optional(),\n // Operation tracing: automatic tracing of Effect.all, Effect.forEach, etc.\n operation_tracing: OperationTracingConfigSchema.optional()\n })\n .optional(),\n http: HttpFilteringConfigSchema.optional()\n})\n\nexport type InstrumentationConfig = z.infer<typeof InstrumentationConfigSchema>\nexport type PatternConfig = z.infer<typeof PatternConfigSchema>\nexport type AutoIsolationConfig = z.infer<typeof AutoIsolationConfigSchema>\nexport type HttpFilteringConfig = z.infer<typeof HttpFilteringConfigSchema>\n\n/**\n * Default configuration when no config file is found\n */\nexport const defaultConfig: InstrumentationConfig = {\n version: '1.0',\n instrumentation: {\n enabled: true,\n logging: 'on',\n description: 'Default instrumentation configuration',\n instrument_patterns: [\n { pattern: '^app\\\\.', enabled: true, description: 'Application operations' },\n { pattern: '^http\\\\.server\\\\.', enabled: true, description: 'HTTP server operations' },\n { pattern: '^http\\\\.client\\\\.', enabled: true, description: 'HTTP client operations' }\n ],\n ignore_patterns: [\n { pattern: '^test\\\\.', description: 'Test utilities' },\n { pattern: '^internal\\\\.', description: 'Internal operations' },\n { pattern: '^health\\\\.', description: 'Health checks' }\n ]\n },\n effect: {\n enabled: true,\n exporter: 'unified' as const,\n auto_extract_metadata: true\n }\n}\n\n/**\n * Parse and validate configuration content (YAML string, JSON string, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Validated InstrumentationConfig\n * @throws Error if parsing or validation fails\n */\nexport function parseAndValidateConfig(content: string | unknown): InstrumentationConfig {\n let parsed: unknown\n\n // If string, parse as YAML (YAML is a superset of JSON)\n if (typeof content === 'string') {\n parsed = parseYaml(content)\n } else {\n parsed = content\n }\n\n // Validate with schema\n return InstrumentationConfigSchema.parse(parsed)\n}\n","/**\n * Typed error hierarchy for @atrim/instrumentation\n *\n * These errors use Effect's Data.TaggedError for typed error handling\n * with proper discriminated unions.\n */\n\nimport { Data } from 'effect'\n\n/**\n * Base error for configuration-related failures\n */\nexport class ConfigError extends Data.TaggedError('ConfigError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when fetching configuration from a URL fails\n */\nexport class ConfigUrlError extends Data.TaggedError('ConfigUrlError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when configuration validation fails (invalid YAML, schema mismatch)\n */\nexport class ConfigValidationError extends Data.TaggedError('ConfigValidationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when reading configuration from a file fails\n */\nexport class ConfigFileError extends Data.TaggedError('ConfigFileError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when service detection fails (package.json not found, invalid format)\n */\nexport class ServiceDetectionError extends Data.TaggedError('ServiceDetectionError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when OpenTelemetry SDK initialization fails\n */\nexport class InitializationError extends Data.TaggedError('InitializationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when span export fails (e.g., ECONNREFUSED to collector)\n */\nexport class ExportError extends Data.TaggedError('ExportError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when shutting down the SDK fails\n */\nexport class ShutdownError extends Data.TaggedError('ShutdownError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n","/**\n * ConfigLoader service using Effect Platform\n *\n * Provides URI-based configuration loading with pluggable platform services:\n * - FileSystem for file:// URIs (Node.js/Bun/Deno)\n * - HttpClient for http:// and https:// URIs (universal)\n *\n * This service has NO Node.js-specific dependencies - it depends only on\n * abstract Effect Platform services that are provided by environment-specific layers.\n */\n\nimport { Effect, Context, Layer } from 'effect'\nimport { FileSystem } from '@effect/platform/FileSystem'\nimport * as HttpClient from '@effect/platform/HttpClient'\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest'\nimport { parse as parseYAML } from 'yaml'\nimport {\n InstrumentationConfigSchema,\n type InstrumentationConfig\n} from '../instrumentation-schema.js'\nimport { ConfigError, ConfigFileError, ConfigUrlError, ConfigValidationError } from '../errors.js'\n\n// Security constraints\nconst SECURITY_DEFAULTS = {\n maxConfigSize: 1_000_000, // 1MB\n requestTimeout: 5_000 // 5 seconds\n} as const\n\n/**\n * ConfigLoader service interface\n */\nexport interface ConfigLoaderService {\n /**\n * Load configuration from a URI\n *\n * Supports:\n * - file:// URIs (uses FileSystem if available)\n * - http:// and https:// URIs (uses HttpClient)\n * - Relative paths (treated as file:// in Node, http:// in browser)\n *\n * @param uri - Configuration URI\n * @returns Effect that resolves to validated configuration (NO requirements)\n */\n readonly loadFromUri: (\n uri: string\n ) => Effect.Effect<\n InstrumentationConfig,\n ConfigError | ConfigFileError | ConfigUrlError | ConfigValidationError\n >\n\n /**\n * Load configuration from inline content (YAML, JSON, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Effect that resolves to validated configuration\n */\n readonly loadFromInline: (\n content: string | unknown\n ) => Effect.Effect<InstrumentationConfig, ConfigError | ConfigValidationError>\n}\n\n/**\n * ConfigLoader service tag\n */\nexport class ConfigLoader extends Context.Tag('ConfigLoader')<\n ConfigLoader,\n ConfigLoaderService\n>() {}\n\n/**\n * Parse and validate YAML content\n */\nconst parseYamlContent = (\n content: string,\n uri?: string\n): Effect.Effect<InstrumentationConfig, ConfigValidationError> =>\n Effect.gen(function* () {\n // Parse YAML\n const parsed = yield* Effect.try({\n try: () => parseYAML(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Failed to parse YAML from ${uri}` : 'Failed to parse YAML',\n cause: error\n })\n })\n\n // Validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(parsed),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Invalid configuration schema from ${uri}` : 'Invalid configuration schema',\n cause: error\n })\n })\n })\n\n/**\n * Load configuration from file using captured FileSystem service\n */\nconst loadFromFileWithFs = (\n fs: FileSystem,\n path: string,\n uri: string\n): Effect.Effect<InstrumentationConfig, ConfigFileError | ConfigValidationError> =>\n Effect.gen(function* () {\n // Read file\n const content = yield* fs.readFileString(path).pipe(\n Effect.mapError(\n (error) =>\n new ConfigFileError({\n reason: `Failed to read config file at ${uri}`,\n cause: error\n })\n )\n )\n\n // Security: Check file size\n if (content.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(content, uri)\n })\n\n/**\n * Load configuration from http using captured HttpClient service\n */\nconst loadFromHttpWithClient = (\n client: HttpClient.HttpClient,\n url: string\n): Effect.Effect<InstrumentationConfig, ConfigUrlError | ConfigValidationError> =>\n Effect.scoped(\n Effect.gen(function* () {\n // Security: Reject non-HTTPS URLs\n if (url.startsWith('http://')) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: 'Insecure protocol: only HTTPS URLs are allowed'\n })\n )\n }\n\n // Create request\n const request = HttpClientRequest.get(url).pipe(\n HttpClientRequest.setHeaders({\n Accept: 'application/yaml, text/yaml, application/x-yaml'\n })\n )\n\n // Execute request with timeout\n const response = yield* client.execute(request).pipe(\n Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),\n Effect.mapError((error) => {\n if (error._tag === 'TimeoutException') {\n return new ConfigUrlError({\n reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`\n })\n }\n return new ConfigUrlError({\n reason: `Failed to load config from URL: ${url}`,\n cause: error\n })\n })\n )\n\n // Check HTTP status\n if (response.status >= 400) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `HTTP ${response.status} from ${url}`\n })\n )\n }\n\n // Get response text\n const text = yield* response.text.pipe(\n Effect.mapError(\n (error) =>\n new ConfigUrlError({\n reason: `Failed to read response body from ${url}`,\n cause: error\n })\n )\n )\n\n // Security: Check size\n if (text.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(text, url)\n })\n )\n\n/**\n * ConfigLoader service implementation\n *\n * Captures FileSystem and HttpClient dependencies at construction time\n */\nconst makeConfigLoader = Effect.gen(function* () {\n // Capture dependencies at construction time\n const fs = yield* Effect.serviceOption(FileSystem)\n const http = yield* HttpClient.HttpClient\n\n // Create the loadFromUri function\n const loadFromUriUncached = (uri: string) =>\n Effect.gen(function* () {\n // file:// protocol\n if (uri.startsWith('file://')) {\n const path = uri.slice(7) // Remove \"file://\"\n\n if (fs._tag === 'None') {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: 'FileSystem not available (browser environment?)',\n cause: { uri }\n })\n )\n }\n\n return yield* loadFromFileWithFs(fs.value, path, uri)\n }\n\n // http:// or https:// protocol\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return yield* loadFromHttpWithClient(http, uri)\n }\n\n // Relative path - try FileSystem first, fallback to HTTP\n if (fs._tag === 'Some') {\n // FileSystem available (Node.js environment)\n return yield* loadFromFileWithFs(fs.value, uri, uri)\n } else {\n // No FileSystem (browser environment) - treat as HTTP\n // Relative URLs will be resolved by browser fetch to current origin\n return yield* loadFromHttpWithClient(http, uri)\n }\n })\n\n // Cache the loadFromUri function with 5 minute TTL (default cache timeout)\n const loadFromUriCached = yield* Effect.cachedFunction(loadFromUriUncached)\n\n return ConfigLoader.of({\n loadFromUri: loadFromUriCached,\n\n loadFromInline: (content: string | unknown) =>\n Effect.gen(function* () {\n // If string, parse as YAML\n if (typeof content === 'string') {\n return yield* parseYamlContent(content)\n }\n\n // Already an object - just validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: 'Invalid configuration schema',\n cause: error\n })\n })\n })\n })\n})\n\n/**\n * ConfigLoader Live layer\n *\n * Provides ConfigLoader service implementation.\n * Requires HttpClient to be provided by platform-specific layers.\n * FileSystem is optional (for browser compatibility).\n */\nexport const ConfigLoaderLive = Layer.effect(ConfigLoader, makeConfigLoader)\n","/**\n * Centralized logging utility for @atrim/instrumentation\n *\n * Supports three levels:\n * - 'on' (default): All logging enabled\n * - 'minimal': Only a single initialization message + errors/warnings\n * - 'off': No logging at all\n */\n\nexport type LogLevel = 'on' | 'off' | 'minimal'\n\nclass Logger {\n private level: LogLevel = 'on'\n private hasLoggedMinimal = false\n\n /**\n * Set the logging level\n */\n setLevel(level: LogLevel): void {\n this.level = level\n this.hasLoggedMinimal = false\n }\n\n /**\n * Get the current logging level\n */\n getLevel(): LogLevel {\n return this.level\n }\n\n /**\n * Log a minimal initialization message (only shown once in minimal mode)\n */\n minimal(message: string): void {\n if (this.level === 'off') {\n return\n }\n\n if (this.level === 'minimal' && !this.hasLoggedMinimal) {\n console.log(message)\n this.hasLoggedMinimal = true\n return\n }\n\n if (this.level === 'on') {\n console.log(message)\n }\n }\n\n /**\n * Log an informational message\n */\n log(...args: unknown[]): void {\n if (this.level === 'on') {\n console.log(...args)\n }\n }\n\n /**\n * Log a warning message (shown in minimal mode)\n */\n warn(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.warn(...args)\n }\n }\n\n /**\n * Log an error message (shown in minimal mode)\n */\n error(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.error(...args)\n }\n }\n\n /**\n * Check if full logging is enabled\n */\n isEnabled(): boolean {\n return this.level === 'on'\n }\n\n /**\n * Check if minimal logging is enabled\n */\n isMinimal(): boolean {\n return this.level === 'minimal'\n }\n\n /**\n * Check if logging is completely disabled\n */\n isDisabled(): boolean {\n return this.level === 'off'\n }\n}\n\n// Singleton instance\nexport const logger = new Logger()\n","/**\n * Node.js configuration loader\n *\n * Provides configuration loading using native Node.js APIs (fs, fetch)\n * This module doesn't require Effect Platform, making it work without Effect installed.\n */\n\nimport { Effect } from 'effect'\nimport {\n type InstrumentationConfig,\n parseAndValidateConfig,\n defaultConfig\n} from '@atrim/instrument-core'\n\n/**\n * Load configuration from a file path using native Node.js fs\n */\nasync function loadFromFile(filePath: string): Promise<InstrumentationConfig> {\n const { readFile } = await import('fs/promises')\n const content = await readFile(filePath, 'utf-8')\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from a URL using native fetch\n */\nasync function loadFromUrl(url: string): Promise<InstrumentationConfig> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`)\n }\n const content = await response.text()\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from URI (file path or URL)\n *\n * @param uri - Configuration URI (file://, http://, https://, or relative path)\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfig(\n uri: string,\n _options?: { cacheTimeout?: number }\n): Promise<InstrumentationConfig> {\n // Handle URL protocols\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return loadFromUrl(uri)\n }\n\n // Handle file:// protocol\n if (uri.startsWith('file://')) {\n const filePath = uri.slice(7) // Remove 'file://'\n return loadFromFile(filePath)\n }\n\n // Treat as file path\n return loadFromFile(uri)\n}\n\n/**\n * Load configuration from inline content\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigFromInline(\n content: string | unknown\n): Promise<InstrumentationConfig> {\n return parseAndValidateConfig(content)\n}\n\n/**\n * Reset the config loader cache (no-op for native implementation)\n * @internal\n */\nexport function _resetConfigLoaderCache(): void {\n // No cache in native implementation\n}\n\n/**\n * Legacy options interface for backward compatibility\n */\nexport interface ConfigLoaderOptions {\n configPath?: string\n configUrl?: string\n config?: InstrumentationConfig\n cacheTimeout?: number\n}\n\n/**\n * Load configuration with priority order (backward compatible API)\n *\n * Priority order (highest to lowest):\n * 1. Explicit config object (options.config)\n * 2. Environment variable (ATRIM_INSTRUMENTATION_CONFIG)\n * 3. Explicit path/URL (options.configPath or options.configUrl)\n * 4. Project root file (./instrumentation.yaml)\n * 5. Default config (built-in defaults)\n *\n * @param options - Configuration options\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigWithOptions(\n options: ConfigLoaderOptions = {}\n): Promise<InstrumentationConfig> {\n // Priority 1: Explicit config object\n if (options.config) {\n return loadConfigFromInline(options.config)\n }\n\n // Priority 2: Environment variable\n const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG\n if (envConfigPath) {\n return loadConfig(envConfigPath, options)\n }\n\n // Priority 3: Explicit options\n if (options.configUrl) {\n return loadConfig(options.configUrl, options)\n }\n if (options.configPath) {\n return loadConfig(options.configPath, options)\n }\n\n // Priority 4: Project root file\n const { existsSync } = await import('fs')\n const { join } = await import('path')\n\n const defaultPath = join(process.cwd(), 'instrumentation.yaml')\n if (existsSync(defaultPath)) {\n return loadConfig(defaultPath, options)\n }\n\n // Priority 5: Default config\n return defaultConfig\n}\n\n// ============================================================================\n// Effect-Based API (for Effect users)\n// ============================================================================\n\n/**\n * Load configuration from URI (Effect version)\n */\nexport const loadConfigEffect = (\n uri: string,\n options?: { cacheTimeout?: number }\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfig(uri, options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration from inline content (Effect version)\n */\nexport const loadConfigFromInlineEffect = (\n content: string | unknown\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigFromInline(content),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration with priority order (Effect version)\n */\nexport const loadConfigWithOptionsEffect = (\n options: ConfigLoaderOptions = {}\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n","/**\n * Auto-Tracing Configuration Loader\n *\n * Loads auto-tracing configuration from instrumentation.yaml\n * and provides a typed Effect service for accessing it.\n */\n\nimport { Effect, Context, Layer } from 'effect'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport * as yaml from 'yaml'\nimport {\n type AutoInstrumentationConfig,\n type InstrumentationConfig,\n type ExporterConfig,\n AutoInstrumentationConfigSchema,\n InstrumentationConfigSchema,\n defaultConfig,\n logger\n} from '@atrim/instrument-core'\nimport { loadConfigWithOptions, type ConfigLoaderOptions } from '../../../core/config-loader.js'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Re-export config type for convenience\n */\nexport type { AutoInstrumentationConfig }\n\n/**\n * Default auto-tracing configuration when not specified in instrumentation.yaml\n */\nexport const defaultAutoTracingConfig: AutoInstrumentationConfig = {\n enabled: false,\n granularity: 'fiber',\n span_naming: {\n default: 'effect.fiber.{fiber_id}',\n infer_from_source: true,\n rules: []\n },\n span_relationships: {\n type: 'parent-child'\n },\n filter: {\n include: [],\n exclude: []\n },\n performance: {\n sampling_rate: 1.0,\n min_duration: '0ms',\n max_concurrent: 0\n },\n metadata: {\n fiber_info: true,\n source_location: true,\n parent_fiber: true\n }\n}\n\n// ============================================================================\n// Service Definition\n// ============================================================================\n\n/**\n * Service tag for auto-tracing configuration\n */\nexport class AutoTracingConfig extends Context.Tag('AutoTracingConfig')<\n AutoTracingConfig,\n AutoInstrumentationConfig\n>() {}\n\n// ============================================================================\n// Configuration Loading\n// ============================================================================\n\n/**\n * Load auto-tracing configuration from instrumentation.yaml\n *\n * Returns the config from effect.auto_instrumentation section,\n * or defaults if not specified.\n */\nexport const loadAutoTracingConfig = (\n options?: ConfigLoaderOptions\n): Effect.Effect<AutoInstrumentationConfig, never, never> =>\n Effect.gen(function* () {\n // Load full config\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => {\n logger.log(`@atrim/auto-trace: Failed to load config: ${error}`)\n return error\n }\n }).pipe(Effect.catchAll(() => Effect.succeed(null)))\n\n if (!config) {\n logger.log('@atrim/auto-trace: No config found, using defaults')\n return defaultAutoTracingConfig\n }\n\n // Extract auto_instrumentation section\n const autoConfig = config.effect?.auto_instrumentation\n\n if (!autoConfig) {\n logger.log('@atrim/auto-trace: No auto_instrumentation config, using defaults')\n return defaultAutoTracingConfig\n }\n\n // Validate and merge with defaults\n const parsed = AutoInstrumentationConfigSchema.safeParse(autoConfig)\n if (!parsed.success) {\n logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${parsed.error.message}`)\n return defaultAutoTracingConfig\n }\n\n logger.log('@atrim/auto-trace: Loaded config from instrumentation.yaml')\n return parsed.data\n })\n\n/**\n * Load auto-tracing configuration synchronously from cache or default\n *\n * Note: This is a synchronous fallback when Effect runtime isn't available.\n * Prefer loadAutoTracingConfig() when possible.\n */\nexport const loadAutoTracingConfigSync = (): AutoInstrumentationConfig => {\n // For synchronous loading, we can only return defaults\n // The async version should be used for actual config loading\n return defaultAutoTracingConfig\n}\n\n// ============================================================================\n// Layer\n// ============================================================================\n\n/**\n * Layer that provides auto-tracing configuration\n */\nexport const AutoTracingConfigLive = Layer.effect(AutoTracingConfig, loadAutoTracingConfig())\n\n/**\n * Layer that provides custom auto-tracing configuration\n */\nexport const AutoTracingConfigLayer = (\n config: AutoInstrumentationConfig\n): Layer.Layer<AutoTracingConfig> => Layer.succeed(AutoTracingConfig, config)\n\n// ============================================================================\n// Full Config Loading\n// ============================================================================\n\n/**\n * Load the full instrumentation config from instrumentation.yaml\n *\n * Returns the complete config including exporter settings for setting up\n * the full auto-instrumentation pipeline.\n */\nexport const loadFullConfig = (\n options?: ConfigLoaderOptions\n): Effect.Effect<InstrumentationConfig, never, never> =>\n Effect.gen(function* () {\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => {\n logger.log(`@atrim/auto-trace: Failed to load config: ${error}`)\n return error\n }\n }).pipe(Effect.catchAll(() => Effect.succeed(null)))\n\n if (!config) {\n logger.log('@atrim/auto-trace: No config found, using defaults')\n return defaultConfig\n }\n\n return config\n })\n\n/**\n * Load the full instrumentation config synchronously\n *\n * This is needed for layers that cannot use Layer.unwrapEffect (which breaks\n * tracer propagation). Falls back to default config if file doesn't exist.\n */\nexport const loadFullConfigSync = (): InstrumentationConfig => {\n const defaultPath = path.join(process.cwd(), 'instrumentation.yaml')\n\n try {\n if (fs.existsSync(defaultPath)) {\n const content = fs.readFileSync(defaultPath, 'utf-8')\n const parsed = yaml.parse(content)\n const result = InstrumentationConfigSchema.safeParse(parsed)\n\n if (result.success) {\n logger.log(`@atrim/auto-trace: Loaded config from ${defaultPath}`)\n return result.data\n } else {\n logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${result.error.message}`)\n return defaultConfig\n }\n }\n } catch (error) {\n logger.log(`@atrim/auto-trace: Failed to load config: ${error}`)\n }\n\n logger.log('@atrim/auto-trace: No config found, using defaults')\n return defaultConfig\n}\n\n/**\n * Default exporter configuration\n */\nexport const defaultExporterConfig: ExporterConfig = {\n type: 'otlp',\n processor: 'batch',\n batch: {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n}\n","/**\n * Traced Fork - Capture call site for better span names\n *\n * This module provides tracedFork() which captures the call site\n * BEFORE entering Effect's runtime, allowing the supervisor to\n * create spans with meaningful names instead of \"effect.anonymous\".\n */\n\nimport { Effect, FiberRef } from 'effect'\nimport type { SourceInfo } from './naming.js'\n\n/**\n * FiberRef to store captured source location\n * Set by tracedFork(), read by supervisor\n */\nexport const CapturedSourceLocation = FiberRef.unsafeMake<SourceInfo | undefined>(undefined)\n\n/**\n * Capture the current call site from stack trace\n * Uses same technique as Effect.withSpan's captureStackTrace\n *\n * @param skipFrames - Number of additional frames to skip (default: 0)\n * Useful when calling from wrapper functions\n */\nexport function captureCallSite(skipFrames: number = 0): SourceInfo | undefined {\n // Limit stack depth for performance\n const originalLimit = Error.stackTraceLimit\n Error.stackTraceLimit = 10\n\n const error = new Error()\n Error.stackTraceLimit = originalLimit\n\n if (!error.stack) return undefined\n\n const lines = error.stack.split('\\n')\n\n // Skip:\n // [0] Error\n // [1] captureCallSite\n // [2] caller (tracedFork or patchedFork wrapper)\n // [3+skipFrames] USER CODE <-- This is what we want!\n\n const startIndex = 3 + skipFrames\n for (let i = startIndex; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined) continue\n\n // Skip @atrim and effect internals\n if (line.includes('@atrim/instrument') || line.includes('node_modules/effect')) {\n continue\n }\n\n // Parse: \" at functionName (file:line:col)\"\n const match = line.match(/at\\s+(?:(.+?)\\s+)?\\(?(.+?):(\\d+):(\\d+)\\)?/)\n if (match) {\n const [, funcName, filePath, lineNum, colNum] = match\n return {\n function: funcName?.trim() ?? 'anonymous',\n file: filePath ?? 'unknown',\n line: parseInt(lineNum ?? '0', 10),\n column: parseInt(colNum ?? '0', 10)\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Fork an effect with captured call site for better span naming\n *\n * This is a drop-in replacement for Effect.fork() that captures the\n * call site location. The supervisor reads this via CapturedSourceLocation\n * FiberRef to create better span names.\n *\n * @example\n * ```typescript\n * // Instead of:\n * yield* Effect.fork(myTask)\n *\n * // Use:\n * yield* tracedFork(myTask)\n *\n * // Span name will be \"effect.index:42\" instead of \"effect.anonymous\"\n * ```\n */\nexport const tracedFork = <A, E, R>(effect: Effect.Effect<A, E, R>) => {\n // Capture call site NOW while user code is still on stack\n const callSite = captureCallSite()\n\n if (!callSite) {\n // No call site captured, use regular fork\n return Effect.fork(effect)\n }\n\n // Set the FiberRef BEFORE forking so it's available in the child fiber's FiberRefs\n // This makes it available to the supervisor's onStart hook\n return FiberRef.set(CapturedSourceLocation, callSite).pipe(Effect.zipRight(Effect.fork(effect)))\n}\n\n/**\n * Fork an effect in daemon mode with captured call site\n *\n * Same as tracedFork() but creates a daemon fiber.\n */\nexport const tracedForkDaemon = <A, E, R>(effect: Effect.Effect<A, E, R>) => {\n const callSite = captureCallSite()\n\n if (!callSite) {\n return Effect.forkDaemon(effect)\n }\n\n return FiberRef.set(CapturedSourceLocation, callSite).pipe(\n Effect.zipRight(Effect.forkDaemon(effect))\n )\n}\n","/**\n * Effect.fork Patching Utilities\n *\n * Due to ESM module immutability, we cannot directly patch Effect.fork at runtime.\n * This module provides status tracking and documentation for users.\n *\n * **For reliable call-site capture, use the explicit wrappers:**\n * - `tracedFork(effect)` - replacement for `Effect.fork(effect)`\n * - `tracedForkDaemon(effect)` - replacement for `Effect.forkDaemon(effect)`\n *\n * **Future options for true auto-instrumentation:**\n * - ESM loader hooks (requires Node.js --import flag)\n * - Build-time transforms (Babel/SWC plugin)\n * - Effect upstream enhancement (proposed)\n */\n\nimport { logger } from '@atrim/instrument-core'\n\n// Track patching state\nlet patchAttempted = false\n\n/**\n * Check if Effect.fork patching was attempted\n *\n * Note: Due to ESM limitations, actual patching is not currently supported.\n * Use `tracedFork()` for reliable call-site capture.\n */\nexport function isEffectForkPatched(): boolean {\n return false // Patching not supported in ESM\n}\n\n/**\n * Attempt to enable automatic call-site capture for Effect.fork.\n *\n * **Note:** Due to ESM module immutability, this is currently a no-op.\n * Use `tracedFork()` and `tracedForkDaemon()` for explicit call-site capture.\n *\n * @example\n * ```typescript\n * // Instead of:\n * yield* Effect.fork(myEffect) // Span: \"effect.anonymous\"\n *\n * // Use:\n * import { tracedFork } from '@atrim/instrument-node/effect/auto'\n * yield* tracedFork(myEffect) // Span: \"effect.myFile:42\"\n * ```\n */\nexport function patchEffectFork(): void {\n if (patchAttempted) {\n return\n }\n patchAttempted = true\n\n // Log once that patching is not available\n logger.log('@atrim/auto-trace: Effect.fork auto-patching not available (ESM limitation)')\n logger.log('@atrim/auto-trace: Use tracedFork() for call-site capture')\n}\n\n/**\n * No-op for API compatibility.\n */\nexport function unpatchEffectFork(): void {\n patchAttempted = false\n}\n","/**\n * Span Name Inference for Auto-Tracing\n *\n * Provides intelligent span naming based on source code information\n * and configuration rules from instrumentation.yaml.\n */\n\nimport type { AutoInstrumentationConfig, SpanNamingRule } from '@atrim/instrument-core'\nimport * as path from 'path'\n\n/**\n * Source code information extracted from stack traces\n */\nexport interface SourceInfo {\n /** Function name (or 'anonymous') */\n function: string\n /** Full file path */\n file: string\n /** Line number */\n line: number\n /** Column number */\n column: number\n}\n\n/**\n * Template variables available for span naming\n */\nexport interface TemplateVariables {\n fiber_id: string\n function: string\n module: string\n file: string\n line: string\n operator: string\n [key: string]: string\n}\n\n/**\n * Compiled naming rule with pre-compiled regex patterns\n */\ninterface CompiledNamingRule {\n original: SpanNamingRule\n filePattern: RegExp | undefined\n functionPattern: RegExp | undefined\n modulePattern: RegExp | undefined\n}\n\n// Cache for compiled naming rules\nconst compiledRulesCache = new WeakMap<SpanNamingRule[], CompiledNamingRule[]>()\n\n/**\n * Compile naming rules for efficient matching\n */\nfunction compileNamingRules(rules: SpanNamingRule[]): CompiledNamingRule[] {\n const cached = compiledRulesCache.get(rules)\n if (cached) return cached\n\n const compiled: CompiledNamingRule[] = rules.map((rule) => ({\n original: rule,\n filePattern: rule.match.file ? new RegExp(rule.match.file) : undefined,\n functionPattern: rule.match.function ? new RegExp(rule.match.function) : undefined,\n modulePattern: rule.match.module ? new RegExp(rule.match.module) : undefined\n }))\n\n compiledRulesCache.set(rules, compiled)\n return compiled\n}\n\n/**\n * Extract module name from file path\n */\nfunction extractModuleName(filePath: string): string {\n const basename = path.basename(filePath, path.extname(filePath))\n // Remove common suffixes (both dot-separated and PascalCase)\n // e.g., \"user.service\" -> \"user\", \"UserService\" -> \"User\"\n return basename\n .replace(/\\.(service|controller|handler|util|helper|model|repo|repository)$/i, '')\n .replace(/(Service|Controller|Handler|Util|Helper|Model|Repo|Repository)$/i, '')\n}\n\n/**\n * Apply template variables to a span name pattern\n *\n * Supports:\n * - {fiber_id} - Fiber ID\n * - {function} - Function name\n * - {module} - Module name (filename without extension)\n * - {file} - Full file path\n * - {line} - Line number\n * - {operator} - Effect operator (if known)\n * - {match:field:N} - Captured regex group from match\n */\nfunction applyTemplate(\n template: string,\n variables: TemplateVariables,\n matchGroups?: Map<string, string[]>\n): string {\n let result = template\n\n // Replace simple variables\n for (const [key, value] of Object.entries(variables)) {\n result = result.replace(new RegExp(`\\\\{${key}\\\\}`, 'g'), value)\n }\n\n // Replace match groups: {match:field:N} where field is 'file', 'function', 'module'\n // and N is the capture group index\n if (matchGroups) {\n result = result.replace(\n /\\{match:(\\w+):(\\d+)\\}/g,\n (_fullMatch, field: string, index: string): string => {\n const groups = matchGroups.get(field)\n const idx = parseInt(index, 10)\n if (groups && groups[idx]) {\n return groups[idx]\n }\n return ''\n }\n )\n }\n\n return result\n}\n\n/**\n * Find matching naming rule for the given source info\n */\nfunction findMatchingRule(\n sourceInfo: SourceInfo | undefined,\n config: AutoInstrumentationConfig\n): { rule: CompiledNamingRule; matchGroups: Map<string, string[]> } | undefined {\n const rules = config.span_naming?.rules\n if (!rules || rules.length === 0) return undefined\n\n const compiledRules = compileNamingRules(rules)\n\n for (const rule of compiledRules) {\n const matchGroups = new Map<string, string[]>()\n let allMatched = true\n\n // Check file pattern\n if (rule.filePattern) {\n if (sourceInfo?.file) {\n const match = sourceInfo.file.match(rule.filePattern)\n if (match) {\n matchGroups.set('file', match.slice(1))\n } else {\n allMatched = false\n }\n } else {\n allMatched = false\n }\n }\n\n // Check function pattern\n if (rule.functionPattern && allMatched) {\n if (sourceInfo?.function) {\n const match = sourceInfo.function.match(rule.functionPattern)\n if (match) {\n matchGroups.set('function', match.slice(1))\n } else {\n allMatched = false\n }\n } else {\n allMatched = false\n }\n }\n\n // Check module pattern\n if (rule.modulePattern && allMatched) {\n const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : ''\n if (moduleName) {\n const match = moduleName.match(rule.modulePattern)\n if (match) {\n matchGroups.set('module', match.slice(1))\n } else {\n allMatched = false\n }\n } else {\n allMatched = false\n }\n }\n\n if (allMatched) {\n return { rule, matchGroups }\n }\n }\n\n return undefined\n}\n\n/**\n * Infer a span name based on fiber ID, source info, and configuration\n *\n * Priority:\n * 1. Match against naming rules (first match wins)\n * 2. Use default template with source info if available\n * 3. Fallback to default template with fiber ID only\n *\n * Smart anonymous handling:\n * - When function is \"anonymous\", falls back to \"module:line\" format\n * - Example: \"effect.index:42\" instead of \"effect.anonymous\"\n *\n * @param fiberId - The fiber's numeric ID\n * @param sourceInfo - Optional source code information from stack trace\n * @param config - Auto-instrumentation configuration\n * @returns The inferred span name\n */\nexport function inferSpanName(\n fiberId: number,\n sourceInfo: SourceInfo | undefined,\n config: AutoInstrumentationConfig\n): string {\n // Determine the best function name\n let functionName = sourceInfo?.function || 'anonymous'\n const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : 'unknown'\n\n // If function is anonymous and we have source location, use module:line format\n if (functionName === 'anonymous' && sourceInfo?.file && sourceInfo?.line) {\n functionName = `${moduleName}:${sourceInfo.line}`\n }\n\n // Build template variables\n const variables: TemplateVariables = {\n fiber_id: String(fiberId),\n function: functionName,\n module: moduleName,\n file: sourceInfo?.file || 'unknown',\n line: sourceInfo?.line ? String(sourceInfo.line) : '0',\n operator: 'gen' // Default operator, could be enhanced with more context\n }\n\n // Try to match a naming rule\n const match = findMatchingRule(sourceInfo, config)\n if (match) {\n return applyTemplate(match.rule.original.name, variables, match.matchGroups)\n }\n\n // Use default template\n const defaultTemplate = config.span_naming?.default || 'effect.fiber.{fiber_id}'\n return applyTemplate(defaultTemplate, variables)\n}\n\n/**\n * Sanitize a span name to be OpenTelemetry compliant\n *\n * - Replaces invalid characters with underscores\n * - Ensures name is not empty\n * - Truncates to reasonable length\n */\nexport function sanitizeSpanName(name: string): string {\n if (!name) return 'effect.fiber.unknown'\n\n // Replace invalid characters (keep alphanumeric, dot, underscore, dash)\n let sanitized = name.replace(/[^a-zA-Z0-9._-]/g, '_')\n\n // Collapse multiple underscores\n sanitized = sanitized.replace(/_+/g, '_')\n\n // Remove leading/trailing underscores\n sanitized = sanitized.replace(/^_+|_+$/g, '')\n\n // Ensure not empty\n if (!sanitized) return 'effect.fiber.unknown'\n\n // Truncate to reasonable length (OTel has no strict limit, but 256 is reasonable)\n if (sanitized.length > 256) {\n sanitized = sanitized.substring(0, 256)\n }\n\n return sanitized\n}\n","/**\n * Auto-Tracing Supervisor for Effect-TS\n *\n * Provides automatic tracing of all Effect fibers without manual Effect.withSpan() calls.\n * Uses Effect's Supervisor API to intercept fiber creation/termination and create\n * OpenTelemetry spans automatically.\n *\n * @example\n * ```typescript\n * import { AutoTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * yield* doWork() // Automatically traced!\n * }).pipe(Effect.provide(AutoTracingLive))\n * ```\n */\n\nimport {\n Supervisor,\n Effect,\n Layer,\n FiberRef,\n FiberRefs,\n Context,\n Option,\n Exit,\n Fiber,\n Tracer as EffectTracer\n} from 'effect'\nimport { CapturedSourceLocation } from './traced-fork.js'\nimport { patchEffectFork } from './patch-fork.js'\nimport * as OtelApi from '@opentelemetry/api'\nimport {\n BatchSpanProcessor,\n SimpleSpanProcessor,\n ConsoleSpanExporter,\n BasicTracerProvider\n} from '@opentelemetry/sdk-trace-base'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'\nimport type { AutoInstrumentationConfig, ExporterConfig } from '@atrim/instrument-core'\nimport { logger } from '@atrim/instrument-core'\nimport { inferSpanName, type SourceInfo } from './naming.js'\nimport { loadAutoTracingConfig, loadFullConfig } from './config.js'\n\n// ============================================================================\n// FiberRefs for opt-out and name override\n// ============================================================================\n\n/**\n * FiberRef to enable/disable auto-tracing for specific fibers\n * Use withoutAutoTracing() to disable\n */\nexport const AutoTracingEnabled = FiberRef.unsafeMake<boolean>(true)\n\n/**\n * FiberRef to override auto-generated span name\n * Use setSpanName() to override\n */\nexport const AutoTracingSpanName = FiberRef.unsafeMake<Option.Option<string>>(Option.none())\n\n// ============================================================================\n// AutoTracingSupervisor\n// ============================================================================\n\n/**\n * Supervisor that automatically creates OpenTelemetry spans for all Effect fibers\n *\n * This supervisor intercepts fiber creation and termination, creating spans\n * based on configuration from instrumentation.yaml.\n */\nexport class AutoTracingSupervisor extends Supervisor.AbstractSupervisor<void> {\n // WeakMap to associate fibers with their OTel spans\n private readonly fiberSpans = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, OtelApi.Span>()\n\n // WeakMap for fiber start times (for min_duration filtering)\n private readonly fiberStartTimes = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, bigint>()\n\n // OpenTelemetry tracer - lazily initialized\n private _tracer: OtelApi.Tracer | null = null\n\n // Optional TracerProvider (if provided, use this instead of global)\n private readonly tracerProvider: OtelApi.TracerProvider | null = null\n\n // Compiled filter patterns\n private readonly includePatterns: RegExp[]\n private readonly excludePatterns: RegExp[]\n\n // Active fiber count (for max_concurrent limiting)\n private activeFiberCount = 0\n\n // Root span for parent context (set by withAutoTracing)\n private _rootSpan: OtelApi.Span | null = null\n\n constructor(\n private readonly config: AutoInstrumentationConfig,\n tracerProvider?: OtelApi.TracerProvider\n ) {\n super()\n\n // Store tracer provider if provided\n if (tracerProvider) {\n this.tracerProvider = tracerProvider\n logger.log('@atrim/auto-trace: Using provided TracerProvider')\n }\n\n // Compile filter patterns\n this.includePatterns = (config.filter?.include || []).map((p) => new RegExp(p))\n this.excludePatterns = (config.filter?.exclude || []).map((p) => new RegExp(p))\n\n logger.log('@atrim/auto-trace: Supervisor initialized')\n logger.log(` Granularity: ${config.granularity || 'fiber'}`)\n logger.log(` Sampling rate: ${config.performance?.sampling_rate ?? 1.0}`)\n logger.log(` Infer from source: ${config.span_naming?.infer_from_source ?? true}`)\n }\n\n /**\n * Set the root span for parent context propagation\n */\n setRootSpan(span: OtelApi.Span): void {\n this._rootSpan = span\n }\n\n /**\n * Get the tracer lazily - uses provided TracerProvider if available, otherwise uses global\n */\n private get tracer(): OtelApi.Tracer {\n if (!this._tracer) {\n if (this.tracerProvider) {\n logger.log('@atrim/auto-trace: Getting tracer from provided TracerProvider')\n this._tracer = this.tracerProvider.getTracer('@atrim/auto-trace', '1.0.0')\n } else {\n logger.log('@atrim/auto-trace: Getting tracer from global API')\n this._tracer = OtelApi.trace.getTracer('@atrim/auto-trace', '1.0.0')\n }\n }\n return this._tracer\n }\n\n /**\n * Returns the current value (void for this supervisor)\n */\n override get value(): Effect.Effect<void> {\n return Effect.void\n }\n\n /**\n * Called when a fiber starts executing\n */\n override onStart<A, E, R>(\n _context: Context.Context<R>,\n _effect: Effect.Effect<A, E, R>,\n parent: Option.Option<Fiber.RuntimeFiber<unknown, unknown>>,\n fiber: Fiber.RuntimeFiber<A, E>\n ): void {\n logger.log(`@atrim/auto-trace: onStart called for fiber ${fiber.id().id}`)\n\n // Check if auto-tracing is enabled for this fiber\n // Note: FiberRef access in supervisor hooks must be synchronous\n const fiberRefsValue = fiber.getFiberRefs()\n const enabled = FiberRefs.getOrDefault(fiberRefsValue, AutoTracingEnabled)\n if (!enabled) {\n logger.log(`@atrim/auto-trace: Auto-tracing disabled for fiber ${fiber.id().id}`)\n return\n }\n\n // Check sampling\n const samplingRate = this.config.performance?.sampling_rate ?? 1.0\n if (samplingRate < 1.0 && Math.random() > samplingRate) {\n return\n }\n\n // Check max concurrent\n const maxConcurrent = this.config.performance?.max_concurrent ?? 0\n if (maxConcurrent > 0 && this.activeFiberCount >= maxConcurrent) {\n return\n }\n\n // Check for span name override\n const nameOverride = FiberRefs.getOrDefault(fiberRefsValue, AutoTracingSpanName)\n\n // Get source info - Priority:\n // 1. CapturedSourceLocation (from tracedFork()) - most accurate\n // 2. Stack trace parsing (fallback, often doesn't work in supervisor hooks)\n let sourceInfo = FiberRefs.getOrDefault(fiberRefsValue, CapturedSourceLocation)\n\n if (sourceInfo) {\n logger.log(`@atrim/auto-trace: Using captured source location for fiber ${fiber.id().id}`)\n logger.log(` function: ${sourceInfo.function}`)\n logger.log(` file: ${sourceInfo.file}`)\n logger.log(` line: ${sourceInfo.line}`)\n } else if (this.config.span_naming?.infer_from_source) {\n // Fallback to stack trace parsing (often doesn't work in supervisor)\n sourceInfo = this.parseStackTrace()\n if (sourceInfo) {\n logger.log(`@atrim/auto-trace: Inferred source from stack for fiber ${fiber.id().id}`)\n logger.log(` function: ${sourceInfo.function}`)\n logger.log(` file: ${sourceInfo.file}`)\n logger.log(` line: ${sourceInfo.line}`)\n } else {\n logger.log(`@atrim/auto-trace: No source info for fiber ${fiber.id().id}`)\n }\n }\n\n // Infer span name\n let spanName: string\n if (Option.isSome(nameOverride)) {\n spanName = nameOverride.value\n } else {\n spanName = inferSpanName(fiber.id().id, sourceInfo, this.config)\n }\n\n // Check filter patterns\n if (!this.shouldTrace(spanName)) {\n return\n }\n\n // Get parent span context and fiber ID if available\n // Priority: Effect ParentSpan (from context) > parent fiber's span > root span > no parent\n //\n // KEY INSIGHT: Effect stores the current span in Context via Tracer.ParentSpan.\n // This is properly propagated through fibers, unlike OTel's AsyncLocalStorage-based\n // context which gets lost across Effect's fiber scheduler boundaries.\n\n // Get span relationship type from config\n const relationshipType = this.config.span_relationships?.type ?? 'parent-child'\n const useParentChild = relationshipType === 'parent-child' || relationshipType === 'both'\n const useSpanLinks = relationshipType === 'span-links' || relationshipType === 'both'\n\n let parentContext: OtelApi.Context = OtelApi.ROOT_CONTEXT\n let parentFiberId: number | undefined\n let spanLinks: OtelApi.Link[] = []\n\n // First, try to get the Effect parent span from the context\n // This is the key to linking fiber spans to HTTP spans created by @effect/opentelemetry\n const maybeEffectParentSpan = Context.getOption(_context, EffectTracer.ParentSpan)\n\n if (Option.isSome(maybeEffectParentSpan)) {\n // We have an Effect parent span - extract its OTel identifiers\n const effectSpan = maybeEffectParentSpan.value\n logger.log(\n `@atrim/auto-trace: Found ParentSpan - traceId=${effectSpan.traceId.slice(0, 8)}..., spanId=${effectSpan.spanId.slice(0, 8)}...`\n )\n\n // Create an OTel SpanContext from the Effect span's identifiers\n const otelSpanContext: OtelApi.SpanContext = {\n traceId: effectSpan.traceId,\n spanId: effectSpan.spanId,\n traceFlags: effectSpan.sampled ? OtelApi.TraceFlags.SAMPLED : OtelApi.TraceFlags.NONE,\n isRemote: false\n }\n\n if (useParentChild) {\n // Wrap the SpanContext in a span object for proper parent-child linking\n // This creates a non-recording span that acts as the parent\n const wrappedSpan = OtelApi.trace.wrapSpanContext(otelSpanContext)\n parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, wrappedSpan)\n }\n\n if (useSpanLinks) {\n // Create a span link to the parent context\n // Per OTel spec, span links are semantically correct for forked/async operations\n const linkAttributes = this.getLinkAttributes()\n spanLinks.push({\n context: otelSpanContext,\n attributes: linkAttributes\n })\n logger.log(`@atrim/auto-trace: Added span link to parent (${relationshipType})`)\n }\n } else if (Option.isSome(parent)) {\n // Fiber has a parent fiber - try to find its span\n parentFiberId = parent.value.id().id\n const parentSpan = this.fiberSpans.get(parent.value)\n if (parentSpan) {\n if (useParentChild) {\n parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, parentSpan)\n }\n if (useSpanLinks) {\n const linkAttributes = this.getLinkAttributes()\n spanLinks.push({\n context: parentSpan.spanContext(),\n attributes: linkAttributes\n })\n }\n } else if (this._rootSpan) {\n if (useParentChild) {\n parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, this._rootSpan)\n }\n if (useSpanLinks) {\n const linkAttributes = this.getLinkAttributes()\n spanLinks.push({\n context: this._rootSpan.spanContext(),\n attributes: linkAttributes\n })\n }\n }\n } else if (this._rootSpan) {\n // No fiber parent and no Effect parent span - use root span if available\n if (useParentChild) {\n parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, this._rootSpan)\n }\n if (useSpanLinks) {\n const linkAttributes = this.getLinkAttributes()\n spanLinks.push({\n context: this._rootSpan.spanContext(),\n attributes: linkAttributes\n })\n }\n }\n\n // Also capture parent fiber ID for metadata\n if (Option.isSome(parent)) {\n parentFiberId = parent.value.id().id\n }\n\n // Create the span with full attributes and optional links\n const spanOptions: OtelApi.SpanOptions = {\n kind: OtelApi.SpanKind.INTERNAL,\n attributes: this.getInitialAttributes(fiber, sourceInfo, parentFiberId)\n }\n if (spanLinks.length > 0) {\n spanOptions.links = spanLinks\n }\n\n const span = this.tracer.startSpan(spanName, spanOptions, parentContext)\n\n logger.log(`@atrim/auto-trace: Created span \"${spanName}\" for fiber ${fiber.id().id}`)\n\n // Store span and start time\n this.fiberSpans.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, span)\n this.fiberStartTimes.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, process.hrtime.bigint())\n this.activeFiberCount++\n }\n\n /**\n * Called when a fiber completes (success or failure)\n */\n override onEnd<A, E>(exit: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n logger.log(`@atrim/auto-trace: onEnd called for fiber ${fiber.id().id}`)\n\n const span = this.fiberSpans.get(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n if (!span) {\n logger.log(\n `@atrim/auto-trace: No span found for fiber ${fiber.id().id} (skipped or filtered)`\n )\n return\n }\n\n // Check min_duration filtering\n const startTime = this.fiberStartTimes.get(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n if (startTime) {\n const duration = process.hrtime.bigint() - startTime\n const minDuration = this.parseMinDuration(this.config.performance?.min_duration)\n if (minDuration > 0 && duration < minDuration) {\n // Drop span if too short\n // Note: We can't actually \"drop\" a started span, but we can avoid ending it properly\n // In practice, this means the span will have no end time which is not ideal\n // A better approach would be to delay span creation, but that's more complex\n this.fiberSpans.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.fiberStartTimes.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.activeFiberCount--\n return\n }\n }\n\n // Set span status based on exit\n if (Exit.isSuccess(exit)) {\n span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n } else {\n // Set error status\n span.setStatus({\n code: OtelApi.SpanStatusCode.ERROR,\n message: 'Fiber failed'\n })\n span.setAttribute('effect.fiber.failed', true)\n }\n\n // End the span\n span.end()\n logger.log(`@atrim/auto-trace: Ended span for fiber ${fiber.id().id}`)\n\n // Cleanup\n this.fiberSpans.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.fiberStartTimes.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.activeFiberCount--\n }\n\n /**\n * Get attributes for span links from config\n */\n private getLinkAttributes(): OtelApi.Attributes {\n const linkConfig = this.config.span_relationships?.link_attributes\n const attrs: OtelApi.Attributes = {\n 'link.type': linkConfig?.['link.type'] ?? 'fork'\n }\n\n // Add custom attributes if configured\n if (linkConfig?.custom) {\n for (const [key, value] of Object.entries(linkConfig.custom)) {\n attrs[key] = value\n }\n }\n\n return attrs\n }\n\n /**\n * Check if a span name should be traced based on filter patterns\n */\n private shouldTrace(spanName: string): boolean {\n // Check exclude patterns first (they take precedence)\n for (const pattern of this.excludePatterns) {\n if (pattern.test(spanName)) {\n return false\n }\n }\n\n // If include patterns are specified, span must match at least one\n if (this.includePatterns.length > 0) {\n for (const pattern of this.includePatterns) {\n if (pattern.test(spanName)) {\n return true\n }\n }\n return false\n }\n\n // No include patterns = trace everything not excluded\n return true\n }\n\n /**\n * Get initial span attributes for a fiber\n */\n private getInitialAttributes(\n fiber: Fiber.RuntimeFiber<unknown, unknown>,\n sourceInfo: SourceInfo | undefined,\n parentFiberId: number | undefined\n ): OtelApi.Attributes {\n const attrs: OtelApi.Attributes = {\n 'effect.auto_traced': true\n }\n\n // Add fiber info\n if (this.config.metadata?.fiber_info !== false) {\n attrs['effect.fiber.id'] = fiber.id().id\n }\n\n // Add source location info\n if (this.config.metadata?.source_location !== false && sourceInfo) {\n attrs['code.function'] = sourceInfo.function\n attrs['code.filepath'] = sourceInfo.file\n attrs['code.lineno'] = sourceInfo.line\n attrs['code.column'] = sourceInfo.column\n }\n\n // Add parent fiber info\n if (this.config.metadata?.parent_fiber !== false && parentFiberId !== undefined) {\n attrs['effect.fiber.parent_id'] = parentFiberId\n }\n\n return attrs\n }\n\n /**\n * Parse stack trace to get source info\n */\n private parseStackTrace(): SourceInfo | undefined {\n const stack = new Error().stack\n if (!stack) {\n logger.log('@atrim/auto-trace: [parseStackTrace] No stack available')\n return undefined\n }\n\n const lines = stack.split('\\n')\n logger.log(`@atrim/auto-trace: [parseStackTrace] Stack has ${lines.length} lines`)\n\n // Debug: show first 10 lines of stack\n for (let i = 0; i < Math.min(10, lines.length); i++) {\n logger.log(`@atrim/auto-trace: [stack ${i}] ${lines[i]}`)\n }\n\n // Skip Error, parseStackTrace, onStart, Effect internals\n // Look for first line that's not from effect or this module\n for (let i = 3; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined) continue\n\n if (\n !line.includes('node_modules/effect') &&\n !line.includes('@atrim/instrument') &&\n !line.includes('auto/supervisor')\n ) {\n logger.log(`@atrim/auto-trace: [parseStackTrace] Found user frame: ${line}`)\n // Parse line like \" at functionName (file:line:col)\"\n const match = line.match(/at\\s+(?:(.+?)\\s+)?\\(?(.+?):(\\d+):(\\d+)\\)?/)\n if (match) {\n const [, funcName, filePath, lineNum, colNum] = match\n const sourceInfo = {\n function: funcName ?? 'anonymous',\n file: filePath ?? 'unknown',\n line: parseInt(lineNum ?? '0', 10),\n column: parseInt(colNum ?? '0', 10)\n }\n logger.log(\n `@atrim/auto-trace: [parseStackTrace] Parsed: ${sourceInfo.function} at ${sourceInfo.file}:${sourceInfo.line}`\n )\n return sourceInfo\n }\n }\n }\n\n logger.log('@atrim/auto-trace: [parseStackTrace] No user code frame found in stack')\n return undefined\n }\n\n /**\n * Parse min_duration string to nanoseconds\n */\n private parseMinDuration(duration: string | undefined): bigint {\n if (!duration || duration === '0ms') return BigInt(0)\n\n const match = duration.match(/^(\\d+)\\s*(ms|millis|s|sec|seconds|us|micros)?$/i)\n if (!match) return BigInt(0)\n\n const value = parseInt(match[1] ?? '0', 10)\n const unit = (match[2] ?? 'ms').toLowerCase()\n\n switch (unit) {\n case 'us':\n case 'micros':\n return BigInt(value) * BigInt(1000)\n case 'ms':\n case 'millis':\n return BigInt(value) * BigInt(1000000)\n case 's':\n case 'sec':\n case 'seconds':\n return BigInt(value) * BigInt(1000000000)\n default:\n return BigInt(value) * BigInt(1000000) // Default to ms\n }\n }\n}\n\n// ============================================================================\n// Layers and factory functions\n// ============================================================================\n\n/**\n * Create a custom AutoTracingSupervisor with the given config\n */\nexport const createAutoTracingSupervisor = (\n config: AutoInstrumentationConfig,\n tracerProvider?: OtelApi.TracerProvider\n): AutoTracingSupervisor => {\n return new AutoTracingSupervisor(config, tracerProvider)\n}\n\n/**\n * Layer that provides auto-tracing with custom configuration\n *\n * @example\n * ```typescript\n * const CustomAutoTracing = createAutoTracingLayer({\n * enabled: true,\n * span_naming: {\n * default: 'app.{function}',\n * rules: [{ match: { file: 'src/services/.*' }, name: 'service.{function}' }]\n * }\n * })\n * ```\n */\nexport const createAutoTracingLayer = (options?: {\n config?: AutoInstrumentationConfig\n}): Layer.Layer<never> => {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n // Load config from options or instrumentation.yaml\n const config = options?.config ?? (yield* loadAutoTracingConfig())\n\n if (!config.enabled) {\n logger.log('@atrim/auto-trace: Auto-tracing disabled via config')\n return Layer.empty\n }\n\n // Note: For proper span names on forked fibers, use tracedFork() instead of Effect.fork()\n // ESM module immutability prevents automatic patching of Effect.fork\n patchEffectFork() // Logs a reminder about using tracedFork\n\n // Create supervisor\n const supervisor = createAutoTracingSupervisor(config)\n\n // Return layer that adds the supervisor\n return Supervisor.addSupervisor(supervisor)\n })\n )\n}\n\n/**\n * Wrap an Effect with auto-tracing supervision\n *\n * This creates a span for the main effect AND supervises all child fibers.\n * Use this when you need to ensure all fibers in an effect are traced.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* doWork() // Automatically traced!\n * })\n *\n * const tracedProgram = withAutoTracing(program, { enabled: true, ... })\n * Effect.runPromise(tracedProgram)\n * ```\n */\nexport const withAutoTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n config: AutoInstrumentationConfig,\n mainSpanName?: string\n): Effect.Effect<A, E, R> => {\n if (!config.enabled) {\n logger.log('@atrim/auto-trace: Auto-tracing disabled via config')\n return effect\n }\n\n const supervisor = createAutoTracingSupervisor(config)\n\n // Get the tracer\n const tracer = OtelApi.trace.getTracer('@atrim/auto-trace', '1.0.0')\n\n // Determine span name for main effect\n const spanName = mainSpanName ?? inferSpanName(0, undefined, config)\n\n // Start span for main effect\n const mainSpan = tracer.startSpan(spanName, {\n kind: OtelApi.SpanKind.INTERNAL,\n attributes: {\n 'effect.auto_traced': true,\n 'effect.fiber.id': 0, // Main fiber\n 'effect.main_fiber': true\n }\n })\n\n // Set the root span on the supervisor so child fibers use it as parent\n supervisor.setRootSpan(mainSpan)\n\n // Wrap the effect to handle the main span lifecycle\n return Effect.acquireUseRelease(\n // Acquire: return the span (already started)\n Effect.succeed(mainSpan),\n // Use: run the supervised effect\n () => Effect.supervised(supervisor)(effect),\n // Release: end the span\n (span, exit) =>\n Effect.sync(() => {\n if (Exit.isSuccess(exit)) {\n span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n } else {\n span.setStatus({\n code: OtelApi.SpanStatusCode.ERROR,\n message: 'Effect failed'\n })\n }\n span.end()\n })\n )\n}\n\n/**\n * Zero-config auto-tracing layer\n *\n * Loads configuration from instrumentation.yaml and automatically traces\n * all Effect fibers based on the configuration.\n *\n * @example\n * ```typescript\n * import { AutoTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * yield* doWork() // Automatically traced!\n * }).pipe(Effect.provide(AutoTracingLive))\n * ```\n */\nexport const AutoTracingLive: Layer.Layer<never> = createAutoTracingLayer()\n\n// ============================================================================\n// Opt-out utilities\n// ============================================================================\n\n/**\n * Disable auto-tracing for a specific Effect\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* publicWork() // Traced\n * yield* withoutAutoTracing(internalWork()) // NOT traced\n * })\n * ```\n */\nexport const withoutAutoTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => effect.pipe(Effect.locally(AutoTracingEnabled, false))\n\n/**\n * Override the auto-generated span name for a specific Effect\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* setSpanName('custom.operation.name')(myEffect)\n * })\n * ```\n */\nexport const setSpanName =\n (name: string) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.locally(AutoTracingSpanName, Option.some(name)))\n\n// ============================================================================\n// Full Auto-Instrumentation Layer (Exporter + Supervisor)\n// ============================================================================\n\n/**\n * Create and register a global TracerProvider based on exporter config\n *\n * Unlike @effect/opentelemetry's NodeSdk.layer(), this function creates a\n * standard OTel BasicTracerProvider and registers it globally so that\n * the AutoTracingSupervisor can access it via the OTel API.\n */\nconst createExporterLayer = (\n exporterConfig: ExporterConfig | undefined,\n serviceName: string,\n serviceVersion: string\n): Layer.Layer<never> => {\n const config = exporterConfig ?? {\n type: 'otlp' as const,\n processor: 'batch' as const,\n batch: {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n }\n\n // Handle 'none' type - no exporter\n if (config.type === 'none') {\n logger.log('@atrim/auto-trace: Exporter type is \"none\", no spans will be exported')\n return Layer.empty\n }\n\n // Create the span exporter\n const createSpanExporter = () => {\n if (config.type === 'console') {\n logger.log('@atrim/auto-trace: Using ConsoleSpanExporter')\n return new ConsoleSpanExporter()\n }\n\n // Default to OTLP\n const endpoint =\n config.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`)\n const exporterConfig: { url: string; headers?: Record<string, string> } = {\n url: `${endpoint}/v1/traces`\n }\n if (config.headers) {\n exporterConfig.headers = config.headers\n logger.log(\n `@atrim/auto-trace: Using custom headers: ${Object.keys(config.headers).join(', ')}`\n )\n }\n return new OTLPTraceExporter(exporterConfig)\n }\n\n // Create the span processor\n const createSpanProcessor = () => {\n const exporter = createSpanExporter()\n\n if (config.processor === 'simple' || config.type === 'console') {\n logger.log('@atrim/auto-trace: Using SimpleSpanProcessor')\n return new SimpleSpanProcessor(exporter)\n }\n\n // Default to batch processor\n const batchConfig = config.batch ?? {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n logger.log('@atrim/auto-trace: Using BatchSpanProcessor')\n return new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: batchConfig.scheduled_delay_millis,\n maxExportBatchSize: batchConfig.max_export_batch_size\n })\n }\n\n // Create a Layer that sets up the global TracerProvider\n // This uses Effect.sync to run setup synchronously when the layer is built\n return Layer.effectDiscard(\n Effect.sync(() => {\n // Create the provider with resource info\n const provider = new BasicTracerProvider({\n resource: resourceFromAttributes({\n [ATTR_SERVICE_NAME]: serviceName,\n [ATTR_SERVICE_VERSION]: serviceVersion\n }),\n spanProcessors: [createSpanProcessor()]\n })\n\n // Register as the global tracer provider using OTel API\n // (BasicTracerProvider.register() was removed in v2, use OTel API directly)\n OtelApi.trace.setGlobalTracerProvider(provider)\n logger.log('@atrim/auto-trace: Global TracerProvider registered')\n\n // Return cleanup function (not used by Layer.effectDiscard but good practice)\n return () => {\n provider.shutdown().catch((err) => {\n logger.log(`@atrim/auto-trace: Error shutting down provider: ${err}`)\n })\n }\n })\n )\n}\n\n/**\n * Create a fully YAML-driven auto-instrumentation layer\n *\n * This layer reads all configuration from instrumentation.yaml including:\n * - Exporter configuration (type, endpoint, processor)\n * - Auto-tracing configuration (naming rules, filters, performance)\n * - Service metadata (name, version)\n *\n * @example\n * ```typescript\n * import { createFullAutoTracingLayer } from '@atrim/instrument-node/effect/auto'\n *\n * // Everything configured via instrumentation.yaml - no code config needed!\n * const AppLive = createFullAutoTracingLayer()\n *\n * Effect.runPromise(program.pipe(Effect.provide(AppLive)))\n * ```\n */\nexport const createFullAutoTracingLayer = (): Layer.Layer<never> => {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n // Load full config from instrumentation.yaml\n const config = yield* loadFullConfig()\n\n // Get service info from env or defaults\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n // Get auto-tracing config\n const autoConfig = config.effect?.auto_instrumentation\n\n // If auto-instrumentation is disabled, return empty layer\n if (!autoConfig?.enabled) {\n logger.log('@atrim/auto-trace: Auto-instrumentation disabled via config')\n return Layer.empty\n }\n\n // Note: For proper span names on forked fibers, use tracedFork() instead of Effect.fork()\n // ESM module immutability prevents automatic patching of Effect.fork\n patchEffectFork() // Logs a reminder about using tracedFork\n\n // Get exporter config\n const exporterConfig = config.effect?.exporter_config\n\n // Log configuration\n logger.log('@atrim/auto-trace: Full auto-instrumentation enabled')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Exporter: ${exporterConfig?.type ?? 'otlp'}`)\n\n // Create exporter layer\n const exporterLayer = createExporterLayer(exporterConfig, serviceName, serviceVersion)\n\n // Create supervisor\n const supervisor = createAutoTracingSupervisor(autoConfig)\n const supervisorLayer = Supervisor.addSupervisor(supervisor)\n\n // Merge both layers\n return Layer.mergeAll(exporterLayer, supervisorLayer)\n })\n )\n}\n\n/**\n * Fully YAML-driven auto-instrumentation layer\n *\n * This is the recommended way to use auto-instrumentation. All configuration\n * comes from instrumentation.yaml - no code configuration needed.\n *\n * @example\n * ```yaml\n * # instrumentation.yaml\n * effect:\n * auto_instrumentation:\n * enabled: true\n * span_naming:\n * default: \"effect.{function}\"\n * rules:\n * - match: { function: \"internal.*\" }\n * name: \"internal.{function}\"\n * filter:\n * exclude:\n * - \"^internal\\\\.\"\n * exporter_config:\n * type: otlp # or 'console' for dev\n * endpoint: http://localhost:4318\n * processor: batch # or 'simple' for dev\n * ```\n *\n * @example\n * ```typescript\n * import { FullAutoTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * // Just provide the layer - everything else from YAML!\n * Effect.runPromise(program.pipe(Effect.provide(FullAutoTracingLive)))\n * ```\n */\nexport const FullAutoTracingLive: Layer.Layer<never> = createFullAutoTracingLayer()\n","/**\n * Effect-Native Tracing Layer\n *\n * Uses @effect/opentelemetry's NodeSdk.layer for proper Effect integration.\n * This provides automatic HTTP request tracing and Effect.withSpan() support.\n *\n * Requires @effect/opentelemetry peer dependency to be installed.\n */\n\nimport { Effect, Layer, Supervisor } from 'effect'\nimport { NodeSdk, Tracer as OtelTracer, Resource } from '@effect/opentelemetry'\nimport {\n BatchSpanProcessor,\n SimpleSpanProcessor,\n ConsoleSpanExporter,\n BasicTracerProvider\n} from '@opentelemetry/sdk-trace-base'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'\nimport * as OtelApi from '@opentelemetry/api'\nimport { logger } from '@atrim/instrument-core'\nimport { loadFullConfig } from './config.js'\nimport { createAutoTracingSupervisor } from './supervisor.js'\n\n/**\n * Create a layer that provides Effect-native tracing via NodeSdk.layer\n *\n * This integrates with Effect's built-in tracing system, which means:\n * - HTTP requests are automatically traced by @effect/platform\n * - Effect.withSpan() creates proper OTel spans\n * - Parent-child span relationships work correctly\n * - No need to fork fibers for tracing to work\n *\n * Configuration is loaded from instrumentation.yaml (exporter_config section).\n *\n * @example\n * ```typescript\n * import { EffectTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * // HTTP requests automatically traced!\n * const HttpLive = router.pipe(\n * HttpServer.serve(),\n * Layer.provide(ServerLive),\n * Layer.provide(EffectTracingLive),\n * )\n * ```\n */\nexport const createEffectTracingLayer = (): Layer.Layer<never> => {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n // Load config from instrumentation.yaml\n const config = yield* loadFullConfig()\n\n // Get service info\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n // Get exporter config\n const exporterConfig = config.effect?.exporter_config ?? {\n type: 'otlp' as const,\n processor: 'batch' as const\n }\n\n logger.log('@atrim/auto-trace: Effect-native tracing enabled')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Exporter: ${exporterConfig.type}`)\n\n // Handle 'none' type\n if (exporterConfig.type === 'none') {\n logger.log('@atrim/auto-trace: Exporter type is \"none\", using empty layer')\n return Layer.empty\n }\n\n // Create span processor based on config\n const createSpanProcessor = () => {\n // Console exporter\n if (exporterConfig.type === 'console') {\n logger.log('@atrim/auto-trace: Using ConsoleSpanExporter with SimpleSpanProcessor')\n return new SimpleSpanProcessor(new ConsoleSpanExporter())\n }\n\n // OTLP exporter\n const endpoint =\n exporterConfig.endpoint ||\n process.env.OTEL_EXPORTER_OTLP_ENDPOINT ||\n 'http://localhost:4318'\n logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`)\n\n const otlpConfig: { url: string; headers?: Record<string, string> } = {\n url: `${endpoint}/v1/traces`\n }\n if (exporterConfig.headers) {\n otlpConfig.headers = exporterConfig.headers\n logger.log(\n `@atrim/auto-trace: Using custom headers: ${Object.keys(exporterConfig.headers).join(', ')}`\n )\n }\n\n const exporter = new OTLPTraceExporter(otlpConfig)\n\n if (exporterConfig.processor === 'simple') {\n logger.log('@atrim/auto-trace: Using SimpleSpanProcessor')\n return new SimpleSpanProcessor(exporter)\n }\n\n // Default: batch processor\n const batchConfig = exporterConfig.batch ?? {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n logger.log('@atrim/auto-trace: Using BatchSpanProcessor')\n return new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: batchConfig.scheduled_delay_millis,\n maxExportBatchSize: batchConfig.max_export_batch_size\n })\n }\n\n // Create NodeSdk layer - this provides Effect's Tracer and integrates with OTel\n const sdkLayer = NodeSdk.layer(() => ({\n resource: {\n serviceName,\n serviceVersion\n },\n spanProcessor: createSpanProcessor()\n }))\n\n logger.log('@atrim/auto-trace: NodeSdk layer created - HTTP requests will be auto-traced')\n\n // Return the layer, discarding the Resource output since we don't need it\n return Layer.discard(sdkLayer)\n })\n )\n}\n\n/**\n * Effect-native tracing layer using @effect/opentelemetry\n *\n * This is the **recommended** layer for Effect HTTP applications. It provides:\n * - Automatic HTTP request tracing (built into @effect/platform)\n * - Full Effect.withSpan() support for manual spans\n * - Proper parent-child span relationships\n * - No need to fork fibers manually\n *\n * Configuration is loaded from your instrumentation.yaml file.\n *\n * @example\n * ```yaml\n * # instrumentation.yaml\n * effect:\n * exporter_config:\n * type: otlp # or 'console' for dev\n * endpoint: http://localhost:4318\n * headers:\n * x-api-key: your-key\n * processor: batch # or 'simple' for immediate export\n * ```\n *\n * @example\n * ```typescript\n * import { EffectTracingLive } from '@atrim/instrument-node/effect/auto'\n * import { HttpRouter, HttpServer } from \"@effect/platform\"\n * import { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\n *\n * const router = HttpRouter.empty.pipe(\n * HttpRouter.get(\"/\", Effect.succeed(HttpServerResponse.text(\"Hello!\"))),\n * )\n *\n * const HttpLive = router.pipe(\n * HttpServer.serve(),\n * Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),\n * Layer.provide(EffectTracingLive), // <- Just add this!\n * )\n *\n * NodeRuntime.runMain(Layer.launch(HttpLive))\n * // All HTTP requests now automatically traced!\n * ```\n */\nexport const EffectTracingLive: Layer.Layer<never> = createEffectTracingLayer()\n\n// ============================================================================\n// Combined Tracing Layer (Effect HTTP + Fiber Supervisor)\n// ============================================================================\n\n/**\n * Create a combined layer that provides both:\n * 1. Effect-native HTTP tracing (via Effect's Tracer + global OTel provider)\n * 2. Fiber-level auto-tracing (via Supervisor)\n *\n * This gives you automatic spans for:\n * - Every HTTP request (from Effect's platform middleware)\n * - Every forked fiber (from our Supervisor)\n *\n * No manual Effect.withSpan() calls needed.\n *\n * ARCHITECTURE NOTE:\n * Unlike EffectTracingLive which uses NodeSdk.layer (scoped provider),\n * CombinedTracingLive uses a single GLOBAL TracerProvider so that both\n * Effect's Tracer and our Supervisor use the same provider and exporter.\n *\n * This solves the dual-provider problem where HTTP spans and fiber spans\n * would otherwise go to different exporters.\n */\nexport const createCombinedTracingLayer = (): Layer.Layer<never> => {\n return Layer.unwrapEffect(\n Effect.gen(function* () {\n // Load config from instrumentation.yaml\n const config = yield* loadFullConfig()\n\n // Get service info\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n // Get exporter config\n const exporterConfig = config.effect?.exporter_config ?? {\n type: 'otlp' as const,\n processor: 'batch' as const\n }\n\n // Get auto-tracing config for supervisor\n const autoConfig = config.effect?.auto_instrumentation ?? {\n enabled: true,\n granularity: 'fiber' as const,\n span_naming: {\n default: 'effect.{function}',\n infer_from_source: true,\n rules: []\n },\n span_relationships: {\n type: 'parent-child' as const\n },\n filter: { include: [], exclude: [] },\n performance: { sampling_rate: 1.0, min_duration: '0ms', max_concurrent: 0 },\n metadata: { fiber_info: true, source_location: true, parent_fiber: true }\n }\n\n logger.log('@atrim/auto-trace: Combined tracing enabled (HTTP + Fiber)')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Exporter: ${exporterConfig.type}`)\n\n // Handle 'none' type\n if (exporterConfig.type === 'none') {\n logger.log('@atrim/auto-trace: Exporter type is \"none\", using empty layer')\n return Layer.empty\n }\n\n // Create span exporter based on config\n const createSpanExporter = () => {\n if (exporterConfig.type === 'console') {\n logger.log('@atrim/auto-trace: Using ConsoleSpanExporter')\n return new ConsoleSpanExporter()\n }\n\n const endpoint =\n exporterConfig.endpoint ||\n process.env.OTEL_EXPORTER_OTLP_ENDPOINT ||\n 'http://localhost:4318'\n logger.log(`@atrim/auto-trace: Using OTLPTraceExporter (${endpoint})`)\n\n const otlpConfig: { url: string; headers?: Record<string, string> } = {\n url: `${endpoint}/v1/traces`\n }\n if (exporterConfig.headers) {\n otlpConfig.headers = exporterConfig.headers\n logger.log(\n `@atrim/auto-trace: Using custom headers: ${Object.keys(exporterConfig.headers).join(', ')}`\n )\n }\n\n return new OTLPTraceExporter(otlpConfig)\n }\n\n // Create span processor\n const createSpanProcessor = () => {\n const exporter = createSpanExporter()\n\n if (exporterConfig.processor === 'simple' || exporterConfig.type === 'console') {\n logger.log('@atrim/auto-trace: Using SimpleSpanProcessor')\n return new SimpleSpanProcessor(exporter)\n }\n\n const batchConfig = exporterConfig.batch ?? {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n logger.log('@atrim/auto-trace: Using BatchSpanProcessor')\n return new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: batchConfig.scheduled_delay_millis,\n maxExportBatchSize: batchConfig.max_export_batch_size\n })\n }\n\n // === SINGLE GLOBAL TRACERPROVIDER ARCHITECTURE ===\n //\n // 1. Create a BasicTracerProvider with the exporter\n // 2. Register it as the GLOBAL provider\n // 3. Use Effect's Tracer.layerGlobal (uses global provider for Effect spans)\n // 4. Supervisor also uses global provider via OtelApi.trace.getTracer()\n //\n // This ensures ALL spans (HTTP + fiber) go to the same exporter.\n\n // Create a layer that sets up the global TracerProvider\n const globalProviderLayer = Layer.effectDiscard(\n Effect.sync(() => {\n const provider = new BasicTracerProvider({\n resource: resourceFromAttributes({\n [ATTR_SERVICE_NAME]: serviceName,\n [ATTR_SERVICE_VERSION]: serviceVersion\n }),\n spanProcessors: [createSpanProcessor()]\n })\n\n // Register as the global tracer provider\n OtelApi.trace.setGlobalTracerProvider(provider)\n logger.log('@atrim/auto-trace: Global TracerProvider registered')\n })\n )\n\n // Create the Resource layer for @effect/opentelemetry\n const resourceLayer = Resource.layer({\n serviceName,\n serviceVersion\n })\n\n // Create Effect Tracer layer that uses the global provider\n // OtelTracer.layerGlobal uses OtelApi.trace.getTracerProvider() internally\n const effectTracerLayer = OtelTracer.layerGlobal\n\n // Create Supervisor layer for fiber-level tracing\n // The supervisor uses OtelApi.trace.getTracer() which gets the global provider\n const supervisor = createAutoTracingSupervisor(autoConfig)\n const supervisorLayer = Supervisor.addSupervisor(supervisor)\n\n logger.log('@atrim/auto-trace: Combined layer created')\n logger.log(' - HTTP requests: auto-traced via Effect platform (global provider)')\n logger.log(' - Forked fibers: auto-traced via Supervisor (global provider)')\n\n // Compose layers:\n // 1. globalProviderLayer - sets up the global OTel provider\n // 2. resourceLayer - provides Resource service for effectTracerLayer\n // 3. effectTracerLayer - provides Effect's Tracer using global provider\n // 4. supervisorLayer - adds fiber supervision\n //\n // effectTracerLayer requires Resource, so we provide it\n const tracerWithResource = effectTracerLayer.pipe(Layer.provide(resourceLayer))\n\n // Merge all layers together\n return Layer.mergeAll(globalProviderLayer, Layer.discard(tracerWithResource), supervisorLayer)\n })\n )\n}\n\n/**\n * Combined tracing layer providing both HTTP and fiber-level auto-tracing\n *\n * This is the **most comprehensive** tracing option. You get automatic spans for:\n * - Every HTTP request (from Effect's @effect/platform middleware)\n * - Every forked fiber (from our Supervisor)\n *\n * No manual Effect.withSpan() calls needed - everything is traced automatically.\n *\n * @example\n * ```yaml\n * # instrumentation.yaml\n * effect:\n * auto_instrumentation:\n * enabled: true\n * granularity: fiber\n * exporter_config:\n * type: otlp\n * endpoint: http://localhost:4318\n * ```\n *\n * @example\n * ```typescript\n * import { CombinedTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * const HttpLive = router.pipe(\n * HttpServer.serve(),\n * Layer.provide(ServerLive),\n * Layer.provide(CombinedTracingLive),\n * )\n *\n * // Both HTTP requests AND forked fibers are auto-traced!\n * ```\n */\nexport const CombinedTracingLive: Layer.Layer<never> = createCombinedTracingLayer()\n","/**\n * Source Capture Supervisor for Effect-TS (POC)\n *\n * Uses Effect's native source capture feature (from @clayroach/effect@3.19.14-source-capture.0)\n * to automatically capture call-site locations when fibers are forked.\n *\n * This is the POC implementation for issue #145:\n * https://github.com/atrim-ai/instrumentation/issues/145\n *\n * @example\n * ```typescript\n * import { SourceCaptureTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * yield* Effect.fork(doWork()) // Automatically traced with source location!\n * }).pipe(Effect.provide(SourceCaptureTracingLive))\n *\n * // Span name will be \"effect.sendEmail (user-handlers.ts:42)\" instead of \"effect.anonymous\"\n * ```\n */\n\nimport {\n Supervisor,\n Effect,\n Layer,\n FiberRef,\n FiberRefs,\n Context,\n Option,\n Exit,\n Fiber,\n Tracer as EffectTracer,\n GlobalValue\n} from 'effect'\n// Import for currentOtelSpanContext FiberRef (OTel context propagation)\nimport * as TracerModule from 'effect/Tracer'\nimport { Tracer as OtelTracer } from '@effect/opentelemetry'\nimport * as fs from 'node:fs'\nimport * as OtelApi from '@opentelemetry/api'\nimport {\n BatchSpanProcessor,\n SimpleSpanProcessor,\n ConsoleSpanExporter,\n BasicTracerProvider\n} from '@opentelemetry/sdk-trace-base'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'\nimport type { AutoInstrumentationConfig } from '@atrim/instrument-core'\nimport { logger } from '@atrim/instrument-core'\nimport { loadFullConfigSync } from './config.js'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Source location captured by Effect's native source capture feature\n */\nexport interface SourceLocation {\n readonly file: string\n readonly line: number\n readonly column: number\n readonly functionName?: string\n}\n\n/**\n * Access Effect's native currentSourceLocation FiberRef\n *\n * Effect stores this FiberRef using globalValue with a well-known symbol.\n * We access it the same way to avoid importing from internal modules.\n *\n * @internal\n */\nconst currentSourceLocation = GlobalValue.globalValue(\n Symbol.for('effect/FiberRef/currentSourceLocation'),\n () => FiberRef.unsafeMake<SourceLocation | undefined>(undefined)\n)\n\n// ============================================================================\n// Source Code Parsing for Function Name Extraction\n// ============================================================================\n\n/**\n * Cache for source file contents to avoid repeated file reads\n */\nconst sourceFileCache = new Map<string, string[]>()\n\n/**\n * Extract the function name from source code at the given location\n *\n * Parses the source line to find what's being passed to Effect.fork(),\n * Effect.forkDaemon(), etc.\n *\n * Example: `yield* Effect.fork(sendEmail(...))` -> \"sendEmail\"\n */\nfunction extractFunctionNameFromSource(location: SourceLocation): string | undefined {\n try {\n // Get cached lines or read file\n let lines = sourceFileCache.get(location.file)\n if (!lines) {\n // Only cache files, skip if file doesn't exist\n if (!fs.existsSync(location.file)) {\n return undefined\n }\n const content = fs.readFileSync(location.file, 'utf-8')\n lines = content.split('\\n')\n sourceFileCache.set(location.file, lines)\n }\n\n // Get the line (1-indexed)\n const lineIndex = location.line - 1\n if (lineIndex < 0 || lineIndex >= lines.length) {\n return undefined\n }\n\n const line = lines[lineIndex]\n if (!line) return undefined\n\n // Look for patterns like:\n // - Effect.fork(functionName(...))\n // - Effect.forkDaemon(functionName(...))\n // - tracedFork(functionName(...))\n // The column points to the start of Effect.fork or similar\n\n // Extract the portion of the line from the column onwards\n const fromColumn = line.slice(location.column - 1)\n\n // Pattern to match: fork/forkDaemon/forkScoped followed by (functionName\n // We want to capture the function name being passed\n const forkPattern = /(?:fork|forkDaemon|forkScoped|forkIn)\\s*\\(\\s*([a-zA-Z_$][a-zA-Z0-9_$]*)/\n const match = fromColumn.match(forkPattern)\n\n if (match && match[1]) {\n return match[1]\n }\n\n // Also try looking backwards from column for yield* pattern\n // Pattern: yield* Effect.fork(name\n const fullLinePattern =\n /(?:fork|forkDaemon|forkScoped|forkIn)\\s*\\(\\s*([a-zA-Z_$][a-zA-Z0-9_$]*)/\n const fullMatch = line.match(fullLinePattern)\n\n if (fullMatch && fullMatch[1]) {\n return fullMatch[1]\n }\n\n return undefined\n } catch {\n // Silently fail - source parsing is best-effort\n return undefined\n }\n}\n\n// ============================================================================\n// FiberRefs for opt-out and name override\n// ============================================================================\n\n/**\n * FiberRef to enable/disable auto-tracing for specific fibers\n */\nexport const AutoTracingEnabled = FiberRef.unsafeMake<boolean>(true)\n\n/**\n * FiberRef to override auto-generated span name\n */\nexport const AutoTracingSpanName = FiberRef.unsafeMake<Option.Option<string>>(Option.none())\n\n// ============================================================================\n// SourceCaptureSupervisor\n// ============================================================================\n\n/**\n * Supervisor that uses Effect's native source capture to create spans with\n * meaningful names based on the actual call site of Effect.fork().\n *\n * This supervisor reads from `currentSourceLocation` FiberRef which is\n * populated automatically by Effect when source capture is enabled via\n * `Layer.enableSourceCapture` or `Effect.withCaptureStackTraces(true)`.\n */\nexport class SourceCaptureSupervisor extends Supervisor.AbstractSupervisor<void> {\n // WeakMap to associate fibers with their OTel spans\n private readonly fiberSpans = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, OtelApi.Span>()\n\n // WeakMap to associate fibers with their OTel contexts (for child fiber lookups)\n private readonly fiberContexts = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, OtelApi.Context>()\n\n // WeakMap for fiber start times (for min_duration filtering)\n private readonly fiberStartTimes = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, bigint>()\n\n // OpenTelemetry tracer - lazily initialized\n private _tracer: OtelApi.Tracer | null = null\n\n // Active fiber count (for max_concurrent limiting)\n private activeFiberCount = 0\n\n // Default root span for fibers without a ParentSpan in their context\n // This enables auto-instrumentation without requiring Effect.withSpan()\n private _rootSpan: OtelApi.Span | null = null\n\n constructor(private readonly config: AutoInstrumentationConfig) {\n super()\n logger.log('@atrim/source-capture: Supervisor initialized (native source capture)')\n logger.log(` Granularity: ${config.granularity || 'fiber'}`)\n logger.log(` Sampling rate: ${config.performance?.sampling_rate ?? 1.0}`)\n }\n\n /**\n * Set the default root span for auto-instrumentation.\n * Fibers without a ParentSpan will use this as their parent.\n */\n setRootSpan(span: OtelApi.Span): void {\n this._rootSpan = span\n logger.log(`@atrim/source-capture: Root span set - spanId=${span.spanContext().spanId}`)\n }\n\n /**\n * Get the root span (if set)\n */\n get rootSpan(): OtelApi.Span | null {\n return this._rootSpan\n }\n\n /**\n * Get the tracer lazily from global OTel API\n */\n private get tracer(): OtelApi.Tracer {\n if (!this._tracer) {\n logger.log('@atrim/source-capture: Getting tracer from global API')\n this._tracer = OtelApi.trace.getTracer('@atrim/source-capture', '1.0.0')\n }\n return this._tracer\n }\n\n /**\n * Returns the current value (void for this supervisor)\n */\n override get value(): Effect.Effect<void> {\n return Effect.void\n }\n\n /**\n * Called when a fiber starts executing\n */\n override onStart<A, E, R>(\n _context: Context.Context<R>,\n _effect: Effect.Effect<A, E, R>,\n parent: Option.Option<Fiber.RuntimeFiber<unknown, unknown>>,\n fiber: Fiber.RuntimeFiber<A, E>\n ): void {\n const fiberId = fiber.id().id\n logger.log(`@atrim/source-capture: onStart called for fiber ${fiberId}`)\n\n // Check if auto-tracing is enabled for this fiber\n const fiberRefsValue = fiber.getFiberRefs()\n const enabled = FiberRefs.getOrDefault(fiberRefsValue, AutoTracingEnabled)\n if (!enabled) {\n logger.log(`@atrim/source-capture: Auto-tracing disabled for fiber ${fiberId}`)\n return\n }\n\n // Check sampling\n const samplingRate = this.config.performance?.sampling_rate ?? 1.0\n if (samplingRate < 1.0 && Math.random() > samplingRate) {\n return\n }\n\n // Check max concurrent\n const maxConcurrent = this.config.performance?.max_concurrent ?? 0\n if (maxConcurrent > 0 && this.activeFiberCount >= maxConcurrent) {\n return\n }\n\n // Check for span name override\n const nameOverride = FiberRefs.getOrDefault(fiberRefsValue, AutoTracingSpanName)\n\n // ============================================================================\n // KEY: Read native source location from Effect's FiberRef\n // This is populated automatically when source capture is enabled!\n // ============================================================================\n const nativeSourceLocation = FiberRefs.getOrDefault(fiberRefsValue, currentSourceLocation) as\n | SourceLocation\n | undefined\n\n if (nativeSourceLocation) {\n logger.log(`@atrim/source-capture: Found native source location for fiber ${fiberId}`)\n logger.log(` file: ${nativeSourceLocation.file}`)\n logger.log(` line: ${nativeSourceLocation.line}`)\n logger.log(` column: ${nativeSourceLocation.column}`)\n logger.log(` functionName: ${nativeSourceLocation.functionName ?? 'N/A'}`)\n } else {\n logger.log(\n `@atrim/source-capture: No source location for fiber ${fiberId} (source capture may be disabled)`\n )\n }\n\n // Generate span name\n let spanName: string\n let extractedFuncName: string | undefined\n if (Option.isSome(nameOverride)) {\n spanName = nameOverride.value\n } else if (nativeSourceLocation) {\n // Try to extract the actual function name from source code\n // This parses the source line to find what's being passed to Effect.fork()\n extractedFuncName = extractFunctionNameFromSource(nativeSourceLocation)\n\n // Use extracted name, or fall back to stack trace functionName, or 'anonymous'\n const funcName = extractedFuncName ?? nativeSourceLocation.functionName ?? 'anonymous'\n const fileName = nativeSourceLocation.file.split('/').pop() ?? 'unknown'\n spanName = `effect.${funcName} (${fileName}:${nativeSourceLocation.line})`\n\n if (extractedFuncName) {\n logger.log(\n `@atrim/source-capture: Extracted function name \"${extractedFuncName}\" from source`\n )\n }\n } else {\n // Fallback to fiber ID\n spanName = `effect.fiber-${fiberId}`\n }\n\n // Get parent span context\n // Priority: Inherited OTel context (FiberRef) > Effect ParentSpan > parent fiber's span > root\n let parentContext: OtelApi.Context = OtelApi.ROOT_CONTEXT\n let parentFiberId: number | undefined\n\n // ============================================================================\n // KEY FIX: Read inherited OTel context from FiberRef\n // This propagates correctly through fiber hierarchy even when AsyncLocalStorage is lost\n // ============================================================================\n const inheritedOtelContext = FiberRefs.getOrDefault(\n fiberRefsValue,\n TracerModule.currentOtelSpanContext\n ) as OtelApi.Context | undefined\n\n if (inheritedOtelContext) {\n // Use the inherited OTel context from parent fiber\n parentContext = inheritedOtelContext\n const inheritedSpan = OtelApi.trace.getSpan(inheritedOtelContext)\n if (inheritedSpan) {\n const spanCtx = inheritedSpan.spanContext()\n logger.log(\n `@atrim/source-capture: Using inherited OTel context - traceId=${spanCtx.traceId}, spanId=${spanCtx.spanId}`\n )\n }\n } else {\n // Fallback: Try to get the Effect parent span from the context\n const maybeEffectParentSpan = Context.getOption(_context, EffectTracer.ParentSpan)\n\n if (Option.isSome(maybeEffectParentSpan)) {\n const effectSpan = maybeEffectParentSpan.value\n logger.log(\n `@atrim/source-capture: Found ParentSpan - traceId=${effectSpan.traceId}, spanId=${effectSpan.spanId}`\n )\n\n // Create an OTel SpanContext from the Effect span's identifiers\n const otelSpanContext: OtelApi.SpanContext = {\n traceId: effectSpan.traceId,\n spanId: effectSpan.spanId,\n traceFlags: effectSpan.sampled ? OtelApi.TraceFlags.SAMPLED : OtelApi.TraceFlags.NONE,\n isRemote: false\n }\n\n // Wrap the SpanContext in a span object for proper parent-child linking\n const wrappedSpan = OtelApi.trace.wrapSpanContext(otelSpanContext)\n parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, wrappedSpan)\n } else if (Option.isSome(parent)) {\n // Fiber has a parent fiber - try to find its context/span\n parentFiberId = parent.value.id().id\n // First try to get the full OTel context (preserves all context values)\n const parentOtelContext = this.fiberContexts.get(parent.value)\n if (parentOtelContext) {\n parentContext = parentOtelContext\n const parentSpan = OtelApi.trace.getSpan(parentOtelContext)\n if (parentSpan) {\n logger.log(\n `@atrim/source-capture: Using parent fiber's OTel context - traceId=${parentSpan.spanContext().traceId}`\n )\n }\n } else {\n // Fall back to span lookup\n const parentSpan = this.fiberSpans.get(parent.value)\n if (parentSpan) {\n parentContext = OtelApi.trace.setSpan(OtelApi.ROOT_CONTEXT, parentSpan)\n }\n }\n }\n }\n\n // Also capture parent fiber ID for metadata\n if (Option.isSome(parent)) {\n parentFiberId = parent.value.id().id\n }\n\n // Build span attributes\n const attributes: OtelApi.Attributes = {\n 'effect.auto_traced': true,\n 'effect.source_capture': true,\n 'effect.fiber.id': fiberId\n }\n\n // Add source location attributes (OTel semantic conventions for code)\n if (nativeSourceLocation) {\n // Use extracted function name if available, otherwise fall back to stack trace name\n attributes['code.function'] =\n extractedFuncName ?? nativeSourceLocation.functionName ?? 'anonymous'\n attributes['code.filepath'] = nativeSourceLocation.file\n attributes['code.lineno'] = nativeSourceLocation.line\n attributes['code.column'] = nativeSourceLocation.column\n }\n\n // Add parent fiber info\n if (parentFiberId !== undefined) {\n attributes['effect.fiber.parent_id'] = parentFiberId\n }\n\n // Create the span\n const span = this.tracer.startSpan(\n spanName,\n {\n kind: OtelApi.SpanKind.INTERNAL,\n attributes\n },\n parentContext\n )\n\n logger.log(`@atrim/source-capture: Created span \"${spanName}\" for fiber ${fiberId}`)\n\n // Store the new OTel context with the span for child fibers to inherit\n // Note: We can't directly set FiberRef on the fiber here (it's already created),\n // but we store the context in a map so parent fiber lookups work\n const newContext = OtelApi.trace.setSpan(parentContext, span)\n\n // Store span, context, and start time\n this.fiberSpans.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, span)\n this.fiberContexts.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, newContext)\n this.fiberStartTimes.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, process.hrtime.bigint())\n this.activeFiberCount++\n }\n\n /**\n * Called when a fiber completes (success or failure)\n */\n override onEnd<A, E>(exit: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n const fiberId = fiber.id().id\n logger.log(`@atrim/source-capture: onEnd called for fiber ${fiberId}`)\n\n const span = this.fiberSpans.get(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n if (!span) {\n logger.log(`@atrim/source-capture: No span found for fiber ${fiberId} (skipped or filtered)`)\n return\n }\n\n // Check min_duration filtering\n const startTime = this.fiberStartTimes.get(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n if (startTime) {\n const duration = process.hrtime.bigint() - startTime\n const minDuration = this.parseMinDuration(this.config.performance?.min_duration)\n if (minDuration > 0 && duration < minDuration) {\n // Drop span if too short\n this.fiberSpans.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.fiberContexts.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.fiberStartTimes.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.activeFiberCount--\n return\n }\n }\n\n // Set span status based on exit\n if (Exit.isSuccess(exit)) {\n span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n } else {\n span.setStatus({\n code: OtelApi.SpanStatusCode.ERROR,\n message: 'Fiber failed'\n })\n span.setAttribute('effect.fiber.failed', true)\n }\n\n // End the span\n span.end()\n logger.log(`@atrim/source-capture: Ended span for fiber ${fiberId}`)\n\n // Cleanup\n this.fiberSpans.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.fiberContexts.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.fiberStartTimes.delete(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n this.activeFiberCount--\n }\n\n /**\n * Parse min_duration string to nanoseconds\n */\n private parseMinDuration(duration: string | undefined): bigint {\n if (!duration || duration === '0ms') return BigInt(0)\n\n const match = duration.match(/^(\\d+)\\s*(ms|millis|s|sec|seconds|us|micros)?$/i)\n if (!match) return BigInt(0)\n\n const value = parseInt(match[1] ?? '0', 10)\n const unit = (match[2] ?? 'ms').toLowerCase()\n\n switch (unit) {\n case 'us':\n case 'micros':\n return BigInt(value) * BigInt(1000)\n case 'ms':\n case 'millis':\n return BigInt(value) * BigInt(1000000)\n case 's':\n case 'sec':\n case 'seconds':\n return BigInt(value) * BigInt(1000000000)\n default:\n return BigInt(value) * BigInt(1000000) // Default to ms\n }\n }\n}\n\n// ============================================================================\n// Global TracerProvider Setup\n// ============================================================================\n\n/**\n * Sets up the global TracerProvider synchronously.\n * This MUST happen before any layers try to access the global provider.\n *\n * Returns the provider and span processor for reference (needed for shutdown).\n */\nconst setupGlobalTracerProvider = (): {\n provider: BasicTracerProvider\n spanProcessor: BatchSpanProcessor | SimpleSpanProcessor\n} | null => {\n // Load config synchronously\n const config = loadFullConfigSync()\n\n // Get service info\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n // Get exporter config\n const exporterConfig = config.effect?.exporter_config ?? {\n type: 'otlp' as const,\n processor: 'batch' as const\n }\n\n logger.log('@atrim/source-capture: Setting up global TracerProvider')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Exporter: ${exporterConfig.type}`)\n\n // Handle 'none' type\n if (exporterConfig.type === 'none') {\n logger.log('@atrim/source-capture: Exporter type is \"none\", skipping provider setup')\n return null\n }\n\n // Create span exporter based on config\n let exporter\n if (exporterConfig.type === 'console') {\n logger.log('@atrim/source-capture: Using ConsoleSpanExporter')\n exporter = new ConsoleSpanExporter()\n } else {\n const endpoint =\n exporterConfig.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n logger.log(`@atrim/source-capture: Using OTLPTraceExporter (${endpoint})`)\n\n const otlpConfig: { url: string; headers?: Record<string, string> } = {\n url: `${endpoint}/v1/traces`\n }\n if (exporterConfig.headers) {\n otlpConfig.headers = exporterConfig.headers\n logger.log(\n `@atrim/source-capture: Using headers: ${Object.keys(exporterConfig.headers).join(', ')}`\n )\n }\n\n exporter = new OTLPTraceExporter(otlpConfig)\n }\n\n // Create span processor\n let spanProcessor: BatchSpanProcessor | SimpleSpanProcessor\n if (exporterConfig.processor === 'simple' || exporterConfig.type === 'console') {\n logger.log('@atrim/source-capture: Using SimpleSpanProcessor')\n spanProcessor = new SimpleSpanProcessor(exporter)\n } else {\n const batchConfig = exporterConfig.batch ?? {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n logger.log('@atrim/source-capture: Using BatchSpanProcessor')\n spanProcessor = new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: batchConfig.scheduled_delay_millis,\n maxExportBatchSize: batchConfig.max_export_batch_size\n })\n }\n\n // Create and set global provider\n const provider = new BasicTracerProvider({\n resource: resourceFromAttributes({\n [ATTR_SERVICE_NAME]: serviceName,\n [ATTR_SERVICE_VERSION]: serviceVersion\n }),\n spanProcessors: [spanProcessor]\n })\n OtelApi.trace.setGlobalTracerProvider(provider)\n logger.log('@atrim/source-capture: Global TracerProvider registered')\n\n return { provider, spanProcessor }\n}\n\n// Set up the global TracerProvider immediately at module load time\n// This ensures it's available before any Effect layers try to access it\nconst globalProviderSetup = setupGlobalTracerProvider()\n\n// ============================================================================\n// Layers\n// ============================================================================\n\n/**\n * Create the SourceCaptureTracingLive layer\n *\n * This layer:\n * 1. Enables Effect's native source capture via Layer.enableSourceCapture\n * 2. Uses the global TracerProvider (set at module load time)\n * 3. Adds the SourceCaptureSupervisor that reads native source locations\n *\n * The key difference from CombinedTracingLive is that this uses Effect's\n * NATIVE source capture instead of our manual tracedFork() workaround.\n */\nexport const createSourceCaptureTracingLayer = (): Layer.Layer<never> => {\n // Load config synchronously for supervisor\n const config = loadFullConfigSync()\n\n // Get auto-tracing config for supervisor\n const autoConfig = config.effect?.auto_instrumentation ?? {\n enabled: true,\n granularity: 'fiber' as const,\n span_naming: {\n default: 'effect.{function}',\n infer_from_source: true,\n rules: []\n },\n span_relationships: {\n type: 'parent-child' as const\n },\n filter: { include: [], exclude: [] },\n performance: { sampling_rate: 1.0, min_duration: '0ms', max_concurrent: 0 },\n metadata: { fiber_info: true, source_location: true, parent_fiber: true }\n }\n\n // Handle case where provider wasn't set up (exporter type = 'none')\n if (!globalProviderSetup) {\n logger.log('@atrim/source-capture: No TracerProvider, using empty layer')\n return Layer.empty\n }\n\n // Create Supervisor layer for fiber-level tracing\n const supervisor = new SourceCaptureSupervisor(autoConfig)\n const supervisorLayer = Supervisor.addSupervisor(supervisor)\n\n logger.log('@atrim/source-capture: Creating layer')\n logger.log(' - Source capture: ENABLED via Layer.enableSourceCapture')\n logger.log(' - Effect.withSpan(): exports to OTel via our tracer')\n logger.log(' - Forked fibers: auto-traced via SourceCaptureSupervisor')\n\n // Create Effect Tracer layer that DIRECTLY uses our global provider's tracer\n // Use layerWithoutOtelTracer (not layerGlobal) so we can provide our own tracer\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n // Get tracer directly from our global provider (set at module load time)\n const otelTracer = OtelApi.trace.getTracer(serviceName, serviceVersion)\n logger.log(`@atrim/source-capture: Using tracer \"${serviceName}\" from our provider`)\n\n // Use layerWithoutOtelTracer and provide our tracer directly\n // This ensures the Effect tracer uses our TracerProvider's tracer\n const effectTracerLayer = OtelTracer.layerWithoutOtelTracer.pipe(\n Layer.provide(Layer.succeed(OtelTracer.OtelTracer, otelTracer))\n )\n\n // Compose all layers\n return Layer.mergeAll(effectTracerLayer, Layer.enableSourceCapture, supervisorLayer)\n}\n\n/**\n * Native Source Capture Tracing Layer (POC for issue #145)\n *\n * This layer uses Effect's NATIVE source capture feature to automatically\n * capture call-site locations when fibers are forked. No more need for\n * manual `tracedFork()` calls!\n *\n * **Key difference from CombinedTracingLive:**\n * - CombinedTracingLive: Requires `tracedFork()` wrapper for source capture\n * - SourceCaptureTracingLive: Uses Effect's native source capture (no wrappers!)\n *\n * @example\n * ```yaml\n * # instrumentation.yaml\n * effect:\n * auto_instrumentation:\n * enabled: true\n * exporter_config:\n * type: console # or 'otlp'\n * ```\n *\n * @example\n * ```typescript\n * import { SourceCaptureTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * // Just use regular Effect.fork() - no wrapper needed!\n * yield* Effect.fork(sendEmail()) // Span: \"effect.sendEmail (user-handlers.ts:42)\"\n * yield* Effect.fork(processOrder()) // Span: \"effect.processOrder (order-service.ts:18)\"\n * }).pipe(Effect.provide(SourceCaptureTracingLive))\n *\n * Effect.runPromise(program)\n * ```\n */\nexport const SourceCaptureTracingLive: Layer.Layer<never> = createSourceCaptureTracingLayer()\n\n// ============================================================================\n// Opt-out utilities\n// ============================================================================\n\n/**\n * Disable auto-tracing for a specific Effect\n */\nexport const withoutAutoTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => effect.pipe(Effect.locally(AutoTracingEnabled, false))\n\n/**\n * Override the auto-generated span name for a specific Effect\n */\nexport const setSpanName =\n (name: string) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.locally(AutoTracingSpanName, Option.some(name)))\n\n/**\n * Disable source capture for a hot path (opt-out)\n *\n * Use this to disable source capture for performance-critical code paths\n * where the ~0.001ms overhead is unacceptable.\n */\nexport const withoutSourceCapture = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => Effect.withCaptureStackTraces(false)(effect)\n\n// ============================================================================\n// Provider Shutdown\n// ============================================================================\n\n/**\n * Flush all pending spans and shutdown the TracerProvider.\n * Call this before your application exits to ensure all spans are exported.\n *\n * @example\n * ```typescript\n * import { flushAndShutdown } from '@atrim/instrument-node/effect/auto'\n *\n * // At the end of your application\n * await flushAndShutdown()\n * process.exit(0)\n * ```\n */\nexport const flushAndShutdown = async (): Promise<void> => {\n if (globalProviderSetup?.provider) {\n logger.log('@atrim/source-capture: Flushing and shutting down TracerProvider...')\n await globalProviderSetup.provider.forceFlush()\n await globalProviderSetup.provider.shutdown()\n logger.log('@atrim/source-capture: TracerProvider shutdown complete')\n }\n}\n\n/**\n * Force flush all pending spans without shutting down.\n * Use this if you need to ensure spans are exported but want to continue tracing.\n */\nexport const forceFlush = async (): Promise<void> => {\n if (globalProviderSetup?.provider) {\n logger.log('@atrim/source-capture: Force flushing TracerProvider...')\n await globalProviderSetup.provider.forceFlush()\n logger.log('@atrim/source-capture: Force flush complete')\n }\n}\n","/**\n * Operation Tracing Supervisor for Effect-TS\n *\n * Uses OpSupervision to trace high-level Effect operations like Effect.all,\n * Effect.forEach, etc. This supervisor reads operation metadata from the\n * `trace` field that Effect populates when operations are created.\n *\n * Requires the @clayroach/effect fork which adds OperationMeta to the trace field.\n *\n * The `OperationTracingLive` layer automatically enables the OpSupervision runtime\n * flag, so no additional configuration is needed.\n *\n * @example\n * ```typescript\n * import { OperationTracingLive } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * // Automatically traced with span \"effect.all\" including item count\n * yield* Effect.all([doA(), doB(), doC()])\n *\n * // Automatically traced with span \"effect.forEach\"\n * yield* Effect.forEach(items, processItem)\n * }).pipe(Effect.provide(OperationTracingLive))\n * ```\n */\n\nimport {\n Supervisor,\n Effect,\n Layer,\n Exit,\n Fiber,\n RuntimeFlags,\n RuntimeFlagsPatch,\n Context,\n Option\n} from 'effect'\nimport * as EffectTracer from 'effect/Tracer'\nimport * as OtelApi from '@opentelemetry/api'\nimport { logger } from '@atrim/instrument-core'\nimport { loadConfigWithOptions } from '../../../core/config-loader.js'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Operation metadata stored in the trace field by Effect.all, Effect.forEach, etc.\n * This matches the OperationMeta interface in the Effect fork's core.ts\n */\nexport interface OperationMeta {\n readonly _tag: 'OperationMeta'\n readonly op: string // 'all', 'forEach', 'retry', etc.\n readonly count?: number // Item count for all/forEach\n readonly capturedAt: string // Stack trace at creation time\n}\n\n/**\n * Global span naming configuration for operation tracing\n */\nexport interface SpanNamingConfig {\n /** Include source location in span name (default: true) */\n readonly includeLocation: boolean\n /** Span name template with variables: {op}, {file}, {filename}, {line}, {column} */\n readonly template: string\n}\n\n/**\n * Default span naming configuration\n */\nconst defaultSpanNaming: SpanNamingConfig = {\n includeLocation: true,\n template: 'effect.{op} ({filename}:{line})'\n}\n\n/**\n * Configuration for which operations to trace\n */\nexport interface OperationConfig {\n readonly name: string // 'all', 'forEach', 'retry'\n readonly spanNameTemplate?: string // Custom span name template (overrides global template)\n readonly includeCount?: boolean // Add item count to attributes\n readonly includeStack?: boolean // Add stack trace to attributes\n}\n\n/**\n * Source location parsed from stack trace\n */\ninterface ParsedSourceLocation {\n readonly file: string\n readonly line: number\n readonly column: number | undefined\n}\n\n// ============================================================================\n// Stack trace parsing\n// ============================================================================\n\n/**\n * Parse source location from a raw stack trace string.\n * Skips internal Effect frames to find the user's call site.\n */\nfunction parseSourceLocation(stack: string): ParsedSourceLocation | undefined {\n const lines = stack.split('\\n')\n\n for (const line of lines.slice(1)) {\n // Skip internal frames\n if (\n line.includes('node_modules') ||\n line.includes('/effect/') ||\n line.includes('fiberRuntime.ts') ||\n line.includes('core.ts')\n ) {\n continue\n }\n\n // Parse: \" at functionName (file:line:column)\" or \" at file:line:column\"\n const match = line.match(/at\\s+(?:.*?\\s+\\()?(.+):(\\d+):(\\d+)\\)?/)\n if (match && match[1] && match[2]) {\n return {\n file: match[1],\n line: parseInt(match[2], 10),\n column: match[3] ? parseInt(match[3], 10) : undefined\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Check if an effect has OperationMeta in its trace field\n */\nfunction getOperationMeta(\n effect: Effect.Effect<unknown, unknown, unknown>\n): OperationMeta | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const trace = (effect as any).trace\n if (trace && trace._tag === 'OperationMeta') {\n return trace as OperationMeta\n }\n return undefined\n}\n\n/**\n * Template variables for span naming\n */\ninterface TemplateVariables {\n op: string\n file: string\n filename: string\n line: string\n column: string\n}\n\n/**\n * Apply template variables to a span name template\n *\n * Supports: {op}, {file}, {filename}, {line}, {column}\n */\nfunction applyTemplate(template: string, vars: TemplateVariables): string {\n return template\n .replace(/\\{op\\}/g, vars.op)\n .replace(/\\{file\\}/g, vars.file)\n .replace(/\\{filename\\}/g, vars.filename)\n .replace(/\\{line\\}/g, vars.line)\n .replace(/\\{column\\}/g, vars.column)\n}\n\n// ============================================================================\n// OperationTracingSupervisor\n// ============================================================================\n\n/**\n * Supervisor that traces Effect operations using OpSupervision.\n *\n * When OpSupervision is enabled, the Effect runtime calls `onEffect(fiber, effect)`\n * for every Effect operation in the runLoop. This supervisor checks if the effect\n * has OperationMeta in its trace field and creates spans accordingly.\n */\nexport class OperationTracingSupervisor extends Supervisor.AbstractSupervisor<void> {\n // Map of configured operations by name\n private readonly configuredOps: Map<string, OperationConfig>\n\n // Global span naming configuration\n private readonly spanNaming: SpanNamingConfig\n\n // Track processed effects to avoid duplicate spans (using WeakSet for GC)\n private readonly processedEffects = new WeakSet<object>()\n\n // Track spans per fiber for proper lifecycle management\n private readonly fiberSpans = new WeakMap<\n Fiber.RuntimeFiber<unknown, unknown>,\n Map<string, OtelApi.Span>\n >()\n\n // OpenTelemetry tracer - lazily initialized\n private _tracer: OtelApi.Tracer | null = null\n\n constructor(operations: OperationConfig[], spanNaming: SpanNamingConfig = defaultSpanNaming) {\n super()\n this.configuredOps = new Map(operations.map((op) => [op.name, op]))\n this.spanNaming = spanNaming\n logger.log('@atrim/operation-tracing: Supervisor initialized')\n logger.log(` Configured operations: ${Array.from(this.configuredOps.keys()).join(', ')}`)\n }\n\n /**\n * Get the tracer lazily from global OTel API\n */\n private get tracer(): OtelApi.Tracer {\n if (!this._tracer) {\n this._tracer = OtelApi.trace.getTracer('@atrim/operation-tracing', '1.0.0')\n }\n return this._tracer\n }\n\n /**\n * Returns the current value (void for this supervisor)\n */\n override get value(): Effect.Effect<void> {\n return Effect.void\n }\n\n /**\n * Called for EVERY Effect operation when OpSupervision is enabled.\n *\n * This is the key hook for operation-level tracing. We check if the effect\n * has OperationMeta and create a span if configured.\n */\n override onEffect<A, E>(\n fiber: Fiber.RuntimeFiber<A, E>,\n effect: Effect.Effect<unknown, unknown, unknown>\n ): void {\n // Quick return if already processed (most common case)\n if (this.processedEffects.has(effect as object)) {\n return\n }\n\n // Check for operation metadata\n const meta = getOperationMeta(effect)\n if (!meta) {\n return\n }\n\n // Check if this operation is configured for tracing\n const config = this.configuredOps.get(meta.op)\n if (!config) {\n return\n }\n\n // Mark as processed to avoid duplicate spans\n this.processedEffects.add(effect as object)\n\n const fiberId = fiber.id().id\n logger.log(`@atrim/operation-tracing: Found operation \"${meta.op}\" in fiber ${fiberId}`)\n\n // Build span attributes (use OtelApi.Attributes like SourceCaptureSupervisor)\n const attributes: OtelApi.Attributes = {\n 'effect.operation': meta.op\n }\n\n if (config.includeCount && meta.count !== undefined) {\n // Set as number directly (no conversion needed - already a number)\n attributes['effect.item_count'] = meta.count\n }\n\n // Parse source location first - we need it for span name and attributes\n const location = config.includeStack ? parseSourceLocation(meta.capturedAt) : undefined\n\n if (config.includeStack && location) {\n attributes['code.filepath'] = location.file\n // Set as numbers directly (parseInt already returns number)\n attributes['code.lineno'] = location.line\n if (location.column !== undefined) {\n attributes['code.column'] = location.column\n }\n }\n\n // Build span name using template system\n // Priority: per-operation template > global template > fallback\n let spanName: string\n\n // Build template variables\n const templateVars: TemplateVariables = {\n op: meta.op,\n file: location?.file ?? 'unknown',\n filename: location?.file?.split('/').pop() ?? 'unknown',\n line: location?.line?.toString() ?? '0',\n column: location?.column?.toString() ?? '0'\n }\n\n if (config.spanNameTemplate) {\n // Per-operation template override\n spanName = applyTemplate(config.spanNameTemplate, templateVars)\n } else if (this.spanNaming.includeLocation && location) {\n // Use global template with location info\n spanName = applyTemplate(this.spanNaming.template, templateVars)\n } else {\n // Fallback: just operation name without location\n spanName = `effect.${meta.op}`\n }\n\n // Get parent context from Effect fiber's context (like SourceCaptureSupervisor does)\n let parentContext: OtelApi.Context = OtelApi.ROOT_CONTEXT\n const fiberContext = fiber.currentContext\n const maybeEffectParentSpan = Context.getOption(fiberContext, EffectTracer.ParentSpan)\n\n if (Option.isSome(maybeEffectParentSpan)) {\n const effectSpan = maybeEffectParentSpan.value\n // Convert Effect span to OTel context\n parentContext = OtelApi.trace.setSpan(\n OtelApi.ROOT_CONTEXT,\n OtelApi.trace.wrapSpanContext({\n traceId: effectSpan.traceId,\n spanId: effectSpan.spanId,\n traceFlags: OtelApi.TraceFlags.SAMPLED\n })\n )\n logger.log(\n `@atrim/operation-tracing: Using parent span traceId=${effectSpan.traceId.slice(0, 8)}...`\n )\n }\n\n // Create span without attributes first\n const span = this.tracer.startSpan(\n spanName,\n {\n kind: OtelApi.SpanKind.INTERNAL\n },\n parentContext\n )\n\n // Set attributes after span creation using setAttribute() for proper type handling\n span.setAttribute('effect.operation', meta.op)\n\n if (config.includeCount && meta.count !== undefined) {\n span.setAttribute('effect.item_count', meta.count)\n }\n\n if (config.includeStack && location) {\n // Set source location attributes (already parsed above for span name)\n span.setAttribute('code.filepath', location.file)\n span.setAttribute('code.lineno', location.line)\n if (location.column !== undefined) {\n span.setAttribute('code.column', location.column)\n }\n }\n\n logger.log(\n `@atrim/operation-tracing: Created span \"${spanName}\" - spanId=${span.spanContext().spanId}`\n )\n\n // End span immediately - operation metadata capture is synchronous\n // OpSupervision only calls onEffect(), not onEnd(), so we can't rely on fiber lifecycle\n span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n span.end()\n\n logger.log(`@atrim/operation-tracing: Ended span \"${spanName}\"`)\n\n // Store span for this fiber (keeping for now, but may not be needed)\n let spanMap = this.fiberSpans.get(fiber)\n if (!spanMap) {\n spanMap = new Map()\n this.fiberSpans.set(fiber, spanMap)\n }\n\n // Use operation + stack hash as key (since same operation might be called multiple times)\n const spanKey = `${meta.op}-${meta.capturedAt.slice(0, 100)}`\n spanMap.set(spanKey, span)\n }\n\n /**\n * Called when a fiber starts - we don't need this for operation tracing\n */\n override onStart(): void {\n // No-op for operation tracing\n }\n\n /**\n * Called when a fiber ends - end all spans for this fiber\n */\n override onEnd<A, E>(exit: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n const spanMap = this.fiberSpans.get(fiber)\n if (!spanMap) {\n return\n }\n\n const isError = exit._tag === 'Failure'\n const fiberId = fiber.id().id\n\n for (const [_key, span] of spanMap) {\n span.setStatus({\n code: isError ? OtelApi.SpanStatusCode.ERROR : OtelApi.SpanStatusCode.OK\n })\n span.end()\n logger.log(\n `@atrim/operation-tracing: Ended span for fiber ${fiberId} (${isError ? 'error' : 'success'})`\n )\n }\n\n this.fiberSpans.delete(fiber)\n }\n}\n\n// ============================================================================\n// Layer Factory\n// ============================================================================\n\n/**\n * Default operation configurations\n */\nconst defaultOperations: OperationConfig[] = [\n { name: 'all', includeCount: true, includeStack: true },\n { name: 'forEach', includeCount: true, includeStack: true }\n]\n\n/**\n * Create a Layer that adds the OperationTracingSupervisor.\n *\n * NOTE: This layer adds the supervisor, but OpSupervision must also be enabled\n * for the runtime to call onEffect(). Use Effect.withRuntimeFlags to enable\n * OpSupervision, or use the enableOpSupervision helper.\n *\n * @param operations - Configuration for which operations to trace\n * @param spanNaming - Global span naming configuration\n */\nexport const makeOperationTracingLayer = (\n operations: OperationConfig[] = defaultOperations,\n spanNaming: SpanNamingConfig = defaultSpanNaming\n): Layer.Layer<never> => {\n const supervisor = new OperationTracingSupervisor(operations, spanNaming)\n return Supervisor.addSupervisor(supervisor)\n}\n\n/**\n * Helper to enable OpSupervision runtime flag for an effect.\n *\n * OpSupervision causes the runtime to call supervisor.onEffect() for every\n * Effect operation. This has a performance cost but enables operation-level tracing.\n *\n * @example\n * ```typescript\n * const program = myEffect.pipe(\n * enableOpSupervision,\n * Effect.provide(OperationTracingLive)\n * )\n * ```\n */\nexport const enableOpSupervision = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n Effect.withRuntimeFlagsPatch(effect, RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision))\n\n/**\n * Load operation tracing config from instrumentation.yaml and create supervisor layer.\n *\n * If no config is found or operation_tracing section is missing, uses sensible defaults\n * (traces Effect.all and Effect.forEach with count and stack info).\n *\n * Only explicitly disabled (enabled: false) will turn off operation tracing.\n */\nconst loadOperationTracingLayer = (): Layer.Layer<never> =>\n Layer.unwrapEffect(\n Effect.gen(function* () {\n // Load config from instrumentation.yaml\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(),\n catch: (error) => {\n logger.log(`@atrim/operation-tracing: Failed to load config: ${error}`)\n return error\n }\n }).pipe(Effect.catchAll(() => Effect.succeed(null)))\n\n // Extract operation_tracing config\n const opTracingConfig = config?.effect?.operation_tracing\n\n // Only disable if explicitly set to enabled: false\n if (opTracingConfig?.enabled === false) {\n logger.log('@atrim/operation-tracing: Operation tracing disabled in config')\n return Layer.empty\n }\n\n // Extract span naming config with defaults\n const spanNaming: SpanNamingConfig = {\n includeLocation: opTracingConfig?.span_naming?.include_location ?? true,\n template: opTracingConfig?.span_naming?.template ?? 'effect.{op} ({filename}:{line})'\n }\n\n logger.log(\n `@atrim/operation-tracing: Span naming - includeLocation=${spanNaming.includeLocation}, template=\"${spanNaming.template}\"`\n )\n\n // Use config operations if provided, otherwise use defaults\n const operations: OperationConfig[] = opTracingConfig?.operations\n ? opTracingConfig.operations.map((op) => ({\n name: op.name,\n ...(op.span_name && { spanNameTemplate: op.span_name }),\n includeCount: op.include_count ?? true,\n includeStack: op.include_stack ?? true\n }))\n : defaultOperations\n\n const source = opTracingConfig?.operations ? 'instrumentation.yaml' : 'defaults'\n logger.log(\n `@atrim/operation-tracing: Loaded ${operations.length} operation configs from ${source}`\n )\n\n return makeOperationTracingLayer(operations, spanNaming)\n })\n )\n\n/**\n * Pre-configured layer for automatic operation tracing.\n *\n * **Zero-config by default** - Works out of the box with sensible defaults:\n * - Traces `Effect.all` and `Effect.forEach` operations\n * - Includes item count and source location in span attributes\n *\n * **Important:** You must enable OpSupervision for operation tracing to work.\n * Use `withOperationTracing(effect)` for the simplest setup, or manually:\n * `enableOpSupervision` + `Effect.provide(OperationTracingLive)`.\n *\n * @example\n * ```typescript\n * // Simplest: use withOperationTracing wrapper\n * const program = Effect.gen(function* () {\n * yield* Effect.all([doA(), doB()]) // Automatically traced\n * }).pipe(withOperationTracing)\n *\n * // Or manually enable OpSupervision + provide layer\n * const program = myEffect.pipe(\n * enableOpSupervision,\n * Effect.provide(OperationTracingLive)\n * )\n * ```\n */\nexport const OperationTracingLive = loadOperationTracingLayer()\n\n/**\n * Convenience wrapper that enables operation tracing for an effect.\n *\n * This is the simplest way to use operation tracing - just wrap your effect:\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* Effect.all([doA(), doB()]) // Automatically creates \"effect.all\" span\n * yield* Effect.forEach(items, process) // Automatically creates \"effect.forEach\" span\n * }).pipe(withOperationTracing)\n *\n * Effect.runPromise(program)\n * ```\n */\nexport const withOperationTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => effect.pipe(enableOpSupervision, Effect.provide(OperationTracingLive))\n"]}
1
+ {"version":3,"sources":["../../../../../../core/src/instrumentation-schema.ts","../../../../../../core/src/errors.ts","../../../../../../core/src/services/config-loader.ts","../../../../../../core/src/logger.ts","../../../../../src/core/config-loader.ts","../../../../../src/integrations/effect/auto/config.ts","../../../../../src/integrations/effect/auto/span-control.ts","../../../../../src/integrations/effect/auto/unified-tracing-supervisor.ts","../../../../../src/integrations/effect/auto/index.ts","../../../../../src/integrations/effect/auto/naming.ts","../../../../../src/integrations/effect/auto/traced-fork.ts","../../../../../src/integrations/effect/auto/patch-fork.ts"],"names":["parseYaml","parseYAML","fs","path","__publicField","existsSync","join","Context","Effect","Layer","trace","FiberRef","Option","EffectTracer","context","OtelTracer","basename"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoXO,SAAS,uBAAuB,OAAA,EAAkD;AACvF,EAAA,IAAI,MAAA;AAGJ,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,MAAA,GAASA,MAAU,OAAO,CAAA;EAC5B,CAAA,MAAO;AACL,IAAA,MAAA,GAAS,OAAA;AACX,EAAA;AAGA,EAAA,OAAO,2BAAA,CAA4B,MAAM,MAAM,CAAA;AACjD;kDA1Xa,mBAAA,CAAA,CAYA,yBAAA,CAAA,CA4CA,sBA2BA,+BAAA,CAAA,CAkGA,4BAAA,CAAA,CAiDA,2BAiCA,oBAAA,CAAA,CAiCA,2BAAA,CAAA,CAuCA,aAAA,CAAA,CC7TA,cAAA,CAAA,CAYA,qBAAA,CAAA,CAYA,iBCzBP,iBAAA,CAAA,CAyCO,YAAA,CAAA,CAQP,kBA6BA,kBAAA,CAAA,CAiCA,sBAAA,CAAA,CA6EA,gBAAA,CAAA,CCxMA,MAAA,CAAA,CAwFO;;;;;;AH7FN,IAAM,mBAAA,GAAsB,EAAE,MAAA,CAAO;AAC1C,MAAA,OAAA,EAAS,EAAE,MAAA,EAAA;MACX,OAAA,EAAS,CAAA,CAAE,OAAA,EAAA,CAAU,QAAA,EAAA;MACrB,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IAAA;AAAA,EACF;AACA,EAAA,cAAA,GAAiB,IAAA;AAGjB,EAAA,MAAA,CAAO,IAAI,6EAA6E,CAAA;AACxF,EAAA,MAAA,CAAO,IAAI,2DAA2D,CAAA;AACxE;AAKO,SAAS,iBAAA,GAA0B;AACxC,EAAA,cAAA,GAAiB,KAAA;AACnB;;;AHgFA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAQA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKA,+BAAA,EAAA;AAKO,IAAM,8BAA8B,CACzC,MAAA,KACG,IAAK,CAAA,+BAAA,EAAA,EAAA,YAAA,CAAA,kCAAA,CAAA,EAA2C,yBAA0B,MAAM","file":"index.js","sourcesContent":["/**\n * Configuration schema using Zod\n */\nimport { z } from 'zod'\nimport { parse as parseYaml } from 'yaml'\n\nexport const PatternConfigSchema = z.object({\n pattern: z.string(),\n enabled: z.boolean().optional(),\n description: z.string().optional()\n})\n\n/**\n * Configuration for automatic span isolation in Effect operations\n *\n * This prevents context leakage when using FiberSet.run, Effect.fork, etc.\n * while maintaining logical parent relationships via span links.\n */\nexport const AutoIsolationConfigSchema = z.object({\n // Global enable/disable for auto-isolation\n enabled: z.boolean().default(false),\n\n // Which operators to auto-isolate\n operators: z\n .object({\n fiberset_run: z.boolean().default(true),\n effect_fork: z.boolean().default(true),\n effect_fork_daemon: z.boolean().default(true),\n effect_fork_in: z.boolean().default(false)\n })\n .default({}),\n\n // Virtual parent tracking configuration\n tracking: z\n .object({\n use_span_links: z.boolean().default(true),\n use_attributes: z.boolean().default(true),\n capture_logical_parent: z.boolean().default(true)\n })\n .default({}),\n\n // Span categorization\n attributes: z\n .object({\n category: z.string().default('background_task'),\n add_metadata: z.boolean().default(true)\n })\n .default({})\n})\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\n/**\n * Span naming rule for auto-instrumentation\n *\n * Allows matching fibers based on file path, function name, etc.\n * and applying custom span names with template variables.\n */\nexport const SpanNamingRuleSchema = z.object({\n // Match criteria (all specified criteria must match)\n match: z.object({\n // Regex pattern to match file path\n file: z.string().optional(),\n // Regex pattern to match function name\n function: z.string().optional(),\n // Regex pattern to match module name\n module: z.string().optional()\n }),\n // Span name template with variables:\n // {fiber_id} - Fiber ID\n // {function} - Function name\n // {module} - Module name\n // {file} - File path\n // {line} - Line number\n // {operator} - Effect operator (gen, all, forEach, etc.)\n // {match:field:N} - Captured regex group from match\n name: z.string()\n})\n\n/**\n * Auto-instrumentation configuration for Effect operations\n *\n * Enables automatic tracing of all Effect fibers without manual\n * Effect.withSpan() calls. Configuration-driven via instrumentation.yaml.\n */\nexport const AutoInstrumentationConfigSchema = z.object({\n // Enable/disable auto-instrumentation\n enabled: z.boolean().default(false),\n\n // Tracing granularity\n // - 'fiber': Trace at fiber creation (recommended, lower overhead)\n // - 'operator': Trace each Effect operator (higher granularity, more overhead)\n granularity: z.enum(['fiber', 'operator']).default('fiber'),\n\n // Smart span naming configuration\n span_naming: z\n .object({\n // Default span name template when no rules match\n default: z.string().default('effect.fiber.{fiber_id}'),\n\n // Infer span names from source code (requires stack trace parsing)\n // Adds ~50-100μs overhead per fiber\n infer_from_source: z.boolean().default(true),\n\n // Naming rules (first match wins)\n rules: z.array(SpanNamingRuleSchema).default([])\n })\n .default({}),\n\n // Span relationship configuration for forked fibers\n // Controls how child fiber spans relate to their parent/forking context\n span_relationships: z\n .object({\n // Relationship type between forked fiber spans and their parent context\n // - 'parent-child': Use parent-child relationship (default, traditional tracing)\n // Parent span shows child as nested. Works well with most observability tools.\n // - 'span-links': Use span links (semantically correct for async forks per OTel spec)\n // Fibers get independent traces linked to parent. Better for long-running fibers.\n // - 'both': Create parent-child AND add span links\n // Maximum visibility but may create redundant data.\n type: z.enum(['parent-child', 'span-links', 'both']).default('parent-child'),\n\n // Custom attributes to add to span links (only used when type includes links)\n link_attributes: z\n .object({\n // Link type identifier\n 'link.type': z.string().default('fork'),\n // Custom attributes (key-value pairs)\n custom: z.record(z.string()).optional()\n })\n .optional()\n })\n .default({}),\n\n // Pattern-based filtering\n filter: z\n .object({\n // Only trace spans matching these patterns (empty = trace all)\n include: z.array(z.string()).default([]),\n\n // Never trace spans matching these patterns\n exclude: z.array(z.string()).default([])\n })\n .default({}),\n\n // Performance controls\n performance: z\n .object({\n // Sample rate (0.0 - 1.0)\n sampling_rate: z.number().min(0).max(1).default(1.0),\n\n // Skip fibers shorter than this duration (e.g., \"10ms\", \"100 millis\")\n min_duration: z.string().default('0ms'),\n\n // Maximum concurrent traced fibers (0 = unlimited)\n max_concurrent: z.number().default(0)\n })\n .default({}),\n\n // Automatic metadata extraction\n metadata: z\n .object({\n // Extract Effect fiber information\n fiber_info: z.boolean().default(true),\n\n // Extract source location (file:line)\n source_location: z.boolean().default(true),\n\n // Extract parent fiber information\n parent_fiber: z.boolean().default(true)\n })\n .default({})\n})\n\nexport type AutoInstrumentationConfig = z.infer<typeof AutoInstrumentationConfigSchema>\nexport type SpanNamingRule = z.infer<typeof SpanNamingRuleSchema>\n\n/**\n * Operation tracing configuration for Effect.all, Effect.forEach, etc.\n *\n * Enables automatic tracing of high-level Effect operations without manual\n * Effect.withSpan() calls. Uses OpSupervision to hook into every operation.\n */\nexport const OperationTracingConfigSchema = z.object({\n // Enable/disable operation tracing\n enabled: z.boolean().default(false),\n\n // Global span naming settings\n span_naming: z\n .object({\n // Include source location (file:line) in span name\n // Default: true - produces \"effect.all (index.ts:42)\"\n // When false - produces \"effect.all\"\n include_location: z.boolean().default(true),\n\n // Span name template with variables:\n // {op} - Operation name (all, forEach, retry, etc.)\n // {file} - Full file path\n // {filename} - Just the filename (basename)\n // {line} - Line number\n // {column} - Column number\n // Default: \"effect.{op} ({filename}:{line})\"\n template: z.string().default('effect.{op} ({filename}:{line})')\n })\n .default({}),\n\n // Operations to trace\n operations: z\n .array(\n z.object({\n // Operation name: 'all', 'forEach', 'retry', etc.\n name: z.string(),\n // Custom span name template (overrides global span_naming.template)\n // Supports same variables: {op}, {file}, {filename}, {line}, {column}\n span_name: z.string().optional(),\n // Include item count in span attributes\n include_count: z.boolean().default(true),\n // Include stack trace in span attributes\n include_stack: z.boolean().default(true)\n })\n )\n .default([])\n})\n\nexport type OperationTracingConfig = z.infer<typeof OperationTracingConfigSchema>\n\n/**\n * HTTP instrumentation filtering configuration\n *\n * Allows filtering of HTTP requests to prevent noisy traces\n * (e.g., health checks, OTLP exports, internal endpoints)\n */\nexport const HttpFilteringConfigSchema = z.object({\n // Patterns to ignore for outgoing HTTP requests (string patterns only in YAML)\n ignore_outgoing_urls: z.array(z.string()).optional(),\n\n // Patterns to ignore for incoming HTTP requests (string patterns only in YAML)\n ignore_incoming_paths: z.array(z.string()).optional(),\n\n // Require parent span for outgoing requests (prevents root spans for HTTP calls)\n require_parent_for_outgoing_spans: z.boolean().optional(),\n\n // Trace context propagation configuration\n // Controls which cross-origin requests receive W3C Trace Context headers (traceparent, tracestate)\n propagate_trace_context: z\n .object({\n // Strategy for trace propagation\n // - \"all\": Propagate to all cross-origin requests (may cause CORS errors)\n // - \"none\": Never propagate trace headers\n // - \"same-origin\": Only propagate to same-origin requests (default, safe)\n // - \"patterns\": Propagate based on include_urls patterns\n strategy: z.enum(['all', 'none', 'same-origin', 'patterns']).default('same-origin'),\n\n // URL patterns to include when strategy is \"patterns\"\n // Supports regex patterns (e.g., \"^https://api\\\\.myapp\\\\.com\")\n include_urls: z.array(z.string()).optional()\n })\n .optional()\n})\n\n/**\n * Exporter configuration for OpenTelemetry tracing\n *\n * Allows configuring how traces are exported via instrumentation.yaml\n */\nexport const ExporterConfigSchema = z.object({\n // Exporter type: 'otlp' | 'console' | 'none'\n // - 'otlp': Export to OTLP endpoint (production)\n // - 'console': Log spans to console (development)\n // - 'none': No export (disable tracing)\n type: z.enum(['otlp', 'console', 'none']).default('otlp'),\n\n // OTLP endpoint URL (for type: otlp)\n // Defaults to OTEL_EXPORTER_OTLP_ENDPOINT env var or http://localhost:4318\n endpoint: z.string().optional(),\n\n // Custom headers to send with OTLP requests (for type: otlp)\n // Useful for authentication (x-api-key, Authorization, etc.)\n headers: z.record(z.string()).optional(),\n\n // Span processor type\n // - 'batch': Batch spans for export (production, lower overhead)\n // - 'simple': Export immediately (development, no batching delay)\n processor: z.enum(['batch', 'simple']).default('batch'),\n\n // Batch processor settings (for processor: batch)\n batch: z\n .object({\n // Max time to wait before exporting (milliseconds)\n scheduled_delay_millis: z.number().default(1000),\n // Max batch size\n max_export_batch_size: z.number().default(100)\n })\n .optional()\n})\n\nexport type ExporterConfig = z.infer<typeof ExporterConfigSchema>\n\nexport const InstrumentationConfigSchema = z.object({\n version: z.string(),\n instrumentation: z.object({\n enabled: z.boolean(),\n description: z.string().optional(),\n logging: z.enum(['on', 'off', 'minimal']).optional().default('on'),\n instrument_patterns: z.array(PatternConfigSchema),\n ignore_patterns: z.array(PatternConfigSchema)\n }),\n effect: z\n .object({\n // Enable/disable Effect tracing entirely\n // When false, EffectInstrumentationLive returns Layer.empty\n enabled: z.boolean().default(true),\n // Exporter mode (legacy - use exporter.type instead):\n // - \"unified\": Use global TracerProvider from Node SDK (recommended, enables filtering)\n // - \"standalone\": Use Effect's own OTLP exporter (bypasses Node SDK filtering)\n exporter: z.enum(['unified', 'standalone']).default('unified'),\n // Exporter configuration (for auto-instrumentation)\n exporter_config: ExporterConfigSchema.optional(),\n auto_extract_metadata: z.boolean(),\n auto_isolation: AutoIsolationConfigSchema.optional(),\n // Auto-instrumentation: automatic tracing of all Effect fibers\n auto_instrumentation: AutoInstrumentationConfigSchema.optional(),\n // Operation tracing: automatic tracing of Effect.all, Effect.forEach, etc.\n operation_tracing: OperationTracingConfigSchema.optional()\n })\n .optional(),\n http: HttpFilteringConfigSchema.optional()\n})\n\nexport type InstrumentationConfig = z.infer<typeof InstrumentationConfigSchema>\nexport type PatternConfig = z.infer<typeof PatternConfigSchema>\nexport type AutoIsolationConfig = z.infer<typeof AutoIsolationConfigSchema>\nexport type HttpFilteringConfig = z.infer<typeof HttpFilteringConfigSchema>\n\n/**\n * Default configuration when no config file is found\n */\nexport const defaultConfig: InstrumentationConfig = {\n version: '1.0',\n instrumentation: {\n enabled: true,\n logging: 'on',\n description: 'Default instrumentation configuration',\n instrument_patterns: [\n { pattern: '^app\\\\.', enabled: true, description: 'Application operations' },\n { pattern: '^http\\\\.server\\\\.', enabled: true, description: 'HTTP server operations' },\n { pattern: '^http\\\\.client\\\\.', enabled: true, description: 'HTTP client operations' }\n ],\n ignore_patterns: [\n { pattern: '^test\\\\.', description: 'Test utilities' },\n { pattern: '^internal\\\\.', description: 'Internal operations' },\n { pattern: '^health\\\\.', description: 'Health checks' }\n ]\n },\n effect: {\n enabled: true,\n exporter: 'unified' as const,\n auto_extract_metadata: true\n }\n}\n\n/**\n * Parse and validate configuration content (YAML string, JSON string, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Validated InstrumentationConfig\n * @throws Error if parsing or validation fails\n */\nexport function parseAndValidateConfig(content: string | unknown): InstrumentationConfig {\n let parsed: unknown\n\n // If string, parse as YAML (YAML is a superset of JSON)\n if (typeof content === 'string') {\n parsed = parseYaml(content)\n } else {\n parsed = content\n }\n\n // Validate with schema\n return InstrumentationConfigSchema.parse(parsed)\n}\n","/**\n * Typed error hierarchy for @atrim/instrumentation\n *\n * These errors use Effect's Data.TaggedError for typed error handling\n * with proper discriminated unions.\n */\n\nimport { Data } from 'effect'\n\n/**\n * Base error for configuration-related failures\n */\nexport class ConfigError extends Data.TaggedError('ConfigError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when fetching configuration from a URL fails\n */\nexport class ConfigUrlError extends Data.TaggedError('ConfigUrlError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when configuration validation fails (invalid YAML, schema mismatch)\n */\nexport class ConfigValidationError extends Data.TaggedError('ConfigValidationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when reading configuration from a file fails\n */\nexport class ConfigFileError extends Data.TaggedError('ConfigFileError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when service detection fails (package.json not found, invalid format)\n */\nexport class ServiceDetectionError extends Data.TaggedError('ServiceDetectionError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when OpenTelemetry SDK initialization fails\n */\nexport class InitializationError extends Data.TaggedError('InitializationError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when span export fails (e.g., ECONNREFUSED to collector)\n */\nexport class ExportError extends Data.TaggedError('ExportError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n\n/**\n * Error when shutting down the SDK fails\n */\nexport class ShutdownError extends Data.TaggedError('ShutdownError')<{\n reason: string\n cause?: unknown\n}> {\n override get message() {\n return this.reason\n }\n}\n","/**\n * ConfigLoader service using Effect Platform\n *\n * Provides URI-based configuration loading with pluggable platform services:\n * - FileSystem for file:// URIs (Node.js/Bun/Deno)\n * - HttpClient for http:// and https:// URIs (universal)\n *\n * This service has NO Node.js-specific dependencies - it depends only on\n * abstract Effect Platform services that are provided by environment-specific layers.\n */\n\nimport { Effect, Context, Layer } from 'effect'\nimport { FileSystem } from '@effect/platform/FileSystem'\nimport * as HttpClient from '@effect/platform/HttpClient'\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest'\nimport { parse as parseYAML } from 'yaml'\nimport {\n InstrumentationConfigSchema,\n type InstrumentationConfig\n} from '../instrumentation-schema.js'\nimport { ConfigError, ConfigFileError, ConfigUrlError, ConfigValidationError } from '../errors.js'\n\n// Security constraints\nconst SECURITY_DEFAULTS = {\n maxConfigSize: 1_000_000, // 1MB\n requestTimeout: 5_000 // 5 seconds\n} as const\n\n/**\n * ConfigLoader service interface\n */\nexport interface ConfigLoaderService {\n /**\n * Load configuration from a URI\n *\n * Supports:\n * - file:// URIs (uses FileSystem if available)\n * - http:// and https:// URIs (uses HttpClient)\n * - Relative paths (treated as file:// in Node, http:// in browser)\n *\n * @param uri - Configuration URI\n * @returns Effect that resolves to validated configuration (NO requirements)\n */\n readonly loadFromUri: (\n uri: string\n ) => Effect.Effect<\n InstrumentationConfig,\n ConfigError | ConfigFileError | ConfigUrlError | ConfigValidationError\n >\n\n /**\n * Load configuration from inline content (YAML, JSON, or object)\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Effect that resolves to validated configuration\n */\n readonly loadFromInline: (\n content: string | unknown\n ) => Effect.Effect<InstrumentationConfig, ConfigError | ConfigValidationError>\n}\n\n/**\n * ConfigLoader service tag\n */\nexport class ConfigLoader extends Context.Tag('ConfigLoader')<\n ConfigLoader,\n ConfigLoaderService\n>() {}\n\n/**\n * Parse and validate YAML content\n */\nconst parseYamlContent = (\n content: string,\n uri?: string\n): Effect.Effect<InstrumentationConfig, ConfigValidationError> =>\n Effect.gen(function* () {\n // Parse YAML\n const parsed = yield* Effect.try({\n try: () => parseYAML(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Failed to parse YAML from ${uri}` : 'Failed to parse YAML',\n cause: error\n })\n })\n\n // Validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(parsed),\n catch: (error) =>\n new ConfigValidationError({\n reason: uri ? `Invalid configuration schema from ${uri}` : 'Invalid configuration schema',\n cause: error\n })\n })\n })\n\n/**\n * Load configuration from file using captured FileSystem service\n */\nconst loadFromFileWithFs = (\n fs: FileSystem,\n path: string,\n uri: string\n): Effect.Effect<InstrumentationConfig, ConfigFileError | ConfigValidationError> =>\n Effect.gen(function* () {\n // Read file\n const content = yield* fs.readFileString(path).pipe(\n Effect.mapError(\n (error) =>\n new ConfigFileError({\n reason: `Failed to read config file at ${uri}`,\n cause: error\n })\n )\n )\n\n // Security: Check file size\n if (content.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: `Config file exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(content, uri)\n })\n\n/**\n * Load configuration from http using captured HttpClient service\n */\nconst loadFromHttpWithClient = (\n client: HttpClient.HttpClient,\n url: string\n): Effect.Effect<InstrumentationConfig, ConfigUrlError | ConfigValidationError> =>\n Effect.scoped(\n Effect.gen(function* () {\n // Security: Reject non-HTTPS URLs\n if (url.startsWith('http://')) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: 'Insecure protocol: only HTTPS URLs are allowed'\n })\n )\n }\n\n // Create request\n const request = HttpClientRequest.get(url).pipe(\n HttpClientRequest.setHeaders({\n Accept: 'application/yaml, text/yaml, application/x-yaml'\n })\n )\n\n // Execute request with timeout\n const response = yield* client.execute(request).pipe(\n Effect.timeout(`${SECURITY_DEFAULTS.requestTimeout} millis`),\n Effect.mapError((error) => {\n if (error._tag === 'TimeoutException') {\n return new ConfigUrlError({\n reason: `Config fetch timeout after ${SECURITY_DEFAULTS.requestTimeout}ms from ${url}`\n })\n }\n return new ConfigUrlError({\n reason: `Failed to load config from URL: ${url}`,\n cause: error\n })\n })\n )\n\n // Check HTTP status\n if (response.status >= 400) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `HTTP ${response.status} from ${url}`\n })\n )\n }\n\n // Get response text\n const text = yield* response.text.pipe(\n Effect.mapError(\n (error) =>\n new ConfigUrlError({\n reason: `Failed to read response body from ${url}`,\n cause: error\n })\n )\n )\n\n // Security: Check size\n if (text.length > SECURITY_DEFAULTS.maxConfigSize) {\n return yield* Effect.fail(\n new ConfigUrlError({\n reason: `Config exceeds maximum size of ${SECURITY_DEFAULTS.maxConfigSize} bytes`\n })\n )\n }\n\n // Parse and validate\n return yield* parseYamlContent(text, url)\n })\n )\n\n/**\n * ConfigLoader service implementation\n *\n * Captures FileSystem and HttpClient dependencies at construction time\n */\nconst makeConfigLoader = Effect.gen(function* () {\n // Capture dependencies at construction time\n const fs = yield* Effect.serviceOption(FileSystem)\n const http = yield* HttpClient.HttpClient\n\n // Create the loadFromUri function\n const loadFromUriUncached = (uri: string) =>\n Effect.gen(function* () {\n // file:// protocol\n if (uri.startsWith('file://')) {\n const path = uri.slice(7) // Remove \"file://\"\n\n if (fs._tag === 'None') {\n return yield* Effect.fail(\n new ConfigFileError({\n reason: 'FileSystem not available (browser environment?)',\n cause: { uri }\n })\n )\n }\n\n return yield* loadFromFileWithFs(fs.value, path, uri)\n }\n\n // http:// or https:// protocol\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return yield* loadFromHttpWithClient(http, uri)\n }\n\n // Relative path - try FileSystem first, fallback to HTTP\n if (fs._tag === 'Some') {\n // FileSystem available (Node.js environment)\n return yield* loadFromFileWithFs(fs.value, uri, uri)\n } else {\n // No FileSystem (browser environment) - treat as HTTP\n // Relative URLs will be resolved by browser fetch to current origin\n return yield* loadFromHttpWithClient(http, uri)\n }\n })\n\n // Cache the loadFromUri function with 5 minute TTL (default cache timeout)\n const loadFromUriCached = yield* Effect.cachedFunction(loadFromUriUncached)\n\n return ConfigLoader.of({\n loadFromUri: loadFromUriCached,\n\n loadFromInline: (content: string | unknown) =>\n Effect.gen(function* () {\n // If string, parse as YAML\n if (typeof content === 'string') {\n return yield* parseYamlContent(content)\n }\n\n // Already an object - just validate schema\n return yield* Effect.try({\n try: () => InstrumentationConfigSchema.parse(content),\n catch: (error) =>\n new ConfigValidationError({\n reason: 'Invalid configuration schema',\n cause: error\n })\n })\n })\n })\n})\n\n/**\n * ConfigLoader Live layer\n *\n * Provides ConfigLoader service implementation.\n * Requires HttpClient to be provided by platform-specific layers.\n * FileSystem is optional (for browser compatibility).\n */\nexport const ConfigLoaderLive = Layer.effect(ConfigLoader, makeConfigLoader)\n","/**\n * Centralized logging utility for @atrim/instrumentation\n *\n * Supports three levels:\n * - 'on' (default): All logging enabled\n * - 'minimal': Only a single initialization message + errors/warnings\n * - 'off': No logging at all\n */\n\nexport type LogLevel = 'on' | 'off' | 'minimal'\n\nclass Logger {\n private level: LogLevel = 'on'\n private hasLoggedMinimal = false\n\n /**\n * Set the logging level\n */\n setLevel(level: LogLevel): void {\n this.level = level\n this.hasLoggedMinimal = false\n }\n\n /**\n * Get the current logging level\n */\n getLevel(): LogLevel {\n return this.level\n }\n\n /**\n * Log a minimal initialization message (only shown once in minimal mode)\n */\n minimal(message: string): void {\n if (this.level === 'off') {\n return\n }\n\n if (this.level === 'minimal' && !this.hasLoggedMinimal) {\n console.log(message)\n this.hasLoggedMinimal = true\n return\n }\n\n if (this.level === 'on') {\n console.log(message)\n }\n }\n\n /**\n * Log an informational message\n */\n log(...args: unknown[]): void {\n if (this.level === 'on') {\n console.log(...args)\n }\n }\n\n /**\n * Log a warning message (shown in minimal mode)\n */\n warn(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.warn(...args)\n }\n }\n\n /**\n * Log an error message (shown in minimal mode)\n */\n error(...args: unknown[]): void {\n if (this.level !== 'off') {\n console.error(...args)\n }\n }\n\n /**\n * Check if full logging is enabled\n */\n isEnabled(): boolean {\n return this.level === 'on'\n }\n\n /**\n * Check if minimal logging is enabled\n */\n isMinimal(): boolean {\n return this.level === 'minimal'\n }\n\n /**\n * Check if logging is completely disabled\n */\n isDisabled(): boolean {\n return this.level === 'off'\n }\n}\n\n// Singleton instance\nexport const logger = new Logger()\n","/**\n * Node.js configuration loader\n *\n * Provides configuration loading using native Node.js APIs (fs, fetch)\n * This module doesn't require Effect Platform, making it work without Effect installed.\n */\n\nimport { Effect } from 'effect'\nimport {\n type InstrumentationConfig,\n parseAndValidateConfig,\n defaultConfig\n} from '@atrim/instrument-core'\n\n/**\n * Load configuration from a file path using native Node.js fs\n */\nasync function loadFromFile(filePath: string): Promise<InstrumentationConfig> {\n const { readFile } = await import('fs/promises')\n const content = await readFile(filePath, 'utf-8')\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from a URL using native fetch\n */\nasync function loadFromUrl(url: string): Promise<InstrumentationConfig> {\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`Failed to fetch config from ${url}: ${response.statusText}`)\n }\n const content = await response.text()\n return parseAndValidateConfig(content)\n}\n\n/**\n * Load configuration from URI (file path or URL)\n *\n * @param uri - Configuration URI (file://, http://, https://, or relative path)\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfig(\n uri: string,\n _options?: { cacheTimeout?: number }\n): Promise<InstrumentationConfig> {\n // Handle URL protocols\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n return loadFromUrl(uri)\n }\n\n // Handle file:// protocol\n if (uri.startsWith('file://')) {\n const filePath = uri.slice(7) // Remove 'file://'\n return loadFromFile(filePath)\n }\n\n // Treat as file path\n return loadFromFile(uri)\n}\n\n/**\n * Load configuration from inline content\n *\n * @param content - YAML string, JSON string, or plain object\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigFromInline(\n content: string | unknown\n): Promise<InstrumentationConfig> {\n return parseAndValidateConfig(content)\n}\n\n/**\n * Reset the config loader cache (no-op for native implementation)\n * @internal\n */\nexport function _resetConfigLoaderCache(): void {\n // No cache in native implementation\n}\n\n/**\n * Legacy options interface for backward compatibility\n */\nexport interface ConfigLoaderOptions {\n configPath?: string\n configUrl?: string\n config?: InstrumentationConfig\n cacheTimeout?: number\n}\n\n/**\n * Load configuration with priority order (backward compatible API)\n *\n * Priority order (highest to lowest):\n * 1. Explicit config object (options.config)\n * 2. Environment variable (ATRIM_INSTRUMENTATION_CONFIG)\n * 3. Explicit path/URL (options.configPath or options.configUrl)\n * 4. Project root file (./instrumentation.yaml)\n * 5. Default config (built-in defaults)\n *\n * @param options - Configuration options\n * @returns Promise that resolves to validated configuration\n */\nexport async function loadConfigWithOptions(\n options: ConfigLoaderOptions = {}\n): Promise<InstrumentationConfig> {\n // Priority 1: Explicit config object\n if (options.config) {\n return loadConfigFromInline(options.config)\n }\n\n // Priority 2: Environment variable\n const envConfigPath = process.env.ATRIM_INSTRUMENTATION_CONFIG\n if (envConfigPath) {\n return loadConfig(envConfigPath, options)\n }\n\n // Priority 3: Explicit options\n if (options.configUrl) {\n return loadConfig(options.configUrl, options)\n }\n if (options.configPath) {\n return loadConfig(options.configPath, options)\n }\n\n // Priority 4: Project root file\n const { existsSync } = await import('fs')\n const { join } = await import('path')\n\n const defaultPath = join(process.cwd(), 'instrumentation.yaml')\n if (existsSync(defaultPath)) {\n return loadConfig(defaultPath, options)\n }\n\n // Priority 5: Default config\n return defaultConfig\n}\n\n// ============================================================================\n// Effect-Based API (for Effect users)\n// ============================================================================\n\n/**\n * Load configuration from URI (Effect version)\n */\nexport const loadConfigEffect = (\n uri: string,\n options?: { cacheTimeout?: number }\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfig(uri, options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration from inline content (Effect version)\n */\nexport const loadConfigFromInlineEffect = (\n content: string | unknown\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigFromInline(content),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n\n/**\n * Load configuration with priority order (Effect version)\n */\nexport const loadConfigWithOptionsEffect = (\n options: ConfigLoaderOptions = {}\n): Effect.Effect<InstrumentationConfig, Error> =>\n Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => (error instanceof Error ? error : new Error(String(error)))\n })\n","/**\n * Auto-Tracing Configuration Loader\n *\n * Loads auto-tracing configuration from instrumentation.yaml\n * and provides a typed Effect service for accessing it.\n */\n\nimport { Effect, Context, Layer } from 'effect'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport * as yaml from 'yaml'\nimport {\n type AutoInstrumentationConfig,\n type InstrumentationConfig,\n type ExporterConfig,\n AutoInstrumentationConfigSchema,\n InstrumentationConfigSchema,\n defaultConfig,\n logger\n} from '@atrim/instrument-core'\nimport { loadConfigWithOptions, type ConfigLoaderOptions } from '../../../core/config-loader.js'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Re-export config type for convenience\n */\nexport type { AutoInstrumentationConfig }\n\n/**\n * Default auto-tracing configuration when not specified in instrumentation.yaml\n */\nexport const defaultAutoTracingConfig: AutoInstrumentationConfig = {\n enabled: false,\n granularity: 'fiber',\n span_naming: {\n default: 'effect.fiber.{fiber_id}',\n infer_from_source: true,\n rules: []\n },\n span_relationships: {\n type: 'parent-child'\n },\n filter: {\n include: [],\n exclude: []\n },\n performance: {\n sampling_rate: 1.0,\n min_duration: '0ms',\n max_concurrent: 0\n },\n metadata: {\n fiber_info: true,\n source_location: true,\n parent_fiber: true\n }\n}\n\n// ============================================================================\n// Service Definition\n// ============================================================================\n\n/**\n * Service tag for auto-tracing configuration\n */\nexport class AutoTracingConfig extends Context.Tag('AutoTracingConfig')<\n AutoTracingConfig,\n AutoInstrumentationConfig\n>() {}\n\n// ============================================================================\n// Configuration Loading\n// ============================================================================\n\n/**\n * Load auto-tracing configuration from instrumentation.yaml\n *\n * Returns the config from effect.auto_instrumentation section,\n * or defaults if not specified.\n */\nexport const loadAutoTracingConfig = (\n options?: ConfigLoaderOptions\n): Effect.Effect<AutoInstrumentationConfig, never, never> =>\n Effect.gen(function* () {\n // Load full config\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => {\n logger.log(`@atrim/auto-trace: Failed to load config: ${error}`)\n return error\n }\n }).pipe(Effect.catchAll(() => Effect.succeed(null)))\n\n if (!config) {\n logger.log('@atrim/auto-trace: No config found, using defaults')\n return defaultAutoTracingConfig\n }\n\n // Extract auto_instrumentation section\n const autoConfig = config.effect?.auto_instrumentation\n\n if (!autoConfig) {\n logger.log('@atrim/auto-trace: No auto_instrumentation config, using defaults')\n return defaultAutoTracingConfig\n }\n\n // Validate and merge with defaults\n const parsed = AutoInstrumentationConfigSchema.safeParse(autoConfig)\n if (!parsed.success) {\n logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${parsed.error.message}`)\n return defaultAutoTracingConfig\n }\n\n logger.log('@atrim/auto-trace: Loaded config from instrumentation.yaml')\n return parsed.data\n })\n\n/**\n * Load auto-tracing configuration synchronously from cache or default\n *\n * Note: This is a synchronous fallback when Effect runtime isn't available.\n * Prefer loadAutoTracingConfig() when possible.\n */\nexport const loadAutoTracingConfigSync = (): AutoInstrumentationConfig => {\n // For synchronous loading, we can only return defaults\n // The async version should be used for actual config loading\n return defaultAutoTracingConfig\n}\n\n// ============================================================================\n// Layer\n// ============================================================================\n\n/**\n * Layer that provides auto-tracing configuration\n */\nexport const AutoTracingConfigLive = Layer.effect(AutoTracingConfig, loadAutoTracingConfig())\n\n/**\n * Layer that provides custom auto-tracing configuration\n */\nexport const AutoTracingConfigLayer = (\n config: AutoInstrumentationConfig\n): Layer.Layer<AutoTracingConfig> => Layer.succeed(AutoTracingConfig, config)\n\n// ============================================================================\n// Full Config Loading\n// ============================================================================\n\n/**\n * Load the full instrumentation config from instrumentation.yaml\n *\n * Returns the complete config including exporter settings for setting up\n * the full auto-instrumentation pipeline.\n */\nexport const loadFullConfig = (\n options?: ConfigLoaderOptions\n): Effect.Effect<InstrumentationConfig, never, never> =>\n Effect.gen(function* () {\n const config = yield* Effect.tryPromise({\n try: () => loadConfigWithOptions(options),\n catch: (error) => {\n logger.log(`@atrim/auto-trace: Failed to load config: ${error}`)\n return error\n }\n }).pipe(Effect.catchAll(() => Effect.succeed(null)))\n\n if (!config) {\n logger.log('@atrim/auto-trace: No config found, using defaults')\n return defaultConfig\n }\n\n return config\n })\n\n/**\n * Load the full instrumentation config synchronously\n *\n * This is needed for layers that cannot use Layer.unwrapEffect (which breaks\n * tracer propagation). Falls back to default config if file doesn't exist.\n */\nexport const loadFullConfigSync = (): InstrumentationConfig => {\n const defaultPath = path.join(process.cwd(), 'instrumentation.yaml')\n\n try {\n if (fs.existsSync(defaultPath)) {\n const content = fs.readFileSync(defaultPath, 'utf-8')\n const parsed = yaml.parse(content)\n const result = InstrumentationConfigSchema.safeParse(parsed)\n\n if (result.success) {\n logger.log(`@atrim/auto-trace: Loaded config from ${defaultPath}`)\n return result.data\n } else {\n logger.log(`@atrim/auto-trace: Invalid config, using defaults: ${result.error.message}`)\n return defaultConfig\n }\n }\n } catch (error) {\n logger.log(`@atrim/auto-trace: Failed to load config: ${error}`)\n }\n\n logger.log('@atrim/auto-trace: No config found, using defaults')\n return defaultConfig\n}\n\n/**\n * Default exporter configuration\n */\nexport const defaultExporterConfig: ExporterConfig = {\n type: 'otlp',\n processor: 'batch',\n batch: {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n}\n","/**\n * Span Control FiberRefs for Effect-TS Tracing\n *\n * Provides FiberRefs that control span creation behavior. These can be used to:\n * - Disable auto-tracing for specific fibers/effects\n * - Override auto-generated span names\n *\n * These FiberRefs are checked by the UnifiedTracingSupervisor during span creation.\n *\n * @example\n * ```typescript\n * import { withoutAutoTracing, setSpanName } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * // Automatically traced\n * yield* publicWork()\n *\n * // Opt-out of tracing\n * yield* withoutAutoTracing(internalWork())\n *\n * // Custom span name\n * yield* setSpanName('custom.operation')(criticalWork())\n * }).pipe(withUnifiedTracing)\n * ```\n */\n\nimport { Effect, FiberRef, Option } from 'effect'\n\n// ============================================================================\n// FiberRefs for span control\n// ============================================================================\n\n/**\n * FiberRef to enable/disable auto-tracing for specific fibers.\n *\n * When set to `false`, the UnifiedTracingSupervisor will skip span creation\n * for the fiber and its children (unless they override it back to `true`).\n *\n * Default: `true` (auto-tracing enabled)\n */\nexport const AutoTracingEnabled = FiberRef.unsafeMake<boolean>(true)\n\n/**\n * FiberRef to override the auto-generated span name.\n *\n * When set to `Some(name)`, the UnifiedTracingSupervisor will use this name\n * instead of inferring it from source location.\n *\n * Default: `None` (use inferred name)\n */\nexport const AutoTracingSpanName = FiberRef.unsafeMake<Option.Option<string>>(Option.none())\n\n// ============================================================================\n// Utility functions\n// ============================================================================\n\n/**\n * Disable auto-tracing for a specific Effect.\n *\n * Use this to opt-out of automatic span creation for internal operations\n * that don't need to be traced.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* publicWork() // Traced\n * yield* withoutAutoTracing(internalWork()) // NOT traced\n * })\n * ```\n */\nexport const withoutAutoTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => effect.pipe(Effect.locally(AutoTracingEnabled, false))\n\n/**\n * Override the auto-generated span name for a specific Effect.\n *\n * Use this when you want a custom span name instead of the inferred one.\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* setSpanName('custom.operation.name')(myEffect)\n * })\n * ```\n */\nexport const setSpanName =\n (name: string) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n effect.pipe(Effect.locally(AutoTracingSpanName, Option.some(name)))\n","/**\n * Unified Tracing Supervisor for Effect-TS\n *\n * Combines operation tracing (Effect.all, Effect.forEach, Effect.fork) with\n * fiber-level tracing, ensuring correct parent-child span relationships.\n *\n * Key feature: Fork spans are correctly set as parents of their resulting fiber spans.\n *\n * Requires the @clayroach/effect fork with OperationMeta and source capture support.\n *\n * @example\n * ```typescript\n * import { withUnifiedTracing } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * // Creates spans: effect.all -> child fiber spans\n * yield* Effect.all([doA(), doB()])\n *\n * // Creates spans: effect.fork -> forked fiber span (correct hierarchy!)\n * yield* Effect.fork(backgroundTask())\n * }).pipe(withUnifiedTracing)\n * ```\n */\n\nimport {\n Supervisor,\n Effect,\n Layer,\n FiberRef,\n FiberRefs,\n Context,\n Option,\n Exit,\n Fiber,\n RuntimeFlags,\n RuntimeFlagsPatch,\n Tracer as EffectTracer,\n GlobalValue\n} from 'effect'\nimport * as TracerModule from 'effect/Tracer'\nimport { Tracer as OtelTracer, Resource } from '@effect/opentelemetry'\nimport * as OtelApi from '@opentelemetry/api'\nimport {\n BatchSpanProcessor,\n SimpleSpanProcessor,\n ConsoleSpanExporter,\n BasicTracerProvider\n} from '@opentelemetry/sdk-trace-base'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'\nimport type { AutoInstrumentationConfig } from '@atrim/instrument-core'\nimport { logger } from '@atrim/instrument-core'\nimport { loadFullConfigSync } from './config.js'\nimport { AutoTracingEnabled, AutoTracingSpanName } from './span-control.js'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Operation metadata stored in the trace field by Effect.all, Effect.forEach, etc.\n */\nexport interface OperationMeta {\n readonly _tag: 'OperationMeta'\n readonly op: string\n readonly count?: number\n readonly capturedAt: string\n}\n\n/**\n * Source location from Effect's native source capture\n */\ninterface SourceLocation {\n readonly file: string\n readonly line: number\n readonly column?: number\n readonly functionName?: string\n}\n\n/**\n * Pending fork span waiting for its child fiber\n */\ninterface PendingFork {\n readonly forkSpan: OtelApi.Span\n readonly forkContext: OtelApi.Context\n readonly timestamp: bigint\n readonly spanEnded: boolean\n}\n\n/**\n * Configuration for which operations to trace\n */\ninterface OperationConfig {\n readonly name: string\n readonly includeCount?: boolean\n readonly includeStack?: boolean\n}\n\n// ============================================================================\n// FiberRefs\n// ============================================================================\n\n/**\n * Access Effect's native currentSourceLocation FiberRef\n */\nconst currentSourceLocation = GlobalValue.globalValue(\n Symbol.for('effect/FiberRef/currentSourceLocation'),\n () => FiberRef.unsafeMake<SourceLocation | undefined>(undefined)\n)\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Check if an effect has OperationMeta in its trace field\n */\nfunction getOperationMeta(\n effect: Effect.Effect<unknown, unknown, unknown>\n): OperationMeta | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const trace = (effect as any).trace\n if (trace && trace._tag === 'OperationMeta') {\n return trace as OperationMeta\n }\n return undefined\n}\n\n/**\n * Parse source location from a raw stack trace string\n */\nfunction parseSourceLocation(stack: string): SourceLocation | undefined {\n const lines = stack.split('\\n')\n\n for (const line of lines.slice(1)) {\n if (\n line.includes('node_modules') ||\n line.includes('/effect/') ||\n line.includes('fiberRuntime.ts') ||\n line.includes('core.ts')\n ) {\n continue\n }\n\n const match = line.match(/at\\s+(?:.*?\\s+\\()?(.+):(\\d+):(\\d+)\\)?/)\n if (match && match[1] && match[2]) {\n return {\n file: match[1],\n line: parseInt(match[2], 10),\n ...(match[3] ? { column: parseInt(match[3], 10) } : {})\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Create a source key for correlating fork operations with fibers\n */\nfunction makeSourceKey(source: SourceLocation | undefined): string {\n if (!source) return 'unknown'\n return `${source.file}:${source.line}`\n}\n\n/**\n * Format source location for span name\n */\nfunction formatLocation(source: SourceLocation | undefined): string {\n if (!source) return 'unknown'\n const filename = source.file.split('/').pop() ?? source.file\n return `${filename}:${source.line}`\n}\n\n// ============================================================================\n// UnifiedTracingSupervisor\n// ============================================================================\n\n/**\n * Unified supervisor that handles both operation tracing and fiber tracing,\n * ensuring correct parent-child relationships for fork spans.\n */\nexport class UnifiedTracingSupervisor extends Supervisor.AbstractSupervisor<void> {\n // ========== Fork span registry ==========\n // Maps sourceKey -> pending fork span (for correlating with child fibers)\n private readonly pendingForkSpans = new Map<string, PendingFork>()\n\n // ========== Fiber tracking ==========\n private readonly fiberSpans = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, OtelApi.Span>()\n private readonly fiberContexts = new WeakMap<\n Fiber.RuntimeFiber<unknown, unknown>,\n OtelApi.Context\n >()\n private readonly fiberStartTimes = new WeakMap<Fiber.RuntimeFiber<unknown, unknown>, bigint>()\n\n // ========== Operation tracking ==========\n private readonly processedEffects = new WeakSet<object>()\n private readonly configuredOps: Map<string, OperationConfig>\n\n // ========== OTel ==========\n private _tracer: OtelApi.Tracer | null = null\n private activeFiberCount = 0\n\n constructor(private readonly config: AutoInstrumentationConfig) {\n super()\n\n // Default operations to trace\n const defaultOps: OperationConfig[] = [\n { name: 'all', includeCount: true, includeStack: true },\n { name: 'forEach', includeCount: true, includeStack: true },\n { name: 'fork', includeStack: true }\n ]\n this.configuredOps = new Map(defaultOps.map((op) => [op.name, op]))\n\n logger.log('@atrim/unified-tracing: Supervisor initialized')\n logger.log(` Operations: ${Array.from(this.configuredOps.keys()).join(', ')}`)\n }\n\n private get tracer(): OtelApi.Tracer {\n if (!this._tracer) {\n this._tracer = OtelApi.trace.getTracer('@atrim/unified-tracing', '1.0.0')\n }\n return this._tracer\n }\n\n override get value(): Effect.Effect<void> {\n return Effect.void\n }\n\n // ==========================================================================\n // onEffect - Operation-level tracing (Effect.all, Effect.forEach, Effect.fork)\n // ==========================================================================\n\n override onEffect<A, E>(\n fiber: Fiber.RuntimeFiber<A, E>,\n effect: Effect.Effect<unknown, unknown, unknown>\n ): void {\n if (this.processedEffects.has(effect as object)) {\n return\n }\n\n const meta = getOperationMeta(effect)\n if (!meta) {\n return\n }\n\n const opConfig = this.configuredOps.get(meta.op)\n if (!opConfig) {\n return\n }\n\n this.processedEffects.add(effect as object)\n\n const fiberId = fiber.id().id\n const location = parseSourceLocation(meta.capturedAt)\n const sourceKey = makeSourceKey(location)\n\n logger.log(`@atrim/unified-tracing: onEffect \"${meta.op}\" in fiber ${fiberId} at ${sourceKey}`)\n\n // Get parent context\n const parentContext = this.resolveParentContext(fiber)\n\n // Build span name\n const spanName = location\n ? `effect.${meta.op} (${formatLocation(location)})`\n : `effect.${meta.op}`\n\n // Create operation span\n const span = this.tracer.startSpan(spanName, { kind: OtelApi.SpanKind.INTERNAL }, parentContext)\n\n // Set attributes\n span.setAttribute('effect.operation', meta.op)\n if (opConfig.includeCount && meta.count !== undefined) {\n span.setAttribute('effect.item_count', meta.count)\n }\n if (opConfig.includeStack && location) {\n span.setAttribute('code.filepath', location.file)\n span.setAttribute('code.lineno', location.line)\n if (location.column !== undefined) {\n span.setAttribute('code.column', location.column)\n }\n }\n\n logger.log(\n `@atrim/unified-tracing: Created operation span \"${spanName}\" spanId=${span.spanContext().spanId}`\n )\n\n // For fork operations, register the span for the child fiber to find\n if (meta.op === 'fork') {\n const forkContext = OtelApi.trace.setSpan(parentContext, span)\n this.pendingForkSpans.set(sourceKey, {\n forkSpan: span,\n forkContext,\n timestamp: process.hrtime.bigint(),\n spanEnded: false\n })\n logger.log(`@atrim/unified-tracing: Registered pending fork at ${sourceKey}`)\n\n // Don't end fork span yet - will be ended when child fiber starts\n // This ensures the fork span has non-zero duration\n } else {\n // For non-fork operations (all, forEach), end immediately\n span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n span.end()\n }\n }\n\n // ==========================================================================\n // onStart - Fiber-level tracing\n // ==========================================================================\n\n override onStart<A, E, R>(\n _context: Context.Context<R>,\n _effect: Effect.Effect<A, E, R>,\n parent: Option.Option<Fiber.RuntimeFiber<unknown, unknown>>,\n fiber: Fiber.RuntimeFiber<A, E>\n ): void {\n const fiberId = fiber.id().id\n const fiberRefs = fiber.getFiberRefs()\n\n // ========================================================================\n // Check span control FiberRefs\n // ========================================================================\n\n // Check if auto-tracing is enabled for this fiber (via FiberRef)\n const enabled = FiberRefs.getOrDefault(fiberRefs, AutoTracingEnabled)\n if (!enabled) {\n logger.log(`@atrim/unified-tracing: Auto-tracing disabled for fiber ${fiberId}`)\n return\n }\n\n // Check sampling rate from config\n const samplingRate = this.config.performance?.sampling_rate ?? 1.0\n if (samplingRate < 1.0 && Math.random() > samplingRate) {\n return\n }\n\n // Check for span name override\n const nameOverride = FiberRefs.getOrDefault(fiberRefs, AutoTracingSpanName)\n\n // Get source location\n const sourceLocation = FiberRefs.getOrDefault(fiberRefs, currentSourceLocation) as\n | SourceLocation\n | undefined\n const sourceKey = makeSourceKey(sourceLocation)\n\n logger.log(`@atrim/unified-tracing: onStart fiber ${fiberId} at ${sourceKey}`)\n\n // ========================================================================\n // KEY: Check if this fiber is the result of a pending fork operation\n // ========================================================================\n let parentContext: OtelApi.Context\n const pendingFork = this.pendingForkSpans.get(sourceKey)\n\n if (pendingFork) {\n // This fiber is the child of a fork operation!\n // Use the fork span's context as the parent\n parentContext = pendingFork.forkContext\n logger.log(\n `@atrim/unified-tracing: Matched fiber ${fiberId} to fork span at ${sourceKey} - using fork span as parent`\n )\n\n // End the fork span now that we've matched it\n if (!pendingFork.spanEnded) {\n pendingFork.forkSpan.setStatus({ code: OtelApi.SpanStatusCode.OK })\n pendingFork.forkSpan.end()\n logger.log(`@atrim/unified-tracing: Ended fork span at ${sourceKey}`)\n }\n\n // Remove from pending\n this.pendingForkSpans.delete(sourceKey)\n } else {\n // No pending fork - use normal parent resolution\n parentContext = this.resolveParentContextFromFiberRefs(\n fiberRefs,\n _context as Context.Context<unknown>,\n parent\n )\n }\n\n // Generate span name - use override if set, otherwise infer from source\n let spanName: string\n if (Option.isSome(nameOverride)) {\n spanName = nameOverride.value\n } else if (sourceLocation) {\n spanName = `effect.fiber (${formatLocation(sourceLocation)})`\n } else {\n spanName = `effect.fiber-${fiberId}`\n }\n\n // Create fiber span\n const span = this.tracer.startSpan(spanName, { kind: OtelApi.SpanKind.INTERNAL }, parentContext)\n\n // Set attributes\n span.setAttribute('effect.auto_traced', true)\n span.setAttribute('effect.fiber.id', fiberId)\n if (sourceLocation) {\n span.setAttribute('code.filepath', sourceLocation.file)\n span.setAttribute('code.lineno', sourceLocation.line)\n if (sourceLocation.column !== undefined) {\n span.setAttribute('code.column', sourceLocation.column)\n }\n }\n if (Option.isSome(parent)) {\n span.setAttribute('effect.fiber.parent_id', parent.value.id().id)\n }\n\n logger.log(\n `@atrim/unified-tracing: Created fiber span \"${spanName}\" spanId=${span.spanContext().spanId}`\n )\n\n // Store for onEnd and child lookups\n const newContext = OtelApi.trace.setSpan(parentContext, span)\n this.fiberSpans.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, span)\n this.fiberContexts.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, newContext)\n this.fiberStartTimes.set(fiber as Fiber.RuntimeFiber<unknown, unknown>, process.hrtime.bigint())\n this.activeFiberCount++\n }\n\n // ==========================================================================\n // onEnd - Fiber completion\n // ==========================================================================\n\n override onEnd<A, E>(exit: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n const fiberId = fiber.id().id\n const span = this.fiberSpans.get(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n\n if (!span) {\n return\n }\n\n // Check min_duration\n const startTime = this.fiberStartTimes.get(fiber as Fiber.RuntimeFiber<unknown, unknown>)\n if (startTime) {\n const duration = process.hrtime.bigint() - startTime\n const minDuration = this.parseMinDuration(this.config.performance?.min_duration)\n if (minDuration > 0 && duration < minDuration) {\n this.cleanup(fiber)\n return\n }\n }\n\n // Set status\n if (Exit.isSuccess(exit)) {\n span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n } else {\n span.setStatus({ code: OtelApi.SpanStatusCode.ERROR, message: 'Fiber failed' })\n span.setAttribute('effect.fiber.failed', true)\n }\n\n span.end()\n logger.log(`@atrim/unified-tracing: Ended fiber span for fiber ${fiberId}`)\n\n this.cleanup(fiber)\n }\n\n // ==========================================================================\n // Helpers\n // ==========================================================================\n\n private cleanup(fiber: Fiber.RuntimeFiber<unknown, unknown>): void {\n this.fiberSpans.delete(fiber)\n this.fiberContexts.delete(fiber)\n this.fiberStartTimes.delete(fiber)\n this.activeFiberCount--\n }\n\n private resolveParentContext(fiber: Fiber.RuntimeFiber<unknown, unknown>): OtelApi.Context {\n const fiberContext = fiber.currentContext\n const maybeParentSpan = Context.getOption(fiberContext, EffectTracer.ParentSpan)\n\n if (Option.isSome(maybeParentSpan)) {\n const effectSpan = maybeParentSpan.value\n return OtelApi.trace.setSpan(\n OtelApi.ROOT_CONTEXT,\n OtelApi.trace.wrapSpanContext({\n traceId: effectSpan.traceId,\n spanId: effectSpan.spanId,\n traceFlags: OtelApi.TraceFlags.SAMPLED\n })\n )\n }\n\n return OtelApi.ROOT_CONTEXT\n }\n\n private resolveParentContextFromFiberRefs(\n fiberRefs: FiberRefs.FiberRefs,\n context: Context.Context<unknown>,\n parent: Option.Option<Fiber.RuntimeFiber<unknown, unknown>>\n ): OtelApi.Context {\n // ========================================================================\n // Parent context resolution priority:\n // 1. Inherited OTel context from FiberRef (set by @effect/opentelemetry)\n // 2. Effect's ParentSpan in Context (Effect's native span tracking)\n // 3. Active OTel context (auto-bridging from OTel → Effect)\n // 4. Parent fiber's tracked context\n // 5. ROOT_CONTEXT (no parent)\n // ========================================================================\n\n // 1. Check inherited OTel context from FiberRef\n const inheritedCtx = FiberRefs.getOrDefault(fiberRefs, TracerModule.currentOtelSpanContext) as\n | OtelApi.Context\n | undefined\n if (inheritedCtx) {\n const span = OtelApi.trace.getSpan(inheritedCtx)\n if (span) {\n logger.log(\n `@atrim/unified-tracing: Using inherited OTel context from FiberRef - spanId=${span.spanContext().spanId}`\n )\n }\n return inheritedCtx\n }\n\n // 2. Check Effect's ParentSpan in Context\n const maybeParentSpan = Context.getOption(context, EffectTracer.ParentSpan)\n if (Option.isSome(maybeParentSpan)) {\n const effectSpan = maybeParentSpan.value\n logger.log(\n `@atrim/unified-tracing: Using Effect ParentSpan - traceId=${effectSpan.traceId.slice(0, 8)}..., spanId=${effectSpan.spanId.slice(0, 8)}...`\n )\n return OtelApi.trace.setSpan(\n OtelApi.ROOT_CONTEXT,\n OtelApi.trace.wrapSpanContext({\n traceId: effectSpan.traceId,\n spanId: effectSpan.spanId,\n traceFlags: OtelApi.TraceFlags.SAMPLED\n })\n )\n }\n\n // 3. Auto-bridge: Check active OTel context (OTel → Effect bridging)\n // This allows spans created by non-Effect code (e.g., HTTP middleware) to be parents\n const activeContext = OtelApi.context.active()\n const activeSpan = OtelApi.trace.getSpan(activeContext)\n if (activeSpan && activeSpan.spanContext().traceFlags === OtelApi.TraceFlags.SAMPLED) {\n logger.log(\n `@atrim/unified-tracing: Auto-bridging from active OTel context - spanId=${activeSpan.spanContext().spanId}`\n )\n return activeContext\n }\n\n // 4. Check parent fiber's tracked context\n if (Option.isSome(parent)) {\n const parentCtx = this.fiberContexts.get(parent.value)\n if (parentCtx) {\n logger.log(`@atrim/unified-tracing: Using parent fiber's context`)\n return parentCtx\n }\n }\n\n // 5. No parent found\n return OtelApi.ROOT_CONTEXT\n }\n\n private parseMinDuration(duration: string | undefined): bigint {\n if (!duration || duration === '0ms') return BigInt(0)\n\n const match = duration.match(/^(\\d+)\\s*(ms|millis|s|sec|seconds|us|micros)?$/i)\n if (!match) return BigInt(0)\n\n const value = parseInt(match[1] ?? '0', 10)\n const unit = (match[2] ?? 'ms').toLowerCase()\n\n switch (unit) {\n case 'us':\n case 'micros':\n return BigInt(value) * BigInt(1000)\n case 'ms':\n case 'millis':\n return BigInt(value) * BigInt(1000000)\n case 's':\n case 'sec':\n case 'seconds':\n return BigInt(value) * BigInt(1000000000)\n default:\n return BigInt(value) * BigInt(1000000)\n }\n }\n}\n\n// ============================================================================\n// Global TracerProvider Setup\n// ============================================================================\n\nconst setupGlobalTracerProvider = (): {\n provider: BasicTracerProvider\n spanProcessor: BatchSpanProcessor | SimpleSpanProcessor\n} | null => {\n const config = loadFullConfigSync()\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n const exporterConfig = config.effect?.exporter_config ?? {\n type: 'otlp' as const,\n processor: 'batch' as const\n }\n\n logger.log('@atrim/unified-tracing: Setting up global TracerProvider')\n logger.log(` Service: ${serviceName}`)\n logger.log(` Exporter: ${exporterConfig.type}`)\n\n if (exporterConfig.type === 'none') {\n logger.log('@atrim/unified-tracing: Exporter type is \"none\", skipping provider setup')\n return null\n }\n\n let exporter\n if (exporterConfig.type === 'console') {\n exporter = new ConsoleSpanExporter()\n } else {\n const endpoint =\n exporterConfig.endpoint || process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'\n const otlpConfig: { url: string; headers?: Record<string, string> } = {\n url: `${endpoint}/v1/traces`\n }\n if (exporterConfig.headers) {\n otlpConfig.headers = exporterConfig.headers\n }\n exporter = new OTLPTraceExporter(otlpConfig)\n }\n\n let spanProcessor: BatchSpanProcessor | SimpleSpanProcessor\n if (exporterConfig.processor === 'simple' || exporterConfig.type === 'console') {\n spanProcessor = new SimpleSpanProcessor(exporter)\n } else {\n const batchConfig = exporterConfig.batch ?? {\n scheduled_delay_millis: 1000,\n max_export_batch_size: 100\n }\n spanProcessor = new BatchSpanProcessor(exporter, {\n scheduledDelayMillis: batchConfig.scheduled_delay_millis,\n maxExportBatchSize: batchConfig.max_export_batch_size\n })\n }\n\n const provider = new BasicTracerProvider({\n resource: resourceFromAttributes({\n [ATTR_SERVICE_NAME]: serviceName,\n [ATTR_SERVICE_VERSION]: serviceVersion\n }),\n spanProcessors: [spanProcessor]\n })\n OtelApi.trace.setGlobalTracerProvider(provider)\n logger.log('@atrim/unified-tracing: Global TracerProvider registered')\n\n return { provider, spanProcessor }\n}\n\n// Lazy initialization of the global TracerProvider\n// Only sets up the provider when first accessed, not at module load time\n// This allows tests to set OTEL_EXPORTER_OTLP_ENDPOINT before the provider is created\nlet _globalProviderSetup: ReturnType<typeof setupGlobalTracerProvider> | undefined\n\nfunction getGlobalProviderSetup() {\n if (_globalProviderSetup === undefined) {\n _globalProviderSetup = setupGlobalTracerProvider()\n }\n return _globalProviderSetup\n}\n\n// ============================================================================\n// Layers and Wrappers\n// ============================================================================\n\n/**\n * Create the UnifiedTracingLive layer\n */\nexport const createUnifiedTracingLayer = (): Layer.Layer<never> => {\n const config = loadFullConfigSync()\n\n const autoConfig = config.effect?.auto_instrumentation ?? {\n enabled: true,\n granularity: 'fiber' as const,\n span_naming: { default: 'effect.{function}', infer_from_source: true, rules: [] },\n span_relationships: { type: 'parent-child' as const },\n filter: { include: [], exclude: [] },\n performance: { sampling_rate: 1.0, min_duration: '0ms', max_concurrent: 0 },\n metadata: { fiber_info: true, source_location: true, parent_fiber: true }\n }\n\n if (!getGlobalProviderSetup()) {\n logger.log('@atrim/unified-tracing: No TracerProvider, using empty layer')\n return Layer.empty\n }\n\n const supervisor = new UnifiedTracingSupervisor(autoConfig)\n const supervisorLayer = Supervisor.addSupervisor(supervisor)\n\n // Use layerGlobal for HTTP tracing integration with Effect Platform\n // This gives us automatic http.server spans for all endpoints\n const serviceName = process.env.OTEL_SERVICE_NAME || 'effect-service'\n const serviceVersion = process.env.npm_package_version || '1.0.0'\n\n // Create the Resource layer required by layerGlobal\n const resourceLayer = Resource.layer({ serviceName, serviceVersion })\n\n // effectTracerLayer uses OtelApi.trace.getTracerProvider() internally\n const effectTracerLayer = OtelTracer.layerGlobal\n\n // Provide Resource to effectTracerLayer and discard the output service\n const tracerWithResource = effectTracerLayer.pipe(Layer.provide(resourceLayer))\n\n // Enable OpSupervision runtime flag so onEffect hook fires\n // This allows us to trace Effect.all, Effect.forEach, Effect.fork operations\n const opSupervisionLayer = Layer.effectDiscard(\n Effect.patchRuntimeFlags(RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision))\n )\n\n return Layer.mergeAll(\n Layer.discard(tracerWithResource),\n Layer.enableSourceCapture,\n supervisorLayer,\n opSupervisionLayer\n )\n}\n\n/**\n * Unified Tracing Layer - combines operation and fiber tracing with correct hierarchy\n *\n * NOTE: Uses Layer.suspend to defer provider setup until the layer is actually used.\n * This prevents the global TracerProvider from being set at module import time,\n * allowing tests to set up their own provider first.\n */\nexport const UnifiedTracingLive: Layer.Layer<never> = Layer.suspend(() =>\n createUnifiedTracingLayer()\n)\n\n/**\n * Helper to enable OpSupervision runtime flag\n */\nexport const enableOpSupervision = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n Effect.withRuntimeFlagsPatch(effect, RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision))\n\n/**\n * Wrap an effect with unified tracing (OpSupervision + layer)\n *\n * @example\n * ```typescript\n * const program = Effect.gen(function* () {\n * yield* Effect.fork(myTask()) // Fork span is parent of fiber span!\n * }).pipe(withUnifiedTracing)\n * ```\n */\nexport const withUnifiedTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, Exclude<R, never>> =>\n effect.pipe(enableOpSupervision, Effect.provide(UnifiedTracingLive))\n\n/**\n * Wrap an effect with auto-tracing using a custom config\n *\n * This is the legacy API for backward compatibility. It allows passing a custom\n * config and optional root span name.\n *\n * @deprecated Use `withUnifiedTracing` with `UnifiedTracingLive` layer instead.\n *\n * @example\n * ```typescript\n * const result = await Effect.runPromise(withAutoTracing(program, config, 'my-root-span'))\n * ```\n */\nexport const withAutoTracing = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n config?: AutoInstrumentationConfig,\n rootSpanName?: string\n): Effect.Effect<A, E, R> => {\n // Create a supervisor with the given config (or default)\n const autoConfig = config ?? {\n enabled: true,\n granularity: 'fiber' as const,\n span_naming: { default: 'effect.{function}', infer_from_source: true, rules: [] },\n span_relationships: { type: 'parent-child' as const },\n filter: { include: [], exclude: [] },\n performance: { sampling_rate: 1.0, min_duration: '0ms', max_concurrent: 0 },\n metadata: { fiber_info: true, source_location: true, parent_fiber: true }\n }\n\n const supervisor = new UnifiedTracingSupervisor(autoConfig)\n const supervisorLayer = Supervisor.addSupervisor(supervisor)\n\n // Enable OpSupervision and source capture\n const opSupervisionLayer = Layer.effectDiscard(\n Effect.patchRuntimeFlags(RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision))\n )\n\n const combinedLayer = Layer.mergeAll(\n supervisorLayer,\n Layer.enableSourceCapture,\n opSupervisionLayer\n )\n\n // Wrap with root span if name provided\n const wrappedEffect = rootSpanName ? effect.pipe(Effect.withSpan(rootSpanName)) : effect\n\n return wrappedEffect.pipe(Effect.provide(combinedLayer))\n}\n\n// ============================================================================\n// Provider Shutdown\n// ============================================================================\n\nexport const flushAndShutdown = async (): Promise<void> => {\n const setup = getGlobalProviderSetup()\n if (setup?.provider) {\n logger.log('@atrim/unified-tracing: Flushing and shutting down TracerProvider...')\n await setup.provider.forceFlush()\n await setup.provider.shutdown()\n logger.log('@atrim/unified-tracing: TracerProvider shutdown complete')\n }\n}\n\nexport const forceFlush = async (): Promise<void> => {\n const setup = getGlobalProviderSetup()\n if (setup?.provider) {\n logger.log('@atrim/unified-tracing: Force flushing TracerProvider...')\n await setup.provider.forceFlush()\n logger.log('@atrim/unified-tracing: Force flush complete')\n }\n}\n\n// ============================================================================\n// Re-export span control utilities\n// ============================================================================\n\nexport {\n withoutAutoTracing,\n setSpanName,\n AutoTracingEnabled,\n AutoTracingSpanName\n} from './span-control.js'\n","/**\n * Unified Tracing for Effect-TS\n *\n * Provides automatic tracing of all Effect operations, fibers, and fork hierarchies.\n * Configuration-driven via instrumentation.yaml.\n *\n * RECOMMENDED API:\n * - `UnifiedTracingLive` - Layer for Effect.provide()\n * - `withUnifiedTracing` - Simple wrapper for pipe()\n *\n * @example\n * ```typescript\n * import { withUnifiedTracing, withoutAutoTracing, setSpanName } from '@atrim/instrument-node/effect/auto'\n *\n * const program = Effect.gen(function* () {\n * // Automatically traced - operations, fibers, and fork hierarchy\n * yield* Effect.all([doA(), doB()])\n * yield* Effect.fork(backgroundTask())\n *\n * // Opt-out for internal operations\n * yield* withoutAutoTracing(internalWork())\n *\n * // Custom span name override\n * yield* setSpanName('custom.operation')(criticalWork())\n * }).pipe(withUnifiedTracing)\n * ```\n *\n * @packageDocumentation\n */\n\n// ============================================================================\n// Unified Tracing (RECOMMENDED)\n// Combines operation + fiber tracing with correct fork span hierarchy\n// ============================================================================\n\n/**\n * Unified Tracing - The recommended API for Effect tracing\n *\n * UnifiedTracingLive provides:\n * - Automatic fiber-level tracing\n * - Operation tracing (Effect.all, Effect.forEach, Effect.fork)\n * - Correct fork span hierarchy (fork spans are parents of fiber spans)\n * - Source location capture for meaningful span names\n * - Auto OTel context bridging\n *\n * @example\n * ```typescript\n * import { UnifiedTracingLive, withUnifiedTracing } from '@atrim/instrument-node/effect/auto'\n *\n * // Option 1: Using the layer\n * const program = myEffect.pipe(Effect.provide(UnifiedTracingLive))\n *\n * // Option 2: Using the wrapper (simpler)\n * const program = myEffect.pipe(withUnifiedTracing)\n * ```\n *\n * Resulting trace hierarchy:\n * ```\n * http.server GET\n * ├── effect.fork (index.ts:15)\n * │ └── effect.fiber (index.ts:15) ← child of fork span\n * └── effect.all (index.ts:18)\n * ├── effect.fiber (task1)\n * └── effect.fiber (task2)\n * ```\n */\nexport {\n // Simplest API - wraps effect with unified tracing\n withUnifiedTracing,\n // Layer for Effect.provide()\n UnifiedTracingLive,\n createUnifiedTracingLayer,\n // Supervisor class (for advanced use)\n UnifiedTracingSupervisor,\n // Provider shutdown (call before exit to ensure spans are exported)\n flushAndShutdown,\n forceFlush,\n // Helper to enable OpSupervision manually\n enableOpSupervision,\n // Span control utilities\n withoutAutoTracing,\n setSpanName,\n // FiberRefs (for advanced use)\n AutoTracingEnabled,\n AutoTracingSpanName\n} from './unified-tracing-supervisor.js'\n\n// Re-export OperationMeta type for advanced users\nexport type { OperationMeta } from './unified-tracing-supervisor.js'\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\nexport {\n AutoTracingConfig,\n AutoTracingConfigLive,\n AutoTracingConfigLayer,\n loadAutoTracingConfig,\n loadAutoTracingConfigSync,\n loadFullConfigSync,\n defaultAutoTracingConfig\n} from './config.js'\nexport type { AutoInstrumentationConfig } from './config.js'\n\n// ============================================================================\n// Naming utilities (for advanced use)\n// ============================================================================\n\nexport { inferSpanName, sanitizeSpanName } from './naming.js'\nexport type { SourceInfo, TemplateVariables } from './naming.js'\n\n// ============================================================================\n// Legacy utilities (maintained for backward compatibility)\n// ============================================================================\n\n/**\n * @deprecated Use Effect.fork() with UnifiedTracingLive instead.\n * The UnifiedTracingSupervisor traces Effect.fork automatically.\n */\nexport {\n tracedFork,\n tracedForkDaemon,\n CapturedSourceLocation,\n captureCallSite\n} from './traced-fork.js'\n\n/**\n * @deprecated Fork patching is no longer needed with UnifiedTracingLive.\n * The UnifiedTracingSupervisor captures source locations natively.\n */\nexport { patchEffectFork, unpatchEffectFork, isEffectForkPatched } from './patch-fork.js'\n\n// ============================================================================\n// Backward compatibility aliases\n// ============================================================================\n\n// For gradual migration, provide aliases to the old names\n// These should be removed in a future major version\n\n/**\n * @deprecated Use UnifiedTracingLive instead\n */\nexport { UnifiedTracingLive as FullAutoTracingLive } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use createUnifiedTracingLayer instead\n */\nexport { createUnifiedTracingLayer as createFullAutoTracingLayer } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use UnifiedTracingLive instead\n */\nexport { UnifiedTracingLive as AutoTracingLive } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use createUnifiedTracingLayer instead\n */\nexport { createUnifiedTracingLayer as createAutoTracingLayer } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use UnifiedTracingLive instead\n */\nexport { UnifiedTracingLive as SourceCaptureTracingLive } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use UnifiedTracingLive instead\n */\nexport { UnifiedTracingLive as CombinedTracingLive } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use UnifiedTracingLive instead\n */\nexport { UnifiedTracingLive as OperationTracingLive } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use withUnifiedTracing instead\n */\nexport { withUnifiedTracing as withOperationTracing } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use withUnifiedTracing instead\n *\n * Note: This version accepts a config and optional rootSpanName for backward compatibility\n * with tests that need custom configs.\n */\nexport { withAutoTracing } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use UnifiedTracingSupervisor instead\n */\nexport { UnifiedTracingSupervisor as AutoTracingSupervisor } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use UnifiedTracingSupervisor instead\n */\nexport { UnifiedTracingSupervisor as SourceCaptureSupervisor } from './unified-tracing-supervisor.js'\n\n/**\n * @deprecated Use new UnifiedTracingSupervisor(config) instead\n */\nexport const createAutoTracingSupervisor = (\n config: import('./config.js').AutoInstrumentationConfig\n) => new (require('./unified-tracing-supervisor.js').UnifiedTracingSupervisor)(config)\n","/**\n * Span Name Inference for Auto-Tracing\n *\n * Provides intelligent span naming based on source code information\n * and configuration rules from instrumentation.yaml.\n */\n\nimport type { AutoInstrumentationConfig, SpanNamingRule } from '@atrim/instrument-core'\nimport * as path from 'path'\n\n/**\n * Source code information extracted from stack traces\n */\nexport interface SourceInfo {\n /** Function name (or 'anonymous') */\n function: string\n /** Full file path */\n file: string\n /** Line number */\n line: number\n /** Column number */\n column: number\n}\n\n/**\n * Template variables available for span naming\n */\nexport interface TemplateVariables {\n fiber_id: string\n function: string\n module: string\n file: string\n line: string\n operator: string\n [key: string]: string\n}\n\n/**\n * Compiled naming rule with pre-compiled regex patterns\n */\ninterface CompiledNamingRule {\n original: SpanNamingRule\n filePattern: RegExp | undefined\n functionPattern: RegExp | undefined\n modulePattern: RegExp | undefined\n}\n\n// Cache for compiled naming rules\nconst compiledRulesCache = new WeakMap<SpanNamingRule[], CompiledNamingRule[]>()\n\n/**\n * Compile naming rules for efficient matching\n */\nfunction compileNamingRules(rules: SpanNamingRule[]): CompiledNamingRule[] {\n const cached = compiledRulesCache.get(rules)\n if (cached) return cached\n\n const compiled: CompiledNamingRule[] = rules.map((rule) => ({\n original: rule,\n filePattern: rule.match.file ? new RegExp(rule.match.file) : undefined,\n functionPattern: rule.match.function ? new RegExp(rule.match.function) : undefined,\n modulePattern: rule.match.module ? new RegExp(rule.match.module) : undefined\n }))\n\n compiledRulesCache.set(rules, compiled)\n return compiled\n}\n\n/**\n * Extract module name from file path\n */\nfunction extractModuleName(filePath: string): string {\n const basename = path.basename(filePath, path.extname(filePath))\n // Remove common suffixes (both dot-separated and PascalCase)\n // e.g., \"user.service\" -> \"user\", \"UserService\" -> \"User\"\n return basename\n .replace(/\\.(service|controller|handler|util|helper|model|repo|repository)$/i, '')\n .replace(/(Service|Controller|Handler|Util|Helper|Model|Repo|Repository)$/i, '')\n}\n\n/**\n * Apply template variables to a span name pattern\n *\n * Supports:\n * - {fiber_id} - Fiber ID\n * - {function} - Function name\n * - {module} - Module name (filename without extension)\n * - {file} - Full file path\n * - {line} - Line number\n * - {operator} - Effect operator (if known)\n * - {match:field:N} - Captured regex group from match\n */\nfunction applyTemplate(\n template: string,\n variables: TemplateVariables,\n matchGroups?: Map<string, string[]>\n): string {\n let result = template\n\n // Replace simple variables\n for (const [key, value] of Object.entries(variables)) {\n result = result.replace(new RegExp(`\\\\{${key}\\\\}`, 'g'), value)\n }\n\n // Replace match groups: {match:field:N} where field is 'file', 'function', 'module'\n // and N is the capture group index\n if (matchGroups) {\n result = result.replace(\n /\\{match:(\\w+):(\\d+)\\}/g,\n (_fullMatch, field: string, index: string): string => {\n const groups = matchGroups.get(field)\n const idx = parseInt(index, 10)\n if (groups && groups[idx]) {\n return groups[idx]\n }\n return ''\n }\n )\n }\n\n return result\n}\n\n/**\n * Find matching naming rule for the given source info\n */\nfunction findMatchingRule(\n sourceInfo: SourceInfo | undefined,\n config: AutoInstrumentationConfig\n): { rule: CompiledNamingRule; matchGroups: Map<string, string[]> } | undefined {\n const rules = config.span_naming?.rules\n if (!rules || rules.length === 0) return undefined\n\n const compiledRules = compileNamingRules(rules)\n\n for (const rule of compiledRules) {\n const matchGroups = new Map<string, string[]>()\n let allMatched = true\n\n // Check file pattern\n if (rule.filePattern) {\n if (sourceInfo?.file) {\n const match = sourceInfo.file.match(rule.filePattern)\n if (match) {\n matchGroups.set('file', match.slice(1))\n } else {\n allMatched = false\n }\n } else {\n allMatched = false\n }\n }\n\n // Check function pattern\n if (rule.functionPattern && allMatched) {\n if (sourceInfo?.function) {\n const match = sourceInfo.function.match(rule.functionPattern)\n if (match) {\n matchGroups.set('function', match.slice(1))\n } else {\n allMatched = false\n }\n } else {\n allMatched = false\n }\n }\n\n // Check module pattern\n if (rule.modulePattern && allMatched) {\n const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : ''\n if (moduleName) {\n const match = moduleName.match(rule.modulePattern)\n if (match) {\n matchGroups.set('module', match.slice(1))\n } else {\n allMatched = false\n }\n } else {\n allMatched = false\n }\n }\n\n if (allMatched) {\n return { rule, matchGroups }\n }\n }\n\n return undefined\n}\n\n/**\n * Infer a span name based on fiber ID, source info, and configuration\n *\n * Priority:\n * 1. Match against naming rules (first match wins)\n * 2. Use default template with source info if available\n * 3. Fallback to default template with fiber ID only\n *\n * Smart anonymous handling:\n * - When function is \"anonymous\", falls back to \"module:line\" format\n * - Example: \"effect.index:42\" instead of \"effect.anonymous\"\n *\n * @param fiberId - The fiber's numeric ID\n * @param sourceInfo - Optional source code information from stack trace\n * @param config - Auto-instrumentation configuration\n * @returns The inferred span name\n */\nexport function inferSpanName(\n fiberId: number,\n sourceInfo: SourceInfo | undefined,\n config: AutoInstrumentationConfig\n): string {\n // Determine the best function name\n let functionName = sourceInfo?.function || 'anonymous'\n const moduleName = sourceInfo?.file ? extractModuleName(sourceInfo.file) : 'unknown'\n\n // If function is anonymous and we have source location, use module:line format\n if (functionName === 'anonymous' && sourceInfo?.file && sourceInfo?.line) {\n functionName = `${moduleName}:${sourceInfo.line}`\n }\n\n // Build template variables\n const variables: TemplateVariables = {\n fiber_id: String(fiberId),\n function: functionName,\n module: moduleName,\n file: sourceInfo?.file || 'unknown',\n line: sourceInfo?.line ? String(sourceInfo.line) : '0',\n operator: 'gen' // Default operator, could be enhanced with more context\n }\n\n // Try to match a naming rule\n const match = findMatchingRule(sourceInfo, config)\n if (match) {\n return applyTemplate(match.rule.original.name, variables, match.matchGroups)\n }\n\n // Use default template\n const defaultTemplate = config.span_naming?.default || 'effect.fiber.{fiber_id}'\n return applyTemplate(defaultTemplate, variables)\n}\n\n/**\n * Sanitize a span name to be OpenTelemetry compliant\n *\n * - Replaces invalid characters with underscores\n * - Ensures name is not empty\n * - Truncates to reasonable length\n */\nexport function sanitizeSpanName(name: string): string {\n if (!name) return 'effect.fiber.unknown'\n\n // Replace invalid characters (keep alphanumeric, dot, underscore, dash)\n let sanitized = name.replace(/[^a-zA-Z0-9._-]/g, '_')\n\n // Collapse multiple underscores\n sanitized = sanitized.replace(/_+/g, '_')\n\n // Remove leading/trailing underscores\n sanitized = sanitized.replace(/^_+|_+$/g, '')\n\n // Ensure not empty\n if (!sanitized) return 'effect.fiber.unknown'\n\n // Truncate to reasonable length (OTel has no strict limit, but 256 is reasonable)\n if (sanitized.length > 256) {\n sanitized = sanitized.substring(0, 256)\n }\n\n return sanitized\n}\n","/**\n * Traced Fork - Capture call site for better span names\n *\n * This module provides tracedFork() which captures the call site\n * BEFORE entering Effect's runtime, allowing the supervisor to\n * create spans with meaningful names instead of \"effect.anonymous\".\n */\n\nimport { Effect, FiberRef } from 'effect'\nimport type { SourceInfo } from './naming.js'\n\n/**\n * FiberRef to store captured source location\n * Set by tracedFork(), read by supervisor\n */\nexport const CapturedSourceLocation = FiberRef.unsafeMake<SourceInfo | undefined>(undefined)\n\n/**\n * Capture the current call site from stack trace\n * Uses same technique as Effect.withSpan's captureStackTrace\n *\n * @param skipFrames - Number of additional frames to skip (default: 0)\n * Useful when calling from wrapper functions\n */\nexport function captureCallSite(skipFrames: number = 0): SourceInfo | undefined {\n // Limit stack depth for performance\n const originalLimit = Error.stackTraceLimit\n Error.stackTraceLimit = 10\n\n const error = new Error()\n Error.stackTraceLimit = originalLimit\n\n if (!error.stack) return undefined\n\n const lines = error.stack.split('\\n')\n\n // Skip:\n // [0] Error\n // [1] captureCallSite\n // [2] caller (tracedFork or patchedFork wrapper)\n // [3+skipFrames] USER CODE <-- This is what we want!\n\n const startIndex = 3 + skipFrames\n for (let i = startIndex; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined) continue\n\n // Skip @atrim and effect internals\n if (line.includes('@atrim/instrument') || line.includes('node_modules/effect')) {\n continue\n }\n\n // Parse: \" at functionName (file:line:col)\"\n const match = line.match(/at\\s+(?:(.+?)\\s+)?\\(?(.+?):(\\d+):(\\d+)\\)?/)\n if (match) {\n const [, funcName, filePath, lineNum, colNum] = match\n return {\n function: funcName?.trim() ?? 'anonymous',\n file: filePath ?? 'unknown',\n line: parseInt(lineNum ?? '0', 10),\n column: parseInt(colNum ?? '0', 10)\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Fork an effect with captured call site for better span naming\n *\n * This is a drop-in replacement for Effect.fork() that captures the\n * call site location. The supervisor reads this via CapturedSourceLocation\n * FiberRef to create better span names.\n *\n * @example\n * ```typescript\n * // Instead of:\n * yield* Effect.fork(myTask)\n *\n * // Use:\n * yield* tracedFork(myTask)\n *\n * // Span name will be \"effect.index:42\" instead of \"effect.anonymous\"\n * ```\n */\nexport const tracedFork = <A, E, R>(effect: Effect.Effect<A, E, R>) => {\n // Capture call site NOW while user code is still on stack\n const callSite = captureCallSite()\n\n if (!callSite) {\n // No call site captured, use regular fork\n return Effect.fork(effect)\n }\n\n // Set the FiberRef BEFORE forking so it's available in the child fiber's FiberRefs\n // This makes it available to the supervisor's onStart hook\n return FiberRef.set(CapturedSourceLocation, callSite).pipe(Effect.zipRight(Effect.fork(effect)))\n}\n\n/**\n * Fork an effect in daemon mode with captured call site\n *\n * Same as tracedFork() but creates a daemon fiber.\n */\nexport const tracedForkDaemon = <A, E, R>(effect: Effect.Effect<A, E, R>) => {\n const callSite = captureCallSite()\n\n if (!callSite) {\n return Effect.forkDaemon(effect)\n }\n\n return FiberRef.set(CapturedSourceLocation, callSite).pipe(\n Effect.zipRight(Effect.forkDaemon(effect))\n )\n}\n","/**\n * Effect.fork Patching Utilities\n *\n * Due to ESM module immutability, we cannot directly patch Effect.fork at runtime.\n * This module provides status tracking and documentation for users.\n *\n * **For reliable call-site capture, use the explicit wrappers:**\n * - `tracedFork(effect)` - replacement for `Effect.fork(effect)`\n * - `tracedForkDaemon(effect)` - replacement for `Effect.forkDaemon(effect)`\n *\n * **Future options for true auto-instrumentation:**\n * - ESM loader hooks (requires Node.js --import flag)\n * - Build-time transforms (Babel/SWC plugin)\n * - Effect upstream enhancement (proposed)\n */\n\nimport { logger } from '@atrim/instrument-core'\n\n// Track patching state\nlet patchAttempted = false\n\n/**\n * Check if Effect.fork patching was attempted\n *\n * Note: Due to ESM limitations, actual patching is not currently supported.\n * Use `tracedFork()` for reliable call-site capture.\n */\nexport function isEffectForkPatched(): boolean {\n return false // Patching not supported in ESM\n}\n\n/**\n * Attempt to enable automatic call-site capture for Effect.fork.\n *\n * **Note:** Due to ESM module immutability, this is currently a no-op.\n * Use `tracedFork()` and `tracedForkDaemon()` for explicit call-site capture.\n *\n * @example\n * ```typescript\n * // Instead of:\n * yield* Effect.fork(myEffect) // Span: \"effect.anonymous\"\n *\n * // Use:\n * import { tracedFork } from '@atrim/instrument-node/effect/auto'\n * yield* tracedFork(myEffect) // Span: \"effect.myFile:42\"\n * ```\n */\nexport function patchEffectFork(): void {\n if (patchAttempted) {\n return\n }\n patchAttempted = true\n\n // Log once that patching is not available\n logger.log('@atrim/auto-trace: Effect.fork auto-patching not available (ESM limitation)')\n logger.log('@atrim/auto-trace: Use tracedFork() for call-site capture')\n}\n\n/**\n * No-op for API compatibility.\n */\nexport function unpatchEffectFork(): void {\n patchAttempted = false\n}\n"]}