main
Drew Owens 0.10.9 source 32473a3 6d ago
//! THE USER-PRESENCE GUARD (0.9.9) — never end a session the user is working in.
//!
//! MEASURED 2026-10-01 on hosted 0.9.8: a "leave the machine as found" swx_stop
//! on a bridge-launched, relaunched, empty-looking session hit SOLIDWORKS's own
//! File Open dialog — Drew had started using the session, and minutes later it
//! held 34 of his documents. Nothing was lost only because his dialog happened
//! to be up. Every verb that ends work now measures presence first: SOLIDWORKS
//! in the foreground with recent input, or documents the bridge did not open,
//! or an earlier take-over — and an unreadable measurement counts as present.

mod common;

use common::{Bridge, TempDir};
use serde_json::{json, Value};

fn s(v: &Value) -> String {
    serde_json::to_string_pretty(v).unwrap_or_default()
}

/// A simulated machine with a scripted quit ladder.
struct Sim {
    dir: TempDir,
}

impl Sim {
    fn new(tag: &str) -> Sim {
        let dir = TempDir::new(tag);
        std::fs::write(dir.join("quit-script.json"), json!({"a": "exited"}).to_string()).unwrap();
        std::fs::write(
            dir.join("sldworks.json"),
            json!({"responding": true, "hwnd": 6622700, "privateMB": 900, "handles": 4000}).to_string(),
        )
        .unwrap();
        Sim { dir }
    }

    fn boot(&self) -> Bridge {
        let b = Bridge::start_in(
            TempDir::new("presence-scratch"),
            &[
                ("SWX_LAUNCH_FAKE_DIR", Box::leak(self.dir.path().into_boxed_str())),
                ("SWX_ALLOW_USER_WRITES", "1"),
                ("SWX_QUIT_SETTLE_MS", "80"),
                ("SWX_QUIT_EXIT_WAIT_SECS", "3"),
            ],
        );
        b.call("swx_start", json!({}));
        b
    }

    /// SOLIDWORKS in the foreground (the user brought it to the front): the pid
    /// the session reports.
    fn foreground_solidworks(&self, b: &Bridge) {
        let pid = b.call("swx_get_app_state", json!({}))["processId"].as_u64().expect("a session pid");
        std::fs::write(
            self.dir.join("foreground.json"),
            json!({"hwnd": 6622700, "pid": pid, "title": "SOLIDWORKS Premium 2026 - [ASM-CRATE.SLDASM]",
                   "className": "Afx:00007FF6B0000000:8"})
            .to_string(),
        )
        .unwrap();
    }

    fn foreground_other_app(&self) {
        std::fs::write(
            self.dir.join("foreground.json"),
            json!({"hwnd": 777, "pid": 4321, "title": "Inbox - Outlook", "className": "rctrl_renwnd32"}).to_string(),
        )
        .unwrap();
    }

    fn last_input(&self, secs: u64) {
        std::fs::write(self.dir.join("last-input-secs"), secs.to_string()).unwrap();
    }

    fn quit_happened(&self) -> bool {
        self.dir.join("quit.jsonl").exists()
    }
}

fn authorized(max_rung: &str) -> Value {
    json!({"userAuthorized": true, "reason": "leave the machine as found", "maxRung": max_rung})
}

