{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://awooop.platform/contracts/v1/runtime_run_state",
  "title": "Runtime Run State Contract",
  "description": "AwoooP Run 狀態機合約 — 定義 run lifecycle 的有效狀態與轉換規則",
  "type": "object",
  "required": ["run_id", "project_id", "agent_id", "state"],
  "additionalProperties": false,
  "properties": {
    "run_id": {
      "type": "string",
      "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
      "description": "Run UUID（UUID v7 格式）"
    },
    "project_id": {
      "type": "string",
      "pattern": "^[a-z0-9][a-z0-9_-]{1,63}$",
      "description": "所屬租戶"
    },
    "agent_id": {
      "type": "string",
      "description": "執行此 run 的 agent"
    },
    "state": {
      "type": "string",
      "enum": [
        "pending",
        "running",
        "waiting_approval",
        "waiting_tool",
        "completed",
        "failed",
        "cancelled",
        "timeout"
      ],
      "description": "Run 當前狀態（FSM）"
    },
    "trace_id": {
      "type": "string",
      "description": "W3C traceparent-compatible trace ID"
    },
    "parent_run_id": {
      "type": ["string", "null"],
      "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
      "description": "父 run ID（sub-agent 場景）"
    },
    "trigger": {
      "type": "object",
      "required": ["trigger_type"],
      "additionalProperties": false,
      "properties": {
        "trigger_type": {
          "type": "string",
          "enum": ["channel_event", "schedule", "api", "sub_agent", "retry"]
        },
        "channel_event_id": {"type": "string"},
        "schedule_id": {"type": "string"},
        "triggered_by": {"type": "string"}
      },
      "description": "觸發此 run 的事件來源"
    },
    "input_sha256": {
      "type": "string",
      "pattern": "^[0-9a-f]{64}$",
      "description": "Run 輸入 payload 的 SHA-256（artifact integrity）"
    },
    "output_sha256": {
      "type": ["string", "null"],
      "pattern": "^[0-9a-f]{64}$",
      "description": "Run 輸出結果的 SHA-256（完成後填入）"
    },
    "started_at": {
      "type": ["string", "null"],
      "format": "date-time",
      "description": "run 開始執行時間"
    },
    "completed_at": {
      "type": ["string", "null"],
      "format": "date-time",
      "description": "run 完成/失敗時間"
    },
    "timeout_at": {
      "type": ["string", "null"],
      "format": "date-time",
      "description": "run 預計超時時間"
    },
    "error_code": {
      "type": ["string", "null"],
      "description": "失敗錯誤碼（state=failed 時填入）"
    },
    "cost_usd": {
      "type": ["number", "null"],
      "minimum": 0,
      "description": "此 run 累計 LLM 費用（USD）"
    },
    "step_count": {
      "type": "integer",
      "minimum": 0,
      "default": 0,
      "description": "已執行 LLM step 數"
    }
  }
}
