Skip to main content

scripts-strategy-brief-generator

#!/usr/bin/env python3 """

title: "Strategy Brief Generator" component_type: script version: "1.0.0" audience: contributor status: stable summary: "Strategy Brief Generator ========================" keywords: ['analysis', 'brief', 'generation', 'generator', 'review'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "strategy-brief-generator.py" language: python executable: true usage: "python3 scripts/strategy-brief-generator.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: false

Strategy Brief Generator

Generate executive strategy briefs with multi-agent research coordination. Produces McKinsey/BCG/Bain-quality market and competitive analysis deliverables.

Usage: python3 scripts/strategy-brief-generator.py --industry "AI Development Tools" python3 scripts/strategy-brief-generator.py --industry "FinTech" --geography "APAC" --output brief.md

Arguments: --industry Industry to analyze (required) --geography Geographic scope (default: Global) --time-horizon Analysis timeframe (default: 12-24 months) --client-type Perspective: Incumbent Expanding, New Entrant, Investor --competitors Number of competitors to analyze (3-10, default: 5) --trends Number of trends to identify (5-12, default: 8) --output Output file path (default: stdout) --format Output format: markdown, json (default: markdown)

Source: Adapted from ANALYZE-REVIEW/extracted-consulting/strategy_brief_system.py """

import argparse import asyncio import json import sys from dataclasses import dataclass, field, asdict from datetime import datetime, timezone from enum import Enum from pathlib import Path from typing import Dict, List, Optional, Any

class AgentRole(Enum): """Specialized research agent roles.""" ORCHESTRATOR = "orchestrator" MARKET_RESEARCHER = "market_researcher" COMPETITIVE_ANALYST = "competitive_analyst" TREND_ANALYST = "trend_analyst" FRAMEWORK_SPECIALIST = "framework_specialist" SYNTHESIS_WRITER = "synthesis_writer" QA_VALIDATOR = "qa_validator"

class BriefSection(Enum): """Strategy brief sections in order.""" EXECUTIVE_SNAPSHOT = "executive_snapshot" MARKET_CONTEXT = "market_context" TRENDS_THREATS = "trends_threats" COMPETITIVE_LANDSCAPE = "competitive_landscape" STRATEGIC_FRAMEWORKS = "strategic_frameworks" GROWTH_OPTIONS = "growth_options" ONE_PAGE_BRIEF = "one_page_brief" DISCLAIMERS = "disclaimers"

@dataclass class BriefParameters: """Input parameters for strategy brief generation.""" industry: str geography: str = "Global" time_horizon: str = "12-24 months" client_type: str = "Incumbent Expanding" focus_areas: List[str] = field(default_factory=list) exclude_topics: List[str] = field(default_factory=list) competitor_count: int = 5 trend_count: int = 8 require_data_validation: bool = True require_financial_metrics: bool = True

def validate(self) -> tuple[bool, Optional[str]]:
"""Validate input parameters."""
if not self.industry or len(self.industry) < 3:
return False, "Industry must be specified (min 3 characters)"
if self.competitor_count < 3 or self.competitor_count > 10:
return False, "Competitor count must be between 3-10"
if self.trend_count < 5 or self.trend_count > 12:
return False, "Trend count must be between 5-12"
if self.client_type not in ["Incumbent Expanding", "New Entrant", "Investor"]:
return False, "Client type must be: Incumbent Expanding, New Entrant, or Investor"
return True, None

@dataclass class ResearchFindings: """Structured research output from agents.""" section: BriefSection content: Dict[str, Any] sources: List[str] confidence_score: float data_gaps: List[str] validation_notes: str token_usage: int agent_id: str timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))

class TokenBudgetManager: """Manage token allocation across agents."""

BUDGET_BY_SECTION = {
BriefSection.EXECUTIVE_SNAPSHOT: 15_000,
BriefSection.MARKET_CONTEXT: 25_000,
BriefSection.TRENDS_THREATS: 30_000,
BriefSection.COMPETITIVE_LANDSCAPE: 40_000,
BriefSection.STRATEGIC_FRAMEWORKS: 20_000,
BriefSection.GROWTH_OPTIONS: 25_000,
BriefSection.ONE_PAGE_BRIEF: 10_000,
BriefSection.DISCLAIMERS: 5_000,
}

def __init__(self, total_budget: int = 180_000):
self.total_budget = total_budget
self.allocated: Dict[str, int] = {}
self.used: Dict[str, int] = {}

def allocate(self, agent_id: str, section: BriefSection) -> int:
"""Allocate tokens for agent task."""
budget = self.BUDGET_BY_SECTION.get(section, 15_000)
self.allocated[agent_id] = budget
return budget

def record_usage(self, agent_id: str, tokens: int):
"""Record actual token usage."""
self.used[agent_id] = tokens

def get_remaining_budget(self) -> int:
"""Calculate remaining budget."""
return self.total_budget - sum(self.used.values())

def get_efficiency_report(self) -> Dict[str, Any]:
"""Generate efficiency metrics."""
total_allocated = sum(self.allocated.values())
total_used = sum(self.used.values())
return {
'total_allocated': total_allocated,
'total_used': total_used,
'efficiency': total_used / total_allocated if total_allocated else 0,
'remaining': self.get_remaining_budget(),
}

class StrategyBriefGenerator: """Main interface for strategy brief generation."""

def __init__(self):
self.token_manager = TokenBudgetManager()
self.findings: Dict[BriefSection, ResearchFindings] = {}

async def generate_brief(self, params: BriefParameters) -> Dict[str, Any]:
"""
Generate complete strategy brief.

Args:
params: Brief generation parameters

Returns:
Dict with brief content, metadata, and quality metrics
"""
# Validate parameters
valid, error = params.validate()
if not valid:
raise ValueError(f"Invalid parameters: {error}")

print(f"\n{'=' * 80}")
print(f"GENERATING STRATEGY BRIEF: {params.industry}")
print(f"Geography: {params.geography} | Horizon: {params.time_horizon}")
print(f"Client Type: {params.client_type}")
print(f"{'=' * 80}\n")

# Execute research stages
await self._execute_stage1_research(params)
await self._execute_stage2_frameworks(params)
await self._execute_stage3_strategy(params)
await self._execute_stage4_synthesis(params)

# Assemble final brief
brief = self._assemble_brief(params)
metadata = self._generate_metadata(params)
quality = self._calculate_quality_metrics()

return {
'brief': brief,
'metadata': metadata,
'quality_metrics': quality,
'token_efficiency': self.token_manager.get_efficiency_report()
}

async def _execute_stage1_research(self, params: BriefParameters):
"""Stage 1: Foundational Research (parallel)."""
print("Stage 1: Foundational Research...")

# In production, these would run in parallel with actual LLM calls
for section in [BriefSection.MARKET_CONTEXT, BriefSection.COMPETITIVE_LANDSCAPE,
BriefSection.TRENDS_THREATS]:
budget = self.token_manager.allocate(f"stage1_{section.value}", section)
print(f" - {section.value}: {budget:,} tokens allocated")

# Mock findings (in production: actual agent calls)
self.findings[section] = ResearchFindings(
section=section,
content={"status": "research_complete", "industry": params.industry},
sources=["Industry Report 2024", "Market Analysis Q4"],
confidence_score=0.85,
data_gaps=["Specific revenue figures require validation"],
validation_notes="Based on publicly available data",
token_usage=int(budget * 0.7),
agent_id=f"researcher_{section.value}"
)
self.token_manager.record_usage(f"stage1_{section.value}",
int(budget * 0.7))

async def _execute_stage2_frameworks(self, params: BriefParameters):
"""Stage 2: Framework Application (sequential)."""
print("Stage 2: Framework Application...")

section = BriefSection.STRATEGIC_FRAMEWORKS
budget = self.token_manager.allocate("stage2_frameworks", section)
print(f" - {section.value}: {budget:,} tokens allocated")

self.findings[section] = ResearchFindings(
section=section,
content={"swot": {}, "porters": {}},
sources=["Internal analysis"],
confidence_score=0.90,
data_gaps=[],
validation_notes="Framework application complete",
token_usage=int(budget * 0.6),
agent_id="framework_specialist"
)
self.token_manager.record_usage("stage2_frameworks", int(budget * 0.6))

async def _execute_stage3_strategy(self, params: BriefParameters):
"""Stage 3: Strategy Development (sequential)."""
print("Stage 3: Strategy Development...")

section = BriefSection.GROWTH_OPTIONS
budget = self.token_manager.allocate("stage3_strategy", section)
print(f" - {section.value}: {budget:,} tokens allocated")

self.findings[section] = ResearchFindings(
section=section,
content={"options": []},
sources=["Strategic analysis"],
confidence_score=0.80,
data_gaps=["Customer validation needed"],
validation_notes="Options require executive review",
token_usage=int(budget * 0.65),
agent_id="strategy_specialist"
)
self.token_manager.record_usage("stage3_strategy", int(budget * 0.65))

async def _execute_stage4_synthesis(self, params: BriefParameters):
"""Stage 4: Synthesis (sequential)."""
print("Stage 4: Synthesis...")

for section in [BriefSection.EXECUTIVE_SNAPSHOT, BriefSection.ONE_PAGE_BRIEF,
BriefSection.DISCLAIMERS]:
budget = self.token_manager.allocate(f"stage4_{section.value}", section)
print(f" - {section.value}: {budget:,} tokens allocated")

self.findings[section] = ResearchFindings(
section=section,
content={"synthesized": True},
sources=[],
confidence_score=0.95,
data_gaps=[],
validation_notes="Synthesis complete",
token_usage=int(budget * 0.5),
agent_id=f"synthesis_{section.value}"
)
self.token_manager.record_usage(f"stage4_{section.value}",
int(budget * 0.5))

def _assemble_brief(self, params: BriefParameters) -> str:
"""Assemble markdown brief from findings."""
now = datetime.now(timezone.utc)

sections = [
f"# {params.industry}",
f"Strategic Market & Competitive Brief | {params.geography} | {params.time_horizon}",
f"\nPrepared {now.strftime('%B %Y')} | Client Type: {params.client_type}",
"\n---\n",
]

section_titles = {
BriefSection.EXECUTIVE_SNAPSHOT: "A. Executive Snapshot",
BriefSection.MARKET_CONTEXT: "B. Market Context",
BriefSection.TRENDS_THREATS: "C. Key Trends, Threats & Disruptions",
BriefSection.COMPETITIVE_LANDSCAPE: "D. Competitive Landscape",
BriefSection.STRATEGIC_FRAMEWORKS: "E. Strategic Frameworks",
BriefSection.GROWTH_OPTIONS: "F. Entry / Growth Strategy Options",
BriefSection.ONE_PAGE_BRIEF: "G. One-Page Strategic Brief",
BriefSection.DISCLAIMERS: "H. Transparency & Disclaimers",
}

for section in BriefSection:
if section in self.findings:
sections.append(f"\n## {section_titles[section]}\n")
sections.append(f"*Content for {section.value} would be generated here.*\n")

# Standard disclaimer
sections.append("\n---\n")
sections.append("**Disclaimer:** This strategic brief is based on publicly available "
"information. It does not constitute investment, legal, or financial advice.\n")

return '\n'.join(sections)

def _generate_metadata(self, params: BriefParameters) -> Dict[str, Any]:
"""Generate brief metadata."""
return {
'generated_at': datetime.now(timezone.utc).isoformat(),
'parameters': asdict(params),
'sections_completed': len(self.findings),
'total_sources': sum(len(f.sources) for f in self.findings.values()),
'average_confidence': (sum(f.confidence_score for f in self.findings.values())
/ len(self.findings) if self.findings else 0),
}

def _calculate_quality_metrics(self) -> Dict[str, Any]:
"""Calculate quality scores."""
if not self.findings:
return {'completeness': 0, 'avg_confidence': 0}

return {
'completeness': len(self.findings) / len(BriefSection),
'avg_confidence': sum(f.confidence_score for f in self.findings.values()) / len(self.findings),
'source_diversity': len(set(
source for f in self.findings.values() for source in f.sources
)),
'data_gap_severity': sum(len(f.data_gaps) for f in self.findings.values()) / len(self.findings),
}

def parse_args() -> argparse.Namespace: """Parse command line arguments.""" parser = argparse.ArgumentParser( description="Generate executive strategy briefs", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python3 scripts/strategy-brief-generator.py --industry "AI Development Tools" python3 scripts/strategy-brief-generator.py --industry "FinTech" --geography "APAC" python3 scripts/strategy-brief-generator.py --industry "EdTech" --client-type "New Entrant" --output brief.md """ )