#[test]
fn solidworks_in_front_with_recent_input_refuses_every_verb_that_ends_work() {
    let m = Sim::new("presence-front");
    let b = m.boot();
    m.foreground_solidworks(&b);
    m.last_input(5);
    let r = b.call("swx_stop", authorized("a"));
    check!(
        b,
        "swx_stop: user_is_active, with the evidence",
        r["errorCode"] == "user_is_active"
            && r["userPresence"]["foregroundIsSolidworks"] == true
            && r["userPresence"]["secondsSinceLastInput"] == 5
            && r["userPresence"]["foregroundWindow"]["title"].as_str().unwrap_or("").contains("ASM-CRATE"),
        s(&r)
    );
    check!(b, "...and SOLIDWORKS was not quit", !m.quit_happened(), String::new());
    for (verb, args) in [
        ("swx_shutdown", json!({"reason": "tidy"})),
        ("swx_close_all_safely", json!({"reason": "tidy"})),
        ("swx_close_all_documents", json!({"confirm": true, "reason": "tidy"})),
        ("swx_reset_workspace", json!({})),
    ] {
        let r = b.call(verb, args);
        check!(b, &format!("{verb}: user_is_active"), r["errorCode"] == "user_is_active", s(&r));
    }

    // THE USER STEPS AWAY. The session stays theirs: taken over, persistently.
    m.foreground_other_app();
    m.last_input(3600);
    let r = b.call("swx_stop", authorized("a"));
    check!(
        b,
        "swx_stop after the user stepped away: still refused — the session was taken over",
        r["errorCode"] == "user_is_active" && r["userPresence"]["takenOverEarlier"] == true,
        s(&r)
    );
    let st = b.call("swx_user_presence", json!({}));
    check!(b, "swx_user_presence: present, taken over earlier", st["present"] == true, s(&st));

    // A verb that ADDS is allowed on a taken-over session, and says so.
    let made = b.call("swx_new_document", json!({"type": "part"}));
    check!(
        b,
        "swx_new_document on a taken-over session: allowed, reporting userPresent",
        made["success"] == true && made["userPresent"]["takenOverByUser"] == true,
        s(&made)
    );
    b.call("swx_close_doc", json!({"name": made["created"]["title"].as_str().unwrap_or("")}));

    // ONLY the explicit override, with the user's authorization and a reason.
    let mut half = authorized("a");
    half["userPresentOverride"] = json!(true);
    half["userAuthorized"] = json!(false);
    let r = b.call("swx_stop", half);
    check!(b, "the override without userAuthorized is not an override", r["errorCode"] == "user_is_active", s(&r));
    let mut over = authorized("a");
    over["userPresentOverride"] = json!(true);
    let r = b.call("swx_stop", over);
    check!(
        b,
        "swx_stop with userPresentOverride + userAuthorized + reason: proceeds, and says it was overridden",
        r["stopped"] == true && r["userPresence"]["overridden"] == true,
        s(&r)
    );
}

#[test]
fn solidworks_in_front_but_idle_is_not_presence() {
    let m = Sim::new("presence-idle");
    let b = m.boot();
    m.foreground_solidworks(&b);
    m.last_input(600);
    let r = b.call("swx_stop", authorized("a"));
    check!(b, "swx_stop: SOLIDWORKS in front, no input for 10 min — not present; it quits", r["stopped"] == true, s(&r));
}

#[test]
fn recent_input_in_another_app_is_not_presence() {
    let m = Sim::new("presence-elsewhere");
    let b = m.boot();
    m.foreground_other_app();
    m.last_input(2);
    let r = b.call("swx_stop", authorized("a"));
    check!(b, "swx_stop: the user is busy in Outlook, not in SOLIDWORKS — it quits", r["stopped"] == true, s(&r));
}

#[test]
fn documents_the_bridge_did_not_open_are_the_user_taking_over() {
    let m = Sim::new("presence-foreign");
    let b = m.boot();
    // The bridge's OWN document is not foreign.
    let mine = b.call("swx_new_document", json!({"type": "part"}));
    check!(b, "precondition: the bridge made a part", mine["success"] == true, s(&mine));
    let pres = b.call("swx_user_presence", json!({}));
    check!(b, "the bridge's own document is not the user's", pres["present"] == false, s(&pres));
    // ...then the user opens their crate assembly.
    std::fs::write(b.scratch.join("mock-user-opens-document"), "").unwrap();
    let r = b.call("swx_close_all_safely", json!({"reason": "tidy"}));
    check!(
        b,
        "swx_close_all_safely: user_is_active, naming the document the bridge did not open",
        r["errorCode"] == "user_is_active"
            && r["userPresence"]["foreignDocuments"]["count"] == 1
            && r["userPresence"]["foreignDocuments"]["titles"].to_string().contains("ASM-CRATE"),
        s(&r)
    );
    let docs = b.call("swx_docs", json!({}));
    check!(b, "...and nothing was closed", s(&docs).contains("ASM-CRATE") && docs["count"] == 2, s(&docs));
}

