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
impl StateManager {
/// Creates a new state manager with default configuration.
///
/// Initializes the state manager with no active session, a new snapshot
/// manager for persistence, and a unique session ID ready for the next
/// refactoring session.
///
/// # Returns
///
/// A new `StateManager` instance ready to manage refactoring sessions.
///
/// # Examples
///
/// ```rust
/// use pmat::mcp_server::state_manager::StateManager;
///
/// let manager = StateManager::new();
///
/// // Manager is ready but has no active session
/// assert!(manager.get_state().is_err());
///
/// // Session ID is pre-generated
/// let session_id = manager.get_session_id();
/// assert!(session_id.starts_with("refactor-session-"));
/// ```
#[must_use]
pub fn new() -> Self {
Self {
state: None,
snapshot_manager: SnapshotManager::new(),
session_id: Self::generate_session_id(),
}
}
#[must_use]
pub fn with_temp_dir(temp_dir: &Path) -> Self {
Self {
state: None,
snapshot_manager: SnapshotManager::with_path(temp_dir),
session_id: Self::generate_session_id(),
}
}
/// Starts a new refactoring session with specified targets and configuration.
///
/// Creates a new refactoring state machine, generates a unique session ID,
/// and saves an initial snapshot for recovery. Ensures only one session
/// is active at a time to maintain state consistency.
///
/// # Parameters
///
/// * `targets` - Vector of file paths to include in the refactoring session
/// * `config` - Refactoring configuration (complexity thresholds, etc.)
///
/// # Returns
///
/// * `Ok(())` - Session started successfully
/// * `Err(String)` - Session already active or configuration invalid
///
/// # Session Management
///
/// - Validates no existing session is active
/// - Creates new state machine with provided targets
/// - Generates unique session ID with timestamp
/// - Saves initial state snapshot for recovery
///
/// # Examples
///
/// ```rust
/// use pmat::mcp_server::state_manager::StateManager;
/// use pmat::models::refactor::RefactorConfig;
/// use std::path::PathBuf;
///
/// let mut manager = StateManager::new();
///
/// // Start session with multiple files
/// let targets = vec![
/// PathBuf::from("/project/src/main.rs"),
/// PathBuf::from("/project/src/lib.rs"),
/// ];
/// let config = RefactorConfig::default();
///
/// let result = manager.start_session(targets, config);
/// assert!(result.is_ok());
///
/// // Session is now active
/// assert!(manager.get_state().is_ok());
///
/// // Cannot start another session while one is active
/// let duplicate_result = manager.start_session(vec![], RefactorConfig::default());
/// assert!(duplicate_result.is_err());
/// ```
///
/// # MCP Protocol Integration
///
/// This method is typically called from the `refactor.start` MCP handler:
///
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "method": "refactor.start",
/// "params": {
/// "targets": ["/path/to/file.rs"],
/// "config": {
/// "target_complexity": 15,
/// "remove_satd": true
/// }
/// }
/// }
/// ```
pub fn start_session(
&mut self,
targets: Vec<PathBuf>,
config: RefactorConfig,
) -> Result<(), String> {
if self.state.is_some() {
return Err(
"Session already active. Stop current session before starting a new one."
.to_string(),
);
}
info!(
"Starting new refactor session with {} targets",
targets.len()
);
self.state = Some(RefactorStateMachine::new(targets, config));
self.session_id = Self::generate_session_id();
// Save initial state
self.save_snapshot()?;
Ok(())
}
/// Advances the refactoring state machine to the next phase.
///
/// Transitions the active refactoring session through its lifecycle phases,
/// automatically saving snapshots after each successful transition for
/// crash recovery and state persistence.
///
/// # Returns
///
/// * `Ok(())` - State advanced successfully
/// * `Err(String)` - No active session or state transition failed
///
/// # State Transitions
///
/// The state machine follows this progression:
/// 1. **Scan** → **Analyze**: Discovery complete, begin analysis
/// 2. **Analyze** → **Plan**: Metrics computed, generate refactoring plan
/// 3. **Plan** → **Refactor**: Operations planned, apply transformations
/// 4. **Refactor** → **Complete**: Transformations applied, finalize
///
/// # Persistence
///
/// Each successful state transition triggers:
/// - Automatic snapshot save for crash recovery
/// - State validation and consistency checks
/// - Progress tracking and metrics update
///
/// # Examples
///
/// ```rust
/// use pmat::mcp_server::state_manager::StateManager;
/// use pmat::models::refactor::RefactorConfig;
/// use std::path::PathBuf;
/// use tempfile::tempdir;
///
/// let temp_dir = tempdir().expect("internal error");
/// let mut manager = StateManager::with_temp_dir(temp_dir.path());
///
/// // Start session first
/// let targets = vec![PathBuf::from("/tmp/test.rs")];
/// let config = RefactorConfig::default();
/// manager.start_session(targets, config).expect("internal error");
///
/// // Advance through state machine phases
/// let advance1 = manager.advance();
/// assert!(advance1.is_ok());
///
/// let advance2 = manager.advance();
/// assert!(advance2.is_ok());
///
/// // Can continue advancing until Complete state
/// // Each advancement saves a recovery snapshot
/// ```
///
/// # MCP Protocol Integration
///
/// This method is called from the `refactor.nextIteration` MCP handler:
///
/// ```json
/// {
/// "jsonrpc": "2.0",
/// "method": "refactor.nextIteration",
/// "params": {}
/// }
/// ```
///
/// # Error Handling
///
/// - **No Active Session**: Returns error if no session is running
/// - **Invalid Transition**: Returns error for illegal state transitions
/// - **Snapshot Failure**: Returns error if state persistence fails
/// - **File Access**: Returns error if target files are inaccessible
pub fn advance(&mut self) -> Result<(), String> {
let state = self.state.as_mut().ok_or("No active session")?;
state.advance()?;
// Save after each state transition
self.save_snapshot()?;
Ok(())
}
pub fn get_state(&self) -> Result<&RefactorStateMachine, String> {
self.state.as_ref().ok_or("No active session".to_string())
}
#[must_use]
pub fn get_session_id(&self) -> &str {
&self.session_id
}
pub fn stop_session(&mut self) -> Result<(), String> {
if self.state.is_none() {
return Err("No active session to stop".to_string());
}
info!("Stopping refactor session");
// Clear in-memory state
self.state = None;
// Remove snapshot file
self.snapshot_manager.remove_snapshot()?;
Ok(())
}
fn save_snapshot(&self) -> Result<(), String> {
if let Some(state) = &self.state {
self.snapshot_manager.save_snapshot(state)?;
}
Ok(())
}
#[allow(dead_code)]
fn load_from_snapshot(&mut self) -> Result<(), String> {
match self.snapshot_manager.load_snapshot() {
Ok(state) => {
self.state = Some(state);
info!("Loaded existing refactor state from snapshot");
Ok(())
}
Err(e) => {
warn!("Failed to load snapshot: {}", e);
Err(e)
}
}
}
fn generate_session_id() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("internal error")
.as_millis();
format!("refactor-session-{timestamp}")
}
}