1"""Handoff documentation generation for session management.

2

3 This module provides utilities for generating comprehensive handoff documentation

4 when sessions end, including quality assessment, recommendations, and context.

5"""

6

7 from __future__ import annotations

8

9 import typing as t

10 from datetime import datetime

11

12 if t.TYPE_CHECKING:

13 from pathlib import Path

14

15

16 def build_handoff_header(summary: dict[str, t.Any]) -> list[str]:

17 """Build handoff documentation header section."""

18 return [

19 f"# Session Handoff Report - {summary['project']}",

20 "",

21 f"**Session ended:** {summary['session_end_time']}",

22 f"**Final quality score:** {summary['final_quality_score']}/100",

23 f"**Working directory:** {summary['working_directory']}",

24 "",

25 ]

26

27

28 def build_quality_section(quality_data: dict[str, t.Any]) -> list[str]:

29 """Build quality assessment section of handoff documentation."""

30 lines = ["## Quality Assessment", ""]

31 breakdown = quality_data.get("breakdown", {})

32 lines.extend(

33 [

34 f"- **Code quality:** {breakdown.get('code_quality', 0):.1f}/40",

35 f"- **Project health:** {breakdown.get('project_health', 0):.1f}/30",

36 f"- **Dev velocity:** {breakdown.get('dev_velocity', 0):.1f}/20",

37 f"- **Security:** {breakdown.get('security', 0):.1f}/10",

38 "",

39 ],

40 )

41 return lines

42

43

44 def build_recommendations_section(recommendations: list[str]) -> list[str]:

45 """Build recommendations section of handoff documentation."""

46 if not recommendations:

47 return []

48

49 lines = ["## Recommendations for Next Session", ""]

50 for rec in recommendations[:5]:

51 lines.append(f"- {rec}")

52 lines.append("")

53 return lines

54

55

56 def build_static_sections() -> list[str]:

57 """Build static sections of handoff documentation."""

58 return [

59 "## Context for Next Session",

60 "",

61 "This session has completed. Use the quality score and recommendations above",

62 "to guide next steps. Review the working directory state and apply any",

63 "suggested improvements.",

64 "",

65 "## Session Continuity",

66 "",

67 "The session management system maintains context between sessions through:",

68 "- Reflection database for key insights",

69 "- Quality score history for trend analysis",

70 "- Project structure analysis for optimization",

71 "",

72 ]

73

74

75 def save_handoff_documentation(content: str, working_dir: Path) -> Path | None:

76 """Save handoff documentation to file."""

77 try:

78 handoff_dir = working_dir / ".claude" / "handoff"

79 handoff_dir.mkdir(parents=True, exist_ok=True)

80

81 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

82 handoff_path = handoff_dir / f"session_handoff_{timestamp}.md"

83

84 handoff_path.write_text(content)

85 return handoff_path

86

87 except Exception:

88 return None

89

90

91 async def generate_handoff_documentation(

92 summary: dict[str, t.Any],

93 quality_data: dict[str, t.Any],

94) -> str:

95 """Generate comprehensive handoff documentation."""

96 lines: list[str] = []

97

98 # Header section

99 lines.extend(build_handoff_header(summary))

100

101 # Quality section

102 lines.extend(build_quality_section(quality_data))

103

104 # Recommendations section

105 lines.extend(build_recommendations_section(summary.get("recommendations", [])))

106

107 # Static sections

108 lines.extend(build_static_sections())

109

110 return "\n".join(lines)