cpm-planner 0.0.1

Critical Path Method (CPM) planner exposed as an MCP server: schedules a task graph (earliest/latest start, slack, critical path, bottlenecks) and coordinates lock-aware parallel execution over MCP.
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
//! SPEC §33 PA4 — roundtrip + error-mapping tests for the `PlanServer`
//! MCP façade.
//!
//! Each test constructs a `PlanServer` backed by an in-memory
//! `BasicCpmPlanner`, invokes one tool via the transport-free
//! `dispatch_call` entry point (the same pattern
//! `mcp-flowgate-mcp-server`'s tests use), and asserts on the JSON
//! response shape — including the stable error-code prefixes
//! (LOCK_NOT_HELD, INVALID_GRAPH, …) on the failure paths.
//!
//! No external transport (stdio / streamable-http) is required: the
//! `dispatch_call` API is the documented test seam for this server.

use std::sync::Arc;

use cpm_planner::{
    BasicCpmPlanner, PlanServer, TOOL_ACQUIRE_COHORT, TOOL_FORCE_RELEASE, TOOL_HEARTBEAT,
    TOOL_MARK_STATUS, TOOL_STATUS, TOOL_SUBMIT,
};
use rmcp::model::{CallToolRequestParams, JsonObject};
use serde_json::{json, Value};

// ── Helpers ──────────────────────────────────────────────────────────────────

fn server() -> PlanServer {
    PlanServer::new(Arc::new(BasicCpmPlanner::new()))
}

fn call_args(name: &str, args: Value) -> CallToolRequestParams {
    let map: JsonObject = match args {
        Value::Object(m) => m,
        _ => panic!("call_args expects a JSON object"),
    };
    CallToolRequestParams::new(name.to_string()).with_arguments(map)
}

fn sample_graph() -> Value {
    json!({
        "deliverables": [
            {
                "id": "d1",
                "owned_files": ["src/a.rs"],
                "prerequisites": [],
                "estimated_effort_hours": 1.0,
                "metadata": { "description": "first" }
            },
            {
                "id": "d2",
                "owned_files": ["src/b.rs"],
                "prerequisites": ["d1"],
                "estimated_effort_hours": 2.0,
                "metadata": { "description": "second" }
            }
        ],
        "max_chained_dispatch": null
    })
}

async fn submit_plan(server: &PlanServer) -> String {
    let req = call_args(TOOL_SUBMIT, json!({ "graph": sample_graph() }));
    let resp = server
        .dispatch_call(req)
        .await
        .expect("plan.submit returns Ok");
    resp["plan_id"]
        .as_str()
        .expect("plan_id is a string")
        .to_string()
}

// ── Roundtrip: plan.submit ──────────────────────────────────────────────────

#[tokio::test]
async fn plan_submit_roundtrip() {
    let server = server();
    let req = call_args(TOOL_SUBMIT, json!({ "graph": sample_graph() }));
    let resp = server
        .dispatch_call(req)
        .await
        .expect("plan.submit returns Ok");
    let plan_id = resp["plan_id"].as_str().expect("plan_id field present");
    assert!(!plan_id.is_empty(), "plan_id must be non-empty");
    assert!(
        plan_id.starts_with("plan_"),
        "plan_id should carry the BasicCpmPlanner `plan_<uuid>` prefix; got {plan_id}"
    );
}

// ── Roundtrip: plan.acquire_cohort ──────────────────────────────────────────

#[tokio::test]
async fn plan_acquire_cohort_roundtrip() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    let req = call_args(
        TOOL_ACQUIRE_COHORT,
        json!({
            "plan_id": plan_id,
            "caller_id": "orchestrator-001",
            "max_count": 4
        }),
    );
    let resp = server
        .dispatch_call(req)
        .await
        .expect("plan.acquire_cohort returns Ok");

    assert_eq!(resp["plan_id"].as_str(), Some(plan_id.as_str()));
    let deliverables = resp["deliverables"]
        .as_array()
        .expect("deliverables is an array");
    let locks = resp["locks"].as_array().expect("locks is an array");
    // d1 is the only Ready deliverable; d2 is Pending until d1 completes.
    assert_eq!(
        deliverables.len(),
        1,
        "only d1 should be ready in the initial cohort"
    );
    assert_eq!(deliverables[0]["id"].as_str(), Some("d1"));
    assert_eq!(locks.len(), 1, "one lock per acquired deliverable");
    assert_eq!(locks[0]["deliverable_id"].as_str(), Some("d1"));
    assert_eq!(locks[0]["caller_id"].as_str(), Some("orchestrator-001"));
}

