claude-dev-env 2.19.0 → 2.21.0

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.
Files changed (53) hide show
  1. package/.agents/skills/_shared/pr-loop/preflight-proposal.contract.test.mjs +31 -1
  2. package/.agents/skills/e-code-review/SKILL.md +12 -1
  3. package/.agents/skills/e-code-review/reference/fix.md +5 -1
  4. package/.agents/skills/e-code-review/reference/loop.md +4 -0
  5. package/.agents/skills/e-code-review/reference/mode-contract.test.mjs +66 -0
  6. package/.agents/skills/e-code-review/reference/preflight-proposal.md +40 -0
  7. package/.agents/skills/e-code-review/reference/runner-selection.md +1 -0
  8. package/.agents/skills/pr-cleanup/SKILL.md +109 -11
  9. package/_shared/pr-loop/scripts/code_rules_gate.py +29 -6
  10. package/_shared/pr-loop/scripts/code_rules_gate_parts/gate_arguments.py +15 -3
  11. package/_shared/pr-loop/scripts/pr_loop_shared_constants/code_rules_gate_constants.py +4 -0
  12. package/_shared/pr-loop/scripts/tests/test_code_rules_gate.py +47 -0
  13. package/docs/CODE_RULES.md +2 -0
  14. package/hooks/advisory/conftest.py +10 -0
  15. package/hooks/advisory/refactor_guard.py +250 -144
  16. package/hooks/advisory/refactor_guard_test_support.py +46 -0
  17. package/hooks/advisory/test_refactor_guard_advisory.py +171 -0
  18. package/hooks/advisory/test_refactor_guard_eligibility.py +166 -0
  19. package/hooks/blocking/block_main_commit.py +66 -33
  20. package/hooks/blocking/code_rules_blast_radius.py +194 -0
  21. package/hooks/blocking/code_rules_enforcer.py +95 -0
  22. package/hooks/blocking/codex_apply_patch.py +238 -0
  23. package/hooks/blocking/test_block_main_commit.py +145 -0
  24. package/hooks/blocking/test_code_rules_blast_radius.py +161 -0
  25. package/hooks/blocking/test_code_rules_enforcer_codex_apply_patch.py +148 -0
  26. package/hooks/blocking/test_code_rules_enforcer_narrow_edit.py +1 -0
  27. package/hooks/blocking/test_destructive_command_blocker.py +154 -138
  28. package/hooks/blocking/test_destructive_command_blocker_deny_mode.py +52 -9
  29. package/hooks/blocking/test_destructive_command_blocker_patterns.py +133 -0
  30. package/hooks/blocking/test_precommit_code_rules_gate_native_owner.py +71 -5
  31. package/hooks/git-hooks/AGENTS.md +1 -1
  32. package/hooks/git-hooks/git_hooks_constants/__init__.py +1 -0
  33. package/hooks/git-hooks/post_commit.py +160 -51
  34. package/hooks/git-hooks/pre_commit.py +3 -3
  35. package/hooks/git-hooks/test_post_commit.py +203 -0
  36. package/hooks/git-hooks/test_pre_commit.py +2 -2
  37. package/hooks/hooks_constants/blast_radius_constants.py +14 -0
  38. package/hooks/hooks_constants/code_rules_enforcer_constants.py +1 -0
  39. package/hooks/hooks_constants/refactor_guard_constants.py +75 -0
  40. package/hooks/hooks_constants/test_refactor_guard_constants.py +21 -0
  41. package/hooks/observability/test_instructions_loaded_logger.py +54 -0
  42. package/hooks/session/test_plugin_data_dir_cleanup.py +70 -0
  43. package/hooks/session/test_session_edit_tracker_cleanup.py +16 -3
  44. package/hooks/validation/mypy_validator.py +213 -80
  45. package/hooks/validation/test_mypy_validator.py +288 -13
  46. package/hooks/workflow/auto_formatter.py +225 -93
  47. package/hooks/workflow/investigation_tracker_reset.py +2 -0
  48. package/hooks/workflow/test_auto_formatter.py +261 -12
  49. package/hooks/workflow/test_investigation_tracker_reset.py +90 -0
  50. package/package.json +1 -1
  51. package/rules/failure-blast-radius.md +126 -0
  52. package/scripts/codex_compat_materializer.py +395 -17
  53. package/scripts/tests/test_codex_compat_materializer.py +17 -3
@@ -9,14 +9,14 @@ import os
9
9
  import re
10
10
  import stat
11
11
  import tempfile
12
- import tomllib
12
+ from collections.abc import Callable, Iterable
13
13
  from dataclasses import dataclass, field
