Skip to content

Index

code_context_agent.agent

Agent orchestration package for code context analysis.

This package provides the core agent functionality: - create_agent: Factory function to create configured analysis agents - run_analysis: Async function to run analysis with event streaming - get_prompt: Dynamic prompt rendering from Jinja2 templates - Hooks: Quality guidance via standard HookProvider pattern

create_agent

create_agent(mode='standard')

Create a configured agent for code context analysis.

Parameters:

Name Type Description Default
mode str

Analysis mode ("standard", "full", "full+focus", "focus", "incremental").

'standard'

Returns:

Type Description
Agent

Configured Agent instance ready for analysis.

Source code in src/code_context_agent/agent/factory.py
def create_agent(mode: str = "standard") -> Agent:
    """Create a configured agent for code context analysis.

    Args:
        mode: Analysis mode ("standard", "full", "full+focus", "focus", "incremental").

    Returns:
        Configured Agent instance ready for analysis.
    """
    settings = get_settings()

    logger.info(
        f"Creating agent: model={settings.model_id}, region={settings.region}, mode={mode}, thinking=adaptive",
    )

    # Create Bedrock model with adaptive thinking and 1M context
    model = BedrockModel(
        model_id=settings.model_id,
        region_name=settings.region,
        temperature=settings.temperature,
        additional_request_fields={
            "thinking": {"type": "adaptive"},
            "anthropic_beta": ["context-1m-2025-08-07"],
        },
    )

    # Render system prompt from Jinja2 template (mode-aware)
    system_prompt = get_prompt(mode=mode)

    tools = get_analysis_tools()

    # Full mode gets FailFastHook for strict error handling
    full_mode = mode in ("full", "full+focus")
    hooks = create_all_hooks(full_mode=full_mode)

    logger.info(f"Agent configured with {len(tools)} tools, {len(hooks)} hooks, mode={mode}")

    return Agent(
        model=model,
        tools=tools,
        system_prompt=system_prompt,
        structured_output_model=AnalysisResult,
        hooks=hooks,
        callback_handler=None,
    )

get_analysis_tools

get_analysis_tools()

Get the list of tools for code analysis.

Returns:

Type Description
list[Any]

List of tool functions and MCP tool providers for the agent.

Source code in src/code_context_agent/agent/factory.py
def get_analysis_tools() -> list[Any]:
    """Get the list of tools for code analysis.

    Returns:
        List of tool functions and MCP tool providers for the agent.
    """
    # Import tools here to avoid circular imports
    # Import graph from strands_tools, but use custom shell for proper STDIO capture
    from strands_tools import graph

    from ..tools import (
        astgrep_inline_rule,
        astgrep_scan,
        astgrep_scan_rule_pack,
        create_file_manifest,
        git_blame_summary,
        git_contributors,
        git_diff_file,
        git_file_history,
        git_files_changed_together,
        git_hotspots,
        git_recent_commits,
        read_file_bounded,
        repomix_bundle,
        repomix_bundle_with_context,
        repomix_compressed_signatures,
        repomix_json_export,
        repomix_orientation,
        repomix_split_bundle,
        rg_search,
        write_file,
        write_file_list,
    )
    from ..tools.clones import detect_clones
    from ..tools.graph import (
        code_graph_analyze,
        code_graph_create,
        code_graph_explore,
        code_graph_export,
        code_graph_ingest_astgrep,
        code_graph_ingest_git,
        code_graph_ingest_lsp,
        code_graph_load,
        code_graph_save,
        code_graph_stats,
    )
    from ..tools.graph.tools import (
        code_graph_ingest_clones,
        code_graph_ingest_inheritance,
        code_graph_ingest_rg,
        code_graph_ingest_tests,
    )
    from ..tools.lsp import (
        lsp_definition,
        lsp_diagnostics,
        lsp_document_symbols,
        lsp_hover,
        lsp_references,
        lsp_shutdown,
        lsp_start,
        lsp_workspace_symbols,
    )
    from ..tools.shell_tool import shell

    tools: list[Any] = [
        # Discovery tools
        create_file_manifest,
        repomix_orientation,
        repomix_bundle,
        repomix_bundle_with_context,
        repomix_compressed_signatures,
        repomix_json_export,
        repomix_split_bundle,
        rg_search,
        write_file,
        write_file_list,
        read_file_bounded,
        # Git history tools (coupling, evolution, authorship)
        git_files_changed_together,
        git_file_history,
        git_recent_commits,
        git_diff_file,
        git_blame_summary,
        git_hotspots,
        git_contributors,
        # LSP tools
        lsp_start,
        lsp_document_symbols,
        lsp_hover,
        lsp_references,
        lsp_definition,
        lsp_workspace_symbols,
        lsp_diagnostics,
        lsp_shutdown,
        # ast-grep tools (rule packs + ad-hoc + inline)
        astgrep_scan,
        astgrep_scan_rule_pack,
        astgrep_inline_rule,
        # Shell for custom commands
        shell,
        # Code graph analysis
        code_graph_create,
        code_graph_ingest_lsp,
        code_graph_ingest_astgrep,
        code_graph_ingest_rg,
        code_graph_ingest_inheritance,
        code_graph_ingest_tests,
        code_graph_ingest_git,
        code_graph_ingest_clones,
        # Code health tools
        detect_clones,
        code_graph_analyze,
        code_graph_explore,
        code_graph_export,
        code_graph_save,
        code_graph_load,
        code_graph_stats,
        # Multi-agent DAG orchestration
        graph,
    ]

    # Add context7 MCP server for library documentation lookup
    context7_provider = _create_context7_provider()
    if context7_provider is not None:
        tools.append(context7_provider)

    return tools

