argentor-builtins 1.4.7

50+ built-in skills (web search, crypto, file ops, security, data processing) for Argentor
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
//! File-system-based artifact backend for persistent storage.
//!
//! Stores artifacts as files on disk with sidecar JSON metadata.
//! Unlike [`InMemoryArtifactBackend`](super::InMemoryArtifactBackend), artifacts
//! survive process restarts and can be shared across runs.
//!
//! # Storage layout
//!
//! ```text
//! base_dir/
//!   artifacts/
//!     {key}/
//!       content.dat    -- the artifact content
//!       metadata.json  -- kind, stored_at, size
//!   index.json         -- list of all keys with metadata
//! ```

use crate::artifact_store::{ArtifactBackend, ArtifactEntry};
use argentor_core::ArgentorResult;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::sync::RwLock;

/// Metadata for a single stored artifact.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactMeta {
    /// Artifact key (same as the directory name).
    pub key: String,
    /// Kind of artifact (e.g. "code", "spec", "test").
    pub kind: String,
    /// Timestamp when the artifact was stored.
    pub stored_at: DateTime<Utc>,
    /// Size of the content in bytes.
    pub size_bytes: usize,
}

/// Serializable index that tracks all stored artifacts.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct ArtifactIndex {
    entries: Vec<ArtifactMeta>,
}

/// File-system-based artifact backend for persistent storage.
///
/// Stores each artifact in its own directory under `base_dir/artifacts/{key}/`,
/// with `content.dat` for the raw content and `metadata.json` for sidecar metadata.
/// A top-level `index.json` tracks all stored artifacts.
///
/// Concurrent access is protected by an async `RwLock` to prevent torn reads/writes.
pub struct FileArtifactBackend {
    base_dir: PathBuf,
    /// Lock to serialize mutations and prevent concurrent index corruption.
    lock: RwLock<()>,
}

impl FileArtifactBackend {
    /// Create a new `FileArtifactBackend` rooted at the given directory.
    ///
    /// The directory structure is created lazily when [`init`](Self::init) is called
    /// or on the first operation.
    pub fn new(base_dir: PathBuf) -> Self {
        Self {
            base_dir,
            lock: RwLock::new(()),
        }
    }

    /// Ensure the required directory structure exists.
    pub async fn init(&self) -> ArgentorResult<()> {
        let artifacts_dir = self.base_dir.join("artifacts");
        tokio::fs::create_dir_all(&artifacts_dir)
            .await
            .map_err(|e| {
                argentor_core::ArgentorError::Skill(format!(
                    "Failed to create artifacts directory: {e}"
                ))
            })?;

        let index_path = self.base_dir.join("index.json");
        if !index_path.exists() {
            let empty_index = ArtifactIndex::default();
            let json = serde_json::to_string_pretty(&empty_index).map_err(|e| {
                argentor_core::ArgentorError::Skill(format!("Failed to serialize index: {e}"))
            })?;
            tokio::fs::write(&index_path, json).await.map_err(|e| {
                argentor_core::ArgentorError::Skill(format!("Failed to write index.json: {e}"))
            })?;
        }

        Ok(())
    }

    /// Return the path to the artifacts sub-directory for a given key.
    fn artifact_dir(&self, key: &str) -> PathBuf {
        self.base_dir.join("artifacts").join(key)
    }

    /// Return the path to `index.json`.
    fn index_path(&self) -> PathBuf {
        self.base_dir.join("index.json")
    }

    /// Validate that a key is safe and does not attempt path traversal.
    fn validate_key(key: &str) -> ArgentorResult<()> {
        if key.is_empty() {
            return Err(argentor_core::ArgentorError::Skill(
                "Artifact key must not be empty".to_string(),
            ));
        }
        if key.contains("..") || key.contains('/') || key.contains('\\') {
            return Err(argentor_core::ArgentorError::Skill(format!(
                "Artifact key contains invalid characters (path traversal attempt): {key}"
            )));
        }
        Ok(())
    }

