willbe 0.34.0

Utility to publish multi-crate and multi-workspace environments and maintain their consistency.
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
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
# Implementation Plan: Dependency Staleness Detection

**Project:** willbe Publishing Algorithm Enhancement
**Goal:** Fix missing dependency staleness detection
**Approach:** Incremental TDD with specification-first development
**Estimated Duration:** 18-26 days

---

## Increment Structure

Each increment follows this template:

```
Increment N: [Name]
├─ Goal: What we achieve
├─ Input State: System before this increment
├─ Output State: System after this increment
├─ Implementation Steps: Ordered list of tasks
├─ Verification: How to verify success
└─ Rollback: How to undo if needed
```

---

## INCREMENT 1: Project Setup & Specification (2 days)

### Goal

Establish project foundation with complete specification and test infrastructure.

### Input State

- Existing publishing algorithm without staleness detection
- No formal specification
- Bug exists: version conflicts during publishing

### Output State

- Complete specification in `spec/` directory
- Test directory structure created
- Development environment ready

### Implementation Steps

**Step 1.1: Create Specification Directory**

```bash
mkdir -p spec/
touch spec/index.md
touch spec/publishing_algorithm.md  # Already created
touch spec/test_scenarios.md
touch spec/architecture.md
```

**Step 1.2: Write Test Scenarios Document**

Create `spec/test_scenarios.md` with comprehensive test matrix covering:
- Basic staleness detection (10 scenarios)
- Cascade publishing (8 scenarios)
- Edge cases (12 scenarios)
- Performance tests (5 scenarios)

**Step 1.3: Create Test Directory Structure**

```bash
mkdir -p tests/inc/publish/
touch tests/inc/publish/mod.rs
touch tests/inc/publish/dependency_staleness_test.rs
touch tests/inc/publish/cascade_test.rs
touch tests/inc/publish/version_conflict_test.rs
touch tests/inc/publish/edge_cases_test.rs
```

**Step 1.4: Set Up Test Utilities**

Create `tests/inc/publish/test_utils.rs`:
- Workspace builder for testing
- Package builder with dependencies
- Version requirement helpers
- Assertion utilities

### Verification

```bash
# All files created
ls spec/
ls tests/inc/publish/

# Specification readable and complete
cargo doc --no-deps --document-private-items
```

### Deliverables

- `spec/publishing_algorithm.md` (complete)
-`spec/test_scenarios.md` (35+ scenarios)
-`spec/architecture.md` (system design)
-`tests/inc/publish/test_utils.rs` (helper functions)

---

## INCREMENT 2: Core Data Structures (3 days)

### Goal

Implement all data structures needed for staleness detection.

### Input State

- Specification complete
- Test infrastructure ready
- No staleness-related types

### Output State

- `PublishReason` enum implemented
- `StaleDependency` struct implemented
- `StaleReason` enum implemented
- Unit tests passing

### Implementation Steps

**Step 2.1: Create `publish_reason.rs` Module**

Location: `src/entity/publish_reason.rs`

```rust
/// Reasons why a package needs publishing
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub enum PublishReason
{
  /// Local source code was modified
  LocalChanges,

  /// Package version was explicitly bumped
  VersionBump,

  /// One or more dependencies have incompatible versions
  StaleDependencies
  {
    /// List of dependencies causing staleness
    stale_deps: Vec< StaleDependency >,
  },

  /// Package depends on another package being published in this batch
  CascadeEffect
  {
    /// Package(s) triggering the cascade
    triggered_by: Vec< PackageName >,
  },
}

impl PublishReason
{
  /// Returns true if this is a local change reason
  pub fn is_local_change( &self ) -> bool
  {
    matches!( self, PublishReason::LocalChanges )
  }

  /// Returns true if this is a staleness reason
  pub fn is_stale( &self ) -> bool
  {
    matches!( self, PublishReason::StaleDependencies { .. } )
  }

  /// Returns true if this is a cascade reason
  pub fn is_cascade( &self ) -> bool
  {
    matches!( self, PublishReason::CascadeEffect { .. } )
  }

  /// Human-readable description
  pub fn description( &self ) -> String
  {
    match self
    {
      PublishReason::LocalChanges => "Local source code modified".to_string(),
      PublishReason::VersionBump => "Version explicitly bumped".to_string(),
      PublishReason::StaleDependencies { stale_deps } =>
        format!( "Stale dependencies: {}", stale_deps.len() ),
      PublishReason::CascadeEffect { triggered_by } =>
        format!( "Cascade from: {}", triggered_by.join( ", " ) ),
    }
  }
}
```

