herdr-sdk 0.0.1

A small synchronous client for Herdr's socket API: typed requests, an event stream, and the pane and agent models plugins actually touch.
Documentation
//! Where an agent is actually working, and how sure we are.
//!
//! ▲ **`foreground_cwd` cannot track a coding agent.** It is the OS working
//! directory of the pane's foreground process, and the agents that matter here
//! change their working directory *internally* without ever calling `chdir`:
//!
//! * omp's `applyCwdChange` calls `setProjectDir` and not `process.chdir`, so a
//!   `/move` or resuming a session from another project leaves the process
//!   where it launched.
//! * Claude Code's `/cd` is the same pattern — the existence of its
//!   `CwdChanged` hook is the admission that no external observer can see it.
//!
//! So `foreground_cwd` is right for a plain shell and for anything that really
//! does `chdir`, and structurally wrong for the two agents this repository is
//! built around. It stays a source; it must not be the only one, and it must
//! not outrank an agent's own report.
//!
//! The agent's own report reaches us as pane metadata: an agent-side hook or
//! extension writes the directory with `pane.report_metadata`, and Herdr hands
//! it back on the pane object — so reading it needs no extra subscription and no
//! new socket call.
//!
//! Everything goes through [`resolve`] so that when a source is added, changed,
//! or found to be a liar, there is one place to fix rather than every call site
//! that wanted a directory.

use std::path::Path;

use crate::model::Pane;
use crate::subagents::{Subagent, SubagentRoster};

/// The metadata key an agent reports its session directory under.
///
/// Prefixed because `Pane::tokens` is one flat map shared by every plugin —
/// a bare `cwd` would be a collision waiting to happen.
pub const AGENT_CWD_TOKEN: &str = "vsh-cwd";

/// Where a directory came from, most specific first.
///
/// The ordering of the variants *is* the precedence, and [`Ord`] is derived from
/// it deliberately: a source that disagrees with a less specific one wins by
/// being declared earlier here, not by an accident of `if` ordering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CwdSource {
    /// A subagent's own directory, from the roster its parent published.
    ///
    /// First because a subagent can be launched with worktree isolation and
    /// genuinely work somewhere its parent does not. Nothing below can see
    /// that: the parent process never moves, so `foreground_cwd` is wrong, and
    /// the parent's own report is wrong *for the child* — it describes the
    /// parent. See [`crate::subagents::Subagent::cwd`].
    ///
    /// ▲ **This is a launch directory, not a live one.** It is recorded when a
    /// teammate joins and is never updated afterwards, so a subagent that has
    /// `cd`-ed since is reported where it started. That is exactly right for the
    /// worktree-isolation case the source exists for, and stale for any other —
    /// and it is the one place in this precedence where the most specific answer
    /// is not also the most current.
    SubagentReported,
    /// The agent told us, via `pane.report_metadata` or the roster file it
    /// points at. The only source that can see a session directory change that
    /// never touched the process, and unlike the one above it is *live*: it comes
    /// from the hook that fires on the change.
    ///
    /// ▲ An absent `vsh-cwd` token does not mean the agent said nothing. A path
    /// too long for the 80-character token limit is **erased** rather than
    /// written truncated — a token naming a directory the agent has left is worse
    /// than no token — so the file is where the answer is in exactly the cases
    /// the token is missing. Which is why both are read here, file first.
    AgentReported,
    /// The OS working directory of the pane's foreground process. Correct for
    /// shells; stale for an agent that moved internally.
    Foreground,
    /// Where the pane was started. A floor, not an answer.
    PaneStart,
}

impl CwdSource {
    /// A short marker for a status line: the panel should be able to say how
    /// much it trusts what it is showing.
    pub fn marker(self) -> &'static str {
        match self {
            Self::SubagentReported => "subagent",
            Self::AgentReported => "agent",
            Self::Foreground => "process",
            Self::PaneStart => "launch",
        }
    }

    /// Whether this answer came from something that can actually see an agent
    /// move. The two reported sources can; the two observed ones cannot.
    pub fn is_reported(self) -> bool {
        matches!(self, Self::SubagentReported | Self::AgentReported)
    }
}

/// A directory and its provenance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cwd<'a> {
    pub path: &'a str,
    pub source: CwdSource,
}

impl<'a> Cwd<'a> {
    pub fn as_path(&self) -> &'a Path {
        Path::new(self.path)
    }
}

