projects/sdk/src/internal/logging.ts

/**
 * Client logger: Levels, categories, record building, formats, sinks, deduplication and counters.
 * Invariant: A configured sink or format replaces the Effect logger, and the default API writes readable lines to a terminal and
 * JSON lines otherwise, deciding separately for standard output and standard error. Effect's cause printer shows raw messages,
 * stacks and own properties, so native records carry masked copies. Deduplication keeps a bounded key set, and sink failures are
 * counted and reported once to standard error without altering outcomes or recursing. Implements [SDK contracts: Logging](/docs/SDK-CONTRACTS.md#logging)
 */
import { readFileSync } from "node:fs"
import { fileURLToPath } from "node:url"
import * as Cause from "effect/Cause"
import * as Clock from "effect/Clock"
import * as Context from "effect/Context"
import * as Effect from "effect/Effect"
import * as Logger from "effect/Logger"
import * as References from "effect/References"
import type { EventName } from "#sdk/events"
import type { ClientCounters, ErrorInfo, LogCategory, LogLevel, LogRecord, LogSink, LogThreshold } from "#sdk/logging"
import { ConfigurationError, FluxerlyError, type ConnectionError } from "#sdk/errors"
import { record } from "./decode/primitives.js"
import { readCaller, suspendMarked } from "./defects.js"
import { stripAnsi, supportsTerminalColor, supportsTerminalUnicode } from "./cli-theme.js"
import { metrics } from "./metrics.js"
import { maskDetails, maskedErrorCode, maskedSummary, maskPayload, maskText, maskValue } from "./masking.js"
import { retryableConnection } from "./retryable-connection.js"
import { unsupportedKeyHint } from "./suggest.js"
import { errorCodes, logCodes, type LogCode } from "./code-catalogue.js"

const logCategories = [
    "lifecycle",
    "gateway",
    "rest",
    "ratelimit",
    "cache",
    "events",
    "commands",
    "collectors",
    "supervisor",
    "sdk",
] as const satisfies readonly LogCategory[]

const levels = ["trace", "debug", "info", "warn", "error", "fatal"] as const satisfies readonly LogLevel[]
const rank: Record<LogThreshold, number> = { trace: 0, debug: 1, info: 2, warn: 3, error: 4, fatal: 5, silent: 6 }
/** Distinct Warn-or-higher records whose repeats are tracked at once */
const dedupeCapacity = 512
const effectLevels = {
    trace: "Trace",
    debug: "Debug",
    info: "Info",
    warn: "Warn",
    error: "Error",
    fatal: "Fatal",
} as const

let cachedVersion: string | undefined
/** The installed SDK version from the package manifest next to the compiled or source directory */
export function sdkVersion(): string {
    if (cachedVersion !== undefined) return cachedVersion
    try {
        const manifest = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")) as unknown
        cachedVersion = record(manifest) && typeof manifest.version === "string" ? manifest.version : "unknown"
    } catch {
        // allow-silent: A missing manifest only removes the version from the startup record
        cachedVersion = "unknown"
    }
    return cachedVersion
}

/** Record fields accepted from SDK call sites. The error is converted to ErrorInfo and cause keeps native Cause detail */
export interface LogInput {
    readonly level: LogLevel
    readonly category: LogCategory
    /** A catalogued code, so every emitted code has an entry on the error and log codes page */
    readonly code: LogCode
    readonly message: string
    readonly hint?: string | undefined
    readonly requestId?: number | undefined
    readonly shardId?: number | undefined
    readonly route?: string | undefined
    readonly event?: string | undefined
    readonly command?: string | undefined
    readonly subscriptionId?: string | undefined
    readonly durationMs?: number | undefined
    readonly attempt?: number | undefined
    readonly delayMs?: number | undefined
    readonly status?: number | undefined
    readonly closeCode?: number | undefined
    readonly fields?: Readonly<Record<string, string | number | boolean | null | undefined>> | undefined
    readonly error?: unknown
    readonly origin?: ErrorInfo["origin"] | undefined
    readonly cause?: Cause.Cause<unknown> | undefined
}

type Counters = {
    -readonly [K in keyof ClientCounters]: ClientCounters[K] extends number
        ? number
        : { -readonly [R in keyof ClientCounters[K]]: number }
}
export type CounterName = Exclude<keyof ClientCounters, "eventsDropped" | "eventsDroppedByEvent">
export type DropReason = keyof ClientCounters["eventsDropped"]

/** Extra safe presentation lines for SDK errors in describeError and pretty logs */
interface ErrorPresentation {
    readonly retry?: string | undefined
}

type ErrorValidationEntry = NonNullable<ErrorInfo["validationErrors"]>[number]

/** ErrorInfo values built from SDK errors, whose stacks only show SDK internals */
const sdkInfos = new WeakSet<ErrorInfo>()
/** Retry guidance and structured validation lines attached to SDK ErrorInfo instances */
const sdkPresentation = new WeakMap<ErrorInfo, ErrorPresentation>()

const retryableReasons = new Set(["busy", "network", "timeout", "rateLimit"])
const connectionTags = new Set([
    "AuthenticationError",
    "ConnectionError",
    "ConnectionTimeoutError",
    "RateLimitError",
    "ShardConnectionError",
])
const localMisuseTags = new Set([
    "ConfigurationError",
    "HelperError",
    "AssetUrlError",
    "ApplicationError",
    "SdkDefect",
    "UnhandledTestFailuresError",
    "TestTimeoutError",
])

/** Whether one failure value is an SDK error whose call is safe to repeat */
export function isRetryableSdkError(error: unknown): boolean {
    try {
        if (!(error instanceof FluxerlyError)) return false
        switch (error._tag) {
            case "RateLimitError":
            case "ConnectionTimeoutError":
                return true
            case "ConnectionError":
                return retryableConnection(error as ConnectionError)
            case "ShardConnectionError":
                return isRetryableSdkError(error.cause)
            case "MessageCleanupError":
                // A failed cleanup is never retryable, because its plan works only once
                if ((error as unknown as { phase?: unknown }).phase === "cleanup") return false
        }
        const fields = error as unknown as { reason?: unknown; outcome?: unknown }
        // Fluxer's busy upload slots answer changed nothing and asks for a retry like a rate limit does, unless the call
        // already read its caller's stream. The REST classifier marks it, since other rejected 503s, such as an OAuth read's,
        // are no such answer
        if (error.details.uploadSlotsBusy === true) return error.details.streamUsed !== true
        if (typeof fields.reason !== "string" || !retryableReasons.has(fields.reason)) return false
        // A rate-limited upload already read its caller's stream, so the same call would send it again empty
        if (error.details.streamUsed === true) return false
        const outcome = fields.outcome
        // A read cannot have changed remote state, so an unknown outcome only matters for writes
        return outcome !== "unknown" || fields.reason === "rateLimit" || error.details.read === true
    } catch {
        // allow-silent: A proxy of an SDK error whose properties reject reads is not treated as retryable
        return false
    }
}

/** The server-required wait of one failure value in milliseconds, or undefined when it carries none */
export function ownRetryAfterMs(error: unknown): number | undefined {
    try {
        if (!(error instanceof FluxerlyError)) return undefined
        // A shard failure carries the wait of the failure that stopped it
        if (error._tag === "ShardConnectionError") return ownRetryAfterMs(error.cause)
        const wait = (error as { readonly retryAfterMs?: unknown }).retryAfterMs
        return typeof wait === "number" && Number.isFinite(wait) && wait >= 0 ? wait : undefined
    } catch {
        // allow-silent: A proxy of an SDK error whose properties reject reads carries no usable wait
        return undefined
    }
}

/** Readable retry guidance line for a FluxerlyError, or undefined for local misuse and defects */
function retryGuidance(error: FluxerlyError): string | undefined {
    if (localMisuseTags.has(error._tag)) return undefined
    const fields = error as unknown as { outcome?: unknown; phase?: unknown }
    const outcome = fields.outcome
    const read = error.details.read === true
    if (error._tag === "MessageCleanupError" && fields.phase === "cleanup")
        return outcome === "unknown"
            ? "Do not retry blindly (outcome is unknown and the change may have been applied. Create a new preview plan after checking submittedBatches and terminalBatchIds)"
            : "Do not retry unchanged (this preview plan is single-use)"
    if (error._tag === "ClientClosedError")
        return outcome === "unknown" && !read
            ? "Do not retry blindly (outcome is unknown and the change may have been applied)"
            : "Do not retry on this client (create a new client)"
    if (error._tag === "CancelledError") return "Do not retry blindly if a write was already sent"
    const wait = ownRetryAfterMs(error)
    if (connectionTags.has(error._tag)) {
        if (!isRetryableSdkError(error)) return "Do not retry unchanged"
        return wait !== undefined
            ? `Safe to retry after ${wait} ms (create a new client if run ended)`
            : "Safe to retry (create a new client if run ended)"
    }
    if (error.details.streamUsed === true)
        return wait !== undefined
            ? `Do not retry unchanged (wait at least ${wait} ms and retry with a fresh stream or bytes)`
            : "Do not retry unchanged (retry with a fresh stream or bytes)"
    if (isRetryableSdkError(error)) return wait !== undefined ? `Safe to retry after ${wait} ms` : "Safe to retry"
    if (outcome === "unknown" && !read)
        return "Do not retry blindly (outcome is unknown and the change may have been applied)"
    return "Do not retry unchanged"
}

