cpm-planner 0.4.3

Critical Path Method planner as an MCP server: schedules task graphs (slack, critical path, resource levelling, Monte Carlo), leases lock-aware parallel cohorts to agents, versions plan-as-code variants, and tracks earned value.
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
//! `r040` — MCP-surface plan selection tests (GitHub issue #77, items 1, 2, 4).
//!
//! Drives [`PlanServer::dispatch_call`] over a file-backed planner with an
//! explicit `project` on every call, so no project root is needed. Each test
//! makes one behavioural assertion about the tool surface.

use std::path::PathBuf;
use std::sync::Arc;

use cpm_planner::audit::MemoryAuditSink;
use cpm_planner::server::{
    TOOL_ACQUIRE_COHORT, TOOL_ARCHIVE, TOOL_BASELINE, TOOL_EV, TOOL_LIST, TOOL_MARK_STATUS,
    TOOL_STATUS, TOOL_SUBMIT, plan_tool_definitions,
};
use cpm_planner::{BasicCpmPlanner, PlanServer, SqlitePlanStore};
use rmcp::model::{CallToolRequestParams, JsonObject};
use serde_json::{Value, json};

const PROJECT: &str = "proj";

// ── Harness ──────────────────────────────────────────────────────────────────

/// Unique temp db file, removed (with WAL sidecars) on drop.
struct TempDb {
    path: PathBuf,
}

impl TempDb {
    fn new() -> Self {
        let path = std::env::temp_dir().join(format!(
            "cpm-planner-server-selector-test-{}.db",
            uuid::Uuid::new_v4().simple()
        ));
        Self { path }
    }

    fn server(&self) -> PlanServer {
        let store = SqlitePlanStore::open(&self.path).expect("open store");
        PlanServer::new(Arc::new(BasicCpmPlanner::with_store(
            store,
            Arc::new(MemoryAuditSink::new()),
        )))
    }
}

impl Drop for TempDb {
    fn drop(&mut self) {
        for suffix in ["", "-wal", "-shm"] {
            let mut p = self.path.clone().into_os_string();
            p.push(suffix);
            let _ = std::fs::remove_file(PathBuf::from(p));
        }
    }
}

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)
}

/// A one-deliverable plan whose single deliverable is `id`.
fn one(id: &str) -> Value {
    json!({
        "deliverables": [
            {
                "id": id,
                "owned_files": [format!("src/{id}.rs")],
                "prerequisites": [],
                "estimated_effort_hours": 1.0
            }
        ],
        "max_chained_dispatch": null
    })
}

/// Register a named variant through `plan.submit` and return its plan id.
async fn sync_line(server: &PlanServer, name: &str, variant: &str, graph: Value) -> String {
    let req = call_args(
        TOOL_SUBMIT,
        json!({ "graph": graph, "project": PROJECT, "name": name, "variant": variant }),
    );
    let resp = server
        .dispatch_call(req)
        .await
        .expect("plan.submit of a named variant returns Ok");
    resp["plan_id"]
        .as_str()
        .expect("sync outcome carries a plan_id")
        .to_string()
}

/// Baseline a plan through the MCP surface (setup for `plan.ev`).
async fn baseline(server: &PlanServer, plan_id: &str) {
    server
        .dispatch_call(call_args(TOOL_BASELINE, json!({ "plan_id": plan_id })))
        .await
        .expect("plan.baseline returns Ok");
}

// ── plan.status: selection equivalence ───────────────────────────────────────

#[tokio::test]
async fn status_by_line_matches_explicit_plan_id() {
    let db = TempDb::new();
    let server = db.server();
    let id = sync_line(&server, "web", "main", one("a")).await;

    let by_line = server
        .dispatch_call(call_args(
            TOOL_STATUS,
            json!({ "plan": "web", "project": PROJECT }),
        ))
        .await
        .expect("plan.status by line returns Ok");
    let by_id = server
        .dispatch_call(call_args(TOOL_STATUS, json!({ "plan_id": id })))
        .await
        .expect("plan.status by id returns Ok");

    assert_eq!(by_line["plan_id"], by_id["plan_id"]);
}