#[test]
fn an_unreadable_presence_is_presence_but_never_a_take_over() {
    let m = Sim::new("presence-unreadable");
    let b = m.boot();
    std::fs::write(m.dir.join("presence-unreadable"), "").unwrap();
    let r = b.call("swx_stop", authorized("a"));
    check!(
        b,
        "swx_stop: presence could not be measured — refused as present",
        r["errorCode"] == "user_is_active" && r["userPresence"]["measurementUnreadable"] == true,
        s(&r)
    );
    check!(b, "...and SOLIDWORKS was not quit", !m.quit_happened(), String::new());
    std::fs::remove_file(m.dir.join("presence-unreadable")).unwrap();
    let r = b.call("swx_stop", authorized("a"));
    check!(
        b,
        "once it can be measured and the user is absent, the quit proceeds — unreadable is not a take-over",
        r["stopped"] == true,
        s(&r)
    );
}

/// NO FOREGROUND WINDOW IS UNREADABLE, NOT ABSENT (0.9.10, adversary pass 46
/// B4): Windows returns NULL on the secure desktop (a UAC prompt, the lock
/// screen) and in a disconnected session — under a UAC prompt the user is
/// certainly there.
#[test]
fn no_foreground_window_counts_as_present() {
    let m = Sim::new("presence-no-foreground");
    let b = m.boot();
    std::fs::write(m.dir.join("foreground.json"), json!({"none": true}).to_string()).unwrap();
    m.last_input(3600);
    let r = b.call("swx_stop", authorized("a"));
    check!(
        b,
        "swx_stop: no window has the foreground — unreadable, refused as present",
        r["errorCode"] == "user_is_active" && r["userPresence"]["measurementUnreadable"] == true,
        s(&r)
    );
    check!(b, "...and SOLIDWORKS was not quit", !m.quit_happened(), String::new());
}

/// THE PRE-PRIMING RE-CHECK (0.9.10, B6), pinned with a mid-verb fixture: the
/// front gate finds the user absent, rung (a) is declined, and in that moment
/// the user brings SOLIDWORKS forward. The prime — which would create and close a
/// document in their session — is refused, and the decline stands.
#[test]
fn a_user_who_comes_back_during_the_ladder_stops_the_prime() {
    let m = Sim::new("presence-mid-ladder");
    std::fs::write(m.dir.join("quit-script.json"), json!({"a": "declined"}).to_string()).unwrap();
    let b = m.boot();
    let pid = b.call("swx_get_app_state", json!({}))["processId"].as_u64().unwrap();
    std::fs::write(
        m.dir.join("presence-after-decline.json"),
        json!({"foreground": {"hwnd": 6622700, "pid": pid, "title": "SOLIDWORKS Premium 2026",
                              "className": "Afx:00007FF6B0000000:8"},
               "lastInputSecs": 3})
        .to_string(),
    )
    .unwrap();
    let r = b.call("swx_stop", authorized("a"));
    let tries = r["rungsTried"].as_array().cloned().unwrap_or_default();
    check!(
        b,
        "swx_stop: the front gate let it through (the user was away), rung (a) declined, NOT primed",
        r["stopped"] == false
            && tries.len() == 1
            && tries[0]["detail"].as_str().unwrap_or("").contains("not primed")
            && tries[0]["detail"].as_str().unwrap_or("").contains("user is working"),
        s(&r)
    );
    let ledger = b.call("swx_action_ledger", json!({"limit": 200}));
    check!(
        b,
        "...and nothing was created to prime it",
        !ledger["actions"].as_array().map(|a| a.iter().any(|e| e["action"] == "quit_prime")).unwrap_or(true),
        s(&ledger)
    );
}

