clawft-core 0.2.1

Core engine for clawft (agent loop, message bus, context management)
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
//! Workspace discovery, lifecycle management, and merged config loading.
//!
//! Provides the 4-step workspace discovery algorithm and [`WorkspaceManager`]
//! for creating, listing, loading, and deleting workspaces.
//!
//! Per-agent workspace isolation is in the [`agent`] submodule.
//! Config merge logic is in the [`config`] submodule.

pub mod agent;
mod config;

pub use config::{load_merged_config, load_merged_config_from};

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

use clawft_types::workspace::{WorkspaceEntry, WorkspaceRegistry};
use clawft_types::{ClawftError, Result};

// ── Discovery ────────────────────────────────────────────────────────────

/// 4-step workspace discovery algorithm.
///
/// 1. `$CLAWFT_WORKSPACE` environment variable
/// 2. Walk from `cwd` upward looking for a `.clawft/` directory
/// 3. Fall back to `~/.clawft/` (global workspace)
///
/// Returns `None` only if the home directory cannot be determined.
pub fn discover_workspace() -> Option<PathBuf> {
    // Step 1: env var
    if let Ok(ws) = std::env::var("CLAWFT_WORKSPACE") {
        let path = PathBuf::from(&ws);
        if path.join(".clawft").is_dir() {
            return Some(path);
        }
    }

    // Step 2: walk cwd upward
    if let Ok(cwd) = std::env::current_dir() {
        let mut dir: &Path = cwd.as_path();
        loop {
            if dir.join(".clawft").is_dir() {
                return Some(dir.to_path_buf());
            }
            match dir.parent() {
                Some(parent) => dir = parent,
                None => break,
            }
        }
    }

    // Step 3: global default
    #[cfg(feature = "native")]
    { dirs::home_dir().map(|h| h.join(".clawft")) }
    #[cfg(not(feature = "native"))]
    { Some(std::path::PathBuf::from(".clawft")) }
}

// ── Workspace status ─────────────────────────────────────────────────────

/// Summary of a workspace's current state.
pub struct WorkspaceStatus {
    /// Workspace display name.
    pub name: String,

    /// Absolute path to workspace root.
    pub path: PathBuf,

    /// Number of session files found in `.clawft/sessions/`.
    pub session_count: usize,

    /// Whether `.clawft/config.json` exists.
    pub has_config: bool,

    /// Whether `CLAWFT.md` exists at the workspace root.
    pub has_clawft_md: bool,
}

// ── WorkspaceManager ─────────────────────────────────────────────────────

/// The canonical subdirectories created inside `.clawft/`.
const WORKSPACE_SUBDIRS: &[&str] =
    &["sessions", "memory", "skills", "agents", "hooks"];

/// Manages workspace lifecycle (create, list, load, status, delete).
pub struct WorkspaceManager {
    /// Path to the global registry file (`~/.clawft/workspaces.json`).
    pub(crate) registry_path: PathBuf,

    /// In-memory copy of the registry.
    registry: WorkspaceRegistry,
}

impl WorkspaceManager {
    /// Create a new manager, loading the registry from the default path.
    ///
    /// The default registry path is `~/.clawft/workspaces.json`.
    pub fn new() -> Result<Self> {
        #[cfg(feature = "native")]
        let home =
            dirs::home_dir().ok_or_else(|| ClawftError::ConfigInvalid {
                reason: "cannot determine home directory".into(),
            })?;
        #[cfg(not(feature = "native"))]
        let home = std::path::PathBuf::from(".clawft");
        let registry_path = home.join(".clawft").join("workspaces.json");
        let registry = WorkspaceRegistry::load(&registry_path).map_err(|e| {
            ClawftError::ConfigInvalid {
                reason: format!("failed to load workspace registry: {e}"),
            }
        })?;

        Ok(Self {
            registry_path,
            registry,
        })
    }

    /// Create a new manager with an explicit registry path.
    ///
    /// Useful for testing.
    pub fn with_registry_path(registry_path: PathBuf) -> Result<Self> {
        let registry = WorkspaceRegistry::load(&registry_path).map_err(|e| {
            ClawftError::ConfigInvalid {
                reason: format!("failed to load workspace registry: {e}"),
            }
        })?;

        Ok(Self {
            registry_path,
            registry,
        })
    }