**Step 2.2: Create `stale_dependency.rs` Module**

Location: `src/entity/stale_dependency.rs`

```rust
/// Details about a stale dependency
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub struct StaleDependency
{
  /// Name of the dependency
  pub name: PackageName,

  /// Version requirement in dependent's Cargo.toml
  pub required: VersionReq,

  /// Actual version in workspace
  pub workspace_version: Version,

  /// Why it's considered stale
  pub reason: StaleReason,
}

/// Why a dependency is stale
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub enum StaleReason
{
  /// Workspace version doesn't satisfy requirement
  IncompatibleVersion,

  /// Dependency is being published in this publish batch
  BeingPublished,
}

impl StaleDependency
{
  /// Check if workspace version satisfies requirement
  pub fn is_compatible( &self ) -> bool
  {
    self.required.matches( &self.workspace_version )
  }

  /// Human-readable description
  pub fn description( &self ) -> String
  {
    match self.reason
    {
      StaleReason::IncompatibleVersion =>
        format!(
          "{}: required {}, workspace has {}",
          self.name, self.required, self.workspace_version
        ),
      StaleReason::BeingPublished =>
        format!(
          "{}: dependency being published in this batch",
          self.name
        ),
    }
  }
}
```

**Step 2.3: Update `publish.rs` to Use New Types**

Add to `src/entity/publish.rs`:

```rust
/// Enhanced publish instruction with reasons
#[ derive( Debug, Clone ) ]
pub struct PackagePublishInstruction
{
  pub package_name: PackageName,
  pub old_version: Version,
  pub new_version: Version,

  /// NEW: Why this package needs publishing
  pub reasons: Vec< PublishReason >,

  // Existing fields...
  pub pack: cargo::PackOptions,
  pub bump: version::BumpOptions,
  pub git_options: git::GitOptions,
  pub publish: cargo::PublishOptions,
  pub dry: bool,
}
```

**Step 2.4: Write Unit Tests**

Create `tests/inc/publish/data_structures_test.rs`:

```rust
#[ test ]
fn publish_reason_local_changes()
{
  let reason = PublishReason::LocalChanges;
  assert!( reason.is_local_change() );
  assert!( !reason.is_stale() );
  assert!( !reason.is_cascade() );
}

#[ test ]
fn stale_dependency_incompatible_version()
{
  let stale = StaleDependency
  {
    name: "former".into(),
    required: VersionReq::parse( "~2.36.0" ).unwrap(),
    workspace_version: Version::parse( "2.37.0" ).unwrap(),
    reason: StaleReason::IncompatibleVersion,
  };

  assert!( !stale.is_compatible() );
  assert!( stale.description().contains( "required ~2.36.0" ) );
}

#[ test ]
fn stale_dependency_being_published()
{
  let stale = StaleDependency
  {
    name: "former".into(),
    required: VersionReq::parse( "~2.37.0" ).unwrap(),
    workspace_version: Version::parse( "2.37.0" ).unwrap(),
    reason: StaleReason::BeingPublished,
  };

  assert!( stale.is_compatible() );  // Version matches
  assert!( stale.description().contains( "being published" ) );
}
```

### Verification

```bash
# Compile check
cargo check --all-features

# Run unit tests
w3 .test level::1

# Verify types exist
cargo doc --no-deps --document-private-items --open
# Navigate to entity::publish_reason, entity::stale_dependency
```

### Deliverables

- `src/entity/publish_reason.rs` (complete with tests)
-`src/entity/stale_dependency.rs` (complete with tests)
- ✅ Updated `src/entity/publish.rs` (with reasons field)
-`tests/inc/publish/data_structures_test.rs` (passing)

---

## INCREMENT 3: Semver Utilities (2 days)

### Goal

Implement semver matching and version requirement utilities.

### Input State

- Data structures exist
- No semver utilities
- Relying on `semver` crate primitives

### Output State

- Semver matching helper functions
- Version requirement parsing utilities
- Comprehensive semver tests

### Implementation Steps

**Step 3.1: Create `semver_utils.rs` Module**

Location: `src/tool/semver_utils.rs`

