Plot summary
Lieutenant Commander Data and Lieutenant Commander Geordi La Forge are enjoying a Sherlock Holmes holodeck program when they notice that a character programmed to be left-handed is right-handed. They ask Lieutenant Barclay (Dwight Schultz) to inspect the holodeck; as he checks the status of the Sherlock Holmes programs, he inadvertently activates the sentient Moriarty character (Daniel Davis). Moriarty wishes to escape the holodeck and was assured by the crew of the Enterprise that they would endeavor to find a way to do so, and is irritated by the lack of results. Captain Picard, along with Data and Barclay, assures Moriarty they are still working toward this goal, but Moriarty is dismissive.
Moriarty walks out the holodeck door and, inexplicably, continues to exist. He explains himself to the stunned Picard and Data by saying, "I think, therefore I am." He demands that the Enterprise crew enable his love interest, the Countess Regina Bartholomew (Stephanie Beacham)—another holodeck character, whom he has endowed with sentience—to leave the holodeck with him. When Picard hesitates, Moriarty takes control of the Enterprise and demands a solution.
While assisting La Forge, Data observes that La Forge's handedness is incorrect, just as they experienced earlier. Data determines that he, Picard, and Barclay remain inside the holodeck with Moriarty; everyone and everything that appears to be the Enterprise is part of a program Moriarty created. Picard realizes that he has unwittingly provided Moriarty with the command codes for the Enterprise. Moriarty takes control of the real Enterprise from within the simulation.
Picard creates a new simulation within the holodeck's simulation of a holodeck in order to convince Moriarty that he and Regina can be beamed into the real world, though they are only "beamed" within the simulation. Moriarty, unaware of the ruse, releases control of the ship back to Picard. He and the Countess use a shuttlecraft given to them by Commander Riker to leave the Enterprise and explore the galaxy. Picard ends the simulation, and Barclay extracts the memory cube from the holodeck and sets it in an extended memory device in order to provide Moriarty and the Countess a lifetime of exploration and adventure.
Picard suggests that the crew's reality may be a fabrication generated by "a little device sitting on someone's table." Barclay tells the computer to "end program" to test whether he is in a simulation.
Credits
Adapted from Wikipedia contributors, Ship in a Bottle (Star Trek: The Next Generation). Paragraphs and formatting adjusted; illustrations, reference markers, block quotations and non-story material omitted.