solverforge-cli 2.0.3

CLI for scaffolding and managing SolverForge constraint solver projects
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use super::{
    domain::{DomainModel, EntityInfo, FactInfo, ScalarVarInfo},
    mod_rewriter::{remove_constraint_from_source, rewrite_mod, validate_constraint_mod_source},
    run::run as run_generate_constraint,
    skeleton::{generate_skeleton, Pattern},
    utils::{snake_to_title, validate_name},
};
use crate::test_support;
use std::{
    fs,
    path::{Path, PathBuf},
};

struct CwdGuard {
    original_dir: PathBuf,
}

impl CwdGuard {
    fn enter(path: &Path) -> Self {
        let original_dir = std::env::current_dir().expect("failed to read current dir");
        std::env::set_current_dir(path).expect("failed to enter temp dir");
        Self { original_dir }
    }
}

impl Drop for CwdGuard {
    fn drop(&mut self) {
        std::env::set_current_dir(&self.original_dir).expect("failed to restore current dir");
    }
}

#[test]
fn test_validate_name() {
    assert!(validate_name("max_hours").is_ok());
    assert!(validate_name("required_skill").is_ok());
    assert!(validate_name("a").is_ok());
    assert!(validate_name("MaxHours").is_err());
    assert!(validate_name("1bad").is_err());
    assert!(validate_name("bad-name").is_err());
    assert!(validate_name("").is_err());
}

#[test]
fn test_snake_to_title() {
    assert_eq!(snake_to_title("max_hours"), "Max Hours");
    assert_eq!(snake_to_title("required_skill"), "Required Skill");
    assert_eq!(snake_to_title("all_assigned"), "All Assigned");
    assert_eq!(snake_to_title("capacity"), "Capacity");
}

#[test]
fn test_rewrite_mod_appends_module_and_call_to_managed_blocks() {
    let src = r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
mod all_assigned;
// @solverforge:end constraint-modules

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        // @solverforge:begin constraint-calls
        (
            all_assigned::constraint(),
        )
        // @solverforge:end constraint-calls
    }
}
"#;
    let result = rewrite_mod(src, "max_hours").expect("rewrite should succeed");
    assert!(result.contains("mod max_hours;"));
    assert!(result.contains("max_hours::constraint(),"));
}

#[test]
fn test_remove_constraint_from_source_preserves_empty_tuple_shape() {
    let src = r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
mod all_assigned;
// @solverforge:end constraint-modules

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        // @solverforge:begin constraint-calls
        (
            all_assigned::constraint(),
        )
        // @solverforge:end constraint-calls
    }
}
"#;
    let result = remove_constraint_from_source(src, "all_assigned").expect("remove should succeed");
    assert!(!result.contains("mod all_assigned;"));
    assert!(result.contains("        ()"));
}

#[test]
fn test_rewrite_mod_flattens_nested_constraint_tuples() {
    let src = r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
mod all_assigned;
mod extra;
// @solverforge:end constraint-modules

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        // @solverforge:begin constraint-calls
        (
            (
                all_assigned::constraint(),
                extra::constraint(),
            ),
        )
        // @solverforge:end constraint-calls
    }
}
"#;

    let result = rewrite_mod(src, "capacity").expect("rewrite should succeed");
    assert!(result.contains("mod capacity;"));
    assert!(result.contains("capacity::constraint(),"));
    assert!(result.contains("all_assigned::constraint(),"));
    assert!(result.contains("extra::constraint(),"));
}

#[test]
fn test_remove_constraint_from_source_handles_nested_tuple_calls() {
    let src = r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
mod one;
mod two;
mod three;
// @solverforge:end constraint-modules

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        // @solverforge:begin constraint-calls
        (
            (
                one::constraint(),
                two::constraint(),
            ),
            three::constraint(),
        )
        // @solverforge:end constraint-calls
    }
}
"#;

    let result = remove_constraint_from_source(src, "two").expect("remove should succeed");
    assert!(!result.contains("mod two;"));
    assert!(!result.contains("two::constraint(),"));
    assert!(result.contains("one::constraint(),"));
    assert!(result.contains("three::constraint(),"));
}

