import io

p = 'crates/spt/tests/webserve_cross_node_e2e.rs'
s = io.open(p, encoding='utf-8', newline='').read()
start = s.index("    // ══ ARM 6c — REGISTER-ON-MY-BEHALF")
end = s.index("    // ══ ARM 7 —")

new = r'''    // ══ ARM 6c — REGISTER-ON-MY-BEHALF, END TO END through BOTH daemons ════
    // [int->REQ-NOW-SIGNAL-FILE-ACCESS-HELPER]
    //
    // The case #17 was minted for: the user who quoted a filepath is on the
    // OTHER node, so the file is there and the registration has to happen
    // there. Driven the way production drives it and no other way — ONE real
    // `spt send` from a Gateway on B to an endpoint hosted on A, its body
    // quoting an absolute path that exists on B — and then WAITED FOR on A's
    // helperline store, which is the observable proving the ingress caller
    // fired after delivery and that `request_serve_for` went daemon to daemon.
    //
    // NOTHING HERE CALLS `request_serve_for`. Its client lives INSIDE the
    // receiving daemon's WAN ingress, exactly as the fetch path's client does;
    // an arm that drove it from the test process was measuring a client that
    // does not exist in production, and it ate the brain IPC read deadline
    // saying so. A deadline I would have to widen to make my own test shape
    // work is the test being wrong about where the client lives.
    //
    // WHAT IS NOT HERE, AND WHERE IT WENT. The five authorization conjuncts are
    // `spt_store::msgid::user_authorized_serve_for` — pure, with one unit cell
    // per conjunct. Four of them CANNOT be produced end to end at all: the
    // receiving daemon only ever asks for a path the user's own words carried,
    // addressed to that message's own target, under that message's own id, so
    // driving them from here would mean forging a request the product cannot
    // make. (iii) is the exception and stays, because it is a DIFFERENT gate —
    // the receiver's own "only a user-msg triggers this" — and nothing else
    // exercises it.
    {
        let quoted = home_b.path().join("quoted-by-the-user.md");
        let quoted_bytes = b"# the file the user pointed at\n";
        std::fs::write(&quoted, quoted_bytes).unwrap();
        let quoted_text = quoted.to_str().unwrap().to_string();
        let words = format!("have a look at {quoted_text} when you get a moment");

        // The two ends' perches. A's is a bare directory ON PURPOSE: what WAN
        // ingress requires of a target is somewhere to spool, and no claim in
        // this arm is about endpoint bringup. The delivery still runs the whole
        // product path — access gate, replay check, user-msg restamp gate,
        // spool — so what is bypassed is the perch's CREATION ceremony and
        // nothing on the message's road.
        std::fs::create_dir_all(home_a.path().join("owlery").join(AUDIENCE_ENDPOINT))
            .expect("the audience's perch on A");
        typed_perch(home_b.path(), SENDER_GATEWAY, spt_proto::event::GATEWAY_TAG);
        typed_perch(home_b.path(), SENDER_AGENT, "live");

        let audience_perch = home_a.path().join("owlery").join(AUDIENCE_ENDPOINT);
        let helper_lines = || spt_store::helperline::read_at(&audience_perch);
        let registry_text = || {
            std::fs::read_to_string(spt_store::perch::serving_registry_file_in(home_b.path()))
                .unwrap_or_default()
        };
        assert!(helper_lines().is_empty(), "PRECONDITION: no helper record before this arm");
        assert!(
            !registry_text().contains("quoted-by-the-user"),
            "PRECONDITION: B has not registered the quoted file"
        );

        // ── (iii) AN AGENT'S message ───────────────────────────────────────
        // Same node, same target, same words, same absolute path. The ONE
        // varied property is WHO AUTHORED IT, and only a `user-msg` — the
        // envelope whose authorship the sending daemon proved to be its human —
        // is an authority ADR-0058 Amendment 1 will act on. Sent FIRST and
        // judged LAST, because its whole claim is a zero: the positive below
        // raises the same counters through the same pipe, so this zero cannot
        // be the zero of an emitter that was never alive.
        let agent_send = send_as(&spt, home_b.path(), SENDER_AGENT, AUDIENCE_ENDPOINT, &words, false);
        eprintln!(
            "=== (iii) agent send (B->A) ===\nstatus={}\n{}\n--stderr--\n{}",
            agent_send.status,
            String::from_utf8_lossy(&agent_send.stdout),
            String::from_utf8_lossy(&agent_send.stderr)
        );
        assert!(
            agent_send.status.success(),
            "an agent's message is DELIVERED — it is simply not acted on: {agent_send:?}"
        );

        // ── (vi) THE POSITIVE ──────────────────────────────────────────────
        let user_send = send_as(&spt, home_b.path(), SENDER_GATEWAY, AUDIENCE_ENDPOINT, &words, true);
        eprintln!(
            "=== (vi) user send (B->A) ===\nstatus={}\n{}\n--stderr--\n{}",
            user_send.status,
            String::from_utf8_lossy(&user_send.stdout),
            String::from_utf8_lossy(&user_send.stderr)
        );
        assert!(user_send.status.success(), "the user's message is delivered: {user_send:?}");
        assert!(
            !String::from_utf8_lossy(&user_send.stderr).contains("USER_MSG_RESTAMP"),
            "PRECONDITION: the Gateway's user-msg was NOT degraded on the way out — a \
             restamped send would make every assertion below vacuous:\n{}",
            String::from_utf8_lossy(&user_send.stderr)
        );

        // The helper request runs on its OWN THREAD, after delivery, and crosses
        // the wire — so the observable is waited for rather than read once.
        let deadline = Instant::now() + Duration::from_secs(90);
        let line = loop {
            if let Some(line) = helper_lines().into_iter().next() {
                break line;
            }
            assert!(
                Instant::now() < deadline,
                "A's helperline never gained the fetch line — the ingress caller did not \
                 complete a round trip to B.\n--- A ---\n{}\n--- B ---\n{}",
                common::daemon_stderr_panel(&home_a.path().join("brain-a.stderr.log")),
                common::daemon_stderr_panel(&home_b.path().join("brain-b.stderr.log"))
            );
            std::thread::sleep(Duration::from_millis(250));
        };
        assert_eq!(line.path, quoted_text, "the record names the path the user quoted");
        assert!(!line.msg_id.is_empty(), "and the message it came from, for the audit trail");
        let served_name = line
            .url
            .rsplit('/')
            .next()
            .expect("the minted URL ends in the served name")
            .to_string();

        // B REGISTERED it, and registered it as the amendment says: a live
        // REFERENCE (the user said look at this, not keep this as it was) with
        // the helper's lifetime, the audience, and the message as its origin.
        let registry = spt_store::serving::ServingRegistry::load_at(
            &spt_store::perch::serving_registry_file_in(home_b.path()),
        )
        .unwrap();
        let entry = registry.get(&served_name).expect("B holds the entry it minted");
        assert_eq!(entry.kind, spt_store::serving::ServedKind::File, "a live reference, not a snapshot");
        assert_eq!(entry.ttl_ms, Some(spt_store::serving::HELPER_ENTRY_TTL_MS), "24h");
        assert_eq!(entry.audience.as_deref(), Some(AUDIENCE_ENDPOINT));
        assert_eq!(
            entry.origin.as_deref(),
            Some(line.msg_id.as_str()),
            "origin is the message short-ID — the audit trail back to the user's own words"
        );
        eprintln!(
            "F1_ARM=vi verdict=registered kind={:?} ttl_ms={:?} audience={:?} origin={:?} msg_id={}",
            entry.kind, entry.ttl_ms, entry.audience, entry.origin, line.msg_id
        );

        // ── (vii) THE AUDIENCE'S NODE PULLS IT ─────────────────────────────
        // The end the requirement is written about: the file is on B, the user
        // is on B, and the endpoint that was told about it is on A.
        let (status, _, body) = http(port_a, "GET", &format!("/{OWNER_LABEL}/f/{served_name}"), &[]);
        assert_eq!(status, 200, "the audience's node fetches what was registered for it");
        assert_eq!(body, quoted_bytes, "byte-equal to the file the user pointed at");
        eprintln!(
            "F1_ARM=vii verdict=fetched status={status} bytes={} served_name={served_name}",
            body.len()
        );

        // ── (iii), judged ──────────────────────────────────────────────────
        // The agent's message quoted the SAME path, so had it been acted on it
        // would have left a SECOND helper line and a second registration under
        // the same name — which is why the COUNT is the assertion rather than
        // the presence.
        let lines = helper_lines();
        let registrations = registry_text().matches("quoted-by-the-user").count();
        assert_eq!(
            lines.len(),
            1,
            "(iii) only the USER's message produced a helper record; the agent's added none: {lines:?}"
        );
        assert_eq!(
            registrations, 1,
            "(iii) and B registered the file exactly once — for the user, not for the agent"
        );
        eprintln!(
            "F1_ARM=iii verdict=refused helper_lines={} registrations={registrations} \
             case=agent-authored message fires no request",
            lines.len()
        );
    }

'''

s = s[:start] + new + s[end:]
io.open(p, 'w', encoding='utf-8', newline='').write(s)
print("ok")
