p = 'd2/_part_cleanup.sh'
s = open(p, encoding='utf-8', newline='').read()

old_start = s.index("            if [ \"$ncreated\" = \"$icreated\" ]")
old_end = s.index("            fi ;;", old_start) + len("            fi ;;")
old = s[old_start:old_end]

new = '''            # WHAT ESTABLISHES WHAT (doyle, 2026-09-13). Only a READABLE creation time that
            # DIFFERS establishes pid reuse -- i.e. that our process is gone and this pid now
            # belongs to a stranger. An unreadable creation time on either side establishes
            # NOTHING and stays UNREADABLE. A path or command-line mismatch ALONE does not make
            # our process gone: pid plus creation instant is the identity, so that case is
            # reported as LIVE with the mismatch named, never as GONE.
            if [ "$ncreated" = UNREADABLE ] || [ "$icreated" = UNREADABLE ]; then
              RESIDUE_UNREADABLE=$((RESIDUE_UNREADABLE + 1))
              echo "RECHECK role=$irole pid=$ipid state=UNREADABLE reason=creation-time-unreadable (recorded=[$icreated] now=[$ncreated]); neither reuse nor survival is established" >> "$R/residue.txt"
            elif [ "$ncreated" != "$icreated" ]; then
              RESIDUE_GONE=$((RESIDUE_GONE + 1))
              echo "RECHECK role=$irole pid=$ipid state=GONE-PID-REUSED (creation time differs: recorded=[$icreated] now=[$ncreated]; the pid answers, OURS is gone, and a bare pid match would have called this stranger residue: exe=[$nexe] cmd=[$ncmd])" >> "$R/residue.txt"
            elif [ "$nexe" = "$iexe" ] && [ "$ncmd" = "$icmd" ]; then
              RESIDUE_LIVE=$((RESIDUE_LIVE + 1))
              echo "RESIDUE role=$irole pid=$ipid created=$icreated exe=[$iexe] cmd=[$icmd] state=LIVE" >> "$R/residue.txt"
            else
              RESIDUE_LIVE=$((RESIDUE_LIVE + 1))
              echo "RESIDUE role=$irole pid=$ipid created=$icreated state=LIVE-FIELD-MISMATCH (same pid and same creation instant, so this IS our process and it is still running; the differing read is reported rather than resolved: exe recorded=[$iexe] now=[$nexe]; cmd recorded=[$icmd] now=[$ncmd])" >> "$R/residue.txt"
            fi ;;'''

s = s[:old_start] + new + s[old_end:]
open(p, 'w', encoding='utf-8', newline='').write(s)
print('R5 rule refined: readable-and-different creation time is the only thing that establishes reuse')