    /// Read the index from disk.
    async fn read_index(&self) -> ArgentorResult<ArtifactIndex> {
        let index_path = self.index_path();
        if !index_path.exists() {
            return Ok(ArtifactIndex::default());
        }
        let data = tokio::fs::read_to_string(&index_path).await.map_err(|e| {
            argentor_core::ArgentorError::Skill(format!("Failed to read index.json: {e}"))
        })?;
        let index: ArtifactIndex = serde_json::from_str(&data).map_err(|e| {
            argentor_core::ArgentorError::Skill(format!("Failed to parse index.json: {e}"))
        })?;
        Ok(index)
    }

    /// Write the index to disk.
    async fn write_index(&self, index: &ArtifactIndex) -> ArgentorResult<()> {
        let json = serde_json::to_string_pretty(index).map_err(|e| {
            argentor_core::ArgentorError::Skill(format!("Failed to serialize index: {e}"))
        })?;
        tokio::fs::write(self.index_path(), json)
            .await
            .map_err(|e| {
                argentor_core::ArgentorError::Skill(format!("Failed to write index.json: {e}"))
            })?;
        Ok(())
    }
}

#[async_trait]
impl ArtifactBackend for FileArtifactBackend {
    async fn store(&self, key: &str, content: &str, kind: &str) -> ArgentorResult<String> {
        Self::validate_key(key)?;

        let _guard = self.lock.write().await;

        // Ensure directories exist.
        self.init().await?;

        // Create artifact directory.
        let dir = self.artifact_dir(key);
        tokio::fs::create_dir_all(&dir).await.map_err(|e| {
            argentor_core::ArgentorError::Skill(format!(
                "Failed to create artifact directory for '{key}': {e}"
            ))
        })?;

        // Write content.
        tokio::fs::write(dir.join("content.dat"), content)
            .await
            .map_err(|e| {
                argentor_core::ArgentorError::Skill(format!(
                    "Failed to write content for '{key}': {e}"
                ))
            })?;

        // Write metadata.
        let meta = ArtifactMeta {
            key: key.to_string(),
            kind: kind.to_string(),
            stored_at: Utc::now(),
            size_bytes: content.len(),
        };
        let meta_json = serde_json::to_string_pretty(&meta).map_err(|e| {
            argentor_core::ArgentorError::Skill(format!("Failed to serialize metadata: {e}"))
        })?;
        tokio::fs::write(dir.join("metadata.json"), meta_json)
            .await
            .map_err(|e| {
                argentor_core::ArgentorError::Skill(format!(
                    "Failed to write metadata for '{key}': {e}"
                ))
            })?;

        // Update index.
        let mut index = self.read_index().await?;
        index.entries.retain(|e| e.key != key);
        index.entries.push(meta);
        self.write_index(&index).await?;

        Ok(key.to_string())
    }

    async fn retrieve(&self, key: &str) -> ArgentorResult<Option<String>> {
        Self::validate_key(key)?;

        let _guard = self.lock.read().await;

        let content_path = self.artifact_dir(key).join("content.dat");
        if !content_path.exists() {
            return Ok(None);
        }

        let content = tokio::fs::read_to_string(&content_path)
            .await
            .map_err(|e| {
                argentor_core::ArgentorError::Skill(format!(
                    "Failed to read content for '{key}': {e}"
                ))
            })?;

        Ok(Some(content))
    }

    async fn list(&self) -> ArgentorResult<Vec<ArtifactEntry>> {
        let _guard = self.lock.read().await;

        let index = self.read_index().await?;

        Ok(index
            .entries
            .iter()
            .map(|meta| ArtifactEntry {
                key: meta.key.clone(),
                kind: meta.kind.clone(),
                size: meta.size_bytes,
            })
            .collect())
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn make_backend() -> (TempDir, FileArtifactBackend) {
        let tmp = TempDir::new().unwrap();
        let backend = FileArtifactBackend::new(tmp.path().to_path_buf());
        (tmp, backend)
    }

    #[tokio::test]
    async fn test_init_creates_directory_structure() {
        let (tmp, backend) = make_backend();
        backend.init().await.unwrap();

        assert!(tmp.path().join("artifacts").is_dir());
        assert!(tmp.path().join("index.json").is_file());
    }

    #[tokio::test]
    async fn test_store_and_retrieve() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        backend
            .store("main.rs", "fn main() {}", "code")
            .await
            .unwrap();

        let content = backend.retrieve("main.rs").await.unwrap();
        assert_eq!(content, Some("fn main() {}".to_string()));
    }

