https://openacs.org/api-doc/proc-view?proc=site%5fnode%3a%3aclosest%5fancestor%5fpackageTake the package_id of the object, find the site_node for it, then use that tcl procedure to search the site map. The site map is an array stored in ram so it can peform the search much more quickly than querying each step from the database.
Also you should understand how to do a tree query in your database. See Hierarchal Data https://openacs.org/doc/openacs-5-0-4/tutorial-advanced.html