    /// Create a new workspace.
    ///
    /// Creates:
    /// 1. `.clawft/` and subdirectories (`sessions`, `memory`, `skills`,
    ///    `agents`, `hooks`)
    /// 2. `.clawft/config.json` with `{}`
    /// 3. `CLAWFT.md` with a starter template
    /// 4. Registers the workspace in the global registry
    ///
    /// Returns the absolute path to the workspace root.
    pub fn create(&mut self, name: &str, parent_dir: &Path) -> Result<PathBuf> {
        let ws_root = parent_dir.join(name);
        let dot_clawft = ws_root.join(".clawft");

        // Create .clawft/ and subdirectories
        for subdir in WORKSPACE_SUBDIRS {
            std::fs::create_dir_all(dot_clawft.join(subdir))?;
        }

        // Create config.json
        std::fs::write(dot_clawft.join("config.json"), "{}\n")?;

        // Create MEMORY.md and HISTORY.md (empty)
        std::fs::write(dot_clawft.join("MEMORY.md"), "")?;
        std::fs::write(dot_clawft.join("HISTORY.md"), "")?;

        // Create CLAWFT.md
        let clawft_md = format!(
            "# {name}\n\n\
             Workspace created by clawft.\n\n\
             ## Configuration\n\n\
             Edit `.clawft/config.json` to customize this workspace.\n"
        );
        std::fs::write(ws_root.join("CLAWFT.md"), clawft_md)?;

        // Register in global registry
        let now = chrono::Utc::now();
        let entry = WorkspaceEntry {
            name: name.into(),
            path: ws_root.clone(),
            last_accessed: Some(now),
            created_at: Some(now),
        };
        self.registry.register(entry);
        self.save_registry()?;

        Ok(ws_root)
    }

    /// List all registered workspaces.
    pub fn list(&self) -> Vec<&WorkspaceEntry> {
        self.registry.workspaces.iter().collect()
    }

    /// Load a workspace by name or path string.
    ///
    /// Returns the workspace root path if found.
    pub fn load(&mut self, name_or_path: &str) -> Result<PathBuf> {
        // Try by name first
        if let Some(entry) = self.registry.find_by_name(name_or_path) {
            return Ok(entry.path.clone());
        }

        // Try as a path
        let path = PathBuf::from(name_or_path);
        if path.join(".clawft").is_dir() {
            return Ok(path);
        }

        Err(ClawftError::ConfigInvalid {
            reason: format!("workspace not found: {name_or_path}"),
        })
    }

    /// Get the status of a workspace at the given path.
    pub fn status(&self, path: &Path) -> Result<WorkspaceStatus> {
        let dot_clawft = path.join(".clawft");
        let name = self
            .registry
            .find_by_path(path)
            .map(|e| e.name.clone())
            .unwrap_or_else(|| {
                path.file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "unknown".into())
            });

        let sessions_dir = dot_clawft.join("sessions");
        let session_count = if sessions_dir.is_dir() {
            std::fs::read_dir(&sessions_dir)
                .map(|rd| rd.count())
                .unwrap_or(0)
        } else {
            0
        };

