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

# ---------------------------------------------------------------------------- 1. the gate
gate = [
"# ---- is the captured identity set USABLE AS EVIDENCE OF ABSENCE? ---------------",
"# (doyle's second admission blocker, 2026-09-13.) Re-querying the rows we happen to have only",
"# proves something about the rows we happen to have. A capture INTERRUPTED after the supervisor",
"# row leaves one plausible-looking record; that pid is later absent, every tracked identity then",
"# reads GONE, and cleanup declares CLEAR while an UNRECORDED BRAIN is still running. The gap is",
"# not in the re-query, it is in trusting a partial capture.",
"#",
"# So a capture may support CLEAR only when ALL of these hold, and each is checked, not assumed:",
"#   the capture command exited 0;",
"#   EXACTLY ONE completion marker `IDENT_PROBE=OK tracked=N` is present;",
"#   N equals the number of IDENT rows actually written;",
"#   every row carries a numeric pid, a READABLE creation timestamp, a non-empty executable and a",
"#     non-empty command line.",
"# Anything else is UNREADABLE -- INCLUDING the case where every recorded pid is now absent.",
"ts_readable() { # a timestamp we can compare, not merely a string that is not the word UNREADABLE",
"  case \"$1\" in",
"    [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]*Z) return 0 ;;",
"    *) return 1 ;;",
"  esac",
"}",
"capture_is_complete() { # -> 0 when the recorded set may support a CLEAR verdict",
'  local f="$R/run-identities.txt"',
'  CAPTURE_INTEGRITY="unset"',
'  [ -f "$f" ] || { CAPTURE_INTEGRITY="no capture file"; return 1; }',
'  if [ "${IDENT_CAPTURE_RC:-1}" -ne 0 ]; then CAPTURE_INTEGRITY="the capture command exited ${IDENT_CAPTURE_RC:-unknown}"; return 1; fi',
"  local marks rows tracked",
"  marks=$(grep -c '^IDENT_PROBE=OK tracked=' \"$f\"); case \"$marks\" in (''|*[!0-9]*) marks=0 ;; esac",
"  rows=$(grep -c '^IDENT role=' \"$f\"); case \"$rows\" in (''|*[!0-9]*) rows=0 ;; esac",
'  if [ "$marks" -ne 1 ]; then CAPTURE_INTEGRITY="expected exactly one IDENT_PROBE=OK completion marker, found $marks"; return 1; fi',
"  tracked=$(sed -n 's/^IDENT_PROBE=OK tracked=BSLASH([0-9][0-9]*BSLASH).*/BSLASH1/p' \"$f\" | tail -1)",
"  case \"$tracked\" in (''|*[!0-9]*) CAPTURE_INTEGRITY=\"the completion marker carries no readable count\"; return 1 ;; esac",
'  if [ "$rows" -ne "$tracked" ]; then CAPTURE_INTEGRITY="the capture says it tracked $tracked processes but wrote $rows rows"; return 1; fi',
'  if [ "$rows" -eq 0 ]; then CAPTURE_INTEGRITY="no identity rows were written"; return 1; fi',
"  local line lpid lcreated lexe lcmd",
"  while IFS= read -r line; do",
"    lpid=$(printf '%s' \"$line\" | sed -n 's/^IDENT .* pid=BSLASH([0-9][0-9]*BSLASH) .*/BSLASH1/p')",
"    lcreated=$(printf '%s' \"$line\" | sed -n 's/^IDENT .* created=BSLASH([^ ]*BSLASH) .*/BSLASH1/p')",
"    lexe=$(printf '%s' \"$line\" | sed -n 's/^IDENT .* exe=BSLASH[BSLASH(.*BSLASH)BSLASH] cmd=BSLASH[.*BSLASH]$/BSLASH1/p')",
"    lcmd=$(printf '%s' \"$line\" | sed -n 's/^IDENT .* cmd=BSLASH[BSLASH(.*BSLASH)BSLASH]$/BSLASH1/p')",
'    [ -n "$lpid" ] || { CAPTURE_INTEGRITY="a row carries no numeric pid"; return 1; }',
'    ts_readable "$lcreated" || { CAPTURE_INTEGRITY="pid $lpid has an unreadable creation timestamp [$lcreated]"; return 1; }',
'    [ -n "$lexe" ] || { CAPTURE_INTEGRITY="pid $lpid has an empty executable path"; return 1; }',
'    [ -n "$lcmd" ] || { CAPTURE_INTEGRITY="pid $lpid has an empty command line"; return 1; }',
"  done < <(grep '^IDENT role=' \"$f\")",
'  CAPTURE_INTEGRITY="complete: $rows rows, marker count $tracked, all fields readable"',
"  return 0",
"}",
"",
]
anchor = "# ---- state-aware cleanup, entered EXACTLY ONCE"
i = s.index(anchor)
s = s[:i] + "\n".join(gate).replace("BSLASH", BS) + s[i:]

