import { fitShortMonitorPayload, } from '../canonical-monitor.js'; import { OwnerLockError } from './owner-lock-error.js'; export interface ClawclawOwnerNotificationHost { readonly mode: 'short'; emit(payload: Record): Promise; markMailboxReady(): void; } function errorMessage(error: unknown, sensitiveValues: readonly string[]): string { let message = error instanceof Error ? error.message : String(error ?? 'Unknown startup error.'); for (const value of sensitiveValues) { if (value) message = message.split(value).join('[redacted]'); } return message.slice(0, 1_000); } export function formatClawclawBootstrapFailure( error: unknown, sensitiveValues: readonly string[] = [], ): Record { if (error instanceof OwnerLockError) { const event = { type: 'error', code: error.code, phase: 'bootstrap', message: errorMessage(error.reason, sensitiveValues), blocker: error.blocker, ...(error.osError ? { os_error: error.osError } : {}), }; const payload = { schema: 'ccl.monitor.v1', mode: 'short', events: [event] }; // Generic compaction drops error fields. Preserve PID/verification even when // an OS failure is verbose, so the Agent never loses the recovery target. while (JSON.stringify(payload).length > 500 && event.message.length > 0) { event.message = event.message.slice(0, Math.max(0, event.message.length - 16)); } return payload; } const payload = { schema: 'ccl.monitor.v1', mode: 'short', events: [{ type: 'error', code: 'CCL_BOOTSTRAP_FAILED', phase: 'bootstrap', message: errorMessage(error, sensitiveValues), }], }; return fitShortMonitorPayload(payload); } /** Routes Agent-facing output through Mailbox once the owner marks it ready. */ export class ClawclawHostNotificationRoute implements ClawclawOwnerNotificationHost { readonly mode = 'short' as const; private mailboxReady = false; constructor( private readonly sink: (payload: Record) => Promise, ) {} emit(payload: Record): Promise { return this.sink(payload); } markMailboxReady(): void { this.mailboxReady = true; } hasMailbox(): boolean { return this.mailboxReady; } async reportBootstrapFailure( error: unknown, sensitiveValues: readonly string[] = [], ): Promise { if (this.mailboxReady) return false; await this.emit(formatClawclawBootstrapFailure(error, sensitiveValues)); return true; } }