wsb 0.155.49

Workspace - A tool suite for file operations, version management, and development workflow automation
Documentation
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

/// A single project registered for wstemplate scanning.
///
/// Each project has exactly one entry defining:
/// - `alias`: the identifier used in `{{ projects.ALIAS.* }}` template vars
/// - `root`: the directory tree to scan for `.wstemplate` files on `wsb update`
///
/// All other projects referenced in a template are resolved dynamically by
/// scanning the `root` directory for `.wsb/state.json` files.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WstemplateEntry {
    pub root: PathBuf,
    pub alias: String,
}

/// Per-project workspace configuration, persisted as `.wsb/state.json`.
///
/// Each project has at most one [`WstemplateEntry`] defining its alias and
/// scan root. Cross-project references are resolved dynamically by scanning
/// the root for sibling `.wsb/state.json` files — no explicit cross-project
/// entries are needed. Loading a state file with more than one entry is a
/// hard error.
#[derive(Debug, Serialize, Deserialize)]
pub struct WorkspaceState {
    pub version: u32,
    pub project_root: PathBuf,
    pub project_name: Option<String>,
    pub tools: HashMap<String, serde_json::Value>,
    #[serde(default)]
    pub wstemplate_entries: Vec<WstemplateEntry>,
    /// Set to true after the shell completion hint has been shown once.
    #[serde(default)]
    pub completion_hint_shown: bool,
}

impl Default for WorkspaceState {
    fn default() -> Self {
        Self {
            version: 1,
            project_root: PathBuf::new(),
            project_name: None,
            tools: HashMap::new(),
            wstemplate_entries: Vec::new(),
            completion_hint_shown: false,
        }
    }
}

impl WorkspaceState {
    /// Initialize workspace state in a project directory.
    /// If `name` is provided it is used as the project name, otherwise the
    /// directory name of `project_root` is used.
    pub fn initialize(project_root: &Path, name: Option<&str>) -> Result<Self> {
        let workspace_dir = project_root.join(".wsb");
        fs::create_dir_all(&workspace_dir).context("Failed to create .wsb directory")?;

        // Create subdirectories
        fs::create_dir_all(workspace_dir.join("templates"))
            .context("Failed to create templates directory")?;
        fs::create_dir_all(workspace_dir.join("logs"))
            .context("Failed to create logs directory")?;

        let mut state = Self::default();
        state.project_root = project_root.to_path_buf();
        state.project_name = match name {
            Some(n) => Some(n.to_string()),
            None => project_root
                .file_name()
                .and_then(|n| n.to_str())
                .map(|s| s.to_string()),
        };

        state.save(project_root)?;
        Ok(state)
    }

    /// Load workspace state from project directory
    pub fn load(project_root: &Path) -> Result<Self> {
        let state_file = project_root.join(".wsb").join("state.json");

        if !state_file.exists() {
            return Self::initialize(project_root, None);
        }

        let content =
            fs::read_to_string(&state_file).context("Failed to read workspace state file")?;

        let mut state: Self =
            serde_json::from_str(&content).context("Failed to parse workspace state file")?;

        // Update project root in case it moved
        state.project_root = project_root.to_path_buf();

        // Enforce single-entry wstemplate model.
        // Each project has at most one entry (its own alias + scan root).
        // All other projects are discovered dynamically by scanning the root.
        if state.wstemplate_entries.len() > 1 {
            anyhow::bail!(
                "state.json at {} has {} wstemplate entries, expected at most 1. \
                 Each project should have exactly one entry (its own alias + scan root). \
                 Remove extra entries from {}",
                state_file.display(),
                state.wstemplate_entries.len(),
                state_file.display()
            );
        }

        Ok(state)
    }

    /// Save workspace state to project directory
    pub fn save(&self, project_root: &Path) -> Result<()> {
        let workspace_dir = project_root.join(".wsb");
        fs::create_dir_all(&workspace_dir).context("Failed to create .wsb directory")?;

        let state_file = workspace_dir.join("state.json");
        let content =
            serde_json::to_string_pretty(self).context("Failed to serialize workspace state")?;

        fs::write(&state_file, content).context("Failed to write workspace state file")?;

        Ok(())
    }

    /// Get workspace directory path
    pub fn workspace_dir(&self) -> PathBuf {
        self.project_root.join(".wsb")
    }

    /// Get tool-specific directory
    pub fn tool_dir(&self, tool_name: &str) -> PathBuf {
        self.workspace_dir().join(tool_name)
    }

    /// Get or create tool-specific configuration
    pub fn get_tool_config<T>(&self, tool_name: &str) -> Option<T>
    where
        T: for<'de> Deserialize<'de>,
    {
        self.tools
            .get(tool_name)
            .and_then(|value| serde_json::from_value(value.clone()).ok())
    }