#[test]
fn test_rewrite_mod_requires_every_declared_constraint_to_be_wired() {
    let src = r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
mod all_assigned;
mod max_hours;
// @solverforge:end constraint-modules

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        // @solverforge:begin constraint-calls
        (
            all_assigned::constraint(),
        )
        // @solverforge:end constraint-calls
    }
}
"#;

    let err = rewrite_mod(src, "capacity").expect_err("missing constraint wiring should fail");

    assert_eq!(
        err,
        "managed constraint block declares module 'max_hours' but 'constraint-calls' does not invoke it"
    );
}

#[test]
fn test_validate_constraint_mod_source_rejects_undeclared_call() {
    let src = r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
mod all_assigned;
// @solverforge:end constraint-modules

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        // @solverforge:begin constraint-calls
        (
            all_assigned::constraint(),
            extra::constraint(),
        )
        // @solverforge:end constraint-calls
    }
}
"#;

    let err =
        validate_constraint_mod_source(src).expect_err("undeclared constraint call should fail");

    assert_eq!(
        err,
        "managed constraint block invokes undeclared module 'extra' in 'constraint-calls'"
    );
}

#[test]
fn test_run_preflights_managed_constraint_mod_before_creating_file() {
    let _cwd_guard = test_support::lock_cwd();
    let tmp = tempfile::tempdir().expect("failed to create temp dir");
    let _dir_guard = CwdGuard::enter(tmp.path());
    write_minimal_domain_project();
    fs::create_dir_all("src/constraints").expect("failed to create constraints dir");
    let invalid_mod = r#"pub use self::assemble::create_constraints;

mod assemble {
    use super::*;

    pub fn create_constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
        ()
    }
}
"#;
    fs::write("src/constraints/mod.rs", invalid_mod).expect("failed to write constraints mod");

    let err = run_generate_constraint(
        "capacity", false, true, false, false, false, false, false, false,
    )
    .expect_err("invalid managed block markers should fail before file creation");

    assert!(
        err.to_string()
            .contains("missing or duplicated managed block markers for 'constraint-modules'"),
        "unexpected error: {err}"
    );
    assert!(
        !Path::new("src/constraints/capacity.rs").exists(),
        "failed preflight must not create an orphan constraint file"
    );
    assert_eq!(
        fs::read_to_string("src/constraints/mod.rs").expect("failed to read constraints mod"),
        invalid_mod
    );
}

#[test]
fn test_run_rejects_hard_constraint_for_soft_score() {
    let _cwd_guard = test_support::lock_cwd();
    let tmp = tempfile::tempdir().expect("failed to create temp dir");
    let _dir_guard = CwdGuard::enter(tmp.path());
    write_minimal_domain_project();
    rewrite_plan_score("SoftScore");
    write_minimal_constraints_mod("SoftScore");

    let err = run_generate_constraint(
        "capacity", false, true, false, false, false, false, false, false,
    )
    .expect_err("hard generated constraints should be rejected for SoftScore");

    assert!(
        err.to_string()
            .contains("SoftScore supports only soft generated constraints"),
        "unexpected error: {err}"
    );
    assert!(
        !Path::new("src/constraints/capacity.rs").exists(),
        "rejected hard SoftScore constraint must not create a file"
    );
}

#[test]
fn test_run_accepts_soft_constraint_for_soft_score() {
    let _cwd_guard = test_support::lock_cwd();
    let tmp = tempfile::tempdir().expect("failed to create temp dir");
    let _dir_guard = CwdGuard::enter(tmp.path());
    write_minimal_domain_project();
    rewrite_plan_score("SoftScore");
    write_minimal_constraints_mod("SoftScore");

    run_generate_constraint(
        "preference",
        true,
        true,
        false,
        false,
        false,
        false,
        false,
        true,
    )
    .expect("soft generated constraints should be accepted for SoftScore");
}