    #[tokio::test]
    async fn test_retrieve_nonexistent_returns_none() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        let content = backend.retrieve("nonexistent").await.unwrap();
        assert!(content.is_none());
    }

    #[tokio::test]
    async fn test_list_returns_stored_artifacts() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        backend.store("a.rs", "code_a", "code").await.unwrap();
        backend.store("b.md", "spec_b", "spec").await.unwrap();

        let entries = backend.list().await.unwrap();
        assert_eq!(entries.len(), 2);

        let keys: Vec<&str> = entries.iter().map(|e| e.key.as_str()).collect();
        assert!(keys.contains(&"a.rs"));
        assert!(keys.contains(&"b.md"));
    }

    #[tokio::test]
    async fn test_store_overwrites_existing() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        backend.store("file", "v1", "code").await.unwrap();
        backend.store("file", "v2", "code").await.unwrap();

        let content = backend.retrieve("file").await.unwrap();
        assert_eq!(content, Some("v2".to_string()));

        // Index should contain only one entry for this key.
        let entries = backend.list().await.unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].size, 2); // "v2".len()
    }

    #[tokio::test]
    async fn test_path_traversal_rejected() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        let result = backend.store("../etc/passwd", "bad", "exploit").await;
        assert!(result.is_err());

        let result = backend.store("foo/bar", "bad", "exploit").await;
        assert!(result.is_err());

        let result = backend.store("foo\\bar", "bad", "exploit").await;
        assert!(result.is_err());

        let result = backend.retrieve("../../secret").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_empty_key_rejected() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        let result = backend.store("", "content", "code").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_metadata_file_written() {
        let (tmp, backend) = make_backend();
        backend.init().await.unwrap();

        backend
            .store("test-artifact", "hello world", "text")
            .await
            .unwrap();

        // Verify the sidecar metadata file exists and has correct content.
        let meta_path = tmp
            .path()
            .join("artifacts")
            .join("test-artifact")
            .join("metadata.json");
        assert!(meta_path.is_file());

        let meta_str = tokio::fs::read_to_string(&meta_path).await.unwrap();
        let meta: ArtifactMeta = serde_json::from_str(&meta_str).unwrap();

        assert_eq!(meta.key, "test-artifact");
        assert_eq!(meta.kind, "text");
        assert_eq!(meta.size_bytes, 11); // "hello world".len()
    }

    #[tokio::test]
    async fn test_list_empty_store() {
        let (_tmp, backend) = make_backend();
        backend.init().await.unwrap();

        let entries = backend.list().await.unwrap();
        assert!(entries.is_empty());
    }

    #[tokio::test]
    async fn test_store_without_explicit_init() {
        let (_tmp, backend) = make_backend();

        // store() should call init() internally, so this works without explicit init.
        backend.store("auto-init", "content", "code").await.unwrap();

        let content = backend.retrieve("auto-init").await.unwrap();
        assert_eq!(content, Some("content".to_string()));
    }

    #[tokio::test]
    async fn test_index_json_reflects_all_entries() {
        let (tmp, backend) = make_backend();
        backend.init().await.unwrap();

        backend.store("x", "data_x", "data").await.unwrap();
        backend.store("y", "data_yy", "data").await.unwrap();

        // Read index.json directly and verify.
        let index_str = tokio::fs::read_to_string(tmp.path().join("index.json"))
            .await
            .unwrap();
        let index: ArtifactIndex = serde_json::from_str(&index_str).unwrap();

        assert_eq!(index.entries.len(), 2);

        let x_entry = index.entries.iter().find(|e| e.key == "x").unwrap();
        assert_eq!(x_entry.size_bytes, 6); // "data_x".len()

        let y_entry = index.entries.iter().find(|e| e.key == "y").unwrap();
        assert_eq!(y_entry.size_bytes, 7); // "data_yy".len()
    }
}