dx-driven 0.1.0

Professional AI-assisted development orchestrator with binary-first architecture
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
465
466
467
468
469
//! # Things 3 Integration
//!
//! Things 3 macOS URL scheme integration for task management.
//!
//! ## Usage
//!
//! ```rust,ignore
//! use driven::integrations::things::{ThingsClient, ThingsConfig};
//!
//! let config = ThingsConfig::from_file("~/.dx/config/things.sr")?;
//! let client = ThingsClient::new(&config)?;
//!
//! // Create a task
//! client.create_task("Buy groceries", Some("Milk, eggs, bread")).await?;
//!
//! // Create a project
//! client.create_project("Home Renovation", vec!["Paint walls", "Fix roof"]).await?;
//! ```

use crate::error::{DrivenError, Result};
use serde::{Deserialize, Serialize};

/// Things 3 configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThingsConfig {
    /// Whether Things integration is enabled
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Things auth token (for JSON API)
    pub auth_token: Option<String>,
    /// Default list/area
    pub default_list: Option<String>,
    /// Default tags
    #[serde(default)]
    pub default_tags: Vec<String>,
}

fn default_true() -> bool {
    true
}

impl Default for ThingsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            auth_token: None,
            default_list: None,
            default_tags: Vec::new(),
        }
    }
}

impl ThingsConfig {
    /// Load from .sr config file
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path.as_ref())
            .map_err(|e| DrivenError::Io(e))?;
        Self::parse_sr(&content)
    }

    fn parse_sr(_content: &str) -> Result<Self> {
        Ok(Self::default())
    }

    /// Resolve environment variables
    pub fn resolve_env_vars(&mut self) {
        if let Ok(token) = std::env::var("THINGS_AUTH_TOKEN") {
            self.auth_token = Some(token);
        }
    }
}

/// Things task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThingsTask {
    /// Task title
    pub title: String,
    /// Task notes
    pub notes: Option<String>,
    /// When (today, tonight, tomorrow, anytime, someday, or date string)
    pub when: Option<String>,
    /// Deadline date
    pub deadline: Option<String>,
    /// Tags
    #[serde(default)]
    pub tags: Vec<String>,
    /// Checklist items
    #[serde(default)]
    pub checklist_items: Vec<String>,
    /// List/Area ID
    pub list_id: Option<String>,
    /// Heading (within a project)
    pub heading: Option<String>,
    /// Completed
    pub completed: bool,
    /// Canceled
    pub canceled: bool,
}

impl Default for ThingsTask {
    fn default() -> Self {
        Self {
            title: String::new(),
            notes: None,
            when: None,
            deadline: None,
            tags: Vec::new(),
            checklist_items: Vec::new(),
            list_id: None,
            heading: None,
            completed: false,
            canceled: false,
        }
    }
}

/// Things project
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThingsProject {
    /// Project title
    pub title: String,
    /// Project notes
    pub notes: Option<String>,
    /// When (today, tonight, tomorrow, anytime, someday, or date string)
    pub when: Option<String>,
    /// Deadline date
    pub deadline: Option<String>,
    /// Tags
    #[serde(default)]
    pub tags: Vec<String>,
    /// Area ID
    pub area_id: Option<String>,
    /// Headings
    #[serde(default)]
    pub headings: Vec<String>,
    /// Tasks within the project
    #[serde(default)]
    pub tasks: Vec<ThingsTask>,
}

impl Default for ThingsProject {
    fn default() -> Self {
        Self {
            title: String::new(),
            notes: None,
            when: None,
            deadline: None,
            tags: Vec::new(),
            area_id: None,
            headings: Vec::new(),
            tasks: Vec::new(),
        }
    }
}

/// URL scheme result
#[derive(Debug, Clone)]
pub struct UrlSchemeResult {
    /// Generated URL
    pub url: String,
    /// Whether URL was opened
    pub opened: bool,
}

/// Things 3 client
pub struct ThingsClient {
    config: ThingsConfig,
}

impl ThingsClient {
    /// URL scheme prefix
    const URL_SCHEME: &'static str = "things:///";

    /// Create a new Things client
    pub fn new(config: &ThingsConfig) -> Result<Self> {
        let mut config = config.clone();
        config.resolve_env_vars();

        Ok(Self { config })
    }

    /// Check if client is configured
    pub fn is_configured(&self) -> bool {
        self.config.enabled
    }

