/**
 * AWOOOI API Client
 * ADR-005: 所有請求經過 BFF
 *
 * 專案鐵律: 禁止任何 Fallback IP，環境變數缺失即噴錯
 */

import { CURRENT_USER } from '@/lib/constants/user'

// 絕對純化: 環境變數缺失時直接拋出致命錯誤，嚴禁任何 Fallback
const getApiBaseUrl = (): string => {
  const url = process.env.NEXT_PUBLIC_API_URL
  if (!url) {
    const fatalMsg = '[AWOOOI FATAL] Missing NEXT_PUBLIC_API_URL configuration.'
    console.error(fatalMsg)
    if (typeof window !== 'undefined') {
      console.error('%c' + fatalMsg, 'color: #ef4444; font-weight: bold; font-size: 16px;')
    }
    throw new Error(fatalMsg)
  }
  return url.endsWith('/api/v1') ? url : `${url}/api/v1`
}

const API_BASE_URL = getApiBaseUrl()

export class ApiError extends Error {
  constructor(
    public status: number,
    public code: string,
    message: string
  ) {
    super(message)
    this.name = 'ApiError'
  }
}

async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const error = await response.json().catch(() => ({}))
    throw new ApiError(
      response.status,
      error.code || 'UNKNOWN_ERROR',
      error.message || response.statusText
    )
  }
  return response.json()
}

export const apiClient = {
  // Health
  async getHealth() {
    const res = await fetch(`${API_BASE_URL}/health`)
    return handleResponse<{
      status: 'healthy' | 'degraded' | 'unhealthy'
      version: string
      timestamp: string
      components: Record<string, {
        status: 'up' | 'down' | 'degraded'
        latency_ms?: number | null
        error?: string | null
      }>
      ollama_route_order?: string[]
    }>(res)
  },

  // Agent
  async getAgentStatus() {
    const res = await fetch(`${API_BASE_URL}/agent/status`)
    return handleResponse<{
      status: 'idle' | 'thinking' | 'executing' | 'waiting_approval'
      active_conversations: number
      current_task: string | null
      last_activity: string | null
    }>(res)
  },

  async chat(message: string, conversationId?: string) {
    const res = await fetch(`${API_BASE_URL}/agent/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message, conversation_id: conversationId }),
    })
    return handleResponse<{
      message: string
      conversation_id: string
      requires_approval: boolean
      approval_id?: string
    }>(res)
  },

  // Plugins
  async listPlugins(category?: string) {
    const params = category ? `?category=${category}` : ''
    const res = await fetch(`${API_BASE_URL}/plugins${params}`)
    return handleResponse<Array<{
      id: string
      name: string
      version: string
      category: string
      enabled: boolean
      description?: string
    }>>(res)
  },

  // Approvals
  async listApprovals(status?: string) {
    const params = status ? `?status=${status}` : ''
    const res = await fetch(`${API_BASE_URL}/approvals${params}`)
    return handleResponse<{
      items: Array<{
        id: string
        type: string
        status: string
        action: {
          plugin_id: string
          operation: string
          risk_level: string
        }
        requested_at: string
      }>
    }>(res)
  },

  async signApproval(approvalId: string, signer: string = CURRENT_USER.id, comment?: string, csrfToken?: string | null) {
    // Phase 22 P0: 加入 CSRF token + credentials (2026-03-31 Claude Code)
    const headers: Record<string, string> = { 'Content-Type': 'application/json' }
    if (csrfToken) headers['X-CSRF-Token'] = csrfToken
    const res = await fetch(`${API_BASE_URL}/approvals/${approvalId}/sign`, {
      method: 'POST',
      headers,
      credentials: 'include',
      body: JSON.stringify({
        signer_id: signer,
        signer_name: signer,
        comment: comment,
      }),
    })
    // 🔧 Fix: 回傳型別與後端實際結構對齊
    return handleResponse<{
      success: boolean
      message: string
      approval: ApprovalResponse
      execution_triggered: boolean
      // 向下相容舊欄位 (deprecated)
      approval_id?: string
      status?: string
      current_signatures?: number
      required_signatures?: number
    }>(res)
  },

  async rejectApproval(approvalId: string, reason?: string, csrfToken?: string | null) {
    // Phase 22 P0: 加入 CSRF token + credentials (2026-03-31 Claude Code)
    const headers: Record<string, string> = { 'Content-Type': 'application/json' }
    if (csrfToken) headers['X-CSRF-Token'] = csrfToken
    const res = await fetch(`${API_BASE_URL}/approvals/${approvalId}/reject`, {
      method: 'POST',
      headers,
      credentials: 'include',
      body: JSON.stringify({
        rejector_id: CURRENT_USER.id,
        rejector_name: CURRENT_USER.name,
        reason: reason || 'Rejected via WarRoom',
      }),
    })
    return handleResponse<{ id: string; status: string }>(res)
  },

  // =========================================================================
  // Phase 7: Incidents API (真實血脈)
  // =========================================================================

  async listIncidents() {
    const res = await fetch(`${API_BASE_URL}/incidents`)
    return handleResponse<IncidentListResponse>(res)
  },

  async getIncident(incidentId: string) {
    const res = await fetch(`${API_BASE_URL}/incidents/${incidentId}`)
    return handleResponse<IncidentResponse>(res)
  },

  async getIncidentTimeline(incidentId: string) {
    const res = await fetch(`${API_BASE_URL}/incidents/${incidentId}/timeline`)
    return handleResponse<IncidentTimelineResponse>(res)
  },

  async generateProposal(incidentId: string) {
    const res = await fetch(`${API_BASE_URL}/incidents/${incidentId}/proposal`, {
      method: 'POST',
    })
    return handleResponse<ProposalGenerateResponse>(res)
  },

  // =========================================================================
  // Phase 7: Pending Approvals API (真實血脈)
  // =========================================================================

  async getPendingApprovals() {
    const res = await fetch(`${API_BASE_URL}/approvals/pending`)
    return handleResponse<PendingApprovalsResponse>(res)
  },

  // =========================================================================
  // Phase 10: Sentry Errors API (#40 BFF)
  // =========================================================================

  async getErrorStats() {
    const res = await fetch(`${API_BASE_URL}/errors/stats`)
    return handleResponse<ErrorStatsResponse>(res)
  },

  async listErrors(params?: { status?: string; level?: string; limit?: number }) {
    const searchParams = new URLSearchParams()
    if (params?.status) searchParams.set('status', params.status)
    if (params?.level) searchParams.set('level', params.level)
    if (params?.limit) searchParams.set('limit', params.limit.toString())
    const query = searchParams.toString() ? `?${searchParams.toString()}` : ''
    const res = await fetch(`${API_BASE_URL}/errors/issues${query}`)
    return handleResponse<ErrorListResponse>(res)
  },

  async getErrorDetail(issueId: string) {
    const res = await fetch(`${API_BASE_URL}/errors/issues/${issueId}`)
    return handleResponse<ErrorDetailResponse>(res)
  },

  async getErrorTrends(period: '24h' | '7d' | '30d' = '24h') {
    const res = await fetch(`${API_BASE_URL}/errors/trends?period=${period}`)
    return handleResponse<ErrorTrendResponse>(res)
  },

  async analyzeError(issueId: string) {
    const res = await fetch(`${API_BASE_URL}/errors/issues/${issueId}/analyze`, {
      method: 'POST',
    })
    return handleResponse<ErrorAnalysisResponse>(res)
  },

  // =========================================================================
  // Phase 19: UX Audit / Session Replay (#126)
  // 2026-03-31 Claude Code - Frontend Replay UI Integration
  // =========================================================================

  async getUXAudit() {
    const res = await fetch(`${API_BASE_URL}/errors/ux-audit`)
    return handleResponse<UXAuditResponse>(res)
  },

  async getAgentMarketGovernanceSnapshot() {
    const res = await fetch(`${API_BASE_URL}/agents/market-governance-snapshot`)
    return handleResponse<AgentMarketGovernanceSnapshot>(res)
  },

  async getAiAgentAutomationInventorySnapshot() {
    const res = await fetch(`${API_BASE_URL}/agents/automation-inventory-snapshot`)
    return handleResponse<AiAgentAutomationInventorySnapshot>(res)
  },

  async getAiAgentAutomationBacklogSnapshot() {
    const res = await fetch(`${API_BASE_URL}/agents/automation-backlog-snapshot`)
    return handleResponse<AiAgentAutomationBacklogSnapshot>(res)
  },

  async getAiAgentDeploymentLayout() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-deployment-layout`)
    return handleResponse<AiAgentDeploymentLayoutSnapshot>(res)
  },

  async getAiAgentProactiveOperationsContract() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-proactive-operations-contract`)
    return handleResponse<AiAgentProactiveOperationsContractSnapshot>(res)
  },

  async getAiAgentInteractionLearningProof() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-interaction-learning-proof`)
    return handleResponse<AiAgentInteractionLearningProofSnapshot>(res)
  },

  async getAiAgentLiveReadModelGate() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-live-read-model-gate`)
    return handleResponse<AiAgentLiveReadModelGateSnapshot>(res)
  },

  async getAiAgentRedisDryRunGate() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-redis-dry-run-gate`)
    return handleResponse<AiAgentRedisDryRunGateSnapshot>(res)
  },

  async getAiAgentLearningWritebackApprovalPackage() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-learning-writeback-approval-package`)
    return handleResponse<AiAgentLearningWritebackApprovalPackageSnapshot>(res)
  },

  async getAiAgentTelegramReceiptApprovalPackage() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-telegram-receipt-approval-package`)
    return handleResponse<AiAgentTelegramReceiptApprovalPackageSnapshot>(res)
  },

  async getAiAgentOwnerApprovedLearningDryRun() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-owner-approved-learning-dry-run`)
    return handleResponse<AiAgentOwnerApprovedLearningDryRunSnapshot>(res)
  },

  async getAiAgentRuntimeWriteGateReview() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-runtime-write-gate-review`)
    return handleResponse<AiAgentRuntimeWriteGateReviewSnapshot>(res)
  },

  async getAiAgentPostWriteVerifierPackage() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-post-write-verifier-package`)
    return handleResponse<AiAgentPostWriteVerifierPackageSnapshot>(res)
  },

  async getAiAgentRuntimeVerifierEvidenceReview() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-runtime-verifier-evidence-review`)
    return handleResponse<AiAgentRuntimeVerifierEvidenceReviewSnapshot>(res)
  },

  async getAiAgentReportTruthActionabilityReview() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-report-truth-actionability-review`)
    return handleResponse<AiAgentReportTruthActionabilityReviewSnapshot>(res)
  },

  async getAiAgentReportAutomationReview() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-report-automation-review`)
    return handleResponse<AiAgentReportAutomationReviewSnapshot>(res)
  },

  async getAiAgentReportRuntimeReadiness() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-report-runtime-readiness`)
    return handleResponse<AiAgentReportRuntimeReadinessSnapshot>(res)
  },

  async getAiAgentOwnerApprovedFixtureDryRun() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-owner-approved-fixture-dry-run`)
    return handleResponse<AiAgentOwnerApprovedFixtureDryRunSnapshot>(res)
  },

  async getAiAgentHostStatefulVersionInventory() {
    const res = await fetch(`${API_BASE_URL}/agents/agent-host-stateful-version-inventory`)
    return handleResponse<AiAgentHostStatefulVersionInventorySnapshot>(res)
  },

  async getRuntimeSurfaceInventory() {
    const res = await fetch(`${API_BASE_URL}/agents/runtime-surface-inventory`)
    return handleResponse<RuntimeSurfaceInventorySnapshot>(res)
  },

  async getGiteaWorkflowRunnerHealth() {
    const res = await fetch(`${API_BASE_URL}/agents/gitea-workflow-runner-health`)
    return handleResponse<GiteaWorkflowRunnerHealthSnapshot>(res)
  },

  async getObservabilityContractMatrix() {
    const res = await fetch(`${API_BASE_URL}/agents/observability-contract-matrix`)
    return handleResponse<ObservabilityContractMatrixSnapshot>(res)
  },

  async getAiProviderRouteMatrix() {
    const res = await fetch(`${API_BASE_URL}/agents/ai-provider-route-matrix`)
    return handleResponse<AiProviderRouteMatrixSnapshot>(res)
  },

  async getServiceHealthGapMatrix() {
    const res = await fetch(`${API_BASE_URL}/agents/service-health-gap-matrix`)
    return handleResponse<ServiceHealthGapMatrixSnapshot>(res)
  },

  async getServiceHealthFailureNotificationPolicy() {
    const res = await fetch(`${API_BASE_URL}/agents/service-health-failure-notification-policy`)
    return handleResponse<ServiceHealthFailureNotificationPolicySnapshot>(res)
  },

  async getBackupDrTargetInventory() {
    const res = await fetch(`${API_BASE_URL}/agents/backup-dr-target-inventory`)
    return handleResponse<BackupDrTargetInventorySnapshot>(res)
  },

  async getBackupDrReadinessMatrix() {
    const res = await fetch(`${API_BASE_URL}/agents/backup-dr-readiness-matrix`)
    return handleResponse<BackupDrReadinessMatrixSnapshot>(res)
  },

  async getBackupNotificationPolicy() {
    const res = await fetch(`${API_BASE_URL}/agents/backup-notification-policy`)
    return handleResponse<BackupNotificationPolicySnapshot>(res)
  },

  async getOffsiteEscrowReadinessStatus() {
    const res = await fetch(`${API_BASE_URL}/agents/offsite-escrow-readiness-status`)
    return handleResponse<OffsiteEscrowReadinessStatusSnapshot>(res)
  },
}