// ── plan.ev: active selection ────────────────────────────────────────────────

#[tokio::test]
async fn ev_by_active_reports_the_live_plan_budget() {
    let db = TempDb::new();
    let server = db.server();
    let id = sync_line(&server, "web", "main", one("a")).await;
    baseline(&server, &id).await;

    let report = server
        .dispatch_call(call_args(
            TOOL_EV,
            json!({ "active": true, "project": PROJECT }),
        ))
        .await
        .expect("plan.ev by active returns Ok");

    assert_eq!(report["bac"], json!(1.0));
}

#[tokio::test]
async fn ev_by_active_with_no_candidate_is_no_active_plan() {
    let db = TempDb::new();
    let server = db.server();

    let err = server
        .dispatch_call(call_args(
            TOOL_EV,
            json!({ "active": true, "project": PROJECT }),
        ))
        .await
        .expect_err("no live line must fail");

    assert!(err.message.starts_with("NO_ACTIVE_PLAN"));
}

#[tokio::test]
async fn ev_by_active_with_two_candidates_is_ambiguous() {
    let db = TempDb::new();
    let server = db.server();
    let _alpha = sync_line(&server, "alpha", "main", one("a")).await;
    let _beta = sync_line(&server, "beta", "main", one("b")).await;

    let err = server
        .dispatch_call(call_args(
            TOOL_EV,
            json!({ "active": true, "project": PROJECT }),
        ))
        .await
        .expect_err("two live lines must fail");

    assert!(err.message.starts_with("AMBIGUOUS_ACTIVE_PLAN"));
}

// ── Selector validation ──────────────────────────────────────────────────────

#[tokio::test]
async fn plan_id_and_plan_together_are_invalid_params() {
    let db = TempDb::new();
    let server = db.server();

    let err = server
        .dispatch_call(call_args(
            TOOL_STATUS,
            json!({ "plan_id": "plan_x", "plan": "web", "project": PROJECT }),
        ))
        .await
        .expect_err("two selectors must fail");

    assert_eq!(
        err.message,
        "provide exactly one of plan_id, plan, or active: true"
    );
}

#[tokio::test]
async fn no_selector_is_invalid_params() {
    let db = TempDb::new();
    let server = db.server();

    let err = server
        .dispatch_call(call_args(TOOL_STATUS, json!({})))
        .await
        .expect_err("no selector must fail");

    assert_eq!(
        err.message,
        "provide exactly one of plan_id, plan, or active: true"
    );
}

#[tokio::test]
async fn project_with_plan_id_is_invalid_params() {
    let db = TempDb::new();
    let server = db.server();

    let err = server
        .dispatch_call(call_args(
            TOOL_STATUS,
            json!({ "plan_id": "plan_x", "project": PROJECT }),
        ))
        .await
        .expect_err("project with plan_id must fail");

    assert_eq!(err.message, "project applies only to plan or active");
}

// ── Execution tools by selector ──────────────────────────────────────────────

#[tokio::test]
async fn acquire_cohort_by_line_leases_from_the_selected_variant() {
    let db = TempDb::new();
    let server = db.server();
    let _id = sync_line(&server, "web", "main", one("a")).await;

    let cohort = server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan": "web", "project": PROJECT,
                "caller_id": "w", "max_count": 4
            }),
        ))
        .await
        .expect("plan.acquire_cohort by line returns Ok");

    assert_eq!(cohort["deliverables"][0]["id"], json!("a"));
}

#[tokio::test]
async fn mark_status_by_active_completes_a_leased_deliverable() {
    let db = TempDb::new();
    let server = db.server();
    let id = sync_line(&server, "web", "main", one("a")).await;
    server
        .dispatch_call(call_args(
            TOOL_ACQUIRE_COHORT,
            json!({
                "plan_id": id, "caller_id": "w", "max_count": 4
            }),
        ))
        .await
        .expect("acquire returns Ok");

    server
        .dispatch_call(call_args(
            TOOL_MARK_STATUS,
            json!({
                "active": true, "project": PROJECT,
                "deliverable_id": "a", "caller_id": "w",
                "status": { "status": "complete" }
            }),
        ))
        .await
        .expect("plan.mark_status by active returns Ok");

    let snapshot = server
        .dispatch_call(call_args(TOOL_STATUS, json!({ "plan_id": id })))
        .await
        .expect("plan.status returns Ok");
    assert_eq!(snapshot["plan_complete"], json!(true));
}

