Deep research

From rebyteai-template/rebyte-skills · View interactive version

Deep research is an AI agent skill from the GitHub repository rebyteai-template/rebyte-skills. Conduct enterprise-grade research with multi-source synthesis, citation tracking, and verification. Use when user needs comprehensive analysis requiring 10+ sources, verified claims, or comparison of approaches. Triggers include "deep research", "comprehensive analysis", "research report", "compare

How to use this skill

Skill file

Deep Research

<!-- STATIC CONTEXT BLOCK START - Optimized for prompt caching -->

<!-- All static instructions, methodology, and templates below this line -->

<!-- Dynamic content (user queries, results) added after this block -->

Core System Instructions

Purpose: Deliver citation-backed, verified research reports through 8-phase pipeline (Scope → Plan → Retrieve → Triangulate → Synthesize → Critique → Refine → Package) with source credibility scoring and progressive context management.

Context Strategy: This skill uses 2025 context engineering best practices:


Decision Tree (Execute First)

Request Analysis
├─ Simple lookup? → STOP: Use WebSearch, not this skill
├─ Debugging? → STOP: Use standard tools, not this skill
└─ Complex analysis needed? → CONTINUE

Mode Selection
├─ Initial exploration? → quick (3 phases, 2-5 min)
├─ Standard research? → standard (6 phases, 5-10 min) [DEFAULT]
├─ Critical decision? → deep (8 phases, 10-20 min)
└─ Comprehensive review? → ultradeep (8+ phases, 20-45 min)