```rust
use semver::{ Version, VersionReq };

/// Check if version satisfies requirement
pub fn matches( req: &VersionReq, version: &Version ) -> bool
{
  req.matches( version )
}

/// Parse version requirement from string
pub fn parse_req( s: &str ) -> Result< VersionReq, semver::Error >
{
  VersionReq::parse( s )
}

/// Parse version from string
pub fn parse_version( s: &str ) -> Result< Version, semver::Error >
{
  Version::parse( s )
}

/// Check if two version requirements are compatible
pub fn requirements_compatible( req1: &VersionReq, req2: &VersionReq ) -> bool
{
  // Two requirements are compatible if there exists a version
  // that satisfies both
  // Simplified check: see if max of one satisfies min of other
  // Full implementation requires range intersection
  todo!( "Implement full compatibility check" )
}

/// Get the maximum version that satisfies a requirement
pub fn max_satisfying< 'a, I >( req: &VersionReq, versions: I ) -> Option< &'a Version >
where
  I: IntoIterator< Item = &'a Version >,
{
  versions
  .into_iter()
  .filter( | v | req.matches( v ) )
  .max()
}
```

**Step 3.2: Write Comprehensive Semver Tests**

Create `tests/inc/tool/semver_test.rs`:

```rust
#[ test ]
fn caret_requirement_matching()
{
  let req = parse_req( "^1.2.3" ).unwrap();

  assert!( matches( &req, &parse_version( "1.2.3" ).unwrap() ) );
  assert!( matches( &req, &parse_version( "1.2.4" ).unwrap() ) );
  assert!( matches( &req, &parse_version( "1.3.0" ).unwrap() ) );
  assert!( !matches( &req, &parse_version( "2.0.0" ).unwrap() ) );
  assert!( !matches( &req, &parse_version( "1.2.2" ).unwrap() ) );
}

#[ test ]
fn tilde_requirement_matching()
{
  let req = parse_req( "~1.2.3" ).unwrap();

  assert!( matches( &req, &parse_version( "1.2.3" ).unwrap() ) );
  assert!( matches( &req, &parse_version( "1.2.4" ).unwrap() ) );
  assert!( !matches( &req, &parse_version( "1.3.0" ).unwrap() ) );
  assert!( !matches( &req, &parse_version( "2.0.0" ).unwrap() ) );
}

// Test the original bug scenario
#[ test ]
fn tilde_breaks_on_minor_bump()
{
  let req = parse_req( "~2.36.0" ).unwrap();
  let old_version = parse_version( "2.36.0" ).unwrap();
  let new_version = parse_version( "2.37.0" ).unwrap();

  assert!( matches( &req, &old_version ) );
  assert!( !matches( &req, &new_version ) );  // THIS IS THE BUG!
}
```

### Verification

```bash
# Run semver tests
cargo test --test semver_test

# Verify level 1 passes
w3 .test level::1
```

### Deliverables

- `src/tool/semver_utils.rs` (utilities)
-`tests/inc/tool/semver_test.rs` (30+ test cases)

---

## INCREMENT 4: Dependency Staleness Detection (4 days)

### Goal

Implement core staleness detection algorithm.

### Input State

- Data structures exist
- Semver utilities ready
- No staleness detection logic

### Output State

- `detect_stale_dependencies()` function working
- Staleness detection integrated into workspace
- Tests passing for simple staleness

### Implementation Steps

**Step 4.1: Add Workspace Helper Methods**

Update `src/entity/workspace.rs`:

```rust
impl Workspace
{
  // ... existing methods ...

  /// Find package by name
  pub fn find_package( &self, name: &PackageName ) -> Option< WorkspacePackageRef >
  {
    self.packages().find( | p | p.name() == Some( name ) )
  }

  /// Get version of a workspace package
  pub fn version_of( &self, name: &PackageName ) -> Option< Version >
  {
    self.find_package( name ).and_then( | p | p.version() )
  }

  /// Find all packages that depend on the given package
  pub fn find_dependents( &self, name: &PackageName ) -> Vec< WorkspacePackageRef >
  {
    self
    .packages()
    .filter( | p |
    {
      p.dependencies( DependencyKind::Normal ).any( | d | &d.name == name )
      || p.dependencies( DependencyKind::Dev ).any( | d | &d.name == name )
      || p.dependencies( DependencyKind::Build ).any( | d | &d.name == name )
    })
    .collect()
  }
}
```