/// WHO PASSED THE OVERRIDE is on the ledger line (0.9.10, B5) — self-asserted,
/// like the reason: recorded, never used to authorize.
#[test]
fn the_override_ledger_line_names_the_caller() {
    let m = Sim::new("presence-override-caller");
    let b = m.boot();
    m.foreground_solidworks(&b);
    m.last_input(1);
    let mut over = authorized("a");
    over["userPresentOverride"] = json!(true);
    over["caller"] = json!({"aiThread": "drew-live-harness", "containerName": "adom-drew", "source": "cli"});
    let r = b.call("swx_stop", over);
    check!(b, "precondition: the override proceeded", r["stopped"] == true, s(&r));
    let ledger = b.call("swx_action_ledger", json!({"limit": 200}));
    let line = ledger["actions"]
        .as_array()
        .and_then(|a| a.iter().find(|e| e["action"] == "user_present_override").cloned())
        .unwrap_or(Value::Null);
    check!(
        b,
        "the user_present_override line records the caller's identity",
        line["detail"]["caller"]["aiThread"] == "drew-live-harness"
            && line["detail"]["caller"]["containerName"] == "adom-drew"
            && line["detail"]["caller"]["source"] == "cli",
        s(&line)
    );
}

// ── 0.10.9: THE SYMMETRIC RULE ──────────────────────────────────────────────
//
// MEASURED 2026-10-14 (hosted 0.10.7, Drew at the keyboard): every
// swx_reset_workspace was refused for his presence (17 in a row) while every
// new scratch part was allowed (18) — 18 of the bridge's windows piled up on
// his screen, a 7-minute stall, SOLIDWORKS at 15.1 GB, 91 % committed. The
// bridge now neither ends his session nor opens its own windows on him.

fn docs(b: &Bridge) -> Vec<String> {
    b.call("swx_docs", json!({}))["docs"]
        .as_array()
        .map(|a| a.iter().filter_map(|d| d["title"].as_str().map(String::from)).collect())
        .unwrap_or_default()
}

fn ledger(b: &Bridge) -> Vec<Value> {
    b.call("swx_action_ledger", json!({"limit": 500}))["actions"].as_array().cloned().unwrap_or_default()
}

fn box_script() -> Value {
    json!([{"op": "new_part"},
           {"op": "sketch_rect", "plane": "Top Plane", "widthMm": 20, "heightMm": 20, "anchor": "center"},
           {"op": "extrude", "depthMm": 10}])
}

#[test]
fn the_bridge_does_not_open_its_own_windows_on_a_working_user() {
    let m = Sim::new("presence-create");
    let b = m.boot();
    m.foreground_other_app();
    m.last_input(5);
    let st = b.call("swx_status", json!({}));
    check!(
        b,
        "swx_status always carries userPresence: active, idle seconds, the foreground window",
        st["userPresence"]["active"] == true && st["userPresence"]["idleSeconds"] == 5
            && st["userPresence"]["foreground"]["title"] == "Inbox - Outlook",
        s(&st["userPresence"])
    );
    let before = docs(&b);
    for (verb, args) in [
        ("swx_new_document", json!({"type": "part", "purpose": "bridge", "waitForIdleSeconds": 0})),
        ("swx_run_script", json!({"script": box_script(), "purpose": "bridge", "waitForIdleSeconds": 0})),
        ("swx_selftest", json!({"level": "write", "waitForIdleSeconds": 0})),
    ] {
        let r = b.call(verb, args);
        check!(
            b,
            &format!("{verb} for the bridge's own purposes while the user works: user_present, nothing created"),
            r["errorCode"] == "user_present" && r["changedNothing"] == true && r["userPresence"]["active"] == true,
            s(&r)
        );
    }
    check!(b, "...not one document appeared", docs(&b) == before, format!("{before:?} -> {:?}", docs(&b)));
    check!(
        b,
        "the refusals are ledgered as creations refused",
        ledger(&b).iter().filter(|e| e["action"] == "user_present_refusal" && e["detail"]["kind"] == "creation").count() == 3,
        s(&json!(ledger(&b)))
    );
    // A USER'S OWN script is their business: allowed, and the reply says the
    // user is active and what it left open.
    let r = b.call("swx_run_script", json!({"script": box_script()}));
    check!(
        b,
        "a user's own script while they work: allowed, saying the user is active and naming the document it left open",
        r["success"] == true && r["userActive"] == true
            && r["documentsLeftOpen"].as_array().map(|a| a.len() == 1).unwrap_or(false)
            && r["why"] == "user_present",
        s(&r)
    );
}