/** Safe allowlisted validation entries from a recognized ApiErrorDetail for ErrorInfo and indented display */
function validationEntries(apiError: unknown, secrets: readonly string[]): readonly ErrorValidationEntry[] {
    if (!record(apiError) || !Array.isArray(apiError.validationErrors) || apiError.validationErrors.length === 0)
        return []
    const entries: ErrorValidationEntry[] = []
    for (const item of apiError.validationErrors.slice(0, 32)) {
        if (!record(item) || typeof item.explanation !== "string") continue
        const path = typeof item.path === "string" && item.path.length > 0 ? maskText(item.path, secrets) : undefined
        const providerCode =
            typeof item.providerCode === "string" && item.providerCode.length > 0
                ? maskText(item.providerCode, secrets)
                : undefined
        const explanation = maskText(item.explanation, secrets)
        entries.push(
            Object.freeze({
                ...(path === undefined ? {} : { path }),
                ...(providerCode === undefined ? {} : { providerCode }),
                explanation,
            }),
        )
    }
    return Object.freeze(entries)
}

/** Format one structured validation entry as a single safe display line */
function formatValidationEntry(item: unknown): string | undefined {
    if (!record(item) || typeof item.explanation !== "string") return undefined
    const path = typeof item.path === "string" && item.path.length > 0 ? sanitizeSingleLine(item.path) : undefined
    const providerCode =
        typeof item.providerCode === "string" && item.providerCode.length > 0
            ? sanitizeSingleLine(item.providerCode)
            : undefined
    const explanation = sanitizeSingleLine(item.explanation)
    if (path !== undefined && providerCode !== undefined) return `${path} [${providerCode}]: ${explanation}`
    if (path !== undefined) return `${path}: ${explanation}`
    if (providerCode !== undefined) return `[${providerCode}]: ${explanation}`
    return explanation
}

/** Reconstruct retry guidance from in-process presentation or serialized ErrorInfo fields */
function retryLineFor(info: ErrorInfo): string | undefined {
    const presentation = sdkPresentation.get(info)
    if (presentation?.retry !== undefined) return presentation.retry
    if (typeof info.retryable !== "boolean" || localMisuseTags.has(info.name)) return undefined
    const wait =
        typeof info.retryAfterMs === "number" && Number.isFinite(info.retryAfterMs) && info.retryAfterMs >= 0
            ? info.retryAfterMs
            : undefined
    if (info.retryable) return wait !== undefined ? `Safe to retry after ${wait} ms` : "Safe to retry"
    if (info.details?.streamUsed === true)
        return wait !== undefined
            ? `Do not retry unchanged (wait at least ${wait} ms and retry with a fresh stream or bytes)`
            : "Do not retry unchanged (retry with a fresh stream or bytes)"
    if (info.details?.outcome === "unknown" && info.details?.read !== true)
        return "Do not retry blindly (outcome is unknown and the change may have been applied)"
    return "Do not retry unchanged"
}

/** Attach SDK presentation lines (nuanced retry guidance) to an ErrorInfo */
function attachSdkPresentation(info: ErrorInfo, value: FluxerlyError): void {
    sdkInfos.add(info)
    const retry = retryGuidance(value)
    if (retry !== undefined) sdkPresentation.set(info, { retry })
}

/** Catalogued SDK error codes as patterns, where a family such as guild.<reason> matches any one reason */
const sdkCodePatterns = Object.keys(errorCodes).map(
    (code) => new RegExp(`^${code.replaceAll(".", "\\.").replace(/<[^>]+>/g, "[^.]+")}$`),
)

/** Treat each error in a parsed record's cause chain with a catalogued SDK code as an SDK error, so its stack stays
 * hidden as it is in the process that built it. A supervisor parent calls this for the records its children print
 */
export function markSdkErrors(info: ErrorInfo | undefined, depth = 0): void {
    if (!info || depth >= 8) return
    if (typeof info.code === "string" && sdkCodePatterns.some((pattern) => pattern.test(info.code!))) sdkInfos.add(info)
    markSdkErrors(info.cause, depth + 1)
    if (Array.isArray(info.errors)) for (const member of info.errors) markSdkErrors(member, depth + 1)
}

/** Most member errors of an AggregateError kept in ErrorInfo */
const maximumMembers = 10

/** Structured SDK fields copied onto ErrorInfo for FluxerlyError values */
function sdkErrorExtras(
    value: FluxerlyError,
    apiError: unknown,
    secrets: readonly string[],
): Pick<ErrorInfo, "hint" | "retryable" | "retryAfterMs" | "validationErrors" | "details"> {
    const retryAfterMs = ownRetryAfterMs(value)
    const validation = validationEntries(apiError, secrets)
    const details = maskDetails(value.details, secrets)
    return {
        ...(value.hint === undefined ? {} : { hint: value.hint }),
        retryable: isRetryableSdkError(value),
        ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
        ...(validation.length > 0 ? { validationErrors: validation } : {}),
        ...(Object.keys(details).length > 0 ? { details } : {}),
    }
}

/** Convert any thrown or failed value to masked ErrorInfo, following the cause chain a few levels.
 * Never throws: Getters, proxies and null-prototype objects that reject inspection get a guarded description
 */
export function errorInfo(
    value: unknown,
    origin: ErrorInfo["origin"],
    secrets: readonly string[] = [],
    depth = 0,
): ErrorInfo {
    try {
        if (value instanceof Error) {
            const sdk = value instanceof FluxerlyError
            const code = sdk
                ? value.code
                : typeof (value as unknown as { code?: unknown }).code === "string"
                  ? (value as unknown as { code: string }).code
                  : undefined
            const apiError = sdk && (value as { apiError?: unknown }).apiError
            const cause = (value as { cause?: unknown }).cause
            // An AggregateError, such as the rejection of Promise.any, holds the reason of each attempt in errors
            const members: unknown = Object.hasOwn(value, "errors") ? (value as { errors?: unknown }).errors : undefined
            const stack: unknown = value.stack
            const info: ErrorInfo = Object.freeze({
                origin: sdk ? (apiError ? "provider" : origin === "application" ? "application" : "sdk") : origin,
                name: maskText(String(value.name), secrets),
                message: maskText(String(value.message), secrets),
                ...(code === undefined ? {} : { code: sdk ? code : maskedErrorCode(value, code, secrets) }),
                ...(sdk ? sdkErrorExtras(value, apiError, secrets) : {}),
                ...(typeof stack === "string" ? { stack: maskText(stack, secrets) } : {}),
                ...(cause === undefined || depth >= 4 ? {} : { cause: errorInfo(cause, origin, secrets, depth + 1) }),
                ...(!Array.isArray(members) || members.length === 0 || depth >= 4
                    ? {}
                    : {
                          errors: Object.freeze(
                              members
                                  .slice(0, maximumMembers)
                                  .map((member) => errorInfo(member, origin, secrets, depth + 1)),
                          ),
                      }),
            })
            if (sdk) attachSdkPresentation(info, value)
            return info
        }
    } catch {
        // allow-silent: An Error-like value whose properties throw is described below instead of failing the record
    }
    let kind: string
    try {
        kind = value === null ? "null" : typeof value
    } catch {
        // allow-silent: The typeof operator never throws, but keep the description total
        kind = "unknown"
    }
    return Object.freeze({
        origin,
        name: `Non-Error value (${kind})`,
        message: maskValue(value, secrets),
    })
}

/** The other failures and defects of a Cause after error, the one a record or report names, at most maximumMembers.
 * A Cause that does not hold error, such as one whose error was replaced, adds nothing, so no failure is shown twice
 */
export function otherFailures(cause: Cause.Cause<unknown> | undefined, error: unknown): unknown[] {
    if (cause === undefined) return []
    const values = cause.reasons.flatMap((reason) =>
        reason._tag === "Fail" ? [reason.error] : reason._tag === "Die" ? [reason.defect] : [],
    )
    if (!values.includes(error)) return []
    return [...new Set(values.filter((value) => value !== error))].slice(0, maximumMembers)
}

/** A copy of an error with its masked name, message, stack and cause chain, and only its code as another own property.
 * Effect's cause printer shows own enumerable properties, so native log records never receive the original value, and
 * the code appears next to the error name. An AggregateError copy keeps its members, and because Effect's printer shows
 * only the stack and cause, its stack also lists each member with its cause chain and nested members right after its
 * first line
 */
