Skip to content

summary

Full name: tenets.models.summary

summary

Summary models for file condensation.

This module defines data structures for managing file summaries when content needs to be condensed to fit within token limits.

Classes

SummaryStrategy

Bases: Enum

Strategies for summarizing files.

Functions
get_defaultclassmethod
Python
get_default() -> SummaryStrategy

Get default summarization strategy.

Source code in tenets/models/summary.py
Python
@classmethod
def get_default(cls) -> "SummaryStrategy":
    """Get default summarization strategy."""
    return cls.EXTRACT
get_priority
Python
get_priority() -> int

Get priority for strategy selection.

Source code in tenets/models/summary.py
Python
def get_priority(self) -> int:
    """Get priority for strategy selection."""
    priorities = {
        cls.LLM: 5,
        cls.SEMANTIC: 4,
        cls.HYBRID: 3,
        cls.EXTRACT: 2,
        cls.COMPRESS: 1,
        cls.TRUNCATE: 0,
    }
    return priorities.get(self, 0)

SummarySectiondataclass

Python
SummarySection(name: str, content: str, line_start: int = 0, line_end: int = 0, importance: float = 1.0, preserved_fully: bool = True, tokens: int = 0, metadata: Dict[str, Any] = dict())

A section within a file summary.

Represents a specific section of code that was extracted for inclusion in the summary.

ATTRIBUTEDESCRIPTION
name

Section name (e.g., "imports", "class_definitions")

TYPE:str

content

Section content

TYPE:str

line_start

Starting line in original file

TYPE:int

line_end

Ending line in original file

TYPE:int

importance

Importance score (0-1)

TYPE:float

preserved_fully

Whether section was preserved in full

TYPE:bool

tokens

Token count for this section

TYPE:int

metadata

Additional section metadata

TYPE:Dict[str, Any]

Functions
truncate
Python
truncate(max_tokens: int) -> SummarySection

Truncate section to fit within token limit.

Source code in tenets/models/summary.py
Python
def truncate(self, max_tokens: int) -> "SummarySection":
    """Truncate section to fit within token limit."""
    if self.tokens <= max_tokens:
        return self

    # Calculate approximate character limit
    char_limit = (max_tokens * 4) - 50  # Leave buffer for ellipsis

    if len(self.content) <= char_limit:
        return self

    # Truncate content
    truncated_content = self.content[:char_limit] + "\n... [truncated]"

    return SummarySection(
        name=self.name,
        content=truncated_content,
        line_start=self.line_start,
        line_end=self.line_start + truncated_content.count("\n"),
        importance=self.importance,
        preserved_fully=False,
        tokens=max_tokens,
        metadata={**self.metadata, "truncated": True},
    )
to_dict
Python
to_dict() -> Dict[str, Any]

Convert to dictionary representation.