#[test]
fn a_bridge_creation_waits_for_the_user_to_go_idle() {
    let m = Sim::new("presence-wait");
    let b = m.boot();
    m.foreground_other_app();
    m.last_input(5);
    let started = std::time::Instant::now();
    let r = std::thread::scope(|sc| {
        let h = sc.spawn(|| b.call("swx_new_document", json!({"type": "part", "purpose": "bridge", "waitForIdleSeconds": 20})));
        std::thread::sleep(std::time::Duration::from_millis(1500));
        m.last_input(3600);
        h.join().unwrap()
    });
    check!(
        b,
        "swx_new_document purpose:bridge WAITED while the user worked, and went ahead when they stopped",
        r["success"] == true && started.elapsed() >= std::time::Duration::from_millis(1400),
        format!("{} after {:?}", s(&r), started.elapsed())
    );
}

#[test]
fn reset_closes_the_bridges_own_scratch_while_the_user_is_present_but_not_the_active_one() {
    let m = Sim::new("presence-reset");
    let b = m.boot();
    // While the user is away: their document, then three of the bridge's.
    b.call("swx_open", json!({"path": "C:\\mock\\plate.sldprt"}));
    let mut ours = Vec::new();
    for _ in 0..3 {
        let r = b.call("swx_new_document", json!({"type": "part"}));
        ours.push(r["created"]["title"].as_str().unwrap_or("").to_string());
    }
    // The user sits down at SOLIDWORKS.
    m.foreground_solidworks(&b);
    m.last_input(5);
    let r = b.call("swx_reset_workspace", json!({}));
    let closed: Vec<String> = r["closed"].as_array().map(|a| a.iter().filter_map(|t| t.as_str().map(String::from)).collect()).unwrap_or_default();
    check!(
        b,
        "swx_reset_workspace while the user is present: closes the bridge's own scratch, leaves the ACTIVE one, says so",
        r["success"] == true && r["userPresent"] == true && closed == ours[..2].to_vec() && r["leftActive"] == json!([ours[2]]),
        s(&r)
    );
    let open = docs(&b);
    check!(
        b,
        "...the user's document and the active scratch part are still open; nothing else of ours is",
        open.iter().any(|t| t.to_lowercase().contains("plate")) && open.contains(&ours[2]) && !open.contains(&ours[0]) && !open.contains(&ours[1]),
        format!("{open:?}")
    );
    check!(
        b,
        "each close is ledgered with userPresent:true",
        ledger(&b).iter().filter(|e| e["action"] == "document_closed" && e["detail"]["userPresent"] == true).count() == 2,
        s(&json!(ledger(&b)))
    );
    let r = b.call("swx_reset_workspace", json!({}));
    check!(
        b,
        "again: only the active one is left, so no document qualifies — refused, naming it",
        r["errorCode"] == "user_is_active" && r["leftActive"] == json!([ours[2]]),
        s(&r)
    );
}

#[test]
fn the_selftest_stops_when_the_user_sits_down_and_closes_its_own_part_first() {
    let m = Sim::new("presence-selftest");
    // The user arrives once the simulated SOLIDWORKS has made one document
    // (the self-test's shared part, made for T01).
    std::fs::write(m.dir.join("user-arrives-after-documents"), "1").unwrap();
    let b = m.boot();
    let r = b.call("swx_selftest", json!({"level": "write", "only": ["T01", "T03"], "waitForIdleSeconds": 0}));
    let names: Vec<String> = r["results"].as_array().map(|a| a.iter().filter_map(|x| x["name"].as_str().map(String::from)).collect()).unwrap_or_default();
    check!(
        b,
        "T01 ran; before T03 the user was at the machine: the run STOPPED (stoppedFor userPresent), it did not plough on",
        r["stoppedFor"] == "userPresent" && r["complete"] == false && r["stopped"]["beforeCheck"] == "T03"
            && names.iter().any(|n| n.starts_with("T01")) && !names.iter().any(|n| n.starts_with("T03"))
            && r["_hint"].as_str().unwrap_or("").contains("THE USER IS AT THE MACHINE"),
        s(&r)
    );
    check!(b, "...having closed its own shared part: nothing of the run's is left on the user's screen", docs(&b).is_empty(), format!("{:?}", docs(&b)));
}