**Step 4.2: Implement Staleness Detection**

Create `src/entity/staleness.rs`:

```rust
use crate:: *;
use std::collections::{ HashMap, HashSet };

/// Detect packages with stale dependencies
pub fn detect_stale_dependencies
(
  workspace: &Workspace,
  already_publishing: &HashSet< PackageName >,
) -> HashMap< PackageName, Vec< StaleDependency > >
{
  let mut stale_map = HashMap::new();

  for package in workspace.packages()
  {
    let pkg_name = match package.name()
    {
      Some( name ) => name,
      None => continue,
    };

    // Skip if already marked for publishing
    if already_publishing.contains( &pkg_name )
    {
      continue;
    }

    let mut stale_deps = Vec::new();

    // Check all dependency kinds
    for dep_kind in [ DependencyKind::Normal, DependencyKind::Dev, DependencyKind::Build ]
    {
      for dep in package.dependencies( dep_kind )
      {
        // Only check workspace dependencies
        let workspace_version = match workspace.version_of( &dep.name )
        {
          Some( v ) => v,
          None => continue,  // External dependency, skip
        };

        // Check 1: Is dependency being published?
        if already_publishing.contains( &dep.name )
        {
          stale_deps.push( StaleDependency
          {
            name: dep.name.clone(),
            required: dep.version_req.clone(),
            workspace_version: workspace_version.clone(),
            reason: StaleReason::BeingPublished,
          });
          continue;
        }

        // Check 2: Version compatibility
        if !dep.version_req.matches( &workspace_version )
        {
          stale_deps.push( StaleDependency
          {
            name: dep.name.clone(),
            required: dep.version_req.clone(),
            workspace_version: workspace_version.clone(),
            reason: StaleReason::IncompatibleVersion,
          });
        }
      }
    }

    if !stale_deps.is_empty()
    {
      stale_map.insert( pkg_name, stale_deps );
    }
  }

  stale_map
}
```

**Step 4.3: Write Staleness Detection Tests**

Create `tests/inc/publish/dependency_staleness_test.rs`:

```rust
use willbe::*;

// Test fixture builder
fn build_test_workspace() -> Workspace
{
  // Build synthetic workspace with known dependencies
  todo!( "Implement workspace builder" )
}

#[ test ]
fn simple_stale_dependency()
{
  // Scenario: A depends on B ~1.0.0, B bumped to 1.1.0
  let workspace = build_test_workspace();
  let publishing = hashset![ "B".into() ];

  let stale = detect_stale_dependencies( &workspace, &publishing );

  assert!( stale.contains_key( &"A".into() ) );
  let stale_deps = &stale[ &"A".into() ];
  assert_eq!( stale_deps.len(), 1 );
  assert_eq!( stale_deps[ 0 ].name, "B".into() );
  assert_eq!( stale_deps[ 0 ].reason, StaleReason::BeingPublished );
}

#[ test ]
fn incompatible_version_stale()
{
  // Scenario: A depends on B ~1.0.0, workspace has B 1.1.0
  let workspace = build_test_workspace();
  let publishing = hashset![];

  let stale = detect_stale_dependencies( &workspace, &publishing );

  assert!( stale.contains_key( &"A".into() ) );
  let stale_deps = &stale[ &"A".into() ];
  assert_eq!( stale_deps[ 0 ].reason, StaleReason::IncompatibleVersion );
}

#[ test ]
fn compatible_version_not_stale()
{
  // Scenario: A depends on B ^1.0.0, workspace has B 1.0.1
  let workspace = build_test_workspace();
  let publishing = hashset![];

  let stale = detect_stale_dependencies( &workspace, &publishing );

  assert!( !stale.contains_key( &"A".into() ) );
}

// MRE test for original bug
// test_kind: bug_reproducer(issue-willbe-staleness-001)
#[ test ]
fn willbe_wca_former_conflict()
{
  // This test reproduces the exact scenario from the bug report
  //
  // ## Root Cause
  // willbe algorithm failed to detect that wca needed republishing
  // when former (its dependency) was bumped from 2.36.0 to 2.37.0.
  // wca's requirement ~2.36.0 became incompatible with workspace version 2.37.0.
  //
  // ## Why Not Caught Initially
  // Algorithm only checked for local code changes and version bumps.
  // Dependency staleness was never implemented.
  //
  // ## Fix Applied
  // Added dependency staleness detection in Phase 2 of publishing algorithm.
  // Detects when workspace version doesn't satisfy dependency requirement.
  //
  // ## Prevention
  // All packages now checked for stale dependencies before publishing.
  // Transitive closure ensures all affected packages republished.
  //
  // ## Pitfall to Avoid
  // Never assume workspace dependencies are always compatible.
  // Always validate semver requirements against workspace versions.

  let workspace = build_workspace_from_manifest( "tests/fixtures/willbe_wca_former.toml" );

  // Initial state: former 2.36.0, wca 0.36.0, willbe 0.28.0
  // wca depends on former ~2.36.0
  // willbe depends on wca ~0.36.0, former ~2.36.0

  // Simulate: former bumped to 2.37.0
  let publishing = hashset![ "former".into() ];

  // Should detect wca as stale
  let stale = detect_stale_dependencies( &workspace, &publishing );

  assert!(
    stale.contains_key( &"wca".into() ),
    "wca should be detected as stale when former is being published"
  );

  let wca_stale_deps = &stale[ &"wca".into() ];
  assert_eq!( wca_stale_deps.len(), 1 );
  assert_eq!( wca_stale_deps[ 0 ].name, "former".into() );
}
```