/// Everything the panel knows that is not on the pane.
///
/// A struct rather than a growing argument list: both fields answer the same
/// question — "has something that can actually see the agent said where it is?" —
/// and a caller that has neither writes `Reported::default()` and reads as
/// obviously meaning "just the pane".
#[derive(Debug, Clone, Copy, Default)]
pub struct Reported<'a> {
    /// The selected subagent, when one rather than the agent is selected.
    pub subagent: Option<&'a Subagent>,
    /// The pane's published roster, which carries the agent's own directory.
    pub roster: Option<&'a SubagentRoster>,
}

/// Resolve a pane's working directory across every source, most specific first.
///
/// For the pane itself, with nothing else known. Use [`resolve_with`] when a
/// subagent is selected or a roster has been read.
pub fn resolve(pane: &Pane) -> Option<Cwd<'_>> {
    resolve_with(pane, Reported::default())
}

/// Resolve the directory for whatever is selected: a pane, or one subagent
/// inside it.
///
/// Precedence: **subagent-reported > agent-reported > foreground > launch.**
/// Each step answers a narrower question than the one below it — "where is this
/// teammate working", "where is this conversation working", "where is this
/// process", "where did this pane start" — and only the reported two survive an
/// agent that moved without the OS noticing.
///
/// The order is not written here. It is the declaration order of [`CwdSource`],
/// which the candidate list below follows, so adding a source means putting one
/// variant in the right place rather than finding every `if` that ranked them.
pub fn resolve_with<'a>(pane: &'a Pane, known: Reported<'a>) -> Option<Cwd<'a>> {
    let candidates = [
        (
            CwdSource::SubagentReported,
            known.subagent.and_then(|subagent| subagent.cwd.as_deref()),
        ),
        // Two agent-reported answers, and the file wins over the token. Same
        // provenance, but a token is truncated at 80 characters — silently, with
        // an `ok` in reply — so a long worktree path arrives there as a directory
        // that does not exist. In the roster file it arrives whole.
        (
            CwdSource::AgentReported,
            known
                .roster
                .and_then(|roster| roster.cwd.as_deref())
                .or_else(|| pane.tokens.get(AGENT_CWD_TOKEN).and_then(Option::as_deref)),
        ),
        (CwdSource::Foreground, pane.foreground_cwd.as_deref()),
        (CwdSource::PaneStart, pane.cwd.as_deref()),
    ];

    candidates.into_iter().find_map(|(source, path)| {
        path.filter(|value| !value.is_empty())
            .map(|path| Cwd { path, source })
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pane() -> Pane {
        Pane {
            cwd: Some("/launch".into()),
            foreground_cwd: Some("/process".into()),
            ..Pane::default()
        }
    }

    fn reported(pane: &mut Pane, value: Option<&str>) {
        pane.tokens
            .insert(AGENT_CWD_TOKEN.to_string(), value.map(str::to_owned));
    }

    fn isolated(cwd: &str) -> Subagent {
        Subagent {
            name: "child".into(),
            cwd: Some(cwd.into()),
            ..Subagent::default()
        }
    }

    /// The case the truncation created: the writer had a path too long for a
    /// token, erased the token rather than storing 80 characters of it, and put
    /// the whole thing in the file. A reader that treats a missing token as "the
    /// agent has not reported" falls through to `foreground_cwd` and shows the
    /// launch directory of a session that has moved.
    #[test]
    fn an_erased_token_still_resolves_from_the_roster_file() {
        let mut pane = pane();
        reported(&mut pane, None);
        let long = format!(
            "/Users/operator/workspace/project/repo/_worktrees/{}",
            "a".repeat(40)
        );
        assert!(
            long.len() > 80,
            "the path has to be one a token could not hold"
        );
        let roster = SubagentRoster {
            cwd: Some(long.clone()),
            ..SubagentRoster::default()
        };

        let resolved = resolve_with(
            &pane,
            Reported {
                roster: Some(&roster),
                ..Reported::default()
            },
        )
        .unwrap();
        assert_eq!(resolved.path, long);
        assert_eq!(resolved.source, CwdSource::AgentReported);
    }

    #[test]
    fn a_worktree_isolated_subagent_outranks_its_parents_own_report() {
        // The case nothing else can see: the parent process never moved, the
        // parent's report describes the parent, and the child is elsewhere.
        let mut pane = pane();
        reported(&mut pane, Some("/where/the/parent/is"));
        let child = isolated("/repo/_worktrees/child");

        let resolved = resolve_with(
            &pane,
            Reported {
                subagent: Some(&child),
                ..Reported::default()
            },
        )
        .unwrap();
        assert_eq!(resolved.path, "/repo/_worktrees/child");
        assert_eq!(resolved.source, CwdSource::SubagentReported);
    }

    #[test]
    fn a_subagent_sharing_its_parents_directory_falls_through_to_the_parent() {
        let mut pane = pane();
        reported(&mut pane, Some("/where/the/parent/is"));
        let child = Subagent {
            name: "child".into(),
            ..Subagent::default()
        };

        let resolved = resolve_with(
            &pane,
            Reported {
                subagent: Some(&child),
                ..Reported::default()
            },
        )
        .unwrap();
        assert_eq!(resolved.path, "/where/the/parent/is");
        assert_eq!(resolved.source, CwdSource::AgentReported);
    }

    #[test]
    fn a_roster_beats_the_token_it_duplicates() {
        // The reason: a worktree path this long truncates in a token and lands as
        // a directory that does not exist, while the write still answers `ok`.
        let long = format!(
            "/Users/operator/workspace/{}/_worktrees/child",
            "x".repeat(60)
        );
        let mut pane = pane();
        reported(&mut pane, Some(&long[..80]));
        let roster = SubagentRoster {
            cwd: Some(long.clone()),
            ..SubagentRoster::default()
        };

        let resolved = resolve_with(
            &pane,
            Reported {
                roster: Some(&roster),
                ..Reported::default()
            },
        )
        .unwrap();
        assert_eq!(resolved.path, long);
        // Same provenance either way — the file is not a *new* source, it is the
        // same source without a length limit.
        assert_eq!(resolved.source, CwdSource::AgentReported);
    }

    #[test]
    fn a_roster_without_a_directory_leaves_the_token_in_charge() {
        let mut pane = pane();
        reported(&mut pane, Some("/from/the/token"));
        let roster = SubagentRoster::default();

        let resolved = resolve_with(
            &pane,
            Reported {
                roster: Some(&roster),
                ..Reported::default()
            },
        )
        .unwrap();
        assert_eq!(resolved.path, "/from/the/token");
    }

    #[test]
    fn selecting_the_parent_ignores_a_subagents_directory() {
        let pane = pane();
        assert_eq!(resolve(&pane).unwrap().source, CwdSource::Foreground);
    }

    #[test]
    fn only_the_reported_sources_can_see_an_agent_move() {
        assert!(CwdSource::SubagentReported.is_reported());
        assert!(CwdSource::AgentReported.is_reported());
        assert!(!CwdSource::Foreground.is_reported());
        assert!(!CwdSource::PaneStart.is_reported());
    }

    #[test]
    fn the_agents_own_report_wins() {
        let mut pane = pane();
        reported(&mut pane, Some("/where/the/agent/actually/is"));
        let resolved = resolve(&pane).unwrap();
        assert_eq!(resolved.path, "/where/the/agent/actually/is");
        assert_eq!(resolved.source, CwdSource::AgentReported);
    }

    #[test]
    fn foreground_is_used_when_no_agent_has_reported() {
        let pane = pane();
        let resolved = resolve(&pane).unwrap();
        assert_eq!(resolved.path, "/process");
        assert_eq!(resolved.source, CwdSource::Foreground);
    }

    #[test]
    fn launch_is_the_floor() {
        let mut pane = pane();
        pane.foreground_cwd = None;
        let resolved = resolve(&pane).unwrap();
        assert_eq!(resolved.path, "/launch");
        assert_eq!(resolved.source, CwdSource::PaneStart);
    }

    #[test]
    fn an_erased_token_falls_through_rather_than_blanking_the_answer() {
        let mut pane = pane();
        // `null` is how a writer erases a token; an empty string is what a
        // half-initialised writer sends. Neither is a directory.
        reported(&mut pane, None);
        assert_eq!(resolve(&pane).unwrap().source, CwdSource::Foreground);
        reported(&mut pane, Some(""));
        assert_eq!(resolve(&pane).unwrap().source, CwdSource::Foreground);
    }

    #[test]
    fn a_pane_with_nothing_to_go_on_resolves_to_nothing() {
        assert_eq!(resolve(&Pane::default()), None);
    }

    #[test]
    fn precedence_is_the_declaration_order() {
        assert!(CwdSource::SubagentReported < CwdSource::AgentReported);
        assert!(CwdSource::AgentReported < CwdSource::Foreground);
        assert!(CwdSource::Foreground < CwdSource::PaneStart);
    }
}