function maskedError(info: ErrorInfo, secrets: readonly string[] = []): Error {
    const options = info.cause ? { cause: maskedError(info.cause, secrets) } : undefined
    const error = info.errors
        ? new AggregateError(
              info.errors.map((member) => maskedError(member, secrets)),
              info.message,
              options,
          )
        : new Error(info.message, options)
    Object.defineProperty(error, "name", { value: info.name, configurable: true, writable: true, enumerable: false })
    if (info.code !== undefined) Object.defineProperty(error, "code", { value: info.code, enumerable: true })
    const first = `${info.name}: ${info.message}`
    const stack = info.stack ?? first
    // Each member prints with its code, hint, cause chain and nested members, as the readable description shows them
    const members = info.errors?.map(
        (member, index) =>
            `    [errors][${index}]: ${errorText(member, "", false, "", false, secrets).replaceAll("\n", "\n      ")}`,
    )
    // Effect's printer keeps the lines after the first one up to the first Effect frame, so the members come first
    error.stack = members?.length
        ? `${first}\n${members.join("\n")}${stack.startsWith(first) ? stack.slice(first.length) : `\n${stack}`}`
        : stack
    return error
}

/** The value a native log record shows in place of a failure or defect: Masked text or a masked Error copy */
function maskedValue(value: unknown, secrets: readonly string[]): unknown {
    if (typeof value === "string") return maskText(value, secrets)
    return maskedError(errorInfo(value, "sdk", secrets), secrets)
}

/** A Cause with every failure and defect replaced by its masked copy, keeping interruptions and annotations */
function maskedCause(cause: Cause.Cause<unknown>, secrets: readonly string[]): Cause.Cause<unknown> {
    return Cause.fromReasons(
        cause.reasons.map((reason) => {
            if (reason._tag === "Interrupt") return reason
            const copy =
                reason._tag === "Fail"
                    ? Cause.makeFailReason(maskedValue(reason.error, secrets))
                    : Cause.makeDieReason(maskedValue(reason.defect, secrets))
            return copy.annotate(Cause.reasonAnnotations(reason))
        }),
    )
}

/** Source and compiled directories of this SDK package, compared with forward slashes and, on Windows, lowercase */
const sdkDirectories = (() => {
    const root = fileURLToPath(new URL("../../", import.meta.url)).replaceAll("\\", "/")
    return [`${root}src/`, `${root}dist/`].map((directory) =>
        process.platform === "win32" ? directory.toLowerCase() : directory,
    )
})()

/** A stack frame with percent escapes decoded, or the frame unchanged when it has none or a malformed one */
function decodedFrame(frame: string): string {
    if (!frame.includes("%")) return frame
    try {
        return decodeURIComponent(frame)
    } catch {
        // allow-silent: A literal % in a plain file path is not an escape, so the frame is compared as written
        return frame
    }
}

/** Whether a stack frame runs inside this SDK or the Effect runtime rather than application code.
 * ESM frames print file URLs, which percent-encode spaces and non-ASCII characters in the install path, so both the
 * written and the decoded frame are compared with the decoded SDK directories
 */
function internalFrame(frame: string): boolean {
    return [frame, decodedFrame(frame)].some((form) => {
        let path = form.replaceAll("\\", "/")
        if (process.platform === "win32") path = path.toLowerCase()
        return (
            sdkDirectories.some((directory) => path.includes(directory)) ||
            /\/node_modules\/(?:\.pnpm\/)?effect[@/]/.test(path)
        )
    })
}

/** Whether a stack shows only where the SDK created an expected error. SdkDefect and ConfigurationError keep theirs,
 * since a defect needs its origin and a thrown configuration error points at the caller's line
 */
function internalStack(info: ErrorInfo): boolean {
    return sdkInfos.has(info) && info.name !== "SdkDefect" && info.name !== "ConfigurationError"
}

/** Details are SDK facts without credentials, and they are masked like any other value on their way to text */
function detailText(value: unknown, secrets: readonly string[] = []): string {
    return typeof value === "string" ? maskText(value, secrets) : maskPayload(value, secrets)
}

/** Sanitize text for a single log line by stripping ANSI escapes and escaping carriage returns and newlines */
function sanitizeSingleLine(text: string): string {
    return stripAnsi(text).replace(/\r\n/g, "\\n").replace(/\r/g, "\\r").replace(/\n/g, "\\n")
}

/** Sanitize multi-line text by stripping ANSI escapes, normalizing CRLF and escaping lone CR before splitting on LF */
function sanitizeMultiLine(text: string): readonly string[] {
    return stripAnsi(text).replaceAll("\r\n", "\n").replaceAll("\r", "\\r").split("\n")
}

/** Format stack frames for display, collapsing consecutive SDK and Effect frames into summary lines */
function collapsedStackLines(stack: string): readonly string[] {
    const output: string[] = []
    let hidden = 0
    const flush = () => {
        if (hidden > 0) output.push(`... ${hidden} SDK and Effect frame${hidden === 1 ? "" : "s"} hidden`)
        hidden = 0
    }
    for (const frame of stack.split("\n")) {
        if (!/^\s+at /.test(frame)) continue
        if (internalFrame(frame)) {
            hidden++
            continue
        }
        flush()
        output.push(sanitizeSingleLine(frame.trim()))
    }
    flush()
    return output
}

const ansi = {
    reset: "\u001b[0m",
    bold: "\u001b[1m",
    dim: "\u001b[2m",
    red: "\u001b[31m",
    green: "\u001b[32m",
    yellow: "\u001b[33m",
    magenta: "\u001b[35m",
    cyan: "\u001b[36m",
    boldRed: "\u001b[1;31m",
    boldGreen: "\u001b[1;32m",
    boldYellow: "\u001b[1;33m",
    boldMagenta: "\u001b[1;35m",
    boldCyan: "\u001b[1;36m",
} as const

function logSymbols(unicode: boolean) {
    return unicode
        ? {
              trace: "·",
              debug: "◆",
              info: "ℹ",
              ok: "✓",
              warn: "▲",
              error: "✖",
              fatal: "✖",
              rail: "│",
              hint: "→",
              retry: "↻",
              cause: "↳",
          }
        : {
              trace: ".",
              debug: "*",
              info: "i",
              ok: "+",
              warn: "!",
              error: "x",
              fatal: "x",
              rail: "|",
              hint: "->",
              retry: "~",
              cause: "->",
          }
}

function styledValidationEntry(item: string): string {
    const colon = item.indexOf(": ")
    if (colon <= 0) return item
    return `${ansi.yellow}${item.slice(0, colon + 1)}${ansi.reset}${item.slice(colon + 1)}`
}

function errorTheme(color: boolean, at: string, prefix: string, symbols: ReturnType<typeof logSymbols> | undefined) {
    const nested = prefix.length > 0
    const rail = color ? `${nested ? ansi.yellow : ansi.red}${symbols!.rail}${ansi.reset}` : ""
    return {
        lead: color ? `${at}${rail} ` : at,
        blank: color ? `${at}${rail}` : at,
        prefixText: nested ? (color ? `${ansi.boldYellow}${symbols!.cause} ${prefix}${ansi.reset}` : prefix) : "",
        name: (safeName: string) =>
            color ? `${ansi.boldRed}${nested ? "" : `${symbols!.error} `}${safeName}${ansi.reset}` : safeName,
        code: (safeCode: string | undefined) =>
            safeCode === undefined ? "" : color ? ` ${ansi.dim}[${safeCode}]${ansi.reset}` : ` [${safeCode}]`,
        message: (line: string) => (color ? `${ansi.bold}${line}${ansi.reset}` : line),
        hintLabel: color ? `${ansi.boldCyan}${symbols!.hint} Hint:${ansi.reset}` : "Hint:",
        detailsLabel: color ? `${ansi.dim}Details:${ansi.reset}` : "Details:",
        pair: (key: string, value: string) => (color ? `${ansi.dim}${key}=${ansi.reset}${value}` : `${key}=${value}`),
        retryLabel: (safeRetry: string) =>
            color
                ? `${safeRetry.startsWith("Safe to retry") ? ansi.boldGreen : ansi.boldYellow}${symbols!.retry} Retry:${ansi.reset}`
                : "Retry:",
        validationHeading: color ? `${ansi.boldYellow}Validation:${ansi.reset}` : "Validation:",
        validationItem: (item: string) => (color ? styledValidationEntry(item) : item),
        frame: (frameLine: string) => (color ? `${ansi.dim}${frameLine}${ansi.reset}` : frameLine),
    }
}

/** Readable multi-line text for an ErrorInfo, indented for console output: Title, hint, safe details and stack frames
 * for each error in the cause chain. Consecutive frames inside the SDK and Effect collapse into one line, and SDK
 * errors other than SdkDefect and ConfigurationError print no frames. JSON output keeps the full stack
 */