### Verification

```bash
# Run staleness tests
cargo test --test dependency_staleness_test

# Verify MRE test passes
cargo test willbe_wca_former_conflict

# Level 1 tests
w3 .test level::1
```

### Deliverables

- `src/entity/staleness.rs` (detection logic)
- ✅ Updated `src/entity/workspace.rs` (helper methods)
-`tests/inc/publish/dependency_staleness_test.rs` (10+ tests)
- ✅ MRE test for original bug (bug_reproducer marker)

---

## INCREMENT 5: Transitive Closure Computation (4 days)

### Goal

Implement cascade effect detection and transitive closure computation.

### Input State

- Staleness detection works
- No cascade/closure logic
- Can detect immediate stale deps only

### Output State

- Transitive closure algorithm implemented
- Cascade effects tracked
- Tests passing for multi-level cascades

### Implementation Steps

**Step 5.1: Implement Closure Computation**

Add to `src/entity/staleness.rs`:

```rust
/// Compute transitive closure of packages to publish
pub fn compute_publish_closure
(
  workspace: &Workspace,
  initial: HashSet< PackageName >,
) -> HashMap< PackageName, Vec< PublishReason > >
{
  let mut result = HashMap::new();

  // Initialize with initial set
  for pkg_name in &initial
  {
    result.insert( pkg_name.clone(), vec![ PublishReason::LocalChanges ] );
  }

  let mut changed = true;
  let mut iteration = 0;
  let max_iterations = workspace.packages().count() * 2;

  while changed && iteration < max_iterations
  {
    changed = false;
    let current_publishing: HashSet< _ > = result.keys().cloned().collect();
    let old_size = result.len();

    // Find stale dependencies
    let stale = detect_stale_dependencies( workspace, &current_publishing );

    for ( pkg_name, stale_deps ) in stale
    {
      if !result.contains_key( &pkg_name )
      {
        result.insert(
          pkg_name,
          vec![ PublishReason::StaleDependencies { stale_deps } ],
        );
        changed = true;
      }
    }

    // Find cascade dependents
    for pkg_name in current_publishing.clone()
    {
      for dependent in workspace.find_dependents( &pkg_name )
      {
        let dep_name = dependent.name().unwrap();
        if !result.contains_key( &dep_name )
        {
          result.insert(
            dep_name,
            vec![ PublishReason::CascadeEffect
            {
              triggered_by: vec![ pkg_name.clone() ],
            }],
          );
          changed = true;
        }
      }
    }

    iteration += 1;

    if result.len() == old_size
    {
      break;  // Converged
    }
  }

  if iteration >= max_iterations
  {
    panic!( "Closure computation did not converge after {} iterations", max_iterations );
  }

  result
}
```

**Step 5.2: Write Cascade Tests**

Create `tests/inc/publish/cascade_test.rs`:

