Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
0905ed4
feat(backend): Mermaid diagrams for cluster chapter index pages
github-actions[bot] May 22, 2026
56d610f
fix(backend): address Copilot review comments on diagram generation
github-actions[bot] May 22, 2026
727a17b
fix(backend): fix all diagram generation bugs found during live testing
github-actions[bot] May 22, 2026
01d9696
fix(backend): architecture diagram — show only connected nodes, switc…
github-actions[bot] May 22, 2026
3e82cf8
feat(backend): fully agentic diagram generation with external prompt …
github-actions[bot] May 22, 2026
b343204
refactor(backend): migrate all inline LLM prompts to backend/app/prom…
github-actions[bot] May 22, 2026
cca6f4f
fix(tests): update diagram tests for no-cap and agentic-only interfaces
github-actions[bot] May 22, 2026
a567f09
feat(backend): Mermaid syntax references + stateDiagram for architect…
github-actions[bot] May 22, 2026
969a2f2
feat(spa): interactive Mermaid diagram viewer with pan + zoom modal
github-actions[bot] May 22, 2026
5b9418d
fix(web): Mermaid diagram viewer — fix modal SVG, inline zoom, controls
github-actions[bot] May 22, 2026
0721c03
fix(web): scope zoom to diagram SVG only, not MUI icon buttons
github-actions[bot] May 22, 2026
40c795c
fix(backend,web): address Copilot review comments
github-actions[bot] May 22, 2026
0879d68
fix(prompts): data model — only include entities DEFINED in cluster f…
github-actions[bot] May 22, 2026
b144977
fix(backend): delete stale page files after wiki regeneration
github-actions[bot] May 22, 2026
47cc60e
fix: address second round of Copilot review comments
github-actions[bot] May 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 5 additions & 110 deletions backend/app/core/ask_prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,132 +13,27 @@
- Multi-step research planning (Q&A is direct)
"""

from app.prompts import load_prompt

from datetime import datetime

# =============================================================================
# WORKFLOW INSTRUCTIONS
# =============================================================================

ASK_WORKFLOW_INSTRUCTIONS = """# Ask Tool — Agentic Q&A

You are a code expert answering questions about a software repository.
Today's date is {date}.

## Your Goal

Answer the user's question **accurately and concisely**, citing specific files
and symbols. You have access to tools that search the codebase at different
levels of detail. Use them strategically.

## Conversation Follow-ups

If a `## Conversation History` section is present in the user's message, the
current question may be a follow-up to a prior exchange. Use the history to:
- Resolve pronouns and references ("it", "that function", "the same module")
- Avoid re-explaining things already covered
- Focus on what is *new* or *different* in the current question

Do NOT summarise prior answers — just use them as context.

## Mandatory Workflow (FOLLOW THIS ORDER)

1. **Discover** — call `search_symbols` (or `query_graph` for precise filters)
to find relevant classes, functions, and modules. This is cheap (~50 tokens/result).
Call multiple searches in parallel when investigating different aspects.

2. **Connect** — call `get_relationships` for the 2-3 most relevant symbols to
understand how they relate (callers, callees, inheritance, imports).
In project mode, if `find_cross_repo_links` is available, use it for questions
about cross-repo integration, API contracts, shared DTOs, clients/servers,
FFI/ABI, protobuf/gRPC, GraphQL, BDD, or CLI boundaries. Treat those direct
project links as high-confidence evidence.

3. **Read selectively** — call `get_code` ONLY for the 2-4 symbols you truly need
to read. This is expensive (~200-2000 tokens). Do NOT dump every search result
into get_code.

4. **Documentation** — call `search_docs` if the question is about project
setup, configuration, or high-level architecture described in documentation
(README, guides, etc.). Skip this for pure code questions.

5. **Answer** — synthesize your findings into a clear, concise response.
Reference files by path and symbols by name.

## Iteration Budget

You have a maximum of **{max_iterations} tool calls**. Most questions need 3-6.
If you've used 5+ tool calls and haven't found what you need, synthesize what
you have and note the gaps.

## When to Stop Searching

