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
//! # Driven
//!
//! Professional AI-assisted development orchestrator with binary-first architecture.
//!
//! Driven brings structure, consistency, and intelligence to AI-powered coding workflows
//! by combining template-driven approaches with methodical frameworks, reimagined in Rust
//! with DX's binary-first philosophy for unparalleled performance.
//!
//! ## Features
//!
//! - **Universal Rule Format**: One source of truth, convert to any editor
//! - **Binary-First Storage**: Using DX serializer principles for 70%+ size reduction
//! - **Context Intelligence**: Deep project analysis for AI guidance
//! - **Professional Templates**: Battle-tested patterns for AI agents
//! - **Zero-Parse Loading**: Instant rule loading with memory-mapped binaries
//! - **DX Binary Dawn**: SIMD scanning, XOR patching, Ed25519 signing
//!
//! ## Quick Start
//!
//! ```rust,ignore
//! use driven::{DrivenConfig, RuleSet};
//!
//! // Load existing rules
//! let rules = RuleSet::load(".cursorrules")?;
//!
//! // Convert to different formats
//! rules.emit_copilot(".github/copilot-instructions.md")?;
//! rules.emit_windsurf(".windsurfrules")?;
//!
//! // Or use binary format for maximum efficiency
//! rules.save_binary(".driven/rules.drv")?;
//! ```
//!
//! ## Architecture
//!
//! Driven is organized into several key modules:
//!
//! - [`format`]: Binary rule format (.drv) encoding/decoding
//! - [`parser`]: Universal parser for all editor rule formats
//! - [`emitter`]: Target format generators for each editor
//! - [`templates`]: Template system with built-in library
//! - [`context`]: AI context intelligence and project analysis
//! - [`sync`]: Multi-editor synchronization
//! - [`validation`]: Rule validation and linting
//!
//! ## DX Binary Dawn Modules
//!
//! - [`binary`]: DX ∞ infinity format, zero-copy schemas, SIMD tokenizer
//! - [`fusion`]: Pre-compiled templates, hot cache, speculative loading
//! - [`streaming`]: HTIP delivery, XOR patching, ETag negotiation
//! - [`security`]: Ed25519 signing, capability manifest, sandbox
//! - [`state`]: Dirty-bit tracking, shared rules, atomic sync

// Note: Some fields are for API completeness and future use

// Core modules
pub mod agents;
pub mod config_validation;
pub mod context;
pub mod dcp;
pub mod dx_integration;
pub mod emitter;
pub mod error;
pub mod format;
pub mod generator_integration;
pub mod hooks;
pub mod integration;
pub mod modules;
pub mod parser;
pub mod scale;
pub mod steering;
pub mod strategy;
pub mod sync;
pub mod sysinfo;
pub mod templates;
pub mod validation;
pub mod workflows;

// DX Binary Dawn modules
pub mod binary;
pub mod fusion;
pub mod security;
pub mod state;
pub mod streaming;

#[cfg(feature = "cli")]
pub mod cli;

// Re-export core types
pub use context::{ProjectAnalyzer, ProjectContext};
pub use emitter::Emitter;
pub use format::{DrvDecoder, DrvEncoder, DrvHeader, RuleCategory};
pub use parser::{ParsedRule, Parser, UnifiedRule};
pub use sync::SyncEngine;
pub use templates::{Template, TemplateRegistry};
pub use validation::{Linter, ValidationResult};

// Re-export DX Binary Dawn types
pub use binary::{
    Blake3Checksum, InfinityHeader, InfinityRule, MappedRule, SimdTokenizer, StringId, StringTable,
    StringTableBuilder,
};
pub use fusion::{BinaryCache, FusionModule, HotCache, SpeculativeLoader};
pub use security::{Capability, CapabilityManifest, Ed25519Signer, IntegrityGuard, Sandbox};
pub use state::{AtomicSync, DirtyBits, RuleSnapshot, SharedRules, SnapshotManager};
pub use streaming::{ChunkStreamer, ETagNegotiator, HtipDelivery, XorPatcher};

// Re-export DX integration
pub use dx_integration::DxSerializable;
pub use dx_integration::{
    DxDocumentable, DxMarkdownConfig, DxMarkdownFormat, rules_to_dx_markdown,
};
pub use dx_integration::{LegacyConverter, LegacyFormat, LegacySerializable};

// Re-export DCP integration
pub use dcp::{ConnectionState, DcpClient, DcpConfig, ToolDefinition};

// Re-export generator integration
pub use generator_integration::{
    DrivenTemplate, DrivenTemplateProvider, DrivenTemplateType, GenerateParams, GeneratedFile,
    GeneratorBridge, TemplateCategory, TemplateInfo,
};

// Re-export cross-crate integration
pub use integration::{
    BinaryFormatChecker, CrossCrateHeader, DrivenDcpBridge, DrivenTool, DrivenToolCategory,
    HookMessage, HookMessenger, SourceCrate, SpecScaffoldResult, SpecScaffolder,
    ValidationResult as IntegrationValidationResult,
};