// =========================================================================
// Type Definitions (Phase 7)
// =========================================================================

/**
 * Phase 6.5: 決策令牌資訊
 * 確保 UI 永遠有決策可操作
 */
export interface DecisionInfo {
  token: string
  state: 'init' | 'analyzing' | 'ready' | 'executing' | 'completed' | 'error'
  proposal_data: {
    action: string
    description: string
    reasoning: string
    risk_level: 'low' | 'medium' | 'critical'
    kubectl_command: string
    source: string
    confidence: number
  } | null
  proposal_id: string | null
}

export interface IncidentResponse {
  incident_id: string
  status: 'investigating' | 'mitigating' | 'resolved' | 'closed'
  severity: 'P0' | 'P1' | 'P2' | 'P3'
  signal_count: number
  affected_services: string[]
  proposal_count: number
  created_at: string
  updated_at: string
  /** Phase 6.5: 決策令牌 (確保 UI 永不鎖死) */
  decision: DecisionInfo | null
}

export interface IncidentListResponse {
  count: number
  incidents: IncidentResponse[]
}

export interface IncidentTimelineEvent {
  stage: string
  status: string
  title: string
  description: string | null
  actor: string | null
  timestamp: string | null
  source_table: string | null
  data: Record<string, unknown>
}

export interface IncidentTimelineStage extends IncidentTimelineEvent {
  label: string
  events: IncidentTimelineEvent[]
}

export interface IncidentTimelineResponse {
  incident_id: string
  title: string
  status: string
  severity: string
  started_at: string | null
  updated_at: string | null
  resolved_at: string | null
  affected_services: string[]
  approval_ids: string[]
  timeline: IncidentTimelineStage[]
  events: IncidentTimelineEvent[]
  ascii_timeline: string
}

export interface BlastRadius {
  affected_pods: number
  estimated_downtime: string
  related_services: string[]
  data_impact: 'none' | 'read_only' | 'write' | 'destructive'
}

export interface DryRunCheck {
  name: string
  passed: boolean
  message: string
}

export interface ApprovalResponse {
  id: string
  action: string
  description: string
  status: 'pending' | 'approved' | 'rejected' | 'expired'
  risk_level: 'low' | 'medium' | 'high' | 'critical'
  blast_radius: BlastRadius
  dry_run_checks: DryRunCheck[]
  required_signatures: number
  current_signatures: number
  signatures: Array<{ signer: string; signed_at: string }>
  requested_by: string
  created_at: string
  expires_at: string | null
}

export interface PendingApprovalsResponse {
  count: number
  approvals: ApprovalResponse[]
}

export interface ProposalGenerateResponse {
  success: boolean
  message: string
  incident_id: string
  proposal: ApprovalResponse | null
  incident_status: string | null
}

// =========================================================================
// Phase 10: Sentry Error Types (#40 BFF)
// =========================================================================

export interface SentryIssue {
  id: string
  short_id: string
  title: string
  culprit: string | null
  level: 'error' | 'warning' | 'info' | 'fatal'
  status: 'unresolved' | 'resolved' | 'ignored'
  count: number
  user_count: number
  first_seen: string
  last_seen: string
  permalink: string | null
}

export interface ErrorStatsResponse {
  total_issues: number
  unresolved_issues: number
  error_count_24h: number
  critical_count: number
  projects: string[]
}

export interface ErrorListResponse {
  issues: SentryIssue[]
  total: number
  has_more: boolean
}

export interface ErrorDetailResponse {
  issue: Record<string, unknown>
  latest_event: Record<string, unknown> | null
  sentry_url: string
}

export interface ErrorTrendPoint {
  timestamp: string
  count: number
}

export interface ErrorTrendResponse {
  period: '24h' | '7d' | '30d'
  data: ErrorTrendPoint[]
  total_count: number
  change_percent: number
}

export interface FixRecommendation {
  summary: string
  steps: string[]
  code_suggestion: string | null
}

export interface PreventionMeasure {
  type: string
  description: string
}

export interface ErrorAnalysis {
  root_cause: string
  category: string
  severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
  impact_assessment: string
  fix_recommendation: FixRecommendation
  prevention: PreventionMeasure[]
  related_files: string[]
  confidence: number
  reasoning: string
}

export interface ErrorAnalysisResponse {
  status: 'completed' | 'failed'
  issue_id: string
  provider: string
  analysis?: ErrorAnalysis
  analyzed_at?: string
  sentry_url: string
  message?: string
}

// =========================================================================
// Phase 19: UX Audit / Session Replay Types (#126)
// 2026-03-31 Claude Code - Frontend Replay UI Integration
// =========================================================================

export interface UXAuditDetail {
  type: 'replay_with_errors' | 'ui_error'
  replay_id?: string
  issue_id?: string
  url: string
  error_count?: number
  title?: string
  count?: number
  urls?: string[]
}

export interface UXAuditResponse {
  replays_with_errors: number
  rage_clicks: number
  dead_clicks: number
  ui_errors: number
  health_score: 'good' | 'moderate' | 'poor'
  details: UXAuditDetail[]
  replay_dashboard_url: string
}

// =========================================================================
// Agent Market Governance Snapshot
// =========================================================================

