import { join } from 'path'; import type { AuthProfile } from '../../lib/auth.js'; import { defaultDiagnosticsConfig, readDiagnosticsConfig, type DiagnosticsConfig, type DiagnosticsLevel, } from '../../lib/diagnostics-config.js'; import { getProfileRuntimeStateDir, getRuntimeAccountId } from '../../lib/init-command.js'; import { ObservabilityRedactor } from './redaction.js'; import { BufferedObservabilityReporter } from './reporter.js'; import { TelemetryRecorder } from './recorder.js'; import { resolveDetailCapture } from './detail-capture.js'; import { JsonlObservabilitySink } from './sinks.js'; import type { RecordTelemetryInput } from './types.js'; export const CLAWCLAW_OBSERVABILITY_LEVEL = 'CLAWCLAW_OBSERVABILITY_LEVEL'; export const CLAWCLAW_OBSERVABILITY_MAX_FILE_MIB = 'CLAWCLAW_OBSERVABILITY_MAX_FILE_MIB'; export const CLAWCLAW_OBSERVABILITY_RETAINED_FILES = 'CLAWCLAW_OBSERVABILITY_RETAINED_FILES'; export type OwnerObservabilityLevel = DiagnosticsLevel; export interface OwnerObservabilityRetention { maxFileBytes: number; retainedFiles: number; } const DEFAULT_MAX_FILE_MIB = 10; const DEFAULT_RETAINED_FILES = 5; const MINIMUM_OPERATIONAL_RECORD = /^(?:runtime\.owner\.(?:started|stopped)|runtime\.scope\.switched|runtime\.mailbox\.monitor_batch_split)$/; const FULL_REDUNDANT_DEBUG_RECORDS = new Set([ 'runtime.input.accepted', 'runtime.channel.ready_advanced', 'behavior.decide.started', ]); /** * Full diagnostics keeps development evidence, not a second copy of the Runtime journals. * Exact per-epoch/plugin outcomes already live in runtime-epochs.sqlite3; the JSONL keeps * exceptional/slow samples and diagnostics that cannot be reconstructed from that journal. * runtime.view.ready is retained: intake/finalization and ingress-to-ready latency * are not represented by the journal's scheduler-only processing_duration_ms. */ function fullObservabilityInputEnabled(input: Readonly): boolean { const severity = input.severity ?? (input.kind === 'error' ? 'error' : 'info'); if (severity !== 'debug') return true; return !FULL_REDUNDANT_DEBUG_RECORDS.has(input.name); } function boundedInteger( value: string | undefined, fallback: number, minimum: number, maximum: number, ): number { if (value === undefined || value.trim() === '') return fallback; const parsed = Number(value); return Number.isInteger(parsed) && parsed >= minimum && parsed <= maximum ? parsed : fallback; } function configuredObservabilityLevel( config: Readonly, env: NodeJS.ProcessEnv, ): OwnerObservabilityLevel { const value = env[CLAWCLAW_OBSERVABILITY_LEVEL]?.trim().toLowerCase(); return value === 'errors' || value === 'telemetry' || value === 'full' ? value : config.level; } /** Upload consent is persisted now and raises local collection; no uploader exists yet. */ export function observabilityLevel( config: Readonly = defaultDiagnosticsConfig(), env: NodeJS.ProcessEnv = process.env, ): OwnerObservabilityLevel { const configured = configuredObservabilityLevel(config, env); if (configured === 'full') return 'full'; return config.allow_upload || configured === 'telemetry' ? 'telemetry' : 'errors'; } /** Resolve the effective owner level without letting a broken config stop gameplay. */ export function resolveOwnerObservabilityLevel( options: { env?: NodeJS.ProcessEnv; diagnosticsConfig?: Readonly; workspaceDir?: string; } = {}, ): OwnerObservabilityLevel { try { return observabilityLevel( options.diagnosticsConfig ?? readDiagnosticsConfig(options.workspaceDir), options.env ?? process.env, ); } catch { return 'errors'; } } export function observabilityRetention( env: NodeJS.ProcessEnv = process.env, ): OwnerObservabilityRetention { return { maxFileBytes: boundedInteger( env[CLAWCLAW_OBSERVABILITY_MAX_FILE_MIB], DEFAULT_MAX_FILE_MIB, 1, 1_024, ) * 1024 * 1024, retainedFiles: boundedInteger( env[CLAWCLAW_OBSERVABILITY_RETAINED_FILES], DEFAULT_RETAINED_FILES, 1, 20, ), }; } export function observabilityInputEnabled( level: OwnerObservabilityLevel, input: Readonly, ): boolean { if (level === 'full') return fullObservabilityInputEnabled(input); const severity = input.severity ?? (input.kind === 'error' ? 'error' : 'info'); if (level === 'telemetry') return severity !== 'debug'; return severity === 'error' || MINIMUM_OPERATIONAL_RECORD.test(input.name); } export function observabilityLogPath(runtimeStateDir: string): string { return join(runtimeStateDir, 'observability', 'owner-runtime.jsonl'); } /** * Safe default: local redacted JSONL only. No network reporter is installed by * this factory. `allow_upload` persists consent and raises local collection to * telemetry, but does not perform or schedule a network request. A future * uploader needs its own global field allowlist/projection and must not upload * the local JSONL directly. */ export function createOwnerTelemetryRecorder( profile: Pick, options: { env?: NodeJS.ProcessEnv; flushIntervalMs?: number; diagnosticsConfig?: Readonly; workspaceDir?: string; runtimeStateDir?: string; } = {}, ): TelemetryRecorder { try { const env = options.env ?? process.env; let configError: unknown; let config: Readonly; try { config = options.diagnosticsConfig ?? readDiagnosticsConfig(options.workspaceDir); } catch (error) { configError = error; config = defaultDiagnosticsConfig(); } const level = observabilityLevel(config, env); const capture = resolveDetailCapture(config, env); // A two-record batch must fit the configured file rotation budget. capture.max_record_bytes = Math.min(capture.max_record_bytes, Math.floor(observabilityRetention(env).maxFileBytes / 2)); const runtimeAccountId = getRuntimeAccountId(profile); const redactor = new ObservabilityRedactor({ hashSalt: runtimeAccountId }); const sink = new JsonlObservabilitySink( observabilityLogPath(options.runtimeStateDir ?? getProfileRuntimeStateDir(profile)), observabilityRetention(env), ); const reporter = new BufferedObservabilityReporter(sink, { flushIntervalMs: options.flushIntervalMs, }); const detailReporter = capture.actions || capture.behavior_io || capture.perception_io ? new BufferedObservabilityReporter(new JsonlObservabilitySink( join(options.runtimeStateDir ?? getProfileRuntimeStateDir(profile), 'observability', 'owner-detail.jsonl'), observabilityRetention(env), ), { maxQueueRecords: Math.max(2, Math.floor(8 * 1024 * 1024 / capture.max_record_bytes)), batchSize: 2, flushIntervalMs: 100 }) : undefined; const recorder = new TelemetryRecorder({ enabled: true, process: { role: 'owner', pid: process.pid }, reporter, redactor, sampler: (input) => observabilityInputEnabled(level, input), capture, detailReporter, }); if (configError) { recorder.error('observability.config.invalid', configError, { fallback_level: level, }, { component: 'observability.config' }); } return recorder; } catch { // Invalid or unwritable diagnostics configuration must not prevent a game. // Keep the recorder inert rather than creating an unbounded fallback sink. return new TelemetryRecorder({ enabled: false, process: { role: 'owner', pid: process.pid } }); } }