@atrim/instrument-node 0.9.0 → 0.9.1-dev.6bfb5ec.20260120022327

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/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","z","Data","Context","Effect","parseYAML","fs","path","HttpClientRequest","FileSystem","HttpClient","Layer","__publicField","existsSync","join","defaultAutoTracingConfig","AutoTracingConfig","loadAutoTracingConfig","loadAutoTracingConfigSync","AutoTracingConfigLive","AutoTracingConfigLayer","loadFullConfigSync","yaml","AutoTracingEnabled","AutoTracingSpanName","withoutAutoTracing","setSpanName","FiberRef","Option","effect","UnifiedTracingLive","UnifiedTracingSupervisor","createUnifiedTracingLayer","enableOpSupervision","flushAndShutdown","forceFlush","withAutoTracing","withUnifiedTracing","trace","GlobalValue","Supervisor","OtelApi","FiberRefs","Exit","EffectTracer","context","TracerModule","ConsoleSpanExporter","OTLPTraceExporter","SimpleSpanProcessor","BatchSpanProcessor","BasicTracerProvider","resourceFromAttributes","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","Resource","OtelTracer","RuntimeFlagsPatch","RuntimeFlags","basename","path2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoXO,SAAS,uBAAuB,OAAA,EAAkD;AACvF,EAAA,IAAI,MAAA;AAGJ,EAAA,IAAI,OAAO,YAAY,Q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AA0B;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.cjs","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"]}
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","z","Data","Context","Effect","parseYAML","fs","path","HttpClientRequest","FileSystem","HttpClient","Layer","__publicField","existsSync","join","defaultAutoTracingConfig","AutoTracingConfig","loadAutoTracingConfig","loadAutoTracingConfigSync","AutoTracingConfigLive","AutoTracingConfigLayer","loadFullConfigSync","yaml","AutoTracingEnabled","AutoTracingSpanName","withoutAutoTracing","setSpanName","FiberRef","Option","effect","UnifiedTracingLive","UnifiedTracingSupervisor","createUnifiedTracingLayer","enableOpSupervision","flushAndShutdown","forceFlush","withAutoTracing","withUnifiedTracing","trace","GlobalValue","Supervisor","OtelApi","FiberRefs","Exit","EffectTracer","context","ConsoleSpanExporter","OTLPTraceExporter","SimpleSpanProcessor","BatchSpanProcessor","BasicTracerProvider","resourceFromAttributes","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","Resource","OtelTracer","RuntimeFlagsPatch","RuntimeFlags","basename","path2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoXO,SAAS,uBAAuB,OAAA,EAAkD;AACvF,EAAA,IAAI,MAAA;AAGJ,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,MAAA,GAASA,WAAU,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,GAAsBC,MAAE,MAAA,CAAO;AAC1C,MAAA,OAAA,EAASA,MAAE,MAAA,EAAA;MACX,OAAA,EAASA,KAAA,CAAE,OAAA,EAAA,CAAU,QAAA,EAAA;MACrB,WAAA,EAAaA,KAAA,CAAE,MAAA,EAA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,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.cjs","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 { 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 build-time injection via @effect/unplugin\n * Matches the SourceLocation interface from effect/SourceLocation\n */\ninterface SourceLocation {\n readonly path: string\n readonly line: number\n readonly column: number\n readonly label?: 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 currentSourceTrace FiberRef from the @clayroach/effect fork\n * This FiberRef is set by @effect/unplugin during build-time transformation\n */\nconst currentSourceTrace = GlobalValue.globalValue(\n Symbol.for('effect/FiberRef/currentSourceTrace'),\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 (used for OperationMeta.capturedAt)\n * Returns SourceLocation with path/line/column to match the interface\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 path: match[1],\n line: parseInt(match[2], 10),\n column: match[3] ? parseInt(match[3], 10) : 0\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.path}:${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.path.split('/').pop() ?? source.path\n return source.label\n ? `${filename}:${source.line} (${source.label})`\n : `${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.path)\n span.setAttribute('code.lineno', location.line)\n span.setAttribute('code.column', location.column)\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 from FiberRef (set by @effect/unplugin build-time transformation)\n const sourceLocation = FiberRefs.getOrDefault(fiberRefs, currentSourceTrace) 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.path)\n span.setAttribute('code.lineno', sourceLocation.line)\n span.setAttribute('code.column', sourceLocation.column)\n if (sourceLocation.label) {\n span.setAttribute('code.function', sourceLocation.label)\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. Effect's ParentSpan in Context (Effect's native span tracking)\n // 2. Active OTel context (auto-bridging from OTel → Effect)\n // 3. Parent fiber's tracked context\n // 4. ROOT_CONTEXT (no parent)\n // ========================================================================\n\n // 1. 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 // 2. 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 // 3. 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 // 4. 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 // Note: Source location is now captured at build-time via @effect/unplugin\n // No runtime source capture layer is needed\n return Layer.mergeAll(Layer.discard(tracerWithResource), supervisorLayer, opSupervisionLayer)\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 (source capture is now handled at build-time via @effect/unplugin)\n const opSupervisionLayer = Layer.effectDiscard(\n Effect.patchRuntimeFlags(RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision))\n )\n\n const combinedLayer = Layer.mergeAll(supervisorLayer, opSupervisionLayer)\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"]}