export function errorText(
    info: ErrorInfo,
    indent = "    ",
    stack = true,
    label = "",
    color = false,
    secrets: readonly string[] = [],
): string {
    const lines: string[] = []
    const symbols = color ? logSymbols(supportsTerminalUnicode()) : undefined
    const add = (start: ErrorInfo, at: string, startLabel: string) => {
        let current: ErrorInfo | undefined = start
        let prefix = startLabel
        while (current) {
            const safeName = sanitizeSingleLine(current.name)
            const safeCode = current.code === undefined ? undefined : sanitizeSingleLine(current.code)
            const messageLines = sanitizeMultiLine(current.message)
            const safeHint = current.hint ? sanitizeSingleLine(current.hint) : undefined
            const retry = retryLineFor(current)
            const safeRetry = retry === undefined ? undefined : sanitizeSingleLine(retry)
            const validation = Array.isArray(current.validationErrors)
                ? current.validationErrors
                      .map((item) => formatValidationEntry(item))
                      .filter((line): line is string => line !== undefined)
                : []
            const theme = errorTheme(color, at, prefix, symbols)

            lines.push(
                `${theme.lead}${theme.prefixText}${theme.name(safeName)}${theme.code(safeCode)}: ${theme.message(messageLines[0]!)}`,
            )
            for (let index = 1; index < messageLines.length; index++) {
                const continuation = messageLines[index]!
                lines.push(continuation.length > 0 ? `${theme.lead}  ${theme.message(continuation)}` : theme.blank)
            }
            if (safeHint) lines.push(`${theme.lead}  ${theme.hintLabel} ${safeHint}`)
            const details = Object.entries(current.details ?? {})
            if (details.length) {
                const pairs = details
                    .map(([key, value]) =>
                        theme.pair(sanitizeSingleLine(key), sanitizeSingleLine(detailText(value, secrets))),
                    )
                    .join(" ")
                lines.push(`${theme.lead}  ${theme.detailsLabel} ${pairs}`)
            }
            if (safeRetry) lines.push(`${theme.lead}  ${theme.retryLabel(safeRetry)} ${safeRetry}`)
            if (validation.length > 0) {
                lines.push(`${theme.lead}  ${theme.validationHeading}`)
                for (const item of validation) lines.push(`${theme.lead}    ${theme.validationItem(item)}`)
            }
            if (stack && current.stack && !internalStack(current)) {
                for (const frameLine of collapsedStackLines(current.stack))
                    lines.push(`${theme.lead}  ${theme.frame(frameLine)}`)
            }
            // The members of an AggregateError print under it, one level deeper
            for (const member of current.errors ?? []) add(member, `${at}  `, "Contains: ")
            prefix = "Caused by: "
            current = current.cause
        }
    }
    add(info, indent, label)
    return lines.join("\n")
}

function formatTime(raw: string): string {
    const date = new Date(raw)
    if (Number.isNaN(date.getTime())) return sanitizeSingleLine(raw) || "invalid-time"
    const pad = (value: number, width = 2) => String(value).padStart(width, "0")
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
}

const successInfoCodes = new Set<string>([
    "lifecycle.ready",
    "lifecycle.connected",
    "lifecycle.sessionRestored",
    "lifecycle.drained",
    "lifecycle.shutdownComplete",
])

const levelStyles: Record<LogLevel, string> = {
    trace: ansi.dim,
    debug: ansi.magenta,
    info: ansi.cyan,
    warn: ansi.boldYellow,
    error: ansi.boldRed,
    fatal: ansi.boldMagenta,
}

const categoryStyles: Record<LogCategory, string> = {
    lifecycle: ansi.green,
    gateway: ansi.cyan,
    rest: ansi.magenta,
    ratelimit: ansi.yellow,
    cache: ansi.dim,
    events: ansi.cyan,
    commands: ansi.magenta,
    collectors: ansi.magenta,
    supervisor: ansi.yellow,
    sdk: ansi.dim,
}

const recordKeys = [
    "requestId",
    "shardId",
    "route",
    "event",
    "command",
    "subscriptionId",
    "status",
    "closeCode",
    "attempt",
    "delayMs",
    "durationMs",
] as const

/** Actionable warn/error log codes whose catalogue action serves as a concise fallback hint when no error hint exists */
const actionableHintCodes = new Set<string>([
    "lifecycle.drainTimedOut",
    "gateway.dispatchRejected",
    "gateway.threadSkipped",
    "gateway.memberSkipped",
    "gateway.gatewayError",
    "gateway.ignoredEventRegistered",
    "rest.busy",
    "rest.responseRejected",
    "ratelimit.wait",
    "ratelimit.queueHeld",
    "ratelimit.deadline",
    "ratelimit.notResent",
    "events.dropped",
    "events.overflow",
    "events.registeredAfterShutdown",
    "cache.changesDropped",
    "supervisor.startupTimeout",
    "supervisor.terminated",
    "sdk.unknownDebugCategory",
    "sdk.unknownEnvironmentValue",
    "sdk.unsafePayloads",
])

/** Avoid duplicating a record's error message verbatim on line 1 when entry.error immediately follows on line 2 */
function prettyMessage(entry: LogRecord): string {
    const raw = entry.message
    const errorMessage = entry.error?.message
    if (!errorMessage) return raw
    const suffix = `: ${errorMessage}`
    if (raw.length > suffix.length && raw.endsWith(suffix)) return raw.slice(0, -suffix.length)
    const index = raw.indexOf(`${suffix} (`)
    if (index > 0) return `${raw.slice(0, index)}${raw.slice(index + suffix.length)}`
    return raw
}

function statusStyle(status: number): string {
    if (status >= 200 && status < 300) return ansi.green
    if (status >= 400 && status < 500) return ansi.yellow
    if (status >= 500) return ansi.red
    return ""
}

function formatFactValue(value: string | number | boolean | null): string {
    if (typeof value === "number") return Number.isInteger(value) ? String(value) : value.toFixed(1)
    if (typeof value === "string") {
        const clean = stripAnsi(value)
        return /\s/.test(clean) ? JSON.stringify(clean) : sanitizeSingleLine(clean)
    }
    return String(value)
}

function prettyFacts(
    entry: LogRecord,
    color: boolean,
    topHint: string | undefined,
): { readonly facts: readonly string[]; readonly payload: string | undefined } {
    const facts: string[] = []
    for (const key of recordKeys) {
        const value = entry[key]
        if (value === undefined) continue
        const formatted = formatFactValue(value)
        if (!color) {
            facts.push(`${key}=${formatted}`)
        } else if (key === "requestId") {
            facts.push(`${ansi.cyan}#${formatted}${ansi.reset}`)
        } else if (key === "status" && typeof value === "number") {
            const tone = statusStyle(value)
            facts.push(`${ansi.dim}status=${ansi.reset}${tone}${formatted}${tone ? ansi.reset : ""}`)
        } else {
            facts.push(`${ansi.dim}${key}=${ansi.reset}${formatted}`)
        }
    }
    let payload: string | undefined
    for (const [key, value] of Object.entries(entry.fields ?? {})) {
        if (key === "payload" && typeof value === "string") {
            payload = value
            continue
        }
        // Skip fields.hint when the indented Hint rail renders the same text below line 1
        if (key === "hint" && typeof value === "string" && topHint === value) continue
        const safeKey = sanitizeSingleLine(key)
        const formatted = formatFactValue(value)
        facts.push(color ? `${ansi.dim}${safeKey}=${ansi.reset}${formatted}` : `${safeKey}=${formatted}`)
    }
    return { facts, payload }
}

function prettyHeader(entry: LogRecord, color: boolean, sym: ReturnType<typeof logSymbols> | undefined): string {
    const level = sanitizeSingleLine(entry.level).toUpperCase().padEnd(5)
    const timestamp = formatTime(entry.time)
    const safeCategory = sanitizeSingleLine(entry.category).padEnd(10)
    const safeCode = sanitizeSingleLine(entry.code)
    const safeMessage = sanitizeSingleLine(prettyMessage(entry))
    if (!color) return `${timestamp} ${level} ${safeCategory} [${safeCode}] ${safeMessage}`
    const icons = sym!
    const positiveInfo = entry.level === "info" && successInfoCodes.has(entry.code)
    const icon = positiveInfo ? icons.ok : (icons[entry.level] ?? icons.info)
    const levelColor = positiveInfo ? ansi.boldGreen : (levelStyles[entry.level] ?? ansi.dim)
    const badge = `${levelColor}${icon} ${level}${ansi.reset}`
    const category = `${categoryStyles[entry.category] ?? ansi.magenta}${safeCategory}${ansi.reset}`
    const code = `${ansi.dim}[${safeCode}]${ansi.reset}`
    const message =
        entry.level === "error" || entry.level === "fatal"
            ? `${ansi.bold}${safeMessage}${ansi.reset}`
            : entry.level === "trace" || entry.level === "debug"
              ? `${ansi.dim}${safeMessage}${ansi.reset}`
              : safeMessage
    return `${ansi.dim}${timestamp}${ansi.reset} ${badge} ${category} ${code} ${message}`
}