    /// Set tool-specific configuration
    pub fn set_tool_config<T>(&mut self, tool_name: &str, config: &T) -> Result<()>
    where
        T: Serialize,
    {
        let value = serde_json::to_value(config).context("Failed to serialize tool config")?;

        self.tools.insert(tool_name.to_string(), value);
        Ok(())
    }

    /// Return the project's wstemplate entry, if configured.
    ///
    /// Each project has at most one entry: its own alias and scan root.
    /// All other projects are discovered dynamically by scanning the root.
    pub fn wstemplate_entry(&self) -> Option<&WstemplateEntry> {
        self.wstemplate_entries.first()
    }

    /// Return the effective wstemplate entry for this project.
    ///
    /// If no entry is explicitly configured, default to scanning this project's
    /// own root using a deterministic alias derived from the project directory.
    /// Missing configuration must not disable `.wstemplate` rendering.
    pub fn effective_wstemplate_entry(&self) -> WstemplateEntry {
        self.wstemplate_entry()
            .cloned()
            .unwrap_or_else(|| WstemplateEntry {
                alias: crate::state::wstemplate::WstemplateEngine::derive_alias(&self.project_root),
                root: self.project_root.clone(),
            })
    }

    /// Set the project's wstemplate entry, replacing any existing entry.
    ///
    /// Each project has exactly ONE entry: its own alias and scan root.
    pub fn set_wstemplate_entry(&mut self, entry: WstemplateEntry) {
        self.wstemplate_entries = vec![entry];
    }