        Ok(WorkspaceStatus {
            name,
            path: path.to_path_buf(),
            session_count,
            has_config: dot_clawft.join("config.json").exists(),
            has_clawft_md: path.join("CLAWFT.md").exists(),
        })
    }

    /// Delete a workspace by name.
    ///
    /// Removes the entry from the registry but does NOT delete files
    /// from disk (that is the caller's responsibility).
    pub fn delete(&mut self, name: &str) -> Result<()> {
        if !self.registry.remove_by_name(name) {
            return Err(ClawftError::ConfigInvalid {
                reason: format!("workspace not found: {name}"),
            });
        }
        self.save_registry()?;
        Ok(())
    }

    /// Persist the registry to disk.
    fn save_registry(&self) -> Result<()> {
        self.registry
            .save(&self.registry_path)
            .map_err(|e| ClawftError::ConfigInvalid {
                reason: format!("failed to save workspace registry: {e}"),
            })
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    /// Monotonic counter to give each test a unique temp directory.
    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    // ── Discovery tests ──────────────────────────────────────────────

    #[test]
    fn discover_workspace_returns_some() {
        let result = discover_workspace();
        assert!(result.is_some(), "discover_workspace should return Some");
    }

    #[test]
    fn discover_workspace_env_var() {
        let n = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir()
            .join(format!("clawft-test-discover-env-{n}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join(".clawft")).unwrap();

        let result =
            temp_env::with_var("CLAWFT_WORKSPACE", Some(dir.to_str().unwrap()), || {
                discover_workspace()
            });

        assert_eq!(result, Some(dir.clone()));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn discover_workspace_env_var_invalid_skipped() {
        let result = temp_env::with_var(
            "CLAWFT_WORKSPACE",
            Some("/nonexistent/path/for/test"),
            || discover_workspace(),
        );

        assert!(result.is_some());
        assert_ne!(
            result.unwrap(),
            PathBuf::from("/nonexistent/path/for/test")
        );
    }

    // ── WorkspaceManager tests ───────────────────────────────────────

    /// Create a unique temp directory and registry path for each test.
    pub(crate) fn temp_registry(label: &str) -> (PathBuf, PathBuf) {
        let n = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir()
            .join(format!("clawft-test-wm-{label}-{n}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let registry_path = dir.join("workspaces.json");
        (dir, registry_path)
    }

    #[test]
    fn workspace_manager_create_directories() {
        let (dir, registry_path) = temp_registry("create-dirs");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        let ws_path = wm.create("test-ws", &dir).unwrap();
        let dot_clawft = ws_path.join(".clawft");

        for subdir in WORKSPACE_SUBDIRS {
            assert!(
                dot_clawft.join(subdir).is_dir(),
                "missing subdir: {subdir}"
            );
        }

        assert!(dot_clawft.join("config.json").exists());
        assert!(dot_clawft.join("MEMORY.md").exists());
        assert!(dot_clawft.join("HISTORY.md").exists());
        assert!(ws_path.join("CLAWFT.md").exists());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_create_registers_in_registry() {
        let (dir, registry_path) = temp_registry("create-reg");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path.clone()).unwrap();

        wm.create("reg-test", &dir).unwrap();

        let loaded = WorkspaceRegistry::load(&registry_path).unwrap();
        assert!(loaded.find_by_name("reg-test").is_some());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_list() {
        let (dir, registry_path) = temp_registry("list");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        assert!(wm.list().is_empty(), "fresh registry should be empty");

        wm.create("ws-a", &dir).unwrap();
        wm.create("ws-b", &dir).unwrap();

        let list = wm.list();
        assert_eq!(list.len(), 2);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_load_by_name() {
        let (dir, registry_path) = temp_registry("load-name");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        let created = wm.create("load-test", &dir).unwrap();
        let loaded = wm.load("load-test").unwrap();
        assert_eq!(created, loaded);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_load_by_path() {
        let (dir, registry_path) = temp_registry("load-path");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        let created = wm.create("path-test", &dir).unwrap();
        let loaded = wm.load(created.to_str().unwrap()).unwrap();
        assert_eq!(created, loaded);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_load_not_found() {
        let (dir, registry_path) = temp_registry("load-notfound");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        let result = wm.load("nonexistent");
        assert!(result.is_err());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_status() {
        let (dir, registry_path) = temp_registry("status");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        let ws_path = wm.create("status-test", &dir).unwrap();
        let status = wm.status(&ws_path).unwrap();

        assert_eq!(status.name, "status-test");
        assert_eq!(status.path, ws_path);
        assert_eq!(status.session_count, 0);
        assert!(status.has_config);
        assert!(status.has_clawft_md);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_delete() {
        let (dir, registry_path) = temp_registry("delete");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        wm.create("del-test", &dir).unwrap();
        assert_eq!(wm.list().len(), 1);

        wm.delete("del-test").unwrap();
        assert!(wm.list().is_empty());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn workspace_manager_delete_not_found() {
        let (dir, registry_path) = temp_registry("delete-notfound");
        let mut wm =
            WorkspaceManager::with_registry_path(registry_path).unwrap();

        let result = wm.delete("nonexistent");
        assert!(result.is_err());

        let _ = std::fs::remove_dir_all(&dir);
    }
}