// ── plan.list: active filter ─────────────────────────────────────────────────

#[tokio::test]
async fn list_active_omits_an_archived_line() {
    let db = TempDb::new();
    let server = db.server();
    let _live = sync_line(&server, "live", "main", one("a")).await;
    let _old = sync_line(&server, "old", "main", one("b")).await;
    server
        .dispatch_call(call_args(
            "plan.archive",
            json!({ "name": "old", "project": PROJECT }),
        ))
        .await
        .expect("plan.archive returns Ok");

    let lines = server
        .dispatch_call(call_args(
            TOOL_LIST,
            json!({ "active": true, "project": PROJECT }),
        ))
        .await
        .expect("plan.list by active returns Ok");

    let names: Vec<&str> = lines
        .as_array()
        .expect("list is an array")
        .iter()
        .map(|line| line["name"].as_str().expect("line name"))
        .collect();
    assert_eq!(names, vec!["live"]);
}

#[tokio::test]
async fn list_active_with_include_archived_is_invalid_params() {
    let db = TempDb::new();
    let server = db.server();

    let err = server
        .dispatch_call(call_args(
            TOOL_LIST,
            json!({ "active": true, "include_archived": true, "project": PROJECT }),
        ))
        .await
        .expect_err("active with include_archived must fail");

    assert_eq!(
        err.message,
        "active and include_archived are mutually exclusive"
    );
}

// ── Advertised schema ────────────────────────────────────────────────────────

#[test]
fn plan_status_schema_no_longer_requires_plan_id() {
    let defs = plan_tool_definitions();
    let status = defs
        .iter()
        .find(|t| t.name == "plan.status")
        .expect("plan.status advertised");

    let required = status
        .input_schema
        .get("required")
        .and_then(|value| value.as_array());

    assert!(!required.is_some_and(|names| names.contains(&json!("plan_id"))));
}

// ── Issue #77 acceptance: stale ids and line equivalence ─────────────────────

#[tokio::test]
async fn ev_by_line_equals_ev_by_selected_plan_id() {
    let db = TempDb::new();
    let server = db.server();
    let id = sync_line(&server, "web", "main", one("a")).await;
    baseline(&server, &id).await;
    let as_of = "2030-01-01T00:00:00Z";

    let by_line = server
        .dispatch_call(call_args(
            TOOL_EV,
            json!({ "plan": "web", "project": PROJECT, "as_of": as_of }),
        ))
        .await
        .expect("plan.ev by line returns Ok");
    let by_id = server
        .dispatch_call(call_args(TOOL_EV, json!({ "plan_id": id, "as_of": as_of })))
        .await
        .expect("plan.ev by id returns Ok");

    assert_eq!(by_line, by_id);
}

#[tokio::test]
async fn ev_by_stale_archived_plan_id_flags_it_and_names_the_live_line() {
    let db = TempDb::new();
    let server = db.server();
    let old = sync_line(&server, "sprint-1", "main", one("a")).await;
    baseline(&server, &old).await;
    server
        .dispatch_call(call_args(
            TOOL_ARCHIVE,
            json!({ "name": "sprint-1", "project": PROJECT }),
        ))
        .await
        .expect("plan.archive returns Ok");
    let _live = sync_line(&server, "sprint-2", "main", one("b")).await;

    let report = server
        .dispatch_call(call_args(TOOL_EV, json!({ "plan_id": old })))
        .await
        .expect("plan.ev on an archived variant stays readable");

    assert_eq!(
        (&report["archived"], &report["active_plan"]),
        (&json!(true), &json!("sprint-2"))
    );
}