When are worms permissible for eating?
According to Halacha one may eat worms which infest fruit after the fruit has fallen from the tree. Worms which are found in fruit before the fruit has fallen are forbidden. What is the difference between a worm which grows in a fruit fallen from a tree and a fruit which is still connected to the tree? A worm which infests a fruit which is still connected to the tree is considered to be teeming upon the earth, and the commands in the Torah forbid only that which has crawled upon the earth, as is written: "And this shall be impure for you amongst the insects which teem upon the earth" (Leviticus 11:29). Worms which grow in fruit which has already fallen from the tree teem in the fruit and not upon the earth; therefore they are permissible for consumption.
But if the worm has left the fruit and begun to crawl upon the ground, it is forbidden for consumption, as it, in fact, teems upon the earth.
The sages asked what the rule would be if a worm came out of a fruit, but before it began crawling upon the ground it died. Does it have to actually crawl upon the earth, or by its very exit from the fruit is it considered to have crawled upon the earth? They continued to ask: what is the rule if, while still alive, it left the fruit, and a person ate it before it had crawled upon the earth? And what is the rule if the worm crawled from one fruit to another, abutting it, without exiting and crawling upon the earth? Is it forbidden because it has left the fruit in which it grew, or, because in fact it did not crawl upon the earth, might it be permitted for consumption? (These doubts were not resolved in the Talmud.)
(Babylonian Talmud, Tractate Chulin 67b)