/** One readable line per record, with key facts and indented hint, payload and error rails */
export function prettyLine(entry: LogRecord, color: boolean, secrets: readonly string[] = []): string {
    const topHint =
        typeof entry.hint === "string" && entry.hint.length > 0
            ? entry.hint
            : typeof entry.fields?.hint === "string" && entry.fields.hint.length > 0
              ? entry.fields.hint
              : undefined
    const { facts, payload } = prettyFacts(entry, color, topHint)
    const sym = color ? logSymbols(supportsTerminalUnicode()) : undefined
    const head = prettyHeader(entry, color, sym)
    const lines: string[] = [facts.length ? `${head} ${facts.join(" ")}` : head]
    if (topHint !== undefined && topHint !== entry.error?.hint) {
        const safeHint = sanitizeSingleLine(topHint)
        lines.push(color ? `    ${ansi.boldCyan}${sym!.hint} Hint:${ansi.reset} ${safeHint}` : `    Hint: ${safeHint}`)
    }
    if (payload !== undefined) {
        const safePayload = sanitizeSingleLine(payload)
        lines.push(
            color ? `    ${ansi.dim}${sym!.rail} Payload:${ansi.reset} ${safePayload}` : `    Payload: ${safePayload}`,
        )
    }
    if (entry.error) {
        lines.push(errorText(entry.error, "    ", true, "", color, secrets))
        for (const other of entry.otherErrors ?? [])
            lines.push(errorText(other, "    ", true, "Also failed: ", color, secrets))
    }
    return lines.join("\n")
}

function jsonLine(entry: LogRecord): string {
    return JSON.stringify(entry, (_, value) => (typeof value === "bigint" ? value.toString() : value))
}

export function isThenable(value: unknown): value is PromiseLike<unknown> {
    return (
        (typeof value === "object" || typeof value === "function") &&
        value !== null &&
        typeof (value as { then?: unknown }).then === "function"
    )
}

type Settings = {
    readonly thresholds: Readonly<Record<LogCategory, number>>
    readonly sinks: readonly LogSink[] | undefined
    readonly format: "pretty" | "json" | undefined
    /** FLUXERLY_LOG_FORMAT read at creation, used by the built-in console output when format is not set */
    readonly environmentFormat: "pretty" | "json" | undefined
    /** FLUXERLY_LOG_COLOR read at creation: `true` forces color, `false` disables it, `undefined` follows the terminal */
    readonly environmentColor: boolean | undefined
    readonly dedupeMs: number | undefined
    readonly unsafe: ReadonlySet<LogCategory> | undefined
    readonly debugCategories: ReadonlySet<LogCategory>
    readonly unknownDebug: readonly string[]
    /** Logging environment variables whose values were not recognized and are ignored */
    readonly unknownEnvironment: readonly { readonly variable: string; readonly accepted: string }[]
}

type Dedupe = { shownAt: number; suppressed: number; last: LogInput | undefined }