    /// Create a task
    pub async fn create_task(&self, title: &str, notes: Option<&str>) -> Result<UrlSchemeResult> {
        let mut task = ThingsTask::default();
        task.title = title.to_string();
        task.notes = notes.map(String::from);
        task.tags = self.config.default_tags.clone();
        task.list_id = self.config.default_list.clone();

        self.add_task(&task).await
    }

    /// Create a task with full options
    pub async fn add_task(&self, task: &ThingsTask) -> Result<UrlSchemeResult> {
        let mut params = vec![format!("title={}", urlencoding::encode(&task.title))];

        if let Some(ref notes) = task.notes {
            params.push(format!("notes={}", urlencoding::encode(notes)));
        }
        if let Some(ref when) = task.when {
            params.push(format!("when={}", urlencoding::encode(when)));
        }
        if let Some(ref deadline) = task.deadline {
            params.push(format!("deadline={}", urlencoding::encode(deadline)));
        }
        if !task.tags.is_empty() {
            params.push(format!("tags={}", urlencoding::encode(&task.tags.join(","))));
        }
        if !task.checklist_items.is_empty() {
            params.push(format!(
                "checklist-items={}",
                urlencoding::encode(&task.checklist_items.join("\n"))
            ));
        }
        if let Some(ref list) = task.list_id {
            params.push(format!("list-id={}", urlencoding::encode(list)));
        }
        if let Some(ref heading) = task.heading {
            params.push(format!("heading={}", urlencoding::encode(heading)));
        }
        if task.completed {
            params.push("completed=true".to_string());
        }
        if task.canceled {
            params.push("canceled=true".to_string());
        }

        let url = format!("{}add?{}", Self::URL_SCHEME, params.join("&"));
        self.open_url(&url).await
    }

    /// Create a project
    pub async fn create_project(&self, title: &str, tasks: Vec<&str>) -> Result<UrlSchemeResult> {
        let mut project = ThingsProject::default();
        project.title = title.to_string();
        project.tasks = tasks
            .into_iter()
            .map(|t| {
                let mut task = ThingsTask::default();
                task.title = t.to_string();
                task
            })
            .collect();

        self.add_project(&project).await
    }

    /// Create a project with full options
    pub async fn add_project(&self, project: &ThingsProject) -> Result<UrlSchemeResult> {
        let mut params = vec![format!("title={}", urlencoding::encode(&project.title))];

        if let Some(ref notes) = project.notes {
            params.push(format!("notes={}", urlencoding::encode(notes)));
        }
        if let Some(ref when) = project.when {
            params.push(format!("when={}", urlencoding::encode(when)));
        }
        if let Some(ref deadline) = project.deadline {
            params.push(format!("deadline={}", urlencoding::encode(deadline)));
        }
        if !project.tags.is_empty() {
            params.push(format!("tags={}", urlencoding::encode(&project.tags.join(","))));
        }
        if let Some(ref area) = project.area_id {
            params.push(format!("area-id={}", urlencoding::encode(area)));
        }
        if !project.headings.is_empty() {
            params.push(format!(
                "headings={}",
                urlencoding::encode(&project.headings.join("\n"))
            ));
        }

        // Add tasks as to-dos parameter
        if !project.tasks.is_empty() {
            let todos: Vec<String> = project
                .tasks
                .iter()
                .map(|t| t.title.clone())
                .collect();
            params.push(format!("to-dos={}", urlencoding::encode(&todos.join("\n"))));
        }

        let url = format!("{}add-project?{}", Self::URL_SCHEME, params.join("&"));
        self.open_url(&url).await
    }

    /// Add to today
    pub async fn add_to_today(&self, title: &str, notes: Option<&str>) -> Result<UrlSchemeResult> {
        let mut task = ThingsTask::default();
        task.title = title.to_string();
        task.notes = notes.map(String::from);
        task.when = Some("today".to_string());

        self.add_task(&task).await
    }

    /// Add to tonight
    pub async fn add_to_tonight(&self, title: &str, notes: Option<&str>) -> Result<UrlSchemeResult> {
        let mut task = ThingsTask::default();
        task.title = title.to_string();
        task.notes = notes.map(String::from);
        task.when = Some("tonight".to_string());

        self.add_task(&task).await
    }