// Re-export error handling
pub use error::{EnhancedError, EnhancedResult, ErrorContext};

// Re-export config validation
pub use config_validation::{
    ConfigValidator, ValidationError, ValidationReport, ValidationWarning, validate_config,
};

// Re-export hooks system
pub use hooks::{
    AgentHook, BuildEvent, GitOp, HookAction, HookCondition, HookContext, HookEngine,
    HookExecutionResult, HookTrigger, TestFilter, TestResult, TestStatus,
};

// Re-export steering system
pub use steering::{AgentContext, FileReference, SteeringEngine, SteeringInclusion, SteeringRule};

// Re-export strategy system
pub use strategy::{
    ClaimId, ClaimStatus, ClaimToken, CommandEvidence, CommandProof, CommandStatus, FileProof,
    GitCheckoutKind, LaneClaim, LaneId, LanePassAssignment, LanePassAssignmentStatus,
    LanePassConfig, LanePassStatePaths, LanePassStore, NextPassHandoff, OutcomeProof, PassNumber,
    PassOutcome, ProofReceipt, ReceiptFormat, SubagentDelegation, VerificationClass, WorkerId,
    WorkerIdentity, WorkerKind, WorktreeCreationDecision, WorktreeIsolationMode,
    WorktreeIsolationPlan, WorktreeMetadata, detect_worktree_metadata, plan_worktree_isolation,
};

// Re-export sysinfo system
pub use sysinfo::{
    BuildToolInfo, GitInfo, LanguageInfo, OsInfo, PackageManagerInfo, ProjectInfo, ProjectType,
    ShellInfo, SystemInfo, SystemInfoCache, SystemInfoProvider, TestFrameworkInfo,
};

// Re-export agents system
pub use agents::{Agent, AgentPersona, AgentRegistry, DelegationRequest, DelegationResult};

// Re-export workflows system
pub use workflows::{
    StepResult, Workflow, WorkflowBranch, WorkflowEngine, WorkflowPhase, WorkflowProgress,
    WorkflowSession, WorkflowStep,
};

// Re-export scale system
pub use scale::{
    ComplexityAnalyzer, DependencyAnalyzer, FileSizeAnalyzer, HistoryAnalyzer,
    ProjectContext as ScaleProjectContext, ProjectScale, ScaleAnalyzer, ScaleDetector,
    ScaleRecommendation, TeamSizeAnalyzer,
};

// Re-export modules system
pub use modules::{Module, ModuleDependency, ModuleManager, ModuleStatus};

/// Configuration for Driven
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct DrivenConfig {
    /// Version of the configuration format
    pub version: String,
    /// Default editor to target
    pub default_editor: Editor,
    /// Enabled editors for sync
    pub editors: EditorConfig,
    /// Template configuration
    pub templates: TemplateConfig,
    /// Sync settings
    pub sync: SyncConfig,
    /// Context analysis settings
    pub context: ContextConfig,
}

impl Default for DrivenConfig {
    fn default() -> Self {
        Self {
            version: "1.0".to_string(),
            default_editor: Editor::Cursor,
            editors: EditorConfig::default(),
            templates: TemplateConfig::default(),
            sync: SyncConfig::default(),
            context: ContextConfig::default(),
        }
    }
}

/// Supported AI code editors
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Editor {
    /// Cursor AI editor
    Cursor,
    /// GitHub Copilot in VS Code
    Copilot,
    /// Windsurf (Codeium)
    Windsurf,
    /// Claude Code (Anthropic)
    Claude,
    /// Aider CLI
    Aider,
    /// Cline extension
    Cline,
}

impl std::fmt::Display for Editor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.display_name())
    }
}

impl Editor {
    /// Get the default rule file path for this editor
    pub fn rule_path(&self) -> &'static str {
        match self {
            Editor::Cursor => ".cursorrules",
            Editor::Copilot => ".github/copilot-instructions.md",
            Editor::Windsurf => ".windsurfrules",
            Editor::Claude => ".claude/settings.json",
            Editor::Aider => ".aider.conf.yml",
            Editor::Cline => ".cline/settings.json",
        }
    }

    /// Get a human-readable name for this editor
    pub fn display_name(&self) -> &'static str {
        match self {
            Editor::Cursor => "Cursor",
            Editor::Copilot => "GitHub Copilot",
            Editor::Windsurf => "Windsurf",
            Editor::Claude => "Claude Code",
            Editor::Aider => "Aider",
            Editor::Cline => "Cline",
        }
    }
}

/// Editor enablement configuration
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct EditorConfig {
    pub cursor: bool,
    pub copilot: bool,
    pub windsurf: bool,
    pub claude: bool,
    pub aider: bool,
    pub cline: bool,
}

impl Default for EditorConfig {
    fn default() -> Self {
        Self {
            cursor: true,
            copilot: true,
            windsurf: false,
            claude: true,
            aider: false,
            cline: false,
        }
    }
}

/// Template configuration
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub struct TemplateConfig {
    /// Active persona templates
    pub personas: Vec<String>,
    /// Project type template
    pub project: Option<String>,
    /// Active standard templates
    pub standards: Vec<String>,
    /// Active workflow template
    pub workflow: Option<String>,
}

