Given a directed graph of agent dependencies, write an algorithm to detect potential deadlocks in a multi-agent system.
Treat each edge A -> B as agent A waiting for or depending on agent B. Implement detect_deadlocks(graph), where graph is a dictionary mapping each agent ID to a list of dependent agent IDs. Return a sorted list of every agent that belongs to a directed cycle, including self-loops. Agents that merely lead into a cycle are not deadlocked. Assume every referenced agent appears as a graph key.
def detect_deadlocks(graph):