Source code in tenets/models/summary.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Convert to dictionary representation."""
    return asdict(self)
from_dictclassmethod
Python
from_dict(data: Dict[str, Any]) -> SummarySection

Create from dictionary.

Source code in tenets/models/summary.py
Python
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SummarySection":
    """Create from dictionary."""
    return cls(**data)

FileSummarydataclass

Python
FileSummary(content: str = '', was_summarized: bool = True, original_tokens: int = 0, summary_tokens: int = 0, original_lines: int = 0, summary_lines: int = 0, preserved_sections: List[str] = list(), ignored_sections: List[str] = list(), sections: List[SummarySection] = list(), strategy: str = 'extract', compression_ratio: float = 0.0, instructions: List[str] = list(), metadata: Dict[str, Any] = dict(), file_path: Optional[str] = None, path: Optional[str] = None, summary: Optional[str] = None, token_count: int = 0, timestamp: datetime = datetime.now())

Summary of a file's content.

Represents a condensed version of a file when the full content would exceed token limits. Contains sections, metadata, and instructions for AI assistants.

ATTRIBUTEDESCRIPTION
content

Summarized content

TYPE:str

was_summarized

Whether content was summarized

TYPE:bool

original_tokens

Token count of original

TYPE:int

summary_tokens

Token count of summary

TYPE:int

original_lines

Line count of original

TYPE:int

summary_lines

Line count of summary

TYPE:int

preserved_sections

Sections that were preserved

TYPE:List[str]

ignored_sections

Sections that were omitted

TYPE:List[str]

sections

List of summary sections

TYPE:List[SummarySection]

strategy

Strategy used for summarization

TYPE:str

compression_ratio

Ratio of summary to original

TYPE:float

instructions

Instructions for AI about summary

TYPE:List[str]

metadata

Additional metadata

TYPE:Dict[str, Any]

file_path

Original file path

TYPE:Optional[str]

timestamp

When summary was created

TYPE:datetime

Compatibility

TYPE:fields

-

legacy alias for file_path

TYPE:path

-

legacy alias for content

TYPE:summary

-

legacy alias for summary_tokens

TYPE:token_count

Functions
add_instruction
Python
add_instruction(instruction: str) -> None

Add an instruction for the AI about this summary.

Source code in tenets/models/summary.py
Python
def add_instruction(self, instruction: str) -> None:
    """Add an instruction for the AI about this summary."""
    if instruction and instruction not in self.instructions:
        self.instructions.append(instruction)
add_default_instructions
Python
add_default_instructions() -> None

Add default instructions based on summary characteristics.

Source code in tenets/models/summary.py
Python
def add_default_instructions(self) -> None:
    """Add default instructions based on summary characteristics."""
    if self.file_path:
        self.add_instruction(
            f"This is a summary of {self.file_path} "
            f"({self.original_lines} lines → {self.summary_lines} lines)"
        )

    if self.compression_ratio < 0.5 and self.original_tokens > 0:
        self.add_instruction(
            f"Significant compression applied ({self.compression_ratio:.1%} of original). "
            f"Request full file if more detail needed."
        )

    if self.ignored_sections:
        self.add_instruction(
            f"Omitted sections: {', '.join(self.ignored_sections)}. "
            f"Request specific sections if needed."
        )
add_metadata
Python
add_metadata(metadata: Dict[str, Any]) -> None

Add metadata about the summary.

Source code in tenets/models/summary.py
Python
def add_metadata(self, metadata: Dict[str, Any]) -> None:
    """Add metadata about the summary."""
    self.metadata.update(metadata)
add_section
Python
add_section(section: SummarySection) -> None

Add a section to the summary.

Source code in tenets/models/summary.py
Python
def add_section(self, section: SummarySection) -> None:
    """Add a section to the summary."""
    self.sections.append(section)
    self.summary_tokens += section.tokens
    self.token_count = self.summary_tokens

    if section.preserved_fully:
        self.preserved_sections.append(section.name)
    else:
        if section.name not in self.ignored_sections:
            self.ignored_sections.append(section.name)
get_section
Python
get_section(name: str) -> Optional[SummarySection]

Get a specific section by name.

Source code in tenets/models/summary.py
Python
def get_section(self, name: str) -> Optional[SummarySection]:
    """Get a specific section by name."""
    for section in self.sections:
        if section.name == name:
            return section
    return None
merge_sections
Python
merge_sections() -> str

Merge all sections into final content.

Source code in tenets/models/summary.py
Python
def merge_sections(self) -> str:
    """Merge all sections into final content."""
    if not self.sections:
        return self.content

    merged = []
    for section in self.sections:
        if section.name:
            merged.append(f"# {section.name}")
        merged.append(section.content)
        merged.append("")  # Empty line between sections

    self.content = "\n".join(merged)
    return self.content
to_dict
Python
to_dict() -> Dict[str, Any]

Convert to dictionary representation.

Source code in tenets/models/summary.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Convert to dictionary representation."""
    return {
        "content": self.content,
        "was_summarized": self.was_summarized,
        "original_tokens": self.original_tokens,
        "summary_tokens": self.summary_tokens,
        "original_lines": self.original_lines,
        "summary_lines": self.summary_lines,
        "preserved_sections": self.preserved_sections,
        "ignored_sections": self.ignored_sections,
        "sections": [s.to_dict() for s in self.sections],
        "strategy": self.strategy,
        "compression_ratio": self.compression_ratio,
        "instructions": self.instructions,
        "metadata": self.metadata,
        "file_path": self.file_path,
        "timestamp": self.timestamp.isoformat(),
    }
from_dictclassmethod
Python
from_dict(data: Dict[str, Any]) -> FileSummary

Create from dictionary.

Source code in tenets/models/summary.py
Python
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "FileSummary":
    """Create from dictionary."""
    if "timestamp" in data and isinstance(data["timestamp"], str):
        data["timestamp"] = datetime.fromisoformat(data["timestamp"])

    if "sections" in data:
        data["sections"] = [
            SummarySection.from_dict(s) if isinstance(s, dict) else s for s in data["sections"]
        ]

    return cls(**data)

ProjectSummarydataclass

Python
ProjectSummary(name: str, description: str = '', structure: Dict[str, Any] = dict(), key_files: List[str] = list(), key_directories: List[str] = list(), technologies: List[str] = list(), frameworks: List[str] = list(), patterns: List[str] = list(), dependencies: List[str] = list(), statistics: Dict[str, Any] = dict(), recent_activity: Dict[str, Any] = dict(), team_info: Dict[str, Any] = dict(), metadata: Dict[str, Any] = dict(), timestamp: datetime = datetime.now())

