//! CLI integration tests for agent-doc.

use assert_cmd::Command;
use assert_cmd::cargo::cargo_bin_cmd;
use predicates::prelude::*;
use std::collections::BTreeSet;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command as ProcessCommand;

fn agent_doc_cmd() -> Command {
    cargo_bin_cmd!("agent-doc")
}

fn init_git_repo(root: &Path, tracked: &Path) {
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/snapshots")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/state/cycles")).unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["init"])
        .status()
        .unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["config", "user.email", "test@example.com"])
        .status()
        .unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["config", "user.name", "Test User"])
        .status()
        .unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["add", tracked.file_name().unwrap().to_str().unwrap()])
        .status()
        .unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["commit", "-m", "initial", "--no-verify"])
        .status()
        .unwrap();
}

fn seed_snapshot(root: &Path, doc: &Path, content: &str) {
    let _ = root;
    agent_doc_snapshot_io::checkpoint_document_baseline(doc, content, |_, _| {}).unwrap();
}

fn read_cycle_phase(root: &Path, doc: &Path) -> Option<String> {
    let _ = root;
    agent_doc_cycle_state_io::load(doc)
        .ok()
        .flatten()
        .map(|state| state.phase.as_str().to_string())
}

fn assert_source_mentions_all(source: &str, label: &str, required: &[&str]) {
    let missing: Vec<_> = required
        .iter()
        .copied()
        .filter(|token| !source.contains(token))
        .collect();
    assert!(
        missing.is_empty(),
        "{label} is missing expected boundary token(s): {missing:?}"
    );
}

fn assert_source_omits_all(source: &str, label: &str, forbidden: &[&str]) {
    let present: Vec<_> = forbidden
        .iter()
        .copied()
        .filter(|token| source.contains(token))
        .collect();
    assert!(
        present.is_empty(),
        "{label} still contains forbidden ownership token(s): {present:?}"
    );
}

fn read_first_existing_source(manifest_dir: &Path, relatives: &[&str]) -> String {
    for relative in relatives {
        let path = manifest_dir.join(relative);
        if path.exists() {
            return fs::read_to_string(path).unwrap();
        }
    }
    panic!("none of the expected source paths exist: {relatives:?}");
}

fn read_retired_orchestration_artifact(manifest_dir: &Path, relative: &str) -> String {
    match relative {
        // The root binary is now the only effect adapter. Historical extraction
        // guards that checked the orchestration manifest should verify its real
        // dependency surface after the retired package is deleted.
        "Cargo.toml" => fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap(),
        // An absent legacy source is the strongest possible proof for guards
        // asserting that an extracted module or facade did not return.
        "src/lib.rs" => String::new(),
        _ => panic!("unsupported retired orchestration artifact: {relative}"),
    }
}

/// Every source file of `agent-doc-process-owner-io`, concatenated.
///
/// The architecture guards below assert that this *crate* owns process-tree
/// owner inspection. It is split into an observation module and a derived
/// owner-map module (`#syncownerreactive`), so a guard that reads only `lib.rs`
/// would fail on a refactor that keeps the responsibility exactly where it
/// belongs.
fn read_process_owner_io_source(manifest_dir: &Path) -> String {
    let src = manifest_dir.join("agent-doc-process-owner-io/src");
    let mut files: Vec<PathBuf> = fs::read_dir(&src)
        .unwrap()
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|ext| ext == "rs"))
        .collect();
    files.sort();
    assert!(
        !files.is_empty(),
        "agent-doc-process-owner-io must have sources at {}",
        src.display()
    );
    files
        .into_iter()
        .map(|path| fs::read_to_string(path).unwrap())
        .collect::<Vec<_>>()
        .join("\n")
}

fn git_commit_count(root: &Path) -> usize {
    let output = ProcessCommand::new("git")
        .current_dir(root)
        .args(["rev-list", "--count", "HEAD"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "git rev-list failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout)
        .unwrap()
        .trim()
        .parse()
        .unwrap()
}

fn assert_terminal_closeout_proof(_root: &Path, doc: &Path) {
    let proof = agent_doc_cycle_state_io::load_latest_terminal_closeout_proof(doc)
        .unwrap()
        .expect("expected typed terminal closeout proof projection");
    assert!(proof.last_event.contains("commit"));
    assert!(proof.did_commit);
    assert_eq!(proof.file_hash, proof.snapshot_hash);
    assert_eq!(proof.snapshot_hash, proof.head_hash);
    assert_eq!(proof.agreement.as_str(), "file_snapshot_head");
}

fn template_doc(title: &str, exchange: &str, backlog: &str, icebox: &str) -> String {
    format!(
        "---\nagent_doc_session: test-session\nagent_doc_format: template\nagent_doc_write: crdt\n---\n\n# {title}\n\n## Status\n\n<!-- agent:status patch=replace -->\n<!-- /agent:status -->\n\n## Exchange\n\n<!-- agent:exchange patch=append -->\n{exchange}<!-- /agent:exchange -->\n\n## Queue\n\n<!-- agent:queue -->\n<!-- /agent:queue -->\n\n## Backlog\n\n<!-- agent:backlog -->\n{backlog}<!-- /agent:backlog -->\n\n## Icebox\n\n<!-- agent:icebox -->\n{icebox}<!-- /agent:icebox -->\n"
    )
}

#[test]
fn test_binary_exists() {
    let _cmd = agent_doc_cmd();
}

#[test]
fn test_cli_admin_json_receipts_and_inspection_cover_controller_paths() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    fs::create_dir_all(root.join(".agent-doc")).unwrap();
    let doc = root.join("tasks/admin-cli.md");
    fs::create_dir_all(doc.parent().unwrap()).unwrap();
    fs::write(
        &doc,
        "---\nagent_doc_session: session-cli-admin\nagent: codex\n---\nBody\n",
    )
    .unwrap();
    agent_doc_session_actor_io::record_session_start_direct(
        &doc,
        "session-cli-admin",
        "%51",
        "@1",
        1,
    )
    .unwrap();
    agent_doc_session_actor_io::transition_state_direct(
        &doc,
        "session-cli-admin",
        "%51",
        Some(1),
        agent_doc_controller::actor::ActorState::Ready,
        "supervisor",
        "prompt_ready",
    )
    .unwrap();

    let root_arg = root.to_str().unwrap();
    let doc_arg = doc.to_str().unwrap();

    let pause = agent_doc_cmd()
        .args([
            "admin",
            "queue",
            "pause",
            doc_arg,
            "--project-root",
            root_arg,
            "--observed-generation",
            "1",
            "--reason",
            "cli pause",
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let pause: serde_json::Value = serde_json::from_slice(&pause).unwrap();
    assert_eq!(pause["operation_kind"], "queue_paused");
    assert_eq!(pause["status"], "accepted");
    assert!(
        pause["document_id"]
            .as_str()
            .unwrap()
            .ends_with("admin-cli.md")
    );

    let stale_handoff = agent_doc_cmd()
        .args([
            "admin",
            "handoff",
            doc_arg,
            "--to-pane",
            "%52",
            "--project-root",
            root_arg,
            "--observed-generation",
            "0",
            "--reason",
            "stale cli handoff",
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stale_handoff: serde_json::Value = serde_json::from_slice(&stale_handoff).unwrap();
    assert_eq!(stale_handoff["status"], "rejected");
    assert_eq!(stale_handoff["failed_stage"], "stale_generation");
    assert_eq!(stale_handoff["current_generation"], 1);

    let handoff = agent_doc_cmd()
        .args([
            "admin",
            "handoff",
            doc_arg,
            "--to-pane",
            "%52",
            "--project-root",
            root_arg,
            "--observed-generation",
            "1",
            "--reason",
            "cli handoff",
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let handoff: serde_json::Value = serde_json::from_slice(&handoff).unwrap();
    assert_eq!(handoff["operation_kind"], "admin_handoff");
    assert_eq!(handoff["status"], "accepted");

    let inspect = agent_doc_cmd()
        .args([
            "admin",
            "inspect",
            doc_arg,
            "--project-root",
            root_arg,
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let inspect: serde_json::Value = serde_json::from_slice(&inspect).unwrap();
    assert_eq!(inspect["record"]["generation"], 2);
    assert_eq!(inspect["record"]["pane_id"], "%52");
    assert_eq!(inspect["queue_control"]["state"], "paused");
    assert!(
        inspect["admin_operations"]
            .as_array()
            .unwrap()
            .iter()
            .any(|operation| operation["operation_kind"] == "queue_paused"
                && operation["status"] == "accepted")
    );
    assert!(
        inspect["admin_operations"]
            .as_array()
            .unwrap()
            .iter()
            .any(|operation| operation["operation_kind"] == "admin_handoff"
                && operation["status"] == "accepted")
    );

    let stale_reap = agent_doc_cmd()
        .args([
            "admin",
            "reap",
            doc_arg,
            "--project-root",
            root_arg,
            "--observed-generation",
            "1",
            "--reason",
            "stale cli reap",
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stale_reap: serde_json::Value = serde_json::from_slice(&stale_reap).unwrap();
    assert_eq!(stale_reap["status"], "rejected");
    assert_eq!(stale_reap["failed_stage"], "stale_generation");
    assert_eq!(stale_reap["current_generation"], 2);

    let reap = agent_doc_cmd()
        .args([
            "admin",
            "reap",
            doc_arg,
            "--project-root",
            root_arg,
            "--observed-generation",
            "2",
            "--reason",
            "cli reap",
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let reap: serde_json::Value = serde_json::from_slice(&reap).unwrap();
    assert_eq!(reap["operation_kind"], "admin_reap");
    assert_eq!(reap["status"], "accepted");
}

#[test]
fn test_cli_admin_reap_all_stale_reports_summary_and_guards_tmux_unavailable() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    fs::create_dir_all(root.join(".agent-doc")).unwrap();
    let doc = root.join("tasks/admin-bulk-reap.md");
    fs::create_dir_all(doc.parent().unwrap()).unwrap();
    fs::write(
        &doc,
        "---\nagent_doc_session: session-cli-bulk-reap\nagent: codex\n---\nBody\n",
    )
    .unwrap();
    let record = agent_doc_session_actor_io::record_session_start_direct(
        &doc,
        "session-cli-bulk-reap",
        "%999999",
        "@999999",
        1,
    )
    .unwrap();
    agent_doc_session_actor_io::transition_state_direct(
        &doc,
        "session-cli-bulk-reap",
        "%999999",
        Some(1),
        agent_doc_controller::actor::ActorState::Ready,
        "supervisor",
        "prompt_ready",
    )
    .unwrap();

    let output = agent_doc_cmd()
        .args([
            "admin",
            "reap",
            "--all-stale",
            "--project-root",
            root.to_str().unwrap(),
            "--reason",
            "cli bulk reap",
            "--json",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let summary: serde_json::Value = serde_json::from_slice(&output).unwrap();
    assert_eq!(summary["reason"], "manual_reap_all_stale cli bulk reap");
    let reaped = summary["reaped"].as_u64().unwrap();
    assert!(
        reaped <= 1,
        "single stale fixture can reap at most one actor: {summary}"
    );

    let current =
        agent_doc_controller_io::project_controller::load_actor_record(root, &record.document_id)
            .unwrap()
            .unwrap();
    if reaped == 1 {
        assert_eq!(
            current.state,
            agent_doc_controller::actor::ActorState::Closed
        );
        assert_eq!(current.pane_id, "");
        assert_eq!(current.window_id, "");
    } else {
        assert_eq!(
            current.state,
            agent_doc_controller::actor::ActorState::Ready
        );
        assert_eq!(current.pane_id, "%999999");
    }
}

#[test]
fn mcp_serve_handles_initialize_list_and_read() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    write!(
        file,
        "<!-- agent:exchange -->\nMCP body\n<!-- /agent:exchange -->\n"
    )
    .unwrap();

    let initialize = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": { "name": "agent-doc-test", "version": "1" }
        }
    });
    let tools_list = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/list"
    });
    let read = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 3,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_read",
            "arguments": {
                "file": file.path().display().to_string(),
                "component": "exchange"
            }
        }
    });
    let input = format!("{initialize}\n{tools_list}\n{read}\n");

    let assert = agent_doc_cmd()
        .args(["mcp", "serve"])
        .write_stdin(input)
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    let responses: Vec<serde_json::Value> = stdout
        .lines()
        .map(|line| serde_json::from_str(line).unwrap())
        .collect();

    assert_eq!(responses.len(), 3);
    assert_eq!(responses[0]["result"]["protocolVersion"], "2025-06-18");
    assert!(
        responses[1]["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .any(|tool| tool["name"] == "agent_doc_finalize")
    );
    assert!(
        responses[1]["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .any(|tool| tool["name"] == "agent_doc_admit")
    );
    assert!(
        responses[1]["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .any(|tool| tool["name"] == "agent_doc_preflight")
    );
    assert!(
        responses[1]["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .any(|tool| tool["name"] == "agent_doc_plan")
    );
    assert_eq!(
        responses[2]["result"]["structuredContent"]["content"],
        "MCP body\n"
    );
}

#[test]
fn mcp_serve_admit_plan_read_finalize_uses_one_cycle() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("session.md");
    let content = template_doc(
        "Session",
        "❯ Please inspect\n<!-- agent:boundary:1234abcd -->\n",
        "",
        "",
    );
    fs::write(&doc, &content).unwrap();
    init_git_repo(tmp.path(), &doc);
    seed_snapshot(tmp.path(), &doc, &content);

    let admit = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_admit",
            "arguments": {
                "file": doc.display().to_string()
            }
        }
    });
    let plan = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_plan",
            "arguments": {
                "file": doc.display().to_string()
            }
        }
    });
    let read = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 3,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_read",
            "arguments": {
                "file": doc.display().to_string(),
                "component": "exchange"
            }
        }
    });
    let finalize = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 4,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_finalize",
            "arguments": {
                "file": doc.display().to_string(),
                "response": "<!-- patch:exchange -->\n### Re: Connected closeout - gpt-5\nbody\n<!-- /patch:exchange -->\n",
                "no_followups": true
            }
        }
    });

    let assert = agent_doc_cmd()
        .current_dir(tmp.path())
        .args(["mcp", "serve"])
        .write_stdin(format!("{admit}\n{plan}\n{read}\n{finalize}\n"))
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
    let responses: Vec<serde_json::Value> = stdout
        .lines()
        .map(|line| serde_json::from_str(line).unwrap())
        .collect();

    assert_eq!(responses.len(), 4);
    assert_eq!(responses[0]["result"]["isError"], false);
    let admitted_cycle_id = responses[0]["result"]["structuredContent"]["admission"]["cycle_id"]
        .as_str()
        .expect("admit should return a cycle id");
    assert_eq!(
        responses[0]["result"]["structuredContent"]["admission"]["source"],
        "admit"
    );
    assert_eq!(
        responses[0]["result"]["structuredContent"]["admission"]["maintenance_required"],
        false
    );
    assert_eq!(responses[1]["result"]["isError"], false);
    assert_eq!(
        responses[1]["result"]["structuredContent"]["plan"]["execution_scope"],
        "normal"
    );
    assert_eq!(responses[2]["result"]["isError"], false);
    assert_eq!(
        responses[2]["result"]["structuredContent"]["component"],
        "exchange"
    );
    assert_eq!(responses[3]["result"]["isError"], false);
    assert!(
        !stderr.contains("repaired stale preflight_started"),
        "connected read/plan/finalize must not repair or replace the admitted cycle:\n{stderr}"
    );

    let state = agent_doc_cycle_state_io::load(&doc)
        .unwrap()
        .expect("finalize should leave terminal cycle state");
    assert_eq!(state.cycle_id, admitted_cycle_id);
    assert_eq!(state.phase, agent_doc_turn::CyclePhase::Committed);
}

#[test]
fn mcp_serve_handles_preflight_probe_and_plan() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("session.md");
    let content = template_doc(
        "Session",
        "❯ Please inspect\n<!-- agent:boundary:1234abcd -->\n",
        "",
        "",
    );
    fs::write(&doc, &content).unwrap();
    init_git_repo(tmp.path(), &doc);
    seed_snapshot(tmp.path(), &doc, &content);

    let preflight = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_preflight",
            "arguments": {
                "file": doc.display().to_string(),
                "probe": true
            }
        }
    });
    let plan = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_plan",
            "arguments": {
                "file": doc.display().to_string()
            }
        }
    });

    let assert = agent_doc_cmd()
        .current_dir(tmp.path())
        .args(["mcp", "serve"])
        .write_stdin(format!("{preflight}\n{plan}\n"))
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    let responses: Vec<serde_json::Value> = stdout
        .lines()
        .map(|line| serde_json::from_str(line).unwrap())
        .collect();

    assert_eq!(responses.len(), 2);
    assert_eq!(responses[0]["result"]["isError"], false);
    assert_eq!(
        responses[0]["result"]["structuredContent"]["report"]["no_changes"],
        true
    );
    assert_eq!(responses[1]["result"]["isError"], false);
    assert_eq!(
        responses[1]["result"]["structuredContent"]["plan"]["execution_scope"],
        "normal"
    );
}

#[test]
fn mcp_finalize_uses_strict_write_commit_path() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("session.md");
    fs::write(
        &doc,
        template_doc(
            "Session",
            "❯ Please reply\n<!-- agent:boundary:1234abcd -->\n",
            "",
            "",
        ),
    )
    .unwrap();
    init_git_repo(tmp.path(), &doc);

    let finalize = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "agent_doc_finalize",
            "arguments": {
                "file": doc.display().to_string(),
                "response": "<!-- patch:exchange -->\n### Re: MCP finalize - gpt-5\nbody\n<!-- /patch:exchange -->\n"
            }
        }
    });

    let assert = agent_doc_cmd()
        .current_dir(tmp.path())
        .args(["mcp", "serve"])
        .write_stdin(format!("{finalize}\n"))
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    let response: serde_json::Value = serde_json::from_str(stdout.lines().next().unwrap()).unwrap();
    assert_eq!(response["result"]["isError"], false);

    let head_blob = ProcessCommand::new("git")
        .current_dir(tmp.path())
        .args(["show", "HEAD:session.md"])
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&head_blob.stdout).contains("### Re: MCP finalize - gpt-5"),
        "HEAD blob should contain the MCP finalize response"
    );
}

#[test]
fn mcp_finalize_close_after_capture_recovers_on_next_preflight_once() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let content = template_doc(
        "Session",
        "❯ Please reply\n<!-- agent:boundary:1234abcd -->\n",
        "",
        "",
    );
    fs::write(&doc, &content).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, &content);
    agent_doc_cycle_state_io::start_preflight(&doc, Some(&content), Some(&content)).unwrap();

    let response =
        "<!-- patch:exchange -->\n### Re: MCP finalize - gpt-5\nbody\n<!-- /patch:exchange -->\n";
    agent_doc_repair_io::pending::save_pending(&doc, response).unwrap();
    let capture_id = agent_doc_capture_io::load_active(&doc)
        .unwrap()
        .expect("response capture should be active before recovery")
        .capture_id;
    assert_eq!(
        read_cycle_phase(root, &doc).as_deref(),
        Some("response_captured")
    );

    let before = git_commit_count(root);
    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.args(["preflight", doc.to_str().unwrap()]);
    preflight.assert().success();
    let after = git_commit_count(root);
    assert_eq!(
        after,
        before + 1,
        "recovery preflight should create exactly one closeout commit"
    );

    let head_blob = ProcessCommand::new("git")
        .current_dir(root)
        .args(["show", "HEAD:session.md"])
        .output()
        .unwrap();
    let head_doc = String::from_utf8_lossy(&head_blob.stdout);
    assert_eq!(
        head_doc.matches("### Re: MCP finalize - gpt-5").count(),
        1,
        "recovery should commit the captured response exactly once:\n{head_doc}"
    );
    assert!(
        agent_doc_repair_io::pending::load_active_pending_response(&doc)
            .unwrap()
            .is_none(),
        "pending response should be cleared after recovery"
    );
    assert!(
        agent_doc_capture_io::load_active(&doc).unwrap().is_none(),
        "a terminal capture must not remain active"
    );
    assert_eq!(
        agent_doc_capture_io::load_by_id(&doc, &capture_id)
            .unwrap()
            .expect("committed capture remains durable history")
            .state,
        agent_doc_capture_io::CaptureState::Committed,
    );

    let mut check = agent_doc_cmd();
    check.current_dir(root);
    check.args(["session-check", doc.to_str().unwrap()]);
    let check_output = check.assert().success().get_output().stdout.clone();
    let check_stdout = String::from_utf8(check_output).unwrap();
    assert!(
        check_stdout.contains("[session-check] ok"),
        "session-check should be clean after close-after-capture recovery:\n{check_stdout}"
    );
    assert_terminal_closeout_proof(root, &doc);
}

#[test]
fn test_codex_shared_closeout_spec_invariants() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let codex_support = fs::read_to_string(root.join("specs/codex-support.md")).unwrap();
    let agent_backend = fs::read_to_string(root.join("specs/05-agent-backend.md")).unwrap();
    let closeout = fs::read_to_string(root.join("specs/07-closeout-commands.md")).unwrap();
    let commit_runbook = fs::read_to_string(root.join("runbooks/commit.md")).unwrap();
    let harness_runbook = fs::read_to_string(root.join("runbooks/harness-invocation.md")).unwrap();

    assert!(
        codex_support.contains("Codex differs from Claude Code")
            && codex_support.contains("layers only"),
        "Codex spec must keep harness differences scoped to launch/routing/backend"
    );
    assert!(
        codex_support.contains("Do not standardize on the Claude Code slash command"),
        "Codex spec must not prescribe the Claude-only slash/Skill path"
    );
    assert!(
        codex_support.contains("full-content editor IPC disabled"),
        "Codex spec must preserve the shared full-content IPC ban"
    );
    assert!(
        agent_backend
            .contains("Agent backends are response producers, not session-document writers"),
        "backend spec must keep document mutation outside harness backends"
    );
    assert!(
        closeout.contains("## Harness-neutral closeout"),
        "closeout spec must name the shared harness-neutral closeout boundary"
    );
    assert!(
        closeout.contains("Codex direct")
            && closeout.contains("Codex Stop hook")
            && closeout.contains("recovery/backstop inputs"),
        "closeout spec must route Codex hook recovery through shared finalize/write machinery"
    );
    assert!(
        commit_runbook.contains("editor_convergence_required")
            && commit_runbook.contains("operator_text_authority_v1")
            && commit_runbook
                .contains("Do not continue queue drain or final-answer delivery past this guard")
            && commit_runbook.contains("Do not run `--force-disk` from a harness"),
        "commit runbook must keep editor convergence failures from becoming harness-level success"
    );
    assert!(
        harness_runbook.contains("editor_convergence_required")
            && harness_runbook.contains("operator_text_authority_v1")
            && harness_runbook.contains("Do not report success, stop, continue an auto-queue")
            && harness_runbook.contains("Do not run `--force-disk`"),
        "harness invocation runbook must forbid bypassing operator-text authority guards"
    );
}

#[test]
fn realtime_workflow_spec_pins_lazily_backed_authority() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime = fs::read_to_string(root.join("specs/14-realtime-workflow.md")).unwrap();
    let spec = fs::read_to_string(root.join("SPEC.md")).unwrap();

    assert!(
        realtime.contains("## Lazily-RS State Backbone")
            && realtime.contains("`agent-doc-document-realtime` must use `lazily-rs`")
            && realtime.contains("Other realtime loops")
            && realtime.contains("tmux, supervisor, editor-plugin, and controller")
            && realtime.contains("lazily::ThreadSafeStateMachine")
            && realtime.contains("lazily::ThreadSafeContext")
            && realtime.contains("lazily-spec")
            && realtime.contains("snapshot/delta graph"),
        "realtime workflow spec must require lazily-rs for realtime state"
    );
    assert!(
        realtime.contains("DiskDriftObserved")
            && realtime.contains("Pluginless editor or external process saves the file")
            && realtime.contains("out-of-band disk write"),
        "realtime workflow spec must model pluginless/out-of-band disk writes"
    );
    assert!(
        realtime.contains("## Disk Visibility And Durability")
            && realtime.contains("fresh\nread of the document path")
            && realtime.contains("not on proof that the\nstorage device has durably flushed")
            && realtime.contains("File watcher events are hints, not proof")
            && realtime.contains("Durability barriers (`fsync`, git object writes,\nbackup snapshots, and commit recovery sidecars) belong to backup"),
        "realtime workflow spec must distinguish hot-path read visibility from durable disk persistence"
    );
    assert!(
        realtime.contains("storing realtime authority only in a turn-local cycle sidecar")
            && realtime.contains("instead of a lazily-backed projection"),
        "realtime workflow spec must forbid turn-local realtime authority"
    );
    assert!(
        realtime.contains("operator_text_authority_v1")
            && realtime.contains("capability-unknown frontend")
            && realtime.contains("safe delivery proof")
            && realtime.contains("current visible text itself remains in the CRDT")
            && realtime.contains("newer monotone\nregistration")
            && realtime.contains("file-IPC fallback")
            && realtime.contains("expected editor text")
            && realtime.contains("Editor API success alone is not proof"),
        "realtime workflow spec must require frontend capability proof before trusting editor mutation delivery"
    );
    assert!(
        realtime.contains("target the newest live reliable-sync editor registration")
            && realtime.contains("Untargeted file-IPC\n   fallback is not delivery proof")
            && spec.contains(
                "Editor delivery must target the `editor_id` from the newest live reliable-sync\n  registration"
            )
            && spec.contains("untargeted file-IPC fallback is not")
            && spec.contains("delivery proof for an editor-owned document"),
        "realtime workflow spec must require targeted editor delivery for editor-owned documents"
    );
    assert!(
        realtime.contains("## Editor Frontend Hot Path")
            && realtime.contains("The editor text-change callback is a capture boundary, not a convergence worker")
            && realtime.contains("must not perform full-buffer reads")
            && realtime.contains("CRDT merge, code-point offset conversion, socket I/O, native sidecar writes, patch application, or document saves")
            && realtime.contains("queued onto cancellable background work")
            && realtime.contains("disposed when the document closes or the plugin unloads"),
        "realtime workflow spec must keep editor UI/extension-host text-change callbacks fast"
    );
    assert!(
        spec.contains("document realtime state\n  machine")
            && spec.contains("`agent-doc-document-realtime`")
            && spec.contains("lazily-rs-backed state"),
        "top-level spec must surface the lazily-backed realtime authority invariant"
    );
}

#[test]
fn realtime_workflow_spec_keeps_merge_and_commit_lifecycles_distinct() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime = fs::read_to_string(root.join("specs/14-realtime-workflow.md")).unwrap();

    assert!(
        realtime.contains("CRDT merge does not commit")
            && realtime.contains("document turn lifecycle owns commits")
            && realtime.contains("merge/realtime paths must not run git commit"),
        "realtime workflow spec must keep pure merge/realtime application separate from turn closeout commits"
    );
}

#[test]
fn realtime_workflow_spec_pins_stale_tool_host_fail_closed() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime = fs::read_to_string(root.join("specs/14-realtime-workflow.md")).unwrap();

    assert!(
        realtime.contains("stale MCP server")
            && realtime.contains("long-lived tool host")
            && realtime.contains("must refuse mutating tools")
            && realtime.contains("agent_doc_admit")
            && realtime.contains("agent_doc_preflight")
            && realtime.contains("agent_doc_finalize"),
        "realtime workflow spec must make stale MCP/tool-host mutation fail closed"
    );
}

#[test]
fn realtime_workflow_spec_models_parse_state_and_editor_feedback() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime = fs::read_to_string(root.join("specs/14-realtime-workflow.md")).unwrap();
    let lifecycle = fs::read_to_string(root.join("specs/15-turn-lifecycle.md")).unwrap();
    let spec = fs::read_to_string(root.join("SPEC.md")).unwrap();

    assert!(
        realtime.contains("## Realtime Parse State")
            && realtime.contains("ParseValid")
            && realtime.contains("ParseRecoverable")
            && realtime.contains("ParseBlocked"),
        "realtime workflow spec must define a separate parse-state machine"
    );
    assert!(
        realtime.contains("editor plugins must surface")
            && realtime.contains("inline diagnostics")
            && realtime.contains("quick-fix proposals"),
        "parse issues must be visible as realtime editor feedback"
    );
    assert!(
        realtime.contains("preflight repair must not be the normal parse recovery path")
            && lifecycle.contains("ParseBlocked")
            && lifecycle.contains("InterruptedBlocked"),
        "preflight/turn lifecycle must consume parse state instead of repairing as the hot path"
    );
    assert!(
        spec.contains("parse state projection")
            && spec.contains("editor diagnostics")
            && spec.contains("preflight repair"),
        "top-level spec must surface realtime parse-state authority"
    );
}

#[test]
fn turn_lifecycle_spec_cross_links_realtime_state_machine() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime = fs::read_to_string(root.join("specs/14-realtime-workflow.md")).unwrap();
    let lifecycle = fs::read_to_string(root.join("specs/15-turn-lifecycle.md")).unwrap();
    let spec = fs::read_to_string(root.join("SPEC.md")).unwrap();

    assert!(
        spec.contains("[Turn Lifecycle Authority](specs/15-turn-lifecycle.md)")
            && realtime.contains("[Turn Lifecycle Authority](15-turn-lifecycle.md)")
            && lifecycle.contains("[Real-Time Workflow Authority](14-realtime-workflow.md)"),
        "realtime and turn lifecycle specs must cross-link their distinct state machines"
    );
    assert!(
        lifecycle.contains("## Turn States")
            && lifecycle.contains("## Turn State Transitions")
            && lifecycle.contains("flowchart LR")
            && lifecycle.contains("CommitPending")
            && lifecycle.contains("NoCommitComplete")
            && lifecycle.contains("InterruptedBlocked")
            && lifecycle.contains("document turn lifecycle owns commits"),
        "turn lifecycle spec must define states, transitions, diagrams, and commit ownership"
    );
    assert!(
        lifecycle.contains("agent-doc-merge does not commit")
            && lifecycle.contains("realtime handoff proof")
            && lifecycle.contains("commit is optional when the selected turn policy is no-commit"),
        "turn lifecycle spec must consume realtime proofs without making merge/realtime commit"
    );
}

#[test]
fn live_tmux_tests_are_not_in_default_development_suite() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let sources = [
        "src/autoclaim.rs",
        "agent-doc-focus-io/src/lib.rs",
        "agent-doc-sync-io/src/resync.rs",
        "agent-doc-route-io/tests/route.rs",
        "src/session_actor_cmd.rs",
        "agent-doc-session-registry-io/src/registration.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-sync-io/src/sync.rs",
    ];
    let mut unignored = Vec::new();

    for source in sources {
        let path = manifest_dir.join(source);
        let content = fs::read_to_string(&path).unwrap();
        for block in content.split("#[test]").skip(1) {
            let Some(fn_pos) = block.find("fn ") else {
                continue;
            };
            let fn_block = &block[fn_pos..];
            let Some(open_brace) = fn_block.find('{') else {
                continue;
            };
            let mut depth = 0usize;
            let mut end = fn_block.len();
            for (index, ch) in fn_block[open_brace..].char_indices() {
                match ch {
                    '{' => depth += 1,
                    '}' => {
                        depth = depth.saturating_sub(1);
                        if depth == 0 {
                            end = open_brace + index + ch.len_utf8();
                            break;
                        }
                    }
                    _ => {}
                }
            }
            let header_and_body = &block[..fn_pos + end];
            if !header_and_body.contains("IsolatedTmux::new") {
                continue;
            }
            if !header_and_body.contains("#[ignore") {
                let name = header_and_body
                    .split("fn ")
                    .nth(1)
                    .and_then(|rest| rest.split('(').next())
                    .unwrap_or("<unknown>");
                unignored.push(format!("{source}::{name}"));
            }
        }
    }

    assert!(
        unignored.is_empty(),
        "live tmux tests must be #[ignore] and run through `make tmux-ci`: {unignored:?}"
    );
}

#[test]
fn process_global_test_mutations_share_session_check_lock() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let test_support = fs::read_to_string(manifest_dir.join("src/test_support.rs")).unwrap();
    assert!(
        test_support.contains("crate::test_support::TEST_ENV_LOCK")
            && test_support.contains("struct ProcessGlobalLockGuard")
            && test_support.contains("PROCESS_GLOBAL_LOCK_DEPTH")
            && test_support.contains("struct ScopedCurrentDir")
            && test_support.contains("std::env::set_current_dir(path)")
            && test_support.contains("std::env::set_current_dir(&self.prev_cwd)"),
        "test_support must route env and cwd test guards through a reentrant shared process-global lock"
    );

    // session_check was decomposed into focused IO modules and the broad boundary
    // coverage now lives with the focused session-check IO crate. The helpers
    // shadow core fn names like `inspect`, so they stay together in that test.
    let session_check_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/tests/session_check.rs"))
            .unwrap();
    assert!(
        session_check_tests.contains("fn inspect(file: &std::path::Path)")
            && session_check_tests.contains("fn inspect_with_warnings(file: &std::path::Path)")
            && session_check_tests
                .contains("let _process_global_lock = agent_doc_test_support::env_lock()"),
        "session_check test inspection helpers must use the focused process-global test lock"
    );

    let pty =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/pty.rs")).unwrap();
    assert!(
        pty.contains("struct EnvGuard")
            && pty.contains("AGENT_DOC_PTY_PARENT_LEAK")
            && pty.contains("std::env::remove_var(self.key)"),
        "parent env leak test must restore process env through a guard"
    );
}

#[test]
fn agent_doc_test_support_owns_orchestration_test_helpers() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-test-support")),
        "agent-doc-test-support must stay a first-class workspace crate"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/test_support.rs")
            .exists(),
        "orchestration must not retain a crate-local test_support source module"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    assert!(
        orchestration["dev-dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-test-support"),
        "orchestration tests should consume the focused test-support crate"
    );

    let test_support =
        fs::read_to_string(manifest_dir.join("agent-doc-test-support/src/lib.rs")).unwrap();
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    for required in [
        "pub struct ProcessGlobalLockGuard",
        "pub fn env_lock()",
        "pub struct ScopedCurrentDir",
        "pub fn tmux_start_lock()",
        "pub fn route_bin_env_lock()",
        "pub fn wait_for_pane_contains(",
        "pub fn send_keys_with_retry(",
        "pub fn write_mock_registered_agent_doc(",
        "pub fn write_mock_busy_registered_agent_doc(",
        "pub fn launch_mock_registered_agent_doc(",
        "pub fn seed_lazily_editor_registration_default(",
        "pub fn init_repo_with_doc(",
        "pub fn start_live_prompt_drift_receipt_listener(",
        "pub fn queue_consume_convergence_source()",
    ] {
        assert!(
            test_support.contains(required),
            "agent-doc-test-support must own orchestration's moved helper: {required}"
        );
    }
    for removed in [
        "static TMUX_START_MUTEX",
        "static TMUX_INJECT_MUTEX",
        "static ROUTE_BIN_ENV_MUTEX",
        "fn wait_for_pane_contains(",
        "fn send_keys_with_retry(",
        "fn write_mock_registered_agent_doc(",
        "fn launch_mock_registered_agent_doc(",
    ] {
        assert!(
            !route_source.contains(removed),
            "route.rs must not retain route test helper body after moving it to agent-doc-test-support: {removed}"
        );
    }
    assert!(
        route_source.contains("pub(crate) use agent_doc_test_support::{")
            && route_source.contains("write_mock_registered_agent_doc")
            && route_source.contains("wait_for_pane_contains"),
        "route.rs should only adapt moved route test helpers through the focused test-support crate"
    );
}

#[test]
fn flowcore_hot_path_guard_and_proof_tokens_are_budgeted() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    const TOKEN_BUDGET_TOLERANCE: usize = 4;
    let hot_paths = [
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-document-realtime/src/write_policy.rs",
        "agent-doc-document/src/commit_normalization.rs",
        "agent-doc-git-io/src/dirs.rs",
        "src/orchestrate.rs",
        "src/orchestrate/dag.rs",
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-preflight-command-io/src/run.rs",
        "agent-doc-preflight-io/src/lib.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-route-io/src/dispatch_only.rs",
        "agent-doc-route-io/src/dispatch_only/proof.rs",
        "agent-doc-route-io/src/authoritative_actor.rs",
        "agent-doc-route-io/tests/route/pane_resolution.rs",
        "agent-doc-route-io/src/dispatch.rs",
        "agent-doc-route-io/src/session_resolution.rs",
        "agent-doc-route-io/src/startup.rs",
        "agent-doc-route-io/src/startup_ready.rs",
        "agent-doc-route-io/src/startup_sync.rs",
        "agent-doc-route-io/src/busy_pane.rs",
        "agent-doc-route-io/src/dispatch_recovery.rs",
        "agent-doc-route-io/src/dispatch_target.rs",
        "agent-doc-route-io/src/pane_provenance.rs",
        "agent-doc-route-io/src/restart_handoff.rs",
        "agent-doc-route-io/src/supervisor_runtime.rs",
        "agent-doc-route-io/src/admission_projection.rs",
        "agent-doc-session-check-io/src/partial_staging.rs",
        "agent-doc-session-check-io/src/pending_guards.rs",
        "agent-doc-session-check-io/src/closeout_guards.rs",
        "agent-doc-session-check-io/src/queue_head_provenance_guards.rs",
        "agent-doc-session-check-io/src/guard_modes.rs",
        "agent-doc-session-check-io/src/queue_head_guards.rs",
        "agent-doc-session-check-io/src/response_guards.rs",
        "agent-doc-session-check-io/src/detect.rs",
        "agent-doc-workflow/src/session_check.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-queue-io/src/queue_consume.rs",
        "agent-doc-write-runtime-io/src/ipc.rs",
        "agent-doc-write-runtime-io/src/ipc/transport.rs",
        "agent-doc-write-ipc-io/src/transport.rs",
        "agent-doc-template-io/src/write_normalize.rs",
        "agent-doc-write-converge-io/src/convergence_fixture_tests.rs",
        "agent-doc-session-check-io/src/write_pending_checks.rs",
        "agent-doc-template-io/src/response_materialization_io.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
    ];
    let tokens = [
        "guard_",
        "proof=",
        "proof_scope=",
        "reason=",
        "flow_reason=",
        "accepted_only",
    ];
    let mut violations = Vec::new();

    for source in hot_paths {
        let content = fs::read_to_string(manifest_dir.join(source)).unwrap();
        for token in tokens {
            let actual = content.matches(token).count();
            let expected = flowcore_hot_path_token_budget(source, token);
            if actual > expected.saturating_add(TOKEN_BUDGET_TOLERANCE) {
                violations.push(format!(
                    "{source} token `{token}`: budget {expected} + tolerance {TOKEN_BUDGET_TOLERANCE}, got {actual}"
                ));
            }
        }
    }

    assert!(
        violations.is_empty(),
        "FlowCore regression gate failed. New hot-path guard/proof/reason tokens exceeded the drift tolerance; audit them and route through the owning flow enum/event before raising the budget:\n{}",
        violations.join("\n")
    );
}

fn flowcore_hot_path_token_budget(source: &str, token: &str) -> usize {
    match (source, token) {
        // 19 -> 13: the `#[cfg(test)] mod tests` was extracted into
        // `git/tests.rs` (large-module split, #splitmods2). The 6 removed
        // `guard_` occurrences were test-assertion literals, not production
        // hot-path guards.
        // +1 (#fccaudit): `strip_guard_markers_from_disk` now routes the
        // working-tree marker strip through `converge_or_disk_write(...,
        // "strip_guard_markers")` instead of a bare `std::fs::write`, so no
        // disk write touches the session doc behind a live JB editor listener.
        // The new `guard_` occurrence is only the `"strip_guard_markers"` source
        // label string — not a new flow guard boundary.
        // +1 (#live-editor-commit-guard): `commit_with_outcome` now routes a
        // live editor buffer ahead of disk through `log_closeout_guard_event`
        // with `CloseoutGuardReason::ReplicaDeliveryPending`, blocking stale
        // already-current/pre-stage commits until editor delivery is proven.
        // +1 (#preserved-queue-replay-neutralized): the committed git path now
        // runs the same stale-snapshot reset drift guard before classifying a
        // preserved queue addition neutralized by replay normalization. This is
        // the existing reset-drift guard call, not a new guard boundary.
        // 21 -> 15 (#transient-marker-document-policy): strip_guard_markers and
        // strip_head_markers policy/tests moved from git into the focused
        // `agent-doc-document::transient_markers` module. The removed tokens are
        // document-normalization names, not removed flow guard boundaries.
        ("agent-doc-commit-io/src/lib.rs", "guard_") => 15,
        // #safe-mutation-extract: safe out-of-band mutation classification moved
        // into the focused realtime write policy crate. The four `guard_` tokens
        // are the existing transient marker stripper name/call plus two policy
        // unit-test names, not new orchestration guard boundaries.
        // 4 -> 2 (#transient-marker-document-policy): realtime write policy now
        // imports transient marker normalization from agent-doc-document instead
        // of carrying duplicate guard-marker stripping helpers.
        // 2 -> 5 (#visible-write-reconcile-policy-extract): the visible-write
        // reconcile loop moved here from orchestration. These are the existing
        // visible-write guard vocabulary and focused policy tests, now owned by
        // the realtime write policy crate.
        ("agent-doc-document-realtime/src/write_policy.rs", "guard_") => 10,
        // Commit normalization is now pure document policy, not an
        // orchestration guard boundary.
        ("agent-doc-document/src/commit_normalization.rs", "guard_") => 0,
        // `#pcwcrt`: the legacy post-commit working-tree revert tower
        // (`postcommit_worktree_lost_committed_content` / `send_postcommit_editor_refresh`
        // and their transport-tagged reconcile logs: `reason=committed_content_lost`,
        // `reason=no_listener`/`reason=no_ack`, `reason=clear_carry_forward_drift`,
        // `reason=stale_editor_exchange`, `reason=stale_editor_queue_resurrection`)
        // was removed in favor of observe-only post-commit drift handling — the binary
        // no longer silently reverts an operator working-tree edit back to HEAD. That
        // drops the historical `reason=` annotations from 20 to the 7 that survive on
        // the non-reverting paths: 3 generic `reason=` log formats, `reason=already_current`,
        // and the 3 `#editorbufwin` P2 `reason=preserved_queue_addition_replay_neutralized`
        // markers/assertions (replay-neutralized queue additions are committed only after
        // closeout recovery evidence, not during ordinary independent queue edits).
        // 7 -> 8 (#preserved-queue-replay-neutralized): a second regression
        // assertion covers the same replay-neutralized queue-addition recovery
        // after stale exchange-collapse cleanup. The production reason remains
        // the existing typed recovery diagnostic.
        // 8 -> 10 (#commit-live-buffer-staged-snapshot): the commit barrier now
        // logs the audited allowance when the staged snapshot already matches a
        // synced operator-authoritative live buffer. This is a proof diagnostic
        // for the existing pre-stage guard path, not a new ad hoc flow branch.
        ("agent-doc-commit-io/src/lib.rs", "reason=") => 10,
        ("src/orchestrate.rs", "guard_") => 0,
        ("src/orchestrate/dag.rs", "guard_") => 2,
        // +1 (`reason=probe_inspection_only`): `preflight --probe` logs why it
        // skipped opening a `preflight_started` cycle (#preflight-probe-side-effect-free).
        // +1 (`reason=struck_items_below_close_marker`): queue-escape repair logs
        // when it removed struck queue items displaced below the closing marker
        // (#queue-completed-items-escape-below-component).
        // +1 (`reason=editor_buffer_lost_committed_exchange`): #ipctruncrecover —
        // the layout-guard editor-buffer-as-truth recovery logs when it REFUSED to
        // trust a flushed editor buffer that itself dropped the committed `exchange`
        // response, falling through to the safe bail instead of auto-committing a
        // response-less document.
        ("agent-doc-preflight-command-io/src/lib.rs", "reason=") => 3,
        // 1 -> 0: queue selected-head handling moved to typed queue projection
        // fields, retiring the last ad hoc `reason=` token from preflight/run.
        ("agent-doc-preflight-command-io/src/run.rs", "reason=") => 0,
        // 1 -> 2 (`reason=clean_session|operator_verify`): the go-mode
        // backlog→queue sync skips agent-undrainable heads and logs
        // `go_queue_skip_undrainable id=#<id> reason=<reason> session=<...>`
        // (#goqueuestall).
        // 2 -> 3 (`reason=plugin_listener_active`): `persist_queue_maintenance_doc`
        // logs `write_authority action=routed reason=plugin_listener_active
        // surface=queue_maintenance` when it routes a queue-maintenance mutation
        // through the editor IPC instead of a raw disk write (#fccqueue).
        // 3 -> 4 (`reason=queue_edit_lease`): `run_queue_maintenance` logs
        // `queue_maintenance_deferred reason=queue_edit_lease holder_pid=<pid>`
        // when it defers ALL queue mutation while a different live process holds a
        // fresh queue-edit lease (a direct `queue prune-noise`/`consume` in flight;
        // #sqedit-race Phase 2).
        // 4 -> 5 (`reason=force_disk`): closeout pending maintenance now logs
        // the explicit operator escape hatch used by `finalize --force-disk` when
        // it bypasses a stale active editor listener instead of failing before
        // the binary-owned closeout boundary (#pzjy closeout recovery).
        // 5 -> 6 (`reason={}`): typed deferred queue-head projection records the
        // owning defer reason for stop/time-gated heads.
        ("agent-doc-preflight-io/src/lib.rs", "reason=") => 7,
        // 1 -> 3 after extracting preflight maintenance into
        // agent-doc-preflight-io: the moved graph now owns an explicit
        // visible-write guard effect port, its production call, and the test
        // adapter.
        ("agent-doc-preflight-io/src/lib.rs", "guard_") => 3,
        ("agent-doc-repair-command-io/tests/repair.rs", "guard_") => 10,
        ("agent-doc-repair-command-io/tests/repair.rs", "reason=") => 5,
        ("agent-doc-route-io/tests/route.rs", "accepted_only") => 2,
        ("agent-doc-route-io/tests/route.rs", "flow_reason=") => 2,
        // +5 for the audited `#snrun` blocked-in-interactive-substate guard:
        // the `dispatch_only_blocked_guard_reason` import + its `guard_reason`
        // binding, the prompt-ready FlowEvent proof-log emission, and the
        // `guard_reason == ...BlockedInInteractiveSubstate`
        // branch that names the interactive terminal substate distinctly from a
        // generic busy actor on the dispatch-only fail-closed path. Routed
        // through the `RoutedReopenGuardReason` enum + `prompt_ready_barrier`
        // FlowEvent.
        // 21 -> 7: authoritative actor runtime dispatch guard policy moved to
        // `agent-doc-controller::dispatch`, and the route-local guard tests were
        // deleted instead of preserving a facade. The surviving route tokens are
        // adapter/logging references around the focused guard decisions.
        // 7 -> 6 (#route-runtime-supervisor-policy): the remaining
        // authoritative actor runtime eligibility wrapper moved to
        // `agent-doc-supervisor::route_runtime`; route.rs now calls the focused
        // supervisor policy directly.
        ("agent-doc-route-io/tests/route.rs", "guard_") => 6,
        // 3 -> 0: route submit-observation proof rendering moved to
        // `agent-doc-controller::dispatch`; route now adapts proof facts into
        // the focused controller formatter instead of owning `proof=` log text.
        ("agent-doc-route-io/tests/route.rs", "proof=") => 0,
        // +1 for the audited route resilience diagnostic
        // `route_queue_dispatch_unparseable_preserved ... reason={parse_err}`:
        // when the existing agent:queue is polluted/unparseable the route
        // preserves it and appends the new dispatch instead of bailing fatally
        // (the "route queue dispatch: failed to parse existing agent:queue" bug).
        // +1 for the audited `#codex-route-busy-ctrl-g-opens-editor` diagnostic
        // `route_busy_existing_pane_interrupt_skipped_ctrl_g ... reason=not_shell_search`:
        // the busy-pane reroute now logs when it skips the editor-opening `C-g`
        // because the live Codex pane is not in a shell reverse-i-search /
        // history-search state, and goes straight to the Escape + C-c path.
        // +1 for the audited `#qdispatchloss` diagnostic
        // `route_dispatch_uncommitted_head ... reason=head_not_in_committed_snapshot`:
        // the inactive-queue-head read defers (returns None) instead of
        // consuming a head that is not backed by the committed snapshot (an
        // uncommitted editor-buffer-only operator edit), so route never feeds a
        // half-typed/uncommitted line into the agent prompt and loses it.
        // +1 (`reason=force_disk`): route's explicit no-listener/headless
        // escape hatch logs when `--force-disk` bypasses editor convergence for
        // route-owned session/queue writes.
        ("agent-doc-route-io/tests/route.rs", "reason=") => 10,
        // Route dispatch-only send/retry moved out of orchestration with its
        // remaining route-local guard terms. Proof wording lives in the nested
        // proof module below.
        ("agent-doc-route-io/src/dispatch_only.rs", "guard_") => 5,
        ("agent-doc-route-io/src/dispatch_only.rs", "reason=") => 2,
        // +1/+1 (#jbsimpleroute): the Codex accepted-only delivery regression
        // asserts the typed `proof=accepted proof_scope=accepted_only` log shape
        // now that accepted Enter delivery is success instead of a hard route
        // failure.
        ("agent-doc-route-io/src/dispatch_only/proof.rs", "proof=") => 5,
        ("agent-doc-route-io/src/dispatch_only/proof.rs", "proof_scope=") => 5,
        // +3 (#jbdisprecycle): the recycle-in-flight dispatch guard adds three
        // audited route-local `reason=` ops_log lines
        // (`route_dispatch_only_recycle_inflight_wait/_unsettled/_settled ... reason={}`).
        // The fail-closed refusal message wording moved to
        // `agent-doc-controller::dispatch`.
        // All route-local reason tokens carry the supervisor recycle reason
        // (`auto_install_reexec` / `restart_reexec`) so a deferred-then-settled
        // or fail-closed dispatch is auditable against the marker that gated it.
        ("agent-doc-route-io/src/dispatch_only/proof.rs", "reason=") => 3,
        // +1 (#3x90): regression coverage for tracked dispatch-start timeouts
        // asserts that `DispatchStartUnproven` fails closed even though plain
        // `CommandAcceptedOnly` remains allowed for harnesses with no tracker.
        ("agent-doc-route-io/src/dispatch_only/proof.rs", "accepted_only") => 12,
        // +1 (`reason=in_flight_coalesce`): #qflood2 `route_dispatch_deduped_pane`
        // logs the benign in-flight dedup before returning deduped-success without a
        // re-send. Routed through the `RouteDispatchAuthorization::CoalescedDeduped`
        // outcome so every dispatch site handles the coalesce at compile time.
        ("agent-doc-route-io/src/authoritative_actor.rs", "reason=") => 2,
        ("agent-doc-route-io/tests/route/pane_resolution.rs", "guard_") => 1,
        ("agent-doc-route-io/tests/route/pane_resolution.rs", "reason=") => 4,
        // +1 (#kjw0 / #jbrunautobug): the busy-pane short-circuit logs the
        // existing busy proof line before returning the typed queued outcome,
        // so an accepted trigger queued behind an active turn is auditable
        // without waiting through the full dispatch-start proof budget.
        ("agent-doc-route-io/src/dispatch.rs", "proof=") => 3,
        // 3 -> 0: dead-harness and auto-start reverify fail-closed reason
        // logging moved with the tmux-facing route dispatch IO graph into
        // `agent-doc-route-io`.
        ("agent-doc-route-io/src/dispatch.rs", "reason=") => 0,
        // +2 (#jbtsiftnosub
        // `reason=harness_not_dispatch_ready_before_auto_start_send`,
        // `reason=harness_exited_to_bare_shell_before_auto_start_send`): the
        // auto-start cold-start re-verify gate (`reverify_auto_start_dispatch_ready`)
        // fails closed and logs `dispatch_into_starting_pane` / `dispatch_into_shell`
        // when a freshly created pane is still cold-starting (or dropped to a bare
        // shell) at send time, instead of typing into a not-yet-submit-ready composer.
        ("agent-doc-route-io/src/startup_ready.rs", "reason=") => 2,
        ("agent-doc-route-io/src/busy_pane.rs", "reason=") => 1,
        // #session-check-workflow-extract: focused workflow policy now owns the
        // canonical blocked-closeout diagnostic text, including its audited
        // `reason={}` field.
        // +14 (#session-check-guard-policy-extract): guard result/message
        // builders for pending, closeout, queue-head, and free-text provenance
        // checks moved to the focused workflow policy crate. These are the
        // canonical guard-result function names, not new orchestration flow
        // boundaries.
        // 14 -> 22 (#partial-staging-workflow-extract): partial closeout and
        // partial-staging warning/result builders and their focused unit tests
        // moved from orchestration into workflow. These are message-formatting
        // ownership tokens, not new hot-path guard branches.
        // 22 -> 38 (#pending-capture-workflow-extract,
        // #prompt-tail-workflow-extract): pending-capture result builders and
        // prompt-tail/direct-patchback/committed-HEAD message builders moved
        // from orchestration into this focused workflow owner with direct unit
        // coverage. These tokens name owned guard message policy, not new flow
        // branches.
        ("agent-doc-workflow/src/session_check.rs", "guard_") => 40,
        ("agent-doc-workflow/src/session_check.rs", "reason=") => 1,
        // 4 -> 7 (#session-check-guard-policy-extract): orchestration keeps the
        // IO/proof collection and calls the focused workflow guard-result
        // builders directly for blocked closeout, gated split, and queue-audit
        // diagnostics.
        ("agent-doc-session-check-io/src/closeout_guards.rs", "guard_") => 7,
        // +3 (#samplequeuepreserve): the audited
        // `queue_head_removal_guard_proof` diagnostic plus two regression test
        // names proving removed id-backed/free-text queue heads log their proof
        // source instead of disappearing silently.
        // +3 (#qheadresidue): the audited
        // `free_text_queue_completed_residue_guard_fired` diagnostic plus two
        // regression test names proving answered free-text heads cannot remain
        // active queue residue.
        ("agent-doc-session-check-io/src/queue_head_provenance_guards.rs", "guard_") => {
            // 12 baseline + 2 (#qimpstrike) for the new `residue_guard_exempts_recurring_imperative_deploy_head`
            // regression test name and its `free_text_queue_completed_residue_guard_fired`
            // negative-assertion substring. Both are test-only `guard_` substrings, not
            // new production flow guards: the residue guard reuses the existing
            // `free_text_queue_completed_residue_guard_fired` event, only adding an
            // early `is_recurring_imperative_head` exemption before it can fire.
            // +3 (#session-check-guard-policy-extract): this adapter now calls
            // the focused workflow guard-result builders directly for
            // expect-done, queue-head removal, and free-text provenance.
            17
        }
        // 8 -> 12: guard-mode precedence/defaulting moved to
        // `agent-doc-frontmatter`, so this file now names the focused
        // `project_config::resolve_*_guard_mode` functions at five adapter
        // call sites. `resolve_review_done_guard_mode_with_context` was deleted
        // because there was no cached-context call site to preserve, for a net
        // +4 audited tokens.
        // 12 -> 13 (#session-check-guard-policy-extract): the adapter now calls
        // the focused workflow pending-done guard-result builder directly.
        // 13 -> 19 (#pending-capture-workflow-extract): pending-capture guard
        // result formatting moved to `agent-doc-workflow`; this adapter keeps
        // only direct calls to the focused builders and no longer owns the
        // message strings.
        ("agent-doc-session-check-io/src/pending_guards.rs", "guard_") => 19,
        // Guard-mode resolution moved out of orchestration as an IO adapter
        // batch. These `guard_` tokens are resolver names, not new flow guards.
        ("agent-doc-session-check-io/src/guard_modes.rs", "guard_") => 10,
        ("agent-doc-session-check-io/src/queue_head_guards.rs", "guard_") => 2,
        // 2 -> 4 (#partial-staging-workflow-extract): this adapter now calls
        // the focused workflow partial closeout and partial-staging result
        // builders directly.
        ("agent-doc-session-check-io/src/partial_staging.rs", "guard_") => 4,
        // 8 -> 14 (#session-check-response-guard-message-extract):
        // response_guards now calls the focused workflow result/message
        // builders directly for dropped queue/exchange prompts, queue-response
        // contamination, completed reap residue, snapshot mismatch, and
        // committed-without-response diagnostics. These are adapter references
        // to the owning policy crate, not new local guard branches.
        ("agent-doc-session-check-io/src/response_guards.rs", "guard_") => 14,
        // 1 -> 2 (#prompt-tail-workflow-extract): the prompt-only exchange tail
        // message moved to `agent-doc-workflow`; this adapter now names the
        // focused guard message builder directly.
        ("agent-doc-session-check-io/src/detect.rs", "guard_") => 2,
        // +1 for the audited `guard_visible_write_current_transition(..., "queue_done_id_mark")`
        // call: opportunistic done-id queue marking is a document write path and
        // must use the same visible editor drift guard as active-head queue consume.
        // +2 for the audited explicit-baseline replay guard: one guard function and
        // one strict write call site reject stale-baseline responses after commit.
        // +7 for the audited #ipc-drift-visbuf-reconcile foreign-disk-write
        // reconcile path after `reconcile_visible_write` moved to
        // `agent-doc-document-realtime`: orchestration keeps the
        // `guard_visible_write_reconcile` effect adapter plus its production
        // call sites/tests, while the loop policy and unit tests live in the
        // realtime write-policy crate. A clean CRDT merge that hits a foreign
        // agent-doc disk append re-merges instead of failing closed.
        // +1 (#nm1x) for the audited `guard_visible_write_reconcile` call in the
        // `visible_write_reconcile_treats_editor_matching_disk_as_reconcilable_drift`
        // regression test: a live-buffer divergence whose editor digest equals the
        // current disk content is reconcilable, not a fail-closed user edit — it
        // reuses the existing visible-write guard, no new flow token.
        // +2 (#8j86) for the audited `agent_doc_document::transient_markers::strip_guard_markers(&probe)` call
        // in `response_materialization_probe_from_response` plus its doc-comment
        // cross-reference: the materialization probe strips the same ephemeral
        // guard markers `git::commit` strips, so a captured response body carrying
        // `<!-- no-pending-done-guard -->` still matches the committed HEAD/archive
        // blob and `stuck_captured_cycle` stops false-alarming. Reuses the existing
        // `agent_doc_document::transient_markers::strip_guard_markers` helper — no new flow guard token.
        // +1 (#sampleipcdrift) for the audited visible-write idle/current guard on
        // the socket already_applied missing-disk-response repair path. The
        // recovery writes only the visible response materialization, then keeps
        // the committed snapshot on content_ours instead of falling back through
        // stale file IPC.
        // +1 (#queueeditloss) for the regression's direct call to the existing
        // live-prompt-drift IPC adoption guard. No new guard boundary; the fix
        // reconciles live `agent:queue` edits inside the existing guard.
        // 91 -> 89 (#fcc0): the queue-consume and done-id-mark direct
        // `guard_visible_write_current_transition(...)` calls were replaced by the shared
        // `converge_document_or_disk` gate, which routes the no-listener disk
        // fallback through the single `guard_visible_write_expected_current`
        // guard inside the document realtime write authority. Fewer hot-path
        // guard tokens, not more — the guard boundary is centralized, not added.
        // +1 (#missing-head-response-recovery): strict empty-response closeout
        // uses the existing visible-write idle/current guard before merging a
        // committed HEAD response back into a stale visible document. This is an
        // audited reuse of the document-write guard, not a new authority source.
        // 47 -> 50 (#visible-write-target-buffer): the visible-write guard now
        // accepts an optional target-buffer proof so editor-visible target
        // content can satisfy the existing idle/current barrier. This extends
        // the same visible-write guard boundary; callers still route through
        // `guard_visible_write_expected_current_or_target` /
        // `guard_visible_write_reconcile_with_target` rather than introducing a
        // new write authority.
        // 47 -> 50 (#falsetyping-guard): three new `#[cfg(test)]` regression
        // tests each call `guard_visible_write_reconcile_with_target` to cover the
        // replica-churn provenance branch (replica churn reconciles; a genuine
        // unsaved operator edit still fails closed). These are test-assertion
        // literals exercising the existing visible-write guard boundary, not new
        // production flow guards.
        // 49 -> 28 and 4 -> 6 (#write-pending-checks-extract): pending
        // capture/done guard policy and the review-done source guard moved out
        // of orchestration into `agent-doc-session-check-io`. Orchestration keeps
        // visible-write guard adapters and closeout sequencing; the focused
        // session-check IO module owns the pending closeout guard tokens.
        ("agent-doc-write-runtime-io/src/lib.rs", "guard_") => 28,
        ("agent-doc-session-check-io/src/write_pending_checks.rs", "guard_") => 6,
        // 3 -> 1 (#template-materialization-policy): raw-response probe
        // construction now lives in `agent-doc-template::response_materialization`,
        // so the audited transient guard-marker stripping token moved out of
        // the write adapter with that focused policy. The later
        // `agent_doc_turn::response_replay` ownership move removed the duplicate
        // materialization-policy copy and its final guard-marker token.
        ("agent-doc-template-io/src/response_materialization_io.rs", "guard_") => 1,
        // -2 `guard_`, -1 `reason=` (#nodiskipc): active IPC timeout/no-proof
        // paths no longer enter the direct document-write fallback, so the removed
        // visible-write guard/reason tokens are retired rather than rerouted.
        // +1 `reason=`: non-git repair template replay now uses an explicit
        // `apply_template_writeback ... reason=force_disk` marker when the
        // existing repair replay policy elects the audited force-disk transport.
        ("agent-doc-write-runtime-io/src/run_entry.rs", "guard_") => 10,
        ("agent-doc-write-runtime-io/src/run_entry.rs", "reason=") => 2,
        // queue-prompt consumption, IPC transport/repair, and live-prompt-drift
        // convergence extracted into agent-doc-queue-io/src/queue_consume.rs,
        // write/ipc.rs, and the moved convergence fixture (#splitmods3 large-module split). The moved
        // `guard_`/`reason=` tokens are tracked against the new submodules,
        // not added anew.
        ("agent-doc-queue-io/src/queue_consume.rs", "guard_") => 0,
        // +3 (#freshqueueauth): direct queue-head removals now log explicit
        // proof fields for prune/orphan/acknowledgement paths, and the new
        // acknowledgement regression asserts that proof marker. The operations
        // stay routed through the existing queue-consume/converge write boundary.
        ("agent-doc-queue-io/src/queue_consume.rs", "proof=") => 3,
        // 1 -> 4 (#editorbufwin Fix A): the queue-consume head-equality check now
        // reconciles a benign live-buffer head divergence instead of hard-bailing,
        // mirroring the existing remaining-queue `reason=crdt_merge_authoritative`
        // reconcile. The new `reason=live_buffer_addition_authoritative` token
        // appears in the production ops_log line, its explanatory comment, and the
        // regression test assertion — gated on recorded dropped-queue evidence
        // (no evidence still bails, preserving the corruption guard).
        // 4 -> 5 (#typed-stop-fence): post-consume next-head projection records
        // typed stop-fence deferral as `QueueHeadDeferred` with the owning reason.
        ("agent-doc-queue-io/src/queue_consume.rs", "reason=") => 4,
        // +4 `guard_` (#dupcontent: two `guard_adopts/refuses_*` adoption tests
        // + two `guard_ipc_snapshot_adoption_against_live_prompt_drift` calls in
        // those tests) and +2 `reason=` (the two `content_ours_adoption_refused_structural`
        // ops_log lines gating corrupt-buffer adoption on both content_ours guards).
        // -2 `guard_`, +1 `reason=` (#nodiskipc): recovery-projection normalization and IPC
        // dedupe repair no longer fall back to direct disk repair guards when
        // editor redelivery is unproven; they fail closed with a retry reason.
        // -2 `reason=` (#fcc0-degraded-file-ipc): the degraded convergence
        // regression assertions moved from the old disk-fallback
        // `reason=listener_degraded*` shape to `degraded_cause=...`, because the
        // raw disk fallback is gone and this is no longer a flow reason.
        // +1 `reason=` (#wedged-ipc-ack-probe): the degraded-socket self-heal
        // path now logs `ipc_socket_degraded_self_heal_probe_failed ... reason=...`
        // when `ipc.sock` is connectable but the plugin does not ack, keeping
        // the session on file-IPC instead of clearing the latch from connect-only
        // evidence.
        // 12 -> 16 (#smconv): +4 `guard_` are test-assertion calls to
        // `guard_ipc_snapshot_adoption_against_live_prompt_drift(` in the new
        // `#smconv` semantic-merge convergence tests — not production hot-path
        // guards (the production guard count is unchanged).
        // 16 -> 17 (#qdup-freetext): +1 more test-assertion call to the same guard
        // in `smconv_preserves_freetext_fenced_queue_head_on_drift`, which proves a
        // multi-line free-text queue head now converges instead of blocking. Still a
        // test call, not a production guard boundary.
        // 17 -> 21 (#live-drift-visible-repair): +4 test-only guard substrings
        // from `guard_live_prompt_drift_requires_visible_repair`,
        // `guard_live_prompt_drift_uses_content_ours_snapshot_when_ack_union_carries_unowned_drift`,
        // and their direct
        // calls to the existing live-prompt-drift IPC adoption guard. These prove
        // content_ours adoption after a live editor receipt requires visible
        // response proof; a response-bearing visible union suppresses redelivery
        // but does not make the lazily visible-write receipt snapshot authority
        // when it carries unowned drift.
        ("agent-doc-write-runtime-io/src/ipc.rs", "guard_") => 21,
        // 17 -> 18 (#smconv): +1 production `reason=node_keyed_semantic_merge` on
        // the new `live_prompt_drift_semantic_merged` ops_log — the node-keyed
        // merge success path, mirroring the sibling `#fintol2`
        // `reason=independent_concurrent_edit` forward-merge log (an ops_log
        // human-reason, not a new flow-enum outcome).
        // 18 -> 19 (#detached-disk-current-file): the degraded-socket editorless
        // regression now asserts `reason=listener_degraded_editor_detached`,
        // proving the path tries file IPC first and only then uses guarded
        // DetachedDisk when no live editor sidecar owns the document.
        // 19 -> 20 (#visible-write-live-buffer-sync): already-applied
        // visible-write adoption logs `reason=no_editor_id` when the binary has no editor id
        // to mark the live-buffer epoch as synced. The snapshot still follows
        // the existing visible-write proof path; this is diagnostic context for
        // skipping the live-buffer barrier update.
        // 20 -> 21 (#visible-write-disk-write-through): proven visible-write
        // disk write-through logs `reason=already_current` when disk already matches
        // the editor-proven content. This is diagnostic context for skipping the
        // write-through effect, not a new flow branch.
        // 21 -> 24 (#whole-buffer-authority): visible-write write-through and
        // editor-repair redelivery now log the `decide_whole_buffer_delivery`
        // policy-table reason when the focused realtime policy rejects a
        // whole-buffer effect. These are diagnostics for the shared authority
        // decision, not ad hoc orchestration flow branches.
        // 24 -> 25 (#visible-write-source-buffer): visible-write write-through now logs
        // `reason=stale_source_buffer` when a live operator-authoritative editor
        // buffer has moved past the visible-write receipt. This is the same realtime
        // policy-table reason as other whole-buffer source-proof rejections.
        // 25 -> 26 (#ipcvisredeliver-incycle): in-cycle live-prompt visible
        // repair logs the existing disk-repair reason on successful editor IPC
        // convergence. This is diagnostic context for the existing recovery
        // path, not a new flow branch.
        // 26 -> 27 (#stale-already-applied): already-applied visible-buffer
        // repair now logs the deferred visible-write guard reason before
        // falling back to file-IPC instead of hard-erroring the closeout. The
        // recovery still routes through the existing file-IPC fallback outcome.
        // 27 -> 32 (#adoc-live-prompt-drift-operator-edit): the operator-edit
        // reconcile path adds diagnostic `reason=` log tokens on the visible-write
        // forward-reconcile: `operator_buffer_ahead` (Phase 1 + Phase 2 loop),
        // `settled_buffer_dropped_response` (fail-closed), and
        // `operator_still_editing` (bounded-loop timeout). These are ops.log
        // diagnostics for the existing snapshot-adoption recovery, not new flow
        // branches; the convergence decision routes through the realtime model's
        // `operator_reconcile_step`.
        ("agent-doc-write-runtime-io/src/ipc.rs", "reason=") => 32,
        // +1 `guard_` (#fcc0-degraded-file-ipc): focused
        // `FileIpcDeliveryOptions` carries the existing committed-cycle file-IPC
        // poll guard for convergence and transport callers; this is an option for
        // the existing guard, not a new flow guard boundary.
        ("agent-doc-write-runtime-io/src/ipc/transport.rs", "guard_") => 9,
        // 10 -> 14 (#whole-buffer-authority): full-content IPC now logs disabled
        // and authority-rejected outcomes from `decide_whole_buffer_delivery`,
        // plus stale-source regression assertions. The write remains blocked
        // before socket/file delivery; the reasons are routed through the shared
        // realtime whole-buffer authority policy.
        // 14 -> 15 (#visible-write-source-buffer): the stale visible-write regression
        // asserts the same shared `reason=stale_source_buffer` table outcome so a
        // stale receipt cannot overwrite a newer live operator edit.
        ("agent-doc-write-runtime-io/src/ipc/transport.rs", "reason=") => 15,
        // #write-ipc-transport-graph: the production socket-first/file-IPC
        // transport graph moved from orchestration into the focused write IPC
        // crate. These are the existing snapshot-adoption, visible-repair, and
        // post-delivery proof guard names, not newly introduced flow boundaries.
        ("agent-doc-write-ipc-io/src/transport.rs", "guard_") => 11,
        ("agent-doc-write-ipc-io/src/transport.rs", "reason=") => 3,
        // -2 (#realtime-authority): removed stale doc-comment references to
        // snapshot-adoption guard fallbacks. The production guard boundary count
        // is unchanged; the comment now describes current-document merge instead.
        // +9 (#fcc0-no-external-write): active editor listeners no longer allow
        // disk fallback when component convergence cannot prove editor apply.
        // The added `reason=` tokens are the blocked production reasons
        // (`no_component_delta`, `no_visible_write_receipt`, `ack_mismatch`, `no_ack`,
        // `send_failed`, and auto-recovery `editor_ipc_unconfirmed`) plus focused
        // regression assertions proving the guarded and plain fallback gates do
        // not write behind the plugin. No new flow guard; this tightens the
        // existing converge boundary from `disk_fallback` to `transport=blocked`
        // while a listener is active.
        // -1 (#fcc0-degraded-file-ipc): the degraded-socket convergence branch no
        // longer logs `reason=listener_degraded` on a disk fallback because that
        // fallback is gone. It now records `degraded_cause=...` on the file-IPC /
        // fail-closed path, preserving diagnostics without expanding flow reasons.
        // +1 (#fccroute): the route/dispatch session-write sites
        // (`route_session_id`, `route_dedup_scrub`, `route_queue_activation`) now
        // route through `converge_document_or_disk`; the added no-listener route
        // fallback regression test asserts `reason=no_listener` in the ops-log,
        // which is a test-assertion string, not a new hot-path flow reason.
        // +1 (#supselfheal Ph2): write_wedged_supervisor_recycle_requested ops-log
        // line carries `reason=repeated_ack_timeout_active_listener` — audited.
        // 19 -> 17 (#6b5h): the no_ack / no_visible_write_receipt / send_failed converge
        // refusals were centralized into `refuse_or_editorless_disk_fallback`,
        // which decides fail-closed (live editor) vs editor-less disk fallback.
        // The four per-branch `reason=` literals collapsed into the helper's three
        // (`transport=blocked reason={reason}`, the bail `(reason={reason})`, and
        // `transport=disk_fallback reason={reason}`), a net -2 audited reduction.
        // 17 -> 20 (#fcc0-ack-mismatch): ACK-mismatched editor convergence now
        // attempts a hash-guarded refresh only for the narrow stale queue-prompt
        // artifact shape. The three added production reasons log why that refresh
        // did not rewrite the editor buffer (`untrusted_visible_write_contains_user_drift`,
        // `no_ack`, `send_failed`) while the existing `ack_mismatch` writeback
        // reason remains the fail-closed flow boundary.
        // 21 -> 20 (#mergestatemachine2): the `ack_mismatch` converge branch stopped
        // emitting its own `bail!("... (reason=ack_mismatch)")` and now routes through
        // `refuse_or_editorless_disk_fallback(file, source, "ack_mismatch")`, so the
        // reason flows through the helper's existing `reason={reason}` token. Net -1:
        // a CLI-only/no-editor session now disk-falls-back on ack_mismatch instead of
        // hard-refusing (the #6b5h wedge). Audited — no new flow boundary.
        // 20 -> 23 (#operator-text-authority): a diverged live-buffer sidecar from
        // a capability-unknown editor now fails closed before IPC send with
        // `reason=editor_capability_missing`; the other two new occurrences are
        // regression assertions proving the guard fired and a capable sidecar did
        // not. Routed through the existing converge fail-closed boundary.
        // 23 -> 24 (#operator-text-authority-clean): a matching live-buffer sidecar
        // from a capability-unknown editor also fails closed before IPC send. This
        // covers the delivery-vs-next-keystroke race while using the same
        // `reason=editor_capability_missing` converge boundary.
        // 9 -> 11 (#operator-text-authority-refresh): two regression test names
        // contain `capability_guard_`; the production guard boundary is unchanged.
        // +1 (#detached-disk-current-file): the detached-disk convergence path
        // calls `guard_visible_write_expected_current` immediately before the
        // atomic write, so no editorless fallback writes over a newer file epoch.
        // +1 (#active-capture-response-preserve): the stale snapshot reset drift
        // guard now has a regression path proving it skips visible rebase when
        // the active captured response is present in the snapshot but missing
        // from visible current content.
        ("agent-doc-write-converge-io/src/convergence_fixture_tests.rs", "guard_") => 13,
        // 24 -> 26 (#operator-text-authority-refresh): a missing-authority sidecar
        // now asks the editor to republish a read-only live-buffer proof before
        // failing closed. The two `reason=publish_live_buffer_failed` diagnostics
        // explain the blocked convergence closeout when that refresh cannot prove
        // authority.
        // 26 -> 27 (#detached-disk-current-file): the audited `DetachedDisk`
        // path logs `transport=disk_detached reason=<...>` after proving no live
        // editor owner/sidecar and rechecking the current visible file.
        // -2 (#cp-editor-ipc): stale-supervisor IPC-drift recycle diagnostics
        // were removed from editor write convergence. CP owns process recycling;
        // editor IPC proof failures now stay on retry/repair paths.
        ("agent-doc-write-converge-io/src/convergence_fixture_tests.rs", "reason=") => 11,
        // -1 (#final-response-transaction): the post-mutation
        // `bare_write_escalated_to_commit ... reason=response_body_placed`
        // recovery path was removed. Bare session writes now fail before input,
        // capture, or document mutation.
        // +1 for the audited `queue_consume_divergence_reconciled ... reason=crdt_merge_authoritative`
        // ops_log diagnostic: when the post-CRDT-merge document queue diverges from
        // the snapshot, consume reconciles (document wins) instead of bailing
        // (#finalize-divergence-orphans-committed-head / IPC-CRDT resilience).
        // +2 for the audited `ipc_listener_degraded_direct_disk ... reason=repeated_ack_timeout`
        // diagnostics: repeated socket IPC receipt timeouts de-wedge the current
        // document/session away from socket/file IPC and onto the direct-disk path.
        // +1 for the audited `ipc_socket_degraded_prefer_file_ipc ... reason=repeated_ack_timeout`
        // diagnostic (#ipc-degraded-prefers-file-ipc): a latched-degraded socket
        // routes the write through the file-IPC patch queue (plugin applies via
        // Document API) instead of a raw disk write; disk write is last resort.
        // +1 (#finalize-stale-baseline-reopen-friction): the
        // `explicit_baseline_replay_rejected ... reason={reason}` diagnostic now
        // names WHY the committed-cycle gate fired (`response_already_in_head`,
        // `empty_response`, `no_head_baseline`) so a true replay is distinguished
        // from the genuinely-new-response path that auto-reopens from HEAD instead
        // of bailing. Routed through the same explicit-baseline replay gate.
        // +2 (#queueeditloss) for the audited
        // `queue_content_ours_reconciled ... reason=live_queue_deletion_authoritative`
        // ops-log marker and its regression assertion. It proves content_ours
        // adoption removes live-deleted baseline queue prompts instead of
        // resurrecting them; live additions remain covered by the existing
        // dropped-queue evidence path.
        // +6 (#w42v) for the audited `compact_writeback ... transport=disk_fallback
        // reason=<no_listener|no_component_delta|no_visible_write_receipt|ack_mismatch|no_ack|
        // send_failed>` markers in `try_editor_converge` (the #fcc0-generalized
        // former `try_compact_editor_converge`). These are diagnostic
        // disk-fallback reasons on the editor-IPC convergence path (not flow
        // guards), each proving why a write site fell back to the guarded disk
        // write instead of converging through the editor.
        // +2 (#mps Rung 3) for the audited `mps_baseline_resolve source=md_fallback
        // reason=<no_model|model_error>` markers in `read_explicit_baseline`. These
        // are diagnostic baseline-fallback reasons on the model-projected-baseline
        // cutover path (not flow guards), logging why finalize fell back to the
        // legacy `.md` baseline instead of the projected model overlay.
        // +1 (#fintol2) for the audited `live_prompt_drift_forward_merged ...
        // reason=independent_concurrent_edit` ops-log marker in
        // `guard_ipc_snapshot_adoption_against_live_prompt_drift`. It proves the
        // finalize-tolerance forward-merge path: when a concurrent user edit is
        // disjoint from the response target (no prompt/directive, outside
        // `exchange`, conflict-free 3-way union), the gate commits the union this
        // cycle instead of carrying it forward through a snapshot-only retry.
        // A diagnostic on the tolerance path, not a new flow guard.
        // +1 (#fcc0) for the `reason=no_listener` assertion literal in the
        // `converge_document_or_disk_falls_back_to_guarded_disk_without_listener`
        // regression test. The 6 production disk-fallback reasons (now emitted by
        // the generalized `try_editor_converge` for every write site, not just
        // compact) are unchanged; this single increment is a test-assertion
        // literal proving the queue-consume disk fallback is source-labelled.
        // +4 (#fcc0e) for the de-wedge circuit-breaker integration of
        // `try_editor_converge`: +1 PRODUCTION `reason=listener_degraded` (the
        // converger now short-circuits to the guarded disk fallback when the
        // `#ipcdrift` latch is degraded, mirroring the reposition/finalize socket
        // paths) and +3 test literals (the comment + the `reason=listener_degraded`
        // / `reason=no_listener` assertions in the degraded-socket convergence
        // tests). The
        // socket failure path also now feeds `record_ipc_socket_ack_timeout` /
        // clears via `clear_ipc_socket_ack_timeouts` — no new `reason=` token.
        // 12 -> 11 (#live-drift-visible-repair): the focused file-IPC regression
        // now proves the earlier partial-materialization retry path instead of
        // asserting an extra visible-repair `reason=` literal. The production
        // recovery still logs `recovery=visible_repair_required` in write/ipc.rs.
        ("agent-doc-write-runtime-io/src/lib.rs", "reason=") => 12,
        _ => 0,
    }
}

#[test]
fn test_cli_help() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("--help");
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("Interactive document sessions"))
        .stdout(predicate::str::contains("repair"))
        .stdout(predicate::str::contains("fix"));
}

#[test]
fn test_sync_without_explicit_columns_fails_closed() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("sync");
    cmd.assert().failure().stderr(predicate::str::contains(
        "sync requires at least one explicit --col",
    ));
}

#[test]
fn test_backlog_reopen_help_exposes_explicit_queue_reactivation() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["backlog", "reopen", "--help"]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("<FILE>"))
        .stdout(predicate::str::contains("<ID>"))
        .stdout(predicate::str::contains("--queue"));
}

#[test]
fn test_respond_help_routes_backlog_only_to_write_commit() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["respond", "--help"]);
    cmd.assert().success().stdout(predicate::str::contains(
        "use `agent-doc write --commit` instead",
    ));
}

#[test]
fn test_admin_recycle_help_accepts_document_or_project_target() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["admin", "recycle", "--help"]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("[FILE_OR_PROJECT_ROOT]"))
        .stdout(predicate::str::contains(
            "Optional document path or project root to recycle",
        ));
}

#[test]
fn test_admin_recycle_accepts_document_target() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    let tasks = root.join("tasks");
    fs::create_dir_all(&tasks).unwrap();
    let doc = tasks.join("session.md");
    fs::write(&doc, "# Session\n").unwrap();
    let doc_arg = Path::new("tasks/session.md");
    let expected_root = root.canonicalize().unwrap().display().to_string();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args(["admin", "recycle", doc_arg.to_str().unwrap(), "--json"]);
    let output = cmd.assert().success().get_output().stdout.clone();
    let stdout = String::from_utf8_lossy(&output);
    assert!(!stdout.contains("unexpected argument"), "{stdout}");
    assert!(stdout.contains("\"scope\":\"project\""), "{stdout}");
    assert!(stdout.contains(&expected_root), "{stdout}");
    assert!(stdout.contains("\"recycled\":false"), "{stdout}");
    // `#recycle-no-boundaries`: escalation to a cold-start fires only for an actual
    // session document (one with an `agent_doc_session` id). This fixture has no
    // frontmatter, so recycle must degrade to a clean no-op exit (not a hard
    // `restart` error) with `escalated_cold_start:false`.
    assert!(
        stdout.contains("\"escalated_cold_start\":false"),
        "{stdout}"
    );
}

#[test]
fn test_queue_sync_materializes_priority_go_backlog_and_session_check_stays_clean_after_commit() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    fs::create_dir_all(root.join(".agent-doc/snapshots")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/state/cycles")).unwrap();

    let content = concat!(
        "---\n",
        "agent_doc_session: test-session\n",
        "agent_doc_format: template\n",
        "agent_doc_write: crdt\n",
        "queue: start\n",
        "prompt_presets:\n",
        "  '#spec-test-commit-push': update spec + tests. commit + push\n",
        "---\n\n",
        "## Exchange\n\n",
        "<!-- agent:exchange patch=append -->\n",
        "### Re: prior\n\nDone.\n",
        "<!-- /agent:exchange -->\n\n",
        "## Queue\n\n",
        "<!-- agent:queue preset=\"#spec-test-commit-push\" priority go -->\n",
        "- advance [#samplefeed-prop]\n",
        "- advance [#gvj5]\n",
        "<!-- /agent:queue -->\n\n",
        "## Backlog\n\n",
        "<!-- agent:backlog priority queue -->\n",
        "- [ ] [#2qrx] [P1] Offline click-upload backfill\n",
        "- [ ] [#rating-emails] [P2] Enable review opt-in\n",
        "- [ ] [#samplefeed-prop] [P3] Existing advance head\n",
        "- [ ] [#cf-txn-email] [P3] Transactional email migration\n",
        "- [ ] [#884m] [P3] News sitemap cleanup\n",
        "- [ ] [#gvj5] [P3] Existing advance head\n",
        "- [ ] [#tk2p] [P3] Hetzner migration\n",
        "- [ ] [#pdp-video-footage] [P3] Product video footage\n",
        "<!-- /agent:backlog -->\n",
    );
    fs::write(&doc, content).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, content);

    let mut sync = agent_doc_cmd();
    sync.current_dir(root);
    sync.args(["queue", "sync", "session.md"]);
    let sync_output = sync.assert().success().get_output().stdout.clone();
    let sync_stdout = String::from_utf8(sync_output).unwrap();
    assert!(
        sync_stdout.contains("synced 8 backlog id(s)"),
        "sync should report all active backlog ids:\n{sync_stdout}"
    );
    assert!(
        sync_stdout.contains(
            "skipped already represented backlog id(s): #samplefeed-prop, #gvj5 (reason: already_in_queue)"
        ),
        "sync should explain ids represented by existing non-do heads:\n{sync_stdout}"
    );
    assert!(
        sync_stdout.contains("materialized backlog id(s): #2qrx, #rating-emails, #cf-txn-email, #884m, #tk2p, #pdp-video-footage"),
        "sync should report newly materialized ids:\n{sync_stdout}"
    );

    let synced = fs::read_to_string(&doc).unwrap();
    assert!(synced.contains("- advance [#samplefeed-prop]"));
    assert!(synced.contains("- advance [#gvj5]"));
    assert!(synced.contains("- do [#2qrx]"));
    assert!(synced.contains("- do [#rating-emails]"));
    assert!(synced.contains("- do [#cf-txn-email]"));
    assert!(synced.contains("- do [#884m]"));
    assert!(synced.contains("- do [#tk2p]"));
    assert!(synced.contains("- do [#pdp-video-footage]"));
    assert_eq!(
        synced.matches("do [#samplefeed-prop]").count(),
        0,
        "existing advance head should prevent duplicate do head:\n{synced}"
    );
    assert_eq!(
        synced.matches("do [#gvj5]").count(),
        0,
        "existing advance head should prevent duplicate do head:\n{synced}"
    );

    ProcessCommand::new("git")
        .current_dir(root)
        .args(["add", "session.md"])
        .status()
        .unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["commit", "-m", "sync queue", "--no-verify"])
        .status()
        .unwrap();

    let mut check = agent_doc_cmd();
    check.current_dir(root);
    check.args(["session-check", doc.to_str().unwrap()]);
    let check_output = check.assert().success().get_output().stdout.clone();
    let check_stdout = String::from_utf8(check_output).unwrap();
    assert!(
        check_stdout.contains("[session-check] ok"),
        "session-check should stay clean after the synced queue is committed:\n{check_stdout}"
    );
}

#[test]
fn test_cli_controller_status_reports_inactive_without_launching() {
    let tmp = tempfile::TempDir::new().unwrap();
    fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.args([
        "controller",
        "status",
        "--project-root",
        tmp.path().to_str().unwrap(),
    ]);
    let output = cmd.assert().success().get_output().stdout.clone();
    let status: serde_json::Value = serde_json::from_slice(&output).unwrap();

    assert_eq!(status["active"], false);
    assert_eq!(
        status["socket_path"],
        tmp.path()
            .join(".agent-doc/controller.sock")
            .to_string_lossy()
            .as_ref()
    );
    assert!(!tmp.path().join(".agent-doc/controller-state.json").exists());
}

#[test]
fn test_cli_controller_status_ensure_lazy_launches_and_persists_bootstrap() {
    let tmp = tempfile::TempDir::new().unwrap();
    fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.args([
        "controller",
        "status",
        "--ensure",
        "--project-root",
        tmp.path().to_str().unwrap(),
    ]);
    let output = cmd.assert().success().get_output().stdout.clone();
    let mut status: serde_json::Value = serde_json::from_slice(&output).unwrap();
    if status["active"] != true {
        for _ in 0..50 {
            std::thread::sleep(std::time::Duration::from_millis(100));
            let mut retry = agent_doc_cmd();
            retry.args([
                "controller",
                "status",
                "--project-root",
                tmp.path().to_str().unwrap(),
            ]);
            let retry_output = retry.assert().success().get_output().stdout.clone();
            status = serde_json::from_slice(&retry_output).unwrap();
            if status["active"] == true {
                break;
            }
        }
    }

    assert_eq!(status["active"], true);
    assert_eq!(status["launch_mode"], "lazy");
    assert!(status["bootstrap_epoch"].as_u64().unwrap() > 0);
    assert!(tmp.path().join(".agent-doc/state.db").exists());
    assert!(!tmp.path().join(".agent-doc/controller-state.json").exists());

    let mut shutdown = agent_doc_cmd();
    shutdown.args([
        "controller",
        "shutdown",
        "--project-root",
        tmp.path().to_str().unwrap(),
    ]);
    shutdown.assert().success();
}

#[test]
fn test_cli_no_args_shows_error() {
    let mut cmd = agent_doc_cmd();
    cmd.assert().failure();
}

#[test]
fn test_cli_unknown_subcommand() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("nonexistent-command");
    cmd.assert().failure();
}

#[test]
fn test_cli_audit_docs_subcommand() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("audit-docs");
    let output = cmd.output().unwrap();
    // Should run (may exit 0 or 1 depending on doc state, but not crash)
    assert!(output.status.code().is_some());
}

#[test]
fn test_cli_audit_docs_in_tempdir_no_project_marker() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.arg("audit-docs");
    // Should succeed with a warning, falling back to CWD
    cmd.assert()
        .success()
        .stderr(predicate::str::contains("no project root marker found"));
}

#[test]
fn test_cli_audit_docs_clean_project() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();

    // Minimal project with no issues
    std::fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.arg("audit-docs");
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("No issues found"));
}

#[test]
fn test_cli_audit_docs_treats_mtime_staleness_as_advisory() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();

    std::fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();
    std::fs::write(
        root.join("AGENTS.md"),
        "# Agent Instructions\n\nUse `cargo test` before changing code.\n",
    )
    .unwrap();
    std::fs::create_dir_all(root.join("src")).unwrap();
    std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();

    let old_time = filetime::FileTime::from_unix_time(1_700_000_000, 0);
    let new_time = filetime::FileTime::from_unix_time(1_700_000_100, 0);
    filetime::set_file_mtime(root.join("AGENTS.md"), old_time).unwrap();
    filetime::set_file_mtime(root.join("src/main.rs"), new_time).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.arg("audit-docs");
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("Mtime advisory"))
        .stdout(predicate::str::contains("No blocking issues found"));
}

#[test]
fn test_cli_ops_summary_groups_ops_log_events() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    fs::write(
        root.join(".agent-doc/logs/ops.log"),
        format!(
            "\
[100] ipc_write_consumed file={} patches=1
[101] commit_success file={}
[102] route_dispatch_only_sent file=tasks/b.md pane=%2 harness=opencode proof=accepted proof_scope=accepted_only
[103] route_dispatch_only_submit_unproven file=tasks/b.md pane=%2 harness=opencode delivery=direct_pane_submit submit_mode=tmux_literal_kitty_return proof=accepted proof_scope=accepted_only timeout_secs=10
[104] sync_latency phase=prune_stash_panes elapsed_ms=309 budget_ms=250 status=over_budget mode=full
[105] flow_event file=tasks/b.md flow=document_mutation stage=pre_write_guard outcome=blocked reason=visible_write_typing_defer_active_typing:socket_ipc
",
            root.join("tasks/a.md").display(),
            root.join("tasks/a.md").display()
        ),
    )
    .unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.args([
        "ops",
        "summary",
        "--project-root",
        root.to_str().unwrap(),
        "--limit",
        "0",
    ]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("write ipc consumed"))
        .stdout(predicate::str::contains("tasks/a.md"))
        .stdout(predicate::str::contains("accepted-only route proof"))
        .stdout(predicate::str::contains("dispatch-only not proven"))
        .stdout(predicate::str::contains(
            "flow document mutation pre-write guard blocked",
        ))
        .stdout(predicate::str::contains("sync over budget"));
}

#[test]
fn test_cli_ops_diagnose_gathers_cycle_artifacts() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/codex-hooks/sessions")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/hooks/post_write")).unwrap();
    let doc = root.join("tasks/a.md");
    fs::create_dir_all(doc.parent().unwrap()).unwrap();
    fs::write(&doc, "body").unwrap();

    fs::write(
        root.join(".agent-doc/logs/ops.log"),
        "[100] flow_event file=tasks/a.md flow=closeout stage=commit outcome=blocked cycle_id=cycle-a patch_id=patch-a\n",
    )
    .unwrap();
    fs::write(
        root.join(".agent-doc/logs/cycles.jsonl"),
        "{\"op\":\"commit\",\"file\":\"tasks/a.md\",\"cycle_id\":\"cycle-a\"}\n",
    )
    .unwrap();
    fs::write(
        root.join(".agent-doc/logs/session-1.log"),
        "[101] codex_start cycle_id=cycle-a patch_id=patch-a\n",
    )
    .unwrap();
    fs::write(
        root.join(".agent-doc/codex-hooks/sessions/thread.json"),
        r#"{"thread_id":"thread-1","cycle_id":"cycle-a"}"#,
    )
    .unwrap();
    fs::write(
        root.join(".agent-doc/hooks/post_write/patch-a.json"),
        r#"{"patch_id":"patch-a","cycle_id":"cycle-a","payload":"large plugin payload"}"#,
    )
    .unwrap();
    let document_hash = agent_doc_fs::document_state_hash(&doc).unwrap();
    agent_doc_controller_io::project_controller::append_state_event_for_test(
        root,
        &agent_doc_state_backbone::StateEvent::new(
            "diagnosis-cycle-a",
            agent_doc_state_backbone::StateFact::PreflightStarted {
                document_hash,
                cycle_id: "cycle-a".to_string(),
                session_id: Some("session-1".to_string()),
                tracked_work_maintenance_required: Some(false),
            },
        ),
    )
    .unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.args([
        "ops",
        "diagnose",
        "--project-root",
        root.to_str().unwrap(),
        "--cycle-id",
        "cycle-a",
        "--patch-id",
        "patch-a",
        "--session-id",
        "session-1",
        "--limit",
        "0",
        "--json",
    ]);
    let output = cmd.assert().success().get_output().stdout.clone();
    let stdout = String::from_utf8(output).unwrap();

    assert!(stdout.contains("\"ops log\""), "{stdout}");
    assert!(stdout.contains("\"state db\""), "{stdout}");
    assert!(stdout.contains("\"codex hook sessions\""), "{stdout}");
    assert!(
        stdout.contains("<22 bytes omitted from diagnosis summary>"),
        "large JSON fields should be summarized instead of dumped:\n{stdout}"
    );
}

#[test]
fn test_cli_audit_docs_finds_claude_md() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();

    std::fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();
    std::fs::write(root.join("CLAUDE.md"), "# Doc\n\nUse serde.\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.arg("audit-docs");
    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("CLAUDE.md"));
}

#[test]
fn test_cli_audit_docs_reports_missing_tree_path() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();

    std::fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();
    std::fs::write(
        root.join("CLAUDE.md"),
        "# Doc\n\n## Project Structure\n\n```\nsrc/\n  missing.rs\n```\n",
    )
    .unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.arg("audit-docs");
    cmd.assert()
        .failure()
        .stdout(predicate::str::contains("Referenced path does not exist"));
}

#[test]
fn test_manifest_uses_publishable_dependency_contract() {
    let manifest_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
    let manifest = fs::read_to_string(manifest_path).unwrap();
    let parsed: toml::Value = toml::from_str(&manifest).unwrap();
    let package_version = parsed["package"]["version"].as_str();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    let agent_kit = dependencies["agent-kit"].as_table().unwrap();

    assert_eq!(
        agent_kit.get("path").and_then(toml::Value::as_str),
        None,
        "published manifests must not depend on a sibling-only agent-kit path"
    );
    assert_eq!(
        agent_kit.get("version").and_then(toml::Value::as_str),
        Some("0.4.1")
    );

    for crate_name in [
        "agent-doc-config",
        "agent-doc-controller-io",
        "agent-doc-codex-hook-io",
        "agent-doc-debounce",
        "agent-doc-diff",
        "agent-doc-diff-io",
        "agent-doc-document-realtime",
        "agent-doc-markdown-ast",
        "agent-doc-ffi",
        "agent-doc-flow",
        "agent-doc-frontmatter",
        "agent-doc-frontmatter-io",
        "agent-doc-fs",
        "agent-doc-hooks-io",
        "agent-doc-ipc-io",
        "agent-doc-ipc-forensics-io",
        "agent-doc-lint-io",
        "agent-doc-memory-io",
        "agent-doc-merge",
        "agent-doc-model-tier",
        "agent-doc-op-capture-io",
        "agent-doc-ops-log-io",
        "agent-doc-owner-pane-io",
        "agent-doc-project-config-io",
        "agent-doc-prompt-context-io",
        "agent-doc-prompt-contract",
        "agent-doc-queue",
        "agent-doc-response-replay-io",
        "agent-doc-response-toc-io",
        "agent-doc-state-backbone",
        "agent-doc-state-wire",
        "agent-doc-status-io",
        "agent-doc-template",
        "agent-doc-template-io",
        "agent-doc-turn",
        "agent-doc-session-accretion-io",
        "agent-doc-sqlite",
        "agent-doc-turn-scope-io",
        "agent-doc-workflow",
        "agent-doc-workflow-io",
        "agent-doc-work-graph",
    ] {
        let dependency = dependencies[crate_name].as_table().unwrap();
        assert!(
            dependency
                .get("path")
                .and_then(toml::Value::as_str)
                .is_some(),
            "{crate_name} should keep a local path for workspace builds"
        );
        assert_eq!(
            dependency.get("version").and_then(toml::Value::as_str),
            package_version,
            "{crate_name} must also carry a registry version for cargo publish"
        );
    }

    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let members = parsed["workspace"]["members"].as_array().unwrap();
    assert!(
        !members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-core")),
        "agent-doc-core must not be retained as an empty facade workspace crate"
    );
    assert!(
        !members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-orchestration")),
        "agent-doc-orchestration must stay retired from the active workspace"
    );
    assert!(
        !dependencies.contains_key("agent-doc-orchestration"),
        "agent-doc-orchestration is retired and must not remain a root dependency"
    );
    assert!(
        !manifest_dir.join("agent-doc-core/Cargo.toml").exists(),
        "agent-doc-core manifest should be deleted once focused crates own the API"
    );

    for manifest in
        std::iter::once(manifest_dir.join("Cargo.toml")).chain(members.iter().map(|member| {
            manifest_dir
                .join(member.as_str().unwrap())
                .join("Cargo.toml")
        }))
    {
        let manifest_content = fs::read_to_string(&manifest).unwrap();
        let parsed_manifest: toml::Value = toml::from_str(&manifest_content).unwrap();
        let dependencies = parsed_manifest
            .get("dependencies")
            .and_then(toml::Value::as_table);
        assert!(
            dependencies.is_none_or(|dependencies| !dependencies.contains_key("agent-doc-core")),
            "{} must not depend on deleted agent-doc-core",
            manifest.display()
        );
    }

    let tmux_router = dependencies["tmux-router"].as_table().unwrap();
    assert_eq!(
        tmux_router.get("path").and_then(toml::Value::as_str),
        Some("../tmux-router")
    );
    assert_eq!(
        tmux_router.get("version").and_then(toml::Value::as_str),
        Some("0.3.20")
    );
}

#[test]
fn test_agent_doc_hooks_io_owns_hook_dispatch_adapters() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let package_version = workspace["package"]["version"].as_str();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-hooks-io")),
        "agent-doc-hooks-io must stay a first-class workspace crate"
    );

    let dependencies = workspace["dependencies"].as_table().unwrap();
    let dependency = dependencies["agent-doc-hooks-io"].as_table().unwrap();
    assert_eq!(
        dependency.get("version").and_then(toml::Value::as_str),
        package_version,
        "root adapter should depend on the versioned hook IO crate"
    );

    let hooks_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-hooks-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&hooks_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-capture-io",
        "agent-doc-frontmatter",
        "agent-doc-document-realtime-io",
        "agent-doc-lease-io",
        "agent-doc-memory-io",
        "agent-doc-model-tier",
        "agent-kit",
    ] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-hooks-io should depend on hook/frontmatter/model focused crate: {required}"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-hooks-io must stay free of orchestration/editor IPC/sqlite/tmux facades: {forbidden}"
        );
    }

    let hooks_io = fs::read_to_string(manifest_dir.join("agent-doc-hooks-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn fire_doc_hooks(",
        "pub fn fire_doc_event(",
        "pub fn fire_doc_event_with_authority(",
        "pub fn fire_post_write(",
        "pub fn fire_post_commit(",
        "pub fn fire_post_write_with_effects(",
        "pub fn fire_post_commit_with_effects(",
        "pub fn fire_claim(",
        "pub fn fire_layout_change(",
        "pub fn poll(",
        "pub trait PostResponseHookEffects",
        "pub struct PostResponseCapture",
        "agent_kit::hooks::{Event, HookRegistry}",
        "std::process::Command::new(\"sh\")",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(\n            file,\n            \"hooks_fire_doc_event\",",
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(\n            file,\n            \"hooks_fire_doc_event_force_disk\",",
        "agent_doc_frontmatter::frontmatter::parse",
        "agent_doc_model_tier::canonical_model_name",
        "fn capture_event_metadata(",
    ] {
        assert!(
            hooks_io.contains(required),
            "agent-doc-hooks-io must own hook dispatch adapter: {required}"
        );
    }
    assert!(
        !hooks_io.contains("std::fs::read_to_string(file)"),
        "agent-doc-hooks-io must not read the active session document directly for hook frontmatter"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/hooks.rs")
            .exists(),
        "orchestration hooks facade should be deleted once hook IO owns post-response adapters"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod hooks;"),
        "orchestration must not expose a public hooks facade"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/hook_effects.rs")
            .exists(),
        "orchestration must not keep a hook_effects facade module"
    );
    for required in [
        "pub struct PostResponseHookEffectFns",
        "pub fn post_response_hook_effects",
        "pub fn default_post_response_hook_effects",
        "impl<Load, Memory, Lease> PostResponseHookEffects",
        "agent_doc_cycle_state_io::load_projected_captured_response",
        "agent_doc_capture_io::load_active(file)",
        "agent_doc_memory_io::closeout::capture_tsift_memory_closeout",
        "agent_doc_lease_io::local_model::reap_local_model_leases",
    ] {
        assert!(
            hooks_io.contains(required),
            "agent-doc-hooks-io must own the post-response hook effects adapter: {required}"
        );
    }
    for forbidden in [
        "agent_kit::hooks",
        "HookRegistry",
        "std::process::Command::new(\"sh\")",
        "post_response_hook_effects() -> impl agent_doc_hooks_io::PostResponseHookEffects",
        "default_post_response_hook_effects()",
        "pub fn fire_doc_hooks(",
        "pub fn fire_doc_event(",
        "pub fn fire_claim(",
        "pub fn fire_layout_change(",
        "pub fn poll(",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration hook bridge must not re-own hook dispatch IO: {forbidden}"
        );
    }

    for (relative, required) in [
        (
            "agent-doc-stream-io/src/lib.rs",
            "effects.fire_post_write(file, &session_id)",
        ),
        (
            "src/main.rs",
            "agent_doc_hooks_io::fire_post_write_with_effects(",
        ),
        (
            "agent-doc-write-runtime-io/src/run_entry.rs",
            "agent_doc_hooks_io::fire_post_write_with_effects(",
        ),
        (
            "agent-doc-commit-io/src/lib.rs",
            "agent_doc_hooks_io::fire_post_commit(file, session_id, None)",
        ),
        (
            "src/main.rs",
            "agent_doc_hooks_io::fire_doc_event(file, \"post_write\")",
        ),
        (
            "agent-doc-write-runtime-io/src/run_entry.rs",
            "agent_doc_hooks_io::fire_doc_event(file, \"post_write\")",
        ),
        (
            "agent-doc-commit-io/src/lib.rs",
            "agent_doc_hooks_io::fire_doc_event_with_authority(",
        ),
        (
            "agent-doc-start-io/src/lib.rs",
            "agent_doc_hooks_io::fire_doc_hooks(",
        ),
        (
            "agent-doc-start-runtime-io/src/supervisor_io.rs",
            "use agent_doc_hooks_io::fire_doc_hooks;",
        ),
        (
            "agent-doc-start-runtime-io/src/lib.rs",
            "use agent_doc_hooks_io::fire_doc_hooks;",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(required),
            "{relative} should call focused hook IO directly: {required}"
        );
    }
}

#[test]
fn test_state_backbone_extraction_stays_first_class_and_facade_free() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let package_version = workspace["package"]["version"].as_str();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-state-backbone")),
        "agent-doc-state-backbone must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-state-observer-io")),
        "agent-doc-state-observer-io must stay a first-class workspace crate"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    let root_dependency = root_dependencies["agent-doc-state-backbone"]
        .as_table()
        .unwrap();
    assert_eq!(
        root_dependency.get("path").and_then(toml::Value::as_str),
        Some("agent-doc-state-backbone")
    );
    assert_eq!(
        root_dependency.get("version").and_then(toml::Value::as_str),
        package_version
    );
    let root_observer_dependency = root_dependencies["agent-doc-state-observer-io"]
        .as_table()
        .unwrap();
    assert_eq!(
        root_observer_dependency
            .get("path")
            .and_then(toml::Value::as_str),
        Some("agent-doc-state-observer-io")
    );
    assert_eq!(
        root_observer_dependency
            .get("version")
            .and_then(toml::Value::as_str),
        package_version
    );

    let state_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/Cargo.toml")).unwrap();
    let state_crate: toml::Value = toml::from_str(&state_manifest).unwrap();
    let state_dependencies = state_crate["dependencies"].as_table().unwrap();
    assert!(
        !state_dependencies.contains_key("agent-doc-orchestration"),
        "state backbone must stay free of orchestration/effect dependencies"
    );
    let observer_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-state-observer-io/Cargo.toml")).unwrap();
    let observer_crate: toml::Value = toml::from_str(&observer_manifest).unwrap();
    let observer_dependencies = observer_crate["dependencies"].as_table().unwrap();
    assert!(
        observer_dependencies.contains_key("agent-doc-state-backbone")
            && observer_dependencies.contains_key("agent-doc-ops-log-io")
            && !observer_dependencies.contains_key("agent-doc-orchestration"),
        "state observer IO should adapt focused state backbone facts to ops-log output without depending on orchestration"
    );
    let observer_source =
        fs::read_to_string(manifest_dir.join("agent-doc-state-observer-io/src/lib.rs")).unwrap();
    assert!(
        observer_source.contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)"),
        "state observer advisory closeout phase should use the projection-aware cycle view"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/state_backbone.rs")
            .exists(),
        "orchestration must not keep a state_backbone source module facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/adstatechart_snapshot.rs")
            .exists(),
        "orchestration must not keep an adstatechart_snapshot observer facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod state_backbone"),
        "orchestration must not re-export state_backbone as a compatibility facade"
    );
    assert!(
        !orchestration_lib.contains("pub mod adstatechart_snapshot"),
        "orchestration must not re-export adstatechart observer IO as a compatibility facade"
    );

    for relative_path in [
        "src/orchestrate.rs",
        "src/ffi.rs",
        "src/sim_world.rs",
        "tests/run_integration.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            !source.contains("agent_doc_orchestration::state_backbone"),
            "{relative_path} must use agent_doc_state_backbone directly"
        );
    }
}

#[test]
fn test_agent_doc_serve_active_cycle_reads_projection_aware_state() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let serve_source = fs::read_to_string(manifest_dir.join("src/serve.rs")).unwrap();

    assert!(
        serve_source.contains("agent_doc_cycle_state_io::load_with_closeout_projection(doc)?"),
        "serve active response/write routing should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        !serve_source.contains("agent_doc_cycle_state_io::load(doc)?"),
        "serve active response/write routing must not use raw compatibility cycle sidecars"
    );
}

#[test]
fn test_state_wire_extraction_stays_first_class_and_facade_free() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let package_version = workspace["package"]["version"].as_str();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-state-wire")),
        "agent-doc-state-wire must stay a first-class workspace crate"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    let root_dependency = root_dependencies["agent-doc-state-wire"]
        .as_table()
        .unwrap();
    assert_eq!(
        root_dependency.get("path").and_then(toml::Value::as_str),
        Some("agent-doc-state-wire")
    );
    assert_eq!(
        root_dependency.get("version").and_then(toml::Value::as_str),
        package_version
    );

    let state_wire_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-state-wire/Cargo.toml")).unwrap();
    let state_wire: toml::Value = toml::from_str(&state_wire_manifest).unwrap();
    let state_wire_dependencies = state_wire["dependencies"].as_table().unwrap();
    assert!(
        state_wire_dependencies.contains_key("agent-doc-state-backbone"),
        "state wire must consume the extracted state backbone directly"
    );
    for forbidden_dependency in ["agent-doc-orchestration", "agent-doc-workflow"] {
        assert!(
            !state_wire_dependencies.contains_key(forbidden_dependency),
            "state wire must stay free of orchestration/workflow facade dependencies: {forbidden_dependency}"
        );
    }

    for removed_module in [
        "agent-doc-orchestration/src/state_wire.rs",
        "agent-doc-workflow/src/state_wire.rs",
    ] {
        assert!(
            !manifest_dir.join(removed_module).exists(),
            "{removed_module} must not remain as a state-wire facade module"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod state_wire"),
        "orchestration must not re-export state_wire as a compatibility facade"
    );
    let workflow_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/lib.rs")).unwrap();
    assert!(
        !workflow_lib.contains("pub mod state_wire"),
        "workflow must not re-export state_wire as a compatibility facade"
    );

    let ffi_source = fs::read_to_string(manifest_dir.join("src/ffi.rs")).unwrap();
    assert!(
        ffi_source.contains("agent_doc_state_wire::subscribe"),
        "FFI subscribe path must call the focused state-wire crate directly"
    );
    assert!(
        !ffi_source.contains("agent_doc_orchestration::state_wire")
            && !ffi_source.contains("agent_doc_workflow::state_wire"),
        "FFI subscribe path must not use removed state-wire facades"
    );
}

#[test]
fn test_turn_scope_io_extraction_stays_first_class_and_facade_free() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let package_version = workspace["package"]["version"].as_str();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-turn-scope-io")),
        "agent-doc-turn-scope-io must stay a first-class workspace crate"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    let root_dependency = root_dependencies["agent-doc-turn-scope-io"]
        .as_table()
        .unwrap();
    assert_eq!(
        root_dependency.get("path").and_then(toml::Value::as_str),
        Some("agent-doc-turn-scope-io")
    );
    assert_eq!(
        root_dependency.get("version").and_then(toml::Value::as_str),
        package_version
    );

    let turn_scope_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-scope-io/Cargo.toml")).unwrap();
    let turn_scope: toml::Value = toml::from_str(&turn_scope_manifest).unwrap();
    let turn_scope_dependencies = turn_scope["dependencies"].as_table().unwrap();
    assert!(
        turn_scope_dependencies.contains_key("agent-doc-turn")
            && turn_scope_dependencies.contains_key("agent-doc-fs"),
        "turn-scope IO must depend only on turn models plus filesystem path helpers"
    );
    for forbidden_dependency in ["agent-doc-core", "agent-doc-orchestration"] {
        assert!(
            !turn_scope_dependencies.contains_key(forbidden_dependency),
            "turn-scope IO must not depend on removed core/orchestration facades: {forbidden_dependency}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/turn_scope_store.rs")
            .exists(),
        "orchestration must not keep a turn_scope_store facade module"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod turn_scope_store"),
        "orchestration must not export a turn_scope_store facade"
    );
    for relative_path in [
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-preflight-command-io/src/run.rs",
        "tests/run_integration.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_turn_scope_io::"),
            "{relative_path} must call the focused turn-scope IO crate directly"
        );
        assert!(
            !source.contains("crate::turn_scope_store")
                && !source.contains("agent_doc_orchestration::turn_scope_store"),
            "{relative_path} must not use the removed orchestration turn-scope facade"
        );
    }
}

#[test]
fn test_agent_doc_model_tier_owns_context_usage_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-model-tier")),
        "agent-doc-model-tier must stay a first-class workspace crate"
    );

    let model_tier_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-model-tier/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&model_tier_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(
        dependencies.contains_key("serde_json"),
        "context transcript token parsing belongs in agent-doc-model-tier and needs serde_json"
    );
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-model-tier context usage policy must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }

    let model_tier_source =
        fs::read_to_string(manifest_dir.join("agent-doc-model-tier/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn canonical_harness_name(",
        "pub const HARNESS_MISMATCH_WARNING_CODE",
        "pub struct HarnessMismatchWarning",
        "pub fn harness_mismatch_warning(",
        "pub const CODEX_NETWORK_ACCESS_NON_CODEX_HARNESS_WARNING_CODE",
        "pub struct CodexNetworkAccessNonCodexHarnessWarning",
        "pub fn codex_network_access_non_codex_harness_warning(",
        "pub fn short_model_name(",
        "pub fn resolve_agent_model(",
    ] {
        assert!(
            model_tier_source.contains(required_snippet),
            "agent-doc-model-tier should own preflight model attribution and harness policy directly: {required_snippet}"
        );
    }

    let context_usage =
        fs::read_to_string(manifest_dir.join("agent-doc-model-tier/src/context_usage.rs")).unwrap();
    for required_snippet in [
        "pub enum Harness",
        "pub struct UsedTokens",
        "pub const CLAUDE_CONTEXT_WINDOW",
        "pub fn claude_project_hash(",
        "pub fn claude_transcript_path(",
        "pub fn claude_projects_subdir(",
        "pub fn parse_claude_jsonl_used_tokens(",
        "pub fn context_window_for_model(",
        "pub fn context_pct(",
        "pub enum TranscriptContextPctDiagnostic",
        "pub struct TranscriptContextPct",
        "pub fn transcript_context_pct_from_content(",
        "pub fn parse_codex_jsonl_context_pct(",
        "pub fn parse_codex_jsonl_session_meta_cwd(",
        "pub struct ClearDecision",
        "pub fn clear_decision(",
    ] {
        assert!(
            context_usage.contains(required_snippet),
            "agent-doc-model-tier should own context usage policy directly: {required_snippet}"
        );
    }

    let context_transcript_io =
        fs::read_to_string(manifest_dir.join("agent-doc-model-tier/src/context_transcript_io.rs"))
            .unwrap();
    for required_snippet in [
        "pub fn read_used_tokens(",
        "pub fn transcript_context_pct(",
        "pub fn latest_claude_transcript(",
        "pub fn latest_codex_transcript(",
    ] {
        assert!(
            context_transcript_io.contains(required_snippet),
            "agent-doc-model-tier should own transcript locator/read IO directly: {required_snippet}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let orchestration_context_path =
        manifest_dir.join("agent-doc-orchestration/src/context_pct.rs");
    assert!(
        !orchestration_context_path.exists(),
        "orchestration must not keep a context_pct adapter module after transcript IO extraction"
    );
    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_warnings_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    for forbidden_snippet in [
        "fn canonical_harness_name(",
        "fn harness_mismatch_warning(",
        "fn codex_network_access_non_codex_harness_warning(",
        "fn short_model_name(",
        "fn resolve_agent_model(",
    ] {
        assert!(
            !preflight_source.contains(forbidden_snippet),
            "preflight.rs must not re-own model-tier attribution or harness policy: {forbidden_snippet}"
        );
        assert!(
            !preflight_run_source.contains(forbidden_snippet),
            "preflight/run.rs must not re-own model-tier attribution or harness policy: {forbidden_snippet}"
        );
    }
    // `#n39j` / `#queuepersiststall`: when queue maintenance fails to PERSIST,
    // preflight must report the queue's REAL drainability by probing it
    // read-only, never a zeroed `QueueState::default()`. Those two are
    // indistinguishable to the loop gate, so a persistence failure silently
    // presenting as "queue empty" stalls a drain that still has work — observed
    // live (0 -> 14 drainable on brookebrodack-dev.md).
    //
    // Reproducing the real failure needs a simulated editor-authority outage,
    // so this pins the CONTRACT at the branch instead: the probe is called, and
    // the zeroed default survives only as the probe's own last resort.
    assert!(
        preflight_run_source.contains("inspect_queue_state(file, diff_result.as_deref())"),
        "the queue-maintenance persist-failure branch must probe real drainability (#queuepersiststall)"
    );
    assert!(
        preflight_run_source
            .contains("inspect_queue_state(file, diff_result.as_deref()).unwrap_or_else("),
        "the zeroed QueueState::default() must remain the PROBE's fallback (`unwrap_or_else`), never the \
         primary persist-failure answer (#queuepersiststall)"
    );

    assert!(
        preflight_warnings_source.contains("agent_doc_model_tier::harness_mismatch_warning(")
            && preflight_warnings_source
                .contains("agent_doc_model_tier::codex_network_access_non_codex_harness_warning(")
            && preflight_run_source.contains("agent_doc_model_tier::resolve_agent_model("),
        "preflight runtime/warnings should adapt preflight facts into focused model-tier policy directly"
    );
    assert!(
        preflight_source.contains("agent_doc_model_tier::canonical_harness_name("),
        "preflight tests should call focused model-tier canonical harness policy directly"
    );
    for forbidden_snippet in [
        "pub enum Harness",
        "pub struct UsedTokens",
        "pub const CLAUDE_CONTEXT_WINDOW",
        "pub fn claude_project_hash(",
        "pub fn claude_transcript_path(",
        "pub fn claude_projects_subdir(",
        "pub fn parse_claude_jsonl_used_tokens(",
        "pub fn context_window_for_model(",
        "pub fn context_pct(",
        "pub enum TranscriptContextPctDiagnostic",
        "pub struct TranscriptContextPct",
        "pub fn transcript_context_pct_from_content(",
        "pub fn parse_codex_jsonl_context_pct(",
        "pub fn parse_codex_jsonl_session_meta_cwd(",
        "pub struct ClearDecision",
        "pub fn clear_decision(",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden_snippet),
            "orchestration lib must not expose context usage policy or transcript IO: {forbidden_snippet}"
        );
    }
    assert!(
        !orchestration_lib.contains("pub mod context_pct;"),
        "orchestration must not keep a context_pct adapter module after transcript IO extraction"
    );

    let codex_hook_io =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-hook-io/src/lib.rs")).unwrap();
    assert!(
        codex_hook_io.contains("use agent_doc_model_tier::context_usage::{")
            && codex_hook_io.contains("use agent_doc_model_tier::context_transcript_io::{")
            && codex_hook_io.contains("clear_decision")
            && codex_hook_io.contains("Harness"),
        "focused Codex hook IO should use focused context usage policy and transcript IO directly"
    );
    let codex_hook =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-stop-io/src/lib.rs")).unwrap();
    assert!(
        !codex_hook.contains("agent_doc_model_tier::context_usage")
            && !codex_hook.contains("agent_doc_model_tier::context_transcript_io")
            && !codex_hook.contains("clear_decision"),
        "orchestration Codex Stop handler must not re-own context usage policy or transcript IO"
    );
}

#[test]
fn test_agent_doc_codex_hook_io_owns_blocked_stop_payload_sidecar() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-codex-hook-io")),
        "agent-doc-codex-hook-io must stay a first-class workspace crate"
    );
    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-codex-hook-io"),
        "root crate should expose focused Codex hook IO directly"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-codex-hook-io"),
        "agent-doc-orchestration should call the focused Codex hook IO crate"
    );

    let codex_hook_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-hook-io/Cargo.toml")).unwrap();
    let codex_hook_io_manifest: toml::Value = toml::from_str(&codex_hook_io_manifest).unwrap();
    let codex_hook_io_dependencies = codex_hook_io_manifest["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-hash",
        "agent-doc-model-tier",
        "agent-doc-ops-log-io",
        "agent-doc-prompt-contract",
        "agent-doc-project-root-io",
        "agent-doc-queue",
        "agent-doc-session-accretion-io",
        "anyhow",
        "serde",
        "serde_json",
        "toml",
    ] {
        assert!(
            codex_hook_io_dependencies.contains_key(required),
            "agent-doc-codex-hook-io should depend on blocked-stop sidecar dependency: {required}"
        );
    }
    for forbidden in [
        "agent-doc-fs",
        "agent-doc-orchestration",
        "agent-doc-tmux-io",
        "tmux-router",
    ] {
        assert!(
            !codex_hook_io_dependencies.contains_key(forbidden),
            "agent-doc-codex-hook-io must stay focused on Codex hook sidecars: {forbidden}"
        );
    }

    let codex_hook_io =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-hook-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn project_root_for(",
        "pub fn project_roots_for(",
        "pub fn tracking_roots(",
        "pub fn push_unique_root(",
        "pub struct SessionState",
        "pub struct ActiveSessionState",
        "pub struct UserPromptSubmitInput",
        "pub fn handle_user_prompt_submit(",
        "pub fn apply_user_prompt_submit(",
        "pub fn resolve_agent_doc_path(",
        "pub fn load_state_any(",
        "pub fn clear_state_across_roots(",
        "pub fn save_state_across_roots(",
        "pub fn load_state(",
        "pub fn save_state(",
        "pub fn clear_state(",
        "pub fn current_session_id(",
        "pub fn load_prompt_for_current_session(",
        "pub fn load_latest_prompt_for_file(",
        "pub fn load_latest_prompt_state_for_file(",
        "pub fn load_active_session_for_current_file(",
        "pub fn record_external_prompt_for_file(",
        "pub fn prompt_requests_clear(",
        "pub fn agent_doc_mcp_configured_for(",
        "pub fn is_context_clear_prompt(",
        "pub fn codex_live_context_pct(",
        "pub fn codex_queue_context_reset_reason(",
        "pub fn codex_continuation_clear_reason(",
        "pub fn log_codex_stop_queue_continuation(",
        "pub fn log_codex_background_context_clear_suppressed(",
        "latest_codex_transcript(",
        "transcript_context_pct(Harness::Codex",
        "clear_decision(true, pct, threshold)",
        "queue_context_reset_reason_if_opted_in(",
        "agent_doc_sqlite::state_store::load_project_runtime_state_from_db(",
        "agent_doc_sqlite::state_store::upsert_project_runtime_state_in_db(",
        "pub fn save_blocked_stop_payload(",
        "struct BlockedStopPayloadRecord",
        ".agent-doc/codex-hooks/blocked-stop",
        "agent_doc_project_root_io::project_root_containing(",
        "agent_doc_hash::content_hash(",
    ] {
        assert!(
            codex_hook_io.contains(required),
            "agent-doc-codex-hook-io should own Codex blocked-stop sidecar persistence: {required}"
        );
    }

    let codex_hook =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-stop-io/src/lib.rs")).unwrap();
    for forbidden in [
        "struct BlockedStopPayloadRecord",
        "fn save_blocked_stop_payload(",
        "fn project_roots_for(",
        "fn tracking_roots(",
        "fn find_git_root(",
        "pub struct ActiveSessionState",
        "struct SessionState",
        "fn load_state_any(",
        "fn clear_state_across_roots(",
        "fn save_state_across_roots(",
        "fn load_state(",
        "pub fn load_prompt_for_current_session(",
        "pub fn load_latest_prompt_for_file(",
        "pub fn load_latest_prompt_state_for_file(",
        "pub fn record_external_prompt_for_file(",
        "pub fn load_active_session_for_current_file(",
        "fn load_latest_state_for_file(",
        "fn save_state(",
        "fn clear_state(",
        "fn state_path(",
        "fn current_session_id(",
        "struct UserPromptSubmitInput",
        "fn handle_user_prompt_submit(",
        "fn apply_user_prompt_submit(",
        "fn resolve_agent_doc_path(",
        "fn agent_doc_mcp_configured_for(",
        "fn is_context_clear_prompt(",
        "fn codex_live_context_pct(",
        "fn codex_queue_context_reset_reason(",
        "fn codex_continuation_clear_reason(",
        "fn log_codex_stop_queue_continuation(",
        "fn log_codex_background_context_clear_suppressed(",
        "latest_codex_transcript(",
        "clear_decision(true,",
        "agent_doc_fs::find_project_root(",
        "resolve project root for blocked stop payload",
        "write blocked stop payload",
    ] {
        assert!(
            !codex_hook.contains(forbidden),
            "codex_hook.rs must not re-own blocked-stop sidecar persistence: {forbidden}"
        );
    }
    assert!(
        codex_hook.contains("use agent_doc_codex_hook_io::{")
            && codex_hook.contains("project_roots_for")
            && codex_hook.contains("tracking_roots")
            && codex_hook.contains("load_state_any")
            && codex_hook.contains("save_state_across_roots")
            && codex_hook.contains("agent_doc_codex_hook_io::save_blocked_stop_payload(")
            && codex_hook.contains("agent_doc_codex_hook_io::codex_continuation_clear_reason")
            && codex_hook.contains("agent_doc_codex_hook_io::agent_doc_mcp_configured_for"),
        "codex_hook.rs should call focused Codex hook IO directly"
    );
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let preflight_hook_source =
        fs::read_to_string(manifest_dir.join("src/preflight_hook.rs")).unwrap();
    assert!(
        main_source.contains("preflight_hook::handle_codex_user_prompt_submit()")
            && !main_source
                .contains("agent_doc_orchestration::codex_hook::handle_user_prompt_submit()"),
        "Codex UserPromptSubmit should route to the binary-owned combined admission hook"
    );
    assert!(
        preflight_hook_source.contains("agent_doc_codex_hook_io::apply_user_prompt_submit(&input)")
            && preflight_hook_source.contains("run_preflight_for_prompt(")
            && preflight_hook_source.contains("&input.prompt,"),
        "combined Codex admission must use focused tracking IO before binary preflight"
    );
}

/// `#hookcontractlost`: a `UserPromptSubmit` hook injects **stdout** as turn
/// context, so preflight diagnostics that go only to stderr reach the operator's
/// log and never the agent. A refusing hook then looks exactly like a hook that
/// never ran, and the agent has no reason and no remedy.
///
/// The hook must therefore always name its outcome inside one valid
/// UserPromptSubmit JSON envelope: the contract marker on success, or an
/// explicit machine-readable admission-failure marker.
#[test]
fn test_preflight_hook_never_emits_silence_on_admission_failure() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_hook_source =
        fs::read_to_string(manifest_dir.join("src/preflight_hook.rs")).unwrap();

    for required in [
        "pub const ADMISSION_FAILURE_MARKER",
        "fn emit_user_prompt_submit_context(",
        "\"hookEventName\": \"UserPromptSubmit\"",
        "\"additionalContext\": context",
        "fn emit_admission_failure(",
        "emit_user_prompt_submit_context(&format!(",
        "reason: {err:#}",
        "emit_admission_failure(&file.display().to_string(), &err)",
    ] {
        assert!(
            preflight_hook_source.contains(required),
            "preflight hook must emit a machine-readable admission failure: {required}"
        );
    }

    // The failure marker is injected context, so it must stay in the stdout
    // response envelope — the whole defect was a diagnostic that only ever
    // reached stderr.
    assert!(
        !preflight_hook_source.contains("eprintln!(\"{ADMISSION_FAILURE_MARKER}\")")
            && preflight_hook_source.contains("println!(\"{output}\")"),
        "the admission-failure marker must reach the agent through valid hook JSON on stdout"
    );

    // Admission still failed, so the failure marker must stay distinct from the
    // success seal; the skill keys "a cycle was opened" off the contract marker.
    let marker_literal = |name: &str| -> String {
        let anchor = format!("pub const {name}: &str =");
        let start = preflight_hook_source
            .find(&anchor)
            .unwrap_or_else(|| panic!("{name} must be declared"))
            + anchor.len();
        let rest = &preflight_hook_source[start..];
        let open = rest.find('"').expect("marker literal must be a string");
        let close = rest[open + 1..]
            .find('"')
            .expect("marker literal unterminated");
        rest[open + 1..open + 1 + close].to_string()
    };
    let contract = marker_literal("CONTRACT_MARKER");
    let failure = marker_literal("ADMISSION_FAILURE_MARKER");
    assert_ne!(
        contract, failure,
        "an admission failure must never be mistaken for an opened cycle"
    );
    assert!(
        !failure.contains(&contract),
        "the failure marker must not embed the contract marker a skill greps for"
    );
}

#[test]
fn test_agent_doc_repair_io_owns_repair_state_adapters() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-repair-io")),
        "agent-doc-repair-io must stay a first-class workspace crate"
    );
    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-repair-io"),
        "root crate should expose focused repair IO directly"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-repair-io"),
        "agent-doc-orchestration should call the focused repair IO crate"
    );

    let repair_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/Cargo.toml")).unwrap();
    let repair_io_manifest: toml::Value = toml::from_str(&repair_io_manifest).unwrap();
    let repair_io_dependencies = repair_io_manifest["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-capture-io",
        "agent-doc-codex-hook-io",
        "agent-doc-cycle-state-io",
        "agent-doc-document",
        "agent-doc-document-realtime",
        "agent-doc-element",
        "agent-doc-element-backlog",
        "agent-doc-element-backlog-io",
        "agent-doc-flow",
        "agent-doc-flow-io",
        "agent-doc-frontmatter",
        "agent-doc-fs",
        "agent-doc-git",
        "agent-doc-git-io",
        "agent-doc-hash",
        "agent-doc-ops-log-io",
        "agent-doc-project-root-io",
        "agent-doc-session-check-io",
        "agent-doc-snapshot-io",
        "agent-doc-template",
        "agent-doc-template-io",
        "agent-doc-turn",
        "agent-doc-turn-scope-io",
        "agent-doc-write-converge-io",
        "agent-doc-workflow",
        "anyhow",
        "serde",
        "serde_json",
    ] {
        assert!(
            repair_io_dependencies.contains_key(required),
            "agent-doc-repair-io should depend on focused repair-state dependency: {required}"
        );
    }
    for forbidden in ["agent-doc-orchestration", "agent-doc-tmux-io"] {
        assert!(
            !repair_io_dependencies.contains_key(forbidden),
            "agent-doc-repair-io must stay focused on repair state: {forbidden}"
        );
    }

    let repair_io =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn save_blocked_repair_payload(",
        "pub fn repair_committed_historical_snapshot_drift(",
        "pub fn recover_missing_commit_boundary(",
        "pub fn repair_completed_backlog_items(",
        "pub fn repair_stale_preflight_started_cycle(",
        "pub fn cancel_preflight_cycle(",
        "fn cycle_has_captured_response_projection(",
        "fn projected_committed_capture_response_body(",
        "fn projected_committed_capture_response(",
        "pub struct HistoricalCommittedCapture",
        "pub fn historical_committed_capture_replay(",
        "pub fn visible_response_patch_from_document(",
        "pub fn head_already_matches_current_doc(",
        "pub fn retire_stale_capture_if_drifted(",
        "pub fn respect_manual_exchange_tail_removal_if_safe(",
        "pub struct RepairCoordinatorEffects",
        "pub fn recover_empty_response_for_strict_closeout<",
        "pub fn run_with_queue_completion_ids<",
        "pub fn repair<",
        "pub trait RepairIoEffects",
        "pub trait RepairStrictReplayWriteEffects",
        "pub trait RepairFallbackWriteEffects",
        "pub trait RepairRecoveredQueueHeadEffects",
        "pub trait RepairReplayWriteEffects",
        "fn apply_closeout_recovery_mutation(",
        "struct BlockedRepairPayloadRecord",
        ".agent-doc/repair-blocked",
        "agent_doc_project_root_io::project_root_containing(",
        "agent_doc_hash::content_hash(",
        "agent_doc_git_io::revision::show_head(",
        "agent_doc_element_backlog::backlog::reap_with_items(",
        "agent_doc_session_check_io::detect_bypassed_response_write(",
        "agent_doc_session_check_io::realtime_steering_since_turn_baseline(",
        "agent_doc_flow_io::closeout::log_closeout_guard_event(",
        "agent_doc_frontmatter::frontmatter::parse(",
        "visible_response_recovery_is_adoptable(",
        "response_replay::response_already_applied(",
        "repair_adopt_existing_response file=",
        "agent_doc_workflow::capture::decide_stale_capture_retirement(",
        "agent_doc_capture_io::replay_baseline_drifted_with_current_content(",
        "agent_doc_capture_io::validate_replay_with_current_content(",
        "agent_doc_capture_io::mark_committed_with_current_content(",
        "agent_doc_cycle_state_io::load_closeout_projection(file)?",
        "agent_doc_cycle_state_io::load_projected_captured_response(file, capture_id)?",
        "projection.captured_response.is_some()",
        "agent_doc_template::strip_conversation_tail_outside_exchange(",
    ] {
        assert!(
            repair_io.contains(required),
            "agent-doc-repair-io should own repair IO persistence and recovery repair graphs: {required}"
        );
    }
    assert!(
        repair_io.contains("pub mod pending;")
            && repair_io.contains("pub use pending::{clear_pending, save_pending};"),
        "agent-doc-repair-io should expose retained response intent IO"
    );
    let pending_io =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/pending.rs")).unwrap();
    for required in [
        "pub fn save_pending(",
        "pub fn clear_pending(",
        "agent_doc_template_io::canonicalize_response_for_capture(",
        "agent_doc_capture_io::capture_response_with_intent(",
        "agent_doc_snapshot_io::clear_undo_content(",
        "agent_doc_capture_io::mark_write_applied(",
    ] {
        assert!(
            pending_io.contains(required),
            "agent-doc-repair-io pending module should own retained response intent IO: {required}"
        );
    }

    let repair =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/tests/repair.rs"))
            .unwrap();
    let commit_io =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    for forbidden in [
        "struct BlockedRepairPayloadRecord",
        "fn save_blocked_repair_payload(",
        "resolve project root for blocked repair payload",
        "write blocked repair payload",
        "agent_doc_fs::find_project_root(",
        "canonicalize_response_for_capture(",
        "agent_doc_capture_io::capture_response(file",
        "std::fs::write(&pending_path",
        "agent_doc_snapshot_io::clear_undo_content(file",
        "agent_doc_capture_io::mark_write_applied(file",
        "pub fn save_pending(",
        "pub fn clear_pending(",
        "pub fn recover_missing_commit_boundary(",
        "pub fn repair_stale_preflight_started_cycle(",
        "pub fn cancel_preflight_cycle(",
        "fn historical_committed_capture_replay(",
        "fn visible_response_patch_from_document(",
        "fn head_already_matches_current_doc(",
        "fn repair_completed_backlog_items(",
        "fn retire_stale_capture_if_drifted(",
        "fn respect_manual_exchange_tail_removal_if_safe(",
        "visible_response_recovery_is_adoptable(",
        "response_replay::response_already_applied(",
        "repair_adopt_existing_response file=",
        "fn discard_pending_capture_for_manual_repair(",
        "agent_doc_capture_io::replay_baseline_drifted(",
        "agent_doc_template::strip_conversation_tail_outside_exchange(",
        "HashSet::new()",
    ] {
        assert!(
            !repair.contains(forbidden),
            "repair.rs must not re-own repair IO graph persistence/recovery: {forbidden}"
        );
    }
    assert!(
        !commit_io.contains("pub fn repair_committed_historical_snapshot_drift(")
            && commit_io
                .contains("agent_doc_repair_io::repair_committed_historical_snapshot_drift("),
        "commit lifecycle must call focused repair IO for committed historical snapshot drift repair"
    );
    let codex_hook =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-stop-io/src/lib.rs")).unwrap();
    assert!(
        repair_io.contains("pub fn save_blocked_repair_payload(")
            && repair_io.contains("pub fn run_with_queue_completion_ids<")
            && codex_hook.contains("agent_doc_repair_io::run_with_queue_completion_ids(")
            && repair.contains("agent_doc_repair_runtime_io::repair_coordinator_effects(")
            && repair.contains("agent_doc_repair_io::repair(")
            && !repair.contains("pub fn run(file: &Path)"),
        "repair callers should adapt into the focused repair IO coordinator without a public orchestration run facade"
    );
    let closeout_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-closeout-runtime-io/src/lib.rs")).unwrap();
    assert!(
        closeout_runtime.contains("agent_doc_repair_io::cancel_preflight_cycle("),
        "closeout runtime effects should route preflight cancel repair through focused repair IO"
    );
    for relative in [
        "agent-doc-codex-stop-io/src/lib.rs",
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "src/main.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert_source_mentions_all(
            &source,
            relative,
            &["agent_doc_repair_io::pending::save_pending"],
        );
        assert_source_omits_all(
            &source,
            relative,
            &[
                "crate::repair::save_pending(",
                "crate::repair::clear_pending(",
                "repair::save_pending(",
                "repair::clear_pending(",
                "agent_doc_orchestration::repair::save_pending(",
                "agent_doc_orchestration::repair::clear_pending(",
            ],
        );
    }
}

#[test]
fn test_repair_io_owns_strict_empty_response_recovery() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let repair =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/tests/repair.rs"))
            .unwrap();
    let repair_command =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/src/lib.rs")).unwrap();
    let repair_io =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    let write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    let main = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();

    assert!(
        repair_io.contains("pub fn recover_empty_response_for_strict_closeout<"),
        "agent-doc-repair-io should own strict empty-response closeout recovery coordination"
    );
    assert!(
        repair_command.contains("agent_doc_repair_io::recover_empty_response_for_strict_closeout("),
        "repair command IO should delegate strict empty-response closeout recovery to repair IO"
    );
    assert!(
        repair_command.contains("pub fn run_write_command_with_empty_response_recovery("),
        "repair command IO should own the write-command recovery bridge"
    );
    assert!(
        !repair.contains("pub fn run_write_command_with_empty_response_recovery("),
        "orchestration repair should not expose the write-command recovery bridge"
    );
    assert!(
        !write.contains("fn recover_empty_response_for_strict_closeout("),
        "write.rs must not re-own strict empty-response closeout recovery coordination"
    );
    for required in [
        "run_with_queue_completion_ids_and_force_disk(effects, file, &[], force_disk_override)?",
        "recover_missing_committed_head_response",
        "recover_dedupe_only_drift",
        "committing pending mutations without a response body",
    ] {
        assert!(
            repair_io.contains(required),
            "agent-doc-repair-io must own strict empty-response recovery marker: {required}"
        );
    }
    for forbidden in [
        "let outcome = run(file)?;",
        "write::recover_missing_committed_head_response",
        "write::recover_dedupe_only_drift",
        "committing pending mutations without a response body",
    ] {
        assert!(
            !repair.contains(forbidden),
            "orchestration repair must not duplicate strict empty-response recovery marker: {forbidden}"
        );
    }
    assert_source_mentions_all(
        &main,
        "src/main.rs",
        &["agent_doc_repair_command_io::run_write_command_with_empty_response_recovery("],
    );
    assert!(
        !write_run_entry.contains("crate::repair::"),
        "write/run_entry.rs must not call repair; empty-response recovery belongs at the repair-owned command boundary"
    );
    assert!(
        write.contains("pub(crate) struct WriteFlags") && !write.contains("pub struct WriteFlags"),
        "write.rs must not expose WriteFlags as a public orchestration DTO"
    );
    assert!(
        write.contains("pub(crate) use run_entry::*;") && !write.contains("pub use run_entry::*;"),
        "write.rs should keep run_entry helpers crate-visible instead of re-exporting them publicly"
    );
    for forbidden in [
        "pub fn run(",
        "pub fn run_template(",
        "pub fn run_stream(",
        "pub fn run_ipc(",
        "pub fn apply_template_from_string(",
    ] {
        assert!(
            !write_run_entry.contains(forbidden),
            "write/run_entry.rs must not expose public command entrypoint facades: {forbidden}"
        );
    }
    assert_source_mentions_all(
        &write_run_entry,
        "agent-doc-write-runtime-io/src/run_entry.rs",
        &[
            "pub fn apply_append_from_string(",
            "pub fn apply_template_from_string_with_options(",
        ],
    );
}

#[test]
fn test_orchestration_write_uses_closeout_commit_adapter() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();

    assert!(
        !write.contains("crate::git::commit("),
        "write.rs must not call git directly; commit ownership belongs behind closeout effects"
    );
    assert!(
        !write.contains("fn commit_via_closeout_effects(")
            && write
                .contains("agent_doc_flow_io::closeout::CloseoutEffects::commit_for_authority(")
            && write.contains("&agent_doc_closeout_runtime_io::closeout_effects()"),
        "write.rs should route commit boundaries through the injected closeout effects adapter without a local helper facade"
    );
}

#[test]
fn test_agent_doc_prompt_cache_owns_prompt_cache_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-prompt-cache")),
        "agent-doc-prompt-cache must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-prompt-cache-io")),
        "agent-doc-prompt-cache-io must stay a first-class workspace crate"
    );

    let prompt_cache_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-cache/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub const PROMPT_CACHE_BOUNDARY",
        "pub const PROMPT_CACHE_CONTROL",
        "pub struct PromptCacheBlocks",
        "pub struct PromptCacheReplayKey",
        "pub struct PromptCacheSessionCostSample",
        "pub struct PromptCacheEffectivenessSample",
        "pub struct PromptCacheMissCause",
        "pub struct PromptCacheTrendThresholds",
        "pub enum PromptCacheTrendStatus",
        "pub struct PromptCacheTrendCheck",
        "pub fn render_prompt_cache_blocks",
        "pub fn rank_cache_miss_causes",
        "pub fn check_prompt_cache_effectiveness_trend",
        "pub fn render_cache_miss_ranking",
    ] {
        assert!(
            prompt_cache_source.contains(required_snippet),
            "prompt-cache policy crate must own {required_snippet}"
        );
    }

    let prompt_cache_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-cache/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&prompt_cache_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(dependencies.contains_key("serde"));
    assert!(dependencies.contains_key("sha2"));
    for forbidden in [
        "agent-doc-controller",
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-project-config-io",
        "agent-doc-tmux-commands",
        "agent-doc-tmux-io",
        "anyhow",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-prompt-cache must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }

    let prompt_cache_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-cache-io/Cargo.toml")).unwrap();
    let prompt_cache_io: toml::Value = toml::from_str(&prompt_cache_io_manifest).unwrap();
    let prompt_cache_io_dependencies = prompt_cache_io["dependencies"].as_table().unwrap();
    assert!(
        prompt_cache_io_dependencies.contains_key("agent-doc-prompt-cache"),
        "prompt-cache IO must depend on the focused prompt-cache policy crate"
    );
    for forbidden in ["agent-doc-core", "agent-doc-orchestration"] {
        assert!(
            !prompt_cache_io_dependencies.contains_key(forbidden),
            "prompt-cache IO must not depend on removed core/orchestration facades: {forbidden}"
        );
    }

    let prompt_cache_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-cache-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub use agent_doc_prompt_cache",
        "pub const PROMPT_CACHE_BOUNDARY",
        "pub const PROMPT_CACHE_CONTROL",
        "pub struct PromptCacheBlocks",
        "pub struct PromptCacheReplayKey",
        "pub struct PromptCacheSessionCostSample",
        "pub struct PromptCacheEffectivenessSample",
        "pub struct PromptCacheMissCause",
        "pub struct PromptCacheTrendThresholds",
        "pub enum PromptCacheTrendStatus",
        "pub struct PromptCacheTrendCheck",
        "pub fn render_prompt_cache_blocks",
        "pub fn rank_cache_miss_causes",
        "pub fn check_prompt_cache_effectiveness_trend",
        "pub fn render_cache_miss_ranking",
        "fn cached_input_loss",
        "fn creation_token_spike",
        "fn content_sha256",
    ] {
        assert!(
            !prompt_cache_io_source.contains(forbidden_snippet),
            "prompt-cache IO must not define or re-export prompt-cache policy: {forbidden_snippet}"
        );
    }
    assert!(
        prompt_cache_io_source.contains("append_prompt_cache_effectiveness_sample")
            && prompt_cache_io_source.contains("load_prompt_cache_effectiveness_history"),
        "prompt-cache history file IO adapters should live in the focused IO crate"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt_cache.rs")
            .exists(),
        "orchestration must not keep a prompt_cache source module facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod prompt_cache"),
        "orchestration must not export a prompt_cache facade"
    );

    let run_source = fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    assert!(
        run_source.contains("use agent_doc_prompt_cache::{"),
        "run IO should import focused prompt-cache APIs directly"
    );
    assert!(
        !run_source.contains("crate::prompt_cache::PromptCache")
            && !run_source.contains("crate::prompt_cache::PROMPT_CACHE")
            && !run_source.contains("crate::prompt_cache::render_cache_miss_ranking"),
        "run.rs must not route pure prompt-cache policy through orchestration"
    );
}

#[test]
fn test_agent_doc_queue_owns_queue_continuation_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-queue")),
        "agent-doc-queue must stay a first-class workspace crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-queue/src/queue_continuation.rs")
            .exists(),
        "queue continuation drainability policy should live in the queue crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-queue-io/src/controller_pause.rs")
            .exists(),
        "controller queue pause state IO should live in the queue IO crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-queue-io/src/continuation_detect.rs")
            .exists(),
        "file-backed queue continuation detection should live in the queue IO crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-queue-io/src/queue_continuation.rs")
            .exists(),
        "queue continuation host IO should live in the queue IO crate"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-queue/src/queue_journal.rs")
            .exists()
            && !manifest_dir
                .join("agent-doc-queue-io/src/queue_journal.rs")
                .exists(),
        "queue journals must remain deleted because replay can resurrect operator-deleted heads"
    );
    let queue_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_continuation.rs")).unwrap();
    for required_snippet in [
        "pub struct QueueContinuation",
        "pub struct BacklogDrainSkip",
        "pub fn required_continuation",
        "pub fn collect_backlog_execution_contexts",
        "pub fn partition_drainable_backlog_ids",
        "pub fn drainable_head_prompt_for_scope",
    ] {
        assert!(
            queue_policy.contains(required_snippet),
            "agent-doc-queue must own queue continuation content policy: {required_snippet}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let queue_io_host =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_continuation.rs"))
            .unwrap();
    let queue_io_pause =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/controller_pause.rs"))
            .unwrap();
    let queue_io_detect =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/continuation_detect.rs"))
            .unwrap();
    for required_snippet in [
        "pub fn document_queue_controller_paused(",
        "pub fn document_queue_controller_pause_reason(",
        "agent_doc_sqlite::state_store::load_effective_queue_control_from_db",
    ] {
        assert!(
            queue_io_pause.contains(required_snippet),
            "agent-doc-queue-io must own controller pause state IO: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn detect_required_continuation_with(",
        "pub fn detect_required_continuation_for_content_with(",
        "recycle_yield_pending(file)",
        "std::fs::read_to_string(file)",
        "let snapshot_content = load_snapshot(file)?",
        "queue_continuation::required_continuation(&content, snapshot_content.as_deref())",
        "queue_continuation::required_continuation(content, snapshot_content.as_deref())",
    ] {
        assert!(
            queue_io_detect.contains(required_snippet),
            "agent-doc-queue-io must own file-backed queue continuation detection: {required_snippet}"
        );
    }
    assert!(
        !orchestration_lib.contains("pub use agent_doc_queue_io::queue_continuation;")
            && !orchestration_lib.contains("pub mod queue_continuation;")
            && !manifest_dir
                .join("agent-doc-orchestration/src/queue_continuation.rs")
                .exists(),
        "orchestration must not re-export the queue-io continuation host facade"
    );
    for forbidden_snippet in [
        "pub struct QueueContinuation",
        "pub fn document_queue_controller_paused(",
        "pub fn document_queue_controller_pause_reason(",
        "load_effective_queue_control_from_db",
        "fn detect_in_content",
        "agent_doc_frontmatter_io::session::parse_for_file_with_context",
        "agent_doc_element::element::parse(content)",
        "document_queue::detect_head_prompt_modified",
        "queue_policy::required_continuation",
        "std::fs::read_to_string(file)",
        "pub fn deferred_backlog_ids",
        "pub(crate) fn deferred_backlog_ids",
        "pub fn supervisor_deferred_backlog_ids",
        "fn head_is_drainable",
        "pub fn is_drainable_queue_head",
        "pub(crate) fn is_drainable_queue_head",
        "pub fn is_noise_queue_head",
        "pub(crate) fn is_noise_queue_head",
        "pub fn live_drainable_continuation_head",
        "pub fn drainable_head_count",
        "pub fn review_phase_routed",
        "const QUEUE_DIRECTIVE_VERBS",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden_snippet),
            "orchestration must not re-own pure queue continuation policy: {forbidden_snippet}"
        );
    }
    assert!(
        queue_io_host.contains("crate::continuation_detect::detect_required_continuation_with")
            && queue_io_host
                .contains("crate::continuation_detect::detect_required_continuation_for_content_with")
            && queue_io_host.contains("pub fn detect_for_content(")
            && queue_io_host.contains("agent_doc_snapshot_io::load_document_baseline")
            && queue_io_host.contains(
                "agent_doc_controller_io::project_controller::supervisor_recycle_yield_pending_for_file"
            ),
        "queue-io continuation host should inject snapshot/controller-projection recycle effects into the focused detector"
    );
    let run_io = fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    let session_check_command =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    let route_authoritative =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_dispatch.rs"))
            .unwrap();
    let mcp_source = fs::read_to_string(manifest_dir.join("src/mcp.rs")).unwrap();
    let session_actor_cmd =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    for (relative, source) in [
        ("agent-doc-run-io/src/lib.rs", run_io.as_str()),
        (
            "agent-doc-session-check-io/src/command.rs",
            session_check_command.as_str(),
        ),
        (
            "agent-doc-route-io/src/authoritative_dispatch.rs",
            route_authoritative.as_str(),
        ),
        ("src/mcp.rs", mcp_source.as_str()),
        ("src/session_actor_cmd.rs", session_actor_cmd.as_str()),
    ] {
        assert!(
            source.contains("queue_continuation::detect_for_content(")
                && !source.contains("queue_continuation::detect(file)")
                && !source.contains("queue_continuation::detect(&file)")
                && !source.contains("queue_continuation::detect(&ctx.canonical_file)"),
            "{relative} should supply realtime-resolved content to queue continuation detection"
        );
    }
    for (relative, source, marker) in [
        (
            "agent-doc-run-io/src/lib.rs",
            run_io.as_str(),
            "owned_pane_self_invocation_queue_continuation",
        ),
        (
            "agent-doc-session-check-io/src/command.rs",
            session_check_command.as_str(),
            "session_check_queue_continuation",
        ),
        (
            "agent-doc-route-io/src/authoritative_dispatch.rs",
            route_authoritative.as_str(),
            "detect_active_queue_continuation",
        ),
        (
            "src/mcp.rs",
            mcp_source.as_str(),
            "mcp_session_check_queue_continuation",
        ),
        (
            "src/session_actor_cmd.rs",
            session_actor_cmd.as_str(),
            "session_actor_busy_clear_queue_continuation",
        ),
    ] {
        assert!(
            source.contains(marker),
            "{relative} should name the current-document authority source for queue continuation detection: {marker}"
        );
    }
    for relative in [
        "agent-doc-session-check-io/tests/session_check.rs",
        "agent-doc-route-io/src/authoritative_actor.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-preflight-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_queue_io::controller_pause::document_queue_controller_"),
            "{relative} should call controller pause IO from agent-doc-queue-io directly"
        );
    }
    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) struct UndrainableSkip",
        "struct UndrainableSkip",
        "pub(crate) fn partition_drainable_backlog_ids",
        "pub(crate) fn collect_backlog_execution_contexts",
    ] {
        assert!(
            !preflight_maintenance.contains(forbidden_snippet),
            "preflight maintenance must not re-own queue backlog drain policy: {forbidden_snippet}"
        );
    }
    assert!(
        preflight_maintenance
            .contains("agent_doc_queue::queue_continuation::collect_backlog_execution_contexts")
            && preflight_maintenance
                .contains("agent_doc_queue::queue_continuation::partition_drainable_backlog_ids"),
        "preflight maintenance should call queue backlog drain policy from agent-doc-queue directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/queue_journal.rs")
            .exists(),
        "orchestration must not keep a queue_journal facade module"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod queue_journal;"),
        "orchestration must not export a queue_journal facade"
    );
    let queue_replay_source =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_replay.rs")).unwrap();
    for required_snippet in [
        "pub fn queue_entry_commit_signature(",
        "pub fn preserved_queue_additions_neutralized_by_replay(",
    ] {
        assert!(
            queue_replay_source.contains(required_snippet),
            "agent-doc-queue must own queue replay-normalization policy: {required_snippet}"
        );
    }
    let commit_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "fn queue_entry_commit_signature(",
        "fn queue_entry_count_map(",
        "fn preserved_queue_additions_neutralized_by_replay(",
    ] {
        assert!(
            !commit_io_source.contains(forbidden_snippet),
            "commit-io must not re-own queue replay-normalization policy: {forbidden_snippet}"
        );
    }
    assert!(
        commit_io_source.contains(
            "agent_doc_queue::queue_replay::preserved_queue_additions_neutralized_by_replay"
        ),
        "commit coordinator should call focused queue replay-normalization policy directly"
    );

    let queue_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&queue_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(dependencies.contains_key("agent-doc-element"));
    assert!(dependencies.contains_key("agent-doc-element-backlog"));
    assert!(dependencies.contains_key("agent-doc-element-queue"));
    assert!(dependencies.contains_key("agent-doc-frontmatter"));
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-queue must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_agent_doc_queue_owns_queue_convergence_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod queue_convergence;"),
        "agent-doc-queue should expose queue convergence policy"
    );

    let queue_convergence =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_convergence.rs")).unwrap();
    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    for required_snippet in [
        "pub fn realign_baseline_to_converged_queue(",
        "pub fn queue_body_diff_is_non_selected_future_state(",
        "pub fn selected_queue_head_unchanged_in_snapshot(",
        "pub fn queue_region_differs_from_snapshot(",
        "pub fn inactive_queue_changed_vs_snapshot(",
        "pub fn queue_entries_are_drained_residue(",
        "fn first_queue_prompt_identity(",
        "fn content_without_queue_body(",
        "fn strip_exchange_boundary_lines(",
        "fn realign_component_when_only_in_progress_marker_changed(",
    ] {
        assert!(
            queue_convergence.contains(required_snippet),
            "agent-doc-queue must own queue convergence policy: {required_snippet}"
        );
    }

    for forbidden_snippet in [
        "fn realign_baseline_to_converged_queue(",
        "fn queue_body_diff_is_non_selected_future_state(",
        "fn first_queue_prompt_identity(",
        "fn queue_prompt_identity(",
        "fn content_without_queue_body(",
        "fn strip_exchange_boundary_lines(",
        "fn realign_component_when_only_in_progress_marker_changed(",
        "fn pending_body_without_in_progress_markers(",
        "pub use agent_doc_queue::queue_convergence",
    ] {
        assert!(
            !preflight_run.contains(forbidden_snippet),
            "preflight/run.rs must not re-own or facade queue convergence policy: {forbidden_snippet}"
        );
    }
    assert!(
        preflight_run.contains("use agent_doc_queue::queue_convergence::{")
            && preflight_run.contains("realign_baseline_to_converged_queue")
            && preflight_run.contains("queue_body_diff_is_non_selected_future_state"),
        "preflight/run.rs should call focused queue convergence policy directly"
    );
    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "fn selected_queue_head_unchanged_in_snapshot(",
        "fn queue_region_differs_from_snapshot(",
        "fn inactive_queue_changed_vs_snapshot(",
        "fn queue_entries_are_drained_residue(",
    ] {
        assert!(
            !preflight_maintenance.contains(forbidden_snippet),
            "agent-doc-preflight-io/src/lib.rs must not re-own queue snapshot convergence policy: {forbidden_snippet}"
        );
    }
    assert!(
        preflight_maintenance.contains("queue_convergence::{")
            && preflight_maintenance.contains("selected_queue_head_unchanged_in_snapshot(")
            && preflight_maintenance.contains("queue_region_differs_from_snapshot(")
            && preflight_maintenance.contains("inactive_queue_changed_vs_snapshot(")
            && preflight_maintenance.contains("queue_entries_are_drained_residue("),
        "agent-doc-preflight-io/src/lib.rs should adapt snapshot IO into focused queue convergence policy directly"
    );
}

#[test]
fn test_agent_doc_queue_owns_do_directive_target_parsing() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_directive =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_directive.rs")).unwrap();
    for required in [
        "pub fn explicit_do_directive_target_id",
        "pub fn explicit_do_directive_target_ids",
        "pub fn first_directive_target_id",
        "pub fn do_directive_target_ids",
        "pub fn do_directive_target_ids_in_line",
        "pub fn filter_expect_done_or_gate_ids",
        "fn leads_with_bare_id_token",
    ] {
        assert!(
            queue_directive.contains(required),
            "agent-doc-queue must own id-backed queue directive parsing: {required}"
        );
    }

    let backlog_source =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/backlog.rs")).unwrap();
    assert!(
        backlog_source.contains("pub fn extract_pending_hash_ids"),
        "ordered tracked-work #id scanning should live with backlog/tracked-work parsing"
    );

    let done_signals_path =
        manifest_dir.join("agent-doc-orchestration/src/session_check/done_signals.rs");
    assert!(
        !done_signals_path.exists(),
        "session_check/done_signals.rs must stay deleted instead of becoming an orchestration facade"
    );
    let closeout_signal =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/closeout_signal.rs")).unwrap();
    for forbidden in [
        "pub fn do_directive_target_ids",
        "pub(crate) fn do_directive_target_ids_in_line",
        "pub(crate) fn extract_pending_hash_ids",
        "pub(crate) fn leads_with_bare_id_token",
    ] {
        assert!(
            !closeout_signal.contains(forbidden),
            "closeout signal policy must not re-own queue directive parsing: {forbidden}"
        );
    }
    assert!(
        closeout_signal.contains("agent_doc_element_backlog::backlog::extract_pending_hash_ids"),
        "done signal parsing should reuse the focused tracked-work #id scanner from agent-doc-turn"
    );

    let tsift_graph = fs::read_to_string(manifest_dir.join("src/tsift_graph.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn extract_do_target",
        "pub(crate) fn extract_do_targets",
        "fn extract_hash_ids",
    ] {
        assert!(
            !tsift_graph.contains(forbidden),
            "root tsift_graph must not re-own queue directive target parsing: {forbidden}"
        );
    }
    assert!(
        tsift_graph.contains("agent_doc_queue::queue_directive::explicit_do_directive_target_id"),
        "root tsift graph should call focused explicit-do target parsing directly"
    );
    for relative in ["src/plan.rs", "src/jobs.rs"] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_queue::queue_directive::explicit_do_directive_target_ids"),
            "{relative} should call focused explicit-do target parsing directly"
        );
        assert!(
            !source.contains("crate::tsift_graph::extract_do_targets"),
            "{relative} must not route explicit-do target parsing through tsift_graph"
        );
    }

    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    assert!(
        preflight_run.contains("agent_doc_queue::queue_directive::do_directive_target_ids"),
        "preflight/run.rs should call focused queue directive parsing directly"
    );
    assert!(
        !preflight_run.contains("crate::session_check::do_directive_target_ids"),
        "preflight/run.rs must not route queue directive parsing through session_check"
    );
    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    assert!(
        response_guards
            .contains("agent_doc_turn::closeout_signal::still_missing_dropped_queue_prompts"),
        "response_guards should route dropped-queue prompt classification through focused closeout_signal policy"
    );
    let closeout_signal =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/closeout_signal.rs")).unwrap();
    assert!(
        closeout_signal.contains("agent_doc_queue::queue_directive::do_directive_target_ids"),
        "closeout_signal should call focused queue directive parsing directly"
    );
    assert!(
        !response_guards.contains("crate::session_check::do_directive_target_ids"),
        "response_guards must not route queue directive parsing through session_check"
    );
    let project_controller =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    assert!(
        project_controller.contains("agent_doc_queue::queue_directive::first_directive_target_id"),
        "project_controller should call focused first queue directive target parsing directly"
    );
    assert!(
        !project_controller.contains("fn queue_head_id_from_prompt("),
        "project_controller must not keep a local queue directive parsing wrapper"
    );
    let queue_closeout_guard =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_closeout_guard.rs"))
            .unwrap();
    assert!(
        queue_closeout_guard.contains("queue_directive::do_directive_target_ids"),
        "queue closeout guard policy should call focused queue directive parsing directly"
    );
    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    assert!(
        !preflight_maintenance.contains("fn filter_expect_done_or_gate_ids"),
        "preflight maintenance must not re-own queue directive lifecycle expectation policy"
    );
    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    assert!(
        preflight_run.contains("agent_doc_queue::queue_directive::filter_expect_done_or_gate_ids"),
        "preflight run should call focused queue directive lifecycle expectation policy directly"
    );
    let queue_head_guards = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_guards.rs"),
    )
    .unwrap();
    assert!(
        !queue_head_guards.contains("agent_doc_queue::queue_directive::do_directive_target_ids"),
        "queue_head_guards should consume queue_closeout_guard policy instead of parsing queue directives directly"
    );
    let queue_head_provenance_guards = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_provenance_guards.rs"),
    )
    .unwrap();
    assert!(
        !queue_head_provenance_guards
            .contains("agent_doc_queue::queue_directive::do_directive_target_ids"),
        "queue_head_provenance_guards should consume queue_closeout_guard policy instead of parsing queue directives directly"
    );
}

#[test]
fn test_agent_doc_queue_owns_queue_response_head_matching_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_response =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_response.rs")).unwrap();
    let queue_directive =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_directive.rs")).unwrap();

    for required in [
        "pub fn queue_prompt_done_id",
        "pub fn normalize_done_id",
        "pub fn response_heading_topic",
        "pub fn response_topic_matches_queue_head",
        "pub fn response_explicitly_targets_queue_head",
        "pub fn normalize_queue_prompt_text",
        "pub fn queue_prompt_text_matches",
    ] {
        assert!(
            queue_response.contains(required),
            "agent-doc-queue must own queue response/head matching policy: {required}"
        );
    }
    for required in [
        "pub fn topic_resolves_to_exact_id",
        "pub fn topic_resolves_to_only_id_directives",
    ] {
        assert!(
            queue_directive.contains(required),
            "agent-doc-queue must own queue topic id-resolution policy: {required}"
        );
    }

    for relative in [
        "agent-doc-queue-io/src/queue_consume.rs",
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-preflight-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "fn queue_prompt_done_id(",
            "fn normalize_done_id(",
            "fn response_heading_topic(",
            "fn response_topic_matches_queue_head(",
            "fn response_explicitly_targets_queue_head(",
            "fn topic_resolves_to_exact_id(",
            "fn topic_resolves_to_only_id_directives(",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own queue response/head matching policy: {forbidden}"
            );
        }
    }
}

#[test]
fn test_agent_doc_queue_owns_queue_consumption_entry_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod queue_consume;"),
        "agent-doc-queue should expose queue consumption entry policy"
    );
    let queue_io =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_consumption_proof.rs"))
            .unwrap();
    for required in [
        "pub enum QueueConsumptionProofStage",
        "pub trait QueueConsumptionProofEffects",
        "pub fn record_queue_consumption_proofs",
        "QueueConsumptionProofStage::BeforeMutation",
        "QueueConsumptionProofStage::AfterMutation",
        "agent_doc_workflow_io::proof_ledger",
        "agent_doc_state_backbone::StateEvent",
    ] {
        assert!(
            queue_io.contains(required),
            "agent-doc-queue-io must own queue-consumption proof IO: {required}"
        );
    }

    let queue_consume_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_consume.rs")).unwrap();
    for required in [
        "pub fn first_n_queue_prompt_texts",
        "pub fn queue_consume_count_for_done_ids",
        "pub fn queue_prompt_texts_match_for_consumption",
        "pub fn mark_first_matching_prompts_completed_by_texts",
        "pub fn mark_entries_completed_by_done_ids",
        "pub fn normalized_done_id_bag",
        "pub fn cycle_answered_foreign_exchange_prompt",
        "pub const STRUCK_FREE_TEXT_NOTE",
        "pub fn annotate_struck_free_text_line",
        "fn strip_list_bullet_prefix",
        "pub fn annotate_newly_struck_free_text_heads",
        "pub fn project_answered_free_text_strike",
        "pub struct QueueConsumptionPlan",
        "pub struct IpcNodeOp",
        "pub struct NextQueueHeadSelection",
        "pub fn next_queue_head_selection",
        "pub fn to_json(&self) -> serde_json::Value",
        "pub fn queue_consume_node_ops(",
    ] {
        assert!(
            queue_consume_policy.contains(required),
            "agent-doc-queue must own queue consumption entry policy: {required}"
        );
    }

    let queue_io_consume =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_consume.rs")).unwrap();
    let commit_io =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn first_n_queue_prompt_texts",
        "pub(crate) fn queue_consume_count_for_done_ids",
        "fn queue_prompt_texts_match_for_consumption",
        "fn mark_first_matching_prompts_completed_by_texts",
        "pub(crate) fn mark_entries_completed_by_done_ids",
        "pub(crate) fn normalized_done_id_bag",
        "pub(crate) fn cycle_answered_foreign_exchange_prompt",
        "fn cycle_answered_foreign_exchange_prompt",
        "pub(crate) const STRUCK_FREE_TEXT_NOTE",
        "pub(crate) fn annotate_struck_free_text_line",
        "pub(crate) use agent_doc_queue_io::queue_consumption_proof::QueueConsumptionProofStage",
        "fn strip_list_bullet_prefix",
        "pub(crate) fn annotate_newly_struck_free_text_heads",
        "pub(crate) struct QueueConsumptionPlan",
        "pub struct IpcNodeOp",
        "impl IpcNodeOp",
        "IpcNodeOp::consume",
        "fn next_queue_head_selection(",
        "pub(crate) fn next_queue_head_selection(",
    ] {
        assert!(
            !queue_io_consume.contains(forbidden),
            "agent-doc-queue-io queue_consume.rs must not re-own queue consumption entry policy: {forbidden}"
        );
    }
    assert!(
        !orchestration_preflight.contains("fn strike_done_queue_head_prompts"),
        "preflight.rs must not re-own resolved-id queue strike policy"
    );
    assert!(
        queue_io_consume.contains("queue_consume::{")
            && queue_io_consume.contains("project_answered_free_text_strike")
            && queue_io_consume.contains("cycle_answered_foreign_exchange_prompt"),
        "agent-doc-queue-io queue_consume.rs should call queue consumption entry policy through agent-doc-queue directly"
    );
    let controller =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    let session_actor =
        fs::read_to_string(manifest_dir.join("agent-doc-session-actor-io/src/lib.rs")).unwrap();
    let binary = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let write_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    assert!(
        controller.contains("fn current_answered_free_text_strike(")
            && controller.contains("fn ensure_answered_free_text_strike_effect(")
            && session_actor.contains("pub fn enqueue_detached<")
            && binary.contains("fn project_answered_free_text_strike(")
            && binary.contains("actor.enqueue_detached(")
            && !queue_io_consume.contains("strike_answered_free_text_heads_at_commit_seam")
            && !commit_io.contains("strike_answered_free_text_heads_at_commit_seam")
            && !write_runtime.contains("strike_answered_free_text_queue_heads"),
        "answered free-text striking must project through the controller graph and per-document worker, without write/commit callbacks"
    );
    let orchestration_write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    assert!(
        orchestration_write_run_entry.contains(
            "use agent_doc_queue_io::queue_consumption_proof::QueueConsumptionProofStage;"
        ) && orchestration_write_run_entry.contains("QueueConsumptionProofStage::BeforeMutation")
            && orchestration_write_run_entry.contains("QueueConsumptionProofStage::AfterMutation"),
        "write/run_entry.rs should import queue-consumption proof stages from agent-doc-queue-io directly"
    );
    assert!(
        orchestration_preflight_maintenance
            .contains("agent_doc_queue::queue_consume::mark_entries_completed_by_done_ids"),
        "preflight maintenance should call resolved-id queue strike policy through agent-doc-queue directly"
    );
}

#[test]
fn test_agent_doc_queue_owns_queue_prompt_drift_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod queue_prompt_drift;"),
        "agent-doc-queue should expose queue prompt drift policy"
    );

    let queue_prompt_drift =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_prompt_drift.rs")).unwrap();
    for required in [
        "pub fn queue_component_text",
        "pub fn queue_prompt_texts",
        "pub fn queue_prompt_texts_including_consumed",
        "pub fn queue_prompt_deletions_between",
        "pub fn dropped_queue_prompt_lines_after_content_ours",
        "pub fn preserve_content_ours_over_live_queue_deletions",
    ] {
        assert!(
            queue_prompt_drift.contains(required),
            "agent-doc-queue must own queue prompt drift policy: {required}"
        );
    }

    let orchestration_write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let write_converge =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn queue_component_text(",
        "fn queue_prompt_texts(",
        "fn queue_prompt_texts_including_consumed(",
        "fn queue_prompt_counts(",
        "fn queue_prompt_count(",
        "fn queue_prompt_deletions_between(",
        "fn dropped_queue_prompt_lines_after_content_ours(",
        "fn preserve_content_ours_over_live_queue_deletions(",
    ] {
        assert!(
            !orchestration_write.contains(forbidden) && !write_converge.contains(forbidden),
            "write/write-converge IO must not re-own queue prompt drift policy: {forbidden}"
        );
    }
    assert!(
        write_converge.contains("agent_doc_queue::queue_prompt_drift::{")
            && write_converge.contains("preserve_content_ours_over_live_queue_deletions"),
        "write-converge IO should call queue prompt drift policy through agent-doc-queue directly"
    );
}

#[test]
fn test_agent_doc_queue_owns_free_text_response_proof_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_response =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_response.rs")).unwrap();
    for required in [
        "pub fn normalize_for_answer_match",
        "pub fn free_text_head_match_prose",
        "pub fn free_text_head_answered_by_response",
        "pub fn free_text_head_present_in_baseline",
    ] {
        assert!(
            queue_response.contains(required),
            "agent-doc-queue must own free-text queue response proof policy: {required}"
        );
    }
    assert!(
        !queue_response.contains("pub fn head_carries_in_progress_marker"),
        "selection markers are not response proof policy (#bugautostruck)"
    );

    for relative in [
        "agent-doc-queue-io/src/queue_consume.rs",
        "agent-doc-session-check-io/src/queue_head_provenance_guards.rs",
        "agent-doc-preflight-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "fn normalize_for_answer_match",
            "fn response_blockquote_text",
            "fn response_explicit_queue_prompt_echoes_head",
            "fn head_carries_in_progress_marker",
            "fn free_text_head_match_prose",
            "fn free_text_head_answered_by_response",
            "fn free_text_head_present_in_baseline",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own free-text queue response proof policy: {forbidden}"
            );
        }
    }

    let queue_consume_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_consume.rs")).unwrap();
    assert!(
        queue_consume_policy.contains("free_text_head_answered_by_response")
            && queue_consume_policy.contains("free_text_head_present_in_baseline")
            && !queue_consume_policy.contains("head_carries_in_progress_marker")
            && !queue_consume_policy.contains("free_text_head_match_prose")
            && !queue_consume_policy.contains("normalize_for_answer_match"),
        "agent-doc-queue::queue_consume should require focused response proof directly and never admit selection-marker proof"
    );

    let queue_io_consume =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_consume.rs")).unwrap();
    assert!(
        !queue_io_consume.contains("free_text_head_present_in_baseline")
            && !queue_io_consume.contains("head_carries_in_progress_marker")
            && !queue_io_consume.contains("free_text_head_match_prose")
            && !queue_io_consume.contains("normalize_for_answer_match"),
        "agent-doc-queue-io queue_consume.rs should not re-own free-text response proof policy"
    );
}

#[test]
fn test_agent_doc_queue_owns_free_text_admission_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let free_text_admission =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/free_text_admission.rs"))
            .unwrap();
    for required in [
        "pub enum FreeTextAdmissionScope",
        "pub fn normalize_admitted_free_text",
        "pub fn free_text_prompt_is_backlog_task",
        "pub struct ActionableFreeTextPrompts",
        "pub struct PreparedFreeTextAdmission",
        "pub struct FreeTextAdmission",
        "pub enum FreeTextAdmissionExecution",
        "pub fn collect_actionable_free_text_prompts",
        "pub fn prepare_free_text_admission",
        "pub fn append_empty_agent_component",
        "pub fn queue_entry_is_admitted_free_text",
        "pub fn ensure_queue_priority_attr",
        "pub fn goal_command_for_ids",
        "pub fn goal_command_already_queued",
        "pub fn queue_currently_active_for_free_text_admission",
        "pub fn queue_free_text_admission_scope",
        "pub fn snapshot_queue_free_text_prompt_keys",
    ] {
        assert!(
            free_text_admission.contains(required),
            "agent-doc-queue must own queue free-text admission policy: {required}"
        );
    }

    let maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden in [
        "enum QueueFreeTextAdmissionScope",
        "fn normalize_admitted_free_text",
        "fn free_text_prompt_is_backlog_task",
        "struct FreeTextWorkPrompt",
        "struct ActionableFreeTextPrompts",
        "struct PreparedFreeTextAdmission",
        "struct FreeTextAdmission",
        "enum FreeTextAdmissionExecution",
        "fn collect_actionable_free_text_prompts",
        "fn prepare_free_text_admission",
        "fn admit_free_text_work",
        "fn append_empty_agent_component",
        "fn queue_entry_is_admitted_free_text",
        "fn ensure_queue_priority_attr",
        "fn goal_command_for_ids",
        "fn goal_command_already_queued",
        "fn queue_currently_active_for_free_text_admission",
        "fn queue_origin_free_text_admission_scope",
        "fn snapshot_queue_free_text_prompt_keys",
    ] {
        assert!(
            !maintenance.contains(forbidden),
            "preflight maintenance must not re-own queue free-text admission policy: {forbidden}"
        );
    }
    assert!(
        maintenance.contains("free_text_admission::{")
            && maintenance.contains("queue_free_text_admission_scope(")
            && maintenance.contains("prepare_free_text_admission("),
        "preflight maintenance should adapt snapshots into focused queue free-text admission policy"
    );
}

#[test]
fn test_agent_doc_queue_owns_queue_prompt_echo_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_response =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_response.rs")).unwrap();
    for required in [
        "pub fn first_nonempty_line",
        "pub fn format_consumed_prompt_echo",
        "pub fn summarize_consumed_prompt",
        "pub fn line_is_response_heading",
        "pub fn normalize_prompt_line",
        "pub fn locate_response_heading_offset",
        "pub fn embed_consumed_prompt_in_response",
    ] {
        assert!(
            queue_response.contains(required),
            "agent-doc-queue must own queue prompt echo/embedding policy: {required}"
        );
    }

    let queue_consume =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_consume.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn first_nonempty_line",
        "pub(crate) fn format_consumed_prompt_echo",
        "pub(crate) fn summarize_consumed_prompt",
        "pub(crate) fn line_is_response_heading",
        "pub(crate) fn normalize_prompt_line",
        "fn normalize_prompt_echo_presence_line",
        "pub(crate) fn locate_response_heading_offset",
        "pub(crate) fn embed_consumed_prompt_in_response",
    ] {
        assert!(
            !queue_consume.contains(forbidden),
            "agent-doc-queue-io queue_consume.rs must not re-own queue prompt echo/embedding policy: {forbidden}"
        );
    }
    assert!(
        queue_consume.contains("embed_consumed_prompt_in_response")
            && queue_consume.contains("first_nonempty_line"),
        "queue_consume should call focused queue prompt echo policy directly"
    );

    let codex_hook =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-stop-io/src/lib.rs")).unwrap();
    assert!(
        codex_hook.contains("agent_doc_queue::queue_response::format_consumed_prompt_echo")
            && !codex_hook.contains("crate::write::format_consumed_prompt_echo"),
        "codex_hook must call queue prompt echo policy through agent-doc-queue directly"
    );
    for required_snippet in [
        "current_document_content(file, \"codex_stop_active_session_queue_head\")",
        "current_document_content(file, \"codex_stop_repeated_queue_before_repair\")",
        "current_document_content(file, \"codex_stop_auto_close_before_repair\")",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
    ] {
        assert!(
            codex_hook.contains(required_snippet),
            "codex Stop queue paths should resolve current document content through realtime IO: {required_snippet}"
        );
    }
    assert!(
        !codex_hook.contains("std::fs::read_to_string(file)"),
        "codex Stop queue paths must not use raw disk reads for active document content"
    );
}

#[test]
fn test_agent_doc_queue_owns_queue_command_classification() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_command =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_command.rs")).unwrap();
    for required in [
        "pub fn is_queue_directive_prompt",
        "pub fn mentions_slash_command_reference",
    ] {
        assert!(
            queue_command.contains(required),
            "agent-doc-queue must own queue command/prompt classification: {required}"
        );
    }

    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn is_queue_directive_prompt",
        "pub(crate) fn mentions_slash_command",
    ] {
        assert!(
            !response_guards.contains(forbidden),
            "response_guards must not re-own queue command/prompt classification: {forbidden}"
        );
    }
    assert!(
        response_guards
            .contains("agent_doc_workflow::session_check::queue_response_contamination_candidates"),
        "response_guards should route queue contamination classification through focused workflow policy"
    );
    let workflow_session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/session_check.rs")).unwrap();
    for required in [
        "agent_doc_queue::queue_command::is_queue_directive_prompt",
        "agent_doc_queue::queue_command::mentions_slash_command_reference",
    ] {
        assert!(
            workflow_session_check.contains(required),
            "workflow session_check should call focused queue command classification directly: {required}"
        );
    }
}

#[test]
fn test_agent_doc_queue_owns_queue_control_binding_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let control_binding =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/control_binding.rs")).unwrap();
    for required in [
        "pub fn explicit_queue_go_mode",
        "pub fn explicit_queue_start_mode",
        "pub fn explicit_queue_stop_mode",
        "pub fn converge_queue_control_binding_content",
        "pub fn strip_queue_activation_tokens_in_content",
    ] {
        assert!(
            control_binding.contains(required),
            "agent-doc-queue must own queue control binding policy: {required}"
        );
    }

    let maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let direct_run_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/tests/direct_run.rs")).unwrap();
    let free_text_admission =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/free_text_admission.rs"))
            .unwrap();
    for forbidden in [
        "fn explicit_queue_go_mode",
        "fn explicit_queue_start_mode",
        "fn explicit_queue_stop_mode",
        "enum QueueBindingMode",
        "fn converge_queue_control_binding_content",
        "fn queue_binding_state",
        "fn queue_binding_target",
        "fn set_queue_marker_binding",
        "fn strip_queue_activation_tokens_in_content",
    ] {
        assert!(
            !maintenance.contains(forbidden),
            "preflight maintenance must not own queue control binding policy: {forbidden}"
        );
        assert!(
            !direct_run_tests.contains(forbidden),
            "orchestration direct-run tests must not own queue control binding policy: {forbidden}"
        );
        assert!(
            !free_text_admission.contains(forbidden),
            "free-text admission must not own queue control binding policy: {forbidden}"
        );
    }
}

#[test]
fn realtime_replica_observation_cannot_rewrite_the_editor_cut() {
    let source = fs::read_to_string("agent-doc-controller-io/src/project_controller/rpc.rs")
        .expect("read project controller RPC source");
    let body = source
        .split("fn observe_realtime_steering_after_replica_update(")
        .nth(1)
        .expect("realtime steering observer")
        .split("fn realtime_steering_event_for_text(")
        .next()
        .expect("observer body");

    assert!(
        !body.contains("apply_cp_write_for_file"),
        "transport-level replica updates must not project a prior full-document cut over live typing",
    );
    assert!(
        body.contains("realtime_queue_control_binding_deferred")
            && body.contains("replica_update_unsettled"),
        "pending queue normalization should remain observable for the settled convergence path",
    );
}

#[test]
fn test_agent_doc_harness_owns_opencode_goal_extension_detection() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let harness = fs::read_to_string(manifest_dir.join("agent-doc-harness/src/lib.rs")).unwrap();
    assert!(
        harness.contains("pub fn opencode_goal_extension_available"),
        "agent-doc-harness must own OpenCode goal extension detection"
    );

    let maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    assert!(
        !maintenance.contains("fn opencode_goal_extension_available"),
        "preflight maintenance must not own OpenCode goal extension detection"
    );
}

#[test]
fn test_agent_doc_queue_owns_dispatch_item_classification_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod dispatch_item;"),
        "agent-doc-queue should expose dispatch item classification policy"
    );

    let dispatch_item =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/dispatch_item.rs")).unwrap();
    for required in [
        "pub enum QueueItemKind",
        "pub struct QueueItem",
        "pub enum InlineDispatchCommand",
        "pub fn classify(",
        "pub fn inline_dispatch_command(",
        "pub fn is_session_clear_command(",
        "pub fn sanitize_progress_field(",
        "pub fn item_fingerprint(",
    ] {
        assert!(
            dispatch_item.contains(required),
            "agent-doc-queue must own dispatch item classification policy: {required}"
        );
    }

    let queue_dispatch_source =
        fs::read_to_string(manifest_dir.join("src/queue_dispatch.rs")).unwrap();
    for forbidden in [
        "pub enum QueueItemKind",
        "pub struct QueueItem",
        "pub enum InlineDispatchCommand",
        "pub fn classify(",
        "fn inline_dispatch_command(",
        "fn is_session_clear_command(",
        "fn sanitize_progress_field(",
        "fn item_fingerprint(",
        "const INLINE_COMMANDS",
        "INLINE_COMMANDS.contains",
        "pub use agent_doc_queue::dispatch_item",
        "pub(crate) use agent_doc_queue::dispatch_item",
    ] {
        assert!(
            !queue_dispatch_source.contains(forbidden),
            "queue_dispatch must stay an effect adapter and not re-own dispatch item classification: {forbidden}"
        );
    }
    assert!(
        queue_dispatch_source.contains("agent_doc_queue::dispatch_item::{")
            && queue_dispatch_source.contains("QueueItem")
            && queue_dispatch_source.contains("InlineDispatchCommand")
            && queue_dispatch_source.contains("inline_dispatch_command")
            && queue_dispatch_source.contains("is_session_clear_command")
            && queue_dispatch_source.contains("item_fingerprint")
            && queue_dispatch_source.contains("sanitize_progress_field"),
        "queue_dispatch should depend on focused dispatch item policy directly"
    );

    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    let orchestrate_dag_source =
        fs::read_to_string(manifest_dir.join("src/orchestrate/dag.rs")).unwrap();
    assert!(
        orchestrate_source.contains("agent_doc_queue::dispatch_item::{")
            && orchestrate_source.contains("QueueItemKind")
            && orchestrate_source.contains("classify")
            && !orchestrate_source.contains("queue_dispatch::classify(")
            && !orchestrate_dag_source.contains("queue_dispatch::classify("),
        "orchestration should use dispatch item classification from agent-doc-queue directly"
    );
}

#[test]
fn test_agent_doc_turn_owns_closeout_signal_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/closeout_signal.rs")
            .exists(),
        "closeout response and done-signal policy should live in the focused turn crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/closeout_recovery.rs")
            .exists(),
        "pure closeout recovery policy should live in the focused turn crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/closeout_guard.rs")
            .exists(),
        "closeout guard vocabulary should live in the focused turn crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/exchange_tail.rs")
            .exists(),
        "exchange-tail prompt/response policy should live in the focused turn crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/document_drift.rs")
            .exists(),
        "closeout document-drift policy should live in the focused turn crate"
    );

    let turn_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/closeout_signal.rs")).unwrap();
    let backlog_source =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/backlog.rs")).unwrap();
    let exchange_tail_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/exchange_tail.rs")).unwrap();
    let document_drift_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/document_drift.rs")).unwrap();
    let guard_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/closeout_guard.rs")).unwrap();
    let recovery_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/closeout_recovery.rs")).unwrap();
    let required = "pub fn line_is_carry_forward_signal";
    assert!(
        turn_source.contains(required),
        "agent-doc-turn must own carry-forward closeout signal policy: {required}"
    );
    let write_adapter =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let realtime_write_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime/src/write_policy.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn line_is_carry_forward_signal",
        "fn carry_forward_signal_candidate",
        "fn strip_markdown_list_marker",
        "fn strip_markdown_checkbox_marker",
    ] {
        assert!(
            !write_adapter.contains(forbidden),
            "write.rs must not re-own carry-forward closeout signal policy: {forbidden}"
        );
    }
    assert!(
        realtime_write_policy
            .contains("use agent_doc_turn::closeout_signal::line_is_carry_forward_signal"),
        "realtime write policy should import carry-forward closeout signal policy directly"
    );
    for required in [
        "pub enum CloseoutGuardReason",
        "pub enum CloseoutGuardOutcome",
        "pub struct CommittedWithoutResponseBodyEvidence",
        "pub enum CommittedWithoutResponseBodyDecision",
        "pub fn closeout_cycle_phase_from_str",
        "pub fn closeout_guard_event",
        "pub const fn closeout_terminal_guard_outcome",
        "pub fn exchange_has_assistant_response_body",
        "pub fn committed_without_response_body_decision",
    ] {
        assert!(
            guard_source.contains(required),
            "agent-doc-turn must own closeout guard policy: {required}"
        );
    }
    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    for forbidden in [
        "if !matches!(state.phase, agent_doc_turn::CyclePhase::Committed)",
        "if state.capture_id.is_some() || state.response_sha256.is_some()",
        "if !state.had_pending_mutations",
        "if crate::cycle_state::is_noop_commit_event(&state.last_event)",
    ] {
        assert!(
            !response_guards.contains(forbidden),
            "response_guards must not re-own committed-without-response-body policy: {forbidden}"
        );
    }
    assert!(
        response_guards
            .contains("agent_doc_turn::closeout_guard::committed_without_response_body_decision")
            && response_guards
                .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)?")
            && !response_guards.contains("agent_doc_cycle_state_io::load(file)?")
            && response_guards
                .contains("agent_doc_turn::closeout_guard::exchange_has_assistant_response_body"),
        "response_guards should call focused turn committed-response guard policy directly and read cycle state through the projection-aware loader"
    );
    for required in [
        "pub enum CloseoutRecoveryState",
        "pub enum CloseoutRecoveryDrift",
        "pub struct CloseoutRecoveryCycleInput",
        "pub struct CloseoutRecoveryStateInput",
        "pub fn classify_closeout_recovery_state_from_input",
        "pub fn closeout_content_component_signature",
        "pub fn classify_snapshot_head_drift",
        "pub fn classify_snapshot_visible_drift",
        "fn closeout_content_signature_after_artifact_normalization",
        "pub struct OpenCycleRecoveryCommandInput",
        "pub struct CloseoutRecoveryCommandInput",
        "pub fn closeout_recovery_command",
        "pub fn open_cycle_recovery_command",
        "pub struct CloseoutRecoveryDecisionInput",
        "pub enum CloseoutRecoveryDecision",
        "pub fn closeout_recovery_decision_from_state",
        "pub fn short_recovery_command_from_recommendation",
        "pub fn blocked_closeout_recovery_command",
        "pub enum CloseoutRecoveryMutationReason",
        "pub enum MetadataDriftAuthority",
        "pub const fn capture_refresh_event",
        "pub const fn capture_refresh_message",
        "pub fn metadata_drift_authority",
        "pub fn repair_leaves_unanswered_prompt_diff",
        "pub fn visible_response_recovery_is_adoptable",
        "pub fn stale_preflight_cycle_age_secs",
        "pub fn prompt_change_is_orchestration_handoff_marker",
        "pub fn content_matches_ignoring_trailing_newlines",
    ] {
        assert!(
            recovery_source.contains(required),
            "agent-doc-turn must own closeout recovery policy: {required}"
        );
    }
    let closeout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/src/closeout.rs")).unwrap();
    let flow_types_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow/src/types.rs")).unwrap();
    let flow_outcome_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow/src/outcome.rs")).unwrap();
    let flow_closeout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow/src/closeout.rs")).unwrap();
    let flow_lib = fs::read_to_string(manifest_dir.join("agent-doc-flow/src/lib.rs")).unwrap();
    let flow_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/src/lib.rs")).unwrap();
    assert!(
        flow_lib.contains("pub mod types;")
            && flow_lib.contains("pub mod outcome;")
            && flow_lib.contains("pub mod closeout;"),
        "agent-doc-flow should expose focused flow vocabulary and outcome contracts"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow")
            .exists(),
        "orchestration must not keep a flow source module for types/outcome/session-cycle/proof shims"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/proof.rs")
            .exists(),
        "orchestration flow must not keep a flow proof logging facade"
    );
    assert!(
        flow_outcome_source.contains("pub enum UserFacingOutcomeKind")
            && flow_outcome_source.contains("pub struct BinaryOutcome"),
        "agent-doc-flow must own typed user-facing and binary outcome contracts"
    );
    assert!(
        flow_closeout_source.contains("pub fn closeout_latency_message"),
        "agent-doc-flow must own closeout flow latency formatting"
    );
    for required_snippet in [
        "pub fn flow_event(",
        "pub fn flow_event_log_message(",
        "fn sanitize_field_value(",
        "pub struct SessionCycleStep",
        "pub fn session_cycle_event(",
    ] {
        assert!(
            flow_types_source.contains(required_snippet),
            "agent-doc-flow must own flow event construction/rendering policy: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub type FlowEventLogger = fn(&Path, &str);",
        "pub fn flow_event_message(",
        "pub fn log_flow_event(",
        "flow_event_log_message(&file.display().to_string(), event)",
    ] {
        assert!(
            flow_io_source.contains(required_snippet),
            "agent-doc-flow-io must own flow event logging IO: {required_snippet}"
        );
    }
    assert!(
        !flow_io_source.contains("crate::ops_log")
            && !flow_io_source.contains("agent_doc_orchestration")
            && !flow_io_source.contains("agent-doc-orchestration"),
        "agent-doc-flow-io must stay free of orchestration and concrete ops-log sinks"
    );
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_authoritative_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_dispatch.rs"))
            .unwrap();
    for forbidden in [
        "pub enum CloseoutGuardReason",
        "impl CloseoutGuardReason",
        "pub fn closeout_state_from_cycle_phase",
        "pub fn closeout_guard_event(",
        "pub fn terminal_guard_outcome",
        "fn closeout_latency_message(",
    ] {
        assert!(
            !closeout_source.contains(forbidden),
            "agent-doc-flow-io closeout must not re-own focused closeout guard policy: {forbidden}"
        );
    }
    assert!(
        !flow_types_source.contains("pub enum CloseoutState"),
        "agent-doc-flow types must not keep a duplicate closeout state vocabulary"
    );
    assert!(
        closeout_source.contains("use agent_doc_turn::closeout_guard::CloseoutGuardReason;")
            && closeout_source.contains("agent_doc_turn::closeout_guard::closeout_guard_event"),
        "agent-doc-flow-io closeout should adapt focused closeout guard events through an injected ops-log sink"
    );
    assert!(
        closeout_source.contains("closeout::closeout_latency_message"),
        "agent-doc-flow-io closeout should call focused flow latency formatting directly"
    );
    for required in [
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)",
        "agent_doc_cycle_state_io::load_closeout_projection(file)",
    ] {
        assert!(
            closeout_source.contains(required),
            "agent-doc-flow-io closeout recovery should use state-ledger projections: {required}"
        );
    }
    for relative in [
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/ipc/transport.rs",
        "agent-doc-session-check-io/src/write_pending_checks.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("crate::flow::closeout::CloseoutGuardReason")
                && !source.contains("closeout::CloseoutGuardReason"),
            "{relative} should use focused closeout guard reasons directly"
        );
    }
    for forbidden in [
        "pub enum CloseoutRecoveryState",
        "pub struct CloseoutRecoveryDecisionInput",
        "pub enum CloseoutRecoveryDecision",
        "pub fn closeout_recovery_decision_from_state",
        "pub enum CloseoutRecoveryMutationReason",
        "pub enum MetadataDriftAuthority",
        "impl CloseoutRecoveryMutationReason",
        "pub fn metadata_drift_authority",
        "pub fn closeout_recovery_command(",
        "fn open_cycle_recovery_command(",
        "fn extract_recovery_command(",
        "fn short_recovery_command_from_recommendation(",
        "fn route_closeout_blocked_recovery_command(",
        "pipe the final response (with `<!-- patch:exchange -->` blocks)",
        "rewrite the response with real `<!-- patch:exchange -->` blocks",
        "preserve the user-authored content and finish through `agent-doc finalize",
        "pub fn classify_closeout_recovery_state(",
        "fn content_component_signature(",
        "fn classify_snapshot_head_drift(",
        "fn classify_snapshot_visible_drift(",
        "fn closeout_content_signature_after_artifact_normalization(",
    ] {
        assert!(
            !closeout_source.contains(forbidden),
            "orchestration must not re-own or facade closeout recovery policy: {forbidden}"
        );
    }
    assert!(
        closeout_source.contains("use agent_doc_turn::closeout_recovery::{")
            && closeout_source.contains("CloseoutRecoveryDecision")
            && closeout_source.contains("CloseoutRecoveryDecisionInput")
            && closeout_source.contains("CloseoutRecoveryStateInput")
            && closeout_source.contains("CloseoutRecoveryMutationReason")
            && closeout_source.contains("CloseoutRecoveryState")
            && closeout_source.contains("CloseoutRecoveryCommandInput")
            && closeout_source.contains("OpenCycleRecoveryCommandInput")
            && closeout_source.contains("MetadataDriftAuthority")
            && closeout_source.contains("classify_closeout_recovery_state_from_input")
            && closeout_source.contains("classify_snapshot_head_drift")
            && closeout_source.contains("classify_snapshot_visible_drift")
            && closeout_source
                .contains("closeout_recovery_command as render_closeout_recovery_command")
            && closeout_source.contains("closeout_recovery_decision_from_state")
            && closeout_source.contains("metadata_drift_authority"),
        "orchestration closeout recovery should call focused turn policy directly"
    );
    assert!(
        route_authoritative_dispatch_source.contains("blocked_closeout_recovery_command")
            && !route_source.contains("fn extract_recovery_command(")
            && !route_source.contains("fn short_recovery_command_from_recommendation(")
            && !route_source.contains("fn route_closeout_blocked_recovery_command("),
        "route authoritative dispatch should call focused turn blocked-recovery projection directly, not re-own the parser"
    );
    for relative in [
        "agent-doc-capture-io/src/lib.rs",
        "agent-doc-repair-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_turn")
                && source.contains("closeout_recovery")
                && source.contains("CloseoutRecoveryMutationReason"),
            "{relative} should use focused closeout recovery reason directly"
        );
        assert!(
            !source.contains("crate::flow::closeout::CloseoutRecoveryMutationReason"),
            "{relative} must not route focused closeout recovery reason through orchestration"
        );
    }
    let repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    assert!(
        repair_source.contains("repair_leaves_unanswered_prompt_diff"),
        "repair IO should call focused unanswered-prompt recovery policy directly"
    );
    for forbidden in [
        "fn repair_leaves_unanswered_prompt_diff(",
        "fn repair_line_looks_like_fresh_prompt_after_response(",
        "fn repair_prompt_target_immediately_before_existing_response(",
        "fn agent_owned_visible_response_is_adoptable(",
        "fn preflight_cycle_age_secs(",
        "fn prompt_change_is_orchestration_handoff_marker(",
        "fn same_content_ignoring_trailing_newlines(",
    ] {
        assert!(
            !repair_source.contains(forbidden),
            "repair IO must not re-own pure unanswered-prompt recovery policy: {forbidden}"
        );
    }
    for required in [
        "pub enum ResponseSource",
        "pub struct ReapedResponseLossInput",
        "pub fn directive_response_source",
        "pub fn content_has_re_heading_for_id",
        "pub fn reaped_directive_ids_without_response",
        "pub fn text_has_blocked_future_action_signal",
        "pub fn text_has_no_followup_justification",
        "pub fn blocked_signal_tied_to_id",
        "pub fn body_enumerates_multiple_gated_phases",
        "pub fn count_phase_markers",
        "pub fn body_already_split_into_child_ids",
        "pub const QUEUE_AUDIT_SUBSTEP_COMPLETE_PHRASES",
        "pub fn queue_audit_collapses_partial_completion",
        "pub fn queue_audit_has_none_complete_claim",
        "pub const QUEUE_AUDIT_GUARD_SUPPRESS_MARKER",
        "pub struct QueueAuditPartialCompletionEvidence",
        "pub enum QueueAuditPartialCompletionDecision",
        "pub fn queue_audit_partial_completion_decision",
        "pub const PARTIAL_CLOSEOUT_REMAINING_PHRASES",
        "pub fn text_has_shipped_signal",
        "pub fn text_has_partial_remaining_signal",
        "pub fn response_text_for_guards",
        "pub const PARTIAL_CLOSEOUT_GUARD_SUPPRESS_MARKER",
        "pub struct PartialCloseoutStateEvidence",
        "pub enum PartialCloseoutStateDecision",
        "pub fn partial_closeout_state_decision",
        "pub const PENDING_DONE_GUARD_SUPPRESS_MARKER",
        "pub struct TrackedWorkCompletionEvidence",
        "pub enum TrackedWorkCompletionDecision",
        "pub fn pending_done_suppressed",
        "pub fn tracked_work_completion_decision",
        "pub fn tracked_work_completion_missing_done_ids",
        "pub struct ExpectDoneOrGateEvidence",
        "pub enum ExpectDoneOrGateDecision",
        "pub fn expect_done_or_gate_decision",
        "pub const BLOCKED_CLOSEOUT_FOLLOWUP_GUARD_SUPPRESS_MARKER",
        "pub struct BlockedCloseoutFollowupEvidence",
        "pub enum BlockedCloseoutFollowupDecision",
        "pub fn blocked_closeout_followup_decision",
        "pub const GATED_PHASE_SPLIT_GUARD_SUPPRESS_MARKER",
        "pub struct GatedPhaseSplitItemEvidence",
        "pub struct GatedPhaseSplitEvidence",
        "pub enum GatedPhaseSplitDecision",
        "pub fn gated_phase_split_decision",
        "pub fn normalized_prompt_for_match",
        "pub fn exchange_contains_prompt_line",
        "pub fn still_missing_dropped_queue_prompts",
        "pub fn still_missing_dropped_exchange_prompts",
        "pub fn is_exchange_response_heading",
        "pub fn is_direct_response_patchback_heading",
        "pub fn has_new_response_heading_marker",
        "pub fn is_binary_authored_recovery_diagnostic_heading",
        "pub fn is_queue_continuation_response_heading",
        "pub fn assistant_response_text",
        "pub fn response_clearly_completes_pending_id",
        "pub fn response_heading_resolves_to_pending_id",
        "pub fn explicit_done_signal_ids",
        "pub fn plain_done_signal",
    ] {
        assert!(
            turn_source.contains(required),
            "agent-doc-turn must own closeout signal policy: {required}"
        );
    }
    assert!(
        turn_source.contains("agent_doc_element_backlog::backlog::extract_pending_hash_ids"),
        "closeout signal policy should reuse tracked-work #id scanning"
    );
    for required in [
        "pub fn unresolved_exchange_prompt_in_content",
        "pub fn exchange_tail_has_response_heading",
        "pub fn prompt_only_exchange_tail",
    ] {
        assert!(
            exchange_tail_source.contains(required),
            "agent-doc-turn must own exchange-tail prompt/response policy: {required}"
        );
    }
    for required in [
        "pub fn exchange_has_new_appended_content",
        "pub fn extract_normalized_exchange_body",
        "pub fn exchange_only_promptless_content_drift",
        "pub fn active_session_drift_is_only_exchange_or_backlog_metadata",
        "pub fn promptless_comment_only_drift",
        "pub fn detect_bypassed_response_write_between",
        "pub fn mask_exchange_component_content",
        "pub fn mask_components_by_name",
    ] {
        assert!(
            document_drift_source.contains(required),
            "agent-doc-turn must own closeout document-drift policy: {required}"
        );
    }
    let turn_lib = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_lib.contains("pub mod document_drift;"),
        "agent-doc-turn should expose document-drift policy through its owning module"
    );
    assert!(
        !turn_lib.contains("pub use document_drift")
            && !turn_lib.contains("pub use agent_doc_turn::document_drift"),
        "agent-doc-turn should not add a document_drift root facade"
    );
    assert!(
        document_drift_source.contains("crate::closeout_signal::is_exchange_response_heading"),
        "document-drift policy should reuse focused closeout response-heading classification"
    );
    for required in [
        "crate::closeout_signal::has_new_response_heading_marker",
        "crate::closeout_signal::is_binary_authored_recovery_diagnostic_heading",
        "crate::closeout_signal::is_direct_response_patchback_heading",
    ] {
        assert!(
            document_drift_source.contains(required),
            "document-drift policy should reuse focused direct-patchback classification: {required}"
        );
    }

    let detect_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/detect.rs")).unwrap();
    for forbidden in [
        "pub(crate) enum ResponseSource",
        "pub(crate) struct ReapedResponseLossInput",
        "pub(crate) fn directive_response_source",
        "pub(crate) fn content_has_re_heading_for_id",
        "pub(crate) fn reaped_directive_ids_without_response",
    ] {
        assert!(
            !detect_source.contains(forbidden),
            "session-check detect IO must not re-own closeout response-loss policy: {forbidden}"
        );
    }

    let queue_head_guards = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_guards.rs"),
    )
    .unwrap();
    for required in [
        // `#respidxparse`: the per-id `directive_response_source` call was
        // replaced by the parse-once index, which is the same focused policy in
        // `agent_doc_turn::closeout_signal` — the ownership rule is unchanged.
        "agent_doc_turn::closeout_signal::ResponseIndex",
        "agent_doc_turn::closeout_signal::reaped_directive_ids_without_response",
        "agent_doc_turn::closeout_signal::ReapedResponseLossInput",
    ] {
        assert!(
            queue_head_guards.contains(required),
            "queue_head_guards should call focused closeout signal policy directly: {required}"
        );
    }

    let closeout_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/closeout_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub fn is_exchange_response_heading",
        "pub fn is_queue_continuation_response_heading",
        "pub(crate) fn has_new_response_heading_marker",
        "pub(crate) fn is_binary_authored_recovery_diagnostic_heading",
        "pub(crate) fn body_enumerates_multiple_gated_phases",
        "pub(crate) fn count_phase_markers",
        "pub(crate) fn body_already_split_into_child_ids",
        "pub(crate) const QUEUE_AUDIT_SUBSTEP_COMPLETE_PHRASES",
        "pub(crate) fn queue_audit_collapses_partial_completion",
        "pub(crate) fn queue_audit_has_none_complete_claim",
        "agent_doc_turn::closeout_signal::queue_audit_collapses_partial_completion",
        ".contains(\"<!-- no-queue-audit-guard -->\")",
        "agent_doc_turn::closeout_signal::response_text_for_guards",
        "agent_doc_turn::closeout_signal::text_has_blocked_future_action_signal",
        "agent_doc_turn::closeout_signal::text_has_no_followup_justification",
        "agent_doc_turn::closeout_signal::blocked_signal_tied_to_id",
        ".contains(\"<!-- no-blocked-followup-guard -->\")",
        ".contains(\"<!-- no-pending-done-guard -->\")",
        "agent_doc_turn::closeout_signal::body_enumerates_multiple_gated_phases",
        "agent_doc_turn::closeout_signal::body_already_split_into_child_ids",
        ".contains(\"<!-- no-gated-phase-split-guard -->\")",
        "agent_doc_element_backlog::backlog::normalize_pending_id",
        "let kept_open: std::collections::HashSet<String>",
        "let directed: std::collections::HashSet<String>",
    ] {
        assert!(
            !closeout_guards.contains(forbidden),
            "closeout_guards must not re-own gated-phase closeout policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::closeout_signal::blocked_closeout_followup_decision",
        "agent_doc_turn::closeout_signal::BlockedCloseoutFollowupEvidence",
        "agent_doc_turn::closeout_signal::BlockedCloseoutFollowupDecision",
        "agent_doc_turn::closeout_signal::gated_phase_split_decision",
        "agent_doc_turn::closeout_signal::GatedPhaseSplitEvidence",
        "agent_doc_turn::closeout_signal::GatedPhaseSplitItemEvidence",
        "agent_doc_turn::closeout_signal::GatedPhaseSplitDecision",
        "agent_doc_turn::closeout_signal::queue_audit_partial_completion_decision",
        "agent_doc_turn::closeout_signal::QueueAuditPartialCompletionEvidence",
        "agent_doc_turn::closeout_signal::QueueAuditPartialCompletionDecision",
    ] {
        assert!(
            closeout_guards.contains(required),
            "closeout_guards should call focused closeout signal policy directly: {required}"
        );
    }
    for required in [
        "super::closeout_signal::is_exchange_response_heading",
        "super::closeout_signal::is_queue_continuation_response_heading",
        "super::closeout_signal::normalized_prompt_for_match",
    ] {
        assert!(
            exchange_tail_source.contains(required),
            "exchange_tail should reuse focused closeout signal policy directly: {required}"
        );
    }
    for forbidden in [
        "pub(crate) fn unresolved_exchange_prompt_in_content",
        "pub(crate) fn prompt_only_exchange_tail",
        "pub(crate) fn exchange_has_new_appended_content",
        "pub(crate) fn extract_normalized_exchange_body",
        "pub(crate) fn exchange_only_promptless_content_drift",
        "pub(crate) fn active_session_drift_is_only_exchange_or_backlog_metadata",
        "pub(crate) fn promptless_comment_only_drift",
        "pub fn detect_bypassed_response_write_between",
        "pub(crate) fn mask_exchange_component_content",
        "pub(crate) fn mask_components_by_name",
    ] {
        assert!(
            !closeout_guards.contains(forbidden),
            "closeout_guards must not re-own exchange-tail prompt/response policy: {forbidden}"
        );
    }
    assert!(
        closeout_guards
            .contains("agent_doc_turn::exchange_tail::unresolved_exchange_prompt_in_content")
            && closeout_guards
                .contains("agent_doc_turn::exchange_tail::exchange_tail_has_response_heading"),
        "closeout_guards should keep only file adapters over focused exchange-tail policy"
    );
    for required in [
        "agent_doc_document_realtime::baseline_comparison::BaselineComparison",
        "BaselineComparison::new(&snapshot, &current)",
        "use agent_doc_turn::document_drift::{",
        "active_session_drift_is_only_exchange_or_backlog_metadata",
        "exchange_has_new_appended_content",
        "exchange_only_promptless_content_drift",
        "promptless_comment_only_drift",
    ] {
        assert!(
            closeout_guards.contains(required),
            "closeout_guards should call focused document drift policy directly: {required}"
        );
    }
    assert!(
        closeout_guards
            .contains("agent_doc_turn::document_drift::detect_bypassed_response_write_between"),
        "closeout_guards should call focused document-drift bypassed-response classifier directly"
    );
    let workflow_session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/session_check.rs")).unwrap();
    assert!(
        detect_source
            .contains("agent_doc_workflow::session_check::prompt_only_exchange_tail_guard")
            && workflow_session_check
                .contains("agent_doc_turn::exchange_tail::prompt_only_exchange_tail"),
        "session-check detect IO should route prompt-only exchange-tail checks through workflow while workflow calls focused turn policy"
    );

    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn normalized_prompt_for_match",
        "pub(crate) fn exchange_contains_prompt_line",
        "pub(crate) fn assistant_response_text",
    ] {
        assert!(
            !response_guards.contains(forbidden),
            "response_guards must not re-own closeout prompt/response text policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::closeout_signal::still_missing_dropped_queue_prompts",
        "agent_doc_workflow::session_check::queue_response_contamination_candidates",
        "agent_doc_turn::closeout_signal::still_missing_dropped_exchange_prompts",
    ] {
        assert!(
            response_guards.contains(required),
            "response_guards should call focused response guard policy directly: {required}"
        );
    }

    let provenance_guards = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_provenance_guards.rs"),
    )
    .unwrap();
    for forbidden in [
        "pub(crate) const BLOCKED_FUTURE_ACTION_PHRASES",
        "pub(crate) const NO_FOLLOWUP_JUSTIFICATION_PHRASES",
        "pub(crate) fn text_has_blocked_future_action_signal",
        "pub(crate) fn text_has_no_followup_justification",
        "pub(crate) fn blocked_signal_tied_to_id",
        "pub(crate) fn free_text_queue_marker_has_bare_heading_residue",
        "pub(crate) fn response_head_plausibly_answers",
        "agent_doc_turn::closeout_signal::free_text_queue_marker_has_bare_heading_residue",
        "agent_doc_turn::closeout_signal::response_head_plausibly_answers",
        "pub(crate) const PARTIAL_CLOSEOUT_REMAINING_PHRASES",
        "pub(crate) fn text_has_shipped_signal",
        "pub(crate) fn text_has_partial_remaining_signal",
        ".contains(\"<!-- no-pending-done-guard -->\")",
        "let resolved: std::collections::HashSet<String>",
    ] {
        assert!(
            !provenance_guards.contains(forbidden),
            "queue_head_provenance_guards must not re-own closeout signal policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::closeout_signal::expect_done_or_gate_decision",
        "agent_doc_turn::closeout_signal::ExpectDoneOrGateEvidence",
        "agent_doc_turn::closeout_signal::ExpectDoneOrGateDecision",
    ] {
        assert!(
            provenance_guards.contains(required),
            "queue_head_provenance_guards should call focused expect-done-or-gate policy directly: {required}"
        );
    }
    assert!(
        provenance_guards.contains(
            "agent_doc_queue::queue_closeout_guard::free_text_queue_head_provenance_decision"
        ),
        "queue_head_provenance_guards should call focused queue provenance policy directly"
    );

    let partial_staging =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/partial_staging.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) const PARTIAL_CLOSEOUT_REMAINING_PHRASES",
        "pub(crate) fn text_has_shipped_signal",
        "pub(crate) fn text_has_partial_remaining_signal",
        "agent_doc_turn::closeout_signal::text_has_shipped_signal",
        "agent_doc_turn::closeout_signal::text_has_partial_remaining_signal",
        ".contains(\"<!-- no-partial-closeout-guard -->\")",
        "let resolved: std::collections::HashSet<String>",
        "let open_backlog: std::collections::HashSet<String>",
        "agent_doc_element_backlog::backlog::normalize_pending_id",
    ] {
        assert!(
            !partial_staging.contains(forbidden),
            "partial_staging must not re-own partial closeout signal policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::closeout_signal::partial_closeout_state_decision",
        "agent_doc_turn::closeout_signal::PartialCloseoutStateEvidence",
        "agent_doc_turn::closeout_signal::PartialCloseoutStateDecision",
    ] {
        assert!(
            partial_staging.contains(required),
            "partial_staging should call focused closeout signal policy directly: {required}"
        );
    }

    let done_signals_path =
        manifest_dir.join("agent-doc-orchestration/src/session_check/done_signals.rs");
    assert!(
        !done_signals_path.exists(),
        "session_check/done_signals.rs must stay deleted instead of becoming a closeout-signal facade"
    );
    for required in [
        "pub fn response_clearly_completes_pending_id",
        "pub fn response_heading_resolves_to_pending_id",
        "pub fn explicit_done_signal_ids",
        "pub fn plain_done_signal",
        "pub fn inline_done_signal_ids",
        "fn normalize_done_signal_text",
        "fn leading_hash_id",
        "fn extract_bracket_ids",
        "fn contains_completion_marker",
    ] {
        assert!(
            turn_source.contains(required),
            "agent-doc-turn should own closeout done-signal policy directly: {required}"
        );
    }
    let tracked_work_source =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/tracked_work_projection.rs"))
            .unwrap();
    for required in [
        "pub fn open_tracked_work_ids",
        "pub fn open_backlog_ids",
        "pub fn open_review_ids",
    ] {
        assert!(
            tracked_work_source.contains(required),
            "agent-doc-document should own open tracked-work projection policy directly: {required}"
        );
    }

    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    assert!(
        preflight_run.contains("agent_doc_element_backlog::backlog::open_backlog_ids_in_content"),
        "preflight should call focused open-backlog id extraction directly"
    );
    for forbidden in [
        "agent_doc_element_backlog::backlog::parse_items(component.content(content))",
        ".filter(|component| {\n                            agent_doc_element::element::is_backlog_component(&component.name)",
    ] {
        assert!(
            !preflight_run.contains(forbidden),
            "preflight must not re-own open backlog id extraction policy: {forbidden}"
        );
    }

    let pending_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/pending_guards.rs"))
            .unwrap();
    assert!(
        !pending_guards.contains("pub fn response_text_for_guards"),
        "pending_guards must not re-own closeout response text normalization"
    );
    for forbidden in [
        "pub fn detect_missing_pending_done_ids",
        ".contains(\"<!-- no-pending-done-guard -->\")",
        "agent_doc_turn::closeout_signal::response_clearly_completes_pending_id",
    ] {
        assert!(
            !pending_guards.contains(forbidden),
            "pending_guards must not re-own tracked-work completion policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::closeout_signal::tracked_work_completion_decision",
        "agent_doc_turn::closeout_signal::TrackedWorkCompletionEvidence",
        "agent_doc_turn::closeout_signal::TrackedWorkCompletionDecision",
    ] {
        assert!(
            pending_guards.contains(required),
            "pending_guards should call focused tracked-work completion policy directly: {required}"
        );
    }

    for relative in [
        "agent-doc-session-check-io/src/pending_guards.rs",
        "agent-doc-session-check-io/src/write_pending_checks.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_turn::closeout_signal::response_text_for_guards"),
            "{relative} should call focused closeout response text normalization directly"
        );
        assert!(
            !source.contains("crate::session_check::response_text_for_guards"),
            "{relative} must not route closeout response text normalization through session_check"
        );
    }

    let backlog_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/backlog_guards.rs"))
            .unwrap();
    let backlog_guard_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/guard_policy.rs"))
            .unwrap();
    assert!(
        !backlog_guards
            .contains("agent_doc_turn::closeout_signal::response_clearly_completes_pending_id")
            && !backlog_guard_policy
                .contains("agent_doc_turn::closeout_signal::response_clearly_completes_pending_id"),
        "document-only backlog guards should not retain unused response-aware closeout filtering"
    );
    assert!(
        !backlog_guards.contains("session_check::response_clearly_completes_pending_id"),
        "backlog_guards must not route closeout signal policy through session_check"
    );

    let pending_checks = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/write_pending_checks.rs"),
    )
    .unwrap();
    let pending_capture_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/pending_capture.rs")).unwrap();
    let pending_capture_io =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/pending_capture.rs"))
            .unwrap();
    let cycle_state =
        fs::read_to_string(manifest_dir.join("agent-doc-cycle-state-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn tracked_work_ids_from_component_body",
        "pub fn tracked_work_ids_for_target",
    ] {
        assert!(
            backlog_source.contains(required),
            "agent-doc-element-backlog must own tracked-work target id parsing: {required}"
        );
    }
    for forbidden in [
        "pub(crate) fn normalize_pending_id",
        "fn normalize_pending_id(",
        "pub(crate) fn tracked_work_ids_from_component_body",
        "fn tracked_work_ids_from_component_body(",
        "pub(crate) fn tracked_work_ids_for_target",
        "fn tracked_work_ids_for_target(",
    ] {
        assert!(
            !pending_checks.contains(forbidden),
            "write pending checks must not re-own tracked-work target id parsing: {forbidden}"
        );
    }
    assert!(
        !cycle_state.contains("fn normalize_pending_id("),
        "cycle_state must reuse the focused backlog id normalizer instead of re-owning it"
    );
    assert!(
        cycle_state.contains("agent_doc_element_backlog::backlog::normalize_pending_id"),
        "cycle_state should import the focused backlog id normalizer directly"
    );
    for forbidden in [
        "crate::session_check::detect_missing_pending_done_ids",
        ".contains(\"<!-- no-pending-done-guard -->\")",
    ] {
        assert!(
            !pending_checks.contains(forbidden),
            "write pending checks must not route tracked-work completion policy through session_check: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::closeout_signal::pending_done_suppressed",
        "agent_doc_turn::closeout_signal::tracked_work_completion_missing_done_ids",
        "agent_doc_turn::closeout_signal::tracked_work_completion_decision",
        "agent_doc_turn::closeout_signal::TrackedWorkCompletionEvidence",
        "agent_doc_turn::closeout_signal::TrackedWorkCompletionDecision",
    ] {
        assert!(
            pending_checks.contains(required),
            "write pending checks should call focused tracked-work completion policy directly: {required}"
        );
    }
    assert!(
        pending_capture_io
            .contains("agent_doc_element_backlog::backlog::tracked_work_ids_for_target"),
        "session-check pending-capture IO should own tracked-work target id lookup"
    );
    assert!(
        pending_capture_policy.contains("backlog::normalize_pending_id")
            && pending_capture_io
                .contains("agent_doc_workflow::pending_capture::missing_promised_backlog_item_ids")
            && pending_checks.contains("unresolved_promised_backlog_item_ids"),
        "write pending checks should route promised-id normalization through session-check IO and agent-doc-workflow pending-capture policy"
    );

    let turn_response_text =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/response_text.rs")).unwrap();
    assert!(
        turn_response_text.contains("pub fn strip_assistant_heading"),
        "agent-doc-turn must own append response heading normalization"
    );
    for required in [
        "pub fn response_prompt_target_from_re_heading",
        "pub fn summarize_response_for_hook",
        "pub fn is_committed_prompt_diff_interruption",
        "pub fn prompt_target_from_interruption_reason",
        "pub fn first_nonempty_prompt_line",
        "fn truncate_response_summary",
    ] {
        assert!(
            turn_response_text.contains(required),
            "agent-doc-turn must own hook response projection policy: {required}"
        );
    }
    for required in [
        "pub fn response_satisfies_imperative_contract",
        "pub enum ImperativeResponseContractDecision",
        "pub fn imperative_response_contract_decision",
        "pub fn truncate_imperative_trigger",
        "const IMPERATIVE_STATUS_ONLY_SIGNALS",
        "const IMPERATIVE_META_REFUSAL_SIGNALS",
        "const IMPERATIVE_BLOCKER_SIGNALS",
        "const IMPERATIVE_EVIDENCE_LABELS",
    ] {
        assert!(
            turn_response_text.contains(required),
            "agent-doc-turn must own imperative response contract policy: {required}"
        );
    }
    let turn_lib = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_lib.contains("pub mod response_text;"),
        "agent-doc-turn should expose response text policy through its owning module"
    );
    assert!(
        !turn_lib.contains("pub use response_text"),
        "agent-doc-turn should not add a response_text root facade"
    );
    let response_replay =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/response_replay.rs")).unwrap();
    for required in [
        "pub fn response_already_applied",
        "pub fn response_already_applied_after_prefix_strip",
        "pub fn response_materialized_in_content",
        "pub fn materialize_response_in_current_exchange",
        "pub fn first_response_heading_line",
        "pub fn live_exchange_answers_heading",
        "pub fn has_matching_orphan_prompt_for_committed_capture",
        "pub fn extract_visible_response_patch_between",
        "pub fn prompt_change_is_known_response",
        "pub fn dedupe_responses",
        "pub fn first_duplicate_response_heading",
        "pub struct JbCacheConflictAcceptDuplicateReplay",
        "pub fn classify_jb_cache_conflict_accept_duplicate_replay",
        "pub struct LateIpcResponseOverapplication",
        "pub fn classify_late_ipc_response_overapplication",
        "pub fn is_committed_response_overapplication",
        "pub fn is_committed_response_replay_including_stale",
        "fn normalized_response_lines",
    ] {
        assert!(
            response_replay.contains(required),
            "agent-doc-turn must own response replay/application policy: {required}"
        );
    }
    assert!(
        turn_lib.contains("pub mod response_replay;"),
        "agent-doc-turn should expose response replay policy through its owning module"
    );
    assert!(
        !turn_lib.contains("pub use response_replay"),
        "agent-doc-turn should not add a response_replay root facade"
    );
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    assert!(
        !write_source.contains("pub fn strip_assistant_heading"),
        "orchestration write must not re-own append response heading normalization"
    );
    assert!(
        write_source.contains("agent_doc_turn::response_replay::response_already_applied"),
        "orchestration write should call focused response replay policy directly"
    );
    let repair_runtime_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-runtime-io/src/lib.rs")).unwrap();
    assert!(
        write_source
            .contains("use agent_doc_turn::response_replay::response_materialized_in_content")
            && repair_runtime_source
                .contains("use agent_doc_turn::response_replay::dedupe_responses;"),
        "write and repair runtime IO should import focused response replay policy directly from the owning module"
    );
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(\n        file,\n        \"recover_missing_committed_head_response\",",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(\n        file,\n        \"recover_dedupe_only_drift\",",
    ] {
        assert!(
            repair_runtime_source.contains(required),
            "repair runtime recovery should resolve current document content through realtime authority: {required}"
        );
    }
    assert!(
        !repair_runtime_source.contains("std::fs::read_to_string(file)"),
        "repair runtime recovery must not read the active document directly"
    );
    let response_replay_io =
        fs::read_to_string(manifest_dir.join("agent-doc-response-replay-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub fn dedupe_responses",
        "pub fn first_duplicate_response_heading",
        "pub fn is_committed_response_overapplication",
        "pub fn is_committed_response_replay_including_stale",
        "fn split_scaffold_and_responses",
        "fn normalize_response_block_line",
    ] {
        assert!(
            !response_replay_io.contains(forbidden),
            "response replay IO must stay a file I/O adapter, not re-own pure response replay policy: {forbidden}"
        );
    }
    for required in [
        "use agent_doc_turn::response_replay::dedupe_responses;",
        "pub trait DedupeEffects",
        "fn current_document_content(file: &Path) -> Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"response_replay_dedupe\"",
        "fn write_deduped_document(",
        "fn save_snapshot(",
    ] {
        assert!(
            response_replay_io.contains(required),
            "response replay IO should own dedupe file effects while calling focused policy: {required}"
        );
    }
    assert!(
        !response_replay_io.contains("std::fs::read_to_string(file)")
            && !response_replay_io.contains("fs::read_to_string(file)"),
        "response replay IO must not read the active document directly from disk"
    );
    let response_replay_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-response-replay-io/Cargo.toml")).unwrap();
    for required in [
        "agent-doc-document-realtime-io",
        "agent-doc-turn",
        "agent-doc-fs",
    ] {
        assert!(
            response_replay_io_manifest.contains(required),
            "response replay IO should depend on focused dependency {required}"
        );
    }
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-git-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
    ] {
        assert!(
            !response_replay_io_manifest.contains(forbidden),
            "response replay IO must not depend on orchestration-side systems: {forbidden}"
        );
    }
    let cli_dedupe_source = fs::read_to_string(manifest_dir.join("src/dedupe_cmd.rs")).unwrap();
    assert!(
        cli_dedupe_source.contains("agent_doc_response_replay_io::run(&EFFECTS, file)")
            && cli_dedupe_source.contains("agent_doc_write_converge_io::converge_or_disk_write")
            && cli_dedupe_source
                .contains("agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS")
            && cli_dedupe_source.contains("agent_doc_snapshot_io::checkpoint_document_baseline("),
        "CLI dedupe adapter should only inject writer and snapshot effects"
    );
    assert!(
        !cli_dedupe_source.contains("agent_doc_write_runtime_io::WRITE_CONVERGENCE_EFFECTS"),
        "CLI dedupe adapter must not route convergence effects through the orchestration write facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/dedupe.rs")
            .exists(),
        "orchestration must not keep a dedupe facade module"
    );
    for forbidden in [
        "use agent_doc_turn::response_replay::dedupe_responses;",
        "agent_doc_fs::document_state_hash",
        ".join(\".agent-doc/patches\")",
    ] {
        assert!(
            !cli_dedupe_source.contains(forbidden),
            "CLI dedupe adapter must not re-own response replay IO details: {forbidden}"
        );
    }
    let write_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    let write_converge =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    assert!(
        !write_ipc.contains("pub fn materialize_response_in_current_exchange")
            && !write_ipc.contains("fn materialize_response_in_current_exchange"),
        "write/ipc must not re-own response exchange materialization policy"
    );
    assert!(
        write_converge.contains("materialize_response_in_current_exchange"),
        "write-converge IO should call focused response exchange materialization policy directly"
    );
    let write_materialize = fs::read_to_string(
        manifest_dir.join("agent-doc-template-io/src/response_materialization_io.rs"),
    )
    .unwrap();
    for forbidden in [
        "pub fn response_materialized_in_content",
        "pub(crate) fn response_materialized_in_content",
        "response_materialization_probe_from_response",
    ] {
        assert!(
            !write_materialize.contains(forbidden),
            "write/materialize must not re-own response materialization policy: {forbidden}"
        );
    }
    let repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/tests/repair.rs"))
            .unwrap();
    for forbidden in [
        "pub fn response_already_applied",
        "pub fn response_already_applied_after_prefix_strip",
        "pub(crate) fn first_response_heading_line",
        "pub(crate) fn live_exchange_answers_heading",
        "fn normalized_response_lines",
        "fn normalize_response_line",
        "fn strip_transient_response_head_marker",
        "fn prompt_change_is_known_response",
    ] {
        assert!(
            !repair_source.contains(forbidden),
            "orchestration repair must not re-own response replay/application policy: {forbidden}"
        );
    }
    let session_check_detect =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/detect.rs")).unwrap();
    for forbidden in [
        "struct JbCacheConflictAcceptDuplicateReplay",
        "struct LateIpcResponseOverapplication",
        "fn classify_jb_cache_conflict_accept_duplicate_replay",
        "fn classify_late_ipc_response_overapplication",
        "fn is_committed_response_overapplication",
        "fn is_committed_response_replay_including_stale",
    ] {
        assert!(
            !session_check_detect.contains(forbidden),
            "session-check detect IO must adapt file IO into focused response replay policy, not re-own it: {forbidden}"
        );
    }
    assert!(
        session_check_detect.contains("use agent_doc_turn::response_replay::{")
            && session_check_detect.contains("classify_jb_cache_conflict_accept_duplicate_replay(")
            && session_check_detect.contains("classify_late_ipc_response_overapplication("),
        "session-check detect IO should call focused response replay classifiers directly"
    );
    for relative in [
        "agent-doc-capture-io/src/lib.rs",
        "agent-doc-flow-io/src/closeout.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_turn::response_replay::"),
            "{relative} should call focused response replay policy directly"
        );
        assert!(
            !source.contains("crate::repair::response_already_applied")
                && !source.contains("crate::repair::response_already_applied_after_prefix_strip")
                && !source.contains("crate::repair::first_response_heading_line")
                && !source.contains("crate::repair::live_exchange_answers_heading"),
            "{relative} must not route response replay policy through repair"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let hooks_io = fs::read_to_string(manifest_dir.join("agent-doc-hooks-io/src/lib.rs")).unwrap();
    let memory_io_closeout =
        fs::read_to_string(manifest_dir.join("agent-doc-memory-io/src/closeout.rs")).unwrap();
    let codex_hook_source =
        fs::read_to_string(manifest_dir.join("agent-doc-codex-stop-io/src/lib.rs")).unwrap();
    assert!(
        memory_io_closeout.contains("agent_doc_turn::response_text::{")
            && memory_io_closeout.contains("response_prompt_target_from_re_heading")
            && memory_io_closeout.contains("summarize_response_for_hook"),
        "memory IO closeout should call focused response text projection directly"
    );
    assert!(
        hooks_io.contains("agent_doc_memory_io::closeout::capture_tsift_memory_closeout")
            && !hooks_io.contains("agent_doc_turn::response_text::{"),
        "hook IO should delegate tsift-memory closeout IO instead of owning response projection"
    );
    assert!(
        codex_hook_source.contains("use agent_doc_turn::response_text::{")
            && codex_hook_source.contains("is_committed_prompt_diff_interruption")
            && codex_hook_source.contains("prompt_target_from_interruption_reason")
            && codex_hook_source.contains("first_nonempty_prompt_line"),
        "Codex stop hook should call focused response-text interruption parsing directly"
    );
    for forbidden in [
        "fn extract_agent_doc_prompt_target",
        "fn summarize_agent_doc_response",
        "fn truncate_agent_doc_summary",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration hook bridge must not re-own hook response projection policy: {forbidden}"
        );
    }
    for forbidden in [
        "fn is_committed_prompt_diff_interruption(",
        "fn prompt_target_from_interruption_reason(",
        "fn first_nonempty_prompt_line(",
    ] {
        assert!(
            !codex_hook_source.contains(forbidden),
            "Codex stop hook must not re-own response-text interruption parsing: {forbidden}"
        );
    }
    let write_normalize =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/write_normalize.rs"))
            .unwrap();
    for forbidden in [
        "const IMPERATIVE_STATUS_ONLY_SIGNALS",
        "const IMPERATIVE_META_REFUSAL_SIGNALS",
        "const IMPERATIVE_BLOCKER_SIGNALS",
        "const IMPERATIVE_EVIDENCE_LABELS",
        "fn response_satisfies_imperative_contract",
        "fn contains_execution_evidence",
        "fn has_commandish_backticks",
        "fn has_code_path",
        "fn contains_commit_hash",
        "fn truncate_signal(",
        "agent_doc_diff::diff_contains_imperative_directive",
        "agent_doc_diff::extract_imperative_directives",
    ] {
        assert!(
            !write_normalize.contains(forbidden),
            "write::normalize must not re-own imperative response contract policy: {forbidden}"
        );
    }
    assert!(
        write_normalize.contains("agent_doc_turn::response_text::{")
            && write_normalize.contains("imperative_response_contract_decision")
            && write_normalize.contains("truncate_imperative_trigger"),
        "write::normalize should call focused imperative response contract policy directly"
    );
    for relative in [
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-run-io/src/lib.rs",
        "src/orchestrate/dispatch.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_turn::response_text::strip_assistant_heading"),
            "{relative} should call focused append response heading normalization directly"
        );
        assert!(
            !source.contains("write::strip_assistant_heading"),
            "{relative} must not route append response heading normalization through write"
        );
    }
}

#[test]
fn test_agent_doc_turn_owns_session_check_ops_log_event_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-ops-log-io")),
        "agent-doc-ops-log-io must stay a first-class workspace crate"
    );
    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-ops-log-io"),
        "root crate should expose focused ops-log IO directly"
    );

    let turn_op_log =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/op_log.rs")).unwrap();
    for required in [
        "pub const PREFLIGHT_START_EVENT",
        "pub const IPC_WRITE_CONSUMED_EVENT",
        "pub const IPC_PROOF_INSUFFICIENT_EVENT",
        "pub enum OpsLogEvent",
        "pub const PARSED_EVENTS:",
        "pub fn strip_timestamp_prefix(",
        "pub fn is_write_completed_commit_missing_event(",
        "pub fn event_name(",
        "pub fn build_ops_from_semantic_diff(",
    ] {
        assert!(
            turn_op_log.contains(required),
            "agent-doc-turn must own session-check ops-log event policy: {required}"
        );
    }
    let turn_lib = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_lib.contains("pub mod op_log;"),
        "agent-doc-turn should expose ops-log policy through its owning module"
    );
    assert!(
        !turn_lib.contains("pub use op_log")
            && !turn_lib.contains("pub use agent_doc_turn::op_log"),
        "agent-doc-turn should not add an op_log root facade"
    );

    let session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    let closeout_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/closeout_guards.rs"))
            .unwrap();
    let ops_log_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-ops-log-io/Cargo.toml")).unwrap();
    let ops_log_io_manifest: toml::Value = toml::from_str(&ops_log_io_manifest).unwrap();
    let ops_log_io_dependencies = ops_log_io_manifest["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-cycle-state-io",
        "agent-doc-frontmatter",
        "agent-doc-git-io",
        "agent-doc-hash",
        "agent-doc-log-time",
        "agent-doc-project-root-io",
        "agent-doc-turn",
        "anyhow",
        "serde",
        "serde_json",
    ] {
        assert!(
            ops_log_io_dependencies.contains_key(required),
            "agent-doc-ops-log-io should depend on focused ops-log read/write dependency: {required}"
        );
    }
    for forbidden in [
        "agent-doc-fs",
        "agent-doc-orchestration",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
        "tmux-router",
    ] {
        assert!(
            !ops_log_io_dependencies.contains_key(forbidden),
            "agent-doc-ops-log-io must stay a focused ops-log reader, not orchestration or transport state: {forbidden}"
        );
    }
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration_manifest["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-ops-log-io"),
        "agent-doc-orchestration should call the focused ops-log IO crate"
    );
    let ops_log_io =
        fs::read_to_string(manifest_dir.join("agent-doc-ops-log-io/src/lib.rs")).unwrap();
    for required in [
        "pub struct CycleEntry",
        "pub const LOG_ROTATE_MAX_BYTES",
        "fn rotate_log_if_oversized(",
        "pub struct OpsLogTracking",
        "pub fn log_op(",
        "pub fn log_cycle(",
        "pub fn append_ops_log_at_project(",
        "pub fn append_cycle_log_for_file(",
        "pub fn append_cycle_entry_at_project(",
        "pub fn last_ops_event(",
        "pub fn latest_ipc_proof_diagnostic(",
        "pub fn latest_ipc_proof_diagnostic_hint(",
        "pub fn detect_write_completed_commit_missing(",
        "pub fn latest_unclosed_write_completed_commit_missing(",
        "agent_doc_project_root_io::project_root_containing(",
        "agent_doc_frontmatter::frontmatter::parse(",
        "agent_doc_cycle_state_io::load_closeout_projection(file)",
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)",
        "agent_doc_turn::op_log::{",
        "strip_timestamp_prefix",
        "OpsLogEvent",
        "is_write_completed_commit_missing_event",
        "agent_doc_log_time::format_ops_log_line",
        "agent_doc_git_io::revision::last_commit_hash",
        "agent_doc_hash::content_hash",
        "serde_json::to_string",
        ".agent-doc/logs/ops.log",
        "cycles.jsonl",
    ] {
        assert!(
            ops_log_io.contains(required),
            "agent-doc-ops-log-io must own ops-log read/write adapters: {required}"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod ops_log")
            && !manifest_dir
                .join("agent-doc-orchestration/src/ops_log.rs")
                .exists(),
        "orchestration must not keep an ops_log facade module"
    );
    for (path, source) in [
        (
            "src/plan.rs",
            fs::read_to_string(manifest_dir.join("src/plan.rs")).unwrap(),
        ),
        (
            "agent-doc-preflight-command-io/src/lib.rs",
            fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs"))
                .unwrap(),
        ),
        (
            "agent-doc-preflight-command-io/src/run.rs",
            fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs"))
                .unwrap(),
        ),
        (
            "agent-doc-session-accretion-io/src/lib.rs",
            fs::read_to_string(manifest_dir.join("agent-doc-session-accretion-io/src/lib.rs"))
                .unwrap(),
        ),
    ] {
        assert!(
            source.contains("agent_doc_ops_log_io::CycleEntry"),
            "{path} should use CycleEntry from the focused ops-log IO crate"
        );
        for forbidden in [
            "crate::ops_log::CycleEntry",
            "agent_doc_orchestration::ops_log::CycleEntry",
        ] {
            assert!(
                !source.contains(forbidden),
                "{path} must not depend on the orchestration CycleEntry facade: {forbidden}"
            );
        }
    }
    for forbidden in [
        "pub const PREFLIGHT_START_EVENT",
        "pub const IPC_WRITE_CONSUMED_EVENT",
        "pub const IPC_PROOF_INSUFFICIENT_EVENT",
        "pub(crate) fn strip_timestamp_prefix(",
        "pub(crate) fn is_write_completed_commit_missing_event(",
        "pub(crate) fn event_name(",
        "fn build_ops_from_semantic_diff(",
    ] {
        assert!(
            !session_check.contains(forbidden) && !closeout_guards.contains(forbidden),
            "session-check must not re-own ops-log event policy: {forbidden}"
        );
    }
    for forbidden in [
        "pub fn last_ops_event(",
        "pub fn latest_ipc_proof_diagnostic(",
        "pub fn latest_ipc_proof_diagnostic_hint(",
        "pub fn detect_write_completed_commit_missing(",
        "pub use agent_doc_ops_log_io::{",
        "agent_doc_fs::find_project_root(",
    ] {
        assert!(
            !session_check.contains(forbidden) && !closeout_guards.contains(forbidden),
            "session-check modules must not re-own or facade ops-log read/path IO: {forbidden}"
        );
    }
    assert!(
        !closeout_guards.contains(".agent-doc/logs/ops.log"),
        "closeout_guards must not re-own ops-log path IO"
    );
    assert!(
        session_check.contains("use agent_doc_turn::op_log::{")
            && session_check.contains("event_name")
            && session_check.contains("is_write_completed_commit_missing_event")
            && session_check.contains("PREFLIGHT_START_EVENT")
            && session_check.contains("agent_doc_ops_log_io::last_ops_event("),
        "session-check command IO should import focused ops-log policy and call focused ops-log IO directly"
    );
    let preflight_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    for (path, source, required) in [
        (
            "agent-doc-preflight-io/src/lib.rs",
            preflight_io_source.as_str(),
            "agent_doc_ops_log_io::latest_ipc_proof_diagnostic(",
        ),
        (
            "agent-doc-preflight-io/src/lib.rs",
            preflight_io_source.as_str(),
            "agent_doc_ops_log_io::latest_ipc_proof_diagnostic_hint(",
        ),
        (
            "agent-doc-preflight-io/src/lib.rs",
            preflight_io_source.as_str(),
            "agent_doc_ops_log_io::detect_write_completed_commit_missing(",
        ),
        (
            "agent-doc-repair-io/src/lib.rs",
            repair_source.as_str(),
            "agent_doc_ops_log_io::latest_unclosed_write_completed_commit_missing(",
        ),
    ] {
        assert!(
            source.contains(required),
            "{path} should call focused ops-log IO directly: {required}"
        );
        assert!(
            !source.contains("crate::session_check::latest_ipc_proof_diagnostic")
                && !source.contains("crate::session_check::latest_ipc_proof_diagnostic_hint")
                && !source.contains("crate::session_check::detect_write_completed_commit_missing"),
            "{path} must not route ops-log IO through session_check"
        );
    }
    assert!(
        closeout_guards.contains("agent_doc_ops_log_io::latest_ipc_proof_diagnostic_hint("),
        "closeout_guards should call focused ops-log IO directly"
    );
}

#[test]
fn test_agent_doc_turn_owns_no_change_cycle_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/no_change.rs")
            .exists(),
        "no-change cycle diagnostics should live in the focused turn crate"
    );

    let turn_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/no_change.rs")).unwrap();
    for required in [
        "pub struct NoChangeCycleStateInput",
        "pub enum NoChangeVerdict",
        "pub fn classify_no_change_cycle_state",
        "pub const fn has_bookkeeping_without_response",
    ] {
        assert!(
            turn_source.contains(required),
            "agent-doc-turn must own no-change cycle policy: {required}"
        );
    }

    let turn_lib = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_lib.contains("pub mod no_change;"),
        "agent-doc-turn should expose no-change policy through its owning module"
    );
    assert!(
        !turn_lib.contains("pub use no_change"),
        "agent-doc-turn should not add a no_change root facade"
    );

    let direct_run_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/tests/direct_run.rs")).unwrap();
    let run_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    for forbidden in [
        "enum NoChangeVerdict",
        "fn classify_no_change_cycle_state(",
        ".starts_with(\"recursive_direct_invocation_blocked\")",
        "bookkeeping-only closeout",
        "let bookkeeping =",
    ] {
        assert!(
            !direct_run_tests.contains(forbidden),
            "orchestration direct-run tests must not re-own or facade no-change cycle policy: {forbidden}"
        );
    }
    for required in [
        "use agent_doc_turn::no_change::{",
        "NoChangeCycleStateInput",
        "classify_no_change_cycle_state",
    ] {
        assert!(
            run_io_source.contains(required),
            "run IO should call focused no-change policy directly: {required}"
        );
    }
    for required in [
        "let cycle_state = agent_doc_cycle_state_io::load_with_closeout_projection(file)?",
        "let open_cycle = agent_doc_cycle_state_io::load_with_closeout_projection(file)",
        "let state = agent_doc_cycle_state_io::load_with_closeout_projection(file)",
    ] {
        assert!(
            run_io_source.contains(required),
            "run IO should use closeout projection facts before compatibility cycle sidecars for direct-run decisions: {required}"
        );
    }
}

#[test]
fn test_agent_doc_turn_owns_turn_status_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let turn_status =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/turn_status.rs")).unwrap();
    for required in [
        "pub const TURN_ACTIVE_PANE_TITLE",
        "pub const STALE_SUPERVISOR_PANE_MARKER",
        "pub const TURN_ACTIVE_TTL_SECS",
        "pub struct TurnActiveMarker",
        "pub fn turn_active_marker_is_fresh",
        "pub fn turn_active_marker_matches_pane",
        "pub fn pane_title_for_state",
        "pub fn pane_title_for_status",
    ] {
        assert!(
            turn_status.contains(required),
            "agent-doc-turn must own turn-status policy vocabulary: {required}"
        );
    }

    let turn_lib = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_lib.contains("pub mod turn_status;"),
        "agent-doc-turn should expose turn-status policy through its owning module"
    );
    assert!(
        !turn_lib.contains("pub use turn_status"),
        "agent-doc-turn should not add a turn_status root facade"
    );

    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-turn-status-io\""),
        "agent-doc-turn-status-io should be a workspace member"
    );
    assert!(
        workspace_manifest
            .contains("agent-doc-turn-status-io = { path = \"agent-doc-turn-status-io\""),
        "CLI shell should depend on turn-status IO directly"
    );

    let turn_status_io =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-status-io/src/lib.rs")).unwrap();
    let turn_status_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-status-io/Cargo.toml")).unwrap();
    let turn_status_io_manifest: toml::Value = toml::from_str(&turn_status_io_manifest).unwrap();
    let turn_status_io_dependencies = turn_status_io_manifest["dependencies"].as_table().unwrap();
    assert!(
        turn_status_io_dependencies.contains_key("agent-doc-project-root-io"),
        "turn-status IO should delegate state root discovery through project-root IO"
    );
    assert!(
        turn_status_io_dependencies.contains_key("agent-doc-sqlite"),
        "turn-status IO should persist coordination facts in state.db"
    );
    assert!(
        !turn_status_io_dependencies.contains_key("agent-doc-fs"),
        "turn-status IO should not own direct filesystem project-root discovery"
    );
    for forbidden in [
        "pub const TURN_ACTIVE_PANE_TITLE",
        "pub const STALE_SUPERVISOR_PANE_MARKER",
        "pub const STALE_SUPERVISOR_MARKER",
        "pub const TURN_ACTIVE_MARKER",
        "pub const TURN_ACTIVE_TTL_SECS",
        "pub struct TurnActiveMarker",
        "pub fn pane_title_for_state",
        "pub fn pane_title_for_status",
        "pub use agent_doc_turn::turn_status",
    ] {
        assert!(
            !turn_status_io.contains(forbidden),
            "turn-status IO must stay an effect adapter, not a policy facade: {forbidden}"
        );
    }
    for required in [
        "agent_doc_turn::turn_status::{",
        "TurnActiveMarker",
        "pane_title_for_status",
        "turn_active_marker_is_fresh",
        "turn_active_marker_matches_pane",
        "read_turn_active_marker_for_file",
        "CoordinationLeaseRecord",
        "upsert_coordination_lease_in_db",
        "load_coordination_lease_from_db",
        "clear_coordination_lease_in_db",
        "agent_doc_project_root_io::project_root_containing(",
        "agent_doc_project_root_io::project_root_from_cwd(",
    ] {
        assert!(
            turn_status_io.contains(required),
            "turn-status IO should call focused turn-status policy directly: {required}"
        );
    }
    assert!(
        !turn_status_io.contains("agent_doc_fs::find_project_root("),
        "turn-status IO should delegate project-root resolution through project-root IO"
    );
    assert!(
        !turn_status_io.contains("agent_doc_orchestration::"),
        "turn-status IO must not reach back through orchestration"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod turn_status;"),
        "orchestration must not expose a turn_status facade"
    );

    let main = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        main.contains("agent_doc_turn_status_io::run(true)")
            && main.contains("agent_doc_turn_status_io::run(false)"),
        "turn-status command should call the focused IO crate directly"
    );
    let session_actor_cmd =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    assert!(
        session_actor_cmd.contains("agent_doc_turn_status_io::read_turn_active_marker"),
        "session actor command should read turn-active markers through the focused IO crate"
    );
    for relative_path in [
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_turn_status_io::"),
            "{relative_path} should call turn-status IO directly"
        );
    }
    let start_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    assert!(
        !start_source.contains("agent_doc_fs::find_project_root(")
            && start_source.contains("agent_doc_turn_status_io::read_turn_active_marker_for_file("),
        "start.rs should ask turn-status IO for file-scoped marker reads instead of owning root discovery"
    );
}

#[test]
fn test_agent_doc_turn_owns_owner_pane_recursion_diagnostics() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/owner_pane_recursion.rs")
            .exists(),
        "owner-pane self-invocation diagnostic policy should live in the focused turn crate"
    );

    let turn_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/owner_pane_recursion.rs"))
            .unwrap();
    for required in [
        "pub struct OwnerPaneQueueHead",
        "pub const OWNER_PANE_WEDGE_THRESHOLD",
        "pub struct OwnerPaneWedgeRecord",
        "pub fn record_owner_pane_wedge_fire",
        "pub fn owner_pane_wedge_threshold_reached",
        "pub fn recursive_direct_invocation_message",
        "pub fn recursive_start_invocation_message",
        "pub fn prompt_miss_message",
        "pub fn queue_handoff_message",
        "pub fn queue_wedge_halt_message",
    ] {
        assert!(
            turn_source.contains(required),
            "agent-doc-turn must own owner-pane recursion diagnostic policy: {required}"
        );
    }

    let turn_lib = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_lib.contains("pub mod owner_pane_recursion;"),
        "agent-doc-turn should expose owner-pane recursion diagnostics through the owning module"
    );
    assert!(
        !turn_lib.contains("pub use owner_pane_recursion"),
        "agent-doc-turn should not add an owner_pane_recursion root facade"
    );

    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let package_version = workspace["package"]["version"].as_str();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-owner-pane-io")),
        "agent-doc-owner-pane-io must stay a first-class workspace crate"
    );
    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    let root_dependency = root_dependencies["agent-doc-owner-pane-io"]
        .as_table()
        .unwrap();
    assert_eq!(
        root_dependency.get("path").and_then(toml::Value::as_str),
        Some("agent-doc-owner-pane-io")
    );
    assert_eq!(
        root_dependency.get("version").and_then(toml::Value::as_str),
        package_version
    );

    let owner_pane_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-owner-pane-io/Cargo.toml")).unwrap();
    let owner_pane_io_crate: toml::Value = toml::from_str(&owner_pane_io_manifest).unwrap();
    let owner_pane_io_dependencies = owner_pane_io_crate["dependencies"].as_table().unwrap();
    assert!(
        owner_pane_io_dependencies.contains_key("agent-doc-turn")
            && owner_pane_io_dependencies.contains_key("agent-doc-fs"),
        "owner-pane IO must depend on turn policy and filesystem path helpers directly"
    );
    for forbidden_dependency in ["agent-doc-core", "agent-doc-orchestration"] {
        assert!(
            !owner_pane_io_dependencies.contains_key(forbidden_dependency),
            "owner-pane IO must not depend on core/orchestration facades: {forbidden_dependency}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/owner_pane_wedge_counter.rs")
            .exists(),
        "orchestration must not keep an owner_pane_wedge_counter source module facade"
    );
    assert!(
        !orchestration_lib.contains("pub mod owner_pane_wedge_counter;"),
        "orchestration must not expose an owner-pane wedge-counter IO facade"
    );

    let direct_run_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/tests/direct_run.rs")).unwrap();
    let run_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    let owner_pane_io =
        fs::read_to_string(manifest_dir.join("agent-doc-owner-pane-io/src/lib.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/recguard_wedge.rs")
            .exists(),
        "old recguard_wedge module path should not remain as a compatibility alias"
    );
    for forbidden in [
        "fn format_recursive_start_diagnostic",
        "fn owned_pane_prompt_miss_diagnostic",
        "fn owned_pane_queue_handoff_diagnostic",
        "fn owned_pane_queue_wedge_halt_diagnostic",
        "recursive self-owned-pane start would deadlock:",
        "owned-pane self-invocation with unresolved exchange prompt:",
        "owned-pane self-invocation with active auto-queue head:",
        "owned-pane self-invocation WEDGE:",
        "managed owner-pane supervisor will submit",
    ] {
        assert!(
            !direct_run_tests.contains(forbidden),
            "orchestration direct-run tests must not re-own or facade owner-pane recursion diagnostics: {forbidden}"
        );
    }
    for forbidden in [
        "pub const WEDGE_THRESHOLD",
        "struct WedgeRecord",
        "pub fn is_wedged(",
        "pub fn threshold_reached(",
    ] {
        assert!(
            !owner_pane_io.contains(forbidden),
            "owner-pane IO must not re-own extracted owner-pane wedge policy: {forbidden}"
        );
    }
    for required in [
        "use agent_doc_turn::owner_pane_recursion::{",
        "OwnerPaneQueueHead",
        "owner_pane_wedge_threshold_reached",
        "prompt_miss_message",
        "queue_handoff_message",
        "queue_wedge_halt_message",
    ] {
        assert!(
            run_io_source.contains(required),
            "run IO should call focused owner-pane recursion diagnostics directly: {required}"
        );
    }
    for required in [
        "use agent_doc_turn::owner_pane_recursion::{",
        "recursive_direct_invocation_message",
        "recursive_start_invocation_message",
    ] {
        assert!(
            run_io_source.contains(required),
            "run IO should call focused recursive owner-pane diagnostics directly: {required}"
        );
    }
    for required in ["OwnerPaneWedgeRecord", "record_owner_pane_wedge_fire"] {
        assert!(
            owner_pane_io.contains(required),
            "owner-pane IO should persist focused owner-pane wedge records directly: {required}"
        );
    }
    for relative_path in [
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-queue-io/src/queue_consume.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_owner_pane_io::"),
            "{relative_path} should call owner-pane IO directly"
        );
        assert!(
            !source.contains("crate::owner_pane_wedge_counter"),
            "{relative_path} must not call an orchestration owner-pane wedge-counter facade"
        );
    }
}

#[test]
fn test_agent_doc_turn_owns_pending_capture_heuristics() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let heuristics =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/heuristics.rs")).unwrap();
    for required in [
        "pub fn detect_uncaptured_recommendations(",
        "pub fn response_explicitly_has_no_followups(",
        "pub fn future_work_signal(",
    ] {
        assert!(
            heuristics.contains(required),
            "agent-doc-turn must own pending-capture closeout heuristic: {required}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt_contract.rs")
            .exists(),
        "orchestration must not keep a prompt_contract module that can re-own turn closeout no-follow-up policy"
    );

    let write_normalize =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/write_normalize.rs"))
            .unwrap();
    for forbidden in [
        "pub fn check_future_work_signals",
        "const FUTURE_WORK_SIGNALS",
        "pub(crate) const FUTURE_WORK_SIGNALS",
    ] {
        assert!(
            !write_normalize.contains(forbidden),
            "write::normalize must not re-own turn future-work phrase policy: {forbidden}"
        );
    }

    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    assert!(
        write_run_entry.contains("agent_doc_turn::heuristics::future_work_signal"),
        "write run entry should call focused future-work response policy directly"
    );

    for relative in [
        "agent-doc-session-check-io/src/pending_guards.rs",
        "agent-doc-session-check-io/src/write_pending_checks.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_turn::heuristics::response_explicitly_has_no_followups"),
            "{relative} should call focused no-follow-up heuristic directly"
        );
        assert!(
            !source.contains("crate::prompt_contract::response_explicitly_has_no_followups"),
            "{relative} must not route no-follow-up policy through prompt_contract"
        );
    }
}

#[test]
fn test_agent_doc_turn_owns_drain_stall_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-turn")),
        "agent-doc-turn must stay a first-class workspace crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-turn/src/drain_stall.rs")
            .exists(),
        "queue-stall turn policy should live in the focused turn crate"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/drain_stall.rs")
            .exists(),
        "orchestration must not keep a drain_stall marker-IO facade"
    );
    let queue_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/lib.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-queue-io/src/drain_stall.rs")
            .exists()
            && !queue_io_lib.contains("pub mod drain_stall;"),
        "agent-doc-queue-io must not keep the queue drain-stall marker sidecar module"
    );

    let state_backbone =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/src/lib.rs")).unwrap();
    for required_snippet in [
        "QueueDrainStallContinuationRecorded",
        "QueueDrainStallContinuationCleared",
        "QueueDrainStallProjection",
        "QueueDrainStallPhase",
        "QueueDrainStallEvent",
        "QueueDrainStallMachine",
        "transition_queue_drain_stall",
        "is_pending",
    ] {
        assert!(
            state_backbone.contains(required_snippet),
            "agent-doc-state-backbone must own queue drain-stall projection policy: {required_snippet}"
        );
    }

    let controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    for required_snippet in [
        "pub fn record_queue_drain_stall_continuation_pending_for_file(",
        "pub fn queue_drain_stall_status_for_file(",
        "pub fn queue_drain_stall_continuation_pending_for_file(",
        "pub fn clear_queue_drain_stall_continuation_pending_for_file(",
        "\"queue_drain_stall_continuation_recorded\"",
        "\"queue_drain_stall_continuation_cleared\"",
        "\"queue_drain_stall_status\"",
        "handle_queue_drain_stall_continuation_recorded",
        "handle_queue_drain_stall_continuation_cleared",
        "handle_queue_drain_stall_status",
    ] {
        assert!(
            controller_rpc.contains(required_snippet),
            "project controller must own queue drain-stall projection helper/RPC: {required_snippet}"
        );
    }
    for forbidden_snippet in [".agent-doc/drain-stall", "mark_continuation_pending("] {
        assert!(
            !state_backbone.contains(forbidden_snippet)
                && !controller_rpc.contains(forbidden_snippet),
            "queue drain-stall projection owners must not preserve marker storage authority: {forbidden_snippet}"
        );
    }

    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    assert!(
        preflight_source.contains("use agent_doc_turn::drain_stall::{"),
        "preflight must consume focused drain-stall policy directly"
    );
    assert!(
        preflight_source.contains(
            "agent_doc_controller_io::project_controller::queue_drain_stall_continuation_pending_for_file"
        ) && preflight_source.contains(
            "agent_doc_controller_io::project_controller::clear_queue_drain_stall_continuation_pending_for_file"
        ) && !preflight_source.contains("agent_doc_queue_io::drain_stall::"),
        "preflight must consume drain-stall projection helpers directly"
    );
    let session_check_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    let idle_watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    assert!(
        session_check_source.contains(
            "agent_doc_controller_io::project_controller::record_queue_drain_stall_continuation_pending_for_file"
        ) && idle_watch_source.contains(
            "agent_doc_controller_io::project_controller::clear_queue_drain_stall_continuation_pending_for_file"
        ) && !session_check_source.contains("agent_doc_queue_io::drain_stall::")
            && !idle_watch_source.contains("agent_doc_queue_io::drain_stall::"),
        "session-check and idle-watch must call controller drain-stall projection helpers directly"
    );
    let turn_drain_stall =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/drain_stall.rs")).unwrap();
    assert!(
        turn_drain_stall.contains("continuation_pending_projection: bool")
            && !turn_drain_stall.contains("pub struct ContinuationPending")
            && !turn_drain_stall.contains("pub fn continuation_pending_marker("),
        "agent-doc-turn must keep only pure drain-stall classification policy"
    );

    let turn_manifest = fs::read_to_string(manifest_dir.join("agent-doc-turn/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&turn_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-turn must stay pure and free of orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_agent_doc_queue_io_owns_write_queue_serialization_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&queue_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    assert!(
        manifest_dir
            .join("agent-doc-queue-io/src/write_queue.rs")
            .exists(),
        "document write queue serialization policy should live in focused queue IO"
    );
    assert!(
        dependencies.contains_key("agent-doc-document-realtime"),
        "queue IO should depend on focused realtime vocabulary for SessionOpKind and owner scope"
    );
    assert!(
        !dependencies.contains_key("agent-doc-orchestration"),
        "queue IO must not depend back on orchestration"
    );

    let queue_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/write_queue.rs")).unwrap();
    for required_snippet in [
        "pub trait DocumentWriteQueueSubmitter",
        "pub fn run_serialized_with",
        "pub fn serialized_atomic_write_with",
        "pub struct DocumentWriteQueue",
        "owner_scope_guard",
        "SessionOpKind::WriteSubmit",
        "SessionOpKind::Closeout",
        "SessionOpKind::Lifecycle",
    ] {
        assert!(
            queue_io_source.contains(required_snippet),
            "agent-doc-queue-io must own write-queue serialization policy: {required_snippet}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/write_queue.rs")
            .exists(),
        "orchestration must not keep a write_queue module after the focused queue IO extraction"
    );
    let realtime_io =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "agent_doc_queue_io::write_queue::DocumentWriteQueueSubmitter",
        "SessionActorWriteQueueSubmitter",
        "document_actor_in(",
    ] {
        assert!(
            realtime_io.contains(required_snippet),
            "realtime IO should adapt queue IO to the session actor effect: {required_snippet}"
        );
    }
    for required_snippet in [
        "serialized_atomic_write_with(",
        "atomic_write_through_authority,",
    ] {
        assert!(
            realtime_io.contains(required_snippet),
            "realtime IO should call focused queue IO directly for serialized writes: {required_snippet}"
        );
    }
}

#[test]
fn test_agent_doc_turn_cycle_phase_has_no_cycle_state_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-turn")),
        "agent-doc-turn must stay a first-class workspace crate"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod cycle_state"),
        "agent-doc-orchestration must not keep a cycle_state facade module"
    );
    assert!(
        !orchestration_lib.contains("pub mod admit"),
        "agent-doc-orchestration must not keep an admit facade module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/admit.rs")
            .exists(),
        "admit must live in the focused cycle-state IO crate, not orchestration"
    );
    let cycle_state_source =
        fs::read_to_string(manifest_dir.join("agent-doc-cycle-state-io/src/lib.rs")).unwrap();
    assert!(
        cycle_state_source.contains("pub fn admit_with_current_resolver"),
        "cycle_state IO must own the realtime admission cycle-open API"
    );
    assert!(
        !cycle_state_source.contains("pub use agent_doc_turn::CyclePhase"),
        "cycle_state must not re-export CyclePhase from the focused turn crate"
    );
    assert!(
        cycle_state_source
            .contains("use agent_doc_turn::{CycleEvent, CyclePhase, CyclePhaseMachine};"),
        "cycle_state should import the focused turn lifecycle model privately"
    );
    let turn_source = fs::read_to_string(manifest_dir.join("agent-doc-turn/src/lib.rs")).unwrap();
    assert!(
        turn_source.contains("pub const fn as_str(self) -> &'static str"),
        "agent-doc-turn must own canonical cycle phase labels"
    );
    assert!(
        turn_source.contains("pub mod repair;"),
        "agent-doc-turn should expose repair outcome vocabulary through its owning module"
    );
    let turn_repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/repair.rs")).unwrap();
    for required in [
        "pub const AMBIGUOUS_PREFLIGHT_STARTED_PATCHBACK_ERROR",
        "pub const RESPONSE_PATCHBACK_UNCOMMITTED_ERROR",
        "pub const EMPTY_PREFLIGHT_STARTED_NO_CAPTURE_ERROR",
        "pub const STALE_EMPTY_PREFLIGHT_TTL_SECS",
        "pub enum CancelOutcome",
        "pub enum RepairOutcome",
        "pub const fn as_str(self) -> &'static str",
        "pub const fn repaired(self) -> bool",
        "pub const fn replayed_response(self) -> bool",
        "pub const fn doctor_message(self) -> &'static str",
    ] {
        assert!(
            turn_repair_source.contains(required),
            "agent-doc-turn must own repair outcome vocabulary: {required}"
        );
    }
    let repair_integration_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/tests/repair.rs"))
            .unwrap();
    for forbidden in [
        "pub const AMBIGUOUS_PREFLIGHT_STARTED_PATCHBACK_ERROR",
        "pub const RESPONSE_PATCHBACK_UNCOMMITTED_ERROR",
        "pub const EMPTY_PREFLIGHT_STARTED_NO_CAPTURE_ERROR",
        "pub const STALE_EMPTY_PREFLIGHT_TTL_SECS",
        "pub enum CancelOutcome",
        "pub enum RepairOutcome",
        "impl RepairOutcome",
    ] {
        assert!(
            !repair_integration_source.contains(forbidden),
            "repair integration tests must stay an adapter, not re-own outcome vocabulary: {forbidden}"
        );
    }
    for required in [
        "pub const fn is_open(self) -> bool",
        "pub const WATCH_CYCLE_IN_FLIGHT_MAX_SECS",
        "pub fn cycle_phase_freshly_in_flight(",
    ] {
        assert!(
            turn_source.contains(required),
            "agent-doc-turn must own pure cycle phase/freshness policy: {required}"
        );
    }
    let watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/daemon.rs")).unwrap();
    assert_source_omits_all(
        &watch_source,
        "watch daemon",
        &[
            "pub(crate) const WATCH_CYCLE_IN_FLIGHT_MAX_SECS",
            "const WATCH_CYCLE_IN_FLIGHT_MAX_SECS",
            "cs.is_open() =>",
            "cs.is_open() &&",
        ],
    );
    assert_source_mentions_all(
        &watch_source,
        "watch daemon",
        &[
            "agent_doc_turn",
            "cycle_phase_freshly_in_flight",
            "agent_doc_cycle_state_io::load_with_closeout_projection(path)",
        ],
    );
    assert!(
        !watch_source.contains("agent_doc_cycle_state_io::load(path)"),
        "watch daemon should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        turn_source.contains("pub mod cycle_policy;"),
        "agent-doc-turn should expose pure cycle-state policy through its owning module"
    );
    let cycle_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/cycle_policy.rs")).unwrap();
    for required in [
        "pub fn is_stable_commit_event",
        "pub fn is_noop_commit_event",
        "pub fn normalize_checkpoint_task_id",
        "pub fn normalize_checkpoint_text_list",
    ] {
        assert!(
            cycle_policy.contains(required),
            "agent-doc-turn must own pure cycle-state policy: {required}"
        );
    }
    for forbidden in [
        "fn is_stable_commit_event(",
        "pub fn is_noop_commit_event(",
        "fn normalize_checkpoint_task_id(",
        "fn normalize_text_list(",
    ] {
        assert!(
            !cycle_state_source.contains(forbidden),
            "cycle_state must not re-own pure cycle policy: {forbidden}"
        );
    }
    assert!(
        cycle_state_source.contains("use agent_doc_turn::cycle_policy::{")
            && cycle_state_source.contains("normalize_checkpoint_text_list(prompt_targets)"),
        "cycle_state should call focused cycle policy directly"
    );

    fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                out.push(path);
            }
        }
    }

    let mut source_files = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut source_files);
    for path in source_files {
        let source = fs::read_to_string(&path).unwrap();
        let relative = path.strip_prefix(manifest_dir).unwrap().display();
        for forbidden_snippet in [
            "cycle_state::CyclePhase",
            "use crate::cycle_state::CyclePhase",
            "fn cycle_phase_name(",
            "fn cycle_phase_label(phase",
            "pub fn cycle_phase_label(phase",
            "fn cycle_phase_store_label(",
            "fn phase_name(phase: agent_doc_turn::CyclePhase)",
            "agent_doc_orchestration::repair::RepairOutcome",
            "crate::repair::RepairOutcome",
            "agent_doc_orchestration::repair::CancelOutcome",
            "crate::repair::CancelOutcome",
            "crate::repair::AMBIGUOUS_PREFLIGHT_STARTED_PATCHBACK_ERROR",
            "crate::repair::RESPONSE_PATCHBACK_UNCOMMITTED_ERROR",
            "crate::repair::EMPTY_PREFLIGHT_STARTED_NO_CAPTURE_ERROR",
            "crate::repair::STALE_EMPTY_PREFLIGHT_TTL_SECS",
            "message.contains(repair::AMBIGUOUS_PREFLIGHT_STARTED_PATCHBACK_ERROR",
            "message.contains(repair::RESPONSE_PATCHBACK_UNCOMMITTED_ERROR",
            "message.contains(repair::EMPTY_PREFLIGHT_STARTED_NO_CAPTURE_ERROR",
            "age_cycle_state(&doc, repair::STALE_EMPTY_PREFLIGHT_TTL_SECS",
            "fn repair_outcome_label(",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must call agent_doc_turn::CyclePhase directly, not re-own turn lifecycle phase policy: {forbidden_snippet}"
            );
        }
    }

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-turn"),
        "orchestration must depend on the focused turn crate directly"
    );
    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-turn"),
        "the CLI shell must depend on the focused turn crate directly"
    );
}

#[test]
fn test_agent_doc_log_time_has_no_ops_log_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-log-time")),
        "agent-doc-log-time must stay a first-class workspace crate"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod ops_log")
            && !manifest_dir
                .join("agent-doc-orchestration/src/ops_log.rs")
                .exists(),
        "orchestration must not keep an ops_log facade module"
    );
    let ops_log_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ops-log-io/src/lib.rs")).unwrap();
    assert!(
        ops_log_io_source.contains("agent_doc_log_time::current_epoch_secs")
            && ops_log_io_source.contains("agent_doc_log_time::format_ops_log_tracking_suffix")
            && ops_log_io_source.contains("agent_doc_log_time::format_ops_log_line"),
        "ops-log IO should call the focused log-time crate directly"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/preflight/semantic_diff.rs")
            .exists(),
        "orchestration must not keep a preflight semantic_diff facade"
    );
    let sqlite_op_log =
        fs::read_to_string(manifest_dir.join("agent-doc-sqlite/src/op_log.rs")).unwrap();
    assert!(
        !sqlite_op_log.contains("fn op_log_timestamp(")
            && !sqlite_op_log.contains("fn timestamp_now(")
            && sqlite_op_log.contains("agent_doc_log_time::current_epoch_secs()"),
        "sqlite op-log must call the focused log-time helper directly"
    );

    let log_time_source =
        fs::read_to_string(manifest_dir.join("agent-doc-log-time/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn current_epoch_secs(",
        "pub fn current_log_timestamp(",
        "pub fn current_local_date_ymd(",
        "pub fn format_ops_log_tracking_suffix(",
        "pub fn format_ops_log_line(",
    ] {
        assert!(
            log_time_source.contains(required_snippet),
            "agent-doc-log-time must own low-level log timestamp/format helpers: {required_snippet}"
        );
    }

    for relative in [
        "agent-doc-ops-log-io/src/lib.rs",
        "agent-doc-session-accretion-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-sync-io/src/sync.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("crate::ops_log::format_log_timestamp")
                && !source.contains("crate::ops_log::parse_log_timestamp"),
            "{relative} must call agent_doc_log_time helpers directly"
        );
    }
    let done_archive_source =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/done_archive.rs"))
            .unwrap();
    assert!(
        done_archive_source.contains("agent_doc_log_time::current_local_date_ymd()")
            && !done_archive_source.contains("Command::new(\"date\")")
            && !done_archive_source.contains("std::process::Command::new(\"date\")"),
        "done-archive IO date stamping must use the focused log-time helper"
    );
    let sqlite_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-sqlite/Cargo.toml")).unwrap();
    let sqlite_manifest: toml::Value = toml::from_str(&sqlite_manifest).unwrap();
    assert!(
        sqlite_manifest["dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-log-time"),
        "agent-doc-sqlite should depend on focused log-time for op-log timestamping"
    );

    let log_time_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-log-time/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&log_time_manifest).unwrap();
    let dependencies = parsed.get("dependencies").and_then(toml::Value::as_table);
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            dependencies.is_none_or(|dependencies| !dependencies.contains_key(forbidden)),
            "agent-doc-log-time must stay pure and free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_agent_doc_session_accretion_owns_pure_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-session-accretion")),
        "agent-doc-session-accretion must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-session-accretion-io")),
        "agent-doc-session-accretion-io must stay a first-class workspace crate"
    );

    let focused_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-accretion/src/lib.rs")).unwrap();
    let focused_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-accretion-io/src/lib.rs")).unwrap();
    let focused_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-session-accretion-io/Cargo.toml")).unwrap();
    let focused_io_manifest: toml::Value = toml::from_str(&focused_io_manifest).unwrap();
    let focused_io_dependencies = focused_io_manifest["dependencies"].as_table().unwrap();
    for required_snippet in [
        "pub enum SessionAccretionLevel",
        "pub struct SessionAccretionReport",
        "pub struct SessionAccretionInput",
        "pub fn evaluate_session_accretion(",
        "pub fn level_label(",
        "pub fn restart_or_drain_guidance(",
        "pub fn compaction_guidance(",
        "pub fn exchange_metrics(",
        "pub fn is_restart_churn_event(",
        "pub fn recent_restart_count_from_session_log(",
        "pub fn resolve_queue_context_reset_opt_in(",
        "pub fn resolve_clear_threshold(",
        "pub fn context_reset_reason_for_recent_compaction(",
        "pub fn context_reset_reason_for_report(",
    ] {
        assert!(
            focused_source.contains(required_snippet),
            "agent-doc-session-accretion must own pure session-accretion policy: {required_snippet}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod session_accretion")
            && !manifest_dir
                .join("agent-doc-orchestration/src/session_accretion.rs")
                .exists(),
        "orchestration must not keep a session_accretion facade module"
    );
    for forbidden_snippet in [
        "pub enum SessionAccretionLevel",
        "pub struct SessionAccretionReport",
        "pub struct SessionAccretionInput",
        "pub fn evaluate_session_accretion(",
        "fn evaluate_session_accretion(",
        "pub fn exchange_metrics(",
        "fn exchange_metrics(",
        "pub fn level_label(",
        "fn level_label(",
        "pub fn is_restart_churn_event(",
        "fn is_restart_churn_event(",
        "pub fn recent_restart_count_from_session_log(",
        "fn recent_restart_count_from_session_log(",
        "strip_prefix('[')",
        "split_once(']')",
        "split_once(\"] \")",
        "pub fn resolve_queue_context_reset_opt_in(",
        "fn resolve_queue_context_reset_opt_in(",
        "pub fn resolve_clear_threshold(",
        "fn resolve_clear_threshold(",
        "pub fn context_reset_reason_for_recent_compaction(",
        "fn context_reset_reason_for_recent_compaction(",
        "pub fn context_reset_reason_for_report(",
        "fn context_reset_reason_for_report(",
        "unwrap_or(DEFAULT_CLEAR_THRESHOLD)",
        "pub use agent_doc_session_accretion",
        "type SessionAccretion",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden_snippet),
            "orchestration must not re-own or facade pure session-accretion policy: {forbidden_snippet}"
        );
    }
    assert!(
        focused_io_source.contains("pub fn inspect(file: &Path)")
            && focused_io_source.contains("evaluate_session_accretion(session_accretion_input(")
            && focused_io_source.contains("SessionAccretionInput {")
            && focused_io_source.contains("pub fn queue_context_reset_reason(")
            && focused_io_source.contains("pub fn queue_context_reset_reason_if_opted_in("),
        "agent-doc-session-accretion-io should own session-accretion fact gathering and context-reset adapter APIs"
    );
    for required_snippet in [
        "const RECENT_EXCHANGE_COMPACTION_SCOPE",
        "pub fn record_recent_exchange_compaction(",
        "pub fn recent_exchange_compaction_timestamp(",
        "pub fn recent_exchange_compaction_timestamp_at(",
        "pub fn cycles_log_path(",
        "pub fn session_log_path(",
        "pub fn relative_file_key(",
        "pub fn recent_cycle_metrics(",
        "pub fn recent_restart_metrics(",
        "pub fn inspect(file: &Path)",
        "pub fn queue_context_reset_reason(",
        "pub fn queue_context_reset_reason_if_opted_in(",
        "fn session_accretion_input(",
        "pub fn queue_context_reset_opted_in(",
        "pub fn clear_threshold_for_doc(",
        "fn recent_exchange_compaction_scope(",
        "fn load_recent_exchange_compaction_timestamp(",
        "agent_doc_sqlite::state_store::CoordinationLeaseRecord",
        "agent_doc_sqlite::state_store::upsert_coordination_lease_in_db(",
        "agent_doc_sqlite::state_store::load_coordination_lease_from_db(",
        "POST_COMPACTION_NOOP_GRACE_SECS",
        "RECENT_WINDOW_SECS",
        "recent_restart_count_from_session_log",
        "resolve_queue_context_reset_opt_in",
        "resolve_clear_threshold",
        "agent_doc_frontmatter::frontmatter::parse",
        "agent_doc_frontmatter_io::session::parse_for_file(",
        "agent_doc_project_config_io::load_project_for_doc(file)",
        "agent_doc_supervisor_io::startup_miss::load_startup_miss(file)",
        "serde_json::from_str::<agent_doc_ops_log_io::CycleEntry>",
        "agent_doc_log_time::parse_log_timestamp",
        "agent_doc_fs::read_optional_text(",
    ] {
        assert!(
            focused_io_source.contains(required_snippet),
            "agent-doc-session-accretion-io must own recent compaction/log metric IO: {required_snippet}"
        );
    }
    for required_dependency in [
        "agent-doc-fs",
        "agent-doc-frontmatter",
        "agent-doc-frontmatter-io",
        "agent-doc-log-time",
        "agent-doc-ops-log-io",
        "agent-doc-project-config-io",
        "agent-doc-session-accretion",
        "agent-doc-sqlite",
        "agent-doc-supervisor-io",
        "anyhow",
        "serde_json",
    ] {
        assert!(
            focused_io_dependencies.contains_key(required_dependency),
            "agent-doc-session-accretion-io should own accretion log IO dependency: {required_dependency}"
        );
    }
    assert!(
        focused_io_source.contains("recent_exchange_compaction_timestamp(file)?")
            && focused_io_source.contains("recent_exchange_compaction_timestamp_at(file, now)?")
            && focused_io_source.contains("recent_cycle_metrics(file, now)?")
            && focused_io_source.contains("recent_restart_metrics(file, session_id, now)"),
        "agent-doc-session-accretion-io should consume focused recent-compaction and log metric IO"
    );
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !focused_io_source.contains(forbidden),
            "agent-doc-session-accretion-io must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects: {forbidden}"
        );
    }

    for relative in [
        "src/orchestrate.rs",
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-run-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_session_accretion::"),
            "{relative} should import session-accretion types from the focused crate"
        );
        assert!(
            !source.contains("agent_doc_orchestration::session_accretion::SessionAccretion")
                && !source.contains("crate::session_accretion::SessionAccretion"),
            "{relative} must not route session-accretion types through orchestration"
        );
    }
    let stream_source =
        fs::read_to_string(manifest_dir.join("agent-doc-stream-io/src/lib.rs")).unwrap();
    assert!(
        stream_source.contains("agent_doc_session_accretion_io::inspect(file)")
            && stream_source
                .contains("agent_doc_prompt_context_io::build_document_section_with_ssh_context"),
        "stream should gather session-accretion facts and delegate document-section rendering to focused IO directly"
    );
    assert!(
        !stream_source.contains("agent_doc_orchestration::session_accretion::SessionAccretion")
            && !stream_source.contains("crate::session_accretion::SessionAccretion"),
        "stream must not route session-accretion types through orchestration"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-session-accretion"),
        "the CLI shell must depend on the focused session-accretion crate directly"
    );
    assert!(
        root_dependencies.contains_key("agent-doc-session-accretion-io"),
        "the CLI shell must depend on the focused session-accretion IO crate directly"
    );
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-session-accretion"),
        "orchestration must depend on the focused session-accretion crate directly"
    );
    assert!(
        orchestration_dependencies.contains_key("agent-doc-session-accretion-io"),
        "orchestration must depend on the focused session-accretion IO crate directly"
    );

    let focused_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-session-accretion/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&focused_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(dependencies.contains_key("agent-doc-element"));
    assert!(dependencies.contains_key("agent-doc-log-time"));
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-session-accretion must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_prompt_context_owns_pure_rendering_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-prompt-context")),
        "agent-doc-prompt-context must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-prompt-context-io")),
        "agent-doc-prompt-context-io must stay a first-class workspace crate"
    );

    let focused_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context/src/lib.rs")).unwrap();
    let loaded_context_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context/src/loaded_context.rs"))
            .unwrap();
    assert!(
        focused_source.contains("pub mod loaded_context;"),
        "agent-doc-prompt-context must expose loaded-context ledger policy"
    );
    for required_snippet in [
        "pub struct BoundedResponseContext",
        "pub struct DocumentSectionContext",
        "pub struct AgentPromptContext",
        "pub struct StreamingAgentPromptContext",
        "pub fn render_agent_prompt(",
        "pub fn render_streaming_agent_prompt(",
        "pub fn document_section_needs_response_toc(",
        "pub fn render_document_section(",
        "pub fn format_active_format_requirements(",
        "pub fn render_full_document_section(",
        "pub fn render_remote_host_scope(",
        "pub fn render_bounded_response_context(",
        "fn collect_active_format_requirements(",
        "fn render_prompt_targets(",
        "fn extract_session_summary(",
        "fn render_backlog_head(",
        "fn render_recent_exchange_turns(",
        "fn collect_recent_exchange_turn_sections(",
        "fn render_available_components(",
        "fn should_render_bounded_document_section(",
    ] {
        assert!(
            focused_source.contains(required_snippet),
            "agent-doc-prompt-context must own pure prompt-context rendering policy: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub struct LoadedContextLedger",
        "pub struct LoadedContextRecord",
        "pub fn loaded_context_record(",
        "pub fn build_loaded_context_ledger(",
    ] {
        assert!(
            loaded_context_source.contains(required_snippet),
            "agent-doc-prompt-context must own loaded-context ledger policy: {required_snippet}"
        );
    }

    let io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "fn render_prompt_targets(",
        "fn extract_session_summary(",
        "fn render_backlog_head(",
        "fn render_recent_exchange_turns(",
        "fn collect_recent_exchange_turn_sections(",
        "fn render_available_components(",
        "render_bounded_response_context(BoundedResponseContext",
        "element::parse(doc)",
        "fn render_remote_host_scope(",
        "Globally approved SSH commands",
        "pub use agent_doc_prompt_context",
    ] {
        assert!(
            !io_source.contains(forbidden_snippet),
            "agent-doc-prompt-context-io must not re-own or facade pure prompt-context rendering policy: {forbidden_snippet}"
        );
    }
    assert!(
        io_source.contains("agent_doc_prompt_context::{")
            && io_source.contains("render_document_section(DocumentSectionContext")
            && io_source.contains("document_section_needs_response_toc(")
            && io_source.contains("render_remote_host_scope(&declared_targets)")
            && io_source.contains("agent_doc_frontmatter_io::session::parse_for_file_with_context")
            && io_source.contains("agent_doc_response_toc_io::render_prompt_toc")
            && io_source.contains("prompt_targets_from_diff(diff_text)"),
        "agent-doc-prompt-context-io should gather project context then call focused rendering policy directly"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt_context.rs")
            .exists(),
        "orchestration must not keep a prompt_context facade module"
    );
    let run_source = fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    let stream_source =
        fs::read_to_string(manifest_dir.join("agent-doc-stream-io/src/lib.rs")).unwrap();
    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    for (relative, source) in [
        ("agent-doc-run-io/src/lib.rs", run_source.as_str()),
        ("agent-doc-stream-io/src/lib.rs", stream_source.as_str()),
        ("src/orchestrate.rs", orchestrate_source.as_str()),
    ] {
        assert!(
            source.contains("agent_doc_prompt_context_io::build_document_section_with_ssh_context")
                && source.contains(".ssh_context()"),
            "{relative} should adapt cached CycleContext SSH context into prompt-context IO directly"
        );
    }
    let combined_prompt_context_callers =
        format!("{run_source}\n{stream_source}\n{orchestrate_source}");
    assert!(
        !combined_prompt_context_callers.contains("prompt_context::build_document_section"),
        "prompt-context call sites must not route document-section rendering through an orchestration facade"
    );
    for forbidden_snippet in [
        "agent_doc_prompt_context::{",
        "render_document_section(DocumentSectionContext",
        "document_section_needs_response_toc(",
        "render_remote_host_scope(&declared_targets)",
        "agent_doc_response_toc_io::render_prompt_toc",
        "prompt_targets_from_diff(diff_text)",
    ] {
        assert!(
            !combined_prompt_context_callers.contains(forbidden_snippet),
            "prompt-context call sites must not re-own prompt-context assembly after IO extraction: {forbidden_snippet}"
        );
    }

    let io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context-io/Cargo.toml")).unwrap();
    let io_manifest: toml::Value = toml::from_str(&io_manifest).unwrap();
    let io_dependencies = io_manifest["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-frontmatter",
        "agent-doc-frontmatter-io",
        "agent-doc-prompt-context",
        "agent-doc-response-toc-io",
        "agent-doc-session-accretion",
        "agent-doc-workflow",
    ] {
        assert!(
            io_dependencies.contains_key(required),
            "agent-doc-prompt-context-io should depend on focused prompt assembly dependency: {required}"
        );
    }
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-git-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
        "interprocess",
    ] {
        assert!(
            !io_dependencies.contains_key(forbidden),
            "agent-doc-prompt-context-io must stay free of orchestration/app transport state: {forbidden}"
        );
    }

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-prompt-context-io"),
        "root crate should depend on focused prompt-context IO directly"
    );
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    assert!(
        orchestration["dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-prompt-context-io"),
        "agent-doc-orchestration should depend on focused prompt-context IO directly"
    );

    let plan_source = fs::read_to_string(manifest_dir.join("src/plan.rs")).unwrap();
    let jobs_source = fs::read_to_string(manifest_dir.join("src/jobs.rs")).unwrap();
    for forbidden_snippet in [
        "pub struct LoadedContextLedger",
        "pub struct LoadedContextRecord",
        "fn loaded_context_record(",
        "fn build_loaded_context_ledger(",
    ] {
        assert!(
            !plan_source.contains(forbidden_snippet),
            "src/plan.rs must not re-own or facade loaded-context ledger policy: {forbidden_snippet}"
        );
    }
    assert!(
        plan_source.contains("agent_doc_prompt_context::loaded_context::{")
            && jobs_source.contains("agent_doc_prompt_context::loaded_context::{")
            && jobs_source.contains("build_loaded_context_ledger")
            && jobs_source.contains("loaded_context_record"),
        "plan/jobs should call loaded-context ledger policy through agent-doc-prompt-context directly"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt_contract.rs")
            .exists(),
        "orchestration must not keep prompt_contract as a facade for prompt-context rendering policy"
    );

    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    assert!(
        orchestrate_source.contains("agent_doc_prompt_context::render_agent_prompt")
            && orchestrate_source.contains("AgentPromptContext")
            && !orchestrate_source.contains("format_prompt_bearing_changes")
            && !orchestrate_source.contains("format_active_format_requirements"),
        "src/orchestrate.rs should gather prompt inputs and delegate pure prompt rendering to agent-doc-prompt-context"
    );

    for (path, required_snippet, forbidden_snippets) in [
        (
            "agent-doc-run-io/src/lib.rs",
            "agent_doc_prompt_context::format_active_format_requirements",
            [
                "agent_doc_orchestration::prompt_contract::format_active_format_requirements",
                "prompt_contract::format_active_format_requirements",
                "crate::prompt_contract::format_active_format_requirements",
            ],
        ),
        (
            "agent-doc-stream-io/src/lib.rs",
            "agent_doc_prompt_context::render_streaming_agent_prompt",
            [
                "agent_doc_orchestration::prompt_contract::format_active_format_requirements",
                "prompt_contract::format_active_format_requirements",
                "crate::prompt_contract::format_active_format_requirements",
            ],
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(path)).unwrap();
        assert!(
            source.contains(required_snippet),
            "{path} should call focused format requirement rendering policy directly"
        );
        for forbidden_snippet in forbidden_snippets {
            assert!(
                !source.contains(forbidden_snippet),
                "{path} must not call orchestration prompt_contract for focused format requirement rendering policy"
            );
        }
    }

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-prompt-context"),
        "orchestration must depend on the focused prompt-context crate directly"
    );

    let focused_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&focused_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-diff",
        "agent-doc-element",
        "agent-doc-element-backlog",
        "agent-doc-hash",
        "agent-doc-session-accretion",
        "serde",
    ] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-prompt-context should depend on {required} for pure rendering inputs"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-frontmatter",
        "agent-doc-fs",
        "agent-doc-workflow",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-prompt-context must stay free of orchestration and project/effect dependencies"
        );
    }
}

#[test]
fn test_agent_doc_topic_owns_compact_summary_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let topic_source = fs::read_to_string(manifest_dir.join("agent-doc-topic/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn parse_topic_sections_with_tail(",
        "pub fn summarize_compacted_exchange(",
        "fn summarize_response_topic(",
        "fn summarize_prior_preamble_context(",
        "fn summarize_prior_compact_summary(",
        "fn collapse_whitespace(",
        "fn truncate_with_ellipsis(",
    ] {
        assert!(
            topic_source.contains(required_snippet),
            "agent-doc-topic must own compact exchange summary text policy: {required_snippet}"
        );
    }

    let compact_archive =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/compact_archive.rs")).unwrap();
    let compact_source =
        fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "fn summarize_compacted_exchange(",
        "fn summarize_response_topic(",
        "fn summarize_prior_preamble_context(",
        "fn summarize_prior_compact_summary(",
        "fn collapse_whitespace(",
        "fn truncate_with_ellipsis(",
    ] {
        assert!(
            !compact_source.contains(forbidden_snippet),
            "compact.rs must stay an archive/write adapter, not re-own topic summary policy: {forbidden_snippet}"
        );
    }
    assert!(
        compact_archive.contains("use agent_doc_topic::summarize_compacted_exchange;")
            && compact_archive.contains("summarize_compacted_exchange(exchange.content(content))"),
        "agent-doc-document compact archive rendering should call focused topic compact-summary policy directly"
    );
    assert!(
        compact_source.contains("agent_doc_document::compact_archive::{")
            && compact_source.contains("build_exchange_compact_summary(")
            && !compact_source.contains("summarize_compacted_exchange"),
        "compact.rs should call document archive rendering instead of reaching into topic policy"
    );
}

#[test]
fn test_cli_read_command_routes_active_document_through_realtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let read_source = fs::read_to_string(manifest_dir.join("src/read.rs")).unwrap();
    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();

    assert!(
        root_dependencies.contains_key("agent-doc-document-realtime-io"),
        "root CLI crate should depend on realtime document authority"
    );
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"read_command_document\"",
        "agent_doc_element::element::parse(&content)",
    ] {
        assert!(
            read_source.contains(required),
            "agent-doc read should resolve active document content through realtime authority before printing/parsing: {required}"
        );
    }
    assert!(
        !read_source.contains("std::fs::read_to_string(file)")
            && !read_source.contains("fs::read_to_string(file)"),
        "agent-doc read must not read the active document directly from disk"
    );
}

#[test]
fn test_cli_outline_command_routes_active_document_through_realtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let outline_source = fs::read_to_string(manifest_dir.join("src/outline_cmd.rs")).unwrap();
    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();

    assert!(
        root_dependencies.contains_key("agent-doc-document-realtime-io"),
        "root CLI crate should depend on realtime document authority"
    );
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"outline_command_document\"",
        "agent_doc_document::outline_projection::project_markdown_outline(body)",
    ] {
        assert!(
            outline_source.contains(required),
            "agent-doc outline should resolve active document content through realtime authority before projecting the outline: {required}"
        );
    }
    assert!(
        !outline_source.contains("std::fs::read_to_string(file)")
            && !outline_source.contains("fs::read_to_string(file)"),
        "agent-doc outline must not read the active document directly from disk"
    );
}

#[test]
fn test_read_only_root_command_adapters_route_active_document_through_realtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();

    assert!(
        root_dependencies.contains_key("agent-doc-document-realtime-io"),
        "root CLI crate should depend on realtime document authority"
    );

    for (source_file, label) in [
        ("src/auto_dag.rs", "auto_dag_command_document"),
        ("src/cleanup_cmd.rs", "cleanup_fallback_document"),
        ("src/layout.rs", "layout_command_document"),
        ("src/parallel.rs", "parallel_command_document"),
        ("src/plan.rs", "plan_command_document"),
    ] {
        let source = fs::read_to_string(manifest_dir.join(source_file)).unwrap();
        for required in [
            "agent_doc_document_realtime_io::try_resolve_current_document_content(",
            label,
        ] {
            assert!(
                source.contains(required),
                "{source_file} should resolve active document content through realtime authority: {required}"
            );
        }
        assert!(
            !source.contains("std::fs::read_to_string(file)")
                && !source.contains("fs::read_to_string(file)"),
            "{source_file} must not read the active document directly from disk"
        );
    }
}

#[test]
fn test_root_mutation_command_adapters_route_active_document_through_realtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();

    assert!(
        root_dependencies.contains_key("agent-doc-document-realtime-io"),
        "root CLI crate should depend on realtime document authority"
    );

    for (source_file, label) in [
        ("src/convert.rs", "convert_command_document"),
        ("src/exchange.rs", "exchange_command_document"),
        ("src/migrate.rs", "migrate_command_document"),
        ("src/mode.rs", "mode_command_document"),
        ("src/patch.rs", "patch_command_document"),
    ] {
        let source = fs::read_to_string(manifest_dir.join(source_file)).unwrap();
        for required in [
            "agent_doc_document_realtime_io::try_resolve_current_document_content(",
            label,
            "agent_doc_document_realtime_io::atomic_write_through_authority(",
        ] {
            assert!(
                source.contains(required),
                "{source_file} should route active document mutation through realtime authority: {required}"
            );
        }
        for forbidden in [
            "std::fs::read_to_string(file)",
            "fs::read_to_string(file)",
            "std::fs::write(file",
            "fs::write(file",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_file} must not directly read/write active document content: {forbidden}"
            );
        }
    }
}

#[test]
fn test_queue_notify_history_commands_route_active_document_through_realtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();

    assert!(
        root_dependencies.contains_key("agent-doc-document-realtime-io"),
        "root CLI crate should depend on realtime document authority"
    );

    let queue_dispatch = fs::read_to_string(manifest_dir.join("src/queue_dispatch.rs")).unwrap();
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"queue_dispatch_command_document\"",
    ] {
        assert!(
            queue_dispatch.contains(required),
            "queue_dispatch should resolve active document content through realtime authority: {required}"
        );
    }
    assert!(
        !queue_dispatch.contains("std::fs::read_to_string(file)")
            && !queue_dispatch.contains("fs::read_to_string(file)"),
        "queue_dispatch must not read active document context directly from disk"
    );

    for (source_file, label) in [
        ("src/history.rs", "history_restore_command_document"),
        ("src/notify.rs", "notify_command_document"),
    ] {
        let source = fs::read_to_string(manifest_dir.join(source_file)).unwrap();
        for required in [
            "agent_doc_document_realtime_io::try_resolve_current_document_content(",
            label,
            "agent_doc_document_realtime_io::atomic_write_through_authority(",
        ] {
            assert!(
                source.contains(required),
                "{source_file} should route active document mutation through realtime authority: {required}"
            );
        }
        for forbidden in [
            "std::fs::read_to_string(file)",
            "fs::read_to_string(file)",
            "std::fs::write(file",
            "fs::write(file",
            "NamedTempFile::new_in(parent)",
        ] {
            assert!(
                !source.contains(forbidden),
                "{source_file} must not directly read/write active document content: {forbidden}"
            );
        }
    }
}

#[test]
fn test_reset_and_session_actor_route_active_document_reads_through_named_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();

    assert!(
        root_dependencies.contains_key("agent-doc-document-realtime-io"),
        "root CLI crate should depend on realtime document authority"
    );

    let reset_source = fs::read_to_string(manifest_dir.join("src/reset.rs")).unwrap();
    for required in [
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"reset_command_document\"",
    ] {
        assert!(
            reset_source.contains(required),
            "reset should split force-disk reads from active current-document reads through named authority helpers: {required}"
        );
    }
    assert!(
        !reset_source.contains("std::fs::read_to_string(file)")
            && !reset_source.contains("fs::read_to_string(file)"),
        "reset must not read active document content directly from disk"
    );

    let session_actor = fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"session_actor_dirty_check_document\"",
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)?",
        "agent_doc_cycle_state_io::load_with_closeout_projection(doc_path)",
    ] {
        assert!(
            session_actor.contains(required),
            "session actor dirty-check should compare committed-cycle state against realtime document authority: {required}"
        );
    }
    assert!(
        !session_actor.contains("agent_doc_cycle_state_io::load(doc_path)"),
        "session actor debug cycle phase should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        !session_actor.contains("std::fs::read_to_string(file)")
            && !session_actor.contains("fs::read_to_string(file)"),
        "session_actor_cmd must not read the active document directly from disk"
    );
}

#[test]
fn test_agent_doc_response_toc_owns_live_toc_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-response-toc")),
        "agent-doc-response-toc must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-response-toc-io")),
        "agent-doc-response-toc-io must stay a first-class workspace crate for file/archive adapters"
    );

    let focused_source =
        fs::read_to_string(manifest_dir.join("agent-doc-response-toc/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub struct LiveTocEntry",
        "pub struct LiveSection",
        "pub struct PromptFilters",
        "pub fn live_toc_entries(",
        "pub fn live_sections(",
        "pub fn collect_live_sections(",
        "pub fn live_section_window(",
        "pub fn extract_backlog_ids(",
        "pub fn preview_text(",
        "pub fn normalize_text(",
        "pub fn normalize_backlog_id(",
    ] {
        assert!(
            focused_source.contains(required_snippet),
            "agent-doc-response-toc must own live response TOC policy: {required_snippet}"
        );
    }

    let io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-response-toc-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn run_toc(",
        "pub fn run_fetch(",
        "pub fn render_prompt_toc(",
        "fn build_toc_entries(",
        "fn archive_entries(",
        "fn fetch_sections(",
        "agent_doc_response_toc::live_toc_entries",
        "agent_doc_sqlite::archive_index",
        "fn current_document_content(file: &Path, source: &str) -> Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "current_document_content(file, \"response_toc_live_entries\")",
        "current_document_content(file, \"response_fetch_live_sections\")",
    ] {
        assert!(
            io_source.contains(required_snippet),
            "agent-doc-response-toc-io must own response TOC file/archive adapter policy: {required_snippet}"
        );
    }
    assert!(
        !io_source.contains("std::fs::read_to_string(file)")
            && !io_source.contains("fs::read_to_string(file)"),
        "agent-doc-response-toc-io must not read the active document directly from disk"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/response_toc.rs")
            .exists(),
        "orchestration must not keep response_toc as an adapter module or facade"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod response_toc"),
        "orchestration must not expose response_toc as a module facade"
    );

    let prompt_context =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context-io/src/lib.rs")).unwrap();
    assert!(
        prompt_context.contains("agent_doc_response_toc_io::render_prompt_toc")
            && !prompt_context.contains("crate::response_toc::render_prompt_toc"),
        "prompt-context IO should call response TOC IO directly"
    );

    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        main_source.contains("agent_doc_response_toc_io::run_toc")
            && main_source.contains("agent_doc_response_toc_io::run_fetch")
            && !main_source.contains("agent_doc_orchestration::response_toc"),
        "CLI response TOC commands should call response TOC IO directly"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-response-toc-io"),
        "orchestration must depend on the focused response-TOC IO crate directly"
    );
    assert!(
        !orchestration_dependencies.contains_key("agent-doc-response-toc"),
        "orchestration should depend on response TOC through the IO adapter, not the pure live-TOC crate"
    );

    let focused_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-response-toc/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&focused_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(dependencies.contains_key("agent-doc-element"));
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-sqlite",
        "agent-doc-fs",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-response-toc must stay free of orchestration and archive/effect dependencies"
        );
    }

    let io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-response-toc-io/Cargo.toml")).unwrap();
    let io_parsed: toml::Value = toml::from_str(&io_manifest).unwrap();
    let io_dependencies = io_parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-document-realtime-io",
        "agent-doc-response-toc",
        "agent-doc-sqlite",
        "serde_json",
    ] {
        assert!(
            io_dependencies.contains_key(required),
            "agent-doc-response-toc-io should depend on {required} for response TOC adapters"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "tmux-router",
    ] {
        assert!(
            !io_dependencies.contains_key(forbidden),
            "agent-doc-response-toc-io must stay free of core, orchestration, git, editor IPC, notify, and tmux-router dependencies"
        );
    }
}

#[test]
fn test_agent_doc_prompt_contract_owns_prompt_contract_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-prompt-contract")),
        "agent-doc-prompt-contract must stay a first-class workspace crate"
    );

    let focused_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-contract/src/lib.rs")).unwrap();
    let focused_harness_prompt_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-contract/src/harness_prompt.rs"))
            .unwrap();
    let harness_source =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/src/lib.rs")).unwrap();
    let harness_prompt_source =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/src/prompt_source.rs")).unwrap();
    for required_snippet in [
        "pub fn prompt_requests_plan_work(",
        "pub fn prompt_requests_backlog_work(",
        "pub fn requested_prompt_presets(",
        "pub struct PromptPresetRequestResolution",
        "pub fn resolve_prompt_preset_requests(",
        "pub fn explicit_backlog_targets(",
        "pub fn required_explicit_backlog_item_count(",
        "pub fn required_plan_reference_count(",
        "pub fn ordered_issue_units_for_agent_doc_bug(",
        "pub fn collect_added_diff_lines(",
        "pub fn push_unique_strings(",
        "pub fn push_unique_prompt_bearing_changes(",
        "fn effective_prompt_texts(",
        "fn referenced_presets_in_text(",
        "fn issue_units_in_text(",
        "agent_doc_fs::referenced_markdown_path_checked",
        "pub mod harness_prompt;",
    ] {
        assert!(
            focused_source.contains(required_snippet),
            "agent-doc-prompt-contract must own prompt contract policy directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub enum HarnessInvocationKind",
        "pub struct ParsedHarnessInvocation",
        "pub fn prompt_body_from_text(",
        "pub fn synthetic_diff_from_body(",
        "pub fn agent_doc_invocation_file_from_text(",
        "pub fn parse_agent_doc_invocation(",
    ] {
        assert!(
            focused_harness_prompt_source.contains(required_snippet),
            "agent-doc-prompt-contract must own harness prompt parsing policy directly: {required_snippet}"
        );
    }
    assert!(
        harness_source.contains("pub mod prompt_source;"),
        "agent-doc-harness must expose the effectful prompt source adapter"
    );
    for required_snippet in [
        "pub fn synthetic_diff_for_file(",
        "pub fn prompt_body_for_file(",
        "load_prompt_for_current_session: impl FnOnce(&Path) -> Result<Option<String>>",
        "load_prompt_for_current_session(&canonical)?",
        "agent_doc_prompt_contract::harness_prompt::prompt_body_from_text",
        "agent_doc_prompt_contract::harness_prompt::synthetic_diff_from_body",
    ] {
        assert!(
            harness_prompt_source.contains(required_snippet),
            "agent-doc-harness must own the effectful harness prompt source adapter: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "crate::codex_hook",
        "agent_doc_orchestration",
        "fn prompt_body_from_text(",
        "fn synthetic_diff_from_body(",
        "fn parse_agent_doc_invocation(",
    ] {
        assert!(
            !harness_prompt_source.contains(forbidden_snippet),
            "agent-doc-harness prompt source must inject effects and delegate pure parsing policy: {forbidden_snippet}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt_contract.rs")
            .exists(),
        "orchestration must not keep a prompt_contract module or facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/harness_prompt.rs")
            .exists(),
        "orchestration must not keep a harness_prompt module or facade"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod prompt_contract"),
        "orchestration must not expose prompt_contract as a module facade"
    );
    assert!(
        !orchestration_lib.contains("pub mod harness_prompt"),
        "orchestration must not expose harness_prompt as a module facade"
    );
    let preflight_mod =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) fn push_unique_strings(",
        "pub(crate) fn push_unique_prompt_bearing_changes(",
    ] {
        assert!(
            !preflight_mod.contains(forbidden_snippet)
                && !preflight_run.contains(forbidden_snippet),
            "orchestration preflight must not re-own prompt accumulator policy: {forbidden_snippet}"
        );
    }

    for (path, required_snippets, forbidden_snippets) in [
        (
            "src/plan.rs",
            vec![
                "agent_doc_prompt_contract::collect_added_diff_lines",
                "agent_doc_prompt_contract::prompt_requests_backlog_work",
                "agent_doc_prompt_contract::ordered_issue_units_for_agent_doc_bug",
                "agent_doc_prompt_contract::explicit_backlog_targets",
            ],
            vec![
                "agent_doc_orchestration::prompt_contract",
                "crate::prompt_contract",
            ],
        ),
        (
            "agent-doc-preflight-command-io/src/lib.rs",
            vec![
                "agent_doc_workflow::preflight_policy::post_exchange_comment_prompt_preset_warning",
            ],
            vec!["crate::prompt_contract"],
        ),
        (
            "agent-doc-workflow/src/preflight_policy.rs",
            vec![
                "agent_doc_prompt_contract::requested_prompt_presets",
                "agent_doc_prompt_contract::push_unique_strings",
            ],
            vec!["crate::prompt_contract"],
        ),
        (
            "agent-doc-preflight-command-io/src/run.rs",
            vec![
                "agent_doc_prompt_contract::collect_added_diff_lines",
                "use agent_doc_prompt_contract::{push_unique_prompt_bearing_changes, push_unique_strings};",
                "agent_doc_prompt_contract::resolve_prompt_preset_requests",
                "agent_doc_prompt_contract::prompt_requests_backlog_work",
                "agent_doc_prompt_contract::explicit_backlog_targets",
                "agent_doc_prompt_contract::required_explicit_backlog_item_count",
                "agent_doc_prompt_contract::required_plan_reference_count",
            ],
            vec![
                "crate::prompt_contract",
                "diff::detect_prompt_preset_requests",
                "frontmatter::resolve_prompt_preset_key(&frontmatter_prompt_presets",
                "let missing_prompt_presets =",
                "prompt_presets_requested = prompt_presets_requested",
            ],
        ),
        (
            "agent-doc-codex-hook-io/src/lib.rs",
            vec!["agent_doc_prompt_contract::harness_prompt::agent_doc_invocation_file_from_text"],
            vec![
                "fn parse_agent_doc_invocation_line(",
                "fn agent_doc_invocation_file_from_text(",
                "pub fn agent_doc_invocation_file_from_text(",
            ],
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(path)).unwrap();
        for required_snippet in required_snippets {
            assert!(
                source.contains(required_snippet),
                "{path} should call prompt contract policy through agent-doc-prompt-contract directly: {required_snippet}"
            );
        }
        for forbidden_snippet in forbidden_snippets {
            assert!(
                !source.contains(forbidden_snippet),
                "{path} must not route prompt contract policy through orchestration"
            );
        }
    }

    for (path, required_snippet) in [
        (
            "src/plan.rs",
            "agent_doc_harness::prompt_source::synthetic_diff_for_file(",
        ),
        (
            "agent-doc-preflight-command-io/src/run.rs",
            "agent_doc_harness::prompt_source::synthetic_diff_for_file(",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(path)).unwrap();
        assert!(
            source.contains(required_snippet),
            "{path} should call the harness-owned prompt source adapter directly"
        );
        for forbidden_snippet in [
            "agent_doc_orchestration::harness_prompt",
            "crate::harness_prompt",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{path} must not call the retired orchestration harness_prompt facade"
            );
        }
    }

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-prompt-contract"),
        "orchestration must depend on the focused prompt-contract crate directly"
    );

    let harness_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/Cargo.toml")).unwrap();
    let harness: toml::Value = toml::from_str(&harness_manifest).unwrap();
    let harness_dependencies = harness["dependencies"].as_table().unwrap();
    assert!(
        harness_dependencies.contains_key("agent-doc-prompt-contract"),
        "agent-doc-harness must depend on the prompt-contract crate for pure harness prompt parsing"
    );
    assert!(
        !harness_dependencies.contains_key("agent-doc-orchestration"),
        "agent-doc-harness prompt source must not depend on orchestration for Codex hook loading"
    );

    let root_manifest = toml::from_str::<toml::Value>(&workspace_manifest).unwrap();
    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-prompt-contract"),
        "the CLI crate must depend on the focused prompt-contract crate directly"
    );

    let focused_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-contract/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&focused_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in ["agent-doc-diff", "agent-doc-frontmatter", "agent-doc-fs"] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-prompt-contract should depend on {required} for prompt contract inputs"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-prompt-contract must stay free of core, orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_fs_owns_markdown_reference_resolution() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let fs_source = fs::read_to_string(manifest_dir.join("agent-doc-fs/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn referenced_markdown_path(",
        "pub fn referenced_markdown_path_checked(",
        "fn strip_redundant_project_prefix(",
        "fn project_roots_for(",
        "ambiguous markdown reference",
        "project-prefixed markdown reference",
    ] {
        assert!(
            fs_source.contains(required_snippet),
            "agent-doc-fs must own markdown reference resolution policy: {required_snippet}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/security.rs")
            .exists(),
        "orchestration must not keep security.rs as a markdown reference adapter or facade"
    );

    for (path, required_snippet, forbidden_snippet) in [
        (
            "src/plan.rs",
            "agent_doc_fs::referenced_markdown_path",
            "security::referenced_markdown_path",
        ),
        (
            "agent-doc-project-config-io/src/lib.rs",
            "agent_doc_fs::referenced_markdown_path_checked",
            "crate::security::referenced_markdown_path_checked",
        ),
        (
            "agent-doc-session-check-io/src/pending_capture.rs",
            "agent_doc_fs::referenced_markdown_path",
            "crate::security::referenced_markdown_path",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(path)).unwrap();
        assert!(
            source.contains(required_snippet),
            "{path} should call markdown reference resolution through agent-doc-fs directly"
        );
        assert!(
            !source.contains(forbidden_snippet),
            "{path} must not route markdown reference resolution through orchestration security"
        );
    }
}

#[test]
fn test_agent_doc_fs_owns_start_path_rewrite_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let fs_source = fs::read_to_string(manifest_dir.join("agent-doc-fs/src/lib.rs")).unwrap();
    assert!(
        fs_source.contains("pub fn rewrite_start_path("),
        "agent-doc-fs must own route start path rewriting"
    );
    assert!(
        fs_source.contains("strip_prefix(&abs_cwd)"),
        "agent-doc-fs must keep the cwd-relative strip policy"
    );

    let startup_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup.rs")).unwrap();
    assert!(
        startup_source.contains("agent_doc_fs::rewrite_start_path("),
        "route startup IO should call agent-doc-fs directly for start path rewriting"
    );
    assert!(
        !startup_source.contains("pub fn rewrite_start_path(")
            && !startup_source.contains("fn rewrite_start_path("),
        "route startup IO must not re-own the start path rewrite helper"
    );
}

#[test]
fn test_agent_doc_lease_is_freshness_boundary() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-lease")),
        "agent-doc-lease must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-lease-io")),
        "agent-doc-lease-io must stay a first-class workspace crate"
    );

    let package_version = workspace["package"]["version"].as_str();
    for relative_manifest in [
        "agent-doc-queue-io/Cargo.toml",
        "agent-doc-supervisor/Cargo.toml",
    ] {
        let manifest = fs::read_to_string(manifest_dir.join(relative_manifest)).unwrap();
        let parsed: toml::Value = toml::from_str(&manifest).unwrap();
        let dependencies = parsed["dependencies"].as_table().unwrap();
        let dependency = dependencies["agent-doc-lease"].as_table().unwrap();
        assert_eq!(
            dependency.get("version").and_then(toml::Value::as_str),
            package_version,
            "{relative_manifest} should depend on the versioned lease crate"
        );
    }
    let relative_manifest = "agent-doc-hooks-io/Cargo.toml";
    let manifest = fs::read_to_string(manifest_dir.join(relative_manifest)).unwrap();
    let parsed: toml::Value = toml::from_str(&manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    let dependency = dependencies["agent-doc-lease-io"].as_table().unwrap();
    assert_eq!(
        dependency.get("version").and_then(toml::Value::as_str),
        package_version,
        "{relative_manifest} should depend on the versioned lease IO crate"
    );

    let lease_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-lease/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&lease_manifest).unwrap();
    let dependencies = parsed.get("dependencies").and_then(toml::Value::as_table);
    assert!(
        dependencies.is_none_or(|dependencies| dependencies.is_empty()),
        "agent-doc-lease must stay pure and dependency-free"
    );

    for (relative, forbidden) in [
        (
            "agent-doc-queue-io/src/drain_owner.rs",
            "pub fn drain_owner_lease_is_fresh(",
        ),
        (
            "agent-doc-queue-io/src/queue_edit_owner.rs",
            "pub fn queue_edit_owner_lease_is_fresh(",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains(forbidden) && !source.contains("saturating_sub("),
            "{relative} must not re-own TTL freshness policy: {forbidden}"
        );
        assert!(
            source.contains("agent_doc_lease::timestamp_is_fresh"),
            "{relative} should call the focused lease crate directly"
        );
    }
    let lease_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-lease-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&lease_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in ["agent-doc-fs", "agent-doc-lease"] {
        let dependency = dependencies[required].as_table().unwrap();
        assert_eq!(
            dependency.get("version").and_then(toml::Value::as_str),
            package_version,
            "agent-doc-lease-io should depend on versioned focused crates: {required}"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-lease-io must stay free of orchestration/editor IPC/sqlite/tmux facades: {forbidden}"
        );
    }
    let lease_io =
        fs::read_to_string(manifest_dir.join("agent-doc-lease-io/src/local_model.rs")).unwrap();
    for required in [
        "pub enum ReapOutcome",
        "pub fn reap_local_model_leases(",
        "agent_doc_fs::find_project_root",
        "agent_doc_lease::DEFAULT_LOCAL_MODEL_LEASE_REGISTRY_RELATIVE",
        "agent_doc_lease::local_model_reap_command_args(None, None)",
        "std::process::Command::new(\"tsift\")",
    ] {
        assert!(
            lease_io.contains(required),
            "agent-doc-lease-io must own local-model lease reap IO: {required}"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "pub(crate) enum ReapOutcome",
        "pub(crate) fn reap_local_model_leases(",
        "agent_doc_lease::DEFAULT_LOCAL_MODEL_LEASE_REGISTRY_RELATIVE",
        "agent_doc_lease::local_model_reap_command_args",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration hook bridge must not re-own local-model lease reap IO: {forbidden}"
        );
    }
    assert!(
        fs::read_to_string(manifest_dir.join("agent-doc-hooks-io/src/lib.rs"))
            .unwrap()
            .contains("agent_doc_lease_io::local_model::reap_local_model_leases"),
        "hook IO should call focused lease IO for local-model reap"
    );
}

#[test]
fn test_plugin_owner_sidecar_crates_are_removed() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(!workspace.contains("\"agent-doc-plugin-owner\""));
    assert!(!workspace.contains("\"agent-doc-plugin-owner-io\""));
    assert!(!manifest_dir.join("agent-doc-plugin-owner").exists());
    assert!(!manifest_dir.join("agent-doc-plugin-owner-io").exists());

    let reliable_sync =
        fs::read_to_string(manifest_dir.join("agent-doc-reliable-sync-io/src/liveness.rs"))
            .unwrap();
    assert!(reliable_sync.contains("pub struct EditorRegistration"));
    assert!(reliable_sync.contains("pub fn live_registrations("));
    assert!(!reliable_sync.contains(".agent-doc/plugin-owner"));
}
#[test]
fn test_agent_doc_memory_owns_semantic_memory_ranking_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-memory")),
        "agent-doc-memory must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-memory-io")),
        "agent-doc-memory-io must stay a first-class workspace crate"
    );
    let package_version = workspace["package"]["version"].as_str();
    let dependencies = workspace["dependencies"].as_table().unwrap();
    let dependency = dependencies["agent-doc-memory-io"].as_table().unwrap();
    assert_eq!(
        dependency.get("version").and_then(toml::Value::as_str),
        package_version,
        "root adapter should depend on the versioned memory IO crate"
    );
    let memory_source =
        fs::read_to_string(manifest_dir.join("agent-doc-memory/src/lib.rs")).unwrap();
    for required in [
        "pub struct MemorySearchResult",
        "pub struct CompletionCandidate",
        "pub struct SemanticCompletionMatch",
        "pub enum QueueStrikeMatchKind",
        "pub struct QueueStrikeMatch",
        "pub const QUEUE_STRIKE_THRESHOLD",
        "pub fn queue_prompt_target_id(",
        "pub fn format_semantic_completion_warning(",
        "pub fn semantic_completion_matches(",
        "pub fn semantic_queue_strike_matches(",
        "pub fn is_done_tracked_work_event(",
        "pub fn is_active_backlog_work_event(",
        "pub fn count_insert_results(",
        "pub fn rank_events(",
        "pub fn dedupe_events(",
        "pub fn trim_chars(",
        "pub fn tracked_work_events(",
        "pub fn tracked_work_event(",
        "pub fn response_summary_events(",
        "pub fn response_sections(",
        "pub fn parse_done_archive_items(",
        "pub fn parse_done_archive_line(",
        "pub fn looks_like_iso_date_prefix(",
        "pub fn pending_state_str(",
    ] {
        assert!(
            memory_source.contains(required),
            "agent-doc-memory must own semantic memory ranking/result/event-shaping policy: {required}"
        );
    }

    let memory_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-memory-io/src/lib.rs")).unwrap();
    let memory_io_session =
        fs::read_to_string(manifest_dir.join("agent-doc-memory-io/src/session.rs")).unwrap();
    assert!(
        memory_io_lib.contains("pub mod session;"),
        "agent-doc-memory-io should expose session memory indexing/search IO"
    );
    for forbidden in [
        "pub struct MemorySearchResult",
        "struct CompletionCandidate",
        "fn count_insert_results(",
        "fn rank_events(",
        "fn score_event(",
        "fn search_result(",
        "fn tokenize(",
        "fn push_token(",
        "fn dedupe_events(",
        "fn trim_chars(",
        "fn tracked_work_events(",
        "fn done_archive_events(",
        "fn parse_done_archive_items(",
        "fn parse_done_archive_line(",
        "fn looks_like_iso_date_prefix(",
        "fn tracked_work_event(",
        "fn response_summary_events(",
        "fn response_sections(",
        "fn pending_state_str(",
        "pub struct SemanticCompletionMatch",
        "pub enum QueueStrikeMatchKind",
        "pub struct QueueStrikeMatch",
        "pub const QUEUE_STRIKE_THRESHOLD",
        "fn queue_prompt_target_id(",
        "pub fn format_semantic_completion_warning(",
        "fn is_done_tracked_work_event(",
        "fn is_active_backlog_work_event(",
    ] {
        assert!(
            !memory_io_session.contains(forbidden),
            "agent-doc-memory-io session adapter must not re-own semantic memory policy: {forbidden}"
        );
    }
    assert!(
        memory_io_session.contains("use agent_doc_memory::{")
            && memory_io_session.contains("CompletionCandidate")
            && memory_io_session.contains("rank_events")
            && memory_io_session.contains("dedupe_events")
            && memory_io_session.contains("queue_prompt_target_id")
            && memory_io_session.contains("tracked_work_events")
            && memory_io_session.contains("parse_done_archive_items")
            && memory_io_session.contains("response_summary_events")
            && memory_io_session
                .contains("semantic_completion_matches as match_semantic_completions")
            && memory_io_session
                .contains("semantic_queue_strike_matches as match_semantic_queue_strikes")
            && memory_io_session.contains("SemanticCompletionMatch")
            && memory_io_session.contains("QueueStrikeMatch")
            && memory_io_session.contains("pub fn run_index(")
            && memory_io_session.contains("pub fn run_search(")
            && memory_io_session.contains("pub fn semantic_completion_matches(")
            && memory_io_session.contains("pub fn semantic_queue_strike_matches("),
        "agent-doc-memory-io session adapter should call focused semantic memory policy directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/memory_cmd.rs")
            .exists(),
        "orchestration must not keep a memory_cmd session-memory IO facade"
    );
    let preflight_warnings =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    assert!(
        preflight_warnings.contains("agent_doc_memory::format_semantic_completion_warning(")
            && preflight_maintenance.contains("agent_doc_memory::QUEUE_STRIKE_THRESHOLD")
            && preflight_maintenance.contains("agent_doc_memory::QueueStrikeMatchKind")
            && preflight_warnings
                .contains("agent_doc_memory_io::session::semantic_completion_matches(")
            && preflight_maintenance
                .contains("agent_doc_memory_io::session::semantic_queue_strike_matches("),
        "preflight should use focused memory IO plus semantic-memory result vocabulary directly"
    );
    let memory_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-memory-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&memory_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-document",
        "agent-doc-element",
        "agent-doc-element-backlog",
        "agent-doc-fs",
        "agent-doc-memory",
        "agent-doc-queue",
        "agent-doc-turn",
    ] {
        let dependency = dependencies[required].as_table().unwrap();
        assert_eq!(
            dependency.get("version").and_then(toml::Value::as_str),
            package_version,
            "agent-doc-memory-io should depend on versioned focused crates: {required}"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-memory-io must stay free of orchestration/editor IPC/sqlite/tmux facades: {forbidden}"
        );
    }
    let memory_io_closeout =
        fs::read_to_string(manifest_dir.join("agent-doc-memory-io/src/closeout.rs")).unwrap();
    for required in [
        "pub enum CloseoutCaptureOutcome",
        "pub fn capture_tsift_memory_closeout(",
        "agent_doc_fs::find_project_root",
        ".join(\".tsift/memory.db\")",
        "agent_doc_turn::response_text::{",
        "response_prompt_target_from_re_heading",
        "summarize_response_for_hook",
        "agent_doc_closeout_events(",
        "MemoryStore::open_or_create",
        "fn git_head(",
    ] {
        assert!(
            memory_io_closeout.contains(required),
            "agent-doc-memory-io must own tsift-memory closeout adapter: {required}"
        );
    }
    assert!(
        !memory_io_closeout.contains("Command::new(\"tsift\")"),
        "agent-doc post-commit closeout must use tsift-memory directly instead of spawning the heavy tsift CLI"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "capture-agent-doc-closeout",
        "fn git_head(",
        ".join(\".tsift/memory.db\")",
        "summarize_response_for_hook",
        "response_prompt_target_from_re_heading",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration hook bridge must not re-own tsift-memory closeout IO: {forbidden}"
        );
    }
    assert!(
        fs::read_to_string(manifest_dir.join("agent-doc-hooks-io/src/lib.rs"))
            .unwrap()
            .contains("agent_doc_memory_io::closeout::capture_tsift_memory_closeout"),
        "hook IO should call focused memory IO closeout adapter"
    );
}

#[test]
fn test_agent_doc_supervisor_recycle_uses_cp_graph_for_inflight() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-supervisor-io")),
        "agent-doc-supervisor-io must stay a first-class workspace crate"
    );

    let supervisor_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/lib.rs")).unwrap();
    assert!(supervisor_lib.contains("pub mod recycle_yield;"));
    assert!(supervisor_lib.contains("pub mod recycle_inflight;"));
    let supervisor_inflight =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/recycle_inflight.rs"))
            .unwrap();
    for required in [
        "Reason labels for the CP-backed supervisor recycle projection",
        "RECYCLE_INFLIGHT_AUTO_INSTALL",
        "RECYCLE_INFLIGHT_RESTART",
    ] {
        assert!(
            supervisor_inflight.contains(required),
            "agent-doc-supervisor recycle_inflight must stay a pure backbone reason-label module: {required}"
        );
    }
    for forbidden in [
        "RECYCLE_INFLIGHT_DIR",
        "RECYCLE_INFLIGHT_FILE",
        "RecycleInflightMarker",
        "recycle_inflight_marker(",
        "recycle_inflight_marker_is_fresh(",
        "agent_doc_lease::timestamp_is_fresh",
    ] {
        assert!(
            !supervisor_inflight.contains(forbidden),
            "recycle-in-flight file sidecar policy must not return to agent-doc-supervisor: {forbidden}"
        );
    }

    let supervisor_yield =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/recycle_yield.rs")).unwrap();
    for required in [
        "Reason labels for recycle-yield requests carried by the CP recycle graph",
        "pub const RECYCLE_YIELD_STALE_BINARY",
        "pub const RECYCLE_YIELD_STATE_FLUSH",
    ] {
        assert!(
            supervisor_yield.contains(required),
            "agent-doc-supervisor must own recycle-yield backbone reason labels: {required}"
        );
    }
    for forbidden in [
        "RECYCLE_YIELD_DIR",
        "DEFAULT_RECYCLE_YIELD_TTL_SECS",
        "RecycleYieldRequest",
        "recycle_yield_request(",
        "recycle_yield_request_is_fresh(",
        "agent_doc_lease::timestamp_is_fresh",
    ] {
        assert!(
            !supervisor_yield.contains(forbidden),
            "recycle-yield file sidecar policy must not return to agent-doc-supervisor: {forbidden}"
        );
    }

    for removed in [
        "agent-doc-orchestration/src/recycle_yield.rs",
        "agent-doc-orchestration/src/recycle_inflight.rs",
        "agent-doc-supervisor-io/src/recycle_yield.rs",
        "agent-doc-supervisor-io/src/recycle_inflight.rs",
    ] {
        assert!(
            !manifest_dir.join(removed).exists(),
            "orchestration must not own supervisor recycle storage IO: {removed}"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "pub mod recycle_yield;",
        "pub mod recycle_inflight;",
        "pub use agent_doc_supervisor_io::recycle_yield",
        "pub use agent_doc_supervisor_io::recycle_inflight",
        "pub use agent_doc_supervisor::recycle_yield",
        "pub use agent_doc_supervisor::recycle_inflight",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration must not expose a supervisor recycle facade: {forbidden}"
        );
    }

    let state_backbone =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/src/lib.rs")).unwrap();
    for required in [
        "SupervisorRecycleRequested",
        "SupervisorRecycleStarted",
        "SupervisorRecycleSettled",
        "pub struct SupervisorRecycleProjection",
        "pub enum SupervisorRecyclePhase",
        "pub struct SupervisorRecycleMachine",
        "pub fn project_supervisor_recycle(",
    ] {
        assert!(
            state_backbone.contains(required),
            "state backbone must own project supervisor recycle graph state: {required}"
        );
    }

    for (relative, forbidden) in [(
        "agent-doc-route-io/src/dispatch_only/proof.rs",
        vec![
            "const RECYCLE_SETTLE_WAIT",
            "const RECYCLE_SETTLE_POLL",
            "agent_doc_supervisor_io::recycle_inflight",
        ],
    )] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in forbidden {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own or poll supervisor recycle marker policy: {forbidden}"
            );
        }
    }

    let supervisor_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/lib.rs")).unwrap();
    assert!(!supervisor_io_lib.contains("pub mod recycle_yield;"));
    assert!(!supervisor_io_lib.contains("pub mod recycle_inflight;"));
    let recycle_request =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/recycle_request.rs"))
            .unwrap();
    assert!(
        recycle_request.contains("pub fn request_recycle_for_doc("),
        "supervisor IO should own Path-based recycle-request scheduling"
    );
    let project_controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        project_controller_rpc.contains("pub fn supervisor_recycle_started(")
            && project_controller_rpc.contains("pub fn supervisor_recycle_settled(")
            && project_controller_rpc.contains("pub fn supervisor_recycle_status(")
            && project_controller_rpc.contains("pub fn wait_for_supervisor_recycle_settle(")
            && project_controller_rpc
                .contains("pub fn supervisor_recycle_yield_requested_for_file(")
            && project_controller_rpc.contains("pub fn supervisor_recycle_yield_pending_for_file(")
            && project_controller_rpc.contains("pub fn clear_supervisor_recycle_yield_for_file(")
            && project_controller_rpc.contains("handle_supervisor_recycle_started")
            && project_controller_rpc.contains("handle_supervisor_recycle_settled")
            && project_controller_rpc
                .contains("agent_doc_supervisor_io::recycle_request::request_recycle_for_doc(")
            && !project_controller_rpc.contains("pub fn schedule_supervisor_recycle_for_doc("),
        "project_controller::rpc must own CP supervisor recycle graph helpers and still call focused recycle-request IO directly"
    );
    for (relative, required) in [
        (
            "agent-doc-start-runtime-io/src/idle_watch.rs",
            "agent_doc_controller_io::project_controller::supervisor_recycle_yield_requested_for_file",
        ),
        (
            "agent-doc-start-runtime-io/src/idle_watch.rs",
            "agent_doc_controller_io::project_controller::clear_supervisor_recycle_yield_for_file",
        ),
        (
            "agent-doc-start-runtime-io/src/idle_watch.rs",
            "agent_doc_controller_io::project_controller::supervisor_recycle_started_for_file",
        ),
        (
            "agent-doc-route-io/src/dispatch_only/proof.rs",
            "agent_doc_controller_io::project_controller::wait_for_supervisor_recycle_settle_for_file",
        ),
        (
            "agent-doc-route-io/src/direct_pane_dispatch.rs",
            "agent_doc_controller_io::project_controller::supervisor_recycle_pending_for_file",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(required),
            "{relative} should use CP supervisor recycle graph helpers directly: {required}"
        );
    }
}

#[test]
fn test_agent_doc_route_submit_uses_controller_projection_not_sidecar_markers() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let supervisor_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/lib.rs")).unwrap();
    let supervisor_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/lib.rs")).unwrap();
    assert!(
        !supervisor_lib.contains("pub mod route_submit_inflight;")
            && !supervisor_io_lib.contains("pub mod route_submit_inflight;"),
        "route-submit in-flight state must not be exported as a supervisor sidecar module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-supervisor/src/route_submit_inflight.rs")
            .exists()
            && !manifest_dir
                .join("agent-doc-supervisor-io/src/route_submit_inflight.rs")
                .exists(),
        "route-submit marker storage files should be retired"
    );

    let state_backbone =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/src/lib.rs")).unwrap();
    for required in [
        "pub const ROUTE_SUBMIT_IN_FLIGHT_TTL_SECS",
        "pub const ROUTE_SUBMIT_READY_PROBE_TTL_SECS",
        "pub const ROUTE_SUBMIT_BLOCKED_TTL_SECS",
        "pub const ROUTE_DISPATCH_SUBMIT_REASON",
        "pub const ROUTE_DISPATCH_ONLY_READY_PROBE_REASON",
        "RouteSubmitStarted",
        "RouteSubmitSettled",
        "RouteSubmitBlocked",
        "pub struct RouteSubmitProjection",
        "pub enum RouteSubmitPhase",
        "pub enum RouteSubmitEvent",
        "pub struct RouteSubmitMachine",
        "pub fn transition_route_submit(",
        "pub fn is_pending_at(",
    ] {
        assert!(
            state_backbone.contains(required),
            "agent-doc-state-backbone must own route-submit projection policy: {required}"
        );
    }

    let controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    for required in [
        "pub struct RouteSubmitProjectionGuard",
        "pub fn begin_route_submit(",
        "pub fn begin_route_submit_with_reason(",
        "pub fn mark_route_submit_blocked(",
        "pub fn route_submit_in_flight_for_file(",
        "command: \"route_submit_started\".to_string()",
        "command: \"route_submit_settled\".to_string()",
        "command: \"route_submit_blocked\".to_string()",
        "command: \"route_submit_status\".to_string()",
        "handle_route_submit_started(",
        "handle_route_submit_settled(",
        "handle_route_submit_blocked(",
        "handle_route_submit_status(",
    ] {
        assert!(
            controller_rpc.contains(required),
            "project controller must own route-submit projection helper: {required}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "pub mod route_in_flight;",
        "pub use agent_doc_supervisor_io::route_submit_inflight",
        "pub use agent_doc_supervisor::route_submit_inflight",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration must not expose a route-submit marker facade: {forbidden}"
        );
    }

    for forbidden in [
        "route_submit_inflight_marker",
        "route_submit_blocked_marker",
        "RouteSubmitMarkerJson",
        ".agent-doc/route-in-flight",
        ".agent-doc/route-submit-blocked",
    ] {
        assert!(
            !state_backbone.contains(forbidden)
                && !controller_rpc.contains(forbidden)
                && !supervisor_lib.contains(forbidden)
                && !supervisor_io_lib.contains(forbidden),
            "route-submit runtime authority must not use marker storage: {forbidden}"
        );
    }
    for (relative, required) in [
        (
            "agent-doc-route-io/src/dispatch.rs",
            "agent_doc_controller_io::project_controller::begin_route_submit",
        ),
        (
            "agent-doc-route-io/src/dispatch_only.rs",
            "agent_doc_controller_io::project_controller::begin_route_submit_with_reason",
        ),
        (
            "agent-doc-start-runtime-io/src/idle_watch.rs",
            "agent_doc_controller_io::project_controller::route_submit_in_flight_for_file",
        ),
        (
            "agent-doc-route-io/src/dispatch_only/proof.rs",
            "agent_doc_controller_io::project_controller::mark_route_submit_blocked",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(required),
            "{relative} should call controller route-submit projection helpers directly: {required}"
        );
    }
}

#[test]
fn test_agent_doc_supervisor_owns_route_runtime_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let supervisor_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/lib.rs")).unwrap();
    assert!(
        supervisor_lib.contains("pub mod route_runtime;"),
        "agent-doc-supervisor should expose route runtime policy through its owning module"
    );

    let route_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/route_runtime.rs")).unwrap();
    for required in [
        "pub enum RouteActorState",
        "pub enum SupervisorHealth",
        "pub struct SupervisorRuntime",
        "pub struct AuthoritativeRuntimeFacts",
        "pub fn effective_authoritative_actor_state",
        "pub fn authoritative_actor_dispatch_guard_reason",
        "pub fn authoritative_actor_dispatch_target_eligible",
        "pub struct DeferToBoundaryRestartRecoveryFacts",
        "pub fn defer_to_boundary_restart_recovery_hint",
    ] {
        assert!(
            route_runtime.contains(required),
            "agent-doc-supervisor must own route runtime policy: {required}"
        );
    }
    let agent_change =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/agent_change.rs")).unwrap();
    for required in [
        "pub enum AgentChangeRouteAction",
        "pub const fn agent_change_route_decision",
    ] {
        assert!(
            agent_change.contains(required),
            "agent-doc-supervisor must own harness handoff route policy: {required}"
        );
    }

    let route = fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_authoritative_actor =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_actor.rs"))
            .unwrap();
    for forbidden in [
        "pub enum RouteActorState",
        "enum SupervisorHealth",
        "struct SupervisorRuntime",
        "fn supervisor_health_label(",
        "fn runtime_actor_state_label(",
        "fn authoritative_actor_dispatch_target_eligible(",
        "fn defer_recovery_hint(",
    ] {
        assert!(
            !route.contains(forbidden) && !route_authoritative_actor.contains(forbidden),
            "route must adapt runtime IO, not re-own or facade supervisor route policy: {forbidden}"
        );
    }
    assert!(
        route.contains("supervisor_authoritative_actor_dispatch_target_eligible")
            && route_authoritative_actor.contains("use agent_doc_supervisor::route_runtime::{")
            && route_authoritative_actor.contains("effective_authoritative_actor_state")
            && route_authoritative_actor.contains("use agent_doc_supervisor::agent_change::{")
            && route_authoritative_actor.contains("AgentChangeRouteAction")
            && route.contains("supervisor_authoritative_actor_dispatch_target_eligible")
            && route_authoritative_actor.contains("agent_change_route_decision("),
        "route should call focused supervisor route runtime policy directly"
    );
}

#[test]
fn test_agent_doc_supervisor_owns_auto_trigger_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let supervisor_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/lib.rs")).unwrap();
    assert!(
        supervisor_lib.contains("pub mod auto_trigger;"),
        "agent-doc-supervisor should expose auto-trigger readiness policy through its owning module"
    );

    let supervisor_auto_trigger =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/auto_trigger.rs")).unwrap();
    for required in [
        "pub struct AutoTriggerMonitor",
        "pub enum AutoTriggerStopOutcome",
        "pub enum AutoTriggerCooldownAction",
        "pub enum AutoTriggerNoPromptAction",
        "pub fn auto_trigger_clear_cooldown_action(",
        "pub fn auto_trigger_no_prompt_action(",
    ] {
        assert!(
            supervisor_auto_trigger.contains(required),
            "agent-doc-supervisor must own auto-trigger readiness policy: {required}"
        );
    }

    let start =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    assert!(
        start.contains("use agent_doc_supervisor::auto_trigger::{")
            && start.contains("auto_trigger_clear_cooldown_action")
            && start.contains("auto_trigger_no_prompt_action"),
        "start.rs should call focused supervisor auto-trigger policy directly"
    );
    assert!(
        !start.contains("agent_doc_turn_executor::auto_trigger::{"),
        "start.rs must not route auto-trigger readiness policy through turn-executor"
    );
}

#[test]
fn test_agent_doc_queue_owns_idle_drain_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));

    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod idle_drain;"),
        "agent-doc-queue should expose idle-drain queue policy"
    );

    let idle_drain =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/idle_drain.rs")).unwrap();
    for required in [
        "pub fn idle_queue_head_slash_command(",
        "pub fn idle_queue_drain_payload(",
        "pub fn idle_queue_drain_payload_kind(",
    ] {
        assert!(
            idle_drain.contains(required),
            "agent-doc-queue must own idle-drain payload policy: {required}"
        );
    }

    let start =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    let idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    for forbidden in [
        "fn idle_queue_head_slash_command(",
        "fn idle_queue_drain_payload(",
        "fn idle_queue_drain_payload_kind(",
    ] {
        assert!(
            !start.contains(forbidden) && !idle_watch.contains(forbidden),
            "start adapters must not re-own idle-drain payload policy: {forbidden}"
        );
    }
    assert!(
        start.contains("use agent_doc_queue::idle_drain::{")
            && idle_watch.contains("owned_pane_queue_continuation_prompt(")
            && idle_watch.contains("idle_queue_drain_payload(&head, continuation_prompt)")
            && idle_watch.contains("idle_queue_drain_payload_kind(&head)")
            && idle_watch.contains("idle_queue_head_slash_command(&head)"),
        "start adapters should render state-derived continuation text and call focused queue idle-drain policy directly"
    );
}

#[test]
fn test_agent_doc_queue_owns_drain_owner_lease_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));

    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod drain_owner;"),
        "agent-doc-queue-io should expose state-ledger drain ownership"
    );

    let drain_owner_source =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/drain_owner.rs")).unwrap();
    let lease_policy = fs::read_to_string(manifest_dir.join("agent-doc-lease/src/lib.rs")).unwrap();
    for required in ["pub const DRAIN_OWNER_SCOPE", "pub fn drain_owner_ttl("] {
        assert!(
            lease_policy.contains(required),
            "drain-owner lease scope/TTL policy must live in the dependency-free lease crate so \
             both the claiming loop and the reading controller share one definition: {required}"
        );
    }
    let lease_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-lease/Cargo.toml")).unwrap();
    let lease_manifest: toml::Value = toml::from_str(&lease_manifest).unwrap();
    assert!(
        lease_manifest
            .get("dependencies")
            .and_then(toml::Value::as_table)
            .is_none_or(|dependencies| dependencies.is_empty()),
        "agent-doc-lease is shared lease policy and must stay dependency-free"
    );
    for required in [
        "pub const DRAIN_OWNER_CLAUDE_LOOP",
        "pub struct DrainOwnerLease",
        "pub use agent_doc_lease::drain_owner_ttl;",
        "pub fn refresh_drain_owner_lease(",
        "pub fn read_drain_owner_lease(",
        "pub fn fresh_drain_owner_lease(",
        "pub fn fresh_loop_drain_owner_lease(",
        "pub fn clear_drain_owner_lease(",
    ] {
        assert!(
            drain_owner_source.contains(required),
            "agent-doc-queue-io must own state-ledger drain-owner coordination: {required}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod drain_owner;"),
        "agent-doc-orchestration must not re-export drain-owner lease policy"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/drain_owner.rs")
            .exists(),
        "agent-doc-orchestration must not keep a drain_owner compatibility module"
    );

    for relative_path in [
        "src/main.rs",
        "src/sim_world.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-preflight-command-io/src/run.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_queue_io::drain_owner::"),
            "{relative_path} should call state-ledger drain ownership through agent-doc-queue-io"
        );
        assert!(
            !source.contains("agent_doc_orchestration::drain_owner")
                && !source.contains("crate::drain_owner"),
            "{relative_path} must not call drain-owner lease policy through orchestration"
        );
    }

    let queue_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&queue_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden_dependency in [
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden_dependency),
            "agent-doc-queue drain-owner lease policy must stay free of orchestration and route effects: {forbidden_dependency}"
        );
    }
}

#[test]
fn test_controller_orphan_drain_dispatch_is_serialized_scoped_and_durably_fenced() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    let start = controller
        .find("fn controller_orphan_drain_tick(")
        .expect("controller owns the orphan-drain effect");
    let end = controller[start..]
        .find("/// Env override (seconds)")
        .map(|offset| start + offset)
        .expect("orphan-drain effect ends before watchdog policy");
    let orphan_drain = &controller[start..end];
    assert!(
        controller.contains("static ORPHAN_DRAIN_ROUTE_WORKER:")
            && controller
                .contains("std::sync::mpsc::sync_channel::<ControllerEditorRouteInvocation>(1)",)
            && controller.contains("effects.run_editor_route(invocation)"),
        "orphan drain must use one bounded controller-owned worker thread"
    );
    assert!(
        orphan_drain.contains("enqueue_orphan_drain_route(invocation)")
            && orphan_drain.contains("pane: Some(record.pane_id.clone())")
            && orphan_drain.contains("prune_before_lookup: false")
            && orphan_drain.contains("background_existing_pane_only: true"),
        "orphan drain must enqueue existing-pane-only target-scoped work without a fleet prune"
    );
    assert!(
        orphan_drain.contains("load_effective_queue_control_from_db(")
            && orphan_drain.contains("queue_control.allows_unattended_drain()"),
        "a retained drainable head must not reactivate controller-paused queue work"
    );
    let orphan_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/orphan_drain.rs")).unwrap();
    assert!(
        orphan_policy.contains("pub enum OrphanDrainEvent")
            && orphan_drain.contains("OrphanDrainEvent::QueueControlReadFailed")
            && !controller.contains("\"controller_orphan_drain_queue_control_read_failed"),
        "orphan-drain ops events must come from the typed policy vocabulary, not inline strings"
    );
    assert!(
        !controller.contains("spawn_editor_route_detached"),
        "orphan drain must not spawn recursive agent-doc route processes"
    );
    assert!(
        orphan_drain.contains("claim_coordination_lease_if_expired_in_db"),
        "orphan drain must atomically persist its per-document dispatch backoff"
    );
    assert!(
        orphan_drain.contains("current_text_for_file_nonblocking"),
        "orphan drain must inspect operator-visible realtime text when an editor is attached"
    );
}

#[test]
fn test_agent_doc_queue_owns_context_clear_in_flight_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));

    let queue_source =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue.rs")).unwrap();
    for required in [
        "pub struct IdleQueueContextClearInFlightSettleFacts",
        "pub struct IdleQueueContextClearInFlightSettle",
        "pub fn idle_queue_context_clear_in_flight_settle_ticks(",
        "projection_active: bool",
    ] {
        assert!(
            queue_source.contains(required),
            "agent-doc-queue must own pure context-clear in-flight decision policy: {required}"
        );
    }

    for forbidden in [
        "pub struct ContextClearInFlight",
        "pub fn context_clear_in_flight_marker(",
        "pub fn context_clear_in_flight_marker_active(",
        "CONTEXT_CLEAR_IN_FLIGHT_TTL_SECS",
        "agent_doc_hash::content_hash",
        "Serialize",
        "Deserialize",
    ] {
        assert!(
            !queue_source.contains(forbidden),
            "agent-doc-queue must not own context-clear marker storage/freshness policy after the CP projection migration: {forbidden}"
        );
    }

    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-queue-io\""),
        "agent-doc-queue-io should be a workspace member"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod context_clear_in_flight;"),
        "orchestration must not expose a context-clear marker IO facade"
    );

    let queue_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/lib.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-queue-io/src/context_clear_in_flight.rs")
            .exists()
            && !queue_io_lib.contains("pub mod context_clear_in_flight;"),
        "agent-doc-queue-io must not keep the context-clear marker sidecar module"
    );

    let state_backbone =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/src/lib.rs")).unwrap();
    for required in [
        "QUEUE_CONTEXT_CLEAR_IN_FLIGHT_TTL_SECS",
        "QueueContextClearStarted",
        "QueueContextClearSettled",
        "QueueContextClearDeferred",
        "QueueContextClearProjection",
        "QueueContextClearPhase",
        "QueueContextClearEvent",
        "QueueContextClearMachine",
        "transition_queue_context_clear",
        "is_pending_at",
        "is_deferred_operator_clear",
        "QUEUE_CONTEXT_CLEAR_SOURCE_OPERATOR_MANUAL_COOLDOWN",
        "is_manual_operator_clear_cooldown",
    ] {
        assert!(
            state_backbone.contains(required),
            "agent-doc-state-backbone must own context-clear projection policy: {required}"
        );
    }

    let controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    for required in [
        "pub fn queue_context_clear_started_for_file(",
        "pub fn queue_context_clear_deferred_for_file(",
        "pub fn queue_context_clear_manual_cooldown_for_file(",
        "pub fn queue_context_clear_settled_for_file(",
        "pub fn queue_context_clear_status_for_file(",
        "pub fn queue_context_clear_in_flight_for_file(",
        "pub fn queue_context_clear_deferred_operator_for_file(",
        "pub fn queue_context_clear_manual_cooldown_active_for_file(",
        "pub fn clear_queue_context_clear_in_flight_for_file(",
        "pub fn clear_queue_context_clear_manual_cooldown_for_file(",
        "pub fn clear_queue_context_clear_deferred_for_file(",
        "\"queue_context_clear_started\"",
        "\"queue_context_clear_deferred\"",
        "\"queue_context_clear_settled\"",
        "\"queue_context_clear_status\"",
        "handle_queue_context_clear_started",
        "handle_queue_context_clear_deferred",
        "handle_queue_context_clear_settled",
        "handle_queue_context_clear_status",
    ] {
        assert!(
            controller_rpc.contains(required),
            "project controller must own context-clear projection helper/RPC: {required}"
        );
    }

    assert!(
        !controller_rpc.contains(".agent-doc/context-clear-in-flight")
            && !state_backbone.contains(".agent-doc/context-clear-in-flight")
            && !controller_rpc.contains(".agent-doc/deferred-clears")
            && !state_backbone.contains(".agent-doc/deferred-clears")
            && !controller_rpc.contains(".agent-doc/queue-cooldowns")
            && !state_backbone.contains(".agent-doc/queue-cooldowns"),
        "context-clear projection owners must not preserve the old marker path authority"
    );

    let queue_io_marker =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/continuation_marker.rs"))
            .unwrap();
    for forbidden in [
        "QUEUE_COOLDOWNS_DIR",
        "cooldown_marker_path(",
        "pub fn write_clear_cooldown(",
        "pub fn clear_cooldown_marker(",
        "pub fn clear_cooldown_active(",
        ".agent-doc/queue-cooldowns",
    ] {
        assert!(
            !queue_io_marker.contains(forbidden),
            "queue IO must not own clear-cooldown sidecar storage after the projection migration: {forbidden}"
        );
    }

    let idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    for forbidden in [
        "clear_settle_idle_ticks = clear_settle_idle_ticks.saturating_add",
        "let clear_settled_now =",
    ] {
        assert!(
            !idle_watch.contains(forbidden),
            "idle_watch.rs must not re-own context-clear settle tick policy: {forbidden}"
        );
    }
    assert!(
        idle_watch.contains("idle_queue_context_clear_in_flight_settle_ticks")
            && idle_watch.contains("IdleQueueContextClearInFlightSettleFacts")
            && idle_watch.contains(
                "agent_doc_controller_io::project_controller::queue_context_clear_in_flight_for_file"
            )
            && idle_watch.contains(
                "agent_doc_controller_io::project_controller::clear_queue_context_clear_in_flight_for_file"
            )
            && idle_watch.contains(
                "agent_doc_controller_io::project_controller::queue_context_clear_started_for_file"
            )
            && idle_watch.contains(
                "agent_doc_controller_io::project_controller::clear_queue_context_clear_manual_cooldown_for_file"
            )
            && !idle_watch.contains("agent_doc_queue_io::context_clear_in_flight::"),
        "idle_watch.rs should call queue policy and controller context-clear projection helpers directly"
    );
}

#[test]
fn test_agent_doc_work_graph_is_source_agnostic_boundary() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-work-graph")),
        "agent-doc-work-graph must stay a first-class workspace crate"
    );
    assert!(
        manifest_dir
            .join("agent-doc-work-graph/src/lib.rs")
            .exists(),
        "work-graph analysis should live in the focused crate"
    );
    let work_graph_source =
        fs::read_to_string(manifest_dir.join("agent-doc-work-graph/src/lib.rs")).unwrap();
    for required in [
        "pub mod schedule;",
        "pub enum AutoDagScheduleDecision",
        "pub enum BatchProgressDecision",
        "pub fn classify_batch_progress",
        "pub struct BatchChildResult",
        "pub fn queue_freeze_event",
        "pub fn source_changed_event",
        "pub fn child_closeout_event",
        "pub fn auto_dag_schedule_event",
        "pub const fn as_str",
    ] {
        assert!(
            work_graph_source.contains(required),
            "agent-doc-work-graph must own Auto-DAG scheduling and batch flow policy: {required}"
        );
    }
    let schedule_source =
        fs::read_to_string(manifest_dir.join("agent-doc-work-graph/src/schedule.rs")).unwrap();
    for required in [
        "pub struct AutoDagSchedule",
        "pub enum AutoDagNodeState",
        "pub fn build_schedule",
        "pub fn schedule_seed",
        "pub fn update_schedule_node_state",
        "pub fn classify_session_review_log",
        "pub fn guard_blocker",
        "pub struct AutoDagGraphEvidence",
        "pub struct AutoDagGraphTargetEvidence",
        "pub fn validate_schedule_graph_evidence",
        "pub fn target_evidence_for_schedule",
    ] {
        assert!(
            schedule_source.contains(required),
            "agent-doc-work-graph must own the Auto-DAG schedule kernel: {required}"
        );
    }
    let root_auto_dag_source = fs::read_to_string(manifest_dir.join("src/auto_dag.rs")).unwrap();
    for forbidden in [
        "pub(crate) struct AutoDagSchedule",
        "pub(crate) enum AutoDagNodeState",
        "pub(crate) struct SessionReviewGuardReport",
        "pub(crate) fn classify_session_review_log",
        "fn parse_tasks(",
        "fn mark_ready_nodes(",
        "fn validate_graph_evidence(",
        "fn target_evidence_from_graph(",
        "pub(crate) fn guard_blocker",
    ] {
        assert!(
            !root_auto_dag_source.contains(forbidden),
            "root auto_dag adapter must not re-own focused schedule behavior: {forbidden}"
        );
    }
    assert!(
        root_auto_dag_source.contains("agent_doc_work_graph::schedule::{")
            && root_auto_dag_source.contains("build_schedule as build_auto_dag_schedule")
            && root_auto_dag_source.contains("update_schedule_node_state")
            && root_auto_dag_source.contains("validate_schedule_graph_evidence")
            && root_auto_dag_source.contains("target_evidence_for_schedule"),
        "root auto_dag adapter should call the focused schedule crate directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/orchestration_batch.rs")
            .exists(),
        "orchestration must not keep an orchestration-batch flow adapter"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow")
            .exists(),
        "orchestration must not keep a flow source module for orchestration-batch facades"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-document/src/auto_dag.rs")
            .exists(),
        "Auto-DAG graph policy should not live under the markdown document projection crate"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-work-graph"),
        "the CLI should call the focused work-graph crate directly"
    );

    let work_graph_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-work-graph/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&work_graph_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    assert!(dependencies.contains_key("agent-doc-element"));
    assert!(dependencies.contains_key("agent-doc-element-backlog"));
    for forbidden in [
        "agent-doc-core",
        "agent-doc-document",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-work-graph must stay source-agnostic and free of document, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_agent_doc_run_context_io_owns_lazily_document_context_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-run-context-io")),
        "agent-doc-run-context-io must stay a first-class workspace crate"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/graph.rs")
            .exists(),
        "orchestration must not retain the Lazily run-context graph source file"
    );

    let run_context_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-context-io/src/lib.rs")).unwrap();
    for required in [
        "lazily::define_schema!(pub CycleContextSchema);",
        "lazily::define_schema!(pub ActorContextSchema);",
        "pub type CycleContext = TypedContext<CycleContextSchema>",
        "pub type ActorContext = TypedContext<ActorContextSchema>",
        "pub fn cycle_context(file_path: PathBuf) -> CycleContext",
        "pub fn actor_context_for_project_root(project_root: PathBuf) -> ActorContext",
        "pub trait AgentDocContextExt",
        "fn snapshot_commit_status(&self) -> agent_doc_snapshot_io::SnapshotCommitStatus",
        "fn session_registry(&self) -> Arc<tmux_router::Registry>",
        "lazily::{TypedCellHandle, TypedContext, TypedFactoryContext, TypedSlotHandle}",
    ] {
        assert!(
            run_context_source.contains(required),
            "agent-doc-run-context-io must own the typed Lazily context graph directly: {required}"
        );
    }
    for forbidden in [
        "pub struct DocumentContext",
        "pub type CycleContext = DocumentContext",
        "pub type ActorContext = DocumentContext",
        "agent_doc_orchestration::",
        "crate::test_support::",
        "pub use agent_doc_run_context_io",
    ] {
        assert!(
            !run_context_source.contains(forbidden),
            "agent-doc-run-context-io must not route through orchestration or expose a facade: {forbidden}"
        );
    }
    assert!(
        run_context_source
            .contains("agent_doc_cycle_state_io::load_with_closeout_projection(&path)")
            && !run_context_source.contains("agent_doc_cycle_state_io::load(&path)"),
        "run-context cycle_state slot should use closeout projections before compatibility cycle sidecars"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod graph;")
            && !orchestration_lib.contains("pub use agent_doc_run_context_io as graph;"),
        "orchestration must not preserve the public graph path with a direct crate re-export"
    );
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    assert!(
        orchestration_manifest["dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-run-context-io"),
        "orchestration should depend on the focused run-context IO crate"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-run-context-io"),
        "the CLI should call the focused run-context IO crate directly"
    );
    for relative in [
        "src/orchestrate.rs",
        "src/patch.rs",
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-start-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            (source.contains("agent_doc_run_context_io::CycleContext")
                || source.contains("agent_doc_run_context_io::CycleContext")
                || source.contains("agent_doc_run_context_io::cycle_context")
                || source.contains("agent_doc_run_context_io::AgentDocContextExt")
                || source.contains("agent_doc_run_context_io::{AgentDocContextExt, CycleContext}")
                || source.contains("agent_doc_run_context_io::{CycleContext, AgentDocContextExt}"))
                && !source.contains("agent_doc_orchestration::graph::CycleContext")
                && !source.contains("crate::graph::CycleContext"),
            "{relative} should use the focused document-context crate directly"
        );
    }
}

#[test]
fn test_agent_doc_run_io_owns_direct_run_prompt_and_queue_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-run-io")),
        "agent-doc-run-io must stay a first-class workspace crate"
    );

    let run_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    for required in [
        "pub enum RunMode",
        "pub struct RunCycleOutcome",
        "pub enum AutoQueueContinuation",
        "pub enum ActiveQueuePromptState",
        "pub trait DirectRunEffects",
        "pub fn run(",
        "pub fn run_with_context(",
        "pub fn run_once(",
        "pub fn repair_document_frontmatter_on_disk",
        "pub fn apply_append_response",
        "pub fn apply_template_response",
        "pub fn normalize_direct_run_prompt_prefixes",
        "pub fn normalize_direct_run_template_content",
        "pub fn update_resume_id",
        "pub fn direct_run_atomic_write",
        "pub fn compute_run_diff",
        "pub fn active_queue_prompt_diff",
        "pub fn active_queue_prompt_state",
        "pub fn should_continue_auto_queue",
        "pub fn build_prompt",
        "pub fn prompt_cache_routing_affinity",
        "pub struct RunStderrRedirect",
        "pub struct RunHeartbeat",
        "pub fn start_run_cycle",
        "pub fn mark_run_write_applied",
        "pub fn record_run_progress",
        "pub fn record_run_preflight_timeout",
        "pub fn abandon_run_recursive_cycle",
        "pub fn owned_pane_self_invocation_detail",
        "pub fn detect_owned_pane_self_invocation_with_options",
        "pub fn recursive_codex_start_invocation_diagnostic",
        "pub fn run_dispatch_timeout_diagnostic",
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(",
        "agent_doc_document_realtime_io::atomic_write_through_authority(file, &repaired)",
        "PromptCacheBlocks::new",
        "agent_doc_controller_io::project_controller::load_state_event_ledger",
    ] {
        assert!(
            run_io_source.contains(required),
            "agent-doc-run-io must own the direct-run prompt/queue graph: {required}"
        );
    }
    for forbidden in ["agent_doc_orchestration::", "crate::write", "crate::git"] {
        assert!(
            !run_io_source.contains(forbidden),
            "agent-doc-run-io must not route through orchestration command internals: {forbidden}"
        );
    }
    for forbidden in [
        "std::fs::read_to_string(file)",
        "std::fs::write(file, &repaired)",
    ] {
        assert!(
            !run_io_source.contains(forbidden),
            "agent-doc-run-io session-document hot paths must not use raw disk IO: {forbidden}"
        );
    }

    let orchestration_run_source = manifest_dir.join("agent-doc-orchestration/src/run.rs");
    assert!(
        !orchestration_run_source.exists(),
        "orchestration must not keep a source-module facade for direct-run tests"
    );
    let direct_run_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/tests/direct_run.rs")).unwrap();
    for forbidden in [
        "enum RunMode",
        "struct RunCycleOutcome",
        "enum AutoQueueContinuation",
        "enum ActiveQueuePromptState",
        "fn compute_run_diff(",
        "fn active_queue_prompt_state(file",
        "fn should_continue_auto_queue(",
        "fn build_prompt(",
        "fn prompt_cache_routing_affinity(",
        "struct RunStderrRedirect",
        "struct RunHeartbeat",
        "fn start_run_cycle(",
        "fn mark_run_write_applied(",
        "fn record_run_progress(",
        "fn record_run_preflight_timeout(",
        "fn abandon_run_recursive_cycle(",
        "fn owned_pane_self_invocation_detail(",
        "fn detect_owned_pane_self_invocation_with_options(",
        "fn recursive_codex_start_invocation_diagnostic(",
        "fn run_dispatch_timeout_diagnostic(",
        "fn run_once(",
        "fn apply_append_response(",
        "fn apply_template_response(",
        "fn normalize_direct_run_prompt_prefixes(",
        "fn normalize_direct_run_template_content(",
        "fn update_resume_id(",
        "fn acquire_doc_lock(",
        "fn atomic_write(path:",
        "fn repair_document_frontmatter_on_disk(",
    ] {
        assert!(
            !direct_run_tests.contains(forbidden),
            "orchestration direct-run integration tests must not re-own the focused direct-run graph: {forbidden}"
        );
    }
    assert!(
        direct_run_tests.contains("agent_doc_run_io::{")
            && direct_run_tests.contains("build_prompt")
            && direct_run_tests.contains("should_continue_auto_queue")
            && direct_run_tests.contains("agent_doc_run_runtime_io::DIRECT_RUN_EFFECTS"),
        "direct-run integration tests should exercise the focused direct-run IO crate directly"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod run;")
            && !orchestration_lib.contains("mod run;")
            && !orchestration_lib.contains("pub struct OrchestrationDirectRunEffects")
            && !orchestration_lib.contains("pub static DIRECT_RUN_EFFECTS")
            && !orchestration_lib.contains("impl agent_doc_run_io::DirectRunEffects"),
        "orchestration must not keep the direct-run source module or runtime effects adapter"
    );
    let run_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-run-runtime-io/src/lib.rs")).unwrap();
    assert!(
        run_runtime.contains("pub struct RuntimeDirectRunEffects")
            && run_runtime.contains("pub static DIRECT_RUN_EFFECTS")
            && run_runtime.contains("impl agent_doc_run_io::DirectRunEffects")
            && run_runtime.contains("agent_doc_closeout_runtime_io::complete_required_closeout("),
        "agent-doc-run-runtime-io should own the direct-run runtime effects adapter"
    );
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        main_source.contains("agent_doc_run_io::run(")
            && main_source.contains("&agent_doc_run_runtime_io::DIRECT_RUN_EFFECTS")
            && !main_source.contains("agent_doc_orchestration::run::run("),
        "CLI run dispatch should call focused direct-run IO directly"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    assert!(
        orchestration_manifest["dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-run-io"),
        "orchestration should depend on the focused direct-run IO crate"
    );
    assert!(
        orchestration_manifest["dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-run-runtime-io"),
        "orchestration should depend on the focused direct-run runtime effects crate while callers are still routed through orchestration modules"
    );

    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-run-io"),
        "the CLI should expose the focused direct-run IO crate in the workspace dependency set"
    );
    assert!(
        root_dependencies.contains_key("agent-doc-run-runtime-io"),
        "the CLI should expose the focused direct-run runtime effects crate in the workspace dependency set"
    );
}

#[test]
fn test_coarse_orchestration_extractions_are_tracked() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tracker =
        fs::read_to_string(manifest_dir.join("tasks/agent-doc/prd-crate-decomposition.md"))
            .unwrap();
    assert!(
        tracker.contains("## Coarse Extraction Ledger"),
        "crate decomposition PRD must track intentionally coarse extraction rounds"
    );
    let statechart_plan = fs::read_to_string(
        manifest_dir.join("tasks/agent-doc/plan-state-backbone-realtime-statecharts.md"),
    )
    .unwrap();
    for required in [
        "agent-doc-state-backbone",
        "agent-doc-document-realtime",
        "lazily-backed projection",
        "Marker files may remain only as advisory wakeups",
        "Visible-write guard proof",
    ] {
        assert!(
            statechart_plan.contains(required),
            "state backbone/realtime statechart theme must document placement rule: {required}"
        );
    }
    let coarse_section = tracker
        .split("## Coarse Extraction Ledger")
        .nth(1)
        .expect("crate decomposition PRD should contain a coarse extraction ledger");
    let coverage_section = coarse_section
        .split("| Coarse graph |")
        .next()
        .expect("coarse extraction ledger should have a coverage section");
    assert!(
        coverage_section.contains("### Coarse Commit Coverage"),
        "coarse extraction ledger must track commit coverage for current and prior large-chunk rounds"
    );
    let coverage_lines: Vec<&str> = coverage_section
        .lines()
        .map(str::trim)
        .filter(|line| {
            line.starts_with('|') && !line.starts_with("|---") && !line.starts_with("| Commit(s) |")
        })
        .collect();
    assert!(
        coverage_lines.len() >= 38,
        "coarse extraction commit coverage should include prior large-chunk rounds and current rounds; found {} rows",
        coverage_lines.len()
    );
    let mut ledger_rows: Vec<Vec<&str>> = Vec::new();
    let mut in_coarse_table = false;
    for line in coarse_section.lines() {
        let line = line.trim();
        if line.starts_with("| Coarse graph |") {
            in_coarse_table = true;
            continue;
        }
        if !in_coarse_table {
            continue;
        }
        if !line.starts_with('|') {
            break;
        }
        if line.starts_with("|---") {
            continue;
        }
        ledger_rows.push(line.trim_matches('|').split('|').map(str::trim).collect());
    }
    assert!(
        ledger_rows.len() >= 85,
        "coarse extraction ledger should include prior large-chunk rounds and current rounds; found {} rows",
        ledger_rows.len()
    );
    for cells in &ledger_rows {
        assert_eq!(
            cells.len(),
            5,
            "coarse extraction ledger rows must preserve graph/from/to/why/follow-up columns: {cells:?}"
        );
        let graph = cells[0];
        let moved_from = cells[1];
        let moved_to = cells[2];
        let why = cells[3];
        let follow_up = cells[4];
        for (label, cell) in [
            ("graph", graph),
            ("moved-from", moved_from),
            ("moved-to", moved_to),
            ("why", why),
            ("follow-up", follow_up),
        ] {
            assert!(
                !cell.is_empty(),
                "coarse extraction ledger row must not leave {label} empty: {cells:?}"
            );
        }
        assert!(
            moved_from.contains("agent-doc-orchestration/src")
                || moved_from.contains("agent-doc-orchestration/tests")
                || moved_from.contains("agent-doc-orchestration/Cargo.toml"),
            "coarse extraction ledger row should name the orchestration source/test/package graph: {cells:?}"
        );
        assert!(
            moved_to.contains("agent-doc-")
                || moved_to.contains("src/main.rs")
                || moved_to.contains("Focused crates"),
            "coarse extraction ledger row should name the focused destination graph: {cells:?}"
        );
        assert!(
            follow_up.contains("Split")
                || follow_up.contains("Move")
                || follow_up.contains("Keep")
                || follow_up.contains("Finish")
                || follow_up.contains("Extract")
                || follow_up.contains("Separate")
                || follow_up.contains("delete"),
            "coarse extraction ledger row must name the fine-grained seams to revisit: {cells:?}"
        );
    }

    let coverage_graphs: BTreeSet<String> = coverage_lines
        .iter()
        .flat_map(|line| {
            let cells: Vec<_> = line.trim_matches('|').split('|').map(str::trim).collect();
            assert_eq!(
                cells.len(),
                2,
                "coarse extraction coverage rows must preserve commit/ledger columns: {line}"
            );
            assert!(
                !cells[0].is_empty() && !cells[1].is_empty(),
                "coarse extraction coverage rows must name commit(s) and ledger row(s): {line}"
            );
            cells[1]
                .split(';')
                .map(str::trim)
                .filter(|graph| !graph.is_empty())
                .map(str::to_owned)
                .collect::<Vec<_>>()
        })
        .collect();
    let ledger_graphs: BTreeSet<String> = ledger_rows
        .iter()
        .map(|cells| cells[0].to_owned())
        .collect();
    for graph in &ledger_graphs {
        assert!(
            coverage_graphs.contains(graph),
            "coarse extraction coverage must include a commit row for ledger graph {graph:?}"
        );
    }
    for graph in &coverage_graphs {
        assert!(
            ledger_graphs.contains(graph),
            "coarse extraction coverage graph {graph:?} must have a detailed ledger row"
        );
    }

    for (commit, graph) in [
        ("539eabb9", "Focused IO crate wave"),
        ("539eabb9", "Codex hook blocked-stop sidecar IO"),
        ("bf6b1735", "Legacy route/controller policy wave"),
        ("a0bb0402", "Legacy route/controller policy wave"),
        ("571c7d0a", "Legacy route/controller policy wave"),
        ("664504cd", "Legacy route/controller policy wave"),
        ("b5a4b32c", "Legacy route/controller policy wave"),
        ("21f3fc3f", "Legacy route/controller policy wave"),
        ("039981a3", "Legacy route/controller policy wave"),
        ("328936a1", "Legacy route/controller policy wave"),
        ("c27e67b3", "Legacy route/controller policy wave"),
        ("79b4677f", "Legacy route/controller policy wave"),
        ("e401939a", "Legacy route/controller policy wave"),
        ("19ac1edf", "Legacy route/controller policy wave"),
        ("31474257", "Legacy route/controller policy wave"),
        ("4adf538e", "Legacy route/controller policy wave"),
        ("66541752", "Legacy route/controller policy wave"),
        ("9f6ad677", "Legacy route/controller policy wave"),
        ("5bcfc07b", "Legacy route/controller policy wave"),
        (
            "27a7a849",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "882f1219",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "e320fd49",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "f6c4f88f",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "702e980c",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "73abc196",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "8dce5536",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "b0ebca68",
            "Legacy write/realtime/session-check policy wave",
        ),
        (
            "571c7d0a",
            "Legacy write/realtime/session-check policy wave",
        ),
        ("6bc00090", "Legacy git/sync/frontmatter helper wave"),
        ("39ad285a", "Legacy git/sync/frontmatter helper wave"),
        ("56f965b6", "Legacy git/sync/frontmatter helper wave"),
        ("10a3b66e", "Legacy git/sync/frontmatter helper wave"),
        ("a5d24044", "Legacy git/sync/frontmatter helper wave"),
        ("6bc00090", "Legacy supervisor/agent runtime IO wave"),
        ("42d504fc", "Legacy supervisor/agent runtime IO wave"),
        ("0a8e273b", "Legacy supervisor/agent runtime IO wave"),
        ("971cb2e2", "Legacy supervisor/agent runtime IO wave"),
        ("b4c9f10c", "Legacy supervisor/agent runtime IO wave"),
        ("8dce5536", "Legacy supervisor/agent runtime IO wave"),
        ("5bcfc07b", "Legacy supervisor/agent runtime IO wave"),
        ("664504cd", "Legacy supervisor/agent runtime IO wave"),
        ("c95eced6", "Legacy supervisor/agent runtime IO wave"),
        ("e24a3fca", "Legacy supervisor/agent runtime IO wave"),
        ("1c57b988", "Legacy memory/queue/harness adapter wave"),
        ("41b388ab", "Legacy memory/queue/harness adapter wave"),
        ("b4c9f10c", "Legacy memory/queue/harness adapter wave"),
        ("8dce5536", "Legacy memory/queue/harness adapter wave"),
        ("96ac3af1", "Agent backend process adapters"),
        ("96ac3af1", "Supervisor process runtime adapters"),
        ("2811d37e", "Orchestration facade deletion sweep"),
        ("8c008cea", "Cycle state sidecar IO"),
        ("016184a3", "Operation-log facade deletion"),
        ("fc5d5de9", "Realtime admission cycle opener"),
        ("e41a6004", "Workflow doctor/autofix IO"),
        ("d30b9b13", "State backbone chart and observer graph"),
        ("cd553da8", "State backbone chart and observer graph"),
        ("8000c8cf", "State backbone chart and observer graph"),
        ("c8ed0f7c", "State backbone chart and observer graph"),
        ("c2e6ca12", "State backbone chart and observer graph"),
        ("ebade5a9", "State wire subscription boundary"),
        ("0a95a821", "Turn-scope sidecar IO"),
        ("160e9f4b", "Turn-scope sidecar IO"),
        ("614a8819", "Transcript context and model-tier graph"),
        ("c886927e", "Transcript context and model-tier graph"),
        ("5c19aee1", "Transcript context and model-tier graph"),
        ("486913a7", "Prompt-cache policy and history IO"),
        ("0a24fa2e", "Prompt-cache policy and history IO"),
        ("1cb21bb6", "Prompt-cache policy and history IO"),
        ("76df51a7", "Session accretion IO adapter"),
        ("f32e1b61", "Response capture IO adapter"),
        ("b3e3edd4", "Prompt and state observer IO"),
        ("05ce84af", "Watch daemon IO"),
        ("44c998d8", "GC IO host"),
        ("0a71ce02", "GC/watch CLI effect adapter cleanup"),
        ("af1b5d32", "Controller dashboard policy and IO"),
        ("539eabb9", "Controller dashboard policy and IO"),
        ("001d5390", "Controller admin command IO host"),
        (
            "8c3efe03",
            "Queue command, pipeline mirror, and write-queue adapter batch",
        ),
        ("d4f20b8c", "CRDT relay host IO"),
        ("b23eb844", "Lazily run-context graph"),
        ("1c0abe65", "Queue continuation host IO"),
        ("35752f5c", "Tracked-work command and done-archive IO"),
        ("1e486e4f", "Session-check guard IO adapter batch"),
        ("7fbe726a", "Focus command host IO"),
        ("369280b0", "Session actor store and mailbox IO"),
        ("5dc7c322", "Session registration and projection IO"),
        ("0f90f7cf", "Project controller runtime IO"),
        ("d6387afa", "Sync and resync runtime IO graph"),
        ("c65b9260", "Compact command archive/write IO graph"),
        ("af54bb9f", "Document realtime authority IO graph"),
        ("e756b12c", "Claim command binding IO graph"),
        ("7af46f2c", "Stream command writeback IO graph"),
    ] {
        assert!(
            coverage_lines
                .iter()
                .any(|line| line.contains(commit) && line.contains(graph)),
            "coarse extraction commit coverage is missing {commit} for {graph}"
        );
    }

    for (graph, moved_from, moved_to, follow_up) in [
        (
            "Focused IO crate wave",
            "agent-doc-orchestration/src/{snapshot.rs,diff_io.rs,template_io.rs,status_cmd.rs,startup_miss.rs,supervisor/ipc.rs,flow/*.rs}",
            "agent-doc-{archive,codex-hook,controller,diff,flow,git,hooks,ipc,lease,lint,memory,merge,ops-log,prompt-context,repair,response-replay,session-registry,snapshot,status,sync,template,workflow}-io",
            "Split the broad IO wave by durable domain once call sites settle",
        ),
        (
            "Legacy route/controller policy wave",
            "agent-doc-orchestration/src/{route*.rs,route/*.rs,project_controller*.rs,start*.rs,repair.rs}",
            "agent-doc-controller",
            "Finish moving remaining route/project-controller authority into focused controller/supervisor IO crates",
        ),
        (
            "Legacy write/realtime/session-check policy wave",
            "agent-doc-orchestration/src/{write.rs,write/*,session_check*.rs,session_check/*,flow/closeout.rs}",
            "agent-doc-document-realtime",
            "Split deterministic markdown/write normalization from live-authority and realtime effects",
        ),
        (
            "Legacy git/sync/frontmatter helper wave",
            "agent-doc-orchestration/src/{git.rs,sync.rs,resync.rs,resync/*,frontmatter_io.rs}",
            "agent-doc-process-owner-io",
            "Keep splitting the moved sync/resync graph inside `agent-doc-sync-io`",
        ),
        (
            "Sync and resync runtime IO graph",
            "agent-doc-orchestration/src/{sync.rs,sync/*,resync.rs,resync/*}",
            "agent-doc-sync-io/src/{sync.rs,sync/*,resync.rs,resync/*}",
            "extract the temporary `SyncRuntimeEffects` callbacks",
        ),
        (
            "Compact command archive/write IO graph",
            "agent-doc-orchestration/src/compact.rs",
            "agent-doc-compact-io/src/lib.rs",
            "Split archive file creation/indexing into `agent-doc-archive-io`",
        ),
        (
            "Document realtime authority IO graph",
            "agent-doc-orchestration/src/realtime_model.rs",
            "agent-doc-document-realtime-io/src/lib.rs",
            "Split durable live-buffer feed",
        ),
        (
            "Claim command binding IO graph",
            "agent-doc-orchestration/src/claim.rs",
            "agent-doc-claim-io/src/lib.rs",
            "Split git commit, route pane provisioning, sync prune",
        ),
        (
            "Stream command writeback IO graph",
            "agent-doc-orchestration/src/stream.rs",
            "agent-doc-stream-io/src/lib.rs",
            "Split streaming runtime callbacks",
        ),
        (
            "Legacy supervisor/agent runtime IO wave",
            "agent-doc-orchestration/src/{supervisor/*,agent/{claude.rs,codex.rs},start/*}",
            "agent-doc-supervisor-process",
            "Separate pure runtime policy from process/PTY/file IO",
        ),
        (
            "Legacy memory/queue/harness adapter wave",
            "agent-doc-orchestration/src/{memory_cmd.rs,queue_continuation.rs,hooks.rs,run.rs,agent/codex.rs,write/ipc.rs}",
            "agent-doc-queue-io",
            "Split memory store policy from command IO",
        ),
        (
            "Agent backend process adapters",
            "agent-doc-orchestration/src/agent/{claude.rs,codex.rs,junie.rs,opencode.rs}",
            "agent-doc-agent-io/src/agent/*",
            "Split CLI-specific stream/protocol parsing from process spawning",
        ),
        (
            "Supervisor process runtime adapters",
            "agent-doc-orchestration/src/supervisor/{in_process.rs,pty.rs}",
            "agent-doc-supervisor-process/src/{in_process.rs,pty.rs,session_liveness.rs}",
            "Split Unix raw child operations, PTY plumbing, and pure reattach/tick decisions",
        ),
        (
            "Orchestration facade deletion sweep",
            "agent-doc-orchestration/src/{agent.rs,commit_integrity.rs}",
            "agent-doc-agent-io",
            "Keep no-facade guard tests current",
        ),
        (
            "Cycle state sidecar IO",
            "agent-doc-orchestration/src/cycle_state.rs",
            "agent-doc-cycle-state-io/src/lib.rs",
            "Split schema/pathing/atomic writes from higher-level lifecycle bookkeeping",
        ),
        (
            "Operation-log facade deletion",
            "agent-doc-orchestration/src/ops_log.rs",
            "agent-doc-ops-log-io/src/lib.rs",
            "never reintroduce an orchestration ops-log facade",
        ),
        (
            "Realtime admission cycle opener",
            "agent-doc-orchestration/src/admit.rs",
            "agent-doc-cycle-state-io/src/lib.rs",
            "keep snapshot and ops-log adapters injected until their dependency graph is acyclic",
        ),
        (
            "Workflow doctor/autofix IO",
            "agent-doc-orchestration/src/{doctor.rs,autofix.rs}",
            "agent-doc-workflow-io/src/{doctor.rs,autofix.rs}",
            "move controller inspection and realtime buffer divergence into focused IO crates",
        ),
        (
            "State backbone chart and observer graph",
            "agent-doc-orchestration/src/state_backbone.rs",
            "agent-doc-state-backbone",
            "Split pure chart/event vocabulary from observer/read-model adapters",
        ),
        (
            "State wire subscription boundary",
            "agent-doc-orchestration/src/state_wire.rs",
            "agent-doc-state-wire",
            "Split wire payload encoding from callback dispatch",
        ),
        (
            "Turn-scope sidecar IO",
            "agent-doc-orchestration/src/turn_scope_store.rs",
            "agent-doc-turn-scope-io",
            "Split pure affectedness/authority decisions from sidecar pathing and filesystem IO",
        ),
        (
            "Transcript context and model-tier graph",
            "agent-doc-orchestration/src/context_pct.rs",
            "agent-doc-model-tier/src/{context_usage.rs,context_transcript_io.rs}",
            "Split deterministic context parsing from transcript filesystem discovery",
        ),
        (
            "Prompt-cache policy and history IO",
            "agent-doc-orchestration/src/prompt_cache.rs",
            "agent-doc-prompt-cache",
            "Split pure cache economics/ranking from history file IO",
        ),
        (
            "Codex hook blocked-stop sidecar IO",
            "agent-doc-orchestration/src/codex_hook.rs",
            "agent-doc-codex-hook-io/src/lib.rs",
            "Split project-root enumeration from blocked-payload persistence",
        ),
        (
            "Session accretion IO adapter",
            "agent-doc-orchestration/src/session_accretion.rs",
            "agent-doc-session-accretion-io/src/lib.rs",
            "Move more deterministic metric reduction into `agent-doc-session-accretion`",
        ),
        (
            "Response capture IO adapter",
            "agent-doc-orchestration/src/capture.rs",
            "agent-doc-capture-io/src/lib.rs",
            "Split capture path/schema helpers from atomic store operations",
        ),
        (
            "Prompt and state observer IO",
            "agent-doc-orchestration/src/prompt.rs",
            "agent-doc-prompt-io/src/lib.rs",
            "Keep pure prompt parsing/navigation in `agent-doc-turn-executor-tmux`",
        ),
        (
            "Watch daemon IO",
            "agent-doc-orchestration/src/document_watcher.rs",
            "agent-doc-watch-io/src/daemon.rs",
            "Split PID/process control, session discovery, file-watch delivery",
        ),
        (
            "GC IO host",
            "agent-doc-orchestration/src/gc.rs",
            "agent-doc-gc-io/src/lib.rs",
            "Split pure retention/path classification from filesystem deletes",
        ),
        (
            "GC/watch CLI effect adapter cleanup",
            "agent-doc-orchestration/src/{gc.rs,watch.rs}",
            "src/main.rs",
            "Move controller/state-event and stream-flush effect bindings out of the CLI",
        ),
        (
            "Controller dashboard policy and IO",
            "agent-doc-orchestration/src/dashboard.rs",
            "agent-doc-controller-io/src/dashboard.rs",
            "Split controller-inspection effects from session-registry/pane-liveness snapshot assembly",
        ),
        (
            "Controller admin command IO host",
            "agent-doc-orchestration/src/admin.rs",
            "agent-doc-admin-io/src/lib.rs",
            "Split JSON view structs from project-controller RPC structs once controller RPC types move",
        ),
        (
            "Queue command, pipeline mirror, and write-queue adapter batch",
            "agent-doc-orchestration/src/{queue_cmd.rs,pipeline_frontmatter.rs,write_queue.rs}",
            "agent-doc-cycle-state-io/src/pipeline_frontmatter.rs",
            "Move the remaining queue write effects out of `write.rs`",
        ),
        (
            "CRDT relay host IO",
            "agent-doc-orchestration/src/crdt_relay_host.rs",
            "agent-doc-crdt-relay-io/src/lib.rs",
            "Separate hub-registry lifecycle from disk projection recovery",
        ),
        (
            "Lazily run-context graph",
            "agent-doc-orchestration/src/graph.rs",
            "agent-doc-run-context-io/src/lib.rs",
            "Split short-lived CLI `CycleContext` slots from long-lived `ActorContext`",
        ),
        (
            "Queue continuation host IO",
            "agent-doc-orchestration/src/queue_continuation.rs",
            "agent-doc-queue-io/src/queue_continuation.rs",
            "Move pure queue policy regression tests into `agent-doc-queue`",
        ),
        (
            "Top-level focused crate re-export facade deletion batch",
            "agent-doc-orchestration/src/lib.rs",
            "agent-doc-crdt-relay-io",
            "Split the remaining root effects providers and delete them once git/write/repair callbacks are focused",
        ),
        (
            "Write visible-guard re-export facade deletion",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-document-realtime-io",
            "Move the remaining visible-write convergence sequencing out of `write.rs`",
        ),
        (
            "Write stale-snapshot convergence IO graph",
            "agent-doc-orchestration/src/write/converge.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Split live-prompt drift recovery, editor convergence, and IPC fallback adapters",
        ),
        (
            "Write IPC de-wedge and stale-supervisor recycle IO graph",
            "agent-doc-orchestration/src/write/{ipc.rs,ipc/transport.rs,converge.rs}",
            "agent-doc-write-converge-io/src/lib.rs",
            "Split editor convergence payload construction",
        ),
        (
            "Write editor convergence IO graph",
            "agent-doc-orchestration/src/write/converge.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move the file-IPC poller and its status/rejection-receipt/content validation",
        ),
        (
            "Write file-IPC delivery proof loop",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move the remaining post-consumption visible-write snapshot repair",
        ),
        (
            "Write IPC transport delivery-loop delegation",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-converge-io::write_file_ipc_and_poll_delivery",
            "Extract the post-delivery repair graph next",
        ),
        (
            "Write IPC transport graph",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-ipc-io/src/transport.rs",
            "Move remaining write IPC transport tests and the orchestration wrapper",
        ),
        (
            "Write IPC production transport facade demotion",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-ipc-io/src/transport.rs",
            "Move remaining write IPC transport tests into `agent-doc-write-ipc-io`",
        ),
        (
            "Direct-run prompt and auto-queue IO graph",
            "agent-doc-orchestration/src/run.rs",
            "agent-doc-run-io/src/lib.rs",
            "Move remaining direct-run prompt and queue tests into `agent-doc-run-io`",
        ),
        (
            "Direct-run runtime and owner-pane IO graph",
            "agent-doc-orchestration/src/run.rs",
            "agent-doc-run-io/src/lib.rs",
            "Split stderr redirection, cycle markers/heartbeat, owner-pane recursion, queue-edit deferral, and dispatch timeout helpers",
        ),
        (
            "Direct-run command runtime and writeback IO graph",
            "agent-doc-orchestration/src/run.rs",
            "agent-doc-run-io/src/lib.rs",
            "Split `DirectRunEffects` into commit, writeback, queue-consume, closeout, and cycle-abandon ports",
        ),
        (
            "Direct-run production facade demotion",
            "agent-doc-orchestration/src/run.rs",
            "agent-doc-run-io/src/lib.rs",
            "Move remaining direct-run tests into `agent-doc-run-io` and split `DirectRunEffects`",
        ),
        (
            "Direct-run test-only source module deletion",
            "agent-doc-orchestration/src/run.rs",
            "agent-doc-orchestration/tests/direct_run.rs",
            "Move the remaining direct-run integration tests into `agent-doc-run-io` once `DirectRunEffects` no longer needs orchestration",
        ),
        (
            "Direct-run integration suite relocation",
            "agent-doc-orchestration/tests/direct_run.rs",
            "agent-doc-run-io/tests/direct_run.rs",
            "Split direct-run effects fixtures into commit, writeback, queue-consume, closeout, and cycle-abandon suites",
        ),
        (
            "Git committed historical snapshot repair IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-repair-io/src/lib.rs",
            "Split visible-rebase guard and historical mutation classification",
        ),
        (
            "Repair commit-boundary and backlog reap IO graph",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-io/src/lib.rs",
            "Split commit-boundary, preflight-cancel, replay detection, and backlog reap effects",
        ),
        (
            "Repair stale preflight recovery IO graph",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-io/src/lib.rs",
            "Split empty-cycle abandonment, bypassed-response detection, committed patchback recovery, and terminal frontmatter effects",
        ),
        (
            "Commit-seam free-text queue strike IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-queue-io/src/queue_consume.rs",
            "Split capture lookup from queue strike writeback",
        ),
        (
            "Codex Stop continuation context IO graph",
            "agent-doc-orchestration/src/codex_hook.rs",
            "agent-doc-codex-hook-io/src/lib.rs",
            "Split MCP config detection, transcript lookup, session-accretion reset policy",
        ),
        (
            "Codex Stop runtime extraction",
            "agent-doc-orchestration/src/codex_hook.rs",
            "agent-doc-codex-stop-io/src/lib.rs",
            "Split Stop payload parsing, queue-continuation decision policy",
        ),
        (
            "Write IPC repair decision model extraction",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-ipc-protocol/src/lib.rs",
            "Extract the post-delivery repair effect graph",
        ),
        (
            "Write visible-write write-through IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move the remaining post-delivery IPC repair orchestration",
        ),
        (
            "Write IPC normalization redelivery IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move snapshot-adoption guards",
        ),
        (
            "Write IPC sidecar repair-decision builder",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move snapshot-adoption guards",
        ),
        (
            "Write IPC visible-state repair IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Split snapshot-adoption guards",
        ),
        (
            "Write IPC full-content redelivery proof IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move snapshot-adoption guards",
        ),
        (
            "Write IPC disabled full-content transport IO graph",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move snapshot-adoption guards",
        ),
        (
            "Write IPC snapshot and CRDT persistence IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Split snapshot-adoption guards",
        ),
        (
            "Write IPC snapshot adoption repair and forensics IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move the remaining snapshot-adoption guard decisions",
        ),
        (
            "Write IPC snapshot semantic convergence and adoption diagnostics graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Move the remaining snapshot-adoption guard decisions",
        ),
        (
            "Write IPC snapshot adoption guard IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Split already-applied socket snapshot adoption",
        ),
        (
            "Tracked-work command and done-archive IO",
            "agent-doc-orchestration/src/backlog_cmd.rs",
            "agent-doc-element-backlog-io/src/{backlog_cmd.rs,done_archive.rs}",
            "Split command rendering from document mutation adapters",
        ),
        (
            "Preflight layout health and repair IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/layout.rs",
            "move remaining preflight command body",
        ),
        (
            "Preflight auto-GC and stale actor cleanup IO graph",
            "agent-doc-orchestration/src/preflight/run.rs",
            "agent-doc-preflight-io/src/gc.rs",
            "move remaining preflight command body",
        ),
        (
            "Preflight debounce wait IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/debounce.rs",
            "Split remaining private debounce config helper",
        ),
        (
            "Preflight stale install and editor-plugin warning IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/warnings.rs",
            "Split stale install freshness from live editor plugin version warnings",
        ),
        (
            "Preflight harness and content-policy warning IO graph",
            "agent-doc-orchestration/src/preflight/run.rs",
            "agent-doc-preflight-io/src/warnings.rs",
            "Split model-tier/harness warnings from content-policy warnings",
        ),
        (
            "Preflight semantic advisory warning graph",
            "agent-doc-orchestration/src/preflight/run.rs",
            "agent-doc-preflight-io/src/warnings.rs",
            "Move remaining queue-stall and stuck-capture warning construction",
        ),
        (
            "Session-check guard IO adapter batch",
            "agent-doc-orchestration/src/session_check/{backlog_guards.rs,partial_staging.rs,queue_head_guards.rs,queue_head_provenance_guards.rs}",
            "agent-doc-session-check-io/src/{backlog_guards.rs,partial_staging.rs,queue_head_guards.rs,queue_head_provenance_guards.rs,guard_modes.rs}",
            "Split durable fact readers from guard-result assembly",
        ),
        (
            "Session-check production facade demotion",
            "agent-doc-orchestration/src/session_check.rs",
            "agent-doc-session-check-io",
            "Move the test-only session-check boundary tests into `agent-doc-session-check-io`",
        ),
        (
            "Session-check test-only command facade deletion",
            "agent-doc-orchestration/src/session_check.rs",
            "agent-doc-session-check-io/src/command.rs",
            "Move the remaining session-check boundary tests into `agent-doc-session-check-io`",
        ),
        (
            "Session-check test-only source module deletion",
            "agent-doc-orchestration/src/session_check.rs",
            "agent-doc-orchestration/tests/session_check.rs",
            "Move the remaining orchestration-bound session-check tests into `agent-doc-session-check-io`",
        ),
        (
            "Session-check integration suite relocation",
            "agent-doc-orchestration/tests/session_check.rs",
            "agent-doc-session-check-io/tests/session_check.rs",
            "Split the broad session-check effects fixtures into smaller owner-crate suites",
        ),
        (
            "Flow closeout effects facade demotion",
            "agent-doc-orchestration/src/flow/mod.rs",
            "agent-doc-flow-io",
            "Split `CloseoutEffects` into narrower",
        ),
        (
            "Flow test-only source module deletion",
            "agent-doc-orchestration/src/flow/{mod.rs,closeout.rs}",
            "agent-doc-orchestration/tests/{flow_closeout.rs,flow_events.rs}",
            "Move the remaining orchestration-bound closeout effect fixtures into `agent-doc-flow-io` after the git/write/repair effects split",
        ),
        (
            "Flow integration suite relocation",
            "agent-doc-orchestration/tests/{flow_closeout.rs,flow_events.rs}",
            "agent-doc-flow-io/tests/{flow_closeout.rs,flow_events.rs}",
            "Split broad closeout fixtures between `agent-doc-flow-io` and smaller owner crates",
        ),
        (
            "Focus command host IO",
            "agent-doc-orchestration/src/focus.rs",
            "agent-doc-focus-io/src/lib.rs",
            "Split stash-window promotion and live-owner lookup out of `sync.rs`",
        ),
        (
            "Session actor store and mailbox IO",
            "agent-doc-orchestration/src/session_actor.rs",
            "agent-doc-session-actor-io/src/lib.rs",
            "Split SQLite actor-store migration/projection emission from in-process mailbox runtime",
        ),
        (
            "Session registration and projection IO",
            "agent-doc-orchestration/src/sessions.rs",
            "agent-doc-session-registry-io/src/registration.rs",
            "Split actor-backed sessions projection and projection diagnostics from tmux registration writes",
        ),
        (
            "Project controller runtime IO",
            "agent-doc-orchestration/src/project_controller.rs",
            "agent-doc-controller-io/src/project_controller.rs",
            "Split RPC client/server wire protocol from SQLite actor-store projection",
        ),
        (
            "Route queue facade deletion batch",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-route-io/src/queue_dispatch.rs",
            "Move the remaining `RouteQueueEffects` write callback",
        ),
        (
            "Route closeout drain IO graph",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-route-io/src/closeout_drain.rs",
            "Split the preflight, repair, and session-check callbacks",
        ),
        (
            "Route authoritative dispatch loop IO graph",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-route-io/src/authoritative_dispatch.rs",
            "Split the queue, dispatch, closeout, and wait-override effect callbacks",
        ),
        (
            "Route command runtime IO graph",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-route-io/src/command.rs",
            "Split the remaining `RouteCommandEffects` bundle",
        ),
        (
            "Route startup test-only provisioning facade deletion",
            "agent-doc-orchestration/src/route/startup.rs",
            "agent-doc-route-io/src/startup.rs",
            "Move the remaining route-startup integration tests",
        ),
        (
            "Orchestration test support helper graph",
            "agent-doc-orchestration/src/test_support.rs",
            "agent-doc-test-support/src/lib.rs",
            "Move remaining orchestration integration fixtures into focused IO crate test helpers",
        ),
        (
            "Supervisor IPC command handler graph",
            "agent-doc-orchestration/src/start/supervisor_io.rs",
            "agent-doc-supervisor-io/src/ipc.rs",
            "Split the `SupervisorIpcHandlerState` adapter",
        ),
        (
            "Supervisor IPC state snapshot adapter graph",
            "agent-doc-orchestration/src/start/supervisor_io.rs",
            "agent-doc-supervisor-io/src/ipc.rs",
            "Split the `SupervisorIpcSnapshotState` adapter",
        ),
        (
            "Supervisor IPC lifecycle adapter graph",
            "agent-doc-orchestration/src/start/supervisor_io.rs",
            "agent-doc-supervisor-io/src/ipc.rs",
            "Split the `SupervisorIpcLifecycleState` adapter",
        ),
        (
            "Supervisor IPC inject delivery adapter graph",
            "agent-doc-orchestration/src/start/supervisor_io.rs",
            "agent-doc-supervisor-io/src/ipc.rs",
            "Split the `SupervisorInjectDeliveryState` adapter",
        ),
        (
            "Supervisor live detection adapter graph",
            "agent-doc-orchestration/src/start/detection.rs",
            "agent-doc-supervisor-io/src/detection.rs",
            "Split the `SupervisorDetectionState` adapter",
        ),
        (
            "Supervisor process observer adapter graph",
            "agent-doc-orchestration/src/start/supervisor_io.rs",
            "agent-doc-supervisor-process-io/src/lib.rs",
            "Split the `SupervisorProcessIoState` adapter",
        ),
        (
            "Supervisor start launch spec and stderr redirect IO graph",
            "agent-doc-orchestration/src/start/run.rs",
            "agent-doc-supervisor-process-io/src/lib.rs",
            "Split launch-spec argument synthesis",
        ),
        (
            "Start admission and session registration IO graph",
            "agent-doc-orchestration/src/start/run.rs",
            "agent-doc-start-io/src/lib.rs",
            "Split `StartRuntime` into document prep, owner admission, registration, and controller lifecycle",
        ),
        (
            "Write IPC already-applied snapshot authority IO graph",
            "agent-doc-orchestration/src/write/ipc.rs",
            "agent-doc-write-converge-io/src/lib.rs",
            "Split remaining transport delivery loops and test-only IPC repair fixtures",
        ),
        (
            "Write IPC reposition transport IO graph",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-ipc-io/src/lib.rs",
            "Split file-patch payload construction from socket send/fallback handling",
        ),
        (
            "Write IPC patch payload synthesis IO graph",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-write-ipc-io/src/lib.rs",
            "Split pure payload policy from file read/eprintln diagnostics",
        ),
        (
            "Write convergence test-wrapper re-export facade deletion",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-write-converge-io",
            "Move the remaining `write/converge.rs` fixture coverage",
        ),
        (
            "Write convergence fixture coverage relocation",
            "agent-doc-orchestration/src/write/converge.rs",
            "agent-doc-write-converge-io/src/convergence_fixture_tests.rs",
            "Split the test-only convergence effects adapter by durable sidecar family",
        ),
        (
            "Route pane-resolution test adapter delegation",
            "agent-doc-orchestration/src/route/pane_resolution.rs",
            "agent-doc-route-io/src/pane_resolution.rs::resolve_or_create_pane*",
            "Move the retained pane-resolution tests into `agent-doc-route-io`",
        ),
        (
            "Route tmux mock-agent test helper graph",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-test-support/src/lib.rs",
            "Move route startup and pane-resolution tests into focused route IO fixtures",
        ),
        (
            "Route integration suite relocation",
            "agent-doc-orchestration/tests/route.rs and agent-doc-orchestration/tests/route/*.rs",
            "agent-doc-route-io/tests/route.rs and agent-doc-route-io/tests/route/*.rs",
            "Split route startup and pane-resolution fixtures into narrower route IO and test-support suites",
        ),
        (
            "Orchestration workspace retirement",
            "agent-doc-orchestration/Cargo.toml",
            "Focused crates plus root `Cargo.toml` and `Makefile` without an active `agent-doc-orchestration` build/publish edge",
            "Delete the historical `agent-doc-orchestration` directory once stale guard tests and release archaeology references no longer need a sentinel path",
        ),
        (
            "Write/repair empty-response command-boundary inversion",
            "agent-doc-orchestration/src/write/run_entry.rs",
            "agent-doc-orchestration/src/repair.rs::run_write_command_with_empty_response_recovery",
            "Move replay/write callbacks out of repair behind a focused repair IO effects port",
        ),
        (
            "Route invocation state and entrypoint IO graph",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-route-io/src/invocation.rs",
            "Split `RouteCommandEffects` into document-write, closeout-drain, route-dispatch, queue-writeback, diagnostics, and startup ports",
        ),
        (
            "Route test-only invocation facade deletion",
            "retained `#[cfg(test)] pub fn run*` wrappers",
            "agent-doc-route-io/src/invocation.rs",
            "Move the remaining route startup and pane-resolution tests into `agent-doc-route-io`",
        ),
        (
            "Repair orphaned response replay/writeback IO graph",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-io/src/lib.rs",
            "The replay callback port is split",
        ),
        (
            "Repair orphaned response replay/writeback port split",
            "agent-doc-repair-io/src/lib.rs::RepairReplayWriteEffects",
            "agent-doc-repair-io::{RepairStrictReplayWriteEffects,RepairFallbackWriteEffects,RepairRecoveredQueueHeadEffects}",
            "Move the write command DTO/runtime into a focused write command crate",
        ),
        (
            "Repair template normalization IO graph",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-io/src/lib.rs",
            "Move `normalize_template_structure_or_fail_preserving` out of `RepairTemplateWriteEffects`",
        ),
        (
            "Git pre-stage response/prompt artifact repair IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/pre_stage_repair.rs",
            "Split `CommitPreStageRepairEffects` into snapshot store, document write, and op-log ports",
        ),
        (
            "Git guard-marker cleanup convergence IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/guard_marker_cleanup.rs",
            "Split this cleanup port into the broader git commit effects trait",
        ),
        (
            "Git boundary reposition IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/boundary_reposition.rs",
            "Split `BoundaryRepositionEffects` into active-run, snapshot-store, IPC delivery, and document-write ports",
        ),
        (
            "Git committed single-boundary invariant self-heal IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/boundary_invariant.rs",
            "Split `BoundaryInvariantEffects` into snapshot-store and log ports",
        ),
        (
            "Git transient worktree and closeout sidecar cleanup IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/transient_cleanup.rs",
            "Split `TransientCleanupEffects` into document-write, snapshot-store, sidecar-refresh, VCS-refresh, and log ports",
        ),
        (
            "Git postcommit worktree proof and IPC reposition safety IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/post_commit_cleanup.rs",
            "Split `PostCommitCleanupEffects` into read and log ports",
        ),
        (
            "Git already-committed closeout finalization IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/post_commit_cleanup.rs",
            "Split `PostCommitCleanupEffects` into lifecycle-log, flow-event, cycle-state, capture-state, queue-continuation, read, and log ports",
        ),
        (
            "Git successful commit reconciliation IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/post_commit_cleanup.rs",
            "Split `PostCommitCleanupEffects` into lifecycle-log, flow-event, cycle-state, capture-state, queue-continuation, session, hooks, read, and log ports",
        ),
        (
            "Git active capture materialization guard IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/capture_materialization_guard.rs",
            "Split `CaptureMaterializationGuardEffects` into capture-read, log, and closeout-guard ports",
        ),
        (
            "Git live-buffer precommit guard IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/live_buffer_guard.rs",
            "Split `LiveBufferGuardEffects` into debounce-read, log, and closeout-guard ports",
        ),
        (
            "Git post-commit local drift handoff IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/post_commit_cleanup.rs",
            "Split `PostCommitCleanupEffects` into lifecycle-log, flow-event, cycle-state, capture-state, queue-continuation, read, and log ports",
        ),
        (
            "Git commit result reporting IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-git-io/src/commit_result_reporting.rs",
            "Split stdout summary emission from ops-log writes",
        ),
        (
            "Git commit lifecycle coordinator IO graph",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-commit-io/src/lib.rs",
            "Split `CommitCoordinatorPorts` into commit admission, snapshot/head drift guard, pre-stage normalization, transaction, and post-commit cleanup ports",
        ),
        (
            "Git commit boundary test-suite relocation",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-orchestration/tests/git.rs",
            "Move the remaining commit-boundary tests into `agent-doc-commit-io` and focused `agent-doc-git-io` fixtures",
        ),
        (
            "Git commit integration suite relocation",
            "agent-doc-orchestration/tests/git.rs",
            "agent-doc-commit-io/tests/git.rs",
            "Split commit-boundary fixtures between `agent-doc-commit-io` and `agent-doc-git-io`",
        ),
        (
            "Git commit runtime facade deletion",
            "agent-doc-orchestration/src/git.rs",
            "agent-doc-commit-io/src/lib.rs",
            "Move the integration test suite from `agent-doc-orchestration/tests/git.rs` into focused `agent-doc-commit-io`/`agent-doc-git-io` fixtures",
        ),
        (
            "Preflight maintenance runtime write-effect adapter graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-runtime-io/src/lib.rs",
            "Split the runtime adapter once write command extraction lands",
        ),
        (
            "Preflight direct write-authority and template-normalization edge removal",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-document-realtime-io::atomic_write_through_authority",
            "relocate the write.rs template-normalization tests beside `agent-doc-template-io`",
        ),
        (
            "Repair empty-response recovery callback inversion",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-repair-io",
            "Split the remaining write-command replay bridge after `CommandOptions`/`CommitMode` leave `write.rs`",
        ),
        (
            "Route document-prep write-authority edge removal",
            "agent-doc-orchestration/src/route.rs",
            "agent-doc-document-realtime-io::{atomic_write_through_authority,RUNTIME_WRITE_CONVERGENCE_EFFECTS}",
            "Split direct route repair closeout from document-prep writes",
        ),
        (
            "Codex hook write-authority edge removal",
            "agent-doc-orchestration/src/codex_hook.rs",
            "agent-doc-document-realtime-io::RUNTIME_QUEUE_CONSUME_WRITEBACK_EFFECTS",
            "Split repeated-queue recovery note formatting from closeout side effects",
        ),
        (
            "Start idle-queue writeback edge removal",
            "agent-doc-orchestration/src/start.rs",
            "agent-doc-document-realtime-io::RUNTIME_QUEUE_CONSUME_WRITEBACK_EFFECTS",
            "Move idle queue completion into a focused start runtime IO adapter",
        ),
        (
            "Start command runtime extraction",
            "agent-doc-orchestration/src/start.rs",
            "agent-doc-start-runtime-io/src/{lib.rs,run.rs,idle_watch.rs,supervisor_io.rs}",
            "Split `SupervisorShared`, idle-watch queue completion",
        ),
        (
            "Write IPC transport convergence effect-provider edge removal",
            "agent-doc-orchestration/src/write/ipc/transport.rs",
            "agent-doc-document-realtime-io::RUNTIME_WRITE_CONVERGENCE_EFFECTS",
            "Move the remaining write IPC transport graph into focused write IPC runtime IO",
        ),
        (
            "Crate-root runtime write-provider edge removal",
            "agent-doc-orchestration/src/lib.rs",
            "agent-doc-document-realtime-io::{RUNTIME_WRITE_CONVERGENCE_EFFECTS,RUNTIME_QUEUE_CONSUME_WRITEBACK_EFFECTS,atomic_write_through_authority,record_document_write_provenance}",
            "Move the remaining repair write-replay adapter after `write.rs` exits orchestration",
        ),
        (
            "Write runtime effect facade deletion",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-document-realtime-io::{RUNTIME_WRITE_CONVERGENCE_EFFECTS,RUNTIME_QUEUE_CONSUME_WRITEBACK_EFFECTS}",
            "Move remaining write command runtime sequencing into focused command IO crates",
        ),
        (
            "Write public write-authority facade deletion",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-document-realtime-io::{atomic_write_through_authority,record_document_write_provenance}",
            "Move remaining CLI document-write adapters to focused command IO crates",
        ),
        (
            "Write required-closeout facade demotion",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-flow-io::closeout::complete_required_closeout",
            "Split write command commit-boundary sequencing after write command DTO extraction",
        ),
        (
            "Write run_command facade demotion",
            "agent-doc-orchestration/src/write.rs::run_command",
            "agent-doc-orchestration/src/repair.rs::run_write_command_with_empty_response_recovery",
            "Move write command runtime sequencing into focused command IO",
        ),
        (
            "Write run_entry public facade demotion",
            "`pub use run_entry::*` plus public",
            "crate-visible helpers behind",
            "Move write command runtime sequencing into focused command IO",
        ),
        (
            "WriteFlags public DTO demotion",
            "agent-doc-orchestration/src/write.rs::WriteFlags",
            "crate-visible `WriteFlags`",
            "Move write command runtime sequencing into focused command IO",
        ),
        (
            "Repair runtime recovery callback IO graph",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-runtime-io/src/lib.rs",
            "move the remaining strict empty-response bridge after write command DTO extraction",
        ),
        (
            "Repair coordinator direct-call edge removal",
            "agent-doc-orchestration/src/{lib.rs,preflight.rs,preflight/run.rs,codex_hook.rs,route.rs}",
            "agent-doc-repair-io::{run,run_with_queue_completion_ids,repair}",
            "Move the remaining `OrchestrationRepairReplayWriteEffects` write-replay adapter after `write.rs` exits orchestration",
        ),
        (
            "Repair run facade deletion",
            "agent-doc-orchestration/src/repair.rs::run",
            "agent-doc-repair-io::run",
            "Move or delete the remaining public `repair`",
        ),
        (
            "Template response prompt-order repair IO graph",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-template-io::repair_response_prompt_order_for_file",
            "Move the remaining response-precedes-prompt rejection guard",
        ),
        (
            "Direct-run compaction diff guard IO graph",
            "agent-doc-orchestration/src/lib.rs",
            "agent-doc-run-io::guard_no_exchange_compaction_request_for_diff",
            "Move the write-path `guard_no_exchange_compaction_request_between` tests",
        ),
        (
            "Write command request DTO graph",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-write-command-io/src/lib.rs",
            "Move the write command runtime/replay entrypoints",
        ),
        (
            "Write strict empty-response repair back-edge removal",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-repair-io::recover_empty_response_for_strict_closeout",
            "Move the write-command empty-response recovery bridge",
        ),
        (
            "Write command runtime crate extraction",
            "agent-doc-orchestration/src/write.rs",
            "agent-doc-write-runtime-io/src/{lib.rs,run_entry.rs,ipc.rs,ipc/transport.rs}",
            "Split `agent-doc-write-runtime-io` into command entry, repair replay/apply, visible-write convergence, and test-fixture modules",
        ),
        (
            "Repair replay write-runtime adapter extraction",
            "agent-doc-orchestration/src/repair.rs::OrchestrationRepairReplayWriteEffects",
            "agent-doc-write-runtime-io::REPAIR_REPLAY_WRITE_EFFECTS",
            "Move the remaining public repair command bridge",
        ),
        (
            "Repair command bridge extraction",
            "agent-doc-orchestration/src/repair.rs::{repair,run_write_command_with_empty_response_recovery}",
            "agent-doc-repair-command-io/src/lib.rs",
            "Relocate the repair integration tests out of `agent-doc-orchestration/src/repair.rs`",
        ),
        (
            "Repair test-only source module deletion",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-command-io/tests/repair.rs",
            "Split long-running repair fixtures between `agent-doc-repair-io`, `agent-doc-repair-runtime-io`, and `agent-doc-repair-command-io`",
        ),
        (
            "Preflight command runtime extraction",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-command-io/src/{lib.rs,run.rs}",
            "Split cycle-completion effect wiring",
        ),
        (
            "Preflight output DTO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Split linked-document change detection and output assembly",
        ),
        (
            "Preflight linked-document change detection IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Move output assembly callers onto the focused linked-change detector",
        ),
        (
            "Preflight claims-log IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Split claim-log path discovery from destructive truncation",
        ),
        (
            "Preflight baseline content IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Split baseline path resolution from disk/model writes",
        ),
        (
            "Preflight explicit backlog target requirement IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Split cross-document review reads from tracked-work fingerprint extraction",
        ),
        (
            "Repair recovery coordinator IO graph",
            "agent-doc-orchestration/src/repair.rs",
            "agent-doc-repair-io/src/lib.rs",
            "Split `RepairCoordinatorEffects` into replay-write, closeout, session-check, pending/capture source selection, and empty-response recovery ports",
        ),
        (
            "Preflight cycle-completion coordinator and runtime effects",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Split `PreflightCycleCompletionEffects` into repair, commit, session-inspection, and bypassed-response evidence ports",
        ),
        (
            "Preflight IPC dogfood note append IO graph",
            "agent-doc-orchestration/src/preflight.rs",
            "agent-doc-preflight-io/src/lib.rs",
            "Split dogfood-root detection, latest diagnostic lookup, exchange note synthesis/dedupe, atomic file write, and ops-log marker",
        ),
        (
            "Codex hook user-prompt-submit tracking IO graph",
            "agent-doc-orchestration/src/codex_hook.rs",
            "agent-doc-codex-hook-io/src/lib.rs",
            "Move Stop-hook decision policy behind an explicit effect port",
        ),
    ] {
        let row_text = ledger_rows
            .iter()
            .find(|cells| cells.first().copied() == Some(graph))
            .map(|cells| cells.join(" | "))
            .unwrap_or_else(|| panic!("coarse extraction tracker is missing a row for {graph}"));
        for required in [graph, moved_from, moved_to, follow_up] {
            assert!(
                row_text.contains(required),
                "coarse extraction tracker is missing {required:?} for {graph}"
            );
        }
    }
}

#[test]
fn test_agent_doc_session_check_io_owns_guard_adapters() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-session-check-io")),
        "agent-doc-session-check-io must stay a first-class workspace crate"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    assert!(
        orchestration["dependencies"]
            .as_table()
            .unwrap()
            .contains_key("agent-doc-session-check-io"),
        "orchestration should depend on the focused session-check IO crate"
    );

    for old_path in [
        "agent-doc-orchestration/src/session_check/backlog_guards.rs",
        "agent-doc-orchestration/src/session_check/partial_staging.rs",
        "agent-doc-orchestration/src/session_check/queue_head_guards.rs",
        "agent-doc-orchestration/src/session_check/queue_head_provenance_guards.rs",
        "agent-doc-orchestration/src/session_check/detect.rs",
        "agent-doc-orchestration/src/session_check/pending_guards.rs",
        "agent-doc-orchestration/src/session_check/closeout_guards.rs",
        "agent-doc-orchestration/src/session_check/response_guards.rs",
    ] {
        assert!(
            !manifest_dir.join(old_path).exists(),
            "orchestration must not keep moved session-check guard adapter source: {old_path}"
        );
    }

    for new_path in [
        "agent-doc-session-check-io/src/backlog_guards.rs",
        "agent-doc-session-check-io/src/partial_staging.rs",
        "agent-doc-session-check-io/src/queue_head_guards.rs",
        "agent-doc-session-check-io/src/queue_head_provenance_guards.rs",
        "agent-doc-session-check-io/src/guard_modes.rs",
        "agent-doc-session-check-io/src/prompt_bearing.rs",
        "agent-doc-session-check-io/src/detect.rs",
        "agent-doc-session-check-io/src/pending_capture.rs",
        "agent-doc-session-check-io/src/pending_guards.rs",
        "agent-doc-session-check-io/src/closeout_guards.rs",
        "agent-doc-session-check-io/src/response_guards.rs",
    ] {
        assert!(
            manifest_dir.join(new_path).exists(),
            "focused session-check IO crate must own moved guard adapter source: {new_path}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/session_check.rs")
            .exists(),
        "orchestration must not keep the moved session_check source module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/tests/session_check.rs")
            .exists(),
        "orchestration must not keep the moved session_check integration suite"
    );
    let session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/tests/session_check.rs"))
            .unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod session_check;")
            && !orchestration_lib.contains("mod session_check;")
            && !orchestration_lib.contains("pub fn session_check_effects()")
            && !orchestration_lib.contains(
                "impl agent_doc_session_check_io::SessionCheckEffects for OrchestrationSessionCheckEffects"
            ),
        "orchestration must delete the session_check source shim and runtime SessionCheckEffects port"
    );
    let closeout_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-closeout-runtime-io/src/lib.rs")).unwrap();
    assert!(
        closeout_runtime.contains("pub fn session_check_effects()")
            && closeout_runtime.contains(
                "impl agent_doc_session_check_io::SessionCheckEffects for RuntimeSessionCheckEffects"
            ),
        "agent-doc-closeout-runtime-io should own the session-check runtime effects port"
    );
    for production_source in [
        "src/main.rs",
        "src/mcp.rs",
        "agent-doc-codex-stop-io/src/lib.rs",
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-preflight-command-io/src/run.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(production_source)).unwrap();
        assert!(
            !source.contains("crate::session_check::")
                && !source.contains("agent_doc_orchestration::session_check::"),
            "{production_source} must call agent-doc-session-check-io directly instead of the orchestration session_check facade"
        );
    }
    for forbidden in [
        "pub use agent_doc_session_check_io",
        "pub fn run_with_options(",
        "pub fn inspect(",
        "pub fn inspect_with_warnings(",
        "pub fn enforce_clean_closeout(",
        "mod backlog_guards;",
        "mod partial_staging;",
        "mod queue_head_guards;",
        "mod queue_head_provenance_guards;",
        "mod detect;",
        "mod pending_guards;",
        "mod closeout_guards;",
        "mod response_guards;",
    ] {
        assert!(
            !session_check.contains(forbidden),
            "moved orchestration session_check test must not retain moved guard module facade: {forbidden}"
        );
    }
    for required in [
        "agent_doc_session_check_io::inspect(",
        "agent_doc_session_check_io::inspect_with_warnings(",
        "&agent_doc_closeout_runtime_io::session_check_effects()",
        "agent_doc_session_check_io::run_with_options(",
        "agent_doc_session_check_io::enforce_clean_closeout(",
    ] {
        assert!(
            session_check.contains(required),
            "moved orchestration session-check tests should call focused command IO directly: {required}"
        );
    }
    let closeout_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/closeout_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub fn first_unstarted_prompt_bearing_change(",
        "pub fn detect_unstarted_prompt_bearing_diff(",
    ] {
        assert!(
            !closeout_guards.contains(forbidden),
            "session-check closeout guards must not retain moved prompt-bearing IO adapter: {forbidden}"
        );
    }
    let session_check_command =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    assert!(
        session_check_command.contains("crate::check_shadow_backlog_guard")
            && session_check_command.contains("crate::check_free_text_queue_head_provenance")
            && session_check_command.contains("crate::check_parent_submodule_pointer_guard")
            && session_check_command.contains("crate::check_prompt_only_exchange_tail_guard")
            && session_check_command.contains("crate::check_pending_capture_guard")
            && session_check_command.contains("crate::check_pending_done_guard")
            && session_check_command.contains("crate::check_blocked_closeout_followup_guard")
            && session_check_command.contains("crate::check_dropped_exchange_prompt_guard")
            && session_check.contains("realtime_steering_since_turn_baseline"),
        "session-check command IO should call the focused guard adapters directly"
    );
    assert!(
        session_check_command.contains("crate::resolve_current_document_content")
            && session_check_command.contains("\"latest_head_response_missing\"")
            && !session_check_command.contains("std::fs::read_to_string(file)"),
        "session-check command should route committed-response visibility checks through current-document authority"
    );
    assert!(
        session_check_command
            .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)")
            && !session_check_command.contains("agent_doc_cycle_state_io::load(file)?"),
        "session-check command should read closeout phase/capture decisions through the projection-aware cycle loader"
    );

    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    assert!(
        !write_source.contains("crate::session_check::resolve_"),
        "write.rs must not route guard-mode resolvers through orchestration session_check"
    );
    let pending_write_checks = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/write_pending_checks.rs"),
    )
    .unwrap();
    let pending_write_checks_prod = pending_write_checks
        .split("#[cfg(test)]")
        .next()
        .expect("write_pending_checks production section");
    for required in [
        "crate::resolve_pending_capture_mode_with_force_disk",
        "crate::resolve_pending_done_mode_with_force_disk",
        "crate::resolve_review_done_guard_mode",
        "state.tracked_work_maintenance_required_at_preflight",
        "agent_doc_document::tracked_work_projection::tracked_work_maintenance_required(content)",
    ] {
        assert!(
            pending_write_checks.contains(required),
            "focused write pending checks should call crate-local guard-mode resolver: {required}"
        );
    }
    assert!(
        !pending_write_checks.contains("agent_doc_session_check_io::resolve_")
            && !pending_write_checks.contains("crate::session_check::resolve_"),
        "focused write pending checks must not route guard-mode resolvers through orchestration"
    );
    assert!(
        !pending_write_checks_prod.contains("std::fs::read_to_string(file)")
            && !pending_write_checks_prod.contains("fs::read_to_string(file)"),
        "focused write pending checks must not probe the active session document on disk in production"
    );
}

#[test]
fn test_agent_doc_flow_io_owns_closeout_effect_adapter() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-flow-io")),
        "agent-doc-flow-io must stay a first-class workspace crate"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod flow;")
            && !orchestration_lib.contains("mod flow;")
            && !orchestration_lib.contains("pub fn closeout_effects()")
            && !orchestration_lib.contains(
                "impl agent_doc_flow_io::closeout::CloseoutEffects for OrchestrationCloseoutEffects"
            ),
        "orchestration must delete the flow source module and runtime CloseoutEffects port"
    );
    let closeout_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-closeout-runtime-io/src/lib.rs")).unwrap();
    assert!(
        closeout_runtime.contains("pub fn closeout_effects()")
            && closeout_runtime.contains(
                "impl agent_doc_flow_io::closeout::CloseoutEffects for RuntimeCloseoutEffects"
            )
            && closeout_runtime.contains("pub static REPAIR_IO_EFFECTS"),
        "agent-doc-closeout-runtime-io should own closeout and repair runtime effects ports"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow")
            .exists(),
        "orchestration must not keep a test-only flow source module"
    );

    let closeout_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/tests/flow_closeout.rs")).unwrap();
    assert!(
        !closeout_tests.contains("crate::")
            && closeout_tests.contains("agent_doc_flow_io::closeout::")
            && closeout_tests.contains("agent_doc_closeout_runtime_io::closeout_effects()"),
        "moved closeout boundary tests should call flow-io directly through the focused closeout runtime effects port"
    );

    let flow_events =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/tests/flow_events.rs")).unwrap();
    assert!(
        flow_events.contains("agent_doc_flow::types")
            && !flow_events.contains("agent_doc_orchestration::flow"),
        "flow event coverage should live as an integration test without an orchestration flow module"
    );

    for production_source in [
        "src/main.rs",
        "src/session_actor_cmd.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(production_source)).unwrap();
        assert!(
            !source.contains("crate::flow::")
                && !source.contains("agent_doc_orchestration::flow::"),
            "{production_source} must call agent-doc-flow-io directly with the root closeout effects port instead of the orchestration flow facade"
        );
    }
}

#[test]
fn test_document_realtime_io_owns_pipeline_frontmatter_runtime_effects() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "PIPELINE_FRONTMATTER_EFFECTS",
        "PipelineFrontmatterEffects",
        "RUNTIME_PIPELINE_FRONTMATTER_EFFECTS as PIPELINE_FRONTMATTER_EFFECTS",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration root must not re-export pipeline-frontmatter runtime effects: {forbidden}"
        );
    }

    let document_realtime_io =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    for required in [
        "pub struct RuntimePipelineFrontmatterEffects",
        "pub static RUNTIME_PIPELINE_FRONTMATTER_EFFECTS",
        "impl agent_doc_cycle_state_io::pipeline_frontmatter::PipelineFrontmatterEffects",
        "fn read_current_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "try_resolve_current_document_content(file, source)",
    ] {
        assert!(
            document_realtime_io.contains(required),
            "document realtime IO must own pipeline-frontmatter runtime effects: {required}"
        );
    }

    let pipeline_frontmatter = fs::read_to_string(
        manifest_dir.join("agent-doc-cycle-state-io/src/pipeline_frontmatter.rs"),
    )
    .unwrap();
    for required in [
        "fn read_current_document_content(&self, file: &Path, source: &str) -> Result<String>;",
        "effects.read_current_document_content(file, \"pipeline_mirror\")",
        "effects.read_current_document_content(file, \"pipeline_clear\")",
    ] {
        assert!(
            pipeline_frontmatter.contains(required),
            "cycle-state pipeline frontmatter must read current content through the effects port: {required}"
        );
    }
    for forbidden in ["std::fs::read_to_string(file)", "fs::read_to_string(file)"] {
        assert!(
            !pipeline_frontmatter.contains(forbidden),
            "cycle-state pipeline frontmatter must not read the active document directly: {forbidden}"
        );
    }

    let cycle_state_io =
        fs::read_to_string(manifest_dir.join("agent-doc-cycle-state-io/src/lib.rs")).unwrap();
    let cycle_state_prod = cycle_state_io.split("#[cfg(test)]").next().unwrap();
    for required in [
        "append_phase_event_to_session_log(file, &state, file_content)",
        "fn append_phase_event_to_session_log(file: &Path, state: &CycleState, file_content: Option<&str>)",
    ] {
        assert!(
            cycle_state_prod.contains(required),
            "cycle-state phase logging must use caller-supplied current content: {required}"
        );
    }
    assert!(
        !cycle_state_prod.contains("std::fs::read_to_string(file)")
            && !cycle_state_prod.contains("fs::read_to_string(file)"),
        "cycle-state production code must not read the active document directly for phase logging"
    );

    fn collect_rs_files(dir: &Path, files: &mut Vec<PathBuf>) {
        if !dir.exists() {
            return;
        }
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, files);
            } else if path.extension().and_then(|extension| extension.to_str()) == Some("rs") {
                files.push(path);
            }
        }
    }

    let mut orchestration_files = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut orchestration_files);
    for focused_path in [
        "agent-doc-commit-io/tests/git.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-route-io/tests/route/startup.rs",
        "agent-doc-route-io/tests/route/pane_resolution.rs",
        "agent-doc-session-check-io/tests/session_check.rs",
    ] {
        orchestration_files.push(manifest_dir.join(focused_path));
    }
    let mut saw_focused_runtime_effects = false;
    for path in orchestration_files {
        let source = fs::read_to_string(&path).unwrap();
        assert!(
            !source.contains("agent_doc_orchestration::PIPELINE_FRONTMATTER_EFFECTS")
                && !source.contains("crate::PIPELINE_FRONTMATTER_EFFECTS"),
            "{} must use document realtime IO directly instead of the orchestration pipeline-frontmatter facade",
            path.display()
        );
        saw_focused_runtime_effects |=
            source.contains("agent_doc_document_realtime_io::RUNTIME_PIPELINE_FRONTMATTER_EFFECTS");
    }
    assert!(
        saw_focused_runtime_effects,
        "orchestration call sites that need pipeline-frontmatter runtime effects should import document realtime IO directly"
    );
}

#[test]
fn test_agent_doc_workflow_owns_cross_cutting_workflow_kernel() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-workflow")),
        "agent-doc-workflow must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-workflow-io")),
        "agent-doc-workflow-io must stay a first-class workspace crate for workflow proof ledger IO"
    );
    assert!(
        manifest_dir.join("agent-doc-workflow/src/lib.rs").exists(),
        "cross-cutting workflow policy should live in the focused workflow crate"
    );

    let workflow_source =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/lib.rs")).unwrap();
    for required in [
        "pub mod autofix;",
        "pub mod invariants;",
        "pub mod doctor;",
        "pub mod doctor_json;",
        "pub mod orchestrate_tasks;",
        "pub mod preflight_policy;",
        "pub mod session_cycle;",
        "pub enum WorkflowEvidenceKind",
        "pub enum WorkflowProof",
        "pub enum WorkflowMutation",
        "pub enum WorkflowDecision",
        "pub struct WorkflowTransition",
        "pub fn decide_stale_supervisor",
        "pub fn decide_queue_drainability",
        "pub fn decide_captured_response",
        "pub fn decide_live_buffer",
    ] {
        assert!(
            workflow_source.contains(required),
            "agent-doc-workflow must own workflow kernel policy: {required}"
        );
    }
    let session_cycle_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/session_cycle.rs")).unwrap();
    let preflight_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/preflight_policy.rs"))
            .unwrap();
    for required in [
        "pub struct PreflightPolicyWarning",
        "pub fn post_exchange_comment_prompt_preset_warning(",
        "pub fn preset_item_id_collision_warning(",
        "pub fn format_ipc_dogfood_note(",
        "pub fn is_url(",
        "pub fn url_cache_path(",
        "pub fn html_to_markdown(",
        "pub fn is_html_content(",
    ] {
        assert!(
            preflight_policy.contains(required),
            "agent-doc-workflow must own pure preflight policy: {required}"
        );
    }
    for required in [
        "pub enum SessionExecutionScope",
        "pub enum FinalizePendingMutationKind",
        "pub struct FinalizePendingMutation",
        "pub fn prompt_targets_from_changes",
        "pub fn prompt_targets_from_diff",
        "pub fn compute_user_intent_prompt_changes",
        "pub fn derive_turn_scope",
        "pub fn exchange_node_count",
        "pub fn resolve_driver_address",
        "pub fn extract_target_id",
        "pub fn component_occurrence_from_node_key",
        "pub fn classify_execution_scope",
        "pub fn finalize_command",
        "pub struct FinalizeRerunCommand",
        "pub fn finalize_rerun_command_base",
        "pub fn shell_quote_cli_arg",
        "pub fn compact_command_hint",
        "pub fn pending_kept_open_ids_from_mutations",
        "pub fn group_pending_add_targets",
        "pub fn parse_id_order",
        "pub fn parse_tracked_work_edits",
    ] {
        assert!(
            session_cycle_policy.contains(required),
            "agent-doc-workflow must own session-cycle workflow policy: {required}"
        );
    }
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    assert!(
        write_source.contains("use agent_doc_workflow::session_cycle::{")
            && write_source.contains("FinalizeRerunCommand")
            && write_source.contains("compact_command_hint")
            && write_source.contains("finalize_rerun_command_base")
            && write_source.contains("group_pending_add_targets")
            && write_source.contains("parse_id_order")
            && write_source.contains("parse_tracked_work_edits")
            && write_source.contains("pending_kept_open_ids_from_mutations"),
        "write.rs should call focused session-cycle command/tracked-work policy directly"
    );
    for forbidden in [
        "fn build_rerun_command_base(",
        "fn shell_quote_cli_arg(",
        "fn compact_command_hint(",
        "fn pending_kept_open_ids_from_options(",
        "fn grouped_pending_add_to(",
        "fn parse_id_order(",
        "fn parse_tracked_work_edits(",
    ] {
        assert!(
            !write_source.contains(forbidden),
            "write.rs must not re-own or facade session-cycle command/tracked-work policy: {forbidden}"
        );
    }
    let workflow_invariants =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/invariants.rs")).unwrap();
    for required in [
        "pub struct WorkflowInvariantCatalog",
        "pub enum WorkflowInvariantId",
        "pub enum FactSourceKind",
        "pub enum RemediationAction",
        "pub const fn as_str(self) -> &'static str",
        "pub fn accepts_autofix_command(self, command: &str) -> bool",
        "pub fn workflow_invariant_catalog",
        "pub fn workflow_invariant_catalog_json",
    ] {
        assert!(
            workflow_invariants.contains(required),
            "agent-doc-workflow must own workflow invariant catalog policy: {required}"
        );
    }

    let workflow_doctor =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/doctor.rs")).unwrap();
    let workflow_doctor_json =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/doctor_json.rs")).unwrap();
    for required in [
        "WORKFLOW_DOCTOR_SCHEMA_VERSION",
        "pub enum WorkflowDoctorOutcome",
        "pub struct WorkflowDoctorReport",
        "pub struct WorkflowDoctorFacts",
        "pub struct PreflightDoctorFacts",
        "pub struct SessionCheckDoctorFacts",
        "pub struct CycleStateDoctorFacts",
        "pub struct OpsLogDoctorFacts",
        "pub struct ActorDoctorFacts",
        "pub struct GitDoctorFacts",
        "pub struct EditorDoctorFacts",
        "pub struct WorkflowInvariantResult",
        "pub fn evaluate_catalog",
        "pub fn format_text_report",
        "pub fn ops_log_facts_from_content",
        "pub fn classify_ops_marker",
    ] {
        assert!(
            workflow_doctor.contains(required),
            "agent-doc-workflow must own workflow doctor policy API: {required}"
        );
    }
    for required in [
        "pub fn project_preflight_facts(",
        "pub fn project_session_check_facts(",
        "pub fn lookup_value",
        "pub fn lookup_bool",
        "pub fn lookup_usize",
        "pub fn lookup_string",
        "pub fn lookup_string_array",
    ] {
        assert!(
            workflow_doctor_json.contains(required),
            "agent-doc-workflow must own workflow doctor JSON projection policy: {required}"
        );
    }
    let workflow_io_doctor =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/doctor.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/doctor.rs")
            .exists(),
        "workflow doctor IO must not remain in orchestration"
    );
    for forbidden in [
        "WORKFLOW_DOCTOR_SCHEMA_VERSION",
        "pub enum WorkflowDoctorOutcome",
        "pub struct WorkflowDoctorReport",
        "pub struct WorkflowDoctorFacts",
        "pub struct PreflightDoctorFacts",
        "pub struct SessionCheckDoctorFacts",
        "pub struct CycleStateDoctorFacts",
        "pub struct OpsLogDoctorFacts",
        "pub struct ActorDoctorFacts",
        "pub struct GitDoctorFacts",
        "pub struct EditorDoctorFacts",
        "pub struct WorkflowInvariantResult",
        "pub fn evaluate_catalog",
        "fn evaluate_queue_continuation",
        "fn evaluate_stale_supervisor",
        "fn evaluate_closeout_commit",
        "fn evaluate_editor_convergence",
        "fn evaluate_generation_redirect",
        "fn evaluate_parent_gitlink",
        "fn closeout_repair_commands",
        "fn safe_commands",
        "fn operator_steps",
        "fn remediation_label",
        "fn has_marker",
        "fn ops_log_facts_from_content(",
        "fn classify_ops_marker(",
        "fn print_text_report(",
        "fn format_text_report(",
        "fn lookup_value",
        "fn lookup_bool",
        "fn lookup_usize",
        "fn lookup_string",
        "fn lookup_string_array",
        "pub use agent_doc_workflow::doctor_json",
        "pub fn classify_ops_marker(",
        "pub use agent_doc_workflow::doctor",
        "pub(crate) use agent_doc_workflow::doctor",
    ] {
        assert!(
            !workflow_io_doctor.contains(forbidden),
            "workflow IO doctor must gather facts, not re-own workflow doctor policy: {forbidden}"
        );
    }
    assert!(
        workflow_io_doctor.contains("use agent_doc_workflow::doctor::{")
            && workflow_io_doctor.contains("evaluate_catalog")
            && workflow_io_doctor.contains("format_text_report")
            && workflow_io_doctor.contains("ops_log_facts_from_content")
            && workflow_io_doctor.contains("pub trait WorkflowDoctorEffects")
            && workflow_io_doctor
                .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)"),
        "workflow IO doctor should own fact IO and call focused doctor policy through injected live effects"
    );
    assert!(
        !workflow_io_doctor.contains("agent_doc_cycle_state_io::load(file)"),
        "workflow doctor cycle facts should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        workflow_io_doctor.contains("use agent_doc_workflow::doctor_json::{")
            && workflow_io_doctor.contains("project_preflight_facts")
            && workflow_io_doctor.contains("project_session_check_facts"),
        "workflow IO doctor should call focused doctor JSON projection directly"
    );
    let workflow_io_autofix =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/autofix.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/autofix.rs")
            .exists(),
        "workflow autofix IO must not remain in orchestration"
    );
    let workflow_autofix =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/autofix.rs")).unwrap();
    for required in [
        "WORKFLOW_AUTOFIX_SCHEMA_VERSION",
        "pub struct WorkflowAutofixReport",
        "pub enum WorkflowAutofixStepStatus",
        "pub struct WorkflowAutofixStep",
        "pub fn operation_key(&self) -> String",
        "pub fn plan_autofix_steps(",
        "fn build_step(",
        "fn repair_command(",
        "accepts_autofix_command",
    ] {
        assert!(
            workflow_autofix.contains(required),
            "agent-doc-workflow must own pure workflow autofix planning: {required}"
        );
    }
    assert!(
        workflow_io_autofix.contains("use agent_doc_workflow::autofix::{")
            && workflow_io_autofix.contains("WorkflowAutofixReport")
            && workflow_io_autofix.contains("WorkflowAutofixStep")
            && workflow_io_autofix.contains("WorkflowAutofixStepStatus")
            && workflow_io_autofix.contains("plan_autofix_steps"),
        "workflow IO autofix should consume focused workflow autofix planning directly"
    );
    assert!(
        workflow_io_autofix.contains("use crate::proof_ledger::{")
            && workflow_io_autofix.contains("append_operation_proof")
            && workflow_io_autofix.contains("read_operation_proofs"),
        "workflow IO autofix should consume focused workflow proof ledger IO directly"
    );
    for forbidden in [
        "fn is_whitelisted_autofix(",
        "fn action_name(",
        "pub struct WorkflowAutofixReport",
        "pub enum WorkflowAutofixStepStatus",
        "pub struct WorkflowAutofixStep",
        "fn plan_autofix_steps(",
        "fn build_step(",
        "fn repair_command(",
        "WorkflowDoctorFacts, evaluate_catalog",
        "RemediationAction::RestartSupervisorOnce =>",
        "RemediationAction::FinalizeOrWriteCommit =>",
    ] {
        assert!(
            !workflow_io_autofix.contains(forbidden),
            "workflow IO autofix must not re-own workflow remediation action policy: {forbidden}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow")
            .exists(),
        "orchestration must not keep a flow source module for workflow/session-cycle facades"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "pub use agent_doc_workflow::session_cycle",
        "SessionExecutionScope",
        "FinalizePendingMutation",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration lib must not re-export session-cycle workflow policy: {forbidden}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/workflow_state.rs")
            .exists(),
        "orchestration must not keep a workflow_state module after extraction"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/workflow_invariants.rs")
            .exists(),
        "orchestration must not keep a workflow_invariants module after extraction"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/proof_ledger.rs")
            .exists(),
        "orchestration must not keep a proof_ledger module after extraction"
    );
    let workflow_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/lib.rs")).unwrap();
    assert!(
        workflow_io_lib.contains("pub mod convergence_playback;")
            && workflow_io_lib.contains("pub mod proof_ledger;")
            && workflow_io_lib.contains("pub mod doctor;")
            && workflow_io_lib.contains("pub mod autofix;"),
        "agent-doc-workflow-io must expose workflow storage modules through their owning modules"
    );
    let workflow_proof_ledger =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/proof_ledger.rs")).unwrap();
    for required in [
        "pub enum ProofOperationKind",
        "pub enum ProofOutcome",
        "pub enum ProofEvidenceKind",
        "pub struct OperationProofRecord",
        "pub struct OperationProofInput",
        "pub fn proof_ledger_path(",
        "pub fn append_operation_proof(",
        "pub fn read_operation_proofs(",
    ] {
        assert!(
            workflow_proof_ledger.contains(required),
            "agent-doc-workflow-io must own workflow proof ledger IO: {required}"
        );
    }
    let workflow_convergence_playback =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/convergence_playback.rs"))
            .unwrap();
    for required in [
        "pub struct IpcAttempt",
        "pub struct ConvergencePlayback",
        "pub fn playback_artifact_path(",
        "pub fn write_convergence_playback(",
        "pub fn blocked_boundary_ops_message(",
        "pub fn record_blocked_boundary_with_logger(",
        "agent_doc_fs::document_state_hash",
        "agent_doc_fs::find_project_root",
    ] {
        assert!(
            workflow_convergence_playback.contains(required),
            "agent-doc-workflow-io must own convergence playback artifact IO: {required}"
        );
    }
    for forbidden in [
        "crate::ops_log",
        "agent-doc-orchestration",
        "agent_doc_orchestration",
    ] {
        assert!(
            !workflow_convergence_playback.contains(forbidden),
            "agent-doc-workflow-io convergence playback must not reach into orchestration: {forbidden}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/convergence_playback.rs")
            .exists(),
        "orchestration must not keep a convergence_playback facade module"
    );
    let orchestration_start_idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    assert!(
        orchestration_start_idle_watch
            .contains("agent_doc_workflow_io::convergence_playback::ConvergencePlayback::new(")
            && orchestration_start_idle_watch.contains(
                "agent_doc_workflow_io::convergence_playback::record_blocked_boundary_with_logger("
            )
            && orchestration_start_idle_watch.contains("agent_doc_ops_log_io::log_op"),
        "orchestration idle-watch should inject ops-log into focused convergence playback IO"
    );
    assert!(
        !orchestration_start_idle_watch.contains("crate::convergence_playback::"),
        "orchestration idle-watch must not call a convergence_playback facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/session_cycle.rs")
            .exists(),
        "orchestration must not keep a session_cycle flow facade"
    );
    let flow_types = fs::read_to_string(manifest_dir.join("agent-doc-flow/src/types.rs")).unwrap();
    assert!(
        flow_types.contains("pub struct SessionCycleStep")
            && flow_types.contains("pub fn session_cycle_event("),
        "agent-doc-flow should own session-cycle flow event vocabulary"
    );
    for forbidden in [
        "pub enum SessionExecutionScope",
        "pub enum FinalizePendingMutationKind",
        "pub struct FinalizePendingMutation",
        "pub fn prompt_targets_from_changes",
        "fn extract_prompt_targets(",
        "pub fn classify_execution_scope",
        "pub fn finalize_command",
        "pub use agent_doc_workflow::session_cycle",
        "agent_doc_workflow::session_cycle::SessionExecutionScope",
        "agent_doc_workflow::session_cycle::FinalizePendingMutation",
    ] {
        assert!(
            !flow_types.contains(forbidden),
            "orchestration must not define or re-export session-cycle workflow policy: {forbidden}"
        );
    }
    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    assert!(
        preflight_run.contains("agent_doc_workflow::session_cycle::prompt_targets_from_changes"),
        "preflight should call focused session-cycle workflow policy directly"
    );
    assert!(
        preflight_run.contains("use agent_doc_workflow::session_cycle::{")
            && preflight_run.contains("compute_user_intent_prompt_changes")
            && preflight_run.contains("derive_turn_scope"),
        "preflight should call focused turn-scope and user-intent workflow policy directly"
    );
    let sqlite_op_log =
        fs::read_to_string(manifest_dir.join("agent-doc-sqlite/src/op_log.rs")).unwrap();
    assert!(
        sqlite_op_log.contains("pub fn append_semantic_diff_ops(")
            && sqlite_op_log.contains("agent_doc_turn::op_log::build_ops_from_semantic_diff")
            && sqlite_op_log.contains("agent_doc_log_time::current_epoch_secs()")
            && sqlite_op_log.contains("append_ops(project_root, &ops)"),
        "agent-doc-sqlite should own semantic-diff durable op-log persistence"
    );
    let preflight_mod =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn post_exchange_comment_prompt_preset_warning(",
        "fn preset_item_id_collision_warning(",
        "fn format_ipc_dogfood_note(",
        "fn append_ipc_dogfood_note_to_content(",
        "fn is_url(",
        "fn url_cache_path(",
        "fn html_to_markdown(",
        "fn is_html_content(",
    ] {
        assert!(
            !preflight_mod.contains(forbidden) && !preflight_run.contains(forbidden),
            "orchestration preflight must not re-own pure preflight policy: {forbidden}"
        );
    }
    assert!(
        preflight_mod.contains("agent_doc_workflow::preflight_policy::")
            && preflight_run.contains("agent_doc_workflow::preflight_policy::"),
        "orchestration preflight should call focused workflow preflight policy directly"
    );
    for forbidden in [
        "pub(crate) fn compute_user_intent_prompt_changes",
        "pub(crate) fn derive_turn_scope",
        "pub(crate) fn exchange_node_count",
        "pub(crate) fn resolve_driver_address",
        "pub(crate) fn extract_target_id",
        "pub(crate) fn component_occurrence_from_node_key",
        "compute_user_intent_prompt_changes, derive_turn_scope",
        "pub(crate) use semantic_diff::*",
    ] {
        assert!(
            !sqlite_op_log.contains(forbidden) && !preflight_mod.contains(forbidden),
            "orchestration preflight must not re-own or re-export session-cycle workflow policy: {forbidden}"
        );
    }
    let plan_source = fs::read_to_string(manifest_dir.join("src/plan.rs")).unwrap();
    assert!(
        plan_source.contains("use agent_doc_workflow::session_cycle::{")
            && plan_source.contains("classify_execution_scope")
            && plan_source.contains("finalize_command")
            && plan_source.contains("prompt_targets_from_changes"),
        "plan.rs should call focused session-cycle workflow policy directly"
    );
    assert!(
        !plan_source.contains("agent_doc_orchestration::flow::session_cycle::"),
        "plan.rs must not route session-cycle workflow policy through orchestration"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt_contract.rs")
            .exists(),
        "orchestration must not keep a prompt_contract module for session-cycle policy facades"
    );
    let prompt_context =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-context-io/src/lib.rs")).unwrap();
    assert!(
        prompt_context.contains("use agent_doc_workflow::session_cycle::prompt_targets_from_diff;")
            && prompt_context.contains("prompt_targets_from_diff(diff_text)")
            && !prompt_context.contains("fn extract_prompt_targets("),
        "prompt-context IO should call focused prompt-target extraction directly"
    );
    for relative_path in [
        "agent-doc-workflow-io/src/doctor.rs",
        "agent-doc-workflow-io/src/autofix.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_workflow::invariants::")
                && source.contains("workflow_invariant_catalog"),
            "{relative_path} should call the focused workflow invariant catalog API directly"
        );
    }

    let workflow_orchestrate_tasks =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/orchestrate_tasks.rs"))
            .unwrap();
    for required in [
        "pub struct ExchangeTaskSourceFingerprint",
        "pub struct ResolvedTaskBatch",
        "pub struct ExecutionTask",
        "pub struct DagTask",
        "pub fn extract_tasks_from_text(",
        "pub fn merge_task_batch(",
        "pub fn extend_task_batch_from_text(",
        "pub fn find_exchange_task_source(",
        "pub fn parse_list_item(",
        "pub fn normalize_task(",
        "pub fn parse_dag_task_line(",
        "pub fn resolve_dag_tasks(",
        "pub fn plan_dag_execution(",
        "pub fn scope_exchange_tail(",
        "pub fn apply_prompt_preset_block(",
        "pub fn append_worker_result_line(",
    ] {
        assert!(
            workflow_orchestrate_tasks.contains(required),
            "agent-doc-workflow must own orchestrate task parsing/DAG policy: {required}"
        );
    }
    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    for forbidden in [
        "struct ExchangeTaskSourceFingerprint",
        "struct ResolvedTaskBatch",
        "struct ExchangeTaskSourceBlock",
        "struct ExecutionTask",
        "struct DagTask",
        "struct DagMetadata",
        "fn extract_tasks_from_text(",
        "fn merge_task_batch(",
        "fn extend_task_batch_from_text(",
        "fn collect_fenced_task_blocks(",
        "fn collect_markdown_list_blocks(",
        "fn collect_markdown_list_source_blocks(",
        "fn contains_ordered_subsequence(",
        "fn find_exchange_task_source(",
        "fn parse_list_item(",
        "fn normalize_task(",
        "fn parse_dag_task_line(",
        "fn resolve_dag_tasks(",
        "fn plan_dag_execution(",
        "fn scope_exchange_tail(",
        "fn apply_prompt_preset_block(",
        "fn append_worker_result_line(",
        "pub use agent_doc_workflow::orchestrate_tasks",
        "pub(crate) use agent_doc_workflow::orchestrate_tasks",
    ] {
        assert!(
            !orchestrate_source.contains(forbidden),
            "src/orchestrate.rs must not re-own or facade orchestrate task parsing/DAG policy: {forbidden}"
        );
    }
    assert!(
        orchestrate_source.contains("use agent_doc_workflow::orchestrate_tasks::{")
            && orchestrate_source.contains("extract_tasks_from_text")
            && orchestrate_source.contains("merge_task_batch")
            && orchestrate_source.contains("extend_task_batch_from_text")
            && orchestrate_source.contains("find_exchange_task_source")
            && orchestrate_source.contains("parse_dag_task_line")
            && orchestrate_source.contains("resolve_dag_tasks")
            && orchestrate_source.contains("plan_dag_execution")
            && orchestrate_source.contains("scope_exchange_tail")
            && orchestrate_source.contains("apply_prompt_preset_block")
            && orchestrate_source.contains("append_worker_result_line"),
        "src/orchestrate.rs should call focused orchestrate task policy directly"
    );

    let workflow_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&workflow_manifest).unwrap();
    let dependencies = parsed
        .get("dependencies")
        .and_then(toml::Value::as_table)
        .cloned()
        .unwrap_or_default();
    for expected in [
        "agent-doc-diff",
        "agent-doc-element-backlog",
        "agent-doc-element-queue",
        "agent-doc-frontmatter",
        "agent-doc-hash",
        "agent-doc-markdown-ast",
        "agent-doc-prompt-contract",
        "agent-doc-queue",
        "agent-doc-turn",
        "anyhow",
        "htmd",
        "indexmap",
        "serde",
        "serde_json",
    ] {
        assert!(
            dependencies.contains_key(expected),
            "agent-doc-workflow may use focused pure-policy dependency: {expected}"
        );
    }
    assert!(
        dependencies.keys().all(|dependency| matches!(
            dependency.as_str(),
            "agent-doc-diff"
                | "agent-doc-element-backlog"
                | "agent-doc-element-queue"
                | "agent-doc-frontmatter"
                | "agent-doc-hash"
                | "agent-doc-markdown-ast"
                | "agent-doc-prompt-contract"
                | "agent-doc-queue"
                | "agent-doc-turn"
                | "anyhow"
                | "htmd"
                | "indexmap"
                | "serde"
                | "serde_json"
        )),
        "agent-doc-workflow should remain pure and free of orchestration, git, editor IPC, sqlite, or tmux dependencies"
    );
    let workflow_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/Cargo.toml")).unwrap();
    let workflow_io: toml::Value = toml::from_str(&workflow_io_manifest).unwrap();
    let workflow_io_dependencies = workflow_io["dependencies"].as_table().unwrap();
    assert!(
        workflow_io_dependencies.contains_key("agent-doc-fs")
            && workflow_io_dependencies.contains_key("agent-doc-hash"),
        "agent-doc-workflow-io pathing should depend on focused filesystem/hash helpers"
    );
    for forbidden in ["agent-doc-core", "agent-doc-orchestration"] {
        assert!(
            !workflow_io_dependencies.contains_key(forbidden),
            "agent-doc-workflow-io must not depend on removed core/orchestration facades: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_workflow_owns_session_check_response_messages() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workflow_session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/session_check.rs")).unwrap();
    for required in [
        "pub fn dropped_queue_prompt_guard_result(",
        "pub fn queue_response_contamination_guard_result(",
        "pub fn queue_response_contamination_candidates(",
        "pub fn dropped_exchange_prompt_guard_result(",
        "pub fn completed_pending_reap_guard_message(",
        "pub fn snapshot_committed_guard_message(",
        "pub fn committed_without_response_body_guard_message(",
        "pub fn partial_closeout_state_guard_result(",
        "pub struct PartialStagingCloseoutGuardFinding",
        "pub fn partial_staging_closeout_guard_result(",
    ] {
        assert!(
            workflow_session_check.contains(required),
            "agent-doc-workflow must own session-check response message policy: {required}"
        );
    }

    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    for forbidden in [
        "user-authored agent:queue edit(s) were dropped during an IPC",
        "agent:queue contains assistant response prose copied",
        "user-authored exchange prompt(s) were dropped during an IPC",
        "document still contains completed tracked item(s) after closeout",
        "cycle state is committed but the snapshot does not match HEAD",
        "cycle committed binary-owned work this turn but no assistant",
    ] {
        assert!(
            !response_guards.contains(forbidden),
            "response_guards must not re-own session-check response message policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_workflow::session_check::dropped_queue_prompt_guard_result",
        "agent_doc_workflow::session_check::queue_response_contamination_guard_result",
        "agent_doc_workflow::session_check::dropped_exchange_prompt_guard_result",
        "agent_doc_workflow::session_check::completed_pending_reap_guard_message",
        "agent_doc_workflow::session_check::snapshot_committed_guard_message",
        "agent_doc_workflow::session_check::committed_without_response_body_guard_message",
    ] {
        assert!(
            response_guards.contains(required),
            "response_guards should call focused workflow message policy directly: {required}"
        );
    }

    let partial_staging =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/partial_staging.rs"))
            .unwrap();
    for forbidden in [
        "[session-check] warn: partial `do [#id]` closeout",
        "[session-check] hint: narrow the backlog item",
        "possible partial staging closeout",
        "additional partial staging candidate(s) omitted",
        "commit the companion changes",
        "fn preview_items(",
    ] {
        assert!(
            !partial_staging.contains(forbidden),
            "partial_staging must not re-own session-check response message policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_workflow::session_check::partial_closeout_state_guard_result",
        "agent_doc_workflow::session_check::PartialStagingCloseoutGuardFinding",
        "agent_doc_workflow::session_check::partial_staging_closeout_guard_result",
    ] {
        assert!(
            partial_staging.contains(required),
            "partial_staging should call focused workflow message policy directly: {required}"
        );
    }
}

#[test]
fn test_agent_doc_diff_owns_partial_staging_pure_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    for required in [
        "pub struct PartialStagingCompanionFinding",
        "pub fn partial_staging_companion_finding(",
        "pub fn is_partial_staging_relevant_path",
        "pub fn partial_staging_paths_look_related",
        "pub fn extract_changed_string_literals",
        "pub fn first_bare_prompt_prefix_target_before_marker",
    ] {
        assert!(
            diff_source.contains(required),
            "agent-doc-diff must own partial-staging pure diff/path policy: {required}"
        );
    }

    let partial_staging =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/partial_staging.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn is_partial_staging_relevant_path",
        "pub(crate) fn partial_staging_paths_look_related",
        "pub(crate) fn path_looks_test_like",
        "pub(crate) fn extract_changed_string_literals",
        "pub(crate) fn extract_string_literals_from_line",
        "pub(crate) fn interesting_changed_literal",
        "agent_doc_diff::partial_staging_companion_finding(",
        "agent_doc_diff::is_partial_staging_relevant_path",
        "agent_doc_diff::partial_staging_paths_look_related",
        "agent_doc_diff::extract_changed_string_literals",
        ".intersection(&dirty_literals)",
    ] {
        assert!(
            !partial_staging.contains(forbidden),
            "session_check partial-staging must stay an adapter, not re-own pure diff/path policy"
        );
    }
    let git_io_partial_staging =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/partial_staging.rs")).unwrap();
    assert!(
        git_io_partial_staging.contains("agent_doc_diff::partial_staging_companion_finding(")
            && partial_staging.contains("agent_doc_git_io::partial_staging::companion_findings("),
        "git IO should compose focused diff classifier output and session_check should call that adapter"
    );
}

#[test]
fn test_agent_doc_diff_owns_truncation_pure_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    for required in [
        "pub fn extract_last_added_line(",
        "pub fn looks_truncated(",
        "pub fn truncate_for_log(",
    ] {
        assert!(
            diff_source.contains(required),
            "agent-doc-diff must own pure truncation policy: {required}"
        );
    }

    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-diff-io\""),
        "workspace should include agent-doc-diff-io as the focused diff IO crate"
    );

    let diff_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-diff-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn extract_last_added_line(",
        "fn looks_truncated(",
        "fn truncate_for_log(",
        "use similar::{ChangeTag, TextDiff};",
    ] {
        assert!(
            !diff_io_source.contains(forbidden),
            "diff_io must stay a file/editor wait adapter, not re-own pure truncation policy: {forbidden}"
        );
    }
    for required in [
        "pub trait DocumentBaselineStore",
        "pub fn compute_with_current<S: DocumentBaselineStore + ?Sized>",
        "snapshots.resolve(doc)?.unwrap_or_default()",
        "snapshots.checkpoint(doc, &current)?",
        "wait_for_stable_content(doc, &previous, live)?",
        "agent_doc_diff::{",
    ] {
        assert!(
            diff_io_source.contains(required),
            "diff_io should call focused diff truncation helpers directly: {required}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/diff_io.rs")
            .exists(),
        "orchestration must not keep a diff_io facade module"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod diff_io"),
        "orchestration must not expose diff_io as a module facade"
    );
    let snapshot_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    for required in [
        "pub struct DiffBaselineStore",
        "pub const fn new(logger: fn(&Path, &str)) -> Self",
        "impl agent_doc_diff_io::DocumentBaselineStore for DiffBaselineStore",
        "resolve(doc)",
        "checkpoint_document_baseline(doc, content, self.logger)",
    ] {
        assert!(
            snapshot_io_source.contains(required),
            "agent-doc-snapshot-io should own the focused diff snapshot-store adapter: {required}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/snapshot.rs")
            .exists(),
        "orchestration must not keep a snapshot facade module"
    );
    for (relative, required_call, required_store) in [
        (
            "agent-doc-preflight-command-io/src/run.rs",
            "agent_doc_diff_io::compute_with_current(",
            "agent_doc_snapshot_io::DiffBaselineStore::new(",
        ),
        (
            "agent-doc-run-io/src/lib.rs",
            "agent_doc_diff_io::compute(",
            "agent_doc_snapshot_io::DiffBaselineStore::new(",
        ),
        (
            "agent-doc-stream-io/src/lib.rs",
            "agent_doc_diff_io::compute(",
            "agent_doc_snapshot_io::DiffBaselineStore::new(",
        ),
        (
            "src/main.rs",
            "agent_doc_diff_io::run(",
            "agent_doc_snapshot_io::DiffBaselineStore::new(",
        ),
        (
            "src/plan.rs",
            "agent_doc_diff_io::compute(",
            "agent_doc_snapshot_io::DiffBaselineStore::new(",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(required_call) && source.contains(required_store),
            "{relative} should call focused diff IO directly with the snapshot store"
        );
    }
    for forbidden in [
        "diff_io::compute",
        "crate::diff_io",
        "agent_doc_orchestration::diff_io",
        "agent_doc_debounce::",
        "extract_last_added_line",
        "looks_truncated",
        "truncate_for_log",
        "unified_diff_from_contents",
        "is_stale_snapshot",
    ] {
        assert!(
            !snapshot_io_source.contains(forbidden),
            "snapshot IO must not re-own diff IO policy: {forbidden}"
        );
    }

    let diff_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-diff-io/Cargo.toml")).unwrap();
    for dependency in [
        "agent-doc-debounce",
        "agent-doc-diff",
        "agent-doc-fs",
        "agent-doc-hash",
    ] {
        assert!(
            diff_io_manifest.contains(dependency),
            "agent-doc-diff-io should declare focused dependency {dependency}"
        );
    }
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-git-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
    ] {
        assert!(
            !diff_io_manifest.contains(forbidden),
            "agent-doc-diff-io must not depend on orchestration-side systems: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_diff_owns_unstarted_prompt_bearing_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    for required in [
        "pub fn prompt_bearing_body_for_unstarted_prompt_guard",
        "pub fn strip_queue_components_for_unstarted_prompt_guard",
        "pub fn prompt_target_is_immediately_before_existing_response",
        "pub fn first_unstarted_prompt_bearing_change_from_diff",
    ] {
        assert!(
            diff_source.contains(required),
            "agent-doc-diff must own unstarted prompt-bearing diff policy: {required}"
        );
    }

    let closeout_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/closeout_guards.rs"))
            .unwrap();
    let baseline_comparison = fs::read_to_string(
        manifest_dir.join("agent-doc-document-realtime/src/baseline_comparison.rs"),
    )
    .unwrap();
    let prompt_bearing_io =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/prompt_bearing.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn strip_queue_components_for_unstarted_prompt_guard",
        "pub(crate) fn prompt_target_is_immediately_before_existing_response",
        "fn strip_queue_components_for_unstarted_prompt_guard",
        "fn prompt_target_is_immediately_before_existing_response",
    ] {
        assert!(
            !closeout_guards.contains(forbidden),
            "session_check closeout guards must not re-own unstarted prompt-bearing policy"
        );
    }
    for required in [
        "agent_doc_diff::prompt_bearing_body_for_unstarted_prompt_guard",
        "agent_doc_diff::first_unstarted_prompt_bearing_change_from_diff",
    ] {
        assert!(
            baseline_comparison.contains(required),
            "realtime baseline comparison should call the focused diff helper directly: {required}"
        );
    }
    for required in [
        "agent_doc_cycle_state_io::load_document_projection",
        "projected_open_turn_steering_set",
        "RealtimeSteeringSet::from_turn_projection",
        "agent_doc_document_realtime::baseline_comparison::BaselineComparison::new",
        ".realtime_steering_all()",
    ] {
        assert!(
            prompt_bearing_io.contains(required),
            "session-check prompt-bearing IO should consume the controller observable set and delegate only the actorless fallback to realtime baseline comparison: {required}"
        );
    }
    assert!(
        !prompt_bearing_io.contains(".realtime_steering()"),
        "session-check must not independently recompute a second single-steering projection"
    );
}

#[test]
fn test_agent_doc_diff_uses_current_prompt_bearing_api_names() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    for forbidden in [
        "pub fn extract_required_response_blocks(",
        "pub fn format_required_response_targets(",
        "extract_required_response_blocks(",
        "format_required_response_targets(",
    ] {
        assert!(
            !diff_source.contains(forbidden),
            "agent-doc-diff must use current prompt-bearing names, not deprecated compatibility wrappers: {forbidden}"
        );
    }
    for required in [
        "fn extract_prompt_target_blocks(",
        "pub fn format_prompt_bearing_changes(",
    ] {
        assert!(
            diff_source.contains(required),
            "agent-doc-diff should expose current prompt-bearing policy names: {required}"
        );
    }
}

#[test]
fn test_preflight_output_uses_user_intent_prompt_changes_json_surface() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();

    assert!(
        preflight_source
            .contains("pub user_intent_prompt_changes: Vec<agent_doc_diff::PromptBearingChange>"),
        "PreflightOutput must expose user_intent_prompt_changes as the prompt JSON surface"
    );
    for forbidden in [
        "pub prompt_bearing_changes: Vec<agent_doc_diff::PromptBearingChange>",
        "rename = \"prompt_bearing_changes\"",
        "alias = \"prompt_bearing_changes\"",
    ] {
        assert!(
            !preflight_source.contains(forbidden),
            "PreflightOutput must not expose the removed prompt_bearing_changes JSON field: {forbidden}"
        );
    }
    assert!(
        !preflight_run_source.contains("\n        prompt_bearing_changes,\n"),
        "preflight run must not populate the removed prompt_bearing_changes JSON field"
    );
}

#[test]
fn test_agent_doc_preflight_io_owns_linked_doc_change_detection_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();

    for forbidden in [
        "fn links_cache_dir(",
        "fn check_url_link(",
        "fn check_linked_docs(",
        "fn recent_commit_summary(",
        "ureq::Agent",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight must not own linked-doc change detection IO: {forbidden}"
        );
    }
    for required in [
        "pub fn links_cache_dir(",
        "pub fn check_url_link(",
        "pub fn check_linked_docs(",
        "pub fn recent_commit_summary(",
        "agent_doc_frontmatter::frontmatter",
        "agent_doc_git_io::revision::last_commit_mtime",
        "agent_doc_git_io::revision::recent_commit_lines",
        "agent_doc_workflow::preflight_policy::url_cache_path",
        "ureq::Agent",
    ] {
        assert!(
            preflight_io.contains(required),
            "agent-doc-preflight-io must own linked-doc change detection IO: {required}"
        );
    }
    assert!(
        preflight_io_manifest.contains("ureq ="),
        "agent-doc-preflight-io should own URL fetch dependency for linked-doc detection"
    );
}

#[test]
fn test_agent_doc_preflight_io_owns_claims_log_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();

    for forbidden in [
        "fn claims_log_path(",
        "fn read_claims(",
        "fn read_and_truncate_claims(",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight must not own claims-log IO: {forbidden}"
        );
    }
    assert!(
        orchestration_preflight_run.contains("read_claims(file)")
            && orchestration_preflight_run.contains("read_and_truncate_claims(file)"),
        "preflight/run should call focused claims-log IO helpers directly"
    );
    for required in [
        "pub fn claims_log_path(",
        "pub fn read_claims(",
        "pub fn read_and_truncate_claims(",
        "agent_doc_project_root_io::project_root_containing",
        ".agent-doc/claims.log",
    ] {
        assert!(
            preflight_io.contains(required),
            "agent-doc-preflight-io must own claims-log IO: {required}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_io_owns_baseline_content_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();

    assert!(
        !orchestration_preflight.contains("fn checkpoint_baseline_content("),
        "orchestration preflight must not own baseline content IO"
    );
    assert!(
        orchestration_preflight_run.contains("checkpoint_baseline_content(file,")
            && orchestration_preflight_run.contains("checkpoint_baseline_content(&doc,"),
        "preflight/run should call focused baseline content IO directly"
    );
    for required in [
        "pub fn checkpoint_baseline_content(",
        "agent_doc_snapshot_io::checkpoint_document_baseline(",
        "agent_doc_ops_log_io::log_op",
    ] {
        assert!(
            preflight_io.contains(required),
            "agent-doc-preflight-io must own baseline content IO: {required}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_io_owns_explicit_backlog_target_requirement_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();

    assert!(
        !orchestration_preflight.contains("fn explicit_backlog_target_requirements("),
        "orchestration preflight must not own explicit backlog target requirement IO"
    );
    assert!(
        orchestration_preflight_run.contains("explicit_backlog_target_requirements(file,"),
        "preflight/run should call focused explicit backlog target requirement IO directly"
    );
    for required in [
        "pub fn explicit_backlog_target_requirements(",
        "agent_doc_frontmatter_io::session::parse_for_file",
        "agent_doc_frontmatter_io::security_review::enforce_cross_document_review",
        "agent_doc_document::tracked_work_projection::tracked_work_fingerprint",
        "agent_doc_cycle_state_io::BacklogTargetRequirement",
    ] {
        assert!(
            preflight_io.contains(required),
            "agent-doc-preflight-io must own explicit backlog target requirement IO: {required}"
        );
    }
    assert!(
        preflight_io_manifest.contains("agent-doc-frontmatter-io ="),
        "agent-doc-preflight-io should own frontmatter IO dependency for cross-document target requirements"
    );
}

#[test]
fn test_agent_doc_diff_owns_post_exchange_comment_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    for required in [
        "pub fn post_exchange_ordinary_html_comments",
        "pub fn post_exchange_comment_directive_signals",
    ] {
        assert!(
            diff_source.contains(required),
            "agent-doc-diff must own post-exchange comment directive policy: {required}"
        );
    }

    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let workflow_preflight_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/preflight_policy.rs"))
            .unwrap();
    for forbidden in [
        "fn post_exchange_ordinary_html_comments",
        "fn comment_is_user_note",
        "fn post_exchange_comment_directive_signals",
        "fn first_word",
        "fn looks_like_slash_command",
    ] {
        assert!(
            !preflight_source.contains(forbidden),
            "preflight must not re-own post-exchange comment directive policy: {forbidden}"
        );
    }
    for required in [
        "agent_doc_diff::post_exchange_ordinary_html_comments",
        "agent_doc_diff::post_exchange_comment_directive_signals",
    ] {
        assert!(
            workflow_preflight_policy.contains(required),
            "workflow preflight policy should call the focused diff comment policy directly: {required}"
        );
    }
    assert!(
        preflight_source.contains(
            "agent_doc_workflow::preflight_policy::post_exchange_comment_prompt_preset_warning",
        ),
        "orchestration preflight should call the focused workflow warning policy directly"
    );
}

#[test]
fn test_agent_doc_diff_owns_semantic_diff_summary_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    assert!(
        diff_source.contains("pub mod semantic;"),
        "agent-doc-diff should expose semantic diff policy from a focused module"
    );

    let semantic_source =
        fs::read_to_string(manifest_dir.join("agent-doc-diff/src/semantic.rs")).unwrap();
    for required in [
        "pub struct SemanticDiffSummary",
        "pub enum SemanticComponentOp",
        "pub struct SemanticComponentChange",
        "pub struct SemanticNavTarget",
        "pub struct SemanticNodeEvent",
        "pub struct SemanticPromptChange",
        "pub fn semantic_diff_summary(",
        "pub fn semantic_component_changes(",
        "pub fn semantic_frontmatter_change(",
        "pub fn frontmatter_span(",
        "pub fn semantic_nav_target(",
        "pub fn semantic_line_at(",
        "pub fn semantic_node_event_kind(",
        "pub fn semantic_preview(",
    ] {
        assert!(
            semantic_source.contains(required),
            "agent-doc-diff must own semantic diff summary policy: {required}"
        );
    }

    let diff_manifest = fs::read_to_string(manifest_dir.join("agent-doc-diff/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&diff_manifest).unwrap();
    let dependencies = parsed
        .get("dependencies")
        .and_then(toml::Value::as_table)
        .cloned()
        .unwrap_or_default();
    assert!(
        dependencies.contains_key("agent-doc-markdown-ast"),
        "agent-doc-diff should own semantic AST projection via a focused dependency"
    );

    let preflight_mod =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    for forbidden in [
        "pub struct SemanticDiffSummary",
        "pub enum SemanticComponentOp",
        "pub struct SemanticComponentChange",
        "pub struct SemanticNavTarget",
        "pub struct SemanticNodeEvent",
        "pub struct SemanticPromptChange",
        "pub(crate) fn semantic_diff_summary(",
        "pub(crate) fn semantic_component_changes(",
        "pub(crate) fn semantic_frontmatter_change(",
        "pub(crate) fn frontmatter_span(",
        "pub(crate) fn semantic_nav_target(",
        "pub(crate) fn semantic_line_at(",
        "pub(crate) fn semantic_node_event_kind(",
        "pub(crate) fn semantic_preview(",
    ] {
        assert!(
            !preflight_mod.contains(forbidden) && !preflight_run.contains(forbidden),
            "orchestration preflight must not re-own semantic diff summary policy: {forbidden}"
        );
    }
    assert!(
        !preflight_mod.contains("semantic_diff_summary,"),
        "orchestration preflight must not re-export semantic_diff_summary as a facade"
    );

    assert!(
        preflight_run.contains("use agent_doc_diff::semantic::semantic_diff_summary;"),
        "preflight run should call the focused semantic diff builder directly"
    );
    let orchestration_run_source = manifest_dir.join("agent-doc-orchestration/src/run.rs");
    assert!(
        !orchestration_run_source.exists(),
        "orchestration run source module should stay deleted after direct-run test relocation"
    );
    let direct_run_tests =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/tests/direct_run.rs")).unwrap();
    let run_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    assert!(
        !direct_run_tests.contains("agent_doc_diff::semantic::semantic_diff_summary("),
        "orchestration direct-run tests must not retain the owner-pane semantic diff policy call"
    );
    assert!(
        run_io_source.contains("agent_doc_diff::semantic::semantic_diff_summary("),
        "agent-doc-run-io should call the focused semantic diff builder directly"
    );
}

#[test]
fn test_project_config_io_tmux_helpers_have_no_config_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-project-config-io")),
        "agent-doc-project-config-io must stay a first-class workspace crate"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/config.rs")
            .exists(),
        "orchestration must not keep global config as a module facade"
    );

    let project_config_source =
        fs::read_to_string(manifest_dir.join("agent-doc-project-config-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn load_project()",
        "pub fn load_project_for_doc(",
        "pub fn project_root_for_doc(",
        "pub fn agent_doc_bug_target_document_for_doc(",
        "pub fn load_project_from(",
        "pub fn project_tmux_session()",
        "pub fn save_project(",
        "pub fn save_project_to(",
        "pub fn update_project_tmux_session(",
        "pub fn clear_project_tmux_session()",
        "agent_doc_fs::find_project_root",
        "agent_doc_fs::referenced_markdown_path_checked",
    ] {
        assert!(
            project_config_source.contains(required_snippet),
            "agent-doc-project-config-io must own file-backed project config helper: {required_snippet}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/project_config_io.rs")
            .exists(),
        "orchestration must not keep project_config_io as an adapter module or facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod project_config_io"),
        "orchestration must not expose project_config_io as a module facade"
    );

    for relative in [
        "src/session_cmd.rs",
        "src/orchestrate.rs",
        "src/describe_image.rs",
        "src/plan.rs",
        "src/patch.rs",
        "agent-doc-frontmatter-io/src/session.rs",
        "agent-doc-template-io/src/lib.rs",
        "agent-doc-lint-io/src/lib.rs",
        "agent-doc-run-context-io/src/lib.rs",
        "agent-doc-claim-io/src/lib.rs",
        "agent-doc-route-io/src/diagnostics.rs",
        "agent-doc-route-io/src/session_resolution.rs",
        "agent-doc-sync-io/src/resync.rs",
        "agent-doc-sync-io/src/sync.rs",
        "agent-doc-session-check-io/src/guard_modes.rs",
        "agent-doc-supervisor-io/src/config.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-start-runtime-io/src/supervisor_io.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_project_config_io"),
            "{relative} should call project config IO through agent-doc-project-config-io directly"
        );
        for forbidden_snippet in [
            "agent_doc_orchestration::project_config_io",
            "crate::project_config_io",
            "pub use agent_doc_project_config_io",
            "pub use crate::project_config_io",
            "use crate::project_config_io",
            "use crate::{project_config_io",
            "config::project_tmux_session",
            "config::clear_project_tmux_session",
            "config::update_project_tmux_session",
            "crate::config::project_tmux_session",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must not route project-config IO through orchestration or config: {forbidden_snippet}"
            );
        }
    }
    let session_accretion =
        fs::read_to_string(manifest_dir.join("agent-doc-session-accretion-io/src/lib.rs")).unwrap();
    assert!(
        session_accretion.contains("agent_doc_project_config_io::load_project_for_doc(file)"),
        "session-accretion IO should consume project config through focused project-config IO"
    );

    let root_manifest: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-project-config-io"),
        "the CLI crate must depend on the focused project-config IO crate directly"
    );
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-project-config-io"),
        "orchestration must depend on the focused project-config IO crate directly"
    );

    let focused_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-project-config-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&focused_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in ["agent-doc-frontmatter", "agent-doc-fs", "toml"] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-project-config-io should depend on {required} for project config IO"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-project-config-io must stay free of core, orchestration, git, editor IPC, sqlite, and tmux-router dependencies"
        );
    }

    let closeout_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/closeout_guards.rs"))
            .unwrap();
    assert!(
        !closeout_guards.contains("pub(crate) fn first_bare_prompt_prefix_target_before_marker"),
        "session_check closeout guards must not re-own marker-scoped prompt-prefix diff slicing"
    );
    let document_drift =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/document_drift.rs")).unwrap();
    assert!(
        document_drift.contains("agent_doc_diff::first_bare_prompt_prefix_target_before_marker"),
        "agent-doc-turn document drift should call the focused diff helper directly"
    );
    assert!(
        closeout_guards
            .contains("agent_doc_turn::document_drift::detect_bypassed_response_write_between",),
        "session_check closeout guards should adapt current-document IO into the focused document-drift classifier"
    );
}

#[test]
fn test_global_config_has_no_orchestration_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-config")),
        "agent-doc-config must stay a first-class workspace crate"
    );

    let config_source =
        fs::read_to_string(manifest_dir.join("agent-doc-config/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub enum ExecutionMode",
        "pub struct Config",
        "pub struct TerminalConfig",
        "pub struct AgentConfig",
        "pub fn load()",
        "fn config_path()",
        "CodexNetworkAccess",
        "ModelConfig",
    ] {
        assert!(
            config_source.contains(required_snippet),
            "agent-doc-config must own global config vocabulary and loading: {required_snippet}"
        );
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod config"),
        "orchestration must not expose global config as a module facade"
    );

    for relative in [
        "src/main.rs",
        "src/init.rs",
        "src/orchestrate.rs",
        "src/session_actor_cmd.rs",
        "src/terminal.rs",
        "agent-doc-agent-io/src/agent/mod.rs",
        "agent-doc-agent-io/src/agent/codex.rs",
        "agent-doc-run-context-io/src/lib.rs",
        "agent-doc-harness/src/lib.rs",
        "agent-doc-run-io/tests/direct_run.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-stream-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_config"),
            "{relative} should call global config through agent-doc-config directly"
        );
        for forbidden_snippet in [
            "agent_doc_orchestration::config",
            "crate::config::",
            "use crate::config",
            "use crate::{config",
            "pub use agent_doc_config",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must not route global config through orchestration: {forbidden_snippet}"
            );
        }
    }

    let root_manifest: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-config"),
        "the CLI crate must depend on the focused global config crate directly"
    );
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-config"),
        "orchestration must depend on the focused global config crate directly"
    );

    let focused_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-config/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&focused_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-frontmatter",
        "agent-doc-model-tier",
        "serde",
        "toml",
    ] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-config should depend on {required} for global config parsing"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-config must stay free of core, orchestration, git, editor IPC, sqlite, and tmux-router dependencies"
        );
    }
}

#[test]
fn test_agent_doc_frontmatter_owns_cross_document_security_review_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-frontmatter-io")),
        "agent-doc-frontmatter-io must stay a first-class workspace crate for frontmatter file/path adapters"
    );

    let frontmatter_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/lib.rs")).unwrap();
    let security_review =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/security_review.rs"))
            .unwrap();

    assert!(
        frontmatter_lib.contains("pub mod security_review;"),
        "agent-doc-frontmatter should expose focused security-review policy"
    );
    for required in [
        "pub enum SecurityReviewSubject",
        "pub struct CrossDocumentSecurityReviewDecision",
        "pub fn cross_document_security_review_decision(",
        "CollaborationMode::Shared",
        "has_security_review()",
    ] {
        assert!(
            security_review.contains(required),
            "agent-doc-frontmatter must own cross-document security-review policy: {required}"
        );
    }

    let frontmatter_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter-io/src/lib.rs")).unwrap();
    let frontmatter_io_security =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter-io/src/security_review.rs"))
            .unwrap();
    assert!(
        frontmatter_io_lib.contains("pub mod security_review;"),
        "agent-doc-frontmatter-io should expose the focused security-review file/path adapter"
    );
    for required in [
        "pub fn enforce_cross_document_review(",
        "agent_doc_frontmatter::security_review::{",
        "cross_document_security_review_decision",
        "SecurityReviewSubject",
        "agent_doc_fs::same_document_path",
    ] {
        assert!(
            frontmatter_io_security.contains(required),
            "agent-doc-frontmatter-io must own the effectful cross-document security-review wrapper: {required}"
        );
    }
    for forbidden in [
        "CollaborationMode::Shared",
        "has_security_review()",
        "pub fn cross_document_security_review_decision(",
        "pub enum SecurityReviewSubject",
        "pub struct CrossDocumentSecurityReviewDecision",
        "pub use agent_doc_frontmatter::security_review",
        "pub(crate) use agent_doc_frontmatter::security_review",
    ] {
        assert!(
            !frontmatter_io_security.contains(forbidden),
            "agent-doc-frontmatter-io security review must adapt paths/errors, not re-own or facade frontmatter security-review policy: {forbidden}"
        );
    }

    let orchestration_security_path = manifest_dir.join("agent-doc-orchestration/src/security.rs");
    assert!(
        !orchestration_security_path.exists(),
        "orchestration must not keep security.rs as a frontmatter security-review adapter or facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod security"),
        "orchestration must not expose security as a module facade"
    );
    for relative in ["src/extract.rs", "agent-doc-preflight-io/src/lib.rs"] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(
                "agent_doc_frontmatter_io::security_review::enforce_cross_document_review"
            ),
            "{relative} should call the focused frontmatter-io security-review wrapper directly"
        );
        for forbidden in [
            "agent_doc_orchestration::security",
            "crate::security::enforce_cross_document_review",
            "security::enforce_cross_document_review",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not route cross-document security review through orchestration security: {forbidden}"
            );
        }
    }

    let frontmatter_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&frontmatter_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in ["agent-doc-frontmatter", "agent-doc-fs", "anyhow"] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-frontmatter-io should depend on {required} for cross-document security review adapters"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-frontmatter-io security-review adapter must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }

    let frontmatter_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&frontmatter_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-frontmatter security-review policy must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_agent_doc_frontmatter_owns_lint_mode_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let frontmatter_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/lib.rs")).unwrap();
    let lint_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/lint.rs")).unwrap();

    assert!(
        frontmatter_lib.contains("pub mod lint;"),
        "agent-doc-frontmatter should expose focused lint mode policy"
    );
    for required in [
        "pub enum LintCliMode",
        "pub enum LintModeSource",
        "pub const fn dialect_label",
        "pub fn resolve_lint_mode(",
        "\"strict\" | \"error\"",
        "LintModeSource::ProjectConfig",
    ] {
        assert!(
            lint_policy.contains(required),
            "agent-doc-frontmatter must own lint mode policy: {required}"
        );
    }

    let frontmatter_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&frontmatter_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-frontmatter lint mode policy must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }

    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let workspace_members = root["workspace"]["members"].as_array().unwrap();
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-lint-io")),
        "agent-doc-lint-io must be a workspace member"
    );
    let root_dependencies = root["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-lint-io"),
        "root crate should depend on focused lint IO crate directly"
    );

    let lint_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-lint-io/Cargo.toml")).unwrap();
    let lint_manifest: toml::Value = toml::from_str(&lint_manifest).unwrap();
    let lint_dependencies = lint_manifest["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-document-realtime-io",
        "agent-doc-frontmatter",
        "agent-doc-project-config-io",
        "anyhow",
        "tagpath",
    ] {
        assert!(
            lint_dependencies.contains_key(required),
            "agent-doc-lint-io should depend on lint gate dependency: {required}"
        );
    }
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-git-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
        "interprocess",
    ] {
        assert!(
            !lint_dependencies.contains_key(forbidden),
            "agent-doc-lint-io must stay a lint adapter, not orchestration/app state: {forbidden}"
        );
    }

    let lint_gate = fs::read_to_string(manifest_dir.join("agent-doc-lint-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub enum LintCliMode",
        "pub enum LintModeSource",
        "fn dialect_label(",
        "pub fn resolve_lint_mode(",
        "pub use agent_doc_frontmatter::lint",
        "pub(crate) use agent_doc_frontmatter::lint",
    ] {
        assert!(
            !lint_gate.contains(forbidden),
            "lint_gate must adapt IO/tagpath only, not re-own or facade frontmatter lint policy: {forbidden}"
        );
    }
    assert!(
        lint_gate.contains("lint::{LintCliMode, LintModeSource, dialect_label, resolve_lint_mode}")
            && lint_gate
                .contains("resolve_mode_from_project_dialect(content, cli, project.lint.dialect)")
            && lint_gate.contains("resolve_lint_mode(content, cli, project_dialect)")
            && lint_gate
                .contains("agent_doc_document_realtime_io::try_resolve_current_document_content(")
            && lint_gate.contains("\"lint_gate_document\"")
            && lint_gate.contains("pub fn run_force_disk_with_logger(")
            && lint_gate
                .contains("agent_doc_document_realtime_io::resolve_disk_current_document_content(")
            && lint_gate.contains("\"lint_gate_document_force_disk\"")
            && lint_gate.contains("fn run_on_content(")
            && lint_gate.contains("tagpath::lint::agent_doc")
            && lint_gate.contains("pub type OpsLogger")
            && lint_gate.contains("pub fn run_with_logger"),
        "agent-doc-lint-io should call focused frontmatter lint policy and own tagpath gate IO"
    );
    assert!(
        !lint_gate.contains("std::fs::read_to_string(file)")
            && !lint_gate.contains("fs::read_to_string(file)"),
        "agent-doc-lint-io must not read the active session document directly from disk"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-lint-io"),
        "agent-doc-orchestration should depend on the focused lint IO crate"
    );
    assert!(
        !orchestration_dependencies.contains_key("tagpath"),
        "tagpath should be confined to agent-doc-lint-io after lint gate extraction"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/lint_gate.rs")
            .exists(),
        "orchestration must not keep a lint_gate facade module"
    );
    let orchestration_write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let orchestration_stream =
        fs::read_to_string(manifest_dir.join("agent-doc-stream-io/src/lib.rs")).unwrap();
    assert!(
        orchestration_write.contains("agent_doc_lint_io::run_with_logger")
            && orchestration_write.contains("agent_doc_lint_io::run_force_disk_with_logger")
            && orchestration_write.contains("agent_doc_ops_log_io::log_op")
            && orchestration_stream.contains("agent_doc_lint_io::run_with_logger")
            && orchestration_stream.contains("agent_doc_ops_log_io::log_op"),
        "orchestration write/stream should inject ops-log into focused lint IO directly"
    );
    for forbidden in [
        "tagpath::",
        "lint_agent_doc",
        "format_findings_text",
        "AgentDocOptions",
        "LintFinding",
        "resolve_mode_from_project_dialect",
    ] {
        assert!(
            !orchestration_write.contains(forbidden) && !orchestration_stream.contains(forbidden),
            "orchestration write/stream must not re-own tagpath lint adapter after extraction: {forbidden}"
        );
    }

    for relative_path in [
        "src/main.rs",
        "agent-doc-write-command-io/src/lib.rs",
        "agent-doc-stream-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_frontmatter::lint::LintCliMode")
                && !source.contains("lint_gate::LintCliMode"),
            "{relative_path} should use the frontmatter-owned LintCliMode directly"
        );
    }
}

#[test]
fn test_agent_doc_frontmatter_owns_raw_frontmatter_yaml_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let frontmatter_source =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/frontmatter.rs")).unwrap();
    assert!(
        frontmatter_source.contains("pub fn raw_frontmatter_yaml("),
        "agent-doc-frontmatter must own raw frontmatter YAML extraction"
    );

    let realtime_io =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    assert!(
        !realtime_io.contains("fn raw_frontmatter_yaml("),
        "agent-doc-document-realtime-io must not re-own raw frontmatter extraction"
    );

    let write_converge =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    assert!(
        !write_converge.contains("fn raw_frontmatter_yaml(")
            && write_converge.contains("agent_doc_frontmatter::frontmatter::raw_frontmatter_yaml("),
        "agent-doc-write-converge-io should call frontmatter-owned raw frontmatter extraction directly"
    );
}

#[test]
fn test_agent_doc_frontmatter_owns_session_id_and_document_gate_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let frontmatter_source =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/frontmatter.rs")).unwrap();
    let project_config_source =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/project_config.rs"))
            .unwrap();
    let frontmatter_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter-io/src/session.rs")).unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let orchestration_graph =
        fs::read_to_string(manifest_dir.join("agent-doc-run-context-io/src/lib.rs")).unwrap();

    assert!(
        frontmatter_source.contains("pub fn session_id_from_content("),
        "agent-doc-frontmatter must own pure session-id extraction from document content"
    );
    assert!(
        frontmatter_source.contains("pub fn needs_session_for_formatted_document(&self) -> bool"),
        "agent-doc-frontmatter must own the pure formatted-document session initialization predicate"
    );
    assert!(
        project_config_source.contains("pub fn require_agent_doc_document("),
        "agent-doc-frontmatter must own pure document opt-in gate policy"
    );
    for required in [
        "pub fn parse_for_file<'a>(content:",
        "pub fn ensure_session_for_file(",
        "pub fn read_session_id(",
        "pub struct EnsureFormattedSessionResult",
        "pub fn ensure_session_uuid_for_formatted_file(",
        "pub struct ResolvedSshContext",
        "pub fn parse_for_file_with_context",
        "pub fn ensure_session_for_file_with_context(",
        "pub fn is_agent_doc_document_for_file(",
        "pub fn require_agent_doc_document(",
        "agent_doc_project_config_io::load_project_for_doc",
        "agent_doc_project_config_io::project_root_for_doc",
    ] {
        assert!(
            frontmatter_io_source.contains(required),
            "agent-doc-frontmatter-io should own file/config-backed frontmatter adapter: {required}"
        );
    }
    for forbidden in [
        "let (fm, _) = parse(&content)",
        "fm.session",
        "is not an agent-doc document. Run `agent-doc init",
    ] {
        assert!(
            !frontmatter_io_source.contains(forbidden),
            "frontmatter_io must adapt path/config IO, not re-own frontmatter policy: {forbidden}"
        );
    }
    assert!(
        frontmatter_io_source.contains("session_id_from_content(&content)")
            && frontmatter_io_source.contains("project_config::require_agent_doc_document("),
        "agent-doc-frontmatter-io should resolve IO inputs then call frontmatter-owned helpers directly"
    );
    assert!(
        frontmatter_io_source.contains("fm.needs_session_for_formatted_document()")
            && frontmatter_io_source.contains("std::fs::write(file, &updated)?"),
        "agent-doc-frontmatter-io should own the formatted-session file adapter while delegating the predicate"
    );
    for forbidden in [
        "pub fn parse_for_file<'a>(content:",
        "pub fn ensure_session_for_file(",
        "pub fn read_session_id(",
        "pub fn is_agent_doc_document_for_file(",
        "pub fn require_agent_doc_document(",
        "agent_doc_project_config_io::load_project_for_doc",
    ] {
        assert!(
            !orchestration_graph.contains(forbidden),
            "orchestration graph must not keep a file-backed frontmatter IO facade: {forbidden}"
        );
    }
    assert!(
        !orchestration_lib.contains("pub mod frontmatter_io;")
            && orchestration_graph.contains("ResolvedSshContext")
            && orchestration_graph.contains("ssh.as_resolver_context("),
        "orchestration should cache focused frontmatter IO context without keeping a frontmatter_io facade"
    );
    let document_init =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/document_init.rs"))
            .unwrap();
    assert!(
        document_init.contains(
            "agent_doc_frontmatter_io::session::ensure_session_uuid_for_formatted_file(doc)"
        ),
        "document initialization IO should delegate formatted session UUID file mutation to frontmatter-io"
    );
    for forbidden in [
        "agent_doc_frontmatter::frontmatter::ensure_session(&content)",
        "fm.format.is_none() || fm.session.is_some()",
    ] {
        assert!(
            !document_init.contains(forbidden),
            "document initialization IO must not re-own formatted session UUID file mutation: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_frontmatter_owns_write_mode_detection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let frontmatter_source =
        fs::read_to_string(manifest_dir.join("agent-doc-frontmatter/src/frontmatter.rs")).unwrap();
    assert!(
        frontmatter_source.contains("pub fn content_uses_crdt_write("),
        "agent-doc-frontmatter must own pure CRDT write-mode detection"
    );

    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    let commit_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    let git_transient_cleanup =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/transient_cleanup.rs")).unwrap();
    for forbidden in ["fn content_uses_crdt_write(", "fn document_uses_crdt("] {
        assert!(
            !write_run_entry.contains(forbidden)
                && !commit_io_source.contains(forbidden)
                && !git_transient_cleanup.contains(forbidden),
            "callers must not re-own CRDT write-mode detection: {forbidden}"
        );
    }
    assert!(
        write_run_entry
            .contains("use agent_doc_frontmatter::frontmatter::content_uses_crdt_write;")
            && !git_transient_cleanup.contains("content_uses_crdt_write(")
            && !commit_io_source.contains("content_uses_crdt_write("),
        "only the write runtime should need frontmatter-owned CRDT write-mode detection"
    );
}

#[test]
fn test_agent_doc_fs_owns_process_inode_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let fs_source = fs::read_to_string(manifest_dir.join("agent-doc-fs/src/lib.rs")).unwrap();
    for required in ["pub fn running_exe_inode_for_pid(", "pub fn inode_of_path("] {
        assert!(
            fs_source.contains(required),
            "agent-doc-fs must own process/file inode probes: {required}"
        );
    }

    for relative in [
        "agent-doc-controller-io/src/project_controller.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in ["fn running_exe_inode_for_pid(", "fn inode_of_path("] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own filesystem inode probes: {forbidden}"
            );
        }
        assert!(
            source.contains("agent_doc_fs::inode_of_path")
                || source.contains("agent_doc_fs::running_exe_inode_for_pid"),
            "{relative} should call agent-doc-fs inode probes directly"
        );
    }
}

#[test]
fn test_agent_doc_config_owns_env_expansion_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let config_env_source =
        fs::read_to_string(manifest_dir.join("agent-doc-config/src/env.rs")).unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let root_orchestrate_source =
        fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    let root_parallel_source = fs::read_to_string(manifest_dir.join("src/parallel.rs")).unwrap();

    for required_snippet in [
        "pub type EnvMap",
        "pub fn expand_values(",
        "pub fn shell_export_prefix(",
    ] {
        assert!(
            config_env_source.contains(required_snippet),
            "agent-doc-config must own env expansion/export policy: {required_snippet}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/env.rs")
            .exists(),
        "orchestration must not keep an env module file after env policy extraction"
    );
    assert!(
        !orchestration_lib.contains("pub mod env;"),
        "orchestration must not expose an env facade over agent-doc-config"
    );
    assert!(
        root_orchestrate_source.contains("agent_doc_config::env::expand_values(")
            && root_parallel_source.contains("agent_doc_config::env::shell_export_prefix("),
        "root callers should use agent-doc-config env helpers directly"
    );
}

#[test]
fn test_hot_state_uses_state_db_and_only_recovery_uses_snapshot_paths() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));

    let cycle =
        fs::read_to_string(manifest_dir.join("agent-doc-cycle-state-io/src/lib.rs")).unwrap();
    let cycle = cycle.split("\n#[cfg(test)]").next().unwrap_or(&cycle);
    assert!(cycle.contains("agent_doc_sqlite::state_store::open_state_db("));
    assert!(cycle.contains("insert_state_event_in_db("));
    assert!(!cycle.contains(".agent-doc/state/cycles"));

    let turn_scope =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-scope-io/src/lib.rs")).unwrap();
    let turn_scope = turn_scope
        .split("\n#[cfg(test)]")
        .next()
        .unwrap_or(&turn_scope);
    assert!(turn_scope.contains("upsert_document_runtime_state_in_db("));
    assert!(turn_scope.contains("load_document_runtime_state_from_db("));
    assert!(!turn_scope.contains(".agent-doc/turn-scope"));

    let snapshot =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    assert!(snapshot.contains("checkpoint_crdt_recovery_projection("));
    assert!(snapshot.contains("StateFact::CrdtRecoveryProjectionCheckpointed"));
    assert!(snapshot.contains("StateFact::CrdtRecoveryProjectionCleared"));
    assert!(!snapshot.contains("agent_doc_fs::crdt_path_for("));
    assert!(!snapshot.contains("agent_doc_fs::overlay_crdt_path_for("));
}

#[test]
fn test_editor_hot_path_has_no_filesystem_sidecar_or_reload_broadcast_transport() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let hot_path_sources = [
        "agent-doc-fs/src/lib.rs",
        "agent-doc-ipc-io/src/lib.rs",
        "agent-doc-ipc-io/src/editor_target.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-controller-io/src/project_controller.rs",
        "agent-doc-controller/src/paths.rs",
        "agent-doc-controller-io/src/starting_actor_timeout.rs",
        "agent-doc-crdt-relay-io/src/lib.rs",
        "agent-doc-sqlite/src/op_log.rs",
        "agent-doc-document-realtime-io/src/lib.rs",
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-write-converge-io/src/lib.rs",
        "agent-doc-supervisor-io/src/recycle_request.rs",
        "agent-doc-supervisor-io/src/startup_miss.rs",
        "agent-doc-turn-status-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-preflight-io/src/layout.rs",
        "agent-doc-preflight-io/src/gc.rs",
        "agent-doc-sync/src/lib.rs",
        "agent-doc-sync-io/src/sync.rs",
        "agent-doc-session-accretion-io/src/lib.rs",
        "agent-doc-cycle-state-io/src/lib.rs",
        "agent-doc-repair-io/src/pending.rs",
        "agent-doc-capture-io/src/lib.rs",
        "agent-doc-write-ipc-io/src/transport.rs",
        "src/lib_install.rs",
        "src/ffi.rs",
        "editors/jetbrains/src/main/kotlin/com/github/btakita/agentdoc/PatchWatcher.kt",
        "editors/jetbrains/src/main/kotlin/com/github/btakita/agentdoc/NativeLib.kt",
        "editors/vscode/src/extension.ts",
        "editors/vscode/src/native.ts",
    ];
    let forbidden = [
        "LIB_RELOAD_BROADCAST",
        "lib-reload-broadcast",
        "lib_reload_broadcast",
        "write_file_ipc",
        "live_buffer_path_for",
        "cycle_state_path_for",
        "starting_actor_timeout_paths",
        "pending_response_path_for",
        "capture_path_for",
        "partial_capture_path_for",
        "write_file_ipc_and_poll_delivery",
        "send_save_document_file_signal",
        "publish_live_buffer_file_signal",
        ".agent-doc/patches",
        ".agent-doc/live-buffer",
        ".agent-doc/plugin-owner",
        ".agent-doc/state/cycles",
        ".agent-doc/state/route-starting-timeouts",
        ".agent-doc/pending",
        ".agent-doc/captures",
        ".agent-doc/ack-content",
        ".agent-doc/recycle-request",
        ".agent-doc/state/startup-miss",
        ".agent-doc/turn-active.json",
        ".agent-doc/supervisor-stale",
        ".agent-doc/state/drift.count",
        ".agent-doc/state/base-index-repair.count",
        ".agent-doc/rename-debounce",
        ".agent-doc/build.stamp",
        ".agent-doc/test-local-crdt-relay",
        ".agent-doc/sync-prune-state.json",
        ".agent-doc/state/session-accretion-compaction",
        ".agent-doc/gc.stamp",
        ".agent-doc/last_layout.json",
        ".agent-doc/controller-state.json",
        "sync_repair_stamp",
        "sync-repair-",
        "reliable_sync_outbox.db",
        "op-log.db",
        ".agent-doc/callbacks",
    ];
    for relative in hot_path_sources {
        let source = fs::read_to_string(root.join(relative)).unwrap();
        let production = source
            .split("\n#[cfg(test)]\nmod tests")
            .next()
            .unwrap_or(&source);
        for token in forbidden {
            assert!(
                !production.contains(token),
                "{relative} must not regain a filesystem editor/state hot path: {token}"
            );
        }
    }

    let ipc = fs::read_to_string(root.join("agent-doc-ipc-io/src/lib.rs")).unwrap();
    let controller =
        fs::read_to_string(root.join("agent-doc-controller-io/src/project_controller/rpc.rs"))
            .unwrap();
    let install = fs::read_to_string(root.join("src/lib_install.rs")).unwrap();
    let idle_watch =
        fs::read_to_string(root.join("agent-doc-start-runtime-io/src/idle_watch.rs")).unwrap();
    assert!(ipc.contains("pub fn send_reload_library_to_editor("));
    assert!(controller.contains("pub fn reload_library_all_projects("));
    assert!(install.contains("reload_library_all_projects(version)"));
    assert!(
        idle_watch.contains("enum QueueHeadObservation")
            && idle_watch.contains("QueueHeadObservation::AuthorityUnavailable")
            && idle_watch.contains("disk_queue_authority_allowed(editor_attached)")
            && idle_watch.contains("attached_editor_never_allows_disk_queue_authority"),
        "idle queue drain must pause when attached Lazily authority is unavailable instead of falling back to disk"
    );
}

#[test]
fn test_actor_domain_types_live_in_the_controller_model() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let session_actor_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-actor-io/src/lib.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/session_actor.rs")
            .exists(),
        "orchestration must not keep a session_actor facade module"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod session_actor;"),
        "orchestration must not expose a session_actor facade module"
    );
    assert!(
        session_actor_source.contains(
            "use agent_doc_controller::actor::{ActorLastTransition, ActorRecord, ActorState};"
        ),
        "agent-doc-session-actor-io should import actor domain types from the controller model"
    );
    assert!(
        !session_actor_source.contains("agent_doc_sqlite::state_store::Actor"),
        "the session actor adapter must not treat SQLite as the owner of actor semantics"
    );
    let sqlite_state_store =
        fs::read_to_string(manifest_dir.join("agent-doc-sqlite/src/state_store.rs")).unwrap();
    for forbidden_snippet in [
        "pub enum ActorState",
        "pub struct ActorRecord",
        "pub struct ActorLastTransition",
        "pub use agent_doc_controller::actor",
    ] {
        assert!(
            !sqlite_state_store.contains(forbidden_snippet),
            "agent-doc-sqlite must serialize actor domain types without defining or re-exporting them: {forbidden_snippet}"
        );
    }

    fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                out.push(path);
            }
        }
    }

    let mut source_files = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut source_files);
    for path in source_files {
        let source = fs::read_to_string(&path).unwrap();
        let relative = path.strip_prefix(manifest_dir).unwrap().display();
        for forbidden_snippet in [
            "agent_doc_sqlite::state_store::Actor",
            "agent_doc_sqlite::Actor",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must import actor domain types from agent_doc_controller::actor: {forbidden_snippet}"
            );
        }
    }
}

#[test]
fn test_project_controller_has_no_sqlite_status_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let project_controller_source =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    let sqlite_state_store =
        fs::read_to_string(manifest_dir.join("agent-doc-sqlite/src/state_store.rs")).unwrap();
    assert!(
        !project_controller_source.contains("pub use state_store::{"),
        "project_controller.rs must not re-export SQLite status/storage types"
    );
    assert!(
        project_controller_source.contains("use state_store::{"),
        "project_controller.rs should import SQLite status/storage types privately"
    );
    assert!(
        project_controller_source
            .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)?")
            && !project_controller_source.contains("agent_doc_cycle_state_io::load(file)?"),
        "project_controller closeout persistence should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        sqlite_state_store.contains("pub fn session_actor_closeout_mutations"),
        "agent-doc-sqlite should own session actor closeout mutation construction"
    );
    for forbidden in [
        "fn session_actor_closeout_mutations",
        "fn append_closeout_mutations(",
    ] {
        assert!(
            !project_controller_source.contains(forbidden),
            "project_controller.rs must not re-own SQLite closeout mutation construction: {forbidden}"
        );
    }

    fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                out.push(path);
            }
        }
    }

    let mut source_files = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut source_files);
    for path in source_files {
        let source = fs::read_to_string(&path).unwrap();
        let relative = path.strip_prefix(manifest_dir).unwrap().display();
        for forbidden_snippet in [
            "project_controller::ActorTransitionStatus",
            "project_controller::AdminOperationStatus",
            "project_controller::DispatchAttemptStatus",
            "project_controller::ProjectionDiagnosticStatus",
            "project_controller::QueueBackpressureStatus",
            "project_controller::QueueControlStatus",
            "project_controller::QueueHeadStatus",
            "project_controller::SessionOperatorStatus",
            "project_controller::SupervisorLeaseStatus",
            "project_controller::state_db_path",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must import controller storage/status types from agent_doc_sqlite::state_store directly: {forbidden_snippet}"
            );
        }
    }
}

#[test]
fn test_sessions_has_no_tmux_router_type_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/sessions.rs")
            .exists(),
        "orchestration must not keep a sessions facade module"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod sessions;"),
        "orchestration must not expose a sessions facade module"
    );
    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    assert!(
        !sessions_source.contains("pub use tmux_router"),
        "session registry registration IO must not re-export tmux-router types"
    );
    assert!(
        sessions_source.contains("use tmux_router::{"),
        "session registry registration IO should import tmux-router types privately for its adapter helpers"
    );

    fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                out.push(path);
            }
        }
    }

    let mut source_files = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut source_files);
    for path in source_files {
        let source = fs::read_to_string(&path).unwrap();
        let relative = path.strip_prefix(manifest_dir).unwrap().display();
        for forbidden_snippet in [
            "sessions::Tmux",
            "sessions::IsolatedTmux",
            "sessions::PaneMoveOp",
            "sessions::RegistryLock",
            "sessions::SessionRegistry",
            "sessions::SessionEntry",
            "agent_doc_session_registry_io::registration::Tmux",
            "agent_doc_session_registry_io::registration::IsolatedTmux",
            "agent_doc_session_registry_io::registration::PaneMoveOp",
            "agent_doc_session_registry_io::registration::RegistryLock",
            "agent_doc_session_registry_io::registration::SessionRegistry",
            "agent_doc_session_registry_io::registration::SessionEntry",
            "agent_doc_session_registry_io::registration::Tmux",
            "agent_doc_session_registry_io::registration::IsolatedTmux",
            "agent_doc_session_registry_io::registration::PaneMoveOp",
            "agent_doc_session_registry_io::registration::RegistryLock",
            "agent_doc_session_registry_io::registration::SessionRegistry",
            "agent_doc_session_registry_io::registration::SessionEntry",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must import tmux-router types from tmux_router directly: {forbidden_snippet}"
            );
        }
    }
}

#[test]
fn test_agent_doc_session_registry_owns_registry_mutation_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-session-registry")),
        "agent-doc-session-registry must stay a first-class workspace crate"
    );

    let registry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry/src/lib.rs")).unwrap();
    for required in [
        "pub struct RegistryEntryFields",
        "pub struct RegistryReplacement",
        "pub struct SessionIdentityOwner",
        "pub enum SessionIdentityClaim",
        "pub fn canonical_registry_key_in(",
        "pub fn session_key(",
        "pub fn session_identity_owner(",
        "pub fn session_identity_claim(",
        "pub fn session_pane(",
        "pub fn session_entry(",
        "pub fn remove_session_by_id(",
        "pub fn stale_pane_keys(",
        "pub fn remove_stale_pane_bindings(",
        "pub fn registry_entry(",
        "pub fn insert_registry_entry(",
        "pub fn replace_registry_entry(",
        "session_identity_owner(registry, session_id)",
        "entry_session_id(key, entry) != session_id",
    ] {
        assert!(
            registry_source.contains(required),
            "agent-doc-session-registry must own pure registry mutation policy: {required}"
        );
    }

    let registry_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&registry_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(
        dependencies.contains_key("tmux-router"),
        "agent-doc-session-registry should depend on tmux-router registry primitives"
    );
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-session-registry-io",
        "agent-doc-tmux",
        "agent-doc-tmux-commands",
        "agent-doc-tmux-io",
        "anyhow",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "serde_json",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-session-registry must stay pure registry policy: {forbidden}"
        );
    }

    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-session-registry"),
        "root crate should expose the focused session-registry policy crate"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-session-registry"),
        "orchestration should depend on focused session-registry policy"
    );

    let registry_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/Cargo.toml")).unwrap();
    let registry_io: toml::Value = toml::from_str(&registry_io_manifest).unwrap();
    let registry_io_dependencies = registry_io["dependencies"].as_table().unwrap();
    assert!(
        registry_io_dependencies.contains_key("agent-doc-session-registry"),
        "registry IO should compose with pure session-registry policy"
    );

    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    let sessions_prod = sessions_source
        .split("\n#[cfg(test)]\nmod tests")
        .next()
        .unwrap();
    assert!(
        sessions_prod.contains("use agent_doc_session_registry as session_registry;")
            && sessions_prod.contains("session_registry::replace_registry_entry(")
            && sessions_prod.contains("session_registry::remove_stale_pane_bindings(")
            && sessions_prod.contains("session_registry::insert_registry_entry("),
        "session registry registration IO should adapt registration effects through focused registry policy"
    );
    for forbidden in [
        "entry_session_id(",
        "find_registry_key_by_session_id(",
        ".filter(|(key, entry)| entry.pane == pane_id",
        ".filter(|(k, e)| e.pane == pane_id",
        "SessionEntry {",
    ] {
        assert!(
            !sessions_prod.contains(forbidden),
            "session registry registration IO must not re-own pure registry mutation policy: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_session_registry_io_owns_registry_state_io() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-session-registry-io")),
        "agent-doc-session-registry-io must stay a first-class workspace crate"
    );

    let registry_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/lib.rs")).unwrap();
    for required in [
        "pub const SESSIONS_FILE: &str = \".agent-doc/state.db\";",
        "pub fn registry_path() -> PathBuf",
        "pub fn registry_path_in(base_dir: &Path) -> PathBuf",
        "pub fn load() -> Result<Registry>",
        "pub fn load_in(base_dir: &Path) -> Result<Registry>",
        "pub fn save(registry: &Registry) -> Result<()>",
        "pub fn save_in(base_dir: &Path, registry: &Registry) -> Result<()>",
        "pub fn lookup(session_id: &str) -> Result<Option<String>>",
        "pub fn lookup_in(base_dir: &Path, session_id: &str) -> Result<Option<String>>",
        "pub fn lookup_entry(session_id: &str) -> Result<Option<RegistryEntry>>",
        "pub fn deregister(session_id: &str) -> Result<bool>",
        "pub fn deregister_in(base_dir: &Path, session_id: &str) -> Result<bool>",
        "pub fn update_session_file_in(",
        "tmux_router::registry::load_registry(&path)",
        "tmux_router::registry::save_registry(&path, &registry)",
        "normalize_registry(base_dir, registry.clone())",
        "agent_doc_session_registry::session_pane(",
        "agent_doc_session_registry::session_entry(",
        "agent_doc_session_registry::remove_session_by_id(",
    ] {
        assert!(
            registry_io_source.contains(required),
            "agent-doc-session-registry-io must own registry state IO/lookup: {required}"
        );
    }

    let registry_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&registry_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required_dependency in [
        "agent-doc-hash",
        "agent-doc-log-time",
        "agent-doc-session-actor-io",
        "agent-doc-session-registry",
        "agent-doc-sqlite",
        "agent-doc-supervisor",
        "agent-doc-tmux-io",
        "anyhow",
        "serde_json",
        "tmux-router",
    ] {
        assert!(
            dependencies.contains_key(required_dependency),
            "agent-doc-session-registry-io should own registry IO dependency: {required_dependency}"
        );
    }
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-tmux",
        "agent-doc-tmux-commands",
        "git2",
        "interprocess",
        "notify",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-session-registry-io must stay focused on registry file IO: {forbidden}"
        );
    }

    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_dependencies = root["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-session-registry-io"),
        "root CLI should depend on registry IO directly instead of routing through orchestration"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-session-registry-io"),
        "orchestration should depend on registry IO directly for registration persistence"
    );

    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    assert!(
        sessions_source.contains("use crate as session_registry_io;"),
        "session registry registration IO should adapt registration updates through the focused registry IO crate"
    );
    for forbidden in [
        "pub fn registry_path(",
        "pub fn registry_path_in(",
        "pub fn load(",
        "pub fn load_in(",
        "pub fn save(",
        "pub fn save_in(",
        "pub fn lookup(",
        "pub fn lookup_in(",
        "pub fn lookup_entry(",
        "pub fn deregister(",
        "const SESSIONS_FILE",
        "serde_json::from_str(&content)",
        "serde_json::to_string_pretty(registry)",
        "std::fs::write(&path",
    ] {
        assert!(
            !sessions_source.contains(forbidden),
            "session registry registration IO must not keep registry snapshot IO/lookup facades: {forbidden}"
        );
    }

    let dispatch_registry_source = fs::read_to_string(
        manifest_dir.join("agent-doc-session-registry-io/src/dispatch_registry.rs"),
    )
    .unwrap();
    for required in [
        "crate::load_in(base_dir)",
        "crate::registry_path_in(&base_dir)",
        "crate::save_in(&base_dir, &registry)",
    ] {
        assert!(
            dispatch_registry_source.contains(required),
            "session dispatch registry should compose with generic registry IO: {required}"
        );
    }
    for forbidden in [
        "const SESSIONS_FILE",
        "pub fn registry_path_in(",
        "tmux_router::registry::load_registry",
        "tmux_router::registry::save_registry",
    ] {
        assert!(
            !dispatch_registry_source.contains(forbidden),
            "session dispatch registry must not duplicate generic registry IO: {forbidden}"
        );
    }

    let route_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch.rs")).unwrap();
    let route_dispatch_recovery =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_recovery.rs"))
            .unwrap();
    let route_dispatch_target =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_target.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn canonical_dispatch_file(",
        "pub(crate) fn canonical_registered_file(",
        "pub(crate) fn registry_base_dir_for_dispatch(",
        "pub(crate) fn lookup_dispatch_registration(",
        "pub(crate) fn load_dispatch_registry(",
        "pub(crate) fn deregister_dispatch_registration(",
        "pub(crate) fn ensure_dispatch_target_can_bind_file(",
        "pub(crate) fn pane_registration_matches_file(",
        "pub(crate) fn ensure_dispatch_target_matches_file(",
        "pub(crate) fn register_dispatch_target(",
        "pub(crate) fn resolve_fresh_dispatch_target_after_ready_wait(",
    ] {
        assert!(
            !route_dispatch.contains(forbidden),
            "route/dispatch.rs must not keep controller dispatch-registry facades: {forbidden}"
        );
    }
    assert!(
        route_dispatch.contains("use agent_doc_session_registry_io::dispatch_registry;")
            && route_dispatch.contains("dispatch_registry::ensure_dispatch_target_matches_file("),
        "route/dispatch.rs should only call focused session dispatch-registry IO for direct pre-send match validation"
    );
    assert!(
        route_dispatch_target.contains("pub fn register_dispatch_target(")
            && route_dispatch_target
                .contains("dispatch_registry::ensure_dispatch_target_can_bind_file(")
            && route_dispatch_target.contains("registration::register_full_with_cwd_in("),
        "agent-doc-route-io dispatch_target should own route dispatch target registry binding"
    );
    assert!(
        route_dispatch_recovery.contains("pub fn resolve_fresh_dispatch_target_after_ready_wait(")
            && route_dispatch_recovery.contains("dispatch_registry::canonical_dispatch_file(")
            && route_dispatch_recovery
                .contains("dispatch_registry::pane_registration_matches_file("),
        "agent-doc-route-io dispatch_recovery should own fresh dispatch target registry validation"
    );

    fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, out);
            } else if path.extension().is_some_and(|extension| extension == "rs") {
                out.push(path);
            }
        }
    }

    let mut source_files = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut source_files);
    for path in source_files {
        let source = fs::read_to_string(&path).unwrap();
        let relative = path.strip_prefix(manifest_dir).unwrap().display();
        for forbidden in [
            "agent_doc_session_registry_io::registration::registry_path",
            "agent_doc_session_registry_io::registration::load",
            "agent_doc_session_registry_io::registration::save",
            "agent_doc_session_registry_io::registration::lookup",
            "agent_doc_session_registry_io::registration::registry_path",
            "agent_doc_session_registry_io::registration::load",
            "agent_doc_session_registry_io::registration::save",
            "agent_doc_session_registry_io::registration::lookup",
            "sessions::registry_path",
            "sessions::load",
            "sessions::save",
            "sessions::lookup",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must call agent_doc_session_registry_io directly: {forbidden}"
            );
        }
    }
}

#[test]
fn test_agent_doc_merge_is_pure_workspace_boundary() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-merge")),
        "agent-doc-merge must stay a first-class workspace crate"
    );
    assert!(
        !members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-document-merge")),
        "merge policy should stay in agent-doc-merge, not under the pure document crate family"
    );
    let realtime_spec =
        fs::read_to_string(manifest_dir.join("specs/14-realtime-workflow.md")).unwrap();
    assert!(
        realtime_spec.contains("`agent-doc-merge` for pure merge semantics")
            && !realtime_spec.contains("agent-doc-document-merge"),
        "realtime spec must keep agent-doc-merge as the pure merge-policy boundary"
    );

    let merge_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-merge/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&merge_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    assert!(
        !dependencies.contains_key("agent-doc-core"),
        "agent-doc-merge owns pure merge policy directly and must not depend on the transitional core crate"
    );
    assert!(dependencies.contains_key("agent-doc-element"));
    assert!(dependencies.contains_key("agent-doc-element-queue"));
    assert!(dependencies.contains_key("agent-doc-frontmatter"));
    assert!(dependencies.contains_key("agent-doc-markdown-ast"));
    let merge_lib = fs::read_to_string(manifest_dir.join("agent-doc-merge/src/lib.rs")).unwrap();
    let markdown_ast_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-markdown-ast/src/lib.rs")).unwrap();
    assert!(
        merge_lib.contains("pub mod document_cell_merge;")
            && !merge_lib.contains("pub use agent_doc_markdown_ast::document_cell_merge"),
        "agent-doc-merge should own document_cell_merge directly, not re-export markdown-ast"
    );
    assert!(
        !markdown_ast_lib.contains("pub mod document_cell_merge;")
            && !manifest_dir
                .join("agent-doc-markdown-ast/src/document_cell_merge.rs")
                .exists(),
        "agent-doc-markdown-ast must not keep document_cell_merge as a compatibility module"
    );
    for relative in [
        "agent-doc-cycle-state-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/ipc.rs",
        "src/sim_world.rs",
        "src/sim_world/engine.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("agent_doc_markdown_ast::document_cell_merge"),
            "{relative} should call semantic merge through agent-doc-merge directly"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/merge.rs")
            .exists(),
        "orchestration must not keep a merge facade after merge IO extraction"
    );
    let merge_io = fs::read_to_string(manifest_dir.join("agent-doc-merge-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn merge_contents(",
        "pub fn merge_contents_crdt_with_ops(",
        "agent_doc_op_capture_io::editor_ops_for_base(doc, &base_text)",
        "agent_doc_op_capture_io::clear_op_capture(doc)",
        "agent_doc_hash::content_hash(&base_text)",
        "summarize_editor_ops_for_log(ops)",
    ] {
        assert!(
            merge_io.contains(required_snippet),
            "agent-doc-merge-io must own git and op-capture merge IO: {required_snippet}"
        );
    }
    for relative in [
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-write-runtime-io/src/ipc.rs",
        "src/sim_world/engine.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_merge_io::merge_contents")
                && !source.contains("crate::merge::merge_contents")
                && !source.contains("agent_doc_orchestration::merge::merge_contents"),
            "{relative} should call focused git merge IO directly instead of the orchestration merge facade"
        );
    }
    for relative in [
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-write-runtime-io/src/ipc.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_merge_io::merge_contents_crdt_with_ops(")
                && source.contains("agent_doc_ops_log_io::log_op")
                && !source.contains("merge::merge_contents_crdt_with_ops("),
            "{relative} should call focused op-capture CRDT merge IO directly"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod merge;"),
        "orchestration must not expose a merge facade module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/merge_control_state_machine.rs")
            .exists(),
        "orchestration must not keep a merge-control facade over agent-doc-merge::ownership"
    );
    assert!(
        !orchestration_lib.contains("merge_control_state_machine"),
        "orchestration must not re-export merge-control ownership policy"
    );
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-merge must not depend on realtime, turn, git, editor, or sqlite crates"
        );
    }
}

#[test]
fn test_agent_doc_debounce_is_pure_settle_policy_boundary() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-debounce")),
        "agent-doc-debounce must stay a first-class workspace crate"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(orchestration_dependencies.contains_key("agent-doc-debounce"));

    let debounce_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-debounce/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&debounce_manifest).unwrap();
    let dependencies = parsed.get("dependencies").and_then(toml::Value::as_table);
    assert!(dependencies.is_none_or(|dependencies| dependencies.is_empty()));
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            dependencies.is_none_or(|dependencies| !dependencies.contains_key(forbidden)),
            "agent-doc-debounce must not depend on core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
    let debounce_source =
        fs::read_to_string(manifest_dir.join("agent-doc-debounce/src/lib.rs")).unwrap();
    assert!(debounce_source.contains("pub fn authority_settle_max_wait("));
    for forbidden in [
        "live_buffer",
        "write_provenance",
        "typing_marker",
        ".agent-doc/live-buffer",
    ] {
        assert!(
            !debounce_source.contains(forbidden),
            "the debounce policy crate must not regain filesystem authority state: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_controller_owns_route_trigger_matching_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/dispatch.rs")).unwrap();
    for required in [
        "pub fn recent_lines_contain_trigger",
        "pub fn line_contains_trigger",
        "pub fn compact_trigger_text",
        "pub fn strip_leading_prompt_prefix",
        "pub fn shares_trigger_prefix",
        "pub fn recent_lines_contain_wrapped_trigger",
        "pub fn dispatch_payload_pending_in_current_input",
        "pub fn route_trigger_visible_in_current_draft",
        "fn line_contains_equivalent_agent_doc_path_trigger",
        "fn single_agent_doc_path_arg",
        "struct AgentDocPathArg",
        "fn agent_doc_path_arg",
        "fn agent_doc_path_args_equivalent",
        "fn wrapped_trigger_starts_at_line",
    ] {
        assert!(
            controller_dispatch.contains(required),
            "agent-doc-controller must own route trigger matching policy: {required}"
        );
    }

    for relative in [
        "agent-doc-route-io/src/admission_projection.rs",
        "agent-doc-route-io/src/dispatch.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-supervisor-io/src/detection.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "fn recent_lines_contain_trigger",
            "fn line_contains_trigger",
            "fn compact_trigger_text",
            "fn strip_leading_prompt_prefix",
            "fn shares_trigger_prefix",
            "fn recent_lines_contain_wrapped_trigger",
            "pub(crate) fn supervisor_pane_payload_pending_in_content",
            "fn supervisor_pane_payload_pending_in_content",
            "pub(crate) fn direct_pane_existing_draft_visible",
            "fn direct_pane_existing_draft_visible",
            "fn line_contains_equivalent_agent_doc_path_trigger",
            "fn single_agent_doc_path_arg",
            "struct AgentDocPathArg",
            "fn agent_doc_path_arg",
            "fn agent_doc_path_args_equivalent",
            "fn wrapped_trigger_starts_at_line",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own route trigger matching policy: {forbidden}"
            );
        }
    }
    let route_direct_pane_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/direct_pane_dispatch.rs"))
            .unwrap();
    let supervisor_io_detection =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/detection.rs")).unwrap();
    assert!(
        route_direct_pane_dispatch
            .contains("route_trigger_visible_in_current_draft(&content, &trigger")
            && supervisor_io_detection.contains("dispatch_payload_pending_in_current_input("),
        "route direct-pane IO and supervisor detection IO should call focused controller dispatch visibility policy directly"
    );
}

#[test]
fn test_agent_doc_controller_owns_handoff_staleness_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller_status =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/status.rs")).unwrap();
    for required in [
        "pub fn preparing_controller_is_stale(",
        "pub fn stale_preparing_controller_threshold_from_env_value(",
        "pub struct ControllerWatchdogFacts",
        "pub fn controller_watchdog_should_suicide(",
        "pub fn handoff_replacement_is_stranded(",
    ] {
        assert!(
            controller_status.contains(required),
            "agent-doc-controller status must own pure controller handoff/watchdog policy: {required}"
        );
    }

    for relative_path in [
        "agent-doc-controller-io/src/project_controller.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        for forbidden in [
            "fn preparing_controller_is_stale(",
            "fn controller_watchdog_should_suicide(",
            "fn handoff_replacement_is_stranded(",
            "fn controller_handoff_replacement_is_stranded(",
            "pub(crate) fn controller_handoff_replacement_is_stranded(",
            "fn stale_preparing_controller_threshold_from_env_value(",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative_path} must not re-own controller handoff/watchdog policy: {forbidden}"
            );
        }
    }

    let project_controller =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    let project_controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        project_controller.contains("preparing_controller_is_stale")
            && project_controller
                .contains("stale_preparing_controller_threshold_from_env_value(raw.as_deref())")
            && project_controller_rpc.contains("status::controller_watchdog_should_suicide")
            && project_controller_rpc.contains("status::ControllerWatchdogFacts"),
        "orchestration should call focused controller handoff/watchdog policy directly"
    );
}

#[test]
fn test_agent_doc_controller_owns_project_controller_paths() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/lib.rs")).unwrap();
    let controller_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/lib.rs")).unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let controller_paths =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/paths.rs")).unwrap();
    assert!(
        controller_lib.contains("pub mod paths;"),
        "agent-doc-controller must expose focused controller path policy"
    );
    assert!(
        controller_io_lib.contains("pub mod project_controller;"),
        "agent-doc-controller-io must own the project-controller IO graph"
    );
    for removed in [
        "agent-doc-orchestration/src/project_controller.rs",
        "agent-doc-orchestration/src/project_controller/rpc.rs",
    ] {
        assert!(
            !manifest_dir.join(removed).exists(),
            "orchestration project-controller facade should be deleted: {removed}"
        );
    }
    assert!(
        !orchestration_lib.contains("pub mod project_controller;"),
        "orchestration must not expose a project_controller root facade"
    );
    for required in ["pub const SOCKET_FILE", "pub fn socket_path("] {
        assert!(
            controller_paths.contains(required),
            "agent-doc-controller paths must own project controller path policy: {required}"
        );
    }

    let project_controller =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    for forbidden in [
        "const SOCKET_FILE",
        "const STATE_FILE",
        "const ACTOR_PROJECTION_FILE",
        "const LAYOUT_PROJECTION_FILE",
        "pub fn socket_path(",
        "pub fn state_path(",
        "fn actor_projection_path(",
        "fn layout_projection_path(",
        "fn sessions_projection_entry(",
    ] {
        assert!(
            !project_controller.contains(forbidden),
            "project_controller.rs must not re-own controller path policy: {forbidden}"
        );
    }
    assert!(
        project_controller.contains("use agent_doc_controller::paths::socket_path;"),
        "project_controller.rs should call focused controller path policy directly"
    );
}

#[test]
fn test_agent_doc_controller_dispatch_has_no_rpc_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-controller")),
        "agent-doc-controller must stay a first-class workspace crate"
    );
    let root_dependencies = workspace["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-controller"),
        "the CLI shell should call focused controller dispatch helpers directly"
    );

    let rpc_source = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    let project_controller_source =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    let command_line_source =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/command_line.rs")).unwrap();
    let controller_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/dispatch.rs")).unwrap();
    let controller_status =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/status.rs")).unwrap();
    let controller_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/lib.rs")).unwrap();
    let supervisor_replacement_source =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/supervisor_replacement.rs"))
            .unwrap();
    let preflight_warnings_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    for required_snippet in [
        "pub fn cmdline_is_agent_doc_owner_session(",
        "pub fn cmdline_references_md_document(",
        "pub fn owner_document_from_cmdline(",
        "pub fn path_has_component_suffix(",
        "pub fn cmdline_has_file_match(",
        "pub fn agent_doc_cmdline_is_owner(",
        "pub fn cmdline_owns_other_document(",
        "pub fn args_have_preparing_handoff(",
        "pub fn canonical_path_for_command_line_compare(",
        "pub fn same_project_controller_args_match_project_root(",
    ] {
        assert!(
            command_line_source.contains(required_snippet),
            "agent-doc-controller should own process command-line ownership recognition: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub enum ControllerDispatchResultStatus",
        "pub enum ControllerDispatchProofScope",
        "pub struct ControllerDispatchReceipt",
        "pub const fn as_str(self) -> &'static str",
        "pub fn dispatch_diagnostic_field",
        "pub fn append_dispatch_proof_payload(",
        "pub fn dispatch_blocked_user_facing_outcome_fields(",
        "pub struct DispatchBlockedProofFacts",
        "pub fn dispatch_blocked_proof_fields(",
        "pub const fn queue_pause_predates_boot(",
    ] {
        assert!(
            controller_dispatch.contains(required_snippet),
            "agent-doc-controller should own controller dispatch diagnostic payload policy: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub struct ControllerProcessFreshness",
        "pub struct ControllerFreshnessStatus",
        "pub struct ControlPlaneStatus",
        "pub struct ControlPlaneActorStatus",
        "pub enum ControllerHandoffState",
        "pub fn default_control_plane_status(",
        "pub fn status_categories",
        "pub fn control_plane_status(",
        "pub fn controller_status_from_bootstrap(",
        "pub fn inactive_controller_status(",
        "pub fn controller_freshness_status(",
        "pub fn controller_process_freshness_from_inodes(",
        "pub fn parse_handoff_state(",
        "pub fn controller_binary_identity_matches(",
        "pub fn process_binary_is_stale(",
        "pub const fn default_controller_generation(",
        "pub const fn controller_restart_recovery_needed(",
        "pub fn supervisor_stale_warning_message(",
        "pub fn host_supervisor_stale_warning_message(",
        "pub struct CrashRecoveryStats",
        "pub fn supervisor_lease_reconcile_payload(",
        "pub fn dispatch_receipt_reconcile_payload(",
        "pub fn open_closeout_preserved_payload(",
    ] {
        assert!(
            controller_status.contains(required_snippet),
            "agent-doc-controller should own controller status/freshness projection: {required_snippet}"
        );
    }
    assert!(
        controller_lib.contains("pub mod supervisor_replacement;"),
        "agent-doc-controller should expose supervisor replacement request parsing"
    );
    for required_snippet in [
        "pub struct SupervisorReplacementRequestFields",
        "pub enum SupervisorReplacementMode",
        "pub struct ParsedSupervisorReplacementRequest",
        "pub enum SupervisorReplacementParseError",
        "pub fn parse_supervisor_replacement_request(",
    ] {
        assert!(
            supervisor_replacement_source.contains(required_snippet),
            "agent-doc-controller should own supervisor replacement request parsing: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub use agent_doc_controller::dispatch",
        "pub use agent_doc_controller::status",
        "pub fn dispatch_error_stale_generation_redirect_target",
        "pub fn dispatch_error_supervisor_restart_redirect",
        "pub(crate) fn dispatch_command_kind_is_operator_reopen",
        "pub(crate) fn pause_reason_is_stale_supervisor_churn_stop",
        "pub(crate) fn stale_supervisor_pid_from_pause_reason",
        "pub(crate) fn spent_preset_id_from_pause_reason",
        "pub(crate) struct StaleQueuePauseRecovery",
        "pub(crate) fn dispatch_error_stale_queue_pause_recovery",
        "fn queue_pause_predates_current_boot(",
        "pub(crate) struct CloseoutBlockDispatchFacts",
        "pub(crate) enum CloseoutBlockDispatchDecision",
        "pub(crate) fn classify_closeout_block_dispatch",
        "pub(crate) fn recycle_debounce_decision",
        "pub(crate) fn force_overrides_in_flight_gate",
        "fn dispatch_diagnostic_field",
        "fn append_dispatch_proof_payload(",
        "fn dispatch_blocked_user_facing_outcome_fields(",
        "struct DispatchBlockedProofFacts",
        "fn dispatch_blocked_proof_fields(",
        "fn supervisor_stale_warning_message(",
        "fn host_supervisor_stale_warning_message(",
        "fn args_match_same_project_controller(",
        "fn canonical_path_for_compare(",
        "fn supervisor_replacement_mode(",
        "fn supervisor_replacement_force_flag(",
    ] {
        assert!(
            !rpc_source.contains(forbidden_snippet),
            "project_controller::rpc must not re-export or wrap pure controller dispatch helpers: {forbidden_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub enum ControllerDispatchResultStatus",
        "pub enum ControllerDispatchProofScope",
        "pub struct ControllerDispatchReceipt",
        "pub struct ControllerProcessFreshness",
        "pub struct ControllerFreshnessStatus",
        "pub struct ControlPlaneStatus",
        "pub struct ControlPlaneActorStatus",
        "pub enum ControllerHandoffState",
        "fn default_control_plane_status(",
        "fn control_plane_status(",
        "fn controller_status_from_bootstrap(",
        "fn inactive_controller_status(",
        "fn controller_freshness_status(",
        "fn controller_process_freshness_from_inodes(",
        "fn parse_handoff_state(",
        "fn controller_binary_identity_matches(",
        "fn process_binary_is_stale(",
        "fn default_controller_generation(",
        "fn controller_restart_recovery_needed(",
        "fn supervisor_stale_warning_message(",
        "fn host_supervisor_stale_warning_message(",
        "fn controller_binary_is_stale(",
        "struct CrashRecoveryStats",
        "fn supervisor_lease_reconcile_payload(",
        "fn dispatch_receipt_reconcile_payload(",
        "fn open_closeout_preserved_payload(",
        "pub use agent_doc_controller::status",
    ] {
        assert!(
            !project_controller_source.contains(forbidden_snippet),
            "project_controller must not re-own or facade controller status/freshness projection: {forbidden_snippet}"
        );
    }
    assert!(
        project_controller_source.contains("use agent_doc_controller::dispatch::{")
            && project_controller_source.contains("ControllerDispatchReceipt")
            && rpc_source.contains("use agent_doc_controller::dispatch::{"),
        "orchestration should import focused controller dispatch vocabulary/helpers directly"
    );
    assert!(
        rpc_source.contains("dispatch_diagnostic_field(&diagnostic_payload,")
            && rpc_source.contains("append_dispatch_proof_payload(&diagnostic_payload,"),
        "project_controller::rpc should call focused controller dispatch diagnostic helpers directly"
    );
    assert!(
        rpc_source.contains("dispatch_blocked_proof_fields(DispatchBlockedProofFacts {"),
        "project_controller::rpc should call focused dispatch-blocked proof field policy directly"
    );
    assert!(
        rpc_source.contains("use agent_doc_controller::status")
            && project_controller_source.contains("use agent_doc_controller::status::{"),
        "orchestration should call focused controller status/freshness helpers directly"
    );
    assert!(
        rpc_source.contains("status::process_binary_is_stale("),
        "project_controller::rpc should call focused controller binary staleness policy directly"
    );
    assert!(
        rpc_source.contains("pub fn recycle_stale_supervisor_for_turn_stage(")
            && preflight_warnings_source.contains("recycle_stale_supervisor_for_turn_stage("),
        "stale-supervisor detection must automatically request a safe idle-boundary recycle, not only warn"
    );
    assert!(
        project_controller_source.contains("CrashRecoveryStats::new(")
            && project_controller_source.contains("status::supervisor_lease_reconcile_payload(")
            && project_controller_source.contains("status::dispatch_receipt_reconcile_payload(")
            && project_controller_source.contains("status::open_closeout_preserved_payload("),
        "project_controller should keep controller recovery IO and call focused crash-recovery marker policy directly"
    );
    let controller_io_process =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/process.rs")).unwrap();
    assert!(
        controller_io_process.contains(
            "agent_doc_controller::command_line::same_project_controller_args_match_project_root",
        ) && controller_io_process.contains(
            "agent_doc_controller::command_line::canonical_path_for_command_line_compare",
        ),
        "agent-doc-controller-io process scanning should call focused controller command-line comparison policy directly"
    );
    for forbidden_snippet in [
        "fn agent_doc_controller_serve_arg_index(args:",
        "fn controller_serve_project_root_from_args(args:",
        "window[0] == \"--handoff-state\" && window[1] == \"preparing\"",
    ] {
        assert!(
            !project_controller_source.contains(forbidden_snippet),
            "project_controller must not wrap pure controller command-line helpers: {forbidden_snippet}"
        );
    }
    assert!(
        controller_io_process
            .contains("agent_doc_controller::command_line::args_have_preparing_handoff"),
        "agent-doc-controller-io process scanning should call focused controller handoff command-line policy directly"
    );
    for required_snippet in [
        "pub fn process_start_age_secs(",
        "pub fn controller_serve_project_root(",
        "pub fn cmdline_has_preparing_handoff(",
    ] {
        assert!(
            controller_io_process.contains(required_snippet),
            "agent-doc-controller-io must own controller process-scan helpers: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "fn process_start_age_secs(",
        "fn controller_serve_project_root(",
        "fn cmdline_has_preparing_handoff(",
        "pub(crate) fn is_same_project_controller_pid(",
        "pub(crate) fn process_is_alive(",
        "pub(crate) fn system_boot_timestamp_secs(",
    ] {
        assert!(
            !project_controller_source.contains(forbidden_snippet),
            "project_controller must not wrap controller process-scan helpers: {forbidden_snippet}"
        );
    }
    assert!(
        project_controller_source.contains("crate::process::process_start_age_secs(")
            && project_controller_source.contains("crate::process::controller_serve_project_root(")
            && project_controller_source.contains("crate::process::cmdline_has_preparing_handoff(")
            && project_controller_source.contains(
                "use crate::process::{is_same_project_controller_pid, process_is_alive};"
            ),
        "project_controller should call focused controller process-scan helpers directly"
    );
    assert!(
        controller_io_process.contains(
            "agent_doc_controller::command_line::controller_serve_project_root_from_args"
        ),
        "agent-doc-controller-io process scanning should call focused controller command-line parsing directly"
    );
    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    // The crate's traversal is split across `lib.rs` (call surface + pure tree
    // lifts), `proc_table.rs` (the `/proc` observation) and `owner_graph.rs`
    // (the derived owner map). The guard is about the crate owning that
    // responsibility, not about which file it lands in, so read the whole crate.
    let process_owner_io_source = read_process_owner_io_source(manifest_dir);
    for forbidden_snippet in [
        "fn token_is_agent_doc_binary(",
        "fn token_is_harness_binary(",
        "fn token_is_non_owner_agent_doc_subcommand(",
        "fn cmdline_is_agent_doc_owner_session(",
        "fn cmdline_references_md_document(",
        "fn owner_document_from_cmdline(",
        "fn path_has_component_suffix(",
        "fn cmdline_has_file_match(",
        "fn agent_doc_cmdline_is_owner(",
        "fn cmdline_owns_other_document(",
        "fn pid_has_agent_doc_for_file(",
        "fn pid_is_agent_session(",
    ] {
        assert!(
            !sync_source.contains(forbidden_snippet),
            "sync.rs must not re-own pure process command-line ownership policy: {forbidden_snippet}"
        );
    }
    assert!(
        process_owner_io_source.contains("use agent_doc_controller::command_line::{")
            && process_owner_io_source.contains("agent_doc_cmdline_is_owner")
            && process_owner_io_source.contains("cmdline_owns_other_document")
            && process_owner_io_source.contains("owner_document_from_cmdline"),
        "agent-doc-process-owner-io should compose process effects with focused controller command-line policy"
    );
    assert!(
        process_owner_io_source.contains("fn observe_proc_children(")
            && process_owner_io_source.contains("fn proc_process_command(")
            && !process_owner_io_source.contains("Command::new(\"pgrep\")"),
        "agent-doc-process-owner-io process-tree traversal must use one /proc snapshot instead of shelling out to pgrep per node"
    );
    for required_snippet in [
        "pub fn process_tree_contains_pid(",
        "pub fn process_tree_agent_doc_owner_pid_for_file(",
        "pub fn process_tree_has_agent_doc_owner_for_file(",
        "pub fn process_tree_has_agent_session(",
        "pub fn process_tree_owner_document_other_than(",
        "pub fn process_tree_owns_other_document(",
    ] {
        assert!(
            process_owner_io_source.contains(required_snippet),
            "agent-doc-process-owner-io must own live process-owner inspection: {required_snippet}"
        );
    }
    assert!(
        sync_source
            .contains("agent_doc_process_owner_io::process_tree_agent_doc_owner_pid_for_file(")
            && sync_source
                .contains("agent_doc_process_owner_io::process_tree_has_agent_doc_owner_for_file(")
            && sync_source.contains("agent_doc_process_owner_io::process_tree_has_agent_session(")
            && sync_source
                .contains("agent_doc_process_owner_io::process_tree_owner_document_other_than(")
            && sync_source
                .contains("agent_doc_process_owner_io::process_tree_owns_other_document("),
        "sync.rs should adapt tmux panes into focused process-owner IO directly"
    );

    let authoritative_actor =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_actor.rs"))
            .unwrap();
    let route_authoritative_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_dispatch.rs"))
            .unwrap();
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_command_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/command.rs")).unwrap();
    let route_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch.rs")).unwrap();
    let route_direct_pane_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/direct_pane_dispatch.rs"))
            .unwrap();
    let route_dispatch_only_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_only.rs")).unwrap();
    let route_busy_pane_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/busy_pane.rs")).unwrap();
    let route_dispatch_recovery_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_recovery.rs"))
            .unwrap();
    let route_dispatch_start_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_start.rs")).unwrap();
    let route_dispatch_only_proof_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_only/proof.rs"))
            .unwrap();
    let route_dispatch_target_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_target.rs")).unwrap();
    let route_pane_provenance_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/pane_provenance.rs")).unwrap();
    let route_restart_handoff_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/restart_handoff.rs")).unwrap();
    let route_supervisor_runtime_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/supervisor_runtime.rs"))
            .unwrap();
    let route_startup_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup.rs")).unwrap();
    let route_startup_ready_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup_ready.rs")).unwrap();
    let route_pane_resolution_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/pane_resolution.rs")).unwrap();
    let route_diagnostics_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/diagnostics.rs")).unwrap();
    let route_closeout_drain_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/closeout_drain.rs")).unwrap();
    let route_pane_resolution_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route/pane_resolution.rs"))
            .unwrap();
    let route_admission_projection_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/admission_projection.rs"))
            .unwrap();
    let route_runtime_effects_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/runtime_effects.rs")).unwrap();
    let flow_types_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow/src/types.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/route/dispatch.rs")
            .exists()
            && !route_source.contains("mod dispatch;")
            && route_source.contains("use agent_doc_route_io::dispatch::"),
        "orchestration must not keep a route dispatch module after the dispatch transport/proof graph moves to agent-doc-route-io"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/route/authoritative_actor.rs")
            .exists()
            && !route_source.contains("mod authoritative_actor;")
            && route_source.contains("use agent_doc_route_io::authoritative_actor::{"),
        "orchestration must not keep a route authoritative-actor module after the actor/controller IO graph moves to agent-doc-route-io"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/route/cycle_ack.rs")
            .exists()
            && !route_source.contains("mod cycle_ack;")
            && route_source.contains("use agent_doc_route_io::admission_projection::")
            && route_runtime_effects_source.contains("pub fn route_admission_effects()"),
        "orchestration must not keep a route cycle-ack module after turn admission moves to the reactive Project Controller projection"
    );
    assert!(
        route_admission_projection_source.contains("await_turn_admission_projection_for_file(")
            && !route_admission_projection_source
                .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)"),
        "route admission must await the reactive Project Controller projection rather than poll cycle persistence"
    );
    for (source, required, context) in [
        (
            route_pane_resolution_io_source.as_str(),
            "agent_doc_cycle_state_io::load_with_closeout_projection(file)?",
            "route pane-resolution cycle baselines",
        ),
        (
            route_startup_source.as_str(),
            "agent_doc_cycle_state_io::load_with_closeout_projection(file).unwrap_or(None)",
            "route startup cycle baseline",
        ),
    ] {
        assert!(
            source.contains(required),
            "{context} should use closeout projection facts before compatibility cycle sidecars: {required}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/route/dispatch_only.rs")
            .exists()
            && !route_source.contains("mod dispatch_only;")
            && route_runtime_effects_source.contains("pub fn route_dispatch_only_effects()")
            && route_dispatch_only_source.contains("pub fn dispatch_only_send_reopen("),
        "orchestration must not keep a route dispatch-only module after the send/retry graph moves to agent-doc-route-io"
    );
    assert!(
        authoritative_actor.contains("agent_doc_controller::dispatch::dispatch_error_is_coalesced"),
        "route authorization should call the focused controller dispatch classifier directly"
    );
    assert!(
        authoritative_actor.contains(
            "agent_doc_controller::dispatch::stale_queue_pause_recovery_from_dispatch_error"
        ),
        "route authorization should call the focused stale-queue recovery classifier directly"
    );
    let controller_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/dispatch.rs")).unwrap();
    let controller_io_starting_actor_timeout = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/starting_actor_timeout.rs"),
    )
    .unwrap();
    let controller_io_starting_actor_timeout_production = controller_io_starting_actor_timeout
        .split("\n#[cfg(test)]")
        .next()
        .unwrap_or(&controller_io_starting_actor_timeout);
    for required_snippet in [
        "pub enum StartingActorTimeoutLogDecision",
        "pub fn record_starting_actor_timeout(",
        "pub fn starting_actor_timeout_record_matches(",
        "pub fn starting_actor_timeout_record_identity_matches(",
        "pub fn clear_starting_actor_timeout_record(",
        "StateFact::StartingActorTimeoutRecorded",
        "StateFact::StartingActorTimeoutCleared",
        "load_state_event_ledger",
        "append_state_event",
    ] {
        assert!(
            controller_io_starting_actor_timeout.contains(required_snippet),
            "agent-doc-controller-io must own starting-actor timeout state-backbone IO: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "route-starting-timeouts",
        "starting_actor_timeout_paths",
        "fs2::FileExt",
        "std::fs::write",
        "std::fs::remove_file",
    ] {
        assert!(
            !controller_io_starting_actor_timeout_production.contains(forbidden_snippet),
            "starting-actor timeout coalescing must not create hot-path files: {forbidden_snippet}"
        );
    }
    assert!(
        !authoritative_actor
            .contains("pub(crate) use agent_doc_controller_io::starting_actor_timeout")
            && authoritative_actor
                .contains("use agent_doc_controller_io::starting_actor_timeout::{")
            && authoritative_actor.contains("clear_starting_actor_timeout_record")
            && authoritative_actor.contains("record_starting_actor_timeout")
            && authoritative_actor.contains("StartingActorTimeoutLogDecision"),
        "agent-doc-route-io/authoritative_actor.rs should call starting-actor timeout IO without re-exporting it"
    );
    assert!(
        !route_source.contains("fn wait_for_authoritative_actor_ready(")
            && !route_source.contains("record_starting_actor_timeout(file_path,")
            && authoritative_actor.contains("pub fn wait_for_authoritative_actor_ready(")
            && authoritative_actor.contains("record_starting_actor_timeout(file_path")
            && authoritative_actor.contains("starting_actor_timeout_record_matches(file_path")
            && authoritative_actor.contains("clear_starting_actor_timeout_record(file_path"),
        "authoritative actor ready-wait IO should live in agent-doc-route-io and call starting-actor timeout state there"
    );
    for required_snippet in [
        "pub enum RoutedDispatchStartTracker",
        "pub fn codex_dispatch_start_tracking_enabled(",
        "fn codex_hooks_visible_from_file(",
        "fn codex_tracking_roots(",
        "pub fn build_routed_dispatch_start_tracker(",
        "fn codex_routed_dispatch_start_proof_facts",
        "fn opencode_pane_dispatch_start_proof_facts",
        "pub fn wait_for_routed_dispatch_start(",
        "agent_doc_codex_hook_io::load_latest_prompt_state_for_file(",
        "agent_doc_tmux_io::capture_pane(",
        "classify_codex_routed_dispatch_start_proof(",
        "opencode_pane_state_changed_from_idle(",
    ] {
        assert!(
            route_dispatch_start_source.contains(required_snippet),
            "agent-doc-route-io dispatch_start should own routed dispatch-start tracking IO: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "enum RoutedDispatchStartTracker",
        "fn codex_dispatch_start_tracking_enabled(",
        "fn codex_hooks_visible_from_file(",
        "fn codex_tracking_roots(",
        "fn build_routed_dispatch_start_tracker(",
        "fn codex_routed_dispatch_start_proof_facts",
        "fn opencode_pane_dispatch_start_proof_facts",
        "fn wait_for_routed_dispatch_start(",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own routed dispatch-start tracking IO after it moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    assert!(
        route_dispatch_source.contains("use crate::dispatch_start::{")
            && route_dispatch_source.contains("RoutedDispatchStartTracker")
            && route_dispatch_source.contains("build_routed_dispatch_start_tracker")
            && route_dispatch_source.contains("wait_for_routed_dispatch_start"),
        "agent-doc-route-io dispatch should call focused route dispatch-start IO directly"
    );
    for required_snippet in [
        "pub fn wait_for_dispatch_only_recycle_inflight_settle(",
        "pub fn dispatch_only_dispatch_start_proof_required(",
        "pub fn require_dispatch_only_dispatch_start_proof(",
        "pub fn dispatch_only_sent_log_message_for(",
        "pub fn dispatch_only_sent_console_message_for(",
        "agent_doc_controller_io::project_controller::supervisor_recycle_status_for_file(",
        "agent_doc_controller_io::project_controller::wait_for_supervisor_recycle_settle_for_file(",
        "agent_doc_state_backbone::SupervisorRecyclePhase::InFlight",
        "agent_doc_controller_io::project_controller::mark_route_submit_blocked(",
        "agent_doc_flow_io::log_flow_event(",
        "crate::dispatch_start::codex_dispatch_start_tracking_enabled(",
        "DispatchOnlyProofOutcomeFacts",
        "DispatchOnlyRecycleInflightMessageFacts",
        "accepted_only_dispatch_start_log_message(",
        "accepted_only_dispatch_start_refusal_message(",
        "dispatch_only_recycle_inflight_message(",
        "routed_dispatch_start_timeout_for_binary(",
    ] {
        assert!(
            route_dispatch_only_proof_source.contains(required_snippet),
            "agent-doc-route-io dispatch_only should own dispatch-only proof/recycle gate IO: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub(crate) fn dispatch_only_dispatch_start_proof_required(",
        "fn dispatch_only_test_sent_log_message(",
        "DispatchOnlyProofOutcomeFacts",
        "DispatchOnlyRecycleInflightMessageFacts",
        "accepted_only_dispatch_start_log_message(",
        "accepted_only_dispatch_start_refusal_message(",
        "dispatch_only_recycle_inflight_message(",
        "route_dispatch_only_recycle_inflight_unsettled file=",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own dispatch-only proof/recycle gate IO after route/dispatch_only.rs moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    assert!(
        route_dispatch_only_source.contains("pub struct DispatchOnlyQueuedPromptOutcome")
            && route_dispatch_only_source.contains("pub struct DispatchOnlyRouteEffects")
            && route_dispatch_only_source.contains("pub struct DispatchOnlySendReopenOptions")
            && route_dispatch_only_source.contains("pub fn dispatch_only_send_reopen(")
            && route_dispatch_only_source.contains("pub fn dispatch_only_reopen_existing_pane(")
            && route_dispatch_only_source.contains("pub fn retry_dispatch_only_after_busy_pane(")
            && route_dispatch_only_source
                .contains("agent_doc_queue::route_dispatch::dispatch_active_turn_queue_source")
            && route_dispatch_only_source.contains(
                "agent_doc_controller_io::project_controller::begin_route_submit_with_reason"
            ),
        "agent-doc-route-io dispatch_only.rs should own dispatch-only send/retry IO directly"
    );
    for required_snippet in [
        "pub struct RouteDispatchEffects",
        "pub struct RouteDispatchBugReportFacts",
        "pub struct BusyRouteQueuedDiagnosticFacts",
        "pub fn dispatch_via_supervisor_ipc_with_mode(",
        "pub fn dispatch_via_supervisor_ipc(",
        "pub fn dispatch_existing_managed_reopen(",
        "pub fn dispatch_routed_reopen(",
        "pub fn dispatch_routed_reopen_with_mode(",
        "pub fn send_command_checked(",
        "pub struct SupervisorIpcDispatchOptions",
        "pub struct DirectPaneDispatchOptions",
        "agent_doc_supervisor_io::ipc::send_command(",
        "agent_doc_controller_io::project_controller::begin_route_submit(",
        "agent_doc_tmux_io::input_diag::log_text_submit(",
        // #runfilesubmit: the pass-through single-submit branch must keep
        // verifying the trigger left the composer. Without it a submit key
        // absorbed by the harness TUI strands the trigger and route still
        // reports exit_code=0.
        "repair_pass_through_stranded_draft(tmux, file, pane, harness, &trigger)",
        "classify_pass_through_stranded_draft_action(PassThroughStrandedDraftFacts",
        "busy_dispatch_start_outcome(true, probe_proof)",
        "routed_dispatch_start_timeout_for_binary(Some(harness.binary.as_str()), cfg!(test))",
        "(effects.file_route_dispatch_bug_report)(RouteDispatchBugReportFacts",
        "(effects.emit_busy_route_queued_diagnostic)(BusyRouteQueuedDiagnosticFacts",
    ] {
        assert!(
            route_dispatch_source.contains(required_snippet),
            "agent-doc-route-io dispatch should own route dispatch transport/proof IO: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub struct CommandDispatchResult",
        "pub struct DirectPaneAcceptance",
        "pub struct RouteSubmitObservationLogFacts",
        "pub const DIRECT_PANE_SUBMIT_ACCEPTANCE_POLL_INTERVAL",
        "pub fn editor_route_attempt_id(",
        "pub fn preserve_route_pane_snapshot(",
        "pub fn print_route_pane_snapshot_hint(",
        "pub fn log_route_submit_observation(",
        "pub fn log_route_latency(",
        "pub fn log_dispatch_inject(",
        "pub fn poll_direct_pane_acceptance(",
        "pub fn send_direct_pane_enter_resubmit(",
        "pub fn send_direct_pane_enter_resubmit_until_stable(",
        "pub fn dead_harness_shell_dispatch_block(",
        "pub fn send_command_unchecked(",
        "pub fn send_command_once_unchecked(",
        "pub fn try_late_direct_pane_enter_resubmit_after_unproven_dispatch(",
        "DirectPaneAcceptancePollState::default()",
        "direct_pane_acceptance_poll_status(",
        ".saw_trigger_visible()",
        "DirectPaneEnterResubmitAttemptFacts",
        "direct_pane_can_continue_enter_resubmit(",
        "DirectPaneExistingDraftSubmitFacts",
        "direct_pane_can_enter_existing_draft(",
        "DirectPaneResubmitProofFacts",
        "direct_pane_resubmit_proof_line(",
        "DeadHarnessShellDispatchFacts",
        "classify_dead_harness_shell_dispatch_block(",
        "RoutedTriggerPayloadFacts",
        "routed_trigger_payload_rejection(",
        "agent_doc_controller_io::route_snapshot::preserve_route_pane_snapshot(",
        "agent_doc_tmux_io::send_submitted_text_for_harness_logged(",
        "agent_doc_controller_io::project_controller::supervisor_recycle_pending_for_file(",
        "agent_doc_controller_io::project_controller::wait_for_supervisor_recycle_settle_for_file(",
    ] {
        assert!(
            route_direct_pane_dispatch_source.contains(required_snippet),
            "agent-doc-route-io direct_pane_dispatch should own direct-pane dispatch IO: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub(crate) fn poll_direct_pane_acceptance(",
        "fn send_direct_pane_enter_resubmit(",
        "fn send_direct_pane_enter_resubmit_until_stable(",
        "pub(crate) fn dead_harness_shell_dispatch_block(",
        "pub(crate) fn send_command_unchecked(",
        "pub(crate) fn send_command_once_unchecked(",
        "fn try_late_direct_pane_enter_resubmit_after_unproven_dispatch(",
        "DirectPaneAcceptancePollState::default()",
        "route_redispatch_not_landed file=",
        "direct_pane_protected_prompt_input",
    ] {
        assert!(
            !route_dispatch_source.contains(forbidden_snippet),
            "route/dispatch.rs must not re-own direct-pane dispatch IO after it moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    assert!(
        route_dispatch_source.contains("use crate::direct_pane_dispatch::{")
            && route_dispatch_source.contains("send_command_unchecked")
            && route_dispatch_source
                .contains("try_late_direct_pane_enter_resubmit_after_unproven_dispatch(")
            && route_dispatch_source.contains("log_route_submit_observation(")
            && route_dispatch_source.contains("log_route_latency("),
        "agent-doc-route-io dispatch should call focused direct-pane route IO directly"
    );
    let unchecked_start = route_direct_pane_dispatch_source
        .find("pub fn send_command_unchecked(")
        .expect("direct-pane unchecked dispatch boundary should exist");
    let unchecked_end = route_direct_pane_dispatch_source[unchecked_start..]
        .find("pub fn send_command_once_unchecked(")
        .map(|offset| unchecked_start + offset)
        .expect("single-attempt direct-pane boundary should follow unchecked dispatch");
    let unchecked_body = &route_direct_pane_dispatch_source[unchecked_start..unchecked_end];
    assert_eq!(
        unchecked_body
            .matches("send_command_once_unchecked(")
            .count(),
        1,
        "one accepted direct-pane route may inject the full payload at most once"
    );
    assert!(
        !unchecked_body.contains("route_redispatch_not_landed"),
        "post-send absence must not authorize full-payload redispatch"
    );
    for required_snippet in [
        "pub enum DispatchActorState",
        "pub enum RouteDecision",
        "pub enum ActorDispatchState",
        "pub enum ReopenMode",
        "pub struct RoutedReopenFacts",
        "pub struct RoutedReopenOutcome",
        "pub fn decide_authoritative_reopen(",
        "pub enum AuthoritativeActorDispatchAction",
        "pub struct AuthoritativeActorDispatchActionFacts",
        "pub fn classify_authoritative_actor_dispatch_action(",
        "pub fn dispatch_only_focus_only_should_fail_closed(",
        "pub struct PromptReadyBarrierFacts",
        "pub enum PromptReadyBarrierDecision",
        "pub fn classify_prompt_ready_barrier(",
        "pub struct AuthoritativeActorReadyFacts",
        "pub struct AuthoritativePromptReadyBarrierFacts",
        "pub fn classify_authoritative_prompt_ready_barrier(",
        "pub struct DispatchOnlyStartingPaneActorReadyFacts",
        "pub fn dispatch_only_starting_pane_actor_ready(",
        "pub struct StartingActorLogFacts",
        "pub fn starting_actor_not_ready_log_line(",
        "pub fn starting_actor_ready_log_line(",
        "pub fn starting_actor_terminal_log_line(",
        "pub fn starting_actor_timeout_coalesced_log_line(",
        "pub const fn actor_start_wait_terminal_state(",
        "pub const fn actor_dispatch_blocker_reason(",
        "pub const fn actor_can_queue_optimistically(",
        "pub const fn busy_projection_repaired_by_ready_prompt(",
        "pub const fn actor_waiting_input_recoverable(",
        "pub fn actor_recovery_hint(",
        "pub enum BusyPaneAutoFixOutcome",
        "pub struct BusyPaneAutoFixFacts",
        "pub fn busy_existing_pane_auto_fix_outcome(",
        "pub struct DegradedAuthoritativeActorFacts",
        "pub fn can_use_degraded_authoritative_actor(",
        "pub struct DegradedAuthoritativeActorDirectSubmit",
        "pub fn degraded_authoritative_actor_direct_submit_log_message(",
        "pub enum RoutedReopenGuardReason",
        "pub fn prompt_ready_barrier_failed_event(",
        "pub fn dispatch_proof_failed_event(",
        "pub fn is_interactive_shell_substate_reason(",
        "pub fn dispatch_only_blocked_guard_reason(",
        "pub enum ActorLifecycleState",
        "pub fn effective_authoritative_actor_state(",
        "pub enum DispatchRuntimeHealth",
        "pub struct AuthoritativeRuntimeFacts",
        "pub fn authoritative_actor_dispatch_guard_reason(",
        "pub enum RoutedDispatchStartProof",
        "pub fn busy_dispatch_start_outcome(",
        "pub struct CodexRoutedDispatchStartProofFacts",
        "pub enum DispatchStartProofDecision",
        "pub struct DispatchStartProofFacts",
        "pub fn classify_dispatch_start_proof(",
        "pub fn classify_codex_routed_dispatch_start_proof(",
        "pub struct OpenCodePaneDispatchStartProofFacts",
        "pub fn opencode_pane_state_changed_from_idle(",
        "pub fn dispatch_only_dispatch_start_proof_required(",
        "pub struct RetryBudget",
        "pub fn authoritative_actor_ready_retry_budget(",
        "pub fn dispatch_only_starting_pane_ready_timeout_for_binary(",
        "pub fn dispatch_only_starting_pane_recovery_timeout_for_binary(",
        "pub fn dispatch_only_starting_pane_ready_retry_budget(",
        "pub fn dispatch_only_starting_pane_recovery_retry_budget(",
        "pub const STARTING_ACTOR_TIMEOUT_REASON",
        "pub struct StartingTimeoutActorFacts",
        "pub fn actor_blocked_by_starting_timeout(",
        "pub fn starting_timeout_blocked_actor_can_recover(",
        "pub struct StartupMissRouteFacts",
        "pub fn startup_miss_requires_fresh_start(",
        "pub fn startup_miss_superseded_by_later_open_start(",
        "pub fn startup_miss_should_restart_live_owner(",
        "pub fn startup_miss_should_fail_closed(",
        "pub enum FreshStartAdmissionOutcome",
        "pub const fn fresh_start_admission_outcome(",
        "pub struct DeadHarnessShellDispatchFacts",
        "pub fn classify_dead_harness_shell_dispatch_block(",
        "pub struct DispatchTargetBindFacts",
        "pub fn classify_dispatch_target_bind(",
        "pub struct DispatchTargetMatchFacts",
        "pub fn classify_dispatch_target_match(",
        "pub struct FreshDispatchTargetAfterReadyWaitFacts",
        "pub enum FreshDispatchTargetAfterReadyWaitDecision",
        "pub fn decide_fresh_dispatch_target_after_ready_wait(",
        "pub enum DirectPaneSubmitStatus",
        "pub fn direct_pane_submit_acceptance_timeout(",
        "pub fn direct_pane_submit_acceptance_budget(",
        "pub fn direct_pane_submit_outcome(",
        "pub struct DirectPaneDispatchStartProofFacts",
        "pub fn direct_pane_should_await_dispatch_start_proof(",
        "pub const DIRECT_PANE_EMPTY_ACCEPTANCE_STABLE_FOR",
        "pub struct DirectPaneAcceptancePollState",
        "pub fn direct_pane_acceptance_poll_status(",
        "pub const DIRECT_PANE_MAX_ENTER_RESUBMITS_DEFAULT",
        "pub fn direct_pane_max_enter_resubmits_from_env_value(",
        "pub fn direct_pane_max_enter_resubmits(",
        "pub struct DirectPaneEnterResubmitFacts",
        "pub fn direct_pane_needs_enter_resubmit(",
        "pub enum DirectPanePostSendAction",
        "pub struct DirectPanePostSendFacts",
        "pub const fn direct_pane_post_send_action(",
        "pub struct DirectPaneEnterResubmitAttemptFacts",
        "pub fn direct_pane_can_continue_enter_resubmit(",
        "pub struct DirectPaneExistingDraftSubmitFacts",
        "pub fn direct_pane_can_enter_existing_draft(",
        "pub fn dispatch_only_busy_should_wait_for_ready(",
        "pub fn dispatch_only_should_probe_active_turn_cue(",
        "pub enum CloseoutProjectionChange",
        "pub enum CloseoutDrainProjection",
        "pub const fn project_closeout_drain(",
        "pub enum RouteCloseoutDrainOutcome",
        "pub struct CloseoutBlockDispatchFacts",
        "pub enum CloseoutBlockDispatchDecision",
        "pub fn classify_closeout_block_dispatch(",
        "pub fn route_closeout_user_outcome_fields(",
        "pub struct RoutedAdmissionFacts",
        "pub fn should_require_routed_admission_projection(",
        "pub struct MissingAdmissionProjectionFacts",
        "pub fn should_optimistically_accept_missing_admission_projection(",
        "pub enum RouteSubmitObservation",
        "pub struct RouteSubmitObservationFacts",
        "pub fn route_submit_observation_message(",
        "pub fn route_submit_issue_message(",
        "pub struct RoutedTriggerPayloadFacts",
        "pub fn routed_trigger_payload_rejection(",
        "pub struct DirectPaneResubmitProofFacts",
        "pub fn direct_pane_resubmit_proof_line(",
        "pub enum RouteLatencyStatus",
        "pub struct RouteLatencyFacts",
        "pub fn route_latency_status(",
        "pub fn route_latency_message(",
        "pub struct RouteStartupMissDiagnosticFacts",
        "pub fn route_startup_miss_diagnostic_message(",
        "pub struct RouteBusyDiagnosticFacts",
        "pub fn route_busy_diagnostic_message(",
        "pub struct RouteBusyQueuedDiagnosticFacts",
        "pub fn route_busy_queued_diagnostic_message(",
        "pub fn failclosed_wait_context(",
        "pub fn format_busy_existing_pane_error(",
        "pub struct DuplicatePanePolicyErrorFacts",
        "pub fn duplicate_pane_policy_error_message(",
        "pub struct RouteDispatchBugReportItemFacts",
        "pub fn route_dispatch_bug_report_item(",
        "pub enum DispatchOnlyReopenDelivery",
        "pub struct DispatchOnlyProofOutcomeFacts",
        "pub const fn dispatch_only_should_print_unproven_progress(",
        "pub fn dispatch_only_sent_log_message(",
        "pub fn dispatch_only_sent_console_message(",
        "pub fn accepted_only_dispatch_start_log_message(",
        "pub fn accepted_only_dispatch_start_refusal_message(",
        "pub struct DispatchOnlyStartingPaneNotReadyMessageFacts",
        "pub fn dispatch_only_starting_pane_not_ready_message(",
        "pub struct DispatchOnlyRecycleInflightMessageFacts",
        "pub fn dispatch_only_recycle_inflight_message(",
        "pub struct DispatchOnlyBlockerRecoveryHintFacts",
        "pub fn dispatch_only_blocker_recovery_hint(",
        "pub fn routed_dispatch_start_timeout(",
        "pub fn routed_dispatch_start_timeout_for_binary(",
        "pub fn dispatch_start_busy_probe_timeout(",
        "pub fn dispatch_start_early_resubmit_probe_timeout(",
        "pub fn fresh_route_admission_timeout(",
        "pub fn routed_admission_timeout(",
        "pub fn existing_pane_ready_timeout(",
        "pub struct DispatchOnlyBusyRefusalFacts",
        "pub fn dispatch_only_busy_refusal_message(",
        "pub fn dispatch_only_busy_refusal_wait_secs(",
    ] {
        assert!(
            controller_dispatch.contains(required_snippet),
            "agent-doc-controller should own route dispatch policy directly: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub enum ActorRuntimeHealth",
        "fn effective_authoritative_actor_state(",
        "pub struct AuthoritativeRuntimeFacts",
        "pub fn authoritative_actor_dispatch_guard_reason(",
        "fn busy_dispatch_only_should_wait_for_ready(",
        "fn dispatch_only_should_probe_active_turn_cue(",
        "fn dispatch_only_starting_pane_ready_timeout_for_binary(",
        "fn dispatch_only_starting_pane_recovery_timeout(",
        "fn actor_blocked_by_starting_timeout(",
        "fn starting_timeout_blocked_actor_can_recover(",
        "fn startup_miss_requires_fresh_start(",
        "fn startup_miss_superseded_by_later_open_start(",
        "fn startup_miss_should_restart_live_owner(",
        "fn startup_miss_should_fail_closed(",
        "fn direct_pane_submit_acceptance_timeout(",
        "fn direct_pane_submit_acceptance_budget(",
        "fn direct_pane_submit_outcome(",
        "fn direct_pane_should_await_dispatch_start_proof(",
        "const DIRECT_PANE_EMPTY_ACCEPTANCE_STABLE_FOR",
        "struct DirectPaneAcceptancePollState",
        "fn direct_pane_acceptance_poll_status(",
        "enum DrainRetryDecision",
        "fn classify_drain_retry(",
        "enum RouteCloseoutDrainOutcome",
        "enum RouteCloseoutBlockDecision",
        "fn classify_closeout_block_dispatch(",
        "fn route_closeout_user_outcome_fields(",
        "enum RouteSubmitObservation",
        "fn route_submit_observation_message(",
        "fn route_submit_issue_message(",
        "fn route_latency_status(",
        "fn route_latency_message(",
        "fn startup_miss_diagnostic_message(",
        "fn busy_route_diagnostic_message(",
        "fn busy_route_queued_diagnostic_message(",
        "fn failclosed_wait_context(",
        "fn format_duplicate_pane_policy_error(",
        "fn route_dispatch_bug_report_item(",
        "fn routed_dispatch_start_timeout(",
        "fn codex_state_advanced(",
        "fn codex_routed_dispatch_start_proof(",
        "fn opencode_pane_state_changed_from_idle(",
        "fn dispatch_only_busy_refusal_message(",
        "fn dispatch_only_busy_refusal_wait_secs(",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own pure controller dispatch policy: {forbidden_snippet}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/route/busy_pane.rs")
            .exists()
            && !route_source.contains("mod busy_pane;")
            && !route_source.contains("pub(crate) use agent_doc_route_io::busy_pane::{")
            && route_pane_resolution_io_source.contains("use crate::busy_pane::{")
            && route_busy_pane_source.contains("pub fn ensure_existing_pane_ready_for_dispatch("),
        "orchestration must not keep or re-export a busy-pane route module after the graph moves to agent-doc-route-io"
    );
    assert!(
        !route_busy_pane_source.contains("fn busy_existing_pane_auto_fix_outcome(")
            && route_busy_pane_source.contains("controller_busy_existing_pane_auto_fix_outcome(")
            && route_busy_pane_source.contains("BusyPaneAutoFixFacts"),
        "agent-doc-route-io busy_pane should adapt supervisor facts into focused controller busy-pane auto-fix policy directly"
    );
    assert!(
        !route_source.contains("fn query_supervisor_runtime(")
            && !route_source.contains("fn restart_via_supervisor(")
            && !route_source.contains("fn pane_route_provenance(")
            && !route_source.contains("fn wait_for_starting_pane_recovery_target(")
            && !route_dispatch_source.contains("fn register_dispatch_target(")
            && !route_dispatch_source
                .contains("fn resolve_fresh_dispatch_target_after_ready_wait(")
            && !route_pane_resolution_source.contains("fn wait_for_busy_restart_handoff(")
            && !route_pane_resolution_source
                .contains("fn recover_dispatch_only_authoritative_waiting_input(")
            && !route_pane_resolution_source.contains("fn rescue_from_stash(")
            && !route_pane_resolution_source.contains("fn optimistic_busy_pane_dispatch(")
            && !route_pane_resolution_source.contains("fn retry_route_after_busy_pane_auto_fix(")
            && route_pane_resolution_source.contains(
                "agent_doc_route_io::pane_resolution::resolve_or_create_pane_dispatch_only("
            )
            && route_pane_resolution_source.contains(
                "agent_doc_route_io::pane_resolution::resolve_or_create_pane("
            )
            && route_pane_resolution_source.contains(
                "agent_doc_route_io::pane_resolution::resolve_or_create_pane_with_auto_fix_retry("
            )
            && route_pane_resolution_source.contains(
                "#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\npub(crate) fn resolve_or_create_pane_dispatch_only("
            )
            && route_supervisor_runtime_source.contains("pub fn query_supervisor_runtime(")
            && route_supervisor_runtime_source.contains("pub fn restart_via_supervisor(")
            && route_pane_provenance_source.contains("pub fn pane_route_provenance(")
            && route_dispatch_target_source.contains("pub fn register_dispatch_target(")
            && route_dispatch_recovery_source
                .contains("pub fn wait_for_starting_pane_recovery_target(")
            && route_dispatch_recovery_source
                .contains("pub fn resolve_fresh_dispatch_target_after_ready_wait(")
            && route_restart_handoff_source.contains("pub fn wait_for_busy_restart_handoff(")
            && route_pane_resolution_io_source.contains("pub fn dispatch_runtime_health(")
            && route_pane_resolution_io_source.contains("pub fn startup_miss_route_facts(")
            && route_pane_resolution_io_source
                .contains("pub fn fail_if_recent_session_loss_window(")
            && route_pane_resolution_io_source.contains("pub fn is_agent_process(")
            && route_pane_resolution_io_source.contains("pub fn cleanup_failed_route_panes(")
            && route_pane_resolution_io_source.contains("pub fn controller_dispatch_actor_state(")
            && route_pane_resolution_io_source
                .contains("pub fn recover_dispatch_only_authoritative_waiting_input(")
            && route_pane_resolution_io_source
                .contains("pub fn resolve_or_create_pane_dispatch_only(")
            && route_pane_resolution_io_source.contains("pub struct ManagedPaneResolutionEffects")
            && route_pane_resolution_io_source.contains("pub fn resolve_or_create_pane(")
            && route_pane_resolution_io_source.contains("pub fn rescue_from_stash(")
            && route_pane_resolution_io_source.contains("DispatchOnlyRouteEffects")
            && route_command_source.contains("crate::pane_resolution::resolve_or_create_pane(")
            && route_source.contains(
                "#[cfg(test)]\n#[path = \"route/pane_resolution.rs\"]\nmod pane_resolution;"
            )
            && route_pane_resolution_io_source.contains("dispatch_only_send_reopen(")
            && route_pane_resolution_io_source.contains("pub fn optimistic_busy_pane_dispatch(")
            && route_pane_resolution_io_source.contains("pub struct RouteBusyPaneRetryEffects")
            && route_pane_resolution_io_source
                .contains("pub fn retry_route_after_busy_pane_auto_fix(")
            && route_pane_resolution_io_source.contains("attempt_busy_existing_pane_auto_fix(")
            && route_pane_resolution_io_source
                .contains("attempt_busy_existing_pane_interrupt_recovery(")
            && route_pane_resolution_io_source.contains("RouteDispatchEffects")
            && route_pane_resolution_io_source.contains("RouteAdmissionEffects")
            && route_pane_resolution_io_source.contains("require_routed_admission_projection("),
        "shared route supervisor/provenance/dispatch-target/recovery/restart-handoff/pane-resolution helper IO should live in agent-doc-route-io"
    );
    for forbidden_snippet in [
        "fn dispatch_runtime_health(",
        "fn startup_miss_route_facts(",
        "fn startup_miss_route_provenance(",
        "fn fail_if_recent_session_loss_window(",
        "fn is_agent_process(",
        "fn cleanup_failed_route_panes(",
        "fn failed_route_pane_has_startup_miss(",
        "fn failed_route_registry_root(",
        "fn should_preserve_failed_route_pane(",
        "fn controller_dispatch_actor_state(",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route pane-resolution helper IO after it moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/routed_reopen.rs")
            .exists(),
        "orchestration must not keep a routed-reopen flow adapter"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow")
            .exists(),
        "orchestration flow must not expose routed-reopen facades"
    );
    assert!(
        !flow_types_source.contains("pub enum RouteDecision"),
        "agent-doc-flow types must not keep route decision policy after it moves to agent-doc-controller"
    );
    assert!(
        route_authoritative_dispatch_source.contains("use agent_doc_controller::dispatch::{")
            && route_authoritative_dispatch_source.contains("ActorDispatchState")
            && route_authoritative_dispatch_source.contains("ReopenMode")
            && route_authoritative_dispatch_source.contains("RoutedReopenFacts")
            && route_authoritative_dispatch_source.contains("decide_authoritative_reopen")
            && route_authoritative_dispatch_source.contains("AuthoritativeActorDispatchAction")
            && route_authoritative_dispatch_source
                .contains("AuthoritativeActorDispatchActionFacts")
            && route_authoritative_dispatch_source
                .contains("classify_authoritative_actor_dispatch_action")
            && authoritative_actor.contains("pub fn wait_for_authoritative_actor_ready(")
            && authoritative_actor.contains("PromptReadyBarrierDecision")
            && authoritative_actor.contains("AuthoritativeActorReadyFacts")
            && authoritative_actor.contains("AuthoritativePromptReadyBarrierFacts")
            && authoritative_actor.contains("classify_authoritative_prompt_ready_barrier")
            && route_authoritative_dispatch_source.contains("RoutedReopenGuardReason")
            && authoritative_actor.contains("prompt_ready_barrier_failed_event")
            && authoritative_actor.contains("agent_doc_flow_io::log_flow_event")
            && route_dispatch_only_source.contains("dispatch_only_blocked_guard_reason")
            && authoritative_actor.contains("effective_authoritative_actor_state")
            && route_pane_resolution_io_source.contains("DispatchRuntimeHealth")
            && route_pane_resolution_io_source.contains("RoutedDispatchStartProof")
            && authoritative_actor.contains("RetryBudget")
            && authoritative_actor.contains("authoritative_actor_ready_retry_budget")
            && route_authoritative_dispatch_source.contains("CloseoutBlockDispatchDecision")
            && route_closeout_drain_source.contains("CloseoutBlockDispatchFacts")
            && route_closeout_drain_source.contains("classify_closeout_block_dispatch")
            && route_authoritative_dispatch_source.contains("RouteCloseoutDrainOutcome")
            && route_authoritative_dispatch_source.contains("route_closeout_user_outcome_fields")
            && route_source.contains("dispatch_only_starting_pane_ready_timeout_for_binary")
            && route_authoritative_dispatch_source
                .contains("dispatch_only_starting_pane_recovery_timeout_for_binary")
            && route_dispatch_recovery_source
                .contains("dispatch_only_starting_pane_recovery_retry_budget")
            && authoritative_actor.contains("STARTING_ACTOR_TIMEOUT_REASON")
            && route_authoritative_dispatch_source.contains("StartingTimeoutActorFacts")
            && route_authoritative_dispatch_source.contains("actor_blocked_by_starting_timeout")
            && authoritative_actor.contains("starting_timeout_blocked_actor_can_recover")
            && route_pane_resolution_io_source.contains("StartupMissRouteFacts")
            && route_pane_resolution_io_source.contains("startup_miss_requires_fresh_start")
            && route_pane_resolution_io_source
                .contains("startup_miss_superseded_by_later_open_start")
            && route_pane_resolution_io_source.contains("startup_miss_should_restart_live_owner")
            && route_pane_resolution_io_source.contains("startup_miss_should_fail_closed")
            && route_admission_projection_source.contains("RoutedAdmissionFacts")
            && route_admission_projection_source
                .contains("should_require_routed_admission_projection")
            && route_admission_projection_source.contains("MissingAdmissionProjectionFacts")
            && route_admission_projection_source
                .contains("should_optimistically_accept_missing_admission_projection")
            && route_diagnostics_source.contains("RouteStartupMissDiagnosticFacts")
            && route_diagnostics_source.contains("route_startup_miss_diagnostic_message(")
            && route_diagnostics_source.contains("RouteBusyDiagnosticFacts")
            && route_diagnostics_source.contains("route_busy_diagnostic_message(")
            && route_diagnostics_source.contains("RouteBusyQueuedDiagnosticFacts")
            && route_diagnostics_source.contains("route_busy_queued_diagnostic_message(")
            && route_authoritative_dispatch_source.contains("failclosed_wait_context(")
            && route_diagnostics_source.contains("RouteDispatchBugReportItemFacts")
            && route_diagnostics_source.contains("route_dispatch_bug_report_item(")
            && route_authoritative_dispatch_source.contains("DispatchOnlyReopenDelivery")
            && route_dispatch_only_source.contains("dispatch_only_should_print_unproven_progress")
            && route_startup_source.contains("fresh_route_admission_timeout")
            && route_admission_projection_source.contains("routed_admission_timeout")
            && route_authoritative_dispatch_source.contains("DispatchOnlyBusyRefusalFacts")
            && route_authoritative_dispatch_source
                .contains("controller_dispatch_only_busy_refusal_message(")
            && route_pane_resolution_io_source.contains("DispatchActorState")
            && route_authoritative_dispatch_source
                .contains("dispatch_only_busy_should_wait_for_ready(")
            && route_authoritative_dispatch_source
                .contains("dispatch_only_should_probe_active_turn_cue(")
            && route_closeout_drain_source.contains("CloseoutProjectionChange")
            && route_closeout_drain_source.contains("CloseoutDrainProjection")
            && route_closeout_drain_source.contains("project_closeout_drain("),
        "agent-doc-route-io authoritative dispatch should project controller-owned closeout state directly"
    );
    assert!(
        route_diagnostics_source.contains("pub struct RouteDispatchBugReportEffects")
            && route_diagnostics_source.contains("pub fn file_route_dispatch_bug_report(")
            && route_diagnostics_source
                .contains("pub fn file_route_dispatch_bug_report_with_runtime_effects(")
            && route_diagnostics_source.contains("pub fn runtime_route_dispatch_bug_report_effects(")
            && route_diagnostics_source.contains("pub fn add_route_dispatch_bug_backlog_items(")
            && route_diagnostics_source
                .contains("agent_doc_element_backlog_runtime_io::RUNTIME_BACKLOG_COMMAND_EFFECTS")
            && route_diagnostics_source.contains("pub fn emit_startup_miss_diagnostic(")
            && route_diagnostics_source.contains("pub fn emit_busy_route_diagnostic(")
            && route_diagnostics_source.contains("pub fn emit_busy_route_queued_diagnostic(")
            && route_diagnostics_source
                .contains("pub fn emit_busy_route_queued_diagnostic_from_facts(")
            && route_diagnostics_source.contains("fn route_current_actor_generation(")
            && route_diagnostics_source.contains("fn route_ops_log_path(")
            && route_source.contains("use agent_doc_route_io::diagnostics::{")
            && route_source.contains(
                "file_route_dispatch_bug_report_with_runtime_effects as file_route_dispatch_bug_report"
            )
            && !route_source.contains("RouteDispatchBugReportEffects")
            && !route_source.contains("route_dispatch_bug_report_effects()")
            && !route_source.contains("file_route_dispatch_bug_report_with_effects("),
        "route diagnostics and dispatch-bug filing should live in agent-doc-route-io with runtime backlog effects owned outside orchestration"
    );
    for forbidden_snippet in [
        "fn route_current_actor_generation(",
        "fn route_ops_log_path(",
        "fn add_route_dispatch_bug_backlog_items(",
        "fn route_dispatch_bug_report_effects(",
        "fn route_dispatch_bug_force_disk_pending_writes(",
        "fn emit_busy_route_queued_diagnostic_from_facts(",
        "fn emit_startup_miss_diagnostic(",
        "fn emit_busy_route_diagnostic(",
        "fn emit_busy_route_queued_diagnostic(",
        "route_startup_miss_diagnostic_message(",
        "route_busy_diagnostic_message(",
        "route_busy_queued_diagnostic_message(",
        "route_dispatch_bug_report_item(RouteDispatchBugReportItemFacts",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route diagnostic or dispatch-bug filing IO after it moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    for forbidden_snippet in [
        "const DIRECT_PANE_EMPTY_ACCEPTANCE_STABLE_FOR",
        "struct DirectPaneAcceptancePollState",
        "fn direct_pane_acceptance_poll_status(",
        "const DIRECT_PANE_MAX_ENTER_RESUBMITS_DEFAULT",
        "fn direct_pane_max_enter_resubmits(",
        "fn direct_pane_needs_enter_resubmit(",
        "fn direct_pane_can_continue_enter_resubmit(",
        "fn direct_pane_can_enter_existing_draft(",
        "fn direct_pane_should_await_dispatch_start_proof(",
        "fn busy_dispatch_start_outcome(",
        "fn dispatch_start_busy_probe_timeout(",
        "fn dispatch_start_early_resubmit_probe_timeout(",
        "fn classify_dead_harness_shell_dispatch_block(",
        "fn decide_fresh_dispatch_target_after_ready_wait(",
        "fn resolve_fresh_dispatch_target_after_ready_wait(",
        "fresh restart re-bound",
        "fn resubmit_result_label(",
        "fn route_submit_resubmit_proof_line(",
        "fn routed_trigger_payload(",
        "fn validate_routed_trigger_payload(",
    ] {
        assert!(
            !route_dispatch_source.contains(forbidden_snippet),
            "route/dispatch.rs must not re-own direct-pane controller policy: {forbidden_snippet}"
        );
    }
    assert!(
        route_direct_pane_dispatch_source.contains("DirectPaneAcceptancePollState::default()")
            && route_direct_pane_dispatch_source.contains("direct_pane_acceptance_poll_status(")
            && route_direct_pane_dispatch_source.contains("direct_pane_submit_outcome")
            && route_direct_pane_dispatch_source.contains(".saw_trigger_visible()")
            && route_direct_pane_dispatch_source.contains("DirectPaneEnterResubmitAttemptFacts")
            && route_direct_pane_dispatch_source
                .contains("direct_pane_can_continue_enter_resubmit(")
            && route_direct_pane_dispatch_source.contains("DirectPaneExistingDraftSubmitFacts")
            && route_direct_pane_dispatch_source.contains("direct_pane_can_enter_existing_draft(")
            && route_direct_pane_dispatch_source.contains("DirectPaneResubmitProofFacts")
            && route_direct_pane_dispatch_source.contains("direct_pane_resubmit_proof_line(")
            && route_direct_pane_dispatch_source.contains("DeadHarnessShellDispatchFacts")
            && route_direct_pane_dispatch_source
                .contains("classify_dead_harness_shell_dispatch_block(")
            && route_direct_pane_dispatch_source.contains("RoutedTriggerPayloadFacts")
            && route_direct_pane_dispatch_source.contains("routed_trigger_payload_rejection(")
            && route_dispatch_source.contains("DirectPaneDispatchStartProofFacts")
            && route_dispatch_source.contains("direct_pane_should_await_dispatch_start_proof(")
            && route_dispatch_source.contains("routed_dispatch_start_timeout_for_binary(")
            && route_dispatch_source.contains("busy_dispatch_start_outcome(true, probe_proof)")
            && route_dispatch_source.contains("dispatch_start_busy_probe_timeout(cfg!(test))")
            && route_dispatch_source
                .contains("dispatch_start_early_resubmit_probe_timeout(cfg!(test))")
            && route_dispatch_recovery_source.contains("FreshDispatchTargetAfterReadyWaitFacts")
            && route_dispatch_recovery_source.contains("FreshDispatchTargetAfterReadyWaitDecision")
            && route_dispatch_recovery_source
                .contains("decide_fresh_dispatch_target_after_ready_wait(")
            && route_dispatch_source.contains("Some(harness.binary.as_str())")
            && route_dispatch_source.contains("cfg!(test)")
            && route_dispatch_source.contains("RoutedTriggerPayloadFacts")
            && route_dispatch_source.contains("routed_trigger_payload_rejection("),
        "route direct-pane IO should live in agent-doc-route-io while route dispatch keeps proof/supervisor adapters"
    );
    for forbidden_snippet in [
        "fn route_dispatch_only_sent_log_message(",
        "fn route_dispatch_only_sent_console_message(",
        "fn dispatch_only_starting_pane_actor_ready_gate(",
        "fn dispatch_only_starting_pane_not_ready_error(",
        "fn dispatch_only_recycle_inflight_error(",
        "fn dispatch_blocker_recovery_hint(",
        "pub fn dispatch_only_sent_log_message(",
        "pub fn accepted_only_dispatch_start_refusal_message(",
    ] {
        assert!(
            !route_dispatch_only_source.contains(forbidden_snippet),
            "agent-doc-route-io dispatch_only.rs must not re-own dispatch-only proof outcome policy: {forbidden_snippet}"
        );
    }
    assert!(
        route_dispatch_only_source.contains("DispatchOnlyStartingPaneActorReadyFacts")
            && route_dispatch_only_source.contains("dispatch_only_starting_pane_actor_settled(")
            && route_dispatch_only_source.contains("DispatchOnlyStartingPaneNotReadyMessageFacts")
            && route_dispatch_only_source
                .contains("dispatch_only_starting_pane_not_ready_message(")
            && route_dispatch_only_source.contains("DispatchOnlyBlockerRecoveryHintFacts")
            && route_dispatch_only_source.contains("dispatch_only_blocker_recovery_hint(")
            && route_dispatch_only_source.contains("dispatch_only_sent_log_message_for(")
            && route_dispatch_only_source.contains("dispatch_only_sent_console_message_for(")
            && route_dispatch_only_source.contains("dispatch_only_should_print_unproven_progress("),
        "agent-doc-route-io dispatch_only.rs should adapt route facts into focused controller readiness/proof policy"
    );
    for forbidden_snippet in [
        "pub(crate) fn fresh_route_admission_timeout(",
        "pub(crate) fn routed_admission_timeout(",
    ] {
        assert!(
            !route_admission_projection_source.contains(forbidden_snippet),
            "agent-doc-route-io admission_projection.rs must not wrap focused route timeout policy: {forbidden_snippet}"
        );
    }
    // `#jbroutasync`: pin the INVARIANT (route/test facts are passed into the
    // controller's timeout policy rather than recomputed locally), not the exact
    // call syntax — the admission-projection timeout also takes the client
    // deadline.
    assert!(
        route_admission_projection_source.contains("fresh_route_admission_timeout(cfg!(test))")
            && route_admission_projection_source
                .contains("routed_admission_timeout_with_client_deadline(")
            && route_admission_projection_source.contains("live_child_for_file,")
            && route_admission_projection_source.contains("cfg!(test),"),
        "agent-doc-route-io admission_projection.rs should pass route/test facts into focused controller timeout policy"
    );
    assert!(
        !route_busy_pane_source.contains("fn existing_pane_ready_timeout(")
            && route_busy_pane_source.contains("existing_pane_ready_timeout(cfg!(test))")
            && route_busy_pane_source.contains("fresh_route_admission_timeout(cfg!(test))"),
        "route/busy_pane.rs should pass route/test facts into focused controller timeout policy without wrappers"
    );
    assert!(
        !route_busy_pane_source.contains("fn format_busy_existing_pane_error(")
            && route_dispatch_only_source
                .contains("agent_doc_controller::dispatch::format_busy_existing_pane_error(")
            && route_pane_resolution_io_source
                .contains("agent_doc_controller::dispatch::format_busy_existing_pane_error("),
        "busy-pane user-facing error formatting should live in controller dispatch and route callers should use it directly"
    );
    assert!(
        !route_pane_resolution_source.contains("startup_miss_route_facts(")
            && !route_pane_resolution_source.contains("startup_miss_requires_fresh_start(")
            && !route_pane_resolution_source
                .contains("startup_miss_superseded_by_later_open_start(")
            && !route_pane_resolution_source.contains("startup_miss_should_restart_live_owner(")
            && !route_pane_resolution_source.contains("startup_miss_should_fail_closed(")
            && route_pane_resolution_source
                .contains("agent_doc_route_io::pane_resolution::resolve_or_create_pane(")
            && route_pane_resolution_io_source.contains("StartupMissRouteFacts")
            && route_pane_resolution_io_source.contains("startup_miss_requires_fresh_start(")
            && route_pane_resolution_io_source
                .contains("startup_miss_superseded_by_later_open_start(")
            && route_pane_resolution_io_source.contains("startup_miss_should_restart_live_owner(")
            && route_pane_resolution_io_source.contains("startup_miss_should_fail_closed("),
        "route pane resolution should adapt startup-miss sidecars in route IO while orchestration only forwards retained tests"
    );
    assert!(
        route_startup_source.contains("DuplicatePanePolicyErrorFacts")
            && route_startup_source.contains("duplicate_pane_policy_error_message("),
        "route startup IO should adapt tmux/session facts into focused duplicate-pane diagnostic policy"
    );
    for forbidden_snippet in [
        "pub(crate) enum FreshStartAdmissionOutcome",
        "pub(crate) fn fresh_start_admission_outcome(",
    ] {
        assert!(
            !route_startup_source.contains(forbidden_snippet),
            "route startup IO must not re-own fresh-start admission policy: {forbidden_snippet}"
        );
    }
    for required_snippet in [
        "pub fn auto_start_dispatch_ready_block(",
        "pub fn reverify_auto_start_dispatch_ready(",
        "AutoStartDispatchBlock",
        "AutoStartDispatchReadyFacts",
        "classify_auto_start_dispatch_ready_block(",
        "agent_doc_tmux_io::target_current_command(",
        "agent_doc_tmux::pane_current_command_is_bare_shell(",
        "auto_start_dispatch_ready_confirmed",
        "dispatch_into_starting_pane",
        "dispatch_into_shell",
        "FreshStartAdmissionOutcome",
        "fresh_start_admission_outcome",
        "agent_doc_harness::project_pane_composer_at_cursor(",
        "PaneComposerReadinessEvidence",
        "agent_doc_tmux_io::pane_cursor_y(tmux, pane_id)",
    ] {
        assert!(
            route_startup_ready_source.contains(required_snippet),
            "agent-doc-route-io startup_ready should own startup readiness/fresh-start admission route IO: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub(crate) fn auto_start_dispatch_ready_block(",
        "pub(crate) fn reverify_auto_start_dispatch_ready(",
        "AutoStartDispatchReadyFacts",
        "classify_auto_start_dispatch_ready_block(",
        "dispatch_into_starting_pane file=",
    ] {
        assert!(
            !route_dispatch_source.contains(forbidden_snippet),
            "route/dispatch.rs must not re-own auto-start dispatch-ready reverify IO after it moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    assert!(
        route_startup_source.contains("crate::startup_ready::reverify_auto_start_dispatch_ready("),
        "route startup IO should call focused route startup-ready IO directly"
    );
    for forbidden_snippet in [
        "pub(crate) fn should_require_routed_admission_projection(",
        "pub(crate) fn should_optimistically_accept_missing_admission_projection(",
    ] {
        assert!(
            !route_admission_projection_source.contains(forbidden_snippet),
            "agent-doc-route-io admission_projection.rs must not re-own pure controller dispatch policy: {forbidden_snippet}"
        );
    }
    assert!(
        route_admission_projection_source.contains("RoutedAdmissionFacts")
            && route_admission_projection_source
                .contains("should_require_routed_admission_projection(")
            && route_admission_projection_source.contains("MissingAdmissionProjectionFacts")
            && route_admission_projection_source
                .contains("should_optimistically_accept_missing_admission_projection("),
        "agent-doc-route-io admission_projection.rs should adapt cycle and harness facts into focused controller policy"
    );
    let sim_world = fs::read_to_string(manifest_dir.join("src/sim_world/engine.rs")).unwrap();
    assert!(
        sim_world.contains("agent_doc_controller::dispatch::dispatch_should_coalesce_in_flight"),
        "SimWorld should share the focused controller dispatch classifier directly"
    );
    let controller_claim =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/claim.rs")).unwrap();
    for required_snippet in [
        "pub enum CrossSessionDecision",
        "pub const CROSS_SESSION_REJECT_MARKER",
        "pub fn cross_session_reject_marker(",
        "pub fn cross_session_decision(",
        "pub fn cross_session_decision_with_lease(",
    ] {
        assert!(
            controller_claim.contains(required_snippet),
            "agent-doc-controller should own claim admission policy directly: {required_snippet}"
        );
    }
    let claim_source =
        fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub enum CrossSessionDecision",
        "pub const CROSS_SESSION_REJECT_MARKER",
        "pub fn cross_session_reject_marker(",
        "pub fn cross_session_decision(",
        "pub fn cross_session_decision_with_lease(",
    ] {
        assert!(
            !claim_source.contains(forbidden_snippet),
            "claim.rs must stay a tmux/file adapter and not re-own controller claim policy: {forbidden_snippet}"
        );
    }
    assert!(
        claim_source.contains("use agent_doc_controller::claim::{"),
        "claim.rs should call focused controller claim policy directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/claim.rs")
            .exists(),
        "orchestration must not keep claim.rs as a command adapter facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod claim;"),
        "orchestration must not expose a claim command facade"
    );
    let workspace_manifest_source = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace_manifest: toml::Value = toml::from_str(&workspace_manifest_source).unwrap();
    let workspace_members = workspace_manifest["workspace"]["members"]
        .as_array()
        .unwrap();
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-claim-io")),
        "workspace must include agent-doc-claim-io"
    );
    let claim_manifest_source =
        fs::read_to_string(manifest_dir.join("agent-doc-claim-io/Cargo.toml")).unwrap();
    let claim_manifest: toml::Value = toml::from_str(&claim_manifest_source).unwrap();
    let claim_dependencies = claim_manifest["dependencies"].as_table().unwrap();
    assert!(
        !claim_dependencies.contains_key("agent-doc-orchestration"),
        "claim IO must not depend back on orchestration"
    );
    let controller_operator_clear =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/operator_clear.rs"))
            .unwrap();
    for required_snippet in [
        "pub enum OperatorClearInputState",
        "pub enum OperatorClearGuardOutcome",
        "pub const fn clear_guard_outcome",
        "pub const fn clear_guard_flow_outcome",
        "pub fn clear_guard_event",
    ] {
        assert!(
            controller_operator_clear.contains(required_snippet),
            "agent-doc-controller should own operator-clear guard policy and flow mapping directly: {required_snippet}"
        );
    }
    assert!(
        controller_operator_clear.contains("use agent_doc_flow::types::{"),
        "agent-doc-controller should use the shared flow vocabulary for operator-clear events"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/operator_clear.rs")
            .exists(),
        "orchestration must not keep an operator-clear flow adapter"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow")
            .exists(),
        "orchestration flow must not expose operator-clear facades"
    );
    let session_actor_cmd_source =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    assert!(
        session_actor_cmd_source.contains("use agent_doc_controller::operator_clear::{")
            && session_actor_cmd_source.contains("OperatorClearInputState")
            && session_actor_cmd_source.contains("clear_guard_event")
            && session_actor_cmd_source
                .contains("use agent_doc_controller::operator_clear::OperatorClearGuardOutcome;")
            && session_actor_cmd_source.contains("agent_doc_flow_io::log_flow_event")
            && session_actor_cmd_source.contains("clear_guard_event(clear_state)")
            && !session_actor_cmd_source
                .contains("agent_doc_orchestration::flow::operator_clear::OperatorClearInputState"),
        "session actor commands should import focused operator-clear policy and flow mapping directly"
    );

    let controller_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&controller_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-controller must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_stale_supervisor_recycle_is_checked_at_every_turn_stage() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    for (relative_path, stage) in [
        (
            "agent-doc-preflight-command-io/src/run.rs",
            "preflight_entry",
        ),
        ("agent-doc-run-io/src/lib.rs", "generation_cycle_start"),
        ("agent-doc-stream-io/src/lib.rs", "stream_generation_start"),
        (
            "agent-doc-write-runtime-io/src/lib.rs",
            "finalize_write_start",
        ),
        ("agent-doc-commit-io/src/lib.rs", "commit_start"),
        ("agent-doc-compact-io/src/lib.rs", "compact_start"),
        (
            "agent-doc-session-check-io/src/command.rs",
            "session_check_start",
        ),
        (
            "agent-doc-session-check-io/src/command.rs",
            "closeout_proof_start",
        ),
        ("agent-doc-flow-io/src/closeout.rs", "closeout_evidence"),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("recycle_stale_supervisor_for_turn_stage(") && source.contains(stage),
            "{relative_path} must schedule a proven-stale supervisor recycle at stage {stage}"
        );
    }

    let preflight_queue =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    assert!(
        preflight_queue.contains("agent_doc_crdt_relay_io::apply_cp_write_for_file(")
            && preflight_queue.contains("authority=lazily surface=queue_maintenance")
            && !preflight_queue.contains("schedule_stale_editor_replica_cp_recycle("),
        "queue convergence must make one Lazily-authoritative compare-and-swap instead of starting a recycle side path"
    );
}

#[test]
fn test_agent_doc_controller_owns_editor_route_error_path_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/lib.rs")).unwrap();
    let controller_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/editor_route_error.rs"))
            .unwrap();
    let controller_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/lib.rs")).unwrap();
    let controller_io_adapter =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/editor_route_errors.rs"))
            .unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");

    assert!(
        controller_lib.contains("pub mod editor_route_error;"),
        "agent-doc-controller should expose editor route-error path policy as a focused module"
    );
    for required in [
        "pub const EDITOR_ROUTE_ERROR_DIAGNOSTICS_DIR",
        "pub enum EditorRouteErrorClearResult",
        "pub fn editor_route_error_diagnostic_name(",
        "pub fn editor_route_error_file_name(",
        "pub fn editor_route_error_path_for_file(",
        "pub fn clear_editor_route_error_for_file(",
    ] {
        assert!(
            controller_policy.contains(required),
            "agent-doc-controller must own editor route-error path/clear policy: {required}"
        );
    }
    for forbidden in [
        "fn route_error_path_for_file(",
        "fn sanitized_route_error_name(",
        "pub fn editor_route_error_diagnostic_name(",
        "pub fn editor_route_error_file_name(",
        "pub fn editor_route_error_path_for_file(",
        "pub const EDITOR_ROUTE_ERROR_DIAGNOSTICS_DIR",
        "pub use agent_doc_controller::editor_route_error",
        "std::fs::remove_file(",
        "ErrorKind::NotFound",
    ] {
        assert!(
            !controller_io_adapter.contains(forbidden),
            "controller IO editor route-error adapter must not re-own or facade path/clear policy: {forbidden}"
        );
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration lib must not facade editor route-error path/clear policy: {forbidden}"
        );
    }
    assert!(
        controller_io_lib.contains("pub mod editor_route_errors;")
            && controller_io_adapter.contains("use agent_doc_controller::editor_route_error::{")
            && controller_io_adapter.contains("clear_editor_route_error_for_file")
            && controller_io_adapter.contains("EditorRouteErrorClearResult")
            && controller_io_adapter.contains("pub fn clear_for_success("),
        "agent-doc-controller-io should import focused editor route-error clear policy directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/editor_route_errors.rs")
            .exists()
            && !orchestration_lib.contains("pub mod editor_route_errors;"),
        "orchestration must not keep an editor_route_errors facade"
    );
    for relative in [
        "agent-doc-route-io/src/command.rs",
        "agent-doc-sync-io/src/sync.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_controller_io::editor_route_errors::clear_for_success("),
            "{relative} should call controller IO editor route-error adapter directly"
        );
        assert!(
            !source.contains("crate::editor_route_errors::clear_for_success("),
            "{relative} must not call the removed orchestration editor_route_errors facade"
        );
    }
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-controller-io"),
        "agent-doc-orchestration should depend on controller IO directly"
    );
}

#[test]
fn test_jetbrains_run_agent_doc_uses_cp_editor_route_rpc() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let terminal_util = fs::read_to_string(
        manifest_dir
            .join("editors/jetbrains/src/main/kotlin/com/github/btakita/agentdoc/TerminalUtil.kt"),
    )
    .unwrap();
    let route_client = fs::read_to_string(
        manifest_dir
            .join("editors/jetbrains/src/main/kotlin/com/github/btakita/agentdoc/CpRouteClient.kt"),
    )
    .unwrap();
    let controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    let editor_route_handler = controller_rpc
        .split("fn handle_editor_route_rpc(")
        .nth(1)
        .and_then(|tail| tail.split("fn editor_route_relative_path(").next())
        .expect("controller RPC should expose handle_editor_route_rpc");

    assert!(
        controller_rpc.contains("\"editor_route\"")
            && controller_rpc.contains("fn handle_editor_route_rpc(")
            && controller_rpc.contains("run_editor_route(ControllerEditorRouteInvocation")
            && controller_rpc.contains("EditorRouteAttemptIdGuard::set(")
            && controller_rpc.contains("validate_editor_route_layout_args("),
        "project controller must expose a high-level editor_route RPC over CP and execute the route through runtime effects"
    );
    assert!(
        !editor_route_handler.contains("Command::new(&binary)")
            && !editor_route_handler.contains("\"route\".to_string()"),
        "project controller editor_route must not shell out to the route CLI"
    );
    assert!(
        route_client
            .contains("request.addProperty(\"command\", EditorCommandName.EditorRoute.token)")
            && route_client.contains("EditorRoute(\"editor_route\")")
            && route_client
                .contains("request.addProperty(\"diagnostic_payload\", payload.toString())")
            && route_client.contains("File(projectRoot, \".agent-doc/controller.sock\")")
            && route_client
                .contains("SocketChannel.open(UnixDomainSocketAddress.of(socket.toPath()))"),
        "JetBrains Run Agent Doc must send editor_route over the existing CP/controller socket"
    );
    assert!(
        terminal_util.contains("CpRouteClient.runEditorRoute(")
            && terminal_util.contains("buildEditorRouteRequestCommand(relativePath)")
            && terminal_util.contains("attemptId = attempt?.id")
            && terminal_util.contains("routeKey = attempt?.routeKey")
            && terminal_util.contains("transport=cp")
            && !terminal_util.contains("ProcessBuilder(cmd)")
            && !terminal_util.contains("val cmd = buildRunRouteCommand("),
        "JetBrains Run Agent Doc must not launch the route dispatch CLI from the plugin"
    );
}

#[test]
fn test_agent_doc_controller_owns_fleet_dashboard_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/lib.rs")).unwrap();
    let controller_fleet =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/fleet.rs")).unwrap();
    let controller_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/lib.rs")).unwrap();
    let controller_io_dashboard =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/dashboard.rs")).unwrap();

    assert!(
        controller_lib.contains("pub mod fleet;"),
        "agent-doc-controller should expose fleet dashboard policy as a focused module"
    );
    for required in [
        "pub struct AdminActor",
        "pub struct AdminFinding",
        "pub struct ActorListRecord",
        "pub struct ActorListRegistryBinding",
        "pub struct AdminReceiptLine",
        "pub struct DashboardRow",
        "pub struct DashboardActorDiagnostics",
        "pub struct DashboardModel",
        "pub fn build_admin_actor_list(",
        "pub fn format_admin_receipt_line(",
        "pub fn detect_admin_findings(",
        "pub fn build_dashboard_model(",
        "pub fn build_dashboard_model_with_diagnostics(",
        "pub fn render_dashboard(",
    ] {
        assert!(
            controller_fleet.contains(required),
            "agent-doc-controller must own fleet dashboard policy: {required}"
        );
    }
    assert!(
        controller_io_lib.contains("pub mod dashboard;"),
        "agent-doc-controller-io should expose dashboard IO as a focused adapter"
    );
    for required in [
        "pub trait DashboardEffects",
        "pub const DEFAULT_INTERVAL_MS",
        "pub fn resolve_root(",
        "pub fn snapshot_model",
        "pub fn dashboard",
        "build_admin_actor_list",
        "detect_admin_findings",
        "build_dashboard_model_with_diagnostics",
        "render_dashboard",
        "agent_doc_fs::find_project_root",
    ] {
        assert!(
            controller_io_dashboard.contains(required),
            "agent-doc-controller-io must own dashboard snapshot/render IO: {required}"
        );
    }

    let admin_io = fs::read_to_string(manifest_dir.join("agent-doc-admin-io/src/lib.rs")).unwrap();
    let cli_dashboard = fs::read_to_string(manifest_dir.join("src/dashboard_cmd.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/dashboard.rs")
            .exists(),
        "orchestration must not keep a dashboard facade module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/admin.rs")
            .exists(),
        "orchestration must not keep an admin command facade module"
    );
    for forbidden in [
        "pub struct AdminActor",
        "pub struct AdminFinding",
        "pub struct DashboardRow",
        "pub struct DashboardActorDiagnostics",
        "pub struct DashboardModel",
        "pub fn detect_findings(",
        "pub fn detect_admin_findings(",
        "pub(crate) fn detect_admin_findings(",
        "pub fn build_dashboard_model(",
        "pub fn build_dashboard_model_with_diagnostics(",
        "pub fn render_dashboard(",
        "fn truncate(",
        "fn queue_summary(",
        "fn row_flags(",
        "pub use agent_doc_controller::fleet",
        "pub(crate) use agent_doc_controller::fleet",
    ] {
        assert!(
            !cli_dashboard.contains(forbidden),
            "orchestration must not re-own or facade fleet dashboard policy: {forbidden}"
        );
    }
    for forbidden in [
        "build_admin_actor_list",
        "detect_admin_findings",
        "build_dashboard_model_with_diagnostics",
        "render_dashboard",
        "serde_json::to_string_pretty",
        "std::thread::sleep",
        "agent_doc_fs::find_project_root",
    ] {
        assert!(
            !cli_dashboard.contains(forbidden),
            "CLI dashboard should only adapt effects, not own dashboard IO/modeling: {forbidden}"
        );
    }
    assert!(
        admin_io.contains("pub trait AdminControllerEffects")
            && admin_io.contains("use agent_doc_controller::fleet::{")
            && admin_io.contains("ActorListRecord")
            && admin_io.contains("ActorListRegistryBinding")
            && admin_io.contains("build_admin_actor_list")
            && admin_io.contains("detect_admin_findings")
            && admin_io.contains("format_admin_receipt_line")
            && admin_io.contains("pub fn list(")
            && admin_io.contains("pub fn inspect(")
            && admin_io.contains("pub fn queue_control(")
            && admin_io.contains("pub fn reap_all_stale("),
        "agent-doc-admin-io should own admin command rendering and call focused fleet list/finding/receipt policy directly"
    );
    let cli_main = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        cli_main.contains(
            "impl agent_doc_admin_io::AdminControllerEffects for CliAdminControllerEffects"
        ) && cli_main.contains("agent_doc_controller_io::project_controller::load_actor_store")
            && cli_main.contains("agent_doc_session_registry_io::load_in")
            && cli_main.contains("tmux_router::Tmux::default_server")
            && cli_main.contains("agent_doc_admin_io::inspect(")
            && !cli_main.contains("agent_doc_orchestration::admin::"),
        "CLI should adapt concrete admin effects and call agent-doc-admin-io directly"
    );
    let reap_admin_start = cli_main
        .find("AdminAction::ReapStaleControllers")
        .expect("admin reap-stale-controllers branch should exist");
    let reap_admin_end = reap_admin_start
        + cli_main[reap_admin_start..]
            .find("AdminAction::Recycle")
            .expect("admin recycle branch should follow reap-stale-controllers");
    let reap_admin = &cli_main[reap_admin_start..reap_admin_end];
    assert!(
        reap_admin.contains("terminate_stale_preparing_controllers_for_caller")
            && reap_admin.contains("reap_orphaned_preparing_controllers_for_caller"),
        "admin reap-stale-controllers should aggregate record-scoped and orphaned process-scan reapers"
    );
    assert!(
        cli_dashboard.contains("impl DashboardEffects for CliDashboardEffects")
            && cli_dashboard.contains("ActorListRecord")
            && cli_dashboard.contains("ActorListRegistryBinding")
            && cli_dashboard.contains("DashboardActorDiagnostics")
            && cli_dashboard
                .contains("agent_doc_controller_io::project_controller::load_actor_store")
            && cli_dashboard.contains("agent_doc_session_registry_io::load_in")
            && cli_dashboard.contains("Tmux::default_server().pane_alive")
            && cli_dashboard.contains("agent_doc_controller_io::project_controller::inspect_actor")
            && cli_dashboard.contains("agent_doc_controller_io::dashboard::dashboard(&EFFECTS"),
        "CLI dashboard should only adapt concrete actor/session/tmux/controller effects"
    );

    let controller_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&controller_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-controller fleet policy must stay free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
    let controller_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/Cargo.toml")).unwrap();
    let controller_dashboard_source =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/dashboard.rs")).unwrap();
    let parsed: toml::Value = toml::from_str(&controller_io_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-controller",
        "agent-doc-fs",
        "anyhow",
        "serde_json",
    ] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-controller-io dashboard adapter should depend on focused dependency {required}"
        );
    }
    for forbidden in ["agent-doc-orchestration", "notify", "git2"] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-controller-io must not depend on orchestration-side systems: {forbidden}"
        );
    }
    for forbidden in ["agent_doc_sqlite", "interprocess", "notify", "tmux_router"] {
        assert!(
            !controller_dashboard_source.contains(forbidden),
            "agent-doc-controller-io dashboard adapter must not directly use controller runtime systems: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_turn_executor_owns_capability_proof_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let package_version = workspace["package"]["version"].as_str();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    let executor_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/capability_proof.rs"))
            .unwrap();
    let executor_codex_launch =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/codex_launch.rs"))
            .unwrap();
    let executor_claude_launch =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/claude_launch.rs"))
            .unwrap();
    let executor_opencode_launch =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/opencode_launch.rs"))
            .unwrap();
    let executor_agent_stream =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/agent_stream.rs"))
            .unwrap();
    let executor_capture =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/capture.rs")).unwrap();
    let executor_binary =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/binary.rs")).unwrap();
    for required_snippet in [
        "pub struct ManagedProofPolicy",
        "pub struct ManagedProofPolicyInputs",
        "pub enum ProofRetryDecision",
        "pub fn resolve_managed_proof_policy(",
        "pub fn proof_retry_decision(",
        "pub fn managed_capability_proof_status_message(",
    ] {
        assert!(
            executor_policy.contains(required_snippet),
            "agent-doc-turn-executor should own capability-proof policy directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV",
        "pub fn default_base_args(",
        "pub fn structural_base_args(",
        "pub enum CodexResumeRestartArgsError",
        "pub struct CodexNetworkPolicyStatus",
        "pub fn resolve_codex_network_access(",
        "pub fn apply_codex_network_access_env_map(",
        "pub fn apply_codex_network_access_env_overrides(",
        "pub fn codex_network_status_from_env_map(",
        "pub fn codex_network_status_from_overrides(",
        "pub fn codex_resume_restart_args(",
        "pub fn looks_like_codex_transport_403_429(",
        "pub fn codex_transport_403_429_diagnostic(",
        "pub struct CodexStderrNoiseReport",
        "pub fn codex_stderr_noise_report(",
        "pub fn filter_codex_stderr_noise(",
        "pub fn codex_exec_args_for_probe(",
        "pub fn opencode_run_args_for_probe(",
        "pub fn codex_child_network_probe_prompt(",
        "pub fn opencode_child_network_probe_prompt(",
        "pub fn opencode_child_required_ssh_probe_prompt(",
        "pub fn codex_child_writable_roots_probe_prompt(",
        "pub fn looks_like_opencode_usage_output(",
        "pub fn validate_codex_child_network_probe_output(",
        "pub fn validate_opencode_child_probe_marker_output(",
        "pub fn validate_codex_child_writable_root_probe_output(",
        "pub fn add_dirs_from_args(",
        "pub fn args_contain_add_dir(",
        "pub fn normalized_writable_root_strings(",
        "pub fn writable_root_contract_id(",
        "pub fn proof_status_label(",
        "pub fn proof_timing_ms(",
        "pub struct ManagedCapabilityProofTimings",
        "pub fn managed_network_child_proof_cache_key(",
        "pub fn classify_child_network_probe_failure(",
        "pub fn classify_child_required_ssh_probe_failure(",
        "pub fn classify_child_writable_root_probe_failure(",
        "pub fn looks_like_local_browser_cdp_permission_denied(",
        "pub fn resume_capability_drift_notice(",
        "pub fn looks_like_ssh_dns_failure(",
        "pub fn looks_like_ssh_network_failure(",
        "pub fn looks_like_ssh_auth_failure(",
        "pub fn looks_like_ssh_alias_config_failure(",
        "pub fn transcript_has_required_ssh_failure(",
        "pub fn transcript_proves_required_ssh_success(",
        "pub fn format_required_ssh_failure(",
    ] {
        assert!(
            executor_codex_launch.contains(required_snippet),
            "agent-doc-turn-executor should own Codex launch/transport policy directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn default_base_args(",
        "pub fn structural_base_args(",
        "pub fn claude_json_args(",
        "pub fn claude_streaming_args(",
        "fn append_claude_session_args(",
    ] {
        assert!(
            executor_claude_launch.contains(required_snippet),
            "agent-doc-turn-executor should own Claude launch argv policy directly: {required_snippet}"
        );
    }
    for required_snippet in ["pub fn default_base_args(", "pub fn opencode_run_args("] {
        assert!(
            executor_opencode_launch.contains(required_snippet),
            "agent-doc-turn-executor should own OpenCode launch argv policy directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub struct StreamChunk",
        "pub trait StreamingAgent",
        "pub fn parse_stream_line(",
        "pub fn parse_codex_line(",
    ] {
        assert!(
            executor_agent_stream.contains(required_snippet),
            "agent-doc-turn-executor should own agent stream parsing and contract directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn capture_delta(",
        "pub fn limit_capture_lines(",
        "capture_delta_returns_from_first_modified_line",
    ] {
        assert!(
            executor_capture.contains(required_snippet),
            "agent-doc-turn-executor should own executor capture-delta policy directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub const AGENT_DOC_BIN_ENV",
        "pub fn current_agent_doc_binary(",
        "pub fn resolve_agent_doc_binary_from_env(",
        "fn launchable_agent_doc_binary(",
        "fn path_looks_like_agent_doc_binary(",
        "pub fn internal_command_spawn_context(",
    ] {
        assert!(
            executor_binary.contains(required_snippet),
            "agent-doc-turn-executor should own agent-doc binary launch resolution directly: {required_snippet}"
        );
    }

    let agent_mod =
        fs::read_to_string(manifest_dir.join("agent-doc-agent-io/src/agent/mod.rs")).unwrap();
    for forbidden_snippet in [
        "pub struct ManagedProofPolicy",
        "pub enum ProofRetryDecision",
        "pub fn resolve_managed_proof_policy(",
        "pub fn proof_retry_decision(",
        "DEFAULT_MANAGED_PROOF",
        "MAX_MANAGED_PROOF",
        "pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV",
        "pub struct CodexNetworkPolicyStatus",
        "pub fn resolve_codex_network_access(",
        "pub fn apply_codex_network_access_env_map(",
        "pub fn apply_codex_network_access_env_overrides(",
        "pub fn codex_network_status_from_env_map(",
        "pub fn codex_network_status_from_overrides(",
    ] {
        assert!(
            !agent_mod.contains(forbidden_snippet),
            "agent::mod must not re-own capability-proof or Codex network launch policy: {forbidden_snippet}"
        );
    }
    assert!(
        agent_mod.contains("agent_doc_turn_executor::opencode_launch::default_base_args()"),
        "agent::mod should call focused OpenCode default launch args directly"
    );

    let start =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "struct AutoTriggerMonitor",
        "enum AutoTriggerCooldownAction",
        "enum AutoTriggerNoPromptAction",
        "fn auto_trigger_clear_cooldown_action(",
        "fn auto_trigger_no_prompt_action(",
        "fn managed_capability_proof_status_message(",
    ] {
        assert!(
            !start.contains(forbidden_snippet),
            "start.rs must not re-own pure auto-trigger readiness policy: {forbidden_snippet}"
        );
    }
    let executor_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/src/lib.rs")).unwrap();
    assert!(
        executor_lib.contains("pub mod claude_launch;"),
        "agent-doc-turn-executor should expose Claude launch argv policy directly"
    );
    assert!(
        executor_lib.contains("pub mod opencode_launch;"),
        "agent-doc-turn-executor should expose OpenCode launch argv policy directly"
    );
    assert!(
        !executor_lib.contains("pub mod auto_trigger;")
            && !manifest_dir
                .join("agent-doc-turn-executor/src/auto_trigger.rs")
                .exists(),
        "agent-doc-turn-executor must not keep an auto-trigger facade after supervisor extraction"
    );
    assert!(
        start.contains("agent_doc_turn_executor::capability_proof::resolve_managed_proof_policy")
            && start.contains("agent_doc_turn_executor::capability_proof::proof_retry_decision")
            && start.contains(
                "use agent_doc_turn_executor::capability_proof::managed_capability_proof_status_message;"
            ),
        "start should call focused turn-executor capability-proof policy directly"
    );
    let harness_crate =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/src/lib.rs")).unwrap();
    let harness_managed_capability =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/src/managed_capability.rs"))
            .unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-harness")),
        "agent-doc-harness must stay a first-class workspace crate"
    );
    let harness_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/Cargo.toml")).unwrap();
    let harness_manifest: toml::Value = toml::from_str(&harness_manifest).unwrap();
    assert_eq!(
        harness_manifest["package"]["version"].as_str(),
        package_version
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod harness;"),
        "orchestration must not expose agent-doc-harness through a harness facade module"
    );
    fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, out);
            } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
                out.push(path);
            }
        }
    }
    let mut orchestration_sources = Vec::new();
    collect_rs_files(&manifest_dir.join("src"), &mut orchestration_sources);
    for forbidden_snippet in [
        "pub struct HarnessConfig",
        "pub enum RestartBehavior",
        "pub enum CleanExitBehavior",
        "pub fn normalize_harness_name(",
        "fn protected_prompt_draft_preview(",
        "fn pane_idle_dispatch_ready(",
        "fn apply_plain_trigger_override(",
        "fn document_harness_from_content(",
    ] {
        for source_path in &orchestration_sources {
            let source = fs::read_to_string(source_path).unwrap();
            assert!(
                !source.contains(forbidden_snippet),
                "{} must not re-own harness prompt/chrome policy: {forbidden_snippet}",
                source_path.display()
            );
        }
    }
    for required_snippet in [
        "pub struct HarnessConfig",
        "pub enum RestartBehavior",
        "pub enum CleanExitBehavior",
        "pub fn from_context(",
        "pub fn dispatch_blocker_reason(",
        "pub fn protected_prompt_input_reason(",
        "pub fn normalize_harness_name(",
        "pub fn document_harness_from_content(",
        "pub fn apply_plain_trigger_override(",
        "pub fn protected_prompt_draft_preview(",
        "pub fn pane_idle_dispatch_ready(",
    ] {
        assert!(
            harness_crate.contains(required_snippet),
            "agent-doc-harness should own harness prompt/chrome policy directly: {required_snippet}"
        );
    }
    assert!(
        harness_crate.contains("pub mod managed_capability;"),
        "agent-doc-harness must expose managed capability policy directly"
    );
    for required_snippet in [
        "pub fn managed_capability_contract_required(",
        "resolve_codex_network_access(",
        "add_dirs_from_args(args)",
    ] {
        assert!(
            harness_managed_capability.contains(required_snippet),
            "agent-doc-harness must own pure managed capability contract policy: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "fn parse_sandbox_mode_config(",
        "fn record_codex_resume_sandbox_mode(",
        "fn push_codex_resume_sandbox_config(",
        "fn codex_resume_restart_args(",
    ] {
        assert!(
            !harness_crate.contains(forbidden_snippet),
            "agent-doc-harness must not re-own pure Codex resume launch policy: {forbidden_snippet}"
        );
    }
    assert!(
        harness_crate
            .contains("use agent_doc_turn_executor::codex_launch::codex_resume_restart_args;"),
        "agent-doc-harness should call focused Codex resume launch policy directly"
    );
    let codex =
        fs::read_to_string(manifest_dir.join("agent-doc-agent-io/src/agent/codex.rs")).unwrap();
    for forbidden_snippet in [
        "fn looks_like_codex_transport_403_429(",
        "fn append_resume_args(",
        "fn codex_resume_restart_args(",
        "fn format_transport_403_429_diagnostic(",
        "fn codex_transport_403_429_diagnostic(",
        "struct CodexStderrNoiseReport",
        "fn is_codex_marketplace_manifest_noise(",
        "fn codex_stderr_noise_report(",
        "fn filter_codex_stderr_noise(",
        "fn codex_exec_args_for_probe(",
        "fn opencode_run_args_for_probe(",
        "fn codex_child_network_probe_prompt(",
        "fn opencode_child_network_probe_prompt(",
        "fn opencode_child_required_ssh_probe_prompt(",
        "fn codex_child_writable_roots_probe_prompt(",
        "fn looks_like_opencode_usage_output(",
        "fn validate_codex_child_network_probe_output(",
        "fn validate_opencode_child_probe_marker_output(",
        "fn validate_codex_child_writable_root_probe_output(",
        "fn collect_json_strings(",
        "fn shell_single_quote(",
        "fn add_dirs_from_args(",
        "fn args_contain_add_dir(",
        "fn normalized_writable_root_strings(",
        "pub fn writable_root_contract_id(",
        "fn proof_status_label(",
        "fn proof_timing_ms(",
        "struct ManagedCapabilityProofTimings",
        "fn managed_network_child_proof_cache_key(",
        "fn classify_child_network_probe_failure(",
        "fn classify_child_required_ssh_probe_failure(",
        "fn classify_child_writable_root_probe_failure(",
        "fn looks_like_local_browser_cdp_permission_denied(",
        "fn resume_capability_drift_notice(",
        "fn looks_like_ssh_dns_failure(",
        "fn looks_like_ssh_network_failure(",
        "fn looks_like_ssh_auth_failure(",
        "fn looks_like_ssh_alias_config_failure(",
        "fn transcript_has_required_ssh_failure(",
        "fn transcript_proves_required_ssh_success(",
        "fn format_required_ssh_failure(",
        "pub fn default_base_args(",
        "pub fn structural_base_args(",
        "pub use agent_doc_turn_executor::codex_launch",
        "pub fn managed_capability_contract_required(",
    ] {
        assert!(
            !codex.contains(forbidden_snippet),
            "agent::codex must not re-own Codex launch/transport policy: {forbidden_snippet}"
        );
    }
    assert!(
        codex.contains("use agent_doc_turn_executor::codex_launch::{")
            && codex.contains("looks_like_codex_transport_403_429")
            && codex.contains("codex_transport_403_429_diagnostic")
            && codex.contains("filter_codex_stderr_noise")
            && codex.contains("codex_exec_args_for_probe")
            && codex.contains("opencode_run_args_for_probe")
            && codex.contains("codex_child_network_probe_prompt")
            && codex.contains("opencode_child_network_probe_prompt")
            && codex.contains("opencode_child_required_ssh_probe_prompt")
            && codex.contains("codex_child_writable_roots_probe_prompt")
            && codex.contains("looks_like_opencode_usage_output")
            && codex.contains("validate_codex_child_network_probe_output")
            && codex.contains("validate_opencode_child_probe_marker_output")
            && codex.contains("validate_codex_child_writable_root_probe_output")
            && codex.contains("add_dirs_from_args")
            && codex.contains("args_contain_add_dir")
            && codex.contains("normalized_writable_root_strings")
            && codex.contains("writable_root_contract_id")
            && codex.contains("ManagedCapabilityProofTimings")
            && codex.contains("managed_network_child_proof_cache_key")
            && codex.contains("classify_child_network_probe_failure")
            && codex.contains("classify_child_required_ssh_probe_failure")
            && codex.contains("classify_child_writable_root_probe_failure")
            && codex.contains("codex_resume_restart_args")
            && codex.contains("looks_like_local_browser_cdp_permission_denied")
            && codex.contains("resolve_codex_network_access")
            && codex.contains("resume_capability_drift_notice")
            && codex.contains("transcript_has_required_ssh_failure")
            && codex.contains("transcript_proves_required_ssh_success")
            && codex.contains("format_required_ssh_failure"),
        "agent::codex should call focused Codex launch/transport policy directly"
    );
    assert!(
        codex.contains("default_base_args")
            && !codex.contains("pub use agent_doc_turn_executor::codex_launch"),
        "agent::codex should import focused Codex default launch args privately, not re-export them"
    );
    assert!(
        codex.contains(
            "agent_doc_harness::managed_capability::managed_capability_contract_required("
        ),
        "agent::codex should call focused managed capability contract policy directly"
    );
    assert!(
        !codex.contains("super::resolve_codex_network_access("),
        "agent::codex must not call obsolete orchestration Codex network policy"
    );
    assert!(
        codex.contains(
            "agent_doc_turn_executor::capability_proof::DEFAULT_MANAGED_PROOF_PROBE_TIMEOUT"
        ),
        "codex probe tests should use the focused capability-proof defaults directly"
    );
    let agent_mod =
        fs::read_to_string(manifest_dir.join("agent-doc-agent-io/src/agent/mod.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/agent/streaming.rs")
            .exists(),
        "agent::streaming must not reintroduce a facade around focused executor stream contracts"
    );
    assert!(
        !agent_mod.contains("pub mod streaming"),
        "agent::mod must not expose an orchestration streaming facade"
    );
    let claude =
        fs::read_to_string(manifest_dir.join("agent-doc-agent-io/src/agent/claude.rs")).unwrap();
    let opencode =
        fs::read_to_string(manifest_dir.join("agent-doc-agent-io/src/agent/opencode.rs")).unwrap();
    let stream = fs::read_to_string(manifest_dir.join("agent-doc-stream-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "args.push(\"--append-system-prompt\".to_string())",
        "fn build_streaming_args(",
        "pub fn default_base_args(",
        "pub fn structural_base_args(",
        "streaming_args_replace_output_format_and_preserve_add_dir",
        "streaming_args_includes_verbose",
    ] {
        assert!(
            !claude.contains(forbidden_snippet),
            "agent::claude must not re-own Claude streaming argv policy: {forbidden_snippet}"
        );
    }
    assert!(
        claude.contains("use agent_doc_turn_executor::claude_launch::{")
            && claude.contains("claude_json_args")
            && claude.contains("claude_streaming_args")
            && claude.contains("default_base_args")
            && claude.contains("claude_json_args(&self.base_args, session_id, fork, model)")
            && claude.contains("claude_streaming_args(&self.base_args, session_id, fork, model)"),
        "agent::claude should call focused Claude launch argv policy directly"
    );
    for forbidden_snippet in [
        "pub fn default_base_args(",
        "pub fn build_args(",
        "fn build_args_fresh_model(",
        "fn build_args_session_resume(",
        "fn build_args_fork_last_session(",
    ] {
        assert!(
            !opencode.contains(forbidden_snippet),
            "agent::opencode must not re-own OpenCode launch argv policy: {forbidden_snippet}"
        );
    }
    assert!(
        opencode.contains("use agent_doc_turn_executor::opencode_launch::{")
            && opencode.contains("default_base_args")
            && opencode.contains("opencode_run_args")
            && opencode
                .contains("opencode_run_args(&self.base_args, prompt, session_id, fork, model)"),
        "agent::opencode should call focused OpenCode launch argv policy directly"
    );
    for (name, source) in [("agent/codex.rs", codex.as_str())] {
        for forbidden_snippet in [
            "pub struct StreamChunk",
            "pub trait StreamingAgent",
            "pub fn parse_stream_line(",
            "pub fn parse_codex_line(",
            "pub use",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{name} must not define or reexport focused stream parser API: {forbidden_snippet}"
            );
        }
    }
    assert!(
        claude.contains("agent_doc_turn_executor::agent_stream::{")
            && claude.contains("StreamingAgent")
            && claude.contains("parse_stream_line")
            && codex.contains("agent_doc_turn_executor::agent_stream::{")
            && codex.contains("StreamingAgent")
            && codex.contains("parse_codex_line")
            && stream.contains("agent_doc_turn_executor::agent_stream::{")
            && stream.contains("StreamingAgent"),
        "stream command code should call focused agent stream parsing/chunk/contract APIs directly"
    );
    let watch = fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/daemon.rs")).unwrap();
    assert_source_omits_all(
        &watch,
        "watch daemon",
        &["fn extract_new_lines(", "fn limit_lines("],
    );
    assert_source_mentions_all(
        &watch,
        "watch daemon",
        &[
            "agent_doc_turn_executor::capture",
            "capture_delta",
            "limit_capture_lines",
        ],
    );
    let project_controller =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    for forbidden_snippet in [
        "fn resolve_agent_doc_binary_from_env(",
        "fn launchable_file(",
        "fn has_path_separator(",
        "pub(crate) fn current_agent_doc_binary(",
        "pub(crate) use agent_doc_turn_executor::binary::current_agent_doc_binary;",
    ] {
        assert!(
            !project_controller.contains(forbidden_snippet),
            "project_controller must not re-own agent-doc binary launch resolution: {forbidden_snippet}"
        );
    }
    assert!(
        project_controller
            .contains("use agent_doc_turn_executor::binary::current_agent_doc_binary;"),
        "project_controller should use focused binary launch resolution directly"
    );
    let start_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    assert!(
        start_source.contains("use agent_doc_turn_executor::binary::current_agent_doc_binary;")
            && !start_source.contains("project_controller::current_agent_doc_binary"),
        "start.rs should import focused binary launch resolution directly"
    );
    let controller_rpc_source = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        controller_rpc_source
            .contains("use agent_doc_turn_executor::binary::current_agent_doc_binary;"),
        "project_controller/rpc.rs should import focused binary launch resolution directly"
    );
    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    let orchestrate_dispatch_source =
        fs::read_to_string(manifest_dir.join("src/orchestrate/dispatch.rs")).unwrap();
    for forbidden_snippet in [
        "fn resolve_agent_doc_binary_from_env(",
        "fn launchable_file(",
        "fn has_path_separator(",
        "fn internal_command_spawn_context(",
    ] {
        assert!(
            !orchestrate_source.contains(forbidden_snippet),
            "src/orchestrate.rs must not re-own agent-doc binary launch resolution: {forbidden_snippet}"
        );
    }
    assert!(
        orchestrate_source
            .contains("binary::{current_agent_doc_binary, internal_command_spawn_context}"),
        "src/orchestrate.rs should call focused binary launch resolution directly"
    );
    assert!(
        orchestrate_dispatch_source.contains("structural_base_args as claude_structural_base_args")
            && orchestrate_dispatch_source.contains("claude_structural_base_args()")
            && orchestrate_dispatch_source.contains("default_base_args as codex_default_base_args")
            && orchestrate_dispatch_source
                .contains("structural_base_args as codex_structural_base_args")
            && orchestrate_dispatch_source.contains("codex_structural_base_args()")
            && orchestrate_dispatch_source.contains("unwrap_or_else(codex_default_base_args)"),
        "orchestrate dispatch should call focused Claude/Codex base-arg helpers directly"
    );

    let executor_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&executor_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-turn-executor must stay pure and free of core, orchestration, git, editor IPC, sqlite, or tmux crates"
        );
    }
}

#[test]
fn test_agent_doc_supervisor_policy_has_no_start_decisions_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .all(|member| member.as_str() != Some("agent-doc-supervisor-crdt-io")),
        "supervisor CRDT IPC adapter crate must be removed; editor CRDT IPC belongs to the CP"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/lifecycle.rs")
            .exists(),
        "agent-doc-supervisor must own supervisor lifecycle policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/agent_change.rs")
            .exists(),
        "agent-doc-supervisor must own harness-change policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/run_loop.rs")
            .exists(),
        "agent-doc-supervisor must own pure run-loop exit dispatch"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/selfkill.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor self-kill policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/crash_policy.rs")
            .exists(),
        "agent-doc-supervisor must own child crash/restart policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/idle_reconcile.rs")
            .exists(),
        "agent-doc-supervisor must own supervisor idle/ready reconcile policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/detection.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor terminal/detection policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/idle_watch.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor idle-watch policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/input.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor input byte policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/reexec.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor reexec candidate policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/auto_install_stdio.rs")
            .exists(),
        "agent-doc-supervisor must own auto-install stdio planning policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/session_owner.rs")
            .exists(),
        "agent-doc-supervisor must own existing-session owner policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/startup_miss.rs")
            .exists(),
        "agent-doc-supervisor must own pure startup-miss/session-log policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/terminal_filter.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor PTY terminal filtering policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/heartbeat.rs")
            .exists(),
        "agent-doc-supervisor must own pure supervisor heartbeat-loss policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/auto_trigger.rs")
            .exists(),
        "agent-doc-supervisor must own pure auto-trigger state policy"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor/src/ipc_protocol.rs")
            .exists(),
        "agent-doc-supervisor must own supervisor IPC protocol vocabulary"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-io/src/cwd.rs")
            .exists(),
        "agent-doc-supervisor-io must own supervisor CWD resolution IO"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-io/src/config.rs")
            .exists(),
        "agent-doc-supervisor-io must own file/env-backed supervisor config IO"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-io/src/ipc.rs")
            .exists(),
        "agent-doc-supervisor-io must own supervisor IPC socket transport IO"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-io/src/detection.rs")
            .exists(),
        "agent-doc-supervisor-io must own live supervisor detection adapters"
    );
    assert!(
        !manifest_dir.join("agent-doc-supervisor-crdt-io").exists(),
        "legacy supervisor CRDT IPC adapter crate must not remain in the workspace tree"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-process/src/route_owned_completion.rs")
            .exists(),
        "agent-doc-supervisor-process must own the route-owned completion thread loop"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/start/decisions.rs")
            .exists(),
        "orchestration must not keep a start::decisions facade over focused policy crates"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/state.rs")
            .exists(),
        "orchestration must not keep a supervisor::state facade over crash policy"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/cwd.rs")
            .exists(),
        "orchestration must not keep a supervisor::cwd facade over supervisor-io CWD resolution"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/start/detection.rs")
            .exists(),
        "orchestration must not keep a start::detection facade after supervisor-io owns live detection adapters"
    );

    let supervisor_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/lib.rs")).unwrap();
    let supervisor_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/lib.rs")).unwrap();
    let supervisor_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/Cargo.toml")).unwrap();
    let start_runtime_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/Cargo.toml")).unwrap();
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/mod.rs")
            .exists(),
        "orchestration must not keep a supervisor facade module"
    );
    let rpc_source = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    let supervisor_config =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/config.rs")).unwrap();
    let supervisor_io_config =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/config.rs")).unwrap();
    let fs_lib = fs::read_to_string(manifest_dir.join("agent-doc-fs/src/lib.rs")).unwrap();
    let fs_install_freshness =
        fs::read_to_string(manifest_dir.join("agent-doc-fs/src/install_freshness.rs")).unwrap();
    let supervisor_auto_install_stdio =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/auto_install_stdio.rs"))
            .unwrap();
    let supervisor_session_owner =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/session_owner.rs")).unwrap();
    let supervisor_crash_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/crash_policy.rs")).unwrap();
    let supervisor_run_loop =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/run_loop.rs")).unwrap();
    let supervisor_input_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/input.rs")).unwrap();
    let supervisor_reexec_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/reexec.rs")).unwrap();
    let supervisor_startup_miss =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/startup_miss.rs")).unwrap();
    let supervisor_idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/idle_watch.rs")).unwrap();
    let supervisor_detection =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/detection.rs")).unwrap();
    let supervisor_auto_trigger =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/auto_trigger.rs")).unwrap();
    let supervisor_terminal_filter =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/terminal_filter.rs"))
            .unwrap();
    let supervisor_heartbeat =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/heartbeat.rs")).unwrap();
    let supervisor_ipc_protocol =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/ipc_protocol.rs")).unwrap();
    let supervisor_io_startup_miss =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/startup_miss.rs"))
            .unwrap();
    let supervisor_io_cwd =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/cwd.rs")).unwrap();
    let supervisor_io_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/ipc.rs")).unwrap();
    let supervisor_io_detection =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/detection.rs")).unwrap();
    let orchestration_supervisor_io =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/supervisor_io.rs"))
            .unwrap();
    let supervisor_pty =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/pty.rs")).unwrap();
    let supervisor_process_io =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process-io/src/lib.rs"))
            .unwrap();
    let supervisor_io_threads =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/io_threads.rs"))
            .unwrap();
    let supervisor_route_owned_completion = fs::read_to_string(
        manifest_dir.join("agent-doc-supervisor-process/src/route_owned_completion.rs"),
    )
    .unwrap();
    let supervisor_in_process =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/in_process.rs"))
            .unwrap();
    let orchestration_start =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    let orchestration_start_run =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/run.rs")).unwrap();
    let orchestration_start_idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    let start_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-io/src/lib.rs")).unwrap();
    let jetbrains_crdt_forwarder = fs::read_to_string(manifest_dir.join(
        "editors/jetbrains/src/main/kotlin/com/github/btakita/agentdoc/CrdtReplicaForwarder.kt",
    ))
    .unwrap();
    let vscode_crdt_replica =
        fs::read_to_string(manifest_dir.join("editors/vscode/src/crdtReplica.ts")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/startup_miss.rs")
            .exists(),
        "orchestration must not keep a public startup_miss facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod startup_miss;"),
        "orchestration must not expose startup-miss as a public module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/ipc.rs")
            .exists(),
        "orchestration must not keep a supervisor IPC transport facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/mod.rs")
            .exists(),
        "orchestration supervisor module must not expose a supervisor IPC facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/startup_miss_registry.rs")
            .exists(),
        "orchestration must not keep a startup-miss registry adapter module"
    );
    let session_registry_io =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub struct OwnershipGeneration",
        "pub struct OwnershipTransitionEvent",
        "pub fn infer_latest_generation_from_content(",
        "pub fn format_transition_event(",
    ] {
        assert!(
            supervisor_lib.contains(required_snippet),
            "agent-doc-supervisor must own ownership generation/event vocabulary: {required_snippet}"
        );
    }
    let session_actor_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-actor-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub struct OwnershipGeneration",
        "pub struct OwnershipTransitionEvent",
        "pub fn infer_latest_generation_from_content(",
        "pub fn format_transition_event(",
    ] {
        assert!(
            !session_actor_source.contains(forbidden_snippet),
            "agent-doc-session-actor-io must not re-own supervisor lifecycle vocabulary: {forbidden_snippet}"
        );
    }
    assert!(
        session_actor_source.contains("use agent_doc_supervisor::{")
            && session_actor_source.contains("infer_latest_generation_from_content(&content)"),
        "agent-doc-session-actor-io should call focused supervisor lifecycle vocabulary directly"
    );
    for required_snippet in [
        "pub enum ExistingSessionPaneAction",
        "pub struct ExistingPaneConflictFacts",
        "pub fn existing_session_pane_action(",
        "pub fn format_existing_pane_conflict_error(",
    ] {
        assert!(
            supervisor_session_owner.contains(required_snippet),
            "agent-doc-supervisor must own existing-session owner policy: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub enum ExistingSessionPaneAction",
        "struct ExistingPaneConflictFacts",
        "fn existing_session_pane_action(",
        "fn existing_session_pane_action_from_entry(",
        "fn format_existing_pane_conflict_error(",
        "pub fn relocate_if_wrong_session(",
        "fn rebind_project_tmux_session_if_expected_dead(",
        "refusing to start {} in pane {} because pane {} is already bound to this document",
    ] {
        assert!(
            !orchestration_start.contains(forbidden_snippet),
            "start.rs must not re-own start admission/session-owner IO: {forbidden_snippet}"
        );
    }
    assert!(
        start_io_source.contains("agent_doc_supervisor::{")
            && start_io_source.contains("format_existing_pane_conflict_error_from_facts(")
            && start_io_source.contains("pub fn prepare_start_runtime(")
            && start_io_source.contains(
                "agent_doc_document_realtime_io::try_resolve_current_document_content("
            )
            && start_io_source.contains(
                "agent_doc_document_realtime_io::atomic_write_through_authority(file, &updated_content)"
            )
            && !start_io_source.contains(
                "agent_doc_document_realtime_io::atomic_write_through_authority(file, &merged)"
            )
            && start_io_source.contains("pub fn prepare_start_runtime_reentry(")
            && orchestration_start_run.contains(
                "prepare_start_runtime_reentry(file, force, route_owned)?"
            )
            && orchestration_start_run.contains("prepare_start_runtime(file, force, route_owned)?"),
        "agent-doc-start-io should own start admission/session-owner IO while start/run.rs calls it directly"
    );
    for forbidden in [
        "std::fs::read_to_string(file)",
        "std::fs::write(file, &updated_content)",
        "std::fs::write(file, &merged)",
    ] {
        assert!(
            !start_io_source.contains(forbidden),
            "agent-doc-start-io session-document startup paths must not use raw disk IO: {forbidden}"
        );
    }
    for required in [
        "start_runtime_restart_frontmatter",
        "idle_watch_queue_boundary",
        "idle_watch_active_queue_head",
        "idle_watch_forced_context_reset_reason",
    ] {
        assert!(
            orchestration_start_run.contains(required)
                || orchestration_start_idle_watch.contains(required),
            "start-runtime session-document helpers should resolve current document content through realtime IO: {required}"
        );
    }
    for (source_name, source) in [
        ("start-runtime run.rs", &orchestration_start_run),
        (
            "start-runtime idle_watch.rs",
            &orchestration_start_idle_watch,
        ),
    ] {
        for forbidden in ["std::fs::read_to_string(file)", "std::fs::write(file"] {
            assert!(
                !source.contains(forbidden),
                "{source_name} session-document helper paths must not use raw disk IO: {forbidden}"
            );
        }
    }
    assert!(
        orchestration_start_run.contains("current_text_via_controller_model_read_for_doc")
            && !orchestration_start_run.contains("current_text_via_controller_model_for_doc(")
            && !orchestration_start_run.contains("agent_doc_crdt_relay_io::ensure_document_model("),
        "start-runtime post-registration current-text checks must use CP read-only state instead of allocating or foreground-ensuring the CRDT hub locally"
    );
    assert!(
        orchestration_start_idle_watch.contains("current_text_via_controller_model_read_for_doc")
            && !orchestration_start_idle_watch.contains("consume_disk_change_reconcile")
            && !orchestration_start_idle_watch
                .contains("agent_doc_crdt_relay_io::current_text_for_file"),
        "start-runtime idle-watch must observe Lazily current state through the project \
         controller, without a second disk-change replay path. This assertion previously \
         required `current_text_for_file_nonblocking`, which codified a defect \
         (`#recycletransitionwedge`): that helper resolves against the process-local \
         `hub_registry()`, which ONLY the controller ever populates (the supervisor IPC \
         protocol rejects the replica methods outright). A supervisor reading its own \
         registry can only miss, and once durable liveness reports the editor attached the \
         miss pins at `EditorAttachedMissingReplica` for the life of the process — which \
         pinned `current_transition_pending` true and wedged the queue drain permanently, \
         with no self-heal, after an execve self-recycle."
    );
    assert!(
        orchestration_start_idle_watch.contains("live_editor_endpoint_attached_for_file(file)")
            && orchestration_start_idle_watch.contains("return idle_watch_disk_queue_head(file)"),
        "idle-watch active-queue-head must skip the controller model read and read disk directly when no live editor is attached (#idlewatchdetacheddisk), so an editorless supervisor cannot wedge polling a slow/degraded controller"
    );
    for required_snippet in [
        "pub enum AutoTriggerOutcome",
        "pub fn from_u8(value: u8) -> Self",
        "pub fn as_str(self) -> &'static str",
        "pub enum CapabilityProofGate",
    ] {
        assert!(
            supervisor_auto_trigger.contains(required_snippet),
            "agent-doc-supervisor must own auto-trigger wire-state policy: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "enum AutoTriggerOutcome",
        "impl AutoTriggerOutcome",
        "enum CapabilityProofGate",
        "impl CapabilityProofGate",
    ] {
        assert!(
            !orchestration_start.contains(forbidden_snippet),
            "start.rs must not re-own auto-trigger wire-state policy: {forbidden_snippet}"
        );
    }
    assert!(
        orchestration_start.contains("use agent_doc_supervisor::auto_trigger::{")
            && orchestration_start.contains("AutoTriggerOutcome")
            && orchestration_start.contains("CapabilityProofGate"),
        "start.rs should import auto-trigger wire-state policy directly"
    );
    for required_snippet in [
        "pub struct TerminalFilterConfig",
        "pub enum TerminalFilterAction",
        "pub enum TerminalFilterTraceKind",
        "pub struct TerminalFilterTrace",
        "pub struct TerminalFilter",
        "pub fn filter_with_trace(",
        "fn kitty_trace_kind(",
    ] {
        assert!(
            supervisor_terminal_filter.contains(required_snippet),
            "agent-doc-supervisor must own PTY terminal filter policy: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "while i < len",
        "data[i] == 0x1b",
        "fn kitty_trace_kind(",
        "fn filter_terminal_queries(",
        "filter_strips_da1_query",
        "filter_strips_kitty_keyboard_push",
    ] {
        assert!(
            !supervisor_pty.contains(forbidden_snippet),
            "supervisor pty adapter must not re-own terminal escape filtering policy: {forbidden_snippet}"
        );
    }
    assert!(
        supervisor_pty.contains("TerminalFilter::with_config")
            && supervisor_pty.contains("log_terminal_filter_trace("),
        "supervisor pty adapter should configure the focused filter and keep only trace logging effects"
    );
    assert!(
        supervisor_heartbeat.contains("pub fn heartbeat_lost("),
        "agent-doc-supervisor must own pure heartbeat-loss policy"
    );
    assert!(
        !supervisor_in_process.contains("pub fn heartbeat_lost(")
            && supervisor_in_process.contains("agent_doc_supervisor::heartbeat::heartbeat_lost("),
        "in-process supervisor adapter must call focused heartbeat-loss policy directly"
    );
    for required_snippet in [
        "pub enum IpcMethod",
        "pub struct IpcResponse",
        "pub fn submit_bytes(",
        "pub const fn ipc_method_requires_capability_gate(",
        "fn default_restart_mode(",
    ] {
        assert!(
            supervisor_ipc_protocol.contains(required_snippet),
            "agent-doc-supervisor must own supervisor IPC protocol vocabulary: {required_snippet}"
        );
    }
    for forbidden_snippet in ["CrdtCheckpoint {", "fn default_checkpoint_source("] {
        assert!(
            !supervisor_ipc_protocol.contains(forbidden_snippet),
            "supervisor IPC must not expose the removed legacy durability checkpoint route: {forbidden_snippet}"
        );
    }
    assert!(
        supervisor_io_lib.contains("pub mod ipc;"),
        "agent-doc-supervisor-io must expose supervisor IPC transport through its owning module"
    );
    assert!(
        !supervisor_io_manifest.contains("agent-doc-debounce"),
        "agent-doc-supervisor-io must not depend on retired typing/file-signal debounce state"
    );
    assert!(
        !supervisor_io_lib.contains("pub mod crdt_replica;"),
        "agent-doc-supervisor-io must not own CRDT relay adapters because that creates a relay/supervisor IO cycle"
    );
    for forbidden_snippet in [
        "ReplicaRegister",
        "ReplicaDeregister",
        "ReplicaUpdate",
        "ReplicaPull",
        "ReplicaProjection",
        "ReplicaAwareness",
        "CrdtCurrentText",
        "default_current_text_source",
        "handle_crdt_checkpoint",
    ] {
        assert!(
            !supervisor_ipc_protocol.contains(forbidden_snippet)
                && !supervisor_io_ipc.contains(forbidden_snippet)
                && !orchestration_supervisor_io.contains(forbidden_snippet),
            "supervisor IPC must not expose or dispatch editor CRDT methods after CP owns editor IPC: {forbidden_snippet}"
        );
    }
    for forbidden_snippet in [
        "replica_register",
        "replica_update",
        "replica_pull",
        "replica_projection",
        "replica_awareness",
        "crdt_current_text",
        "crdt_checkpoint",
    ] {
        assert!(
            !supervisor_io_ipc.contains(forbidden_snippet)
                && !orchestration_supervisor_io.contains(forbidden_snippet),
            "supervisor IO dispatch must not expose editor CRDT wire methods after CP owns editor IPC: {forbidden_snippet}"
        );
    }
    for source in [
        &workspace_manifest,
        &start_runtime_manifest,
        &orchestration_manifest,
    ] {
        assert!(
            !source.contains("agent-doc-supervisor-crdt-io"),
            "manifests must not depend on the removed supervisor CRDT IPC adapter"
        );
    }
    for forbidden_snippet in [
        "agent_doc_crdt_relay_io::register_replica_for_file(",
        "agent_doc_crdt_relay_io::relay_replica_update_for_file(",
        "agent_doc_crdt_relay_io::set_replica_awareness_for_file(",
    ] {
        assert!(
            !orchestration_supervisor_io.contains(forbidden_snippet),
            "orchestration supervisor IPC dispatch must not re-own CRDT replica handler graph: {forbidden_snippet}"
        );
    }
    assert!(
        orchestration_supervisor_io.contains(
            "impl agent_doc_supervisor_io::ipc::SupervisorIpcHandlerState for SupervisorShared"
        ) && orchestration_supervisor_io.contains(
            "impl agent_doc_supervisor_io::ipc::SupervisorInjectDeliveryState for SupervisorShared"
        ),
        "orchestration supervisor IPC dispatch should expose only non-editor-CRDT supervisor state/effects"
    );
    assert!(
        !orchestration_supervisor_io.contains("pub(crate) fn deliver_ipc_inject("),
        "orchestration supervisor IPC dispatch must not re-own the inject delivery adapter"
    );
    for required_snippet in [
        "\"crdt_commit_barrier\"",
        "\"crdt_record_committed_baseline\"",
        "\"crdt_disk_projection_reconcile\"",
        "\"crdt_route_disk_change_signal\"",
        "DiskChangeSignal::from_delivery(delivery)",
        "let signal: DiskChangeSignal",
        "signal.into_delivery()",
    ] {
        assert!(
            rpc_source.contains(required_snippet),
            "controller RPC must own CP CRDT hub mutation boundary: {required_snippet}"
        );
    }
    let cp_owned_crdt_hub_mutators = [
        "agent_doc_crdt_relay_io::ensure_document_model(",
        "agent_doc_crdt_relay_io::consume_disk_change_reconcile(",
        "agent_doc_crdt_relay_io::checkpoint_durable_projection_for_file(",
        "agent_doc_crdt_relay_io::register_replica_for_file(",
        "agent_doc_crdt_relay_io::deregister_replica_for_file(",
        "agent_doc_crdt_relay_io::relay_replica_update_for_file(",
        "agent_doc_crdt_relay_io::pull_rebootstrap_for_file(",
        "agent_doc_crdt_relay_io::pull_replica_updates_for_file(",
        "agent_doc_crdt_relay_io::observe_replica_projection_for_file(",
        "agent_doc_crdt_relay_io::set_replica_awareness_for_file(",
        "agent_doc_crdt_relay_io::commit_barrier_for_file(",
        "agent_doc_crdt_relay_io::record_committed_baseline_for_file(",
        "agent_doc_crdt_relay_io::reconcile_disk_projection_for_file(",
        "agent_doc_crdt_relay_io::route_disk_change_signal(",
    ];
    for relative in [
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-flow-io/src/closeout.rs",
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-start-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "src/main.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden_snippet in cp_owned_crdt_hub_mutators {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative} must route CP-owned CRDT hub mutations through controller RPC: {forbidden_snippet}"
            );
        }
    }
    let realtime_io =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "with_controller_document_mutation",
        "agent_doc_crdt_relay_io::embedded_relay_is_available_for_file(file)",
        "if controller_document_mutation_in_progress() {\n        return agent_doc_crdt_relay_io::current_text_for_file(file);",
        "if controller_document_mutation_in_progress() {\n        return agent_doc_crdt_relay_io::ensure_document_model(file, source);",
    ] {
        assert!(
            realtime_io.contains(required_snippet),
            "document realtime must allow direct relay access only inside the CP-owned document mutation scope: {required_snippet}"
        );
    }
    // `#ensurereplicagen`: queue maintenance runs in the short-lived preflight CLI
    // process, where `hub_registry()` is always empty because only the controller
    // ever populates it. Reading or writing the relay directly from there can only
    // ever miss — it reported `editor_attached_model_missing` forever, and once the
    // read was fixed the *write* still compare-and-swapped against a stale durable
    // projection and failed with a permanently unsatisfiable `retry_crdt_merge`.
    // Both halves must be routed through the hub-owning controller, guarded by the
    // embedded-relay check so in-process callers keep the direct path.
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "fn ensure_document_model_via_authority(",
        "agent_doc_crdt_relay_io::embedded_relay_is_available_for_file(file)",
        "current_text_via_controller_model_for_doc(",
        "apply_cp_write_via_controller_model_for_doc(",
    ] {
        assert!(
            preflight_io.contains(required_snippet),
            "queue maintenance must reach the relay through the hub-owning controller: {required_snippet}"
        );
    }
    assert!(
        !preflight_io.contains(
            "let ensured = agent_doc_crdt_relay_io::ensure_document_model(file, source);"
        ),
        "queue maintenance must not ensure the document model against this process's empty local hub registry"
    );

    // The process role still prevents the controller from asking its own socket,
    // but projection retention no longer branches on that role or creates a
    // background repair request. It observes the process-scoped Lazily map.
    let relay_io =
        fs::read_to_string(manifest_dir.join("agent-doc-crdt-relay-io/src/lib.rs")).unwrap();
    assert!(
        relay_io.contains("retained_canonical_projections().observe(&document_hash)")
            && relay_io.contains("storage=controller_lazily_projection")
            && !relay_io.contains("durable_checkpoint_deferral_reason")
            && !relay_io.contains("record_durable_projection_repair_request"),
        "projection observation must read the process-scoped Lazily target without a repair request",
    );
    // Keep the role out of tests. Only the controller's own
    // `mark_process_as_relay_hub_owner` may write the flag.
    assert_eq!(
        relay_io.matches("PROCESS_SERVES_RELAY_HUB.store(").count(),
        1,
        "only mark_process_as_relay_hub_owner may write the relay-hub-owner role; \
         tests must exercise durable_checkpoint_deferral_reason directly instead"
    );
    for relative in [
        "agent-doc-preflight-io/src/lib.rs",
        "agent-doc-start-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-document-realtime-io/src/lib.rs",
        "src/main.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("mark_process_as_relay_hub_owner("),
            "{relative} must not claim the relay-hub-owner role; only the controller serves the hub"
        );
    }

    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        main_source.contains("with_controller_document_mutation(||"),
        "Compact Exchange CP runtime effect must enter the in-process document mutation scope"
    );
    for (editor_name, source) in [
        ("JetBrains", &jetbrains_crdt_forwarder),
        ("VS Code", &vscode_crdt_replica),
    ] {
        assert!(
            source.contains("crdt_replica") && source.contains("diagnostic_payload"),
            "{editor_name} CRDT transport must use the CP controller RPC envelope"
        );
        assert!(
            source.contains("controller.sock"),
            "{editor_name} CRDT transport must connect to the CP controller socket"
        );
        assert!(
            !source.contains(".agent-doc/supervisor") && !source.contains("supervisor/$"),
            "{editor_name} CRDT transport must not open a per-session supervisor socket"
        );
    }
    assert!(
        jetbrains_crdt_forwarder.contains("obj.addProperty(\"command\", \"crdt_replica\")")
            && jetbrains_crdt_forwarder
                .contains("obj.addProperty(\"diagnostic_payload\", payload.toString())")
            && jetbrains_crdt_forwarder.contains(
                "private fun cpcSocket(): File = File(projectRoot, \".agent-doc/controller.sock\")"
            )
            && !jetbrains_crdt_forwarder.contains("agentDocSessionId(")
            && !jetbrains_crdt_forwarder.contains("File(filePath).readText()"),
        "JetBrains CRDT transport must route directly through CP/controller.sock without resolving session frontmatter"
    );
    for required_snippet in [
        "use agent_doc_supervisor::ipc_protocol::{IpcMethod, IpcResponse};",
        "interprocess::local_socket",
        "pub fn socket_path(",
        "pub fn active_supervisor_pids(",
        "pub struct SupervisorIpc",
        "pub struct SupervisorIpcStateSnapshot",
        "pub trait SupervisorIpcSnapshotState",
        "pub fn supervisor_ipc_state_snapshot",
        "pub trait SupervisorIpcLifecycleState",
        "pub fn request_supervisor_restart",
        "pub fn request_supervisor_stop_agent",
        "pub trait SupervisorIpcHandlerState",
        "pub trait SupervisorInjectDeliveryState",
        "pub fn deliver_supervisor_inject",
        "pub fn handle_supervisor_ipc",
        "pub enum SocketLiveness",
        "pub fn probe_socket(",
        "pub fn send_command(",
    ] {
        assert!(
            supervisor_io_ipc.contains(required_snippet),
            "agent-doc-supervisor-io must own supervisor IPC transport: {required_snippet}"
        );
    }
    assert!(
        supervisor_io_ipc.contains("ipc_method_requires_capability_gate(&method)")
            && supervisor_io_ipc.contains("state.editor_authority_snapshot()")
            && !orchestration_start.contains("ipc_method_requires_capability_gate"),
        "agent-doc-supervisor-io should own supervisor IPC command gating and state snapshot assembly while start.rs keeps only concrete state/effect adapters"
    );
    assert!(
        orchestration_supervisor_io.contains(
            "impl agent_doc_supervisor_io::ipc::SupervisorIpcSnapshotState for SupervisorShared"
        ) && !orchestration_supervisor_io.contains("agent_doc_debounce::editor_sync_statuses"),
        "orchestration supervisor IPC adapter should expose snapshot fields without assembling editor-sync JSON"
    );
    assert!(
        orchestration_supervisor_io.contains(
            "impl agent_doc_supervisor_io::ipc::SupervisorIpcLifecycleState for SupervisorShared"
        ) && !orchestration_supervisor_io.contains("ipc_restart_requested")
            && !orchestration_supervisor_io.contains("ipc_stop_agent_requested")
            && !orchestration_supervisor_io.contains("fn request_restart("),
        "orchestration supervisor IPC adapter should expose lifecycle fields without owning restart/stop semantics"
    );
    for relative in [
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-sync-io/src/sync.rs",
        "src/queue_dispatch.rs",
        "src/session_actor_cmd.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("agent_doc_supervisor_io::ipc::IpcMethod")
                && !source.contains("agent_doc_supervisor_io::ipc::IpcResponse")
                && !source.contains("agent_doc_orchestration::supervisor::ipc")
                && !source.contains("crate::supervisor::ipc"),
            "{relative} must call focused supervisor IPC protocol vocabulary directly"
        );
    }
    for required_snippet in [
        "pub enum CwdSource",
        "pub struct ResolvedCwd",
        "pub fn resolve(",
    ] {
        assert!(
            supervisor_io_cwd.contains(required_snippet),
            "agent-doc-supervisor-io must own supervisor CWD resolution IO: {required_snippet}"
        );
    }
    assert!(
        orchestration_start.contains("use agent_doc_supervisor_io::cwd;")
            && orchestration_start_run
                .contains("cwd::resolve(None, fm.cwd.as_deref(), &canonical)?"),
        "start should call supervisor-io CWD resolution directly"
    );
    for required_snippet in [
        "pub fn session_log_status_from_content(",
        "pub fn is_harness_run_start_event(",
        "pub fn event_reason(",
        "pub enum StartingPaneRecoveryTarget",
        "pub fn starting_pane_recovery_target(",
        "pub fn recent_session_loss_window_at(",
        "pub fn registered_start_supersedes_miss(",
        "pub fn latest_log_anchor(",
    ] {
        assert!(
            supervisor_startup_miss.contains(required_snippet),
            "agent-doc-supervisor must own startup-miss/session-log policy: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn supervisor_session_log_path(",
        "pub fn startup_miss_project_root(",
        "pub fn record_startup_miss(",
        "pub fn load_startup_miss(",
        "pub fn clear_startup_miss(",
        "pub struct RegisteredStartupOwner",
        "pub trait StartupMissRegistryLookup",
        "pub struct SessionRegistryStartupMissLookup",
        "pub fn session_registry_lookup() -> &'static SessionRegistryStartupMissLookup",
        "impl StartupMissRegistryLookup for SessionRegistryStartupMissLookup",
        "agent_doc_session_registry_io::lookup_file_entry_in(",
        "pub fn superseded_by_newer_registered_start(",
        "pub fn take_superseded_startup_miss(",
        "pub fn append_session_log_event(",
        "pub struct RegistryRebindSessionLog",
        "pub fn append_registry_rebind_session_log(",
        "pub fn session_log_status(",
        "pub fn recent_session_loss_window(",
        "pub fn record_session_loss(",
        "StateFact::StartupMissRecorded",
        "StateFact::StartupMissCleared",
    ] {
        assert!(
            supervisor_io_startup_miss.contains(required_snippet),
            "agent-doc-supervisor-io must own startup-miss/session-log IO: {required_snippet}"
        );
    }
    assert!(
        session_registry_io.contains("pub fn lookup_file_entry_in(")
            && session_registry_io.contains("-> Result<Option<RegistryEntry>>")
            && session_registry_io.contains("canonical_registry_key_in(base_dir,"),
        "agent-doc-session-registry-io must own canonical file-entry registry lookup"
    );
    for (relative, required) in [
        (
            "agent-doc-sync-io/src/sync.rs",
            "agent_doc_supervisor_io::startup_miss::take_superseded_startup_miss(",
        ),
        (
            "agent-doc-start-io/src/lib.rs",
            "agent_doc_supervisor_io::startup_miss::take_superseded_startup_miss(",
        ),
        (
            "agent-doc-session-check-io/src/command.rs",
            "agent_doc_supervisor_io::startup_miss::superseded_by_newer_registered_start(",
        ),
        (
            "agent-doc-route-io/src/pane_resolution.rs",
            "agent_doc_supervisor_io::startup_miss::superseded_by_newer_registered_start(",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(required)
                && source
                    .contains("agent_doc_supervisor_io::startup_miss::session_registry_lookup()"),
            "{relative} should call focused startup-miss supersession IO through the focused registry lookup"
        );
    }
    for relative in [
        "agent-doc-sync-io/src/sync.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-session-check-io/src/command.rs",
        "agent-doc-route-io/src/pane_resolution.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("crate::startup_miss::"),
            "{relative} must not call the deleted orchestration startup_miss facade"
        );
    }
    let orchestration_route =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_dispatch_recovery =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_recovery.rs"))
            .unwrap();
    for forbidden_snippet in [
        "enum StartingPaneRecoveryTarget",
        "fn starting_pane_generation_changed(",
        "fn starting_pane_recovery_target(",
    ] {
        assert!(
            !orchestration_route.contains(forbidden_snippet),
            "route.rs must not re-own supervisor startup-miss recovery policy: {forbidden_snippet}"
        );
    }
    assert!(
        !orchestration_route.contains("starting_pane_recovery_target(")
            && route_dispatch_recovery.contains("use agent_doc_supervisor::startup_miss::{")
            && route_dispatch_recovery.contains("starting_pane_recovery_target("),
        "agent-doc-route-io dispatch_recovery should gather runtime facts and call focused startup-miss recovery policy directly"
    );
    for required_snippet in [
        "pub struct AgentLaunchArgsSources",
        "pub fn resolve_agent_launch_args(",
        "pub const STALE_INSTALL_GRACE_SECS",
        "pub fn classify_stale_install_artifacts",
        "pub fn is_agent_doc_dogfood_session",
    ] {
        assert!(
            supervisor_config.contains(required_snippet),
            "agent-doc-supervisor config should own stale-install policy directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub enum AutoInstallStdioStream",
        "pub struct AutoInstallChildStdioPlan",
        "pub fn auto_install_child_stdio_plan_to_fd",
        "pub fn auto_install_child_stdio_plan",
    ] {
        assert!(
            supervisor_auto_install_stdio.contains(required_snippet),
            "agent-doc-supervisor should own auto-install stdio planning directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub const SUPERVISOR_AUTO_RECYCLE_ENV",
        "pub const AGENT_CHANGE_RESTART_ENV",
        "pub const SUPERVISOR_AUTO_INSTALL_ENV",
        "pub fn supervisor_auto_recycle_enabled(",
        "pub fn agent_change_restart_enabled(",
        "pub fn supervisor_auto_install_enabled(",
        "agent_doc_supervisor::config::resolve_supervisor_auto_recycle",
        "agent_doc_supervisor::config::resolve_agent_change_restart",
        "agent_doc_supervisor::config::resolve_supervisor_auto_install",
    ] {
        assert!(
            supervisor_io_config.contains(required_snippet),
            "agent-doc-supervisor-io config should own file/env-backed supervisor config reads: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub(crate) fn supervisor_auto_recycle_enabled",
        "pub(crate) fn agent_change_restart_enabled",
        "pub(crate) fn supervisor_auto_install_enabled",
        "std::env::var(SUPERVISOR_AUTO_RECYCLE_ENV)",
        "std::env::var(AGENT_CHANGE_RESTART_ENV)",
        "std::env::var(SUPERVISOR_AUTO_INSTALL_ENV)",
        "pub(crate) fn resolve_supervisor_auto_recycle",
        "pub(crate) fn resolve_agent_change_restart",
        "pub(crate) fn source_newer_than_installed_binary",
        "pub(crate) fn resolve_supervisor_auto_install",
        "pub(crate) fn auto_install_should_retry",
        "pub(crate) fn host_supervisor_is_stale",
        "fn is_agent_doc_dogfood_session",
        "fn auto_install_child_stdio_to_fd(",
        "fn auto_install_child_stdio()",
    ] {
        assert!(
            !rpc_source.contains(forbidden_snippet),
            "project_controller::rpc must not wrap pure supervisor config helpers: {forbidden_snippet}"
        );
    }
    for required_snippet in [
        "agent_doc_supervisor::config::auto_install_should_retry",
        "agent_doc_supervisor::config::host_supervisor_is_stale",
        "agent_doc_supervisor::config::is_agent_doc_dogfood_session",
        "agent_doc_supervisor::auto_install_stdio::auto_install_child_stdio_plan",
    ] {
        assert!(
            rpc_source.contains(required_snippet),
            "project_controller::rpc should call focused supervisor config helpers directly: {required_snippet}"
        );
    }
    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let start_idle_watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    let route_authoritative_actor =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_actor.rs"))
            .unwrap();
    let write_converge_io =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    let preflight_warnings =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    assert!(
        fs_lib.contains("pub mod install_freshness;"),
        "agent-doc-fs must expose install freshness filesystem probes"
    );
    for required_snippet in [
        "pub fn artifact_mtime_secs(",
        "pub fn newest_artifact_mtime(",
        "pub fn cargo_bin_dir(",
        "pub fn installed_agent_doc_cdylib_mtime(",
        "pub fn locate_agent_doc_source_repo(",
        "pub fn newest_crate_source_mtime_secs(",
        "pub fn agent_doc_install_artifacts(",
    ] {
        assert!(
            fs_install_freshness.contains(required_snippet),
            "agent-doc-fs should own install freshness filesystem policy: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "const STALE_INSTALL_GRACE_SECS",
        "fn classify_stale_install_artifacts",
        "fn artifact_mtime_secs(",
        "fn newest_artifact_mtime(",
        "fn cargo_bin_dir(",
        "fn installed_cdylib_mtime(",
        "fn locate_agent_doc_source_repo(",
    ] {
        assert!(
            !preflight.contains(forbidden_snippet),
            "preflight must not re-own stale-install or install-freshness policy: {forbidden_snippet}"
        );
    }
    assert!(
        !rpc_source.contains("fn newest_crate_source_mtime_secs("),
        "project_controller::rpc must not re-own install freshness source mtime scanning"
    );
    assert!(
        preflight_warnings
            .contains("agent_doc_supervisor::config::classify_stale_install_artifacts")
            && preflight_warnings
                .contains("agent_doc_supervisor::config::STALE_INSTALL_GRACE_SECS")
            && preflight_warnings
                .contains("agent_doc_fs::install_freshness::locate_agent_doc_source_repo")
            && preflight_warnings
                .contains("agent_doc_fs::install_freshness::newest_crate_source_mtime_secs")
            && preflight_warnings
                .contains("agent_doc_fs::install_freshness::agent_doc_install_artifacts"),
        "focused preflight warnings should call stale-install and install-freshness policy directly"
    );
    assert!(
        start_idle_watch_source
            .contains("agent_doc_fs::install_freshness::newest_crate_source_mtime_secs"),
        "idle_watch should call install freshness source mtime scanning through agent-doc-fs directly"
    );
    assert!(
        start_idle_watch_source
            .contains("agent_doc_supervisor_io::config::supervisor_auto_recycle_enabled")
            && start_idle_watch_source
                .contains("agent_doc_supervisor_io::config::agent_change_restart_enabled")
            && start_idle_watch_source
                .contains("agent_doc_supervisor_io::config::supervisor_auto_install_enabled")
            && route_authoritative_actor
                .contains("agent_doc_supervisor_io::config::agent_change_restart_enabled")
            && write_converge_io
                .contains("agent_doc_supervisor_io::config::supervisor_auto_recycle_enabled"),
        "orchestration should call file/env-backed supervisor config readers through agent-doc-supervisor-io directly"
    );
    for required_snippet in [
        "pub enum SupervisorPromptDecision",
        "pub enum SupervisorCleanExitResolution",
        "pub enum SupervisorRestartContinueExitStrategy",
        "pub const FAILED_RESTART_WINDOW",
        "pub struct FailedRestartTracker",
        "pub fn classify_supervisor_prompt_input",
        "pub fn supervisor_policy_exit_code",
        "pub fn supervisor_clean_exit_resolution",
        "pub fn restart_continue_exit_strategy",
        "pub fn supervisor_resume_handoff_failed",
        "pub fn supervisor_clean_exit_before_prompt_seen",
        "pub fn format_exit_provenance_fields(",
        "pub fn forwarded_ctrl_c_interrupt_exit(",
    ] {
        assert!(
            supervisor_crash_policy.contains(required_snippet),
            "agent-doc-supervisor crash_policy should own supervisor restart policy directly: {required_snippet}"
        );
    }
    let start_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    let start_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/run.rs")).unwrap();
    let forbidden_snippet = "fn resolve_agent_args(";
    assert!(
        !start_source.contains(forbidden_snippet),
        "start.rs must not re-own pure supervisor launch-args precedence: {forbidden_snippet}"
    );
    assert!(
        start_source.contains("#[cfg(test)]\nfn agent_launch_args_sources(")
            && !start_run_source
                .contains("agent_doc_supervisor::config::resolve_agent_launch_args(")
            && supervisor_process_io.contains("fn agent_launch_args_sources(")
            && supervisor_process_io
                .contains("agent_doc_supervisor::config::resolve_agent_launch_args("),
        "agent-doc-supervisor-process-io should project launch-args facts and call focused supervisor config policy directly"
    );
    for required_snippet in ["pub struct ChildLaunchPlan", "pub fn child_launch_plan("] {
        assert!(
            supervisor_run_loop.contains(required_snippet),
            "agent-doc-supervisor run_loop should own supervisor child-launch planning directly: {required_snippet}"
        );
    }
    for forbidden_snippet in ["struct ChildLaunchPlan", "fn child_launch_plan("] {
        assert!(
            !start_run_source.contains(forbidden_snippet),
            "start/run.rs must not re-own pure supervisor child-launch planning: {forbidden_snippet}"
        );
    }
    assert!(
        start_run_source.contains("run_loop::{") && start_run_source.contains("child_launch_plan"),
        "start/run.rs should call focused supervisor child-launch planning directly"
    );
    for forbidden_snippet in [
        "enum PromptDecision",
        "fn classify_prompt_decision",
        "fn policy_exit_code_for_supervisor",
        "enum CleanExitResolution",
        "enum RestartContinueExitStrategy",
        "struct FailedRestartTracker",
        "const FAILED_RESTART_THRESHOLD",
        "fn clean_exit_resolution",
        "fn restart_continue_exit_strategy",
        "fn resume_handoff_failed",
        "fn clean_exit_before_prompt_seen",
        "format!(\"exit_kind=signal",
        "format!(\"exit_kind=success",
        "format!(\"exit_kind=exit_code",
        "signal.eq_ignore_ascii_case(\"Interrupt\")",
        "status.exit_code() == 130",
    ] {
        assert!(
            !start_source.contains(forbidden_snippet),
            "start.rs must not re-own pure supervisor restart policy: {forbidden_snippet}"
        );
    }
    assert!(
        start_source.contains("classify_supervisor_prompt_input")
            && start_source.contains("SupervisorPromptDecision")
            && start_source.contains("supervisor_policy_exit_code")
            && start_source.contains("FailedRestartTracker")
            && start_run_source.contains("supervisor_policy_exit_code(")
            && start_run_source.contains("supervisor_clean_exit_resolution(")
            && start_run_source.contains("restart_continue_exit_strategy(")
            && start_run_source.contains("supervisor_resume_handoff_failed(")
            && start_run_source.contains("supervisor_clean_exit_before_prompt_seen(")
            && start_source.contains("format_exit_provenance_fields(&rendered, status.success())")
            && start_source.contains(
                "forwarded_ctrl_c_interrupt_exit(&rendered, status.exit_code(), ctrl_c_forwarded)"
            ),
        "start paths should call focused supervisor restart policy directly"
    );
    for required_snippet in [
        "pub fn strip_stale_ctrl_d_before_prompt(",
        "pub fn normalize_supervisor_inject_bytes(",
        "pub fn prompt_input_summary(",
    ] {
        assert!(
            supervisor_input_policy.contains(required_snippet),
            "agent-doc-supervisor input should own pure supervisor byte policy directly: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "fn strip_stale_ctrl_d_before_prompt(",
        "fn normalize_supervisor_inject_bytes(",
        "fn prompt_input_summary(",
    ] {
        assert!(
            !start_source.contains(forbidden_snippet),
            "start.rs must not re-own pure supervisor byte policy: {forbidden_snippet}"
        );
    }
    assert!(
        start_source.contains("use agent_doc_supervisor::input::prompt_input_summary;")
            && start_source.contains("prompt_input_summary")
            && supervisor_io_ipc
                .contains("use agent_doc_supervisor::input::normalize_supervisor_inject_bytes;")
            && supervisor_io_ipc.contains("normalize_supervisor_inject_bytes(bytes)")
            && supervisor_io_threads
                .contains("agent_doc_supervisor::input::strip_stale_ctrl_d_before_prompt"),
        "start/supervisor process paths should call focused supervisor input byte policy directly"
    );
    let required_snippet = "pub fn build_reexec_candidates(";
    assert!(
        supervisor_reexec_policy.contains(required_snippet),
        "agent-doc-supervisor reexec should own supervisor reexec candidate policy directly: {required_snippet}"
    );
    let forbidden_snippet = "fn build_reexec_candidates(";
    assert!(
        !start_source.contains(forbidden_snippet),
        "start.rs must not re-own pure supervisor reexec candidate policy: {forbidden_snippet}"
    );
    assert!(
        supervisor_lib.contains("pub mod reexec;")
            && start_source.contains("agent_doc_supervisor::reexec::build_reexec_candidates("),
        "start.rs should project reexec facts and call focused supervisor reexec policy directly"
    );
    let supervisor_route_owned =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/route_owned.rs")).unwrap();
    for required_snippet in [
        "pub enum RouteOwnedReapPolicy",
        "pub enum RouteOwnedLivenessReason",
        "pub struct RouteOwnedReapDecision",
        "pub struct RouteOwnedCycleFacts",
        "pub enum RouteOwnedCyclePhase",
        "pub fn route_owned_reap_decision(",
        "pub fn route_owned_cycle_changed_since_start(",
        "pub fn route_owned_cycle_committed_since_start(",
        "pub fn route_owned_file_dirty_after_commit(",
        "pub fn route_owned_liveness_reason_for_content(",
        "pub fn route_owned_backlog_has_live_items(",
        "pub fn route_owned_queue_has_prompts(",
        "pub fn route_owned_exchange_tail_has_unresolved_prompt(",
    ] {
        assert!(
            supervisor_route_owned.contains(required_snippet),
            "agent-doc-supervisor route_owned should own route-owned reap policy directly: {required_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub enum RouteOwnedReapPolicy",
        "pub enum RouteOwnedLivenessReason",
        "struct RouteOwnedReapDecision",
        "fn route_owned_facts_from_cycle_state(",
        "fn route_owned_liveness_reason_for_file(",
        "fn spawn_route_owned_completion_thread(",
        "fn route_owned_reap_decision(",
        "fn route_owned_cycle_changed_after_start(",
        "fn route_owned_cycle_completed_after_start(",
        "fn route_owned_cycle_changed_since_start(",
        "fn route_owned_cycle_committed_since_start(",
        "fn route_owned_file_dirty_after_commit(",
        "fn route_owned_liveness_reason_for_content(",
        "fn route_owned_reap_decision_for_file(",
        "fn route_owned_backlog_has_live_items(",
        "fn route_owned_queue_has_prompts(",
        "fn route_owned_exchange_tail_has_unresolved_prompt(",
        "fn route_owned_line_is_response_heading(",
    ] {
        assert!(
            !start_source.contains(forbidden_snippet),
            "start.rs must not re-own pure route-owned reap policy: {forbidden_snippet}"
        );
    }
    for required_snippet in [
        "pub trait RouteOwnedCompletionState",
        "pub struct RouteOwnedCompletionConfig",
        "pub fn route_owned_facts_from_cycle_state(",
        "pub fn route_owned_liveness_reason_for_file(",
        "pub fn load_route_owned_cycle_state(",
        "pub fn spawn_route_owned_completion_thread",
        "route_owned_liveness_reason_for_content",
        "route_owned_reap_decision(",
        "route_owned_cycle_committed_since_start(",
        "RouteOwnedLivenessReason::AdapterFailure",
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)",
        "load_route_owned_cycle_state(&file)",
    ] {
        assert!(
            supervisor_route_owned_completion.contains(required_snippet),
            "agent-doc-supervisor-process should own route-owned completion adapters and loop: {required_snippet}"
        );
    }
    assert!(
        !supervisor_route_owned_completion.contains("agent_doc_cycle_state_io::load(&file)"),
        "route-owned completion should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        start_source.contains(
            "impl agent_doc_supervisor_process::route_owned_completion::RouteOwnedCompletionState"
        ) && start_source.contains("fn live_pane_busy_reason(")
            && start_source.contains("fn request_child_stop("),
        "start.rs should only implement the live SupervisorShared adapter for the route-owned completion seam"
    );
    assert!(
        start_run_source.contains("RouteOwnedCompletionConfig::new(")
            && start_run_source.contains("spawn_route_owned_completion_thread(")
            && start_run_source.contains("log_event,"),
        "start/run.rs should call the supervisor-process route-owned completion loop directly"
    );
    let cli_main = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        cli_main.contains("agent_doc_supervisor::route_owned::RouteOwnedReapPolicy")
            && !cli_main.contains("agent_doc_orchestration::start::RouteOwnedReapPolicy"),
        "the CLI shell should use the focused route-owned reap policy type directly"
    );

    for relative in [
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-supervisor-process/src/in_process.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-harness/src/lib.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("start::decisions")
                && !source.contains("pub mod decisions")
                && !source.contains("super::decisions")
                && !source.contains("supervisor::state")
                && !source.contains("super::state"),
            "{relative} must call focused supervisor/queue/process crates directly"
        );
    }

    let supervisor_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/lib.rs")).unwrap();
    assert!(
        supervisor_io_lib.contains("pub mod selfkill;"),
        "agent-doc-supervisor-io must expose supervisor selfkill effect IO through its owning module"
    );
    let supervisor_selfkill =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/selfkill.rs")).unwrap();
    for forbidden_snippet in [
        "pub fn supervisor_self_kill_action(",
        "pub fn supervisor_force_kill_decision(",
        "pub fn start_route_owned_doc_from_args(",
    ] {
        assert!(
            !supervisor_selfkill.contains(forbidden_snippet),
            "supervisor selfkill IO must stay an effect adapter, not re-own pure self-kill policy: {forbidden_snippet}"
        );
    }
    let supervisor_selfkill_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/selfkill.rs")).unwrap();
    let supervisor_lifecycle_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/lifecycle.rs")).unwrap();
    for required_snippet in [
        "pub fn supervisor_self_kill_action(",
        "pub fn supervisor_force_kill_decision(",
        "pub fn start_route_owned_doc_from_args(",
    ] {
        assert!(
            supervisor_selfkill_policy.contains(required_snippet),
            "agent-doc-supervisor should expose pure self-kill policy directly: {required_snippet}"
        );
    }
    assert!(
        supervisor_lifecycle_policy.contains("pub fn write_wedged_from_ipc_failures("),
        "agent-doc-supervisor lifecycle policy should own the write_wedged evidence classifier"
    );
    for required_snippet in [
        "pub enum SupervisorAutoInstallPhase",
        "pub fn supervisor_auto_install_pane_message(",
        "pub fn paused_idle_watch_should_skip(",
        "pub fn idle_queue_submit_mode(",
        "pub fn idle_queue_context_reset_ops_log_message(",
    ] {
        assert!(
            supervisor_idle_watch.contains(required_snippet),
            "agent-doc-supervisor idle_watch should own pure idle-watch policy/messages directly: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn start_session_retryable_during_recycle(",
        "pub fn recycle_interrupted_resubmit_should_wait(",
    ] {
        assert!(
            supervisor_lifecycle_policy.contains(required_snippet),
            "agent-doc-supervisor lifecycle policy should own recycle-in-flight routing decisions: {required_snippet}"
        );
    }
    let write_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    assert!(
        !write_converge_io.contains("pub fn write_wedged_from_ipc_failures(")
            && !write_ipc.contains("pub fn write_wedged_from_ipc_failures("),
        "orchestration write modules must not re-own pure supervisor write-wedge classification"
    );
    assert!(
        write_converge_io
            .contains("agent_doc_supervisor::lifecycle::write_wedged_from_ipc_failures"),
        "write convergence IO should call focused supervisor write-wedge classification directly"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor_selfkill.rs")
            .exists(),
        "orchestration must not keep a supervisor_selfkill source module facade"
    );
    assert!(
        !orchestration_lib.contains("pub mod supervisor_selfkill"),
        "orchestration must not expose a supervisor_selfkill facade"
    );
    for forbidden_snippet in [
        "pub fn start_session_retryable_during_recycle(",
        "fn start_session_retryable_during_recycle(",
        "pub fn recycle_interrupted_resubmit_should_wait(",
        "fn recycle_interrupted_resubmit_should_wait(",
        "pub use agent_doc_supervisor::lifecycle",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden_snippet),
            "orchestration must not expose a supervisor lifecycle facade: {forbidden_snippet}"
        );
    }
    assert!(
        start_io_source.contains("agent_doc_supervisor::{")
            && start_io_source.contains("start_session_retryable_during_recycle"),
        "agent-doc-start-io should call focused supervisor start-session recycle retry policy directly"
    );
    let route_direct_pane_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/direct_pane_dispatch.rs"))
            .unwrap();
    assert!(
        route_direct_pane_dispatch.contains("agent_doc_supervisor::")
            && route_direct_pane_dispatch.contains("recycle_interrupted_resubmit_should_wait"),
        "direct-pane route IO should call focused supervisor recycle-resubmit policy directly"
    );
    let idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    assert!(
        idle_watch.contains("agent_doc_supervisor::selfkill::supervisor_self_kill_action"),
        "idle_watch should call focused supervisor self-kill policy directly"
    );
    assert!(
        supervisor_lib.contains("pub mod idle_watch;")
            && idle_watch.contains("agent_doc_supervisor::{")
            && idle_watch.contains("idle_watch::{"),
        "idle_watch should call focused supervisor idle-watch policy directly"
    );
    for forbidden_snippet in [
        "enum SupervisorAutoInstallPhase",
        "fn supervisor_auto_install_pane_message(",
        "pub fn paused_idle_watch_should_skip(",
        "fn paused_idle_watch_should_skip(",
        "fn idle_queue_submit_mode(",
        "fn idle_queue_context_reset_ops_log_message(",
    ] {
        assert!(
            !idle_watch.contains(forbidden_snippet)
                && !orchestration_start.contains(forbidden_snippet),
            "orchestration idle_watch must not re-own pure supervisor idle-watch policy: {forbidden_snippet}"
        );
    }
    // Supervisor process DISCOVERY moved out of the kill path into
    // `agent-doc-supervisor-io/src/process.rs`: "which pid supervises this doc?"
    // is a liveness question (no supervisor => no idle-queue watch => an active
    // `queue: go` document cannot self-drain), not a kill-path concern. The guard
    // still pins the same invariant — the supervisor IO layer calls the focused
    // pure cmdline parser DIRECTLY, with no facade in between.
    let supervisor_process =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/process.rs")).unwrap();
    assert!(
        supervisor_process
            .contains("agent_doc_supervisor::selfkill::start_route_owned_doc_from_args"),
        "supervisor process discovery IO should call focused route-owned cmdline parsing directly"
    );
    assert!(
        supervisor_selfkill
            .contains("agent_doc_supervisor::selfkill::supervisor_force_kill_decision"),
        "supervisor selfkill IO should call focused force-kill escalation policy directly"
    );
    for relative in [
        "src/main.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_supervisor_io::selfkill"),
            "{relative} should call focused supervisor selfkill IO directly"
        );
        assert!(
            !source.contains("crate::supervisor_selfkill")
                && !source.contains("agent_doc_orchestration::supervisor_selfkill"),
            "{relative} must not call the removed orchestration supervisor_selfkill facade"
        );
    }

    for forbidden_snippet in [
        "pub(crate) fn ready_busy_conflict_reconcile_decision(",
        "pub(crate) fn stale_busy_idle_reconcile_decision(",
        "pub(crate) fn reconcile_stale_busy_idle_queue_state(",
        "recoverable_ready_busy_blocker_reason",
        "harness.dispatch_blocker_reason(&output)",
        "agent_doc_harness::ready_prompt_candidate(&content, harness).is_some()",
        "harness.has_busy_cue(&content)",
        "harness.is_help_screen_output(",
    ] {
        assert!(
            !supervisor_io_detection.contains(forbidden_snippet),
            "supervisor detection IO must not re-own pure supervisor reconcile/detection policy: {forbidden_snippet}"
        );
    }
    for required_snippet in [
        "pub enum IdleQueuePromptVisibility",
        "pub fn prompt_visible_requires_ready_transition(",
        "pub fn idle_queue_prompt_visibility(",
        "pub fn idle_queue_prompt_visible_after_live_pane_dispatch_ready(",
        "pub fn ready_busy_blocker_reason(",
        "pub fn help_screen_visible(",
        "pub fn pane_dispatch_ready(",
        "pub fn pane_dispatch_ready_at_cursor(",
        "pub fn pane_has_busy_cue(",
    ] {
        assert!(
            supervisor_detection.contains(required_snippet),
            "agent-doc-supervisor must own pure terminal/detection policy: {required_snippet}"
        );
    }
    assert!(
        supervisor_lib.contains("pub mod detection;")
            && supervisor_io_lib.contains("pub mod detection;")
            && supervisor_io_detection
                .contains("use agent_doc_supervisor::detection as supervisor_detection;")
            && supervisor_io_detection.contains("pub trait SupervisorDetectionState")
            && supervisor_io_detection.contains("supervisor_detection::idle_queue_prompt_visibility")
            && supervisor_io_detection.contains("supervisor_detection::ready_busy_blocker_reason")
            && supervisor_io_detection.contains("supervisor_detection::pane_dispatch_ready")
            && supervisor_io_detection.contains("supervisor_detection::pane_has_busy_cue")
            && supervisor_io_detection.contains("supervisor_detection::help_screen_visible")
            && orchestration_start.contains(
                "impl agent_doc_supervisor_io::detection::SupervisorDetectionState for SupervisorShared"
            ),
        "supervisor-io detection should adapt live buffers and call focused supervisor detection policy directly while start.rs keeps only the concrete state adapter"
    );
    let idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    assert!(
        idle_watch.contains("agent_doc_supervisor::{")
            && idle_watch.contains("idle_reconcile::{")
            && idle_watch.contains("ready_busy_conflict_reconcile_decision")
            && supervisor_route_owned_completion.contains(
                "agent_doc_supervisor::idle_reconcile::ready_busy_conflict_reconcile_decision"
            ),
        "start paths should call focused supervisor idle_reconcile policy directly"
    );

    for relative in [
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-supervisor-process/src/in_process.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_supervisor::crash_policy::{"),
            "{relative} should call focused crash policy directly"
        );
    }

    let supervisor_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&supervisor_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-diff",
        "agent-doc-element",
        "agent-doc-element-backlog",
        "agent-doc-hash",
        "agent-doc-queue",
    ] {
        assert!(
            dependencies.contains_key(required),
            "agent-doc-supervisor route-owned liveness should depend only on focused pure domain crates: {required}"
        );
    }
    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-supervisor-process",
        "interprocess",
        "notify",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-supervisor must stay pure and not depend on orchestration/process effects"
        );
    }
}

#[test]
fn test_agent_doc_queue_has_no_manual_addition_compatibility_shim() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_source =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/document_queue.rs")).unwrap();

    for required in [
        "pub fn operator_authored_prompt_identities(",
        "pub fn normalized_queue_line_for_match(",
        "pub fn queue_contains_prompt_line(",
        "pub fn queue_ids_including_struck(",
        "pub fn queue_delete_counts(",
        "pub fn queue_counts_are_subset(",
        "pub fn queue_counts_have_deletion(",
    ] {
        assert!(
            queue_source.contains(required),
            "agent-doc-queue should expose the focused queue identity API: {required}"
        );
    }
    for forbidden_snippet in [
        "pub fn annotate_manual_queue_additions(",
        "compatibility shim for older call sites",
        "pub use agent_doc_document::queue_projection",
    ] {
        assert!(
            !queue_source.contains(forbidden_snippet),
            "agent-doc-queue must not retain the removed manual-addition compatibility shim: {forbidden_snippet}"
        );
    }

    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn normalized_queue_line_for_match(",
        "pub(crate) fn queue_contains_prompt_line(",
        "pub(crate) fn queue_ids_including_struck(",
    ] {
        assert!(
            !response_guards.contains(forbidden),
            "response_guards must not re-own queue prompt identity policy: {forbidden}"
        );
    }
    assert!(
        response_guards
            .contains("agent_doc_turn::closeout_signal::still_missing_dropped_queue_prompts"),
        "response_guards should call focused dropped-queue classifier directly"
    );
    let closeout_signal =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/closeout_signal.rs")).unwrap();
    for required in [
        "agent_doc_queue::document_queue::queue_contains_prompt_line",
        "agent_doc_queue::document_queue::queue_ids_including_struck",
    ] {
        assert!(
            closeout_signal.contains(required),
            "closeout_signal should call focused queue identity policy directly: {required}"
        );
    }
    let queue_consume =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_consume.rs")).unwrap();
    assert!(
        queue_consume.contains("use agent_doc_document::queue_projection::{")
            && queue_consume.contains("strip_in_progress_marker")
            && queue_consume.contains("strip_priority_markers"),
        "agent-doc-queue modules should import marker projection helpers directly instead of through document_queue"
    );

    let maintenance_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden in [
        "type QueueDeleteCounts =",
        "fn queue_entry_delete_key(",
        "fn queue_delete_counts(",
        "fn queue_counts_are_subset(",
        "fn queue_counts_have_deletion(",
        "agent_doc_queue::document_queue::queue_delete_counts",
        "agent_doc_queue::document_queue::queue_counts_are_subset",
        "agent_doc_queue::document_queue::queue_counts_have_deletion",
    ] {
        assert!(
            !maintenance_source.contains(forbidden),
            "preflight maintenance must not reconcile a second queue image: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_markdown_ast_uses_current_node_key_mutation_api_names() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let mutations =
        fs::read_to_string(manifest_dir.join("agent-doc-markdown-ast/src/mutations.rs")).unwrap();
    for required in [
        "pub fn consume_node(",
        "pub fn dedup_node_keys(",
        "pub fn reorder_nodes(",
        "pub fn enqueue_node(",
        "pub fn parse_node_patches_payload(",
        "pub fn node_patches_already_landed(",
    ] {
        assert!(
            mutations.contains(required),
            "agent-doc-markdown-ast should expose current node-key mutation API: {required}"
        );
    }
    for forbidden in [
        "pub fn consume_item(",
        "pub fn dedup_id_backed_items(",
        "pub fn reorder_items(",
        "pub fn enqueue_item_after(",
        "fn find_node_key_by_item_id(",
        "ItemNotFound",
        "Compatibility wrapper for older id-keyed callers",
    ] {
        assert!(
            !mutations.contains(forbidden),
            "agent-doc-markdown-ast must not preserve deprecated id-keyed mutation wrappers: {forbidden}"
        );
    }
    let converge =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    let write_normalization =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/write_normalization.rs"))
            .unwrap();
    for forbidden in [
        "fn parse_convergence_node_patches(",
        "fn convergence_node_patches_already_landed(",
        "fn optional_payload_string(",
    ] {
        assert!(
            !converge.contains(forbidden),
            "write convergence IO must not re-own node-key mutation payload policy: {forbidden}"
        );
    }
    assert!(
        converge.contains("convergence_recovered_editor_wins_for_payload"),
        "write convergence IO should delegate convergence payload policy to agent-doc-document"
    );
    for required in [
        "agent_doc_markdown_ast::mutations::parse_node_patches_payload",
        "agent_doc_markdown_ast::mutations::node_patches_already_landed",
    ] {
        assert!(
            write_normalization.contains(required),
            "agent-doc-document should call focused node-key mutation payload policy directly: {required}"
        );
    }
}

#[test]
fn test_agent_doc_supervisor_process_owns_resize_effects() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-process/src/resize.rs")
            .exists(),
        "agent-doc-supervisor-process must own terminal resize process effects"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/resize.rs")
            .exists(),
        "orchestration must not keep a supervisor::resize facade"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/mod.rs")
            .exists(),
        "orchestration must not keep a supervisor facade module for resize effects"
    );

    let start_run =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/run.rs")).unwrap();
    assert!(
        start_run.contains("agent_doc_supervisor_process::{") && start_run.contains("resize,"),
        "supervisor run loop should import resize from agent-doc-supervisor-process directly"
    );

    let supervisor_process =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/lib.rs")).unwrap();
    for required in [
        "pub const ROUTE_BIN_ENV: &str = \"AGENT_DOC_ROUTE_BIN\";",
        "pub fn agent_doc_start_bin() -> String",
        "pub mod start_command;",
        "pub mod detached_child;",
    ] {
        assert!(
            supervisor_process.contains(required),
            "agent-doc-supervisor-process should own supervisor start-binary resolution: {required}"
        );
    }
    let supervisor_start_command =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/start_command.rs"))
            .unwrap();
    for required in [
        "pub fn route_owned_start_command(",
        "pub fn route_owned_start_command_with_options(",
        "fn shell_quote_arg(",
        "start --route-owned",
    ] {
        assert!(
            supervisor_start_command.contains(required),
            "agent-doc-supervisor-process should own route-owned supervisor start command rendering: {required}"
        );
    }
    assert!(
        !supervisor_start_command.contains("pub stderr_log:")
            && !supervisor_start_command.contains("route_owned_stderr_log_path"),
        "agent-doc start must own supervisor stderr setup; its shell command must carry no log path or redirect"
    );
    // `#fresh-project-supervisor-log`: route and cold-replacement callers own
    // only process submission. The start binary owns config resolution,
    // directory creation, file open, deterministic fallback, and fd2 redirect.
    for relative in [
        "agent-doc-route-io/src/startup.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        let names_a_renderer = source.contains("route_owned_start_command_with_options");
        assert!(
            names_a_renderer,
            "{relative} must render its route-owned start command through agent-doc-supervisor-process"
        );
        assert!(
            !source.contains("stderr_log: Some(&stderr_log)"),
            "{relative} must not pass a caller-owned stderr log into the start command"
        );
    }
    let supervisor_process_io =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process-io/src/lib.rs"))
            .unwrap();
    for required in [
        "pub fn open_supervisor_stderr_log(",
        "agent_doc_supervisor_stderr_log",
        "std::fs::create_dir_all(parent)",
        "supervisor_stderr_fallback_path(project_root)",
        "libc::dup2(stderr_log.file().as_raw_fd(), libc::STDERR_FILENO)",
    ] {
        assert!(
            supervisor_process_io.contains(required),
            "agent-doc start must own supervisor stderr setup in-process: {required}"
        );
    }
    let supervisor_detached_child =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/detached_child.rs"))
            .unwrap();
    for required in ["pub fn reap_detached(", "fn spawn_reaper("] {
        assert!(
            supervisor_detached_child.contains(required),
            "agent-doc-supervisor-process should own detached child reaping: {required}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/detached_child.rs")
            .exists(),
        "orchestration must not keep a detached_child process-effects facade"
    );
    for (relative, required) in [
        (
            "agent-doc-route-io/src/startup.rs",
            "agent_doc_supervisor_process::agent_doc_start_bin()",
        ),
        (
            "agent-doc-controller-io/src/project_controller/rpc.rs",
            "agent_doc_supervisor_process::agent_doc_start_bin()",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains(required),
            "{relative} should call focused supervisor-process start-binary resolution directly"
        );
        for forbidden in [
            "fn agent_doc_start_bin(",
            "fn agent_doc_start_bin_for_supervisor_replacement(",
            "fn supervisor_replacement_start_command(",
            "fn shell_quote_arg(",
            "std::env::var(\"AGENT_DOC_ROUTE_BIN\")",
            "std::env::current_exe()",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own supervisor start-binary resolution: {forbidden}"
            );
        }
    }
    for relative in [
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-watch-io/src/daemon.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_supervisor_process::detached_child::reap_detached("),
            "{relative} should call focused supervisor-process detached-child reaping directly"
        );
        assert!(
            !source.contains("crate::detached_child::reap_detached("),
            "{relative} must not call the removed orchestration detached_child facade"
        );
    }
}

#[test]
fn test_agent_doc_supervisor_launch_env_and_owned_screen_are_extracted() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-io/src/env.rs")
            .exists(),
        "agent-doc-supervisor-io must own supervisor launch env resolution"
    );
    assert!(
        manifest_dir
            .join("agent-doc-supervisor-process/src/screen.rs")
            .exists(),
        "agent-doc-supervisor-process must own supervised PTY screen state"
    );
    for removed in [
        "agent-doc-orchestration/src/supervisor/env.rs",
        "agent-doc-orchestration/src/supervisor/screen.rs",
    ] {
        assert!(
            !manifest_dir.join(removed).exists(),
            "orchestration must not retain removed supervisor seam module: {removed}"
        );
    }

    let supervisor_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/lib.rs")).unwrap();
    assert!(
        supervisor_io_lib.contains("pub mod env;"),
        "agent-doc-supervisor-io must expose EnvSpec through its owning env module"
    );
    let supervisor_process_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/lib.rs")).unwrap();
    assert!(
        supervisor_process_lib.contains("pub mod screen;"),
        "agent-doc-supervisor-process must expose OwnedPtyScreen through its owning screen module"
    );

    let supervisor_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/Cargo.toml")).unwrap();
    let supervisor_io: toml::Value = toml::from_str(&supervisor_io_manifest).unwrap();
    let supervisor_io_dependencies = supervisor_io["dependencies"].as_table().unwrap();
    for required in ["agent-doc-config", "agent-doc-frontmatter", "indexmap"] {
        assert!(
            supervisor_io_dependencies.contains_key(required),
            "agent-doc-supervisor-io env module must own its dependency: {required}"
        );
    }
    let supervisor_process_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/Cargo.toml")).unwrap();
    let supervisor_process: toml::Value = toml::from_str(&supervisor_process_manifest).unwrap();
    let supervisor_process_dependencies = supervisor_process["dependencies"].as_table().unwrap();
    for required in ["alacritty_terminal", "portable-pty"] {
        assert!(
            supervisor_process_dependencies.contains_key(required),
            "agent-doc-supervisor-process screen module must own its dependency: {required}"
        );
    }
    let supervisor_process_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process-io/Cargo.toml"))
            .unwrap();
    let supervisor_process_io: toml::Value =
        toml::from_str(&supervisor_process_io_manifest).unwrap();
    let supervisor_process_io_dependencies =
        supervisor_process_io["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-config",
        "agent-doc-frontmatter",
        "agent-doc-git-io",
        "agent-doc-harness",
        "agent-doc-model-tier",
        "agent-doc-supervisor",
        "agent-doc-supervisor-io",
        "agent-doc-supervisor-process",
        "agent-doc-turn-executor",
        "anyhow",
        "libc",
    ] {
        assert!(
            supervisor_process_io_dependencies.contains_key(required),
            "agent-doc-supervisor-process-io launch/process adapter must own its dependency: {required}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/supervisor/mod.rs")
            .exists(),
        "orchestration must not expose an env/screen supervisor facade"
    );
    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration["dependencies"].as_table().unwrap();
    assert!(
        !orchestration_dependencies.contains_key("alacritty_terminal"),
        "agent-doc-orchestration must not depend on the screen emulator after screen extraction"
    );

    let start_run =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/run.rs")).unwrap();
    assert!(
        start_run.contains("build_harness_launch_spec(")
            && start_run.contains("StartRunLaunchLog")
            && !start_run.contains("EnvSpec::from_frontmatter(fm)")
            && !start_run.contains("CODEX_SANDBOX_NETWORK_DISABLED_ENV"),
        "start/run.rs should delegate supervisor launch-spec assembly to agent-doc-supervisor-process-io"
    );
    let supervisor_process_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/lib.rs")).unwrap();
    let output_state_source =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/output_state.rs"))
            .unwrap();
    let io_threads_source =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process/src/io_threads.rs"))
            .unwrap();
    let process_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-process-io/src/lib.rs"))
            .unwrap();
    assert!(
        supervisor_process_lib.contains("pub mod output_state;")
            && output_state_source.contains("use crate::screen::OwnedPtyScreen;")
            && output_state_source.contains("pub struct SupervisorOutputState")
            && output_state_source.contains("terminal_screen: Mutex<OwnedPtyScreen>"),
        "agent-doc-supervisor-process should own terminal screen state through SupervisorOutputState"
    );
    assert!(
        supervisor_process_lib.contains("pub mod io_threads;")
            && io_threads_source.contains("pub trait PtyReaderObserver")
            && io_threads_source.contains("pub trait StdinForwardObserver")
            && io_threads_source.contains("pub fn spawn_reader_thread")
            && io_threads_source.contains("pub fn spawn_writer_thread"),
        "agent-doc-supervisor-process should own PTY reader/stdin-forwarder thread loops behind callback traits"
    );
    let start_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    let start_supervisor_io =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/supervisor_io.rs"))
            .unwrap();
    assert!(
        start_source.contains("output_state::SupervisorOutputState")
            && start_source.contains("output: SupervisorOutputState")
            && start_source.contains("output: SupervisorOutputState::default()")
            && !start_source.contains("terminal_screen: Mutex<OwnedPtyScreen>")
            && !start_source.contains("recent_output: Mutex<Vec<u8>>"),
        "start.rs should depend on the supervisor-process output-state boundary, not own screen buffers"
    );
    assert!(
        process_io_source.contains("pub struct SupervisorProcessIoObserver")
            && process_io_source.contains("pub trait SupervisorProcessIoState")
            && process_io_source.contains("pub trait SupervisorLaunchLog")
            && process_io_source.contains("pub struct HarnessLaunchSpec")
            && process_io_source.contains("pub struct SupervisorStderrRedirect")
            && process_io_source.contains("pub fn build_harness_launch_spec(")
            && process_io_source.contains("pub fn supervisor_stderr_redirect_needed(")
            && process_io_source
                .contains("agent_doc_supervisor_io::env::EnvSpec::from_frontmatter")
            && process_io_source
                .contains("impl<S> PtyReaderObserver for SupervisorProcessIoObserver<S>")
            && process_io_source
                .contains("impl<S> StdinForwardObserver for SupervisorProcessIoObserver<S>")
            && start_supervisor_io
                .contains("impl agent_doc_supervisor_process_io::SupervisorProcessIoState")
            && !start_supervisor_io
                .contains("impl agent_doc_supervisor_process::io_threads::PtyReaderObserver")
            && !start_supervisor_io
                .contains("impl agent_doc_supervisor_process::io_threads::StdinForwardObserver")
            && !start_supervisor_io.contains("pub(crate) fn spawn_reader_thread")
            && !start_supervisor_io.contains("pub(crate) fn spawn_writer_thread"),
        "agent-doc-supervisor-process-io should own supervisor-process observer and launch adapters"
    );
    assert!(
        !start_run.contains("struct HarnessLaunchSpec")
            && !start_run.contains("struct SupervisorStderrRedirect")
            && !start_run.contains("fn build_harness_launch_spec(")
            && !start_run.contains("fn supervisor_stderr_redirect_needed(")
            && !start_run.contains("fn parent_codex_network_disabled("),
        "start/run.rs must not re-own supervisor launch-spec or stderr redirect helpers after extraction"
    );
    for forbidden in [
        "crate::supervisor::env",
        "crate::supervisor::screen",
        "supervisor::env::EnvSpec",
        "supervisor::screen::OwnedPtyScreen",
    ] {
        assert!(
            !start_source.contains(forbidden) && !start_run.contains(forbidden),
            "start call sites must not route through old orchestration supervisor seams: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_watch_io_owns_pid_effects() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    assert!(
        manifest_dir.join("agent-doc-watch-io/src/lib.rs").exists(),
        "agent-doc-watch-io must own watch daemon PID and controller-watch effects"
    );

    let _: fn(u32) -> bool = agent_doc_watch_io::pid_alive;
    let _: fn() -> bool = agent_doc_watch_io::is_running;
    let _: fn() -> Option<u32> = agent_doc_watch_io::read_pid;
    let _: fn(&Path) -> Option<u32> = agent_doc_watch_io::read_pid_in;
    let _: fn() -> anyhow::Result<()> = agent_doc_watch_io::write_current_pid;
    let _: fn(&Path) -> anyhow::Result<()> = agent_doc_watch_io::write_current_pid_in;
    // `#stalewatchpid`: removal is fallible and must report — a discarded
    // result is how a pid file that could not be removed stayed readable as a
    // live daemon.
    let _: fn() -> anyhow::Result<()> = agent_doc_watch_io::remove_pid;
    let _: fn(&Path) -> anyhow::Result<()> = agent_doc_watch_io::remove_pid_in;
    let _: fn() -> anyhow::Result<Option<u32>> = agent_doc_watch_io::clear_stale_pid;
    let _: fn(&Path) -> anyhow::Result<Option<u32>> = agent_doc_watch_io::clear_stale_pid_in;
    let _: fn(u32) -> bool = agent_doc_watch_io::pid_is_agent_doc_watch;
    let _: fn(
        &str,
        &str,
        &agent_doc_document_realtime::watch_authority::RawWatchEvent,
        &str,
    ) -> agent_doc_watch_io::WatchObservation = agent_doc_watch_io::observe_document_event;

    let watch_io = fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/lib.rs")).unwrap();
    assert_source_mentions_all(
        &watch_io,
        "agent-doc-watch-io",
        &[
            "PID_FILE",
            "WatchObservation",
            "WatcherRegistry",
            "observe_document_event",
            "WatchWriteProvenance",
            "agent_doc_hash::content_hash",
            "file_watch_event_id",
            "StateFact::FileWatchChangeObserved",
        ],
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/watch.rs")
            .exists(),
        "orchestration must not keep a watch source module facade"
    );
    let watch = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert_source_omits_all(
        &watch,
        "CLI watch effects adapter",
        &[
            "const PID_FILE",
            "fn pid_alive(",
            "fn read_pid(",
            "fn read_pid_in(",
            "fn write_pid(",
            "fn write_pid_in(",
            "fn remove_pid(",
            "fn remove_pid_in(",
        ],
    );
    let daemon = fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/daemon.rs")).unwrap();
    assert_source_mentions_all(
        &daemon,
        "watch daemon",
        &[
            "read_pid",
            "pid_alive",
            "write_current_pid",
            "remove_pid",
            "PID_FILE",
        ],
    );
}

#[test]
fn test_agent_doc_queue_owns_backlog_queue_sync_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_sync =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/backlog_sync.rs")).unwrap();
    for required in [
        "pub struct BacklogQueueSyncRequest",
        "pub fn collect_backlog_queue_sync",
        "pub struct OneShotBacklogQueueSyncRequest",
        "pub fn collect_one_shot_backlog_queue_sync",
        "pub struct BacklogQueueSyncReport",
        "pub fn backlog_queue_sync_report",
        "pub enum AutoBacklogQueueSyncPolicy",
        "pub struct AutoBacklogQueueSyncPlan",
        "pub struct AutoBacklogQueueSyncInput",
        "pub fn plan_auto_backlog_queue_sync_ids",
        "pub fn reconcile_queue_tombstones",
        "pub fn format_queue_ids",
        "pub fn collect_backlog_priority_ranks",
        "pub fn collect_after_deps",
    ] {
        assert!(
            queue_sync.contains(required),
            "agent-doc-queue should own backlog-to-queue sync policy: {required}"
        );
    }

    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) struct BacklogQueueSyncRequest",
        "struct BacklogQueueSyncRequest",
        "pub(crate) fn collect_backlog_queue_sync",
        "pub(crate) fn collect_backlog_priority_ranks",
        "pub(crate) fn collect_after_deps",
        "let enqueue_ids: std::collections::HashSet<String>",
        "let mut backlog_ids = sync_request.ids",
        "existing_queue_ids.contains(&key) || enqueue_ids.contains(&key)",
    ] {
        assert!(
            !preflight_maintenance.contains(forbidden_snippet),
            "preflight maintenance must not re-own backlog queue sync policy: {forbidden_snippet}"
        );
    }
    assert!(
        preflight_maintenance.contains("agent_doc_queue::backlog_sync::collect_backlog_queue_sync")
            && preflight_maintenance
                .contains("agent_doc_queue::backlog_sync::collect_backlog_priority_ranks")
            && preflight_maintenance.contains("agent_doc_queue::backlog_sync::collect_after_deps")
            && preflight_maintenance
                .contains("agent_doc_queue::backlog_sync::plan_auto_backlog_queue_sync_ids"),
        "preflight maintenance should call backlog queue sync policy from agent-doc-queue directly"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/preflight/queue_tombstone.rs")
            .exists(),
        "preflight must not keep a queue_tombstone IO facade module"
    );
    let preflight_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    assert!(
        !preflight_lib.contains("mod queue_tombstone"),
        "preflight must not expose a queue_tombstone IO facade"
    );
    let queue_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/Cargo.toml")).unwrap();
    let queue_io: toml::Value = toml::from_str(&queue_io_manifest).unwrap();
    let queue_io_dependencies = queue_io["dependencies"].as_table().unwrap();
    assert!(
        queue_io_dependencies.contains_key("agent-doc-queue")
            && queue_io_dependencies.contains_key("agent-doc-fs"),
        "queue tombstone IO belongs in agent-doc-queue-io with queue policy plus filesystem helpers"
    );
    let queue_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/lib.rs")).unwrap();
    assert!(
        queue_io_lib.contains("pub mod queue_tombstone;"),
        "agent-doc-queue-io must expose queue tombstone sidecar IO through its owning module"
    );
    let queue_tombstone =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_tombstone.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) fn reconcile(",
        "fn reconcile(",
        "snapshot_active_ids.difference(current_all_ids)",
    ] {
        assert!(
            !queue_tombstone.contains(forbidden_snippet),
            "queue tombstone IO must not re-own tombstone reconciliation policy: {forbidden_snippet}"
        );
    }
    assert!(
        queue_tombstone.contains("use agent_doc_queue::backlog_sync::reconcile_queue_tombstones;")
            && queue_tombstone.contains("pub fn reconcile_for_file(")
            && queue_tombstone.contains("reconcile_queue_tombstones("),
        "queue tombstone IO should load/save sidecars and call focused queue tombstone policy directly"
    );
    assert!(
        preflight_maintenance.contains("agent_doc_queue_io::queue_tombstone::reconcile_for_file("),
        "preflight maintenance should call focused queue tombstone IO directly"
    );

    let component_attrs =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/component_attrs.rs")).unwrap();
    for required in [
        "pub struct ComponentAttrWarning",
        "pub fn component_attr_warning",
        "pub fn message_body",
    ] {
        assert!(
            component_attrs.contains(required),
            "agent-doc-queue should own component attribute warning policy: {required}"
        );
    }
    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_warnings_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    for forbidden_snippet in [
        "QUEUE_ONLY_COMPONENT_ATTRS",
        "KNOWN_COMPONENT_ATTRS",
        "fn misplaced_component_attr_warning",
        "BacklogQueueSyncMode::parse(value)",
    ] {
        assert!(
            !preflight_source.contains(forbidden_snippet),
            "preflight.rs must not re-own or facade component attribute warning policy: {forbidden_snippet}"
        );
    }
    assert!(
        preflight_warnings_source
            .contains("agent_doc_workflow::preflight_policy::component_attr_preflight_warning"),
        "focused preflight warnings should delegate component-attr warning adaptation to workflow policy"
    );
    let preflight_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/preflight_policy.rs"))
            .unwrap();
    assert!(
        preflight_policy
            .contains("agent_doc_queue::component_attrs::component_attr_warning(content)")
            && preflight_policy.contains("pub fn component_attr_preflight_warning("),
        "workflow preflight policy should adapt focused component-attr warning facts"
    );

    let queue_io_one_shot =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/one_shot_sync.rs")).unwrap();
    for required_snippet in [
        "pub struct OneShotQueueSyncApplied",
        "pub enum OneShotQueueSyncResult",
        "pub fn sync_one_shot_backlog_queue_with_snapshot(",
        "backlog_sync::collect_one_shot_backlog_queue_sync",
        "document_queue::sync_backlog_into_queue",
        "backlog_sync::backlog_queue_sync_report",
        "write_document(file, content, &new_content)",
    ] {
        assert!(
            queue_io_one_shot.contains(required_snippet),
            "agent-doc-queue-io should own one-shot backlog queue sync file mutation: {required_snippet}"
        );
    }
    let queue_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/Cargo.toml")).unwrap();
    assert!(
        queue_io_manifest.contains("agent-doc-element ="),
        "agent-doc-queue-io should parse agent components directly for one-shot queue sync"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/queue_cmd.rs")
            .exists(),
        "orchestration must not keep a queue_cmd facade after queue command host extraction"
    );
    let queue_cmd =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_cmd.rs")).unwrap();
    for forbidden_snippet in [
        "agent_doc_queue::backlog_sync",
        "agent_doc_queue::document_queue",
        "element::parse(&content)",
        "fn queue_prompt_reference_id",
        "fn queue_entry_reference_id",
        "pub fn format_queue_ids",
        "fn collect_one_shot_backlog_queue_sync",
        "fn backlog_queue_sync_report",
        "document_queue::sync_backlog_into_queue",
        "std::fs::write(file, &new_content)",
    ] {
        assert!(
            !queue_cmd.contains(forbidden_snippet),
            "queue_cmd.rs must not re-own one-shot backlog queue sync file mutation: {forbidden_snippet}"
        );
    }
    assert!(
        queue_cmd.contains("crate::one_shot_sync::sync_one_shot_backlog_queue_with_snapshot(")
            && queue_cmd.contains("OneShotQueueSyncResult")
            && queue_cmd.contains("pub trait QueueCommandEffects"),
        "agent-doc-queue-io queue_cmd should own command rendering and inject remaining write effects"
    );
}

#[test]
fn test_agent_doc_preflight_io_owns_layout_health_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_layout =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/layout.rs")).unwrap();
    let preflight_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();

    assert!(
        preflight_io_lib.contains("pub mod layout;"),
        "agent-doc-preflight-io must expose the focused layout health module"
    );
    for forbidden in [
        "fn maybe_auto_resync_on_drift(",
        "fn close_superseded_drift_sessions(",
        "fn current_tmux_session_name(",
        "fn maybe_auto_repair_base_index(",
        "pub fn check_layout(",
        "fn detect_duplicate_claims(",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not own moved layout health IO: {forbidden}"
        );
    }
    for required in [
        "pub fn maybe_auto_resync_on_drift(",
        "fn close_superseded_drift_sessions(",
        "fn current_tmux_session_name(",
        "pub fn maybe_auto_repair_base_index(",
        "pub fn check_layout(",
        "pub fn detect_duplicate_claims(",
        "CoordinationLeaseRecord",
        "\"preflight_layout_drift\"",
        "agent_doc_sync_io::resync::run(true, None, None)",
        "agent_doc_sync_io::sync::repair_layout",
        "agent_doc_tmux_io::list_windows",
    ] {
        assert!(
            preflight_layout.contains(required),
            "agent-doc-preflight-io layout module should own layout health IO: {required}"
        );
    }
    assert!(
        orchestration_preflight.contains("use agent_doc_preflight_io::{")
            && orchestration_preflight.contains("layout::{")
            && orchestration_preflight.contains("maybe_auto_resync_on_drift")
            && orchestration_preflight.contains("maybe_auto_repair_base_index")
            && orchestration_preflight.contains("check_layout"),
        "orchestration preflight should import focused layout adapters directly"
    );
}

#[test]
fn test_agent_doc_preflight_io_owns_auto_gc_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_gc =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/gc.rs")).unwrap();
    let preflight_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();

    assert!(
        preflight_io_lib.contains("pub mod gc;")
            && preflight_manifest.contains("agent-doc-gc-io ="),
        "agent-doc-preflight-io must expose the focused preflight GC module and depend on gc IO"
    );
    for forbidden in [
        "struct PreflightGcControllerEffects",
        "impl agent_doc_gc_io::GcControllerEffects for PreflightGcControllerEffects",
        "fn run_auto_gc(",
        "close_stale_starting_actors_for_caller(",
        "const PREFLIGHT_AUTO_GC_SCOPE",
    ] {
        assert!(
            !orchestration_preflight_run.contains(forbidden),
            "orchestration preflight/run.rs must not own moved auto-GC IO: {forbidden}"
        );
    }
    assert!(
        orchestration_preflight_run
            .contains("agent_doc_preflight_io::gc::run_preflight_auto_gc(file);"),
        "orchestration preflight/run.rs should call focused preflight GC IO directly"
    );
    for required in [
        "struct PreflightGcControllerEffects",
        "impl agent_doc_gc_io::GcControllerEffects for PreflightGcControllerEffects",
        "fn run_auto_gc(",
        "pub fn run_preflight_auto_gc(",
        "close_stale_starting_actors_for_caller(",
        "reap_removed_project_root_controllers_all_projects(",
        "pub fn record_auto_gc_run(",
        "load_coordination_lease_from_db(",
        "upsert_coordination_lease_in_db(",
        "agent_doc_gc_io::run_with_controller_effects(",
    ] {
        assert!(
            preflight_gc.contains(required),
            "agent-doc-preflight-io gc module should own preflight auto-GC IO: {required}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_io_owns_debounce_wait_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let _idle_watch =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    let preflight_debounce =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/debounce.rs")).unwrap();
    let preflight_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();

    assert!(
        preflight_io_lib.contains("pub mod debounce;"),
        "agent-doc-preflight-io must expose the focused preflight debounce module"
    );
    for forbidden in [
        "pub(crate) fn preflight_debounce_ms(",
        "fn wait_for_typing_idle_before_mutation(",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not own moved debounce IO: {forbidden}"
        );
    }
    for forbidden in [
        "let debounce = std::time::Duration::from_millis(debounce_ms)",
        "agent_doc_debounce::authority_settle_max_wait(debounce_ms)",
        "agent_doc_debounce::is_typing_via_file(&file_str, debounce_ms)",
    ] {
        assert!(
            !orchestration_preflight_run.contains(forbidden),
            "orchestration preflight/run.rs must not retain the moved debounce wait loop: {forbidden}"
        );
    }
    assert!(
        orchestration_preflight_run.contains(
            "agent_doc_preflight_io::debounce::wait_for_lazily_current_before_mutation(file)?;"
        ) && orchestration_preflight_run.contains(
            "agent_doc_preflight_io::debounce::wait_for_lazily_current_observation(file);"
        ),
        "preflight callers should settle against Lazily current state directly"
    );
    for required in [
        "pub fn authority_settle_ms(",
        "pub fn wait_for_lazily_current_before_mutation(",
        "pub fn wait_for_lazily_current_observation(",
        "agent_doc_debounce::authority_settle_max_wait(settle_ms)",
        "preflight_visible_mutation_deferred_lazily_current",
        "tracing::debug!",
    ] {
        assert!(
            preflight_debounce.contains(required),
            "agent-doc-preflight-io debounce module should own preflight debounce IO: {required}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_io_owns_cycle_completion_coordinator() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_runtime = orchestration_preflight
        .split("\n#[cfg(test)]")
        .next()
        .unwrap_or(&orchestration_preflight);
    let preflight_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    let preflight_runtime_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/Cargo.toml")).unwrap();

    for required in [
        "pub trait PreflightCycleCompletionEffects",
        "fn repair(&self, file: &Path) -> Result<agent_doc_turn::repair::RepairOutcome>;",
        "fn commit(&self, file: &Path) -> Result<bool>;",
        "fn session_interruption(&self, file: &Path) -> Result<Option<String>>;",
        "fn detect_bypassed_response_write(&self, file: &Path) -> Result<Option<String>>;",
        "pub fn enforce_cycle_completion(",
        "pub fn append_latest_ipc_dogfood_note(",
        "pub fn append_ipc_dogfood_note_for_diagnostic(",
        "detect_write_completed_commit_missing(file)?",
        "OpsLogEvent::InterruptedCycleDetected",
        "resume_commit_attempt file=",
        "resume_commit_success file=",
        "resume_commit_blocked_drift file=",
        "previous cycle `{}` is still `{}` after recovery/commit",
        ".detect_bypassed_response_write(file)?",
        "append_latest_ipc_dogfood_note(file)",
        "dogfood_agent_doc_crate_root(file).is_none()",
        "latest_ipc_proof_diagnostic(file)?",
        "format_ipc_dogfood_note(diagnostic)",
        "append_deduped_content_to_exchange(",
        "ipc_dogfood_note_appended file=",
    ] {
        assert!(
            preflight_io.contains(required),
            "agent-doc-preflight-io must own preflight cycle-completion coordinator marker: {required}"
        );
    }

    for required in [
        "pub struct RuntimePreflightCycleCompletionEffects",
        "pub fn preflight_cycle_completion_effects",
        "RepairIoEffects:",
        "agent_doc_repair_io::RepairCoordinatorEffects",
        "repair_effects:",
        "session_check_effects: SessionCheckEffects",
        "impl<RepairIoEffects, ReplayWriteEffects, SessionCheckEffects>",
        "agent_doc_repair_io::run(self.repair_effects, file)",
        "agent_doc_commit_io::commit(file)",
        "agent_doc_session_check_io::inspect(file, &self.session_check_effects)",
        "agent_doc_session_check_io::detect_bypassed_response_write(file)",
    ] {
        assert!(
            preflight_runtime.contains(required),
            "agent-doc-preflight-runtime-io must own preflight cycle-completion runtime marker: {required}"
        );
    }

    let required_dep = "agent-doc-repair-io =";
    assert!(
        preflight_runtime_manifest.contains(required_dep),
        "agent-doc-preflight-runtime-io should declare cycle-completion runtime dependency: {required_dep}"
    );

    for forbidden in [
        "detect_write_completed_commit_missing(file)?",
        "interrupted_cycle_detected file=",
        "resume_commit_success file=",
        "resume_commit_blocked_drift file=",
        "previous cycle `{}` is still `{}` after recovery/commit",
        ".detect_bypassed_response_write(file)?",
        "fn append_latest_ipc_dogfood_note(",
        "fn append_ipc_dogfood_note_for_diagnostic(",
        "dogfood_agent_doc_crate_root(file).is_none()",
        "latest_ipc_proof_diagnostic(file)?",
        "format_ipc_dogfood_note(diagnostic)",
        "append_deduped_content_to_exchange(",
        "ipc_dogfood_note_appended file=",
        "struct OrchestrationPreflightCycleCompletionEffects",
        "impl PreflightCycleCompletionEffects for OrchestrationPreflightCycleCompletionEffects",
        "agent_doc_session_check_io::inspect(",
        "agent_doc_session_check_io::detect_bypassed_response_write(file)",
    ] {
        assert!(
            !orchestration_preflight_runtime.contains(forbidden),
            "orchestration preflight.rs must not re-own cycle-completion coordinator marker: {forbidden}"
        );
    }

    assert!(
        orchestration_preflight.contains("agent_doc_preflight_io::enforce_cycle_completion(")
            && orchestration_preflight
                .contains("agent_doc_preflight_runtime_io::preflight_cycle_completion_effects(")
            && orchestration_preflight
                .contains("agent_doc_repair_runtime_io::repair_coordinator_effects(")
            && orchestration_preflight
                .contains("&agent_doc_write_runtime_io::REPAIR_REPLAY_WRITE_EFFECTS")
            && orchestration_preflight
                .contains("agent_doc_closeout_runtime_io::session_check_effects()"),
        "orchestration preflight.rs should only inject the focused repair replay writer and session-check runtime effects"
    );
    assert!(
        preflight_manifest.contains("agent-doc-element-exchange =")
            && !preflight_manifest.contains("agent-doc-session-check-io"),
        "preflight IO cycle completion should own exchange note append IO while using callbacks instead of depending on session-check IO"
    );
}

#[test]
fn test_agent_doc_preflight_runtime_io_owns_prompt_cleanup_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    let preflight_runtime_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/Cargo.toml")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_runtime = orchestration_preflight
        .split("\n#[cfg(test)]")
        .next()
        .unwrap_or(&orchestration_preflight);
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();

    for required in [
        "pub fn relocate_out_of_exchange_prompt_before_diff(",
        "pub fn remove_duplicate_answered_exchange_prompt_tail_for_preflight(",
        "pub fn remove_post_exchange_duplicate_prompt_comments_for_preflight(",
        "agent_doc_template::repair_prompt_tail_outside_exchange(",
        "agent_doc_template::remove_duplicate_answered_exchange_prompt_tail(",
        "agent_doc_template::remove_post_exchange_duplicate_prompt_comments_preserving_docs(",
        "agent_doc_document_realtime_io::atomic_write_through_authority(",
        "agent_doc_snapshot_io::load_document_baseline(file)",
        "preflight_repair_prompt_tail_outside_exchange file=",
        "post_exchange_duplicate_prompt_comment_removed file=",
    ] {
        assert!(
            preflight_runtime.contains(required),
            "agent-doc-preflight-runtime-io must own preflight prompt-cleanup runtime marker: {required}"
        );
    }

    for required_dep in [
        "agent-doc-frontmatter =",
        "agent-doc-ops-log-io =",
        "agent-doc-run-context-io =",
        "agent-doc-snapshot-io =",
        "agent-doc-template =",
        "agent-doc-template-io =",
    ] {
        assert!(
            preflight_runtime_manifest.contains(required_dep),
            "agent-doc-preflight-runtime-io should declare prompt-cleanup runtime dependency: {required_dep}"
        );
    }

    for forbidden in [
        "fn relocate_out_of_exchange_prompt_before_diff(",
        "fn remove_duplicate_answered_exchange_prompt_tail_for_preflight(",
        "fn remove_post_exchange_duplicate_prompt_comments_for_preflight(",
        "agent_doc_template::repair_prompt_tail_outside_exchange(",
        "agent_doc_template::remove_duplicate_answered_exchange_prompt_tail(",
        "agent_doc_template::remove_post_exchange_duplicate_prompt_comments_preserving_docs(",
    ] {
        assert!(
            !orchestration_preflight_runtime.contains(forbidden),
            "orchestration preflight.rs must not re-own prompt-cleanup runtime marker: {forbidden}"
        );
    }

    for required_call in [
        "relocate_out_of_exchange_prompt_before_diff(file)?",
        "remove_duplicate_answered_exchange_prompt_tail_for_preflight(file)?",
        "remove_post_exchange_duplicate_prompt_comments_for_preflight(file, &rc)?",
    ] {
        assert!(
            orchestration_preflight_run.contains(required_call),
            "preflight run sequencing should call focused runtime cleanup helper: {required_call}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_runtime_io_owns_route_queue_snapshot_recovery_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    let preflight_runtime_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/Cargo.toml")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_command_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();

    for required in [
        "pub fn recover_route_queue_snapshot_commit_boundary(",
        "pub fn detect_route_queue_snapshot_commit_boundary_recoverable(",
        "agent_doc_commit_io::commit(file)",
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)?",
        "agent_doc_queue::route_dispatch::active_auto_route_queue_prompt_texts",
        "agent_doc_queue::route_dispatch::strip_route_queue_state_for_boundary_compare",
        "agent_doc_diff::classify_prompt_bearing_changes",
        "route_queue_snapshot_auto_recovery_succeeded file=",
    ] {
        assert!(
            preflight_runtime.contains(required),
            "agent-doc-preflight-runtime-io must own route-queue snapshot recovery marker: {required}"
        );
    }

    for required_dep in [
        "agent-doc-commit-io =",
        "agent-doc-cycle-state-io =",
        "agent-doc-diff =",
        "agent-doc-queue =",
        "agent-doc-turn =",
    ] {
        assert!(
            preflight_runtime_manifest.contains(required_dep),
            "agent-doc-preflight-runtime-io should declare route-queue recovery dependency: {required_dep}"
        );
    }

    for forbidden in [
        "fn recover_route_queue_snapshot_commit_boundary(",
        "fn detect_route_queue_snapshot_commit_boundary_recoverable(",
        "agent_doc_queue::route_dispatch::strip_route_queue_state_for_boundary_compare",
        "agent_doc_diff::classify_prompt_bearing_changes",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not re-own route-queue snapshot recovery marker: {forbidden}"
        );
    }

    assert!(
        preflight_runtime.contains("recover_route_queue_snapshot_commit_boundary(file, rc)?"),
        "preflight runtime sequencing should call the focused route-queue snapshot recovery helper"
    );
    assert!(
        !preflight_runtime.contains("agent_doc_cycle_state_io::load(file)?"),
        "preflight route-queue recovery should use closeout projections before compatibility cycle sidecars"
    );
    assert!(
        preflight_command_run.contains("fn closeout_cycle_is_open(file: &Path)")
            && preflight_command_run
                .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)?")
            && !preflight_command_run.contains("agent_doc_cycle_state_io::load(file)?"),
        "preflight command open-cycle checks should read through the projection-aware cycle loader"
    );
}

#[test]
fn test_agent_doc_preflight_runtime_io_owns_ipc_truncation_recovery_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    let preflight_runtime_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/Cargo.toml")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();

    for required in [
        "pub fn recover_ipc_truncated_worktree_from_editor_buffer(",
        "agent_doc_crdt_relay_io::current_text_for_file(&canonical)?",
        "ipc_truncation_recover_pending file=",
        "editor_buffer_preserved_head_exchange(",
        "ipc_truncation_recovered_from_editor_projection file=",
    ] {
        assert!(
            preflight_runtime.contains(required),
            "agent-doc-preflight-runtime-io must own IPC truncation recovery marker: {required}"
        );
    }

    for required_dep in ["agent-doc-document =", "agent-doc-session-check-io ="] {
        assert!(
            preflight_runtime_manifest.contains(required_dep),
            "agent-doc-preflight-runtime-io should declare IPC truncation recovery dependency: {required_dep}"
        );
    }

    for forbidden in [
        "fn recover_ipc_truncated_worktree_from_editor_buffer(",
        "fn poll_save_document_visible_write_receipt(",
        "agent_doc_ipc_io::send_save_document_to_editor(",
        "agent_doc_debounce::await_editor_sync_barrier(",
        "editor_buffer_preserved_head_exchange(",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not re-own IPC truncation recovery marker: {forbidden}"
        );
    }

    assert!(
        !preflight_runtime.contains("send_save_document_to_editor(")
            && !preflight_runtime.contains("poll_save_document_visible_write_receipt("),
        "preflight truncation recovery must consume normal state projection without requesting or polling an editor save"
    );
    assert!(
        preflight_runtime.contains("recover_ipc_truncated_worktree_from_editor_buffer(file, rc)?"),
        "preflight runtime sequencing should call the focused IPC truncation recovery helper"
    );
}

#[test]
fn test_agent_doc_preflight_runtime_io_owns_closeout_drift_recovery_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();

    for required in [
        "pub fn enforce_no_uncommitted_closeout_drift(",
        "session_check_effects: &impl agent_doc_session_check_io::SessionCheckEffects",
        "recover_route_queue_snapshot_commit_boundary(file, rc)?",
        "detect_jb_cache_conflict_accept_duplicate_replay_with_context(",
        "jb_cache_conflict_accept_duplicate_replay_repaired file=",
        "detect_late_ipc_response_overapplication_with_context(file, rc)?",
        "late_ipc_response_overapplication_repaired file=",
        "detect_jb_cache_conflict_cancel_recoverable_with_context(",
        "jb_cache_conflict_cancel_auto_recovery_attempt file=",
        "agent_doc_commit_io::commit(file)",
        "recover_ipc_truncated_worktree_from_editor_buffer(file, rc)?",
        "detect_uncommitted_closeout_drift_with_context(",
        "preflight_blocked_uncommitted_closeout_drift file=",
        // `#hookcontractlost`: document-only drift must be recovered in place,
        // not reported with a remedy only the operator can run.
        "document_only_drift_is_commit_recoverable(file)",
        "preflight_document_only_drift_auto_commit_attempt file=",
        "preflight_document_only_drift_auto_commit_succeeded file=",
        "preflight_document_only_drift_auto_commit_failed file=",
    ] {
        assert!(
            preflight_runtime.contains(required),
            "agent-doc-preflight-runtime-io must own closeout-drift recovery marker: {required}"
        );
    }

    for forbidden in [
        "fn enforce_no_uncommitted_closeout_drift(",
        "detect_jb_cache_conflict_accept_duplicate_replay_with_context(",
        "detect_late_ipc_response_overapplication_with_context(",
        "detect_jb_cache_conflict_cancel_recoverable_with_context(",
        "detect_uncommitted_closeout_drift_with_context(",
        "jb_cache_conflict_cancel_auto_recovery_attempt file=",
        "late_ipc_response_overapplication_repaired file=",
        "jb_cache_conflict_accept_duplicate_replay_repaired file=",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not re-own closeout-drift recovery marker: {forbidden}"
        );
    }

    assert!(
        orchestration_preflight_run
            .contains("agent_doc_preflight_runtime_io::enforce_no_uncommitted_closeout_drift(")
            && orchestration_preflight_run
                .contains("&agent_doc_closeout_runtime_io::session_check_effects()"),
        "preflight run sequencing should call the focused closeout-drift runtime helper"
    );
}

#[test]
fn test_agent_doc_preflight_io_owns_sweep_owner_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let preflight_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_sweep =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/sweep.rs")).unwrap();
    let preflight_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();

    assert!(
        preflight_io_lib.contains("pub mod sweep;"),
        "agent-doc-preflight-io should expose the focused sweep owner module"
    );
    for required in [
        "pub struct SweepOwner",
        "fn actor_sweep_owner(",
        "agent_doc_controller_io::project_controller::authoritative_actor_binding(",
        "tmux_router::registry::canonical_registry_key_in(",
        "pub fn sweep_owner_for_doc(",
        "pub fn current_sweep_owner(",
        "pub fn log_and_skip_foreign_owned_sweep_if_needed(",
        "agent_doc_workflow::preflight_policy::should_skip_foreign_owned_sweep(",
        "foreign_owned_sweep_owner_warning file=",
        "foreign_owned_sweep_skip file=",
    ] {
        assert!(
            preflight_sweep.contains(required),
            "agent-doc-preflight-io sweep module must own sweep owner marker: {required}"
        );
    }
    for required_dep in [
        "agent-doc-controller-io =",
        "agent-doc-ops-log-io =",
        "agent-doc-workflow =",
        "tmux-router =",
    ] {
        assert!(
            preflight_manifest.contains(required_dep),
            "agent-doc-preflight-io should declare sweep owner dependency: {required_dep}"
        );
    }
    for forbidden in [
        "struct SweepOwner",
        "enum ActorSweepOwner",
        "fn actor_sweep_owner(",
        "fn registry_sweep_owner(",
        "fn sweep_owner_for_doc(",
        "fn current_sweep_owner(",
        "fn log_and_skip_foreign_owned_sweep_if_needed(",
        "foreign_owned_sweep_skip file=",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not re-own sweep owner marker: {forbidden}"
        );
    }
    assert!(
        orchestration_preflight_run.contains("agent_doc_preflight_io::{")
            && orchestration_preflight_run.contains("sweep::{")
            && orchestration_preflight_run.contains("current_sweep_owner(")
            && orchestration_preflight_run.contains("sweep_owner_for_doc(")
            && orchestration_preflight_run.contains("log_and_skip_foreign_owned_sweep_if_needed("),
        "preflight run sequencing should call focused sweep owner helpers"
    );
}

#[test]
fn test_agent_doc_preflight_io_owns_stale_warning_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let orchestration_build = String::new();
    let preflight_warnings =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    let preflight_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();
    let preflight_build =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/build.rs")).unwrap();

    assert!(
        preflight_io_lib.contains("pub mod warnings;")
            && preflight_manifest.contains("agent-doc-supervisor ="),
        "agent-doc-preflight-io must expose stale warning IO and own supervisor freshness classification dependency"
    );
    for forbidden in [
        "fn stale_install_warning(",
        "fn expected_plugin_version(",
        "fn plugin_version_is_older(",
        "fn stale_plugin_warnings(",
        "fn stale_plugin_warnings_from_snapshots(",
    ] {
        assert!(
            !orchestration_preflight.contains(forbidden),
            "orchestration preflight.rs must not own moved stale warning graph: {forbidden}"
        );
    }
    assert!(
        !orchestration_build.contains("AGENT_DOC_EXPECTED_JETBRAINS_PLUGIN_VERSION")
            && !orchestration_build.contains("AGENT_DOC_EXPECTED_VSCODE_PLUGIN_VERSION"),
        "orchestration build.rs must not own editor plugin version baking after warning extraction"
    );
    assert!(
        orchestration_preflight_run
            .contains("agent_doc_preflight_io::warnings::content_and_staleness_warnings("),
        "preflight command should reach stale warning adapters through focused warning aggregation"
    );
    for required in [
        "pub fn stale_install_warning(",
        "pub fn expected_plugin_version(",
        "pub fn plugin_version_is_older(",
        "pub fn stale_plugin_warnings(",
        "pub fn stale_plugin_warnings_from_registrations(",
        "stale_install_warning(&git_root)",
        "stale_plugin_warnings(file)",
        "agent_doc_fs::install_freshness::locate_agent_doc_source_repo",
        "agent_doc_supervisor::config::classify_stale_install_artifacts",
        "agent_doc_controller_io::project_controller::live_editor_registrations_for_file",
        "registration.editor_version",
        "option_env!(\"AGENT_DOC_EXPECTED_JETBRAINS_PLUGIN_VERSION\")",
    ] {
        assert!(
            preflight_warnings.contains(required),
            "agent-doc-preflight-io warnings module should own stale warning IO: {required}"
        );
    }
    for required in [
        "cargo:rustc-env=AGENT_DOC_EXPECTED_JETBRAINS_PLUGIN_VERSION",
        "cargo:rustc-env=AGENT_DOC_EXPECTED_VSCODE_PLUGIN_VERSION",
        "jetbrains/gradle.properties",
        "vscode/package.json",
    ] {
        assert!(
            preflight_build.contains(required),
            "agent-doc-preflight-io build.rs should own plugin version baking: {required}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_io_owns_warning_collection_graph() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_warnings =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    let preflight_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();

    assert!(
        preflight_manifest.contains("agent-doc-model-tier =")
            && preflight_manifest.contains("agent-doc-git-io =")
            && preflight_manifest.contains("indexmap ="),
        "agent-doc-preflight-io must own focused deps for warning collection"
    );
    for forbidden in [
        "agent_doc_model_tier::harness_mismatch_warning(",
        "agent_doc_controller_io::project_controller::stale_supervisor_warning_for_doc(file)",
        "agent_doc_model_tier::codex_network_access_non_codex_harness_warning(",
        "agent_doc_workflow::preflight_policy::component_attr_preflight_warning(",
        "agent_doc_workflow::preflight_policy::preset_item_id_collision_warning(",
        "agent_doc_git_io::dirs::resolve_to_git_root(file)",
        "stale_plugin_warnings(file)",
    ] {
        assert!(
            !orchestration_preflight_run.contains(forbidden),
            "orchestration preflight/run.rs must not own moved warning collection IO: {forbidden}"
        );
    }
    assert!(
        orchestration_preflight_run.contains("agent_doc_preflight_io::warnings::initial_warnings(")
            && orchestration_preflight_run
                .contains("agent_doc_preflight_io::warnings::content_and_staleness_warnings("),
        "preflight command should call focused warning collection adapters"
    );
    for required in [
        "pub fn initial_warnings(",
        "pub fn content_and_staleness_warnings(",
        "agent_doc_model_tier::harness_mismatch_warning",
        "agent_doc_controller_io::project_controller::recycle_stale_supervisor_for_turn_stage",
        "agent_doc_model_tier::codex_network_access_non_codex_harness_warning",
        "agent_doc_workflow::preflight_policy::post_exchange_comment_prompt_preset_warning",
        "agent_doc_workflow::preflight_policy::component_attr_preflight_warning",
        "agent_doc_workflow::preflight_policy::preset_item_id_collision_warning",
        "agent_doc_git_io::dirs::resolve_to_git_root",
        "warnings.extend(stale_plugin_warnings(file))",
    ] {
        assert!(
            preflight_warnings.contains(required),
            "agent-doc-preflight-io warnings module should own warning collection IO: {required}"
        );
    }
}

#[test]
fn test_agent_doc_preflight_io_owns_semantic_completion_warnings_without_merge_courtesy_turns() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let orchestration_preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let preflight_warnings =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    let preflight_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/Cargo.toml")).unwrap();

    assert!(
        preflight_manifest.contains("agent-doc-memory =")
            && preflight_manifest.contains("agent-doc-memory-io ="),
        "agent-doc-preflight-io must own focused deps for semantic completion warning collection"
    );
    for forbidden in [
        "agent_doc_memory_io::session::semantic_completion_matches(file, None, 5)",
        "agent_doc_memory::format_semantic_completion_warning",
        "code: \"semantic_completion_match\".to_string()",
        "code: \"semantic_completion_retrieval_unavailable\".to_string()",
        "document_cell_merge_ack_pending",
        "document_cell_merge_ack_warning",
    ] {
        assert!(
            !orchestration_preflight_run.contains(forbidden),
            "orchestration preflight/run.rs must not own moved semantic advisory warning graph: {forbidden}"
        );
    }
    assert!(
        orchestration_preflight_run
            .contains("agent_doc_preflight_io::warnings::semantic_completion_warnings(file)"),
        "preflight command should call the focused semantic completion warning adapter"
    );
    for required in [
        "pub fn semantic_completion_warnings(",
        "agent_doc_memory_io::session::semantic_completion_matches",
        "agent_doc_memory::format_semantic_completion_warning",
        "code: \"semantic_completion_match\".to_string()",
        "code: \"semantic_completion_retrieval_unavailable\".to_string()",
    ] {
        assert!(
            preflight_warnings.contains(required),
            "agent-doc-preflight-io warnings module should own semantic advisory warnings: {required}"
        );
    }
    assert!(
        !preflight_warnings.contains("document_cell_merge_ack")
            && !orchestration_preflight_run.contains("semantic_merge_conflict_advisories"),
        "semantic merge conflicts must remain cycle-local reactive state, not a next-turn warning"
    );
}

#[test]
fn test_agent_doc_queue_owns_continuation_guidance_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_continuation.rs")).unwrap();
    assert!(
        queue_policy.contains("pub const CONTINUATION_NO_STALL_GUIDANCE")
            && queue_policy.contains("pub const RECYCLE_YIELD_GUIDANCE")
            && queue_policy.contains("pub fn continuation_guidance")
            && queue_policy.contains("pub struct EffectiveContinuationOutput")
            && queue_policy.contains("pub fn effective_continuation_output"),
        "agent-doc-queue must own queue continuation guidance policy"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in [
        "pub const CONTINUATION_NO_STALL_GUIDANCE",
        "pub const RECYCLE_YIELD_GUIDANCE",
        "pub fn continuation_guidance",
        "pub fn effective_continuation_output",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration must not keep queue continuation guidance facades"
        );
    }

    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    assert!(
        preflight_run
            .contains("agent_doc_queue::queue_continuation::effective_continuation_output"),
        "preflight should delegate effective continuation output policy to agent-doc-queue"
    );
    for forbidden in [
        "queue_state.queue_continuation_required && !recycle_yield_pending",
        "let queue_continuation_guidance = if recycle_yield_pending",
        "RECYCLE_YIELD_GUIDANCE.to_string()",
    ] {
        assert!(
            !preflight_run.contains(forbidden),
            "preflight/run.rs must not re-own effective continuation output policy: {forbidden}"
        );
    }
    assert!(
        session_check.contains("agent_doc_queue::queue_continuation::continuation_guidance")
            || session_check
                .contains("agent_doc_queue::queue_continuation::CONTINUATION_NO_STALL_GUIDANCE"),
        "session_check should use agent-doc-queue guidance directly"
    );
}

#[test]
fn test_agent_doc_queue_owns_operator_clear_preemption_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_preemption =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_preemption.rs")).unwrap();
    for required in [
        "pub enum OperatorQueuePreemption",
        "pub enum BusyClearOutcome",
        "pub enum DeferredClearStep",
        "pub fn plan_operator_queue_preemption(",
        "pub fn plan_busy_clear(",
        "pub fn plan_deferred_clear_step(",
    ] {
        assert!(
            queue_preemption.contains(required),
            "agent-doc-queue must own operator clear preemption policy: {required}"
        );
    }

    let queue_io_marker =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/continuation_marker.rs"))
            .unwrap();
    for required in [
        "pub struct ContinuationMarker",
        "pub enum ContinuationMarkerScanAction",
        "pub fn write_continuation_marker(",
        "pub fn load_continuation_marker(",
        "pub fn scan_pending_marker_continuations_for_roots",
        "pub fn record_continuation_requested_head(",
    ] {
        assert!(
            queue_io_marker.contains(required),
            "agent-doc-queue-io must own queue continuation marker IO: {required}"
        );
    }
    for forbidden in [
        "pub struct DeferredOperatorClear",
        "DeferredOperatorClear {",
        "pub fn write_deferred_operator_clear(",
        "pub fn read_deferred_operator_clear(",
        "pub fn clear_deferred_operator_clear_marker(",
        "deferred_operator_clear_marker(",
        "deferred_operator_clear_marker_json(",
        "parse_deferred_operator_clear_marker_json(",
        ".agent-doc/deferred-clears",
    ] {
        assert!(
            !queue_io_marker.contains(forbidden),
            "queue continuation marker IO must not keep deferred-clear marker authority: {forbidden}"
        );
    }
    for forbidden in [
        "pub struct DeferredOperatorClear",
        "deferred_operator_clear_marker(",
        "deferred_operator_clear_marker_json(",
        "parse_deferred_operator_clear_marker_json(",
    ] {
        assert!(
            !queue_preemption.contains(forbidden),
            "agent-doc-queue must not own deferred-clear marker payload policy after projection migration: {forbidden}"
        );
    }
    let state_backbone =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/src/lib.rs")).unwrap();
    let controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    for required in [
        "QueueContextClearDeferred",
        "QueueContextClearPhase::Deferred",
        "QueueContextClearEvent::Deferred",
        "is_deferred_operator_clear",
        "pub fn queue_context_clear_deferred_for_file(",
        "pub fn queue_context_clear_deferred_operator_for_file(",
        "pub fn clear_queue_context_clear_deferred_for_file(",
        "\"queue_context_clear_deferred\"",
        "handle_queue_context_clear_deferred",
    ] {
        assert!(
            state_backbone.contains(required) || controller_rpc.contains(required),
            "deferred operator clears must use the context-clear projection: {required}"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let queue_io_host =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_continuation.rs"))
            .unwrap();
    for forbidden in [
        "pub struct ContinuationMarker",
        "pub struct DeferredOperatorClear",
        "deferred_operator_clear_marker(",
        "deferred_operator_clear_marker_json(",
        "parse_deferred_operator_clear_marker_json(",
        "std::fs::read_dir(",
        "serde_json::from_str::<ContinuationMarker>",
        "std::fs::remove_file(&path)",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "queue_continuation.rs must not re-own marker scan IO or deferred-clear payload policy: {forbidden}"
        );
    }
    assert!(
        queue_io_host.contains("crate::continuation_marker")
            && queue_io_host.contains("scan_pending_marker_continuations_for_roots")
            && queue_io_host.contains("ContinuationMarkerScanAction")
            && !queue_io_host.contains("use agent_doc_queue::queue_preemption::{"),
        "queue-io queue_continuation host should use focused marker storage/scanning, not queue-preemption directly"
    );
}

#[test]
fn test_agent_doc_element_done_owns_done_archive_content_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-element-done")),
        "agent-doc-element-done must stay a first-class workspace crate"
    );

    let done_model =
        fs::read_to_string(manifest_dir.join("agent-doc-element-done/src/lib.rs")).unwrap();
    for required in [
        "pub const DONE_SECTION_HEADING",
        "pub const EMPTY_DONE_COMPONENT",
        "pub fn insert_done_component_after_tracked_work(",
        "pub fn render_done_archive_entry(",
        "pub fn collect_done_item_own_ids(",
        "pub fn collect_done_component_own_ids(",
        "pub fn collect_done_document_own_ids(",
    ] {
        assert!(
            done_model.contains(required),
            "agent-doc-element-done must own done archive content policy: {required}"
        );
    }

    let orchestration_cargo = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    assert!(
        orchestration_cargo.contains("agent-doc-element-done"),
        "agent-doc-orchestration should depend on the focused done element crate directly"
    );
    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let done_archive =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/done_archive.rs"))
            .unwrap();
    for forbidden in [
        "fn insert_pending_done_component(",
        "fn insert_done_component_after_tracked_work(",
        "fn render_done_archive_entry(",
        "fn collect_done_item_own_ids(",
        "fn collect_done_component_own_ids(",
        "fn collect_done_document_own_ids(",
        "trimmed.starts_with(\"- \")",
        "trimmed.find(\"[#\")",
        "## Completed / Reaped\\n\\n<!-- agent:done -->",
    ] {
        assert!(
            !preflight.contains(forbidden),
            "preflight.rs must not re-own done archive content policy: {forbidden}"
        );
    }
    assert!(
        preflight.contains("agent_doc_element_backlog_io::done_archive::archive_pending_done")
            && !preflight.contains("agent_doc_element_done::render_done_archive_entry"),
        "preflight.rs should call the focused done-archive IO host instead of owning archive rendering"
    );
    assert!(
        done_archive.contains("agent_doc_element_done::insert_done_component_after_tracked_work")
            && done_archive.contains("agent_doc_element_done::render_done_archive_entry"),
        "done_archive IO should call archive insertion/rendering policy through agent-doc-element-done directly"
    );
}

#[test]
fn test_agent_doc_element_review_owns_review_projection_and_ungate_planning() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let review_model =
        fs::read_to_string(manifest_dir.join("agent-doc-element-review/src/lib.rs")).unwrap();
    for required in [
        "pub struct ReviewItemView",
        "pub struct ReviewListFilter",
        "pub fn find_review_component_in_content",
        "pub fn ensure_review_component_in_document",
        "pub struct ReviewItemRemovalPlan",
        "pub fn remove_review_items_from_document",
        "pub fn resolve_review_items_in_document",
        "pub fn review_item_views_from_content",
        "pub struct UngateTasksReport",
        "pub struct UngateTasksPlan",
        "pub fn plan_ungate_tasks_for_review",
        "pub fn collect_gated_review_ids",
    ] {
        assert!(
            review_model.contains(required),
            "agent-doc-element-review must own review projection and planning API"
        );
    }

    let backlog_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/lib.rs")).unwrap();
    let backlog_cmd =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/backlog_cmd.rs"))
            .unwrap();
    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/pending_cmd.rs")
            .exists(),
        "orchestration must not keep a pending_cmd compatibility module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/backlog_cmd.rs")
            .exists()
            && backlog_io_lib.contains("pub mod backlog_cmd;")
            && !orchestration_lib.contains("pub mod backlog_cmd;")
            && !orchestration_lib.contains("pub mod pending_cmd")
            && !orchestration_lib.contains("pub use backlog_cmd as pending_cmd"),
        "tracked-work command IO should live in agent-doc-element-backlog-io without orchestration backlog/pending facades"
    );
    for forbidden in [
        "pub struct ReviewItemView",
        "pub struct ReviewListFilter",
        "pub struct UngateTasksReport",
        "fn find_review_component_in_content",
        "fn insert_empty_review_after_backlog",
        "fn ensure_review_component(",
        "fn ungate_task_text",
        "fn extract_review_tags",
        "fn extract_review_next",
        "fn collect_agent_review_gated_ids",
        "fn collect_gated_review_ids",
        "backlog::op_take_all_by_id(existing, id)",
        "item.state = backlog::PendingState::Done",
    ] {
        assert!(
            !backlog_cmd.contains(forbidden),
            "backlog_cmd must stay a file-IO adapter, not a review projection/planning facade"
        );
    }
    assert!(
        backlog_cmd.contains("find_review_component_in_content")
            && backlog_cmd.contains("ensure_review_component_in_document"),
        "backlog_cmd should call review component helpers from agent-doc-element-review"
    );
    assert!(
        backlog_cmd.contains("remove_review_items_from_document")
            && backlog_cmd.contains("resolve_review_items_in_document"),
        "backlog_cmd should delegate review removal/resolve planning to agent-doc-element-review directly"
    );
    assert!(
        backlog_cmd.contains("agent_doc_element_review::review_item_views_from_content"),
        "backlog_cmd should delegate review projection to agent-doc-element-review directly"
    );
    assert!(
        backlog_cmd.contains("agent_doc_element_review::plan_ungate_tasks_for_review"),
        "backlog_cmd should delegate review ungate planning to agent-doc-element-review directly"
    );
    assert!(
        !preflight.contains("fn collect_agent_review_gated_ids")
            && !preflight.contains("fn collect_gated_review_ids"),
        "preflight.rs must not re-own gated review id extraction"
    );
    assert!(
        preflight_maintenance.contains("agent_doc_element_review::collect_gated_review_ids"),
        "preflight maintenance should call gated review id extraction through agent-doc-element-review directly"
    );

    let cli = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        cli.contains("agent_doc_element_review::ReviewListFilter"),
        "CLI should construct review filters from the focused review crate"
    );
}

#[test]
fn test_agent_doc_element_backlog_runtime_io_owns_runtime_backlog_command_effects() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let runtime_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-runtime-io/Cargo.toml"))
            .unwrap();
    let runtime_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-runtime-io/src/lib.rs"))
            .unwrap();
    let backlog_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/Cargo.toml")).unwrap();
    let backlog_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/lib.rs")).unwrap();
    let backlog_cmd =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/backlog_cmd.rs"))
            .unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_diagnostics =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/diagnostics.rs")).unwrap();

    for required in [
        "\"agent-doc-element-backlog-runtime-io\"",
        "agent-doc-element-backlog-runtime-io = { path = \"agent-doc-element-backlog-runtime-io\"",
    ] {
        assert!(
            workspace_manifest.contains(required),
            "workspace must expose backlog runtime IO as a first-class focused crate: {required}"
        );
    }
    for required in [
        "agent-doc-document-realtime-io =",
        "agent-doc-element-backlog-io =",
        "agent-doc-write-converge-io =",
    ] {
        assert!(
            runtime_manifest.contains(required),
            "agent-doc-element-backlog-runtime-io must own runtime backlog write dependencies: {required}"
        );
    }
    for required in [
        "pub struct RuntimeBacklogCommandEffects",
        "pub static RUNTIME_BACKLOG_COMMAND_EFFECTS",
        "impl agent_doc_element_backlog_io::BacklogCommandEffects for RuntimeBacklogCommandEffects",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(file, source)",
        "agent_doc_write_converge_io::converge_or_disk_write(",
        "agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS",
        "agent_doc_document_realtime_io::record_document_write_provenance",
    ] {
        assert!(
            runtime_lib.contains(required),
            "agent-doc-element-backlog-runtime-io must own runtime backlog command effects: {required}"
        );
    }
    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "fn force_disk_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "fn read_command_document(file: &Path, source: &str) -> Result<String>",
        "crate::current_document_content(file, source)",
        "crate::force_disk_document_content(file, source)",
    ] {
        assert!(
            backlog_io_lib.contains(required) || backlog_cmd.contains(required),
            "agent-doc-element-backlog-io must route command document reads through injected authority effects: {required}"
        );
    }
    for forbidden in [
        "agent-doc-document-realtime-io =",
        "agent-doc-write-converge-io =",
        "RUNTIME_BACKLOG_COMMAND_EFFECTS",
    ] {
        assert!(
            !backlog_io_manifest.contains(forbidden) && !backlog_io_lib.contains(forbidden),
            "agent-doc-element-backlog-io must stay below runtime document authority dependencies: {forbidden}"
        );
    }
    assert!(
        !backlog_cmd.contains("std::fs::read_to_string(file)"),
        "backlog command document reads must go through the injected authority effect"
    );
    for forbidden in ["CliBacklogCommandEffects", "CLI_BACKLOG_COMMAND_EFFECTS"] {
        assert!(
            !backlog_cmd.contains(forbidden) && !main_source.contains(forbidden),
            "backlog command/runtime wiring must not bypass the realtime read authority boundary: {forbidden}"
        );
    }
    for forbidden in [
        "pub(crate) struct BacklogCommandEffects",
        "pub(crate) static BACKLOG_COMMAND_EFFECTS",
        "impl agent_doc_element_backlog_io::BacklogCommandEffects for BacklogCommandEffects",
        "crate::BACKLOG_COMMAND_EFFECTS",
    ] {
        assert!(
            !orchestration_lib.contains(forbidden)
                && !write_source.contains(forbidden)
                && !route_source.contains(forbidden),
            "orchestration must not own or inject backlog command runtime effects after extraction: {forbidden}"
        );
    }
    assert!(
        write_source.contains("agent_doc_element_backlog_runtime_io::RUNTIME_BACKLOG_COMMAND_EFFECTS")
            && route_diagnostics.contains("agent_doc_element_backlog_io::with_backlog_command_effects")
            && route_diagnostics
                .contains("agent_doc_element_backlog_runtime_io::RUNTIME_BACKLOG_COMMAND_EFFECTS")
            && route_diagnostics.contains("pub fn add_route_dispatch_bug_backlog_items(")
            && route_source.contains(
                "file_route_dispatch_bug_report_with_runtime_effects as file_route_dispatch_bug_report"
            ),
        "write and route should consume the focused backlog runtime effect provider directly"
    );
}

#[test]
fn test_agent_doc_element_backlog_owns_tracked_line_remove_and_reap_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let backlog_model =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/backlog.rs")).unwrap();
    for required in [
        "pub enum TrackedWorkList",
        "pub fn find_tracked_work_component_in_content",
        "pub fn find_done_archive_component_in_content",
        "pub fn find_open_tracked_work_component_in_content",
        "pub fn open_tracked_work_component_name_in_content",
        "pub fn content_has_resolved_tracked_work_id",
        "pub struct TrackedComponentItemDrop",
        "pub fn tracked_component_item_counts",
        "pub fn dropped_tracked_component_items",
        "pub fn component_matches_tracked_surface",
        "pub fn maintenance_surface_label",
        "pub fn should_reap_already_done_mirrors",
        "pub fn should_reap_ops_proof_completions",
        "pub fn tracked_body_for_reorder",
        "pub fn review_counts",
        "pub fn completed_items",
        "pub fn completed_tracked_items_in_components",
        "pub fn completed_tracked_items_in_content",
        "pub fn tracked_item_ref",
        "pub fn tracked_item_refs",
        "pub fn ensure_no_completed_tracked_items",
        "pub fn trim_tracked_parent_prefix",
        "pub fn op_remove_matching_tracked_line",
        "pub fn reap_with_items",
        "pub struct PendingAddBatchOutcome",
        "pub fn op_prepend_many_with_outcomes",
    ] {
        assert!(
            backlog_model.contains(required),
            "agent-doc-element-backlog must own tracked line remove/prune policy"
        );
    }
    for forbidden in [
        "pub fn line_is_legacy_done_item",
        "pub fn op_prune_legacy_done_lines",
    ] {
        assert!(
            !backlog_model.contains(forbidden),
            "agent-doc-element-backlog must not keep deprecated tracked-line prune names: {forbidden}"
        );
    }

    let backlog_cmd =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/backlog_cmd.rs"))
            .unwrap();
    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_run =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    for forbidden in [
        "pub pending_reordered:",
        "pub pending_gated_count:",
        "let pending_reordered =",
        "let pending_gated_count =",
    ] {
        assert!(
            !preflight.contains(forbidden) && !preflight_run.contains(forbidden),
            "preflight must not preserve deprecated pending_* JSON aliases: {forbidden}"
        );
    }
    for forbidden in [
        "enum TrackedWorkList",
        "enum TrackedList",
        "is_icebox_component",
        "is_tracked_work_component",
        "is_backlog_done_component",
        "fn trim_tracked_parent_prefix",
        "fn line_is_legacy_done_item",
        "op_prune_legacy_done_lines",
        "let lines: Vec<&str> = existing.lines().collect();",
        ".filter(|line| !line_is_legacy_done_item(line))",
        "for item in items.iter().rev()",
        "ids.reverse()",
    ] {
        assert!(
            !backlog_cmd.contains(forbidden),
            "backlog_cmd must stay a file-IO adapter, not re-own tracked-work batch/remove/prune policy"
        );
    }
    assert!(
        backlog_cmd.contains("backlog::find_tracked_work_component_in_content")
            && backlog_cmd.contains("backlog::find_open_tracked_work_component_in_content")
            && backlog_cmd.contains("backlog::open_tracked_work_component_name_in_content")
            && backlog_cmd.contains("backlog::content_has_resolved_tracked_work_id")
            && backlog_cmd.contains("backlog::TrackedWorkList"),
        "backlog_cmd should call tracked-work component lookup helpers from agent-doc-element-backlog"
    );
    assert!(
        backlog_cmd.contains("backlog::op_remove_matching_tracked_line")
            && backlog_cmd.contains("backlog::reap_with_items"),
        "backlog_cmd should call tracked line remove/reap policy from agent-doc-element-backlog"
    );
    assert!(
        backlog_cmd.contains("backlog::op_prepend_many_with_outcomes"),
        "backlog_cmd should call tracked-work batch add policy from agent-doc-element-backlog"
    );

    let compact = fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn non_exchange_list_item_counts(",
        "fn tracked_component_item_counts(",
        "fn dropped_tracked_component_items(",
        "agent_doc_element_backlog::backlog::parse_items",
    ] {
        assert!(
            !compact.contains(forbidden),
            "compact must stay an adapter, not re-own tracked component preservation policy: {forbidden}"
        );
    }
    assert!(
        compact.contains("agent_doc_element_backlog::backlog::dropped_tracked_component_items"),
        "compact should call tracked component preservation policy from agent-doc-element-backlog"
    );

    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn component_matches_tracked_surface",
        "fn component_matches_tracked_surface",
        "pub(crate) fn maintenance_surface_label",
        "pub(crate) fn should_reap_already_done_mirrors",
        "pub(crate) fn should_reap_ops_proof_completions",
        "pub(crate) fn tracked_body_for_reorder",
        "pub(crate) fn review_counts",
        "pub(crate) fn ensure_no_completed_tracked_items",
        "pub(crate) fn completed_pending_items",
        "fn completed_pending_items",
    ] {
        assert!(
            !preflight_maintenance.contains(forbidden),
            "preflight maintenance must stay an adapter, not re-own tracked-work completion projection policy: {forbidden}"
        );
    }
    assert!(
        preflight_maintenance.contains("component_matches_tracked_surface")
            && preflight_maintenance.contains("maintenance_surface_label")
            && preflight_maintenance.contains("tracked_body_for_reorder")
            && preflight_maintenance.contains("review_counts")
            && preflight_maintenance.contains("ensure_no_completed_tracked_items")
            && preflight_maintenance.contains("backlog::completed_items"),
        "preflight maintenance should import tracked-surface/completion policy from agent-doc-element-backlog"
    );

    let response_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/response_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub(crate) fn completed_pending_items",
        "fn completed_pending_items",
        "parse_items(component.content(&content))",
        "PendingItem::is_done",
    ] {
        assert!(
            !response_guards.contains(forbidden),
            "response_guards must not re-own completed tracked-item projection policy: {forbidden}"
        );
    }
    assert!(
        response_guards.contains("backlog::completed_tracked_items_in_components")
            && response_guards.contains("backlog::tracked_item_refs"),
        "response_guards should call completed tracked-item projection policy from agent-doc-element-backlog"
    );
}

#[test]
fn test_agent_doc_element_backlog_uses_current_hash_api_name() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let backlog_model =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/backlog.rs")).unwrap();
    assert!(
        !backlog_model.contains("pub fn generate_hash("),
        "agent-doc-element-backlog must not preserve deprecated width-4 hash wrapper"
    );
    assert!(
        backlog_model.contains("pub fn generate_hash_n("),
        "agent-doc-element-backlog should expose the width-aware hash API directly"
    );
}

#[test]
fn test_agent_doc_element_backlog_owns_malformed_tracked_item_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let backlog_model =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/backlog.rs")).unwrap();
    let guard_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/guard_policy.rs"))
            .unwrap();
    for required in [
        "pub struct MalformedPendingItemLine",
        "pub struct MalformedTrackedItemRef",
        "pub fn detect_malformed_item_lines",
        "pub fn malformed_tracked_item_refs_in_components",
        "pub fn malformed_tracked_item_refs",
        "pub fn malformed_tracked_item_interruption_message",
        "pub fn format_shadow_refs",
        "pub fn format_dropped_refs",
    ] {
        assert!(
            backlog_model.contains(required),
            "agent-doc-element-backlog must own malformed tracked checklist policy: {required}"
        );
    }
    for required in [
        "pub enum BacklogGuardOutcome",
        "pub fn shadow_backlog_guard",
        "pub fn malformed_tracked_item_guard",
        "pub fn dropped_from_history_guard",
    ] {
        assert!(
            guard_policy.contains(required),
            "agent-doc-element-backlog guard policy must own session-check backlog guard projection: {required}"
        );
    }

    let backlog_guards =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/backlog_guards.rs"))
            .unwrap();
    for forbidden in [
        "pub fn malformed_tracked_item_refs",
        "pub(crate) fn malformed_tracked_item_refs_in",
        "pub fn malformed_tracked_item_message",
        "detect_malformed_item_lines(",
        "detect_shadow_open_items(",
        "detect_dropped_from_history_with_extra_current_ids(",
        "malformed_tracked_item_refs_in_components(",
        "malformed_tracked_item_interruption_message(",
        "agent_doc_fs::document_state_hash(",
        "agent_doc_fs::find_project_root(",
        ".agent-doc/baselines",
    ] {
        assert!(
            !backlog_guards.contains(forbidden),
            "session_check backlog guards must not re-own malformed tracked checklist policy: {forbidden}"
        );
    }
    assert!(
        backlog_guards.contains("agent_doc_element_backlog::guard_policy::{")
            && backlog_guards.contains("malformed_tracked_item_guard")
            && backlog_guards.contains("shadow_backlog_guard")
            && backlog_guards.contains("dropped_from_history_guard")
            && backlog_guards.contains("agent_doc_snapshot_io::load_document_baseline("),
        "session_check backlog guards should call focused backlog policy and baseline path helpers directly"
    );

    let pending_checks = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/write_pending_checks.rs"),
    )
    .unwrap();
    assert!(
        !pending_checks.contains("crate::session_check::malformed_tracked_item"),
        "write pending checks must not route malformed tracked checklist policy through session_check"
    );
    assert!(
        pending_checks.contains("agent_doc_element_backlog::backlog::malformed_tracked_item_refs")
            && pending_checks.contains(
                "agent_doc_element_backlog::backlog::malformed_tracked_item_interruption_message"
            ),
        "write pending checks should call malformed tracked checklist policy directly"
    );
}

#[test]
fn test_extracted_pure_layers_keep_focused_owners() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));

    let git = fs::read_to_string(manifest_dir.join("agent-doc-git/src/lib.rs")).unwrap();
    for required in [
        "pub fn short_oid(",
        "pub fn parent_pointer_recovery_hint(",
        "pub fn parent_submodule_pointer_message(",
    ] {
        assert!(
            git.contains(required),
            "agent-doc-git must own parent submodule pointer messaging policy: {required}"
        );
    }
    let detect =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/detect.rs")).unwrap();
    let session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    for forbidden in [
        "fn short_oid(",
        "fn parent_pointer_recovery_hint(",
        "fn parent_submodule_pointer_message(",
    ] {
        assert!(
            !detect.contains(forbidden),
            "session-check detect IO must not keep git messaging shims: {forbidden}"
        );
    }
    assert!(
        detect.contains("agent_doc_git::parent_submodule_pointer_guard_message(")
            && session_check.contains("agent_doc_git::parent_submodule_pointer_message("),
        "session-check detect IO and command IO should call agent-doc-git messaging helpers directly"
    );

    let compact_archive =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/compact_archive.rs")).unwrap();
    for required in [
        "pub struct CompactArchiveMetadata",
        "pub fn compact_archive_session(",
        "pub fn build_component_archive_content(",
        "pub fn build_inline_exchange_archive_content(",
        "pub fn build_exchange_compact_summary(",
        "pub fn compact_archive_pointers(",
        "pub fn format_compact_timestamp_from_unix_secs(",
    ] {
        assert!(
            compact_archive.contains(required),
            "agent-doc-document must own compact archive rendering policy: {required}"
        );
    }
    let compact = fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn append_compact_summary_section(",
        "fn format_compact_timestamp_from_unix_secs(",
        "fn is_leap_year(",
    ] {
        assert!(
            !compact.contains(forbidden),
            "compact.rs must not re-own pure compact archive rendering policy: {forbidden}"
        );
    }
    assert!(
        compact.contains("agent_doc_document::compact_archive::{")
            && compact.contains("build_component_archive_content(")
            && compact.contains("build_inline_exchange_archive_content(")
            && compact.contains("build_exchange_compact_summary("),
        "compact.rs should call compact archive renderers from agent-doc-document directly"
    );

    let workflow_capture =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/pending_capture.rs")).unwrap();
    for required in [
        "pub struct InventoryShortfall",
        "pub fn promised_backlog_item_ids_from_response",
        "pub fn promised_backlog_item_inventory_shortfall",
        "pub fn promised_plan_reference_candidate_lines",
        "pub fn promised_plan_reference_shortfall",
        "pub fn missing_promised_backlog_item_ids",
    ] {
        assert!(
            workflow_capture.contains(required),
            "agent-doc-workflow must own pending-capture pure policy: {required}"
        );
    }
    let pending_checks = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/write_pending_checks.rs"),
    )
    .unwrap();
    for forbidden in [
        "backlog::parse_items(response_text)",
        "fn inventory_shortfall(",
        ".lines()\n        .map(str::trim)",
    ] {
        assert!(
            !pending_checks.contains(forbidden),
            "write pending checks must not re-own pure pending-capture policy: {forbidden}"
        );
    }
    assert!(
        pending_checks.contains("use crate::{")
            && pending_checks.contains("promised_backlog_item_inventory_shortfall")
            && pending_checks.contains("unresolved_promised_backlog_item_ids")
            && !pending_checks.contains("use agent_doc_workflow::pending_capture;"),
        "write pending checks should call focused session-check IO pending-capture adapters directly"
    );
    let session_check_pending_capture =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/pending_capture.rs"))
            .unwrap();
    assert!(
        session_check_pending_capture.contains(
            "agent_doc_workflow::pending_capture::promised_backlog_item_ids_from_response"
        ) && session_check_pending_capture
            .contains("agent_doc_workflow::pending_capture::missing_promised_backlog_item_ids"),
        "session-check IO pending-capture adapters should compose focused workflow policy directly"
    );

    let claim_binding =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/claim_binding.rs")).unwrap();
    for required in [
        "pub struct ClaimRegistryEntry",
        "pub fn registry_entry_matches_claimed_document",
        "pub fn claimed_session_label",
        "pub fn find_alive_window_in_registry",
    ] {
        assert!(
            claim_binding.contains(required),
            "agent-doc-supervisor must own pure claim binding policy: {required}"
        );
    }
    let claim = fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    let git_io_dirs =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/dirs.rs")).unwrap();
    assert!(
        git_io_dirs.contains("pub fn resolve_canonical_or_absolute_file_path("),
        "agent-doc-git-io should own claim path canonicalization helper"
    );
    for forbidden in [
        "fn registry_entry_matches_claimed_document(",
        "fn claimed_session_label(",
        "fn find_alive_window_in_registry(",
        "fn normalize_claim_path(",
    ] {
        assert!(
            !claim.contains(forbidden),
            "claim.rs must not keep claim-binding policy shims: {forbidden}"
        );
    }
    assert!(
        claim.contains("agent_doc_supervisor::claim_binding::{")
            && claim.contains("ClaimRegistryEntry")
            && claim.contains("registry_entry_matches_claimed_document(")
            && claim.contains("agent_doc_git_io::dirs::resolve_canonical_or_absolute_file_path"),
        "claim.rs should call focused claim-binding policy directly"
    );
}

#[test]
fn test_agent_doc_workflow_owns_capture_repairability_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workflow_capture =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/capture.rs")).unwrap();
    assert!(
        workflow_capture.contains("pub const fn capture_state_is_repairable("),
        "agent-doc-workflow must own pure capture repairability policy"
    );
    for required in [
        "pub enum StaleCaptureRetirementDecision",
        "pub struct StaleCaptureRetirementEvidence",
        "pub const fn decide_stale_capture_retirement(",
        "pub enum RepairTemplateChangeKind",
        "pub struct RepairTemplateChanges",
        "pub const fn should_persist(",
        "pub fn changed_kinds(",
    ] {
        assert!(
            workflow_capture.contains(required),
            "agent-doc-workflow must own pure capture/repair-template policy: {required}"
        );
    }

    let repair =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/tests/repair.rs"))
            .unwrap();
    let repair_io =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn capture_is_repairable(",
        "fn retire_wedged_write_applied_capture_if_drifted(",
        "fn retire_superseded_captured_only_orphan_if_drifted(",
        "fn retire_stale_capture_if_drifted(",
        "fn decide_stale_capture_retirement(",
        "capture_state_is_repairable(",
        "agent_doc_capture_io::replay_baseline_drifted(",
        "if duplicate_opener_changed",
        "if duplicate_close_changed",
        "if duplicate_scaffold_changed",
        "if tail_changed",
        "if boundary_changed",
        "if order_changed",
        "if prompt_changed",
    ] {
        assert!(
            !repair.contains(forbidden),
            "repair.rs must not re-own capture lifecycle or repair-template aggregation policy: {forbidden}"
        );
    }
    assert!(
        repair_io.contains("capture_state_is_repairable(")
            && !repair.contains("RepairTemplateChanges {")
            && !repair.contains("template_changes.should_persist()")
            && !repair.contains("template_changes.changed_kinds()"),
        "agent-doc-repair-io should own capture repairability while repair.rs no longer owns repair-template aggregation policy"
    );
    assert!(
        repair_io.contains("agent_doc_workflow::capture::RepairTemplateChanges {")
            && repair_io.contains("template_changes.should_persist()")
            && repair_io.contains("template_changes.changed_kinds()"),
        "agent-doc-repair-io should own the file-backed repair-template aggregation policy"
    );
    assert!(
        repair_io.contains("agent_doc_workflow::capture::decide_stale_capture_retirement(")
            && repair_io.contains("agent_doc_workflow::capture::StaleCaptureRetirementEvidence")
            && repair_io
                .contains("agent_doc_capture_io::replay_baseline_drifted_with_current_content(")
            && repair_io.contains("agent_doc_capture_io::validate_replay_with_current_content("),
        "agent-doc-repair-io should gather stale-capture evidence and call workflow capture policy directly from resolved current content"
    );
}

#[test]
fn test_agent_doc_element_backlog_owns_ops_proof_completion_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let ops_proof =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/ops_proof.rs"))
            .unwrap();
    for required in [
        "pub struct OpsProofCompletion",
        "pub fn surface_pending_ids",
        "pub fn ops_proof_completion_candidates",
        "pub fn classify_ops_proof_completion",
        "pub fn marker_is_leading_status",
        "pub fn is_live_verify_gate",
        "pub fn contains_successful_ci_proof",
        "pub fn contains_commit_hash",
    ] {
        assert!(
            ops_proof.contains(required),
            "agent-doc-element-backlog must own ops-proof tracked-work completion policy: {required}"
        );
    }

    let preflight_maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub(crate) struct OpsProofCompletion",
        "struct OpsProofCompletion",
        "pub(crate) fn surface_pending_ids",
        "pub(crate) fn ops_proof_completion_candidates",
        "pub(crate) fn classify_ops_proof_completion",
        "pub(crate) fn marker_is_leading_status",
        "pub(crate) fn is_live_verify_gate",
        "pub(crate) fn contains_successful_ci_proof",
        "pub(crate) fn contains_commit_hash",
        "fn component_matches_tracked_surface",
    ] {
        assert!(
            !preflight_maintenance.contains(forbidden),
            "preflight maintenance must not re-own ops-proof tracked-work completion policy: {forbidden}"
        );
    }
    assert!(
        preflight_maintenance.contains("agent_doc_element_backlog::ops_proof::surface_pending_ids")
            && preflight_maintenance
                .contains("agent_doc_element_backlog::ops_proof::ops_proof_completion_candidates"),
        "preflight maintenance should call ops-proof policy from agent-doc-element-backlog directly"
    );
    assert!(
        ops_proof.contains("backlog::component_matches_tracked_surface")
            && !ops_proof.contains("fn component_matches_tracked_surface"),
        "ops-proof should use tracked-surface policy from backlog.rs instead of a private duplicate"
    );
}

#[test]
fn test_focus_no_stash_promote_compatibility_shim_is_removed() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    for relative in [
        "src/main.rs",
        "agent-doc-focus-io/src/lib.rs",
        "specs/07-session-tmux-commands.md",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("no-stash-promote")
                && !source.contains("no_stash_promote")
                && !source.contains("run_no_promote"),
            "{relative} must not keep the removed focus no-promotion compatibility shim"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_focus_pane_decision() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    assert!(
        tmux_source.contains("pub enum FocusPaneDecision")
            && tmux_source.contains("pub fn decide_focus_pane("),
        "agent-doc-tmux must own pure focus pane selection"
    );

    let focus_source =
        fs::read_to_string(manifest_dir.join("agent-doc-focus-io/src/lib.rs")).unwrap();
    for forbidden_snippet in ["pub enum FocusPaneDecision", "pub fn decide_focus_pane("] {
        assert!(
            !focus_source.contains(forbidden_snippet),
            "agent-doc-focus-io must call agent_doc_tmux directly instead of re-owning focus pane policy: {forbidden_snippet}"
        );
    }
    assert!(
        focus_source.contains("use agent_doc_tmux::{FocusPaneDecision, decide_focus_pane};"),
        "agent-doc-focus-io should import the focused tmux pane decision API directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/focus.rs")
            .exists(),
        "orchestration must not keep a focus command facade module"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod focus;"),
        "orchestration must not expose a focus command facade"
    );
    let focus_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-focus-io/Cargo.toml")).unwrap();
    let focus_crate: toml::Value = toml::from_str(&focus_manifest).unwrap();
    let focus_dependencies = focus_crate["dependencies"].as_table().unwrap();
    assert!(
        !focus_dependencies.contains_key("agent-doc-orchestration"),
        "agent-doc-focus-io must stay free of orchestration dependencies"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux focus policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_editor_column_split_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    assert!(
        tmux_source.contains("pub fn is_first_column("),
        "agent-doc-tmux should own editor column split policy"
    );
    for required in [
        "pub fn auto_start_candidate_files(",
        "pub fn projected_sync_pane_count(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux should own editor sync column-list policy: {required}"
        );
    }

    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_pane_resolution_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/pane_resolution.rs")).unwrap();
    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    let pane_repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/pane_repair.rs")).unwrap();
    for forbidden in ["pub fn is_first_column(", "fn is_first_column("] {
        assert!(
            !route_source.contains(forbidden),
            "route.rs must not re-own editor column split policy: {forbidden}"
        );
    }
    for forbidden in [
        "pub(crate) fn auto_start_candidate_files(",
        "fn auto_start_candidate_files(",
        "pub(crate) fn projected_sync_pane_count(",
        "fn projected_sync_pane_count(",
        "pub(crate) use agent_doc_tmux::{auto_start_candidate_files",
    ] {
        assert!(
            !sync_source.contains(forbidden) && !pane_repair_source.contains(forbidden),
            "sync modules must not re-own or facade editor sync column-list policy: {forbidden}"
        );
    }
    assert!(
        route_pane_resolution_source.contains("use agent_doc_tmux::is_first_column;"),
        "route pane-resolution IO should import editor column split policy from agent-doc-tmux directly"
    );
    assert!(
        sync_source.contains("auto_start_candidate_files")
            && sync_source.contains("projected_sync_pane_count")
            && sync_source.contains("use agent_doc_tmux::{"),
        "sync.rs should import editor sync column-list policy from agent-doc-tmux directly"
    );
}

#[test]
fn test_cross_root_sync_uses_owning_controller_effect_and_ephemeral_router_binding() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let sync_lib = fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/lib.rs")).unwrap();
    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let router_source = fs::read_to_string(
        manifest_dir
            .parent()
            .unwrap()
            .join("tmux-router/src/sync.rs"),
    )
    .unwrap();

    for required in [
        "fn ensure_cross_root_document_pane(",
        "focus_document_pane(project_root, file)?",
        "cross_root_controller_pane_resolved",
        "pre_resolved_panes: Some(&pre_resolved_panes)",
    ] {
        assert!(
            sync_lib.contains(required)
                || sync_source.contains(required)
                || main_source.contains(required),
            "cross-root sync must delegate to the owning controller and carry only an ephemeral pane binding: {required}"
        );
    }
    assert!(
        router_source.contains("pub pre_resolved_panes:")
            && router_source.contains(".and_then(|panes| panes.get(*file))"),
        "tmux-router must prefer caller-proven cross-root pane bindings over spare geometry"
    );
    assert!(
        !sync_source.contains("cross_root_autostart_skipped"),
        "cross-root sync must not report success after skipping owning-controller provisioning"
    );
}

#[test]
fn test_agent_doc_tmux_owns_destructive_repair_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    for required in [
        "pub fn repair_layout_skips_rescue_phase(",
        "pub const DESTRUCTIVE_REPAIR_MIN_INTERVAL_MS",
        "pub fn destructive_repair_throttled(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own destructive repair pure policy: {required}"
        );
    }

    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    for forbidden in [
        "fn repair_layout_skips_rescue_phase(",
        "const DESTRUCTIVE_REPAIR_MIN_INTERVAL_MS",
        "fn destructive_repair_throttled(",
        "pub fn repair_layout_skips_rescue_phase(",
        "pub const DESTRUCTIVE_REPAIR_MIN_INTERVAL_MS",
        "pub fn destructive_repair_throttled(",
    ] {
        assert!(
            !sync_source.contains(forbidden),
            "sync.rs must call agent_doc_tmux directly instead of re-owning destructive repair policy: {forbidden}"
        );
    }
    assert!(
        sync_source.contains("agent_doc_tmux::repair_layout_skips_rescue_phase(")
            && sync_source.contains("agent_doc_tmux::destructive_repair_throttled(")
            && sync_source.contains("agent_doc_tmux::DESTRUCTIVE_REPAIR_MIN_INTERVAL_MS"),
        "sync.rs should import destructive repair policy from agent-doc-tmux directly"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux destructive repair policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_missing_pane_repair_message_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    for required in [
        "pub fn format_missing_pane_manual_repair_reason(",
        "pub fn format_missing_pane_closeout_block_reason(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own missing-pane repair message policy: {required}"
        );
    }

    let pane_repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/pane_repair.rs")).unwrap();
    for forbidden in [
        "fn missing_pane_manual_repair_reason(",
        "fn missing_pane_closeout_block_reason(",
        "\"stale preflight state is still open\"",
        "\"a captured response still needs explicit closeout recovery\"",
        "\"the write reached disk but the commit boundary is still open\"",
    ] {
        assert!(
            !pane_repair_source.contains(forbidden),
            "sync pane repair must not re-own missing-pane repair message policy: {forbidden}"
        );
    }
    assert!(
        pane_repair_source.contains("agent_doc_tmux::format_missing_pane_manual_repair_reason")
            && pane_repair_source
                .contains("agent_doc_tmux::format_missing_pane_closeout_block_reason"),
        "sync pane repair should call focused tmux missing-pane repair message helpers directly"
    );
}

#[test]
fn test_agent_doc_tmux_owns_stash_prune_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    for required in [
        "pub enum PruneCleanupMode",
        "pub struct StashTtlCandidate",
        "pub fn stash_ttl_prune_candidate(",
        "pub fn stash_ttl_prune_targets(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own stash prune policy: {required}"
        );
    }

    let resync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/resync.rs")).unwrap();
    for forbidden in [
        "pub enum PruneCleanupMode",
        "pub struct StashTtlCandidate",
        "pub fn stash_ttl_prune_candidate(",
        "pub fn stash_ttl_prune_targets(",
        "pub use agent_doc_tmux",
        "pub(crate) use agent_doc_tmux",
    ] {
        assert!(
            !resync_source.contains(forbidden),
            "resync.rs must keep prune effects only, not re-own or facade stash prune policy: {forbidden}"
        );
    }
    assert!(
        resync_source.contains("use agent_doc_tmux::{")
            && resync_source.contains("PruneCleanupMode")
            && resync_source.contains("StashTtlCandidate")
            && resync_source.contains("stash_ttl_prune_targets"),
        "resync.rs should import focused stash prune policy directly"
    );

    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    assert!(
        !sync_source.contains("resync::PruneCleanupMode")
            && !sync_source.contains("crate::resync::PruneCleanupMode"),
        "sync.rs must not route prune cleanup mode through resync.rs"
    );
    assert!(
        sync_source.contains("agent_doc_tmux::PruneCleanupMode"),
        "sync.rs should use the focused prune cleanup mode directly"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-tmux-commands",
        "agent-doc-tmux-io",
        "anyhow",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux stash prune policy must stay free of orchestration, git, editor IPC, sqlite, tmux command, or tmux-router effects"
        );
    }
}

#[test]
fn test_tmux_router_owns_session_registry_normalization_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let router_registry = fs::read_to_string(
        manifest_dir
            .parent()
            .unwrap()
            .join("tmux-router/src/registry.rs"),
    )
    .unwrap();

    for required in [
        "pub fn canonical_registry_key_in(",
        "pub fn entry_session_id",
        "pub fn normalize_registry(",
        "pub fn find_registry_key_by_session_id(",
    ] {
        assert!(
            router_registry.contains(required),
            "tmux-router registry must own session registry normalization policy: {required}"
        );
    }

    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    for forbidden in [
        "pub fn canonical_registry_key_in(",
        "fn canonical_registry_key_in(",
        "fn canonicalize_or_normalize(",
        "fn normalize_path(",
        "fn entry_session_id",
        "fn choose_preferred_entry(",
        "fn normalize_registry(",
        "fn find_registry_key_by_session_id(",
    ] {
        assert!(
            !sessions_source.contains(forbidden),
            "session registry registration IO must call tmux-router registry policy directly, not re-own it: {forbidden}"
        );
    }
    assert!(
        sessions_source.contains("use agent_doc_session_registry as session_registry;")
            && !sessions_source.contains("use tmux_router::registry::{")
            && !sessions_source.contains("normalize_registry"),
        "session registry registration IO should import focused agent-doc session registry policy directly"
    );

    let registry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry/src/lib.rs")).unwrap();
    assert!(
        registry_source.contains("use tmux_router::registry::{")
            && registry_source.contains("canonical_registry_key_in")
            && registry_source.contains("entry_session_id")
            && registry_source.contains("session_identity_owner(registry, session_id)"),
        "agent-doc-session-registry should adapt tmux-router registry policy directly"
    );

    let registry_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/lib.rs")).unwrap();
    assert!(
        registry_io_source.contains("use tmux_router::registry::normalize_registry;")
            && registry_io_source.contains("agent_doc_session_registry::session_pane(")
            && registry_io_source.contains("agent_doc_session_registry::session_entry("),
        "agent-doc-session-registry-io should combine tmux-router normalization with focused lookup policy"
    );

    let direct_call_sources = [
        "src/rename.rs",
        "agent-doc-sync-io/src/sync.rs",
        "agent-doc-session-actor-io/src/lib.rs",
        "agent-doc-controller-io/src/project_controller.rs",
        "agent-doc-sync-io/src/sync/pane_repair.rs",
        "agent-doc-sync-io/src/sync/registry.rs",
        "agent-doc-sync-io/src/sync/layout.rs",
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-prompt-io/src/lib.rs",
    ];
    for relative_path in direct_call_sources {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            !source.contains("sessions::canonical_registry_key_in")
                && !source.contains(
                    "agent_doc_session_registry_io::registration::canonical_registry_key_in"
                ),
            "{relative_path} must call tmux-router registry policy directly"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_pane_position_selection() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    let tmux_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-io/src/lib.rs")).unwrap();
    let claim_source =
        fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    for required in [
        "pub const TMUX_PANE_GEOMETRY_FORMAT",
        "pub enum PanePosition",
        "pub struct TmuxPaneGeometry",
        "pub fn parse_tmux_pane_geometry(",
        "pub fn select_pane_by_position(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own pure pane position selection: {required}"
        );
    }

    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    for forbidden in [
        "fn select_pane_by_position(",
        "pub fn pane_by_position(",
        "pub fn pane_by_position_in_window(",
        "pane_by_position_with_mux(",
        "pane_by_position_in_window_with_mux(",
        "Vec<(String, u32, u32, u32, u32)>",
        "\"#{pane_id} #{pane_left} #{pane_top} #{pane_width} #{pane_height}\"",
    ] {
        assert!(
            !sessions_source.contains(forbidden),
            "session registry registration IO must query tmux, not re-own pane geometry selection: {forbidden}"
        );
    }
    assert!(
        tmux_io_source.contains("pub fn pane_by_position(")
            && tmux_io_source.contains("pub fn pane_by_position_in_window(")
            && tmux_io_source.contains("agent_doc_tmux::TMUX_PANE_GEOMETRY_FORMAT")
            && tmux_io_source.contains("agent_doc_tmux::select_pane_by_position"),
        "agent-doc-tmux-io should own the effectful pane-position tmux query adapter"
    );
    assert!(
        !claim_source.contains("sessions::pane_by_position")
            && claim_source.contains("agent_doc_tmux_io::pane_by_position(")
            && claim_source.contains("agent_doc_tmux_io::pane_by_position_in_window("),
        "claim should resolve positional panes through focused tmux IO, not session registry registration IO"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux pane position policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_associated_pane_resolution_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    for required in [
        "pub enum AssociatedPaneSource",
        "pub struct AssociatedPaneCandidate",
        "pub enum AssociatedPaneResolution",
        "pub fn parse_pane_inventory_line(",
        "pub fn resolve_associated_panes(",
        "pub fn is_stash(&self) -> bool",
        "pub fn source_summary(&self) -> String",
        "pub fn format_associated_pane_resolution_error(",
        "pub fn format_associated_pane_selected_error(",
        "pub fn format_associated_pane_fix_error(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own associated pane resolution policy: {required}"
        );
    }

    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    for forbidden in [
        "pub enum AssociatedPaneSource",
        "pub struct AssociatedPaneCandidate",
        "pub enum AssociatedPaneResolution",
        "fn parse_pane_inventory_line(",
        "pub fn resolve_associated_panes(",
        "pub use agent_doc_tmux",
        "pub(crate) use agent_doc_tmux",
        "fn format_associated_pane_resolution_error(",
        "fn format_associated_pane_selected_error(",
    ] {
        assert!(
            !sync_source.contains(forbidden),
            "sync.rs must collect tmux evidence, not re-own or facade associated pane resolution policy: {forbidden}"
        );
    }
    assert!(
        sync_source.contains("use agent_doc_tmux::{")
            && sync_source.contains("AssociatedPaneCandidate")
            && sync_source.contains("AssociatedPaneResolution")
            && sync_source.contains("AssociatedPaneSource")
            && sync_source.contains("parse_pane_inventory_line")
            && sync_source.contains("resolve_associated_panes"),
        "sync.rs should call the focused associated pane API directly"
    );

    for relative_path in [
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-sync-io/src/resync.rs",
        "agent-doc-route-io/tests/route/pane_resolution.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            !source.contains("crate::sync::AssociatedPane")
                && !source.contains("crate::sync::resolve_associated_panes"),
            "{relative_path} must import associated pane policy from agent-doc-tmux, not through sync.rs"
        );
        assert!(
            !source.contains("fn format_associated_pane_resolution_error(")
                && !source.contains("fn format_associated_pane_selected_error(")
                && !source.contains("multiple tmux panes are associated with {}")
                && !source.contains("route found legacy pane-association evidence for {}"),
            "{relative_path} must not re-own associated pane diagnostic formatting policy"
        );
        assert!(
            source.contains("agent_doc_tmux::AssociatedPane")
                || source.contains("agent_doc_tmux::resolve_associated_panes")
                || source.contains("agent_doc_tmux::format_associated_pane_")
                || !source.contains("associated_pane"),
            "{relative_path} should call the focused associated pane API directly"
        );
    }

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-tmux-commands",
        "agent-doc-tmux-io",
        "anyhow",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux associated pane policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_bare_shell_command_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    let tmux_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn pane_current_command_is_bare_shell(",
        "pub enum TmuxPaneProcessKind",
        "pub fn pane_current_command_is_agent_process(",
        "pub fn pane_process_kind_from_current_command(",
        "pub fn pane_process_kind_from_current_command_samples",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own pure pane current-command process classification: {required}"
        );
    }

    let dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch.rs")).unwrap();
    let startup_ready_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup_ready.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn pane_current_command_is_bare_shell(",
        "\"zsh\" | \"bash\" | \"sh\" | \"fish\" | \"dash\" | \"ksh\" | \"tcsh\" | \"csh\"",
    ] {
        assert!(
            !dispatch_source.contains(forbidden),
            "route dispatch must observe tmux state, not re-own bare-shell command policy: {forbidden}"
        );
    }
    assert!(
        startup_ready_source.contains("agent_doc_tmux::pane_current_command_is_bare_shell("),
        "route startup-ready IO should call the focused tmux bare-shell API directly"
    );

    for relative in [
        "agent-doc-sync-io/src/resync.rs",
        "agent-doc-sync-io/src/resync/prune.rs",
        "agent-doc-sync-io/src/resync/stash.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "const AGENT_PROCESSES",
            "const IDLE_SHELLS",
            "enum PaneProcessKind",
            "fn pane_process_kind_from_current_command(",
            "fn pane_current_command_is_agent_process(",
            "fn pane_current_command(",
            "fn pane_window_name(",
            "fn pane_session_name(",
            "fn has_named_window(",
            "fn pane_process_tree_contains_pid(",
            "sessions::pane_pid_with_mux(",
            "sessions::pane_window_with_mux(",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not re-own or facade tmux pane process/observation policy: {forbidden}"
            );
        }
    }
    for relative in [
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-route-io/src/dispatch.rs",
        "agent-doc-route-io/src/session_resolution.rs",
        "agent-doc-route-io/tests/route/pane_resolution.rs",
        "agent-doc-route-io/src/startup.rs",
        "agent-doc-route-io/src/startup_sync.rs",
        "agent-doc-route-io/src/pane_provenance.rs",
        "agent-doc-route-io/src/dispatch_target.rs",
        "agent-doc-route-io/src/restart_handoff.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "fn pane_window_name(",
            "fn pane_session_name(",
            "fn has_named_window(",
            "fn pane_display_value(",
            "agent_doc_tmux_io::list_windows(tmux, Some(session_name), \"#{window_name}\")",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not keep route-local tmux observation facades: {forbidden}"
            );
        }
    }
    let resync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/resync.rs")).unwrap();
    let route_session_resolution =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/session_resolution.rs"))
            .unwrap();
    let route_pane_resolution_io =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/pane_resolution.rs")).unwrap();
    let route_startup =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup.rs")).unwrap();
    let route_startup_sync =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup_sync.rs")).unwrap();
    let route_pane_provenance =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/pane_provenance.rs")).unwrap();
    let route_dispatch_target =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_target.rs")).unwrap();
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let test_support_source =
        fs::read_to_string(manifest_dir.join("agent-doc-test-support/src/lib.rs")).unwrap();
    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    let claim_source =
        fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    let session_actor_cmd_source =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    let prompt_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-io/src/lib.rs")).unwrap();
    let watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/daemon.rs")).unwrap();
    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let preflight_layout =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/layout.rs")).unwrap();
    let start_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-io/src/lib.rs")).unwrap();
    assert!(
        resync_source.contains("pane_process_kind_from_current_command_samples")
            && resync_source.contains("agent_doc_tmux_io::target_current_command(")
            && resync_source.contains("agent_doc_tmux_io::target_window_name(")
            && resync_source.contains("agent_doc_tmux_io::target_window_id(")
            && resync_source.contains("agent_doc_process_owner_io::process_tree_contains_pid("),
        "resync should call focused tmux process and observation APIs directly"
    );
    assert!(
        tmux_io_source.contains("pub fn has_window_named(")
            && tmux_io_source.contains("pub fn in_tmux() -> bool")
            && tmux_io_source.contains("pub fn target_window_id(")
            && tmux_io_source.contains("pub fn capture_pane(")
            && tmux_io_source.contains("pub fn capture_pane_with_ansi(")
            && tmux_io_source.contains("pub fn join_pane_guarded(")
            && tmux_io_source.contains("pub fn send_key_logged(")
            && route_session_resolution.contains("agent_doc_tmux_io::target_session_name(")
            && route_session_resolution.contains("agent_doc_tmux_io::target_window_name(")
            && route_session_resolution.contains("agent_doc_tmux_io::has_window_named(")
            && route_pane_resolution_io.contains("agent_doc_tmux_io::target_session_name(")
            && route_pane_resolution_io.contains("agent_doc_tmux_io::target_window_name(")
            && route_startup.contains("agent_doc_tmux_io::has_window_named(")
            && route_pane_provenance.contains("agent_doc_tmux_io::pane_pid(")
            && route_pane_provenance.contains("agent_doc_tmux_io::target_session_name(")
            && route_pane_provenance.contains("agent_doc_tmux_io::target_current_command(")
            && route_source.contains("pub(crate) use agent_doc_test_support::{")
            && test_support_source.contains("agent_doc_tmux_io::target_current_command(")
            && startup_ready_source.contains("agent_doc_tmux_io::target_current_command(")
            && route_dispatch_target.contains("agent_doc_tmux_io::target_window_id(")
            && route_startup_sync.contains("agent_doc_tmux_io::target_window_id(")
            && tmux_io_source.contains("pub fn current_pane_id_from_env_or_tmux(")
            && claim_source.contains("agent_doc_tmux_io::pane_pid(")
            && claim_source.contains("agent_doc_tmux_io::current_pane_id_from_env_or_tmux(")
            && session_actor_cmd_source.contains("agent_doc_tmux_io::pane_pid(")
            && session_actor_cmd_source
                .contains("agent_doc_tmux_io::current_pane_id_from_env_or_tmux(")
            && session_actor_cmd_source.contains("agent_doc_tmux_io::capture_pane(")
            && prompt_source.contains("agent_doc_tmux_io::capture_pane_with_ansi(")
            && prompt_source.contains("agent_doc_tmux_io::send_key_logged(")
            && watch_source.contains("agent_doc_tmux_io::capture_pane(")
            && route_pane_resolution_io.contains("agent_doc_tmux_io::join_pane_guarded(")
            && sync_source.contains("agent_doc_tmux_io::join_pane_guarded(")
            && write_source.contains("agent_doc_tmux_io::in_tmux()")
            && preflight_layout.contains("agent_doc_tmux_io::in_tmux()")
            && start_run_source.contains("agent_doc_tmux_io::in_tmux()")
            && !sessions_source.contains("pub fn pane_pid(")
            && !sessions_source.contains("pub fn pane_pid_with_mux(")
            && !sessions_source.contains("pub fn pane_window(")
            && !sessions_source.contains("pub fn pane_window_with_mux(")
            && !sessions_source.contains("pub fn current_pane(")
            && !sessions_source.contains("pub fn current_pane_with_mux(")
            && !sessions_source.contains("pub fn capture_pane(")
            && !sessions_source.contains("pub fn capture_pane_with_ansi(")
            && !sessions_source.contains("pub fn join_pane_guarded(")
            && !sessions_source.contains("pub fn send_key(")
            && !sessions_source.contains("pub fn send_submitted_text(")
            && !sessions_source.contains("pub fn send_submitted_text_for_harness(")
            && !sessions_source.contains("pub fn in_tmux(")
            && !sessions_source.contains("capture_pane_plain")
            && !sessions_source.contains("fn display_message(&self")
            && !sessions_source.contains("trait Multiplexer")
            && !sessions_source.contains("impl Multiplexer for"),
        "route should call focused tmux IO observation helpers directly"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "agent-doc-tmux-io",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux bare-shell policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_prompt_io_routes_document_reads_through_realtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let prompt_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&prompt_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    let prompt_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-io/src/lib.rs")).unwrap();

    assert!(
        dependencies.contains_key("agent-doc-document-realtime-io"),
        "prompt IO should depend on the realtime document authority for active document reads"
    );
    for required in [
        "fn current_document_content(file: &Path, source: &str) -> Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "current_document_content(file, \"prompt_run_frontmatter\")",
        "current_document_content(file, \"prompt_answer_frontmatter\")",
    ] {
        assert!(
            prompt_source.contains(required),
            "prompt IO should resolve prompt command frontmatter through realtime authority: {required}"
        );
    }
    assert!(
        !prompt_source.contains("std::fs::read_to_string(file)")
            && !prompt_source.contains("fs::read_to_string(file)"),
        "prompt IO must not read the active session document directly from disk"
    );
}

#[test]
fn test_agent_doc_turn_executor_tmux_owns_prompt_parser_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_executor_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_executor_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let prompt_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor-tmux/src/prompt.rs"))
            .unwrap();
    for required in [
        "pub struct PromptInfo",
        "pub struct PromptOption",
        "pub fn parse_prompt(",
        "pub fn strip_ansi(",
        "pub fn navigation_axis_for_prompt(",
        "pub fn navigation_keys_for_prompt(",
        "pub fn opencode_option_requires_confirmation(",
        "pub fn is_codex_idle_placeholder_prompt(",
        "pub fn codex_idle_placeholder_prompt(",
        "pub fn codex_idle_placeholder_candidate(",
        "pub fn codex_prompt_candidate_is_dim_placeholder(",
    ] {
        assert!(
            prompt_source.contains(required),
            "agent-doc-turn-executor-tmux must own pure prompt parser policy: {required}"
        );
    }

    let prompt_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub struct PromptInfo",
        "pub struct PromptOption",
        "pub fn parse_prompt(",
        "pub fn strip_ansi(",
        "fn parse_claude_prompt(",
        "fn parse_opencode_prompt(",
        "fn parse_option_line(",
        "fn opencode_selected_option_from_ansi(",
    ] {
        assert!(
            !prompt_io_source.contains(forbidden),
            "prompt IO command adapter must not re-own parser policy: {forbidden}"
        );
    }
    assert!(
        prompt_io_source.contains("use agent_doc_turn_executor_tmux::prompt::{"),
        "prompt IO adapter should call the focused prompt parser directly"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/prompt.rs")
            .exists(),
        "orchestration prompt facade should be deleted once prompt IO owns the command adapter"
    );
    assert!(
        !orchestration_lib.contains("pub mod prompt;"),
        "orchestration must not expose a public prompt facade"
    );

    let harness_source =
        fs::read_to_string(manifest_dir.join("agent-doc-harness/src/lib.rs")).unwrap();
    for forbidden in [
        "fn codex_idle_placeholder_prompt(",
        "fn codex_idle_placeholder_candidate(",
        "fn codex_prompt_candidate_is_dim_placeholder(",
        "fn codex_prompt_line_body_starts_dim(",
        "fn apply_sgr_sequence(",
        "fn is_safe_codex_placeholder_token(",
    ] {
        assert!(
            !harness_source.contains(forbidden),
            "agent-doc-harness must not re-own Codex prompt placeholder parsing policy: {forbidden}"
        );
    }
    assert!(
        harness_source.contains("codex_idle_placeholder_candidate")
            && harness_source.contains("codex_prompt_candidate_is_dim_placeholder")
            && harness_source.contains("is_codex_idle_placeholder_prompt"),
        "agent-doc-harness should call focused Codex prompt placeholder policy directly"
    );
    let supervisor_io_detection_source =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/detection.rs")).unwrap();
    let session_actor_source =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    let sim_world_engine_source =
        fs::read_to_string(manifest_dir.join("src/sim_world/engine.rs")).unwrap();
    for source in [
        &harness_source,
        &supervisor_io_detection_source,
        &session_actor_source,
        &sim_world_engine_source,
    ] {
        assert!(
            !source.contains("agent_doc_orchestration::prompt::strip_ansi")
                && !source.contains("crate::prompt::strip_ansi")
                && !source.contains("agent_doc_orchestration::prompt::parse_prompt")
                && !source.contains("crate::prompt::parse_prompt"),
            "callers should import prompt parser policy from agent-doc-turn-executor-tmux directly"
        );
    }

    for forbidden in [
        "agent-doc-orchestration",
        "anyhow",
        "tmux-router",
        "agent-doc-frontmatter",
        "interprocess",
        "notify",
        "rusqlite",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-turn-executor-tmux prompt parser must stay free of orchestration/session/tmux effects"
        );
    }
}

#[test]
fn test_agent_doc_turn_executor_tmux_owns_context_clear_submit_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_executor_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_executor_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let lib_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor-tmux/src/lib.rs")).unwrap();
    assert!(
        lib_source.contains("pub mod context_clear;"),
        "agent-doc-turn-executor-tmux must export context-clear submit policy directly"
    );
    assert!(
        !lib_source.contains("pub use agent_doc_tmux::{"),
        "agent-doc-turn-executor-tmux must not facade tmux model types; callers should use agent-doc-tmux directly"
    );

    let context_clear_source =
        fs::read_to_string(manifest_dir.join("agent-doc-turn-executor-tmux/src/context_clear.rs"))
            .unwrap();
    for required in [
        "pub enum ContextClearSubmitStatus",
        "pub struct ContextClearSubmitObservation",
        "pub fn context_clear_command_visible_in_active_input(",
        "pub fn context_clear_submit_needs_enter_resubmit(",
        "pub fn context_clear_submit_observation_line(",
        "pub fn context_clear_submit_resubmit_proof_line(",
        "pub fn context_clear_submit_blocked_line(",
        "pub fn context_clear_submit_blocked_message(",
        "pub fn busy_clear_deferred_message(",
        "pub fn busy_clear_already_deferred_message(",
        "pub fn protected_clear_refusal_message(",
        "pub fn busy_clear_refusal_message(",
        "pub struct InterruptClearTimeoutFacts",
        "pub fn interrupt_clear_timeout_message(",
        "pub fn terminal_editor_command(",
        "pub fn operator_interrupt_key_plan(",
        "pub fn operator_interrupt_step_delay(",
    ] {
        assert!(
            context_clear_source.contains(required),
            "agent-doc-turn-executor-tmux must own context-clear submit policy: {required}"
        );
    }

    let session_actor_source =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    for forbidden in [
        "enum ClearDirectSubmitStatus",
        "struct ClearDirectSubmitObservation",
        "fn clear_direct_submit_needs_enter_resubmit(",
        "fn clear_direct_submit_observation_line(",
        "fn clear_direct_submit_resubmit_proof_line(",
        "fn clear_direct_submit_blocked_line(",
        "fn clear_direct_submit_blocked_message(",
        "fn clear_command_visible_in_active_input(",
        "fn line_shows_clear_command_input(",
        "fn clear_command_candidate_visible(",
        "fn line_starts_with_clear_prompt_prefix(",
        "fn strip_clear_prompt_prefix(",
        "fn busy_clear_deferred_message(",
        "fn busy_clear_already_deferred_message(",
        "fn protected_clear_refusal_message(",
        "fn busy_clear_refusal_message(",
        "fn interrupt_clear_timeout_message(",
        "fn terminal_editor_command(",
        "fn operator_interrupt_key_plan(",
        "fn operator_interrupt_step_delay(",
    ] {
        assert!(
            !session_actor_source.contains(forbidden),
            "session_actor_cmd.rs must keep context-clear submit effects only, not re-own pure policy: {forbidden}"
        );
    }
    assert!(
        session_actor_source.contains("use agent_doc_turn_executor_tmux::context_clear::{"),
        "session_actor_cmd.rs should call focused context-clear policy directly"
    );

    let supervisor_io_detection_source =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor-io/src/detection.rs")).unwrap();
    let controller_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/dispatch.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn context_clear_command_visible_in_active_input(",
        "fn line_shows_context_clear_command_input(",
        "fn context_clear_command_candidate_visible(",
        "fn line_starts_with_context_clear_prompt_prefix(",
        "fn strip_context_clear_prompt_prefix(",
    ] {
        assert!(
            !supervisor_io_detection_source.contains(forbidden),
            "supervisor detection IO must not duplicate context-clear visibility policy: {forbidden}"
        );
    }
    assert!(
        supervisor_io_detection_source.contains("dispatch_payload_pending_in_current_input(")
            && controller_dispatch.contains("agent_doc_turn_executor_tmux::context_clear::context_clear_command_visible_in_active_input("),
        "supervisor detection IO should call controller payload policy, and controller dispatch should call focused context-clear policy directly"
    );

    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-tmux-commands",
        "anyhow",
        "tmux-router",
        "agent-doc-frontmatter",
        "interprocess",
        "notify",
        "rusqlite",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-turn-executor-tmux context-clear policy must stay free of orchestration/session/tmux command effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_owns_layout_memory_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_manifest = fs::read_to_string(manifest_dir.join("agent-doc-tmux/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_source = fs::read_to_string(manifest_dir.join("agent-doc-tmux/src/lib.rs")).unwrap();
    for required in [
        "pub struct TmuxLayoutColumn",
        "pub fn apply_column_memory(",
        "pub fn build_layout_state(",
        "pub fn classify_sync_layout_columns",
        "pub fn same_sync_file(",
        "pub fn focused_column_index(",
        "pub enum TmuxFocusOnlyExpansionMode",
        "pub fn expand_focus_only_columns_for_editor_switch(",
        "pub fn apply_focus_only_expansion_policy(",
    ] {
        assert!(
            tmux_source.contains(required),
            "agent-doc-tmux must own tmux layout memory and focus-only expansion policy: {required}"
        );
    }

    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    assert!(
        sync_source.contains("agent_doc_tmux::apply_column_memory(")
            && sync_source.contains("agent_doc_tmux::build_layout_state(")
            && sync_source.contains("agent_doc_tmux::classify_sync_layout_columns(")
            && sync_source.contains("agent_doc_tmux::focused_column_index(")
            && sync_source.contains("agent_doc_tmux::apply_focus_only_expansion_policy("),
        "sync.rs should call the focused tmux layout policy API directly"
    );

    let sync_layout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/layout.rs")).unwrap();
    let sync_registry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/registry.rs")).unwrap();
    assert!(
        sync_layout_source.contains("active_pane_column_index(")
            && sync_layout_source.contains("agent_doc_tmux::classify_sync_layout_columns(")
            && sync_registry_source.contains("first_agent_doc_in_col("),
        "orchestration should keep tmux/file adapters and call focused layout policy directly"
    );
    for forbidden in [
        "fn classify_sync_layout_columns(",
        "fn same_sync_file(",
        "fn focused_column_index(",
        "TmuxLayoutColumn::new(",
        "fn apply_column_memory(",
        "fn build_layout_state(",
        "fn expand_focus_only_columns_for_editor_switch(",
        "fn apply_focus_only_expansion_policy(",
    ] {
        assert!(
            !sync_layout_source.contains(forbidden),
            "sync/layout.rs must not keep old layout policy wrappers after extraction: {forbidden}"
        );
    }

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux layout policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_commands_owns_submit_profile_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tmux_commands_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-commands/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_commands_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_commands_source =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-commands/src/lib.rs")).unwrap();
    for required in [
        "pub struct TmuxSubmitProfile",
        "pub const fn tmux_submit_profile_for_harness(",
        "pub const fn tmux_submit_mode_for_harness(",
        "pub const fn tmux_submit_transform_for_harness(",
        "pub const fn tmux_submit_key_for_harness(",
        "pub fn submitted_text_without_trailing_line_endings(",
        "pub fn text_submit_command(",
        "pub fn text_only_command(",
    ] {
        assert!(
            tmux_commands_source.contains(required),
            "agent-doc-tmux-commands must own pure tmux submit policy: {required}"
        );
    }

    let sessions_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-registry-io/src/registration.rs"))
            .unwrap();
    let tmux_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-io/src/lib.rs")).unwrap();
    for forbidden in [
        "pub struct TmuxSubmitProfile",
        "pub const fn tmux_submit_profile_for_harness(",
        "pub const fn tmux_submit_mode_for_harness(",
        "pub const fn tmux_submit_transform_for_harness(",
        "pub const fn tmux_submit_key_for_harness(",
        "fn text_submit_command_args(",
        "fn text_only_command_args(",
    ] {
        assert!(
            !sessions_source.contains(forbidden),
            "session registry registration IO must execute tmux commands, not re-own submit profile policy: {forbidden}"
        );
    }
    assert!(
        !sessions_source.contains("tmux_submit_profile_for_harness(")
            && !sessions_source.contains("agent_doc_tmux_io::send_submitted_text_with_profile(")
            && tmux_io_source.contains("pub fn send_submitted_text_logged(")
            && tmux_io_source.contains("pub fn send_submitted_text_for_harness_logged(")
            && tmux_io_source.contains("tmux_submit_profile_for_harness(")
            && tmux_io_source.contains("send_submitted_text_with_profile("),
        "logged submitted-text profile selection should live in focused tmux IO, not session registry registration IO"
    );

    let route_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch.rs")).unwrap();
    let route_direct_pane_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/direct_pane_dispatch.rs"))
            .unwrap();
    let start_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/lib.rs")).unwrap();
    let idle_watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    let session_actor_source =
        fs::read_to_string(manifest_dir.join("src/session_actor_cmd.rs")).unwrap();
    let queue_dispatch_source =
        fs::read_to_string(manifest_dir.join("src/queue_dispatch.rs")).unwrap();
    let sim_world_source = fs::read_to_string(manifest_dir.join("src/sim_world.rs")).unwrap();
    for source in [
        &route_dispatch_source,
        &start_source,
        &idle_watch_source,
        &session_actor_source,
        &queue_dispatch_source,
        &sim_world_source,
    ] {
        assert!(
            !source.contains("agent_doc_session_registry_io::registration::tmux_submit_")
                && !source.contains("agent_doc_session_registry_io::registration::tmux_submit_"),
            "orchestration callers should import tmux submit policy from agent-doc-tmux-commands directly"
        );
    }
    assert!(
        !route_dispatch_source.contains("fn routed_trigger_submit_diagnostic(")
            && !route_dispatch_source.contains("fn routed_trigger_payload(")
            && !route_dispatch_source.contains("fn validate_routed_trigger_payload(")
            && route_direct_pane_dispatch_source.contains("tmux_submit_transform_for_harness(")
            && route_direct_pane_dispatch_source.contains("tmux_submit_key_for_harness("),
        "direct-pane route IO should call focused tmux submit diagnostics directly, without a local wrapper"
    );
    let supervisor_ipc_protocol_source =
        fs::read_to_string(manifest_dir.join("agent-doc-supervisor/src/ipc_protocol.rs")).unwrap();
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    for source in [
        &supervisor_ipc_protocol_source,
        &route_dispatch_source,
        &route_source,
        &start_source,
        &queue_dispatch_source,
        &session_actor_source,
    ] {
        assert!(
            !source.contains("normalize_submit_text(")
                && !source.contains("routed_trigger_submit_payload("),
            "submit-text normalization should be consumed from agent-doc-tmux-commands directly, without orchestration wrappers"
        );
    }
    assert!(
        supervisor_ipc_protocol_source.contains("submitted_text_without_trailing_line_endings(")
            && route_dispatch_source.contains("submitted_text_without_trailing_line_endings(")
            && start_source.contains("submitted_text_without_trailing_line_endings(")
            && queue_dispatch_source.contains("submitted_text_without_trailing_line_endings(")
            && session_actor_source.contains("submitted_text_without_trailing_line_endings("),
        "submit-text callers should use the focused tmux command normalization API directly"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-tmux-commands submit policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_hash_owns_sha256_content_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root_manifest: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let workspace_members = root_manifest["workspace"]["members"].as_array().unwrap();
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-hash")),
        "agent-doc-hash must be a workspace member"
    );
    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-hash"),
        "root crate callers should depend on agent-doc-hash directly"
    );

    let hash_source = fs::read_to_string(manifest_dir.join("agent-doc-hash/src/lib.rs")).unwrap();
    assert!(
        hash_source.contains("pub fn content_hash(")
            && hash_source.contains("pub fn bytes_hash(")
            && hash_source.contains("pub fn short_content_hash(")
            && hash_source.contains("pub fn path_hash(")
            && hash_source.contains("pub fn path_string_hash(")
            && hash_source.contains("pub fn document_id_for_path(")
            && hash_source.contains("Sha256::new()"),
        "agent-doc-hash must own shared SHA-256 hex and path-derived document-id policy"
    );
    let debounce_source =
        fs::read_to_string(manifest_dir.join("agent-doc-debounce/src/lib.rs")).unwrap();
    assert!(
        debounce_source.contains("pub fn authority_settle_max_wait("),
        "agent-doc-debounce must own pure preflight debounce wait policy"
    );

    let debounce_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-debounce/Cargo.toml")).unwrap();
    let debounce_manifest: toml::Value = toml::from_str(&debounce_manifest).unwrap();
    let debounce_dependencies = debounce_manifest
        .get("dependencies")
        .and_then(toml::Value::as_table);
    assert!(
        debounce_dependencies.is_none_or(|dependencies| dependencies.is_empty()),
        "agent-doc-debounce is pure settle-budget policy and must stay dependency-free"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration_manifest["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-hash")
            && !orchestration_dependencies.contains_key("sha2")
            && !orchestration_dependencies.contains_key("hex"),
        "agent-doc-orchestration should call the focused hash crate instead of owning SHA-256 deps"
    );

    for relative in [
        "agent-doc-ops-log-io/src/lib.rs",
        "agent-doc-op-capture-io/src/lib.rs",
        "agent-doc-element-backlog-io/src/backlog_cmd.rs",
        "agent-doc-run-context-io/src/lib.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-debounce/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "pub fn content_hash(",
            "fn content_hash(",
            "fn short_content_hash(",
            "pub fn doc_id_for(",
            "fn doc_id_for(",
            "fn hash_path_str(",
            "use sha2::",
            "hex::encode(",
            "pub use agent_doc_hash",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not keep a content-hash shim or local SHA-256 policy: {forbidden}"
            );
        }
    }

    fn collect_rs_files(dir: &Path, files: &mut Vec<PathBuf>) {
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                collect_rs_files(&path, files);
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                files.push(path);
            }
        }
    }

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod op_capture;")
            && !manifest_dir
                .join("agent-doc-orchestration/src/op_capture.rs")
                .exists(),
        "orchestration must not keep an op_capture sidecar facade"
    );

    for relative in ["src", "agent-doc-debounce/src"] {
        let mut files = Vec::new();
        collect_rs_files(&manifest_dir.join(relative), &mut files);
        for file in files {
            let source = fs::read_to_string(&file).unwrap();
            for forbidden in [
                "ops_log::content_hash",
                "op_capture::content_hash",
                "agent_doc_debounce::content_hash",
                "pending_cmd::doc_id_for",
                "crate::pending_cmd::doc_id_for",
                "agent_doc_orchestration::pending_cmd",
                "backlog_cmd::doc_id_for",
                "crate::backlog_cmd::doc_id_for",
            ] {
                assert!(
                    !source.contains(forbidden),
                    "callers must import agent_doc_hash directly instead of old path {forbidden} in {}",
                    file.display()
                );
            }
        }
    }
}

#[test]
fn test_agent_doc_archive_io_owns_head_compact_archive_reads() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root_manifest: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let workspace_members = root_manifest["workspace"]["members"].as_array().unwrap();
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-archive-io")),
        "agent-doc-archive-io must be a workspace member"
    );

    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-archive-io"),
        "root crate should expose the focused compact archive IO crate"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration_manifest["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-archive-io"),
        "agent-doc-orchestration should call the focused compact archive IO crate"
    );

    let archive_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-archive-io/Cargo.toml")).unwrap();
    let archive_io_manifest: toml::Value = toml::from_str(&archive_io_manifest).unwrap();
    let archive_io_dependencies = archive_io_manifest["dependencies"].as_table().unwrap();
    for required in ["agent-doc-document", "agent-doc-project-root-io"] {
        assert!(
            archive_io_dependencies.contains_key(required),
            "agent-doc-archive-io should depend on compact archive read dependency: {required}"
        );
    }
    for forbidden in ["agent-doc-orchestration", "agent-doc-fs"] {
        assert!(
            !archive_io_dependencies.contains_key(forbidden),
            "agent-doc-archive-io must stay focused on compact archive reads: {forbidden}"
        );
    }

    let archive_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-archive-io/src/lib.rs")).unwrap();
    assert!(
        archive_io_source.contains("pub fn read_head_compact_archives(")
            && archive_io_source.contains("pub fn read_head_compact_archive(")
            && archive_io_source.contains(".agent-doc/archives")
            && archive_io_source.contains("agent_doc_project_root_io::project_root_containing(")
            && archive_io_source
                .contains("agent_doc_document::compact_archive::compact_archive_pointers("),
        "agent-doc-archive-io should own HEAD compact archive read pathing"
    );

    let closeout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/src/closeout.rs")).unwrap();
    for forbidden in [
        "pub(crate) fn compact_archive_pointers(",
        "pub(crate) fn read_head_compact_archive(",
        "agent_doc_fs::find_project_root(&canonical)?",
    ] {
        assert!(
            !closeout_source.contains(forbidden),
            "flow closeout must not re-own compact archive read pathing: {forbidden}"
        );
    }
    assert!(
        closeout_source.contains("agent_doc_archive_io::read_head_compact_archives("),
        "flow closeout should call compact archive IO directly"
    );

    let queue_head_guards_source = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_guards.rs"),
    )
    .unwrap();
    assert!(
        !queue_head_guards_source.contains("crate::flow::closeout::read_head_compact_archive")
            && !queue_head_guards_source
                .contains("crate::flow::closeout::compact_archive_pointers")
            && queue_head_guards_source
                .contains("agent_doc_archive_io::read_head_compact_archives("),
        "session_check queue-head guards should call compact archive IO directly"
    );
}

#[test]
fn test_agent_doc_capture_io_owns_response_capture_ledger() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root_manifest: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let workspace_members = root_manifest["workspace"]["members"].as_array().unwrap();
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-capture-io")),
        "agent-doc-capture-io must be a workspace member"
    );

    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-capture-io"),
        "root crate should expose the focused response capture IO crate"
    );

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration_manifest["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-capture-io"),
        "agent-doc-orchestration should call the focused response capture IO crate"
    );

    let capture_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-capture-io/Cargo.toml")).unwrap();
    let capture_io_manifest: toml::Value = toml::from_str(&capture_io_manifest).unwrap();
    let capture_io_dependencies = capture_io_manifest["dependencies"].as_table().unwrap();
    for required in ["agent-doc-fs", "agent-doc-project-root-io", "anyhow"] {
        assert!(
            capture_io_dependencies.contains_key(required),
            "agent-doc-capture-io should depend on response capture path dependency: {required}"
        );
    }
    for forbidden in ["agent-doc-orchestration", "agent-doc-op-capture-io"] {
        assert!(
            !capture_io_dependencies.contains_key(forbidden),
            "agent-doc-capture-io must stay focused on response capture paths, not orchestration or editor op-capture sidecars: {forbidden}"
        );
    }

    let capture_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-capture-io/src/lib.rs")).unwrap();
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        capture_io_source.contains("pub fn capture_response(")
            && capture_io_source.contains("pub fn load_active(")
            && capture_io_source.contains("pub fn validate_replay("),
        "agent-doc-capture-io should own the response capture ledger"
    );
    for forbidden in [
        "pub fn capture_dir_for(",
        "pub fn capture_path_for(",
        "pub fn partial_capture_path_for(",
        ".agent-doc/captures",
    ] {
        assert!(
            !capture_io_source.contains(forbidden),
            "response capture must not expose a filesystem sidecar path: {forbidden}"
        );
    }
    for required in [
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)",
        "agent_doc_cycle_state_io::load_with_closeout_projection(&self.file)",
    ] {
        assert!(
            capture_io_source.contains(required),
            "capture IO active cycle/capture readers should use the state projection: {required}"
        );
    }
    for forbidden in [
        "let cycle_id = agent_doc_cycle_state_io::load(file)",
        "let existing_cycle_id = agent_doc_cycle_state_io::load(file)?",
        "let Some(state) = agent_doc_cycle_state_io::load(file)?",
        "agent_doc_cycle_state_io::load(&self.file)?",
    ] {
        assert!(
            !capture_io_source.contains(forbidden),
            "capture IO production readers must not bypass the state projection: {forbidden}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/capture.rs")
            .exists(),
        "orchestration capture facade should be deleted once capture IO owns the response capture ledger"
    );
    assert!(
        !orchestration_lib.contains("pub mod capture;"),
        "orchestration must not expose a public capture facade"
    );
}

#[test]
fn test_agent_doc_ipc_protocol_owns_receipt_classification() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root_manifest: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let workspace_members = root_manifest["workspace"]["members"].as_array().unwrap();
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-ipc-protocol")),
        "agent-doc-ipc-protocol must be a workspace member"
    );
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-ipc-io")),
        "agent-doc-ipc-io must be a workspace member"
    );
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-ipc-forensics-io")),
        "agent-doc-ipc-forensics-io must be a workspace member"
    );
    let root_dependencies = root_manifest["dependencies"].as_table().unwrap();
    assert!(
        root_dependencies.contains_key("agent-doc-ipc-protocol"),
        "root crate callers should depend on agent-doc-ipc-protocol directly"
    );
    assert!(
        root_dependencies.contains_key("agent-doc-ipc-io"),
        "root crate callers should depend on agent-doc-ipc-io directly"
    );
    assert!(
        root_dependencies.contains_key("agent-doc-ipc-forensics-io"),
        "root crate callers should depend on agent-doc-ipc-forensics-io directly"
    );
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-callback-io")),
        "agent-doc-callback-io must be a workspace member"
    );
    assert!(
        workspace_members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-project-root-io")),
        "agent-doc-project-root-io must be a workspace member"
    );
    assert!(
        root_dependencies.contains_key("agent-doc-callback-io"),
        "root crate callback callers should depend on agent-doc-callback-io directly"
    );
    assert!(
        root_dependencies.contains_key("agent-doc-project-root-io"),
        "root crate project-root callers should depend on agent-doc-project-root-io directly"
    );

    let protocol_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-protocol/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&protocol_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    let protocol_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-protocol/src/lib.rs")).unwrap();
    assert!(
        protocol_source.contains("pub enum SocketReceiptClassification")
            && protocol_source.contains("pub fn classify_socket_receipt(")
            && protocol_source.contains("pub fn is_already_applied_receipt_error_message("),
        "agent-doc-ipc-protocol must own plugin IPC receipt classification"
    );
    for required in [
        "pub fn early_receipt_tagged_message(",
        "pub fn message_requests_early_receipt(",
        "pub fn early_receipt_line(",
        "pub fn early_receipt_ops_marker(",
        "pub fn ipc_accept_thread_ops_marker(",
        "pub fn patch_message(",
        "pub fn queue_convergence_message(",
        "pub fn reposition_message(",
        "pub fn refresh_content_message(",
        "pub enum EditorIntent",
        "pub fn vcs_refresh_message(",
        "pub fn vcs_refresh_probe_message(",
        "pub fn is_socket_receipt_timeout_error(",
        "pub fn is_socket_status_error(",
        "pub enum IpcSnapshotSource",
        "pub const fn is_visible_write_proven(self) -> bool",
        "pub enum IpcDiskRepairReason",
        "pub const fn redelivery_kind(self) -> FullContentRepairRedelivery",
        "pub const fn merge_with_ipc_dedupe(self) -> Self",
        "pub enum AlreadyAppliedSnapshotOutcome",
        "pub enum FullContentRepairRedelivery",
        "pub const fn success_message(self) -> &'static str",
        "pub const fn not_consumed_message(self) -> &'static str",
        "pub fn failed_message(self, error: impl fmt::Display) -> String",
        "pub enum FullContentIpcMode",
        "pub const fn source_label(",
    ] {
        assert!(
            protocol_source.contains(required),
            "agent-doc-ipc-protocol must own IPC protocol policy: {required}"
        );
    }
    for required in [
        "pub struct CallbackRequest",
        "pub struct CallbackPatch",
        "pub struct CallbackResponse",
        "pub struct PendingCallback",
        "pub fn callback_request(",
        "pub fn callback_response(",
        "pub fn callback_request_is_expired(",
        "pub fn callback_urgency_for_elapsed(",
        "pub fn pending_callback_from_request(",
        "pub fn callback_response_matches_request(",
    ] {
        assert!(
            protocol_source.contains(required),
            "agent-doc-ipc-protocol must own callback protocol policy: {required}"
        );
    }

    let orchestration_manifest = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    let orchestration_manifest: toml::Value = toml::from_str(&orchestration_manifest).unwrap();
    let orchestration_dependencies = orchestration_manifest["dependencies"].as_table().unwrap();
    assert!(
        orchestration_dependencies.contains_key("agent-doc-ipc-protocol"),
        "agent-doc-orchestration should call the focused IPC protocol crate"
    );
    assert!(
        orchestration_dependencies.contains_key("agent-doc-ipc-io"),
        "agent-doc-orchestration should call the focused IPC IO crate"
    );
    assert!(
        orchestration_dependencies.contains_key("agent-doc-ipc-forensics-io"),
        "agent-doc-orchestration should call the focused IPC forensic sidecar IO crate"
    );
    assert!(
        orchestration_dependencies.contains_key("agent-doc-callback-io"),
        "agent-doc-orchestration should call the focused callback IO crate"
    );
    assert!(
        orchestration_dependencies.contains_key("agent-doc-project-root-io"),
        "agent-doc-orchestration should call the focused project-root IO crate"
    );

    let project_root_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-project-root-io/Cargo.toml")).unwrap();
    let project_root_manifest: toml::Value = toml::from_str(&project_root_manifest).unwrap();
    let project_root_dependencies = project_root_manifest["dependencies"].as_table().unwrap();
    for required in ["agent-doc-fs", "agent-doc-git-io"] {
        assert!(
            project_root_dependencies.contains_key(required),
            "agent-doc-project-root-io should depend on project-root dependency: {required}"
        );
    }
    assert!(
        project_root_dependencies.contains_key("anyhow"),
        "agent-doc-project-root-io should own fallible CLI project-root argument resolution"
    );
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-ipc-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
    ] {
        assert!(
            !project_root_dependencies.contains_key(forbidden),
            "agent-doc-project-root-io must stay a focused project-root adapter, not orchestration, IPC transport, sqlite, or tmux-router state: {forbidden}"
        );
    }
    let project_root_source =
        fs::read_to_string(manifest_dir.join("agent-doc-project-root-io/src/lib.rs")).unwrap();
    assert!(
        project_root_source.contains("pub fn resolve_ipc_project_root(")
            && project_root_source.contains("pub fn project_root_from_arg(")
            && project_root_source.contains("pub fn project_root_from_cwd(")
            && project_root_source.contains("pub fn project_root_containing(")
            && project_root_source.contains("pub fn project_root_or_cwd(")
            && project_root_source.contains("pub fn project_root_for_target_or_cwd(")
            && project_root_source.contains("pub fn project_root_or_file_parent(")
            && project_root_source.contains("agent_doc_fs::find_project_root")
            && project_root_source.contains("agent_doc_git_io::dirs::git_toplevel_at"),
        "agent-doc-project-root-io should own .agent-doc project-root resolution constrained by git toplevel"
    );
    let project_controller_rpc_source = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        !project_controller_rpc_source.contains("pub fn project_root_from_arg(")
            && project_controller_rpc_source
                .contains("agent_doc_project_root_io::project_root_from_arg(")
            && !project_controller_rpc_source.contains("agent_doc_fs::find_project_root(")
            && project_controller_rpc_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "orchestration project-controller RPC should call focused project-root IO instead of owning CLI/stale-supervisor root resolution"
    );
    let project_controller_source =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    assert!(
        !project_controller_source.contains("agent_doc_fs::find_project_root(")
            && project_controller_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "orchestration project-controller should call focused project-root IO instead of owning closeout actor root discovery"
    );
    let gc_source = fs::read_to_string(manifest_dir.join("agent-doc-gc-io/src/lib.rs")).unwrap();
    assert_source_omits_all(
        &gc_source,
        "agent-doc-gc-io",
        &["fn find_project_root_from_cwd("],
    );
    assert_source_mentions_all(
        &gc_source,
        "agent-doc-gc-io",
        &["agent_doc_project_root_io", "project_root_from_cwd"],
    );
    let git_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    assert!(
        !git_source.contains("agent_doc_fs::find_project_root(")
            && !git_source.contains("agent_doc_project_root_io::project_root_containing("),
        "commit runtime should not rediscover a project root after VCS refresh moved behind the controller intent boundary"
    );
    let admin_source =
        fs::read_to_string(manifest_dir.join("agent-doc-admin-io/src/lib.rs")).unwrap();
    assert!(
        !admin_source.contains("fn resolve_root(")
            && !admin_source.contains("fn resolve_root_for_target(")
            && admin_source.contains("agent_doc_project_root_io::project_root_or_cwd(")
            && admin_source.contains("agent_doc_project_root_io::project_root_for_target_or_cwd("),
        "admin should call focused project-root IO instead of owning root selection helpers"
    );
    let watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/daemon.rs")).unwrap();
    assert_source_omits_all(
        &watch_source,
        "watch daemon",
        &["agent_doc_fs::find_project_root("],
    );
    assert_source_mentions_all(
        &watch_source,
        "watch daemon",
        &["agent_doc_project_root_io", "project_root_containing"],
    );
    let ops_log_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ops-log-io/src/lib.rs")).unwrap();
    assert!(
        !ops_log_source.contains("agent_doc_fs::find_project_root(")
            && ops_log_source.contains("agent_doc_project_root_io::project_root_containing("),
        "ops-log IO should call focused project-root IO instead of owning .agent-doc root discovery"
    );
    let realtime_model_source =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    assert!(
        !realtime_model_source.contains("agent_doc_fs::find_project_root(")
            && realtime_model_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "realtime_model should call focused project-root IO instead of owning broadcast patches root discovery"
    );
    let graph_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-context-io/src/lib.rs")).unwrap();
    assert!(
        !graph_source.contains("agent_doc_fs::find_project_root(")
            && graph_source.contains("agent_doc_project_root_io::project_root_containing("),
        "graph should call focused project-root IO instead of owning run-context root discovery"
    );
    let start_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-io/src/lib.rs")).unwrap();
    assert!(
        !start_run_source.contains("agent_doc_fs::find_project_root(")
            && start_run_source.contains("agent_doc_project_root_io::project_root_containing("),
        "agent-doc-start-io should call focused project-root IO instead of owning supervisor-start root discovery"
    );
    let preflight_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    assert!(
        !preflight_run_source.contains("agent_doc_fs::find_project_root(")
            && preflight_run_source.contains("agent_doc_project_root_io::project_root_containing("),
        "preflight/run should call focused project-root IO instead of owning actor cleanup/sweep root discovery"
    );
    let preflight_maintenance_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    assert!(
        !preflight_maintenance_source.contains("agent_doc_fs::find_project_root(")
            && preflight_maintenance_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "preflight maintenance should call focused project-root IO instead of owning queue/done/ops-log root discovery"
    );
    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    assert!(
        !preflight_source.contains("agent_doc_fs::find_project_root("),
        "preflight must not own drift/archive/claims root discovery"
    );
    let run_source = fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    assert!(
        !run_source.contains("agent_doc_fs::find_project_root(")
            && run_source.contains("agent_doc_project_root_io::project_root_containing("),
        "run IO should call focused project-root IO instead of owning stderr/queue/actor root discovery"
    );
    let repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-command-io/tests/repair.rs"))
            .unwrap();
    assert!(
        !repair_source.contains("agent_doc_fs::find_project_root("),
        "repair tests must not own sidecar root discovery"
    );
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let realtime_io =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    assert!(
        !write_source.contains("agent_doc_fs::find_project_root(")
            && realtime_io.contains("agent_doc_project_root_io::project_root_containing("),
        "realtime IO should call focused project-root IO for write-authority root discovery"
    );
    let flow_closeout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/src/closeout.rs")).unwrap();
    assert!(
        !flow_closeout_source.contains("agent_doc_fs::find_project_root(")
            && flow_closeout_source.contains("agent_doc_project_root_io::project_root_containing("),
        "flow closeout should call focused project-root IO instead of owning terminal proof/editor IPC root discovery"
    );
    let session_actor_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-actor-io/src/lib.rs")).unwrap();
    assert!(
        !session_actor_source.contains("agent_doc_fs::find_project_root(")
            && session_actor_source.contains("agent_doc_project_root_io::project_root_containing("),
        "agent-doc-session-actor-io should call focused project-root IO instead of owning actor log/store root discovery"
    );
    let snapshot_source =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    assert!(
        !snapshot_source.contains("agent_doc_fs::find_project_root(")
            && snapshot_source.contains("agent_doc_project_root_io::project_root_containing("),
        "snapshot IO should call focused project-root IO instead of owning rename-migration root discovery"
    );
    let safe_passive_source = read_first_existing_source(
        manifest_dir,
        &[
            "agent-doc-sync-io/src/sync/safe_passive.rs",
            "agent-doc-sync-io/src/sync.rs",
        ],
    );
    assert_source_omits_all(
        &safe_passive_source,
        "sync safe-passive",
        &["agent_doc_fs::find_project_root("],
    );
    assert_source_mentions_all(
        &safe_passive_source,
        "sync safe-passive",
        &["agent_doc_project_root_io", "project_root_containing"],
    );
    let sync_registry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/registry.rs")).unwrap();
    assert!(
        !sync_registry_source.contains("agent_doc_fs::find_project_root(")
            && sync_registry_source.contains("agent_doc_project_root_io::project_root_containing("),
        "sync registry should call focused project-root IO instead of owning registry location root discovery"
    );
    let sync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    assert!(
        !sync_source.contains("agent_doc_fs::find_project_root(")
            && sync_source.contains("agent_doc_project_root_io::project_root_containing("),
        "sync should call focused project-root IO instead of owning actor/supervisor root discovery"
    );
    let route_busy_pane_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/busy_pane.rs")).unwrap();
    assert!(
        !route_busy_pane_source.contains("agent_doc_fs::find_project_root(")
            && route_busy_pane_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "route busy-pane IO should call focused project-root IO instead of owning .agent-doc root discovery"
    );
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_queue_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/queue_dispatch.rs")).unwrap();
    assert!(
        !route_source.contains("agent_doc_fs::find_project_root(")
            && !route_queue_dispatch_source.contains("agent_doc_fs::find_project_root(")
            && !route_queue_dispatch_source.contains("acquire_route_queue_lock"),
        "route queue IO must not own broad project-root discovery or a bespoke route-queue flock (#lazily-hot-path); CRDT merge retries serialize concurrent route-queue writes"
    );
    let route_startup_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/startup.rs")).unwrap();
    assert!(
        !route_startup_source.contains("agent_doc_fs::find_project_root(")
            && route_startup_source
                .contains("agent_doc_project_root_io::project_root_or_file_parent("),
        "route startup IO should call focused project-root IO instead of owning registry base fallback discovery"
    );
    let workflow_doctor_source =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/doctor.rs")).unwrap();
    assert!(
        !workflow_doctor_source.contains("agent_doc_fs::find_project_root(")
            && workflow_doctor_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "workflow doctor should call focused project-root IO instead of owning .agent-doc root discovery"
    );
    let workflow_autofix_source =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/autofix.rs")).unwrap();
    assert!(
        !workflow_autofix_source.contains("agent_doc_fs::find_project_root(")
            && workflow_autofix_source
                .contains("agent_doc_project_root_io::project_root_containing("),
        "workflow autofix should call focused project-root IO instead of owning .agent-doc root discovery"
    );
    let focus_source = fs::read_to_string(manifest_dir.join("src/focus_effects.rs")).unwrap();
    assert!(
        !focus_source.contains("agent_doc_fs::find_project_root(")
            && focus_source.contains("agent_doc_project_root_io::project_root_containing("),
        "focus effects should call focused project-root IO instead of owning .agent-doc root discovery"
    );
    let claim_source =
        fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    assert!(
        !claim_source.contains("agent_doc_fs::find_project_root(")
            && claim_source.contains("agent_doc_project_root_io::project_root_containing(")
            && claim_source.contains("agent_doc_project_root_io::project_root_or_file_parent("),
        "claim should call focused project-root IO instead of owning lease/log root discovery"
    );
    let resync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/resync.rs")).unwrap();
    assert!(
        !resync_source.contains("agent_doc_fs::find_project_root(")
            && resync_source.contains("agent_doc_project_root_io::project_root_containing("),
        "resync should call focused project-root IO instead of owning registry root discovery"
    );
    let compact_source =
        fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    assert!(
        !compact_source.contains("fn find_project_root(")
            && compact_source.contains("agent_doc_project_root_io::project_root_or_file_parent("),
        "compact should call focused project-root IO instead of owning archive root fallback resolution"
    );
    let write_converge_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    assert!(
        !write_converge_source.contains("agent_doc_fs::find_project_root(file)")
            && write_converge_source
                .contains("agent_doc_project_root_io::project_root_containing(file)"),
        "write converge IO should call focused project-root IO instead of owning stale-supervisor recycle root discovery"
    );

    let ipc_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-io/Cargo.toml")).unwrap();
    let ipc_io_manifest: toml::Value = toml::from_str(&ipc_io_manifest).unwrap();
    let ipc_io_dependencies = ipc_io_manifest["dependencies"].as_table().unwrap();
    for required in [
        "agent-doc-ipc-protocol",
        "agent-doc-ops-log-io",
        "anyhow",
        "interprocess",
        "serde_json",
    ] {
        assert!(
            ipc_io_dependencies.contains_key(required),
            "agent-doc-ipc-io should depend on socket/protocol dependency: {required}"
        );
    }
    for forbidden in [
        "agent-doc-fs",
        "agent-doc-orchestration",
        "agent-doc-git-io",
        "agent-doc-project-root-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
    ] {
        assert!(
            !ipc_io_dependencies.contains_key(forbidden),
            "agent-doc-ipc-io must stay a socket/file-signal adapter, not orchestration or app state: {forbidden}"
        );
    }

    let ipc_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-io/src/lib.rs")).unwrap();
    assert!(
        ipc_io_source.contains("use agent_doc_ipc_protocol::{")
            && ipc_io_source.contains("SocketReceiptClassification")
            && ipc_io_source.contains("classify_socket_receipt")
            && ipc_io_source.contains("early_receipt_tagged_message")
            && ipc_io_source.contains("message_requests_early_receipt")
            && ipc_io_source.contains("vcs_refresh_message")
            && ipc_io_source.contains("interprocess::local_socket")
            && ipc_io_source.contains("pub type OpsLogger")
            && ipc_io_source.contains("pub mod editor_target;")
            && ipc_io_source.contains("pub fn start_listener_with_logger")
            && !ipc_io_source.contains("send_save_document"),
        "agent-doc-ipc-io should own PID-scoped socket transport while importing protocol vocabulary"
    );
    for forbidden in [
        "pub enum SocketReceiptClassification",
        "pub fn classify_socket_receipt(",
        "pub fn is_already_applied_error(",
        "fn early_receipt_tagged_message(",
        "pub fn message_requests_early_receipt(",
        "pub fn early_receipt_line(",
        "pub fn early_receipt_ops_marker(",
        "pub fn ipc_accept_thread_ops_marker(",
        "pub fn resolve_ipc_project_root(",
        "pub fn resolve_project_root(",
        "fn patch_message(",
        "fn queue_convergence_message(",
        "fn reposition_message(",
        "save_document_message(",
        "fn refresh_content_message(",
        "fn publish_live_buffer_message(",
        "fn vcs_refresh_message(",
        "fn vcs_refresh_probe_message(",
    ] {
        assert!(
            !ipc_io_source.contains(forbidden),
            "agent-doc-ipc-io must not keep old IPC protocol policy after extraction: {forbidden}"
        );
    }
    let ipc_io_editor_target_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-io/src/editor_target.rs")).unwrap();
    assert!(
        ipc_io_editor_target_source.contains("pub fn target_payload_to_editor(")
            && !ipc_io_editor_target_source.contains("live_editor_delivery_target(")
            && !ipc_io_editor_target_source
                .contains("live_editor_delivery_has_operator_authority(")
            && !ipc_io_editor_target_source.contains("target_payload_to_live_editor(")
            && !ipc_io_editor_target_source.contains("agent_doc_plugin_owner::")
            && !ipc_io_editor_target_source.contains("agent_doc_debounce::live_buffer_snapshots(")
            && !ipc_io_editor_target_source
                .contains("agent_doc_document_realtime::select_live_editor_delivery_target(")
            && ipc_io_editor_target_source.contains("agent_doc_ops_log_io::log_op("),
        "agent-doc-ipc-io editor_target should target an explicitly registered editor without selecting from filesystem sidecars or leases"
    );

    let ipc_forensics_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-forensics-io/Cargo.toml")).unwrap();
    let ipc_forensics_manifest: toml::Value = toml::from_str(&ipc_forensics_manifest).unwrap();
    let ipc_forensics_dependencies = ipc_forensics_manifest["dependencies"].as_table().unwrap();
    assert!(
        ipc_forensics_dependencies.contains_key("agent-doc-project-root-io"),
        "agent-doc-ipc-forensics-io should use the focused project-root adapter"
    );
    for forbidden in [
        "agent-doc-fs",
        "agent-doc-ipc-io",
        "agent-doc-ipc-protocol",
        "agent-doc-orchestration",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
    ] {
        assert!(
            !ipc_forensics_dependencies.contains_key(forbidden),
            "agent-doc-ipc-forensics-io must stay focused on forensic sidecar files: {forbidden}"
        );
    }
    let ipc_forensics_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-forensics-io/src/lib.rs")).unwrap();
    assert!(
        ipc_forensics_source.contains("pub fn preserve_ipcfullprompt_forensic(")
            && ipc_forensics_source.contains(".agent-doc/logs/ipcfullprompt")
            && ipc_forensics_source.contains("agent_doc_project_root_io::project_root_containing("),
        "agent-doc-ipc-forensics-io should own IPC full-prompt forensic capture sidecars"
    );
    let write_ipc_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let write_converge_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    assert!(
        !write_ipc_source.contains("pub(crate) fn preserve_ipcfullprompt_forensic(")
            && !write_ipc_source.contains("agent_doc_fs::find_project_root(")
            && !write_ipc_source
                .contains("agent_doc_ipc_forensics_io::preserve_ipcfullprompt_forensic(")
            && write_converge_source
                .contains("agent_doc_ipc_forensics_io::preserve_ipcfullprompt_forensic("),
        "IPC write convergence should call focused IPC forensic sidecar IO instead of orchestration owning root/path capture"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/ipc_socket.rs")
            .exists(),
        "orchestration must not keep an ipc_socket facade after agent-doc-ipc-io extraction"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod ipc_socket;"),
        "orchestration must not expose focused IPC IO through an ipc_socket facade"
    );
    let ipc_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-ipc-io/src/lib.rs")).unwrap();
    assert!(
        ipc_io_source.contains("pub fn start_listener_with_logger")
            && ipc_io_source.contains("pub fn send_message_to_pid(")
            && !ipc_io_source.contains("send_save_document")
            && ipc_io_source.contains("pub fn send_observe_lazily_current_to_editor("),
        "agent-doc-ipc-io should own PID-scoped socket listener and intent transport"
    );
    let ffi_source = fs::read_to_string(manifest_dir.join("src/ffi.rs")).unwrap();
    assert!(
        ffi_source.contains("agent_doc_ipc_io::start_listener_with_logger_until(")
            && ffi_source.contains("agent_doc_ops_log_io::log_op")
            && ffi_source.contains("agent_doc_ipc_io::wake_listener(")
            && ffi_source.contains(
                "agent_doc_controller_io::project_controller::load_state_backbone_projection("
            )
            && !ffi_source.contains("agent_doc_cycle_state_io::load_with_closeout_projection(")
            && !ffi_source.contains("agent_doc_orchestration::ipc_socket"),
        "FFI should call cancellable focused IPC IO directly, inject the ops-log sink, wake listeners during native reload quiescence, and read the Project Controller state-backbone projection (sidecars demoted, #sidecardemote) for editor-facing turn projection"
    );
    for relative in [
        "agent-doc-write-converge-io/src/convergence_fixture_tests.rs",
        "agent-doc-write-runtime-io/src/ipc.rs",
        "agent-doc-write-ipc-io/src/transport.rs",
        "agent-doc-compact-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_ipc_io::") && !source.contains("crate::ipc_socket::"),
            "{relative} should call focused IPC IO directly instead of an orchestration facade"
        );
    }
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    assert!(
        !preflight_runtime.contains("agent_doc_ipc_io::")
            && !preflight_runtime.contains("crate::ipc_socket::"),
        "preflight recovery should consume reactive document projection without any editor IPC request"
    );

    let callback_source =
        fs::read_to_string(manifest_dir.join("agent-doc-callback-io/src/lib.rs")).unwrap();
    assert!(
        callback_source.contains("use agent_doc_ipc_protocol::{")
            && callback_source.contains("callback_request_is_expired")
            && callback_source.contains("pending_callback_from_request")
            && callback_source.contains("callback_response_matches_request")
            && callback_source.contains("upsert_document_runtime_state_in_db")
            && callback_source.contains("list_document_runtime_state_kind_from_db")
            && !callback_source.contains("request.json")
            && !callback_source.contains("response.json"),
        "agent-doc-callback-io should combine focused protocol policy with the shared state-machine store"
    );
    for forbidden in [
        "pub struct CallbackRequest",
        "pub struct Patch",
        "pub struct CallbackResponse",
        "pub struct PendingCallback",
        "fn callback_request_is_expired(",
        "fn callback_urgency_for_elapsed(",
        "pub use agent_doc_ipc_protocol",
        "agent_doc_orchestration::",
        "crate::snapshot",
    ] {
        assert!(
            !callback_source.contains(forbidden),
            "agent-doc-callback-io must stay a focused state-machine adapter, not a callback protocol facade or orchestration shim: {forbidden}"
        );
    }
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod callback;"),
        "orchestration must not expose callback IO through a callback facade module"
    );
    for relative in [
        "src/main.rs",
        "src/cleanup_cmd.rs",
        "agent-doc-preflight-command-io/src/run.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_callback_io")
                && !source.contains("agent_doc_orchestration::callback")
                && !source.contains("crate::callback::"),
            "{relative} should call focused callback IO directly"
        );
    }

    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let orchestration_preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    assert!(
        preflight_source.contains("Vec<agent_doc_ipc_protocol::PendingCallback>")
            && !orchestration_preflight_source.contains("Vec<crate::callback::PendingCallback>"),
        "preflight should type pending callbacks through the focused IPC protocol crate"
    );

    let sim_world_source = fs::read_to_string(manifest_dir.join("src/sim_world.rs")).unwrap();
    assert!(
        sim_world_source.contains("agent_doc_ipc_protocol::classify_socket_receipt(")
            && sim_world_source
                .contains("agent_doc_ipc_protocol::is_already_applied_receipt_error_message(")
            && !sim_world_source.contains("ipc_socket::classify_socket_receipt")
            && !sim_world_source.contains("ipc_socket::SocketReceiptClassification")
            && !sim_world_source
                .contains("agent_doc_orchestration::ipc_socket::is_already_applied_error"),
        "root callers should use the focused IPC protocol crate instead of the old orchestration path"
    );

    let write_ipc_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    for forbidden in [
        "fn is_socket_receipt_timeout_error(",
        "fn is_socket_status_error(",
        "fn existing_patch_is_reposition_only(",
        "pub(crate) enum IpcSnapshotSource",
        "pub(crate) enum IpcDiskRepairReason",
        "pub(crate) enum AlreadyAppliedSnapshotOutcome",
        "pub(crate) enum FullContentRepairRedelivery",
        "fn redelivery_kind(self) -> FullContentRepairRedelivery",
        "fn success_message(self) -> &'static str",
        "fn not_consumed_message(self) -> &'static str",
    ] {
        assert!(
            !write_ipc_source.contains(forbidden),
            "write IPC must not re-own socket/reposition protocol helpers after extraction: {forbidden}"
        );
    }

    let write_ipc_transport_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/transport.rs")).unwrap();
    let orchestration_write_ipc_transport_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc/transport.rs"))
            .unwrap();
    let write_ipc_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/lib.rs")).unwrap();
    let write_ipc_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/Cargo.toml")).unwrap();
    assert!(
        write_ipc_transport_source.contains("use agent_doc_ipc_protocol::{")
            && write_ipc_transport_source.contains("target_payload_to_editor")
            && write_ipc_transport_source.contains("decide_editor_delivery_admission")
            && write_ipc_transport_source.contains("reliable_sync_editor_live_for_file")
            && write_ipc_transport_source.contains("FullContentIpcMode")
            && write_ipc_transport_source.contains("is_already_applied_receipt_error_message")
            && write_ipc_transport_source.contains("is_socket_receipt_timeout_error"),
        "write IPC transport should import remaining IPC protocol vocabulary from the focused protocol crate"
    );
    let admission_index = write_ipc_transport_source
        .find("decide_editor_delivery_admission(EditorDeliveryAdmissionFacts")
        .expect("write IPC must decide editor-delivery admission");
    let socket_send_index = write_ipc_transport_source
        .find("agent_doc_ipc_io::send_message_to_pid(")
        .expect("write IPC socket send should exist");
    assert!(
        admission_index < socket_send_index
            && write_ipc_transport_source.contains("EditorDeliveryAdmission::Detached")
            && write_ipc_transport_source
                .contains("EditorDeliveryAdmission::RefuseIncompleteRegistration")
            && write_ipc_transport_source.contains("ipc_editor_delivery_refused"),
        "write IPC must fail closed on reliable-open-set versus legacy-endpoint disagreement before payload delivery"
    );
    assert!(
        write_source.contains("#[cfg(test)]\nmod ipc;")
            && write_source.contains("#[cfg(test)]\npub(crate) use ipc::*;")
            && !write_source.contains("pub use ipc::*;")
            && write_ipc_source.contains("#[cfg(test)]\nmod transport;")
            && write_ipc_source.contains("#[cfg(test)]\npub(crate) use transport::try_ipc;")
            && !write_ipc_source.contains("pub use transport::*;")
            && orchestration_write_ipc_transport_source.contains("#[cfg(test)]")
            && orchestration_write_ipc_transport_source.contains("pub(crate) fn try_ipc(")
            && orchestration_write_ipc_transport_source
                .contains("agent_doc_write_ipc_io::try_ipc_with_effects("),
        "orchestration write IPC transport should be a test-only wrapper over the focused transport crate"
    );
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let write_run_entry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    assert!(
        main_source.contains("agent_doc_write_ipc_io::try_ipc_with_effects(")
            && main_source
                .contains("&agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS")
            && !main_source.contains("agent_doc_write_runtime_io::try_ipc(")
            && write_run_entry_source.contains("agent_doc_write_ipc_io::try_ipc_with_effects(")
            && write_run_entry_source
                .contains("&agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS")
            && !write_run_entry_source.contains("&WRITE_CONVERGENCE_EFFECTS"),
        "production write IPC callers should call the focused transport crate directly"
    );
    assert!(
        write_ipc_io_source.contains("EditorIntent::Reposition.as_str()")
            && write_ipc_io_source.contains("is_socket_receipt_timeout_error")
            && write_ipc_io_source.contains("pub fn try_ipc_reposition_boundary(")
            && write_ipc_io_source.contains("pub fn build_ipc_patches_json(")
            && write_ipc_io_source.contains("normalize_patch_content(")
            && write_ipc_io_source.contains("boundary_id_from_seed_with_summary")
            && write_ipc_io_source.contains("find_boundary_id")
            && write_ipc_io_source
                .contains("use agent_doc_ipc_io::editor_target::target_payload_to_editor;")
            && write_ipc_io_source.contains("live_editor_registration_for_file(file)"),
        "agent-doc-write-ipc-io should own reposition IPC transport and payload synthesis imports"
    );
    assert!(
        write_ipc_io_manifest.contains("agent-doc-document-realtime-io")
            && write_ipc_io_source
                .contains("agent_doc_document_realtime_io::try_resolve_current_document_content")
            && write_ipc_io_source.contains("pub(crate) fn ipc_document_content(")
            && write_ipc_io_source.contains("\"write_ipc_build_patches_current\"")
            && write_ipc_io_source.contains("\"write_ipc_reposition_working_doc\"")
            && write_ipc_transport_source.contains("\"try_ipc_before_content\"")
            && write_ipc_transport_source.contains("\"try_ipc_mid_turn_cycle_state_current\"")
            && !write_ipc_io_source.contains("disk_fallback")
            && !write_ipc_transport_source.contains("disk_fallback"),
        "agent-doc-write-ipc-io should route active reads only through Lazily current authority"
    );
    assert!(
        !write_ipc_transport_source.contains("file_ipc_fallback_skip_already_applied"),
        "file IPC must not treat disk equality as an editor delivery acknowledgement"
    );
    assert!(
        write_ipc_io_source.contains("pub(crate) fn projected_cycle_id(")
            && write_ipc_io_source
                .contains("agent_doc_cycle_state_io::load_closeout_projection(file)")
            && write_ipc_transport_source.contains("projected_cycle_id(file)"),
        "agent-doc-write-ipc-io should tag IPC payloads from state-ledger closeout projections"
    );
    let forbidden = "agent_doc_cycle_state_io::load(file)";
    assert!(
        !write_ipc_io_source.contains(forbidden) && !write_ipc_transport_source.contains(forbidden),
        "agent-doc-write-ipc-io production payload/diagnostic cycle ids must not use raw compatibility sidecars: {forbidden}"
    );
    for forbidden in [
        "std::fs::read_to_string(file)",
        "fs::read_to_string(file)",
        "std::fs::read_to_string(doc_file)",
        "fs::read_to_string(doc_file)",
    ] {
        assert!(
            !write_ipc_io_source.contains(forbidden)
                && !write_ipc_transport_source.contains(forbidden),
            "agent-doc-write-ipc-io must not read the active document directly in production IPC flow: {forbidden}"
        );
    }
    for forbidden in [
        "pub enum FullContentIpcMode",
        "fn full_content_source_label(",
        "pub(crate) fn full_content_source_label(",
        "fn is_socket_receipt_timeout_error(",
        "fn existing_patch_is_reposition_only(",
        "crate::ipc_socket::is_already_applied_error",
        "pub use agent_doc_ipc_protocol",
        "fn live_editor_delivery_has_operator_authority(",
        "fn target_payload_to_live_editor(",
        "pub fn try_ipc_full_content(",
        "pub(crate) fn try_ipc_full_content(",
        "fn try_ipc_full_content_with_mode(",
        "pub(crate) fn log_full_content_ipc_disabled(",
        "pub(crate) fn full_content_ipc_scope_allows(",
        "pub(crate) fn build_ipc_patches_json(",
        "fn build_ipc_patches_json(",
    ] {
        assert!(
            !write_ipc_transport_source.contains(forbidden),
            "write IPC transport must not re-own or facade full-content IPC protocol vocabulary: {forbidden}"
        );
    }
    let write_converge_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    assert!(
        write_converge_source.contains("use agent_doc_ipc_protocol::{")
            && write_converge_source.contains("is_socket_receipt_timeout_error")
            && write_converge_source
                .contains("use agent_doc_ipc_io::editor_target::target_payload_to_editor;")
            && write_converge_source.contains("reliable_sync_editor_has_operator_text_authority")
            && write_converge_source.contains("target_payload_to_registered_editor")
            && write_converge_source.contains("live_editor_registration_for_file(file)"),
        "write convergence IO should use socket classifiers plus Lazily registration-based editor targeting"
    );
    for forbidden in [
        "fn is_socket_receipt_timeout_error(",
        "fn is_socket_status_error(",
    ] {
        assert!(
            !write_converge_source.contains(forbidden),
            "write convergence must not re-own socket error classifiers after extraction: {forbidden}"
        );
    }

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !dependencies.contains_key(forbidden),
            "agent-doc-ipc-protocol must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_tmux_commands_and_io_own_input_diag_layers() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_direct_pane_dispatch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/direct_pane_dispatch.rs"))
            .unwrap();
    let tmux_commands_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-commands/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_commands_manifest).unwrap();
    let tmux_commands_dependencies = parsed["dependencies"].as_table().unwrap();

    let tmux_commands_source =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-commands/src/lib.rs")).unwrap();
    for required in [
        "pub mod input_diag",
        "pub const PREFIX",
        "pub const EDITOR_ROUTE_ATTEMPT_ID_ENV",
        "pub struct KeyEventMeta",
        "pub fn sanitize_field(",
        "pub fn bytes_hash(",
        "pub fn key_name(",
        "pub fn verbose_enabled(",
        "pub fn format_key_event(",
        "pub fn format_payload_event(",
        "pub fn format_byte_event(",
        "pub fn format_transform_event(",
        "pub fn format_prompt_detection(",
        "pub fn sanitize_route_snapshot_field(",
        "pub fn format_route_pane_snapshot_filename(",
        "pub struct RoutePaneSnapshotFacts",
        "pub struct RoutePaneSnapshotLogFacts",
        "pub struct RoutePaneSnapshotFailedLogFacts",
        "pub struct RoutePaneSnapshotHintFacts",
        "pub fn format_route_pane_snapshot_log(",
        "pub fn format_route_pane_snapshot_failed_log(",
        "pub fn format_route_pane_snapshot_hint(",
    ] {
        assert!(
            tmux_commands_source.contains(required),
            "agent-doc-tmux-commands must own pure input diagnostic policy: {required}"
        );
    }

    let tmux_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-io/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&tmux_io_manifest).unwrap();
    let tmux_io_dependencies = parsed["dependencies"].as_table().unwrap();
    assert!(
        tmux_io_dependencies.contains_key("agent-doc-tmux-commands"),
        "agent-doc-tmux-io input diagnostics must consume pure formatting from agent-doc-tmux-commands"
    );
    assert!(
        !tmux_io_dependencies.contains_key("agent-doc-orchestration"),
        "agent-doc-tmux-io must stay free of orchestration dependencies"
    );

    let tmux_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-tmux-io/src/lib.rs")).unwrap();
    assert!(
        tmux_io_lib.contains("pub mod input_diag;"),
        "agent-doc-tmux-io must expose the effectful input diagnostic adapter"
    );
    let tmux_io_input_diag_path = manifest_dir.join("agent-doc-tmux-io/src/input_diag.rs");
    assert!(
        tmux_io_input_diag_path.exists(),
        "agent-doc-tmux-io must own the input diagnostic adapter source"
    );
    let tmux_io_input_diag = fs::read_to_string(&tmux_io_input_diag_path).unwrap();
    for required in [
        "agent_doc_tmux_commands::input_diag::{self, KeyEventMeta}",
        "pub type OpsLogFn = fn(&Path, &str);",
        "pub fn log_key_event(",
        "pub fn log_key_event_verbose(",
        "pub fn log_text_submit(",
        "pub fn log_byte_events(",
        "pub fn log_transform_event(",
        "pub fn log_prompt_detection(",
        "pub struct InputDiagSink",
        "pub fn new(file: Option<&'a Path>, log_op: OpsLogFn)",
        "(sink.log_op)(file, &message);",
        "input_diag::format_key_event(",
        "input_diag::format_payload_event(",
        "input_diag::format_byte_event(",
        "input_diag::format_transform_event(",
        "input_diag::format_prompt_detection(",
    ] {
        assert!(
            tmux_io_input_diag.contains(required),
            "agent-doc-tmux-io must own the effectful input diagnostic adapter: {required}"
        );
    }
    for forbidden in [
        "const PREFIX",
        "EDITOR_ROUTE_ATTEMPT_ID_ENV",
        "pub struct KeyEventMeta",
        "fn sanitize_field(",
        "fn bytes_hash(",
        "fn key_name(",
        "pub fn verbose_enabled(",
        "pub fn format_key_event(",
        "pub fn format_payload_event(",
        "pub fn format_byte_event(",
        "pub fn format_transform_event(",
        "pub fn format_prompt_detection(",
        "pub use agent_doc_tmux_commands::input_diag",
        "use sha2::",
        "agent_doc_orchestration::",
    ] {
        assert!(
            !tmux_io_input_diag.contains(forbidden),
            "agent-doc-tmux-io input_diag must stay an effectful adapter, not re-own pure policy or reach into orchestration: {forbidden}"
        );
    }

    let orchestration_input_diag_path =
        manifest_dir.join("agent-doc-orchestration/src/input_diag.rs");
    assert!(
        !orchestration_input_diag_path.exists(),
        "orchestration must not keep an input_diag source module facade"
    );
    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod input_diag"),
        "orchestration must not expose an input_diag facade"
    );

    for relative in [
        "src/queue_dispatch.rs",
        "src/session_actor_cmd.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-run-io/tests/direct_run.rs",
        "agent-doc-route-io/tests/route.rs",
        "agent-doc-route-io/src/dispatch.rs",
        "agent-doc-route-io/src/startup.rs",
        "agent-doc-session-registry-io/src/registration.rs",
        "agent-doc-sync-io/src/sync/pane_repair.rs",
        "agent-doc-start-runtime-io/src/run.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-start-runtime-io/src/supervisor_io.rs",
        "agent-doc-supervisor-io/src/ipc.rs",
        "agent-doc-supervisor-process/src/io_threads.rs",
        "agent-doc-supervisor-process/src/pty.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("crate::input_diag::verbose_enabled(")
                && !source.contains("agent_doc_orchestration::input_diag::verbose_enabled(")
                && !source.contains("crate::input_diag::KeyEventMeta")
                && !source.contains("agent_doc_orchestration::input_diag::KeyEventMeta")
                && !source.contains("crate::input_diag::")
                && !source.contains("agent_doc_orchestration::input_diag::"),
            "{relative} should call focused input diagnostic APIs directly"
        );
    }
    for relative in [
        "src/queue_dispatch.rs",
        "src/session_actor_cmd.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-route-io/src/dispatch.rs",
        "agent-doc-route-io/src/startup.rs",
        "agent-doc-sync-io/src/sync/pane_repair.rs",
        "agent-doc-start-runtime-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-supervisor-io/src/ipc.rs",
        "agent-doc-supervisor-process/src/io_threads.rs",
        "agent-doc-supervisor-process/src/pty.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_tmux_io::input_diag::log_"),
            "{relative} should call agent-doc-tmux-io input diagnostic logging directly"
        );
        for forbidden in [
            "crate::input_diag::log_",
            "agent_doc_orchestration::input_diag::log_",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must not route input diagnostic logging through the removed orchestration facade: {forbidden}"
            );
        }
    }
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    assert!(
        !route_source.contains("const EDITOR_ROUTE_ATTEMPT_ID_ENV"),
        "route diagnostics should use the focused editor route attempt-id env constant"
    );
    for forbidden in [
        "fn append_editor_route_attempt(",
        "fn route_snapshot_field(",
        "route_pane_snapshot file={}",
        "route_pane_snapshot_failed file={}",
        "[route] preserved dispatch-start proof snapshot",
    ] {
        assert!(
            !route_source.contains(forbidden),
            "route.rs must not re-own route snapshot diagnostic formatting policy: {forbidden}"
        );
    }
    assert!(
        route_direct_pane_dispatch_source
            .contains("agent_doc_controller_io::route_snapshot::preserve_route_pane_snapshot(")
            && route_direct_pane_dispatch_source
                .contains("agent_doc_controller_io::route_snapshot::route_pane_snapshot_hint("),
        "direct-pane route IO should preserve snapshots through the focused route snapshot IO adapter"
    );

    for forbidden in [
        "agent-doc-core",
        "agent-doc-orchestration",
        "git2",
        "interprocess",
        "notify",
        "rusqlite",
        "tmux-router",
    ] {
        assert!(
            !tmux_commands_dependencies.contains_key(forbidden),
            "agent-doc-tmux-commands input diagnostic policy must stay free of orchestration, git, editor IPC, sqlite, or tmux-router effects"
        );
    }
}

#[test]
fn test_agent_doc_document_owns_status_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let document_status =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/status_projection.rs"))
            .unwrap();
    for required in [
        "pub const STALE_SUPERVISOR_STATUS_MARKER",
        "pub fn replace_status_content",
        "pub fn reconcile_top_backlog_status_content",
        "pub fn apply_stale_supervisor_marker",
        "pub fn reconcile_stale_supervisor_status_content",
    ] {
        assert!(
            document_status.contains(required),
            "agent-doc-document must own pure status projection policy: {required}"
        );
    }

    let status_io = fs::read_to_string(manifest_dir.join("agent-doc-status-io/src/lib.rs"))
        .expect("status IO crate should exist");
    for required in [
        "pub trait StatusWriteEffects",
        "pub struct RuntimeStatusWriteEffects",
        "pub static RUNTIME_STATUS_WRITE_EFFECTS",
        "fn current_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "fn force_disk_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "pub fn set<E: StatusWriteEffects + ?Sized>",
        "pub fn set_with_runtime_options(",
        "pub fn set_with_options<E: StatusWriteEffects + ?Sized>",
        "agent_doc_document::status_projection::replace_status_content",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(file, source)",
        "agent_doc_write_converge_io::converge_or_disk_write(",
        "agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS",
        "agent_doc_document_realtime_io::record_document_write_provenance(file, updated)",
        "agent_doc_ops_log_io::log_op(file, message)",
        "effects.current_document_content(file, \"status_set\")",
        "effects.force_disk_document_content(file, \"status_set\")",
        "effects.converge_or_disk_write(file, &full_content, &new_doc, \"status_set\")",
        "effects.record_document_write_provenance(file, &new_doc)",
        "effects.log_op(",
        "agent_doc_hash::content_hash(&new_doc)",
    ] {
        assert!(
            status_io.contains(required),
            "agent-doc-status-io should own status writeback flow: {required}"
        );
    }
    let status_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-status-io/Cargo.toml")).unwrap();
    for required in [
        "agent-doc-document",
        "agent-doc-document-realtime-io",
        "agent-doc-hash",
        "agent-doc-ops-log-io",
        "agent-doc-write-converge-io",
    ] {
        assert!(
            status_io_manifest.contains(required),
            "agent-doc-status-io should depend on focused dependency {required}"
        );
    }
    for forbidden in [
        "agent-doc-orchestration",
        "agent-doc-git-io",
        "agent-doc-sqlite",
        "agent-doc-tmux-io",
    ] {
        assert!(
            !status_io_manifest.contains(forbidden),
            "agent-doc-status-io must not depend on orchestration-side systems: {forbidden}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/status_cmd.rs")
            .exists(),
        "orchestration must not keep a status_cmd facade module"
    );
    let orchestration_write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let status_adapter_start = orchestration_write
        .find("fn set_status_with_options")
        .expect("write.rs should define the status command helper");
    let status_adapter_end = orchestration_write
        .find("fn run_command(")
        .expect("write.rs should define run_command after the status helper");
    let status_adapter = &orchestration_write[status_adapter_start..status_adapter_end];
    assert!(
        !orchestration_write.contains("pub fn run_command("),
        "write.rs must not expose run_command as a public facade; CLI write/finalize should enter through the repair-owned recovery bridge"
    );
    for forbidden in [
        "struct WriteStatusEffects",
        "impl agent_doc_status_io::StatusWriteEffects for WriteStatusEffects",
        "const STATUS_EFFECTS",
    ] {
        assert!(
            !orchestration_write.contains(forbidden),
            "write.rs must not keep a private status runtime effects provider: {forbidden}"
        );
    }
    for forbidden in [
        "STALE_SUPERVISOR_STATUS_MARKER",
        "fn find_status_component",
        "element::parse",
        "replace_content(&full_content",
        "fn first_live_backlog_id",
        "fn extract_status_top_backlog_id",
        "fn replace_top_backlog_sentence",
        "fn reconcile_top_backlog_status_content",
        "fn apply_stale_supervisor_marker",
        "fn reconcile_stale_supervisor_status_content",
    ] {
        assert!(
            !status_adapter.contains(forbidden),
            "write status adapter must stay an effects adapter, not a status projection/writeback owner: {forbidden}"
        );
    }
    assert!(
        status_adapter.contains("agent_doc_status_io::set_with_runtime_options(")
            && !status_adapter.contains("agent_doc_status_io::set_with_options(&STATUS_EFFECTS"),
        "write status adapter should call focused status runtime IO directly"
    );
    for forbidden in [
        "agent_doc_document::status_projection::replace_status_content",
        "agent_doc_hash::content_hash",
        "std::fs::write(file",
        "std::fs::read_to_string(file)",
    ] {
        assert!(
            !status_adapter.contains(forbidden),
            "write status adapter must not re-own status writeback IO details: {forbidden}"
        );
    }

    for relative in [
        "agent-doc-compact-io/src/lib.rs",
        "agent-doc-repair-io/src/lib.rs",
        "agent-doc-element-backlog-io/src/backlog_cmd.rs",
        "agent-doc-preflight-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_document::status_projection::"),
            "{relative} should call focused document status projection directly"
        );
        assert!(
            !source.contains("status_cmd::reconcile")
                && !source.contains("status_cmd::STALE_SUPERVISOR_STATUS_MARKER"),
            "{relative} must not route status projection through status_cmd"
        );
    }
}

#[test]
fn test_legacy_overlay_merge_base_policy_is_not_on_the_hot_path() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        !document_lib.contains("pub mod model_projection;")
            && !manifest_dir
                .join("agent-doc-document/src/model_projection.rs")
                .exists(),
        "the legacy overlay model projection module must be deleted"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/snapshot.rs")
            .exists(),
        "orchestration must not keep a snapshot adapter that can re-own model projection policy"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-document-realtime/src/crdt_merge_base.rs")
            .exists(),
        "the legacy overlay-sidecar merge-base policy must be deleted"
    );
    let snapshot_io =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    let merge_io = fs::read_to_string(manifest_dir.join("agent-doc-merge-io/src/lib.rs")).unwrap();
    for forbidden in [
        "crdt_merge_base_state_with",
        "overlay_crdt_path_for",
        "write_overlay_crdt_state_file_from_markdown",
        "save_document_crdt",
        "multinode_crdt_state",
    ] {
        assert!(
            !snapshot_io.contains(forbidden),
            "snapshot IO retains {forbidden}"
        );
        assert!(
            !merge_io.contains(forbidden),
            "merge IO retains {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_snapshot_io_owns_durable_baselines_without_sidecar_fallback() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-snapshot-io\""),
        "workspace should include agent-doc-snapshot-io as the focused snapshot IO crate"
    );

    let snapshot_io =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn load_document_baseline(",
        "pub fn checkpoint_document_baseline(",
        "pub trait CrashStateEffects",
        "pub fn checkpoint_document_baseline_with_effects(",
        "effects.write_markdown_crash_state(doc, content)?;",
        "pub fn resolve(",
        "pub struct DiffBaselineStore",
        "impl agent_doc_diff_io::DocumentBaselineStore for DiffBaselineStore",
        "pub fn delete_recovery_projection_and_clear_baseline(",
        "pub fn ensure_initial_snapshot(",
        "pub fn detect_document_path_transition(",
        "pub fn checkpoint_undo_content(",
        "pub fn load_undo_content(",
        "pub fn clear_undo_content(",
        "pub fn load_crdt_recovery_projection(",
        "pub fn checkpoint_crdt_recovery_projection(",
        "pub fn clear_crdt_recovery_projection(",
        "agent_doc_secret_redact::redact(content)",
        "StateFact::UndoCheckpointed",
        "StateFact::CrdtRecoveryProjectionCheckpointed",
        "StateFact::CrdtRecoveryProjectionCleared",
        "agent_doc_project_root_io::project_root_containing(",
        "agent_doc_session_registry_io::lookup_entry_in(",
    ] {
        assert!(
            snapshot_io.contains(required),
            "agent-doc-snapshot-io must own model-baseline snapshot IO: {required}"
        );
    }
    for forbidden in [
        "std::fs::read_dir(snap_dir)",
        "find_snapshot_hash_for_session",
        "migrate_state_files_for_hash",
        "session_id_from_content(&snapshot_content)",
        "merge_document_state_for_path_transition_in_db",
        "rekey_actor_document_path_in_db",
        "update_session_file_in",
    ] {
        assert!(
            !snapshot_io.contains(forbidden),
            "snapshot IO must never recover authority from sidecars: {forbidden}"
        );
    }
    for relative in [
        "src/notify.rs",
        "src/patch.rs",
        "agent-doc-run-context-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in [
            "rc.snapshot_path_for()",
            "fn snapshot_path_for(&self)",
            "std::fs::write(&snap_abs",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} must checkpoint typed baseline state, not write a normal sidecar: {forbidden}"
            );
        }
    }

    let sqlite_store =
        fs::read_to_string(manifest_dir.join("agent-doc-sqlite/src/state_store.rs")).unwrap();
    for required in [
        "pub struct DocumentStateRekeyReport",
        "pub fn rekey_document_state_in_db(",
        "pub fn merge_document_state_for_path_transition_in_db(",
        "pub fn rekey_actor_document_path_in_db(",
        ".pointer_mut(\"/fact/document_hash\")",
        "DELETE FROM state_event_peer_acks",
    ] {
        assert!(
            sqlite_store.contains(required),
            "typed state rekey must be owned by the durable ledger: {required}"
        );
    }

    let document_init =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/document_init.rs"))
            .unwrap();
    for required in [
        "pub fn ensure_initialized(",
        "migrate_renamed_via_controller(doc)?",
        "agent_doc_snapshot_io::detect_document_path_transition(doc)?",
        "observe_document_path_transition(",
        "agent_doc_snapshot_io::ensure_initial_snapshot(",
        "agent_doc_element_exchange::strip_exchange_content",
        "ensure_git_tracked_with_commit(doc, commit)?",
        "agent_doc_git_io::status::is_tracked(doc)",
        "agent_doc_git_io::status::add(doc)",
    ] {
        assert!(
            document_init.contains(required),
            "workflow IO document initialization should compose focused snapshot/git IO: {required}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/snapshot.rs")
            .exists(),
        "orchestration must not keep a snapshot facade module"
    );
    for forbidden in [
        "pub fn save(doc:",
        "pub fn load(doc:",
        "pub fn resolve(doc:",
        "pub fn ensure_snapshot(",
        "pub fn try_migrate_renamed(",
        "pub fn crdt_merge_base_state(",
        "fn rebuild_overlay_to_baseline(",
        "pub struct DiffBaselineStore",
        "pub const DIFF_SNAPSHOT_STORE",
    ] {
        assert!(
            !document_init.contains(forbidden),
            "workflow IO initialization must not keep markdown read/resolve facades: {forbidden}"
        );
    }
    for forbidden in [
        "pub struct SnapshotLock",
        "pub fn delete(",
        "pub fn checkpoint_undo_content(",
        "pub fn load_undo_content(",
        "pub fn clear_undo_content(",
        "pub fn mps_enabled(",
        "pub fn load_crdt(",
        "pub fn load_overlay_crdt(",
        "pub fn save_crdt(",
        "pub fn save_overlay_crdt(",
        "pub fn load_multinode_crdt(",
        "pub fn save_multinode_crdt(",
        "pub fn delete_crdt(",
        "fn load_unlocked(",
        "fn save_unlocked(",
        "fn acquire_crdt_lock(",
        "fn write_crdt_state(",
        "fn probe_overlay_projection(",
        "let snapshot_content = strip_exchange_content(&content);",
        "const MIGRATE_DIRS",
        "std::fs::rename(&old_file, &new_file)?",
        "std::fs::read_dir(&snap_dir)?",
        "agent_doc_frontmatter::frontmatter::parse(&snap_content)",
        "agent_doc_session_registry_io::update_session_file_in(",
        "agent_doc_secret_redact::redact(content)",
        "let lock_path = agent_doc_fs::snapshot_flock_path_for(doc)?;",
        "let lock_path = agent_doc_fs::crdt_flock_path_for(doc)?;",
        "resolve_crdt_merge_base(",
        "event.log_message(doc.display())",
        "agent_doc_snapshot_io::with_crdt_lock(doc, ||",
        "project_overlay_roundtrip(",
        "overlay_state_from_markdown(",
        "fn rebuild_overlay_crdt_locked(",
        "agent_doc_snapshot_io::write_crdt_state_file(",
        "ModelBaselineSource::",
    ] {
        assert!(
            !document_init.contains(forbidden),
            "workflow IO initialization must not re-own model-baseline IO/policy: {forbidden}"
        );
    }
    for relative in [
        "src/undo.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-flow-io/src/closeout.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("agent_doc_snapshot_io::")
                && !source.contains("snapshot::checkpoint_undo_content(")
                && !source.contains("snapshot::load_undo_content(")
                && !source.contains("snapshot::clear_undo_content(")
                && !source.contains("crate::snapshot::checkpoint_undo_content(")
                && !source.contains("crate::snapshot::load_undo_content(")
                && !source.contains("crate::snapshot::clear_undo_content("),
            "{relative} should call focused snapshot IO directly for undo checkpoints"
        );
    }
    for relative in [
        "src/reset.rs",
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-compact-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(source.contains("agent_doc_snapshot_io::"));
        for forbidden in [
            "load_crdt(",
            "save_crdt(",
            "load_overlay_crdt(",
            "save_overlay_crdt(",
            "delete_crdt(",
        ] {
            assert!(
                !source.contains(forbidden),
                "{relative} retains legacy CRDT sidecar API {forbidden}"
            );
        }
    }
    let reset_source = fs::read_to_string(manifest_dir.join("src/reset.rs")).unwrap();
    assert!(
        reset_source.contains(
            "agent_doc_snapshot_io::delete_recovery_projection_and_clear_baseline(file)?"
        ) && !reset_source.contains("snapshot::delete(file)?"),
        "reset should clear the focused recovery projection and ledger baseline"
    );
}

#[test]
fn test_document_path_transition_writes_are_project_controller_owned() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let rename = fs::read_to_string(manifest_dir.join("src/rename.rs")).unwrap();
    assert!(
        rename.contains("new_document_path_transition_observation(")
            && rename.contains("observe_document_path_transition("),
        "the CLI rename path must publish one retained controller observation",
    );
    for forbidden in [
        "open_state_db(",
        "merge_document_state_for_path_transition_in_db(",
        "rekey_actor_document_path_in_db(",
        "RegistryLock::acquire(",
        "sync_tmux_layout",
    ] {
        assert!(
            !rename.contains(forbidden),
            "the short-lived rename caller must not own `{forbidden}`",
        );
    }

    let document_init =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/document_init.rs"))
            .unwrap();
    assert!(document_init.contains("detect_document_path_transition(doc)?"));
    assert!(document_init.contains("observe_document_path_transition("));
    assert!(
        !document_init.contains("open_state_db("),
        "mid-cycle rename detection must not race the controller's durable write",
    );
}

#[test]
fn test_agent_doc_stream_io_routes_document_reads_through_runtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let stream_source =
        fs::read_to_string(manifest_dir.join("agent-doc-stream-io/src/lib.rs")).unwrap();
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let capture_source =
        fs::read_to_string(manifest_dir.join("agent-doc-capture-io/src/lib.rs")).unwrap();
    let repair_pending_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/pending.rs")).unwrap();
    let orchestrate_dispatch_source =
        fs::read_to_string(manifest_dir.join("src/orchestrate/dispatch.rs")).unwrap();
    let stream_impl_start = main_source
        .find("impl agent_doc_stream_io::StreamRuntimeEffects for CliStreamRuntimeEffects")
        .expect("CLI stream effects implementation should exist");
    let stream_impl_end = stream_impl_start
        + main_source[stream_impl_start..]
            .find("fn queue_command_consume_outcome")
            .expect("queue command helper should follow stream effects implementation");
    let stream_impl = &main_source[stream_impl_start..stream_impl_end];

    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "effects.current_document_content(file, \"stream_run_initial\")",
        "effects.atomic_write(file, &content_original)?",
        "effects.current_document_content(file, \"stream_run_resume_update\")",
        "effects\n                    .current_document_content(file, \"stream_content_ours_fallback\")",
        "effects\n        .current_document_content(file, \"stream_flush_to_document\")",
        "effects.current_document_content(file, \"stream_partial_response_checkpoint\")",
        ".maybe_checkpoint_with_current_content(&checkpoint_text, &current_content)",
    ] {
        assert!(
            stream_source.contains(required),
            "agent-doc-stream-io should route document reads/writes through runtime authority effects: {required}"
        );
    }
    for forbidden in [
        "let raw_content = std::fs::read_to_string(file)",
        "std::fs::write(file, &content_original)",
        "let current = std::fs::read_to_string(file)",
        "std::fs::read_to_string(file).unwrap_or_default()",
        "let content_current = std::fs::read_to_string(file)",
    ] {
        assert!(
            !stream_source.contains(forbidden),
            "agent-doc-stream-io must not read/write the active document directly in production stream flow: {forbidden}"
        );
    }

    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> anyhow::Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "stream_save_pending_capture",
        "agent_doc_repair_io::pending::save_pending_with_current_content(",
        "agent_doc_document_realtime_io::atomic_write_through_authority(file, content)",
    ] {
        assert!(
            stream_impl.contains(required),
            "CLI stream effects must bind stream current-document authority to realtime IO: {required}"
        );
    }

    for required in [
        "pub fn capture_response_with_current_content(",
        "capture_response_with_current_content_and_intent(file, response, &file_content, None)",
        "pub fn maybe_checkpoint_with_current_content(",
        "checkpoint_partial_response_for_cycle_with_current_content(",
    ] {
        assert!(
            capture_source.contains(required),
            "capture IO should expose a caller-supplied current-content capture path: {required}"
        );
    }
    for required in [
        "orchestrate_partial_response_checkpoint",
        "checkpoint_writer\n                    .maybe_checkpoint_with_current_content(&response, &current_content)",
    ] {
        assert!(
            orchestrate_dispatch_source.contains(required),
            "orchestrated stream checkpoints should pass resolved current content to capture IO: {required}"
        );
    }
    assert!(
        repair_pending_source.contains("pub fn save_pending_with_current_content(")
            && repair_pending_source.contains(
                "agent_doc_template_io::canonicalize_response_for_capture_with_current_content("
            )
            && repair_pending_source.contains(
                "agent_doc_capture_io::capture_response_with_current_content_and_intent_and_plan("
            ),
        "repair pending IO should let realtime callers save pending captures without capture IO rereading the active document"
    );
}

#[test]
fn test_agent_doc_commit_io_marks_capture_committed_from_resolved_current_content() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let commit_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    let post_commit_cleanup =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/post_commit_cleanup.rs"))
            .unwrap();
    assert!(
        commit_source.contains("commit_current_document_content(file, \"commit_initial_current\")")
            && commit_source.contains("commit failed to resolve current document content")
            && !commit_source.contains(
                "commit_current_document_content(file, \"commit_initial_current\").unwrap_or_default()"
            ),
        "commit must fail explicitly when current-document resolution fails; it must not treat a controller timeout as an empty visible document"
    );
    // `#lazily-hot-path`: document closeout no longer takes a bespoke `flock`
    // commit lock. Commit serialization relies on git's own `index.lock` retries
    // (the hard safety net) instead of a repo-scoped `CommitLock`, so the lock
    // type must be gone entirely and current-document content must still resolve
    // before the git stage/commit transaction.
    assert!(
        !commit_source.contains("CommitLock"),
        "commit closeout must not use a bespoke flock commit lock (#lazily-hot-path: flock is never used for document closeout)"
    );
    let initial_current_idx = commit_source
        .find("commit_current_document_content(file, \"commit_initial_current\")")
        .expect("commit should resolve initial current document content");
    let stage_commit_idx = initial_current_idx
        + commit_source[initial_current_idx..]
            .find("match stage_and_commit_exact_paths_once(")
            .expect(
                "normal commit should run a git stage/commit transaction after authority resolve",
            );
    assert!(
        initial_current_idx < stage_commit_idx,
        "commit must resolve controller/current-document content before entering the git stage/commit transaction"
    );
    let impl_start = commit_source
        .find("impl agent_doc_git_io::post_commit_cleanup::PostCommitCleanupEffects")
        .expect("commit IO should implement post-commit cleanup effects");
    let impl_end = impl_start
        + commit_source[impl_start..]
            .find("fn reconcile_queue_continuation")
            .expect("queue continuation effect should follow capture effect");
    let post_commit_impl = &commit_source[impl_start..impl_end];

    for required in [
        "fn mark_capture_committed(&self, file: &Path, current_content: &str) -> Result<()>",
        "agent_doc_capture_io::mark_committed_with_current_content(file, current_content)",
    ] {
        assert!(
            post_commit_impl.contains(required),
            "commit IO should mark committed captures from already-resolved current content: {required}"
        );
    }
    assert!(
        !post_commit_impl.contains("agent_doc_capture_io::mark_committed(file)"),
        "commit IO post-commit cleanup must not reread active document content through capture IO when current content is available"
    );
    assert!(
        post_commit_impl.contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)")
            && !post_commit_impl.contains("agent_doc_cycle_state_io::load(file)"),
        "commit IO post-commit cleanup should use closeout projections before compatibility cycle sidecars"
    );
    for required in [
        "fn mark_capture_committed(&self, file: &Path, current_content: &str) -> Result<()>",
        "effects.mark_capture_committed(file, file_content)",
        "capture-state update skipped: current document content unavailable",
    ] {
        assert!(
            post_commit_cleanup.contains(required),
            "git post-commit cleanup should thread resolved current content into capture commit state: {required}"
        );
    }
}

#[test]
fn test_controller_serve_sanitizes_inherited_fds_in_child_process() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let controller_rpc_source = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    let run_serve_start = controller_rpc_source
        .find("pub fn run_serve(")
        .expect("controller run_serve entrypoint should exist");
    let serve_call = controller_rpc_source[run_serve_start..]
        .find("serve_with_options(")
        .expect("run_serve should call serve_with_options");
    let sanitize_call = controller_rpc_source[run_serve_start..]
        .find("sanitize_controller_serve_inherited_fds()")
        .expect("run_serve should sanitize inherited file descriptors");
    assert!(
        sanitize_call < serve_call,
        "controller serve must close inherited IDE file descriptors before opening the controller listener"
    );
    assert!(
        controller_rpc_source.contains("fn controller_serve_inherited_fds_to_close()")
            && controller_rpc_source.contains("std::fs::read_dir(\"/proc/self/fd\")")
            && controller_rpc_source.contains("controller_serve_inherited_fds_closed")
            && controller_rpc_source.contains("#[cfg(any(not(unix), test))]\nfn sanitize_controller_serve_inherited_fds() -> usize"),
        "controller child process should own a production fd sanitizer without closing test harness descriptors"
    );
}

#[test]
fn test_agent_doc_compact_io_routes_document_reads_through_runtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let compact_source =
        fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let compact_impl_start = main_source
        .find("impl agent_doc_compact_io::CompactRuntimeEffects for CliCompactRuntimeEffects")
        .expect("CLI compact effects implementation should exist");
    let compact_impl_end = compact_impl_start
        + main_source[compact_impl_start..]
            .find("static COMPACT_RUNTIME_EFFECTS")
            .expect("compact runtime static should follow compact effects implementation");
    let compact_impl = &main_source[compact_impl_start..compact_impl_end];

    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "fn force_disk_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "effects.current_document_content(file, \"compact_run_initial\")",
        "effects.force_disk_document_content(file, \"compact_run_initial_force_disk\")",
        "effects\n        .force_disk_document_content(file, \"compact_post_write_disk_verify\")",
        "let disk_projection = std::fs::read_to_string(file)",
        "\"compact_disk_projection_pending file={}",
        "pub fn complete_retained_projection(",
    ] {
        assert!(
            compact_source.contains(required),
            "agent-doc-compact-io should route document reads through named runtime authority effects: {required}"
        );
    }
    for forbidden in [
        "let content = std::fs::read_to_string(file)",
        "let disk_is_pre_compact = std::fs::read_to_string(file)",
        "let updated = std::fs::read_to_string(file)",
        "std::fs::read_to_string(file).is_ok_and",
    ] {
        assert!(
            !compact_source.contains(forbidden),
            "agent-doc-compact-io must not read the active document directly in compact flow: {forbidden}"
        );
    }

    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> anyhow::Result<String>",
        "fn force_disk_document_content(&self, file: &Path, source: &str) -> anyhow::Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(file, source)",
        "agent_doc_document_realtime_io::atomic_write_through_authority(file, content)",
    ] {
        assert!(
            compact_impl.contains(required),
            "CLI compact effects must bind compact document authority to realtime/disk IO explicitly: {required}"
        );
    }
}

#[test]
fn test_legacy_crdt_filesystem_sidecars_are_deleted_from_write_paths() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-merge-io\""),
        "workspace should include agent-doc-merge-io as the focused merge IO crate"
    );

    let merge_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-merge-io/Cargo.toml")).unwrap();
    assert!(merge_io_manifest.contains("agent-doc-merge"));

    let merge_io = fs::read_to_string(manifest_dir.join("agent-doc-merge-io/src/lib.rs")).unwrap();
    for forbidden in [
        "multinode_crdt_state",
        "save_document_crdt",
        "sidecar_projection",
        "overlay_crdt_path_for",
        "nodes.yrs",
    ] {
        assert!(
            !merge_io.contains(forbidden),
            "merge IO retains legacy sidecar behavior: {forbidden}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/snapshot.rs")
            .exists(),
        "orchestration must not keep a snapshot module that can re-own per-node CRDT sidecar adapters"
    );
    for relative in [
        "src/reset.rs",
        "agent-doc-compact-io/src/lib.rs",
        "agent-doc-stream-io/src/lib.rs",
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-flow-io/src/closeout.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-commit-io/src/lib.rs",
        "agent-doc-write-converge-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("save_document_crdt("),
            "{relative} must not persist CRDT filesystem sidecars"
        );
    }
    let write_converge =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn checkpoint_document_baseline(",
        "pub fn checkpoint_ipc_baseline_nonfatal(",
    ] {
        assert!(
            write_converge.contains(required),
            "agent-doc-write-converge-io should own IPC baseline persistence helper: {required}"
        );
    }
    let write_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    assert!(
        !write_ipc.contains("save_document_snapshot_and_crdt("),
        "write/ipc.rs should not keep the deleted snapshot/CRDT compatibility helper"
    );
    let write_ipc_transport =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/transport.rs")).unwrap();
    assert!(
        write_ipc_transport.contains("checkpoint_ipc_baseline_nonfatal(")
            && !write_ipc_transport.contains("save_document_crdt("),
        "write/ipc/transport.rs should checkpoint the baseline without filesystem CRDT projections"
    );
    let transient_cleanup_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/transient_cleanup.rs")).unwrap();
    assert!(
        !transient_cleanup_source.contains("save_document_crdt")
            && !transient_cleanup_source.contains("sidecar_lock"),
        "commit closeout must not contain CRDT sidecar compatibility logic"
    );
}

#[test]
fn test_agent_doc_document_owns_tracked_work_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let tracked_work =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/tracked_work_projection.rs"))
            .unwrap();
    for required in [
        "pub struct TrackedWorkFingerprint",
        "pub fn tracked_work_fingerprint",
    ] {
        assert!(
            tracked_work.contains(required),
            "agent-doc-document must own tracked-work projection policy: {required}"
        );
    }
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod tracked_work_projection;"),
        "agent-doc-document should expose tracked-work projection through its owning module"
    );
    let orchestration_preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_io =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let forbidden = "fn tracked_work_component_fingerprint(";
    assert!(
        !orchestration_preflight.contains(forbidden) && !preflight_io.contains(forbidden),
        "preflight must not re-own tracked-work projection policy: {forbidden}"
    );
    assert!(
        preflight_io
            .contains("agent_doc_document::tracked_work_projection::tracked_work_fingerprint")
            && preflight_io.contains(
                "agent_doc_document::tracked_work_projection::TrackedWorkFingerprint::empty"
            ),
        "preflight IO should call focused tracked-work projection policy directly"
    );
}

#[test]
fn test_agent_doc_document_owns_claim_scaffold_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let claim_scaffold =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/claim_scaffold.rs")).unwrap();
    for required in [
        "pub fn should_scaffold_empty_markdown",
        "pub fn render_empty_template_scaffold",
        "pub fn default_format_and_write_content",
        "pub fn uses_template_format",
        "pub fn scaffold_default_template_components",
        "pub fn merge_default_template_component_config",
    ] {
        assert!(
            claim_scaffold.contains(required),
            "agent-doc-document must own claim scaffold/defaulting policy: {required}"
        );
    }
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod claim_scaffold;"),
        "agent-doc-document should expose claim scaffold policy through its owning module"
    );

    let claim = fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    for forbidden in [
        "project_config::ComponentConfig",
        "frontmatter::set_format_and_write",
        "agent_doc_element::element::parse(&content)",
        "agent_doc_format: template\\nagent_doc_write: crdt",
    ] {
        assert!(
            !claim.contains(forbidden),
            "claim.rs must stay an IO adapter, not re-own claim scaffold policy: {forbidden}"
        );
    }
    assert!(
        claim.contains("use agent_doc_document::claim_scaffold::{")
            && claim.contains("should_scaffold_empty_markdown")
            && claim.contains("render_empty_template_scaffold")
            && claim.contains("merge_default_template_component_config"),
        "claim.rs should call focused document claim scaffold policy directly"
    );
}

#[test]
fn test_agent_doc_claim_io_routes_document_reads_through_runtime_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let claim_source = fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs"))
        .expect("agent-doc-claim-io source should exist");
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    let claim_impl_start = main_source
        .find("impl ClaimRuntimeEffects for CliClaimRuntimeEffects")
        .expect("CLI claim effects implementation should exist");
    let claim_impl_end = claim_impl_start
        + main_source[claim_impl_start..]
            .find("fn route_repair_closeout")
            .expect("route repair helper should follow claim effects implementation");
    let claim_impl = &main_source[claim_impl_start..claim_impl_end];

    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> Result<String>",
        "fn atomic_write(&self, file: &Path, content: &str) -> Result<()>",
        "let raw = effects.current_document_content(file, \"claim_empty_scaffold\")",
        "effects.atomic_write(file, &scaffold)?",
        "let (updated_content, session_id) = frontmatter::ensure_session(&content)?",
        "effects\n            .atomic_write(file, &updated_content)",
        "content = updated_content",
        "default_format_and_write_content(&content)?",
        "effects.atomic_write(file, &updated).with_context(",
        "content = updated",
        "scaffold_default_template_components(&content)?",
        "effects.atomic_write(file, &scaffolded).with_context(",
    ] {
        assert!(
            claim_source.contains(required),
            "agent-doc-claim-io should route active document reads/writes through runtime authority effects: {required}"
        );
    }
    for forbidden in [
        "std::fs::read_to_string(file)",
        "std::fs::write(file, &scaffold)",
        "std::fs::write(file, &updated_content)",
        "std::fs::write(file, &updated)",
        "std::fs::write(file, &scaffolded)",
    ] {
        assert!(
            !claim_source.contains(forbidden),
            "agent-doc-claim-io must not read/write the active document directly during claim flow: {forbidden}"
        );
    }

    for required in [
        "fn current_document_content(&self, file: &Path, source: &str) -> anyhow::Result<String>",
        "fn atomic_write(&self, file: &Path, content: &str) -> anyhow::Result<()>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "agent_doc_document_realtime_io::atomic_write_through_authority(file, content)",
    ] {
        assert!(
            claim_impl.contains(required),
            "CLI claim effects must bind claim document authority to realtime IO: {required}"
        );
    }
}

#[test]
fn test_agent_doc_repair_io_routes_force_disk_reads_through_document_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();

    for required in [
        "fn repair_current_document_content(",
        "agent_doc_document_realtime_io::resolve_disk_current_document(file, source)",
        "agent_doc_document_realtime_io::try_resolve_current_document_with_source(file, source)",
        "authority: current.authority()",
    ] {
        assert!(
            repair_source.contains(required),
            "repair IO should route current/force-disk document reads through named document authority helpers: {required}"
        );
    }
    assert!(
        !repair_source.contains("std::fs::read_to_string(file)"),
        "repair IO must not read the active document directly, including force-disk repair overrides"
    );
}

#[test]
fn test_agent_doc_write_runtime_run_entry_routes_document_reads_through_document_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let run_entry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .expect("write runtime run_entry source should exist");

    for required in [
        "fn resolve_current_document_content(file: &Path, source: &str) -> Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "fn resolve_disk_document_content(file: &Path, source: &str) -> Result<String>",
        "agent_doc_document_realtime_io::resolve_disk_current_document_content(file, source)",
        "fn resolve_document_content_for_write_mode(",
        "resolve_disk_document_content(file, disk_source)",
        "resolve_current_document_content(file, current_source)",
        "\"write_append_current_content\"",
        "\"write_append_force_disk_current_content\"",
        "\"write_append_merge_current_content\"",
        "\"write_append_force_disk_merge_current_content\"",
        "\"write_template_current_content\"",
        "\"write_template_force_disk_current_content\"",
        "\"write_template_merge_current_content\"",
        "\"write_template_force_disk_merge_current_content\"",
        "\"write_stream_current_content\"",
        "\"write_stream_force_disk_current_content\"",
        "\"write_stream_empty_patch_component_check\"",
        "\"write_stream_force_disk_empty_patch_component_check\"",
        "\"write_stream_merge_current_content\"",
        "\"write_stream_force_disk_merge_current_content\"",
        "resolve_current_document_content(file, \"write_ipc_current_content\")",
        "resolve_current_document_content(file, \"apply_append_from_string\")",
        "resolve_current_document_content(file, \"apply_append_from_string_current_content\")",
        "\"apply_template_from_string\"",
        "\"apply_template_from_string_force_disk_initial\"",
        "\"apply_template_from_string_current_content\"",
        "\"apply_template_from_string_force_disk_current_content\"",
    ] {
        assert!(
            run_entry_source.contains(required),
            "write-runtime run_entry should route document reads through the named current/disk document authority split: {required}"
        );
    }
    for forbidden in [
        "std::fs::read_to_string(file)",
        "agent_doc_document_realtime_io::try_resolve_current_doc_from_file(",
    ] {
        assert!(
            !run_entry_source.contains(forbidden),
            "write-runtime run_entry must not bypass the current/disk document authority helpers: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_document_owns_compact_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let compact_projection =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/compact_projection.rs"))
            .unwrap();
    for required in [
        "pub struct CompactExchange",
        "pub struct NonExchangeMarkerChange",
        "pub fn parse_inline_exchanges",
        "pub fn build_inline_compacted_document",
        "pub fn split_component_content_at_boundary",
        "pub fn malformed_compact_summary_lines",
        "pub fn non_exchange_opening_markers",
        "pub fn changed_non_exchange_opening_markers",
    ] {
        assert!(
            compact_projection.contains(required),
            "agent-doc-document must own compact projection policy: {required}"
        );
    }
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod compact_projection;"),
        "agent-doc-document should expose compact projection through its owning module"
    );

    let compact = fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn parse_exchanges(",
        "fn build_compacted(",
        "fn split_component_content_at_boundary(",
        "pub fn malformed_compact_summary_lines(",
        "fn non_exchange_opening_markers(",
        "fn changed_non_exchange_opening_markers(",
    ] {
        assert!(
            !compact.contains(forbidden),
            "compact.rs must stay an IO/archive adapter, not re-own compact projection policy: {forbidden}"
        );
    }
    assert!(
        compact.contains("use agent_doc_document::compact_projection::{")
            && compact.contains("parse_inline_exchanges")
            && compact.contains("build_inline_compacted_document")
            && compact.contains("changed_non_exchange_opening_markers"),
        "compact.rs should call focused compact projection policy directly"
    );
}

#[test]
fn test_agent_doc_document_owns_transient_marker_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let transient_markers =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/transient_markers.rs"))
            .unwrap();
    for required in [
        "pub fn strip_boundary_markers(",
        "pub fn strip_head_markers(",
        "pub fn strip_guard_markers(",
        "pub fn normalize_transient_agent_doc_markers(",
        "pub fn neutralize_queue_component",
        "pub fn strip_queue_active_frontmatter",
        "pub fn normalize_for_replay_hash",
        "pub fn replay_content_hash",
        "pub fn strip_re_heading_attribution(",
        "pub fn normalize_post_commit_re_heading_drift(",
        "pub fn strip_exchange_prompt_prefixes_for_compare",
        "pub fn exchange_prompt_prefix_equivalent",
        "pub fn stale_agent_response_collapse_exchange",
        "pub fn repair_stale_agent_response_collapse_doc",
    ] {
        assert!(
            transient_markers.contains(required),
            "agent-doc-document must own transient marker document policy: {required}"
        );
    }
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod transient_markers;"),
        "agent-doc-document should expose transient marker policy through its owning module"
    );

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git/normalize.rs")
            .exists(),
        "orchestration must not keep the old git normalization facade"
    );

    for relative in [
        "agent-doc-preflight-command-io/src/lib.rs",
        "agent-doc-session-check-io/src/command.rs",
        "agent-doc-session-check-io/src/detect.rs",
        "agent-doc-session-check-io/src/closeout_guards.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-write-converge-io/src/convergence_fixture_tests.rs",
        "agent-doc-template-io/src/response_materialization_io.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-write-runtime-io/src/ipc/transport.rs",
        "agent-doc-flow-io/src/closeout.rs",
        "agent-doc-run-context-io/src/lib.rs",
        "agent-doc-document-realtime-io/src/lib.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-cycle-state-io/src/lib.rs",
        "agent-doc-start-runtime-io/src/idle_watch.rs",
        "agent-doc-document-realtime/src/write_policy.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("crate::git::normalize_transient_agent_doc_markers")
                && !source.contains("crate::git::strip_guard_markers")
                && !source.contains("crate::git::normalize_for_replay_hash")
                && !source.contains("git::normalize_transient_agent_doc_markers")
                && !source.contains("git::strip_guard_markers")
                && !source.contains("git::normalize_for_replay_hash"),
            "{relative} must call focused transient marker policy directly, not through git"
        );
    }
    for relative in [
        "agent-doc-repair-io/src/lib.rs",
        "agent-doc-cycle-state-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("replay_content_hash"),
            "{relative} should call focused replay-normalized content hashing directly"
        );
        assert!(
            !source.contains("fn normalized_content_hash("),
            "{relative} must not re-own replay-normalized content hashing"
        );
    }

    let git_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    assert!(
        !git_source.contains("mod normalize;") && !git_source.contains("pub use normalize"),
        "commit-io must call document commit normalization directly, not keep a facade module"
    );
    let git_pre_stage_repair =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/pre_stage_repair.rs")).unwrap();
    let git_transient_cleanup =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/transient_cleanup.rs")).unwrap();
    assert!(
        git_pre_stage_repair.contains("exchange_prompt_prefix_equivalent")
            && git_transient_cleanup.contains("repair_stale_agent_response_collapse_doc")
            && !git_source.contains("repair_stale_agent_response_collapse_doc"),
        "git-io pre-stage repair and transient cleanup should call focused transient-marker repair policy"
    );
    let realtime_write_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime/src/write_policy.rs"))
            .unwrap();
    for forbidden in [
        "pub fn normalize_transient_agent_doc_markers(",
        "fn normalize_transient_agent_doc_markers(",
        "pub fn neutralize_queue_component(",
        "fn neutralize_queue_component(",
        "pub fn strip_queue_active_frontmatter(",
        "fn strip_queue_active_frontmatter(",
        "pub fn normalize_for_replay_hash(",
        "fn normalize_for_replay_hash(",
        "pub fn normalize_post_commit_re_heading_drift(",
        "fn normalize_post_commit_re_heading_drift(",
        "fn strip_re_heading_attribution(",
        "fn strip_boundary_markers(",
    ] {
        assert!(
            !realtime_write_policy.contains(forbidden),
            "transient marker policy must not be re-owned outside agent-doc-document: {forbidden}"
        );
    }
    for forbidden in [
        "fn strip_head_markers(",
        "fn strip_guard_markers(",
        "fn code_block_byte_ranges(",
        "fn neutralize_queue_component(",
        "fn strip_queue_active_frontmatter(",
        "fn normalize_for_replay_hash(",
        "fn strip_exchange_prompt_prefixes_for_compare(",
        "fn exchange_prompt_prefix_equivalent(",
        "fn exchange_component(doc: &str)",
        "fn first_hash_id(",
        "fn normalized_response_heading_key(",
        "fn normalized_exchange_inventory_line(",
        "fn exchange_line_counts(",
        "fn current_exchange_is_committed_line_subset(",
        "fn exchange_has_blockquoted_prompt_for_id(",
        "fn stale_agent_response_collapse_exchange(",
        "fn repair_stale_agent_response_collapse_doc(",
    ] {
        assert!(
            !git_source.contains(forbidden),
            "git must not re-own transient marker stripping policy: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_prompt_lines_owns_prompt_line_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let prompt_lines =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-lines/src/lib.rs")).unwrap();
    for required in [
        "pub fn parse_slash_command_candidate",
        "pub fn line_looks_like_slash_command",
        "pub fn text_line_looks_like_prompt_target",
        "pub fn normalized_prompt_preview_line",
        "pub fn line_looks_like_fresh_prompt_after_response",
        "pub fn line_looks_like_soft_prompt_request",
        "pub fn line_looks_like_prompt_prefix_repair_start",
        "pub fn line_looks_like_targeted_prompt_prefix_repair_start",
        "pub fn line_looks_like_targeted_or_prefixed_prompt_repair_start",
        "pub fn line_looks_like_plain_response_after_prompt",
        "pub fn looks_like_imperative_directive",
        "pub fn normalize_imperative_candidate",
        "pub fn parse_markdown_list_item",
        "pub fn line_looks_like_markdown_list_item",
    ] {
        assert!(
            prompt_lines.contains(required),
            "agent-doc-prompt-lines must own pure prompt-line policy: {required}"
        );
    }
    let prompt_lines_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-prompt-lines/Cargo.toml")).unwrap();
    assert!(
        prompt_lines_manifest.contains("name = \"agent-doc-prompt-lines\""),
        "prompt-line policy should live in its focused crate"
    );
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        !document_lib.contains("pub mod prompt_lines;")
            && !manifest_dir
                .join("agent-doc-document/src/prompt_lines.rs")
                .exists(),
        "agent-doc-document must not keep a prompt-line facade"
    );

    let diff_source = fs::read_to_string(manifest_dir.join("agent-doc-diff/src/lib.rs")).unwrap();
    for forbidden in [
        "pub fn text_line_looks_like_prompt_target",
        "fn line_looks_like_prompt_target",
        "fn parse_slash_command_candidate",
        "fn normalize_imperative_candidate",
        "fn parse_markdown_list_item",
        "const APPROVAL_WORDS",
    ] {
        assert!(
            !diff_source.contains(forbidden),
            "agent-doc-diff must use prompt-line policy directly, not keep a facade: {forbidden}"
        );
    }

    let exchange_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-element-exchange/src/lib.rs")).unwrap();
    for forbidden in [
        "pub fn starts_prompt_run_after_response",
        "pub fn starts_targeted_prompt_repair_after_response",
        "pub fn starts_targeted_or_prefixed_prompt_repair_after_response",
    ] {
        assert!(
            !exchange_lib.contains(forbidden),
            "exchange must not keep old prompt-line compatibility wrappers: {forbidden}"
        );
    }
}

#[test]
fn test_agent_doc_document_owns_commit_normalization_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let commit_normalization =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/commit_normalization.rs"))
            .unwrap();
    for required in [
        "pub fn canonicalize_answered_prompt_prefixes",
        "pub fn normalize_committed_exchange_artifacts",
        "pub fn normalize_component_content_for_absorb",
        "pub fn redact_component_contents_for_absorb",
    ] {
        assert!(
            commit_normalization.contains(required),
            "agent-doc-document must own pure commit normalization policy: {required}"
        );
    }
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod commit_normalization;"),
        "agent-doc-document should expose commit normalization through its owning module"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git/normalize.rs")
            .exists(),
        "orchestration must not retain the old git normalization module or facade"
    );

    let git_policy_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git/src/lib.rs")).unwrap();
    let commit_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    for required in [
        "pub fn relative_to_root(",
        "pub fn is_index_lock_contention_text(",
        "pub fn render_git_process_output(",
        "pub fn parse_porcelain_path(",
        "pub struct RecoveryTag",
        "pub fn doc_stem(",
        "pub fn parse_recovery_tags(",
        "pub fn has_blocking_non_exchange_component_drift(",
    ] {
        assert!(
            git_policy_source.contains(required),
            "agent-doc-git must own pure git command/path policy: {required}"
        );
    }
    for forbidden in [
        "mod normalize;",
        "pub use normalize",
        "pub fn normalize_committed_exchange_artifacts",
        "pub(crate) fn normalize_component_content_for_absorb",
        "pub(crate) fn redact_component_contents_for_absorb",
        "pub(crate) fn canonicalize_answered_prompt_prefixes",
        "fn relative_to(",
        "fn is_index_lock_contention_text(",
        "fn render_git_output(",
        "fn has_non_exchange_component_drift(",
        "fn has_non_exchange_component_drift_scoped(",
        "fn non_exchange_change_is_turn_independent(",
    ] {
        assert!(
            !commit_io_source.contains(forbidden),
            "commit-io must stay a coordinator, not re-own commit normalization: {forbidden}"
        );
    }
    assert!(
        commit_io_source.contains("normalize_committed_exchange_artifacts")
            && fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/boundary_reposition.rs"))
                .unwrap()
                .contains("canonicalize_answered_prompt_prefixes"),
        "commit coordinator and git-io boundary reposition should import focused commit normalization directly"
    );
    assert!(
        commit_io_source.contains("use agent_doc_git::{"),
        "commit coordinator should import focused git command/path policy directly"
    );
    assert!(
        commit_io_source.contains("has_blocking_non_exchange_component_drift("),
        "commit coordinator should call focused non-exchange component drift policy directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git.rs")
            .exists()
            && commit_io_source.contains("pub fn commit_with_outcome("),
        "orchestration git facade should be deleted and commit-io should own the default commit API"
    );

    let partial_staging =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/partial_staging.rs"))
            .unwrap();
    let git_io_partial_staging =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/partial_staging.rs")).unwrap();
    for required in [
        "pub struct PartialStagingDiffEvidence",
        "pub struct PartialStagingFinding",
        "pub fn candidate_repos(",
        "pub fn diff_evidence(",
        "pub fn companion_findings(",
        "agent_doc_git::parse_porcelain_path",
        "agent_doc_diff::partial_staging_companion_finding(",
    ] {
        assert!(
            git_io_partial_staging.contains(required),
            "agent-doc-git-io must own partial-staging git evidence/finding adapter: {required}"
        );
    }
    let git_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/Cargo.toml")).unwrap();
    assert!(
        git_io_manifest.contains("agent-doc-diff ="),
        "agent-doc-git-io should compose partial-staging git evidence with focused diff policy"
    );
    assert!(
        !partial_staging.contains("fn parse_porcelain_path(")
            && !partial_staging.contains("pub(crate) fn parse_porcelain_path(")
            && !partial_staging.contains("pub use agent_doc_git::parse_porcelain_path")
            && !partial_staging.contains("pub(crate) use agent_doc_git::parse_porcelain_path")
            && !partial_staging.contains("use agent_doc_git::parse_porcelain_path")
            && !partial_staging.contains("pub(crate) fn git_toplevel(")
            && !partial_staging.contains("pub(crate) fn git_name_lines(")
            && !partial_staging.contains("pub(crate) fn git_stdout(")
            && !partial_staging.contains("std::process::Command::new(\"git\")")
            && !partial_staging.contains("agent_doc_git_io::partial_staging::candidate_repos(")
            && !partial_staging.contains("agent_doc_git_io::partial_staging::diff_evidence("),
        "partial_staging must stay an orchestration adapter, not re-own partial-staging git evidence/finding IO"
    );
    assert!(
        partial_staging.contains("agent_doc_git_io::partial_staging::companion_findings("),
        "partial_staging should call focused git IO partial-staging finding assembly directly"
    );

    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-git-io\""),
        "agent-doc-git-io should be a workspace member"
    );
    assert!(
        workspace_manifest.contains("agent-doc-git-io = { path = \"agent-doc-git-io\""),
        "CLI shell should depend on git IO directly"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    for forbidden in ["pub mod checkpoint;", "pub mod git_sibling;"] {
        assert!(
            !orchestration_lib.contains(forbidden),
            "orchestration must not expose a git IO facade: {forbidden}"
        );
    }

    let checkpoint_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/checkpoint.rs")).unwrap();
    for forbidden in [
        "pub struct RecoveryTag",
        "fn doc_stem(",
        "fn parse_recovery_tags(",
        "pub use agent_doc_git::RecoveryTag",
        "pub(crate) use agent_doc_git::RecoveryTag",
        "agent_doc_orchestration::",
    ] {
        assert!(
            !checkpoint_source.contains(forbidden),
            "git IO checkpoint must stay a git command adapter, not re-own or facade recovery tag policy: {forbidden}"
        );
    }
    assert!(
        checkpoint_source
            .contains("use agent_doc_git::{RecoveryTag, doc_stem, parse_recovery_tags};"),
        "git IO checkpoint should import focused recovery tag policy directly"
    );
    for required in [
        "pub fn create_pre_mutation_tag(",
        "pub const KEEP_RECOVERY_TAGS",
        "pub fn prune_old_recovery_tags(",
    ] {
        assert!(
            checkpoint_source.contains(required),
            "git IO checkpoint must own recovery checkpoint tag pruning: {required}"
        );
    }
    let compact_source =
        fs::read_to_string(manifest_dir.join("agent-doc-compact-io/src/lib.rs")).unwrap();
    assert!(
        compact_source.contains("agent_doc_git_io::checkpoint::create_pre_mutation_tag(")
            && !compact_source.contains("pub fn create_pre_mutation_tag(")
            && !compact_source.contains("fn create_pre_compact_tag("),
        "compact must call the focused git IO checkpoint tag creation adapter directly"
    );
    let gc_source = fs::read_to_string(manifest_dir.join("agent-doc-gc-io/src/lib.rs")).unwrap();
    assert_source_mentions_all(
        &gc_source,
        "agent-doc-gc-io",
        &["agent_doc_git_io::checkpoint", "prune_old_recovery_tags"],
    );
    assert_source_omits_all(
        &gc_source,
        "agent-doc-gc-io",
        &["fn clean_old_recovery_tags(", "const KEEP_RECOVERY_TAGS"],
    );

    let sibling_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/sibling.rs")).unwrap();
    assert!(
        sibling_source.contains("pub fn commit_siblings_for_session_doc("),
        "git IO should own sibling commit I/O"
    );
    assert!(
        !sibling_source.contains("agent_doc_orchestration::"),
        "git IO sibling commits must not reach back through orchestration"
    );

    let git_io_lib = fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/lib.rs")).unwrap();
    assert!(
        git_io_lib.contains("pub mod dirs;"),
        "agent-doc-git-io should expose git directory/path IO helpers"
    );
    assert!(
        git_io_lib.contains("pub mod partial_staging;"),
        "agent-doc-git-io should expose partial-staging git evidence IO helpers"
    );
    assert!(
        git_io_lib.contains("pub mod submodule;"),
        "agent-doc-git-io should expose submodule pointer drift IO helpers"
    );
    assert!(
        git_io_lib.contains("pub mod transaction;"),
        "agent-doc-git-io should expose commit transaction IO helpers"
    );
    let git_branch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/branch.rs")).unwrap();
    assert!(
        git_branch_source.contains("pub fn create_session_branch(")
            && git_branch_source.contains("agent_doc_git::agent_doc_branch_name_for_file(file)")
            && git_branch_source.contains("checkout_new_or_existing(&git_root, &branch_name)"),
        "agent-doc-git-io branch module must own session branch assembly"
    );
    let git_squash_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/squash.rs")).unwrap();
    assert!(
        git_squash_source.contains("pub fn squash_session(")
            && git_squash_source.contains("agent_doc_git::relative_to_root(&resolved, &git_root)")
            && git_squash_source
                .contains("squash_agent_doc_commits(&git_root, &pathspec, &message)?"),
        "agent-doc-git-io squash module must own session squash assembly"
    );
    let git_revision_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/revision.rs")).unwrap();
    for required in ["pub enum RecentCommitLog", "pub fn recent_commit_lines("] {
        assert!(
            git_revision_source.contains(required),
            "agent-doc-git-io revision must own recent commit log IO: {required}"
        );
    }
    for required in [
        "pub enum HeadWorktreeFallback",
        "pub fn head_fallback_when_differs_from_worktree(",
        "last_commit_mtime(file).unwrap_or(None)",
        "show_head(file)?",
        "std::fs::read_to_string(file).unwrap_or_default()",
    ] {
        assert!(
            git_revision_source.contains(required),
            "agent-doc-git-io revision must own HEAD/worktree fallback recovery decisions: {required}"
        );
    }
    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    assert!(
        preflight_source.contains("agent_doc_git_io::revision::recent_commit_lines("),
        "preflight linked-doc checks should call focused git revision IO"
    );
    let git_submodule_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/submodule.rs")).unwrap();
    for required in [
        "pub fn is_submodule_pointer_stale(",
        "pub fn submodule_pointer_drift(",
        "agent_doc_git::SubmodulePointerDrift",
        "narrow_to_submodule(&super_root, &resolved)",
        "revision::rev_parse(&git_root, \"HEAD\")?",
        "revision::rev_parse(&super_root, &parent_spec)?",
        "SubmodulePointerDrift {",
    ] {
        assert!(
            git_submodule_source.contains(required),
            "agent-doc-git-io submodule module must own parent gitlink drift IO: {required}"
        );
    }
    let git_transaction_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/transaction.rs")).unwrap();
    for required in [
        "pub fn update_parent_submodule_pointer(",
        "pub enum CommitTransactionError",
        "pub fn stage_and_commit_once(",
        "pub fn stage_and_commit_exact_paths_once(",
        "crate::index::hash_object(git_root, &staged_content)",
        "for cacheinfo in &cacheinfos",
        ".args([\"update-index\", \"--add\", \"--cacheinfo\", cacheinfo])",
        "GIT_INDEX_FILE",
        "\"commit-tree\"",
        "\"update-ref\", \"HEAD\"",
        "RetryableHeadMoved",
    ] {
        assert!(
            git_transaction_source.contains(required),
            "agent-doc-git-io transaction module must own commit transaction IO: {required}"
        );
    }
    assert!(
        !git_transaction_source.contains("struct CommitLock")
            && !git_transaction_source.contains("try_lock_exclusive()")
            && git_transaction_source.contains("output_has_index_lock_contention(&output)"),
        "commit transaction must not take a bespoke advisory commit lock (#lazily-hot-path: flock is never used for document closeout); git index-lock retries are the hard safety net"
    );
    assert!(
        !git_transaction_source.contains("agent_doc_orchestration::"),
        "git transaction IO must not reach back through orchestration"
    );
    let snapshot_source =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    assert!(
        snapshot_source
            .contains("agent_doc_git_io::revision::head_fallback_when_differs_from_worktree(doc)?")
            && snapshot_source.contains("HeadWorktreeFallback::DiffersFromCurrent")
            && snapshot_source.contains("HeadWorktreeFallback::MatchesCurrent")
            && snapshot_source.contains("HeadWorktreeFallback::NoHead"),
        "agent-doc-snapshot-io resolve should adapt focused git HEAD/worktree fallback decisions"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/snapshot.rs")
            .exists(),
        "orchestration must not keep a snapshot module that can re-own git HEAD/worktree fallback recovery decisions"
    );
    let snapshot_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/Cargo.toml")).unwrap();
    assert!(
        snapshot_io_manifest.contains("agent-doc-git-io ="),
        "agent-doc-snapshot-io should compose snapshot sidecars with focused git revision/status IO"
    );
    let snapshot_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    for required in [
        "pub enum SnapshotCommitStatus",
        "pub fn snapshot_commit_status_from_contents(",
        "pub fn verify_snapshot_committed(",
        "agent_doc_git_io::status::is_in_git_repo(file)",
        "agent_doc_git_io::revision::show_head(file)?",
        "normalize_transient_agent_doc_markers",
    ] {
        assert!(
            snapshot_io_source.contains(required),
            "agent-doc-snapshot-io must own snapshot-vs-HEAD commit verification: {required}"
        );
    }
    for forbidden in [
        "pub enum SnapshotCommitStatus",
        "pub fn verify_snapshot_committed(",
    ] {
        assert!(
            !commit_io_source.contains(forbidden),
            "commit-io must not re-own snapshot-vs-HEAD commit verification: {forbidden}"
        );
    }
    let git_dirs_source =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/dirs.rs")).unwrap();
    for required in [
        "pub fn absolute_git_dir_at",
        "pub fn git_toplevel_at",
        "pub fn git_superproject_at",
        "pub fn resolve_absolute_file_path",
        "pub fn resolve_to_git_root",
        "pub fn resolve_pane_cwd",
        "pub fn workspace_access_dirs_for_doc",
        "pub fn append_workspace_access_args",
    ] {
        assert!(
            git_dirs_source.contains(required),
            "agent-doc-git-io must own git directory/path IO helper: {required}"
        );
    }
    let agent_mod_source =
        fs::read_to_string(manifest_dir.join("agent-doc-agent-io/src/agent/mod.rs")).unwrap();
    assert!(
        !agent_mod_source.contains("pub fn append_workspace_access_args"),
        "orchestration agent module must not facade git workspace access arg assembly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git/dirs.rs")
            .exists(),
        "orchestration must not retain a git dirs shim module"
    );
    assert!(
        commit_io_source.contains("dirs::{narrow_to_submodule, resolve_to_git_root}")
            && commit_io_source.contains("transaction::{"),
        "commit coordinator should import focused git IO helpers directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git.rs")
            .exists()
            && commit_io_source.contains("pub struct CommitCoordinatorPorts"),
        "orchestration git adapter should be deleted and focused commit coordinator should own ports"
    );
    let doctor_source =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/doctor.rs")).unwrap();
    let closeout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-flow-io/src/closeout.rs")).unwrap();
    let detect_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/detect.rs")).unwrap();
    let session_check_source =
        fs::read_to_string(manifest_dir.join("agent-doc-session-check-io/src/command.rs")).unwrap();
    let preflight_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    let preflight_run_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/run.rs")).unwrap();
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let repair_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    let git_post_commit_cleanup =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/post_commit_cleanup.rs"))
            .unwrap();
    let graph_source =
        fs::read_to_string(manifest_dir.join("agent-doc-run-context-io/src/lib.rs")).unwrap();
    assert!(
        graph_source.contains("agent_doc_snapshot_io::snapshot_commit_status_from_contents(")
            && !graph_source.contains("normalize_transient_agent_doc_markers"),
        "orchestration graph should cache snapshot/HEAD inputs but call focused snapshot IO for comparison"
    );
    assert!(
        commit_io_source.contains("agent_doc_git_io::submodule::is_submodule_pointer_stale(file)")
            && git_post_commit_cleanup.contains("crate::revision::show_rev(file, \"HEAD^\")")
            && commit_io_source.contains("agent_doc_git_io::revision::show_head(file)?")
            && write_source.contains("agent_doc_git_io::revision::show_head(file)")
            && write_source.contains("agent_doc_git_io::status::is_in_git_repo(file)")
            && repair_io_source.contains("agent_doc_git_io::status::is_in_git_repo(file)")
            && repair_io_source.contains("agent_doc_git_io::revision::show_head(file)?")
            && graph_source.contains("agent_doc_git_io::status::is_in_git_repo(&path)")
            && graph_source.contains("agent_doc_git_io::revision::show_head(&canonical)")
            && doctor_source.contains("agent_doc_git_io::status::tracked_modified_paths(file)")
            && doctor_source.contains("agent_doc_git_io::submodule::submodule_pointer_drift(file)")
            && closeout_source
                .contains("agent_doc_git_io::submodule::submodule_pointer_drift(file)")
            && detect_source.contains("agent_doc_git_io::submodule::submodule_pointer_drift(file)")
            && session_check_source
                .contains("agent_doc_git_io::status::tracked_side_effect_note(file)?")
            && preflight_io_source
                .contains("agent_doc_git_io::revision::last_commit_mtime(&resolved)")
            && preflight_run_source
                .contains("agent_doc_git_io::revision::last_commit_mtime(&doc_path)"),
        "runtime callers should use focused git IO status/submodule/revision helpers directly"
    );
    for forbidden in [
        "mod dirs;",
        "pub use dirs",
        "pub mod dirs",
        "pub fn resolve_pane_cwd",
        "pub fn create_branch",
        "pub fn squash_session",
        "pub fn tracked_modified_paths",
        "pub fn is_in_git_repo",
        "pub fn is_submodule_pointer_stale",
        "pub fn submodule_pointer_drift",
        "pub fn last_commit_mtime",
        "pub fn show_head",
        "fn show_rev(",
        "fn stage_snapshot_for_commit(",
        "fn stage_and_commit_once(",
        "fn update_parent_submodule_pointer(",
        "enum CommitTransactionError",
        "struct CommitLock",
        "pub(crate) fn tracked_side_effect_note(",
    ] {
        assert!(
            !commit_io_source.contains(forbidden),
            "commit-io must not facade git directory/path IO: {forbidden}"
        );
    }
    assert!(
        !session_check_source.contains("pub(crate) fn tracked_side_effect_note("),
        "session_check.rs must call focused git status IO directly"
    );
    for forbidden in [
        "fn git_rev_parse(",
        "let parent_spec = format!(\"HEAD:{rel}\");",
        "revision::rev_parse(&git_root, \"HEAD\")?",
        "revision::rev_parse(&super_root, &parent_spec)?",
    ] {
        assert!(
            !commit_io_source.contains(forbidden),
            "commit-io must not re-own submodule pointer drift IO: {forbidden}"
        );
    }

    let main = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        main.contains("agent_doc_git_io::checkpoint::run("),
        "checkpoint command should call git IO directly"
    );
    assert!(
        !main.contains("agent_doc_orchestration::checkpoint::"),
        "checkpoint command must not route through orchestration"
    );

    let write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    assert!(
        write.contains("agent_doc_git_io::sibling::commit_siblings_for_session_doc"),
        "write commit flow should call git IO sibling commits directly"
    );
    assert!(
        !write.contains("crate::git_sibling::"),
        "write commit flow must not route sibling commits through orchestration"
    );

    for relative in [
        "agent-doc-flow-io/src/closeout.rs",
        "agent-doc-session-check-io/src/closeout_guards.rs",
        "agent-doc-write-converge-io/src/convergence_fixture_tests.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-document-realtime/src/write_policy.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            !source.contains("crate::git::normalize_committed_exchange_artifacts")
                && !source.contains("crate::git::normalize_component_content_for_absorb")
                && !source.contains("crate::git::redact_component_contents_for_absorb"),
            "{relative} must call focused commit normalization directly, not through git"
        );
    }
}

#[test]
fn test_agent_doc_document_owns_singleton_component_repair_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod singleton_repair;"),
        "agent-doc-document should expose singleton repair through its owning module"
    );

    let singleton_repair =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/singleton_repair.rs"))
            .unwrap();
    for required in [
        "pub struct DuplicateSingletonComponentRepair",
        "pub fn repair_duplicate_singleton_components(",
        "fn canonical_singleton_component_name(",
        "fn singleton_components_by_name(",
        "fn component_block",
    ] {
        assert!(
            singleton_repair.contains(required),
            "agent-doc-document must own duplicate singleton component repair policy: {required}"
        );
    }
    assert!(
        !singleton_repair.contains("agent_doc_orchestration::"),
        "singleton repair policy must not reach back through orchestration"
    );

    let write_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    let write_converge =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn canonical_singleton_component_name(",
        "fn singleton_components_by_name(",
        "fn component_block(",
        "fn repair_duplicate_singleton_components(",
    ] {
        assert!(
            !write_ipc.contains(forbidden),
            "write IPC must not re-own singleton component repair policy: {forbidden}"
        );
    }
    assert!(
        write_converge.contains(
            "agent_doc_document::singleton_repair::repair_duplicate_singleton_components("
        ),
        "write-converge IO should call focused singleton repair policy directly"
    );
}

#[test]
fn test_agent_doc_document_owns_write_normalization_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod write_normalization;"),
        "agent-doc-document should expose write normalization through its owning module"
    );
    assert!(
        !document_lib.contains("pub use write_normalization"),
        "agent-doc-document should not add a write-normalization root facade"
    );

    let write_normalization =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/write_normalization.rs"))
            .unwrap();
    for required in [
        "pub fn cleanup_resolved_backlog_prompts_after_response(",
        "pub fn remove_prompt_target_blocks_from_body(",
        "pub fn latest_response_block_missing_from_current(",
        "pub fn splice_response_block_into_current_exchange(",
        "pub fn lift_pending_from_exchange(",
        "pub fn strip_boundary_for_dedup(",
        "pub fn splice_pending_component(",
        "pub fn count_code_fence_openings(",
    ] {
        assert!(
            write_normalization.contains(required),
            "agent-doc-document must own write normalization policy: {required}"
        );
    }
    assert!(
        !write_normalization.contains("agent_doc_orchestration::"),
        "write normalization policy must not reach back through orchestration"
    );

    let write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn normalized_prompt_line(",
        "fn prompt_target_lines(",
        "fn prompt_target_matches_at(",
        "fn remove_prompt_target_blocks_from_body(",
        "fn prompt_targets_added_to_backlog(",
        "fn cleanup_resolved_backlog_prompts_after_response(",
        "fn latest_response_block_missing_from_current(",
        "fn latest_response_block_from_exchange_body(",
        "fn splice_response_block_into_current_exchange(",
        "pub fn lift_pending_from_exchange(",
        "fn strip_boundary_for_dedup(",
        "fn splice_pending_component(",
        "fn count_code_fence_openings(",
    ] {
        assert!(
            !write.contains(forbidden),
            "write.rs must not re-own write normalization policy: {forbidden}"
        );
    }
    assert!(
        write.contains("use agent_doc_document::write_normalization::{"),
        "write.rs should call focused write normalization policy directly"
    );
}

#[test]
fn test_agent_doc_document_owns_queue_in_progress_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_projection =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/queue_projection.rs"))
            .unwrap();
    for required in [
        "pub fn set_in_progress_work_item_markers(",
        "pub fn sync_in_progress_marker_regions(",
        "pub fn strip_in_progress_marker(",
        "pub fn strip_priority_markers(",
    ] {
        assert!(
            queue_projection.contains(required),
            "agent-doc-document must own queue in-progress document projection policy: {required}"
        );
    }

    let maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden in [
        "fn set_in_progress_work_item_markers(",
        "fn sync_in_progress_marker_regions(",
    ] {
        assert!(
            !maintenance.contains(forbidden),
            "preflight maintenance must not re-own queue in-progress projection policy: {forbidden}"
        );
    }
    assert!(
        maintenance.contains("set_in_progress_work_item_markers")
            && maintenance.contains("sync_in_progress_marker_regions"),
        "preflight maintenance should call focused queue in-progress projection policy directly"
    );
}

#[test]
fn test_agent_doc_element_exchange_owns_exchange_prompt_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let exchange_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-element-exchange/src/lib.rs")).unwrap();
    for required in [
        "pub fn exchange_content_len",
        "pub fn exchange_content",
        "pub fn exchange_component",
        "pub fn insert_prompt_line_before_boundary",
        "pub fn append_deduped_content_to_exchange",
        "pub fn strip_exchange_content",
        "pub fn redact_exchange_component_content",
        "pub fn post_commit_ipc_reposition_only_exchange_safe",
        "pub fn normalized_prompt_text",
        "pub fn is_markdown_heading_line",
        "pub fn normalized_prompt_counts",
        "pub fn split_line_segment",
        "pub fn is_code_fence_delimiter",
        "pub fn response_aware_user_prompt_counts",
        "pub fn user_prompt_count_growth",
        "pub fn exchange_has_live_user_edit",
        "pub struct ExchangeShrinkGuardBlock",
        "pub fn exchange_shrink_guard_block",
        "pub fn live_exchange_without_visible_write_retry_required",
        "pub fn exchange_prompt_prefix_count",
        "pub fn exchange_prompt_text_duplicated",
        "pub fn normalization_target_counts",
        "pub fn exchange_user_region",
        "pub fn is_exchange_response_heading_for_prefix_repair",
        "pub fn is_prefixed_exchange_response_heading_for_prefix_repair",
        "pub fn normalization_target_matches_line",
        "pub fn exchange_prompt_prefix_eligible_lines",
        "pub struct PromptLineInfo",
        "pub fn exchange_prompt_reconciliation_infos",
        "pub fn prompt_reconciliation_counts",
        "pub fn last_exchange_boundary_tail_start",
        "pub fn probable_live_prompt_prefix_variant",
        "pub fn dedupe_live_prompt_prefix_variants_in_exchange_tail",
        "pub fn dedupe_live_prompt_prefix_variants_in_doc",
        "pub fn dedupe_adjacent_prompt_prefix_duplicates_in_exchange",
        "pub fn dedupe_adjacent_prompt_prefix_duplicates_in_doc",
        "pub fn dedupe_prompt_lines_against_before_exchange",
        "pub fn dedupe_prompt_lines_against_before_doc",
        "pub fn response_precedes_prompt_in_exchange",
        "pub fn repair_response_precedes_prompt_in_exchange",
        "pub fn strip_prompt_prefix_from_response_body_first_lines",
        "pub fn extract_post_commit_normalization_targets",
        "pub fn normalize_exchange_prefixes_for_targets",
        "pub fn normalization_prefix_observation_counts",
        "pub fn duplicate_prompt_line_count",
        "pub fn extract_normalization_targets",
        "pub fn normalize_user_prompts_in_exchange",
        "pub fn preserve_head_exchange_prompt_prefix_state",
        "pub fn verify_visible_normalization",
    ] {
        assert!(
            exchange_lib.contains(required),
            "agent-doc-element-exchange must own exchange prompt/content policy: {required}"
        );
    }

    let orchestration_cargo = read_retired_orchestration_artifact(manifest_dir, "Cargo.toml");
    assert!(
        orchestration_cargo.contains("agent-doc-element-exchange"),
        "orchestration must depend on the focused exchange element crate directly"
    );

    let exchange_io =
        fs::read_to_string(manifest_dir.join("agent-doc-element-exchange-io/src/lib.rs")).unwrap();
    assert!(
        exchange_io.contains("pub fn check_exchange_shrink_guard_with_log(")
            && !exchange_io
                .contains("file_ipc_consumed_without_live_exchange_visible_write_with_log"),
        "exchange IO must own the shrink guard without a file-delivery adapter"
    );
    let snapshot_source =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow-io/src/document_init.rs"))
            .unwrap();
    assert!(
        snapshot_source.contains("agent_doc_element_exchange::strip_exchange_content"),
        "workflow document initialization should import exchange stripping policy from the focused crate"
    );
    let claim_source =
        fs::read_to_string(manifest_dir.join("agent-doc-claim-io/src/lib.rs")).unwrap();
    assert!(
        !claim_source.contains("fn strip_exchange_content(")
            && !claim_source.contains("pub fn strip_exchange_content("),
        "claim.rs must not retain the old exchange stripping helper path"
    );

    let write_normalize =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/write_normalize.rs"))
            .unwrap();
    assert!(
        write_normalize.contains("use agent_doc_element_exchange::{"),
        "write normalization should import exchange prefix policy from the focused crate"
    );

    let write_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    assert!(
        write_ipc
            .contains("use agent_doc_element_exchange::normalize_exchange_prefixes_for_targets;"),
        "write IPC should import exchange prefix policy from the focused crate"
    );

    let write_ipc_transport =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/transport.rs")).unwrap();
    let write_ipc_io =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/lib.rs")).unwrap();
    let realtime_write_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime/src/write_policy.rs"))
            .unwrap();
    assert!(
        write_ipc_io.contains("normalize_patch_content")
            && realtime_write_policy.contains("use agent_doc_element_exchange::{")
            && realtime_write_policy.contains("normalization_target_counts"),
        "write IPC payload synthesis should call realtime patch normalization, and realtime should import exchange prefix policy from the focused crate"
    );

    let write_main =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    assert!(
        write_main.contains("use agent_doc_element_exchange::{"),
        "write.rs should import exchange prompt/order policy from the focused crate"
    );
    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    assert!(
        write_run_entry.contains("use agent_doc_element_exchange::extract_normalization_targets;"),
        "write run entry should import normalization target extraction from the focused crate"
    );
    assert!(
        write_run_entry
            .contains("agent_doc_element_exchange_io::check_exchange_shrink_guard_with_log(")
            && !write_run_entry
                .contains("file_ipc_consumed_without_live_exchange_visible_write_with_log(")
            && !write_ipc_transport
                .contains("file_ipc_consumed_without_live_exchange_visible_write_with_log("),
        "write adapters should call focused exchange IO without a file-IPC compatibility path"
    );
    assert!(
        !write_main.contains("mod exchange_reconcile"),
        "orchestration write must not keep an exchange_reconcile facade module"
    );
    let repair = fs::read_to_string(manifest_dir.join("agent-doc-repair-io/src/lib.rs")).unwrap();
    assert!(
        repair.contains(
            "agent_doc_element_exchange::strip_prompt_prefix_from_response_body_first_lines"
        ),
        "repair IO should import response-body prompt-prefix repair from the focused crate directly"
    );
    let commit_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    let git_post_commit_cleanup =
        fs::read_to_string(manifest_dir.join("agent-doc-git-io/src/post_commit_cleanup.rs"))
            .unwrap();
    assert!(
        git_post_commit_cleanup.contains(
            "use agent_doc_element_exchange::post_commit_ipc_reposition_only_exchange_safe;"
        ) && !commit_io_source.contains(
            "use agent_doc_element_exchange::post_commit_ipc_reposition_only_exchange_safe;"
        ),
        "git post-commit cleanup should import exchange-only reposition policy from the focused crate"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git.rs")
            .exists()
            && !commit_io_source.contains("fn redact_exchange_component_content(")
            && !commit_io_source.contains("fn post_commit_ipc_reposition_only_exchange_safe(")
            && !git_post_commit_cleanup
                .contains("fn post_commit_ipc_reposition_only_exchange_safe("),
        "orchestration git facade must be gone and commit/git IO must not re-own exchange-only post-commit IPC policy"
    );
    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    assert!(
        orchestrate_source
            .contains("agent_doc_element_exchange::insert_prompt_line_before_boundary")
            && !orchestrate_source.contains("fn inject_prompt_into_doc(")
            && !orchestrate_source.contains("starts_with(\"<!-- agent:boundary:\")"),
        "src/orchestrate.rs should adapt file IO and delegate exchange prompt insertion to agent-doc-element-exchange"
    );

    let orchestration_policy_sources = [
        ("write.rs", write_main),
        ("write_normalize.rs", write_normalize),
        ("write/run_entry.rs", write_run_entry),
        ("write/ipc.rs", write_ipc),
        ("write/ipc/transport.rs", write_ipc_transport),
        ("repair.rs", repair),
    ];
    for forbidden in [
        "pub(crate) fn extract_exchange_content_len",
        "pub(crate) fn exchange_content(",
        "pub(crate) fn normalized_prompt_text",
        "pub(crate) fn is_markdown_heading_line",
        "pub(crate) fn normalized_prompt_counts",
        "pub(crate) fn split_line_segment",
        "pub(crate) fn is_exchange_code_fence_delimiter",
        "pub(crate) fn response_aware_user_prompt_counts",
        "pub(crate) fn user_prompt_count_growth",
        "pub(crate) fn exchange_has_live_user_edit",
        "pub(crate) struct ExchangeShrinkGuardBlock",
        "pub(crate) fn exchange_shrink_guard_block",
        "pub(crate) fn live_exchange_without_visible_write_retry_required",
        "pub(crate) fn exchange_prompt_prefix_count",
        "pub(crate) fn exchange_prompt_text_duplicated",
        "pub(crate) fn exchange_user_region",
        "pub(crate) fn is_exchange_response_heading_for_prefix_repair",
        "pub(crate) fn is_prefixed_exchange_response_heading_for_prefix_repair",
        "pub(crate) fn normalization_target_matches_line",
        "pub(crate) fn starts_prompt_run_after_response",
        "pub(crate) fn starts_targeted_prompt_repair_after_response",
        "pub(crate) fn starts_targeted_or_prefixed_prompt_repair_after_response",
        "pub(crate) fn exchange_prompt_prefix_eligible_lines",
        "pub(crate) struct PromptLineInfo",
        "pub(crate) fn exchange_prompt_reconciliation_infos",
        "pub(crate) fn prompt_reconciliation_counts",
        "pub(crate) fn last_exchange_boundary_tail_start",
        "pub(crate) fn probable_live_prompt_prefix_variant",
        "pub(crate) fn dedupe_live_prompt_prefix_variants_in_exchange_tail",
        "pub(crate) fn dedupe_live_prompt_prefix_variants_in_doc",
        "pub(crate) fn dedupe_adjacent_prompt_prefix_duplicates_in_exchange",
        "pub(crate) fn dedupe_adjacent_prompt_prefix_duplicates_in_doc",
        "pub(crate) fn dedupe_prompt_lines_against_before_exchange",
        "pub(crate) fn dedupe_prompt_lines_against_before_doc",
        "struct ExchangeLineSegment",
        "fn split_exchange_line_segments",
        "fn line_is_exchange_boundary",
        "fn normalized_response_signature_lines",
        "fn exchange_response_block_matches_signature",
        "fn find_response_precedes_prompt_candidate",
        "fn response_precedes_prompt_in_exchange",
        "pub fn repair_response_precedes_prompt_in_exchange",
        "fn normalized_non_boundary_exchange_lines",
        "fn exchange_contains_normalized_line_sequence",
        "pub fn strip_prompt_prefix_from_response_body_first_lines(",
        "pub(crate) fn strip_prompt_prefix_from_response_body_first_lines(",
        "write::strip_prompt_prefix_from_response_body_first_lines",
        "pub use strip_prompt_prefix_from_response_body_first_lines",
        "pub fn extract_post_commit_normalization_targets",
        "pub fn normalize_exchange_prefixes_for_targets",
        "pub fn normalization_prefix_observation_counts",
        "pub fn duplicate_prompt_line_count",
        "pub(crate) fn normalization_prefix_observation_counts",
        "pub(crate) fn duplicate_prompt_line_count",
        "pub fn extract_normalization_targets(",
        "pub fn normalize_user_prompts_in_exchange(",
        "pub(crate) fn preserve_head_exchange_prompt_prefix_state(",
        "pub fn preserve_head_exchange_prompt_prefix_state(",
        "pub fn verify_visible_normalization(",
        "pub(crate) fn normalization_target_counts",
    ] {
        for (path, source) in &orchestration_policy_sources {
            assert!(
                !source.contains(forbidden),
                "{path} must stay an adapter, not re-own or facade exchange element policy: {forbidden}"
            );
        }
    }
}

#[test]
fn test_agent_doc_element_backlog_owns_active_identity_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let backlog_source =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog/src/backlog.rs")).unwrap();
    for required in [
        "pub fn document_active_identities",
        "pub fn detect_identity_collisions",
        "pub fn identity_collision_for_new_id",
        "pub fn ensure_new_item_explicit_id_available",
    ] {
        assert!(
            backlog_source.contains(required),
            "agent-doc-element-backlog must own active tracked-work identity policy: {required}"
        );
    }

    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        !document_lib.contains("active_identity"),
        "agent-doc-document must not keep an active_identity facade after tracked-work identity policy moves"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-document/src/active_identity.rs")
            .exists(),
        "agent-doc-document must not keep the old active_identity module as a facade"
    );

    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_warnings =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/warnings.rs")).unwrap();
    let workflow_preflight_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/preflight_policy.rs"))
            .unwrap();
    for forbidden in [
        "pub fn document_active_identities",
        "pub fn detect_identity_collisions",
        "pub fn identity_collision_for_new_id",
        "fn document_active_identities",
        "fn detect_identity_collisions",
        "fn identity_collision_for_new_id",
    ] {
        assert!(
            !preflight.contains(forbidden),
            "preflight must stay a warning adapter, not an active identity policy facade: {forbidden}"
        );
    }
    assert!(
        workflow_preflight_policy
            .contains("agent_doc_element_backlog::backlog::detect_identity_collisions"),
        "workflow preflight policy should call focused active identity collision detection directly"
    );
    assert!(
        preflight_warnings
            .contains("agent_doc_workflow::preflight_policy::preset_item_id_collision_warning",),
        "focused preflight warnings should call the workflow identity warning policy directly"
    );

    let backlog_cmd =
        fs::read_to_string(manifest_dir.join("agent-doc-element-backlog-io/src/backlog_cmd.rs"))
            .unwrap();
    assert!(
        backlog_cmd.contains("backlog::ensure_new_item_explicit_id_available"),
        "backlog_cmd should call focused active identity collision enforcement directly"
    );
    assert!(
        !preflight.contains("agent_doc_document::active_identity")
            && !backlog_cmd.contains("agent_doc_document::active_identity"),
        "orchestration must not call the old document active_identity facade"
    );
    assert!(
        !backlog_cmd.contains("crate::preflight::identity_collision_for_new_id"),
        "backlog_cmd must not route active identity policy through preflight"
    );
}

#[test]
fn test_agent_doc_element_boundary_owns_boundary_id_lookup() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    assert!(
        workspace_manifest.contains("\"agent-doc-boundary-io\""),
        "agent-doc-boundary-io should be a workspace member"
    );
    assert!(
        workspace_manifest.contains("agent-doc-boundary-io = { path = \"agent-doc-boundary-io\""),
        "CLI shell should depend on boundary IO directly"
    );

    let orchestration_lib = read_retired_orchestration_artifact(manifest_dir, "src/lib.rs");
    assert!(
        !orchestration_lib.contains("pub mod boundary_io;"),
        "orchestration must not expose a boundary_io facade"
    );

    let boundary_io =
        fs::read_to_string(manifest_dir.join("agent-doc-boundary-io/src/lib.rs")).unwrap();
    let boundary_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-boundary-io/Cargo.toml")).unwrap();
    let boundary_io_manifest: toml::Value = toml::from_str(&boundary_io_manifest).unwrap();
    let boundary_io_dependencies = boundary_io_manifest["dependencies"].as_table().unwrap();
    assert!(
        boundary_io.contains("pub fn run(file: &Path, component: Option<&str>)"),
        "agent-doc-boundary-io should own the boundary CLI file-I/O path"
    );
    assert!(
        boundary_io_dependencies.contains_key("agent-doc-document-realtime-io"),
        "boundary IO should depend on realtime document authority for active document mutation"
    );
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"boundary_insert\"",
        "agent_doc_document_realtime_io::atomic_write_through_authority(file, &updated)",
    ] {
        assert!(
            boundary_io.contains(required),
            "boundary IO should route active document mutation through realtime authority: {required}"
        );
    }
    for forbidden in [
        "std::fs::read_to_string(file)",
        "std::fs::write(&tmp",
        "std::fs::rename(&tmp",
        "file.with_extension(\"boundary.tmp\")",
    ] {
        assert!(
            !boundary_io.contains(forbidden),
            "boundary IO must not directly read/write active document content: {forbidden}"
        );
    }
    assert!(
        !boundary_io.contains("agent_doc_orchestration::"),
        "boundary IO must not reach back through orchestration"
    );

    let main = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        main.contains("agent_doc_boundary_io::run(&file, component.as_deref())"),
        "boundary command should call the focused IO crate directly"
    );
    assert!(
        !main.contains("agent_doc_orchestration::boundary_io::"),
        "boundary command must not route through orchestration"
    );

    let boundary =
        fs::read_to_string(manifest_dir.join("agent-doc-element-boundary/src/boundary.rs"))
            .unwrap();
    assert!(
        boundary.contains("pub fn find_boundary_id("),
        "agent-doc-element-boundary must own document-level boundary id lookup"
    );

    for relative_path in [
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/ipc/transport.rs",
        "agent-doc-commit-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        for forbidden_snippet in [
            "pub fn find_boundary_id(",
            "fn find_boundary_id(",
            "crate::write::find_boundary_id",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative_path} must not re-own or facade boundary id lookup: {forbidden_snippet}"
            );
        }
    }
}

#[test]
fn test_agent_doc_element_registry_has_no_base_type_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let registry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-element-registry/src/lib.rs")).unwrap();
    for forbidden in [
        "pub use agent_doc_element::{",
        "pub use agent_doc_element::ElementAuthority",
        "pub use agent_doc_element::ElementDescriptor",
        "pub use agent_doc_element::ElementRegistration",
    ] {
        assert!(
            !registry_source.contains(forbidden),
            "agent-doc-element-registry should compose built-ins, not re-export base element types: {forbidden}"
        );
    }
    for required in [
        "pub const BUILT_IN_ELEMENTS",
        "pub fn built_in_elements(",
        "pub fn find_built_in(",
        "pub fn descriptor_for(",
        "pub fn built_in_registrations(",
    ] {
        assert!(
            registry_source.contains(required),
            "agent-doc-element-registry should still own built-in registry composition: {required}"
        );
    }

    let document_models =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/element_models.rs")).unwrap();
    assert!(
        document_models.contains("use agent_doc_element::{")
            && !document_models.contains("use agent_doc_element_registry::{"),
        "agent-doc-document should import base element types directly and use registry only for built-in composition"
    );
}

#[test]
fn test_agent_doc_document_owns_markdown_outline_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let outline_projection =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/outline_projection.rs"))
            .unwrap();
    for required in [
        "pub struct MarkdownOutlineSection",
        "pub fn project_markdown_outline",
        "pub fn render_markdown_outline_text",
        "fn collect_headings",
    ] {
        assert!(
            outline_projection.contains(required),
            "agent-doc-document must own pure markdown outline projection: {required}"
        );
    }
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod outline_projection;"),
        "agent-doc-document should expose outline projection through its owning module"
    );

    assert!(
        !manifest_dir.join("src/outline.rs").exists(),
        "root crate must not keep the old outline parser module or facade"
    );
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        !main_source.contains("mod outline;") && !main_source.contains("outline::run"),
        "root main must route outline through the adapter, not the old parser module"
    );

    let adapter = fs::read_to_string(manifest_dir.join("src/outline_cmd.rs")).unwrap();
    for forbidden in [
        "pulldown_cmark",
        "fn parse_sections",
        "fn collect_headings",
        "struct Section",
    ] {
        assert!(
            !adapter.contains(forbidden),
            "outline_cmd must stay an IO/stdout adapter, not re-own outline projection: {forbidden}"
        );
    }
    assert!(
        adapter.contains("agent_doc_document::outline_projection::project_markdown_outline")
            && adapter
                .contains("agent_doc_document::outline_projection::render_markdown_outline_text"),
        "outline_cmd should call focused document outline projection directly"
    );

    let root_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let root_toml: toml::Value = toml::from_str(&root_manifest).unwrap();
    let root_deps = root_toml["dependencies"].as_table().unwrap();
    assert!(
        root_deps.contains_key("agent-doc-document"),
        "root CLI adapter should depend on focused document projection crate"
    );
    assert!(
        !root_deps.contains_key("pulldown-cmark"),
        "root crate must not depend on pulldown-cmark after outline projection extraction"
    );

    let document_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-document/Cargo.toml")).unwrap();
    let document_toml: toml::Value = toml::from_str(&document_manifest).unwrap();
    let document_deps = document_toml["dependencies"].as_table().unwrap();
    assert!(
        document_deps.contains_key("pulldown-cmark"),
        "agent-doc-document should own markdown parser dependency for outline projection"
    );
}

#[test]
fn test_agent_doc_document_owns_watch_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let _: fn(&str) -> String =
        agent_doc_document::watch_projection::strip_boundaries_for_watch_hash;
    let _: fn(&str) -> String = agent_doc_document::watch_projection::watch_content_hash;
    let _: fn(&str, u64, &str) -> String =
        agent_doc_document::watch_projection::file_watch_event_id;
    let _: fn(Option<&str>, &str) -> Vec<agent_doc_markdown_ast::events::DocumentNodeEvent> =
        agent_doc_document::watch_projection::project_watch_node_events;
    let _: fn(&agent_doc_markdown_ast::events::DocumentNodeEvent) -> serde_json::Value =
        agent_doc_document::watch_projection::document_node_event_json;
    let _: fn(&str, &[agent_doc_markdown_ast::events::DocumentNodeEvent]) -> serde_json::Value =
        agent_doc_document::watch_projection::document_node_events_payload;

    let watch_projection =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/watch_projection.rs"))
            .unwrap();
    assert_source_mentions_all(
        &watch_projection,
        "agent-doc-document watch projection",
        &[
            "strip_boundaries_for_watch_hash",
            "watch_content_hash",
            "file_watch_event_id",
            "project_watch_node_events",
            "document_node_event_json",
            "document_node_events_payload",
        ],
    );
    let document_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-document/src/lib.rs")).unwrap();
    assert!(
        document_lib.contains("pub mod watch_projection;"),
        "agent-doc-document should expose watch projection through its owning module"
    );

    let document_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-document/Cargo.toml")).unwrap();
    let document_toml: toml::Value = toml::from_str(&document_manifest).unwrap();
    let document_deps = document_toml["dependencies"].as_table().unwrap();
    assert!(
        document_deps.contains_key("agent-doc-hash")
            && document_deps.contains_key("agent-doc-markdown-ast")
            && document_deps.contains_key("serde_json"),
        "watch projection should keep its hash, AST, and JSON dependencies in agent-doc-document"
    );

    let watch_daemon =
        fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/daemon.rs")).unwrap();
    assert_source_mentions_all(
        &watch_daemon,
        "watch daemon",
        &[
            "agent_doc_document::watch_projection",
            "watch_content_hash",
            "project_watch_node_events",
            "document_node_events_payload",
        ],
    );
    assert_source_omits_all(
        &watch_daemon,
        "watch daemon",
        &[
            "fn hash_content(",
            "fn strip_boundaries_for_hash(",
            "fn node_event_json(",
            "fn file_watch_event_id(",
            "pub use agent_doc_document::watch_projection",
        ],
    );

    let watch_io = fs::read_to_string(manifest_dir.join("agent-doc-watch-io/src/lib.rs")).unwrap();
    assert_source_mentions_all(
        &watch_io,
        "agent-doc-watch-io",
        &[
            "agent_doc_document::watch_projection",
            "file_watch_event_id",
            "generation",
            "content_hash",
        ],
    );
    assert_source_mentions_all(&watch_io, "agent-doc-watch-io", &["is_running"]);
    assert_source_mentions_all(&watch_daemon, "watch daemon", &["is_running"]);
    assert_source_omits_all(&watch_daemon, "watch daemon", &["pub fn is_running("]);
    assert_source_mentions_all(
        &watch_io,
        "agent-doc-watch-io",
        &[
            "WatchWriteProvenance::new",
            "StateFact::FileWatchChangeObserved",
            "observe_document_event",
        ],
    );

    let watch_effects = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert_source_mentions_all(
        &watch_effects,
        "CLI watch effects",
        &[
            "agent_doc_watch_io::observe_document_event",
            "agent_doc_controller_io::project_controller::publish_state_event",
            "document_actor_in",
        ],
    );
    assert_source_omits_all(
        &watch_effects,
        "CLI watch effects",
        &[
            "file_watch_event_id",
            "agent_doc_hash::content_hash",
            "WatchWriteProvenance",
            "WatcherRegistry",
            "pub fn registry(",
            "fn file_watch_event_id(",
            "pub use agent_doc_document::watch_projection",
            "pub struct DocumentWatchGate",
            "pub type RawWatchEvent",
            "pub type WatchDelivery",
            "pub type DocumentWatchGate",
            "pub use agent_doc_document_realtime::watch_authority",
        ],
    );
}

#[test]
fn test_automatic_state_event_routes_use_controller_reactive_ingress() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    for relative in [
        "agent-doc-document-realtime-io/src/lib.rs",
        "agent-doc-preflight-io/src/lib.rs",
        "agent-doc-compact-io/src/lib.rs",
        "agent-doc-queue-io/src/queue_consume.rs",
        "src/main.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        assert!(
            source.contains("project_controller::publish_state_event"),
            "{relative} must publish automatic facts through the live controller"
        );
    }

    let controller =
        fs::read_to_string(manifest_dir.join("agent-doc-controller-io/src/project_controller.rs"))
            .unwrap();
    assert!(
        controller.contains("pub(crate) fn append_state_event("),
        "the raw durable append must remain private to controller-io"
    );
    assert!(
        !controller.contains("\npub fn append_state_event("),
        "external runtime crates must not regain a raw durable append route"
    );

    let rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        !rpc.contains("record_visible_write_commit_candidate_direct"),
        "visible-write publication must fail closed instead of bypassing the live projection"
    );
}

#[test]
fn test_agent_doc_document_realtime_owns_ack_mismatch_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime_write_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime/src/write_policy.rs"))
            .unwrap();
    for required in [
        "pub enum AckMismatchRecovery",
        "pub fn classify_socket_receipt_mismatch_recovery",
    ] {
        assert!(
            realtime_write_policy.contains(required),
            "agent-doc-document-realtime must own ACK-mismatch recovery policy: {required}"
        );
    }

    let write_converge_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    let convergence_fixture_source = fs::read_to_string(
        manifest_dir.join("agent-doc-write-converge-io/src/convergence_fixture_tests.rs"),
    )
    .unwrap();
    for forbidden in [
        "enum AckMismatchRecovery",
        "fn classify_socket_receipt_mismatch_recovery",
        "fn missing_agent_response_block",
        "fn stale_queue_prompt_exchange_artifact",
        "fn blank_components_named",
    ] {
        assert!(
            !write_converge_source.contains(forbidden)
                && !convergence_fixture_source.contains(forbidden),
            "write convergence layers must not re-own ACK-mismatch recovery policy: {forbidden}"
        );
    }
    assert!(
        write_converge_source.contains("agent_doc_document_realtime::write_policy::{")
            && write_converge_source.contains("classify_socket_receipt_mismatch_recovery("),
        "agent-doc-write-converge-io should call the focused realtime ACK-mismatch policy directly"
    );
}

#[test]
fn test_agent_doc_document_realtime_owns_safe_mutation_classification() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime_write_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime/src/write_policy.rs"))
            .unwrap();
    for required_snippet in [
        "pub fn classify_safe_out_of_band_agent_doc_mutation",
        "pub fn classify_committed_historical_agent_doc_mutation",
        "pub fn detect_reintroduced_reaped_pending_ids",
        "pub fn is_empty_template_scaffold_snapshot",
        "pub fn is_safe_user_follow_up_exchange_growth",
    ] {
        assert!(
            realtime_write_policy.contains(required_snippet),
            "agent-doc-document-realtime must own safe mutation classification: {required_snippet}"
        );
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git/safe_mutation.rs")
            .exists(),
        "agent-doc-orchestration must not keep a safe_mutation policy module"
    );

    let commit_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "mod safe_mutation",
        "pub use safe_mutation",
        "fn classify_safe_out_of_band_agent_doc_mutation",
        "fn classify_committed_historical_agent_doc_mutation(",
        "classify_committed_historical_agent_doc_mutation_policy",
        "fn detect_reintroduced_reaped_pending_ids",
        "fn is_empty_template_scaffold_snapshot",
        "fn is_safe_user_follow_up_exchange_growth",
    ] {
        assert!(
            !commit_io_source.contains(forbidden_snippet),
            "commit-io must not define or reexport safe mutation classification: {forbidden_snippet}"
        );
    }
    assert!(
        commit_io_source.contains("agent_doc_document_realtime::write_policy::{")
            && commit_io_source.contains("classify_safe_out_of_band_agent_doc_mutation")
            && commit_io_source.contains("classify_committed_historical_agent_doc_mutation"),
        "commit coordinator should call the focused realtime safe mutation policy directly"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git.rs")
            .exists()
            && commit_io_source.contains("pub fn commit_with_outcome("),
        "orchestration git facade should be deleted and commit-io should own commit lifecycle policy"
    );
}

#[test]
fn test_lazily_current_and_state_db_own_snapshot_persistence() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let snapshot =
        fs::read_to_string(manifest_dir.join("agent-doc-snapshot-io/src/lib.rs")).unwrap();
    assert!(snapshot.contains("pub fn load_document_baseline("));
    assert!(snapshot.contains("pub fn checkpoint_document_baseline("));
    assert!(snapshot.contains("StateFact::DocumentBaselineCheckpointed"));
    assert!(snapshot.contains("pub fn checkpoint_crdt_recovery_projection("));

    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/debounce.rs")).unwrap();
    assert!(preflight.contains("wait_for_lazily_current_before_mutation"));
    assert!(preflight.contains("wait_for_lazily_current_observation"));
    assert!(!preflight.contains("is_typing_via_file"));

    let transport =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/transport.rs")).unwrap();
    assert!(transport.contains("EditorIntent::ApplyCanonical"));
    assert!(!transport.contains("send_save_document_file_signal"));
    assert!(!transport.contains("publish_live_buffer_file_signal"));
}
#[test]
fn test_lazily_is_the_only_live_document_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    assert!(realtime.contains("current_text_via_controller_model_read_for_doc"));
    assert!(realtime.contains("current_text_via_controller_model_for_doc"));
    assert!(realtime.contains("apply_cp_write_for_file"));
    assert!(!realtime.contains("await_idle_via_file"));
    assert!(!realtime.contains("send_publish_live_buffer_file_signal"));

    let authority =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime/src/crdt_authority.rs"))
            .unwrap();
    for required in [
        "pub enum CrdtAuthority",
        "pub fn authority_for_document(",
        "pub fn commit_barrier_under_authority(",
    ] {
        assert!(
            authority.contains(required),
            "missing authority seam: {required}"
        );
    }

    let registration =
        fs::read_to_string(manifest_dir.join("agent-doc-reliable-sync-io/src/liveness.rs"))
            .unwrap();
    assert!(registration.contains("pub struct EditorRegistration"));
    assert!(registration.contains("pub fn live_registrations("));
    assert!(!registration.contains(".agent-doc/live-buffer"));
}
#[test]
fn test_patch_pending_compatibility_strings_do_not_remain_in_production_code() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let production_files = [
        "src/main.rs",
        "agent-doc-template/src/template.rs",
        "agent-doc-write-runtime-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-template-io/src/response_materialization_io.rs",
        "agent-doc-template-io/src/backlog_normalization.rs",
    ];
    let forbidden_snippets = [
        "--allow-patch-pending",
        "allow-patch-pending",
        "AGENT_DOC_ALLOW_PATCH_PENDING",
        "Dual-accept",
        "dual-accept",
        "deprecated aliases",
        "deprecation warning",
        "`patch:pending` is deprecated",
    ];

    for relative in production_files {
        let content = fs::read_to_string(manifest_dir.join(relative)).unwrap();
        for forbidden in forbidden_snippets.iter().copied() {
            assert!(
                !content.contains(forbidden),
                "{relative} must not retain deprecated patch:pending compatibility string: {forbidden}"
            );
        }
    }
}

#[test]
fn test_agent_doc_template_owns_patchback_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let template_patchback =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/patchback.rs")).unwrap();
    for required_snippet in [
        "pub enum PatchbackShape",
        "pub struct PatchbackShapeFacts",
        "pub fn classify_patchback_shape",
        "pub fn raw_component_block_count",
        "pub fn patchback_marker_count_outside_code",
        "pub struct TemplatePatchbackPlan",
        "pub fn parse_template_patchback_plan",
        "pub enum OrchestratePatchbackRejectReason",
        "pub fn classify_orchestrate_patchback",
        "pub fn classify_orchestrate_plain_response",
        "pub fn enforce_orchestrate_patchback_contract",
        "pub enum ChildPatchbackNormalizationDecision",
        "pub struct ChildPatchbackNormalization",
        "pub fn normalize_child_template_response",
        "pub fn child_patchback_normalization_event",
        "pub fn child_template_finalize_text",
        "pub fn should_stream_exchange_patch",
        "pub fn finalize_suffix_from_streamed_prefix",
    ] {
        assert!(
            template_patchback.contains(required_snippet),
            "agent-doc-template must own template patchback policy: {required_snippet}"
        );
    }

    let template_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/lib.rs")).unwrap();
    assert!(
        template_lib.contains("pub mod patchback;"),
        "agent-doc-template should expose patchback policy through its owning module"
    );
    assert!(
        template_lib.contains("pub mod structure_guard;"),
        "agent-doc-template should expose template structure guard policy through its owning module"
    );
    assert!(
        !template_lib.contains("pub use patchback"),
        "agent-doc-template should not add a patchback root facade"
    );
    let template_structure_guard =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/structure_guard.rs")).unwrap();
    for required_snippet in [
        "pub enum TemplateStructureGuardReason",
        "pub fn template_structure_guard_event(",
        "FlowName::DocumentMutation",
        "FlowStage::DocumentMutation",
    ] {
        assert!(
            template_structure_guard.contains(required_snippet),
            "agent-doc-template must own template structure guard event policy: {required_snippet}"
        );
    }
    let template_io =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn parse_template_patchback(",
        "pub fn patchback_parse_event(",
        "pub fn log_patchback_parse_event(",
        "pub fn log_template_structure_guard_event(",
        "parse_template_patchback_plan(response)",
        "agent_doc_flow_io::log_flow_event",
        "agent_doc_hash::content_hash(response)",
        "agent_doc_template::structure_guard::template_structure_guard_event",
    ] {
        assert!(
            template_io.contains(required_snippet),
            "agent-doc-template-io must own template patchback parse/log adapters: {required_snippet}"
        );
    }
    for forbidden_snippet in ["crate::ops_log", "agent_doc_orchestration"] {
        assert!(
            !template_io.contains(forbidden_snippet),
            "agent-doc-template-io must not depend on orchestration logging internals: {forbidden_snippet}"
        );
    }

    let flow_types = fs::read_to_string(manifest_dir.join("agent-doc-flow/src/types.rs")).unwrap();
    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/document_mutation.rs")
            .exists(),
        "orchestration must not keep a document-mutation flow facade"
    );
    let write_materialize = fs::read_to_string(
        manifest_dir.join("agent-doc-template-io/src/response_materialization_io.rs"),
    )
    .unwrap();
    let orchestration_sources = [
        ("agent-doc-flow/src/types.rs", flow_types.as_str()),
        (
            "agent-doc-template-io/src/response_materialization_io.rs",
            write_materialize.as_str(),
        ),
    ];
    for (source, content) in orchestration_sources {
        for forbidden_snippet in [
            "pub enum PatchbackShape",
            "pub struct PatchbackShapeFacts",
            "pub fn classify_patchback_shape",
            "pub fn raw_component_block_count",
            "pub fn patchback_marker_count_outside_code",
            "pub struct TemplatePatchbackPlan",
            "pub enum OrchestratePatchbackRejectReason",
            "pub fn classify_orchestrate_patchback",
            "pub fn classify_orchestrate_plain_response",
            "pub fn enforce_orchestrate_patchback_contract",
            "pub fn parse_template_patchback(",
            "pub fn patchback_parse_event(",
            "pub fn log_patchback_parse_event(",
            "pub enum TemplateStructureGuardReason",
            "pub fn template_structure_guard_event(",
            "pub fn log_template_structure_guard_event(",
            "pub enum ChildPatchbackNormalizationDecision",
            "pub struct ChildPatchbackNormalization",
            "pub fn normalize_child_template_response",
            "pub fn child_patchback_normalization_event",
        ] {
            assert!(
                !content.contains(forbidden_snippet),
                "orchestration must not re-own or facade template patchback policy in {source}: {forbidden_snippet}"
            );
        }
    }

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/flow/orchestration_batch.rs")
            .exists(),
        "orchestration must not keep an orchestration-batch patchback facade"
    );
    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    assert!(
        write_run_entry
            .contains("agent_doc_template::patchback::enforce_orchestrate_patchback_contract"),
        "write run entry should enforce orchestrate patchback contracts through the focused template API"
    );
    let orchestrate_source = fs::read_to_string(manifest_dir.join("src/orchestrate.rs")).unwrap();
    for forbidden_snippet in [
        "fn orchestrate_finalize_text_for_template(",
        "fn should_stream_exchange_patch(",
        "fn finalize_suffix_from_streamed_prefix(",
        "fn finalize_suffix_from_open_patch_prefix(",
        "pub use agent_doc_template::patchback",
        "pub(crate) use agent_doc_template::patchback",
    ] {
        assert!(
            !orchestrate_source.contains(forbidden_snippet),
            "src/orchestrate.rs must not re-own or facade template patchback stream/finalize policy: {forbidden_snippet}"
        );
    }
    assert!(
        orchestrate_source.contains("use agent_doc_template::patchback::{")
            && orchestrate_source.contains("finalize_suffix_from_streamed_prefix")
            && orchestrate_source.contains("should_stream_exchange_patch"),
        "src/orchestrate.rs should call template patchback stream/finalize policy directly"
    );
}

#[test]
fn test_agent_doc_template_has_no_boundary_id_facade() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let template_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub mod id {",
        "pub mod id;",
        "pub use agent_doc_element::id",
        "pub use agent_doc_element :: id",
    ] {
        assert!(
            !template_lib.contains(forbidden_snippet),
            "agent-doc-template must not facade agent-doc-element boundary ids: {forbidden_snippet}"
        );
    }

    for relative_path in [
        "agent-doc-template/src/template.rs",
        "agent-doc-template/src/template/tail_repair.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            !source.contains("crate::id::"),
            "{relative_path} must call agent_doc_element::id directly, not the removed template id facade"
        );
    }
}

#[test]
fn test_agent_doc_template_owns_response_materialization_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let template_response_materialization =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/response_materialization.rs"))
            .unwrap();
    for required_snippet in [
        "pub struct TemplateResponseWriteProof",
        "pub fn template_response_write_proof",
        "pub fn ensure_template_response_write_proof",
        "pub fn same_ignoring_trailing_newlines",
        "pub fn serialize_template_response",
        "pub fn response_materialization_probe",
        "pub fn response_materialization_probe_from_response",
        "pub fn extract_response_headings_from_patches",
        "pub fn strip_partial_response_materialization_from_exchange",
        "pub fn materialized_template_response",
        "pub fn push_materialization_segment",
        "pub fn reject_marker_response_with_zero_patches",
        "pub fn sanitize_template_patchback_response",
    ] {
        assert!(
            template_response_materialization.contains(required_snippet),
            "agent-doc-template must own template response materialization policy: {required_snippet}"
        );
    }

    let template_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/lib.rs")).unwrap();
    assert!(
        template_lib.contains("pub mod response_materialization;"),
        "agent-doc-template should expose response materialization through its owning module"
    );
    assert!(
        !template_lib.contains("pub use response_materialization"),
        "agent-doc-template should not add a response materialization root facade"
    );
    let template_io =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/lib.rs")).unwrap();
    let template_io_backlog =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/backlog_normalization.rs"))
            .unwrap();
    assert!(
        template_io.contains("pub fn response_materialization_probe_from_ipc_payload(")
            && template_io.contains("response_materialization_probe(&patches, unmatched)"),
        "agent-doc-template-io must own IPC payload adapters for response materialization"
    );
    assert!(
        !template_io.contains("agent_doc_orchestration")
            && !template_io.contains("crate::ops_log")
            && !template_io.contains("tmux_router"),
        "agent-doc-template-io response materialization adapters must stay free of orchestration effects"
    );
    assert!(
        template_io
            .contains("agent_doc_document_realtime_io::try_resolve_current_document_content("),
        "agent-doc-template-io template info should resolve current document content through realtime authority"
    );
    for required_snippet in [
        "pub struct NormalizedTemplateResponse",
        "pub fn pending_replace_escape_hatch_enabled(",
        "pub fn enforce_no_replace_pending(",
        "pub fn normalize_backlog_patch_response(",
        "pub fn canonicalize_response_for_capture(",
        "pub fn canonicalize_response_for_capture_with_current_content(",
        "agent_doc_document_realtime_io::try_resolve_current_document_content",
        "agent_doc_document_realtime_io::guard_visible_write_current_transition",
        "agent_doc_document_realtime_io::atomic_write_through_authority",
        "agent_doc_cycle_state_io::mark_pending_mutations",
        "agent_doc_cycle_state_io::record_pending_done_ids",
    ] {
        assert!(
            template_io_backlog.contains(required_snippet),
            "agent-doc-template-io must own backlog patch normalization IO: {required_snippet}"
        );
    }
    assert!(
        !template_io_backlog.contains("agent_doc_orchestration")
            && !template_io_backlog.contains("crate::write")
            && !template_io_backlog.contains("tmux_router"),
        "agent-doc-template-io backlog normalization must stay free of orchestration/tmux facades"
    );
    for (source, content) in [
        ("agent-doc-template-io/src/lib.rs", template_io.as_str()),
        (
            "agent-doc-template-io/src/backlog_normalization.rs",
            template_io_backlog.as_str(),
        ),
    ] {
        for forbidden_snippet in [
            "std::fs::read_to_string(file)",
            "fs::read_to_string(file)",
            "std::fs::write(file",
            "fs::write(file",
        ] {
            assert!(
                !content.contains(forbidden_snippet),
                "{source} must not read or write active documents directly: {forbidden_snippet}"
            );
        }
    }

    let write_materialize = fs::read_to_string(
        manifest_dir.join("agent-doc-template-io/src/response_materialization_io.rs"),
    )
    .unwrap();
    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub struct TemplateResponseWriteProof",
        "pub(crate) struct TemplateResponseWriteProof",
        "pub fn template_response_write_proof",
        "pub(crate) fn template_response_write_proof",
        "pub fn ensure_template_response_write_proof",
        "pub(crate) fn ensure_template_response_write_proof",
        "pub fn same_ignoring_trailing_newlines",
        "pub(crate) fn same_ignoring_trailing_newlines",
        "pub fn serialize_template_response",
        "pub(crate) fn serialize_template_response",
        "pub fn response_materialization_probe(",
        "pub(crate) fn response_materialization_probe(",
        "pub fn response_materialization_probe_from_response",
        "pub(crate) fn response_materialization_probe_from_response",
        "pub fn response_materialization_probe_from_ipc_payload",
        "pub(crate) fn response_materialization_probe_from_ipc_payload",
        "pub fn strip_partial_response_materialization_from_exchange",
        "pub(crate) fn strip_partial_response_materialization_from_exchange",
        "pub fn materialized_template_response",
        "pub(crate) fn materialized_template_response",
        "pub fn push_materialization_segment",
        "pub(crate) fn push_materialization_segment",
        "pub fn reject_marker_response_with_zero_patches",
        "pub(crate) fn reject_marker_response_with_zero_patches",
        "pub fn sanitize_template_patchback_response",
        "pub(crate) fn sanitize_template_patchback_response",
        "sanitize_template_patchback_response_for_write",
        "pub struct NormalizedTemplateResponse",
        "pub fn normalize_backlog_patch_response",
        "pub fn canonicalize_response_for_capture",
        "pub fn enforce_no_replace_pending",
        "pub(crate) fn pending_replace_escape_hatch_enabled",
    ] {
        assert!(
            !write_materialize.contains(forbidden_snippet),
            "orchestration must not re-own or facade template response materialization policy: {forbidden_snippet}"
        );
    }
    for forbidden_snippet in [
        "pub use agent_doc_template_io::{",
        "pub fn normalize_backlog_patch_response",
        "pub fn canonicalize_response_for_capture",
        "pub fn enforce_no_replace_pending",
        "pub(crate) fn pending_replace_escape_hatch_enabled",
    ] {
        assert!(
            !write_source.contains(forbidden_snippet),
            "orchestration write must not re-own or facade template backlog normalization: {forbidden_snippet}"
        );
    }
    let transport_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/transport.rs")).unwrap();
    assert!(
        transport_source.contains(
            "agent_doc_template::response_materialization::response_materialization_probe("
        ),
        "write IPC transport should call the focused pure response materialization seam directly"
    );
    assert!(
        write_materialize
            .contains("strip_partial_response_materialization_from_exchange(&current, response)"),
        "write materialization adapters should call the focused response materialization API directly"
    );
    assert!(
        write_materialize
            .contains("agent_doc_document_realtime_io::try_resolve_current_document_content(")
            && !write_materialize.contains("std::fs::read_to_string(file)")
            && !write_materialize.contains("fs::read_to_string(file)"),
        "write materialization retry diagnostics should resolve active documents through realtime authority"
    );

    let write_ipc =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/ipc.rs")).unwrap();
    let write_ipc_io =
        fs::read_to_string(manifest_dir.join("agent-doc-write-ipc-io/src/lib.rs")).unwrap();
    assert!(
        !write_ipc.contains("fn extract_response_headings_from_patches("),
        "write IPC must not re-own or facade response heading extraction"
    );
    assert!(
        write_ipc_io.contains("pub fn patch_response_bodies_already_in_head(")
            && write_ipc_io.contains("pub fn build_ipc_patches_json("),
        "agent-doc-write-ipc-io should own the full-response-body HEAD gate and IPC payload builder"
    );

    let focused_callers = [
        "agent-doc-run-io/src/lib.rs",
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-write-ipc-io/src/transport.rs",
        "agent-doc-template-io/src/response_materialization_io.rs",
        "agent-doc-template-io/src/write_normalize.rs",
    ];
    for relative_path in focused_callers {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains("agent_doc_template::response_materialization::"),
            "{relative_path} should call the focused response materialization API directly"
        );
    }
}

#[test]
fn test_agent_doc_template_owns_todo_patch_guard_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let todo_guard =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/todo_patch_guard.rs"))
            .unwrap();
    for required in [
        "pub fn enforce_no_destructive_todo_patch(",
        "fn count_markdown_checklist_items(",
        "fn todo_component_checklist_count(",
    ] {
        assert!(
            todo_guard.contains(required),
            "agent-doc-template must own pure todo patch guard policy: {required}"
        );
    }

    let template_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/lib.rs")).unwrap();
    assert!(
        template_lib.contains("pub mod todo_patch_guard;"),
        "agent-doc-template should expose todo patch guard through its owning module"
    );
    assert!(
        !template_lib.contains("pub use todo_patch_guard"),
        "agent-doc-template should not add a todo patch guard root facade"
    );

    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    for forbidden in [
        "fn count_markdown_checklist_items(",
        "fn todo_component_checklist_count(",
        "pub fn enforce_no_destructive_todo_patch(",
        "pub(crate) fn enforce_no_destructive_todo_patch(",
    ] {
        assert!(
            !write_source.contains(forbidden),
            "orchestration write must not re-own todo patch guard policy: {forbidden}"
        );
    }
    assert!(
        write_run_entry.contains(
            "use agent_doc_template::todo_patch_guard::enforce_no_destructive_todo_patch;"
        ),
        "write run entry should call todo patch guard through the focused template module"
    );
}

#[test]
fn test_agent_doc_template_owns_stale_baseline_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let template_stale_baseline =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/stale_baseline.rs")).unwrap();
    for required_snippet in [
        "pub fn is_append_mode_component",
        "pub fn patch_touches_exchange",
        "pub fn exchange_append_patch_can_rebase_to_head",
        "pub fn is_stale_baseline",
        "agent_doc_document::transient_markers::strip_boundary_markers",
    ] {
        assert!(
            template_stale_baseline.contains(required_snippet),
            "agent-doc-template must own stale-baseline template policy: {required_snippet}"
        );
    }

    let template_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/lib.rs")).unwrap();
    assert!(
        template_lib.contains("pub mod stale_baseline;"),
        "agent-doc-template should expose stale-baseline policy through its owning module"
    );
    assert!(
        !template_lib.contains("pub use stale_baseline"),
        "agent-doc-template should not add a stale-baseline root facade"
    );

    let write =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "fn is_append_mode_component(",
        "fn patch_touches_exchange(",
        "fn exchange_append_patch_can_rebase_to_head(",
        "pub fn is_stale_baseline(",
        "fn is_stale_baseline(",
    ] {
        assert!(
            !write.contains(forbidden_snippet),
            "write.rs must not re-own or facade stale-baseline policy: {forbidden_snippet}"
        );
    }
    assert!(
        write.contains("use agent_doc_template::stale_baseline::{"),
        "write.rs should import focused stale-baseline policy directly"
    );

    let git = fs::read_to_string(manifest_dir.join("agent-doc-commit-io/tests/git.rs")).unwrap();
    assert!(
        git.contains("agent_doc_template::stale_baseline::is_stale_baseline"),
        "git write-path tests should call focused stale-baseline policy directly"
    );
}

#[test]
fn test_commit_lifecycle_policy_has_single_owner() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let commit_io =
        fs::read_to_string(manifest_dir.join("agent-doc-commit-io/src/lib.rs")).unwrap();

    assert!(
        !manifest_dir
            .join("agent-doc-orchestration/src/git.rs")
            .exists()
            && commit_io.contains("pub fn commit_with_outcome(")
            && commit_io.contains("pub struct CommitCoordinatorPorts"),
        "orchestration git facade should be deleted and commit-io should own the commit API and ports"
    );

    for required in [
        "try_auto_recover_live_prompt_drift(",
        "commit_blocked_reintroduced_reaped_pending file=",
        "snapshot_resync_blocked file=",
        "commit_frontmatter_self_heal file=",
        "stage_and_commit_exact_paths_once(",
    ] {
        assert!(
            commit_io.contains(required),
            "agent-doc-commit-io must own commit lifecycle policy marker: {required}"
        );
    }
}

#[test]
fn test_agent_doc_template_owns_strict_response_heading_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let template_response_materialization =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/response_materialization.rs"))
            .unwrap();
    for required_snippet in [
        "pub fn ensure_strict_template_response_heading",
        "pub fn ensure_strict_template_response_heading_for_current_doc",
        "pub fn template_response_has_heading",
        "pub fn live_exchange_tail_proves_streamed_response_heading",
        "pub fn offset_after_last_prompt_line",
        "pub fn response_text_has_heading",
    ] {
        assert!(
            template_response_materialization.contains(required_snippet),
            "agent-doc-template must own strict template response-heading policy: {required_snippet}"
        );
    }

    let write_materialize = fs::read_to_string(
        manifest_dir.join("agent-doc-template-io/src/response_materialization_io.rs"),
    )
    .unwrap();
    for forbidden_snippet in [
        "pub use agent_doc_template::response_materialization",
        "pub fn ensure_strict_template_response_heading",
        "pub(crate) fn ensure_strict_template_response_heading",
        "fn template_response_has_heading",
        "fn live_exchange_tail_proves_streamed_response_heading",
        "fn offset_after_last_prompt_line",
        "fn response_text_has_heading",
    ] {
        assert!(
            !write_materialize.contains(forbidden_snippet),
            "response_materialization_io.rs must not facade or re-own strict heading policy: {forbidden_snippet}"
        );
    }

    for relative_path in [
        "agent-doc-write-runtime-io/src/run_entry.rs",
        "agent-doc-template-io/src/write_normalize.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains(
                "agent_doc_template::response_materialization::ensure_strict_template_response_heading"
            ),
            "{relative_path} should call strict heading policy through agent-doc-template directly"
        );
    }
}

#[test]
fn test_agent_doc_queue_owns_queue_head_classification_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_consume_policy =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_consume.rs")).unwrap();
    let queue_response =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_response.rs")).unwrap();
    for required_snippet in [
        "pub fn queue_consumption_allowed_for_response(",
        "pub fn should_consume_queue_prompt_for_write(",
        "pub fn should_consume_queue_prompt_for_diff_content(",
        "pub fn queue_targeted_completion_id_for_current_head(",
        "pub fn queue_diff_completion_id_for_current_head(",
        "pub fn answered_free_text_head_node_keys(",
        "fn response_targets_synthetic_queue_head_id(",
    ] {
        assert!(
            queue_consume_policy.contains(required_snippet),
            "agent-doc-queue must own queue consumption decision policy: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn head_id_names_tracked_directive_item",
        "pub fn head_id_is_registered_preset",
        "pub fn active_queue_head_is_registered_preset",
        "pub fn queue_head_is_bare_do_directive",
        "pub fn queue_prompt_text_is_queue_activation_trigger",
        "pub fn queue_prompt_text_is_free_text",
        "pub fn queue_head_is_free_text_prompt",
    ] {
        assert!(
            queue_response.contains(required_snippet),
            "agent-doc-queue must own queue-head classification policy: {required_snippet}"
        );
    }

    let queue_consume =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_consume.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) use agent_doc_queue::queue_response",
        "pub fn queue_head_is_free_text_prompt",
        "pub(crate) fn queue_head_is_free_text_prompt",
        "pub fn queue_prompt_text_is_free_text",
        "pub(crate) fn queue_prompt_text_is_free_text",
        "pub(crate) use agent_doc_queue::{",
        "pub(crate) fn queue_consumption_allowed_for_response(",
        "pub(crate) fn should_consume_queue_prompt_for_write(",
        "pub(crate) fn should_consume_queue_prompt_for_diff_content(",
        "pub(crate) fn queue_targeted_completion_id_for_current_head(",
        "pub(crate) fn queue_diff_completion_id_for_current_head(",
        "pub(crate) fn response_targets_synthetic_queue_head_id(",
        "pub(crate) fn answered_free_text_head_node_keys(",
        "pub fn head_id_is_registered_preset",
        "pub(crate) fn head_id_is_registered_preset",
        "pub fn queue_head_is_bare_do_directive",
        "pub(crate) fn queue_head_is_bare_do_directive",
    ] {
        assert!(
            !queue_consume.contains(forbidden_snippet),
            "agent-doc-queue-io queue_consume.rs must not re-own or facade queue-head classification: {forbidden_snippet}"
        );
    }
    let required_snippet = "answered_free_text_head_node_keys";
    assert!(
        queue_consume.contains(required_snippet),
        "agent-doc-queue-io queue_consume.rs should call focused queue consumption helpers directly: {required_snippet}"
    );

    for relative_path in [
        "agent-doc-queue-io/src/queue_cmd.rs",
        "agent-doc-controller-io/src/project_controller/rpc.rs",
        "agent-doc-session-check-io/src/queue_head_provenance_guards.rs",
        "agent-doc-repair-command-io/tests/repair.rs",
        "agent-doc-preflight-io/src/lib.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            !source.contains("crate::write::queue_head_is_free_text_prompt")
                && !source.contains("crate::write::queue_prompt_text_is_free_text")
                && !source.contains("crate::write::head_id_is_registered_preset")
                && !source.contains("fn active_queue_head_is_registered_preset("),
            "{relative_path} should call queue classification through agent-doc-queue directly"
        );
    }
    let rpc_source = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        rpc_source
            .contains("agent_doc_queue::queue_response::active_queue_head_is_registered_preset("),
        "project_controller::rpc should call the queue-owned registered-preset classifier directly"
    );
    for (relative_path, required_snippet) in [
        (
            "agent-doc-write-runtime-io/src/lib.rs",
            "queue_consumption_allowed_for_response",
        ),
        (
            "agent-doc-write-runtime-io/src/lib.rs",
            "queue_targeted_completion_id_for_current_head",
        ),
        (
            "agent-doc-codex-stop-io/src/lib.rs",
            "agent_doc_queue::queue_consume::queue_targeted_completion_id_for_current_head",
        ),
        (
            "agent-doc-run-io/src/lib.rs",
            "agent_doc_queue::queue_consume::queue_diff_completion_id_for_current_head",
        ),
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        assert!(
            source.contains(required_snippet),
            "{relative_path} should call queue consumption policy through agent-doc-queue directly: {required_snippet}"
        );
    }
}

#[test]
fn test_agent_doc_queue_owns_active_queue_head_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_heads =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_heads.rs")).unwrap();
    for required_snippet in [
        "pub fn active_queue_heads(",
        "pub fn active_free_text_queue_heads(",
        "pub fn active_queue_head_text(",
        "pub fn active_queue_prompt(",
        "pub fn queue_is_active_for_diff(",
        "pub enum ActiveQueueHeadKind",
        "pub fn classify_active_queue_head(",
        "pub fn queue_skip_diagnostic_for_content(",
        "pub fn queue_head_has_explicit_completion_signal(",
        "pub fn explicit_queue_completion_ids(",
        "pub fn queue_head_matches_done_ids(",
        "pub fn free_text_queue_head_identity(",
        "pub fn committed_queue_contains_free_text_head(",
        "pub fn free_text_queue_head_is_completed_residue(",
        "pub fn is_do_directive(",
        "fn leads_with_bare_id_directive(",
    ] {
        assert!(
            queue_heads.contains(required_snippet),
            "agent-doc-queue must own active queue-head projection policy: {required_snippet}"
        );
    }

    for forbidden_snippet in [
        "pub fn active_queue_directive_heads(",
        "pub use active_queue_heads as active_queue_directive_heads",
    ] {
        assert!(
            !queue_heads.contains(forbidden_snippet),
            "agent-doc-queue must not keep the deprecated queue-head projection name: {forbidden_snippet}"
        );
    }

    let cycle_state =
        fs::read_to_string(manifest_dir.join("agent-doc-cycle-state-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub fn active_queue_directive_heads(",
        "pub fn active_free_text_queue_heads(",
        "fn is_do_directive(",
        "fn leads_with_bare_id_directive(",
        "pub use agent_doc_queue::queue_heads",
        "active_queue_directive_heads",
    ] {
        assert!(
            !cycle_state.contains(forbidden_snippet),
            "cycle_state must not re-own, facade, or preserve deprecated active queue-head policy: {forbidden_snippet}"
        );
    }
    assert!(
        cycle_state.contains("agent_doc_queue::queue_heads::active_queue_heads"),
        "cycle_state should call active queue-head projection through agent-doc-queue directly"
    );
    assert!(
        cycle_state.contains("agent_doc_queue::queue_heads::active_free_text_queue_heads"),
        "cycle_state should call free-text queue-head projection through agent-doc-queue directly"
    );

    let queue_consume =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_consume.rs")).unwrap();
    let queue_consume_prod = queue_consume
        .split("#[cfg(test)]")
        .next()
        .expect("queue_consume production section");
    let run_io = fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    let write_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) fn active_queue_head_text(",
        "pub(crate) fn queue_skip_diagnostic_for_content(",
        "pub(crate) fn queue_head_has_explicit_completion_signal(",
        "pub(crate) fn explicit_queue_completion_ids(",
        "pub(crate) fn queue_head_matches_done_ids(",
        "pub fn queue_skip_diagnostic_for_file(",
        "pub fn should_consume_queue_prompt_for_diff(",
        "pub fn response_explicitly_targets_active_queue_head(",
        "std::fs::read_to_string(file)",
    ] {
        assert!(
            !queue_consume_prod.contains(forbidden_snippet),
            "queue_consume must not re-own, facade, or raw-read active queue-head policy: {forbidden_snippet}"
        );
    }
    assert!(
        run_io.contains("direct_run_queue_guard")
            && run_io.contains(
                "agent_doc_queue::queue_consume::should_consume_queue_prompt_for_diff_content"
            )
            && run_io.contains("agent_doc_queue::queue_heads::queue_skip_diagnostic_for_content")
            && write_runtime.contains("fn queue_skip_diagnostic_for_current_document(")
            && write_runtime
                .contains("agent_doc_queue::queue_heads::queue_skip_diagnostic_for_content"),
        "runtime callers should resolve current document content before queue skip/diff diagnostics"
    );

    let queue_cmd =
        fs::read_to_string(manifest_dir.join("agent-doc-queue-io/src/queue_cmd.rs")).unwrap();
    for forbidden_snippet in [
        "enum HeadKind",
        "fn classify_active_head(",
        "agent_doc_queue::document_queue as queue",
        "agent_doc_queue::queue_response::queue_head_is_free_text_prompt",
    ] {
        assert!(
            !queue_cmd.contains(forbidden_snippet),
            "queue_cmd must not re-own explicit queue-head classification policy: {forbidden_snippet}"
        );
    }
    assert!(
        queue_cmd.contains("agent_doc_queue::queue_heads::{")
            && queue_cmd.contains("ActiveQueueHeadKind")
            && queue_cmd.contains("classify_active_queue_head"),
        "queue_cmd should call explicit queue-head classification through agent-doc-queue directly"
    );

    let queue_response =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_response.rs")).unwrap();
    assert!(
        !queue_response.contains("fn active_queue_head_text("),
        "queue_response must not duplicate active queue-head document projection"
    );
    assert!(
        queue_response.contains("crate::queue_heads::active_queue_head_text"),
        "queue_response should share active queue-head projection through queue_heads"
    );

    // `#adturnscopehotloop`: the two processes that emit almost every `ops.log`
    // line must memoize turn attribution per request / per tick.
    //
    // `log_op` resolves a `turn=` id for each line, and outside a
    // `begin_turn_attribution_scope()` that resolution is
    // `load_document_projection` — a SQLite ledger replay inside the controller,
    // and a 5s-timeout controller IPC round trip everywhere else. Measured on
    // agent-loop: 12,700 log lines per 20k-op window, so the diagnostic label on
    // a line cost more than the operation it described, and the supervisor's
    // round trips fed the very saturation that made them time out.
    //
    // The memo already existed (`#adturnscope`) with `route` as its only caller.
    // Deleting either guard below silently restores the storm — nothing else
    // fails — so pin them at the source.
    let controller_rpc = fs::read_to_string(
        manifest_dir.join("agent-doc-controller-io/src/project_controller/rpc.rs"),
    )
    .unwrap();
    assert!(
        controller_rpc.contains("agent_doc_ops_log_io::begin_turn_attribution_scope()"),
        "the controller request handler must open a turn-attribution scope so `log_op` does not replay the state ledger once per log line (#adturnscopehotloop)"
    );
    let idle_watch_source =
        fs::read_to_string(manifest_dir.join("agent-doc-start-runtime-io/src/idle_watch.rs"))
            .unwrap();
    assert!(
        idle_watch_source.contains("agent_doc_ops_log_io::begin_turn_attribution_scope()"),
        "the supervisor idle-watch tick must open a turn-attribution scope so `log_op` does not issue a controller IPC round trip per log line (#adturnscopehotloop)"
    );
    assert!(
        idle_watch_source.contains("idle_watch_queue_head_revision_gate"),
        "the idle watch must compare the cheap revision before materializing canonical text, which is the contract `CurrentRevision` documents (#idlewatchrevisiongate)"
    );

    let plan_source = fs::read_to_string(manifest_dir.join("src/plan.rs")).unwrap();
    for forbidden_snippet in [
        "fn active_queue_prompt(",
        "fn queue_is_active_for_diff(",
        "agent_doc_queue::document_queue::resolve_activation(",
    ] {
        assert!(
            !plan_source.contains(forbidden_snippet),
            "plan.rs must not re-own active queue activation policy: {forbidden_snippet}"
        );
    }
    // `#planhead`: plan must not derive its own "which head is next" either.
    // `queue_heads::active_queue_prompt` returns the FIRST head regardless of
    // drainability, so calling it here made plan name an `[operator-verify]` head
    // that preflight had already deferred — and SKILL.md step 0d treats plan's
    // output as the execution contract. The deferral-aware selector is the single
    // source; reaching back for the raw head is the regression.
    assert!(
        !plan_source.contains("agent_doc_queue::queue_heads::active_queue_prompt"),
        "plan.rs must not select the raw first queue head; use the deferral-aware selector (#planhead)"
    );
    assert!(
        plan_source.contains("agent_doc_queue::queue_continuation::dispatchable_head_prompt_text")
            && plan_source.contains("agent_doc_queue::queue_heads::queue_is_active_for_diff"),
        "plan.rs should call active queue activation policy through agent-doc-queue directly"
    );

    let queue_closeout_guard =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_closeout_guard.rs"))
            .unwrap();
    let workflow_session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-workflow/src/session_check.rs")).unwrap();
    for required_snippet in [
        "pub fn committed_queue_head_ids(",
        "pub fn committed_current_queue_head_ids(",
        "pub fn no_response_live_queue_head_ids(",
        "pub fn reaped_queue_directive_head_ids(",
        "pub fn queue_head_removal_decision(",
        "pub struct FreeTextQueueHeadProvenanceDecision",
        "pub fn free_text_queue_head_provenance_decision(",
        "pub enum QueueHeadRemovalProofSource",
    ] {
        assert!(
            queue_closeout_guard.contains(required_snippet),
            "agent-doc-queue must own queue closeout guard policy: {required_snippet}"
        );
    }
    for required_snippet in [
        "pub fn no_response_active_queue_head_result(",
        "pub fn reaped_queue_head_without_response_result(",
    ] {
        assert!(
            workflow_session_check.contains(required_snippet),
            "agent-doc-workflow must own queue-head session-check result formatting: {required_snippet}"
        );
    }

    let queue_head_guards = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_guards.rs"),
    )
    .unwrap();
    let provenance_guards = fs::read_to_string(
        manifest_dir.join("agent-doc-session-check-io/src/queue_head_provenance_guards.rs"),
    )
    .unwrap();
    for forbidden_snippet in [
        "pub(crate) fn committed_queue_head_ids(",
        "pub(crate) fn committed_current_queue_head_ids(",
        "fn committed_queue_head_ids(",
        "fn committed_current_queue_head_ids(",
        "fn normalized_free_text_queue_head_identity(",
        "fn committed_queue_contains_active_free_text_head(",
        "fn no_response_live_queue_head_ids(",
        "fn reaped_queue_directive_head_ids(",
        "fn queue_head_removal_decision(",
        "fn free_text_queue_head_provenance_decision(",
        "agent_doc_queue::queue_directive::do_directive_target_ids(&state.active_queue_heads)",
        "queue_heads::free_text_queue_head_is_completed_residue(",
        "queue_heads::committed_queue_contains_free_text_head(",
        "free_text_head_answered_by_response(",
        "queue_continuation::is_recurring_imperative_head(",
        "let warn_line = format!(",
        "let repair = format!(",
        "warn_line.replacen(\"[session-check] warn:\"",
    ] {
        assert!(
            !queue_head_guards.contains(forbidden_snippet)
                && !provenance_guards.contains(forbidden_snippet),
            "session_check must not re-own queue closeout/provenance policy: {forbidden_snippet}"
        );
    }
    assert!(
        queue_head_guards
            .contains("agent_doc_queue::queue_closeout_guard::no_response_live_queue_head_ids",)
            && queue_head_guards
                .contains("agent_doc_queue::queue_closeout_guard::reaped_queue_directive_head_ids",)
            && queue_head_guards
                .contains("agent_doc_workflow::session_check::no_response_active_queue_head_result")
            && queue_head_guards.contains(
                "agent_doc_workflow::session_check::reaped_queue_head_without_response_result"
            )
            && provenance_guards
                .contains("agent_doc_queue::queue_closeout_guard::queue_head_removal_decision",)
            && provenance_guards.contains(
                "agent_doc_queue::queue_closeout_guard::free_text_queue_head_provenance_decision"
            ),
        "session_check should call queue closeout/provenance policy through agent-doc-queue directly"
    );

    let queue_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/Cargo.toml")).unwrap();
    let parsed: toml::Value = toml::from_str(&queue_manifest).unwrap();
    let dependencies = parsed["dependencies"].as_table().unwrap();
    for forbidden_dependency in [
        "agent-doc-orchestration",
        "tmux-router",
        "interprocess",
        "notify",
        "rusqlite",
        "git2",
    ] {
        assert!(
            !dependencies.contains_key(forbidden_dependency),
            "agent-doc-queue must keep active queue-head projection free of orchestration/effect dependencies: {forbidden_dependency}"
        );
    }
}

#[test]
fn test_agent_doc_queue_owns_queue_worklist_projection_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let queue_projection =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/queue_projection.rs")).unwrap();
    for required_snippet in [
        "pub fn queue_entry_do_id(",
        "pub fn queue_prompt_projection_rows(",
        "pub fn active_queue_prompt_projection(",
        "pub fn in_progress_marker_retarget_requested(",
        "pub fn selected_queue_head_node_key(",
        "pub fn queue_worklist_hash(",
        "pub fn dedup_queue_nodes_by_key(",
        "fn queue_prompt_node_key(",
        "pub fn queue_worklist_entries(",
        "pub enum QueueWorklistEntryKind",
        "pub struct QueueWorklistEntry",
    ] {
        assert!(
            queue_projection.contains(required_snippet),
            "agent-doc-queue must own pure queue worklist/projection policy: {required_snippet}"
        );
    }

    let queue_lib = fs::read_to_string(manifest_dir.join("agent-doc-queue/src/lib.rs")).unwrap();
    assert!(
        queue_lib.contains("pub mod queue_projection;"),
        "agent-doc-queue should expose queue projection/worklist policy through its owning module"
    );

    let maintenance =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub(crate) fn queue_entry_do_id(",
        "fn queue_prompt_projection_rows(",
        "fn active_queue_prompt_projection(",
        "fn in_progress_marker_retarget_requested(",
        "fn selected_queue_head_node_key(",
        "fn queue_worklist_hash(",
        "fn dedup_queue_nodes_by_key(",
        "fn queue_prompt_node_key(",
        "fn queue_worklist_entries(",
    ] {
        assert!(
            !maintenance.contains(forbidden_snippet),
            "preflight maintenance must not re-own or facade queue worklist/projection policy: {forbidden_snippet}"
        );
    }
    for required_snippet in [
        "agent_doc_queue::queue_projection::queue_entry_do_id",
        "agent_doc_queue::queue_projection::active_queue_prompt_projection(",
        "agent_doc_queue::queue_projection::in_progress_marker_retarget_requested(",
        "agent_doc_queue::queue_projection::selected_queue_head_node_key(",
        "agent_doc_queue::queue_projection::queue_worklist_hash(",
        "agent_doc_queue::queue_projection::dedup_queue_nodes_by_key(",
        "agent_doc_queue::queue_projection::queue_worklist_entries(",
    ] {
        assert!(
            maintenance.contains(required_snippet),
            "preflight maintenance should call focused queue projection/worklist policy directly: {required_snippet}"
        );
    }
}

#[test]
fn test_agent_doc_queue_owns_route_dispatch_queue_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-queue/src/route_dispatch.rs")).unwrap();
    for required_snippet in [
        "pub fn route_prompt_text_for_change(",
        "pub fn active_auto_route_queue_prompt_texts(",
        "pub fn strip_route_queue_state_for_boundary_compare(",
        "pub fn operator_prioritize_route_prompt(",
        "pub fn prepare_route_dispatch_queue_update(",
        "pub fn dispatch_active_turn_queue_source(",
        "pub fn activate_existing_route_queue_content(",
        "pub fn inactive_route_queue_head(",
        "pub fn committed_snapshot_backs_queue_head(",
        "pub enum RouteInactiveQueueHead",
        "pub struct RouteDispatchQueueUpdate",
    ] {
        assert!(
            route_dispatch.contains(required_snippet),
            "agent-doc-queue must own route-dispatch queue policy: {required_snippet}"
        );
    }

    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_queue_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/queue_dispatch.rs")).unwrap();
    let route_dispatch_only =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/dispatch_only.rs")).unwrap();
    let route_admission_projection =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/admission_projection.rs"))
            .unwrap();
    let preflight_debounce =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-io/src/debounce.rs")).unwrap();
    let turn_prompt_bearing =
        fs::read_to_string(manifest_dir.join("agent-doc-turn/src/prompt_bearing_route.rs"))
            .unwrap();
    let preflight_source =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-command-io/src/lib.rs")).unwrap();
    let preflight_runtime =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "fn queue_prompt_text_for_route_change(",
        "fn operator_prioritize_route_prompt(",
        "fn route_queue_head_backed_by_committed_snapshot(",
        "fn strip_route_queue_state_for_boundary_compare(",
        "fn strip_queue_component_auto_attr(",
        "fn insert_queue_component(",
        "document_queue::resolve_activation(",
        "document_queue::has_stop_fence_at_head(",
        "document_queue::time_gate_at_head(",
        "document_queue::marker_control(",
        "fn dispatch_active_turn_queue_source(",
        "pub(crate) fn dispatch_active_turn_queue_source(",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet)
                && !route_queue_dispatch.contains(forbidden_snippet)
                && !route_dispatch_only.contains(forbidden_snippet)
                && !route_admission_projection.contains(forbidden_snippet),
            "route must stay an effect adapter and not re-own route-dispatch queue policy: {forbidden_snippet}"
        );
    }
    for forbidden_snippet in [
        "fn route_queue_lock_path(",
        "fn acquire_route_queue_lock(",
        "fn enqueue_route_dispatch_prompt(",
        "fn enqueue_exchange_slash_command_for_idle_drain(",
        "fn activate_existing_route_queue_head(",
        "enqueue_route_dispatch_prompt_with_effects",
        "enqueue_exchange_slash_command_for_idle_drain_with_effects",
        "activate_existing_route_queue_head_with_effects",
        "agent_doc_queue::route_dispatch::prepare_route_dispatch_queue_update",
        "agent_doc_queue::route_dispatch::inactive_route_queue_head",
        "agent_doc_queue::route_dispatch::activate_existing_route_queue_content",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route dispatch queue writeback IO after it moves to agent-doc-route-io: {forbidden_snippet}"
        );
    }
    for forbidden_snippet in [
        "fn route_queue_prompt_texts(",
        "fn normalize_route_queue_prompt_text(",
        "fn authority_settle_max_wait(",
    ] {
        assert!(
            !preflight_source.contains(forbidden_snippet),
            "preflight must stay an effect adapter and not re-own route queue prompt policy: {forbidden_snippet}"
        );
    }
    assert!(
        route_queue_dispatch
            .contains("agent_doc_queue::route_dispatch::prepare_route_dispatch_queue_update")
            && route_queue_dispatch
                .contains("agent_doc_queue::route_dispatch::inactive_route_queue_head")
            && route_queue_dispatch
                .contains("agent_doc_queue::route_dispatch::activate_existing_route_queue_content")
            && route_queue_dispatch.contains("pub struct RouteQueueEffects")
            && route_queue_dispatch.contains("pub struct RouteQueueEnqueueOutcome")
            && route_queue_dispatch.contains("pub fn enqueue_route_dispatch_prompt(")
            && route_queue_dispatch.contains("pub fn activate_existing_route_queue_head(")
            && route_queue_dispatch.contains("pub fn inactive_route_queue_head(")
            && route_source.contains("use agent_doc_route_io::queue_dispatch::{")
            && route_source.contains("route_queue_effects()")
            && route_admission_projection.contains("agent_doc_turn::prompt_bearing_route")
            && turn_prompt_bearing
                .contains("agent_doc_queue::route_dispatch::route_prompt_text_for_change")
            && preflight_runtime
                .contains("agent_doc_queue::route_dispatch::active_auto_route_queue_prompt_texts")
            && preflight_runtime.contains(
                "agent_doc_queue::route_dispatch::strip_route_queue_state_for_boundary_compare",
            )
            && preflight_debounce.contains("agent_doc_debounce::authority_settle_max_wait")
            && route_dispatch_only
                .contains("agent_doc_queue::route_dispatch::dispatch_active_turn_queue_source"),
        "route/preflight should call route-dispatch queue policy through focused effect adapters and agent-doc-queue directly"
    );
    for required in [
        "agent_doc_document_realtime_io::try_resolve_current_document_content(",
        "\"route_dispatch_queue_enqueue\"",
        "\"route_inactive_queue_head\"",
        "\"route_queue_activation\"",
    ] {
        assert!(
            route_queue_dispatch.contains(required),
            "route queue dispatch should resolve active document content through realtime authority: {required}"
        );
    }
    assert!(
        !route_queue_dispatch.contains("std::fs::read_to_string(file)")
            && !route_queue_dispatch.contains("fs::read_to_string(file)"),
        "route queue dispatch must not read active documents directly from disk"
    );
}

#[test]
fn test_agent_doc_route_io_owns_route_document_prep() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let document_prep =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/document_prep.rs")).unwrap();
    let route_command =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/command.rs")).unwrap();
    let runtime_effects =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/runtime_effects.rs")).unwrap();

    for forbidden_snippet in [
        "agent_doc_frontmatter_io::session::ensure_session_for_file(&content, file)",
        "agent_doc_snapshot_io::load_document_baseline(file).ok().flatten()",
        "agent_doc_git_io::revision::show_head(file).ok().flatten()",
        "fn scrub_duplicate_prompt_comments_for_route(",
        "document_prep_effects: route_document_prep_effects()",
        "agent_doc_template::remove_duplicate_answered_exchange_prompt_tail",
        "agent_doc_template::remove_post_exchange_duplicate_prompt_comments_preserving_docs",
        "agent_doc_template::guard_no_duplicate_prompt_residue_outside_exchange",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route document preparation after it moves to route IO: {forbidden_snippet}"
        );
    }

    assert!(
        document_prep.contains("pub struct RouteDocumentPrepEffects")
            && document_prep.contains("pub struct RouteDocumentPreparation")
            && document_prep.contains("pub fn prepare_route_document(")
            && document_prep
                .contains("agent_doc_document_realtime_io::resolve_disk_current_document_content(")
            && document_prep.contains("\"route_document_prep\"")
            && document_prep.contains("pub fn scrub_duplicate_prompt_comments_for_route(")
            && document_prep
                .contains("agent_doc_frontmatter_io::session::require_agent_doc_document")
            && document_prep
                .contains("agent_doc_frontmatter_io::session::ensure_session_for_file")
            && document_prep.contains("agent_doc_snapshot_io::load_document_baseline(file)")
            && document_prep.contains("agent_doc_git_io::revision::show_head(file)")
            && document_prep
                .contains("agent_doc_template::remove_duplicate_answered_exchange_prompt_tail")
            && document_prep.contains(
                "agent_doc_template::remove_post_exchange_duplicate_prompt_comments_preserving_docs",
            )
            && route_command.contains("prepare_route_document(file, effects.document_prep_effects)")
            && runtime_effects.contains("document_prep_effects: route_document_prep_effects()"),
        "route document preparation should live in agent-doc-route-io and use the fast disk snapshot after route debounce"
    );
    assert!(
        !document_prep.contains("std::fs::read_to_string(file)")
            && !document_prep.contains("fs::read_to_string(file)"),
        "route document preparation must not read active documents directly from disk"
    );
}

#[test]
fn test_agent_doc_route_io_owns_route_document_write_authority() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/Cargo.toml")).unwrap();
    let route_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/lib.rs")).unwrap();
    let document_write =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/document_write.rs")).unwrap();
    let route_runtime_effects =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/runtime_effects.rs")).unwrap();

    for forbidden_snippet in [
        "fn route_write_document(",
        "agent_doc_write_converge_io::converge_document_or_disk(",
        "agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS",
        "transport=disk_force",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route document write authority after it moves to route IO: {forbidden_snippet}"
        );
    }

    assert!(
        route_io_manifest.contains("agent-doc-document-realtime-io =")
            && route_io_manifest.contains("agent-doc-write-converge-io =")
            && route_io_lib.contains("pub mod document_write;")
            && document_write.contains("pub fn route_write_document(")
            && document_write.contains("crate::invocation::force_disk_route_writes()")
            && document_write
                .contains("agent_doc_document_realtime_io::atomic_write_through_authority(")
            && document_write.contains("agent_doc_write_converge_io::converge_document_or_disk(")
            && document_write
                .contains("agent_doc_document_realtime_io::RUNTIME_WRITE_CONVERGENCE_EFFECTS")
            && document_write.contains("transport=disk_force")
            && document_write.contains("agent_doc_hash::content_hash(next_content)")
            && route_runtime_effects.contains("use crate::document_write::route_write_document;")
            && route_runtime_effects.contains("write_document: route_write_document"),
        "agent-doc-route-io should own route document write authority while orchestration wires the focused callback into route effects"
    );
}

#[test]
fn test_agent_doc_route_io_owns_route_runtime_effect_bundles() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/lib.rs")).unwrap();
    let runtime_effects =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/runtime_effects.rs")).unwrap();
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();

    for forbidden_snippet in [
        "fn route_dispatch_effects(",
        "fn route_admission_effects(",
        "fn route_busy_pane_retry_effects(",
        "fn route_queue_effects(",
        "fn route_document_prep_effects(",
        "fn route_dispatch_only_effects(",
        "pub fn route_startup_effects(",
        "fn enqueue_route_dispatch_prompt_for_dispatch_only(",
        "fn dispatch_only_starting_pane_ready_timeout(",
        "fn route_run_pending_maintenance(",
        "fn route_inspect_session(",
        "fn route_decide_closeout_recovery(",
        "pub fn route_managed_pane_resolution_effects(",
        "pub fn route_authoritative_actor_effects(",
        "pub fn route_closeout_drain_effects(",
        "pub fn route_command_effects(",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route runtime effect bundle assembly after it moves to route IO: {forbidden_snippet}"
        );
    }

    for required_snippet in [
        "pub fn route_dispatch_effects(",
        "pub fn route_admission_effects(",
        "pub fn route_busy_pane_retry_effects(",
        "pub fn route_queue_effects(",
        "pub fn route_document_prep_effects(",
        "pub fn enqueue_route_dispatch_prompt_for_dispatch_only(",
        "pub fn dispatch_only_starting_pane_ready_timeout(",
        "pub fn route_dispatch_only_effects(",
        "pub fn route_startup_effects(",
        "pub fn route_managed_pane_resolution_effects(",
        "pub fn route_authoritative_actor_effects(",
        "pub fn route_closeout_drain_effects(",
        "pub fn route_command_effects(",
        "fn route_run_pending_maintenance(",
        "fn route_inspect_session(",
        "fn route_decide_closeout_recovery(",
        "file_route_dispatch_bug_report_with_runtime_effects",
        "route_write_document",
        "enqueue_route_dispatch_prompt(",
        "dispatch_only_starting_pane_ready_timeout_for_binary",
        "wait_for_ready_override: crate::invocation::wait_for_ready_override",
    ] {
        assert!(
            runtime_effects.contains(required_snippet),
            "agent-doc-route-io runtime_effects should own route effect bundle assembly: {required_snippet}"
        );
    }
    assert!(
        route_io_lib.contains("pub mod runtime_effects;")
            && route_source.contains("fn runtime_route_command_effects() -> RouteCommandEffects")
            && route_source.contains("route_command_effects(route_repair_closeout)")
            && main_source.contains("agent_doc_route_io::runtime_effects::route_command_effects(")
            && main_source.contains("route_repair_closeout")
            && !main_source
                .contains("agent_doc_orchestration::route::runtime_route_command_effects()")
            && !main_source.contains("agent_doc_orchestration::route::route_startup_effects()"),
        "production route command should consume focused route runtime effects directly while orchestration keeps only a test adapter"
    );
}

#[test]
fn test_agent_doc_route_io_owns_route_closeout_drain() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/lib.rs")).unwrap();
    let closeout_drain =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/closeout_drain.rs")).unwrap();

    for forbidden_snippet in [
        "fn drain_open_closeout_before_routed_dispatch(",
        "fn classify_route_closeout_block(",
        "const DRAIN_MAX_ATTEMPTS",
        "dispatch_drain_retry_decision(",
        "classify_closeout_block_dispatch(",
        "route_dispatch_drain_pending_maintenance_warning",
        "agent_doc_queue::queue_continuation::live_continuation_head(&content)",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own route closeout drain/classification after it moves to route IO: {forbidden_snippet}"
        );
    }

    assert!(
        route_io_lib.contains("pub mod closeout_drain;")
            && closeout_drain.contains("pub struct RouteCloseoutDrainEffects")
            && closeout_drain.contains("pub fn drain_open_closeout_before_routed_dispatch(")
            && closeout_drain.contains("pub fn classify_route_closeout_block(")
            && closeout_drain
                .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)")
            && closeout_drain
                .contains("agent_doc_document_realtime_io::try_resolve_current_document_content(")
            && closeout_drain.contains("\"route_closeout_block_active_queue_head\"")
            && closeout_drain.contains("await_closeout_projection")
            && closeout_drain.contains("project_closeout_drain(")
            && closeout_drain.contains("classify_closeout_block_dispatch(")
            && closeout_drain.contains("agent_doc_ops_log_io::log_op")
            && closeout_drain
                .contains("agent_doc_queue::queue_continuation::live_continuation_head"),
        "route closeout drain and block classification should live in agent-doc-route-io while orchestration injects only runtime closeout effects"
    );
    assert!(
        !closeout_drain.contains("std::fs::read_to_string(file)")
            && !closeout_drain.contains("fs::read_to_string(file)")
            && !closeout_drain.contains("std::thread::sleep"),
        "route closeout drain must await controller projections instead of reading active documents or sleeping"
    );
}

#[test]
fn test_agent_doc_route_io_owns_authoritative_dispatch_loop() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/lib.rs")).unwrap();
    let authoritative_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_dispatch.rs"))
            .unwrap();
    let authoritative_actor =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/authoritative_actor.rs"))
            .unwrap();
    let pane_resolution =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/pane_resolution.rs")).unwrap();

    for forbidden_snippet in [
        "fn route_via_authoritative_actor(",
        "decide_authoritative_reopen(RoutedReopenFacts",
        "classify_authoritative_actor_dispatch_action(",
        "AuthoritativeActorDispatchAction::",
        "RouteCloseoutDrainOutcome::",
        "dispatch_only_busy_should_wait_for_ready(",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own the authoritative actor dispatch loop after it moves to route IO: {forbidden_snippet}"
        );
    }

    assert!(
        route_io_lib.contains("pub mod authoritative_dispatch;")
            && authoritative_dispatch.contains("pub struct RouteAuthoritativeActorEffects")
            && authoritative_dispatch.contains("pub fn route_via_authoritative_actor(")
            && authoritative_dispatch.contains("decide_authoritative_reopen(RoutedReopenFacts")
            && authoritative_dispatch.contains("classify_authoritative_actor_dispatch_action(")
            && authoritative_dispatch.contains("AuthoritativeActorDispatchAction::")
            && authoritative_dispatch.contains("RouteCloseoutDrainOutcome::")
            && authoritative_dispatch.contains("dispatch_only_busy_should_wait_for_ready(")
            && authoritative_dispatch.contains("dispatch_via_supervisor_ipc(")
            && authoritative_dispatch.contains("require_routed_admission_projection(")
            && authoritative_dispatch.contains("dispatch_only_send_reopen(")
            && authoritative_dispatch.contains("activate_existing_route_queue_head(")
            && authoritative_actor.contains("pub fn managed_capability_proof_status(")
            && authoritative_actor.contains("fn document_declares_expected_harness(")
            && authoritative_actor
                .contains("agent_doc_document_realtime_io::try_resolve_current_document_content(")
            && authoritative_actor.contains("\"route_managed_capability_proof_status\"")
            && authoritative_actor.contains("\"route_authoritative_expected_harness\"")
            && pane_resolution.contains("RouteAuthoritativeActorEffects")
            && pane_resolution.contains("route_via_authoritative_actor("),
        "agent-doc-route-io authoritative_dispatch should own authoritative actor reroute decisions and pane resolution should call it directly"
    );
    assert!(
        !authoritative_actor.contains("std::fs::read_to_string(file)")
            && !authoritative_actor.contains("fs::read_to_string(file)"),
        "route authoritative actor helpers must not read active documents directly from disk"
    );
}

#[test]
fn test_agent_doc_route_io_owns_route_command_runtime() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let route_source =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/tests/route.rs")).unwrap();
    let route_io_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/lib.rs")).unwrap();
    let route_command =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/command.rs")).unwrap();
    let route_invocation =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/invocation.rs")).unwrap();
    let route_runtime_effects =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/runtime_effects.rs")).unwrap();
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();

    for forbidden_snippet in [
        "agent_doc_sync_io::resync::prune_with_tmux_timed_in_mode",
        "agent_doc_queue_io::continuation_marker::clear_cooldown_marker",
        "prepare_route_document(file,",
        "parse_for_file_with_context(\n        &updated_content",
        "agent_doc_git_io::dirs::resolve_absolute_file_path(file)",
        "resolve_target_session(tmux",
        "clear_for_success(\n                file,\n                \"route_success\"",
        "cleanup_failed_route_panes(tmux",
        "pub fn route_command_effects() -> RouteCommandEffects",
        "fn route_run_pending_maintenance(",
        "fn route_inspect_session(",
        "fn route_decide_closeout_recovery(",
        "pub fn route_closeout_drain_effects() -> RouteCloseoutDrainEffects",
        "static WAIT_FOR_READY_OVERRIDE",
        "static WAIT_FOR_READY_DEADLINE",
        "static FORCE_DISK_ROUTE_WRITES",
    ] {
        assert!(
            !route_source.contains(forbidden_snippet),
            "route.rs must not re-own the top-level route command runtime or invocation state after it moves to route IO: {forbidden_snippet}"
        );
    }

    assert!(
        route_io_lib.contains("pub mod command;")
            && route_io_lib.contains("pub mod invocation;")
            && route_command.contains("pub enum RouteMode")
            && route_command.contains("pub struct RouteCommandEffects")
            && route_command.contains("pub fn run_with_tmux_with_options(")
            && route_command.contains("agent_doc_sync_io::resync::prune_with_tmux_timed_in_mode")
            && route_command.contains(
                "agent_doc_controller_io::project_controller::clear_queue_context_clear_manual_cooldown_for_file"
            )
            && route_command
                .contains("prepare_route_document(file, effects.document_prep_effects)")
            && route_command
                .contains("agent_doc_frontmatter_io::session::parse_for_file_with_context")
            && route_command.contains("agent_doc_git_io::dirs::resolve_absolute_file_path(file)")
            && route_command.contains("resolve_target_session(tmux")
            && route_command.contains("crate::pane_resolution::resolve_or_create_pane(")
            && route_command
                .contains("crate::pane_resolution::resolve_or_create_pane_dispatch_only(")
            && route_command
                .contains("agent_doc_controller_io::editor_route_errors::clear_for_success")
            && route_command.contains("cleanup_failed_route_panes(tmux")
            && route_invocation.contains("static WAIT_FOR_READY_DEADLINE")
            && route_invocation.contains("static FORCE_DISK_ROUTE_WRITES")
            && route_invocation.contains("pub fn wait_for_ready_override(")
            && route_invocation.contains("pub fn force_disk_route_writes(")
            && route_invocation.contains("pub fn run_with_tmux_with_options(")
            && route_invocation.contains("command::run_with_tmux_with_options(")
            && route_runtime_effects
                .contains("pub fn route_command_effects(repair_closeout: fn(&Path) -> Result<String>) -> RouteCommandEffects")
            && route_runtime_effects.contains("pub fn route_managed_pane_resolution_effects(")
            && route_runtime_effects.contains("pub fn route_authoritative_actor_effects(")
            && route_runtime_effects.contains("pub fn route_closeout_drain_effects(")
            && route_runtime_effects.contains("fn route_run_pending_maintenance(")
            && route_runtime_effects.contains("fn route_inspect_session(")
            && route_runtime_effects.contains("fn route_decide_closeout_recovery(")
            && route_source.contains("#[cfg(test)]\nuse agent_doc_route_io::command::RouteMode;")
            && !route_source.contains("pub use agent_doc_route_io::command::RouteMode;")
            && route_source.contains("#[cfg(test)]\nfn runtime_route_command_effects() -> RouteCommandEffects")
            && route_source.contains("route_command_effects(route_repair_closeout)")
            && route_source.contains("#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\nfn run_with_tmux(")
            && !route_source.contains("#[cfg(test)]\npub fn run(")
            && !route_source.contains("#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\npub fn run_with_force_disk(")
            && !route_source.contains("#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\npub fn run_with_tmux(")
            && !route_source.contains("#[cfg(test)]\nfn run(")
            && !route_source.contains("#[cfg(test)]\n#[allow(clippy::too_many_arguments)]\nfn run_with_force_disk(")
            && !route_source.contains("fn run_with_tmux_with_options(")
            && route_source.contains("agent_doc_route_io::invocation::run_with_tmux(")
            && main_source.contains("agent_doc_route_io::invocation::run_with_force_disk(")
            && main_source
                .contains("agent_doc_route_io::runtime_effects::route_command_effects(")
            && main_source.contains("route_repair_closeout")
            && !main_source.contains("agent_doc_orchestration::route::runtime_route_command_effects()")
            && !main_source.contains("agent_doc_orchestration::route::run_with_force_disk(")
            && !main_source.contains("agent_doc_orchestration::route::RouteMode"),
        "agent-doc-route-io command/invocation/runtime_effects should own top-level route runtime while main injects only repair closeout"
    );
}

#[test]
fn test_exchange_recovery_reenters_the_monotonic_write_pipeline() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let convergence =
        fs::read_to_string(manifest_dir.join("agent-doc-write-converge-io/src/lib.rs")).unwrap();
    for required in [
        "pub trait EditorConvergenceEffects",
        "pub fn poll_visible_write_text_lazily_event_or_projection(",
        "pub fn try_editor_converge(",
        "pub fn converge_document_or_disk(",
        "EditorIntent::ApplyCanonical",
    ] {
        assert!(
            convergence.contains(required),
            "missing convergence seam: {required}"
        );
    }
    for forbidden in [
        "pub fn ipc_direct_disk_degraded",
        "struct FileIpcDeliveryOptions",
        "fn try_editor_converge_file_ipc(",
        "pub fn write_file_ipc_and_poll_delivery(",
        ".agent-doc/ack-content",
    ] {
        assert!(
            !convergence.contains(forbidden),
            "retired recovery path remains: {forbidden}"
        );
    }

    let pipeline =
        fs::read_to_string(manifest_dir.join("agent-doc-state-backbone/src/write_pipeline.rs"))
            .unwrap();
    for phase in [
        "IntentCaptured",
        "CanonicalApplied",
        "ReplicaAccepted",
        "ReplicaVisible",
        "DiskProjected",
        "Committed",
    ] {
        assert!(pipeline.contains(phase), "missing monotonic phase: {phase}");
    }
}
#[test]
fn test_agent_doc_controller_owns_route_text_predicates() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-route-io")),
        "agent-doc-route-io must stay a first-class workspace crate for route tmux/session resolution effects"
    );

    let controller_dispatch =
        fs::read_to_string(manifest_dir.join("agent-doc-controller/src/dispatch.rs")).unwrap();
    for required_snippet in [
        "pub fn is_codex_shell_search_blocker",
        "pub fn normalize_context_session",
        "pub fn is_stash_window_name",
    ] {
        assert!(
            controller_dispatch.contains(required_snippet),
            "agent-doc-controller must own route textual predicate policy: {required_snippet}"
        );
    }

    for relative_path in [
        "agent-doc-route-io/src/busy_pane.rs",
        "agent-doc-route-io/src/session_resolution.rs",
        "agent-doc-sync-io/src/sync.rs",
        "agent-doc-sync-io/src/resync.rs",
    ] {
        let source = fs::read_to_string(manifest_dir.join(relative_path)).unwrap();
        for forbidden_snippet in [
            "pub(crate) use agent_doc_controller::dispatch",
            "pub fn is_codex_shell_search_blocker",
            "pub(crate) fn is_codex_shell_search_blocker",
            "fn normalize_context_session",
            "fn is_stash_window_name(",
        ] {
            assert!(
                !source.contains(forbidden_snippet),
                "{relative_path} must not re-own or facade route textual predicate policy: {forbidden_snippet}"
            );
        }
    }
}

#[test]
fn test_agent_doc_sync_owns_sync_scope_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_manifest = fs::read_to_string(manifest_dir.join("Cargo.toml")).unwrap();
    let workspace: toml::Value = toml::from_str(&workspace_manifest).unwrap();
    let members = workspace["workspace"]["members"].as_array().unwrap();

    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-sync")),
        "agent-doc-sync must stay a first-class workspace crate"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-sync-io")),
        "agent-doc-sync-io must stay a first-class workspace crate for sync lock/status effects"
    );
    assert!(
        members
            .iter()
            .any(|member| member.as_str() == Some("agent-doc-process-owner-io")),
        "agent-doc-process-owner-io must stay a first-class workspace crate for live process-owner inspection"
    );

    let sync_manifest = fs::read_to_string(manifest_dir.join("agent-doc-sync/Cargo.toml")).unwrap();
    let sync: toml::Value = toml::from_str(&sync_manifest).unwrap();
    let dependencies = sync["dependencies"].as_table().unwrap();
    assert!(
        dependencies.contains_key("agent-doc-fs"),
        "sync scope root policy may depend on focused filesystem root discovery"
    );
    for forbidden_dependency in [
        "agent-doc-orchestration",
        "agent-doc-tmux",
        "agent-doc-tmux-commands",
        "agent-doc-tmux-io",
        "tmux-router",
        "notify",
        "rusqlite",
        "interprocess",
    ] {
        assert!(
            !dependencies.contains_key(forbidden_dependency),
            "agent-doc-sync scope policy must stay free of orchestration and tmux/effect crates: {forbidden_dependency}"
        );
    }

    let sync_source = fs::read_to_string(manifest_dir.join("agent-doc-sync/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub fn normalize_scope_arg",
        "pub fn sync_candidate_files",
        "pub fn canonical_sync_candidate_files",
        "pub fn common_ancestor_dir",
        "pub const RENAME_DEBOUNCE_TTL_SECS",
        "pub const SYNC_WINDOW_RESOLUTION_BUDGET",
        "pub const SYNC_PRUNE_BUDGET",
        "pub const SYNC_PRUNE_SUBPHASE_BUDGET",
        "pub const SYNC_LOCK_WAIT_LATENCY_BUDGET",
        "pub const SYNC_PRELOCK_ACTOR_FOCUS_BUDGET",
        "pub const SYNC_CONTROLLER_ACTOR_LOOKUP_BUDGET",
        "pub const SYNC_PROJECTION_REFRESH_BUDGET",
        "pub const SYNC_OWNERSHIP_PROOF_BUDGET",
        "pub const SYNC_ROUTER_BUDGET",
        "pub const SYNC_SAFE_PASSIVE_TOTAL_BUDGET",
        "pub const SYNC_LOCK_WAIT_BUDGET",
        "pub fn shared_sync_scope_root",
        "pub fn sync_scope_root",
        "pub fn layout_state_scope_root",
        "pub fn latency_budget_status",
        "pub fn sync_latency_message",
        "pub const SYNC_FRONTMATTER_STATUS_PREFIX",
        "pub fn sync_frontmatter_status_message",
        "pub const SAFE_PASSIVE_SYNC_LOCK_SKIPPED_MARKER",
        "pub fn safe_passive_lock_contention_message",
        "pub fn duration_millis_saturating",
        "pub fn epoch_millis_now",
        "pub fn sanitize_coordination_scope_component",
        "pub fn planned_stash_window_indices",
        "pub enum AutoStartMode",
        "pub fn destructive_repair_throttle_state_key",
        "pub fn rename_debounce_expired",
        "pub fn auto_started_panes_summary",
        "pub enum WindowIndexNormalizationPlan",
        "pub fn plan_window_index_normalization",
        "pub fn effective_sync_columns",
        "pub fn is_file_rename",
        "pub fn superseded_candidates",
        "pub struct SyntheticRegistryCandidateFacts",
        "pub enum SyntheticRegistryDuplicateBasis",
        "pub enum SyntheticRegistryDuplicateResolution",
        "pub struct SyntheticRegistryCandidateFilter",
        "pub fn filter_synthetic_registry_candidate_facts",
        "pub struct ResyncTargetMatcher",
        "pub fn same_document_path",
        "pub fn candidate_matches_target",
        "pub fn registry_file_for_target",
    ] {
        assert!(
            sync_source.contains(required_snippet),
            "agent-doc-sync must own sync scope policy: {required_snippet}"
        );
    }
    let sync_layout_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/layout.rs")).unwrap();
    assert!(
        sync_layout_source.contains("agent_doc_sync::filter_synthetic_registry_candidate_facts")
            && sync_layout_source.contains("agent_doc_sync::SyntheticRegistryCandidateFacts"),
        "sync/layout.rs should adapt synthetic registry candidate facts into focused sync policy"
    );
    for forbidden_snippet in [
        "let live_owner_matches: Vec<usize>",
        "let pane_root_matches: Vec<usize>",
        "if live_owner_matches.len() == 1",
        "pane_root_matches.len() == 1",
    ] {
        assert!(
            !sync_layout_source.contains(forbidden_snippet),
            "sync/layout.rs must not re-own duplicate synthetic registry candidate policy: {forbidden_snippet}"
        );
    }

    let sync_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/Cargo.toml")).unwrap();
    let sync_io: toml::Value = toml::from_str(&sync_io_manifest).unwrap();
    let sync_io_dependencies = sync_io["dependencies"].as_table().unwrap();
    for required_dependency in ["agent-doc-project-root-io", "agent-doc-sync", "fs2"] {
        assert!(
            sync_io_dependencies.contains_key(required_dependency),
            "agent-doc-sync-io should own sync lock/process effects dependency: {required_dependency}"
        );
    }
    for forbidden_dependency in [
        "agent-doc-orchestration",
        "agent-doc-tmux-commands",
        "notify",
        "rusqlite",
        "interprocess",
    ] {
        assert!(
            !sync_io_dependencies.contains_key(forbidden_dependency),
            "agent-doc-sync-io must not regain orchestration or unrelated command/watch/db/socket dependencies: {forbidden_dependency}"
        );
    }
    let sync_io_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/lib.rs")).unwrap();
    for required_snippet in [
        "pub enum SyncLockAcquire",
        "pub fn acquire_sync_lock(",
        "pub fn write_sync_status_with(",
        "pub fn surface_frontmatter_status_with(",
        "pub fn clear_frontmatter_status_with(",
        "fn resolve_current_document(&self, file: &Path, source: &str) -> Result<String>;",
        "fn write_current_document(&self, file: &Path, content: &str) -> Result<()>;",
        "resolve_current_document(file, \"sync_status_document\")",
        "write_current_document(file, &updated)",
        "agent_doc_project_root_io::project_root_containing(",
        "agent_doc_sync::sync_frontmatter_status_message",
        "agent_doc_sync::SYNC_FRONTMATTER_STATUS_PREFIX",
    ] {
        assert!(
            sync_io_source.contains(required_snippet),
            "agent-doc-sync-io must own sync lock/process/status IO directly: {required_snippet}"
        );
    }
    let sync_io_prod = sync_io_source.split("#[cfg(test)]").next().unwrap();
    for forbidden in [
        "let doc = std::fs::read_to_string(file)",
        "let doc = match std::fs::read_to_string(file)",
        "std::fs::write(file, &updated)",
    ] {
        assert!(
            !sync_io_prod.contains(forbidden),
            "sync status production IO must route active document reads/writes through runtime document authority: {forbidden}"
        );
    }
    let main_source = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    for required in [
        "fn resolve_current_document(&self, file: &Path, source: &str) -> anyhow::Result<String>",
        "agent_doc_document_realtime_io::try_resolve_current_document_content(file, source)",
        "fn write_current_document(&self, file: &Path, content: &str) -> anyhow::Result<()>",
        "agent_doc_document_realtime_io::atomic_write_through_authority(file, content)",
    ] {
        assert!(
            main_source.contains(required),
            "CLI sync runtime effects should bind sync status document IO to realtime authority: {required}"
        );
    }
    let sync_resync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/resync.rs")).unwrap();
    for required in [
        "fn finish_turn_current_document_hash(file: &Path) -> Option<String>",
        "resolve_current_document(file, \"resync_finish_turn_document\")",
    ] {
        assert!(
            sync_resync_source.contains(required),
            "resync finish-turn progress checks should read through sync runtime document authority: {required}"
        );
    }
    assert!(
        !sync_resync_source.contains("std::fs::read_to_string(file)")
            && !sync_resync_source.contains("fs::read_to_string(file)"),
        "resync production helpers must not read the active session document directly"
    );
    let sync_pane_repair_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/pane_repair.rs")).unwrap();
    for required in [
        "resolve_current_document(file, \"sync_harness_document\")",
        "rc.set_doc_content(content)",
        "agent_doc_cycle_state_io::load_with_closeout_projection(file)",
    ] {
        assert!(
            sync_pane_repair_source.contains(required),
            "sync pane-repair harness resolution should read through sync runtime document authority: {required}"
        );
    }
    assert!(
        !sync_pane_repair_source.contains("std::fs::read_to_string(file)")
            && !sync_pane_repair_source.contains("fs::read_to_string(file)"),
        "sync pane-repair production helpers must not read the active session document directly"
    );
    let sync_registry_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync/registry.rs")).unwrap();
    assert!(
        sync_registry_source
            .contains("agent_doc_cycle_state_io::load_with_closeout_projection(file)"),
        "sync registry cycle phase labels should use the projection-aware cycle view"
    );
    let process_owner_io_manifest =
        fs::read_to_string(manifest_dir.join("agent-doc-process-owner-io/Cargo.toml")).unwrap();
    let process_owner_io: toml::Value = toml::from_str(&process_owner_io_manifest).unwrap();
    let process_owner_io_dependencies = process_owner_io["dependencies"].as_table().unwrap();
    assert!(
        process_owner_io_dependencies.contains_key("agent-doc-controller"),
        "agent-doc-process-owner-io should compose process observations with controller command-line policy"
    );
    for forbidden_dependency in [
        "agent-doc-orchestration",
        "agent-doc-sync-io",
        "agent-doc-tmux",
        "agent-doc-tmux-commands",
        "agent-doc-tmux-io",
        "tmux-router",
        "notify",
        "rusqlite",
        "interprocess",
    ] {
        assert!(
            !process_owner_io_dependencies.contains_key(forbidden_dependency),
            "agent-doc-process-owner-io must stay free of orchestration, sync, and tmux adapters: {forbidden_dependency}"
        );
    }
    // The crate's traversal is split across `lib.rs` (call surface + pure tree
    // lifts), `proc_table.rs` (the `/proc` observation) and `owner_graph.rs`
    // (the derived owner map). The guard is about the crate owning that
    // responsibility, not about which file it lands in, so read the whole crate.
    let process_owner_io_source = read_process_owner_io_source(manifest_dir);
    for required_snippet in [
        "pub fn child_pids(",
        "pub fn process_command(",
        "pub fn process_tree_contains_pid(",
        // The traversal seam is `tree_pids` over an observed `/proc` snapshot,
        // not a test-only injected-children twin of the real walk.
        "pub fn tree_pids(",
        "pub fn process_tree_agent_doc_owner_pid_for_file(",
        "pub fn process_tree_has_agent_doc_owner_for_file(",
        "pub fn process_tree_has_agent_session(",
        "pub fn process_tree_owner_document_other_than(",
        "pub fn process_tree_owns_other_document(",
        "agent_doc_controller::command_line::{",
        "fn observe_proc_children(",
        "fn proc_process_command(",
    ] {
        assert!(
            process_owner_io_source.contains(required_snippet),
            "agent-doc-process-owner-io must own process-tree owner inspection directly: {required_snippet}"
        );
    }
    assert!(
        !process_owner_io_source.contains("Command::new(\"pgrep\")"),
        "agent-doc-process-owner-io must not spawn pgrep while traversing process trees"
    );

    let sync_runtime_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/sync.rs")).unwrap();
    let sync_safe_passive = read_first_existing_source(
        manifest_dir,
        &[
            "agent-doc-sync-io/src/sync/safe_passive.rs",
            "agent-doc-sync-io/src/sync.rs",
        ],
    );
    let route_session_resolution =
        fs::read_to_string(manifest_dir.join("agent-doc-route-io/src/session_resolution.rs"))
            .unwrap();
    let resync_source =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/resync.rs")).unwrap();
    let resync_prune =
        fs::read_to_string(manifest_dir.join("agent-doc-sync-io/src/resync/prune.rs")).unwrap();
    for forbidden_snippet in [
        "fn normalize_scope_arg",
        "fn sync_candidate_files(",
        "fn canonical_sync_candidate_files",
        "fn common_ancestor_dir",
        "const RENAME_DEBOUNCE_TTL_SECS",
        "const SYNC_WINDOW_RESOLUTION_BUDGET",
        "const SYNC_PRUNE_BUDGET",
        "const SYNC_PRUNE_SUBPHASE_BUDGET",
        "const SYNC_LOCK_WAIT_LATENCY_BUDGET",
        "const SYNC_PRELOCK_ACTOR_FOCUS_BUDGET",
        "const SYNC_CONTROLLER_ACTOR_LOOKUP_BUDGET",
        "const SYNC_PROJECTION_REFRESH_BUDGET",
        "const SYNC_OWNERSHIP_PROOF_BUDGET",
        "const SYNC_ROUTER_BUDGET",
        "const SYNC_SAFE_PASSIVE_TOTAL_BUDGET",
        "const SYNC_LOCK_WAIT_BUDGET",
        "const SYNC_LOCK_POLL_INTERVAL",
        "const STALE_SYNC_LOCK_OWNER_AGE",
        "pub fn shared_sync_scope_root",
        "fn sync_scope_root",
        "fn layout_state_scope_root_for_sync",
        "fn layout_state_path_for_sync",
        "fn sync_prune_state_path_for_sync",
        "fn latency_budget_status",
        "fn sync_latency_message",
        "const SYNC_FRONTMATTER_STATUS_PREFIX",
        "fn sync_frontmatter_status_message",
        "const SAFE_PASSIVE_SYNC_LOCK_SKIPPED_MARKER",
        "fn safe_passive_lock_contention_message",
        "fn destructive_repair_now_ms",
        "fn epoch_millis_now",
        "fn sanitize_coordination_scope_component",
        "fn sync_prune_fingerprint",
        "struct SyncPruneState",
        "fn sync_prune_state_update",
        "fn planned_stash_window_indices",
        "enum AutoStartMode",
        "fn safe_passive_prune_cleanup_throttle",
        "fn sync_repair_stamp_filename",
        "fn sync_repair_stamp_path",
        "fn rename_debounce_expired",
        "fn auto_started_panes_summary",
        "enum WindowIndexNormalizationPlan",
        "fn plan_window_index_normalization",
        "const SAFE_PASSIVE_STASH_CLEANUP_THROTTLE",
        "serde_json::from_str::<SyncPruneState>",
        "fn effective_sync_columns",
        "pub fn is_file_rename",
        "fn same_document_path",
        "fn candidate_matches_target",
        "fn registry_file_for_target",
        "enum SyncLockAcquire",
        "fn acquire_sync_lock(",
        "fn reap_stale_orphaned_sync_lock_owners(",
        "fn sync_lock_process_from_proc(",
        "fn read_proc_ppid(",
        "fn read_proc_cmdline(",
        "fn read_proc_age(",
        "fn proc_has_fd_for_path(",
        "fn pane_process_tree_contains_pid(",
        "fn process_tree_contains_pid(",
        "fn pid_has_agent_doc_for_file(",
        "fn pid_is_agent_session(",
    ] {
        assert!(
            !sync_runtime_source.contains(forbidden_snippet)
                && !sync_safe_passive.contains(forbidden_snippet),
            "agent-doc-sync-io sync modules must not re-own or facade sync scope policy: {forbidden_snippet}"
        );
    }
    assert!(
        !manifest_dir
            .join("agent-doc-sync-io/src/sync/lock.rs")
            .exists(),
        "agent-doc-sync-io must not keep a nested sync lock/process IO facade"
    );
    assert!(
        !manifest_dir
            .join("agent-doc-sync-io/src/sync/frontmatter_status.rs")
            .exists(),
        "agent-doc-sync-io must not keep a nested sync frontmatter-status IO facade"
    );
    for forbidden_snippet in [
        "fn same_document_path",
        "fn candidate_matches_target",
        "fn registry_file_for_target",
        "fn superseded_candidates",
        "fn process_tree_contains_pid(",
    ] {
        assert!(
            !resync_source.contains(forbidden_snippet) && !resync_prune.contains(forbidden_snippet),
            "agent-doc-sync-io resync must not re-own or facade target matching policy: {forbidden_snippet}"
        );
    }
    assert!(
        sync_runtime_source.contains("agent_doc_sync::normalize_scope_arg")
            && sync_runtime_source.contains("agent_doc_sync::shared_sync_scope_root")
            && sync_runtime_source.contains("agent_doc_sync::layout_state_scope_root")
            && sync_runtime_source.contains("use agent_doc_sync::{")
            && sync_runtime_source.contains("effective_sync_columns")
            && sync_runtime_source.contains("is_file_rename")
            && sync_runtime_source.contains("latency_budget_status")
            && sync_runtime_source.contains("sync_latency_message")
            && sync_runtime_source.contains("agent_doc_sync::safe_passive_lock_contention_message")
            && sync_runtime_source.contains("crate::surface_frontmatter_status_with")
            && sync_runtime_source.contains("crate::clear_frontmatter_status_with")
            && sync_runtime_source.contains("planned_stash_window_indices")
            && sync_runtime_source.contains("AutoStartMode")
            && sync_runtime_source.contains("epoch_millis_now")
            && sync_runtime_source.contains("destructive_repair_throttle_state_key")
            && sync_runtime_source.contains("load_project_runtime_state_from_db")
            && sync_runtime_source.contains("upsert_project_runtime_state_in_db")
            && sync_runtime_source.contains("rename_debounce_expired")
            && sync_runtime_source.contains("auto_started_panes_summary")
            && sync_runtime_source.contains("WindowIndexNormalizationPlan")
            && sync_runtime_source.contains("plan_window_index_normalization")
            && sync_runtime_source.contains("use crate::acquire_sync_lock;")
            && sync_runtime_source.contains("acquire_sync_lock(lock_path, sync_lock_wait_budget")
            && sync_runtime_source
                .contains("agent_doc_process_owner_io::process_tree_contains_pid(")
            && sync_runtime_source
                .contains("agent_doc_process_owner_io::process_tree_agent_doc_owner_pid_for_file(")
            && sync_runtime_source
                .contains("agent_doc_process_owner_io::process_tree_has_agent_doc_owner_for_file(")
            && route_session_resolution.contains("agent_doc_sync::shared_sync_scope_root"),
        "agent-doc-sync-io runtime graph should call focused sync policy and process-owner IO crates directly, while route session resolution keeps using focused sync scope policy"
    );
    assert!(
        resync_source.contains("use agent_doc_sync::{")
            && resync_source.contains("ResyncTargetMatcher")
            && resync_source.contains("superseded_candidates")
            && resync_source.contains("ResyncTargetMatcher::new")
            && resync_source.contains("superseded_candidates(canonical, drift_sessions)")
            && resync_source.contains("agent_doc_process_owner_io::process_tree_contains_pid(")
            && resync_prune.contains("ResyncTargetMatcher::new"),
        "agent-doc-sync-io resync should call focused target matching/planner and process-owner IO directly"
    );
}

#[test]
fn test_agent_doc_template_owns_patch_sanitization_policy() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let template_sanitize =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/sanitize.rs")).unwrap();
    for required_snippet in [
        "pub fn sanitize_component_tags",
        "pub fn sanitize_patches",
        "pub fn sanitize_unmatched",
        "fn utf8_char_len",
        "fn find_comment_close",
    ] {
        assert!(
            template_sanitize.contains(required_snippet),
            "agent-doc-template must own template patch sanitization policy: {required_snippet}"
        );
    }

    let template_lib =
        fs::read_to_string(manifest_dir.join("agent-doc-template/src/lib.rs")).unwrap();
    assert!(
        template_lib.contains("pub mod sanitize;"),
        "agent-doc-template should expose sanitization through its owning module"
    );
    assert!(
        !template_lib.contains("pub use sanitize"),
        "agent-doc-template should not add a sanitization root facade"
    );

    let write_source =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();
    for forbidden_snippet in [
        "pub fn sanitize_component_tags",
        "pub fn sanitize_patches",
        "pub fn sanitize_unmatched",
        "fn utf8_char_len",
        "fn find_comment_close",
    ] {
        assert!(
            !write_source.contains(forbidden_snippet),
            "orchestration must not re-own or facade template sanitization policy: {forbidden_snippet}"
        );
    }

    let write_run_entry =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/run_entry.rs"))
            .unwrap();
    let write_materialize = fs::read_to_string(
        manifest_dir.join("agent-doc-template-io/src/response_materialization_io.rs"),
    )
    .unwrap();
    let template_io_backlog =
        fs::read_to_string(manifest_dir.join("agent-doc-template-io/src/backlog_normalization.rs"))
            .unwrap();
    let run_source = fs::read_to_string(manifest_dir.join("agent-doc-run-io/src/lib.rs")).unwrap();
    for (source, content) in [
        (
            "agent-doc-write-runtime-io/src/run_entry.rs",
            write_run_entry.as_str(),
        ),
        (
            "agent-doc-template-io/src/backlog_normalization.rs",
            template_io_backlog.as_str(),
        ),
    ] {
        assert!(
            content.contains("agent_doc_template::sanitize")
                || content.contains("template::sanitize"),
            "template write adapters should call focused sanitization directly in {source}"
        );
    }
    assert!(
        run_source.contains("agent_doc_template_io::{")
            && run_source.contains("normalize_backlog_patch_response"),
        "run IO should delegate pending patch normalization to focused template IO"
    );
    assert!(
        write_materialize.contains(
            "agent_doc_template::response_materialization::strip_partial_response_materialization_from_exchange"
        ) && !write_materialize.contains("agent_doc_template::sanitize")
            && !write_materialize.contains("template::sanitize"),
        "response_materialization_io.rs should stay limited to response materialization helpers"
    );
}

#[test]
fn test_codex_plugin_manifest_omits_invalid_claude_skill_path() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let manifest_path = manifest_dir.join(".codex-plugin/plugin.json");
    let manifest = fs::read_to_string(&manifest_path).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&manifest).unwrap();

    assert!(
        parsed.get("skills").is_none(),
        "Codex plugin manifests must not point skills at .claude/skills; use ./skills/ only when a Codex skills tree exists"
    );

    for field in ["composerIcon", "logo"] {
        let path = parsed["interface"][field].as_str().unwrap();
        assert!(
            path.starts_with("./assets/") && !path.contains(".."),
            "{field} must be a plugin-root-relative asset path, got {path}"
        );
        assert!(
            manifest_dir.join(path.trim_start_matches("./")).exists(),
            "{field} asset does not exist: {path}"
        );
    }
}

#[test]
fn test_cli_run_requires_file() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("run");
    cmd.assert().failure();
}

#[test]
fn test_cli_patch_replaces_exchange_even_when_component_is_append_mode() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    fs::create_dir_all(root.join(".agent-doc/snapshots")).unwrap();
    fs::write(&doc, template_doc("Session", "old exchange body\n", "", "")).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args([
        "patch",
        doc.to_str().unwrap(),
        "exchange",
        "new exchange body\n",
    ]);
    cmd.assert().success();

    let content = fs::read_to_string(&doc).unwrap();
    assert!(content.contains("new exchange body"));
    assert!(!content.contains("old exchange body"));
}

#[test]
fn test_commit_explains_head_current_follow_up_without_repair_body_noise() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let committed = "---\nagent_doc_format: template\nagent_doc_write: crdt\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior response — gpt-5\n\
        Already committed.\n\
        <!-- agent:boundary:head-boundary -->\n\
        <!-- /agent:exchange -->\n";
    fs::write(&doc, committed).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, committed);

    let working = "---\nagent_doc_format: template\nagent_doc_write: crdt\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior response — gpt-5\n\
        Already committed.\n\
        <!-- agent:boundary:head-boundary -->\n\
        ❯ write response back\n\
        ❯ commit\n\
        <!-- /agent:exchange -->\n";
    fs::write(&doc, working).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args(["commit", doc.to_str().unwrap()]);
    cmd.assert().success();
    let head = ProcessCommand::new("git")
        .current_dir(root)
        .args(["show", "HEAD:session.md"])
        .output()
        .unwrap();
    let head = String::from_utf8(head.stdout).unwrap();
    assert!(!head.contains("❯ write response back"));
    assert!(!head.contains("❯ commit"));
    let working = fs::read_to_string(&doc).unwrap();
    assert!(working.contains("❯ write response back"));
    assert!(working.contains("❯ commit"));
}

#[test]
fn test_preflight_active_auto_queue_head_is_not_user_intent() {
    // #agent-doc-bug auto-queue stall: with an active `auto` queue and NO real
    // user/document diff this cycle, preflight synthesizes the queue head as the
    // cycle prompt. That synthetic continuation must NOT appear in
    // `user_intent_prompt_changes`, or the skill's auto-loop precondition never
    // holds and the queue stalls after each item. The head must still be exposed
    // via `queue_prompts` so the cycle has work to do.
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let content = "---\nagent_doc_session: test-session\nagent_doc_format: template\nagent_doc_write: crdt\nqueue_active: true\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior — gpt-5\n\nDone.\n\
        <!-- agent:boundary:head-boundary -->\n\
        <!-- /agent:exchange -->\n\n\
        <!-- agent:queue auto -->\n\
        - do [#alpha]\n\
        - do [#beta]\n\
        <!-- /agent:queue -->\n";
    fs::write(&doc, content).unwrap();
    // Commit is the baseline; no separate seeded snapshot. There is no real diff
    // this cycle, so the active queue head is the only prompt source — the stall
    // repro shape.
    init_git_repo(root, &doc);

    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.args(["preflight", doc.to_str().unwrap()]);
    let output = preflight.output().unwrap();
    assert!(
        output.status.success(),
        "preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let parsed: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("preflight stdout must be JSON");

    assert_eq!(
        parsed["queue_active"],
        serde_json::Value::Bool(true),
        "queue should be active: {parsed}"
    );
    let queue_prompts = parsed["queue_prompts"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    assert!(
        !queue_prompts.is_empty(),
        "active queue must still expose its head as work: {parsed}"
    );
    // `user_intent_prompt_changes` is `skip_serializing_if` empty, so an empty
    // value is omitted (null) — exactly what we want here.
    let user_intent_empty = parsed["user_intent_prompt_changes"]
        .as_array()
        .is_none_or(|a| a.is_empty());
    assert!(
        user_intent_empty,
        "synthetic auto-queue head must NOT count as user intent (would stall the auto-loop): {}",
        parsed["user_intent_prompt_changes"]
    );
    assert!(
        parsed.get("prompt_bearing_changes").is_none(),
        "preflight JSON must not expose removed prompt_bearing_changes field: {parsed}"
    );
}

/// `#cleardrainsim`: pin the FULL preflight JSON drainability contract — not just
/// the `queue_continuation::drainable_head_count` unit — that the SKILL.md
/// auto-loop (`queue_continuation_required`) and the supervisor idle-watch both
/// depend on. A go-mode active queue whose only materialized heads are
/// `[operator-verify]` + inert-noise must emit `queue_continuation_required:false`
/// + `queue_drainable_head_count:0` (the `#qchurn` no-op-loop guard) WITHOUT the
///   non-stall guidance, so the auto-loop stops instead of churning. `[clean-session]`
///   heads stay drainable in place (`#qcontdrain`).
fn preflight_json(root: &Path, doc: &Path) -> serde_json::Value {
    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.args(["preflight", doc.to_str().unwrap()]);
    let output = preflight.output().unwrap();
    assert!(
        output.status.success(),
        "preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("preflight stdout must be JSON")
}

#[test]
fn test_preflight_drainability_contract_zero_when_only_deferred_and_noise() {
    // Active go-mode queue whose ONLY heads are an `[operator-verify]` id-head and
    // an inert artifact noise line. Neither is agent-drainable, so the
    // authoritative no-loop signal must be `queue_continuation_required:false` +
    // `queue_drainable_head_count:0`, and the don't-stall guidance must be ABSENT.
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let content = "---\nagent_doc_session: test-session\nagent_doc_format: template\nagent_doc_write: crdt\nqueue_active: true\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior — gpt-5\n\nDone.\n\
        <!-- agent:boundary:head-boundary -->\n\
        <!-- /agent:exchange -->\n\n\
        ## Backlog\n\n\
        <!-- agent:backlog -->\n\
        - [ ] [#ov1] [operator-verify] live drive needs a human editor\n\
        <!-- /agent:backlog -->\n\n\
        ## Queue\n\n\
        <!-- agent:queue go -->\n\
        - do [#ov1]\n\
        - [route] target tmux session: 0\n\
        <!-- /agent:queue -->\n";
    fs::write(&doc, content).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, content);

    let parsed = preflight_json(root, &doc);
    assert_eq!(
        parsed["queue_active"],
        serde_json::Value::Bool(true),
        "queue should still be active: {parsed}"
    );
    assert_eq!(
        parsed["queue_drainable_head_count"], 0,
        "operator-verify + noise heads are not agent-drainable: {parsed}"
    );
    assert_eq!(
        parsed["queue_continuation_required"],
        serde_json::Value::Bool(false),
        "no drainable head → auto-loop must stop, not churn (#qchurn): {parsed}"
    );
    assert!(
        parsed["queue_continuation_guidance"].is_null(),
        "non-stall guidance must be absent when continuation is not required: {parsed}"
    );
}

#[test]
fn test_preflight_drainability_contract_true_with_real_drainable_head() {
    // Same active go-mode queue but now with a `[clean-session]` id-head (drains in
    // place, #qcontdrain) and a free-text directive head ("fix ...") alongside the
    // deferred `[operator-verify]` head and the inert noise line. The drainable
    // count must be EXACTLY 2 (clean-session + directive), continuation required,
    // and the shared non-stall guidance present.
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let content = "---\nagent_doc_session: test-session\nagent_doc_format: template\nagent_doc_write: crdt\nqueue_active: true\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior — gpt-5\n\nDone.\n\
        <!-- agent:boundary:head-boundary -->\n\
        <!-- /agent:exchange -->\n\n\
        ## Backlog\n\n\
        <!-- agent:backlog -->\n\
        - [ ] [#cs1] [clean-session] tighten the parser\n\
        - [ ] [#ov1] [operator-verify] live drive needs a human editor\n\
        <!-- /agent:backlog -->\n\n\
        ## Queue\n\n\
        <!-- agent:queue go -->\n\
        - do [#cs1]\n\
        - do [#ov1]\n\
        - fix the parser bug in the tokenizer\n\
        - [route] target tmux session: 0\n\
        <!-- /agent:queue -->\n";
    fs::write(&doc, content).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, content);

    let parsed = preflight_json(root, &doc);
    assert_eq!(
        parsed["queue_drainable_head_count"], 2,
        "clean-session id-head + free-text directive are drainable; operator-verify + noise are not: {parsed}"
    );
    assert_eq!(
        parsed["queue_continuation_required"],
        serde_json::Value::Bool(true),
        "a real drainable head remains → keep draining: {parsed}"
    );
    let guidance = parsed["queue_continuation_guidance"]
        .as_str()
        .expect("non-stall guidance must be present when continuation is required");
    assert!(
        guidance.contains("CP editor delivery") && guidance.contains("NOT stop reasons"),
        "guidance must carry the proven-delivery no-stall contract: {guidance}"
    );
}

#[test]
fn test_preflight_exchange_slash_command_is_command_only() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let baseline = "---\nagent_doc_session: test-session\nagent_doc_format: template\nagent_doc_write: crdt\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior — gpt-5\n\nDone.\n\
        <!-- /agent:exchange -->\n";
    fs::write(&doc, baseline).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, baseline);

    let current = baseline.replace(
        "<!-- /agent:exchange -->",
        "/clear\n<!-- /agent:exchange -->",
    );
    fs::write(&doc, current).unwrap();

    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.args(["preflight", doc.to_str().unwrap()]);
    let output = preflight.output().unwrap();
    assert!(
        output.status.success(),
        "preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let parsed: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("preflight stdout must be JSON");

    assert_eq!(parsed["no_changes"], false);
    assert_eq!(parsed["builtin_commands"][0], "/clear");
    assert!(
        parsed.get("prompt_bearing_changes").is_none(),
        "preflight JSON must not expose removed prompt_bearing_changes field: {parsed}"
    );
    assert!(
        parsed
            .get("user_intent_prompt_changes")
            .and_then(|value| value.as_array())
            .is_none_or(|changes| changes.is_empty()),
        "slash-only exchange diff must not count as user intent prompt work: {parsed}"
    );
    let phase = read_cycle_phase(root, &doc);
    assert!(
        !matches!(
            phase.as_deref(),
            Some("preflight_started" | "response_captured" | "write_applied")
        ),
        "slash-only exchange command must not open a response cycle, got {phase:?}"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("command-only"),
        "preflight should explain the command-only handoff:\n{stderr}"
    );
    assert!(
        !stderr.contains("preflight_diff_start"),
        "command-only handoff must not start a normal response cycle:\n{stderr}"
    );
}

#[test]
fn test_preflight_finalize_preflight_follow_up_lifecycle_has_no_stale_cycle() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let committed = "---\nagent_doc_session: test-session\nagent_doc_format: template\nagent_doc_write: crdt\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: prior response — gpt-5\n\
        Already committed.\n\
        <!-- agent:boundary:head-boundary -->\n\
        <!-- /agent:exchange -->\n";
    fs::write(&doc, committed).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, committed);

    let working = committed.replace(
        "<!-- agent:boundary:head-boundary -->",
        "❯ follow-up after dispatch\n<!-- agent:boundary:head-boundary -->",
    );
    fs::write(&doc, working).unwrap();

    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.args(["preflight", doc.to_str().unwrap()]);
    let output = preflight.output().unwrap();
    assert!(
        output.status.success(),
        "preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        !combined.contains("prior_patchback_without_response_body"),
        "preflight should not reopen missed-response repair for a follow-up prompt:\n{combined}"
    );

    let mut finalize = agent_doc_cmd();
    finalize.current_dir(root);
    finalize.args(["finalize", doc.to_str().unwrap(), "--origin", "skill"]);
    finalize
        .write_stdin(
            "<!-- patch:exchange -->\n### Re: follow-up — gpt-5\n\nHandled.\n<!-- /patch:exchange -->\n",
        )
        .assert()
        .success();

    let mut second_preflight = agent_doc_cmd();
    second_preflight.current_dir(root);
    second_preflight.args(["preflight", doc.to_str().unwrap()]);
    let second = second_preflight.output().unwrap();
    assert!(
        second.status.success(),
        "second preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&second.stdout),
        String::from_utf8_lossy(&second.stderr)
    );
    let second_combined = format!(
        "{}{}",
        String::from_utf8_lossy(&second.stdout),
        String::from_utf8_lossy(&second.stderr)
    );
    assert!(
        second_combined.contains("\"no_changes\": true"),
        "preflight after finalize should be clean:\n{second_combined}"
    );
    assert!(
        !second_combined.contains("snapshot/head guard mismatch")
            && !second_combined.contains("prior_patchback_without_response_body"),
        "clean follow-up lifecycle should not report stale cycle guards:\n{second_combined}"
    );
}

#[test]
fn test_preflight_warns_on_frontmatter_agent_harness_mismatch() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let content = concat!(
        "---\n",
        "agent_doc_session: test-session\n",
        "agent_doc_format: template\n",
        "agent: codex\n",
        "---\n\n",
        "## Exchange\n\n",
        "<!-- agent:exchange patch=append -->\n",
        "### Re: prior response — gpt-5\n",
        "Already committed.\n",
        "<!-- /agent:exchange -->\n",
    );
    fs::write(&doc, content).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, content);

    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.env("CLAUDE_CODE", "1");
    preflight.args(["preflight", doc.to_str().unwrap()]);
    let output = preflight.output().unwrap();
    assert!(
        output.status.success(),
        "preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value =
        serde_json::from_str(&stdout).expect("preflight output should be JSON");
    assert_eq!(json["warnings"][0]["code"], "harness_mismatch");
    assert_eq!(json["warnings"][0]["document_agent"], "codex");
    assert_eq!(json["warnings"][0]["active_harness"], "claude-code");
    assert_eq!(json["no_changes"], true);
}

#[test]
fn test_preflight_warns_but_does_not_target_inactive_queue_edit() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let baseline = concat!(
        "---\n",
        "agent_doc_session: test-session\n",
        "agent_doc_format: template\n",
        "agent_doc_write: crdt\n",
        "queue_active: false\n",
        "---\n\n",
        "## Exchange\n\n",
        "<!-- agent:exchange patch=append -->\n",
        "### Re: prior response — gpt-5\n",
        "Already committed.\n",
        "<!-- /agent:exchange -->\n\n",
        "<!-- agent:queue -->\n",
        "<!-- /agent:queue -->\n\n",
        "<!-- agent:backlog -->\n",
        "- [ ] [#gdbpropscan] Inspect graph DB properties.\n",
        "<!-- /agent:backlog -->\n",
    );
    let current = baseline.replace(
        "<!-- agent:queue -->\n<!-- /agent:queue -->",
        "<!-- agent:queue -->\n- do [#gdbpropscan]\n<!-- /agent:queue -->",
    );
    fs::write(&doc, baseline).unwrap();
    init_git_repo(root, &doc);
    seed_snapshot(root, &doc, baseline);
    fs::write(&doc, current).unwrap();

    let mut preflight = agent_doc_cmd();
    preflight.current_dir(root);
    preflight.args(["preflight", doc.to_str().unwrap()]);
    let output = preflight.output().unwrap();
    assert!(
        output.status.success(),
        "preflight failed:\nstdout={}\nstderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value =
        serde_json::from_str(&stdout).expect("preflight output should be JSON");
    assert!(
        json["warnings"].as_array().is_some_and(|warnings| warnings
            .iter()
            .any(|warning| warning["code"] == "inactive_queue_residue")),
        "a newly edited inactive queue should warn once without becoming executable context: {json}"
    );
    assert!(
        json.get("prompt_bearing_changes").is_none(),
        "preflight JSON must not expose removed prompt_bearing_changes field: {json}"
    );
    assert_eq!(json["queue_active"], serde_json::Value::Bool(false));
}

#[test]
fn test_cli_bare_file_path_aliases_to_run() {
    let tmp = tempfile::TempDir::new().unwrap();
    let missing = tmp.path().join("missing.md");

    let mut cmd = agent_doc_cmd();
    cmd.arg(&missing);
    cmd.env_remove("CLAUDECODE");
    cmd.env_remove("CLAUDE_CODE");
    cmd.env_remove("CLAUDE_CODE_SESSION");
    cmd.env_remove("OPENCODE");
    cmd.env_remove("OPENCODE_CLIENT");
    cmd.env_remove("CODEX");
    cmd.env_remove("CODEX_CLI");
    cmd.env_remove("CODEX_THREAD_ID");
    cmd.env("CODEX_SESSION", "codex-session");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));

    let mut plain_shell = agent_doc_cmd();
    plain_shell.arg(&missing);
    plain_shell.env_remove("CLAUDECODE");
    plain_shell.env_remove("CLAUDE_CODE");
    plain_shell.env_remove("CLAUDE_CODE_SESSION");
    plain_shell.env_remove("OPENCODE");
    plain_shell.env_remove("OPENCODE_CLIENT");
    plain_shell.env_remove("CODEX");
    plain_shell.env_remove("CODEX_CLI");
    plain_shell.env_remove("CODEX_SESSION");
    plain_shell.env_remove("CODEX_THREAD_ID");
    plain_shell.assert().failure().stderr(
        predicate::str::contains("bare `agent-doc <FILE>` must be run")
            .and(predicate::str::contains(
                "supported harness (Codex, Claude Code, or OpenCode)",
            ))
            .and(predicate::str::contains("agent-doc run <FILE>")),
    );
}

#[test]
fn test_cli_done_flag_has_no_removed_aliases() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let cli = fs::read_to_string(manifest_dir.join("src/main.rs")).unwrap();
    assert!(
        cli.contains(r#"#[arg(long = "done")]"#),
        "tracked-work completion should expose canonical --done"
    );
    for forbidden in [
        r#"alias = "pending-done""#,
        r#"alias = "backlog-done""#,
        "deprecated_done_flag_used",
        "--pending-done",
        "--backlog-done",
    ] {
        assert!(
            !cli.contains(forbidden),
            "removed tracked-work completion alias must not remain in the CLI: {forbidden}"
        );
    }
}

#[test]
fn test_compact_commit_explains_commit_scope() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("session.md");
    let content = "---\nagent_doc_session: test\nagent_doc_format: template\n---\n\n\
        ## Exchange\n\n\
        <!-- agent:exchange patch=append -->\n\
        ### Re: first topic — gpt-5\n\
        first body\n\n\
        ### Re: second topic — gpt-5\n\
        second body\n\
        <!-- /agent:exchange -->\n";
    fs::create_dir_all(root.join(".agent-doc/snapshots")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/archives")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    fs::write(&doc, content).unwrap();
    seed_snapshot(root, &doc, content);
    init_git_repo(root, &doc);

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args([
        "compact",
        doc.to_str().unwrap(),
        "--component",
        "exchange",
        "--tag",
        "skip",
        "--commit",
        "--force-disk",
    ]);
    cmd.assert().success().stderr(predicate::str::contains(
        "[compact] note: --commit persists only the compacted document state now in HEAD",
    ));
}

#[test]
fn test_archive_index_and_search_commands() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("tasks/session.md");
    fs::create_dir_all(root.join(".agent-doc/archives")).unwrap();
    fs::create_dir_all(doc.parent().unwrap()).unwrap();
    fs::write(
        &doc,
        "---\nagent_doc_session: current-session\nagent_doc_format: template\n---\n\nbody\n",
    )
    .unwrap();
    fs::write(
        root.join(".agent-doc/archives/hash-20260506-000000.md"),
        concat!(
            "---\n",
            "archived_from: compact\n",
            "archived_at: 20260506-000000\n",
            "component: exchange\n",
            "document: tasks/session.md\n",
            "session: current-session\n",
            "---\n\n",
            "## User\n\nDo #sqlarcidx.\n\n",
            "## Assistant\n\nPlan: tasks/agent-doc/plan-sqlite-compacted-turn-archive.md\n"
        ),
    )
    .unwrap();

    let mut index_cmd = agent_doc_cmd();
    index_cmd.current_dir(root);
    index_cmd.args(["archive-index", doc.to_str().unwrap(), "--rebuild"]);
    index_cmd
        .assert()
        .success()
        .stdout(predicate::str::contains("1 archive(s) indexed"));

    let mut search_cmd = agent_doc_cmd();
    search_cmd.current_dir(root);
    search_cmd.args([
        "archive-search",
        doc.to_str().unwrap(),
        "--id",
        "sqlarcidx",
        "--json",
    ]);
    search_cmd
        .assert()
        .success()
        .stdout(predicate::str::contains("\"archive_path\""))
        .stdout(predicate::str::contains("#sqlarcidx"));
}

#[test]
fn test_response_toc_and_fetch_commands() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let doc = root.join("tasks/session.md");
    fs::create_dir_all(root.join(".agent-doc/archives")).unwrap();
    fs::create_dir_all(doc.parent().unwrap()).unwrap();
    fs::write(
        &doc,
        concat!(
            "---\n",
            "agent_doc_session: current-session\n",
            "agent_doc_format: template\n",
            "---\n\n",
            "## Exchange\n\n",
            "<!-- agent:exchange patch=append -->\n",
            "### Re: current topic — gpt-5\n\n",
            "Body for #restoc.\n",
            "<!-- /agent:exchange -->\n",
        ),
    )
    .unwrap();
    fs::write(
        root.join(".agent-doc/archives/hash-20260506-000000.md"),
        concat!(
            "---\n",
            "archived_from: compact\n",
            "archived_at: 20260506-000000\n",
            "component: exchange\n",
            "document: tasks/session.md\n",
            "session: current-session\n",
            "---\n\n",
            "## User\n\nDo #restoc.\n\n",
            "## Assistant\n\n### Re: archived topic — gpt-5\n\nArchived body for #restoc.\n"
        ),
    )
    .unwrap();

    let mut toc_cmd = agent_doc_cmd();
    toc_cmd.current_dir(root);
    toc_cmd.args([
        "response-toc",
        doc.to_str().unwrap(),
        "--id",
        "restoc",
        "--json",
    ]);
    toc_cmd
        .assert()
        .success()
        .stdout(predicate::str::contains("\"locator\""))
        .stdout(predicate::str::contains("live:1"))
        .stdout(predicate::str::contains(
            "archive:.agent-doc/archives/hash-20260506-000000.md#2",
        ));

    let mut fetch_cmd = agent_doc_cmd();
    fetch_cmd.current_dir(root);
    fetch_cmd.args([
        "response-fetch",
        doc.to_str().unwrap(),
        "--locator",
        "archive:.agent-doc/archives/hash-20260506-000000.md#2",
        "--json",
    ]);
    fetch_cmd
        .assert()
        .success()
        .stdout(predicate::str::contains("Archived body for #restoc."));
}

#[test]
fn test_cli_repair_aliases_legacy_recover() {
    let tmp = tempfile::TempDir::new().unwrap();
    let missing = tmp.path().join("missing.md");

    let mut repair = agent_doc_cmd();
    repair.arg("repair").arg(&missing);
    repair
        .assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));

    let mut recover = agent_doc_cmd();
    recover.arg("recover").arg(&missing);
    recover
        .assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));
}

#[test]
fn test_cli_fix_missing_file_errors() {
    let tmp = tempfile::TempDir::new().unwrap();
    let missing = tmp.path().join("missing.md");

    let mut cmd = agent_doc_cmd();
    cmd.arg("fix").arg(&missing);
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));
}

#[test]
fn test_cli_resync_fix_alias_accepts_optional_file() {
    let tmp = tempfile::TempDir::new().unwrap();
    let missing = tmp.path().join("missing.md");

    let mut cmd = agent_doc_cmd();
    cmd.args(["resync", "--fix", missing.to_str().unwrap()]);
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));
}

#[test]
fn test_cli_init_no_file_runs_project_init() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.arg("init");
    cmd.assert()
        .success()
        .stderr(predicate::str::contains("Project initialized"));
    // .agent-doc/ directory should be created
    assert!(tmp.path().join(".agent-doc").is_dir());
}

#[test]
fn test_cli_start_requires_file() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("start");
    cmd.assert().failure();
}

#[test]
fn test_cli_route_requires_file() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("route");
    cmd.assert().failure();
}

#[test]
fn test_cli_start_file_not_found() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["start", "/nonexistent/file.md"]);
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));
}

#[test]
fn test_cli_route_file_not_found() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["route", "/nonexistent/file.md"]);
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("file not found"));
}

#[test]
fn test_cli_start_not_in_tmux() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("test.md");
    std::fs::write(&doc, "---\nsession: test-123\n---\n# Test\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("start");
    cmd.arg(&doc);
    // Remove TMUX env vars to simulate not being in tmux
    cmd.env_remove("TMUX");
    cmd.env_remove("TMUX_PANE");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("not running inside tmux"));
}

#[test]
fn test_cli_route_generates_session_for_bare_file() {
    let tmp = tempfile::TempDir::new().unwrap();
    // Opt the bare file in via the `auto_session_for_all_md` escape hatch so the
    // session-generation behavior is still exercised under the opt-in gate (#4a6p).
    std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
    std::fs::write(
        tmp.path().join(".agent-doc/config.toml"),
        "[documents]\nauto_session_for_all_md = true\n",
    )
    .unwrap();
    let doc = tmp.path().join("test.md");
    std::fs::write(&doc, "# No frontmatter\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("route");
    cmd.arg(&doc);
    cmd.arg("--force-disk");
    cmd.current_dir(tmp.path());
    // Prevent auto-start from creating real tmux windows
    cmd.env("AGENT_DOC_NO_AUTOSTART", "1");
    // Route should generate a session UUID (not error), then fail on tmux (not available in CI)
    // The key behavior: it should NOT fail with "no session UUID"
    let output = cmd.output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("no session UUID"),
        "route should auto-generate session UUID, got: {}",
        stderr
    );
    // Verify the file was updated with frontmatter
    let content = std::fs::read_to_string(&doc).unwrap();
    assert!(
        content.contains("session:"),
        "frontmatter should have been generated"
    );
}

#[test]
fn test_cli_route_rejects_plain_md_without_opt_in() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("notes.md");
    let original = "# Plain notes\n\nNot a session.\n";
    std::fs::write(&doc, original).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("route");
    cmd.arg(&doc);
    cmd.arg("--force-disk");
    cmd.current_dir(tmp.path());
    cmd.env("AGENT_DOC_NO_AUTOSTART", "1");
    let output = cmd.output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("is not an agent-doc document"),
        "route should fail closed on a plain .md, got: {}",
        stderr
    );
    // The gate must not mutate the file (no session injected).
    assert_eq!(std::fs::read_to_string(&doc).unwrap(), original);
}

#[test]
fn test_cli_route_generates_session_for_null_session() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("test.md");
    std::fs::write(&doc, "---\nsession: null\nagent: claude\n---\n# Test\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("route");
    cmd.arg(&doc);
    cmd.arg("--force-disk");
    cmd.current_dir(tmp.path());
    // Prevent auto-start from creating real tmux windows
    cmd.env("AGENT_DOC_NO_AUTOSTART", "1");
    let output = cmd.output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("no session UUID"),
        "route should auto-generate UUID for null session, got: {}",
        stderr
    );
    // Verify the file now has a real session UUID (not null)
    let content = std::fs::read_to_string(&doc).unwrap();
    assert!(content.contains("session:"), "frontmatter should exist");
    assert!(
        !content.contains("session: null"),
        "session should no longer be null"
    );
    // Agent field should be preserved
    assert!(
        content.contains("agent:"),
        "other frontmatter fields should be preserved"
    );
}

#[test]
fn test_cli_start_generates_session_for_bare_file() {
    let tmp = tempfile::TempDir::new().unwrap();
    // Opt in via the escape hatch so the session-generation path runs under the
    // opt-in gate (#4a6p).
    std::fs::create_dir_all(tmp.path().join(".agent-doc")).unwrap();
    std::fs::write(
        tmp.path().join(".agent-doc/config.toml"),
        "[documents]\nauto_session_for_all_md = true\n",
    )
    .unwrap();
    let doc = tmp.path().join("test.md");
    std::fs::write(&doc, "# No frontmatter\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("start");
    cmd.arg(&doc);
    cmd.env_remove("TMUX");
    cmd.env_remove("TMUX_PANE");
    // start should generate the UUID first, THEN fail on tmux check
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("not running inside tmux"));
    // Verify the file was updated with frontmatter before the tmux error
    let content = std::fs::read_to_string(&doc).unwrap();
    assert!(
        content.contains("session:"),
        "start should auto-generate session UUID"
    );
}

#[test]
fn test_cli_start_rejects_plain_md_without_opt_in() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("notes.md");
    let original = "# Plain notes\n";
    std::fs::write(&doc, original).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("start");
    cmd.arg(&doc);
    cmd.env_remove("TMUX");
    cmd.env_remove("TMUX_PANE");
    // The opt-in gate fails closed before the tmux check.
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("is not an agent-doc document"));
    // The gate must not mutate the file.
    assert_eq!(std::fs::read_to_string(&doc).unwrap(), original);
}

#[test]
fn test_cli_start_generates_session_for_null_session() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("test.md");
    // `agent:` is an agent-doc marker, so this opts in even with a null session.
    std::fs::write(&doc, "---\nsession: null\nagent: claude\n---\n# Test\n").unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.arg("start");
    cmd.arg(&doc);
    cmd.env_remove("TMUX");
    cmd.env_remove("TMUX_PANE");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("not running inside tmux"));
    let content = std::fs::read_to_string(&doc).unwrap();
    assert!(content.contains("session:"), "frontmatter should exist");
    assert!(
        !content.contains("session: null"),
        "session should no longer be null"
    );
}

#[test]
fn test_cli_help_shows_start_and_route() {
    let mut cmd = agent_doc_cmd();
    cmd.arg("--help");
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("start"))
        .stdout(predicate::str::contains("route"));
}

// ── install tests ────────────────────────────────────────────────────────────

#[test]
fn test_cli_install_help() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["install", "--help"]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("skip-prereqs"))
        .stdout(predicate::str::contains("skip-plugins"));
}

#[test]
fn test_cli_install_skip_all() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["install", "--skip-prereqs", "--skip-plugins"]);
    cmd.assert()
        .success()
        .stderr(predicate::str::contains("Skipping plugin installation"));
}

#[test]
fn test_cli_install_checks_prereqs() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["install", "--skip-plugins"]);
    cmd.assert()
        .success()
        .stderr(predicate::str::contains("tmux"))
        .stderr(predicate::str::contains("claude"));
}

// ── init tests (project-level, no file arg) ──────────────────────────────────

#[test]
fn test_cli_init_creates_agent_doc_dir() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.arg("init");
    cmd.assert().success();
    assert!(tmp.path().join(".agent-doc/snapshots").is_dir());
    assert!(!tmp.path().join(".agent-doc/patches").exists());
}

#[test]
fn test_cli_init_idempotent() {
    let tmp = tempfile::TempDir::new().unwrap();

    // First run
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.arg("init");
    cmd.assert().success();

    // Second run in the same dir must also succeed
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.arg("init");
    cmd.assert().success();
}

#[test]
fn test_cli_init_prints_quickstart() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.arg("init");
    // The quick-start hint mentions "agent-doc init" or "quick"
    cmd.assert().success().stderr(
        predicate::str::contains("agent-doc init")
            .or(predicate::str::contains("quick"))
            .or(predicate::str::contains("Quick")),
    );
}

// ── init tests (document-level, with file arg) ───────────────────────────────

#[test]
fn test_cli_init_file_creates_document() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("test.md");

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.args(["init", "test.md"]);
    cmd.assert().success();

    assert!(doc.exists());
    let content = std::fs::read_to_string(&doc).unwrap();
    // Must have YAML frontmatter with a session ID
    assert!(
        content.contains("agent_doc_session:"),
        "expected frontmatter with session id"
    );
}

#[test]
fn test_cli_init_file_with_mode() {
    let tmp = tempfile::TempDir::new().unwrap();
    let doc = tmp.path().join("test.md");

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.args(["init", "test.md", "--mode", "template"]);
    cmd.assert().success();

    assert!(doc.exists());
    let content = std::fs::read_to_string(&doc).unwrap();
    // Template-mode documents have component markers
    assert!(
        content.contains("agent:exchange"),
        "expected exchange component marker"
    );
    assert!(
        content.contains("agent_doc_format: template"),
        "expected template format in frontmatter"
    );
}

#[test]
fn test_cli_init_file_lazy_project_init() {
    let tmp = tempfile::TempDir::new().unwrap();
    // Confirm .agent-doc/ does not exist yet
    assert!(!tmp.path().join(".agent-doc").exists());

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.args(["init", "test.md"]);
    cmd.assert().success();

    // Both the project directory and the document should have been created
    assert!(
        tmp.path().join(".agent-doc").is_dir(),
        ".agent-doc/ should be lazily created"
    );
    assert!(
        tmp.path().join("test.md").exists(),
        "test.md should be created"
    );
}

// ── skill tests ───────────────────────────────────────────────────────────────

fn assert_operator_authority_instructions(content: &str, surface: &str) {
    assert!(
        content.contains("Preserve user edits")
            && content.contains("Lazily-owned semantic response checkpoints")
            && content.contains("agent-doc respond --stream")
            && content.contains("finalize")
            && content.contains("compatibility alias"),
        "{surface} should preserve user edits through checkpoints and binary-owned turn resolution"
    );
    assert!(
        content.contains("Operator-visible document text is authoritative"),
        "{surface} should state the operator-visible document is authoritative"
    );
    assert!(
        content.contains("never recover, patch, or hook-closeout by replacing")
            && content.contains("`content_ours`")
            && content.contains("a snapshot")
            && content.contains("a lazily visible-write receipt"),
        "{surface} should forbid content_ours/snapshot/receipt replacement that drops operator text"
    );
    assert!(
        content.contains(
            "Snapshots and incomplete token captures are backup/audit state, not hot-path authority"
        ),
        "{surface} should keep snapshots out of hot-path document authority"
    );
    assert!(
        content.contains("fail closed or retry through the editor instead"),
        "{surface} should require fail-closed/editor retry instead of dropping operator text"
    );
    assert!(
        !content.contains("content_ours (baseline + response, no user edits) is saved as the snapshot on IPC success"),
        "{surface} must not describe content_ours as the IPC-success snapshot authority"
    );
}

#[test]
fn root_agents_instructions_preserve_operator_authority() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let content = fs::read_to_string(root.join("AGENTS.md")).unwrap();

    assert_operator_authority_instructions(&content, "root AGENTS.md");
}

#[test]
fn docs_do_not_reintroduce_content_ours_snapshot_authority() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let docs = [
        "AGENTS.md",
        "README.md",
        "SPEC.md",
        "specs/06-config.md",
        "specs/07-closeout-commands.md",
        "specs/14-realtime-workflow.md",
        "specs/pending-system.md",
        ".claude/skills/agent-doc/SKILL.md",
    ];
    let banned = [
        "content_ours (baseline + response, no user edits) is saved as the snapshot on IPC success",
        "snapshot == baseline + response",
        "saves the `content_ours` snapshot (baseline + response)",
    ];

    for doc in docs {
        let content = fs::read_to_string(root.join(doc)).unwrap();
        for phrase in banned {
            assert!(
                !content.contains(phrase),
                "{doc} must not reintroduce content_ours snapshot authority phrase: {phrase}"
            );
        }
    }
}

#[test]
fn test_cli_skill_install_help() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["skill", "install", "--help"]);
    cmd.assert().success();
}

#[test]
fn test_cli_skill_check_help() {
    let mut cmd = agent_doc_cmd();
    cmd.args(["skill", "check", "--help"]);
    cmd.assert().success();
}

#[test]
fn test_cli_skill_install_creates_file() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1"); // Force ClaudeCode environment for deterministic path
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    let skill_path = tmp.path().join(".claude/skills/agent-doc/SKILL.md");
    assert!(skill_path.exists(), "SKILL.md should be created");
    let content = std::fs::read_to_string(&skill_path).unwrap();
    assert!(
        content.contains("agent-doc-version:"),
        "SKILL.md should have agent-doc-version in frontmatter"
    );
}

#[test]
fn test_cli_skill_check_after_install() {
    let tmp = tempfile::TempDir::new().unwrap();

    // Install first
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    // Check should succeed (version matches)
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "check"]);
    cmd.assert().success();
}

#[test]
fn test_cli_skill_install_idempotent() {
    let tmp = tempfile::TempDir::new().unwrap();

    // First install
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    // Second install must also succeed
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    let skill_path = tmp.path().join(".claude/skills/agent-doc/SKILL.md");
    assert!(
        skill_path.exists(),
        "SKILL.md should still exist after second install"
    );
}

#[test]
fn test_cli_skill_install_reload_compact() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "install", "--reload", "compact"]);
    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "skill install --reload compact should succeed"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    // Either the skill was freshly installed (prints SKILL_RELOAD=compact to stdout)
    // or it was already up to date (prints "already up to date" to stderr).
    assert!(
        stdout.contains("SKILL_RELOAD=compact") || stderr.contains("already up to date"),
        "expected SKILL_RELOAD=compact or 'already up to date', got stdout={stdout:?} stderr={stderr:?}"
    );
}

#[test]
fn test_skill_md_contains_required_steps() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    let skill_path = tmp.path().join(".claude/skills/agent-doc/SKILL.md");
    let content = std::fs::read_to_string(&skill_path).unwrap();
    assert_operator_authority_instructions(&content, "Claude SKILL.md");

    let required_steps = ["### 0.", "### 1.", "### 2."];
    for step in &required_steps {
        assert!(
            content.contains(step),
            "SKILL.md missing required workflow step: {step}"
        );
    }
    assert!(
        content.contains("agent-doc respond <FILE>"),
        "SKILL.md should use binary-owned respond for the normal response cycle"
    );
    assert!(
        content.contains("agent-doc session-check <FILE>"),
        "SKILL.md should still mention the direct session-check command"
    );
    assert!(
        content.contains(
            "The `respond` command is the binary-owned turn-resolution and final document-mutation boundary for the cycle"
        ),
        "SKILL.md should delegate turn resolution to the binary closeout boundary"
    );
    assert!(
        content.contains("Imperative edits are executable directives"),
        "SKILL.md should treat document-local `do` edits as executable work directives"
    );
    assert!(
        content.contains(
            "Harness-native `agent-doc` entrypoints start the binary-owned response cycle"
        ),
        "SKILL.md should treat harness-native agent-doc invocations as binary-owned workflow starts"
    );
    assert!(
        content.contains("Do not manually patch the final assistant response into the document"),
        "SKILL.md should forbid manual final-response patchback on harness-native agent-doc turns"
    );
    assert!(
        content.contains("Do not stop at the newest question"),
        "SKILL.md should require reconciling the changed exchange tail oldest-first"
    );
    assert!(
        content.contains("runbooks/command-synonyms.md"),
        "SKILL.md should point agents to the orchestrate synonym runbook"
    );
    assert!(
        content.contains("runbooks/compound-task-steering.md"),
        "SKILL.md should point agents to the compound-task steering runbook"
    );
    assert!(
        content.contains("orchestration_request"),
        "SKILL.md should treat binary-owned orchestration requests as first-class preflight output"
    );
    assert!(
        content.contains(
            "agent-doc orchestrate <FILE> --mode <orchestration_request.mode> --from-exchange"
        ),
        "SKILL.md should require dispatching preflight orchestration requests through agent-doc orchestrate"
    );
    assert!(
        content.contains("agent-doc plan <FILE>"),
        "SKILL.md should require the binary-owned planning phase after preflight"
    );
    assert!(
        content.contains("runbooks/planning-dispatch.md"),
        "SKILL.md should point agents to the planning/dispatch runbook"
    );
    assert!(
        content.contains("external CI-start blocker"),
        "SKILL.md should classify empty-step no-log GitHub jobs as external CI-start blockers"
    );
    assert!(
        content.contains("billing/spending-limit exhaustion"),
        "SKILL.md should name billing/spending-limit failures as CI-start blockers"
    );
    assert!(
        content.contains("create the plan file first"),
        "SKILL.md should require creating plan files before adding plan-backed backlog items"
    );
    assert!(
        content.contains("include that exact plan file path"),
        "SKILL.md should require plan-backed backlog items to include the plan path"
    );
    assert!(
        tmp.path()
            .join(".claude/skills/agent-doc/runbooks/compound-task-steering.md")
            .exists(),
        "skill install should write the compound-task steering runbook"
    );
    assert!(
        tmp.path()
            .join(".claude/skills/agent-doc/runbooks/planning-dispatch.md")
            .exists(),
        "skill install should write the planning-dispatch runbook"
    );
    assert!(
        tmp.path()
            .join(".claude/skills/agent-doc/okf/index.md")
            .exists(),
        "skill install should write the OKF concept index"
    );
    let okf_index =
        std::fs::read_to_string(tmp.path().join(".claude/skills/agent-doc/okf/index.md")).unwrap();
    assert!(
        okf_index.contains("Session Cycle"),
        "installed OKF index should include session-cycle navigation"
    );
    let pending_ops = std::fs::read_to_string(
        tmp.path()
            .join(".claude/skills/agent-doc/runbooks/pending-ops.md"),
    )
    .unwrap();
    assert!(
        pending_ops.contains("plan-spec2-rollout.md"),
        "installed pending-ops runbook should document plan-backed backlog items"
    );
}

#[test]
fn test_codex_skill_install_writes_hook_artifacts() {
    let tmp = tempfile::TempDir::new().unwrap();
    let codex_home = tmp.path().join("user-codex-home");
    std::fs::create_dir_all(&codex_home).unwrap();
    std::fs::write(
        codex_home.join("hooks.json"),
        serde_json::json!({
            "hooks": {
                "UserPromptSubmit": [{
                    "hooks": [{
                        "type": "command",
                        "command": "agent-doc turn-status active"
                    }]
                }],
                "Stop": [{
                    "hooks": [{
                        "type": "command",
                        "command": "agent-doc turn-status idle"
                    }]
                }]
            }
        })
        .to_string(),
    )
    .unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CODEX_CLI", "1");
    cmd.env("CODEX_HOME", &codex_home);
    cmd.env_remove("CLAUDE_CODE");
    cmd.env_remove("CLAUDE_CODE_ENTRYPOINT");
    cmd.env_remove("OPENCODE");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    let hooks_path = codex_home.join("hooks.json");
    let config_path = tmp.path().join(".codex/config.toml");
    let skill_path = tmp.path().join(".codex/skills/agent-doc/SKILL.md");
    assert!(hooks_path.exists(), "missing {}", hooks_path.display());
    assert!(config_path.exists(), "missing {}", config_path.display());
    assert!(skill_path.exists(), "missing {}", skill_path.display());
    assert!(
        !tmp.path().join(".codex/hooks.json").exists(),
        "Codex lifecycle hooks must have one user-level owner, not a duplicate project install"
    );
    assert!(
        !tmp.path().join(".codex/AGENTS.md").exists(),
        "Codex workflow must not be installed into always-on .codex/AGENTS.md"
    );

    let skill = std::fs::read_to_string(&skill_path).unwrap();
    assert_operator_authority_instructions(&skill, "Codex SKILL.md");
    assert!(skill.contains("Interactive markdown session for Codex"));
    assert!(skill.contains("agent-doc skill install --harness codex` without a reload request"));
    assert!(skill.contains("re-read the installed `.codex/skills/agent-doc/SKILL.md` completely"));
    assert!(skill.contains("Do not call `agent-doc session restart-supervisor`"));
    assert!(!skill.contains("codex resume --last"));

    let hooks: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&hooks_path).unwrap()).unwrap();
    assert!(
        hooks["hooks"]["UserPromptSubmit"]
            .as_array()
            .unwrap()
            .iter()
            .any(|entry| {
                entry["hooks"].as_array().unwrap().iter().any(|hook| {
                    hook["command"].as_str() == Some("agent-doc hook codex-user-prompt-submit")
                })
            })
    );
    assert!(
        hooks["hooks"]["Stop"]
            .as_array()
            .unwrap()
            .iter()
            .any(|entry| {
                entry["hooks"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .any(|hook| hook["command"].as_str() == Some("agent-doc hook codex-stop"))
            })
    );
    assert!(
        hooks["hooks"]["UserPromptSubmit"]
            .as_array()
            .unwrap()
            .iter()
            .any(|entry| {
                entry["hooks"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .any(|hook| hook["command"].as_str() == Some("agent-doc turn-status active"))
            }),
        "install must preserve an existing user-level prompt hook"
    );

    let config: toml::Value =
        toml::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
    assert_eq!(config["features"]["hooks"].as_bool(), Some(true));
    assert!(config["features"].get("codex_hooks").is_none());
    assert_eq!(
        config["mcp_servers"]["agent-doc"]["command"].as_str(),
        Some("agent-doc")
    );
    assert_eq!(
        config["mcp_servers"]["agent-doc"]["default_tools_approval_mode"].as_str(),
        Some("approve")
    );
    let mcp_args: Vec<&str> = config["mcp_servers"]["agent-doc"]["args"]
        .as_array()
        .unwrap()
        .iter()
        .map(|arg| arg.as_str().unwrap())
        .collect();
    // `#skillinstallconfigpath`: the installed args must stay machine-agnostic,
    // because this file is project-local and usually tracked. `mcp serve`
    // resolves the project root from its own working directory instead.
    assert_eq!(mcp_args, vec!["mcp", "serve"]);
    assert!(
        !std::fs::read_to_string(&config_path)
            .unwrap()
            .contains("--project-root"),
        "no absolute install-machine path may be written into .codex/config.toml"
    );
    assert!(
        std::fs::read_to_string(&hooks_path)
            .unwrap()
            .ends_with('\n'),
        "installed user-level Codex hooks.json must end with a newline"
    );
}

#[test]
fn test_opencode_skill_install_preserves_operator_authority_instructions() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("OPENCODE", "1");
    cmd.env_remove("CLAUDE_CODE");
    cmd.env_remove("CLAUDE_CODE_ENTRYPOINT");
    cmd.env_remove("CODEX_CLI");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    let skill_path = tmp.path().join(".opencode/skills/agent-doc/SKILL.md");
    let content = std::fs::read_to_string(&skill_path).unwrap();
    assert_operator_authority_instructions(&content, "OpenCode SKILL.md");
    assert!(content.contains("Interactive markdown session for OpenCode"));
    assert!(content.contains("agent-doc skill install --harness opencode"));
}

#[test]
fn test_skill_md_references_valid_commands() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mut cmd = agent_doc_cmd();
    cmd.current_dir(tmp.path());
    cmd.env("CLAUDE_CODE", "1");
    cmd.args(["skill", "install"]);
    cmd.assert().success();

    let skill_path = tmp.path().join(".claude/skills/agent-doc/SKILL.md");
    let content = std::fs::read_to_string(&skill_path).unwrap();

    // Get valid subcommands by running `agent-doc --help`
    let help_output = agent_doc_cmd().arg("--help").output().unwrap();
    let help_text = String::from_utf8_lossy(&help_output.stdout);
    let valid_subcommands: std::collections::HashSet<String> = help_text
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim();
            // Help lines for subcommands start with the command name followed by spaces and description
            let word = trimmed.split_whitespace().next()?;
            // Only accept lowercase words that look like subcommand names (no punctuation)
            if word.chars().all(|c| c.is_ascii_lowercase() || c == '-') && !word.is_empty() {
                Some(word.to_string())
            } else {
                None
            }
        })
        .collect();

    // Tokens that are not subcommands but are valid in SKILL.md:
    // - `submit` is the skill's invocation name (used in the title/heading)
    // - `finalize` is the compatibility alias for the primary `respond` command
    // - flags like `--version`, `--help` are valid options, not subcommands
    let allowed_non_subcommands: std::collections::HashSet<&str> =
        ["submit", "finalize", "--version", "--help"]
            .iter()
            .copied()
            .collect();

    // Extract all `agent-doc <word>` patterns from SKILL.md
    let mut invalid_refs: Vec<String> = Vec::new();
    for line in content.lines() {
        // Find all occurrences of `agent-doc <something>` in the line
        let mut search = line;
        while let Some(pos) = search.find("agent-doc") {
            let after = &search[pos + "agent-doc".len()..];
            // Skip if nothing follows or followed by non-whitespace (e.g., `agent-doc-version:`)
            let after_trimmed = after.trim_start_matches(' ');
            if after_trimmed == after && !after.is_empty() {
                // No space after `agent-doc` — skip (it's part of another word like `agent-doc-version`)
                search = &search[pos + "agent-doc".len()..];
                continue;
            }
            // Extract the next word after `agent-doc `
            let next_word = after_trimmed.split_whitespace().next();
            if let Some(cmd_name) = next_word {
                // Strip any trailing punctuation like `:`, `)`, `` ` ``
                let cmd_clean: String = cmd_name
                    .chars()
                    .take_while(|c| c.is_ascii_lowercase() || *c == '-')
                    .collect();
                if !cmd_clean.is_empty()
                    && !valid_subcommands.contains(&cmd_clean)
                    && !allowed_non_subcommands.contains(cmd_clean.as_str())
                {
                    invalid_refs.push(format!("agent-doc {cmd_clean}"));
                }
            }
            search = &search[pos + "agent-doc".len()..];
        }
    }

    assert!(
        invalid_refs.is_empty(),
        "SKILL.md references unknown agent-doc subcommands: {:?}\nValid subcommands: {:?}",
        invalid_refs,
        valid_subcommands
    );
}

#[test]
fn test_submodule_write_patches_dir_structure() {
    use std::fs;
    use tempfile::TempDir;

    // This is a simpler integration test that verifies the expected directory structure
    // for submodule patch routing. The actual git submodule test is in write.rs unit tests
    // where we can create real git structures.

    let parent_dir = TempDir::new().unwrap();
    let parent = parent_dir.path();

    // Set up parent repo's .agent-doc structure
    let parent_agent_doc = parent.join(".agent-doc");
    fs::create_dir_all(parent_agent_doc.join("patches")).unwrap();
    fs::create_dir_all(parent_agent_doc.join("snapshots")).unwrap();
    fs::create_dir_all(parent_agent_doc.join("crdt")).unwrap();

    // Verify patches directory exists and is accessible
    let parent_patches = parent.join(".agent-doc/patches");
    assert!(
        parent_patches.exists(),
        "parent should have .agent-doc/patches directory"
    );
    assert!(
        parent_patches.is_dir(),
        ".agent-doc/patches should be a directory"
    );

    // Simulate a document in a submodule location
    let simulated_submodule_path = parent.join("src/submodule/tasks");
    fs::create_dir_all(&simulated_submodule_path).unwrap();
    let doc = simulated_submodule_path.join("test.md");
    fs::write(&doc, "---\nagent_doc_session: test\n---\n\n<!-- agent:exchange -->test<!-- /agent:exchange -->\n").unwrap();

    // Verify the document file exists
    assert!(doc.exists(), "test document should exist");
    assert!(doc.is_file(), "test document should be a file");

    // Verify parent's patches directory is still accessible (would receive patches in actual IPC scenario)
    let entries: Vec<_> = fs::read_dir(&parent_patches)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    // Directory should be empty initially
    assert!(
        entries.is_empty(),
        "patches directory should be initially empty"
    );
}

#[test]
fn test_compact_message_dash_reads_stdin() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    fs::create_dir_all(root.join(".agent-doc/snapshots")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/archives")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/logs")).unwrap();
    fs::create_dir_all(root.join(".agent-doc/state/cycles")).unwrap();

    init_git_repo(root, &root.join("session.md"));

    let doc = concat!(
        "---\nagent_doc_session: stdin-test\nagent_doc_format: template\n---\n\n",
        "## Exchange\n\n",
        "<!-- agent:exchange patch=append -->\n",
        "### Re: topic\n\nSome response content.\n",
        "<!-- /agent:exchange -->\n",
    );
    fs::write(root.join("session.md"), doc).unwrap();

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args([
        "compact",
        "session.md",
        "--message",
        "-",
        "--tag",
        "skip",
        "--force-disk",
    ]);
    cmd.write_stdin("Summary from stdin pipe.");
    cmd.assert().success();

    let result = fs::read_to_string(root.join("session.md")).unwrap();
    assert!(
        result.contains("Summary from stdin pipe."),
        "compact should use stdin content as message, got:\n{result}"
    );
    assert!(
        !result.contains("### Re: topic"),
        "original content should be archived"
    );
}

#[test]
fn test_transfer_exchange_auto_creates_target_with_backlog_and_icebox_scaffold() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let source = root.join("source.md");
    let target = root.join("target.md");

    let source_doc = template_doc(
        "Source",
        "### Re: topic — gpt-5\n\nTransferred exchange body.\n",
        "- [ ] [#back1] Keep this backlog item with the transfer\n",
        "- [ ] [#cold1] Parked context that should transfer too\n",
    );
    fs::write(&source, &source_doc).unwrap();
    init_git_repo(root, &source);
    seed_snapshot(root, &source, &source_doc);

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args([
        "transfer",
        "source.md",
        "target.md",
        "exchange",
        "--bypass-claim",
    ]);
    cmd.assert().success();

    let source_after = fs::read_to_string(&source).unwrap();
    assert!(
        !source_after.contains("Transferred exchange body."),
        "source exchange should be cleared after transfer:\n{source_after}"
    );
    assert!(
        !source_after.contains("[#back1]"),
        "source backlog should be cleared after transfer:\n{source_after}"
    );
    assert!(
        !source_after.contains("[#cold1]"),
        "source icebox should be cleared after transfer:\n{source_after}"
    );

    let target_after = fs::read_to_string(&target).unwrap();
    assert!(target_after.contains("## Status"));
    assert!(target_after.contains("## Queue"));
    assert!(target_after.contains("<!-- agent:backlog -->"));
    assert!(target_after.contains("<!-- agent:icebox -->"));
    assert!(target_after.contains("Transferred exchange body."));
    assert!(target_after.contains("[#back1]"));
    assert!(target_after.contains("[#cold1]"));
}

#[test]
fn test_transfer_items_supports_icebox_component() {
    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path();
    let source = root.join("source.md");
    let target = root.join("target.md");

    let source_doc = template_doc(
        "Source",
        "",
        "",
        "- [ ] [#cold1] First parked item\n- [ ] [#cold2] Second parked item\n",
    );
    let target_doc = template_doc("Target", "", "", "- [ ] [#keep1] Existing target item\n");
    fs::write(&source, &source_doc).unwrap();
    fs::write(&target, &target_doc).unwrap();
    init_git_repo(root, &source);
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["add", "target.md"])
        .status()
        .unwrap();
    ProcessCommand::new("git")
        .current_dir(root)
        .args(["commit", "-m", "add target", "--no-verify"])
        .status()
        .unwrap();
    seed_snapshot(root, &source, &source_doc);
    seed_snapshot(root, &target, &target_doc);

    let mut cmd = agent_doc_cmd();
    cmd.current_dir(root);
    cmd.args([
        "transfer",
        "source.md",
        "target.md",
        "icebox",
        "--items",
        "#cold1",
        "--bypass-claim",
    ]);
    cmd.assert().success();

    let source_after = fs::read_to_string(&source).unwrap();
    assert!(
        !source_after.contains("[#cold1]"),
        "matched icebox item should leave source:\n{source_after}"
    );
    assert!(source_after.contains("[#cold2]"));

    let target_after = fs::read_to_string(&target).unwrap();
    assert!(target_after.contains("[#keep1]"));
    assert!(target_after.contains("[#cold1]"));
    assert!(
        !target_after.contains("[#cold2]"),
        "unmatched icebox item should stay in source:\n{target_after}"
    );
}

#[test]
fn retained_write_boundary_flags_are_typed_at_development_call_sites() {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let realtime =
        fs::read_to_string(manifest_dir.join("agent-doc-document-realtime-io/src/lib.rs")).unwrap();
    let preflight =
        fs::read_to_string(manifest_dir.join("agent-doc-preflight-runtime-io/src/lib.rs")).unwrap();
    let session_check =
        fs::read_to_string(manifest_dir.join("agent-doc-closeout-runtime-io/src/lib.rs")).unwrap();
    let finalize =
        fs::read_to_string(manifest_dir.join("agent-doc-write-runtime-io/src/lib.rs")).unwrap();

    assert!(
        realtime.contains("pub enum RetainedWriteCycleBoundary")
            && realtime.contains("FinalizePreCapture")
            && realtime.contains("pub const fn recovery_source")
            && realtime.contains("pub const fn gate_source"),
        "closed-set retained-write transition flags must be owned by one Rust enum",
    );
    assert!(
        !realtime.contains("enum ZeroReplicaRepairSource")
            && !realtime.contains("repair_force_disk_canonical_projection")
            && !realtime.contains("zero_replica_repair_projected")
            && realtime.contains("Repair is not an authority escape hatch"),
        "repair must retain the reactive controller projection instead of exposing a zero-replica force-disk boundary",
    );
    assert!(
        preflight.contains("RetainedWriteCycleBoundary::Preflight")
            && !preflight.contains("\"preflight_retained_write_recovery\"")
            && session_check.contains("RetainedWriteCycleBoundary::SessionCheck")
            && !session_check.contains("\"session_check_retained_write_recovery\"")
            && finalize.contains("RetainedWriteCycleBoundary::FinalizePreCapture")
            && !finalize.contains("\"finalize_pre_capture_retained_write_recovery\""),
        "development/runtime call sites must pass typed variants, not free-text transition flags",
    );
    assert!(
        session_check.contains("enum CapturedFinalizeSource")
            && session_check
                .contains("CapturedFinalizeSource::NativeSaveWithoutRetainedIntent")
            && !session_check.contains(
                "settle_projected_captured_response_through_authority(\n                file,\n                \"session_check_capture_without_retained_intent_native_save\"",
            ),
        "captured-finalize native-save siblings must remain typed at call sites",
    );

    let run_start = finalize
        .find("fn run_command_inner(")
        .expect("finalize runtime entrypoint");
    let run_body = &finalize[run_start..];
    let guard = run_body
            .find(
                "guard_historical_retained_write_before_new_capture(file, commit_mode, closeout_role)?;",
            )
            .expect("historical retained-write guard");
    let capture_boundary = run_body
        .find("let write_result = if options.is_ipc")
        .expect("response capture/write boundary");
    assert!(
        guard < capture_boundary,
        "historical retained effects must reject before response capture/admission",
    );
}
