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
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GitCheckoutKind {
    NotRepository,
    MainWorktree,
    LinkedWorktree,
    Submodule,
    Bare,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorktreeIsolationMode {
    NoGitRepository,
    MainWorktree,
    LinkedWorktree,
    Submodule,
    BareRepository,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorktreeCreationDecision {
    Blocked,
    CreateGitWorktree,
    ReuseCurrentWorktree,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeMetadata {
    pub kind: GitCheckoutKind,
    pub input_root: PathBuf,
    pub worktree_root: Option<PathBuf>,
    pub git_dir: Option<PathBuf>,
    pub common_dir: Option<PathBuf>,
    pub superproject_root: Option<PathBuf>,
    pub branch: Option<String>,
    pub detached: bool,
    pub head_sha: Option<String>,
    pub remote: Option<String>,
    pub is_dirty: Option<bool>,
    pub ahead: Option<u32>,
    pub behind: Option<u32>,
    pub detection_error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeIdentity {
    pub kind: GitCheckoutKind,
    pub input_root: PathBuf,
    pub worktree_root: Option<PathBuf>,
    pub git_dir: Option<PathBuf>,
    pub common_dir: Option<PathBuf>,
    pub superproject_root: Option<PathBuf>,
    pub branch: Option<String>,
    pub remote: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeIsolationPlan {
    pub schema: String,
    pub metadata: WorktreeMetadata,
    pub mode: WorktreeIsolationMode,
    pub creation_decision: WorktreeCreationDecision,
    pub can_create_git_worktree: bool,
    pub native_isolation_detected: bool,
    pub execution_root: Option<PathBuf>,
    pub blockers: Vec<String>,
    pub warnings: Vec<String>,
}

impl WorktreeMetadata {
    pub fn is_not_repository(&self) -> bool {
        self.kind == GitCheckoutKind::NotRepository
    }

    pub fn identity(&self) -> WorktreeIdentity {
        WorktreeIdentity::from_metadata(self)
    }

    pub fn has_same_identity(&self, other: &Self) -> bool {
        self.identity() == other.identity()
    }
}

impl WorktreeIdentity {
    pub fn from_metadata(metadata: &WorktreeMetadata) -> Self {
        let input_root = metadata
            .worktree_root
            .clone()
            .unwrap_or_else(|| metadata.input_root.clone());
        Self {
            kind: metadata.kind,
            input_root,
            worktree_root: metadata.worktree_root.clone(),
            git_dir: metadata.git_dir.clone(),
            common_dir: metadata.common_dir.clone(),
            superproject_root: metadata.superproject_root.clone(),
            branch: metadata.branch.clone(),
            remote: metadata.remote.clone(),
        }
    }
}

impl WorktreeIsolationPlan {
    pub fn from_metadata(metadata: WorktreeMetadata) -> Self {
        let mut blockers = Vec::new();
        let mut warnings = Vec::new();

        let (mode, creation_decision, can_create_git_worktree, native_isolation_detected) =
            match metadata.kind {
                GitCheckoutKind::NotRepository => {
                    blockers.push(
                        "path is not a Git repository; git worktree creation is blocked"
                            .to_string(),
                    );
                    if let Some(error) = &metadata.detection_error {
                        blockers.push(error.clone());
                    }
                    (
                        WorktreeIsolationMode::NoGitRepository,
                        WorktreeCreationDecision::Blocked,
                        false,
                        false,
                    )
                }
                GitCheckoutKind::Bare => {
                    blockers.push(
                        "bare repository has no working tree; provide an explicit checkout target before isolation"
                            .to_string(),
                    );
                    (
                        WorktreeIsolationMode::BareRepository,
                        WorktreeCreationDecision::Blocked,
                        false,
                        false,
                    )
                }
                GitCheckoutKind::LinkedWorktree => {
                    if metadata.is_dirty == Some(true) {
                        warnings.push(
                            "linked worktree has local changes; confirm ownership before reuse"
                                .to_string(),
                        );
                    }
                    if metadata.detached {
                        warnings.push(
                            "linked worktree is detached; preserve external orchestration metadata"
                                .to_string(),
                        );
                    }
                    (
                        WorktreeIsolationMode::LinkedWorktree,
                        WorktreeCreationDecision::ReuseCurrentWorktree,
                        false,
                        true,
                    )
                }
                GitCheckoutKind::Submodule => {
                    warnings.push(
                        "path is a Git submodule; reuse current checkout unless the superproject owns orchestration"
                            .to_string(),
                    );
                    if metadata.is_dirty == Some(true) {
                        warnings.push(
                            "submodule has local changes; confirm ownership before reuse"
                                .to_string(),
                        );
                    }
                    (
                        WorktreeIsolationMode::Submodule,
                        WorktreeCreationDecision::ReuseCurrentWorktree,
                        false,
                        true,
                    )
                }
                GitCheckoutKind::MainWorktree => {
                    if metadata.is_dirty == Some(true) {
                        blockers.push(
                            "main worktree has local changes; commit, stash, or claim an existing isolated worktree before creating isolation"
                                .to_string(),
                        );
                    }
                    if metadata.detached {
                        blockers.push(
                            "main worktree must be on a branch with a resolved HEAD before creating a git worktree"
                                .to_string(),
                        );
                    }
                    if metadata.head_sha.is_none() {
                        blockers.push(
                            "main worktree must have a branch with a resolved HEAD before creating a git worktree"
                                .to_string(),
                        );
                    }
                    let can_create = blockers.is_empty();
                    (
                        WorktreeIsolationMode::MainWorktree,
                        if can_create {
                            WorktreeCreationDecision::CreateGitWorktree
                        } else {
                            WorktreeCreationDecision::Blocked
                        },
                        can_create,
                        false,
                    )
                }
            };

        let execution_root = match mode {
            WorktreeIsolationMode::NoGitRepository | WorktreeIsolationMode::BareRepository => None,
            _ => metadata.worktree_root.clone(),
        };

        Self {
            schema: "driven.worktree_isolation_plan.v1".to_string(),
            metadata,
            mode,
            creation_decision,
            can_create_git_worktree,
            native_isolation_detected,
            execution_root,
            blockers,
            warnings,
        }
    }
}

pub fn plan_worktree_isolation(root: &Path) -> WorktreeIsolationPlan {
    WorktreeIsolationPlan::from_metadata(detect_worktree_metadata(root))
}

pub fn detect_worktree_metadata(root: &Path) -> WorktreeMetadata {
    let input_root = normalize_worktree_root(root);
    let root = input_root.as_path();
    let worktree_root = match git(root, &["rev-parse", "--show-toplevel"]) {
        Ok(value) => PathBuf::from(value),
        Err(error) => {
            if git(root, &["rev-parse", "--is-bare-repository"])
                .map(|value| value == "true")
                .unwrap_or(false)
            {
                return bare_metadata(root, input_root.clone());
            }

            return WorktreeMetadata {
                kind: GitCheckoutKind::NotRepository,
                input_root,
                worktree_root: None,
                git_dir: None,
                common_dir: None,
                superproject_root: None,
                branch: None,
                detached: false,
                head_sha: None,
                remote: None,
                is_dirty: None,
                ahead: None,
                behind: None,
                detection_error: Some(error),
            };
        }
    };

    let bare = git(root, &["rev-parse", "--is-bare-repository"])
        .map(|value| value == "true")
        .unwrap_or(false);
    let git_dir = git(root, &["rev-parse", "--git-dir"])
        .ok()
        .map(|path| normalize_git_path(root, path));
    let common_dir = git(root, &["rev-parse", "--git-common-dir"])
        .ok()
        .map(|path| normalize_git_path(root, path));
    let superproject_root = git(root, &["rev-parse", "--show-superproject-working-tree"])
        .ok()
        .filter(|value| !value.is_empty())
        .map(PathBuf::from);

    let kind = if bare {
        GitCheckoutKind::Bare
    } else if superproject_root.is_some() {
        GitCheckoutKind::Submodule
    } else if git_dir.is_some() && common_dir.is_some() && git_dir != common_dir {
        GitCheckoutKind::LinkedWorktree
    } else {
        GitCheckoutKind::MainWorktree
    };

    let branch = git(root, &["rev-parse", "--abbrev-ref", "HEAD"])
        .ok()
        .filter(|value| value != "HEAD");
    let detached = branch.is_none();
    let head_sha = git(root, &["rev-parse", "HEAD"]).ok();
    let remote = git(root, &["config", "--get", "remote.origin.url"]).ok();
    let is_dirty = git(root, &["status", "--porcelain"])
        .ok()
        .map(|value| !value.trim().is_empty());
    let (ahead, behind) = ahead_behind(root);

    WorktreeMetadata {
        kind,
        input_root,
        worktree_root: Some(worktree_root),
        git_dir,
        common_dir,
        superproject_root,
        branch,
        detached,
        head_sha,
        remote,
        is_dirty,
        ahead,
        behind,
        detection_error: None,
    }
}

fn bare_metadata(root: &Path, input_root: PathBuf) -> WorktreeMetadata {
    let git_dir = git(root, &["rev-parse", "--git-dir"])
        .ok()
        .map(|path| normalize_git_path(root, path));
    let common_dir = git(root, &["rev-parse", "--git-common-dir"])
        .ok()
        .map(|path| normalize_git_path(root, path));
    let branch = git(root, &["rev-parse", "--abbrev-ref", "HEAD"])
        .ok()
        .filter(|value| value != "HEAD");

    WorktreeMetadata {
        kind: GitCheckoutKind::Bare,
        input_root,
        worktree_root: None,
        git_dir,
        common_dir,
        superproject_root: None,
        branch: branch.clone(),
        detached: branch.is_none(),
        head_sha: git(root, &["rev-parse", "HEAD"]).ok(),
        remote: git(root, &["config", "--get", "remote.origin.url"]).ok(),
        is_dirty: None,
        ahead: None,
        behind: None,
        detection_error: None,
    }
}

pub(crate) fn normalize_worktree_root(root: &Path) -> PathBuf {
    if let Ok(canonical) = root.canonicalize() {
        return normalize_platform_path(canonical);
    }
    if root.is_absolute() {
        return normalize_platform_path(root.to_path_buf());
    }
    let absolute = std::env::current_dir()
        .map(|cwd| cwd.join(root))
        .unwrap_or_else(|_| root.to_path_buf());
    normalize_platform_path(absolute)
}

#[cfg(windows)]
fn normalize_platform_path(path: PathBuf) -> PathBuf {
    let path_text = path.to_string_lossy();
    if let Some(rest) = path_text.strip_prefix(r"\\?\UNC\") {
        return PathBuf::from(format!(r"\\{}", rest));
    }
    if let Some(rest) = path_text.strip_prefix(r"\\?\") {
        return PathBuf::from(rest);
    }
    path
}

#[cfg(not(windows))]
fn normalize_platform_path(path: PathBuf) -> PathBuf {
    path
}

fn normalize_git_path(root: &Path, path: String) -> PathBuf {
    let path = PathBuf::from(path);
    if path.is_absolute() {
        path
    } else {
        root.join(path)
    }
}

fn ahead_behind(root: &Path) -> (Option<u32>, Option<u32>) {
    let output = match git(
        root,
        &["rev-list", "--left-right", "--count", "@{upstream}...HEAD"],
    ) {
        Ok(output) => output,
        Err(_) => return (None, None),
    };

    let mut parts = output.split_whitespace();
    let behind = parts.next().and_then(|value| value.parse().ok());
    let ahead = parts.next().and_then(|value| value.parse().ok());
    (ahead, behind)
}

fn git(root: &Path, args: &[&str]) -> Result<String, String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(root)
        .output()
        .map_err(|e| format!("failed to run git: {}", e))?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        if stderr.is_empty() {
            Err(format!("git {:?} exited with {}", args, output.status))
        } else {
            Err(stderr)
        }
    }
}