prizmkit 1.1.167 → 1.1.170

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,6 +38,7 @@ from utils import (
38
38
  read_checkpoint_cursor,
39
39
  dependency_rank_map,
40
40
  causal_reset_selection,
41
+ orphaned_auto_skipped_ids,
41
42
  )
42
43
 
43
44
 
@@ -747,11 +748,55 @@ def auto_skip_blocked_features(feature_list_path, state_dir, failed_feature_id):
747
748
  return skipped_info
748
749
 
749
750
 
751
+ def reconcile_orphaned_auto_skipped_features(feature_list_path, state_dir):
752
+ """Restore auto-skipped features that have no current blocking root."""
753
+ data, err = load_json_file(feature_list_path)
754
+ if err:
755
+ raise RuntimeError("Cannot load feature list for orphan recovery: {}".format(err))
756
+ features = data.get("features", [])
757
+ orphan_ids = orphaned_auto_skipped_ids(
758
+ features,
759
+ blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
760
+ item_label="Feature",
761
+ )
762
+ if not orphan_ids:
763
+ return []
764
+
765
+ orphan_set = set(orphan_ids)
766
+ for feature in features:
767
+ if isinstance(feature, dict) and feature.get("id") in orphan_set:
768
+ feature["status"] = "pending"
769
+ err = write_json_file(feature_list_path, data)
770
+ if err:
771
+ raise RuntimeError("Failed to recover orphaned features: {}".format(err))
772
+
773
+ for feature_id in orphan_ids:
774
+ fs = load_feature_status(state_dir, feature_id)
775
+ fs["updated_at"] = now_iso()
776
+ err = save_feature_status(state_dir, feature_id, fs)
777
+ if err:
778
+ raise RuntimeError("Failed to save recovered feature status: {}".format(err))
779
+
780
+ print(
781
+ "[auto-skip] recovered {} orphaned feature(s): {}".format(
782
+ len(orphan_ids), ", ".join(orphan_ids)
783
+ ),
784
+ file=sys.stderr,
785
+ )
786
+ return list(orphan_ids)
787
+
788
+
750
789
  # ---------------------------------------------------------------------------
751
790
  # Action: get_next
752
791
  # ---------------------------------------------------------------------------
753
792
 
754
- def action_get_next(feature_list_data, state_dir, feature_filter=None, project_root=None):
793
+ def action_get_next(
794
+ feature_list_data,
795
+ state_dir,
796
+ feature_filter=None,
797
+ project_root=None,
798
+ feature_list_path=None,
799
+ ):
755
800
  """Find the next feature to process.
756
801
 
757
802
  Priority logic:
@@ -761,6 +806,23 @@ def action_get_next(feature_list_data, state_dir, feature_filter=None, project_r
761
806
  4. Prefer in_progress features over pending ones (interrupted session resume)
762
807
  5. Among eligible features, pick highest priority (high > medium > low)
763
808
  """
809
+ if feature_list_path:
810
+ try:
811
+ recovered = reconcile_orphaned_auto_skipped_features(
812
+ feature_list_path, state_dir
813
+ )
814
+ except ValueError:
815
+ print("PIPELINE_BLOCKED")
816
+ return
817
+ except RuntimeError as exc:
818
+ error_out(str(exc))
819
+ return
820
+ if recovered:
821
+ feature_list_data, err = load_json_file(feature_list_path)
822
+ if err:
823
+ error_out("Cannot reload feature list after orphan recovery: {}".format(err))
824
+ return
825
+
764
826
  features = feature_list_data.get("features", [])
765
827
  if not features:
766
828
  print("PIPELINE_COMPLETE")
@@ -945,6 +1007,13 @@ def action_update(args, feature_list_path, state_dir):
945
1007
  and fs.get("last_session_id") == session_id
946
1008
  )
947
1009
  if already_completed and not pending_continuation_metadata and (same_session_already_recorded or not session_id):
1010
+ try:
1011
+ recovered_auto_skipped = reconcile_orphaned_auto_skipped_features(
1012
+ feature_list_path, state_dir
1013
+ )
1014
+ except (ValueError, RuntimeError) as exc:
1015
+ error_out(str(exc))
1016
+ return
948
1017
  summary = {
949
1018
  "action": "update",
950
1019
  "feature_id": feature_id,
@@ -957,6 +1026,8 @@ def action_update(args, feature_list_path, state_dir):
957
1026
  "updated_at": fs.get("updated_at"),
958
1027
  "no_op": True,
959
1028
  }