/** One client's logging configuration, counters and output. Emission is synchronous and never fails its caller */
export class ClientLogger {
    readonly #settings: Settings
    /** Category thresholds, replaced by configure while the client runs */
    #thresholds: Readonly<Record<LogCategory, number>>
    /** Categories lowered to Debug: The debug setting and FLUXERLY_DEBUG at creation, until configure replaces them */
    #debugCategories: ReadonlySet<LogCategory>
    #secrets: string[] = []
    readonly #counters: Counters = {
        handlerFailures: 0,
        hookFailures: 0,
        reportsDropped: 0,
        eventsDropped: { overflow: 0, malformed: 0, collector: 0, closed: 0 },
        eventsDroppedByEvent: {},
        cacheChangesDropped: 0,
        protocolFailures: 0,
        unknownDispatches: 0,
        unknownOpcodes: 0,
        restRetries: 0,
        rateLimitWaits: 0,
        restBusy: 0,
        reconnects: 0,
        resumes: 0,
        sinkFailures: 0,
        cleanupFailures: 0,
        commandRejections: 0,
        unmatchedCommands: 0,
    }
    readonly #dedupe = new Map<string, Dedupe>()
    /** Error values already shown in an Error or Fatal record, so the bot runner does not print a final failure twice */
    readonly #loggedErrors = new WeakSet<object>()
    #sinkFailureReported = false
    #bannerShown = false
    #unsafeBannerShown = false
    /** Native context used when a record is emitted outside a fiber, normally the client's creation context */
    context: Context.Context<never> | undefined
    /** Receives every Error and Fatal record before level thresholds and deduplication. The test kit sets it, so its
     * failure checks see unhandled failures however quiet the test client's logging is
     */
    errorTap: ((record: LogRecord) => void) | undefined
    /** The Clock that default-API work runs with, set only when the default test client attaches its manual clock, so
     * waits that read the caller's Clock, such as waitFor, follow the same time as the client's own timers
     */
    clock: Clock.Clock | undefined

    constructor(
        settings: Settings,
        readonly native: boolean,
    ) {
        this.#settings = settings
        this.#thresholds = settings.thresholds
        this.#debugCategories = settings.debugCategories
    }

    /**
     * Replace the level and category thresholds from caller settings. A debug setting replaces the Debug categories,
     * including those from FLUXERLY_DEBUG, and an omitted one keeps the current categories. Invalid settings return
     * ConfigurationError and change nothing. Caller reads are marked, so the caller must run this under a defect boundary
     */
    configure(value: unknown): ConfigurationError | undefined {
        const settings = readCaller(() => {
            if (!record(value)) return new ConfigurationError("logging", "Logging level settings must be an object")
            const keys = ["level", "categories", "debug"]
            const unsupported = Object.keys(value).find((key) => !keys.includes(key))
            if (unsupported !== undefined)
                return new ConfigurationError(
                    "logging",
                    `Unsupported logging level setting ${JSON.stringify(unsupported)}`,
                    {
                        hint: `${unsupportedKeyHint(unsupported, keys, "settings")}. Other logging settings are fixed at creation`,
                    },
                )
            const thresholds = levelThresholds(value)
            if (thresholds instanceof ConfigurationError) return thresholds
            const debug = value.debug
            const debugCategories = debug === undefined ? undefined : debugSetting(debug)
            if (debugCategories instanceof ConfigurationError) return debugCategories
            return { thresholds, debugCategories }
        })
        if (settings instanceof ConfigurationError) return settings
        const { thresholds, debugCategories } = settings
        if (debugCategories !== undefined) this.#debugCategories = new Set(debugCategories)
        for (const category of this.#debugCategories) thresholds[category] = Math.min(thresholds[category], rank.debug)
        this.#thresholds = Object.freeze(thresholds)
        return undefined
    }

    /** Mask this credential in every later record */
    addSecret(secret: string) {
        if (secret.length >= 6 && !this.#secrets.includes(secret)) this.#secrets.push(secret)
    }

    get secrets(): readonly string[] {
        return this.#secrets
    }

    enabled(level: LogLevel, category: LogCategory): boolean {
        return rank[level] >= this.#thresholds[category]
    }

    unsafePayloads(category: LogCategory): boolean {
        return this.#settings.unsafe?.has(category) === true
    }

    count(name: CounterName, amount = 1) {
        this.#counters[name] += amount
        try {
            if (name === "reconnects") metrics.reconnect(this.context)
        } catch (error) {
            this.#sinkFailure(error)
        }
    }

    countDrop(reason: DropReason, amount = 1, event?: EventName) {
        this.#counters.eventsDropped[reason] += amount
        if (event !== undefined)
            this.#counters.eventsDroppedByEvent[event] = (this.#counters.eventsDroppedByEvent[event] ?? 0) + amount
        try {
            metrics.dropped(reason, amount, event, this.context)
        } catch (error) {
            this.#sinkFailure(error)
        }
    }

    counters(): ClientCounters {
        return Object.freeze({
            ...this.#counters,
            eventsDropped: Object.freeze({ ...this.#counters.eventsDropped }),
            eventsDroppedByEvent: Object.freeze({ ...this.#counters.eventsDroppedByEvent }),
        })
    }

    /** Record an intentionally discarded item: Count it, then log at Debug for expected drops or Warn for anomalies */
    drop(
        counter:
            | CounterName
            | { readonly event: DropReason; readonly amount?: number; readonly eventName?: EventName | undefined }
            | undefined,
        input: LogInput & { readonly level: "debug" | "warn" | "error" },
        context?: Context.Context<never>,
    ) {
        if (typeof counter === "string") this.count(counter)
        else if (counter) this.countDrop(counter.event, counter.amount, counter.eventName)
        this.log(input, context)
    }

    /** Emit the startup banners once per client, including the unsafe payload warning and unknown debug categories */
    banners(context?: Context.Context<never>) {
        if (this.#bannerShown) return
        this.#bannerShown = true
        this.#unsafeBanner(context)
        if (this.#settings.unknownDebug.length)
            this.log(
                {
                    level: "warn",
                    category: "sdk",
                    code: "sdk.unknownDebugCategory",
                    message: `FLUXERLY_DEBUG names unknown categories, which are ignored: ${this.#settings.unknownDebug.join(", ")}. Known categories are ${logCategories.join(", ")}`,
                    fields: { known: logCategories.join(",") },
                },
                context,
            )
        for (const { variable, accepted } of this.#settings.unknownEnvironment)
            this.log(
                {
                    level: "warn",
                    category: "sdk",
                    code: "sdk.unknownEnvironmentValue",
                    message: `${variable} has an unrecognized value and is ignored. Accepted values are ${accepted}`,
                    fields: { variable, accepted },
                },
                context,
            )
    }

    /** Whether any unsafe payload category can print, so the unsafe banner is due */
    #unsafeVisible(): boolean {
        const unsafe = this.#settings.unsafe
        if (!unsafe) return false
        for (const category of unsafe) if (this.#thresholds[category] < rank.silent) return true
        return false
    }

    /** Warn once that payload printing is on, at startup or before the first payload record, whichever comes first.
     * It bypasses level thresholds so a Warn-or-higher level cannot hide it, while silent payload categories print nothing
     */
    #unsafeBanner(context: Context.Context<never> | undefined) {
        if (this.#unsafeBannerShown || !this.#unsafeVisible()) return
        this.#unsafeBannerShown = true
        this.#emit(
            {
                level: "warn",
                category: "sdk",
                code: "sdk.unsafePayloads",
                message:
                    "Unsafe payload logging is enabled. Trace records include gateway and REST payloads, which can contain private message content. Bot tokens and recognized credentials stay masked",
                fields: { categories: [...this.#settings.unsafe!].join(",") },
            },
            context,
        )
    }

    /** Print a masked payload body at Trace when unsafe payload logging covers this category.
     * A silent category prints nothing. Otherwise the unsafe banner precedes the first payload record
     */
    payload(
        category: LogCategory,
        code: LogCode,
        message: string,
        value: unknown,
        extra?: Partial<LogInput>,
        context?: Context.Context<never>,
    ) {
        if (!this.unsafePayloads(category) || this.#thresholds[category] >= rank.silent) return
        this.#unsafeBanner(context)
        this.#emit(
            {
                ...extra,
                level: "trace",
                category,
                code,
                message,
                fields: { ...extra?.fields, payload: maskPayload(value, this.#secrets, undefined, extra?.route) },
            },
            context,
        )
    }

    /** Emit a record synchronously when its category threshold allows it. Output failures never reach the caller */
    log(input: LogInput, context?: Context.Context<never>) {
        if (this.errorTap !== undefined && rank[input.level] >= rank.error)
            try {
                this.errorTap(this.#record(input))
            } catch (error) {
                this.#sinkFailure(error)
            }
        if (!this.enabled(input.level, input.category)) return
        if (rank[input.level] >= rank.error && typeof input.error === "object" && input.error !== null)
            this.#loggedErrors.add(input.error)
        if (rank[input.level] >= rank.warn && this.#settings.dedupeMs !== undefined) {
            // The shard, subscription, route and command keep the same fault on different targets apart. The message is
            // compared as printed, so messages that differ only in a hidden credential are repeats
            const key = `${input.level}|${input.code}|${input.shardId ?? ""}|${input.subscriptionId ?? ""}|${input.route ?? ""}|${input.command ?? ""}|${maskText(input.message, this.#secrets)}|${this.#errorKey(input.error, input.cause)}`
            const now = Date.now()
            const entry = this.#dedupe.get(key)
            if (entry && now - entry.shownAt < this.#settings.dedupeMs) {
                entry.suppressed++
                entry.last = input
                return
            }
            const suppressed = entry?.suppressed ?? 0
            this.#dedupe.delete(key)
            this.#dedupe.set(key, { shownAt: now, suppressed: 0, last: undefined })
            if (this.#dedupe.size > dedupeCapacity) {
                const [evicted, oldest] = this.#dedupe.entries().next().value!
                this.#dedupe.delete(evicted)
                // Eviction ends that key's window early, so announce what it suppressed instead of losing the count,
                // unless configure has since silenced that level
                if (oldest.suppressed > 0 && oldest.last && this.enabled(oldest.last.level, oldest.last.category))
                    this.#emit(this.#repeated(oldest.last, oldest.suppressed), context)
            }
            if (suppressed > 0) input = this.#repeated(input, suppressed)
        }
        this.#emit(input, context)
    }

    /** Whether this error value already appeared in an Error or Fatal record of this logger */
    loggedError(error: unknown): boolean {
        return typeof error === "object" && error !== null && this.#loggedErrors.has(error)
    }

    /** Emit through the current fiber's context, so native records keep the caller's logger, annotations and spans */
    logEffect(input: LogInput): Effect.Effect<void> {
        return Effect.withFiber((fiber) => {
            this.log(input, fiber.context)
            return Effect.void
        })
    }

    /** Report suppressed duplicates that no later record announced and the current thresholds allow, normally during shutdown */
    flush(context?: Context.Context<never>) {
        for (const [key, entry] of this.#dedupe) {
            if (entry.suppressed > 0 && entry.last && this.enabled(entry.last.level, entry.last.category))
                this.#emit(this.#repeated(entry.last, entry.suppressed), context)
            this.#dedupe.delete(key)
        }
    }

    #repeated(input: LogInput, suppressed: number): LogInput {
        return {
            ...input,
            message: `${input.message} (repeated ${suppressed}× since last shown)`,
            fields: { ...input.fields, repeated: suppressed },
        }
    }

    /** The error part of a dedupe key: Name, code and message of each error in the cause chain and of each member of an
     * AggregateError, so the same outer error with a different cause or member is a new record rather than a repeat
     */
    #errorKey(error: unknown, cause?: Cause.Cause<unknown>) {
        if (error === undefined) return ""
        const parts: string[] = []
        const add = (info: ErrorInfo | undefined) => {
            for (; info; info = info.cause) {
                parts.push(`${info.name}|${info.code ?? ""}|${info.message}`)
                // Two aggregates with different members are different failures
                for (const member of info.errors ?? []) add(member)
            }
        }
        add(errorInfo(error, "sdk", this.#secrets))
        // The same failure with a different cleanup failure is a different record
        for (const other of otherFailures(cause, error)) add(errorInfo(other, "sdk", this.#secrets))
        return parts.join("|")
    }

    #record(input: LogInput): LogRecord {
        const fields: Record<string, string | number | boolean | null> = {}
        for (const [key, value] of Object.entries(input.fields ?? {}))
            if (value !== undefined) fields[key] = typeof value === "string" ? maskText(value, this.#secrets) : value
        const entry: Record<string, unknown> = {
            time: new Date().toISOString(),
            level: input.level,
            category: input.category,
            code: input.code,
            message: maskText(input.message, this.#secrets),
        }
        let info: ErrorInfo | undefined
        if (input.error !== undefined) {
            info = errorInfo(input.error, input.origin ?? "sdk", this.#secrets)
        }
        const catalogueEntry = actionableHintCodes.has(input.code)
            ? (logCodes as Readonly<Record<string, { readonly action?: string }>>)[input.code]
            : undefined
        const hint =
            input.hint !== undefined
                ? maskText(input.hint, this.#secrets)
                : typeof fields.hint === "string"
                  ? fields.hint
                  : rank[input.level] >= rank.warn && info?.hint === undefined
                    ? catalogueEntry?.action
                    : undefined
        if (hint !== undefined) entry.hint = hint
        for (const key of recordKeys) {
            const value = input[key]
            if (value !== undefined) entry[key] = typeof value === "string" ? maskText(value, this.#secrets) : value
        }
        if (Object.keys(fields).length) entry.fields = Object.freeze(fields)
        if (info !== undefined) {
            entry.error = info
            const others = otherFailures(input.cause, input.error)
            if (others.length)
                entry.otherErrors = Object.freeze(
                    others.map((other) => errorInfo(other, input.origin ?? "sdk", this.#secrets)),
                )
        }
        return Object.freeze(entry) as unknown as LogRecord
    }

    #emit(input: LogInput, context: Context.Context<never> | undefined) {
        let entry: LogRecord
        try {
            entry = this.#record(input)
        } catch (error) {
            this.#sinkFailure(error)
            return
        }
        const sinks = this.#settings.sinks
        if (sinks) {
            for (const sink of sinks) {
                try {
                    const result: unknown = sink(entry)
                    if (isThenable(result))
                        void Promise.resolve(result).then(undefined, (error: unknown) => this.#sinkFailure(error))
                } catch (error) {
                    this.#sinkFailure(error)
                }
            }
            return
        }
        if (this.native && this.#settings.format === undefined) {
            this.#effectLog(entry, input, context ?? this.context)
            return
        }
        this.#console(entry)
    }

    /** The built-in console format and color for one output stream, which decides from its own terminal state.
     * Warn and higher records go to standard error
     */
    consoleFormat(stream: "stdout" | "stderr"): { readonly format: "pretty" | "json"; readonly color: boolean } {
        const target = stream === "stderr" ? process.stderr : process.stdout
        const terminal = Boolean(target.isTTY)
        const format = this.#settings.format ?? this.#settings.environmentFormat ?? (terminal ? "pretty" : "json")
        const color =
            format === "pretty" && supportsTerminalColor(target, { override: this.#settings.environmentColor })
        return { format, color }
    }

    #console(entry: LogRecord) {
        try {
            const error = rank[entry.level] >= rank.warn
            const { format, color } = this.consoleFormat(error ? "stderr" : "stdout")
            const text = format === "pretty" ? prettyLine(entry, color, this.#secrets) : jsonLine(entry)
            if (error) console.error(text)
            else console.log(text)
        } catch (error) {
            this.#sinkFailure(error)
        }
    }

    #effectLog(entry: LogRecord, input: LogInput, context: Context.Context<never> | undefined) {
        const annotations: Record<string, unknown> = {
            "fluxerly.category": entry.category,
            "fluxerly.code": entry.code,
        }
        if (entry.hint !== undefined) annotations["fluxerly.hint"] = entry.hint
        for (const key of recordKeys) if (entry[key] !== undefined) annotations[`fluxerly.${key}`] = entry[key]
        for (const [key, value] of Object.entries(entry.fields ?? {})) annotations[`fluxerly.${key}`] = value
        // The code, hint, retry safety, validation issues and safe details of each error in the cause chain, which the
        // default console output prints too. The first cause uses fluxerly.error.cause., its cause fluxerly.error.cause.cause., and so on
        const annotateError = (root: ErrorInfo | undefined, basePrefix: string) => {
            for (let error = root, prefix = basePrefix; error; error = error.cause, prefix += "cause.") {
                if (error.code !== undefined) annotations[`${prefix}code`] = error.code
                if (error.hint !== undefined) annotations[`${prefix}hint`] = error.hint
                if (error.retryable !== undefined) annotations[`${prefix}retryable`] = error.retryable
                if (error.retryAfterMs !== undefined) annotations[`${prefix}retryAfterMs`] = error.retryAfterMs
                if (error.validationErrors && error.validationErrors.length > 0)
                    annotations[`${prefix}validationErrors`] = JSON.stringify(error.validationErrors)
                for (const [key, value] of Object.entries(error.details ?? {}))
                    annotations[`${prefix}${key}`] =
                        typeof value === "string" || (typeof value === "object" && value !== null)
                            ? detailText(value, this.#secrets)
                            : value
            }
        }
        annotateError(entry.error, "fluxerly.error.")
        if (entry.otherErrors && entry.otherErrors.length > 0) {
            for (let index = 0; index < entry.otherErrors.length; index++) {
                const other = entry.otherErrors[index]!
                const prefix = `fluxerly.otherErrors.${index}.`
                annotations[`${prefix}name`] = other.name
                annotations[`${prefix}message`] = other.message
                annotateError(other, prefix)
            }
        }
        let cause: Cause.Cause<unknown> | undefined
        try {
            const original =
                input.cause ??
                (input.error === undefined
                    ? undefined
                    : input.error instanceof FluxerlyError
                      ? Cause.fail(input.error)
                      : Cause.die(input.error))
            // Effect's cause printer shows raw messages, stacks and own properties, so it only receives masked copies
            cause = original && maskedCause(original, this.#secrets)
        } catch (error) {
            this.#sinkFailure(error)
            cause = undefined
        }
        let log: Effect.Effect<void> = Effect.logWithLevel(effectLevels[entry.level])(
            entry.message,
            ...(cause ? [cause] : []),
        ).pipe(Effect.annotateLogs(annotations))
        // SDK settings already chose this Debug or Trace record, so the Effect minimum level must not hide it again
        if (rank[entry.level] < rank.info)
            log = log.pipe(Effect.provideService(References.MinimumLogLevel, effectLevels[entry.level]))
        try {
            const exit = context ? Effect.runSyncExitWith(context)(log) : Effect.runSyncExit(log)
            if (exit._tag === "Failure") this.#sinkFailure(Cause.squash(exit.cause))
        } catch (error) {
            this.#sinkFailure(error)
        }
    }

    /** Count a log output or failure-reporting fault and describe the first one on standard error. Never throws */
    outputFailure(error: unknown) {
        this.#sinkFailure(error)
    }

    #sinkFailure(error: unknown) {
        this.#counters.sinkFailures++
        if (this.#sinkFailureReported) return
        this.#sinkFailureReported = true
        try {
            process.stderr.write(
                `Fluxerly diagnostics output failed: ${maskedSummary(error, this.#secrets)}. Check logging.sink, the observe callback, metrics exporters and the configured Effect logger. Later failures are counted in diagnostics().counters.sinkFailures\n`,
            )
        } catch {
            // allow-silent: Standard error itself failed, and the counter still records the sink failure
        }
    }

    /** A default-runtime Effect logger that turns stray Effect log calls from SDK internals into SDK records */
    bridge(): Logger.Logger<unknown, void> {
        return Logger.make((options) => {
            const level = (Object.entries(effectLevels).find(([, value]) => value === options.logLevel)?.[0] ??
                "info") as LogLevel
            const message = Array.isArray(options.message)
                ? options.message.map((part) => maskValue(part, this.#secrets)).join(" ")
                : maskValue(options.message, this.#secrets)
            const failure =
                Cause.isCause(options.cause) && options.cause.reasons.length ? Cause.squash(options.cause) : undefined
            this.log({
                level,
                category: "sdk",
                code: "sdk.effectLog",
                message,
                ...(failure === undefined ? {} : { error: failure }),
            })
        })
    }

    /** Run default-API work with SDK-internal Effect logs routed into this client's records, and with the attached
     * Clock when there is one
     */
    provide<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {
        if (this.native) return effect
        const provided = effect.pipe(
            Effect.provideService(Logger.CurrentLoggers, new Set([this.bridge()])),
            Effect.provideService(References.MinimumLogLevel, "Trace"),
        )
        return this.clock === undefined ? provided : provided.pipe(Effect.provideService(Clock.Clock, this.clock))
    }
}

/** A validated threshold. The option names the setting as typed, such as logging.level or logging.categories.rest */
function threshold(value: unknown, field: "level" | "categories", option: string): LogThreshold | ConfigurationError {
    if (typeof value === "string" && (value === "silent" || (levels as readonly string[]).includes(value)))
        return value as LogThreshold
    return new ConfigurationError(
        field,
        `The option ${JSON.stringify(option)} must be trace, debug, info, warn, error, fatal or silent`,
    )
}

/** FLUXERLY_LOG_COLOR values, compared after trimming and lowercasing */
const colorValues = { 1: true, true: true, yes: true, on: true, 0: false, false: false, no: false, off: false } as const

/** Parse FLUXERLY_DEBUG: 1, true or * enable every category, otherwise a comma-separated category list */
function debugEnvironment(value: string | undefined): { categories: LogCategory[]; unknown: string[] } {
    if (value === undefined || value.trim() === "" || value.trim() === "0" || value.trim().toLowerCase() === "false")
        return { categories: [], unknown: [] }
    const parts = value
        .split(",")
        .map((part) => part.trim())
        .filter(Boolean)
    if (parts.some((part) => part === "1" || part === "*" || part.toLowerCase() === "true"))
        return { categories: [...logCategories], unknown: [] }
    return {
        categories: parts.filter((part): part is LogCategory => (logCategories as readonly string[]).includes(part)),
        unknown: parts.filter((part) => !(logCategories as readonly string[]).includes(part)),
    }
}

/** Caller logging settings after validation, before the logger combines them with the environment */
interface LoggingInput {
    readonly thresholds: Record<LogCategory, number>
    readonly debugCategories: readonly LogCategory[]
    readonly format: "pretty" | "json" | undefined
    readonly sinks: LogSink[] | undefined
    readonly dedupeMs: number | undefined
    readonly unsafe: Set<LogCategory> | undefined
}

/** Validate the level and categories settings into category thresholds, reading each setting once */
function levelThresholds(settings: Record<string, unknown>): Record<LogCategory, number> | ConfigurationError {
    const level = settings.level
    const base = level === undefined ? "info" : threshold(level, "level", "logging.level")
    if (base instanceof ConfigurationError) return base
    const thresholds = Object.fromEntries(logCategories.map((category) => [category, rank[base]])) as Record<
        LogCategory,
        number
    >
    const categories = settings.categories
    if (categories !== undefined) {
        if (!record(categories))
            return new ConfigurationError(
                "categories",
                'The option "logging.categories" must be an object of category levels',
            )
        for (const [category, level] of Object.entries(categories)) {
            if (!(logCategories as readonly string[]).includes(category))
                return new ConfigurationError("categories", `Unknown log category ${JSON.stringify(category)}`, {
                    hint: unsupportedKeyHint(category, logCategories, "categories"),
                })
            if (level === undefined) continue
            const parsed = threshold(level, "categories", `logging.categories.${category}`)
            if (parsed instanceof ConfigurationError) return parsed
            thresholds[category as LogCategory] = rank[parsed]
        }
    }
    return thresholds
}

/** Validate a debug setting into its categories: True for every category, false for none or a list of categories */
function debugSetting(debug: unknown): LogCategory[] | ConfigurationError {
    if (debug === true) return [...logCategories]
    if (debug === false) return []
    if (!Array.isArray(debug))
        return new ConfigurationError(
            "debug",
            'The option "logging.debug" must be true, false or an array of categories',
        )
    const categories: LogCategory[] = []
    for (const category of debug) {
        if (!(logCategories as readonly unknown[]).includes(category))
            return new ConfigurationError(
                "debug",
                typeof category === "string"
                    ? `Unknown log category ${JSON.stringify(category)} in logging.debug`
                    : 'The option "logging.debug" must list log category names',
                {
                    hint:
                        typeof category === "string"
                            ? unsupportedKeyHint(category, logCategories, "categories")
                            : `Known categories are ${logCategories.join(", ")}`,
                },
            )
        categories.push(category as LogCategory)
    }
    return categories
}

function sinkSetting(sink: unknown): LogSink[] | undefined | ConfigurationError {
    if (sink === undefined) return undefined
    const list = Array.isArray(sink) ? [...(sink as unknown[])] : [sink]
    if (list.length === 0 || list.some((entry) => typeof entry !== "function"))
        return new ConfigurationError(
            "sink",
            'The option "logging.sink" must be a function or a non-empty array of functions',
        )
    return list as LogSink[]
}

function dedupeSetting(dedupe: unknown): number | undefined | ConfigurationError {
    if (dedupe === false) return undefined
    if (dedupe === undefined) return 60_000
    if (!record(dedupe))
        return new ConfigurationError("dedupe", 'The option "logging.dedupe" must be false or an object with windowMs')
    const unsupported = Object.keys(dedupe).find((key) => key !== "windowMs")
    if (unsupported !== undefined)
        return new ConfigurationError("dedupe", `Unsupported logging.dedupe setting ${JSON.stringify(unsupported)}`, {
            hint: unsupportedKeyHint(unsupported, ["windowMs"], "settings"),
        })
    const windowMs = dedupe.windowMs
    if (windowMs !== undefined && (typeof windowMs !== "number" || !Number.isSafeInteger(windowMs) || windowMs < 0))
        return new ConfigurationError(
            "dedupe",
            'The option "logging.dedupe.windowMs" must be a nonnegative safe integer of milliseconds',
        )
    return windowMs === 0 ? undefined : (windowMs ?? 60_000)
}

function unsafeSetting(option: unknown): Set<LogCategory> | undefined | ConfigurationError {
    if (option === undefined) return undefined
    if (!record(option))
        return new ConfigurationError(
            "unsafe",
            'The option "logging.unsafe" must be { payloads: true }, with optional categories',
        )
    const unsupported = Object.keys(option).find((key) => key !== "payloads" && key !== "categories")
    if (unsupported !== undefined)
        return new ConfigurationError("unsafe", `Unsupported logging.unsafe setting ${JSON.stringify(unsupported)}`, {
            hint: unsupportedKeyHint(unsupported, ["payloads", "categories"], "settings"),
        })
    if (option.payloads !== true)
        return new ConfigurationError(
            "unsafe",
            'The option "logging.unsafe" must be { payloads: true }, with optional categories',
        )
    const unsafeCategories = option.categories
    if (unsafeCategories === undefined) return new Set(logCategories)
    if (!Array.isArray(unsafeCategories))
        return new ConfigurationError(
            "unsafe",
            'The option "logging.unsafe.categories" must be an array of log category names',
            { hint: `Known categories are ${logCategories.join(", ")}` },
        )
    const badCategory = unsafeCategories.find((category) => !(logCategories as readonly unknown[]).includes(category))
    if (badCategory !== undefined)
        return new ConfigurationError(
            "unsafe",
            typeof badCategory === "string"
                ? `Unknown log category ${JSON.stringify(badCategory)} in logging.unsafe.categories`
                : 'The option "logging.unsafe.categories" must be an array of log category names',
            {
                hint:
                    typeof badCategory === "string"
                        ? unsupportedKeyHint(badCategory, logCategories, "categories")
                        : `Known categories are ${logCategories.join(", ")}`,
            },
        )
    return new Set(unsafeCategories as LogCategory[])
}

/** Validate caller logging settings, reading each setting once so the validated value is the one used */
function loggingInput(value: unknown): LoggingInput | ConfigurationError {
    if (value !== undefined && !record(value))
        return new ConfigurationError("logging", "Logging settings must be an object")
    const settings = (value ?? {}) as Record<string, unknown>
    const keys = ["level", "categories", "debug", "format", "sink", "dedupe", "unsafe"]
    const unsupported = Object.keys(settings).filter((key) => !keys.includes(key))
    if (unsupported.length)
        return new ConfigurationError("logging", `Unsupported logging setting ${JSON.stringify(unsupported[0])}`, {
            hint: unsupported.some((key) => ["development", "measurements", "minimumLevel", "logger"].includes(key))
                ? "The settings development, measurements, minimumLevel and logger no longer exist. Use level, categories, debug, format and sink instead"
                : unsupportedKeyHint(unsupported[0]!, keys, "settings"),
        })
    const thresholds = levelThresholds(settings)
    if (thresholds instanceof ConfigurationError) return thresholds
    const debug = settings.debug
    const debugCategories = debug === undefined ? [] : debugSetting(debug)
    if (debugCategories instanceof ConfigurationError) return debugCategories
    const format = settings.format
    if (format !== undefined && format !== "pretty" && format !== "json")
        return new ConfigurationError("format", 'The option "logging.format" must be "pretty" or "json"')
    const sinks = sinkSetting(settings.sink)
    if (sinks instanceof ConfigurationError) return sinks
    const dedupeMs = dedupeSetting(settings.dedupe)
    if (dedupeMs instanceof ConfigurationError) return dedupeMs
    const unsafe = unsafeSetting(settings.unsafe)
    if (unsafe instanceof ConfigurationError) return unsafe
    return { thresholds, debugCategories, format, sinks, dedupeMs, unsafe }
}

/** Run client.logging.configure: Replace the logger's thresholds and, when given, its Debug categories, failing with ConfigurationError for invalid settings */
export const configureLogging = (logger: ClientLogger, settings: unknown): Effect.Effect<void, ConfigurationError> =>
    suspendMarked(() => {
        const failure = logger.configure(settings)
        return failure === undefined ? Effect.void : Effect.fail(failure)
    })

/**
 * Validate and copy logging settings, then create the logger. Both entry points accept the same keys.
 * Only reading the caller settings is marked as application input, so the caller must run this under a defect boundary
 */
export function loggingConfiguration(value: unknown, native: boolean): ClientLogger | ConfigurationError {
    const input = readCaller(() => loggingInput(value))
    if (input instanceof ConfigurationError) return input
    const { thresholds, format, sinks, dedupeMs, unsafe } = input
    const debugCategories = new Set<LogCategory>(input.debugCategories)
    const environment = debugEnvironment(process.env.FLUXERLY_DEBUG)
    const formatVariable = process.env.FLUXERLY_LOG_FORMAT?.trim().toLowerCase()
    const colorVariable = process.env.FLUXERLY_LOG_COLOR?.trim().toLowerCase()
    const environmentFormat = formatVariable === "pretty" || formatVariable === "json" ? formatVariable : undefined
    const environmentColor =
        colorVariable !== undefined && Object.hasOwn(colorValues, colorVariable)
            ? colorValues[colorVariable as keyof typeof colorValues]
            : undefined
    // An empty variable counts as unset, and any other value that is not recognized gets one startup Warn
    const unknownEnvironment = [
        ...(formatVariable && environmentFormat === undefined
            ? [{ variable: "FLUXERLY_LOG_FORMAT", accepted: "pretty, json" }]
            : []),
        ...(colorVariable && environmentColor === undefined
            ? [{ variable: "FLUXERLY_LOG_COLOR", accepted: Object.keys(colorValues).join(", ") }]
            : []),
    ]
    for (const category of environment.categories) debugCategories.add(category)
    for (const category of debugCategories) thresholds[category] = Math.min(thresholds[category], rank.debug)
    return new ClientLogger(
        {
            thresholds: Object.freeze(thresholds),
            sinks: sinks && Object.freeze(sinks),
            format,
            environmentFormat,
            environmentColor,
            dedupeMs,
            unsafe,
            debugCategories,
            unknownDebug: environment.unknown,
            unknownEnvironment,
        },
        native,
    )
}