The Fourth Doctor has arrived on Gallifrey after receiving a mysterious summons from the Time Lords. Along the way, he has a precognitive vision about the President of the Time Lords being murdered.
As soon as the TARDIS materialises within the Citadel, it is surrounded by the Chancellry Guard. Their leader, Commander Hildred, reports to Castellan Spandrell. Both note that the TARDIS is a Type 40, which is no longer in service. Since the arrival is unauthorised, the soldiers are ordered to impound the TARDIS and arrest the occupant. The Doctor overhears this, and realises that the Time Lords did not summon him.
Spandrell goes to see Coordinator Engin in the Archives Section, leaving Hildred in charge. Hildred and his troops enter the TARDIS, but the Doctor manages to sneak out and make his way to a service lift that leads to the main tower. A soldier is present, and threatens to place the Doctor under arrest. However, the soldier is quickly killed by a phantom-like figure who disappears before the Doctor can identify him. The Doctor sends the lift on its way, in an attempt to fool the soldiers into thinking he has gone into the tower. All of this has been observed by the Doctor's old adversary, the Master, who is wearing a black hood that conceals his features. "Predictable as ever, Doctor," he mutters, before returning to the shadows.
Chancellor Goth arrives outside the TARDIS to see the situation for himself. Inside the TARDIS, the Doctor is watching a news broadcast by a reporter he recognises as Runcible (whom the Doctor nicknames "the Fatuous"), a classmate from his days at the Academy. It is revealed that the President is set to retire, and he is to name a successor. Runcible is talking to Cardinal Borusa, one of the Doctor's former teachers. He asks Borusa who the Presidential successor will be, but Borusa brushes him off.
The TARDIS is transducted to the museum within the Capitol, and the Doctor takes the opportunity to borrow a set of traditional Gallifreyan robes in order to maintain anonymity. At the same time several floors beneath the archive tower, the Master, severely emaciated as a result of a failed regeneration confers with an unseen accomplice. He says that the trap has been set, and they must make sure the Doctor dies quickly.
At the Panopticon, a Gallifreyan quasi-ceremonial chamber, the disguised Doctor briefly converses with Runcible before the outgoing President appears. The Doctor scans the area and notes a camera stationed on an unguarded catwalk. He also spots a sniper rifle next to the camera. The Doctor fights his way to the catwalk, warning that the President is about to be killed. Unbeknownst to the Doctor the assassin is actually among the delegates. He pulls out a pistol when the Doctor reaches the camera level and shoots the President dead. The crowd sees the Doctor on the catwalk firing the sniper rifle (in an attempt to stop the assassin) and assume he is the killer.
Under interrogation (including torture) the Doctor maintains his innocence and that he had been 'framed'. Eventually, Spandrell starts to believe him and orders Engin to assist him in an independent investigation. Meanwhile, Goth and Borusa debate over the Doctor's impending trial. Goth notes that the election for a new President will occur in forty-eight hours, and he is eager to see the Doctor executed before then since it is customary for Presidents to pardon all political prisoners on assuming office. On the other hand wishes to ensure that proper standards of jurisprudence are maintained. The Doctor surprises everyone by invoking Article 17: he will run for President, which guarantees liberty for those running for Presidential office during the course of an election. The Master and his assassin are not pleased with this turn of events.
The Doctor returns to the scene of the crime with Spandrell. They discover that the sight on the Doctor's rifle was distorted, making it virtually impossible for this weapon to have killed the President. They decide to check the recorded proceedings of the event, conveniently still stored in the camera. The Master, hastening to extract the record himself, kills Runcible's technician using his TCE (Tissue Compression Eliminator). Runcible attempts to take the tape from the camera to the archives for review, but he is killed by a spear to the back.
The Doctor realises that the Master sent the Doctor the premonition of the assassination through the Matrix, a vast electronic neural network which can turn thought patterns into virtual reality. He decides to enter the Matrix as a means of tracking the Master. Engin warns him that if he dies in the virtual world, he will die in the real world as well.
The Doctor enters the Matrix and finds himself in a forbidding landscape of crumbling white cliffs and sparse vegetation. The disembodied laughter of some unknown presence echoes off the canyon walls. The Doctor is then engaged in a series of surreal nightmare episodes. First he nearly walks into the open jaws of a hungry crocodile, which simply disappears into thin air. He is then attacked by a masked samurai warrior and falls from a cliff into unconsciousness. He revives upon an outdoor operating table with a masked surgeon standing over him. The surgeon tries to inject him with a substance from an extremely large hypodermic needle. The Doctor pushes the surgeon away and runs off to find himself in the midst of a World War I battle. Shell and machine gun fire is heard and gas canisters explode all around. A soldier and his horse stumble out of the smoke wearing gas masks. The Doctor runs bewildered until he comes upon a train track, the rail of which closes upon one of his boots and traps him. A group of three masked men appear and one attempts to run him down with a mine train.
The train disappears before hitting the Doctor and he works his foot free. The Doctor realizes that his surroundings are but an illusion and tries to deny their existence, but passes out from the strain. Recovering consciousness he becomes aware of the two large black eyes of his unknown adversary in the side of a cliff, telling him that he is the creator of this world and that there is no escape. The Doctor, dehydrated and thirsty, hears the sound of running water, but when he attempts to dig into the ground to locate its source he is greeted by a red-nosed clown peering through a window, laughing manically. He is then strafed by machine gun fire by a masked pilot in a biplane, eventually receiving a bullet wound in the leg. The Doctor tries to deny the existence of the wound, and it disappears. However, the disembodied voice of the assassin reminds him that this is his reality, and his rules, and the wound reappears. The Doctor declares that he will then fight the assassin in his reality.
In the real world, Engin tells Spandrell that the Doctor’s adversary is using a lot of energy to maintain the virtual environment, so the Doctor can defeat him if he provides an adequate distraction.
Inside the Matrix, the dry barren virtual environment merges into a thick, sticky jungle, and the assassin soon appears dressed as a big game hunter, a mesh veil obscuring his face. The assassin concludes that the Doctor will need water, and, leaving his backpack behind him, goes off to contaminate the local supply with poison from a small bottle. The Doctor finds the assassin's backpack and takes a grenade and some twine, setting up a makeshift booby trap. The assassin returns and trips it, setting off an explosion which wounds him in the abdomen.
Fearing that his protégé might lose, the Master sends a hypnotised guard to kill the Doctor's physical form.
Back inside the Matrix, the Doctor continues to be hunted through the virtual jungle. Coming to the pool of water, he finds dead floating fish and an empty bottle and realises that the water has been poisoned. He finds a small amount of uncontaminated water and drinks it through a reed, then uses the reed and some thorns off of a nearby tree to make a blowgun, dipping the ends of the darts into the remnants of the poison from the bottle. The Doctor climbs up into a tree and shoots the assassin in the leg with a dart. The assassin fires his rifle and hits the Doctor in the arm, causing him to fall out of the tree. Ripping his pants leg open to reveal a potentially fatal wound, the assassin injects himself with an antidote while the Doctor again escapes.
In the real world, the hypnotised guard makes his way to the Matrix chamber, but Spandrell manages to shoot him before he can sabotage the Matrix link.
Back in the Matrix, the Doctor has made it to a gas-filled marsh, where the assassin reveals his true identity: Chancellor Goth. Goth tries to shoot the Doctor but ignites the marsh gas, setting himself on fire. Goth falls into the water to extinguish the spreading flames. The Doctor comes out of hiding to confront him, but is caught by surprise by Goth and tackled. Intense hand-to-hand combat ensues, with Goth seeming to gain the upper hand. He attempts to drown the Doctor.
However, the strain of fighting and keeping up the virtual reality overcomes Goth. The Doctor breaks free and hits Goth over the head with a small tree branch. The Master, realising that Goth has been effectively defeated, decides to hedge his bets and tries to trap the Doctor in the Matrix by overloading the neuron fields, even though this will kill Goth. Engin manages to get the Doctor out of the Matrix, but Goth is fatally burnt. The Master then injects himself with a hypodermic needle.
The Doctor and Spandrell, accompanied by soldiers, manage to make their way to the chamber where the Master and Goth were accessing the Matrix. They find the Master slumped in a chair without a pulse and Goth dying. Goth reveals that he found the Master, near death, on Tersurus. The Master was nearing the end of his twelfth and final regeneration. Goth went along with his schemes mainly for power: he knew the President had no intention of naming him as a successor, but if a new election was held, he would be the front runner. Before he dies, Goth warns that the Master has a doomsday plan.
When Spandrell relates the story to Borusa, the Cardinal orders that a cover story ('we must adjust the truth') be created to maintain confidence in the Time Lords and their leadership. The official story will be that the Master arrived in secret to assassinate the President, and Goth heroically tracked him down and killed him but perished in the attempt. The charge against the Doctor will be dropped on condition that he leave Gallifrey.
Attempting to piece together what the Master and Goth were planning, the Doctor inquires as to what becoming the President entails. He is told that the President has access to the symbols of office: the Sash and Great Key of Rassilon. As Engin plays the records of the Old Time, which describes how Rassilon found the Eye of Harmony within the "black void", the Doctor realises these objects are not merely ceremonial. The Doctor inspects the hypodermic needle, and realises that it contained a neural inhibitor which mimics induces a death-like state, but not death itself, and that the Master is still alive.
The Doctor, Spandrell, and Engin arrive at the morgue, to find that the Master has revived and killed Hildred. Armed with Hildred’s staser pistol, the Master seizes the Sash from the President's corpse and traps the three in the morgue. The Doctor explains what he has deduced: that the Eye is actually the nucleus of a black hole, an inexhaustible energy source that Rassilon captured to power Gallifrey, and the Sash and Key are its control devices. The Doctor deduces that the Master was planning to steal this energy to gain a new cycle of regenerations. However, if the Eye is disrupted, Gallifrey will be destroyed and a hundred other worlds will be consumed in a chain reaction.
Inside the Panopticon, the Master makes his way to the obelisk containing the Eye. He unhooks the coils that connect it to Gallifrey, and is prepared to access the energy. The Doctor makes his way to the Panopticon via a service shaft. The Citadel begins to quake, and cracks appear in the floor. The Doctor and the Master fight, until the Master loses his footing and falls into a chasm. The Doctor reconnects the coils and saves Gallifrey, although half the city is in ruins and many lives have been lost.
The Doctor is now free to return to his TARDIS. He bids farewell to Borusa, Spandrell, and Engin, but also warns that the Master may not be dead. He had harvested some energy from the obelisk before he was stopped, and may have been able to channel it. As the Doctor’s TARDIS dematerialises, Spandrell and Engin witness the Master sneak into his own TARDIS – disguised as a grandfather clock – and make his escape.