dx_forge/
lib.rs

1//! # DX Forge - Production-Ready VCS and Orchestration Engine
2//!
3//! Forge is the orchestration backbone for the DX tools ecosystem, providing:
4//! - Content-addressable storage with SHA-256 blob hashing
5//! - Git-compatible versioning with traffic branch safety system
6//! - Dual-watcher architecture (LSP + File System monitoring)
7//! - Tool orchestration with priority-based execution and dependency resolution
8//! - Component injection for zero-bloat dependency management
9//! - Semantic versioning with dependency resolution
10//! - Pattern detection for dx-tools (dxButton, dxiIcon, dxfRoboto, etc.)
11//! - R2 component caching and injection
12//! - Production error handling with retry logic
13//!
14//! ## Architecture Overview
15//!
16//! Forge eliminates node_modules bloat by detecting code patterns via LSP,
17//! injecting only needed components directly into user files, and coordinating
18//! DX tool execution with traffic branch safety logic.
19//!
20//! ### Core Components
21//!
22//! - **Orchestrator**: Coordinates tool execution with lifecycle hooks, circular dependency detection
23//! - **Dual-Watcher**: Monitors LSP + file system changes with pattern detection
24//! - **Traffic Branch System**: Green (auto), Yellow (merge), Red (manual) for safe updates
25//! - **Storage Layer**: Content-addressable blobs with R2 cloud sync
26//! - **Version Manager**: Semantic versioning with compatibility checking
27//! - **Pattern Detector**: Identifies dx-tool patterns in source code
28//! - **Injection Manager**: Fetches and caches components from R2 storage
29//!
30//! ## Quick Start - Tool Development
31//!
32//! ```rust,no_run
33//! use dx_forge::{DxTool, ExecutionContext, ToolOutput, Orchestrator};
34//! use async_trait::async_trait;
35//! use anyhow::Result;
36//!
37//! struct MyDxTool;
38//!
39//! #[async_trait]
40//! impl DxTool for MyDxTool {
41//!     fn name(&self) -> &str { "dx-mytool" }
42//!     fn version(&self) -> &str { "1.0.0" }
43//!     fn priority(&self) -> i32 { 50 }
44//!     
45//!     async fn execute(&self, ctx: &ExecutionContext) -> Result<ToolOutput> {
46//!         // Your tool logic here
47//!         Ok(ToolOutput::success("Done!"))
48//!     }
49//! }
50//!
51//! #[tokio::main]
52//! async fn main() -> Result<()> {
53//!     let mut orchestrator = Orchestrator::new(".")?;
54//!     orchestrator.register_tool(Box::new(MyDxTool));
55//!     orchestrator.execute_all().await?;
56//!     Ok(())
57//! }
58//! ```
59//!
60//! ## Quick Start - Change Detection
61//!
62//! ```rust,no_run
63//! use dx_forge::{DualWatcher, FileChange};
64//! use tokio::sync::broadcast;
65//!
66//! #[tokio::main]
67//! async fn main() -> anyhow::Result<()> {
68//!     let watcher = DualWatcher::new(".")?;
69//!     let mut rx = watcher.subscribe();
70//!     
71//!     tokio::spawn(async move {
72//!         watcher.start().await
73//!     });
74//!     
75//!     while let Ok(change) = rx.recv().await {
76//!         println!("Change detected: {:?} ({})", change.path, change.source);
77//!     }
78//!     Ok(())
79//! }
80//! ```
81
82// Core modules
83pub mod context;
84pub mod crdt;
85pub mod server;
86pub mod storage;
87pub mod sync;
88
89// Core library - NEW unified API
90pub mod core;
91
92// ========================================================================
93// The 132 Eternal API Functions (v0.1.0)
94// ========================================================================
95pub mod api;
96
97// Legacy watcher module (for CLI compatibility)
98#[path = "watcher_legacy/mod.rs"]
99pub mod watcher_legacy;
100
101// Production orchestration modules (v1.0.0)
102pub mod orchestrator;
103pub mod watcher;
104
105// DX Tools support modules
106pub mod version;
107pub mod patterns;
108pub mod injection;
109pub mod error;
110
111// Phase 5 modules
112pub mod auto_update;
113pub mod profiler;
114pub mod cache;
115
116// ========================================================================
117// Primary Public API - Forge Unified Interface
118// ========================================================================
119
120pub use core::{
121    Forge, ForgeConfig,
122    LifecycleEvent, ToolId, ToolStatus,
123    EditorInfo, EditorType, OutputStrategy,
124    GeneratedFileInfo,
125};
126
127// ========================================================================
128// Re-export orchestration types (public API)
129// ========================================================================
130
131pub use orchestrator::{
132    Conflict, DxTool, ExecutionContext, Orchestrator, OrchestratorConfig, ToolOutput,
133    TrafficAnalyzer, TrafficBranch,
134};
135
136pub use watcher::{ChangeKind, ChangeSource, DualWatcher, FileChange, FileWatcher, LspWatcher};
137
138// ========================================================================
139// Re-export storage types
140// ========================================================================
141
142pub use context::{ComponentStateManager, UpdateResult};
143pub use crdt::{Operation, OperationType, Position};
144pub use storage::{Database, OperationLog};
145
146// ========================================================================
147// Re-export DX tools support types
148// ========================================================================
149
150pub use version::{
151    ToolInfo, ToolRegistry, ToolSource, Version, VersionReq,
152    Snapshot, SnapshotId, SnapshotManager, Branch, ToolState, FileSnapshot, SnapshotDiff,
153};
154pub use patterns::{DxToolType, PatternDetector, PatternMatch};
155pub use injection::{CacheStats, ComponentMetadata, InjectionManager};
156pub use error::{categorize_error, EnhancedError, EnhancedResult, ErrorCategory, RetryPolicy, ToEnhanced, with_retry};
157
158// ========================================================================
159// Legacy exports (deprecated in favor of new Forge API)
160// ========================================================================
161
162#[deprecated(since = "1.0.0", note = "use `Forge` instead")]
163pub use watcher::DualWatcher as ForgeWatcher;
164
165/// Library version
166pub const VERSION: &str = env!("CARGO_PKG_VERSION");
167
168// ========================================================================
169// Re-export The 132 Eternal API Functions
170// ========================================================================
171
172// Core Lifecycle & System Orchestration (4 functions)
173pub use api::lifecycle::{
174    initialize_forge, register_tool, get_tool_context, shutdown_forge,
175};
176
177// Version Governance & Package Identity (6 functions)
178pub use api::version::{
179    declare_tool_version, enforce_exact_version, require_forge_minimum,
180    current_forge_version, query_active_package_variant, activate_package_variant,
181};
182
183// Pipeline Execution & Orchestration (7 functions)
184pub use api::pipeline::{
185    execute_pipeline, execute_tool_immediately, get_resolved_execution_order,
186    temporarily_override_pipeline_order, restart_current_pipeline,
187    suspend_pipeline_execution, resume_pipeline_execution,
188};
189
190// Triple-Path Reactivity Engine (5 functions)
191pub use api::reactivity::{
192    trigger_realtime_event, trigger_debounced_event, trigger_idle_event,
193    begin_batch_operation, end_batch_operation,
194};
195
196// Safe File Application & Branching Decision Engine (15 functions)
197pub use api::branching::{
198    apply_changes, apply_changes_with_preapproved_votes, apply_changes_force_unchecked,
199    preview_proposed_changes, automatically_accept_green_conflicts,
200    prompt_review_for_yellow_conflicts, automatically_reject_red_conflicts,
201    revert_most_recent_application, submit_branching_vote,
202    register_permanent_branching_voter, query_predicted_branch_color,
203    is_change_guaranteed_safe, issue_immediate_veto, reset_branching_engine_state,
204    BranchColor, BranchingVote,
205};
206// Note: FileChange is already exported from watcher module
207
208// Global Event Bus & Observability (9 functions)
209pub use api::events::{
210    publish_event, subscribe_to_event_stream, emit_tool_started_event,
211    emit_tool_completed_event, emit_pipeline_started_event, emit_pipeline_completed_event,
212    emit_package_installation_begin, emit_package_installation_success,
213    emit_security_violation_detected, emit_magical_config_injection, ForgeEvent,
214};
215
216// The One True Configuration System (16 functions)
217pub use api::config::{
218    get_active_config_file_path, reload_configuration_manifest,
219    enable_live_config_watching, inject_full_config_section_at_cursor,
220    expand_config_placeholder, jump_to_config_section, validate_config_in_realtime,
221    provide_config_completion_suggestions, auto_format_config_file,
222    perform_config_schema_migration, inject_style_tooling_config,
223    inject_authentication_config, inject_ui_framework_config,
224    inject_icon_system_config, inject_font_system_config,
225    inject_media_pipeline_config, inject_package_specific_config,
226};
227
228// CI/CD & Workspace Orchestration (8 functions)
229pub use api::cicd::{
230    trigger_ci_cd_pipeline, register_ci_stage, query_current_ci_status,
231    abort_running_ci_job, synchronize_monorepo_workspace, detect_workspace_root,
232    list_all_workspace_members, broadcast_change_to_workspace,
233};
234
235// .dx/ Directory Management (10 functions)
236pub use api::dx_directory::{
237    get_dx_directory_path, get_dx_binary_storage_path, cache_tool_offline_binary,
238    load_tool_offline_binary, commit_current_dx_state, checkout_dx_state,
239    list_dx_history, show_dx_state_diff, push_dx_state_to_remote,
240    pull_dx_state_from_remote,
241};
242
243// Offline-First Architecture (5 functions)
244pub use api::offline::{
245    detect_offline_mode, force_offline_operation, download_missing_tool_binaries,
246    verify_binary_integrity_and_signature, update_tool_binary_atomically,
247};
248
249// Cart System (8 functions)
250pub use api::cart::{
251    stage_item_in_cart, commit_entire_cart, commit_cart_immediately,
252    clear_cart_completely, remove_specific_cart_item, get_current_cart_contents,
253    export_cart_as_shareable_json, import_cart_from_json, CartItem,
254};
255
256// Package Management (8 functions)
257pub use api::packages::{
258    install_package_with_variant, uninstall_package_safely, update_package_intelligently,
259    list_all_installed_packages, search_dx_package_registry, pin_package_to_exact_version,
260    fork_existing_variant, publish_your_variant, PackageInfo,
261};
262
263// Generated Code Governance (5 functions)
264pub use api::codegen::{
265    mark_code_region_as_dx_generated, is_region_dx_generated,
266    allow_safe_manual_edit_of_generated_code, claim_full_ownership_of_file,
267    release_ownership_of_file,
268};
269
270// Developer Experience & Editor Integration (26 functions)
271pub use api::dx_experience::{
272    project_root_directory, path_to_forge_manifest, dx_global_cache_directory,
273    create_watcher_ignored_scratch_file, log_structured_tool_action,
274    schedule_task_for_idle_time, await_editor_idle_state, request_user_attention_flash,
275    open_file_and_reveal_location, display_inline_code_suggestion,
276    apply_user_accepted_suggestion, show_onboarding_welcome_tour,
277    execute_full_security_audit, generate_comprehensive_project_report,
278    display_dx_command_palette, open_embedded_dx_terminal,
279    trigger_ai_powered_suggestion, apply_ai_generated_completion,
280    open_dx_explorer_sidebar, update_dx_status_bar_indicator,
281};
282
283// Testing forge logging
284// test logging
285// test event
286// event2
287// test edit