import io

p = 'crates/spt/tests/webserve_cross_node_e2e.rs'
s = io.open(p, encoding='utf-8', newline='').read()
assert '\r\n' not in s

start = s.index("        // ── (iii) AN AGENT'S message ")
end = s.index("    // ══ ARM 7 —")

new = r'''        // ── (iii) AN AGENT'S message — the receiver's own gate ─────────────
        // Same node, same target, same words, same absolute path. The ONE
        // varied property is WHO AUTHORED IT: 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.
        //
        // Judged FIRST, and its zero is not a bare zero: the arm WAITS for A's
        // own decline breadcrumb, so what is asserted is "the ingress helper ran
        // and declined", not "nothing has happened yet". That ordering is also
        // what makes the caller's falsifier readable — with `request_serve_for`
        // no-opped this arm still passes, because the decline happens before the
        // caller is ever reached, and (vi) below then dies at its wait.
        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:?}"
        );
        let declined_started = Instant::now();
        let declined_deadline = declined_started + Duration::from_secs(60);
        let declined_marker = "outcome=declined";
        while !dae_a.stderr().contains(declined_marker) {
            assert!(
                Instant::now() < declined_deadline,
                "A never said why it declined the agent's message in {:?} — without that \
                 line this arm's zero cannot be told from an ingress helper that never \
                 ran.\n--- A ---\n{}",
                declined_started.elapsed(),
                common::daemon_stderr_panel(&home_a.path().join("brain-a.stderr.log"))
            );
            std::thread::sleep(Duration::from_millis(200));
        }
        let declined_lines: Vec<String> = dae_a
            .stderr()
            .lines()
            .filter(|line| line.contains(declined_marker))
            .map(str::to_owned)
            .collect();
        let lines_after_iii = helper_lines();
        let registrations_after_iii = registry_text().matches("quoted-by-the-user").count();
        assert!(
            lines_after_iii.is_empty(),
            "(iii) an agent-authored message leaves NO helper record: {lines_after_iii:?}"
        );
        assert_eq!(
            registrations_after_iii, 0,
            "(iii) and B registered nothing on its behalf"
        );
        eprintln!(
            "F1_ARM=iii verdict=refused helper_lines={} registrations={registrations_after_iii} \
             waited_ms={} case=agent-authored message fires no request; A said: {}",
            lines_after_iii.len(),
            declined_started.elapsed().as_millis(),
            declined_lines.last().map(String::as_str).unwrap_or("<none>")
        );

        // ── (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. The
        // panel carries what both stores held when the wait expired: that is what
        // names the mechanism (a decline reason, a refusal, or silence) instead of
        // leaving a bare timeout.
        let wait_started = Instant::now();
        let deadline = wait_started + 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 in {:?} — the ingress caller did \
                 not complete a round trip to B.\nhelper_lines={} registrations={}\n\
                 --- A ---\n{}\n--- B ---\n{}",
                wait_started.elapsed(),
                helper_lines().len(),
                registry_text().matches("quoted-by-the-user").count(),
                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"
        );
        // Both messages quoted the SAME path, so a fired (iii) would have left a
        // SECOND record here: the count is the assertion, not the presence.
        assert_eq!(
            helper_lines().len(),
            1,
            "exactly ONE helper record exists — the user's; the agent's added none"
        );
        assert_eq!(
            registry_text().matches("quoted-by-the-user").count(),
            1,
            "and B registered the file exactly once — for the user, not for the agent"
        );
        eprintln!(
            "F1_ARM=vi verdict=registered kind={:?} ttl_ms={:?} audience={:?} origin={:?} \
             msg_id={} waited_ms={}",
            entry.kind,
            entry.ttl_ms,
            entry.audience,
            entry.origin,
            line.msg_id,
            wait_started.elapsed().as_millis()
        );

        // ── (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()
        );
    }

'''

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