    /// Remove the project's wstemplate entry entirely.
    pub fn clear_wstemplate_entry(&mut self) {
        self.wstemplate_entries.clear();
    }
}


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

    #[test]
    fn test_workspace_state_initialize() {
        let temp_dir = TempDir::new().unwrap();
        let state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        assert_eq!(state.version, 1);
        assert_eq!(state.project_root, temp_dir.path());
        assert!(temp_dir.path().join(".wsb").exists());
        assert!(temp_dir.path().join(".wsb").join("templates").exists());
        assert!(temp_dir.path().join(".wsb").join("state.json").exists());
        assert!(state.wstemplate_entries.is_empty());
        assert!(!state.completion_hint_shown);
    }

    #[test]
    fn test_workspace_state_save_load() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        // Set some tool config
        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct TestConfig {
            enabled: bool,
            value: String,
        }

        let test_config = TestConfig {
            enabled: true,
            value: "test".to_string(),
        };

        state.set_tool_config("test_tool", &test_config).unwrap();
        state.save(temp_dir.path()).unwrap();

        // Load and verify
        let loaded_state = WorkspaceState::load(temp_dir.path()).unwrap();
        let loaded_config: TestConfig = loaded_state.get_tool_config("test_tool").unwrap();

        assert_eq!(loaded_config, test_config);
    }

    #[test]
    fn test_wstemplate_entry_roundtrips_through_state_json() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        let entry = WstemplateEntry {
            alias: "my_project".to_string(),
            root: PathBuf::from("/some/scan/root"),
        };
        state.set_wstemplate_entry(entry.clone());
        state.save(temp_dir.path()).unwrap();

        let loaded = WorkspaceState::load(temp_dir.path()).unwrap();
        assert_eq!(loaded.wstemplate_entries.len(), 1);
        assert_eq!(loaded.wstemplate_entries[0], entry);
    }

    #[test]
    fn test_state_without_wstemplate_entries_loads_with_empty_vec() {
        // State JSON written without the wstemplate_entries field must deserialize
        // to an empty Vec (via serde default), not fail.
        let temp_dir = TempDir::new().unwrap();
        let ws_dir = temp_dir.path().join(".wsb");
        std::fs::create_dir_all(&ws_dir).unwrap();
        let state_json = r#"{
            "version": 1,
            "project_root": "/some/path",
            "project_name": "test",
            "tools": {}
        }"#;
        std::fs::write(ws_dir.join("state.json"), state_json).unwrap();

        let state = WorkspaceState::load(temp_dir.path()).unwrap();
        assert!(
            state.wstemplate_entries.is_empty(),
            "missing wstemplate_entries field must default to empty Vec"
        );
        assert!(
            !state.completion_hint_shown,
            "missing completion_hint_shown field must default to false"
        );
    }

    #[test]
    fn test_wstemplate_entry_returns_configured_entry() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();
        assert!(state.wstemplate_entry().is_none());

        state.set_wstemplate_entry(WstemplateEntry {
            alias: "my_alias".to_string(),
            root: PathBuf::from("/scan/root"),
        });
        assert_eq!(state.wstemplate_entry().unwrap().alias, "my_alias");
    }

    #[test]
    fn test_set_wstemplate_entry_replaces_not_appends() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        state.set_wstemplate_entry(WstemplateEntry {
            alias: "first".to_string(),
            root: PathBuf::from("/scan/root"),
        });
        state.set_wstemplate_entry(WstemplateEntry {
            alias: "second".to_string(),
            root: PathBuf::from("/scan/root"),
        });

        assert_eq!(state.wstemplate_entries.len(), 1);
        assert_eq!(state.wstemplate_entry().unwrap().alias, "second");
    }

    #[test]
    fn test_clear_wstemplate_entry() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        state.set_wstemplate_entry(WstemplateEntry {
            alias: "test".to_string(),
            root: PathBuf::from("/root"),
        });
        assert!(state.wstemplate_entry().is_some());

        state.clear_wstemplate_entry();
        assert!(state.wstemplate_entry().is_none());
        assert!(state.wstemplate_entries.is_empty());
    }

    #[test]
    fn test_effective_wstemplate_entry_defaults_to_project_root_and_alias() {
        let temp_dir = TempDir::new().unwrap();
        let state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        let effective = state.effective_wstemplate_entry();
        assert_eq!(effective.root, temp_dir.path());
        assert_eq!(
            effective.alias,
            crate::state::wstemplate::WstemplateEngine::derive_alias(temp_dir.path())
        );
    }

    #[test]
    fn test_effective_wstemplate_entry_prefers_explicit_entry() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();
        let explicit = WstemplateEntry {
            alias: "wsb".to_string(),
            root: temp_dir.path().parent().unwrap().to_path_buf(),
        };
        state.set_wstemplate_entry(explicit.clone());

        assert_eq!(state.effective_wstemplate_entry(), explicit);
    }

    #[test]
    fn test_load_fails_hard_on_multi_entry() {
        let temp_dir = TempDir::new().unwrap();
        let ws_dir = temp_dir.path().join(".wsb");
        fs::create_dir_all(&ws_dir).unwrap();

        let state_json = serde_json::json!({
            "version": 1,
            "project_root": temp_dir.path().to_str().unwrap(),
            "project_name": "test",
            "tools": {},
            "wstemplate_entries": [
                {"alias": "self_alias", "root": "/scan/root"},
                {"alias": "other_proj", "root": "/some/other"},
                {"alias": "third_proj", "root": "/yet/another"}
            ]
        });
        fs::write(
            ws_dir.join("state.json"),
            serde_json::to_string_pretty(&state_json).unwrap(),
        )
        .unwrap();

        let err = WorkspaceState::load(temp_dir.path()).unwrap_err();
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("3 wstemplate entries"),
            "error must report the count, got: {}",
            msg
        );
        assert!(
            msg.contains("expected at most 1"),
            "error must explain the constraint, got: {}",
            msg
        );
    }

    #[test]
    fn test_completion_hint_shown_persists() {
        let temp_dir = TempDir::new().unwrap();
        let mut state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();
        assert!(!state.completion_hint_shown);

        state.completion_hint_shown = true;
        state.save(temp_dir.path()).unwrap();

        let loaded = WorkspaceState::load(temp_dir.path()).unwrap();
        assert!(
            loaded.completion_hint_shown,
            "completion_hint_shown must persist through save/load"
        );
    }

    #[test]
    fn test_initialize_uses_directory_name_by_default() {
        let temp_dir = TempDir::new().unwrap();
        let named_dir = temp_dir.path().join("capdag-js");
        fs::create_dir_all(&named_dir).unwrap();

        let state = WorkspaceState::initialize(&named_dir, None).unwrap();
        assert_eq!(state.project_name.as_deref(), Some("capdag-js"));
    }

    #[test]
    fn test_initialize_uses_explicit_name_over_directory() {
        let temp_dir = TempDir::new().unwrap();
        let named_dir = temp_dir.path().join("capdag-js");
        fs::create_dir_all(&named_dir).unwrap();

        let state = WorkspaceState::initialize(&named_dir, Some("my-project")).unwrap();
        assert_eq!(state.project_name.as_deref(), Some("my-project"));
    }

    #[test]
    fn test_initialize_ignores_package_file_names() {
        let temp_dir = TempDir::new().unwrap();
        let named_dir = temp_dir.path().join("capdag-js");
        fs::create_dir_all(&named_dir).unwrap();

        // Even with a package.json that has a different name, the directory name wins
        fs::write(
            named_dir.join("package.json"),
            r#"{ "name": "capdag", "version": "1.0.0" }"#,
        )
        .unwrap();

        let state = WorkspaceState::initialize(&named_dir, None).unwrap();
        assert_eq!(
            state.project_name.as_deref(),
            Some("capdag-js"),
            "project_name must come from the directory, not package.json"
        );
    }

    #[test]
    fn test_tool_directory_paths() {
        let temp_dir = TempDir::new().unwrap();
        let state = WorkspaceState::initialize(temp_dir.path(), None).unwrap();

        assert_eq!(state.workspace_dir(), temp_dir.path().join(".wsb"));
        assert_eq!(
            state.tool_dir("state"),
            temp_dir.path().join(".wsb").join("state")
        );
    }
}