{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://polytraders.dev/schemas/AuditEnvelope.json",
  "title": "AuditEnvelope",
  "description": "Receipt written for every state change a developer or auditor would care about. builderCode and reason code are NEVER masked.",
  "type": "object",
  "required": [
    "envelope_id",
    "ts",
    "reason",
    "builder_code",
    "actor",
    "subject"
  ],
  "properties": {
    "envelope_id":  { "$ref": "_common.json#/$defs/EnvelopeId" },
    "ts":           { "$ref": "_common.json#/$defs/ISO8601" },
    "reason":       { "$ref": "_common.json#/$defs/ReasonCode" },
    "builder_code": { "$ref": "_common.json#/$defs/BuilderCode" },
    "actor": {
      "type": "object",
      "required": ["kind", "id"],
      "properties": {
        "kind": { "type": "string", "enum": ["bot", "operator", "system"] },
        "id":   { "type": "string", "minLength": 1 }
      }
    },
    "subject": {
      "type": "object",
      "description": "What this envelope is about. At least one of the *_id fields below is required.",
      "properties": {
        "portfolio_id": { "$ref": "_common.json#/$defs/PortfolioId" },
        "strategy_id":  { "$ref": "_common.json#/$defs/StrategyId" },
        "intent_id":    { "type": "string", "pattern": "^oi_[0-9a-zA-Z]{12,}$" },
        "signal_id":    { "type": "string", "pattern": "^sig_[0-9a-zA-Z]{12,}$" },
        "condition_id": { "$ref": "_common.json#/$defs/ConditionId" }
      },
      "anyOf": [
        { "required": ["portfolio_id"] },
        { "required": ["strategy_id"] },
        { "required": ["intent_id"] },
        { "required": ["signal_id"] },
        { "required": ["condition_id"] }
      ]
    },
    "scope_snapshot": {
      "type": "object",
      "description": "Required on STRAT_MARKET_IN_SCOPE / STRAT_MARKET_OUT_OF_SCOPE envelopes. Records the resolved condition ID set at the moment of change.",
      "required": ["mode", "resolved_condition_ids"],
      "properties": {
        "mode": { "type": "string", "enum": ["cluster", "manual"] },
        "resolved_condition_ids": {
          "type": "array",
          "items": { "$ref": "_common.json#/$defs/ConditionId" },
          "minItems": 0,
          "maxItems": 500
        }
      }
    }
  },
  "additionalProperties": false
}
