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
//! CPM Task data structures
//!
//! Defines the core types for Critical Path Management:
//! - [`Task`]: A unit of work to be scheduled
//! - [`TaskKind`]: Domain-neutral classification of work
//! - [`TaskBatch`]: A group of tasks that can run in parallel
//! - [`Bottleneck`]: A task that blocks significant downstream work
//! - [`CriticalPathResult`]: The full CPM analysis output
//!
//! These types are the *algorithm's internal* data model. The wire model
//! that crosses the [`crate::ports::Planner`] boundary lives in
//! `crate::plan`. PA3 will provide the bridge.
use serde::{Deserialize, Serialize};
/// Kind of task that can be planned.
///
/// Variants are deliberately domain-neutral. Specialised variants for any
/// given problem domain belong outside this crate.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TaskKind {
/// Break a circular dependency cycle in the task graph.
///
/// This is a generic graph operation, not coupled to any particular
/// problem domain.
BreakCycle {
/// Module identifiers (or generally, node ids) forming the cycle.
cycle: Vec<String>,
},
/// Implement a spec requirement.
ImplementSpec {
/// Opaque identifier of the specification to implement.
spec_id: String,
},
/// Custom user-defined task.
Custom {
/// Free-form description of the work.
description: String,
},
}
impl std::fmt::Display for TaskKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BreakCycle { .. } => write!(f, "CYCLE"),
Self::ImplementSpec { spec_id, .. } => write!(f, "SPEC-{spec_id}"),
Self::Custom { .. } => write!(f, "CUSTOM"),
}
}
}
/// Status of a task in the execution plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
/// Not started, dependencies may not be met.
#[default]
Pending,
/// Dependencies met, can start.
Ready,
/// Currently being worked on.
InProgress,
/// Successfully completed.
Completed,
/// Has unmet dependencies.
Blocked,
}
impl std::fmt::Display for TaskStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pending => write!(f, "pending"),
Self::Ready => write!(f, "ready"),
Self::InProgress => write!(f, "in_progress"),
Self::Completed => write!(f, "completed"),
Self::Blocked => write!(f, "blocked"),
}
}
}
/// A single task in the CPM plan.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
/// Unique identifier.
pub id: String,
/// Human-readable name.
pub name: String,
/// Type of task.
pub kind: TaskKind,
/// Scheduled length in hours. For tasks built from a deliverable this is
/// its calendar `duration_hours` when set, else its effort estimate;
/// earned value reads effort from the graph, not from here.
pub effort_hours: f32,
/// Task IDs this depends on (must complete before this can start).
pub dependencies: Vec<String>,
/// Minimum wait in hours between a dependency's finish and this task's
/// start, keyed by dependency id. Absent means 0.
#[serde(default)]
pub lag_by_dependency: std::collections::HashMap<String, f32>,
/// Current status.
pub status: TaskStatus,
/// Earliest start time (calculated by forward pass).
pub earliest_start: f32,
/// Earliest finish time (ES + effort).
pub earliest_finish: f32,
/// Latest start time (calculated by backward pass).
pub latest_start: f32,
/// Latest finish time.
pub latest_finish: f32,
/// Float/slack time (LS - ES).
pub float: f32,
/// Is this task on the critical path?
pub is_critical: bool,
/// Files affected by this task (for context building, domain-neutral).
pub affected_files: Vec<String>,
}
impl Default for Task {
fn default() -> Self {
Self {
id: String::new(),
name: String::new(),
kind: TaskKind::Custom {
description: String::new(),
},
effort_hours: 0.0,
dependencies: Vec::new(),
lag_by_dependency: std::collections::HashMap::new(),
status: TaskStatus::Pending,
earliest_start: 0.0,
earliest_finish: 0.0,
latest_start: 0.0,
latest_finish: 0.0,
float: 0.0,
is_critical: false,
affected_files: Vec::new(),
}
}
}
impl Task {
/// Create a new task with the given ID, name, kind, and effort.
pub fn new(
id: impl Into<String>,
name: impl Into<String>,
kind: TaskKind,
effort_hours: f32,
) -> Self {
Self {
id: id.into(),
name: name.into(),
kind,
effort_hours,
..Default::default()
}
}
/// Add a dependency to this task.
#[must_use]
pub fn depends_on(mut self, task_id: impl Into<String>) -> Self {
self.dependencies.push(task_id.into());
self
}
/// Add an affected file.
#[must_use]
pub fn affects_file(mut self, file: impl Into<String>) -> Self {
self.affected_files.push(file.into());
self
}
}
/// A batch of tasks that can run in parallel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskBatch {
/// Batch identifier (e.g., "Batch-1").
pub id: String,
/// Tasks in this batch (all have same ES).
pub tasks: Vec<String>,
/// Total effort if done sequentially.
pub total_effort_hours: f32,
/// Actual duration (max of task efforts in batch).
pub duration_hours: f32,
/// Earliest start time for this batch.
pub start_time: f32,
}
impl Default for TaskBatch {
fn default() -> Self {
Self {
id: String::new(),
tasks: Vec::new(),
total_effort_hours: 0.0,
duration_hours: 0.0,
start_time: 0.0,
}
}
}
/// A bottleneck task that blocks significant downstream work.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bottleneck {
/// The bottleneck task ID.
pub task_id: String,
/// Task name for display.
pub task_name: String,
/// Number of tasks blocked by this one (directly or transitively).
pub blocks_count: usize,
/// Total scheduled hours of work blocked. Uses the scheduled length (`duration_hours` when set, else effort); earned value reads effort from the graph.
pub blocked_hours: f32,
/// ROI: `blocked_hours / effort_hours` (higher = higher priority). Both
/// are scheduled lengths; earned value reads effort from the graph.
pub roi: f32,
/// Scheduled length of this task (`duration_hours` when set, else effort).
pub effort_hours: f32,
}
/// Critical Path Analysis Results.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CriticalPathResult {
/// Total number of tasks in the plan.
pub total_tasks: usize,
/// One longest prerequisite chain, in execution order: each element is a
/// prerequisite of the next. Sink ties resolve to the later earliest start,
/// then the smallest id; predecessor ties resolve to the smallest id.
pub critical_path: Vec<String>,
/// Every zero-float (critical) task, sorted by earliest start then id.
/// Unlike `critical_path` this may contain several parallel chains.
#[serde(default)]
pub critical_ids: Vec<String>,
/// Project length: the maximum earliest finish (the scheduled lengths plus
/// edge lags along `critical_path`).
pub critical_path_duration: f32,
/// Total duration if done sequentially. Uses the scheduled length (`duration_hours` when set, else effort); earned value reads effort from the graph.
pub total_duration_sequential: f32,
/// Makespan with unlimited parallelism (maximum earliest finish). Uses the scheduled length (`duration_hours` when set, else effort); earned value reads effort from the graph.
pub optimal_duration_parallel: f32,
/// Speedup factor (sequential / parallel).
pub speedup_factor: f32,
/// Batches for parallel execution.
pub parallelizable_batches: Vec<TaskBatch>,
/// Bottleneck tasks (sorted by ROI descending).
pub bottlenecks: Vec<Bottleneck>,
/// All tasks with calculated times.
pub tasks: Vec<Task>,
/// Task ids the forward pass could not schedule. Non-empty iff the
/// dependency graph is cyclic or otherwise unschedulable; in that case
/// every other field is confidently-wrong and must not be trusted.
/// Callers that do not pre-validate (e.g. direct
/// [`CpmAlgorithm::calculate`][crate::algorithm::CpmAlgorithm::calculate]
/// users) MUST check this is empty before using the result.
pub unscheduled: Vec<String>,
}
impl CriticalPathResult {
/// Get a task by ID.
#[must_use]
pub fn get_task(&self, id: &str) -> Option<&Task> {
self.tasks.iter().find(|t| t.id == id)
}
}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use super::*;
#[test]
fn test_task_creation() {
let task = Task::new(
"SPEC-001",
"Implement login flow",
TaskKind::ImplementSpec {
spec_id: "auth.login".to_string(),
},
2.0,
)
.depends_on("SPEC-000")
.affects_file("src/auth/login.rs")
.affects_file("src/auth/mod.rs");
assert_eq!(task.id, "SPEC-001");
assert_eq!(task.effort_hours, 2.0);
assert_eq!(task.dependencies, vec!["SPEC-000"]);
assert_eq!(
task.affected_files,
vec!["src/auth/login.rs", "src/auth/mod.rs"]
);
}
#[test]
fn test_task_kind_display() {
assert_eq!(
TaskKind::ImplementSpec {
spec_id: "auth.login".to_string()
}
.to_string(),
"SPEC-auth.login"
);
assert_eq!(
TaskKind::BreakCycle {
cycle: vec!["a".to_string(), "b".to_string()]
}
.to_string(),
"CYCLE"
);
assert_eq!(
TaskKind::Custom {
description: "anything".to_string()
}
.to_string(),
"CUSTOM"
);
}
#[test]
fn test_get_task() {
let result = CriticalPathResult {
total_tasks: 2,
tasks: vec![
Task {
id: "T1".to_string(),
effort_hours: 5.0,
..Default::default()
},
Task {
id: "T2".to_string(),
effort_hours: 3.0,
..Default::default()
},
],
..Default::default()
};
assert_eq!(result.get_task("T2").expect("T2 present").effort_hours, 3.0);
assert!(result.get_task("missing").is_none());
}
}