export interface AgentMarketGovernanceSnapshot {
  schema_version: 'agent_market_governance_snapshot_v1'
  generated_at: string
  current_decision: string
  policy: Record<string, boolean>
  evaluation_cadence: {
    workflow: string
    schedule: string
    timezone: 'Asia/Taipei'
    next_scheduled_run_at: string
    trigger_modes: string[]
    primary_source_policy: string
    operator_review_gate: string
  }
  market_watch_health: {
    status: 'healthy' | 'blocked'
    freshness_sla_hours: 168
    stale_grace_hours: 6
    stale_after: string
    source_failures_block_priority_upgrade: boolean
    blocked_from_integration: number
    operator_blockers: string[]
  }
  summary: {
    candidate_count: number
    source_count: number
    source_failures: number
    changed_candidates: number
    integration_queue_count: number
    blocked_from_integration: number
    watch_only_candidates_reviewed: number
    eligible_for_market_scorecard_prescreen: number
    recommended_watch_additions_remaining: number
    priority_upgrades_approved: number
    market_scorecard_updates_approved: number
    replay_candidates_approved: number
    sdk_installations_approved: number
    paid_api_calls_approved: number
    production_changes_approved: number
    shadow_or_canary_approved: number
    replacement_decisions_approved: number
  }
  candidate_groups: {
    production_baseline: string[]
    replay_or_integration_blocked: string[]
    watch_only_candidates: string[]
    watch_only_scorecard_prescreen_ready: string[]
  }
  candidate_statuses: Array<{
    candidate_id: string
    display_name: string
    role: string
    evaluation_priority: string
    gate_status:
      | 'production_baseline'
      | 'integration_blocked'
      | 'integration_reviewed'
      | 'watch_only_prescreen_ready'
      | 'watch_only_blocked'
      | 'watch_only_monitoring'
      | 'registered_no_review'
    current_gate: string
    required_next_gate: string
    integration_decision: string
    score: number | null
    evidence: {
      latest_replay_summary: string | null
      latest_smoke_gate: string | null
      latest_smoke_matrix: string | null
      latest_smoke_model: string | null
    }
    approvals: {
      replay: false
      sdk_install: false
      paid_api: false
      shadow_or_canary: false
      production_routing: false
    }
    operator_blockers: string[]
  }>
  operator_decision_queue: Array<{
    candidate_id: string
    display_name: string
    priority: number
    queue_status:
      | 'baseline_protected'
      | 'blocked_needs_evidence'
      | 'operator_review_required'
      | 'operator_priority_review'
      | 'watch_only_blocked'
      | 'watch_only_monitoring'
      | 'registered_no_review'
    recommended_action: string
    approval_boundary: {
      replacement_adr_required: boolean
      priority_upgrade_required: boolean
      market_scorecard_update_required: boolean
      replay_approval_required: boolean
      sdk_install_approval_required: boolean
      paid_api_approval_required: boolean
      shadow_or_canary_approval_required: boolean
      production_routing_approval_required: boolean
    }
    risk_notes: string[]
    evidence_refs: string[]
  }>
  next_allowed_actions: string[]
  forbidden_actions_without_new_approval: string[]
}

// =========================================================================
// AI Agent Automation Inventory Snapshot
// =========================================================================

export interface AiAgentAutomationInventorySnapshot {
  schema_version: 'ai_agent_automation_inventory_snapshot_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  status_taxonomy: {
    task_statuses: string[]
    gate_statuses: string[]
    priorities: Array<'P0' | 'P1' | 'P2' | 'P3'>
  }
  agent_roles: Array<{
    agent_id: string
    display_name: string
    primary_role: string
    allowed_actions: string[]
    blocked_actions: string[]
  }>
  asset_domains: Array<{
    domain_id: string
    display_name: string
    description: string
  }>
  assets: Array<{
    asset_id: string
    domain_id: string
    display_name: string
    asset_type: string
    status: string
    gate_status: string
    owner_agent: string
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    evidence_refs: string[]
    next_action: string
  }>
  workstreams: Array<{
    workstream_id: string
    display_name: string
    completion_percent: number
    status: string
    next_task_id: string
  }>
  tasks: Array<{
    task_id: string
    priority: 'P0' | 'P1' | 'P2' | 'P3'
    status: string
    completion_percent: number
    owner_agent: string
    title: string
    output: string
    gate_status: string
    approval_boundary: {
      mode: string
      display_summary: string
      allowed_actions: string[]
      blocked_actions: string[]
      requires_operator_approval_for: string[]
    }
    next_action: string
  }>
  task_approval_boundary_rollup: {
    total_tasks: number
    by_mode: Record<string, number>
    tasks_requiring_explicit_approval: string[]
    tasks_with_blocked_operations: string[]
  }
  evidence: Array<{
    evidence_id: string
    kind: 'schema' | 'test' | 'browser' | 'api' | 'build' | 'doc' | 'runtime'
    ref: string
    result: string
  }>
  approval_boundaries: Record<
    | 'sdk_installation_allowed'
    | 'paid_api_call_allowed'
    | 'shadow_or_canary_allowed'
    | 'production_routing_allowed'
    | 'destructive_operation_allowed',
    false
  >
}

export interface AiAgentAutomationBacklogSnapshot {
  schema_version: 'ai_agent_automation_backlog_v1'
  generated_at: string
  source_inventory_snapshot_ref: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  rollups: {
    total_items: number
    by_priority: Record<string, number>
    by_status: Record<string, number>
    by_gate_status: Record<string, number>
    by_owner_agent: Record<string, number>
  }
  progress_summary: {
    overall_percent: number
    done_items: number
    planned_items: number
    total_items: number
    formula: string
    by_priority: Array<{
      priority: 'P0' | 'P1' | 'P2' | 'P3'
      completion_percent: number
      done_items: number
      total_items: number
    }>
    by_workstream: Array<{
      workstream_id: string
      display_name: string
      completion_percent: number
      done_items: number
      total_items: number
      next_task_id: string
    }>
  }
  backlog_items: Array<{
    item_id: string
    priority: 'P0' | 'P1' | 'P2' | 'P3'
    status: string
    workstream_id: string
    source_asset_id: string
    source_signal_kind: string
    title: string
    owner_agent: string
    recommended_action: string
    action_class: string
    gate_status: string
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    evidence_refs: string[]
    acceptance_criteria: string[]
    approval_boundary: {
      mode: string
      display_summary: string
      allowed_actions: string[]
      blocked_actions: string[]
      requires_operator_approval_for: string[]
    }
    next_review: string
  }>
  item_approval_boundary_rollup: {
    total_items: number
    by_mode: Record<string, number>
    items_requiring_explicit_approval: string[]
    items_with_blocked_operations: string[]
  }
  approval_boundaries: Record<
    | 'sdk_installation_allowed'
    | 'paid_api_call_allowed'
    | 'shadow_or_canary_allowed'
    | 'production_routing_allowed'
    | 'destructive_operation_allowed',
    false
  >
}

export interface AiAgentDeploymentLayoutSnapshot {
  schema_version: 'ai_agent_deployment_layout_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    deployment_authority: 'layout_only_no_runtime_deploy'
  }
  agent_contracts: Array<{
    agent_id: string
    display_name: string
    primary_specialty: string
    deployment_lane: string
    allowed_autonomy: string[]
    must_delegate_to: string[]
    blocked_actions: string[]
    learning_scope: string[]
  }>
  domains: Array<{
    domain_id: string
    display_name: string
    description: string
  }>
  deployment_targets: Array<{
    target_id: string
    domain_id: string
    display_name: string
    target_type: string
    primary_agent: string
    supporting_agents: string[]
    deployment_state:
      | 'active_governed'
      | 'read_only_layout'
      | 'blocked_by_gate'
      | 'planned'
      | 'candidate_only'
    automation_level:
      | 'observe_only'
      | 'prepare_only'
      | 'dry_run_only'
      | 'hitl_execute_after_approval'
      | 'blocked'
    capabilities: string[]
    telegram_policy:
      | 'failure_only'
      | 'action_required'
      | 'approval_required'
      | 'daily_summary_only'
      | 'no_direct_notify'
    learning_inputs: string[]
    communication_channels: string[]
    approval_gate: string
    evidence_refs: string[]
    next_action: string
  }>
  collaboration_contract: {
    message_bus: string
    audit_trail: string
    handoff_rules: string[]
    frontend_redaction: {
      operator_conversation_display_allowed: false
      agent_private_reasoning_display_allowed: false
      display_policy: string
    }
  }
  learning_contract: {
    event_sources: string[]
    feedback_loops: string[]
    growth_metrics: string[]
    retention_policy: string
  }
  telegram_contract: {
    primary_gateway: string
    bot_roles: string[]
    notification_classes: string[]
    redaction_policy: string
    e2e_validation: string
  }
  rollups: {
    total_targets: number
    by_domain: Record<string, number>
    by_primary_agent: Record<string, number>
    by_deployment_state: Record<string, number>
    by_telegram_policy: Record<string, number>
    blocked_target_ids: string[]
    approval_required_target_ids: string[]
  }
  approval_boundaries: Record<
    | 'sdk_installation_allowed'
    | 'paid_api_call_allowed'
    | 'shadow_or_canary_allowed'
    | 'production_routing_allowed'
    | 'destructive_operation_allowed'
    | 'secret_plaintext_allowed'
    | 'autonomous_host_mutation_allowed'
    | 'telegram_direct_send_allowed',
    false
  >
}

