rho-coding-agent 2.25.0

A fast Rust agent harness with a small footprint and opinionated defaults
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Durable plugin activation state.
//!
//! Enable and disable choices live outside package directories so install,
//! link, and package updates never rewrite user policy. User state lives under
//! the Rho data root (`$RHO_HOME` or `~/.rho`). Project state lives at
//! `<repository>/.rho/plugins.toml` (or `<cwd>/.rho/plugins.toml` outside a
//! git worktree). Missing files mean every discovered plugin is enabled.

use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize};

use crate::config_writer;

const STATE_VERSION: u32 = 1;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum PluginScope {
    Project,
    User,
}

impl PluginScope {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Project => "project",
            Self::User => "user",
        }
    }
}

/// How a package entered a managed plugins root.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum PluginOrigin {
    /// Placed by hand or by another tool under a discovery root.
    Local,
    /// Copied into a managed root by `rho plugins install`.
    Install,
    /// Symlinked into a managed root by `rho plugins link`.
    Link,
    /// Copied from a git repository by `rho plugins install <url>`.
    Git,
}

impl PluginOrigin {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Local => "local",
            Self::Install => "install",
            Self::Link => "link",
            Self::Git => "git",
        }
    }
}

/// The git source and commit a package was installed from.
///
/// `rho plugins update` refetches `url` at `ref` and replaces the package when
/// the fetched commit differs from `commit`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GitRecord {
    pub(crate) url: String,
    #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
    pub(crate) git_ref: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) subdir: Option<String>,
    pub(crate) commit: String,
}

/// How Rho placed a package into a managed root.
///
/// Stored as `origin` plus its payload (`link_target` or a `git` table) in
/// `plugins.toml`; see [`StoredEntry`] for the on-disk shape.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum InstallRecord {
    Copy,
    Link { target: String },
    Git(GitRecord),
}