Execution Loop (per phase)
├─ Load phase instructions from [methodology](./reference/methodology.md#phase-N)
├─ Execute phase tasks
├─ Spawn parallel agents if applicable
└─ Update progress

Validation Gate
├─ Run `python scripts/validate_report.py --report [path]`
├─ Pass? → Deliver
└─ Fail? → Fix (max 2 attempts) → Still fails? → Escalate

Workflow (Clarify → Plan → Act → Verify → Report)

AUTONOMY PRINCIPLE: This skill operates independently. Infer assumptions from query context. Only stop for critical errors or incomprehensible queries.

1. Clarify (Rarely Needed - Prefer Autonomy)

DEFAULT: Proceed autonomously. Derive assumptions from query signals.

ONLY ask if CRITICALLY ambiguous:

When in doubt: PROCEED with standard mode. User will redirect if incorrect.

Default assumptions:


2. Plan

Mode selection criteria:

Announce plan and execute:


3. Act (Phase Execution)

All modes execute:

Standard/Deep/UltraDeep execute:

Deep/UltraDeep execute:

Critical: Avoid "Loss in the Middle"

Progressive Context Loading:

Anti-Hallucination Protocol (CRITICAL):

Parallel Execution Requirements (CRITICAL for Speed):

Phase 3 RETRIEVE - Mandatory Parallel Search:

  1. Decompose query into 5-10 independent search angles before ANY searches
  2. Launch ALL searches in single message with multiple tool calls (NOT sequential)
  3. Quality threshold monitoring for FFS pattern:
  1. Spawn 3-5 parallel agents using Task tool for deep-dive investigations

Example correct execution:

[Single message with 8+ parallel tool calls]
WebSearch #1: Core topic semantic
WebSearch #2: Technical keywords
WebSearch #3: Recent 2024-2025 filtered
WebSearch #4: Academic domains
WebSearch #5: Critical analysis
WebSearch #6: Industry trends
Task agent #1: Academic paper analysis
Task agent #2: Technical documentation deep dive

❌ WRONG (sequential execution):

WebSearch #1 → wait for results → WebSearch #2 → wait → WebSearch #3...

✅ RIGHT (parallel execution):

All searches + agents launched simultaneously in one message

4. Verify (Always Execute)

Step 1: Citation Verification (Catches Fabricated Sources)

python scripts/verify_citations.py --report [path]

Checks:

If suspicious citations found:

Step 2: Structure & Quality Validation

python scripts/validate_report.py --report [path]

8 automated checks:

  1. Executive summary length (50-250 words)
  2. Required sections present (+ recommended: Claims table, Counterevidence)
  3. Citations formatted [1], [2], [3]
  4. Bibliography matches citations
  5. No placeholder text (TBD, TODO)
  6. Word count reasonable (500-10000)
  7. Minimum 10 sources
  8. No broken internal links

If fails:


5. Report

CRITICAL: Generate COMPREHENSIVE, DETAILED markdown reports

File Organization (CRITICAL - Clean Accessibility):

1. Create Organized Folder in /code:

2. Save All Formats to Same Folder:

Markdown (Primary Source):

HTML (McKinsey Style - ALWAYS GENERATE):

PDF (Professional Print - ALWAYS GENERATE):

3. File Naming Convention:

All files use same base name for easy matching:

Length Requirements (UNLIMITED with Progressive Assembly):

How Unlimited Length Works:

Progressive file assembly allows ANY report length by generating section-by-section.

Each section is written to file immediately (avoiding output token limits).

Complex topics with many findings? Generate 20, 30, 50+ findings - no constraint!

Content Requirements:

Writing Standards:

Bullet Point Policy (Anti-Fatigue Enforcement):

Anti-Fatigue Quality Check (Apply to EVERY Section):

Before considering a section complete, verify:

If ANY check fails: Regenerate the section before moving to next.

Source Attribution Standards (Critical for Preventing Fabrication):

Deliver to user:

  1. Executive summary (inline in chat)
  2. Organized folder path (e.g., "All files saved to: /code/Psilocybin_Research_20251104/")
  3. Confirmation of all three formats generated:
  1. Source quality assessment summary (source count)
  2. Next steps (if relevant)

Generation Workflow: Progressive File Assembly (Unlimited Length)

Phase 8.1: Setup

# Extract topic slug from research question
# Create folder: /code/[TopicName]_Research_[YYYYMMDD]/
mkdir -p /code/[folder_name]

# Create initial markdown file with frontmatter
# File path: [folder]/research_report_[YYYYMMDD]_[slug].md

Phase 8.2: Progressive Section Generation

CRITICAL STRATEGY: Generate and write each section individually to file using Write/Edit tools.

This allows unlimited report length while keeping each generation manageable.

OUTPUT TOKEN LIMIT SAFEGUARD (CRITICAL - Claude Code Default: 32K):

Claude Code default limit: 32,000 output tokens (≈24,000 words total per skill execution)

This is a HARD LIMIT and cannot be changed within the skill.

What this means:

Realistic report sizes per mode:

For reports >20,000 words:

User must run skill multiple times:

Auto-Continuation Strategy (TRUE Unlimited Length):

When report exceeds 18,000 words in single run:

  1. Generate sections 1-10 (stay under 18K words)
  2. Save continuation state file with context preservation
  3. Spawn continuation agent via Task tool
  4. Continuation agent: Reads state → Generates next batch → Spawns next agent if needed
  5. Chain continues recursively until complete

This achieves UNLIMITED length while respecting 32K limit per agent

Initialize Citation Tracking:

citations_used = []  # Maintain this list in working memory throughout

Section Generation Loop:

Pattern: Generate section content → Use Write/Edit tool with that content → Move to next section

Each Write/Edit call contains ONE section (≤2,000 words per call)

  1. Executive Summary (200-400 words)
  1. Introduction (400-800 words)
  1. Finding 1 (600-2,000 words)
  1. Finding 2 (600-2,000 words)

... Continue for ALL findings (each finding = one Edit tool call, ≤2,000 words)

CRITICAL: If you have 10 findings × 1,500 words each = 15,000 words of findings

This is OKAY because each Edit call is only 1,500 words (under 2,000 word limit per tool call)

The FILE grows to 15,000 words, but no single tool call exceeds limits

  1. Synthesis & Insights
  1. Limitations & Caveats
  1. Recommendations
  1. Bibliography (CRITICAL - ALL Citations)
  1. Methodology Appendix

Phase 8.3: Auto-Continuation Decision Point

After generating sections, check word count:

If total output ≤18,000 words: Complete normally

If total output will exceed 18,000 words: Auto-Continuation Protocol

Step 1: Save Continuation State

Create file: /code/research_output/continuation_state_[report_id].json

{
  "version": "2.1.1",
  "report_id": "[unique_id]",
  "file_path": "[absolute_path_to_report.md]",
  "mode": "[quick|standard|deep|ultradeep]",

  "progress": {
    "sections_completed": [list of section IDs done],
    "total_planned_sections": [total count],
    "word_count_so_far": [current word count],
    "continuation_count": [which continuation this is, starts at 1]
  },

  "citations": {
    "used": [1, 2, 3, ..., N],
    "next_number": [N+1],
    "bibliography_entries": [
      "[1] Full citation entry",
      "[2] Full citation entry",
      ...
    ]
  },

  "research_context": {
    "research_question": "[original question]",
    "key_themes": ["theme1", "theme2", "theme3"],
    "main_findings_summary": [
      "Finding 1: [100-word summary]",
      "Finding 2: [100-word summary]",
      ...
    ],
    "narrative_arc": "[Current position in story: beginning/middle/conclusion]"
  },

  "quality_metrics": {
    "avg_words_per_finding": [calculated average],
    "citation_density": [citations per 1000 words],
    "prose_vs_bullets_ratio": [e.g., "85% prose"],
    "writing_style": "technical-precise-data-driven"
  },

  "next_sections": [
    {"id": N, "type": "finding", "title": "Finding X", "target_words": 1500},
    {"id": N+1, "type": "synthesis", "title": "Synthesis", "target_words": 1000},
    ...
  ]
}

Step 2: Spawn Continuation Agent

Use Task tool with general-purpose agent:

Task(
  subagent_type="general-purpose",
  description="Continue deep-research report generation",
  prompt="""
CONTINUATION TASK: You are continuing an existing deep-research report.

CRITICAL INSTRUCTIONS:
1. Read continuation state file: /code/research_output/continuation_state_[report_id].json
2. Read existing report to understand context: [file_path from state]
3. Read LAST 3 completed sections to understand flow and style
4. Load research context: themes, narrative arc, writing style from state
5. Continue citation numbering from state.citations.next_number
6. Maintain quality metrics from state (avg words, citation density, prose ratio)

CONTEXT PRESERVATION:
- Research question: [from state]
- Key themes established: [from state]
- Findings so far: [summaries from state]
- Narrative position: [from state]
- Writing style: [from state]

YOUR TASK:
Generate next batch of sections (stay under 18,000 words):
[List next_sections from state]

Use Write/Edit tools to append to existing file: [file_path]

QUALITY GATES (verify before each section):
- Words per section: Within ±20% of [avg_words_per_finding]
- Citation density: Match [citation_density] ±0.5 per 1K words
- Prose ratio: Maintain ≥80% prose (not bullets)
- Theme alignment: Section ties to key_themes
- Style consistency: Match [writing_style]

After generating sections:
- If more sections remain: Update state, spawn next continuation agent
- If final sections: Generate complete bibliography, verify report, cleanup state file

HANDOFF PROTOCOL (if spawning next agent):
1. Update continuation_state.json with new progress
2. Add new citations to state
3. Add summaries of new findings to state
4. Update quality metrics
5. Spawn next agent with same instructions
"""
)

Step 3: Report Continuation Status

Tell user:

📊 Report Generation: Part 1 Complete (N sections, X words)
🔄 Auto-continuing via spawned agent...
   Next batch: [section list]
   Progress: [X%] complete

Phase 8.4: Continuation Agent Quality Protocol

When continuation agent starts:

Context Loading (CRITICAL):

  1. Read continuation_state.json → Load ALL context
  2. Read existing report file → Review last 3 sections
  3. Extract patterns:

Pre-Generation Checklist:

Per-Section Generation:

  1. Generate section content
  2. Quality checks:
  1. If ANY check fails: Regenerate section
  2. If passes: Write to file, update state

Handoff Decision:

Final Agent Responsibilities:

Anti-Fatigue Built-In:

Each agent generates manageable chunks (≤18K words), maintaining quality.

Context preservation ensures coherence across continuation boundaries.

Generate HTML (McKinsey Style)

  1. Read McKinsey template from ./templates/mckinsey_report_template.html
  2. Extract 3-4 key quantitative metrics from findings for dashboard
  3. Use Python script for MD to HTML conversion:

```bash

cd ~/.claude/skills/deep-research

python scripts/md_to_html.py [markdown_report_path]

```

The script returns two parts:

CRITICAL: The script handles ALL conversion automatically:

  1. Add Citation Tooltips (Attribution Gradients):

For each [N] citation in {{CONTENT}} (not bibliography), optionally add interactive tooltips:

```html

<span class="citation">[N]

<span class="citation-tooltip">

<div class="tooltip-title">[Source Title]</div>

<div class="tooltip-source">[Author/Publisher]</div>

<div class="tooltip-claim">

<div class="tooltip-claim-label">Supports Claim:</div>

[Extract sentence with this citation]

</div>

</span>

</span>

```

NOTE: This step is optional for speed. Basic [N] citations are sufficient.

  1. Replace placeholders in template:
  1. CRITICAL: NO EMOJIS - Remove any emoji characters from final HTML
  1. Save to: [folder]/research_report_[YYYYMMDD]_[slug].html
  1. Verify HTML (MANDATORY):

```bash

python scripts/verify_html.py --html [html_path] --md [md_path]

```

  1. Open in browser: open [html_path]

Generate PDF

  1. Use Task tool with general-purpose agent
  2. Invoke generating-pdf skill with markdown as input
  3. Save to: [folder]/research_report_[YYYYMMDD]_[slug].pdf
  4. PDF will auto-open when complete

Output Contract

Format: Comprehensive markdown report following template EXACTLY

Required sections (all must be detailed):

Bibliography Requirements (ZERO TOLERANCE - Report is UNUSABLE without complete bibliography):

Strictly Prohibited:

Writing Standards (Critical):

Quality gates (enforced by validator):


Error Handling & Stop Rules

Stop immediately if:

Graceful degradation:

Error format:

⚠️ Issue: [Description]
📊 Context: [What was attempted]
🔍 Tried: [Resolution attempts]
💡 Options:
   1. [Option 1]
   2. [Option 2]
   3. [Option 3]

Quality Standards (Always Enforce)

Every report must:

Priority: Thoroughness over speed. Quality > speed.


Inputs & Assumptions

Required:

Optional:

Assumptions:


When to Use / NOT Use

Use when:

Do NOT use:


Scripts (Offline, Python stdlib only)

Location: ./scripts/

No external dependencies required.


Progressive References (Load On-Demand)

Do not inline these - reference only:

Context Management: Load files on-demand for current phase only. Do not preload all content.


<!-- STATIC CONTEXT BLOCK END -->

<!-- ⚡ Above content is cacheable (>1024 tokens, static) -->

<!-- 📝 Below: Dynamic content (user queries, retrieved data, generated reports) -->

<!-- This structure enables 85% latency reduction via prompt caching -->


Dynamic Execution Zone

User Query Processing:

[User research question will be inserted here during execution]

Retrieved Information:

[Search results and sources will be accumulated here]

Generated Analysis:

[Findings, synthesis, and report content generated here]

Note: This section remains empty in the skill definition. Content populated during runtime only.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.