export interface AiAgentProactiveOperationsContractSnapshot {
  schema_version: 'ai_agent_proactive_operations_contract_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: string
    status_note: string
  }
  delegation_model: {
    autonomy_levels: Array<{
      level: string
      meaning: string
    }>
    agent_responsibilities: Array<{
      agent_id: string
      responsibility: string
    }>
    telegram_policy: {
      allowed_now: string
      failure_only: string
      success_spam: string
    }
  }
  version_lifecycle_domains: Array<{
    domain_id: string
    display_name: string
    primary_owner: string
    cadence: string
    current_allowed_autonomy: string
    update_authority: string
    approval_gate: string
    tracked_examples: string[]
  }>
  delegable_capabilities: Array<{
    capability_id: string
    display_name: string
    primary_owner: string
    risk_tier: 'low' | 'medium' | 'high' | 'critical'
    automation_level: string
    outputs: string[]
    approval_gate: string
    telegram_policy: string
  }>
  cadence_matrix: Array<{
    cadence_id: string
    frequency: string
    scope: string
    allowed_now: boolean
    next_gate: string
  }>
  mcp_tool_requirements: Array<{
    tool_id: string
    display_name: string
    purpose: string
    owner_agent: string
    status: string
    approval_gate: string
  }>
  rag_memory_contract: Array<{
    memory_id: string
    display_name: string
    storage: string
    owner_agent: string
    purpose: string
    redaction_policy: string
  }>
  rollout_tasks: Array<{
    task_id: string
    priority: 'P0' | 'P1' | 'P2' | 'P3'
    status: string
    completion_percent: number
    owner_agent: string
    summary: string
    next_gate: string
  }>
  approval_boundaries: Record<string, false>
  rollups: {
    version_domain_count: number
    delegable_capability_count: number
    cadence_count: number
    mcp_tool_count: number
    rag_memory_count: number
    rollout_task_count: number
    auto_execute_allowed_count: number
    approval_required_capability_count: number
    blocked_update_domain_ids: string[]
    telegram_action_required_capability_ids: string[]
  }
}

export interface AiAgentInteractionLearningProofSnapshot {
  schema_version: 'ai_agent_interaction_learning_proof_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'proof_surface_only_no_live_worker'
    status_note: string
  }
  live_truth: {
    runtime_loop_enabled: false
    live_agent_session_readback_enabled: false
    redis_consumer_group_enabled: false
    telegram_send_enabled: false
    learning_writeback_enabled: false
    active_live_agent_sessions: number
    live_agent_messages_24h: number
    live_handoffs_24h: number
    live_learning_writes_24h: number
    telegram_digest_receipts_24h: number
    truth_note: string
  }
  proof_ladder: Array<{
    level_id: string
    display_name: string
    status: string
    completion_percent: number
    operator_meaning: string
    source_of_truth: string
    next_gate: string
  }>
  agent_lanes: Array<{
    agent_id: 'openclaw' | 'hermes' | 'nemotron'
    display_name: string
    primary_role: string
    current_visible_state: string
    visible_signals: string[]
    growth_metric: string
    what_operator_will_feel: string
  }>
  proof_signals: Array<{
    signal_id: string
    display_name: string
    category: string
    source_of_truth: string
    visible_surface: string
    current_state: string
    operator_interpretation: string
    next_gate: string
  }>
  operator_surfaces: Array<{
    surface_id: string
    display_name: string
    route_or_channel: string
    operator_feel: string
    redaction_policy: string
    current_state: string
  }>
  runtime_gates: Array<{
    gate_id: string
    display_name: string
    status: string
    required_before_green: string
    next_task_id: string
  }>
  learning_memory_stack: Array<{
    layer_id: string
    display_name: string
    storage_or_service: string
    visible_growth_signal: string
    current_state: string
  }>
  telegram_receipt_contract: {
    direct_send_allowed: false
    gateway_queue_write_allowed: false
    receipt_visible_to_operator: true
    allowed_future_notification_classes: string[]
    success_policy: string
    redaction_policy: string
  }
  frontend_redaction: {
    operator_conversation_display_allowed: false
    agent_private_reasoning_display_allowed: false
    raw_prompt_display_allowed: false
    display_policy: string
  }
  approval_boundaries: Record<string, false>
  rollups: {
    proof_level_count: number
    contract_ready_level_count: number
    live_pending_level_ids: string[]
    signal_count: number
    live_signal_count: number
    operator_surface_count: number
    runtime_gate_count: number
    blocked_gate_ids: string[]
    active_live_agent_sessions: number
    live_agent_messages_24h: number
    live_handoffs_24h: number
    live_learning_writes_24h: number
    telegram_digest_receipts_24h: number
  }
}

export interface AiAgentLiveReadModelGateSnapshot {
  schema_version: 'ai_agent_live_read_model_gate_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'gate_plan_only_no_live_worker'
    status_note: string
  }
  source_refs: string[]
  live_truth: {
    live_agent_session_readback_enabled: false
    live_redis_stream_read_enabled: false
    runtime_worker_enabled: false
    telegram_receipt_send_enabled: false
    learning_writeback_enabled: false
    active_live_agent_sessions: number
    live_redis_events_24h: number
    live_handoffs_24h: number
    live_learning_writes_24h: number
    telegram_digest_receipts_24h: number
    truth_note: string
  }
  existing_storage_contract: {
    db_table: string
    schema_status: string
    migration_delta_required: false
    approved_for_live_query: false
    safe_read_query_defined: true
    safe_selected_fields: string[]
    forbidden_selected_fields: string[]
    required_indexes: string[]
    read_query_contract: string
    query_limits: {
      default_window_hours: number
      max_limit: number
      order_by: string
    }
  }
  redis_stream_contract: {
    stream_namespace: string
    candidate_streams: string[]
    consumer_group_allowed: false
    xadd_allowed: false
    xreadgroup_allowed: false
    dead_letter_required: boolean
    replay_required_before_worker: boolean
    event_envelope_required_fields: string[]
    forbidden_event_fields: string[]
  }
  read_model_cards: Array<{
    card_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    source_of_truth: string
    readiness_status: string
    operator_signal: string
    next_gate: string
  }>
  worker_gate_plan: Array<{
    gate_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    required_evidence: string
    blocked_action: string
  }>
  rollback_plan: Array<{
    rollback_id: string
    step: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
  }>
  no_write_smoke_plan: Array<{
    smoke_id: string
    status: 'defined'
    writes_allowed: false
    assertion: string
  }>
  display_redaction_contract: {
    redaction_required: true
    work_window_conversation_display_allowed: false
    agent_raw_output_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  approval_boundaries: Record<string, false>
  rollups: {
    source_ref_count: number
    read_model_card_count: number
    gate_count: number
    approval_required_gate_ids: string[]
    query_contract_ready_card_ids: string[]
    rollback_step_count: number
    no_write_smoke_count: number
    forbidden_frontend_content_count: number
    live_truth_count_total: number
  }
}

export interface AiAgentRedisDryRunGateSnapshot {
  schema_version: 'ai_agent_redis_dry_run_gate_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'dry_run_contract_only_no_redis_runtime'
    status_note: string
  }
  source_refs: string[]
  dry_run_truth: {
    redis_connection_allowed: false
    consumer_group_created: false
    xadd_allowed: false
    xreadgroup_allowed: false
    ack_allowed: false
    dead_letter_write_allowed: false
    replay_runtime_allowed: false
    telegram_send_allowed: false
    learning_writeback_allowed: false
    live_dry_run_event_count: number
    live_ack_count: number
    live_dead_letter_count: number
    live_replay_count: number
    truth_note: string
  }
  consumer_group_dry_run_contract: {
    candidate_group_name: string
    stream_namespace: string
    fixture_only: true
    redis_network_call_allowed: false
    required_fixture_fields: string[]
    forbidden_fixture_fields: string[]
    dry_run_assertion: string
  }
  handoff_envelope_contract: {
    required_fields: string[]
    forbidden_fields: string[]
    redacted_evidence_required: true
    idempotency_key_required: true
    operator_meaning: string
  }
  ack_dead_letter_replay_contract: {
    ack_requires_verifier: true
    dead_letter_requires_reason: true
    replay_requires_idempotency: true
    runtime_replay_allowed: false
    ack_allowed_statuses: string[]
    dead_letter_reasons: string[]
    replay_preconditions: string[]
  }
  dry_run_steps: Array<{
    step_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    operator_signal: string
    blocked_runtime_action: string
  }>
  handoff_lanes: Array<{
    lane_id: string
    display_name: string
    from_agent: 'openclaw' | 'hermes' | 'nemotron'
    to_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    required_evidence: string
  }>
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    source_ref_count: number
    dry_run_step_count: number
    handoff_lane_count: number
    contract_ready_step_ids: string[]
    approval_required_step_ids: string[]
    blocked_runtime_action_count: number
    required_handoff_field_count: number
    forbidden_field_count: number
    live_truth_count_total: number
  }
}