/// Synchronization configuration
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SyncConfig {
    /// Watch for file changes
    pub watch: bool,
    /// Automatically convert on change
    pub auto_convert: bool,
    /// Source of truth file
    pub source_of_truth: String,
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            watch: true,
            auto_convert: true,
            source_of_truth: ".driven/rules.drv".to_string(),
        }
    }
}

/// Context analysis configuration
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ContextConfig {
    /// Patterns to include in analysis
    pub include: Vec<String>,
    /// Patterns to exclude from analysis
    pub exclude: Vec<String>,
    /// Path to binary index
    pub index_path: String,
}

impl Default for ContextConfig {
    fn default() -> Self {
        Self {
            include: vec!["src/**".to_string(), "crates/**".to_string()],
            exclude: vec!["target/**".to_string(), "node_modules/**".to_string()],
            index_path: ".driven/index.drv".to_string(),
        }
    }
}

/// A complete rule set that can be converted between formats
#[derive(Debug, Clone, Default)]
pub struct RuleSet {
    /// The unified rules
    pub rules: Vec<UnifiedRule>,
    /// Source file path (if loaded from file)
    pub source: Option<std::path::PathBuf>,
}

impl RuleSet {
    /// Create an empty rule set
    pub fn new() -> Self {
        Self::default()
    }

    /// Load rules from any supported format
    pub fn load(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let path = path.as_ref();
        let parser = Parser::detect(path)?;
        let rules = parser.parse_file(path)?;
        Ok(Self {
            rules,
            source: Some(path.to_path_buf()),
        })
    }

    /// Load rules from binary format (.drv)
    pub fn load_binary(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let data = std::fs::read(path.as_ref())?;
        let decoder = DrvDecoder::new(&data)?;
        let rules = decoder.decode_all()?;
        Ok(Self {
            rules,
            source: Some(path.as_ref().to_path_buf()),
        })
    }

    /// Save rules to binary format (.drv)
    pub fn save_binary(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        let encoder = DrvEncoder::new();
        let data = encoder.encode(&self.rules)?;
        std::fs::write(path, data)?;
        Ok(())
    }

    /// Emit rules to a specific editor format
    pub fn emit(&self, editor: Editor, path: impl AsRef<std::path::Path>) -> Result<()> {
        let emitter = Emitter::for_editor(editor);
        emitter.emit(&self.rules, path)?;
        Ok(())
    }

    /// Emit rules to Cursor format
    pub fn emit_cursor(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        self.emit(Editor::Cursor, path)
    }

    /// Emit rules to Copilot format
    pub fn emit_copilot(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        self.emit(Editor::Copilot, path)
    }

    /// Emit rules to Windsurf format
    pub fn emit_windsurf(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        self.emit(Editor::Windsurf, path)
    }

    /// Get the number of rules
    pub fn len(&self) -> usize {
        self.rules.len()
    }

    /// Check if the rule set is empty
    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }

    /// Get rules as unified format
    pub fn as_unified(&self) -> Vec<UnifiedRule> {
        self.rules.clone()
    }
}

/// Main error type for Driven
#[derive(Debug, thiserror::Error)]
pub enum DrivenError {
    #[error("IO error: {0}")]
    Io(std::io::Error),

    #[error("Parse error: {0}")]
    Parse(String),

    #[error("Format error: {0}")]
    Format(String),

    #[error("Invalid binary format: {0}")]
    InvalidBinary(String),

    #[error("Template error: {0}")]
    Template(String),

    #[error("Template not found: {0}")]
    TemplateNotFound(String),

    #[error("Validation error: {0}")]
    Validation(String),

    #[error("Sync error: {0}")]
    Sync(String),

    #[error("Config error: {0}")]
    Config(String),

    #[error("Security error: {0}")]
    Security(String),

    #[error("Context error: {0}")]
    Context(String),

    #[error("CLI error: {0}")]
    Cli(String),

    #[error("Unsupported format: {0}")]
    UnsupportedFormat(String),
}

/// Result type alias for Driven operations
pub type Result<T> = std::result::Result<T, DrivenError>;

impl From<std::io::Error> for DrivenError {
    fn from(err: std::io::Error) -> Self {
        DrivenError::Io(err)
    }
}

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

    #[test]
    fn test_default_config() {
        let config = DrivenConfig::default();
        assert_eq!(config.version, "1.0");
        assert_eq!(config.default_editor, Editor::Cursor);
        assert!(config.editors.cursor);
        assert!(config.editors.copilot);
    }

    #[test]
    fn test_editor_paths() {
        assert_eq!(Editor::Cursor.rule_path(), ".cursorrules");
        assert_eq!(
            Editor::Copilot.rule_path(),
            ".github/copilot-instructions.md"
        );
        assert_eq!(Editor::Windsurf.rule_path(), ".windsurfrules");
    }

    #[test]
    fn test_empty_ruleset() {
        let rules = RuleSet::new();
        assert!(rules.rules.is_empty());
        assert!(rules.source.is_none());
    }
}