p = 'crates/spt-daemon/tests/attach.rs'
s = open(p, encoding='utf-8', newline='').read()
nl = '\r\n' if '\r\n' in s else '\n'


def b(t):
    return t.replace('\n', nl)


def rep(old, new):
    global s
    o, n = b(old), b(new)
    assert s.count(o) == 1, (s.count(o), old[:60])
    s = s.replace(o, n)


rep("""    arm: &str,
    mut target: Brain,
    session_id: u64,""",
    """    arm: &str,
    op_seq: u64,
    mut target: Brain,
    session_id: u64,""")

rep("""        session_id,
        0,
        MintedOp::new(Minter::Rc, 2),
        intent,""",
    """        session_id,
        0,
        MintedOp::new(Minter::Rc, op_seq),
        intent,""")

rep('    eprintln!("ARM_OPEN arm={arm} viewport_stream={stream_b} serve_stream={stream_a} conn={conn_id}");',
    '''    eprintln!(
        "ARM_OPEN arm={arm} op_seq={op_seq} viewport_stream={stream_b} serve_stream={stream_a} conn={conn_id}"
    );''')

_start = s.index(b('    // ONE operator conn for every arm'))
_end = s.index(b('    let stream_b = request_attach_endpoint('))
s = s[:_start] + b("""    // EVERY ARM NEEDS ITS OWN `op_seq`, and that is the whole reason this
    // parameter exists. The effect journal keys a stream open on
    // class+minter+op ALONE - no conn, no session (`EffectKey`) - so a second
    // arm reusing one seq does not open anything: `apply_once` returns Replayed
    // and `stream_op_id` hands back the id the FIRST arm recorded, which that
    // arm's opener exit has since terminal-retired. Measured the expensive way:
    // four arms all on seq 2 red at every position after the first, identity or
    // no identity, with "no such stream" and then, once the conn was shared,
    // "broken pipe". It read as a policy-record defect and it was a reused
    // integer.
""") + s[_end:]

i = s.index(b('/// ONE arm, ONE broker, ONE session, ONE operator conn, torn down with the'))
head = s[:i]

tail = '''// [int->REQ-ATTACH-CLIENT-STALE] The advisory's inputs cross the REAL attach
// wire: the running client's own identity rides its Request, and the serving
// daemon answers at admission with the demonstrated defects that apply to THAT
// identity and role - never with its own build version. Five arms over ONE live
// session, each with its own effect seq (see the helper): an N-1 client that
// declares no identity is answered with no record at all, and answered the same
// way again in second position; a stale Windows controller is told what is
// demonstrated against it; a viewer carrying that same stale identity is reached
// by the same transport and told nothing applies, because a controller-only
// ceremony defect never reached its role; and this build's own client is not
// advised against itself.
#[test]
fn admission_answers_the_clients_own_identity_with_applicable_policy() {
    let _home = init_home();
    let dir = tempfile::tempdir().expect("tempdir");
    let name = unique_name();
    let broker = net_broker(&name, &dir.path().join("solo"));
    let mut target = connect_retry(&name);
    let sid = target
        .spawn_session(echo_spawn_req())
        .expect("spawn echo child");
    let mut operator = connect_retry(&name);
    let dialed = operator.net_dial_loopback().expect("operator loopback dial");
    let own_origin = dialed.remote_id_hex.clone();
    let stale = AttachClientIdentity { version: "0.62.0".into(), platform: "windows".into() };

    let mut arm = |arm: &str,
                   op_seq: u64,
                   target: Brain,
                   intent: AttachIntent,
                   client: Option<AttachClientIdentity>,
                   marker: Option<&[u8]>| {
        attach_and_observe_client_policy(
            &mut operator,
            dialed.conn_id,
            &own_origin,
            &name,
            arm,
            op_seq,
            target,
            sid,
            intent,
            client,
            marker,
        )
    };

    // The identity-free control, FIRST - and again SECOND, which is where every
    // earlier revision of this test died on a reused seq rather than on anything
    // it was trying to measure.
    let (n_minus_one, target) = arm(
        "n-1-control",
        2,
        target,
        AttachIntent::Control,
        None,
        Some(b"UNKNOWN_CONTROLLER"),
    );
    assert_eq!(
        n_minus_one, None,
        "a client that declared no identity is never advised about one"
    );
    let (n_minus_one_again, target) = arm(
        "n-1-control-second-position",
        3,
        target,
        AttachIntent::Control,
        None,
        Some(b"UNKNOWN_CONTROLLER_AGAIN"),
    );
    assert_eq!(
        n_minus_one_again, None,
        "a second identity-free attach is answered no differently for running second"
    );

    let (controller, target) = arm(
        "stale-windows-controller",
        4,
        target,
        AttachIntent::Control,
        Some(stale.clone()),
        Some(b"STALE_CONTROLLER"),
    );
    let controller = controller.expect("an identified client is answered");
    assert!(
        !controller.is_empty(),
        "a client below a demonstrated floor is told about it"
    );
    assert!(
        controller.iter().all(|p| p.affects(&stale, AttachIntent::Control)),
        "every pushed policy applies to the identity that asked: {controller:?}"
    );
    assert!(
        controller.iter().any(|p| p.reason.contains("releases#223")),
        "the concrete degraded function is named: {controller:?}"
    );

    let (viewer, target) = arm(
        "stale-windows-viewer",
        5,
        target,
        AttachIntent::Viewer,
        Some(stale),
        None,
    );
    assert_eq!(
        viewer,
        Some(Vec::new()),
        "the viewer is reached by the same transport and told nothing applies to its role"
    );

    let (modern, mut target) = arm(
        "this-build-controller",
        6,
        target,
        AttachIntent::Control,
        Some(AttachClientIdentity {
            version: env!("CARGO_PKG_VERSION").into(),
            platform: std::env::consts::OS.into(),
        }),
        Some(b"CURRENT_CONTROLLER"),
    );
    assert_eq!(
        modern,
        Some(Vec::new()),
        "this build's own client is not advised against itself"
    );

    assert_eq!(
        broker.session_count(),
        1,
        "every advisory arm left the session running"
    );
    target.kill_session().expect("cleanup kill");
}
'''

s = head + tail.replace('\n', nl)
open(p, 'w', encoding='utf-8', newline='').write(s)
print('rebuilt one-broker distinct-seq case')