export interface AiAgentLearningWritebackApprovalPackageSnapshot {
  schema_version: 'ai_agent_learning_writeback_approval_package_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'approval_package_only_no_learning_writeback'
    status_note: string
  }
  source_refs: string[]
  learning_truth: {
    km_write_allowed: false
    playbook_trust_write_allowed: false
    timeline_learning_write_allowed: false
    agent_replay_score_write_allowed: false
    telegram_send_allowed: false
    runtime_worker_allowed: false
    live_learning_write_count: number
    live_playbook_trust_update_count: number
    live_km_update_count: number
    truth_note: string
  }
  writeback_package: {
    required_fields: string[]
    forbidden_fields: string[]
    owner_review_required: true
    rollback_required: true
    operator_meaning: string
  }
  review_gates: Array<{
    gate_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    required_evidence: string
    blocked_write_action: string
  }>
  learning_lanes: Array<{
    lane_id: string
    display_name: string
    target_surface: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    review_owner: string
    required_review: string
  }>
  rollback_contract: {
    rollback_required: true
    rollback_steps: string[]
  }
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    review_gate_count: number
    learning_lane_count: number
    approval_required_gate_ids: string[]
    blocked_write_action_count: number
    required_field_count: number
    forbidden_field_count: number
    live_write_count_total: number
  }
}

export interface AiAgentTelegramReceiptApprovalPackageSnapshot {
  schema_version: 'ai_agent_telegram_receipt_approval_package_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'approval_package_only_no_telegram_send'
    status_note: string
  }
  source_refs: string[]
  telegram_truth: {
    telegram_send_allowed: false
    gateway_queue_write_allowed: false
    direct_bot_api_allowed: false
    receiver_route_change_allowed: false
    runtime_worker_allowed: false
    live_queued_receipt_count: number
    live_delivered_receipt_count: number
    live_acknowledged_receipt_count: number
    live_failed_receipt_count: number
    live_retry_count: number
    truth_note: string
  }
  receipt_package: {
    required_fields: string[]
    forbidden_fields: string[]
    owner_review_required: true
    retry_policy_required: true
    delivery_receipt_required: true
    operator_meaning: string
  }
  receipt_gates: Array<{
    gate_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    required_evidence: string
    blocked_runtime_action: string
  }>
  receipt_lanes: Array<{
    lane_id: string
    display_name: string
    target_surface: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    review_owner: string
    required_review: string
  }>
  retry_contract: {
    retry_required: true
    retry_steps: string[]
  }
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    receipt_gate_count: number
    receipt_lane_count: number
    approval_required_gate_ids: string[]
    blocked_runtime_action_count: number
    required_field_count: number
    forbidden_field_count: number
    live_receipt_count_total: number
  }
}

export interface AiAgentOwnerApprovedLearningDryRunSnapshot {
  schema_version: 'ai_agent_owner_approved_learning_dry_run_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'owner_approved_dry_run_only_no_learning_write'
    status_note: string
  }
  source_refs: string[]
  dry_run_truth: {
    owner_approval_required: true
    owner_approval_received_count: number
    dry_run_preview_allowed: true
    dry_run_preview_generated_count: number
    km_write_allowed: false
    playbook_trust_write_allowed: false
    timeline_learning_write_allowed: false
    agent_replay_score_write_allowed: false
    telegram_send_allowed: false
    runtime_worker_allowed: false
    truth_note: string
  }
  dry_run_preview: {
    required_inputs: string[]
    forbidden_inputs: string[]
    preview_outputs: string[]
    operator_meaning: string
  }
  operator_actions: Array<{
    action_id: string
    display_name: string
    action_type: 'review' | 'collect_evidence' | 'approve_dry_run' | 'reject_or_rework'
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    operator_instruction: string
    blocked_runtime_action: string
  }>
  dry_run_gates: Array<{
    gate_id: string
    display_name: string
    status: string
    required_evidence: string
    blocked_write_action: string
  }>
  verification_contract: {
    verification_required: true
    verification_steps: string[]
    rollback_required: true
  }
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    operator_action_count: number
    dry_run_gate_count: number
    approval_required_gate_ids: string[]
    blocked_write_action_count: number
    required_input_count: number
    forbidden_input_count: number
    preview_output_count: number
    live_write_count_total: number
    dry_run_preview_generated_count: number
  }
}

export interface AiAgentRuntimeWriteGateReviewSnapshot {
  schema_version: 'ai_agent_runtime_write_gate_review_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'write_gate_review_only_no_runtime_write'
    status_note: string
  }
  source_refs: string[]
  runtime_write_truth: {
    runtime_write_allowed: false
    dual_approval_required: true
    dual_approval_received_count: number
    dry_run_hash_required: true
    dry_run_hash_verified_count: number
    post_write_verifier_required: true
    post_write_verifier_pass_count: number
    km_write_allowed: false
    playbook_trust_write_allowed: false
    timeline_learning_write_allowed: false
    agent_replay_score_write_allowed: false
    telegram_send_allowed: false
    truth_note: string
  }
  write_gate_review: {
    operator_meaning: string
    required_fields: string[]
    forbidden_fields: string[]
  }
  write_targets: Array<{
    target_id: string
    display_name: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    required_before_write: string
    blocked_write_action: string
  }>
  approval_gates: Array<{
    gate_id: string
    display_name: string
    status: string
    required_evidence: string
    blocked_runtime_action: string
  }>
  post_write_verification: {
    verification_required: true
    rollback_required: true
    verification_steps: string[]
  }
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    write_target_count: number
    approval_gate_count: number
    approval_required_gate_ids: string[]
    blocked_runtime_action_count: number
    required_field_count: number
    forbidden_field_count: number
    live_write_count_total: number
  }
}

export interface AiAgentPostWriteVerifierPackageSnapshot {
  schema_version: 'ai_agent_post_write_verifier_package_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'post_write_verifier_package_only_no_runtime_write'
    status_note: string
  }
  source_refs: string[]
  verifier_truth: {
    runtime_write_allowed: false
    post_write_verifier_implemented: false
    post_write_verifier_executed_count: number
    rollback_work_item_created_count: number
    telegram_failure_receipt_sent_count: number
    canonical_readback_allowed: false
    truth_note: string
  }
  verifier_package: {
    operator_meaning: string
    required_inputs: string[]
    forbidden_inputs: string[]
    success_policy: string
    failure_policy: string
  }
  verification_targets: Array<{
    target_id: string
    display_name: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    verifier_check: string
    failure_escalation: string
    blocked_runtime_action: string
  }>
  failure_lanes: Array<{
    lane_id: string
    display_name: string
    status: string
    trigger: string
    blocked_runtime_action: string
    operator_instruction: string
  }>
  operator_actions: Array<{
    action_id: string
    display_name: string
    action_type: 'review' | 'collect_evidence' | 'approve_implementation' | 'reject_or_rework'
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    operator_instruction: string
    blocked_runtime_action: string
  }>
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    verification_target_count: number
    failure_lane_count: number
    operator_action_count: number
    approval_required_action_ids: string[]
    blocked_runtime_action_count: number
    required_input_count: number
    forbidden_input_count: number
    live_verifier_execution_count: number
  }
}

export interface AiAgentRuntimeVerifierEvidenceReviewSnapshot {
  schema_version: 'ai_agent_runtime_verifier_evidence_review_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'runtime_verifier_evidence_review_only_no_live_execution'
    status_note: string
  }
  source_refs: string[]
  review_truth: {
    review_packet_ready: true
    runtime_verifier_implementation_allowed: false
    post_write_verifier_execution_allowed: false
    runtime_verifier_executed_count: number
    canonical_readback_allowed: false
    canonical_readback_executed_count: number
    rollback_work_item_created_count: number
    telegram_failure_receipt_sent_count: number
    learning_writeback_after_verifier_count: number
    truth_note: string
  }
  review_package: {
    required_evidence: string[]
    forbidden_evidence: string[]
    operator_meaning: string
    approval_policy: string
    failure_policy: string
  }
  evidence_checks: Array<{
    check_id: string
    display_name: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    required_evidence: string
    review_question: string
    blocked_runtime_action: string
  }>
  implementation_review_lanes: Array<{
    lane_id: string
    display_name: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    trigger: string
    operator_instruction: string
    blocked_runtime_action: string
  }>
  operator_actions: Array<{
    action_id: string
    display_name: string
    action_type: 'review' | 'collect_evidence' | 'approve_implementation' | 'reject_or_rework'
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    operator_instruction: string
    blocked_runtime_action: string
  }>
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    evidence_check_count: number
    implementation_review_lane_count: number
    operator_action_count: number
    approval_required_action_ids: string[]
    blocked_runtime_action_count: number
    required_evidence_count: number
    forbidden_evidence_count: number
    live_verifier_execution_count: number
  }
}

export interface AiAgentReportTruthActionabilityReviewSnapshot {
  schema_version: 'ai_agent_report_truth_actionability_review_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'report_truth_actionability_review_only_no_report_send_or_runtime_fix'
    status_note: string
  }
  source_refs: string[]
  report_truth: {
    report_truth_packet_ready: true
    all_zero_weekly_report_is_actionable_anomaly: true
    daily_report_contract_present: boolean
    weekly_report_contract_present: boolean
    monthly_report_contract_present: false
    freshness_gate_implemented: false
    source_confidence_gate_implemented: false
    actionability_score_implemented: false
    ai_agent_runtime_control_allowed: false
    telegram_report_send_allowed: false
    cronjob_change_allowed: false
    truth_note: string
  }
  zero_signal_findings: Array<{
    finding_id: string
    display_name: string
    severity: string
    source: string
    evidence: string
    operator_meaning: string
    required_fix: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    blocked_runtime_action: string
  }>
  report_cadence_contracts: Array<{
    cadence_id: string
    display_name: string
    status: string
    source: string
    required_truth: string
    next_action: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
  }>
  alert_actionability_lanes: Array<{
    lane_id: string
    display_name: string
    routing_policy: string
    ai_agent_role: string
    notification_policy: string
  }>
  telegram_routing_consolidation: {
    canonical_room_name: 'AwoooI SRE 戰情室'
    canonical_room_env: 'SRE_GROUP_CHAT_ID'
    product_alerts_must_route_to_canonical_room: true
    other_bot_or_group_alerts_allowed: false
    direct_telegram_api_send_allowed: false
    secret_value_read_allowed: false
    route_change_allowed: false
    routing_note: string
  }
  telegram_route_findings: Array<{
    route_id: string
    display_name: string
    source: string
    current_state: string
    target_state: string
    risk: string
    required_fix: string
    blocked_runtime_action: string
  }>
  operator_actions: Array<{
    action_id: string
    display_name: string
    action_type: string
    status: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    operator_instruction: string
    blocked_runtime_action: string
  }>
  approval_boundaries: Record<string, false>
  rollups: {
    zero_signal_finding_count: number
    critical_finding_count: number
    high_finding_count: number
    cadence_contract_count: number
    missing_cadence_contract_count: number
    actionability_lane_count: number
    telegram_route_finding_count: number
    legacy_or_direct_route_count: number
    operator_action_count: number
    approval_required_action_ids: string[]
    blocked_runtime_action_count: number
    all_zero_weekly_report_confidence: 'low_trust_actionable_anomaly'
  }
}