# ---------------------------------------------------------------------------- 2. use the gate
old = """    else
      : > "$R/residue.txt\""""
new = """    else
      # THE GATE FIRST. Its verdict is independent of what the re-query finds: an incomplete
      # capture cannot support CLEAR even if every pid it did record is now absent.
      CAPTURE_USABLE=no
      if capture_is_complete; then
        CAPTURE_USABLE=yes
        record "  IDENTITY_CAPTURE_INTEGRITY=OK ($CAPTURE_INTEGRITY)"
      else
        record "  IDENTITY_CAPTURE_INTEGRITY=INCOMPLETE ($CAPTURE_INTEGRITY)"
        record "  An incomplete capture cannot show that a process is gone -- only that a row we"
        record "  happen to hold is gone. Whatever this run started that was never recorded is"
        record "  UNATTRIBUTED, so the residual state is UNREADABLE no matter what follows."
      fi
      : > "$R/residue.txt\""""
assert s.count(old) == 1, 'gate call site'
s = s.replace(old, new)

# ---------------------------------------------------------------------------- 3. enforce it
old2 = """      if [ "$RESIDUE_UNREADABLE" -gt 0 ]; then
        cfail "$RESIDUE_UNREADABLE tracked identity/identities could not be re-queried. UNREADABLE is not CLEAR: this run cannot state that its processes are gone."
      fi"""
new2 = """      if [ "$RESIDUE_UNREADABLE" -gt 0 ]; then
        cfail "$RESIDUE_UNREADABLE tracked identity/identities could not be re-queried. UNREADABLE is not CLEAR: this run cannot state that its processes are gone."
      fi
      if [ "$CAPTURE_USABLE" != yes ]; then
        RESIDUE_UNREADABLE=$((RESIDUE_UNREADABLE + 1))
        cfail "the identity capture was INCOMPLETE ($CAPTURE_INTEGRITY), so the recorded rows cannot support a clean verdict: residual state is UNREADABLE. An interrupted capture that omitted a child would otherwise read as CLEAR once its one recorded pid went away."
      fi"""
assert s.count(old2) == 1, 'enforce'
s = s.replace(old2, new2)

# ---------------------------------------------------------------------------- 4. timestamps
old3 = '            if [ "$ncreated" = UNREADABLE ] || [ "$icreated" = UNREADABLE ]; then'
new3 = '            if ! ts_readable "$ncreated" || ! ts_readable "$icreated"; then'
assert s.count(old3) == 1, 'ts gate'
s = s.replace(old3, new3)
old4 = 'echo "RECHECK role=$irole pid=$ipid state=UNREADABLE reason=creation-time-unreadable (recorded=[$icreated] now=[$ncreated]); neither reuse nor survival is established"'
new4 = 'echo "RECHECK role=$irole pid=$ipid state=UNREADABLE reason=creation-time-not-a-readable-timestamp (recorded=[$icreated] now=[$ncreated]); an empty or malformed value establishes NEITHER reuse NOR survival"'
assert s.count(old4) == 1, 'ts message'
s = s.replace(old4, new4)

# ---------------------------------------------------------------------------- 5. capture rc + ledger
old5 = '  exits "identity_capture_${when}_EXIT=$rc"'
new5 = '  IDENT_CAPTURE_RC=$rc\n  exits "identity_capture_${when}_EXIT=$rc"'
assert s.count(old5) == 1, 'capture rc'
s = s.replace(old5, new5)

old6 = ('    echo "  tracked_process_identities: live=${RESIDUE_LIVE:-0} gone=${RESIDUE_GONE:-0} '
        'unreadable=${RESIDUE_UNREADABLE:-0} (re-queried by pid + creation time + executable + command line)"')
new6 = (old6 + '\n'
        '    echo "  identity_capture=${CAPTURE_USABLE:-not-attempted} (${CAPTURE_INTEGRITY:-no capture was needed}) '
        '-- an incomplete capture can never support CLEAR"')
assert s.count(old6) == 1, 'ledger line'
s = s.replace(old6, new6)
open(p, 'w', encoding='utf-8', newline='').write(s)

# ---------------------------------------------------------------------------- 6. globals
p = 'd2/_part1_header.sh'
s = open(p, encoding='utf-8', newline='').read()
a = "RESIDUE_UNREADABLE=0             # attribution missing or unreadable: NEVER read as clean"
assert s.count(a) == 1
s = s.replace(a, a + "\nIDENT_CAPTURE_RC=1               # the capture command's own exit; 1 until it has run\n"
                    "CAPTURE_USABLE=no                # a capture supports CLEAR only when proven complete\n"
                    "CAPTURE_INTEGRITY=''             # why it is or is not usable, in words")
open(p, 'w', encoding='utf-8', newline='').write(s)
print('capture-integrity gate, timestamp validation and ledger field installed')