    /// Add to someday
    pub async fn add_to_someday(&self, title: &str, notes: Option<&str>) -> Result<UrlSchemeResult> {
        let mut task = ThingsTask::default();
        task.title = title.to_string();
        task.notes = notes.map(String::from);
        task.when = Some("someday".to_string());

        self.add_task(&task).await
    }

    /// Show Today view
    pub async fn show_today(&self) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id=today", Self::URL_SCHEME);
        self.open_url(&url).await
    }

    /// Show Inbox view
    pub async fn show_inbox(&self) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id=inbox", Self::URL_SCHEME);
        self.open_url(&url).await
    }

    /// Show Upcoming view
    pub async fn show_upcoming(&self) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id=upcoming", Self::URL_SCHEME);
        self.open_url(&url).await
    }

    /// Show Anytime view
    pub async fn show_anytime(&self) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id=anytime", Self::URL_SCHEME);
        self.open_url(&url).await
    }

    /// Show Someday view
    pub async fn show_someday(&self) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id=someday", Self::URL_SCHEME);
        self.open_url(&url).await
    }

    /// Show Logbook view
    pub async fn show_logbook(&self) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id=logbook", Self::URL_SCHEME);
        self.open_url(&url).await
    }

    /// Show a specific item by ID
    pub async fn show_item(&self, item_id: &str) -> Result<UrlSchemeResult> {
        let url = format!("{}show?id={}", Self::URL_SCHEME, urlencoding::encode(item_id));
        self.open_url(&url).await
    }

    /// Search for items
    pub async fn search(&self, query: &str) -> Result<UrlSchemeResult> {
        let url = format!("{}search?query={}", Self::URL_SCHEME, urlencoding::encode(query));
        self.open_url(&url).await
    }

    /// Update an existing item (via JSON)
    pub async fn update_item(&self, item_id: &str, updates: serde_json::Value) -> Result<UrlSchemeResult> {
        if self.config.auth_token.is_none() {
            return Err(DrivenError::Config("Auth token required for updates".into()));
        }

        let json_data = serde_json::json!([{
            "type": "to-do",
            "id": item_id,
            "attributes": updates
        }]);

        let encoded = urlencoding::encode(&json_data.to_string());
        let url = format!(
            "{}json?auth-token={}&data={}",
            Self::URL_SCHEME,
            self.config.auth_token.as_ref().unwrap(),
            encoded
        );

        self.open_url(&url).await
    }

    /// Add multiple items via JSON API
    pub async fn add_json(&self, items: serde_json::Value) -> Result<UrlSchemeResult> {
        let encoded = urlencoding::encode(&items.to_string());
        let mut url = format!("{}json?data={}", Self::URL_SCHEME, encoded);

        if let Some(ref token) = self.config.auth_token {
            url.push_str(&format!("&auth-token={}", token));
        }

        self.open_url(&url).await
    }

    /// Open a URL scheme URL
    async fn open_url(&self, url: &str) -> Result<UrlSchemeResult> {
        // On macOS, use `open` command
        #[cfg(target_os = "macos")]
        {
            use tokio::process::Command;

            let status = Command::new("open")
                .arg(url)
                .status()
                .await
                .map_err(|e| DrivenError::Process(format!("Failed to open URL: {}", e)))?;

            Ok(UrlSchemeResult {
                url: url.to_string(),
                opened: status.success(),
            })
        }

        // On other platforms, just return the URL
        #[cfg(not(target_os = "macos"))]
        {
            Ok(UrlSchemeResult {
                url: url.to_string(),
                opened: false,
            })
        }
    }
}

/// Build a Things URL for quick add
pub fn quick_add_url(title: &str) -> String {
    format!("things:///add?title={}", urlencoding::encode(title))
}

/// Build a Things URL for showing a list
pub fn show_list_url(list: &str) -> String {
    format!("things:///show?id={}", urlencoding::encode(list))
}

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

    #[test]
    fn test_default_config() {
        let config = ThingsConfig::default();
        assert!(config.enabled);
        assert!(config.default_tags.is_empty());
    }

    #[test]
    fn test_quick_add_url() {
        let url = quick_add_url("Buy milk");
        assert!(url.contains("things:///add"));
        assert!(url.contains("title=Buy%20milk"));
    }

    #[test]
    fn test_show_list_url() {
        let url = show_list_url("today");
        assert_eq!(url, "things:///show?id=today");
    }
}