parser.add_argument('--industry', required=True, help='Industry to analyze')
parser.add_argument('--geography', default='Global', help='Geographic scope')
parser.add_argument('--time-horizon', default='12-24 months', help='Analysis timeframe')
parser.add_argument('--client-type', default='Incumbent Expanding',
choices=['Incumbent Expanding', 'New Entrant', 'Investor'],
help='Analysis perspective')
parser.add_argument('--competitors', type=int, default=5, help='Number of competitors (3-10)')
parser.add_argument('--trends', type=int, default=8, help='Number of trends (5-12)')
parser.add_argument('--output', help='Output file path (default: stdout)')
parser.add_argument('--format', default='markdown', choices=['markdown', 'json'],
help='Output format')

return parser.parse_args()

async def main(): """Main entry point.""" args = parse_args()

params = BriefParameters(
industry=args.industry,
geography=args.geography,
time_horizon=args.time_horizon,
client_type=args.client_type,
competitor_count=args.competitors,
trend_count=args.trends,
)

generator = StrategyBriefGenerator()

try:
result = await generator.generate_brief(params)
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)

# Output
if args.format == 'json':
output = json.dumps(result, indent=2, default=str)
else:
output = result['brief']

# Add summary
output += f"\n\n---\n"
output += f"**Generation Complete**\n"
output += f"- Sections: {result['quality_metrics']['completeness'] * 100:.0f}%\n"
output += f"- Confidence: {result['quality_metrics']['avg_confidence'] * 100:.0f}%\n"
output += f"- Token Efficiency: {result['token_efficiency']['efficiency'] * 100:.0f}%\n"

if args.output:
Path(args.output).write_text(output)
print(f"Brief saved to: {args.output}")
else:
print(output)

if name == "main": asyncio.run(main())