trusty_code/binding/mod.rs
1//! Project binding — the ONE typed object `task.run` and `session.create`
2//! converge on (spec DOC-39 §4.2/§5.5, ACs 2.1–2.4 and 16.1–16.3).
3//!
4//! Why: "project" was one concept split across two disagreeing API surfaces.
5//! `task.run` took a REQUIRED `project: PathBuf` (`task/protocol.rs:48`), which
6//! made a projectless workstream — Bob-mandated, and the entry state screen 7a
7//! renders — literally impossible to express. `session.create` took an untyped,
8//! free-form `project: Option<String>` label (`session/protocol.rs:157`) that was
9//! never validated, never bound, and disconnected from the path `task.run`
10//! demanded. A label that cannot be indexed and a path that cannot be omitted are
11//! two halves of one missing object. [`ProjectBinding`] is that object.
12//!
13//! What: a three-state enum, matching the spec's §4.2 table exactly:
14//!
15//! | State | Indexing | Git affordances |
16//! |---|---|---|
17//! | [`ProjectBinding::None`] — projectless | none | none |
18//! | [`ProjectBinding::Directory`] — bound, non-git | **yes** | none |
19//! | [`ProjectBinding::GitRepo`] — bound, git worktree | yes | full |
20//!
21//! **Binding is NOT gated on `.git`.** The design proposal this spec corrects
22//! claimed work binds "the moment work touches files in a git repo"; that rule
23//! would exclude the non-git working dirs (#2728) and OS temp dirs (#2747) we
24//! deliberately support and have already shipped. `Directory` is a first-class
25//! BOUND state that indexes — it is emphatically not a synonym for projectless.
26//! The git/non-git split exists only to decide which *git affordances* are
27//! offered, never whether the project binds or indexes.
28//!
29//! Test: `binding::tests::*`.
30//!
31//! [`ProjectBinding`]: crate::binding::ProjectBinding
32//! [`ProjectBinding::None`]: crate::binding::ProjectBinding::None
33//! [`ProjectBinding::Directory`]: crate::binding::ProjectBinding::Directory
34//! [`ProjectBinding::GitRepo`]: crate::binding::ProjectBinding::GitRepo
35
36use std::path::{Path, PathBuf};
37use std::process::Command;
38
39use serde::de::Error as DeError;
40use serde::{Deserialize, Deserializer, Serialize, Serializer};
41use serde_json::{Value, json};
42
43/// A workstream's project binding — zero or one project, in one of three states.
44///
45/// Why: see the module docs — this is the single typed object that replaces
46/// `task.run`'s un-omittable path and `session.create`'s un-indexable label.
47/// What: [`None`](ProjectBinding::None) is projectless (chat/planning; no index,
48/// no diff target, no project-scoped memory palace). The two bound variants both
49/// carry a canonical root and both index; they differ ONLY in whether git
50/// affordances are available.
51/// Test: `binding::tests::*`.
52#[derive(Debug, Clone, PartialEq, Eq, Default)]
53pub enum ProjectBinding {
54 /// Projectless — no directory bound. Chat/planning only.
55 #[default]
56 None,
57 /// Bound to a plain directory that is NOT a git worktree (#2728/#2747).
58 /// Indexes; git affordances are hidden, never faked.
59 Directory(PathBuf),
60 /// Bound to a git worktree. Indexes; full git affordances.
61 GitRepo(PathBuf),
62}
63
64/// The wire `state` discriminant for [`ProjectBinding::None`].
65pub const STATE_PROJECTLESS: &str = "projectless";
66/// The wire `state` discriminant for [`ProjectBinding::Directory`].
67pub const STATE_DIRECTORY: &str = "directory";
68/// The wire `state` discriminant for [`ProjectBinding::GitRepo`].
69pub const STATE_GIT_REPO: &str = "git_repo";
70
71/// Why a path could not be resolved into a bound [`ProjectBinding`].
72///
73/// Why: `session.create`'s old free-form label accepted anything — `"my-app"`
74/// bound nothing and indexed nothing, and the caller was never told. Now that the
75/// label IS the binding, a path that cannot bind must say so loudly rather than
76/// degrade into a lie. Callers map this onto `-32003 invalid_argument`.
77/// What: the two ways a supplied path fails to name a bindable project root.
78/// Test: `binding::tests::resolve_rejects_missing_path`,
79/// `binding::tests::resolve_rejects_file_path`.
80#[derive(Debug, thiserror::Error, PartialEq, Eq)]
81pub enum BindingError {
82 /// The path does not exist on disk.
83 #[error("project path does not exist: {0}")]
84 NotFound(PathBuf),
85 /// The path exists but is not a directory.
86 #[error("project path is not a directory: {0}")]
87 NotADirectory(PathBuf),
88}
89
90impl ProjectBinding {
91 /// Classify an optional project path into one of the three binding states.
92 ///
93 /// Why: the single entry point every API surface funnels through, so
94 /// `task.run` and `session.create` can never again disagree about what a
95 /// project is or how one is recognised.
96 /// What: `None` ⇒ [`ProjectBinding::None`] (projectless — the supported,
97 /// non-error case). `Some(p)` ⇒ an existing directory classified as
98 /// [`GitRepo`](ProjectBinding::GitRepo) when [`is_git_worktree`] says so,
99 /// else [`Directory`](ProjectBinding::Directory) — a BOUND, indexing state,
100 /// not a fallback to projectless. A `Some(p)` naming a nonexistent path or a
101 /// non-directory is a [`BindingError`], never a silent downgrade to
102 /// projectless: omitting a project is a deliberate choice, whereas naming one
103 /// that cannot bind is a caller mistake, and collapsing the two would hide it.
104 /// The root is canonicalised when the filesystem allows, so two spellings of
105 /// one project (`.`, `/abs/path`, a symlink) yield one binding.
106 /// Test: `binding::tests::resolve_none_is_projectless`,
107 /// `binding::tests::resolve_plain_dir_binds_as_directory`,
108 /// `binding::tests::resolve_git_repo_binds_as_git_repo`,
109 /// `binding::tests::resolve_rejects_missing_path`,
110 /// `binding::tests::resolve_rejects_file_path`.
111 pub fn resolve(path: Option<PathBuf>) -> Result<Self, BindingError> {
112 let Some(path) = path else {
113 return Ok(Self::None);
114 };
115 if !path.exists() {
116 return Err(BindingError::NotFound(path));
117 }
118 if !path.is_dir() {
119 return Err(BindingError::NotADirectory(path));
120 }
121 // Canonicalise best-effort: a failure here (permissions, a race) is not
122 // a reason to reject a directory we already confirmed exists.
123 let root = path.canonicalize().unwrap_or(path);
124 if is_git_worktree(&root) {
125 Ok(Self::GitRepo(root))
126 } else {
127 Ok(Self::Directory(root))
128 }
129 }
130
131 /// The bound project root, or `None` when projectless.
132 ///
133 /// Why: every consumer that needs a real directory (fs tools, `CLAUDE.md`
134 /// loading, indexing) asks here, and the `Option` makes "there may be no
135 /// project" impossible to forget at the type level — which is exactly the
136 /// bug the old required `PathBuf` encoded.
137 /// What: `Some(&Path)` for both bound variants; `None` for projectless.
138 /// Test: `binding::tests::root_is_none_only_when_projectless`.
139 pub fn root(&self) -> Option<&Path> {
140 match self {
141 Self::None => Option::None,
142 Self::Directory(p) | Self::GitRepo(p) => Some(p),
143 }
144 }
145
146 /// Whether a project is bound at all (either bound state).
147 ///
148 /// Why: the index/diff/palace decisions key off "is there a project", NOT
149 /// off "is it git" — conflating those two is precisely the proposal's error.
150 /// What: `false` only for [`ProjectBinding::None`].
151 /// Test: `binding::tests::non_git_dir_is_bound_and_indexes`.
152 pub fn is_bound(&self) -> bool {
153 !matches!(self, Self::None)
154 }
155
156 /// Whether git affordances (branch, PR, dirty-tree) are available.
157 ///
158 /// Why: the ONLY question the git/non-git split is allowed to answer. It
159 /// must never be used to decide whether to bind or index (AC-2.2/AC-2.3).
160 /// What: `true` only for [`ProjectBinding::GitRepo`].
161 /// Test: `binding::tests::non_git_dir_is_bound_and_indexes`,
162 /// `binding::tests::resolve_git_repo_binds_as_git_repo`.
163 pub fn is_git(&self) -> bool {
164 matches!(self, Self::GitRepo(_))
165 }
166
167 /// Whether this binding's project should be indexed (AC-2.3).
168 ///
169 /// Why: names the rule in one place so no call site re-derives it and
170 /// accidentally reintroduces the git-only gate.
171 /// What: identical to [`is_bound`](Self::is_bound) — **both** bound states
172 /// index, git or not. Projectless does not.
173 /// Test: `binding::tests::non_git_dir_is_bound_and_indexes`,
174 /// `binding::tests::projectless_does_not_index`.
175 pub fn should_index(&self) -> bool {
176 self.is_bound()
177 }
178
179 /// The wire `state` discriminant for this binding.
180 ///
181 /// Why: the SPA renders three distinct states (§4.2) and needs to tell them
182 /// apart without inferring from the presence of a path.
183 /// What: one of [`STATE_PROJECTLESS`], [`STATE_DIRECTORY`], [`STATE_GIT_REPO`].
184 /// Test: `binding::tests::wire_shape_round_trips_each_state`.
185 pub fn state(&self) -> &'static str {
186 match self {
187 Self::None => STATE_PROJECTLESS,
188 Self::Directory(_) => STATE_DIRECTORY,
189 Self::GitRepo(_) => STATE_GIT_REPO,
190 }
191 }
192
193 /// A human display label for the bound project, or `None` when projectless.
194 ///
195 /// Why: preserves `Session.project`'s existing `Option<String>` wire field —
196 /// which is now DERIVED from the binding rather than being an independent,
197 /// unvalidated source of truth. That derivation is the whole reconciliation:
198 /// the label still exists for humans, but it can no longer disagree with the
199 /// path, because there is only one path and the label is computed from it.
200 /// What: the root's display string; `None` for projectless.
201 /// Test: `binding::tests::label_is_derived_from_root`.
202 pub fn label(&self) -> Option<String> {
203 self.root().map(|p| p.display().to_string())
204 }
205
206 /// The agents directory this binding resolves `<agent>.md` from.
207 ///
208 /// Why: a projectless daemon still runs a PM and still needs agent configs;
209 /// with no project root there is no project-scoped `.claude/agents` to read,
210 /// so it must fall back rather than fail. Falling back to the process CWD
211 /// would silently bind to a directory the operator never chose — the exact
212 /// implicit-binding bug this type exists to prevent — so it falls back to the
213 /// USER-level location instead.
214 /// What: bound ⇒ [`crate::agents::locate_agents_dir`] on the project root
215 /// (the `.claude/agents` → `.open-mpm/agents` convention). Projectless ⇒ the
216 /// same convention rooted at `$HOME`, i.e. `~/.claude/agents`, matching
217 /// Claude Code's user-level agents location. With no resolvable home
218 /// directory, degrades to a bare relative `.claude/agents` — which simply
219 /// will not exist, surfacing as a normal "PM config error" rather than a panic.
220 /// Test: `binding::tests::agents_dir_uses_project_root_when_bound`,
221 /// `binding::tests::projectless_agents_dir_is_user_level`.
222 pub fn agents_dir(&self) -> PathBuf {
223 match self.root() {
224 Some(root) => crate::agents::locate_agents_dir(root),
225 Option::None => match dirs::home_dir() {
226 Some(home) => crate::agents::locate_agents_dir(&home),
227 Option::None => PathBuf::from(".claude").join("agents"),
228 },
229 }
230 }
231
232 /// The JSON wire representation: `{ "state": …, "root": … }`.
233 ///
234 /// Why: the SPA needs the state discriminant explicitly rather than
235 /// inferring projectless from a null path (AC-2.1) — an absent `root` and a
236 /// `projectless` state are the same fact today, but only the discriminant
237 /// stays honest if a future state carries no path for a different reason.
238 /// What: `root` is `null` for projectless, the display path otherwise.
239 /// Test: `binding::tests::wire_shape_round_trips_each_state`.
240 pub fn to_json(&self) -> Value {
241 json!({ "state": self.state(), "root": self.label() })
242 }
243}
244
245impl Serialize for ProjectBinding {
246 /// Serialise via [`ProjectBinding::to_json`] so the wire shape is defined
247 /// in exactly one place.
248 ///
249 /// Why: `Session` derives `Serialize`; without this the enum would emit
250 /// serde's default externally-tagged shape and drift from `to_json`.
251 /// What: delegates to [`ProjectBinding::to_json`].
252 /// Test: `binding::tests::serialize_matches_to_json`.
253 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
254 self.to_json().serialize(serializer)
255 }
256}
257
258/// The `{ state, root }` wire shape, used only as [`ProjectBinding`]'s
259/// deserialization intermediate.
260#[derive(Deserialize)]
261struct BindingWire {
262 state: String,
263 #[serde(default)]
264 root: Option<PathBuf>,
265}
266
267impl<'de> Deserialize<'de> for ProjectBinding {
268 /// Reconstruct a binding from its wire shape.
269 ///
270 /// Why: `Session` derives `Deserialize`, so its `binding` field needs one.
271 /// What: reconstructs from the EXPLICIT `state` discriminant and does NOT
272 /// re-probe the filesystem — deserializing a value must not depend on
273 /// whether a path still exists or is still a git repo on THIS machine, which
274 /// would make a round-trip lossy (a `GitRepo` read back on a host without
275 /// the repo would silently become a `Directory`). A bound state missing its
276 /// `root`, or an unknown discriminant, is a hard error rather than a silent
277 /// downgrade to projectless.
278 /// Test: `binding::tests::deserialize_round_trips_without_touching_disk`,
279 /// `binding::tests::deserialize_rejects_bound_state_without_root`.
280 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
281 let wire = BindingWire::deserialize(deserializer)?;
282 let root = |w: Option<PathBuf>| {
283 w.ok_or_else(|| {
284 D::Error::custom(format!("binding state `{}` requires a root", wire.state))
285 })
286 };
287 match wire.state.as_str() {
288 STATE_PROJECTLESS => Ok(Self::None),
289 STATE_DIRECTORY => Ok(Self::Directory(root(wire.root.clone())?)),
290 STATE_GIT_REPO => Ok(Self::GitRepo(root(wire.root.clone())?)),
291 other => Err(D::Error::custom(format!(
292 "unknown project binding state `{other}` (expected one of \
293 `{STATE_PROJECTLESS}`, `{STATE_DIRECTORY}`, `{STATE_GIT_REPO}`)"
294 ))),
295 }
296 }
297}
298
299/// Whether `root` is inside a git worktree.
300///
301/// Why: the ONE git-detection implementation in the crate. `run_task::diff`'s
302/// snapshot logic needs the identical answer this binding classifies on; two
303/// independent probes could disagree and produce a `GitRepo` binding whose diff
304/// silently took the non-git file-map path.
305/// What: shells out to `git -C <root> rev-parse --is-inside-work-tree`. Fail-open
306/// to `false` — no git binary, a non-repo, or any error means "no git
307/// affordances", which is a fully supported bound state (§4.2), never an error.
308/// Test: `binding::tests::resolve_git_repo_binds_as_git_repo`,
309/// `binding::tests::resolve_plain_dir_binds_as_directory`.
310pub fn is_git_worktree(root: &Path) -> bool {
311 Command::new("git")
312 .arg("-C")
313 .arg(root)
314 .args(["rev-parse", "--is-inside-work-tree"])
315 .output()
316 .map(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "true")
317 .unwrap_or(false)
318}
319
320#[cfg(test)]
321#[path = "tests.rs"]
322mod tests;