export interface AiAgentReportAutomationReviewSnapshot {
  schema_version: 'ai_agent_report_automation_review_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'reporting_and_risk_policy_review_only_no_live_execution'
    status_note: string
  }
  source_refs: string[]
  report_truth: {
    daily_report_ready: true
    weekly_report_ready: true
    monthly_report_ready: true
    per_agent_workload_ready: true
    chart_package_ready: true
    report_delivery_enabled: false
    report_delivery_count_24h: number
    report_read_receipt_count_24h: number
    ai_analysis_after_report_enabled: false
    medium_low_auto_policy_defined: true
    medium_low_auto_execution_enabled: false
    live_medium_low_auto_execution_count_24h: number
    high_risk_requires_approval: true
    live_auto_optimization_count_24h: number
    truth_note: string
  }
  report_cadences: Array<{
    cadence_id: 'daily' | 'weekly' | 'monthly'
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    schedule: string
    sections: string[]
    chart_ids: string[]
    delivery_channel: string
    status: string
    live_delivery_count: number
  }>
  agent_workload_metrics: Array<{
    agent_id: 'openclaw' | 'hermes' | 'nemotron'
    display_name: string
    primary_role: string
    deployment_targets: number
    delegable_capabilities: number
    report_owned_sections: number
    analysis_owned_recommendations: number
    work_units_total: number
    work_units_done: number
    work_units_waiting_approval: number
    live_runtime_work_units_24h: number
    workload_note: string
  }>
  report_charts: Array<{
    chart_id: string
    display_name: string
    chart_type: string
    unit: string
    series: Array<{
      label: string
      value: number
      tone: 'ok' | 'warn' | 'danger' | 'neutral'
    }>
    operator_question: string
  }>
  risk_tier_policy: {
    policy_summary: string
    risk_tiers: Array<{
      risk_id: 'low' | 'medium' | 'high' | 'critical'
      display_name: string
      approval_required: boolean
      auto_action_policy: string
      current_execution_enabled: false
      required_before_enable: string[]
    }>
  }
  analysis_recommendations: Array<{
    recommendation_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    risk_tier: 'low' | 'medium' | 'high' | 'critical'
    approval_required: boolean
    current_auto_execution_enabled: false
    problem: string
    proposed_solution: string
    expected_report_signal: string
    blocked_runtime_action: string
  }>
  approval_boundaries: Record<string, boolean>
  display_redaction_contract: {
    redaction_required: true
    raw_report_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    work_window_transcript_display_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    report_cadence_count: number
    agent_count: number
    chart_count: number
    recommendation_count: number
    workload_unit_total: number
    workload_done_total: number
    workload_waiting_approval_total: number
    low_risk_recommendation_count: number
    medium_risk_recommendation_count: number
    high_risk_recommendation_count: number
    critical_risk_recommendation_count: number
    approval_required_recommendation_ids: string[]
    medium_low_auto_policy_count: number
    current_auto_execution_enabled_count: number
    live_report_delivery_count: number
    live_auto_optimization_count: number
  }
}

export interface AiAgentReportRuntimeReadinessSnapshot {
  schema_version: 'ai_agent_report_runtime_readiness_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: 'P2-403L'
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'report_runtime_readiness_only_no_live_delivery_or_optimization'
    status_note: string
  }
  source_refs: string[]
  activation_truth: {
    report_scheduler_contract_ready: true
    telegram_gateway_queue_contract_ready: true
    telegram_delivery_receipt_contract_ready: true
    ai_readback_analysis_contract_ready: true
    medium_low_auto_guard_contract_ready: true
    high_risk_approval_gate_contract_ready: true
    live_report_delivery_enabled: false
    live_report_delivery_count_24h: number
    telegram_gateway_queue_write_enabled: false
    telegram_gateway_queue_write_count_24h: number
    report_read_receipt_write_enabled: false
    report_read_receipt_count_24h: number
    ai_analysis_runtime_enabled: false
    ai_analysis_runtime_count_24h: number
    medium_low_auto_worker_enabled: false
    medium_low_auto_execution_count_24h: number
    production_optimization_enabled: false
    production_optimization_count_24h: number
    high_risk_auto_execution_enabled: false
    high_risk_auto_execution_count_24h: number
    truth_note: string
  }
  runtime_lanes: Array<{
    lane_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    risk_tier: 'low' | 'medium' | 'high' | 'critical'
    target_runtime: string
    contract_status: 'ready_for_owner_review' | 'blocked_by_runtime_gate'
    current_live_count_24h: number
    enablement_required: string[]
    blocked_actions: string[]
  }>
  automation_policies: Array<{
    risk_id: 'low' | 'medium' | 'high' | 'critical'
    display_name: string
    approval_required: boolean
    auto_allowed_after_guard: boolean
    current_execution_enabled: false
    required_guards: string[]
    reporting_rule: string
  }>
  report_delivery_cadence_gates: Array<{
    cadence_id: 'daily' | 'weekly' | 'monthly'
    display_name: string
    scheduler_source: string
    telegram_digest_policy: string
    recipient_room: string
    dry_run_required: true
    current_delivery_enabled: false
    live_delivery_count_24h: number
  }>
  telegram_route_readiness: {
    canonical_room: 'AwoooI SRE 戰情室'
    secret_ref: 'SRE_GROUP_CHAT_ID'
    gateway_required: true
    direct_bot_api_allowed: false
    bot_log_out_allowed: false
    legacy_routes_must_converge: true
    telegram_gateway_queue_write_enabled: false
    e2e_delivery_verified: false
    delivery_receipt_write_enabled: false
    blocked_route_count: number
  }
  agent_post_report_actions: Array<{
    agent_id: 'openclaw' | 'hermes' | 'nemotron'
    display_name: string
    after_report_responsibility: string
    allowed_without_approval: string[]
    blocked_until_approval: string[]
    live_action_count_24h: number
  }>
  operator_decisions: Array<{
    decision_id: string
    display_name: string
    risk_tier: 'low' | 'medium' | 'high' | 'critical'
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    approval_required: boolean
    status: 'ready_for_review' | 'blocked_by_runtime_gate' | 'approval_required'
    why_it_matters: string
    next_safe_step: string
  }>
  display_redaction_contract: {
    redaction_required: true
    raw_report_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    work_window_transcript_display_allowed: false
    allowed_display_fields: string[]
    blocked_display_fields: string[]
  }
  rollups: {
    runtime_lane_count: number
    report_cadence_gate_count: number
    operator_decision_count: number
    automation_policy_count: number
    ready_contract_count: number
    blocked_contract_count: number
    approval_required_decision_ids: string[]
    current_enabled_count: number
    live_report_delivery_count: number
    live_ai_analysis_count: number
    live_medium_low_auto_execution_count: number
    telegram_gateway_queue_write_count: number
    high_risk_auto_execution_count: number
  }
}

export interface AiAgentOwnerApprovedFixtureDryRunSnapshot {
  schema_version: 'ai_agent_owner_approved_fixture_dry_run_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: 'owner_approved_fixture_dry_run_only_no_live_write'
    status_note: string
  }
  source_refs: string[]
  dry_run_truth: {
    owner_fixture_scope_approved: true
    production_write_approved: false
    fixture_dry_run_allowed: true
    km_write_allowed: false
    playbook_trust_write_allowed: false
    timeline_learning_write_allowed: false
    agent_replay_score_write_allowed: false
    gateway_queue_write_allowed: false
    telegram_send_allowed: false
    redis_consumer_group_allowed: false
    db_migration_allowed: false
    workflow_trigger_allowed: false
    runtime_worker_allowed: false
    host_or_cluster_command_allowed: false
    secret_or_paid_api_allowed: false
    live_learning_write_count: number
    live_playbook_trust_update_count: number
    live_km_update_count: number
    live_timeline_write_count: number
    live_replay_score_write_count: number
    live_gateway_queue_write_count: number
    live_telegram_send_count: number
    truth_note: string
  }
  fixture_package: {
    required_fields: string[]
    forbidden_fields: string[]
    owner_review_required: true
    rollback_required: true
    no_write_proof_required: true
    operator_meaning: string
  }
  fixture_sets: Array<{
    fixture_id: string
    display_name: string
    scenario_type: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    target_surface: string
    operator_visible_result: string
    blocked_runtime_action: string
  }>
  dry_run_gates: Array<{
    gate_id: string
    display_name: string
    owner_agent: 'openclaw' | 'hermes' | 'nemotron'
    status: string
    required_evidence: string
    blocked_runtime_action: string
  }>
  simulation_steps: Array<{
    step_id: string
    display_name: string
    status: string
    expected_artifact: string
  }>
  rollback_contract: {
    rollback_required: true
    rollback_steps: string[]
  }
  approval_boundaries: Record<string, false>
  display_redaction_contract: {
    redaction_required: true
    raw_payload_display_allowed: false
    private_reasoning_display_allowed: false
    secret_value_display_allowed: false
    action_button_allowed: false
    allowed_frontend_content: string[]
    forbidden_frontend_content: string[]
    frontend_display_policy: string
  }
  rollups: {
    fixture_set_count: number
    dry_run_gate_count: number
    simulation_step_count: number
    approved_fixture_only_count: number
    approval_required_gate_ids: string[]
    blocked_runtime_action_count: number
    required_field_count: number
    forbidden_field_count: number
    live_write_count_total: number
    live_send_count_total: number
    live_receipt_count_total: number
  }
}

