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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! CLI helpers for DX lane/pass strategy commands.

use crate::Result;
use crate::strategy::artifacts::read_receipt_artifact;
use crate::strategy::{
    LaneClaim, LaneId, LanePassAssignment, LanePassConfig, LanePassStore, OutcomeProof, PassNumber,
    ProofReceipt, ReceiptFormat, WorkerId, WorktreeIsolationPlan, WorktreeMetadata,
    detect_worktree_metadata,
};
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

pub struct StrategyCommand;

#[derive(Debug, Clone, Default)]
pub struct StrategyStateOptions {
    pub cycle_lanes: bool,
    pub project_root: Option<PathBuf>,
    pub strict_isolation: bool,
    pub handoff_required_for_next: bool,
}

impl StrategyStateOptions {
    pub fn with_lane_cycling(mut self, cycle_lanes: bool) -> Self {
        self.cycle_lanes = cycle_lanes;
        self
    }

    pub fn with_project_root(mut self, project_root: impl Into<PathBuf>) -> Self {
        self.project_root = Some(project_root.into());
        self
    }

    pub fn with_strict_isolation(mut self, strict_isolation: bool) -> Self {
        self.strict_isolation = strict_isolation;
        self
    }

    pub fn with_handoff_required_for_next(mut self, required: bool) -> Self {
        self.handoff_required_for_next = required;
        self
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct StrategyClaimOutput {
    pub claim: LaneClaim,
    pub receipt_id: String,
    pub handoff: crate::strategy::NextPassHandoff,
    pub worktree: WorktreeMetadata,
    pub worktree_plan: WorktreeIsolationPlan,
    pub recommended_small_commands: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct StrategyWorktreeInspection {
    pub worktree: WorktreeMetadata,
    pub worktree_plan: WorktreeIsolationPlan,
}

impl StrategyCommand {
    pub fn inspect_worktree(path: &Path, json: bool) -> Result<String> {
        let metadata = detect_worktree_metadata(path);
        let plan = WorktreeIsolationPlan::from_metadata(metadata.clone());
        let inspection = StrategyWorktreeInspection {
            worktree: metadata,
            worktree_plan: plan,
        };
        if json {
            return serde_json::to_string_pretty(&inspection)
                .map(|mut output| {
                    output.push('\n');
                    output
                })
                .map_err(|e| crate::DrivenError::Format(format!("failed to render JSON: {}", e)));
        }

        Ok(format!(
            "Worktree kind: {:?}\nRoot: {}\nBranch: {}\nDirty: {}\nDecision: {:?}\n",
            inspection.worktree.kind,
            inspection
                .worktree
                .worktree_root
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_else(|| "not a repository".to_string()),
            inspection
                .worktree
                .branch
                .as_deref()
                .unwrap_or("detached-or-none"),
            inspection
                .worktree
                .is_dirty
                .map(|dirty| dirty.to_string())
                .unwrap_or_else(|| "unknown".to_string()),
            inspection.worktree_plan.creation_decision
        ))
    }

    pub fn claim(
        project_root: &Path,
        lane: u8,
        pass: u32,
        worker_id: &str,
        scope: &str,
        next_action: &str,
        json: bool,
    ) -> Result<String> {
        let worker = WorkerId::new(worker_id)?;
        let claim = LaneClaim::new(LaneId::new(lane)?, PassNumber::new(pass)?, worker, scope);
        let receipt = ProofReceipt::new(claim.clone(), "lane/pass claim modeled").with_outcome(
            OutcomeProof::partial(
                "claim created; run verification commands before closing the pass",
            ),
        );
        let receipt_id = receipt.receipt_id()?;
        let handoff = claim.next_pass_handoff(receipt.clone(), next_action)?;

        let worktree = detect_worktree_metadata(project_root);
        let worktree_plan = WorktreeIsolationPlan::from_metadata(worktree.clone());
        let output = StrategyClaimOutput {
            claim,
            receipt_id,
            handoff,
            worktree,
            worktree_plan,
            recommended_small_commands: vec![
                "git status --short --branch".to_string(),
                "rg -n \"(<{7}|>{7}|={7})\"".to_string(),
                "cargo fmt --check".to_string(),
            ],
        };

        if json {
            serde_json::to_string_pretty(&output)
                .map(|mut output| {
                    output.push('\n');
                    output
                })
                .map_err(|e| crate::DrivenError::Format(format!("failed to render JSON: {}", e)))
        } else {
            render_claim_markdown(&output, &receipt)
        }
    }

    pub fn peek_state(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        json: bool,
    ) -> Result<String> {
        Self::peek_state_with_options(
            state_dir,
            scope,
            max_lanes,
            max_passes,
            json,
            StrategyStateOptions::default(),
        )
    }

    pub fn peek_state_with_options(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        json: bool,
        options: StrategyStateOptions,
    ) -> Result<String> {
        let store = LanePassStore::new(
            state_config(state_dir, scope, &options)
                .with_max_lanes(max_lanes)
                .with_max_passes(max_passes),
        )?;
        render_assignment(&store.peek_next_claim()?, json)
    }

    pub fn claim_state(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        json: bool,
    ) -> Result<String> {
        Self::claim_state_with_options(
            state_dir,
            scope,
            max_lanes,
            max_passes,
            worker_id,
            json,
            StrategyStateOptions::default(),
        )
    }

    pub fn claim_state_with_options(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        json: bool,
        options: StrategyStateOptions,
    ) -> Result<String> {
        let config = state_config(state_dir, scope, &options)
            .with_max_lanes(max_lanes)
            .with_max_passes(max_passes);
        enforce_strict_isolation(&config, &options)?;
        let store = LanePassStore::new(config)?;
        render_assignment(&store.claim(WorkerId::new(worker_id)?)?, json)
    }

    pub fn next_state(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        json: bool,
    ) -> Result<String> {
        Self::next_state_with_options(
            state_dir,
            scope,
            max_lanes,
            max_passes,
            worker_id,
            json,
            StrategyStateOptions::default(),
        )
    }

    pub fn next_state_with_options(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        json: bool,
        options: StrategyStateOptions,
    ) -> Result<String> {
        let config = state_config(state_dir, scope, &options)
            .with_max_lanes(max_lanes)
            .with_max_passes(max_passes);
        enforce_strict_isolation(&config, &options)?;
        let store = LanePassStore::new(config)?;
        render_assignment(&store.next_pass(&WorkerId::new(worker_id)?)?, json)
    }

    pub fn next_state_with_handoff_options(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        receipt_path: &Path,
        next_action: &str,
        json: bool,
        options: StrategyStateOptions,
    ) -> Result<String> {
        let config = state_config(state_dir, scope, &options)
            .with_max_lanes(max_lanes)
            .with_max_passes(max_passes);
        enforce_strict_isolation(&config, &options)?;
        let store = LanePassStore::new(config)?;
        let worker = WorkerId::new(worker_id)?;
        let receipt = read_receipt_artifact(receipt_path)?;
        render_assignment(
            &store.next_pass_with_handoff(&worker, &receipt, next_action)?,
            json,
        )
    }

    pub fn release_state(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        json: bool,
    ) -> Result<String> {
        Self::release_state_with_options(
            state_dir,
            scope,
            max_lanes,
            max_passes,
            worker_id,
            json,
            StrategyStateOptions::default(),
        )
    }

    pub fn release_state_with_options(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        json: bool,
        options: StrategyStateOptions,
    ) -> Result<String> {
        let config = state_config(state_dir, scope, &options)
            .with_max_lanes(max_lanes)
            .with_max_passes(max_passes);
        enforce_strict_isolation(&config, &options)?;
        let store = LanePassStore::new(config)?;
        render_assignment(&store.release_lane(&WorkerId::new(worker_id)?)?, json)
    }

    pub fn complete_state(
        _state_dir: PathBuf,
        _scope: &str,
        _max_lanes: u8,
        _max_passes: u32,
        _worker_id: &str,
        _json: bool,
    ) -> Result<String> {
        Err(crate::DrivenError::Validation(
            "completion requires a canonical proof receipt; use complete_state_with_receipt"
                .to_string(),
        ))
    }

    pub fn complete_state_with_receipt(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        receipt_path: &Path,
        json: bool,
    ) -> Result<String> {
        Self::complete_state_with_receipt_options(
            state_dir,
            scope,
            max_lanes,
            max_passes,
            worker_id,
            receipt_path,
            json,
            StrategyStateOptions::default(),
        )
    }

    pub fn complete_state_with_receipt_options(
        state_dir: PathBuf,
        scope: &str,
        max_lanes: u8,
        max_passes: u32,
        worker_id: &str,
        receipt_path: &Path,
        json: bool,
        options: StrategyStateOptions,
    ) -> Result<String> {
        let config = state_config(state_dir, scope, &options)
            .with_max_lanes(max_lanes)
            .with_max_passes(max_passes);
        enforce_strict_isolation(&config, &options)?;
        let store = LanePassStore::new(config)?;
        let worker = WorkerId::new(worker_id)?;
        let receipt = read_receipt_artifact(receipt_path)?;
        render_assignment(&store.complete_pass_with_receipt(&worker, &receipt)?, json)
    }
}

pub(super) fn render_receipt(receipt: &ProofReceipt, json: bool) -> Result<String> {
    if json {
        return receipt.render(ReceiptFormat::Json);
    }

    receipt.render(ReceiptFormat::Markdown)
}

fn render_claim_markdown(output: &StrategyClaimOutput, receipt: &ProofReceipt) -> Result<String> {
    let mut markdown = String::new();
    markdown.push_str("# DX Lane/Pass Claim\n\n");
    markdown.push_str(&format!("- Lane: {}\n", output.claim.lane));
    markdown.push_str(&format!("- Pass: {}\n", output.claim.pass));
    markdown.push_str(&format!("- Worker: {}\n", output.claim.worker_id));
    markdown.push_str(&format!(
        "- Scope: {}\n",
        escape_markdown_text(&output.claim.scope)
    ));
    markdown.push_str(&format!("- Next pass: {}\n", output.handoff.next_pass));
    markdown.push_str(&format!(
        "- Next action: {}\n",
        escape_markdown_text(&output.handoff.next_action)
    ));
    markdown.push_str(&format!("- Worktree kind: {:?}\n\n", output.worktree.kind));
    markdown.push_str(&format!(
        "- Worktree decision: {:?}\n",
        output.worktree_plan.creation_decision
    ));
    for blocker in &output.worktree_plan.blockers {
        markdown.push_str(&format!(
            "- Worktree blocker: {}\n",
            escape_markdown_text(blocker)
        ));
    }
    markdown.push('\n');
    markdown.push_str("## Small Commands First\n");
    for command in &output.recommended_small_commands {
        markdown.push_str(&format!("- `{}`\n", command));
    }
    markdown.push('\n');
    markdown.push_str(&receipt.render(ReceiptFormat::Markdown)?);
    Ok(markdown)
}

fn render_assignment(assignment: &LanePassAssignment, json: bool) -> Result<String> {
    if json {
        return serde_json::to_string_pretty(assignment)
            .map(|mut output| {
                output.push('\n');
                output
            })
            .map_err(|e| crate::DrivenError::Format(format!("failed to render JSON: {}", e)));
    }

    Ok(format!(
        "# DX Lane/Pass Assignment\n\n- Status: {:?}\n- Scope: {}\n- Lane: {}\n- Pass: {}\n- Worker: {}\n- Counter: {}\n- Claims: {}\n",
        assignment.status,
        escape_markdown_text(&assignment.scope),
        assignment.lane,
        assignment.pass,
        assignment.worker_id,
        assignment.paths.counter_path.display(),
        assignment.paths.claims_path.display()
    ))
}

pub(super) fn state_config(
    state_dir: PathBuf,
    scope: &str,
    options: &StrategyStateOptions,
) -> LanePassConfig {
    let config = LanePassConfig::new(state_dir, scope);
    let config = if let Some(project_root) = &options.project_root {
        config.with_project_root(project_root.clone())
    } else {
        match std::env::current_dir() {
            Ok(project_root) => config.with_project_root(project_root),
            Err(_) => config,
        }
    };
    config
        .with_lane_cycling(options.cycle_lanes)
        .with_handoff_required_for_next(options.handoff_required_for_next)
}

pub(super) fn enforce_strict_isolation(
    config: &LanePassConfig,
    options: &StrategyStateOptions,
) -> Result<()> {
    if !options.strict_isolation {
        return Ok(());
    }
    let project_root = match &config.project_root {
        Some(project_root) => project_root.clone(),
        None => std::env::current_dir().map_err(crate::DrivenError::Io)?,
    };
    let metadata = detect_worktree_metadata(&project_root);
    let plan = WorktreeIsolationPlan::from_metadata(metadata);
    if plan.native_isolation_detected && plan.blockers.is_empty() && plan.warnings.is_empty() {
        return Ok(());
    }
    Err(crate::DrivenError::Validation(format!(
        "strict isolation requires a clean isolated worktree; decision={:?}; blockers={}; warnings={}",
        plan.creation_decision,
        plan.blockers.join("; "),
        plan.warnings.join("; ")
    )))
}

pub(super) fn unix_seconds_now() -> Result<u64> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .map_err(|e| crate::DrivenError::Validation(format!("system time is before epoch: {}", e)))
}

pub(super) fn command_display(program: &str, args: &[String]) -> String {
    std::iter::once(program.to_string())
        .chain(args.iter().cloned())
        .map(|arg| display_command_arg(&arg))
        .collect::<Vec<_>>()
        .join(" ")
}

fn display_command_arg(arg: &str) -> String {
    if arg
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | '/' | '\\' | ':'))
    {
        return arg.to_string();
    }
    format!("{:?}", arg)
}