1029
+ if recovered_auto_skipped:
1030
+ summary["recovered_auto_skipped"] = recovered_auto_skipped
960
1031
  print(json.dumps(summary, indent=2, ensure_ascii=False))
961
1032
  return
962
1033
 
@@ -1118,12 +1189,22 @@ def action_update(args, feature_list_path, state_dir):
1118
1189
  error_out("Failed to save feature status: {}".format(err))
1119
1190
  return
1120
1191
 
1121
- # Auto-skip downstream features when this feature is marked as failed or skipped
1192
+ # Auto-skip downstream features for current blockers; otherwise converge
1193
+ # descendants whose complete transitive blocker set is now empty.
1122
1194
  auto_skipped_features = []
1123
- if new_status in ("failed", "skipped"):
1195
+ recovered_auto_skipped = []
1196
+ if new_status in RESET_BLOCKING_ROOT_STATUSES:
1124
1197
  auto_skipped_features = auto_skip_blocked_features(
1125
1198
  feature_list_path, state_dir, feature_id
1126
1199
  )
1200
+ else:
1201
+ try:
1202
+ recovered_auto_skipped = reconcile_orphaned_auto_skipped_features(
1203
+ feature_list_path, state_dir
1204
+ )
1205
+ except (ValueError, RuntimeError) as exc:
1206
+ error_out(str(exc))
1207
+ return
1127
1208
 
1128
1209
  summary = {
1129
1210
  "action": "update",
@@ -1139,6 +1220,8 @@ def action_update(args, feature_list_path, state_dir):
1139
1220
  }
1140
1221
  if auto_skipped_features:
1141
1222
  summary["auto_skipped"] = [info["feature_id"] for info in auto_skipped_features]
1223
+ if recovered_auto_skipped:
1224
+ summary["recovered_auto_skipped"] = recovered_auto_skipped
1142
1225
  if session_status in ("commit_missing", "docs_missing", "merge_conflict"):
1143
1226
  summary["degraded_reason"] = session_status
1144
1227
  summary["restart_policy"] = "finalization_retry"