// ── Roundtrip: plan.heartbeat ───────────────────────────────────────────────

#[tokio::test]
async fn plan_heartbeat_roundtrip() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    // Acquire first so the heartbeat target lock exists.
    let _ = server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan_id": plan_id,
                "caller_id": "orchestrator-001",
                "max_count": 4
            }),
        ))
        .await
        .expect("acquire ok");

    let resp = server
        .dispatch_call(call_args(
            TOOL_HEARTBEAT,
            json!({
                "plan_id": plan_id,
                "deliverable_id": "d1",
                "caller_id": "orchestrator-001"
            }),
        ))
        .await
        .expect("plan.heartbeat returns Ok");
    assert_eq!(resp["ok"].as_bool(), Some(true));
}

// ── Roundtrip: plan.mark_status (complete releases the lock) ────────────────

#[tokio::test]
async fn plan_mark_status_complete_roundtrip() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    // Acquire d1.
    let _ = server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan_id": plan_id,
                "caller_id": "orchestrator-001",
                "max_count": 4
            }),
        ))
        .await
        .expect("acquire ok");

    // Mark complete.
    let resp = server
        .dispatch_call(call_args(
            TOOL_MARK_STATUS,
            json!({
                "plan_id": plan_id,
                "deliverable_id": "d1",
                "caller_id": "orchestrator-001",
                "status": { "status": "complete" }
            }),
        ))
        .await
        .expect("plan.mark_status returns Ok");
    assert_eq!(resp["ok"].as_bool(), Some(true));

    // Verify the lock was released by inspecting status.
    let status = server
        .dispatch_call(call_args(TOOL_STATUS, json!({ "plan_id": plan_id })))
        .await
        .expect("plan.status returns Ok");
    let locks = status["locks_held"]
        .as_array()
        .expect("locks_held array present");
    assert!(
        locks.is_empty(),
        "completing d1 should have released its lock; got {locks:?}"
    );
}

// ── Roundtrip: plan.status ──────────────────────────────────────────────────

#[tokio::test]
async fn plan_status_roundtrip() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    let resp = server
        .dispatch_call(call_args(TOOL_STATUS, json!({ "plan_id": plan_id })))
        .await
        .expect("plan.status returns Ok");

    assert_eq!(resp["plan_id"].as_str(), Some(plan_id.as_str()));

    let deliverables = resp["deliverables"]
        .as_array()
        .expect("deliverables is an array");
    assert_eq!(deliverables.len(), 2, "graph has two deliverables");
    // Wire format is Vec<(String, DeliverableStatus)> -> array of [id, status].
    let first = &deliverables[0];
    assert_eq!(first[0].as_str(), Some("d1"));
    assert_eq!(first[1]["status"].as_str(), Some("ready"));

    let cp = resp["critical_path"]
        .as_array()
        .expect("critical_path is an array");
    assert!(
        !cp.is_empty(),
        "critical_path must be populated for a non-empty graph"
    );
    // CPM should put d1 -> d2 on the critical path (effort 1.0 + 2.0 = 3.0).
    assert!(
        resp["critical_path_hours"]
            .as_f64()
            .map(|h| h > 0.0)
            .unwrap_or(false),
        "critical_path_hours must be positive; got {}",
        resp["critical_path_hours"]
    );
}

// ── Roundtrip: plan.force_release ───────────────────────────────────────────

#[tokio::test]
async fn plan_force_release_roundtrip() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    // Acquire d1 first so there is a lock to force-release.
    let _ = server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan_id": plan_id,
                "caller_id": "orchestrator-001",
                "max_count": 4
            }),
        ))
        .await
        .expect("acquire ok");

    let resp = server
        .dispatch_call(call_args(
            TOOL_FORCE_RELEASE,
            json!({
                "plan_id": plan_id,
                "deliverable_id": "d1",
                "reason": "orchestrator crashed; releasing manually"
            }),
        ))
        .await
        .expect("plan.force_release returns Ok");
    assert_eq!(resp["ok"].as_bool(), Some(true));

    // Confirm the lock is gone.
    let status = server
        .dispatch_call(call_args(TOOL_STATUS, json!({ "plan_id": plan_id })))
        .await
        .expect("status ok");
    let locks = status["locks_held"]
        .as_array()
        .expect("locks_held array present");
    assert!(
        locks.is_empty(),
        "force_release should have removed the lock; got {locks:?}"
    );
}