fn write_minimal_domain_project() {
    fs::create_dir_all("src/domain").expect("failed to create domain dir");
    fs::write(
        "src/domain/mod.rs",
        r#"solverforge::planning_model! {
    root = "src/domain";

    // @solverforge:begin domain-exports
mod task;
mod plan;

pub use task::Task;
pub use plan::Plan;
// @solverforge:end domain-exports
}
"#,
    )
    .expect("failed to write domain mod");
    fs::write(
        "src/domain/task.rs",
        r#"use serde::{Deserialize, Serialize};
use solverforge::prelude::*;

#[planning_entity]
#[derive(Clone, Serialize, Deserialize)]
pub struct Task {
    #[planning_id]
    pub id: String,
}
"#,
    )
    .expect("failed to write task");
    fs::write(
        "src/domain/plan.rs",
        r#"use serde::{Deserialize, Serialize};
use solverforge::prelude::*;

use super::Task;

#[planning_solution(
    constraints = "crate::constraints::create_constraints",
    solver_toml = "../../solver.toml"
)]
#[derive(Serialize, Deserialize)]
pub struct Plan {
    // @solverforge:begin solution-collections
    #[planning_entity_collection]
    pub tasks: Vec<Task>,
    // @solverforge:end solution-collections
    #[planning_score]
    pub score: Option<HardSoftScore>,
}

impl Plan {
    pub fn new(
        // @solverforge:begin solution-constructor-params
        tasks: Vec<Task>,
        // @solverforge:end solution-constructor-params
    ) -> Self {
        Self {
            // @solverforge:begin solution-constructor-init
            tasks,
            // @solverforge:end solution-constructor-init
            score: None,
        }
    }
}
"#,
    )
    .expect("failed to write plan");
}

fn rewrite_plan_score(score_type: &str) {
    let path = Path::new("src/domain/plan.rs");
    let source = fs::read_to_string(path).expect("failed to read plan");
    fs::write(path, source.replace("HardSoftScore", score_type)).expect("failed to rewrite plan");
}

fn write_minimal_constraints_mod(score_type: &str) {
    fs::create_dir_all("src/constraints").expect("failed to create constraints dir");
    fs::write(
        "src/constraints/mod.rs",
        format!(
            r#"pub use self::assemble::create_constraints;

// @solverforge:begin constraint-modules
// @solverforge:end constraint-modules

mod assemble {{
    use solverforge::prelude::*;
    use crate::domain::Plan;

    pub fn create_constraints() -> impl ConstraintSet<Plan, {score_type}> {{
        // @solverforge:begin constraint-calls
        ()
        // @solverforge:end constraint-calls
    }}
}}
"#
        ),
    )
    .expect("failed to write constraints mod");
}

#[test]
fn test_generate_skeleton_unary_hard() {
    let domain = DomainModel {
        solution_type: "EmployeeSchedule".to_string(),
        score_type: "HardSoftDecimalScore".to_string(),
        entities: vec![EntityInfo {
            field_name: "shifts".to_string(),
            item_type: "Shift".to_string(),
            scalar_vars: vec![ScalarVarInfo {
                field: "employee_idx".to_string(),
                value_range_provider: "employees".to_string(),
                allows_unassigned: true,
            }],
            list_vars: vec![],
        }],
        facts: vec![],
    };
    let result = generate_skeleton(
        "no_overlap",
        Pattern::Unary,
        false,
        "EmployeeSchedule",
        "HardSoftDecimalScore",
        "No Overlap",
        Some(&domain),
    );
    assert!(result.contains("for_each(|s: &EmployeeSchedule| s.shifts.as_slice())"));
    assert!(result.contains("<HardSoftDecimalScore as Score>::one_hard()"));
    assert!(result.contains("HARD:"));
    assert!(!result.contains("todo!"));
    assert!(result
        .contains("panic!(\"replace placeholder condition before enabling this constraint\")"));
}