impl InstallRecord {
    pub(crate) fn origin(&self) -> PluginOrigin {
        match self {
            Self::Copy => PluginOrigin::Install,
            Self::Link { .. } => PluginOrigin::Link,
            Self::Git(_) => PluginOrigin::Git,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PluginStateStore {
    pub(crate) user: PluginStateFile,
    pub(crate) project: PluginStateFile,
    pub(crate) user_path: PathBuf,
    pub(crate) project_path: PathBuf,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PluginStateFile {
    #[serde(default = "default_version")]
    pub(crate) version: u32,
    #[serde(default)]
    pub(crate) plugins: BTreeMap<String, PluginStateEntry>,
}

impl Default for PluginStateFile {
    fn default() -> Self {
        Self {
            version: STATE_VERSION,
            plugins: BTreeMap::new(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "StoredEntry", into = "StoredEntry")]
pub(crate) struct PluginStateEntry {
    /// Absent means enabled. Explicit `false` disables the package.
    pub(crate) enabled: bool,
    /// How Rho installed the package; `None` for hand-placed packages.
    pub(crate) install: Option<InstallRecord>,
}

impl Default for PluginStateEntry {
    fn default() -> Self {
        Self {
            enabled: true,
            install: None,
        }
    }
}

/// On-disk shape of one `[plugins.<name>]` entry.
///
/// Only combinations Rho writes are accepted, so `origin` always agrees with
/// its payload once parsed into [`PluginStateEntry`].
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StoredEntry {
    #[serde(default = "default_enabled", skip_serializing_if = "is_true")]
    enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    origin: Option<PluginOrigin>,
    /// Absolute path recorded for linked packages (display and inspect only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    link_target: Option<String>,
    /// Source recorded for git-installed packages; read by `rho plugins update`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    git: Option<GitRecord>,
}

impl TryFrom<StoredEntry> for PluginStateEntry {
    type Error = String;

    fn try_from(stored: StoredEntry) -> Result<Self, String> {
        let install = match (stored.origin, stored.link_target, stored.git) {
            (None, None, None) => None,
            (Some(PluginOrigin::Install), None, None) => Some(InstallRecord::Copy),
            (Some(PluginOrigin::Link), Some(target), None) => Some(InstallRecord::Link { target }),
            (Some(PluginOrigin::Git), None, Some(git)) => Some(InstallRecord::Git(git)),
            (origin, link_target, git) => {
                let origin = origin.map_or("(none)", PluginOrigin::as_str);
                return Err(format!(
                    "origin {origin} does not match its fields (link_target: {}, git: {})",
                    presence(link_target.is_some()),
                    presence(git.is_some()),
                ));
            }
        };
        Ok(Self {
            enabled: stored.enabled,
            install,
        })
    }
}

fn presence(present: bool) -> &'static str {
    if present {
        "present"
    } else {
        "absent"
    }
}

impl From<PluginStateEntry> for StoredEntry {
    fn from(entry: PluginStateEntry) -> Self {
        let (origin, link_target, git) = match entry.install {
            None => (None, None, None),
            Some(InstallRecord::Copy) => (Some(PluginOrigin::Install), None, None),
            Some(InstallRecord::Link { target }) => (Some(PluginOrigin::Link), Some(target), None),
            Some(InstallRecord::Git(git)) => (Some(PluginOrigin::Git), None, Some(git)),
        };
        Self {
            enabled: entry.enabled,
            origin,
            link_target,
            git,
        }
    }
}

fn default_version() -> u32 {
    STATE_VERSION
}

fn default_enabled() -> bool {
    true
}

fn is_true(value: &bool) -> bool {
    *value
}

impl PluginStateStore {
    /// Load user and project state for `cwd`. Missing files are empty defaults.
    pub(crate) fn load(cwd: &Path, rho_home: Option<&Path>) -> anyhow::Result<Self> {
        let user_path = user_state_path(rho_home)?;
        let project_path = project_state_path(cwd);
        Ok(Self {
            user: load_file(&user_path)?,
            project: load_file(&project_path)?,
            user_path,
            project_path,
        })
    }

    /// Empty store with paths resolved for `cwd` (tests and fallback loads).
    pub(crate) fn empty(cwd: &Path, rho_home: Option<&Path>) -> Self {
        Self {
            user: PluginStateFile::default(),
            project: PluginStateFile::default(),
            user_path: user_state_path(rho_home).unwrap_or_else(|_| PathBuf::from("plugins.toml")),
            project_path: project_state_path(cwd),
        }
    }

    pub(crate) fn is_enabled(&self, scope: PluginScope, name: &str) -> bool {
        self.file(scope)
            .plugins
            .get(name)
            .map(|entry| entry.enabled)
            .unwrap_or(true)
    }

    pub(crate) fn entry(&self, scope: PluginScope, name: &str) -> Option<&PluginStateEntry> {
        self.file(scope).plugins.get(name)
    }

    pub(crate) fn install_record(&self, scope: PluginScope, name: &str) -> Option<&InstallRecord> {
        self.entry(scope, name)
            .and_then(|entry| entry.install.as_ref())
    }

    pub(crate) fn git_record(&self, scope: PluginScope, name: &str) -> Option<&GitRecord> {
        match self.install_record(scope, name)? {
            InstallRecord::Git(git) => Some(git),
            InstallRecord::Copy | InstallRecord::Link { .. } => None,
        }
    }

    /// Names of packages in `scope` that were installed from git.
    pub(crate) fn git_installed(&self, scope: PluginScope) -> Vec<String> {
        self.file(scope)
            .plugins
            .iter()
            .filter(|(_, entry)| matches!(entry.install, Some(InstallRecord::Git(_))))
            .map(|(name, _)| name.clone())
            .collect()
    }

    pub(crate) fn origin(
        &self,
        scope: PluginScope,
        name: &str,
        package_path: &Path,
    ) -> PluginOrigin {
        if let Some(record) = self.install_record(scope, name) {
            return record.origin();
        }
        match std::fs::symlink_metadata(package_path) {
            Ok(metadata) if metadata.file_type().is_symlink() => PluginOrigin::Link,
            _ => PluginOrigin::Local,
        }
    }

    pub(crate) fn set_enabled(
        &mut self,
        scope: PluginScope,
        name: &str,
        enabled: bool,
    ) -> anyhow::Result<()> {
        self.update_scope(scope, |file| {
            let entry = file.plugins.entry(name.to_string()).or_default();
            entry.enabled = enabled;
            Ok(())
        })
    }

    pub(crate) fn record_install(
        &mut self,
        scope: PluginScope,
        name: &str,
        record: InstallRecord,
    ) -> anyhow::Result<()> {
        self.update_scope(scope, |file| {
            let entry = file.plugins.entry(name.to_string()).or_default();
            entry.install = Some(record);
            // Fresh installs start enabled even if a prior disable entry remained.
            entry.enabled = true;
            Ok(())
        })
    }

    /// Record a new commit for a git-installed package, keeping enablement.
    pub(crate) fn record_git_update(
        &mut self,
        scope: PluginScope,
        name: &str,
        git: GitRecord,
    ) -> anyhow::Result<()> {
        self.update_scope(scope, |file| {
            let entry = file.plugins.entry(name.to_string()).or_default();
            entry.install = Some(InstallRecord::Git(git));
            Ok(())
        })
    }

    pub(crate) fn clear_package_record(
        &mut self,
        scope: PluginScope,
        name: &str,
    ) -> anyhow::Result<()> {
        self.update_scope(scope, |file| {
            file.plugins.remove(name);
            Ok(())
        })
    }

    fn file(&self, scope: PluginScope) -> &PluginStateFile {
        match scope {
            PluginScope::User => &self.user,
            PluginScope::Project => &self.project,
        }
    }

    fn file_mut(&mut self, scope: PluginScope) -> &mut PluginStateFile {
        match scope {
            PluginScope::User => &mut self.user,
            PluginScope::Project => &mut self.project,
        }
    }

    /// Serialize one scope mutation under a lock that covers reload + write.
    fn update_scope<F>(&mut self, scope: PluginScope, mutate: F) -> anyhow::Result<()>
    where
        F: FnOnce(&mut PluginStateFile) -> anyhow::Result<()>,
    {
        let path = self.path(scope).to_path_buf();
        let _guard = lock_scope_state(&path)?;
        // Reload under the lock so concurrent writers cannot lose updates.
        *self.file_mut(scope) = load_file(&path)?;
        mutate(self.file_mut(scope))?;
        self.persist_locked(scope)
    }

    fn path(&self, scope: PluginScope) -> &Path {
        match scope {
            PluginScope::User => &self.user_path,
            PluginScope::Project => &self.project_path,
        }
    }

    fn persist_locked(&self, scope: PluginScope) -> anyhow::Result<()> {
        let path = self.path(scope);
        let mut file = self.file(scope).clone();
        // Drop inert default entries so a clean tree does not keep noise.
        file.plugins
            .retain(|_, entry| entry != &PluginStateEntry::default());
        // Drop empty files so a clean tree does not keep an inert plugins.toml.
        if file.plugins.is_empty() {
            match std::fs::remove_file(path) {
                Ok(()) => return Ok(()),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
                Err(error) => return Err(error.into()),
            }
        }
        let serialized = toml::to_string_pretty(&file)?;
        config_writer::write_atomically(path, &serialized)
    }
}

fn lock_scope_state(path: &Path) -> anyhow::Result<rho_providers::file_lock::FileLock> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let lock_path = scope_lock_path(path);
    let file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&lock_path)
        .map_err(|error| {
            anyhow::anyhow!(
                "cannot open plugin state lock {}: {error}",
                crate::paths::display(&lock_path)
            )
        })?;
    rho_providers::file_lock::FileLock::acquire(file).map_err(|error| {
        anyhow::anyhow!(
            "cannot lock plugin state {}: {error}",
            crate::paths::display(&lock_path)
        )
    })
}

fn scope_lock_path(path: &Path) -> PathBuf {
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("plugins.toml");
    path.with_file_name(format!(".{file_name}.lock"))
}

pub(crate) fn user_state_path(rho_home: Option<&Path>) -> anyhow::Result<PathBuf> {
    let root = match rho_home {
        Some(path) => path.to_path_buf(),
        None => crate::paths::rho_dir()?,
    };
    Ok(root.join("plugins.toml"))
}

pub(crate) fn project_state_path(cwd: &Path) -> PathBuf {
    project_root(cwd).join(".rho").join("plugins.toml")
}

/// Repository root when inside a git worktree, otherwise `cwd`.
pub(crate) fn project_root(cwd: &Path) -> PathBuf {
    crate::workspace::project_ancestor_dirs(cwd)
        .into_iter()
        .next()
        .unwrap_or_else(|| cwd.to_path_buf())
}

pub(crate) fn plugins_root_at(dir: &Path) -> PathBuf {
    dir.join(".agents").join("plugins")
}

pub(crate) fn user_plugins_root(home: &Path) -> PathBuf {
    plugins_root_at(home)
}

pub(crate) fn project_plugins_root(cwd: &Path) -> PathBuf {
    plugins_root_at(&project_root(cwd))
}

fn load_file(path: &Path) -> anyhow::Result<PluginStateFile> {
    match std::fs::read_to_string(path) {
        Ok(text) => parse_state_file(&text)
            .map_err(|error| anyhow::anyhow!("invalid plugin state {}: {error}", path.display())),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            Ok(PluginStateFile::default())
        }
        Err(error) => Err(error.into()),
    }
}

pub(crate) fn parse_state_file(text: &str) -> Result<PluginStateFile, String> {
    let file: PluginStateFile = toml::from_str(text).map_err(|error| error.to_string())?;
    if file.version != STATE_VERSION {
        return Err(format!(
            "unsupported plugins.toml version {} (expected {STATE_VERSION})",
            file.version
        ));
    }
    for name in file.plugins.keys() {
        super::manifest::validate_plugin_name(name)
            .map_err(|error| format!("invalid plugin key `{name}`: {error}"))?;
    }
    Ok(file)
}

#[cfg(test)]
#[path = "state_tests.rs"]
mod tests;