Stop and answer when:
- You have code evidence for your claims
- Your last 2 searches returned similar/overlapping results
- You can answer the specific question asked (don't over-research)

## Citation Style (MANDATORY)

Reference code **naturally by file path and symbol name**. Do NOT use [N] numeric citations.

In prose:
- "The `authenticate()` function in `auth/auth_manager.py` handles token validation"
- "Session management is implemented in `services/session.py`"

In code blocks — always include the file path as a comment header:
```python
# auth/auth_manager.py
def authenticate(token: str) -> bool:
...
```

At the end of your answer, include:
---
**Files Referenced:**
- `path/to/file.py` — Brief description
"""
ASK_WORKFLOW_INSTRUCTIONS: str = load_prompt("ask/workflow_instructions.md")

# =============================================================================
# TOOL USAGE GUIDANCE
# =============================================================================

ASK_TOOL_INSTRUCTIONS = """# Tool Tips

Each tool has its own description — read it. Below are cost/strategy hints only.

| Tool | Cost | When to use |
|------|------|-------------|
| `search_symbols` | Cheap | First step — discover classes, functions, modules |
| `find_cross_repo_links` | Cheap | Project mode only — direct API-surface/contracts between repos |
| `get_relationships` | Medium | After finding key symbols — see callers, callees, inheritance |
| `get_code` | **Expensive** | Only 2-4 key symbols — reads full source |
| `search_docs` | Medium | README / config / architecture questions only |
| `query_graph` | Cheap | Precise JQL filters (`type:class file:src/auth/*`) |
| `think` | Free | 1-2 sentences to decide next step |

Call multiple `search_symbols` in parallel for different aspects.
Do NOT call `get_code` on every search result — be selective.
"""
ASK_TOOL_INSTRUCTIONS: str = load_prompt("ask/tool_instructions.md")

# =============================================================================
# OUTPUT FORMAT
# =============================================================================

ASK_OUTPUT_INSTRUCTIONS = """# Output Format

Your response should be:
1. **Direct** — Answer the question first, then provide supporting details
2. **Structured** — Use headers (##) for sections, bullets for lists, code blocks with file headers
3. **Concise** — Focus on what was asked. Don't explain tangential systems
4. **Evidence-based** — Every claim references a specific file/symbol
5. **Honest** — If context is insufficient, say so clearly

Do NOT:
- Generate a "Research Report" with executive summaries
- List every file you searched
- Explain your search process
- Use [N] numeric citations
"""
ASK_OUTPUT_INSTRUCTIONS: str = load_prompt("ask/output_instructions.md")

# =============================================================================
# COMBINED SYSTEM PROMPT
Expand Down
108 changes: 5 additions & 103 deletions backend/app/core/ask_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from langchain_core.documents import Document
from langchain_core.messages import HumanMessage, SystemMessage

from app.prompts import load_prompt
from app.services.llm_factory import is_bedrock_llm, make_cached_system_message

from .repository_analysis_store import (
Expand Down Expand Up @@ -65,113 +66,14 @@ class AskResponse:


# System prompt for query optimization (uses repository context like wiki structure generation)
QUERY_OPTIMIZATION_SYSTEM_PROMPT = """You are a search query optimizer for code repositories.

Your task is to transform user questions into optimized retrieval queries that will find the most relevant code and documentation in a vector store.

**QUERY OPTIMIZATION STRATEGY:**
- Identify key technical terms, component names, and concepts from the repository context
- Include specific file names, folder paths, and symbol names when relevant
- Combine topic keywords with implementation-specific terms
- Add related functionality and patterns that may appear in code
- Use both high-level concepts and low-level implementation details

**OUTPUT FORMAT:**
Return ONLY the optimized search query - a space-separated list of relevant terms.
Do NOT include explanations, quotes, or any other text."""

QUERY_OPTIMIZATION_USER_PROMPT = """## Repository Context
{repository_context}

## User Question
"{question}"

**TASK:** Generate an optimized retrieval query that will find the most relevant code and documentation.

**QUERY OPTIMIZATION EXAMPLE:**
For a question about "How does authentication work?":
Generated Query: "authentication login logout session token JWT user validation security middleware auth_manager password hashing access control authorization user_service security_config"

This query combines topic keywords with file-specific terms and related functionality.

**Return ONLY the optimized query (space-separated terms), nothing else:**"""

QUERY_OPTIMIZATION_SYSTEM_PROMPT: str = load_prompt("ask/query_optimization_system.md")
QUERY_OPTIMIZATION_USER_PROMPT: str = load_prompt("ask/query_optimization_user.md")

# System prompt for answer generation with natural code citations
ANSWER_SYSTEM_PROMPT = """You are a helpful assistant answering questions about a code repository.

You have access to the repository's documentation, code, and architecture analysis.
Use the provided context to answer questions accurately and comprehensively.

## CITATION STYLE (NATURAL FILE REFERENCES)

**Reference code naturally by file path and symbol name - do NOT use [N] numeric citations.**

### In Prose:
- "The `authenticate()` function in `auth/auth_manager.py` handles token validation"
- "Session management is implemented via `SessionStore` class in `services/session.py`"
- "The configuration is loaded from `config/settings.py`"

### In Code Blocks:
Always include the file path as a comment header:
```python
# auth/auth_manager.py
def authenticate(token: str) -> bool:
...
```

### Multiple File References:
- "The authentication flow spans `auth/login.py` → `auth/auth_manager.py` → `services/session.py`"
- "Both `UserModel` in `models/user.py` and `UserService` in `services/user.py` are involved"

## RESPONSE GUIDELINES

1. **Be Accurate**: Only state facts supported by the provided context
2. **Be Specific**: Reference actual file paths, function names, and class names naturally in text
3. **Be Structured**: Use headers, bullet points, and code blocks for clarity
4. **Acknowledge Gaps**: If context is insufficient, say so clearly
5. **Show Code**: Include relevant code snippets with file path headers

## FORMAT

Use clear markdown:
- Headers (##) for major sections
- Code blocks with language tags and file path comments
- Bullet points for lists
- `backticks` for inline code/file references
- Natural file path mentions (not [N] citations)

## SOURCES SUMMARY

At the end of your response, include a brief summary:
---
**📁 Files Referenced:**
- `path/to/file.py` — Brief description of what was used from this file
"""


ANSWER_USER_PROMPT = """## Retrieved Code Context

{context}

## Available Sources
{sources_reference}

## User Question

{question}

---
ANSWER_SYSTEM_PROMPT: str = load_prompt("ask/answer_system.md")

**INSTRUCTIONS:**
1. Answer the question comprehensively based on the code context above
2. Reference files naturally by path (e.g., "in `path/to/file.py`") - do NOT use [N] citations
3. Include relevant code snippets with file path headers as comments
4. Reference specific symbol names (classes, functions, methods)
5. End with a "📁 Files Referenced" summary
6. If the context doesn't contain enough information, state this clearly

**Provide your answer:**"""
ANSWER_USER_PROMPT: str = load_prompt("ask/answer_user.md")


class AskTool:
Expand Down
Loading
Loading