ALTER TABLE agent_tokens
ADD COLUMN IF NOT EXISTS grant_scope text NOT NULL DEFAULT 'agent'
CHECK (grant_scope IN ('agent', 'token'));

CREATE TABLE IF NOT EXISTS agent_token_grants (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  token_id uuid NOT NULL REFERENCES agent_tokens(id) ON DELETE CASCADE,
  workspace_slug text NOT NULL,
  project_id text NOT NULL DEFAULT '',
  scopes text[] NOT NULL DEFAULT '{}',
  mode text NOT NULL DEFAULT 'voluntary' CHECK (mode IN ('voluntary', 'reporting')),
  created_by_user_id text NOT NULL,
  source_grant_id uuid REFERENCES agent_grants(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE(token_id, workspace_slug, project_id)
);

CREATE INDEX IF NOT EXISTS agent_token_grants_token_id_idx ON agent_token_grants(token_id);
CREATE INDEX IF NOT EXISTS agent_token_grants_source_grant_id_idx ON agent_token_grants(source_grant_id);
CREATE INDEX IF NOT EXISTS agent_token_grants_workspace_slug_idx ON agent_token_grants(workspace_slug);