14
14
  from pathlib import Path
15
- from typing import Callable, Iterable
15
+ from typing import NoReturn
16
16
 
17
+ import tomllib
17
18
  import yaml
18
19
 
19
-
20
20
  ManagedContent = str | bytes
21
21
 
22
22
  path_separator = "/"
@@ -27,6 +27,87 @@ publish_plan_max_positional_arguments = 3
27
27
  publish_plan_failure_injector_position = 2
28
28
  frontmatter_unsupported_fields = ("tools", "model", "color")
29
29
  instruction_alias_filenames = frozenset({"AGENTS.md", "CLAUDE.md"})
30
+ failure_blast_radius_rule_relative_path = "rules/failure-blast-radius.md"
31
+ codex_instruction_target_path = "AGENTS.md"
32
+ codex_instruction_section_heading = "## Excerpt for repository-instruction sessions"
33
+ codex_hook_manifest_source_path = "hooks/hooks.json"
34
+ codex_hook_manifest_target_path = "hooks.json"
35
+ codex_hook_event_name = "PreToolUse"
36
+ codex_hook_matcher = "apply_patch"
37
+ codex_enforcer_script_relative_path = "hooks/blocking/code_rules_enforcer.py"
38
+ codex_enforcer_script_name = "code_rules_enforcer.py"
39
+ codex_enforcer_path_suffix = path_separator + codex_enforcer_script_relative_path
40
+ codex_hook_command_token_pattern = r'''(?:"[^"]*"|'[^']*'|\S+)'''
41
+ codex_hook_merge_action = "merge"
42
+ codex_hook_timeout_seconds = 60
43
+ codex_hook_dependency_manifest = (
44
+ "hooks/blocking/__init__.py",
45
+ "hooks/blocking/code_rules_annotations_length.py",
46
+ "hooks/blocking/code_rules_banned_identifiers.py",
47
+ "hooks/blocking/code_rules_blast_radius.py",
48
+ "hooks/blocking/code_rules_boolean_mustcheck.py",
49
+ "hooks/blocking/code_rules_command_dispatch.py",
50
+ "hooks/blocking/code_rules_comments.py",
51
+ "hooks/blocking/code_rules_constants_config.py",
52
+ "hooks/blocking/codex_apply_patch.py",
53
+ "hooks/blocking/code_rules_dead_argparse_argument.py",
54
+ "hooks/blocking/code_rules_dead_config_field.py",
55
+ "hooks/blocking/code_rules_dead_dataclass_field.py",
56
+ "hooks/blocking/code_rules_dead_module_constant.py",
57
+ "hooks/blocking/code_rules_dead_split_branch.py",
58
+ "hooks/blocking/code_rules_docstrings.py",
59
+ "hooks/blocking/code_rules_duplicate_body.py",
60
+ "hooks/blocking/code_rules_enforcer.py",
61
+ "hooks/blocking/code_rules_imports_logging.py",
62
+ "hooks/blocking/code_rules_js_conventions.py",
63
+ "hooks/blocking/code_rules_magic_values.py",
64
+ "hooks/blocking/code_rules_mock_completeness.py",
65
+ "hooks/blocking/code_rules_naming_collection.py",
66
+ "hooks/blocking/code_rules_optional_params.py",
67
+ "hooks/blocking/code_rules_orphan_css_class.py",
68
+ "hooks/blocking/code_rules_paired_test.py",
69
+ "hooks/blocking/code_rules_path_utils.py",
70
+ "hooks/blocking/code_rules_paths_syspath.py",
71
+ "hooks/blocking/code_rules_probe_chains.py",
72
+ "hooks/blocking/code_rules_probe_detection.py",
73
+ "hooks/blocking/code_rules_probe_recording.py",
74
+ "hooks/blocking/code_rules_scope_binding.py",
75
+ "hooks/blocking/code_rules_shared.py",
76
+ "hooks/blocking/code_rules_string_magic.py",
77
+ "hooks/blocking/code_rules_test_assertions.py",
78
+ "hooks/blocking/code_rules_test_branching_except.py",
79
+ "hooks/blocking/code_rules_test_isolation.py",
80
+ "hooks/blocking/code_rules_test_layout.py",
81
+ "hooks/blocking/code_rules_type_escape.py",
82
+ "hooks/blocking/code_rules_typeddict_stub.py",
83
+ "hooks/blocking/code_rules_unused_imports.py",
84
+ "hooks/hooks_constants/__init__.py",
85
+ "hooks/hooks_constants/any_type_config.py",
86
+ "hooks/hooks_constants/banned_identifiers_constants.py",
87
+ "hooks/hooks_constants/blast_radius_constants.py",
88
+ "hooks/hooks_constants/blocking_check_limits.py",
89
+ "hooks/hooks_constants/code_rules_enforcer_constants.py",
90
+ "hooks/hooks_constants/code_rules_path_utils_constants.py",
91
+ "hooks/hooks_constants/command_dispatch_constants.py",
92
+ "hooks/hooks_constants/dead_argparse_argument_constants.py",
93
+ "hooks/hooks_constants/dead_config_field_constants.py",
94
+ "hooks/hooks_constants/dead_dataclass_field_constants.py",
95
+ "hooks/hooks_constants/dead_module_constant_constants.py",
96
+ "hooks/hooks_constants/duplicate_function_body_constants.py",
97
+ "hooks/hooks_constants/hardcoded_user_path_constants.py",
98
+ "hooks/hooks_constants/harness_scratchpad_constants.py",
99
+ "hooks/hooks_constants/hook_block_logger.py",
100
+ "hooks/hooks_constants/inline_tuple_string_magic_constants.py",
101
+ "hooks/hooks_constants/js_conventions_constants.py",
102
+ "hooks/hooks_constants/orphan_css_class_constants.py",
103
+ "hooks/hooks_constants/paired_test_coverage_constants.py",
104
+ "hooks/hooks_constants/setup_project_paths_constants.py",
105
+ "hooks/hooks_constants/stuttering_check_config.py",
106
+ "hooks/hooks_constants/stuttering_import_binding_constants.py",
107
+ "hooks/hooks_constants/sys_path_insert_constants.py",
108
+ "hooks/hooks_constants/test_layout_constants.py",
109
+ "hooks/hooks_constants/unused_module_import_constants.py",
110
+ )
30
111
  full_prune_opt_in_flag = "--allow-prune-all"