```rust
#[ test ]
fn linear_cascade()
{
  // A → B → C → D
  // D has local changes
  // Should cascade: D, C, B, A

  let workspace = build_linear_dependency_workspace();
  let initial = hashset![ "D".into() ];

  let closure = compute_publish_closure( &workspace, initial );

  assert_eq!( closure.len(), 4 );
  assert!( closure.contains_key( &"D".into() ) );
  assert!( closure.contains_key( &"C".into() ) );
  assert!( closure.contains_key( &"B".into() ) );
  assert!( closure.contains_key( &"A".into() ) );

  // Verify reasons
  assert!( closure[ &"D" ].iter().any( | r | r.is_local_change() ) );
  assert!( closure[ &"C" ].iter().any( | r | r.is_cascade() ) );
  assert!( closure[ &"B" ].iter().any( | r | r.is_cascade() ) );
  assert!( closure[ &"A" ].iter().any( | r | r.is_cascade() ) );
}

#[ test ]
fn diamond_dependency()
{
  //     A
  //    / \
  //   B   C
  //    \ /
  //     D
  // D has local changes

  let workspace = build_diamond_dependency_workspace();
  let initial = hashset![ "D".into() ];

  let closure = compute_publish_closure( &workspace, initial );

  assert_eq!( closure.len(), 4 );
  assert!( closure.contains_key( &"D".into() ) );
  assert!( closure.contains_key( &"C".into() ) );
  assert!( closure.contains_key( &"B".into() ) );
  assert!( closure.contains_key( &"A".into() ) );
}

#[ test ]
fn no_cascade_for_compatible_versions()
{
  // A depends on B ^1.0.0
  // B bumped 1.0.0 → 1.0.1 (compatible)

  let workspace = build_compatible_version_workspace();
  let initial = hashset![ "B".into() ];

  let closure = compute_publish_closure( &workspace, initial );

  // Only B should be in closure (A compatible)
  assert_eq!( closure.len(), 1 );
  assert!( closure.contains_key( &"B".into() ) );
  assert!( !closure.contains_key( &"A".into() ) );
}
```

### Verification

```bash
# Run cascade tests
cargo test --test cascade_test

# Full test suite
w3 .test level::1
```

### Deliverables

- `compute_publish_closure()` function
-`tests/inc/publish/cascade_test.rs` (10+ tests)
- ✅ Convergence guarantees (max iterations)

---

## INCREMENT 6: Integration with Publish Plan (3 days)

### Goal

Integrate staleness detection into main publish plan builder.

### Input State

- Staleness detection works standalone
- Closure computation works standalone
- Not integrated into `PublishPlan::build()`

### Output State

- Enhanced `build_publish_plan()` using all phases
- Publish reasons tracked for all packages
- Integration tests passing

### Implementation Steps

**Step 6.1: Refactor `build_publish_plan()`**

Update `src/entity/publish.rs`:

```rust
impl PublishPlanFormer
{
  pub fn build( self ) -> PublishPlan
  {
    let workspace = /* get workspace */;

    // Phase 1: Initial detection
    let initial = self.detect_initial_packages( &workspace );

    // Phase 2 & 3: Staleness + Closure
    let all_packages = staleness::compute_publish_closure( &workspace, initial );

    // Phase 4: Topological sort
    let ordered = self.topological_sort( &workspace, &all_packages );

    // Phase 5: Build instructions
    let mut plans = Vec::new();
    for pkg_name in ordered
    {
      let reasons = all_packages[ &pkg_name ].clone();
      let instruction = self.build_instruction( &workspace, pkg_name, reasons );
      plans.push( instruction );
    }

    PublishPlan
    {
      workspace_dir: self.workspace_dir.unwrap(),
      base_temp_dir: self.base_temp_dir,
      channel: self.channel.unwrap_or_default(),
      dry: self.dry.unwrap_or( true ),
      roots: self.determine_roots( &plans ),
      plans,
    }
  }

  fn detect_initial_packages( &self, workspace: &Workspace ) -> HashSet< PackageName >
  {
    let mut result = HashSet::new();

    for package in workspace.packages()
    {
      // Check for local changes
      if self.has_local_changes( &package )
      {
        result.insert( package.name().unwrap() );
        continue;
      }

      // Check for version bump
      if self.version_bumped( &package )
      {
        result.insert( package.name().unwrap() );
      }
    }

    result
  }

  fn topological_sort
  (
    &self,
    workspace: &Workspace,
    packages: &HashMap< PackageName, Vec< PublishReason > >,
  ) -> Vec< PackageName >
  {
    // Kahn's algorithm
    // ... existing implementation ...
  }
}
```

**Step 6.2: Update Display Logic**

Update `src/action/publish.rs` to show reasons:

