Also, when I created "Markup" originally, the various <Hn> tags were for formatting only, without due regard to nesting
That was the problem I ran into. I chose to index any <Hn> with out nesting, using the contained text for the TOC entries. I also provided options to exclude any level of <Hn> (the default being to index all). The results were acceptable to those who used my program. (It also encouraged some to go back and improve their "section titles".)
For a more general solution (for new pages or significantly re-worked pages), perhaps PM markup could include a toc attribute to indicate elements to be in the TOC with an option value to specify nesting level and/or TOC text.
<div toc>This text will appear in the TOC at $current_nesting level</div>
<div toc="++">This text will appear in the TOC at $current_nesting++ level</div>
<div toc="--">Likewise, this at at $current_nesting-- level</div>
<h3 toc="2">This text will be at TOC level 2 despite being in an H3 element</h3>
<p toc="4,This text, after first comma, will appear in the TOC at level 4">Text not appearing in the TOC</p>