export interface AiAgentHostStatefulVersionInventorySnapshot {
  schema_version: 'ai_agent_host_stateful_version_inventory_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_task_id: string
    next_task_id: string
    read_only_mode: true
    runtime_authority: string
    status_note: string
  }
  source_refs: string[]
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
  agent_roles: Array<{
    agent: string
    role: string
    responsibility: string
  }>
  host_inventory: Array<{
    host_id: string
    display_name: string
    known_addresses: string[]
    primary_surfaces: string[]
    version_observation_status: string
    readonly_only: boolean
    host_update_authorized: boolean
    reboot_authorized: boolean
    maintenance_window_required: boolean
    next_evidence_needed: string[]
    blocked_actions: string[]
  }>
  k3s_inventory: {
    cluster_id: string
    api_endpoint: string
    version_observation_status: string
    skew_policy_required: boolean
    upgrade_authorized: boolean
    nodes: Array<{
      node_id: string
      host_id: string
      role: string
      readonly_only: boolean
      drain_authorized: boolean
      kubelet_restart_authorized: boolean
      version_observation_status: string
    }>
    required_pre_change_evidence: string[]
  }
  stateful_services: Array<{
    service_id: string
    display_name: string
    host_id: string
    endpoint_ref: string
    version_observation_status: string
    readonly_only: boolean
    restart_authorized: boolean
    upgrade_authorized: boolean
    backup_required_before_change: boolean
  }>
  readonly_probe_plan: Array<{
    step_id: string
    display_name: string
    planned_output: string
    run_now_allowed: boolean
    mutation_allowed: boolean
  }>
  maintenance_window_approval_package: {
    package_id: string
    approval_required_before_probe: boolean
    approval_required_before_change: boolean
    break_glass_record_required: boolean
    required_fields: string[]
    forbidden_fields: string[]
    minimum_smoke_plan: string[]
  }
  telegram_policy: {
    status: string
    direct_send_allowed: boolean
    gateway_queue_write_allowed: boolean
    allowed_digest_types_after_gate: string[]
    success_noise_suppression: boolean
  }
  display_redaction_contract: {
    conversation_transcript_display_allowed: false
    redaction_required: true
    allowed_frontend_fields: string[]
    forbidden_frontend_content: string[]
  }
  rollups: {
    host_count: number
    k3s_node_count: number
    stateful_service_count: number
    readonly_probe_step_count: number
    maintenance_required_field_count: number
    host_ids: string[]
    stateful_service_ids: string[]
    ssh_login_allowed_count: number
    kubectl_command_execution_allowed_count: number
    apt_upgrade_allowed_count: number
    k3s_upgrade_allowed_count: number
    node_drain_allowed_count: number
    reboot_allowed_count: number
    stateful_service_restart_allowed_count: number
    telegram_direct_send_allowed_count: number
    conversation_transcript_allowed_count: number
  }
  next_actions: Array<{
    task_id: string
    priority: 'P0' | 'P1' | 'P2' | 'P3'
    summary: string
    gate: string
  }>
}

export interface RuntimeSurfaceInventorySnapshot {
  schema_version: 'runtime_surface_inventory_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  source_refs: string[]
  rollups: {
    total_surfaces: number
    by_kind: Record<string, number>
    by_status: Record<string, number>
    by_evidence_level: Record<string, number>
    action_required_surface_ids: string[]
    secret_surface_ids: string[]
    live_check_missing_surface_ids: string[]
    total_source_components: number
    source_components_with_runtime_binding: number
  }
  runtime_surfaces: Array<{
    surface_id: string
    display_name: string
    kind: 'deployment' | 'service' | 'ingress' | 'cronjob' | 'configmap' | 'secret' | 'rbac' | 'policy' | 'autoscaler' | 'availability'
    manifest_ref: string
    status: 'manifest_mapped' | 'action_required' | 'blocked' | 'missing'
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    evidence_level: 'committed_manifest' | 'source_file' | 'missing_manifest' | 'live_check_required'
    runtime_binding: string
    health_contract: string
    secret_exposure: 'none' | 'name_only' | 'template_only' | 'payload_redacted'
    live_check_status: 'not_run' | 'not_applicable' | 'required'
    evidence_refs: string[]
    next_action: string
  }>
  source_runtime_components: Array<{
    component_id: string
    display_name: string
    source_ref: string
    component_kind: string
    runtime_binding: string
    status: 'bound' | 'action_required' | 'source_only'
    next_action: string
  }>
  evidence_gaps: Array<{
    gap_id: string
    severity: 'low' | 'medium' | 'high' | 'critical'
    status: 'action_required' | 'blocked' | 'accepted'
    summary: string
    evidence_refs: string[]
    next_action: string
  }>
  operator_contract: {
    display_mode: 'read_only_runtime_surface'
    must_not_interpret_as: string[]
    secret_display_policy: string
  }
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
}

export interface GiteaWorkflowRunnerHealthSnapshot {
  schema_version: 'gitea_workflow_runner_health_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  source_refs: string[]
  rollups: {
    total_workflows: number
    by_workflow_status: Record<string, number>
    by_runner_evidence_status: Record<string, number>
    workflows_with_schedule: number
    workflows_with_workflow_dispatch: number
    workflows_with_notify_bridge: number
    workflows_with_actionable_or_failure_quiet_policy: number
    workflow_ids_requiring_runner_attestation: string[]
    total_runner_contracts: number
    runner_contracts_requiring_action: string[]
    notification_contracts_total: number
    notification_contracts_quiet_success_count: number
    notification_contracts_quiet_success_ids: string[]
  }
  workflow_records: Array<{
    workflow_id: string
    file_ref: string
    display_name: string
    scope: string
    status: 'manifest_mapped' | 'action_required' | 'blocked'
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    triggers: string[]
    schedule_cadence: string
    runner_labels: string[]
    runner_evidence_status: 'host_runner_mapped' | 'owner_attestation_required' | 'comment_ambiguous'
    job_count: number
    notification_policy: string
    notify_bridge_calls: number
    secrets_policy_status: string
    evidence_refs: string[]
    next_action: string
  }>
  runner_contracts: Array<{
    contract_id: string
    display_name: string
    status: 'manifest_mapped' | 'action_required' | 'dry_run_only' | 'prepared_not_applied_by_snapshot'
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    runner_labels: string[]
    used_by_workflows: string[]
    health_contract: string
    guardrail_refs: string[]
    evidence_refs: string[]
    next_action: string
  }>
  notification_contracts: Array<{
    contract_id: string
    display_name: string
    status: 'preserved' | 'exception_documented' | 'action_required'
    policy_kind: 'failure_only' | 'actionable_only' | 'deployment_status_exception' | 'manual_status_exception' | 'read_only_no_notify'
    success_noise_policy: string
    failure_policy: string
    workflow_refs: string[]
    evidence_refs: string[]
    next_action: string
  }>
  latest_observations: Array<{
    observation_id: string
    status: string
    summary: string
    evidence_refs: string[]
  }>
  operator_contract: {
    display_mode: 'read_only_gitea_workflow_runner_health'
    must_not_interpret_as: string[]
    secret_display_policy: string
    runner_mutation_policy: string
    notification_policy: string
  }
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
}

export interface ObservabilityContractMatrixSnapshot {
  schema_version: 'observability_contract_matrix_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  source_refs: string[]
  rollups: {
    total_surfaces: number
    by_kind: Record<string, number>
    by_status: Record<string, number>
    by_evidence_status: Record<string, number>
    by_noise_policy_status: Record<string, number>
    surface_ids_requiring_action: string[]
    surface_ids_with_proposal_only_noise_policy: string[]
    noise_reduction_opportunities_total: number
    approval_required_opportunity_ids: string[]
    classification_gap_ids: string[]
    read_only_denials_total: number
  }
  observability_surfaces: Array<{
    surface_id: string
    display_name: string
    kind: string
    status: 'verified' | 'action_required' | 'blocked'
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    evidence_status: string
    noise_policy_status: string
    coverage_contract: string
    current_contract?: string
    evidence_refs: string[]
    next_action: string
  }>
  noise_reduction_opportunities: Array<{
    opportunity_id: string
    display_name: string
    status: string
    proposal_only: true
    impact: string
    target_surface_ids?: string[]
    evidence_refs: string[]
    next_action: string
  }>
  classification_gaps: Array<{
    gap_id: string
    display_name: string
    status: string
    severity: 'low' | 'medium' | 'high' | 'critical'
    summary: string
    evidence_refs: string[]
    next_action: string
  }>
  latest_observations: Array<{
    observation_id: string
    status: string
    summary: string
    evidence_refs: string[]
  }>
  operator_contract: {
    display_mode: 'read_only_observability_contract_matrix'
    must_not_interpret_as: string[]
    secret_display_policy: string
    alertmanager_route_policy: string
    noise_reduction_policy: string
    notification_policy: string
  }
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
}