31
112
  unreadable_source_root_message = (
32
113
  "source root is missing or is not a directory, so nothing was planned or changed; "
@@ -50,6 +131,10 @@ class MaterializerError(ValueError):
50
131
  """Raised when a materialization request cannot be safely planned."""
51
132
 
52
133
 
134
+ class MaterializerRunFatal(MaterializerError):
135
+ """Raised when invalid materializer state stops the whole run."""
136
+
137
+
53
138
  class ArgumentParserError(ValueError):
54
139
  """Raised when command-line arguments cannot be parsed."""
55
140
 
@@ -57,7 +142,7 @@ class ArgumentParserError(ValueError):
57
142
  class MaterializerArgumentParser(argparse.ArgumentParser):
58
143
  """Parse materializer arguments while keeping errors in the JSON contract."""
59
144
 
60
- def error(self, message: str) -> None:
145
+ def error(self, message: str) -> NoReturn:
61
146
  """Raise a reportable parser error instead of writing process output."""
62
147
  raise ArgumentParserError(message)
63
148
 
@@ -407,6 +492,246 @@ def convert_agent(agent: ClaudeAgent) -> str:
407
492
  return content
408
493
 
409
494
 
495
+ def render_codex_failure_blast_radius(rule_content: str) -> str:
496
+ """Extract the repository-instruction contract from the canonical rule.
497
+
498
+ Args:
499
+ rule_content: Canonical failure blast-radius rule text.
500
+
501
+ Returns:
502
+ The fenced repository-instruction excerpt with a trailing newline.
503
+
504
+ Raises:
505
+ MaterializerError: If the canonical rule lacks the required excerpt.
506
+ """
507
+ heading_start = rule_content.find(codex_instruction_section_heading)
508
+ if heading_start < 0:
509
+ raise MaterializerError("failure blast-radius rule requires a Codex excerpt")
510
+ fence_start = rule_content.find("```", heading_start)
511
+ if fence_start < 0:
512
+ raise MaterializerError("failure blast-radius rule requires a Codex excerpt")
513
+ content_start = rule_content.find(line_separator, fence_start)
514
+ fence_end = rule_content.find(line_separator + "```", content_start + 1)
515
+ if content_start < 0 or fence_end < 0:
516
+ raise MaterializerError("failure blast-radius rule requires a complete Codex excerpt")
517
+ return rule_content[content_start + len(line_separator) : fence_end].rstrip() + line_separator
518
+
519
+
520
+ def _build_codex_instruction_projection(config: MaterializerConfig) -> PlannedFile | None:
521
+ """Build the managed AGENTS.md projection when the canonical rule is present."""
522
+ source_path = config.source_root / failure_blast_radius_rule_relative_path
523
+ if not source_path.is_file():
524
+ return None
525
+ rule_content = source_path.read_text(encoding="utf-8")
526
+ projected_content = render_codex_failure_blast_radius(rule_content)
527
+ return PlannedFile(
528
+ failure_blast_radius_rule_relative_path,
529
+ codex_instruction_target_path,
530
+ projected_content,
531
+ hash_content(projected_content),
532
+ )
533
+
534
+
535
+ def _read_json_object(file_path: Path, description: str) -> dict[str, object]:
536
+ """Read one JSON object and report the required content shape."""
537
+ try:
538
+ parsed_json = json.loads(file_path.read_text(encoding="utf-8"))
539
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
540
+ raise MaterializerError(f"{description} requires readable UTF-8 content: {file_path}") from error
541
+ if not isinstance(parsed_json, dict):
542
+ raise MaterializerError(f"{description} must be a JSON object: {file_path}")
543
+ if not all(isinstance(each_key, str) for each_key in parsed_json):
544
+ raise MaterializerError(f"{description} requires string keys: {file_path}")
545
+ return {each_key: each_record for each_key, each_record in parsed_json.items()}
546
+
547
+
548
+ def _validated_agent_iterable(candidate: object) -> tuple[ClaudeAgent, ...]:
549
+ """Validate the optional agent iterable used by the legacy call form."""
550
+ if not isinstance(candidate, Iterable):
551
+ raise TypeError("agent collection requires an iterable")
552
+ all_candidate_agents = tuple(candidate)
553
+ if not all(isinstance(each_agent, ClaudeAgent) for each_agent in all_candidate_agents):
554
+ raise TypeError("agent collection requires ClaudeAgent entries")
555
+ return all_candidate_agents
556
+
557
+
558
+ def _validated_planned_file_iterable(candidate: object) -> tuple[PlannedFile, ...]:
559
+ """Validate planned files passed through the legacy publication call form."""
560
+ if not isinstance(candidate, Iterable):
561
+ raise TypeError("planned files require an iterable")
562
+ all_candidate_files = tuple(candidate)
563
+ if not all(isinstance(each_file, PlannedFile) for each_file in all_candidate_files):
564
+ raise TypeError("planned files require PlannedFile entries")
565
+ return all_candidate_files
566
+
567
+
568
+ def _find_codex_hook_source(config: MaterializerConfig) -> Path | None:
569
+ """Find the source hook manifest alongside the compatibility sources."""
570
+ all_candidates = (
571
+ config.source_root / codex_hook_manifest_source_path,
572
+ config.source_root / Path(codex_hook_manifest_source_path).name,
573
+ )
574
+ return next((each_path for each_path in all_candidates if each_path.is_file()), None)
575
+
576
+
577
+ def _resolved_codex_enforcer_command(config: MaterializerConfig) -> str:
578
+ """Build the target-root command for the focused Codex enforcer."""
579
+ script_path = (config.target_root / codex_enforcer_script_relative_path).resolve()
580
+ return f'python3 "{script_path}"'
581
+
582
+
583
+ def _source_codex_enforcer_hook(
584
+ all_source_manifest: dict[str, object], command: str
585
+ ) -> dict[str, object]:
586
+ """Read the source enforcer hook shape and resolve its target command."""
587
+ all_events = all_source_manifest.get("hooks")
588
+ if not isinstance(all_events, dict):
589
+ raise MaterializerError("source Codex hook manifest requires a hooks object")
590
+ all_pre_tool_use = all_events.get(codex_hook_event_name)
591
+ if not isinstance(all_pre_tool_use, list):
592
+ raise MaterializerError("source Codex hook manifest requires a PreToolUse list")
593
+ for each_entry in all_pre_tool_use:
594
+ if not isinstance(each_entry, dict) or each_entry.get("matcher") != codex_hook_matcher:
595
+ continue
596
+ all_hook_records = each_entry.get("hooks")
597
+ if not isinstance(all_hook_records, list):
598
+ continue
599
+ for each_hook in all_hook_records:
600
+ if not isinstance(each_hook, dict):
601
+ continue
602
+ if not _is_code_rules_enforcer_hook(each_hook):
603
+ continue
604
+ resolved_hook = dict(each_hook)
605
+ resolved_hook["command"] = command
606
+ return resolved_hook
607
+ return {
608
+ "type": "command",
609
+ "command": command,
610
+ "timeout": codex_hook_timeout_seconds,
611
+ }
612
+
613
+
614
+ def _hook_records(raw_hooks: object) -> list[dict[str, object]]:
615
+ """Validate and copy a Codex hook-record list."""
616
+ if not isinstance(raw_hooks, list):
617
+ raise MaterializerError("Codex hook manifest entry requires a hooks list")
618
+ if not all(isinstance(each_hook, dict) for each_hook in raw_hooks):
619
+ raise MaterializerError("Codex hook manifest requires valid hook entries")
620
+ return [dict(each_hook) for each_hook in raw_hooks]
621
+
622
+
623
+ def _is_code_rules_enforcer_hook(all_hook_record: dict[str, object]) -> bool:
624
+ """Report whether a hook record names the focused code-rules enforcer."""
625
+ command = str(all_hook_record.get("command", ""))
626
+ normalized_command = command.replace("\\", path_separator)
627
+ all_command_tokens = (
628
+ each_token.strip("\"'")
629
+ for each_token in re.findall(codex_hook_command_token_pattern, normalized_command)
630
+ )
631
+ return any(
632
+ each_token in (codex_enforcer_script_name, codex_enforcer_script_relative_path)
633
+ or each_token.endswith(codex_enforcer_path_suffix)
634
+ for each_token in all_command_tokens
635
+ )
636
+
637
+
638
+ def _merge_codex_hook_manifest(
639
+ all_target_manifest: dict[str, object], all_focused_hook: dict[str, object]
640
+ ) -> dict[str, object]:
641
+ """Preserve target hook order while merging one deterministic enforcer entry."""
642
+ all_events = all_target_manifest.get("hooks", {})
643
+ if not isinstance(all_events, dict):
644
+ raise MaterializerError("Codex hook manifest requires a hooks object")
645
+ all_pre_tool_use = all_events.get(codex_hook_event_name, [])
646
+ if not isinstance(all_pre_tool_use, list):
647
+ raise MaterializerError("Codex hook manifest requires a PreToolUse list")
648
+ merged_pre_tool_use: list[dict[str, object]] = []
649
+ merged_apply_patch_entry: dict[str, object] | None = None
650
+ merged_hooks: list[dict[str, object]] = []
651
+ for each_entry in all_pre_tool_use:
652
+ if not isinstance(each_entry, dict):
653
+ raise MaterializerRunFatal("Codex hook manifest requires valid matcher entries")
654
+ copied_entry = dict(each_entry)
655
+ if copied_entry.get("matcher") != codex_hook_matcher:
656
+ merged_pre_tool_use.append(copied_entry)
657
+ continue
658
+ all_hook_records = _hook_records(copied_entry.get("hooks", []))
659
+ if merged_apply_patch_entry is None:
660
+ merged_apply_patch_entry = copied_entry
661
+ merged_hooks = [
662
+ each_hook for each_hook in all_hook_records if not _is_code_rules_enforcer_hook(each_hook)
663
+ ]
664
+ merged_apply_patch_entry["hooks"] = merged_hooks
665
+ merged_pre_tool_use.append(merged_apply_patch_entry)
666
+ else:
667
+ merged_hooks.extend(
668
+ each_hook for each_hook in all_hook_records if not _is_code_rules_enforcer_hook(each_hook)
669
+ )
670
+ if merged_apply_patch_entry is None:
671
+ merged_apply_patch_entry = {"matcher": codex_hook_matcher, "hooks": merged_hooks}
672
+ merged_pre_tool_use.append(merged_apply_patch_entry)
673
+ merged_hooks.append(all_focused_hook)
674
+ merged_events = dict(all_events)
675
+ merged_events[codex_hook_event_name] = merged_pre_tool_use
676
+ merged_manifest = dict(all_target_manifest)
677
+ merged_manifest["hooks"] = merged_events
678
+ return merged_manifest
679
+
680
+
681
+ def _build_codex_hook_projection(config: MaterializerConfig) -> PlannedFile | None:
682
+ """Build an additive managed hooks.json projection when its source exists."""
683
+ source_path = _find_codex_hook_source(config)
684
+ if source_path is None:
685
+ return None
686
+ source_manifest = _read_json_object(source_path, "source Codex hook manifest")
687
+ target_path = config.target_root / codex_hook_manifest_target_path
688
+ target_manifest = (
689
+ _read_json_object(target_path, "target Codex hook manifest")
690
+ if target_path.is_file()
691
+ else {"hooks": {}}
692
+ )
693
+ focused_hook = _source_codex_enforcer_hook(
694
+ source_manifest, _resolved_codex_enforcer_command(config)
695
+ )
696
+ projected_manifest = _merge_codex_hook_manifest(target_manifest, focused_hook)
697
+ projected_content = json.dumps(projected_manifest, ensure_ascii=False, indent=manifest_indentation_width) + line_separator
698
+ return PlannedFile(
699
+ codex_hook_manifest_source_path,
700
+ codex_hook_manifest_target_path,
701
+ projected_content,
702
+ hash_content(projected_content),
703
+ action=codex_hook_merge_action,
704
+ )
705
+
706
+
707
+ def _build_codex_hook_dependency_projection(
708
+ config: MaterializerConfig,
709
+ ) -> list[PlannedFile]:
710
+ """Build the reviewed source files required by the target enforcer."""
711
+ all_dependencies: list[PlannedFile] = []
712
+ for each_relative_path in codex_hook_dependency_manifest:
713
+ source_path = config.source_root / each_relative_path
714
+ if not source_path.is_file():
715
+ raise MaterializerError(
716
+ f"source file is missing from the reviewed hook source list: {each_relative_path}"
717
+ )
718
+ try:
719
+ dependency_content = source_path.read_bytes()
720
+ except OSError as error:
721
+ raise MaterializerError(
722
+ f"reviewed Codex hook dependency has unreadable bytes: {each_relative_path}"
723
+ ) from error
724
+ all_dependencies.append(
725
+ PlannedFile(
726
+ each_relative_path,
727
+ each_relative_path,
728
+ dependency_content,
729
+ hash_content(dependency_content),
730
+ )
731
+ )
732
+ return all_dependencies
733
+
734
+
410
735
  def discover_agents(config: MaterializerConfig) -> list[ClaudeAgent]:
411
736
  """Discover and parse Markdown agents below the source root.
412
737
 
@@ -437,14 +762,17 @@ def discover_agents(config: MaterializerConfig) -> list[ClaudeAgent]:
437
762
  if _is_reparse_point(each_path):
438
763
  raise MaterializerError(f"source reparse point is not allowed: {each_path}")
439
764
  relative_source = each_path.relative_to(config.source_root).as_posix()
765
+ if relative_source == failure_blast_radius_rule_relative_path:
766
+ _validate_containment(config.source_root, each_path)
767
+ continue
440
768
  _validate_containment(config.source_root, each_path)
441
769
  all_agents.append(parse_frontmatter(each_path, each_path.read_text(encoding="utf-8"), relative_source))
442
770
  return all_agents
443
771
 
444
772
 
445
- def _case_fold_collision_error(target_relative_path: str) -> MaterializerError:
773
+ def _case_fold_collision_error(target_relative_path: str) -> MaterializerRunFatal:
446
774
  """Build the error for two target names that differ only by letter case."""
447
- return MaterializerError(f"case-fold collision: {target_relative_path}")
775
+ return MaterializerRunFatal(f"case-fold collision: {target_relative_path}")
448
776
 
449
777
 
450
778
  def _validate_orphan_target_is_adoptable(
@@ -479,6 +807,13 @@ def _validate_orphan_target_is_adoptable(
479
807
  raise MaterializerError(unmanaged_target_message.format(path=target_relative_path))
480
808
 
481
809
 
810
+ def _configured_manifest_path(config: MaterializerConfig) -> Path:
811
+ """Return the manifest path established during configuration validation."""
812
+ if config.manifest_path is None:
813
+ raise MaterializerError("compatibility manifest path requires configuration")
814
+ return config.manifest_path
815
+
816
+
482
817
  def _build_plan(config: MaterializerConfig, all_agents: Iterable[ClaudeAgent]) -> tuple[list[PlannedFile], MaterializationReport]:
483
818
  """Build planned agent publications and their report.
484
819
 
@@ -495,7 +830,8 @@ def _build_plan(config: MaterializerConfig, all_agents: Iterable[ClaudeAgent]) -
495
830
  report = MaterializationReport()
496
831
  planned: list[PlannedFile] = []
497
832
  target_by_name: dict[str, str] = {}
498
- previous_records = _manifest_record_by_path(load_manifest(config.manifest_path))
833
+ manifest_path = _configured_manifest_path(config)
834
+ previous_records = _manifest_record_by_path(load_manifest(manifest_path))
499
835
  existing_by_name = {
500
836
  each_path.relative_to(config.target_root).as_posix().casefold(): each_path
501
837
  for each_path in config.target_root.rglob("*")
@@ -506,16 +842,45 @@ def _build_plan(config: MaterializerConfig, all_agents: Iterable[ClaudeAgent]) -
506
842
  target_relative_path = _normalize_relative_path(each_agent.name + toml_suffix)
507
843
  folded_path = target_relative_path.casefold()
508
844
  if folded_path in target_by_name:
509
- raise _case_fold_collision_error(target_relative_path)
845
+ raise MaterializerRunFatal(f"case-fold collision: {target_relative_path}")
510
846
  content = convert_agent(each_agent)
511
847
  _validate_orphan_target_is_adoptable(config, existing_by_name.get(folded_path), target_relative_path, content)
512
848
  target_by_name[folded_path] = target_relative_path
513
849
  target_path = validate_target_path(config.target_root, target_relative_path)
514
- if _casefold_normalized_path(target_path) == _casefold_normalized_path(config.manifest_path):
515
- raise MaterializerError("planned target collides with compatibility manifest")
850
+ if _casefold_normalized_path(target_path) == _casefold_normalized_path(manifest_path):
851
+ raise MaterializerRunFatal("planned target collides with compatibility manifest")
516
852
  planned.append(PlannedFile(source_identity, target_relative_path, content, hash_content(content)))
517
853
  report.unsupported += len(each_agent.unsupported)
518
854
  report.details["unsupported"].extend(f"{source_identity}:{each_key}" for each_key in each_agent.unsupported)
855
+ codex_instruction = _build_codex_instruction_projection(config)
856
+ if codex_instruction is not None:
857
+ folded_path = codex_instruction.target_relative_path.casefold()
858
+ if folded_path in target_by_name:
859
+ raise _case_fold_collision_error(codex_instruction.target_relative_path)
860
+ _validate_orphan_target_is_adoptable(
861
+ config,
862
+ existing_by_name.get(folded_path),
863
+ codex_instruction.target_relative_path,
864
+ codex_instruction.content,
865
+ )
866
+ validate_target_path(config.target_root, codex_instruction.target_relative_path)
867
+ planned.append(codex_instruction)
868
+ target_by_name[folded_path] = codex_instruction.target_relative_path
869
+ codex_hooks = _build_codex_hook_projection(config)
870
+ if codex_hooks is not None:
871
+ all_hook_dependencies = _build_codex_hook_dependency_projection(config)
872
+ for each_dependency in all_hook_dependencies:
873
+ folded_dependency_path = each_dependency.target_relative_path.casefold()
874
+ if folded_dependency_path in target_by_name:
875
+ raise _case_fold_collision_error(each_dependency.target_relative_path)
876
+ validate_target_path(config.target_root, each_dependency.target_relative_path)
877
+ target_by_name[folded_dependency_path] = each_dependency.target_relative_path
878
+ planned.append(each_dependency)
879
+ folded_path = codex_hooks.target_relative_path.casefold()
880
+ if folded_path in target_by_name:
881
+ raise _case_fold_collision_error(codex_hooks.target_relative_path)
882
+ validate_target_path(config.target_root, codex_hooks.target_relative_path)
883
+ planned.append(codex_hooks)
519
884
  report.planned_files = planned
520
885
  return planned, report
521
886
 
@@ -542,7 +907,11 @@ def build_plan(config: MaterializerConfig, *all_arguments: object, **all_keyword
542
907
  if supplied_agents is not None:
543
908
  raise TypeError("build_plan received duplicate all_agents")
544
909
  supplied_agents = all_arguments[0]
545
- discovered_agents = discover_agents(config) if supplied_agents is None else supplied_agents
910
+ discovered_agents = (
911
+ discover_agents(config)
912
+ if supplied_agents is None
913
+ else _validated_agent_iterable(supplied_agents)
914
+ )
546
915
  return _build_plan(config, discovered_agents)
547
916
 
548
917
 
@@ -770,6 +1139,8 @@ def _record_target_state(config: MaterializerConfig, planned_file: PlannedFile,
770
1139
  if current_bytes == content_to_bytes(planned_file.content):
771
1140
  _record_matching_target(report, planned_file.target_relative_path, previous_record)
772
1141
  return target_path, current_bytes, False
1142
+ if planned_file.action == codex_hook_merge_action:
1143
+ return target_path, current_bytes, True
773
1144
  if _is_pristine_managed(previous_record, current_bytes):
774
1145
  return target_path, current_bytes, True
775
1146
  _record_target_conflict(report, planned_file.target_relative_path, previous_record)
@@ -845,9 +1216,10 @@ def _publish_planned_targets(
845
1216
  all_backups: dict[Path, bytes | None],
846
1217
  failure_injector: Callable[[str], None] | None,
847
1218
  ) -> None:
1219
+ manifest_path = _configured_manifest_path(config)
848
1220
  for each_planned_file in all_planned_files:
849
1221
  target_path, current_bytes, is_publishable = _record_target_state(config, each_planned_file, all_previous_records, report)
850
- if _casefold_normalized_path(target_path) == _casefold_normalized_path(config.manifest_path):
1222
+ if _casefold_normalized_path(target_path) == _casefold_normalized_path(manifest_path):
851
1223
  raise MaterializerError("planned target collides with compatibility manifest")
852
1224
  if not is_publishable:
853
1225
  continue
@@ -950,7 +1322,8 @@ def _publish_plan(
950
1322
  publication.planned_files = all_planned_files
951
1323
  if not config.should_apply:
952
1324
  return publication
953
- previous_manifest = load_manifest(config.manifest_path)
1325
+ manifest_path = _configured_manifest_path(config)
1326
+ previous_manifest = load_manifest(manifest_path)
954
1327
  previous_records = _manifest_record_by_path(previous_manifest)
955
1328
  _validate_full_prune_consent(config, all_planned_files, previous_records)
956
1329
  backups: dict[Path, bytes | None] = {}
@@ -962,10 +1335,10 @@ def _publish_plan(
962
1335
  config, all_planned_files, previous_records, publication, backups, failure_injector
963
1336
  )
964
1337
  _remove_stale_files(config, previous_records, all_planned_files, publication, backups)
965
- save_manifest(config.manifest_path, _build_manifest(all_planned_files), failure_injector)
966
- except (OSError, RuntimeError, ValueError) as error:
1338
+ save_manifest(manifest_path, _build_manifest(all_planned_files), failure_injector)
1339
+ except (OSError, RuntimeError, ValueError):
967
1340
  _rollback_publication(backups, publication, initial_written, initial_deleted)
968
- raise error
1341
+ raise
969
1342
  _sort_report_details(publication)
970
1343
  return publication
971
1344
 
@@ -1003,7 +1376,10 @@ def publish_plan(config: MaterializerConfig, *all_arguments: object, **all_keywo
1003
1376
  raise TypeError("publish_plan received duplicate failure injector")
1004
1377
  failure_injector = all_arguments[2]
1005
1378
  publication = report if isinstance(report, MaterializationReport) else MaterializationReport()
1006
- return _publish_plan(config, planned_files, publication, failure_injector)
1379
+ all_planned_files = _validated_planned_file_iterable(planned_files)
1380
+ if failure_injector is not None and not callable(failure_injector):
1381
+ raise TypeError("failure injector requires a callable")
1382
+ return _publish_plan(config, all_planned_files, publication, failure_injector)
1007
1383
 
1008
1384
 
1009
1385
  def _redact_private_paths(
@@ -1086,6 +1462,8 @@ def main(*all_arguments: object) -> int:
1086
1462
  should_apply = options.should_apply
1087
1463
  source_root = options.source_root
1088
1464
  target_root = options.target_root
1465
+ if source_root is None or target_root is None:
1466
+ raise TypeError("materializer roots are required")
1089
1467
  config = MaterializerConfig(
1090
1468
  source_root,
1091
1469
  target_root,
@@ -1,9 +1,9 @@
1
1
  import json
2
- from pathlib import Path
3
2
  import sys
4
- import tomllib
3
+ from pathlib import Path
5
4
 
6
5
  import pytest
6
+ import tomllib
7
7
 
8
8
  module_directory = str(Path(__file__).parents[1])
9
9
  if module_directory not in sys.path:
@@ -17,8 +17,8 @@ from codex_compat_materializer import (
17
17
  PlannedFile,
18
18
  atomic_write,
19
19
  build_plan,
20
- convert_agent,
21
20
  content_to_bytes,
21
+ convert_agent,
22
22
  hash_content,
23
23
  load_manifest,
24
24
  parse_frontmatter,
@@ -144,6 +144,20 @@ def test_validation_rejects_overlap_and_unsafe_paths(tmp_path: Path) -> None:
144
144
  validate_target_path(config.target_root, name)
145
145
 
146
146
 
147
+ def test_public_legacy_call_forms_validate_collection_entries(tmp_path: Path) -> None:
148
+ config = MaterializerConfig(tmp_path / "source", tmp_path / "target")
149
+
150
+ with pytest.raises(TypeError, match="ClaudeAgent entries"):
151
+ build_plan(config, all_agents=[object()])
152
+ with pytest.raises(TypeError, match="PlannedFile entries"):
153
+ publish_plan(config, all_planned_files=[object()])
154
+
155
+
156
+ def test_render_codex_failure_blast_radius_requires_the_excerpt_heading() -> None:
157
+ with pytest.raises(MaterializerError, match="requires a Codex excerpt"):
158
+ materializer.render_codex_failure_blast_radius("# No excerpt\n")
159
+
160
+
147
161
  def test_validation_rejects_reparse_point_from_portable_attribute_seam(
148
162
  tmp_path: Path, monkeypatch: pytest.MonkeyPatch
149
163
  ) -> None: