UPDATE: More info: I'm triggering this script from a rule on the Sites directory. I'm wondering if there is a race condition where the site gets created under Sites but does not yet have it's documentLibrary node. That would cause what I'm seeing if this can happen.
UPDATE2: Yes something like this is happening because document.children is empty. If I don't fire the rule the site gets created just fine and has a documentLibrary. Why doesn't the site have all its children such as the documentLibrary when it first gets placed under Sites?
Because containers for tools don't get created until the tool is used the first time. It is the same reason there is not a wiki, discussion, or calendar folder when the site gets created.
The workaround is simple though. Modify your script to check to see if the documentLibrary node exists. If it does not, just create it. You can look up an existing documentLibrary folder in the node browser to make sure you get the type and name exactly right.