get_prompt

get_prompt(mode='standard')

Render the unified system prompt.

Parameters:

Name Type Description Default
mode str

Analysis mode ("standard" or "full").

'standard'

Returns:

Type Description
str

Rendered system prompt string from system.md.j2

Source code in src/code_context_agent/agent/prompts.py
def get_prompt(mode: str = "standard") -> str:
    """Render the unified system prompt.

    Args:
        mode: Analysis mode ("standard" or "full").

    Returns:
        Rendered system prompt string from system.md.j2
    """
    return render_prompt("system.md.j2", mode=mode)

run_analysis async

run_analysis(
    repo_path,
    output_dir=None,
    focus=None,
    consumer=None,
    quiet=False,
    issue_context=None,
    since_context=None,
    mode="standard",
)

Run code context analysis on a repository.

This function orchestrates the analysis by: 1. Creating an agent with tools, prompt, hooks, and structured output 2. Wrapping it with ag-ui-strands for typed event streaming 3. Streaming events to the consumer for display 4. Returning analysis results

Parameters:

Name Type Description Default
repo_path str | Path

Path to the repository to analyze.

required
output_dir str | Path | None

Output directory for context files. Defaults to repo/.code-context

None
focus str | None

Optional focus area to steer analysis (e.g., "authentication", "API layer").

None
consumer EventConsumer | None

Event consumer for display. Defaults to RichEventConsumer.

None
quiet bool

If True and no consumer, use QuietConsumer.

False
issue_context str | None

Optional XML-wrapped issue context for issue-focused analysis.

None
since_context str | None

Optional XML-wrapped incremental analysis context from --since.

None
mode str

Analysis mode ("standard", "full", "full+focus", "focus", "incremental").

'standard'

Returns:

Type Description
dict[str, Any]

Dict with analysis status and output paths.

Source code in src/code_context_agent/agent/runner.py
async def run_analysis(
    repo_path: str | Path,
    output_dir: str | Path | None = None,
    focus: str | None = None,
    consumer: EventConsumer | None = None,
    quiet: bool = False,
    issue_context: str | None = None,
    since_context: str | None = None,
    mode: str = "standard",
) -> dict[str, Any]:
    """Run code context analysis on a repository.

    This function orchestrates the analysis by:
    1. Creating an agent with tools, prompt, hooks, and structured output
    2. Wrapping it with ag-ui-strands for typed event streaming
    3. Streaming events to the consumer for display
    4. Returning analysis results

    Args:
        repo_path: Path to the repository to analyze.
        output_dir: Output directory for context files. Defaults to repo/.code-context
        focus: Optional focus area to steer analysis (e.g., "authentication", "API layer").
        consumer: Event consumer for display. Defaults to RichEventConsumer.
        quiet: If True and no consumer, use QuietConsumer.
        issue_context: Optional XML-wrapped issue context for issue-focused analysis.
        since_context: Optional XML-wrapped incremental analysis context from --since.
        mode: Analysis mode ("standard", "full", "full+focus", "focus", "incremental").

    Returns:
        Dict with analysis status and output paths.
    """
    # Setup phase
    context = _setup_analysis_context(repo_path, output_dir, consumer, quiet, mode=mode)

    # Build prompt
    prompt = _build_analysis_prompt(context.repo, context.output, focus, issue_context, since_context)

    # Execution phase
    try:
        stream_result = await _execute_analysis_stream(context, prompt)
    finally:
        await _cleanup_context(context)

    # Build final result
    context_path = context.output / "CONTEXT.md"

    return {
        "status": stream_result.status,
        "error": stream_result.error_message,
        "exceeded_limit": stream_result.exceeded_limit,
        "turn_count": stream_result.turn_count,
        "duration_seconds": stream_result.duration_seconds,
        "repo_path": str(context.repo),
        "output_dir": str(context.output),
        "context_path": str(context_path) if context_path.exists() else None,
    }

run_analysis_sync

run_analysis_sync(repo_path, output_dir=None, quiet=False)

Synchronous wrapper for run_analysis.

Parameters:

Name Type Description Default
repo_path str | Path

Path to the repository.

required
output_dir str | Path | None

Output directory for context files.

None
quiet bool

Suppress live display.

False

Returns:

Type Description
dict[str, Any]

Dict with analysis status and output paths.

Source code in src/code_context_agent/agent/runner.py
def run_analysis_sync(
    repo_path: str | Path,
    output_dir: str | Path | None = None,
    quiet: bool = False,
) -> dict[str, Any]:
    """Synchronous wrapper for run_analysis.

    Args:
        repo_path: Path to the repository.
        output_dir: Output directory for context files.
        quiet: Suppress live display.

    Returns:
        Dict with analysis status and output paths.
    """
    return asyncio.run(
        run_analysis(
            repo_path=repo_path,
            output_dir=output_dir,
            quiet=quiet,
        ),
    )