# Scope-commit patch for traceable-reqs.toml on the assembly worktree.
# 1) REQ-UPDATE-RUNNING-IMAGE-SURFACE: restore main's evidence map + discriminator note (verbatim from de5a44bc) and append an AMENDED note.
# 2) REQ-UPDATE-APPLY-RESTART-NOTICE: rewrite the evidence map to the #292 symbols.
# Byte-mode; preserves the file's own line terminator; refuses on anything but exactly one match per anchor.
import io, re, sys
path = sys.argv[1]
main_line_path = sys.argv[2]   # treqs-ris-main-line.txt (main's required_stages line for RIS, LF-terminated)
b = io.open(path, 'rb').read()
eol = b'\r\n' if b.count(b'\r\n') > 0 else b'\n'
assert not (b.count(b'\r\n') and b.count(b'\n') != b.count(b'\r\n')), "mixed terminators"
main_line = io.open(main_line_path, 'rb').read().rstrip(b'\r\n')
assert main_line.startswith(b'required_stages = ["impl", "unit", "int"]  # ACTIVATED F-025 item 1a')
ris_new = main_line + b' AMENDED releases#292 (111568f2): title re-keyed so the resident-web exception (REQ-RESIDENT-WEB-SKEW-DIAGNOSIS) is the only restart advice; the evidence map above is UNCHANGED by #292 (render_broker_image_line now also carries resident_web_skew_notice, informational otherwise).'
def patch(b, req_id, new_line):
    pat = re.compile(rb'(id = "' + re.escape(req_id) + rb'"' + re.escape(eol) + rb'title = "[^\r\n]*"' + re.escape(eol) + rb')(required_stages = [^\r\n]*)')
    m = list(pat.finditer(b)); assert len(m) == 1, (req_id, len(m))
    m = m[0]
    print(req_id, 'OLD:', m.group(2)[:100])
    return b[:m.start(2)] + new_line + b[m.end(2):]
b = patch(b, 'REQ-UPDATE-RUNNING-IMAGE-SURFACE', ris_new)
arn_new = (b'required_stages = ["impl", "unit"]  # ACTIVATED F-025 item 1b (todlando); RE-PINNED releases#292 (111568f2): '
    b'impl = resident_web_skew_notice(running, installed) (cli.rs) is the ONE predicate + notice shared by node status (render_broker_image_line) and apply: '
    b'Some(notice) only when the installed / signed-applied product version is >= 0.68.0 AND the live broker image reports < 0.68.0; compatible skew and an unknown (None) resident version yield None. '
    b'render_applied_message(version, product_version, resident) appends that notice, with resident sourced from resident_image_after_apply() (a live KIND_BROKER_IMAGE query AFTER the apply; a failed query is unknown, never stale). '
    b'restart_required_notice() and the unconditional F-025 tail are DELETED. '
    b'unit = resident_web_notice_is_shared_by_status_and_apply_only_for_incompatible_versions (table over (resident, installed, incompatible): both renderers contain the unavailable-routes / full-daemon-restart / stops-hosted-sessions / refresh-does-not-replace wording iff incompatible, and print none of it for compatible skew or None).')
b = patch(b, 'REQ-UPDATE-APPLY-RESTART-NOTICE', arn_new)
io.open(path, 'wb').write(b)
print('written', len(b), 'eol', eol)