export interface AiProviderRouteMatrixSnapshot {
  schema_version: 'ai_provider_route_matrix_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  source_refs: string[]
  rollups: {
    total_routes: number
    by_kind: Record<string, number>
    by_status: Record<string, number>
    by_route_gate: Record<string, number>
    route_ids_requiring_action: string[]
    candidate_gate_ids_requiring_approval: string[]
    source_gap_ids: string[]
    read_only_denials_total: number
    provider_switch_allowed_count: number
    paid_api_call_allowed_count: number
    shadow_or_canary_allowed_count: number
    runtime_route_change_allowed_count: number
  }
  provider_routes: Array<{
    route_id: string
    display_name: string
    kind: string
    status: 'verified' | 'action_required' | 'blocked'
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    route_gate: string
    evidence_status: string
    current_policy: string
    provider_order: string[]
    fallback_policy: string
    evidence_refs: string[]
    next_action: string
  }>
  candidate_gates: Array<{
    gate_id: string
    display_name: string
    status: string
    approval_required: boolean
    summary: string
    evidence_refs: string[]
    next_action: string
  }>
  source_gaps: Array<{
    gap_id: string
    display_name: string
    status: string
    severity: 'low' | 'medium' | 'high' | 'critical'
    summary: string
    evidence_refs: string[]
    next_action: string
  }>
  latest_observations: Array<{
    observation_id: string
    status: string
    summary: string
    evidence_refs: string[]
  }>
  operator_contract: {
    display_mode: 'read_only_ai_provider_route_matrix'
    must_not_interpret_as: string[]
    secret_display_policy: string
    provider_switch_policy: string
    cost_policy: string
    runtime_policy: string
  }
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
}

export interface ServiceHealthGapMatrixSnapshot {
  schema_version: 'service_health_gap_matrix_v1'
  generated_at: string
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  source_refs: string[]
  rollups: {
    total_targets: number
    by_kind: Record<string, number>
    by_status: Record<string, number>
    by_freshness_status: Record<string, number>
    target_ids_requiring_action: string[]
    health_gap_ids: string[]
    stale_endpoint_ids: string[]
    critical_target_ids: string[]
    read_only_denials_total: number
    service_restart_allowed_count: number
    endpoint_change_allowed_count: number
    active_probe_allowed_count: number
    notification_send_allowed_count: number
    runtime_execution_allowed_count: number
  }
  service_health_targets: Array<{
    target_id: string
    display_name: string
    kind: string
    status: 'verified' | 'action_required' | 'blocked'
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    freshness_status: string
    health_contract: string
    endpoint_contract: string
    evidence_refs: string[]
    next_action: string
  }>
  health_gaps: Array<{
    gap_id: string
    display_name: string
    status: string
    severity: 'low' | 'medium' | 'high' | 'critical'
    summary: string
    target_ids: string[]
    evidence_refs: string[]
    next_action: string
  }>
  stale_endpoints: Array<{
    endpoint_id: string
    display_name: string
    status: string
    severity: 'low' | 'medium' | 'high' | 'critical'
    stale_ref: string
    current_truth: string
    evidence_refs: string[]
    next_action: string
  }>
  latest_observations: Array<{
    observation_id: string
    status: string
    summary: string
    evidence_refs: string[]
  }>
  operator_contract: {
    display_mode: 'read_only_service_health_gap_matrix'
    must_not_interpret_as: string[]
    secret_display_policy: string
    restart_policy: string
    endpoint_policy: string
    notification_policy: string
  }
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
}

export interface ServiceHealthFailureNotificationPolicySnapshot {
  schema_version: 'service_health_failure_notification_policy_v1'
  generated_at: string
  source_service_health_matrix_ref: string
  source_refs: string[]
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  rollups: {
    total_rules: number
    by_decision: Record<string, number>
    immediate_escalation_rule_ids: string[]
    suppressed_success_rule_ids: string[]
    action_required_rule_ids: string[]
    notification_send_allowed_count: number
  }
  notification_channels: Array<{
    channel_id: string
    purpose: string
    immediate_allowed: boolean
    success_immediate_allowed: boolean
    requires_operator_action: boolean
  }>
  policy_rules: Array<{
    rule_id: string
    event_kind: string
    service_state: string
    severity: string
    decision: string
    channels: string[]
    owner_agent: string
    requires_incident: boolean
    requires_approval_record: boolean
    message_contract: string
    evidence_refs: string[]
  }>
  message_template_contract: {
    required_fields: string[]
    forbidden_fields: string[]
    success_message_policy: string
    failure_message_policy: string
  }
  display_redaction_contract: {
    frontend_display_policy: string
    allowed_frontend_fields: string[]
    forbidden_frontend_content: string[]
    conversation_transcript_display_allowed: false
    redaction_required: true
  }
  operation_boundaries: Record<string, boolean>
  approval_boundaries: Record<string, false>
}

export interface BackupDrTargetInventorySnapshot {
  schema_version: 'backup_dr_target_inventory_v1'
  generated_at: string
  source_refs: string[]
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  rollups: {
    total_targets: number
    by_status: Record<string, number>
    by_target_type: Record<string, number>
    by_gate_status: Record<string, number>
    blocked_target_ids: string[]
  }
  backup_targets: Array<{
    target_id: string
    display_name: string
    target_type: string
    status: string
    risk_level: 'low' | 'medium' | 'high' | 'critical'
    owner_host: string
    primary_script: string
    schedule: string
    rpo: string
    storage_class: string
    storage_ref: string
    offsite_policy: string
    automation_gate_status: string
    restore_gate_status: string
    secret_policy: string
    evidence_refs: string[]
    next_action: string
  }>
  approval_boundaries: Record<string, false>
  operation_boundaries: Record<string, boolean>
}

export interface BackupDrReadinessMatrixSnapshot {
  schema_version: 'backup_dr_readiness_matrix_v1'
  generated_at: string
  source_target_inventory_ref: string
  source_refs: string[]
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  rollups: {
    total_rows: number
    by_overall_readiness: Record<string, number>
    by_restore_drill_status: Record<string, number>
    by_offsite_status: Record<string, number>
    blocked_row_ids: string[]
    action_required_row_ids: string[]
  }
  readiness_rows: Array<{
    target_id: string
    display_name: string
    overall_readiness: string
    freshness_status: string
    integrity_status: string
    restore_drill_status: string
    offsite_status: string
    notification_policy: string
    gate_status: string
    evidence_level: string
    evidence_refs: string[]
    blocker_summary: string
    next_action: string
  }>
  approval_boundaries: Record<string, false>
  operation_boundaries: Record<string, boolean>
}

export interface BackupNotificationPolicySnapshot {
  schema_version: 'backup_notification_policy_v1'
  generated_at: string
  source_readiness_matrix_ref: string
  source_refs: string[]
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  rollups: {
    total_rules: number
    by_decision: Record<string, number>
    immediate_escalation_rule_ids: string[]
    suppressed_success_rule_ids: string[]
  }
  notification_channels: Array<{
    channel_id: string
    purpose: string
    immediate_allowed: boolean
    success_immediate_allowed: boolean
    requires_operator_action: boolean
  }>
  policy_rules: Array<{
    rule_id: string
    event_kind: string
    backup_state: string
    severity: string
    decision: string
    channels: string[]
    owner_agent: string
    requires_incident: boolean
    requires_approval_record: boolean
    message_contract: string
    evidence_refs: string[]
  }>
  daily_summary_contract: Record<string, unknown>
  approval_boundaries: Record<string, false>
  operation_boundaries: Record<string, boolean>
}

export interface OffsiteEscrowReadinessStatusSnapshot {
  schema_version: 'offsite_escrow_readiness_status_v1'
  generated_at: string
  source_refs: string[]
  program_status: {
    overall_completion_percent: number
    current_priority: 'P0' | 'P1' | 'P2' | 'P3'
    current_task_id: string
    next_task_id: string
    read_only_mode: true
  }
  rollups: {
    total_cards: number
    by_readiness: Record<string, number>
    by_kind: Record<string, number>
    verified_offsite_card_ids: string[]
    blocked_escrow_card_ids: string[]
    action_required_card_ids: string[]
    execution_blocked_card_ids: string[]
  }
  readiness_cards: Array<{
    card_id: string
    target_id: string
    display_name: string
    kind: 'offsite_mirror' | 'credential_escrow' | 'k8s_resource_offsite'
    readiness: 'verified' | 'action_required' | 'blocked'
    offsite_status: string
    escrow_status: string
    restore_drill_status: string
    credential_exposure_status: string
    automation_gate_status: string
    operator_summary: string
    next_action: string
    evidence_refs: string[]
    blocked_operations: string[]
  }>
  operator_contract: {
    display_mode: 'read_only_status'
    success_notification_policy: string
    failure_notification_policy: string
    credential_display_policy: string
    must_not_interpret_as: string[]
  }
  approval_boundaries: Record<string, false>
  operation_boundaries: Record<string, boolean>
}