```rust
pub fn publish( /* ... */ ) -> Result< (), Error >
{
  let plan = build_publish_plan( /* ... */ );

  println!( "The following packages are pending for publication:" );
  for ( idx, instruction ) in plan.plans.iter().enumerate()
  {
    println!(
      "[{}] {} ({} -> {})",
      idx,
      instruction.package_name,
      instruction.old_version,
      instruction.new_version
    );

    // NEW: Show reasons
    for reason in &instruction.reasons
    {
      println!( "    Reason: {}", reason.description() );
    }
  }

  // ... rest of publish logic ...
}
```

**Step 6.3: Write Integration Tests**

Create `tests/inc/publish/integration_test.rs`:

```rust
#[ test ]
fn full_publish_plan_with_staleness()
{
  let workspace = build_test_workspace();
  let plan = build_publish_plan( workspace );

  // Verify all affected packages included
  assert!( plan.plans.iter().any( | p | p.package_name == "former" ) );
  assert!( plan.plans.iter().any( | p | p.package_name == "wca" ) );
  assert!( plan.plans.iter().any( | p | p.package_name == "willbe" ) );

  // Verify reasons
  let wca_plan = plan.plans.iter().find( | p | p.package_name == "wca" ).unwrap();
  assert!( wca_plan.reasons.iter().any( | r | r.is_stale() ) );

  let willbe_plan = plan.plans.iter().find( | p | p.package_name == "willbe" ).unwrap();
  assert!( willbe_plan.reasons.iter().any( | r | r.is_cascade() ) );
}
```

### Verification

```bash
# Integration tests
cargo test --test integration_test

# Full test suite
w3 .test level::3
```

### Deliverables

- ✅ Refactored `build_publish_plan()`
- ✅ Enhanced display with reasons
-`tests/inc/publish/integration_test.rs` (5+ tests)

---

## INCREMENT 7: Bug Documentation (2 days)

### Goal

Document the bug fix following rulebook standards.

### Input State

- Fix implemented and tested
- No documentation

### Output State

- Complete bug documentation (5 sections + 3 fields)
- Module-level Known Pitfalls section
- Architecture documentation updated

### Implementation Steps

**Step 7.1: Add Source Code Fix Comments**

In `src/entity/staleness.rs` at the top of `detect_stale_dependencies()`:

```rust
// Fix(issue-willbe-staleness-001): Add dependency staleness detection
// Root cause: Algorithm only checked local changes, never validated dependency versions
// Pitfall: Always verify workspace dependency versions satisfy dependent requirements
pub fn detect_stale_dependencies
(
  workspace: &Workspace,
  already_publishing: &HashSet< PackageName >,
) -> HashMap< PackageName, Vec< StaleDependency > >
{
  // ... implementation ...
}
```

**Step 7.2: Add Module-Level Known Pitfalls**

In `src/entity/publish.rs`:

```rust
//! Publishing infrastructure for multi-package workspaces.
//!
//! ## Known Pitfalls
//!
//! ### Dependency Staleness
//!
//! Never assume workspace dependencies are always compatible with dependent packages.
//! When a workspace package is bumped, all dependents must be checked for version
//! requirement compatibility.
//!
//! Root cause (issue-willbe-staleness-001): Original algorithm only detected local
//! code changes and explicit version bumps. It failed to detect when a package's
//! dependency requirements became incompatible with workspace versions.
//!
//! Prevention: Always run dependency staleness detection before computing publish plan.
//! Use `detect_stale_dependencies()` to find packages with incompatible requirements.
//!
//! ```rust
//! // ✅ CORRECT: Check staleness before publishing
//! let initial = detect_local_changes( workspace );
//! let with_stale = detect_stale_dependencies( workspace, &initial );
//! let full_closure = compute_publish_closure( workspace, with_stale );
//!
//! // ❌ FORBIDDEN: Only check local changes
//! let to_publish = detect_local_changes( workspace );  // MISSES STALE DEPS
//! ```
```

**Step 7.3: Update Architecture Documentation**

Update `spec/architecture.md` with:
- New algorithm flow diagram
- Staleness detection explanation
- Cascade effect mechanics
- Performance characteristics

### Verification

```bash
# Documentation builds
cargo doc --no-deps --all-features