@@ -1346,18 +1429,35 @@ def action_status(feature_list_data, state_dir, feature_filter=None, project_roo
1346
1429
  as ETA, degraded reasons, and live checkpoint phase is read from status.json
1347
1430
  and workflow-checkpoint.json.
1348
1431
  """
1349
- features = feature_list_data.get("features", [])
1432
+ all_features = feature_list_data.get("features", [])
1350
1433
  project_name = feature_list_data.get("project_name", "Unknown")
1351
1434
  project_root = os.path.abspath(project_root) if project_root else _default_project_root()
1352
1435
 
1353
- # Apply feature filter
1436
+ # Dependency truth always comes from the complete plan, even when rendering
1437
+ # only a filtered subset.
1438
+ status_map = {
1439
+ feature["id"]: feature.get("status", "pending")
1440
+ for feature in all_features
1441
+ if isinstance(feature, dict) and feature.get("id")
1442
+ }
1443
+ try:
1444
+ orphaned_ids = set(orphaned_auto_skipped_ids(
1445
+ all_features,
1446
+ blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
1447
+ item_label="Feature",
1448
+ ))
1449
+ except ValueError:
1450
+ orphaned_ids = set()
1451
+
1452
+ features = all_features
1354
1453
  if feature_filter is not None:
1355
1454
  features = [
1356
- f for f in features
1357
- if isinstance(f, dict) and f.get("id") in feature_filter
1455
+ feature
1456
+ for feature in features
1457
+ if isinstance(feature, dict) and feature.get("id") in feature_filter
1358
1458
  ]
1359
1459
 
1360
- # Gather status info
1460
+ # Gather status info for the rendered subset.
1361
1461
  counts = {
1362
1462
  "completed": 0,
1363
1463
  "in_progress": 0,
@@ -1368,16 +1468,6 @@ def action_status(feature_list_data, state_dir, feature_filter=None, project_roo
1368
1468
  }
1369
1469
  feature_lines = []
1370
1470
 
1371
- # Build status map from .prizmkit/plans/feature-list.json only
1372
- status_map = {}
1373
- for feature in features:
1374
- if not isinstance(feature, dict):
1375
- continue
1376
- fid = feature.get("id")
1377
- if not fid:
1378
- continue
1379
- status_map[fid] = feature.get("status", "pending")
1380
-
1381
1471
  # Build degraded_reason map from status.json (internal pipeline state)
1382
1472
  degraded_reason_map = {}
1383
1473
  for feature in features:
@@ -1457,13 +1547,16 @@ def action_status(feature_list_data, state_dir, feature_filter=None, project_roo
1457
1547
  elif fstatus == "in_progress" and resume_phase is not None:
1458
1548
  detail = " (CP-F-{})".format(resume_phase)
1459
1549
  elif fstatus == "auto_skipped":
1460
- deps = feature.get("dependencies", [])
1461
- blockers = [
1462
- d for d in deps
1463
- if status_map.get(d, "pending") in ("failed", "skipped", "auto_skipped")
1464
- ]
1465
- if blockers:
1466
- detail = " (auto-skipped: blocked by {})".format(", ".join(blockers))
1550
+ if fid in orphaned_ids:
1551
+ detail = " (orphaned: no blocking dependency)"
1552
+ else:
1553
+ deps = feature.get("dependencies", [])
1554
+ blockers = [
1555
+ d for d in deps
1556
+ if status_map.get(d, "pending") in ("failed", "skipped", "auto_skipped")
1557
+ ]
1558
+ if blockers:
1559
+ detail = " (auto-skipped: blocked by {})".format(", ".join(blockers))
1467
1560
  elif fstatus == "failed" and degraded_reason:
1468
1561
  detail = " (last failure: {})".format(degraded_reason)
1469
1562
 
@@ -1588,6 +1681,14 @@ def action_start(args, feature_list_path, state_dir):
1588
1681
  error_out("Failed to update .prizmkit/plans/feature-list.json: {}".format(err))
1589
1682
  return
1590
1683
 
1684
+ try:
1685
+ recovered_auto_skipped = reconcile_orphaned_auto_skipped_features(
1686
+ feature_list_path, state_dir
1687
+ )
1688
+ except (ValueError, RuntimeError) as exc:
1689
+ error_out(str(exc))
1690
+ return
1691
+
1591
1692
  result = {
1592
1693
  "action": "start",
1593
1694
  "feature_id": feature_id,
@@ -1597,6 +1698,8 @@ def action_start(args, feature_list_path, state_dir):
1597
1698
  "infra_error_count": fs.get("infra_error_count", 0),
1598
1699
  "updated_at": fs["updated_at"],
1599
1700
  }
1701
+ if recovered_auto_skipped:
1702
+ result["recovered_auto_skipped"] = recovered_auto_skipped
1600
1703
  print(json.dumps(result, indent=2, ensure_ascii=False))
1601
1704
 
1602
1705
 
@@ -1896,7 +1999,13 @@ def main():
1896
1999
 
1897
2000
  # Dispatch action
1898
2001
  if args.action == "get_next":
1899
- action_get_next(feature_list_data, args.state_dir, feature_filter, args.project_root)
2002
+ action_get_next(
2003
+ feature_list_data,
2004
+ args.state_dir,
2005
+ feature_filter,
2006
+ args.project_root,
2007
+ args.feature_list,
2008
+ )
1900
2009
  elif args.action == "start":
1901
2010
  action_start(args, args.feature_list, args.state_dir)
1902
2011
  elif args.action == "update":
@@ -35,6 +35,7 @@ from utils import (
35
35
  read_checkpoint_cursor,
36
36
  dependency_rank_map,
37
37
  causal_reset_selection,
38
+ orphaned_auto_skipped_ids,
38
39
  )
39
40
 
40
41
 
@@ -397,7 +398,12 @@ def _dependencies_met(refactor, completed_set):
397
398
  return all(dep in completed_set for dep in deps)
398
399
 
399
400
 
400
- def action_get_next(refactor_list_data, state_dir, project_root=None):
401
+ def action_get_next(
402
+ refactor_list_data,
403
+ state_dir,
404
+ project_root=None,
405
+ refactor_list_path=None,
406
+ ):
401
407
  """Find the next refactor to process.
402
408
 
403
409
  Priority logic:
@@ -406,6 +412,23 @@ def action_get_next(refactor_list_data, state_dir, project_root=None):
406
412
  3. Prefer in_progress refactors (interrupted session resume) over pending
407
413
  4. Within each status class, use stable topological list order
408
414
  """
415
+ if refactor_list_path:
416
+ try:
417
+ recovered = reconcile_orphaned_auto_skipped_refactors(
418
+ refactor_list_path, state_dir
419
+ )
420
+ except ValueError:
421
+ print("PIPELINE_BLOCKED")
422
+ return
423
+ except RuntimeError as exc:
424
+ error_out(str(exc))
425
+ return
426
+ if recovered:
427
+ refactor_list_data, err = load_json_file(refactor_list_path)
428
+ if err:
429
+ error_out("Cannot reload refactor list after orphan recovery: {}".format(err))
430
+ return
431
+
409
432
  refactors = refactor_list_data.get("refactors", [])
410
433
  if not refactors:
411
434
  print("PIPELINE_COMPLETE")
@@ -689,12 +712,22 @@ def action_update(args, refactor_list_path, state_dir):
689
712
  error_out("Failed to save refactor status: {}".format(err))
690
713
  return
691
714
 
692
- # Auto-skip downstream refactors when this refactor is marked as failed or skipped
715
+ # Auto-skip downstream refactors for current blockers; otherwise converge
716
+ # descendants whose complete transitive blocker set is now empty.
693
717
  auto_skipped_refactors = []
694
- if new_status in ("failed", "skipped"):
718
+ recovered_auto_skipped = []
719
+ if new_status in RESET_BLOCKING_ROOT_STATUSES:
695
720
  auto_skipped_refactors = auto_skip_blocked_refactors(
696
721
  refactor_list_path, state_dir, refactor_id
697
722
  )
723
+ else:
724
+ try:
725
+ recovered_auto_skipped = reconcile_orphaned_auto_skipped_refactors(
726
+ refactor_list_path, state_dir
727
+ )
728
+ except (ValueError, RuntimeError) as exc:
729
+ error_out(str(exc))
730
+ return
698
731
 
699
732
  summary = {
700
733
  "action": "update",
@@ -710,6 +743,8 @@ def action_update(args, refactor_list_path, state_dir):
710
743
  }
711
744
  if auto_skipped_refactors:
712
745
  summary["auto_skipped"] = [info["refactor_id"] for info in auto_skipped_refactors]
746
+ if recovered_auto_skipped:
747
+ summary["recovered_auto_skipped"] = recovered_auto_skipped
713
748
  if session_status in ("commit_missing", "docs_missing", "merge_conflict"):
714
749
  summary["degraded_reason"] = session_status
715
750
  summary["restart_policy"] = "finalization_retry"
@@ -961,6 +996,44 @@ def auto_skip_blocked_refactors(refactor_list_path, state_dir, failed_refactor_i
961
996
  return skipped_info
962
997
 
963
998
 
999
+ def reconcile_orphaned_auto_skipped_refactors(refactor_list_path, state_dir):
1000
+ """Restore auto-skipped refactors that have no current blocking root."""
1001
+ data, err = load_json_file(refactor_list_path)
1002
+ if err:
1003
+ raise RuntimeError("Cannot load refactor list for orphan recovery: {}".format(err))
1004
+ refactors = data.get("refactors", [])
1005
+ orphan_ids = orphaned_auto_skipped_ids(
1006
+ refactors,
1007
+ blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
1008
+ item_label="Refactor",
1009
+ )
1010
+ if not orphan_ids:
1011
+ return []
1012
+
1013
+ orphan_set = set(orphan_ids)
1014
+ for refactor in refactors:
1015
+ if isinstance(refactor, dict) and refactor.get("id") in orphan_set:
1016
+ refactor["status"] = "pending"
1017
+ err = write_json_file(refactor_list_path, data)
1018
+ if err:
1019
+ raise RuntimeError("Failed to recover orphaned refactors: {}".format(err))
1020
+
1021
+ for refactor_id in orphan_ids:
1022
+ rs = load_refactor_status(state_dir, refactor_id)
1023
+ rs["updated_at"] = now_iso()
1024
+ err = save_refactor_status(state_dir, refactor_id, rs)
1025
+ if err:
1026
+ raise RuntimeError("Failed to save recovered refactor status: {}".format(err))
1027
+
1028
+ print(
1029
+ "[auto-skip] recovered {} orphaned refactor(s): {}".format(
1030
+ len(orphan_ids), ", ".join(orphan_ids)
1031
+ ),
1032
+ file=sys.stderr,
1033
+ )
1034
+ return list(orphan_ids)
1035
+
1036
+
964
1037
  # ---------------------------------------------------------------------------
965
1038
  # Action: status
966
1039
  # ---------------------------------------------------------------------------
@@ -998,6 +1071,14 @@ def action_status(refactor_list_data, state_dir, project_root=None):
998
1071
  project_root = os.path.abspath(project_root) if project_root else _default_project_root()
999
1072
 
1000
1073
  counts = {"completed": 0, "in_progress": 0, "failed": 0, "pending": 0, "skipped": 0, "auto_skipped": 0}
1074
+ try:
1075
+ orphaned_ids = set(orphaned_auto_skipped_ids(
1076
+ refactors,
1077
+ blocking_root_statuses=RESET_BLOCKING_ROOT_STATUSES,
1078
+ item_label="Refactor",
1079
+ ))
1080
+ except ValueError:
1081
+ orphaned_ids = set()
1001
1082
  refactor_lines = []
1002
1083
 
1003
1084
  for r in refactors:
@@ -1055,6 +1136,8 @@ def action_status(refactor_list_data, state_dir, project_root=None):
1055
1136
  detail = " ({})".format(", ".join(parts))
1056
1137
  elif rstatus == "failed":
1057
1138
  detail = " (failed after {} retries)".format(retry_count)
1139
+ elif rstatus == "auto_skipped" and rid in orphaned_ids:
1140
+ detail = " (orphaned: no blocking dependency)"
1058
1141
 
1059
1142
  # Colorize title based on status
1060
1143
  if rstatus == "completed":
@@ -1283,6 +1366,14 @@ def action_start(args, refactor_list_path, state_dir):
1283
1366
  error_out("Failed to update .prizmkit/plans/refactor-list.json: {}".format(err))
1284
1367
  return
1285
1368
 
1369
+ try:
1370
+ recovered_auto_skipped = reconcile_orphaned_auto_skipped_refactors(
1371
+ refactor_list_path, state_dir
1372
+ )
1373
+ except (ValueError, RuntimeError) as exc:
1374
+ error_out(str(exc))
1375
+ return
1376
+
1286
1377
  result = {
1287
1378
  "action": "start",
1288
1379
  "refactor_id": refactor_id,
@@ -1292,6 +1383,8 @@ def action_start(args, refactor_list_path, state_dir):
1292
1383
  "infra_error_count": rs.get("infra_error_count", 0),
1293
1384
  "updated_at": rs["updated_at"],
1294
1385
  }
1386
+ if recovered_auto_skipped:
1387
+ result["recovered_auto_skipped"] = recovered_auto_skipped
1295
1388
  print(json.dumps(result, indent=2, ensure_ascii=False))
1296
1389
 
1297
1390
 
@@ -1389,7 +1482,12 @@ def main():
1389
1482
  error_out("Cannot load refactor list: {}".format(err))
1390
1483
 
1391
1484
  if args.action == "get_next":
1392
- action_get_next(refactor_list_data, args.state_dir, args.project_root)
1485
+ action_get_next(
1486
+ refactor_list_data,
1487
+ args.state_dir,
1488
+ args.project_root,
1489
+ args.refactor_list,
1490
+ )
1393
1491
  elif args.action == "update":
1394
1492
  action_update(args, args.refactor_list, args.state_dir)
1395
1493
  elif args.action == "status":
@@ -228,24 +228,19 @@ def dependency_rank_map(items, id_key="id", dependencies_key="dependencies", ite
228
228
  return {item[id_key]: index for index, item in enumerate(ordered) if id_key in item}, errors
229
229
 
230
230
 
231
- def causal_reset_selection(
231
+ def _causal_blocker_analysis(
232
232
  items,
233
- selected_id=None,
234
- blocking_root_statuses=None,
233
+ blocking_root_statuses,
235
234
  id_key="id",
236
235
  dependencies_key="dependencies",
237
236
  status_key="status",
238
237
  auto_skipped_status="auto_skipped",
239
238
  item_label="Item",
240
239
  ):
241
- """Return the exact state-only recovery closure for one dependency graph.
240
+ """Validate a dependency graph and derive current transitive blockers.
242
241
 
243
- A selected terminal root recovers itself and only ``auto_skipped`` items
244
- whose complete transitive blocking-root set is contained by that selection.
245
- Selecting an ``auto_skipped`` item first expands the selection to every
246
- blocking root required by that item. ``selected_id=None`` means recover all
247
- supported blocking roots. Invalid graph or target state raises ``ValueError``
248
- before callers perform any mutation.
242
+ The second result tracks rootless ``auto_skipped`` ancestors separately so
243
+ a selected recovery never crosses another orphan branch by accident.
249
244
  """
250
245
  if not isinstance(items, list):
251
246
  raise ValueError("{} list must be an array".format(item_label))
@@ -255,7 +250,6 @@ def causal_reset_selection(
255
250
  raise ValueError("Blocking root statuses must not be empty")
256
251
 
257
252
  item_by_id = {}
258
- ordered_ids = []
259
253
  for index, item in enumerate(items):
260
254
  if not isinstance(item, dict):
261
255
  raise ValueError("{} at index {} is not an object".format(item_label, index))
@@ -265,9 +259,8 @@ def causal_reset_selection(
265
259
  if item_id in item_by_id:
266
260
  raise ValueError("Duplicate {} id: {}".format(item_label.lower(), item_id))
267
261
  item_by_id[item_id] = item
268
- ordered_ids.append(item_id)
269
262
 
270
- _ordered, graph_errors = stable_topological_order(
263
+ ordered_items, graph_errors = stable_topological_order(
271
264
  items,
272
265
  id_key=id_key,
273
266
  dependencies_key=dependencies_key,
@@ -276,27 +269,93 @@ def causal_reset_selection(
276
269
  if graph_errors:
277
270
  raise ValueError(graph_errors[0])
278
271
 
279
- blocker_cache = {}
280
-
281
- def transitive_blockers(item_id):
282
- cached = blocker_cache.get(item_id)
283
- if cached is not None:
284
- cached_roots, cached_unresolved = cached
285
- return set(cached_roots), set(cached_unresolved)
272
+ ordered_ids = tuple(item[id_key] for item in ordered_items)
273
+ roots_by_id = {}
274
+ orphan_ancestors_by_id = {}
275
+ for item_id in ordered_ids:
286
276
  item = item_by_id[item_id]
287
277
  roots = set()
288
- unresolved = set()
289
- item_status = item.get(status_key, "pending")
290
- if item_status in roots_statuses:
278
+ orphan_ancestors = set()
279
+ if item.get(status_key, "pending") in roots_statuses:
291
280
  roots.add(item_id)
292
281
  for dependency_id in item.get(dependencies_key, []) or []:
293
- dependency_roots, dependency_unresolved = transitive_blockers(dependency_id)
282
+ dependency_roots = roots_by_id[dependency_id]
294
283
  roots.update(dependency_roots)
295
- unresolved.update(dependency_unresolved)
296
- if item_status == auto_skipped_status and not roots and not unresolved:
297
- unresolved.add(item_id)
298
- blocker_cache[item_id] = (frozenset(roots), frozenset(unresolved))
299
- return roots, unresolved
284
+ orphan_ancestors.update(orphan_ancestors_by_id[dependency_id])
285
+ dependency = item_by_id[dependency_id]
286
+ if (
287
+ dependency.get(status_key, "pending") == auto_skipped_status
288
+ and not dependency_roots
289
+ ):
290
+ orphan_ancestors.add(dependency_id)
291
+ roots_by_id[item_id] = frozenset(roots)
292
+ orphan_ancestors_by_id[item_id] = frozenset(orphan_ancestors)
293
+
294
+ return ordered_ids, item_by_id, roots_by_id, orphan_ancestors_by_id
295
+
296
+
297
+ def orphaned_auto_skipped_ids(
298
+ items,
299
+ blocking_root_statuses,
300
+ id_key="id",
301
+ dependencies_key="dependencies",
302
+ status_key="status",
303
+ auto_skipped_status="auto_skipped",
304
+ item_label="Item",
305
+ ):
306
+ """Return auto-skipped IDs with no current transitive blocking root."""
307
+ ordered_ids, item_by_id, roots_by_id, _orphan_ancestors = _causal_blocker_analysis(
308
+ items,
309
+ blocking_root_statuses,
310
+ id_key=id_key,
311
+ dependencies_key=dependencies_key,
312
+ status_key=status_key,
313
+ auto_skipped_status=auto_skipped_status,
314
+ item_label=item_label,
315
+ )
316
+ return tuple(
317
+ item_id
318
+ for item_id in ordered_ids
319
+ if item_by_id[item_id].get(status_key, "pending") == auto_skipped_status
320
+ and not roots_by_id[item_id]
321
+ )
322
+
323
+
324
+ def causal_reset_selection(
325
+ items,
326
+ selected_id=None,
327
+ blocking_root_statuses=None,
328
+ id_key="id",
329
+ dependencies_key="dependencies",
330
+ status_key="status",
331
+ auto_skipped_status="auto_skipped",
332
+ item_label="Item",
333
+ ):
334
+ """Return the exact state-only recovery closure for one dependency graph.
335
+
336
+ A selected terminal root recovers itself and only ``auto_skipped`` items
337
+ whose complete transitive blocking-root set is contained by that selection.
338
+ Selecting an ``auto_skipped`` item expands the selection to every blocking
339
+ root and rootless auto-skipped ancestor required by that item. Selecting all
340
+ recovers every supported root and every orphan. Invalid graph or target
341
+ state raises ``ValueError`` before callers perform any mutation.
342
+ """
343
+ roots_statuses = set(blocking_root_statuses or ())
344
+ ordered_ids, item_by_id, roots_by_id, orphan_ancestors_by_id = _causal_blocker_analysis(
345
+ items,
346
+ roots_statuses,
347
+ id_key=id_key,
348
+ dependencies_key=dependencies_key,
349
+ status_key=status_key,
350
+ auto_skipped_status=auto_skipped_status,
351
+ item_label=item_label,
352
+ )
353
+ orphan_ids = {
354
+ item_id
355
+ for item_id in ordered_ids
356
+ if item_by_id[item_id].get(status_key, "pending") == auto_skipped_status
357
+ and not roots_by_id[item_id]
358
+ }
300
359
 
301
360
  if selected_id is None:
302
361
  selected_roots = {
@@ -304,29 +363,22 @@ def causal_reset_selection(
304
363
  for item_id in ordered_ids
305
364
  if item_by_id[item_id].get(status_key, "pending") in roots_statuses
306
365
  }
307
- if not selected_roots:
366
+ selected_orphans = set(orphan_ids)
367
+ if not selected_roots and not selected_orphans:
308
368
  raise ValueError("No recoverable blocking roots found")
309
369
  else:
310
370
  target = item_by_id.get(selected_id)
311
371
  if target is None:
312
372
  raise ValueError("{} '{}' not found".format(item_label, selected_id))
313
373
  target_status = target.get(status_key, "pending")
374
+ selected_orphans = set()
314
375
  if target_status in roots_statuses:
315
376
  selected_roots = {selected_id}
316
377
  elif target_status == auto_skipped_status:
317
- selected_roots, unresolved = transitive_blockers(selected_id)
318
- if unresolved:
319
- raise ValueError(
320
- "{} '{}' has unresolved auto_skipped blocker(s): {}".format(
321
- item_label, selected_id, ", ".join(sorted(unresolved))
322
- )
323
- )
324
- if not selected_roots:
325
- raise ValueError(
326
- "{} '{}' is auto_skipped but has no transitive blocking root".format(
327
- item_label, selected_id
328
- )
329
- )
378
+ selected_roots = set(roots_by_id[selected_id])
379
+ selected_orphans.update(orphan_ancestors_by_id[selected_id])
380
+ if selected_id in orphan_ids:
381
+ selected_orphans.add(selected_id)
330
382
  else:
331
383
  supported = sorted(roots_statuses | {auto_skipped_status})
332
384
  raise ValueError(
@@ -335,14 +387,21 @@ def causal_reset_selection(
335
387
  )
336
388
  )
337
389
 
338
- selected = set(selected_roots)
390
+ selected = set(selected_roots) | set(selected_orphans)
339
391
  for item_id in ordered_ids:
340
392
  item = item_by_id[item_id]
341
393
  if item.get(status_key, "pending") != auto_skipped_status:
342
394
  continue
343
- blockers, unresolved = transitive_blockers(item_id)
344
- if blockers and not unresolved and blockers.issubset(selected_roots):
395
+ blockers = roots_by_id[item_id]
396
+ required_orphans = orphan_ancestors_by_id[item_id]
397
+ if not blockers.issubset(selected_roots):
398
+ continue
399
+ if not required_orphans.issubset(selected_orphans):
400
+ continue
401
+ if blockers or required_orphans or item_id in selected_orphans:
345
402
  selected.add(item_id)
403
+ if not blockers:
404
+ selected_orphans.add(item_id)
346
405
 
347
406
  return tuple(item_id for item_id in ordered_ids if item_id in selected)
348
407