Summary of an entire project.

High-level summary for initial context or overview, providing a bird's eye view of the project structure and characteristics.

ATTRIBUTEDESCRIPTION
name

Project name

TYPE:str

description

Project description

TYPE:str

structure

Project structure overview

TYPE:Dict[str, Any]

key_files

Most important files

TYPE:List[str]

key_directories

Important directories

TYPE:List[str]

technologies

Technologies used

TYPE:List[str]

frameworks

Frameworks detected

TYPE:List[str]

patterns

Architectural patterns detected

TYPE:List[str]

dependencies

Key dependencies

TYPE:List[str]

statistics

Project statistics

TYPE:Dict[str, Any]

recent_activity

Recent development activity

TYPE:Dict[str, Any]

team_info

Team/contributor information

TYPE:Dict[str, Any]

metadata

Additional metadata

TYPE:Dict[str, Any]

timestamp

When summary was created

TYPE:datetime

Functions
add_technology
Python
add_technology(tech: str) -> None

Add a detected technology.

Source code in tenets/models/summary.py
Python
def add_technology(self, tech: str) -> None:
    """Add a detected technology."""
    if tech and tech not in self.technologies:
        self.technologies.append(tech)
add_framework
Python
add_framework(framework: str) -> None

Add a detected framework.

Source code in tenets/models/summary.py
Python
def add_framework(self, framework: str) -> None:
    """Add a detected framework."""
    if framework and framework not in self.frameworks:
        self.frameworks.append(framework)
add_pattern
Python
add_pattern(pattern: str) -> None

Add a detected architectural pattern.

Source code in tenets/models/summary.py
Python
def add_pattern(self, pattern: str) -> None:
    """Add a detected architectural pattern."""
    if pattern and pattern not in self.patterns:
        self.patterns.append(pattern)
update_statistics
Python
update_statistics(key: str, value: Any) -> None

Update a statistic value.

Source code in tenets/models/summary.py
Python
def update_statistics(self, key: str, value: Any) -> None:
    """Update a statistic value."""
    self.statistics[key] = value
to_markdown
Python
to_markdown() -> str

Generate markdown representation of project summary.

Source code in tenets/models/summary.py
Python
def to_markdown(self) -> str:
    """Generate markdown representation of project summary."""
    lines = [f"# Project: {self.name}", ""]

    if self.description:
        lines.extend([self.description, ""])

    # Technologies and frameworks
    if self.technologies or self.frameworks:
        lines.append("## Technologies & Frameworks")
        if self.technologies:
            lines.append(f"**Technologies:** {', '.join(self.technologies)}")
        if self.frameworks:
            lines.append(f"**Frameworks:** {', '.join(self.frameworks)}")
        lines.append("")

    # Key structure
    if self.key_directories:
        lines.append("## Key Directories")
        for dir in self.key_directories[:10]:  # Top 10
            lines.append(f"- `{dir}`")
        lines.append("")

    if self.key_files:
        lines.append("## Key Files")
        for file in self.key_files[:10]:  # Top 10
            lines.append(f"- `{file}`")
        lines.append("")

    # Statistics
    if self.statistics:
        lines.append("## Statistics")
        for key, value in self.statistics.items():
            if isinstance(value, dict):
                lines.append(f"**{key}:**")
                for k, v in value.items():
                    lines.append(f"  - {k}: {v}")
            else:
                lines.append(f"- **{key}:** {value}")
        lines.append("")

    # Patterns
    if self.patterns:
        lines.append("## Architectural Patterns")
        for pattern in self.patterns:
            lines.append(f"- {pattern}")
        lines.append("")

    return "\n".join(lines)
to_dict
Python
to_dict() -> Dict[str, Any]

Convert to dictionary representation.

Source code in tenets/models/summary.py
Python
def to_dict(self) -> Dict[str, Any]:
    """Convert to dictionary representation."""
    return {
        "name": self.name,
        "description": self.description,
        "structure": self.structure,
        "key_files": self.key_files,
        "key_directories": self.key_directories,
        "technologies": self.technologies,
        "frameworks": self.frameworks,
        "patterns": self.patterns,
        "dependencies": self.dependencies,
        "statistics": self.statistics,
        "recent_activity": self.recent_activity,
        "team_info": self.team_info,
        "metadata": self.metadata,
        "timestamp": self.timestamp.isoformat(),
    }
from_dictclassmethod
Python
from_dict(data: Dict[str, Any]) -> ProjectSummary

Create from dictionary.

Source code in tenets/models/summary.py
Python
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ProjectSummary":
    """Create from dictionary."""
    if "timestamp" in data and isinstance(data["timestamp"], str):
        data["timestamp"] = datetime.fromisoformat(data["timestamp"])
    return cls(**data)