# Check Known Pitfalls section
cargo doc --open
# Navigate to entity::publish module docs
```

### Deliverables

- ✅ Source code fix comments (3 fields)
- ✅ Module-level Known Pitfalls section
- ✅ Updated architecture documentation

---

## INCREMENT 8: Performance Optimization (2 days)

### Goal

Optimize algorithm for large workspaces.

### Input State

- Algorithm works correctly
- May be slow on large workspaces (100+ packages)

### Output State

- Optimized dependency lookups
- Cached version resolutions
- Performance tests passing

### Implementation Steps

**Step 8.1: Add Caching Layer**

```rust
struct WorkspaceCache
{
  version_cache: HashMap< PackageName, Version >,
  dependents_cache: HashMap< PackageName, Vec< PackageName > >,
}

impl WorkspaceCache
{
  fn new( workspace: &Workspace ) -> Self
  {
    // Pre-compute all versions and dependents
    // ...
  }
}
```

**Step 8.2: Optimize Closure Computation**

- Early termination when no changes
- Skip packages already in closure
- Batch dependency lookups

**Step 8.3: Write Performance Tests**

```rust
#[ test ]
#[ ignore ]  // Run with --ignored
fn large_workspace_performance()
{
  let workspace = build_large_workspace( 100 );  // 100 packages
  let initial = hashset![ "pkg_50".into() ];

  let start = Instant::now();
  let closure = compute_publish_closure( &workspace, initial );
  let duration = start.elapsed();

  assert!( duration < Duration::from_secs( 10 ) );
}
```

### Verification

```bash
# Performance tests
cargo test --ignored

# Benchmark
cargo bench
```

### Deliverables

- ✅ Caching layer implemented
- ✅ Performance tests (3+ tests)
-<10s for 100 packages

---

## INCREMENT 9: Final Verification & Deployment (3 days)

### Goal

Complete verification and prepare for deployment.

### Input State

- All features implemented
- All tests passing locally

### Output State

- All level 5 tests passing
- Documentation complete
- Ready for merge

### Implementation Steps

**Step 9.1: Full Test Suite**

```bash
# Level 5 verification
w3 .test level::5

# Manual testing
cd /home/user1/pro/lib/wTools/module/core/wca
will .publish dry:1  # Should detect staleness

cd ../willbe
will .publish dry:1  # Should show cascade effects
```

**Step 9.2: Update Changelog**

Add to `changelog.md`:

```markdown
## [0.29.0] - 2025-11-XX

### Added
- Dependency staleness detection in publishing algorithm
- Cascade effect tracking for transitive dependencies
- Enhanced publish plan with reasons display

### Fixed
- [CRITICAL] Publishing fails with version conflicts when dependencies bumped (#issue-willbe-staleness-001)
- Missing detection of packages needing republish due to stale deps
- Incomplete transitive closure in publish sequence

### Changed
- PublishPlan now includes PublishReason for each package
- Display shows why each package is being published
```

**Step 9.3: Review Checklist**

- [ ] All tests pass (level 5)
- [ ] Documentation complete
- [ ] Bug documented (5 sections + 3 fields)
- [ ] No breaking API changes
- [ ] Performance acceptable
- [ ] Manual testing successful
- [ ] Changelog updated

### Deliverables

- ✅ All tests passing
- ✅ Documentation complete
- ✅ Ready for deployment

---

## Total Timeline

| Increment | Duration | Cumulative |
|-----------|----------|------------|
| 1. Setup | 2 days | 2 days |
| 2. Data Structures | 3 days | 5 days |
| 3. Semver Utils | 2 days | 7 days |
| 4. Staleness Detection | 4 days | 11 days |
| 5. Closure Computation | 4 days | 15 days |
| 6. Integration | 3 days | 18 days |
| 7. Documentation | 2 days | 20 days |
| 8. Performance | 2 days | 22 days |
| 9. Final Verification | 3 days | 25 days |

**Total: 25 days (5 weeks)**

---

## Risk Mitigation

### Risk: Performance Issues

**Mitigation:** Increment 8 dedicated to optimization

### Risk: Breaking Changes

**Mitigation:** Maintain backward compatibility, add feature flag

### Risk: Complex Testing

**Mitigation:** Test utilities built in Increment 1, reused throughout

---

## Success Metrics

- ✅ Original bug scenario resolved
- ✅ Zero version conflicts in publishing
- ✅ <10s performance for 100 packages
- ✅ >90% test coverage
- ✅ Complete documentation