// ── Error mapping: INVALID_GRAPH on cycles ──────────────────────────────────

#[tokio::test]
async fn plan_invalid_graph_returns_error() {
    let server = server();
    let cyclic = json!({
        "deliverables": [
            { "id": "a", "owned_files": ["src/a.rs"], "prerequisites": ["b"] },
            { "id": "b", "owned_files": ["src/b.rs"], "prerequisites": ["a"] }
        ]
    });
    let err = server
        .dispatch_call(call_args(TOOL_SUBMIT, json!({ "graph": cyclic })))
        .await
        .expect_err("cyclic graph must be rejected");
    assert!(
        err.message.contains("INVALID_GRAPH"),
        "MCP error must carry the INVALID_GRAPH prefix; got: {}",
        err.message
    );
}

// ── Error mapping: LOCK_NOT_HELD on wrong caller ────────────────────────────

#[tokio::test]
async fn plan_wrong_caller_returns_lock_not_held() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    // Acquire under one caller.
    let _ = server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan_id": plan_id,
                "caller_id": "owner-001",
                "max_count": 4
            }),
        ))
        .await
        .expect("acquire ok");

    // Attempt to mark complete from a different caller.
    let err = server
        .dispatch_call(call_args(
            TOOL_MARK_STATUS,
            json!({
                "plan_id": plan_id,
                "deliverable_id": "d1",
                "caller_id": "imposter-002",
                "status": { "status": "complete" }
            }),
        ))
        .await
        .expect_err("wrong caller must be rejected");
    assert!(
        err.message.contains("LOCK_NOT_HELD"),
        "MCP error must carry the LOCK_NOT_HELD prefix; got: {}",
        err.message
    );
}

// ── Wire format: deny_unknown_fields enforced ───────────────────────────────

#[tokio::test]
async fn plan_submit_rejects_unknown_fields() {
    let server = server();
    let err = server
        .dispatch_call(call_args(
            TOOL_SUBMIT,
            json!({
                "graph": sample_graph(),
                "stray_field": "should be rejected"
            }),
        ))
        .await
        .expect_err("unknown fields must be rejected at the wire boundary");
    // The MCP layer wraps serde errors as invalid_params; the message
    // should mention the offending field.
    assert!(
        err.message.contains("stray_field") || err.message.contains("unknown field"),
        "expected wire-level rejection of unknown field; got: {}",
        err.message
    );
}

// ── DeliverableStatus::Failed round-trip ────────────────────────────────────

#[tokio::test]
async fn plan_mark_status_failed_carries_reason() {
    let server = server();
    let plan_id = submit_plan(&server).await;

    // Acquire so we hold the lock with the expected caller_id.
    let _ = server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan_id": plan_id,
                "caller_id": "orchestrator-001",
                "max_count": 4
            }),
        ))
        .await
        .expect("acquire ok");

    // Mark the deliverable failed with a structured reason.
    let resp = server
        .dispatch_call(call_args(
            TOOL_MARK_STATUS,
            json!({
                "plan_id": plan_id,
                "deliverable_id": "d1",
                "caller_id": "orchestrator-001",
                "status": { "status": "failed", "reason": "intentional test failure" }
            }),
        ))
        .await
        .expect("mark_status failed must succeed when caller holds the lock");
    assert_eq!(resp["ok"], json!(true));

    // Status reflects the Failed variant with the reason preserved.
    let status_resp = server
        .dispatch_call(call_args(TOOL_STATUS, json!({ "plan_id": plan_id })))
        .await
        .expect("status ok");
    let deliverables = status_resp["deliverables"]
        .as_array()
        .expect("deliverables array present");
    let d1 = deliverables
        .iter()
        .find(|row| row[0].as_str() == Some("d1"))
        .expect("d1 entry present");
    assert_eq!(d1[1]["status"], json!("failed"));
    assert_eq!(d1[1]["reason"], json!("intentional test failure"));
}