I wrote this up as a response to a question someone asked on Facebook:
If you're asking where the Torah came from, the answer is that it was too far in the past for us to know for sure, but here's a thumbnail sketch of a plausible reconstruction based on the bits and pieces we do know.
The stories in the Torah started out as oral myths. Many of them have parallels in Mesopotamian and, to a lesser extent, Egyptian mythology. At some point, scribes wrote down the myths, probably as exercises or for academic interest, and stored the writings in the various Temples' libraries. When the Assyrians conquered the Northern Kingdom, about half of the Israelites fled south into (the much smaller) Judea. The Israelite priests likely brought the libraries from the Temples at Dan and Bethel with them.
The Judean government now had to deal with the population doubling overnight. It had to find a way to knit together the native Judeans and the Israelite refugees into a single nation and to consolidate its control over the country. The solution was to "find" a book in the Temple library that drew on the old, well-known myths. Yoshiyahu had this book read to the people, and in it they found things they had not known. It provided the idea that all of the Judean and Israelite tribes were members of a single nation, with a single ancestor and a single God that was to be worshiped at a single place, the Temple in Yerushalayim.
The text and its myths were now an important part of Jewish identity and religion, but they were not yet authoritative. Someone, perhaps Ezra, combined all of the old written myths from the libraries (and by now the Yoshiyahu's book was also old) to produce a textual canon of the sacred myths.
In the late 2nd Temple period, there was friction between the Tzedukim and the Perushim. The Tzedukim were mainly the Temple priests, who were literate and had access to the written canon in the Temple library. They regarded the canon as an authoritative source of practice. They were also connected to the new Chashmonai dynasty, and later, to Rome, and many of them were urban aristocrats. The Perushim were the old rural aristocracy and the common people, who regarded the mimetic transition of tradition to be authoritative, as it had always been.
Eventually there was a merging of the Tzeduki and Perushi positions. The canon became TSBS, and the mimetic tradition became TSBP. Part of the gemara's project was to weave these traditions together.
The written Torah remained in flux through the medieval era, with several versions with minor variations in circulation. It was finalized by the masorties shortly before the advent of the printing press, and printed versions that sofrim could refer to froze that version as the final one.