#[test]
fn test_generate_skeleton_pair_hard() {
    let domain = DomainModel {
        solution_type: "EmployeeSchedule".to_string(),
        score_type: "HardSoftDecimalScore".to_string(),
        entities: vec![EntityInfo {
            field_name: "shifts".to_string(),
            item_type: "Shift".to_string(),
            scalar_vars: vec![ScalarVarInfo {
                field: "employee_idx".to_string(),
                value_range_provider: "employees".to_string(),
                allows_unassigned: true,
            }],
            list_vars: vec![],
        }],
        facts: vec![],
    };
    let result = generate_skeleton(
        "no_overlap",
        Pattern::Pair,
        false,
        "EmployeeSchedule",
        "HardSoftDecimalScore",
        "No Overlap",
        Some(&domain),
    );
    assert!(result.contains("for_each(|s: &EmployeeSchedule| s.shifts.as_slice())"));
    assert!(result.contains("joiner::equal(|e: &Shift| e.employee_idx)"));
    assert!(result.contains(
        "panic!(\"replace placeholder pair condition before enabling this constraint\")"
    ));
    assert!(!result.contains("todo!"));
}

#[test]
fn test_generate_skeleton_join_hard() {
    let domain = DomainModel {
        solution_type: "EmployeeSchedule".to_string(),
        score_type: "HardSoftDecimalScore".to_string(),
        entities: vec![EntityInfo {
            field_name: "shifts".to_string(),
            item_type: "Shift".to_string(),
            scalar_vars: vec![ScalarVarInfo {
                field: "employee_idx".to_string(),
                value_range_provider: "employees".to_string(),
                allows_unassigned: true,
            }],
            list_vars: vec![],
        }],
        facts: vec![FactInfo {
            field_name: "employees".to_string(),
            item_type: "Employee".to_string(),
        }],
    };
    let result = generate_skeleton(
        "required_skill",
        Pattern::Join,
        false,
        "EmployeeSchedule",
        "HardSoftDecimalScore",
        "Required Skill",
        Some(&domain),
    );
    assert!(result.contains("equal_bi"));
    assert!(result.contains("employees.as_slice()"));
    assert!(result.contains("Employee"));
    assert!(result.contains("|e: &Shift| e.employee_idx"));
    assert!(
        result.contains("replace placeholder join key extractor before enabling this constraint")
    );
    assert!(result.contains("replace placeholder join condition before enabling this constraint"));
    assert!(!result.contains("todo!"));
}

#[test]
fn test_generate_skeleton_balance_soft() {
    let domain = DomainModel {
        solution_type: "EmployeeSchedule".to_string(),
        score_type: "HardSoftDecimalScore".to_string(),
        entities: vec![EntityInfo {
            field_name: "shifts".to_string(),
            item_type: "Shift".to_string(),
            scalar_vars: vec![ScalarVarInfo {
                field: "employee_idx".to_string(),
                value_range_provider: "employees".to_string(),
                allows_unassigned: true,
            }],
            list_vars: vec![],
        }],
        facts: vec![],
    };
    let result = generate_skeleton(
        "balance",
        Pattern::Balance,
        true,
        "EmployeeSchedule",
        "HardSoftDecimalScore",
        "Balance",
        Some(&domain),
    );
    assert!(result.contains(".balance(|e: &Shift| e.employee_idx)"));
    assert!(result.contains("SOFT:"));
}

#[test]
fn test_generate_skeleton_reward_soft_is_compile_safe() {
    let domain = DomainModel {
        solution_type: "EmployeeSchedule".to_string(),
        score_type: "HardSoftDecimalScore".to_string(),
        entities: vec![EntityInfo {
            field_name: "shifts".to_string(),
            item_type: "Shift".to_string(),
            scalar_vars: vec![ScalarVarInfo {
                field: "employee_idx".to_string(),
                value_range_provider: "employees".to_string(),
                allows_unassigned: true,
            }],
            list_vars: vec![],
        }],
        facts: vec![],
    };
    let result = generate_skeleton(
        "preferred_assignment",
        Pattern::Reward,
        true,
        "EmployeeSchedule",
        "HardSoftDecimalScore",
        "Preferred Assignment",
        Some(&domain),
    );
    assert!(result.contains(".reward(<HardSoftDecimalScore as Score>::one_soft())"));
    assert!(result.contains(
        "panic!(\"replace placeholder reward condition before enabling this constraint\")"
    ));
    assert!(!result.contains("todo!"));
}