fn escape_markdown_text(value: &str) -> String {
    value
        .replace('\r', "")
        .replace('|', "\\|")
        .replace('\n', "<br>")
}

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

    #[test]
    fn claim_json_contains_lane_worker_and_next_action() {
        let temp = tempfile::tempdir().unwrap();
        let output = StrategyCommand::claim(
            temp.path(),
            2,
            1,
            "worker-cli",
            "cli strategy",
            "continue with receipts",
            true,
        )
        .unwrap();

        assert!(output.contains("\"lane\": 2"));
        assert!(output.contains("\"worker_id\": \"worker-cli\""));
        assert!(output.contains("continue with receipts"));
    }

    #[test]
    fn claim_state_json_preserves_lane_across_next_pass() {
        let temp = tempfile::tempdir().unwrap();
        let state_dir = temp.path().join("state");

        let claimed =
            StrategyCommand::claim_state(state_dir.clone(), "cli state", 30, 3, "worker-cli", true)
                .unwrap();
        let next =
            StrategyCommand::next_state(state_dir, "cli state", 30, 3, "worker-cli", true).unwrap();

        assert!(claimed.contains("\"lane\": 1"));
        assert!(claimed.contains("\"pass\": 1"));
        assert!(next.contains("\"lane\": 1"));
        assert!(next.contains("\"pass\": 2"));
    }
}