Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update market research evidence workflows

Timothy Kassisebc0ccea0e99
diff --git a/skills/market-research-reports/SKILL.md b/skills/market-research-reports/SKILL.md
index fbd97c71..03cb8bf1 100644
--- a/skills/market-research-reports/SKILL.md
+++ b/skills/market-research-reports/SKILL.md
@@ -1,904 +1,337 @@
---
name: market-research-reports
-description: Generate comprehensive market research reports (50+ pages) in the style of top consulting firms (McKinsey, BCG, Gartner). Features professional LaTeX formatting, extensive visual generation with scientific-schematics and generate-image, deep integration with research-lookup for data gathering, and multi-framework strategic analysis including Porter Five Forces, PESTLE, SWOT, TAM/SAM/SOM, and BCG Matrix.
-allowed-tools: Read Write Edit Bash
-license: MIT license
-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+description: Build evidence-traceable market research reports and assumption-driven market sizing or forecast scenarios. Use for market definition, industry and customer evidence, competitive landscapes, TAM/SAM/SOM reconciliation, forecast sensitivity, and auditable report scaffolds.
+license: MIT
+compatibility: Python 3.11+ standard library for optional offline CLIs. The optional LaTeX template uses XeLaTeX or LuaLaTeX. Online research requires user-approved network access and source-specific terms; bundled scripts make no network, LLM, or image calls.
+metadata:
+ version: "1.1"
+ skill-author: "K-Dense Inc."
---
# Market Research Reports
-## Overview
-
-Market research reports are comprehensive strategic documents that analyze industries, markets, and competitive landscapes to inform business decisions, investment strategies, and strategic planning. This skill generates **professional-grade reports of 50+ pages** with extensive visual content, modeled after deliverables from top consulting firms like McKinsey, BCG, Bain, Gartner, and Forrester.
-
-**Key Features:**
-- **Comprehensive length**: Reports are designed to be 50+ pages with no token constraints
-- **Visual-rich content**: 5-6 key diagrams generated at start (more added as needed during writing)
-- **Data-driven analysis**: Deep integration with research-lookup for market data
-- **Multi-framework approach**: Porter's Five Forces, PESTLE, SWOT, BCG Matrix, TAM/SAM/SOM
-- **Professional formatting**: Consulting-firm quality typography, colors, and layout
-- **Actionable recommendations**: Strategic focus with implementation roadmaps
-
-**Output Format:** LaTeX with professional styling, compiled to PDF. Uses the `market_research.sty` style package for consistent, professional formatting.
-
-## When to Use This Skill
-
-This skill should be used when:
-- Creating comprehensive market analysis for investment decisions
-- Developing industry reports for strategic planning
-- Analyzing competitive landscapes and market dynamics
-- Conducting market sizing exercises (TAM/SAM/SOM)
-- Evaluating market entry opportunities
-- Preparing due diligence materials for M&A activities
-- Creating thought leadership content for industry positioning
-- Developing go-to-market strategy documentation
-- Analyzing regulatory and policy impacts on markets
-- Building business cases for new product launches
-
-## Visual Enhancement Requirements
-
-**CRITICAL: Market research reports should include key visual content.**
-
-Every report should generate **6 essential visuals** at the start, with additional visuals added as needed during writing. Start with the most critical visualizations to establish the report framework.
-
-### Visual Generation Tools
-
-**Use `scientific-schematics` for:**
-- Market growth trajectory charts
-- TAM/SAM/SOM breakdown diagrams (concentric circles)
-- Porter's Five Forces diagrams
-- Competitive positioning matrices
-- Market segmentation charts
-- Value chain diagrams
-- Technology roadmaps
-- Risk heatmaps
-- Strategic prioritization matrices
-- Implementation timelines/Gantt charts
-- SWOT analysis diagrams
-- BCG Growth-Share matrices
-
-```bash
-# Example: Generate a TAM/SAM/SOM diagram
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "TAM SAM SOM concentric circle diagram showing Total Addressable Market $50B outer circle, Serviceable Addressable Market $15B middle circle, Serviceable Obtainable Market $3B inner circle, with labels and arrows pointing to each segment" \
- -o figures/tam_sam_som.png --doc-type report
-
-# Example: Generate Porter's Five Forces
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Porter's Five Forces diagram with center box 'Competitive Rivalry' connected to four surrounding boxes: 'Threat of New Entrants' (top), 'Bargaining Power of Suppliers' (left), 'Bargaining Power of Buyers' (right), 'Threat of Substitutes' (bottom). Each box should show High/Medium/Low rating" \
- -o figures/porters_five_forces.png --doc-type report
-```
-
-**Use `generate-image` for:**
-- Executive summary hero infographics
-- Industry/sector conceptual illustrations
-- Abstract technology visualizations
-- Cover page imagery
-
-```bash
-# Example: Generate executive summary infographic
-python skills/generate-image/scripts/generate_image.py \
- "Professional executive summary infographic for market research report, showing key metrics in modern data visualization style, blue and green color scheme, clean minimalist design with icons representing market size, growth rate, and competitive landscape" \
- --output figures/executive_summary.png
-```
-
-### Recommended Visuals by Section (Generate as Needed)
-
-| Section | Priority Visuals | Optional Visuals |
-|---------|-----------------|------------------|
-| Executive Summary | Executive infographic (START) | - |
-| Market Size & Growth | Growth trajectory (START), TAM/SAM/SOM (START) | Regional breakdown, segment growth |
-| Competitive Landscape | Porter's Five Forces (START), Positioning matrix (START) | Market share chart, strategic groups |
-| Risk Analysis | Risk heatmap (START) | Mitigation matrix |
-| Strategic Recommendations | Opportunity matrix | Priority framework |
-| Implementation Roadmap | Timeline/Gantt | Milestone tracker |
-| Investment Thesis | Financial projections | Scenario analysis |
-
-**Start with 6 priority visuals** (marked as START above), then generate additional visuals as specific sections are written and require visual support.
-
----
-
-## Report Structure (50+ Pages)
-
-### Front Matter (~5 pages)
-
-#### Cover Page (1 page)
-- Report title and subtitle
-- Hero visualization (generated)
-- Date and classification
-- Prepared for / Prepared by
-
-#### Table of Contents (1-2 pages)
-- Automated from LaTeX
-- List of Figures
-- List of Tables
-
-#### Executive Summary (2-3 pages)
-- **Market Snapshot Box**: Key metrics at a glance
-- **Investment Thesis**: 3-5 bullet point summary
-- **Key Findings**: Major discoveries and insights
-- **Strategic Recommendations**: Top 3-5 actionable recommendations
-- **Executive Summary Infographic**: Visual synthesis of report highlights
-
----
-
-### Core Analysis (~35 pages)
-
-#### Chapter 1: Market Overview & Definition (4-5 pages)
-
-**Content Requirements:**
-- Market definition and scope
-- Industry ecosystem mapping
-- Key stakeholders and their roles
-- Market boundaries and adjacencies
-- Historical context and evolution
-
-**Required Visuals (2):**
-1. Market ecosystem/value chain diagram
-2. Industry structure diagram
-
-**Key Data Points:**
-- Market definition criteria
-- Included/excluded segments
-- Geographic scope
-- Time horizon for analysis
-
----
-
-#### Chapter 2: Market Size & Growth Analysis (6-8 pages)
-
-**Content Requirements:**
-- Total Addressable Market (TAM) calculation
-- Serviceable Addressable Market (SAM) definition
-- Serviceable Obtainable Market (SOM) estimation
-- Historical growth analysis (5-10 years)
-- Growth projections (5-10 years forward)
-- Growth drivers and inhibitors
-- Regional market breakdown
-- Segment-level analysis
-
-**Required Visuals (4):**
-1. Market growth trajectory chart (historical + projected)
-2. TAM/SAM/SOM concentric circles diagram
-3. Regional market breakdown (pie chart or treemap)
-4. Segment growth comparison (bar chart)
-
-**Key Data Points:**
-- Current market size (with source)
-- CAGR (historical and projected)
-- Market size by region
-- Market size by segment
-- Key assumptions for projections
-
-**Data Sources:**
-Use `research-lookup` to find:
-- Market research reports (Gartner, Forrester, IDC, etc.)
-- Industry association data
-- Government statistics
-- Company financial reports
-- Academic studies
-
----
-
-#### Chapter 3: Industry Drivers & Trends (5-6 pages)
-
-**Content Requirements:**
-- Macroeconomic factors
-- Technology trends
-- Regulatory drivers
-- Social and demographic shifts
-- Environmental factors
-- Industry-specific trends
-
-**Analysis Frameworks:**
-- **PESTLE Analysis**: Political, Economic, Social, Technological, Legal, Environmental
-- **Trend Impact Assessment**: Likelihood vs Impact matrix
-
-**Required Visuals (3):**
-1. Industry trends timeline or radar chart
-2. Driver impact matrix
-3. PESTLE analysis diagram
-
-**Key Data Points:**
-- Top 5-10 growth drivers with quantified impact
-- Emerging trends with timeline
-- Disruption factors
-
----
-
-#### Chapter 4: Competitive Landscape (6-8 pages)
-
-**Content Requirements:**
-- Market structure analysis
-- Major player profiles
-- Market share analysis
-- Competitive positioning
-- Barriers to entry
-- Competitive dynamics
-
-**Analysis Frameworks:**
-- **Porter's Five Forces**: Comprehensive industry analysis
-- **Competitive Positioning Matrix**: 2x2 matrix on key dimensions
-- **Strategic Group Mapping**: Cluster competitors by strategy
-
-**Required Visuals (4):**
-1. Porter's Five Forces diagram
-2. Market share pie chart or bar chart
-3. Competitive positioning matrix (2x2)
-4. Strategic group map
-
-**Key Data Points:**
-- Market share by company (top 10)
-- Competitive intensity rating
-- Entry barriers assessment
-- Supplier/buyer power assessment
-
----
-
-#### Chapter 5: Customer Analysis & Segmentation (4-5 pages)
-
-**Content Requirements:**
-- Customer segment definitions
-- Segment size and growth
-- Buying behavior analysis
-- Customer needs and pain points
-- Decision-making process
-- Value drivers by segment
-
-**Analysis Frameworks:**
-- **Customer Segmentation Matrix**: Size vs Growth
-- **Value Proposition Canvas**: Jobs, Pains, Gains
-- **Customer Journey Mapping**: Awareness to Advocacy
-
-**Required Visuals (3):**
-1. Customer segmentation breakdown (pie/treemap)
-2. Segment attractiveness matrix
-3. Customer journey or value proposition diagram
-
-**Key Data Points:**
-- Segment sizes and percentages
-- Growth rates by segment
-- Average deal size / revenue per customer
-- Customer acquisition cost by segment
-
----
-
-#### Chapter 6: Technology & Innovation Landscape (4-5 pages)
-
-**Content Requirements:**
-- Current technology stack
-- Emerging technologies
-- Innovation trends
-- Technology adoption curves
-- R&D investment analysis
-- Patent landscape
-
-**Analysis Frameworks:**
-- **Technology Readiness Assessment**: TRL levels
-- **Hype Cycle Positioning**: Where technologies sit
-- **Technology Roadmap**: Evolution over time
-
-**Required Visuals (2):**
-1. Technology roadmap diagram
-2. Innovation/adoption curve or hype cycle
-
-**Key Data Points:**
-- R&D spending in the industry
-- Key technology milestones
-- Patent filing trends
-- Technology adoption rates
-
----
-
-#### Chapter 7: Regulatory & Policy Environment (3-4 pages)
-
-**Content Requirements:**
-- Current regulatory framework
-- Key regulatory bodies
-- Compliance requirements
-- Upcoming regulatory changes
-- Policy trends
-- Impact assessment
-
-**Required Visuals (1):**
-1. Regulatory timeline or framework diagram
-
-**Key Data Points:**
-- Key regulations and effective dates
-- Compliance costs
-- Regulatory risks
-- Policy change probability
-
----
-
-#### Chapter 8: Risk Analysis (3-4 pages)
-
-**Content Requirements:**
-- Market risks
-- Competitive risks
-- Regulatory risks
-- Technology risks
-- Operational risks
-- Financial risks
-- Risk mitigation strategies
-
-**Analysis Frameworks:**
-- **Risk Heatmap**: Probability vs Impact
-- **Risk Register**: Comprehensive risk inventory
-- **Mitigation Matrix**: Risk vs Mitigation strategy
-
-**Required Visuals (2):**
-1. Risk heatmap (probability vs impact)
-2. Risk mitigation matrix
-
-**Key Data Points:**
-- Top 10 risks with ratings
-- Risk probability scores
-- Impact severity scores
-- Mitigation cost estimates
-
----
-
-### Strategic Recommendations (~10 pages)
-
-#### Chapter 9: Strategic Opportunities & Recommendations (4-5 pages)
-
-**Content Requirements:**
-- Opportunity identification
-- Opportunity sizing
-- Strategic options analysis
-- Prioritization framework
-- Detailed recommendations
-- Success factors
-
-**Analysis Frameworks:**
-- **Opportunity Attractiveness Matrix**: Attractiveness vs Ability to Win
-- **Strategic Options Framework**: Build, Buy, Partner, Ignore
-- **Priority Matrix**: Impact vs Effort
-
-**Required Visuals (3):**
-1. Opportunity matrix
-2. Strategic options framework
-3. Priority/recommendation matrix
-
-**Key Data Points:**
-- Opportunity sizes
-- Investment requirements
-- Expected returns
-- Timeline to value
-
----
-
-#### Chapter 10: Implementation Roadmap (3-4 pages)
-
-**Content Requirements:**
-- Phased implementation plan
-- Key milestones and deliverables
-- Resource requirements
-- Timeline and sequencing
-- Dependencies and critical path
-- Governance structure
-
-**Required Visuals (2):**
-1. Implementation timeline/Gantt chart
-2. Milestone tracker or phase diagram
-
-**Key Data Points:**
-- Phase durations
-- Resource requirements
-- Key milestones with dates
-- Budget allocation by phase
-
----
-
-#### Chapter 11: Investment Thesis & Financial Projections (3-4 pages)
-
-**Content Requirements:**
-- Investment summary
-- Financial projections
-- Scenario analysis
-- Return expectations
-- Key assumptions
-- Sensitivity analysis
-
-**Required Visuals (2):**
-1. Financial projection chart (revenue, growth)
-2. Scenario analysis comparison
-
-**Key Data Points:**
-- Revenue projections (3-5 years)
-- CAGR projections
-- ROI/IRR expectations
-- Key financial assumptions
-
----
-
-### Back Matter (~5 pages)
-
-#### Appendix A: Methodology & Data Sources (1-2 pages)
-- Research methodology
-- Data collection approach
-- Data sources and citations
-- Limitations and assumptions
-
-#### Appendix B: Detailed Market Data Tables (2-3 pages)
-- Comprehensive market data tables
-- Regional breakdowns
-- Segment details
-- Historical data series
-
-#### Appendix C: Company Profiles (1-2 pages)
-- Brief profiles of key competitors
-- Financial highlights
-- Strategic focus areas
-
-#### References/Bibliography
-- All sources cited
-- BibTeX format for LaTeX
-
----
+## Purpose
+
+Create decision-focused market reports whose claims, calculations, assumptions,
+and uncertainties can be audited. Match depth and format to the question and
+evidence. There is no required length, chapter count, visual count, or output
+format.
+
+Do not:
+
+- imitate or imply affiliation with a consulting, analyst, or research brand;
+- invent citations, quotes, market shares, or paid-market figures;
+- present TAM/SAM/SOM or a forecast as one certain truth;
+- treat a framework, chart, or fluent narrative as evidence;
+- provide investment, legal, antitrust, tax, accounting, or regulatory advice.
+
+## Operating principles
+
+1. **Define before sizing.** Fix product, customer, geography, channel, period,
+ measure, unit, denominator, currency/base year, and taxonomy.
+2. **Map every claim.** Every factual or quantitative claim has a claim ID and
+ exact source IDs.
+3. **Separate statement types.** Distinguish facts, estimates, calculations,
+ forecasts, opinions, and recommendations.
+4. **Prefer primary evidence.** Use official statistics, regulator records,
+ filed company disclosures, and transparent original studies before
+ secondary synthesis.
+5. **Preserve uncertainty.** Retain source conflicts, revisions, scenario
+ ranges, sensitivity, and limitations.
+6. **Keep methods reproducible.** Use local structured inputs and deterministic
+ calculations when practical.
+7. **Collect lawfully and ethically.** No deception, PII disclosure, access
+ circumvention, confidential material, or trade-secret acquisition.
## Workflow
-### Phase 1: Research & Data Gathering
-
-**Step 1: Define Scope**
-- Clarify market definition
-- Set geographic boundaries
-- Determine time horizon
-- Identify key questions to answer
+### 1. Establish the research contract
-**Step 2: Conduct Deep Research**
+Clarify:
-Use `research-lookup` extensively to gather market data:
+- decision, audience, deadline, and materiality threshold;
+- formal market definition and adjacent exclusions;
+- buyer, payer, user, transaction, and value-chain level;
+- geography and treatment of imports, exports, and channels;
+- historical period, forecast period, and retrieval cutoff;
+- revenue/expenditure, gross output/value added, units, capacity, users, or
+ another measure;
+- stock/flow, gross/net, taxes, and denominator;
+- currency, base year, and nominal/real/current/constant basis;
+- industry and product classification with version;
+- permitted data sources, primary research, confidentiality, and output format.
-```bash
-# Market size and growth data
-python skills/research-lookup/scripts/research_lookup.py \
- "What is the current market size and projected growth rate for [MARKET] industry? Include TAM, SAM, SOM estimates and CAGR projections"
+Ask a focused question when a missing choice would materially change the
+denominator or result. Otherwise state a provisional scope and proceed.
-# Competitive landscape
-python skills/research-lookup/scripts/research_lookup.py \
- "Who are the top 10 competitors in the [MARKET] market? What is their market share and competitive positioning?"
+Use `references/report_structure_guide.md` for modular report design.
-# Industry trends
-python skills/research-lookup/scripts/research_lookup.py \
- "What are the major trends and growth drivers in the [MARKET] industry for 2024-2030?"
-
-# Regulatory environment
-python skills/research-lookup/scripts/research_lookup.py \
- "What are the key regulations and policy changes affecting the [MARKET] industry?"
-```
+### 2. Build the evidence plan
-**Step 3: Data Organization**
-- Create `sources/` folder with research notes
-- Organize data by section
-- Identify data gaps
-- Conduct follow-up research as needed
+Route each question to the source closest to the underlying event:
-### Phase 2: Analysis & Framework Application
+1. primary law, regulator decision, official filing, or official statistic;
+2. original company filing or attributable first-party disclosure;
+3. transparent survey/study with inspectable methods;
+4. institutional or peer-reviewed research using identifiable primary data;
+5. industry association data with disclosed coverage;
+6. reputable secondary synthesis;
+7. lawfully accessed paid estimate with inspectable scope and method;
+8. news/commentary for leads or attributable events.
-**Step 4: Apply Analysis Frameworks**
+For company data, prefer the official filing system in the relevant
+jurisdiction. For industry, labor, prices, population, trade, and national
+accounts, prefer the responsible national statistical agency or central bank.
+For cross-country work, use harmonized World Bank, IMF, OECD, or Eurostat data
+only after checking definitions and original-source lineage.
-For each framework, conduct structured analysis:
+Read `references/official_data_sources.md` before using public APIs. API rules
+and limits are a dated snapshot: verify current official terms before automated
+or high-volume retrieval. Never put an API key in a report or bundled script.
-- **Market Sizing**: TAM → SAM → SOM with clear assumptions
-- **Porter's Five Forces**: Rate each force High/Medium/Low with rationale
-- **PESTLE**: Analyze each dimension with trends and impacts
-- **SWOT**: Internal strengths/weaknesses, external opportunities/threats
-- **Competitive Positioning**: Define axes, plot competitors
+### 3. Create the source ledger
-**Step 5: Develop Insights**
-- Synthesize findings into key insights
-- Identify strategic implications
-- Develop recommendations
-- Prioritize opportunities
+Assign stable IDs (`S-001`, `S-002`, ...). Record:
-### Phase 3: Visual Generation
+- title, publisher, URL/persistent ID, source type;
+- publication date and retrieval date;
+- original producer when accessed through an aggregator;
+- geography, covered population, period, and vintage;
+- currency, base year, price basis, measure type, unit, and denominator;
+- taxonomy and version;
+- preliminary/revised/final/current status;
+- method, sample, imputation, suppression, and limitations;
+- license/terms and lawful local snapshot path.
-**Step 6: Generate All Visuals**
-
-Generate visuals BEFORE writing the report. Use the batch generation script:
+Use `assets/source_ledger_template.csv` and validate it:
```bash
-# Generate all standard market report visuals
-python skills/market-research-reports/scripts/generate_market_visuals.py \
- --topic "[MARKET NAME]" \
- --output-dir figures/
+python3 scripts/validate_evidence_ledger.py data/source_ledger.csv
```
-Or generate individually:
+If publication date is unavailable, record `not-stated`; do not guess.
-```bash
-# 1. Market growth trajectory
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Bar chart showing market growth from 2020 to 2034, with historical bars in dark blue (2020-2024) and projected bars in light blue (2025-2034). Y-axis shows market size in billions USD. Include CAGR annotation" \
- -o figures/01_market_growth.png --doc-type report
-
-# 2. TAM/SAM/SOM breakdown
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "TAM SAM SOM concentric circles diagram. Outer circle TAM Total Addressable Market, middle circle SAM Serviceable Addressable Market, inner circle SOM Serviceable Obtainable Market. Each labeled with acronym and description. Blue gradient" \
- -o figures/02_tam_sam_som.png --doc-type report
-
-# 3. Porter's Five Forces
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Porter's Five Forces diagram with center box 'Competitive Rivalry' connected to four surrounding boxes: Threat of New Entrants (top), Bargaining Power of Suppliers (left), Bargaining Power of Buyers (right), Threat of Substitutes (bottom). Color code by rating: High=red, Medium=yellow, Low=green" \
- -o figures/03_porters_five_forces.png --doc-type report
-
-# 4. Competitive positioning matrix
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 competitive positioning matrix with X-axis 'Market Focus (Niche to Broad)' and Y-axis 'Solution Approach (Product to Platform)'. Plot 8-10 competitors as labeled circles of varying sizes. Include quadrant labels" \
- -o figures/04_competitive_positioning.png --doc-type report
-
-# 5. Risk heatmap
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Risk heatmap matrix. X-axis Impact (Low to Critical), Y-axis Probability (Unlikely to Very Likely). Color gradient: Green (low risk) to Red (critical risk). Plot 10-12 risks as labeled points" \
- -o figures/05_risk_heatmap.png --doc-type report
-
-# 6. (Optional) Executive summary infographic
-python skills/generate-image/scripts/generate_image.py \
- "Professional executive summary infographic for market research report, modern data visualization style, blue and green color scheme, clean minimalist design" \
- --output figures/06_exec_summary.png
-```
+### 4. Maintain a claims ledger
-### Phase 4: Report Writing
+Assign IDs (`C-001`, ...). Keep the exact claim text, statement type, source
+IDs, report location, as-of date, geography, currency/base, measure/unit,
+taxonomy, revision status, confidence, calculation ID, and assumption IDs.
-**Step 7: Initialize Project Structure**
+Rules:
-Create the standard project structure:
+- one end-of-paragraph citation does not support unrelated sentences;
+- split compound claims that rely on different evidence;
+- a calculation cites its inputs, not a source that never published the result;
+- an aggregator and its original source are not independent corroboration;
+- an interview theme is not population prevalence;
+- absence of public feature evidence means `unknown`, not `no`.
-```
-writing_outputs/YYYYMMDD_HHMMSS_market_report_[topic]/
-├── progress.md
-├── drafts/
-│ └── v1_market_report.tex
-├── references/
-│ └── references.bib
-├── figures/
-│ └── [all generated visuals]
-├── sources/
-│ └── [research notes]
-└── final/
-```
-
-**Step 8: Write Report Using Template**
-
-Use the `market_report_template.tex` as a starting point. Write each section following the structure guide, ensuring:
-
-- **Comprehensive coverage**: Every subsection addressed
-- **Data-driven content**: Claims supported by research
-- **Visual integration**: Reference all generated figures
-- **Professional tone**: Consulting-style writing
-- **No token constraints**: Write fully, don't abbreviate
-
-**Writing Guidelines:**
-- Use active voice where possible
-- Lead with insights, support with data
-- Use numbered lists for recommendations
-- Include data sources for all statistics
-- Create smooth transitions between sections
-
-### Phase 5: Compilation & Review
-
-**Step 9: Compile LaTeX**
+Audit mappings:
```bash
-cd writing_outputs/[project_folder]/drafts/
-xelatex v1_market_report.tex
-bibtex v1_market_report
-xelatex v1_market_report.tex
-xelatex v1_market_report.tex
+python3 scripts/audit_claim_citations.py \
+ data/claims.csv data/source_ledger.csv
```
-**Step 10: Quality Review**
-
-Verify the report meets quality standards:
-
-- [ ] Total page count is 50+ pages
-- [ ] All essential visuals (5-6 core + any additional) are included and render correctly
-- [ ] Executive summary captures key findings
-- [ ] All data points have sources cited
-- [ ] Analysis frameworks are properly applied
-- [ ] Recommendations are actionable and prioritized
-- [ ] No orphaned figures or tables
-- [ ] Table of contents, list of figures, list of tables are accurate
-- [ ] Bibliography is complete
-- [ ] PDF renders without errors
+See `references/evidence_model.md`.
-**Step 11: Peer Review**
+### 5. Size the market as scenarios
-Use the peer-review skill to evaluate the report:
-- Assess comprehensiveness
-- Verify data accuracy
-- Check logical flow
-- Evaluate recommendation quality
+#### Measurement guardrails
----
+Give every component a disjoint `coverage_key` and one shared
+`denominator_id`. Do not add:
-## Quality Standards
-
-### Page Count Targets
-
-| Section | Minimum Pages | Target Pages |
-|---------|---------------|--------------|
-| Front Matter | 4 | 5 |
-| Market Overview | 4 | 5 |
-| Market Size & Growth | 5 | 7 |
-| Industry Drivers | 4 | 6 |
-| Competitive Landscape | 5 | 7 |
-| Customer Analysis | 3 | 5 |
-| Technology Landscape | 3 | 5 |
-| Regulatory Environment | 2 | 4 |
-| Risk Analysis | 2 | 4 |
-| Strategic Recommendations | 3 | 5 |
-| Implementation Roadmap | 2 | 4 |
-| Investment Thesis | 2 | 4 |
-| Back Matter | 4 | 5 |
-| **TOTAL** | **43** | **66** |
-
-### Visual Quality Requirements
-
-- **Resolution**: All images at 300 DPI minimum
-- **Format**: PNG for raster, PDF for vector
-- **Accessibility**: Colorblind-friendly palettes
-- **Consistency**: Same color scheme throughout
-- **Labeling**: All axes, legends, and data points labeled
-- **Source Attribution**: Sources cited in figure captions
-
-### Data Quality Requirements
-
-- **Currency**: Data no older than 2 years (prefer current year)
-- **Sourcing**: All statistics attributed to specific sources
-- **Validation**: Cross-reference multiple sources when possible
-- **Assumptions**: All projections state underlying assumptions
-- **Limitations**: Acknowledge data limitations and gaps
-
-### Writing Quality Requirements
-
-- **Objectivity**: Present balanced analysis, acknowledge uncertainties
-- **Clarity**: Avoid jargon, define technical terms
-- **Precision**: Use specific numbers over vague qualifiers
-- **Structure**: Clear headings, logical flow, smooth transitions
-- **Actionability**: Recommendations are specific and implementable
+- manufacturer revenue to distributor or end-customer spend;
+- production, imports, and sales without trade/inventory reconciliation;
+- parent and subsidiary revenue;
+- bundles and their included components;
+- gross output and value added;
+- installed-base stock and annual transaction flow;
+- overlapping customer or geographic segments.
----
+Use product classifications and supply-use logic when industry codes are too
+broad. Preserve an unknown/residual category instead of forcing totals.
-## LaTeX Formatting
+#### Top-down and bottom-up
-### Using the Style Package
+Compute independently:
-The `market_research.sty` package provides professional formatting. Include it in your document:
+```text
+TAM_top = sum(disjoint in-scope component values)
-```latex
-\documentclass[11pt,letterpaper]{report}
-\usepackage{market_research}
+TAM_bottom =
+ sum(customer_count
+ * addressable_fraction
+ * annual_quantity_per_customer
+ * price_per_unit)
```
-### Box Environments
-
-Use colored boxes to highlight key content:
-
-```latex
-% Key insight box (blue)
-\begin{keyinsightbox}[Key Finding]
-The market is projected to grow at 15.3% CAGR through 2030.
-\end{keyinsightbox}
-
-% Market data box (green)
-\begin{marketdatabox}[Market Snapshot]
-\begin{itemize}
- \item Market Size (2024): \$45.2B
- \item Projected Size (2030): \$98.7B
- \item CAGR: 15.3%
-\end{itemize}
-\end{marketdatabox}
-
-% Risk box (orange/warning)
-\begin{riskbox}[Critical Risk]
-Regulatory changes could impact 40% of market participants.
-\end{riskbox}
-
-% Recommendation box (purple)
-\begin{recommendationbox}[Strategic Recommendation]
-Prioritize market entry in the Asia-Pacific region.
-\end{recommendationbox}
-
-% Callout box (gray)
-\begin{calloutbox}[Definition]
-TAM (Total Addressable Market) represents the total revenue opportunity.
-\end{calloutbox}
-```
+Then apply scenario-specific serviceability and capture assumptions:
-### Figure Formatting
-
-```latex
-\begin{figure}[htbp]
-\centering
-\includegraphics[width=0.9\textwidth]{../figures/market_growth.png}
-\caption{Market Growth Trajectory (2020-2030). Source: Industry analysis, company data.}
-\label{fig:market_growth}
-\end{figure}
+```text
+SAM_s = TAM * serviceable_fraction_s
+SOM_s = SAM_s * obtainable_share_s
```
-### Table Formatting
-
-```latex
-\begin{table}[htbp]
-\centering
-\caption{Market Size by Region (2024)}
-\begin{tabular}{@{}lrrr@{}}
-\toprule
-\textbf{Region} & \textbf{Size (USD)} & \textbf{Share} & \textbf{CAGR} \\
-\midrule
-North America & \$18.2B & 40.3\% & 12.5\% \\
-\rowcolor{tablealt} Europe & \$12.1B & 26.8\% & 14.2\% \\
-Asia-Pacific & \$10.5B & 23.2\% & 18.7\% \\
-\rowcolor{tablealt} Rest of World & \$4.4B & 9.7\% & 11.3\% \\
-\midrule
-\textbf{Total} & \textbf{\$45.2B} & \textbf{100\%} & \textbf{15.3\%} \\
-\bottomrule
-\end{tabular}
-\label{tab:market_by_region}
-\end{table}
-```
+Use at least two genuinely different scenarios; a downside/base/upside set is
+usually useful. State horizon, constraints, evidence, and assumptions. SOM is
+not a guaranteed revenue forecast.
-For complete formatting reference, see `assets/FORMATTING_GUIDE.md`.
+Run the deterministic calculator:
----
-
-## Integration with Other Skills
+```bash
+python3 scripts/calculate_market_sizing.py \
+ assets/market_sizing_scenarios_template.json
+```
-This skill works synergistically with:
+Report both methods, midpoint-relative gap, scope differences, sensitivity, and
+unresolved reconciliation. Do not average incompatible methods.
-- **research-lookup**: Essential for gathering market data, statistics, and competitive intelligence
-- **scientific-schematics**: Generate all diagrams, charts, and visualizations
-- **generate-image**: Create infographics and conceptual illustrations
-- **peer-review**: Evaluate report quality and completeness
-- **citation-management**: Manage BibTeX references
+### 6. Forecast with explicit uncertainty
----
+Separate observed, estimated, and forecast periods. Record series ID,
+frequency, units, seasonal adjustment, transformations, taxonomy breaks,
+retrieval date, and vintage/revisions.
-## Example Prompts
+For each scenario:
-### Market Overview Section
+- provide an annual rate path or driver equations;
+- state demand, price, supply, regulation, competition, capacity, and timing
+ assumptions;
+- list evidence and assumption IDs;
+- identify conditions that invalidate the scenario.
-```
-Write a comprehensive market overview section for the [Electric Vehicle Charging Infrastructure] market. Include:
-- Clear market definition and scope
-- Industry ecosystem with key stakeholders
-- Value chain analysis
-- Historical evolution of the market
-- Current market dynamics
-
-Generate 2 supporting visuals using scientific-schematics.
-```
+Do not call scenario bounds confidence or prediction intervals. Do not assign
+probabilities without a validated probabilistic model and diagnostics.
-### Competitive Landscape Section
+Run:
-```
-Analyze the competitive landscape for the [Cloud Computing] market. Include:
-- Porter's Five Forces analysis with High/Medium/Low ratings
-- Top 10 competitors with market share
-- Competitive positioning matrix
-- Strategic group mapping
-- Barriers to entry analysis
-
-Generate 4 supporting visuals including Porter's Five Forces diagram and positioning matrix.
+```bash
+python3 scripts/forecast_sensitivity.py \
+ assets/forecast_sensitivity_template.json
```
-### Strategic Recommendations Section
+Show the range by year, endpoint sensitivity, influential assumptions, and
+switching values. See `references/data_analysis_patterns.md`.
-```
-Develop strategic recommendations for entering the [Renewable Energy Storage] market. Include:
-- 5-7 prioritized recommendations
-- Opportunity sizing for each
-- Implementation considerations
-- Risk factors and mitigations
-- Success criteria
-
-Generate 3 supporting visuals including opportunity matrix and priority framework.
-```
-
----
+### 7. Analyze customers and primary research
-## Checklist: 50+ Page Validation
-
-Before finalizing the report, verify:
-
-### Structure Completeness
-- [ ] Cover page with hero visual
-- [ ] Table of contents (auto-generated)
-- [ ] List of figures (auto-generated)
-- [ ] List of tables (auto-generated)
-- [ ] Executive summary (2-3 pages)
-- [ ] All 11 core chapters present
-- [ ] Appendix A: Methodology
-- [ ] Appendix B: Data tables
-- [ ] Appendix C: Company profiles
-- [ ] References/Bibliography
-
-### Visual Completeness (Core 5-6)
-- [ ] Market growth trajectory chart (Priority 1)
-- [ ] TAM/SAM/SOM diagram (Priority 2)
-- [ ] Porter's Five Forces (Priority 3)
-- [ ] Competitive positioning matrix (Priority 4)
-- [ ] Risk heatmap (Priority 5)
-- [ ] Executive summary infographic (Priority 6, optional)
-
-### Additional Visuals (Generate as Needed)
-- [ ] Market ecosystem diagram
-- [ ] Regional breakdown chart
-- [ ] Segment growth chart
-- [ ] Industry trends/PESTLE diagram
-- [ ] Market share chart
-- [ ] Customer segmentation chart
-- [ ] Technology roadmap
-- [ ] Regulatory timeline
-- [ ] Opportunity matrix
-- [ ] Implementation timeline
-- [ ] Financial projections chart
-- [ ] Other section-specific visuals
-
-### Content Quality
-- [ ] All statistics have sources
-- [ ] Projections include assumptions
-- [ ] Frameworks properly applied
-- [ ] Recommendations are actionable
-- [ ] Writing is professional quality
-- [ ] No placeholder or incomplete sections
-
-### Technical Quality
-- [ ] PDF compiles without errors
-- [ ] All figures render correctly
-- [ ] Cross-references work
-- [ ] Bibliography complete
-- [ ] Page count exceeds 50
+For survey evidence, disclose sponsor, target population, frame,
+probability/non-probability design, recruitment, mode/language, field dates,
+unweighted sample, subgroup bases, weighting, response/participation,
+instrument wording, precision, processing, and limitations.
----
+For interviews/focus groups, disclose recruitment, consent, role coverage,
+dates/mode, guide, coding, divergent evidence, privacy controls, and limits to
+generalization.
-## Resources
+Never:
-### Reference Files
+- collect more personal data than necessary;
+- place direct identifiers or raw recordings in report artifacts;
+- use research as disguised selling or lead generation;
+- misrepresent identity/purpose;
+- pressure participants to reveal employer/customer secrets;
+- report qualitative mention counts as market prevalence.
-Load these files for detailed guidance:
+Follow `references/methods_and_ethics.md`.
-- **`references/report_structure_guide.md`**: Detailed section-by-section content requirements
-- **`references/visual_generation_guide.md`**: Complete prompts for generating all visual types
-- **`references/data_analysis_patterns.md`**: Templates for Porter's, PESTLE, SWOT, etc.
+### 8. Analyze competitors and concentration
-### Assets
+Define product and geographic scope from the customer perspective before
+selecting competitors or calculating shares. Consider non-price dimensions,
+channels, imports, digital/multi-sided features, innovation, and dynamic change
+where relevant.
-- **`assets/market_research.sty`**: LaTeX style package
-- **`assets/market_report_template.tex`**: Complete LaTeX template
-- **`assets/FORMATTING_GUIDE.md`**: Quick reference for box environments and styling
+Use lawful public evidence and a common product edition, geography, and as-of
+date. Validate a complete matrix:
-### Scripts
+```bash
+python3 scripts/validate_competitor_matrix.py \
+ assets/competitor_feature_matrix_template.csv \
+ --source-ledger assets/source_ledger_template.csv
+```
-- **`scripts/generate_market_visuals.py`**: Batch generate all report visuals
+For shares, state revenue/units/capacity/users or other metric, denominator,
+period, residual share, and source coverage. HHI/CRn are descriptive screens,
+not legal conclusions. A TAM category is not automatically a relevant antitrust
+market.
----
+### 9. Normalize units and definitions
-## Troubleshooting
+Before combining values:
-### Common Issues
+- align geography, period, stock/flow, gross/net, unit, and denominator;
+- convert currencies with an identified source and rate convention;
+- align base year and nominal/real basis;
+- do not force chained-dollar additivity;
+- preserve taxonomy versions and document concordance uncertainty;
+- record every conversion as a calculation.
-**Problem**: Report is under 50 pages
-- **Solution**: Expand data tables in appendices, add more detailed company profiles, include additional regional breakdowns
+Check comparison groups:
-**Problem**: Visuals not rendering
-- **Solution**: Check file paths in LaTeX, ensure images are in figures/ folder, verify file extensions
+```bash
+python3 scripts/check_unit_consistency.py \
+ assets/consistency_check_template.csv
+```
-**Problem**: Bibliography missing entries
-- **Solution**: Run bibtex after first xelatex pass, check .bib file for syntax errors
+### 10. Draft and review
-**Problem**: Table/figure overflow
-- **Solution**: Use `\resizebox` or `adjustbox` package, reduce image width percentage
+Lead with findings and uncertainty, not frameworks. Use optional frameworks
+only to organize questions; do not force scores or a fixed number of factors.
+Keep recommendations separate from evidence and include dependencies,
+trade-offs, decision thresholds, and disconfirming evidence.
-**Problem**: Poor visual quality from generation
-- **Solution**: Use `--doc-type report` flag, increase iterations with `--iterations 5`
+Visuals are optional. If used, build them from validated local data and include
+scope, units, source IDs, calculation ID, observed/forecast distinction, and
+limitations. See `references/visual_generation_guide.md`.
----
+Generate a Markdown workspace:
-Use this skill to create comprehensive, visually-rich market research reports that rival top consulting firm deliverables. The combination of deep research, structured frameworks, and extensive visualization produces documents that inform strategic decisions and demonstrate analytical rigor.
+```bash
+python3 scripts/generate_report_scaffold.py \
+ assets/report_manifest_template.json ./market-report-workspace
+```
+Or use the optional LaTeX assets:
+
+- `assets/market_report_template.tex`
+- `assets/market_research.sty`
+- `assets/FORMATTING_GUIDE.md`
+
+## Release gate
+
+- Market boundary, taxonomy, denominator, geography, and period are explicit.
+- Every factual/quantitative claim maps to exact source IDs.
+- Publication/retrieval dates, revisions, method, and limitations are recorded.
+- Currency/base year, nominal/real basis, stock/flow, and units are consistent.
+- Top-down and bottom-up methods use disjoint coverage and are reconciled.
+- TAM/SAM/SOM and forecasts are conditional scenarios with sensitivity.
+- Survey/interview evidence carries method, privacy, and inference limits.
+- Competitor evidence is lawful, dated, scoped, and uses `unknown` honestly.
+- Source conflicts and revisions remain visible.
+- No fabricated/unsupported paid figures, PII, trade secrets, deceptive
+ collection, brand impersonation, or investment-advice framing appears.
+
+## Bundled resources
+
+### References
+
+- `references/report_structure_guide.md` — modular report architecture.
+- `references/evidence_model.md` — claim-source mapping and provenance.
+- `references/data_analysis_patterns.md` — sizing, forecast, consistency,
+ survey, and concentration methods.
+- `references/official_data_sources.md` — current official source/API routing.
+- `references/methods_and_ethics.md` — survey, interview, privacy, competitor,
+ and antitrust safeguards.
+- `references/visual_generation_guide.md` — optional evidence-led displays.
+- `references/sources.md` — dated authoritative source ledger.
+
+### Templates and CLIs
+
+Use the templates in `assets/` as synthetic schemas, not real-world evidence.
+All scripts in `scripts/` are standard-library, bounded, local-only tools. They
+reject oversized or malformed input, do not follow symlink inputs, do not
+overwrite outputs without explicit permission, and make no network, LLM, image,
+dynamic-evaluation, or pickle calls.
diff --git a/skills/market-research-reports/assets/FORMATTING_GUIDE.md b/skills/market-research-reports/assets/FORMATTING_GUIDE.md
index 09a1da48..8f445b17 100644
--- a/skills/market-research-reports/assets/FORMATTING_GUIDE.md
+++ b/skills/market-research-reports/assets/FORMATTING_GUIDE.md
@@ -1,428 +1,149 @@
-# Market Research Report Formatting Guide
+# Market Report Formatting Guide
-Quick reference for using the `market_research.sty` style package.
+Use formatting to expose evidence quality and uncertainty, not to make estimates
+look more certain. The bundled LaTeX files are optional; Markdown, HTML, DOCX, or
+another user-requested format is equally acceptable.
-## Color Palette
+## Information hierarchy
-### Primary Colors
-| Color Name | RGB | Hex | Usage |
-|------------|-----|-----|-------|
-| `primaryblue` | (0, 51, 102) | `#003366` | Headers, titles, links |
-| `secondaryblue` | (51, 102, 153) | `#336699` | Subsections, secondary elements |
-| `lightblue` | (173, 216, 230) | `#ADD8E6` | Key insight box backgrounds |
-| `accentblue` | (0, 120, 215) | `#0078D7` | Accent highlights, opportunity boxes |
+Use the following order within each analytical section:
-### Secondary Colors
-| Color Name | RGB | Hex | Usage |
-|------------|-----|-----|-------|
-| `accentgreen` | (0, 128, 96) | `#008060` | Market data boxes, positive indicators |
-| `lightgreen` | (200, 230, 201) | `#C8E6C9` | Market data box backgrounds |
-| `warningorange` | (255, 140, 0) | `#FF8C00` | Risk boxes, warnings |
-| `alertred` | (198, 40, 40) | `#C62828` | Critical risks |
-| `recommendpurple` | (103, 58, 183) | `#673AB7` | Recommendation boxes |
+1. finding or question;
+2. evidence and exact claim IDs;
+3. calculation or interpretation;
+4. assumptions and uncertainty;
+5. implication or decision threshold.
-### Neutral Colors
-| Color Name | RGB | Hex | Usage |
-|------------|-----|-----|-------|
-| `darkgray` | (66, 66, 66) | `#424242` | Body text |
-| `mediumgray` | (117, 117, 117) | `#757575` | Secondary text |
-| `lightgray` | (240, 240, 240) | `#F0F0F0` | Backgrounds, callout boxes |
-| `tablealt` | (245, 247, 250) | `#F5F7FA` | Alternating table rows |
+Keep these statement types visually and verbally distinct:
----
+- **Observed fact** — directly represented by cited evidence.
+- **Estimate** — a source's or analyst's uncertain estimate.
+- **Calculation** — deterministic result from listed inputs and formula.
+- **Scenario** — conditional result, not a prediction or confidence interval.
+- **Recommendation** — judgment based on findings and stated objectives.
-## Box Environments
+## Required labels for quantitative content
-### Key Insight Box (Blue)
-For major findings, insights, and important discoveries.
+Every quantitative table, figure, callout, or headline metric should show:
-```latex
-\begin{keyinsightbox}[Custom Title]
-The market is projected to grow at 15.3% CAGR through 2030, driven by
-increasing enterprise adoption and favorable regulatory conditions.
-\end{keyinsightbox}
-```
-
-### Market Data Box (Green)
-For market statistics, metrics, and data highlights.
-
-```latex
-\begin{marketdatabox}[Market Snapshot]
-\begin{itemize}
- \item \textbf{Market Size (2024):} \marketsize{45.2 billion}
- \item \textbf{Projected Size (2030):} \marketsize{98.7 billion}
- \item \textbf{CAGR:} \growthrate{15.3}
-\end{itemize}
-\end{marketdatabox}
-```
-
-### Risk Box (Orange/Warning)
-For risk factors, warnings, and cautions.
-
-```latex
-\begin{riskbox}[Market Risk]
-Regulatory changes in the European Union could impact 40% of market
-participants within the next 18 months.
-\end{riskbox}
-```
-
-### Critical Risk Box (Red)
-For high-severity or critical risks.
-
-```latex
-\begin{criticalriskbox}[Critical: Supply Chain Disruption]
-A major supply chain disruption could result in 6-12 month delays
-and 30% cost increases.
-\end{criticalriskbox}
-```
-
-### Recommendation Box (Purple)
-For strategic recommendations and action items.
-
-```latex
-\begin{recommendationbox}[Strategic Recommendation]
-\begin{enumerate}
- \item Prioritize market entry in Asia-Pacific region
- \item Develop strategic partnerships with local distributors
- \item Invest in localization of product offerings
-\end{enumerate}
-\end{recommendationbox}
-```
-
-### Callout Box (Gray)
-For definitions, notes, and supplementary information.
-
-```latex
-\begin{calloutbox}[Definition: TAM]
-Total Addressable Market (TAM) represents the total revenue opportunity
-available if 100% market share was achieved.
-\end{calloutbox}
-```
-
-### Executive Summary Box
-Special styling for executive summary highlights.
-
-```latex
-\begin{executivesummarybox}[Executive Summary]
-Key findings and highlights of the report...
-\end{executivesummarybox}
-```
-
-### Opportunity Box (Teal/Accent Blue)
-For opportunities and positive findings.
-
-```latex
-\begin{opportunitybox}[Growth Opportunity]
-The Asia-Pacific market represents a \$15 billion opportunity
-growing at 22% CAGR.
-\end{opportunitybox}
-```
+- geography and coverage;
+- period or as-of date;
+- currency and base year when monetary;
+- nominal, real, current-price, constant-price, or chained basis;
+- stock, flow, count, share, rate, price, or index;
+- unit and denominator;
+- taxonomy and version when classifications define scope;
+- historical versus forecast status;
+- source IDs and calculation ID;
+- revision status and material limitations.
-### Framework Boxes
-For strategic analysis frameworks.
+Do not combine differently defined values in one visual scale. Normalize them
+first and retain the conversion record.
-```latex
-% SWOT Analysis
-\begin{swotbox}[SWOT Analysis Summary]
-Content...
-\end{swotbox}
-
-% Porter's Five Forces
-\begin{porterbox}[Porter's Five Forces Analysis]
-Content...
-\end{porterbox}
-```
-
----
-
-## Pull Quotes
+## Color and accessibility
-For highlighting important statistics or quotes.
+The style uses a restrained, colorblind-aware palette:
-```latex
-\begin{pullquote}
-"The convergence of AI and healthcare represents a \$199 billion
-opportunity by 2034."
-\end{pullquote}
-```
+- navy: structure and observed evidence;
+- teal: calculated values;
+- amber: assumptions or uncertainty;
+- red: limitations or unresolved conflicts;
+- gray: context and unavailable evidence.
----
+Never rely on color alone. Add labels, symbols, line styles, or direct
+annotations. Check grayscale legibility and reading order.
-## Stat Boxes
+## LaTeX usage
-For highlighting key statistics (use in rows of 3).
+Place `market_research.sty` next to the report and use:
```latex
-\begin{center}
-\statbox{\$45.2B}{Market Size 2024}
-\statbox{15.3\%}{CAGR 2024-2030}
-\statbox{23\%}{Market Leader Share}
-\end{center}
+\documentclass[11pt]{report}
+\usepackage{market_research}
```
----
+The package provides:
-## Custom Commands
-
-### Highlighting Text
```latex
-\highlight{Important text} % Blue bold
-```
+\begin{evidencebox}[Observed evidence]
+Claim C-014 maps to sources S-003 and S-011.
+\end{evidencebox}
-### Market Size Formatting
-```latex
-\marketsize{45.2 billion} % Outputs: $45.2 billion in green
-```
+\begin{calculationbox}[Calculation CALC-007]
+Top-down and bottom-up estimates differ by 12.4\% of their midpoint.
+\end{calculationbox}
-### Growth Rate Formatting
-```latex
-\growthrate{15.3} % Outputs: 15.3% in green
-```
-
-### Risk Indicators
-```latex
-\riskhigh{} % Outputs: HIGH in red
-\riskmedium{} % Outputs: MEDIUM in orange
-\risklow{} % Outputs: LOW in green
-```
+\begin{assumptionbox}[Scenario assumptions]
+The upside case assumes faster adoption; it is not assigned a probability.
+\end{assumptionbox}
-### Rating Stars (1-5)
-```latex
-\rating{4} % Outputs: ★★★★☆
+\begin{limitationbox}[Material limitation]
+The source series was revised after the original retrieval date.
+\end{limitationbox}
```
-### Trend Indicators
-```latex
-\trendup{} % Green up triangle
-\trenddown{} % Red down triangle
-\trendflat{} % Gray right arrow
-```
+The compatibility aliases `keyinsightbox`, `marketdatabox`, `riskbox`,
+`recommendationbox`, and `calloutbox` remain available for existing reports,
+but prefer the evidence-specific environments above.
----
+## Tables
-## Table Formatting
+Put units in column headers and scope in the caption. Do not mix percentages and
+currency on a single unlabelled axis.
-### Standard Table with Alternating Rows
```latex
\begin{table}[htbp]
\centering
-\caption{Market Size by Region}
-\begin{tabular}{@{}lrrr@{}}
+\caption{Conditional market-size scenarios, Exampleland, nominal 2025 USD/year}
+\begin{tabular}{@{}lrrrl@{}}
\toprule
-\textbf{Region} & \textbf{Size} & \textbf{Share} & \textbf{CAGR} \\
-\midrule
-North America & \$18.2B & 40.3\% & 12.5\% \\
-\rowcolor{tablealt} Europe & \$12.1B & 26.8\% & 14.2\% \\
-Asia-Pacific & \$10.5B & 23.2\% & 18.7\% \\
-\rowcolor{tablealt} Rest of World & \$4.4B & 9.7\% & 11.3\% \\
+Scenario & TAM & SAM & SOM & Evidence \\
\midrule
-\textbf{Total} & \textbf{\$45.2B} & \textbf{100\%} & \textbf{15.3\%} \\
+Downside & [value] & [value] & [value] & S-001; S-004 \\
+Base & [value] & [value] & [value] & S-001; S-004 \\
+Upside & [value] & [value] & [value] & S-001; S-004 \\
\bottomrule
\end{tabular}
-\label{tab:regional}
\end{table}
```
-### Table with Trend Indicators
-```latex
-\begin{tabular}{@{}lrrl@{}}
-\toprule
-\textbf{Company} & \textbf{Revenue} & \textbf{Share} & \textbf{Trend} \\
-\midrule
-Company A & \$5.2B & 15.3\% & \trendup{} +12\% \\
-Company B & \$4.8B & 14.1\% & \trenddown{} -3\% \\
-Company C & \$4.2B & 12.4\% & \trendflat{} +1\% \\
-\bottomrule
-\end{tabular}
-```
-
----
-
-## Figure Formatting
-
-### Standard Figure
-```latex
-\begin{figure}[htbp]
-\centering
-\includegraphics[width=0.9\textwidth]{../figures/market_growth.png}
-\caption{Market Growth Trajectory (2020-2030)}
-\label{fig:growth}
-\end{figure}
-```
-
-### Figure with Source Attribution
-```latex
-\begin{figure}[htbp]
-\centering
-\includegraphics[width=0.85\textwidth]{../figures/market_share.png}
-\caption{Market Share Distribution (2024)}
-\figuresource{Company annual reports, industry analysis}
-\label{fig:market_share}
-\end{figure}
-```
-
----
-
-## List Formatting
-
-### Bullet Lists
-```latex
-\begin{itemize}
- \item First item with automatic blue bullet
- \item Second item
- \item Third item
-\end{itemize}
-```
-
-### Numbered Lists
-```latex
-\begin{enumerate}
- \item First item with blue number
- \item Second item
- \item Third item
-\end{enumerate}
-```
-
-### Nested Lists
-```latex
-\begin{itemize}
- \item Main point
- \begin{itemize}
- \item Sub-point A
- \item Sub-point B
- \end{itemize}
- \item Another main point
-\end{itemize}
-```
-
----
-
-## Title Page
-
-### Using the Custom Title Command
-```latex
-\makemarketreporttitle
- {Market Title} % Report title
- {Subtitle Here} % Subtitle
- {../figures/cover.png} % Hero image (leave empty for no image)
- {January 2025} % Date
- {Market Intelligence Team} % Author/prepared by
-```
-
-### Manual Title Page
-See the template for full manual title page code.
-
----
-
-## Appendix Sections
-
-```latex
-\appendix
-
-\chapter{Methodology}
-
-\appendixsection{Data Sources}
-Content that appears in table of contents...
-```
-
----
+Use `unknown` rather than a zero when evidence is missing. Explain suppression,
+rounding, residual categories, and totals that do not add because of chain
+weighting or independent seasonal adjustment.
-## Common Patterns
+## Optional figures
-### Market Snapshot Section
-```latex
-\begin{marketdatabox}[Market Snapshot]
-\begin{itemize}
- \item \textbf{Current Market Size:} \marketsize{45.2 billion}
- \item \textbf{Projected Size (2030):} \marketsize{98.7 billion}
- \item \textbf{CAGR:} \growthrate{15.3}
- \item \textbf{Largest Segment:} Enterprise (42\% share)
- \item \textbf{Fastest Growing Region:} APAC (\growthrate{22.1} CAGR)
-\end{itemize}
-\end{marketdatabox}
-```
+Figures are optional and should be created only when they improve
+understanding. A figure caption must identify:
-### Risk Register Summary
```latex
-\begin{table}[htbp]
-\centering
-\caption{Risk Assessment Summary}
-\begin{tabular}{@{}llccl@{}}
-\toprule
-\textbf{Risk} & \textbf{Category} & \textbf{Prob.} & \textbf{Impact} & \textbf{Rating} \\
-\midrule
-Market disruption & Market & High & High & \riskhigh{} \\
-\rowcolor{tablealt} Regulatory change & Regulatory & Med & High & \riskhigh{} \\
-New entrant & Competitive & Med & Med & \riskmedium{} \\
-\rowcolor{tablealt} Tech obsolescence & Technology & Low & High & \riskmedium{} \\
-Currency fluctuation & Financial & Med & Low & \risklow{} \\
-\bottomrule
-\end{tabular}
-\end{table}
-```
-
-### Competitive Comparison Table
-```latex
-\begin{table}[htbp]
-\centering
-\caption{Competitive Comparison}
-\begin{tabular}{@{}lccccc@{}}
-\toprule
-\textbf{Factor} & \textbf{Co. A} & \textbf{Co. B} & \textbf{Co. C} & \textbf{Co. D} \\
-\midrule
-Market Share & \rating{5} & \rating{4} & \rating{3} & \rating{2} \\
-\rowcolor{tablealt} Product Quality & \rating{4} & \rating{5} & \rating{3} & \rating{4} \\
-Price Competitiveness & \rating{3} & \rating{3} & \rating{5} & \rating{4} \\
-\rowcolor{tablealt} Innovation & \rating{5} & \rating{4} & \rating{2} & \rating{3} \\
-Customer Service & \rating{4} & \rating{4} & \rating{4} & \rating{5} \\
-\bottomrule
-\end{tabular}
-\end{table}
+\caption{Scenario range by year. Nominal 2025 USD/year; Exampleland;
+historical through 2025 and conditional scenarios thereafter.
+Sources: S-001, S-004. Calculation: CALC-FCST-002.}
```
----
+Never use decorative imagery as evidence. Never infer market share from logo
+size, search rank, or an unlabelled generated graphic.
-## Troubleshooting
+## Citations
-### Box Overflow
-If box content overflows the page, break into multiple boxes or use page breaks:
-```latex
-\newpage
-\begin{keyinsightbox}[Continued...]
-```
+Use stable source IDs in the report body and a complete evidence ledger in the
+appendix. A suggested compact notation is:
-### Figure Placement
-Use `[htbp]` for flexible placement, or `[H]` (requires `float` package) for exact placement:
-```latex
-\begin{figure}[H] % Requires \usepackage{float}
+```text
+The published count increased after the latest revision [C-014; S-003].
```
-### Table Too Wide
-Use `\resizebox` or `adjustbox`:
-```latex
-\resizebox{\textwidth}{!}{
-\begin{tabular}{...}
-...
-\end{tabular}
-}
-```
-
-### Color Not Appearing
-Ensure `xcolor` package is loaded with `[table]` option (already included in style file).
-
----
+The bibliography entry alone is not enough: the claims ledger must map each
+claim to the exact source record, retrieval date, and applicable calculation or
+assumption IDs.
-## Compilation
+## Final checks
-Compile with XeLaTeX for best results:
-```bash
-xelatex report.tex
-bibtex report
-xelatex report.tex
-xelatex report.tex
-```
-
-Or use latexmk:
-```bash
-latexmk -xelatex report.tex
-```
+- No placeholder numbers or unsupported precision remain.
+- Forecasts and TAM/SAM/SOM are visibly labeled as scenarios.
+- Observed and forecast periods are visually separated.
+- All monetary content states currency, base year, and price basis.
+- Every table and optional figure has source and calculation IDs.
+- Unknowns, conflicts, revisions, and limitations are visible.
+- Layout does not imply endorsement, legal advice, or investment advice.
diff --git a/skills/market-research-reports/assets/claims_ledger_template.csv b/skills/market-research-reports/assets/claims_ledger_template.csv
new file mode 100644
index 00000000..67733215
--- /dev/null
+++ b/skills/market-research-reports/assets/claims_ledger_template.csv
@@ -0,0 +1,4 @@
+claim_id,claim_text,claim_type,source_ids,calculation_id,assumption_ids,location,as_of_date,geography,currency,base_year,price_basis,measure_type,unit,taxonomy,taxonomy_version,revision_status,confidence,notes
+C-001,The synthetic fixture contains 11000 in-scope establishments.,quantitative_fact,S-001,,,Section 2,2026-07-23,Exampleland,,,not-applicable,count,establishments,EXAMPLE-INDUSTRY,2026,final,high,Synthetic example only
+C-002,Top-down synthetic TAM is 100000000 USD per year.,calculation,S-001;S-002,CALC-TAM-001,A-PRICE-001,Section 3,2026-07-23,Exampleland,USD,2025,nominal,flow,USD per year,EXAMPLE-INDUSTRY,2026,final,medium,Conditional calculation from synthetic inputs
+C-003,The upside scenario reaches 146932807.68 USD per year in 2030.,forecast,S-001;S-002,CALC-FCST-001,A-GROWTH-UPSIDE,Section 6,2026-07-23,Exampleland,USD,2025,nominal,flow,USD per year,EXAMPLE-INDUSTRY,2026,current,low,Scenario output rather than a confidence interval
diff --git a/skills/market-research-reports/assets/competitor_feature_matrix_template.csv b/skills/market-research-reports/assets/competitor_feature_matrix_template.csv
new file mode 100644
index 00000000..c7728170
--- /dev/null
+++ b/skills/market-research-reports/assets/competitor_feature_matrix_template.csv
@@ -0,0 +1,5 @@
+competitor_id,competitor_name,feature_id,feature_name,status,evidence_source_ids,as_of_date,geography,product_scope,notes
+COMP-A,Synthetic Competitor A,FEATURE-1,Synthetic feature one,yes,S-003,2026-07-23,Exampleland,Synthetic widget service,Fixture only
+COMP-A,Synthetic Competitor A,FEATURE-2,Synthetic feature two,partial,S-003,2026-07-23,Exampleland,Synthetic widget service,Fixture only
+COMP-B,Synthetic Competitor B,FEATURE-1,Synthetic feature one,no,S-003,2026-07-23,Exampleland,Synthetic widget service,Fixture only
+COMP-B,Synthetic Competitor B,FEATURE-2,Synthetic feature two,unknown,,2026-07-23,Exampleland,Synthetic widget service,No public evidence in synthetic fixture
diff --git a/skills/market-research-reports/assets/consistency_check_template.csv b/skills/market-research-reports/assets/consistency_check_template.csv
new file mode 100644
index 00000000..c9f6d8b3
--- /dev/null
+++ b/skills/market-research-reports/assets/consistency_check_template.csv
@@ -0,0 +1,3 @@
+record_id,comparison_group,value,unit,currency,base_year,price_basis,measure_type,geography,period,taxonomy,taxonomy_version,denominator_id,source_id
+R-001,annual-market-spend,60000000,USD per year,USD,2025,nominal,flow,Exampleland,2025,EXAMPLE-INDUSTRY,2026,annual-end-customer-spend,S-002
+R-002,annual-market-spend,40000000,USD per year,USD,2025,nominal,flow,Exampleland,2025,EXAMPLE-INDUSTRY,2026,annual-end-customer-spend,S-002
diff --git a/skills/market-research-reports/assets/forecast_sensitivity_template.json b/skills/market-research-reports/assets/forecast_sensitivity_template.json
new file mode 100644
index 00000000..b7866658
--- /dev/null
+++ b/skills/market-research-reports/assets/forecast_sensitivity_template.json
@@ -0,0 +1,90 @@
+{
+ "schema_version": "1.0",
+ "metadata": {
+ "series_id": "synthetic-annual-market-spend",
+ "description": "Synthetic annual end-customer spend",
+ "geography": "Exampleland",
+ "currency": "USD",
+ "base_year": "2025",
+ "price_basis": "nominal",
+ "unit": "USD per year",
+ "measure_type": "flow",
+ "as_of_date": "2026-07-23",
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ]
+ },
+ "start_year": 2025,
+ "start_value": 100000000,
+ "horizon_years": 5,
+ "scenarios": [
+ {
+ "scenario_id": "downside",
+ "label": "Downside",
+ "annual_growth_rates": [
+ 0.02,
+ 0.02,
+ 0.02,
+ 0.02,
+ 0.02
+ ],
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumptions": [
+ "Demand grows slowly",
+ "No change to the market denominator"
+ ]
+ },
+ {
+ "scenario_id": "base",
+ "label": "Base",
+ "annual_growth_rates": [
+ 0.05,
+ 0.05,
+ 0.05,
+ 0.05,
+ 0.05
+ ],
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumptions": [
+ "Demand follows the documented synthetic baseline",
+ "Price basis remains nominal 2025 USD"
+ ]
+ },
+ {
+ "scenario_id": "upside",
+ "label": "Upside",
+ "annual_growth_rates": [
+ 0.08,
+ 0.08,
+ 0.08,
+ 0.08,
+ 0.08
+ ],
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumptions": [
+ "Adoption accelerates",
+ "No probability is assigned to this scenario"
+ ]
+ }
+ ],
+ "sensitivity": {
+ "base_scenario_id": "base",
+ "growth_rate_shifts": [
+ -0.02,
+ -0.01,
+ 0,
+ 0.01,
+ 0.02
+ ]
+ }
+}
diff --git a/skills/market-research-reports/assets/market_report_template.tex b/skills/market-research-reports/assets/market_report_template.tex
index 244264b6..f0b01ae6 100644
--- a/skills/market-research-reports/assets/market_report_template.tex
+++ b/skills/market-research-reports/assets/market_report_template.tex
@@ -1,1380 +1,279 @@
% !TEX program = xelatex
-% Market Research Report Template
-% Professional formatting for 50+ page comprehensive market reports
-% Use with market_research.sty style package
-
+% Evidence-first market research report template.
\documentclass[11pt,letterpaper]{report}
\usepackage{market_research}
-% ============================================================================
-% DOCUMENT METADATA - CUSTOMIZE THESE
-% ============================================================================
-\newcommand{\reporttitle}{[MARKET NAME]}
-\newcommand{\reportsubtitle}{Comprehensive Market Analysis Report}
-\newcommand{\reportdate}{\today}
-\newcommand{\reportauthor}{Market Intelligence Division}
-\newcommand{\reportclassification}{Confidential}
+\newcommand{\reporttitle}{[Market name]}
+\newcommand{\reportsubtitle}{Evidence-first market assessment}
+\newcommand{\retrievalcutoff}{[YYYY-MM-DD]}
+\newcommand{\reportauthor}{[Prepared by]}
+\newcommand{\reportclassification}{[Public / Internal / Confidential]}
-% ============================================================================
-% PDF METADATA
-% ============================================================================
\hypersetup{
- pdftitle={\reporttitle{} - \reportsubtitle{}},
- pdfauthor={\reportauthor{}},
- pdfsubject={Market Research Report},
- pdfkeywords={market research, market analysis, competitive landscape, strategic analysis}
+ pdftitle={\reporttitle{} --- \reportsubtitle{}},
+ pdfauthor={\reportauthor{}},
+ pdfkeywords={market definition, evidence ledger, scenario analysis}
}
-% ============================================================================
-% DOCUMENT START
-% ============================================================================
\begin{document}
-% ============================================================================
-% TITLE PAGE
-% ============================================================================
-% To use a hero image, replace the empty braces with the path:
-% \makemarketreporttitle{\reporttitle}{\reportsubtitle}{../figures/cover_image.png}{\reportdate}{\reportauthor}
-
-\begin{titlepage}
-\centering
-\vspace*{2cm}
-
-{\Huge\bfseries\color{primaryblue} \reporttitle\\[0.5cm]}
-{\LARGE\bfseries \reportsubtitle\\[1.5cm]}
-
-% VISUAL: Generate hero/cover image
-% python skills/generate-image/scripts/generate_image.py "Professional executive summary infographic for [MARKET] market research report, showing key metrics in modern data visualization style, blue and green color scheme, clean minimalist design" --output figures/cover_image.png
-% Uncomment below when image is generated:
-% \includegraphics[width=\textwidth]{../figures/cover_image.png}\\[1.5cm]
-
-\vspace{4cm}
-
-{\Large\bfseries Comprehensive Market Research Report\\[0.5cm]}
-{\large Strategic Intelligence for Business Decision-Making\\[3cm]}
-
-{\large
-\textbf{Date:} \reportdate\\[0.3cm]
-\textbf{Prepared By:} \reportauthor\\[0.3cm]
-\textbf{Classification:} \reportclassification\\[0.3cm]
-\textbf{Report Type:} Full Market Analysis
-}
-
-\vfill
-
-{\footnotesize
-\textit{This report contains market intelligence and strategic analysis based on publicly available data and proprietary research. All sources are cited and independently verifiable.}
-}
-
-\end{titlepage}
+\makemarketreporttitle
+ {\reporttitle}
+ {\reportsubtitle}
+ {\retrievalcutoff}
+ {\reportauthor}
-% ============================================================================
-% FRONT MATTER
-% ============================================================================
\pagenumbering{roman}
-% Table of Contents
-\tableofcontents
-\newpage
-
-% List of Figures
-\listoffigures
-\newpage
+\begin{calloutbox}[Use and limitations]
+This report distinguishes observed facts, estimates, calculations, scenarios,
+opinions, and recommendations. Claim IDs map to the claims ledger; source IDs
+map to the evidence ledger. Scenario ranges are conditional and are not
+confidence intervals unless a separately documented statistical model supports
+that interpretation. This report is not investment, legal, or financial advice.
+\end{calloutbox}
-% List of Tables
-\listoftables
-\newpage
+\textbf{Classification:} \reportclassification
-% ============================================================================
-% MAIN CONTENT
-% ============================================================================
+\tableofcontents
+\clearpage
\pagenumbering{arabic}
-% ============================================================================
-% EXECUTIVE SUMMARY (2-3 pages)
-% ============================================================================
-\chapter{Executive Summary}
-
-\section{Report Overview}
-
-This comprehensive market analysis examines the \reporttitle{} market, providing strategic intelligence for investors, executives, and strategic planners. The report synthesizes data from authoritative sources including market research firms, regulatory agencies, industry associations, and enterprise surveys.
+\chapter{Executive Synopsis}
-% VISUAL: Executive summary infographic
-% python skills/scientific-schematics/scripts/generate_schematic.py "Executive summary infographic showing 4 key metrics: Market Size $XX.XB (2024), CAGR XX.X%, Top 3 Players, and Key Trend. Use blue boxes with white text, professional layout" -o figures/exec_summary_infographic.png --doc-type report
+\section{Decision Context}
+[State the decision, audience, retrieval cutoff, and material scope constraints.]
-\subsection{Market Snapshot}
-
-\begin{marketdatabox}[Market Snapshot: \reporttitle{}]
-\begin{itemize}[leftmargin=*]
- \item \textbf{Current Market Size (2024):} \marketsize{X.XX billion}
- \item \textbf{Projected Market Size (2034):} \marketsize{XX.XX billion}
- \item \textbf{Compound Annual Growth Rate (CAGR):} \growthrate{XX.X}
- \item \textbf{Growth Multiple:} Xx increase over 10 years
- \item \textbf{Largest Segment:} [Segment Name] (XX\% market share)
- \item \textbf{Fastest Growing Region:} [Region] (\growthrate{XX.X} CAGR)
- \item \textbf{Current Enterprise Adoption:} XX\%
+\section{Findings}
+\begin{evidencebox}[Observed findings]
+\begin{itemize}
+ \item [Finding with \claimref{C-001} and \sourceref{S-001}.]
+ \item [Finding with explicit geography, period, unit, and revision status.]
\end{itemize}
-\end{marketdatabox}
+\end{evidencebox}
-\subsection{Investment Thesis}
+\section{Scenario Range}
+\begin{calculationbox}[Conditional range]
+[State the range across named scenarios and methods. Include calculation IDs,
+currency, base year, price basis, period, and denominator.]
+\end{calculationbox}
-The convergence of multiple market catalysts creates a compelling opportunity for investment and strategic action in the \reporttitle{} market:
+\begin{assumptionbox}[Key assumptions]
+[List the assumptions that most influence the result and their
+\assumptionref{A-...} identifiers.]
+\end{assumptionbox}
-\begin{keyinsightbox}[Key Investment Drivers]
-\begin{enumerate}
- \item \textbf{[Driver 1]:} [Brief explanation of why this driver creates opportunity]
- \item \textbf{[Driver 2]:} [Brief explanation]
- \item \textbf{[Driver 3]:} [Brief explanation]
- \item \textbf{[Driver 4]:} [Brief explanation]
-\end{enumerate}
-\end{keyinsightbox}
+\begin{limitationbox}[Material limitations]
+[List unresolved source conflicts, missing evidence, revisions, sample
+limitations, taxonomy breaks, and model limitations.]
+\end{limitationbox}
-\subsection{Key Findings}
-
-\paragraph{Market Dynamics}
-[Summarize the most important findings about market size, growth, and dynamics. Include 3-5 key statistics with sources.]
-
-\paragraph{Competitive Landscape}
-[Summarize competitive dynamics, market concentration, and key players. Include market share of top players.]
-
-\paragraph{Growth Drivers}
-[Summarize the primary factors driving market growth and their expected impact.]
-
-\paragraph{Risk Factors}
-[Summarize the key risks that could impact market development.]
-
-\subsection{Strategic Recommendations}
-
-Based on the comprehensive analysis presented in this report, we recommend the following strategic actions:
-
-\begin{recommendationbox}[Top Strategic Recommendations]
-\begin{enumerate}
- \item \textbf{[Recommendation 1]:} [Action-oriented recommendation with expected outcome]
- \item \textbf{[Recommendation 2]:} [Action-oriented recommendation with expected outcome]
- \item \textbf{[Recommendation 3]:} [Action-oriented recommendation with expected outcome]
- \item \textbf{[Recommendation 4]:} [Action-oriented recommendation with expected outcome]
- \item \textbf{[Recommendation 5]:} [Action-oriented recommendation with expected outcome]
-\end{enumerate}
-\end{recommendationbox}
-
-% ============================================================================
-% CHAPTER 1: MARKET OVERVIEW & DEFINITION (4-5 pages)
-% ============================================================================
-\chapter{Market Overview \& Definition}
+\chapter{Scope, Definitions, and Method}
\section{Market Definition}
-
-[Provide a clear, comprehensive definition of the market being analyzed. Include:
-- What products/services are included
-- What is explicitly excluded
-- How this market relates to adjacent markets
-- Industry classification codes if applicable (NAICS, SIC)]
-
-\begin{calloutbox}[Market Definition]
-The \reporttitle{} market encompasses [comprehensive definition]. This includes [included elements] and excludes [excluded elements].
+\begin{calloutbox}[Formal definition]
+[Define the product or service, customer, geography, transaction type,
+measurement basis, and period.]
\end{calloutbox}
-\subsection{Scope and Boundaries}
-
-\paragraph{Geographic Scope}
-[Define the geographic boundaries of the analysis - global, regional, or specific countries.]
-
-\paragraph{Product/Service Scope}
-[Define what products and services are included in the market definition.]
-
-\paragraph{Time Horizon}
-[Specify the historical period analyzed and the forecast period.]
-
-\subsection{Market Classification}
-
-[Provide detailed market classification and taxonomy, including:
-- Market segments
-- Sub-segments
-- Categories]
-
-\section{Industry Ecosystem}
-
-% VISUAL: Industry ecosystem diagram
-% python skills/scientific-schematics/scripts/generate_schematic.py "Industry ecosystem diagram showing value chain from [Raw Materials/Inputs] on left through [Manufacturing/Processing] through [Distribution] to [End Users] on right. Include key players at each stage. Use blue boxes connected by arrows" -o figures/industry_ecosystem.png --doc-type report
-
-[Describe the industry ecosystem and value chain, including:
-- Key stakeholders and their roles
-- Relationships between stakeholders
-- Value creation at each stage
-- Information and money flows]
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.95\textwidth]{../figures/industry_ecosystem.png}
-\caption{Industry Ecosystem and Value Chain}
-\label{fig:ecosystem}
-\end{figure}
-
-\subsection{Key Stakeholders}
-
-[Describe each category of stakeholder:]
-
-\paragraph{Suppliers/Vendors}
-[Description of upstream suppliers and their role.]
-
-\paragraph{Manufacturers/Service Providers}
-[Description of core market participants.]
-
-\paragraph{Distributors/Channels}
-[Description of distribution and go-to-market channels.]
-
-\paragraph{End Users/Customers}
-[Description of customer segments and their needs.]
-
-\paragraph{Regulators and Industry Bodies}
-[Description of regulatory environment and industry associations.]
-
-\section{Market Structure}
-
-% VISUAL: Market structure diagram
-% python skills/scientific-schematics/scripts/generate_schematic.py "Market structure diagram showing industry layers: [Core Market] in center, surrounded by [Adjacent Markets], with [Enabling Technologies] as foundation and [Regulatory Framework] as overlay. Use concentric rectangles" -o figures/market_structure.png --doc-type report
-
-[Describe the structure of the market:]
-
-\subsection{Market Concentration}
-
-[Analyze market concentration using metrics like:
-- Herfindahl-Hirschman Index (HHI)
-- CR4/CR8 concentration ratios
-- Market fragmentation assessment]
-
-\subsection{Industry Lifecycle Stage}
-
-[Identify where the market is in its lifecycle:
-- Introduction
-- Growth
-- Maturity
-- Decline]
-
-\section{Historical Context}
-
-[Provide historical background on the market:
-- When did the market emerge?
-- Key milestones in market development
-- Major industry shifts and disruptions
-- How has the market evolved over time?]
-
-% ============================================================================
-% CHAPTER 2: MARKET SIZE & GROWTH ANALYSIS (6-8 pages)
-% ============================================================================
-\chapter{Market Size \& Growth Analysis}
-
-\section{Total Addressable Market (TAM)}
-
-The Total Addressable Market represents the total revenue opportunity available if 100\% market share was achieved. Based on comprehensive analysis from multiple research sources:
-
-% VISUAL: Market growth trajectory
-% python skills/scientific-schematics/scripts/generate_schematic.py "Bar chart showing market growth from 2020 to 2034. Historical bars (2020-2024) in dark blue, projected bars (2025-2034) in light blue. Y-axis in billions USD, X-axis showing years. Include CAGR label. Title: [MARKET] Market Growth Trajectory" -o figures/market_growth_trajectory.png --doc-type report
-
-\begin{table}[htbp]
-\centering
-\caption{Global \reporttitle{} Market Projections (2024-2034)}
-\begin{tabular}{@{}lrrr@{}}
-\toprule
-\textbf{Year} & \textbf{Market Size (USD)} & \textbf{YoY Growth} & \textbf{CAGR} \\
-\midrule
-2024 & \$X.XX B & -- & -- \\
-\rowcolor{tablealt} 2025 & \$X.XX B & XX.X\% & XX.X\% \\
-2026 & \$X.XX B & XX.X\% & XX.X\% \\
-\rowcolor{tablealt} 2027 & \$X.XX B & XX.X\% & XX.X\% \\
-2028 & \$X.XX B & XX.X\% & XX.X\% \\
-\rowcolor{tablealt} 2029 & \$X.XX B & XX.X\% & XX.X\% \\
-2030 & \$X.XX B & XX.X\% & XX.X\% \\
-\rowcolor{tablealt} 2031 & \$X.XX B & XX.X\% & XX.X\% \\
-2032 & \$X.XX B & XX.X\% & XX.X\% \\
-\rowcolor{tablealt} 2033 & \$X.XX B & XX.X\% & XX.X\% \\
-2034 & \$X.XX B & XX.X\% & XX.X\% \\
-\bottomrule
-\end{tabular}
-\label{tab:tam_projections}
-\end{table}
-
-\textbf{Source:} [Primary research source, year]
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/market_growth_trajectory.png}
-\caption{Market Growth Trajectory (2020-2034)}
-\label{fig:market_growth}
-\end{figure}
-
-\subsection{Historical Growth Analysis}
-
-[Analyze historical market performance over the past 5-10 years:
-- Historical CAGR
-- Key growth periods and drivers
-- Impact of major events (recessions, disruptions, etc.)
-- Comparison to overall economic growth]
-
-\subsection{Growth Projections Methodology}
-
-[Explain the methodology behind growth projections:
-- Key assumptions
-- Data sources
-- Modeling approach
-- Confidence intervals]
-
-\section{Serviceable Addressable Market (SAM)}
-
-The Serviceable Addressable Market represents the portion of TAM that can be served given current product offerings, geographic presence, and regulatory constraints.
-
-% VISUAL: TAM/SAM/SOM diagram
-% python skills/scientific-schematics/scripts/generate_schematic.py "TAM SAM SOM concentric circle diagram. Outer circle: TAM $XXB (Total Addressable Market). Middle circle: SAM $XXB (Serviceable Addressable Market). Inner circle: SOM $XXB (Serviceable Obtainable Market). Labels with arrows pointing to each. Professional blue color scheme" -o figures/tam_sam_som.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.8\textwidth]{../figures/tam_sam_som.png}
-\caption{TAM/SAM/SOM Market Opportunity Breakdown}
-\label{fig:tam_sam_som}
-\end{figure}
-
-\begin{table}[htbp]
-\centering
-\caption{Market Segments Within SAM (2024 vs 2034)}
-\begin{tabular}{@{}lrrrr@{}}
-\toprule
-\textbf{Segment} & \textbf{2024 Value} & \textbf{2034 Value} & \textbf{CAGR} & \textbf{Share} \\
-\midrule
-Segment A & \$X.XX B & \$XX.XX B & XX.X\% & XX\% \\
-\rowcolor{tablealt} Segment B & \$X.XX B & \$XX.XX B & XX.X\% & XX\% \\
-Segment C & \$X.XX B & \$XX.XX B & XX.X\% & XX\% \\
-\rowcolor{tablealt} Segment D & \$X.XX B & \$XX.XX B & XX.X\% & XX\% \\
-Segment E & \$X.XX B & \$XX.XX B & XX.X\% & XX\% \\
-\midrule
-\textbf{Total SAM} & \textbf{\$X.XX B} & \textbf{\$XX.XX B} & \textbf{XX.X\%} & \textbf{100\%} \\
-\bottomrule
-\end{tabular}
-\label{tab:sam_segments}
-\end{table}
-
-\section{Serviceable Obtainable Market (SOM)}
-
-The Serviceable Obtainable Market represents the realistic market share capture based on competitive dynamics, go-to-market capabilities, and strategic positioning.
-
-\begin{keyinsightbox}[SOM Projections (2034)]
-\textbf{Conservative Scenario (XX\% Market Share):} \marketsize{X.X billion}
-\begin{itemize}
- \item Assumes competitive market with multiple major players
- \item Typical XX-XX month enterprise sales cycles
- \item Focus on [specific segments]
-\end{itemize}
-
-\textbf{Base Case Scenario (XX\% Market Share):} \marketsize{X.X billion}
+\subsection{Included}
\begin{itemize}
- \item Captures first-mover advantages in key segments
- \item Strong product-market fit
- \item Established partnership ecosystem
+ \item [Included product, customer, or channel.]
\end{itemize}
-\textbf{Optimistic Scenario (XX\% Market Share):} \marketsize{X.X billion}
+\subsection{Excluded}
\begin{itemize}
- \item Market leadership position
- \item Platform effects and network advantages
- \item Proprietary advantages and moats
+ \item [Excluded category and reason.]
\end{itemize}
-\end{keyinsightbox}
-\section{Regional Market Analysis}
-
-% VISUAL: Regional breakdown
-% python skills/scientific-schematics/scripts/generate_schematic.py "Pie chart or treemap showing regional market breakdown. North America XX%, Europe XX%, Asia-Pacific XX%, Latin America XX%, Middle East & Africa XX%. Use distinct colors for each region. Include both percentage and dollar values" -o figures/regional_breakdown.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.8\textwidth]{../figures/regional_breakdown.png}
-\caption{Market Size by Region (2024)}
-\label{fig:regional_breakdown}
-\end{figure}
-
-\begin{table}[htbp]
-\centering
-\caption{Regional Market Size and Growth}
-\begin{tabular}{@{}lrrrr@{}}
+\section{Measurement Contract}
+\begin{longtable}{@{}p{0.28\textwidth}p{0.64\textwidth}@{}}
\toprule
-\textbf{Region} & \textbf{2024 Size} & \textbf{Share} & \textbf{CAGR} & \textbf{2034 Size} \\
+Field & Definition \\
\midrule
-North America & \$X.XX B & XX.X\% & XX.X\% & \$XX.XX B \\
-\rowcolor{tablealt} Europe & \$X.XX B & XX.X\% & XX.X\% & \$XX.XX B \\
-Asia-Pacific & \$X.XX B & XX.X\% & XX.X\% & \$XX.XX B \\
-\rowcolor{tablealt} Latin America & \$X.XX B & XX.X\% & XX.X\% & \$XX.XX B \\
-Middle East \& Africa & \$X.XX B & XX.X\% & XX.X\% & \$XX.XX B \\
-\midrule
-\textbf{Global Total} & \textbf{\$X.XX B} & \textbf{100\%} & \textbf{XX.X\%} & \textbf{\$XX.XX B} \\
+\endhead
+Geography & [Boundary and treatment of imports/exports] \\
+Historical period & [Start--end] \\
+Forecast period & [Start--end] \\
+Currency and base year & [Currency; nominal/real/current/constant basis] \\
+Measure type & [Stock/flow/count/share/rate/price/index] \\
+Unit and denominator & [Explicit unit and denominator ID] \\
+Industry taxonomy & [NAICS/NACE/ISIC or other taxonomy and version] \\
+Product taxonomy & [NAPCS/CPA/PRODCOM/CPC or other taxonomy and version] \\
+Retrieval cutoff & \retrievalcutoff \\
\bottomrule
-\end{tabular}
-\label{tab:regional_market}
-\end{table}
-
-\subsection{North America}
-[Detailed analysis of North American market including US and Canada specifics.]
-
-\subsection{Europe}
-[Detailed analysis of European market including key country breakdowns.]
-
-\subsection{Asia-Pacific}
-[Detailed analysis of APAC market with focus on China, Japan, India, and emerging markets.]
-
-\subsection{Rest of World}
-[Analysis of Latin America, Middle East, and Africa markets.]
-
-\section{Segment Analysis}
-
-% VISUAL: Segment growth comparison
-% python skills/scientific-schematics/scripts/generate_schematic.py "Horizontal bar chart comparing segment growth rates. Segments listed on Y-axis, CAGR percentage on X-axis. Bars colored from green (highest growth) to blue (lowest growth). Include data labels on each bar" -o figures/segment_growth.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/segment_growth.png}
-\caption{Segment Growth Rate Comparison (CAGR 2024-2034)}
-\label{fig:segment_growth}
-\end{figure}
-
-[Provide detailed analysis of each market segment including:
-- Current size and market share
-- Growth trajectory
-- Key drivers for each segment
-- Competitive dynamics within segment]
-
-% ============================================================================
-% CHAPTER 3: INDUSTRY DRIVERS & TRENDS (5-6 pages)
-% ============================================================================
-\chapter{Industry Drivers \& Trends}
-
-\section{Primary Growth Drivers}
-
-[Identify and analyze the key factors driving market growth:]
-
-% VISUAL: Driver impact matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "2x2 matrix showing market drivers. X-axis: Impact (Low to High). Y-axis: Likelihood (Low to High). Plot 8-10 drivers as circles. Upper-right quadrant labeled 'Critical Drivers', lower-right 'Watch Carefully', upper-left 'Monitor', lower-left 'Lower Priority'. Professional blue and green colors" -o figures/driver_impact_matrix.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/driver_impact_matrix.png}
-\caption{Market Driver Impact Assessment Matrix}
-\label{fig:driver_matrix}
-\end{figure}
-
-\subsection{Driver 1: [Name]}
-[Detailed analysis of this driver including:
-- How it affects the market
-- Quantified impact
-- Timeline for impact
-- Supporting evidence and data]
-
-\subsection{Driver 2: [Name]}
-[Detailed analysis]
-
-\subsection{Driver 3: [Name]}
-[Detailed analysis]
-
-\subsection{Driver 4: [Name]}
-[Detailed analysis]
-
-\subsection{Driver 5: [Name]}
-[Detailed analysis]
-
-\section{PESTLE Analysis}
-
-% VISUAL: PESTLE diagram
-% python skills/scientific-schematics/scripts/generate_schematic.py "PESTLE analysis diagram with center hexagon labeled 'Market' surrounded by 6 hexagons: Political (red), Economic (blue), Social (green), Technological (orange), Legal (purple), Environmental (teal). Each outer hexagon contains 2-3 bullet points of key factors" -o figures/pestle_analysis.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/pestle_analysis.png}
-\caption{PESTLE Analysis Framework}
-\label{fig:pestle}
-\end{figure}
-
-\subsection{Political Factors}
-[Analysis of political factors affecting the market:
-- Government policies
-- Political stability
-- Trade policies
-- Tax regulations]
-
-\subsection{Economic Factors}
-[Analysis of economic factors:
-- Economic growth
-- Interest rates
-- Inflation
-- Exchange rates
-- Consumer spending]
+\end{longtable}
-\subsection{Social Factors}
-[Analysis of social factors:
-- Demographics
-- Cultural trends
-- Consumer attitudes
-- Workforce trends]
+\section{Evidence Hierarchy and Conflicts}
+[Describe the source hierarchy, exact claim--source mapping, snapshot/archive
+policy, revision treatment, and how conflicting sources were reconciled or
+retained as a range.]
-\subsection{Technological Factors}
-[Analysis of technological factors:
-- Technology adoption
-- R\&D activity
-- Automation
-- Digital transformation]
+\chapter{Market Size and Reconciliation}
-\subsection{Legal Factors}
-[Analysis of legal factors:
-- Industry regulations
-- Compliance requirements
-- Intellectual property
-- Employment laws]
+\section{Top-Down Method}
+[List disjoint components, coverage keys, sources, conversions, and exclusions.
+Do not sum gross output, revenue, trade, and end-customer spend as though they
+were the same denominator.]
-\subsection{Environmental Factors}
-[Analysis of environmental factors:
-- Sustainability requirements
-- Environmental regulations
-- Climate impact
-- Resource availability]
+\section{Bottom-Up Method}
+[Show customer or unit counts, annual quantities, price assumptions,
+addressable fractions, sources, and formulas.]
-\section{Emerging Trends}
-
-% VISUAL: Trends timeline
-% python skills/scientific-schematics/scripts/generate_schematic.py "Horizontal timeline showing emerging trends from 2024 to 2030. Mark 6-8 trends at different points on timeline with icons and labels. Use different colors for Technology trends (blue), Market trends (green), and Regulatory trends (orange). Include brief descriptions below each trend" -o figures/trends_timeline.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/trends_timeline.png}
-\caption{Emerging Industry Trends Timeline}
-\label{fig:trends}
-\end{figure}
-
-[Identify and analyze emerging trends that will shape the market:]
-
-\subsection{Trend 1: [Name]}
-[Detailed trend analysis]
-
-\subsection{Trend 2: [Name]}
-[Detailed trend analysis]
-
-\subsection{Trend 3: [Name]}
-[Detailed trend analysis]
-
-\section{Growth Inhibitors}
-
-[Identify factors that could slow market growth:
-- Market barriers
-- Resource constraints
-- Adoption challenges
-- Competitive pressures]
-
-% ============================================================================
-% CHAPTER 4: COMPETITIVE LANDSCAPE (6-8 pages)
-% ============================================================================
-\chapter{Competitive Landscape}
-
-\section{Market Structure Analysis}
-
-[Analyze the competitive structure of the market:]
-
-\subsection{Market Concentration}
-
-[Provide market concentration analysis:
-- Number of competitors
-- Market share distribution
-- Concentration metrics (HHI, CR4)]
-
-\section{Porter's Five Forces Analysis}
-
-% VISUAL: Porter's Five Forces
-% python skills/scientific-schematics/scripts/generate_schematic.py "Porter's Five Forces diagram. Center box labeled 'Competitive Rivalry: [HIGH/MEDIUM/LOW]'. Four boxes around it connected by arrows: 'Threat of New Entrants: [RATING]' (top), 'Bargaining Power of Suppliers: [RATING]' (left), 'Bargaining Power of Buyers: [RATING]' (right), 'Threat of Substitutes: [RATING]' (bottom). Color code by rating: High=red, Medium=orange, Low=green" -o figures/porters_five_forces.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/porters_five_forces.png}
-\caption{Porter's Five Forces Analysis}
-\label{fig:porter}
-\end{figure}
-
-\begin{porterbox}[Porter's Five Forces Summary]
-\begin{tabular}{@{}ll@{}}
-\textbf{Force} & \textbf{Rating} \\
-\midrule
-Threat of New Entrants & \riskmedium{} \\
-Bargaining Power of Suppliers & \risklow{} \\
-Bargaining Power of Buyers & \riskhigh{} \\
-Threat of Substitutes & \risklow{} \\
-Competitive Rivalry & \riskhigh{} \\
-\end{tabular}
-\end{porterbox}
-
-\subsection{Threat of New Entrants}
-[Detailed analysis of barriers to entry and threat level]
-
-\subsection{Bargaining Power of Suppliers}
-[Detailed analysis of supplier power dynamics]
-
-\subsection{Bargaining Power of Buyers}
-[Detailed analysis of buyer power dynamics]
-
-\subsection{Threat of Substitutes}
-[Detailed analysis of substitute products/services]
-
-\subsection{Competitive Rivalry}
-[Detailed analysis of competitive intensity]
-
-\section{Market Share Analysis}
-
-% VISUAL: Market share chart
-% python skills/scientific-schematics/scripts/generate_schematic.py "Pie chart showing market share of top 10 companies. Company A XX%, Company B XX%, Company C XX%, [etc.], Others XX%. Use distinct colors for each company. Include legend with company names and percentages" -o figures/market_share.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.8\textwidth]{../figures/market_share.png}
-\caption{Market Share by Company (2024)}
-\label{fig:market_share}
-\end{figure}
-
-\begin{table}[htbp]
-\centering
-\caption{Top 10 Companies by Market Share}
-\begin{tabular}{@{}clrrr@{}}
+\section{TAM, SAM, and SOM Scenarios}
+\begin{markettable}{Conditional TAM/SAM/SOM scenarios}
+\begin{tabular}{@{}lrrrl@{}}
\toprule
-\textbf{Rank} & \textbf{Company} & \textbf{Revenue} & \textbf{Share} & \textbf{YoY Growth} \\
+Scenario & TAM & SAM & SOM & Calculation \\
\midrule
-1 & Company A & \$X.XX B & XX.X\% & \trendup{} XX\% \\
-\rowcolor{tablealt} 2 & Company B & \$X.XX B & XX.X\% & \trendup{} XX\% \\
-3 & Company C & \$X.XX B & XX.X\% & \trendflat{} XX\% \\
-\rowcolor{tablealt} 4 & Company D & \$X.XX B & XX.X\% & \trendup{} XX\% \\
-5 & Company E & \$X.XX B & XX.X\% & \trenddown{} XX\% \\
-\rowcolor{tablealt} 6 & Company F & \$X.XX B & XX.X\% & \trendup{} XX\% \\
-7 & Company G & \$X.XX B & XX.X\% & \trendup{} XX\% \\
-\rowcolor{tablealt} 8 & Company H & \$X.XX B & XX.X\% & \trendflat{} XX\% \\
-9 & Company I & \$X.XX B & XX.X\% & \trendup{} XX\% \\
-\rowcolor{tablealt} 10 & Company J & \$X.XX B & XX.X\% & \trenddown{} XX\% \\
-\midrule
-& Others & \$X.XX B & XX.X\% & -- \\
+Downside & [value] & [value] & [value] & \calcref{CALC-...} \\
+\tablerowcolor
+Base & [value] & [value] & [value] & \calcref{CALC-...} \\
+Upside & [value] & [value] & [value] & \calcref{CALC-...} \\
\bottomrule
\end{tabular}
-\label{tab:market_share}
-\end{table}
-
-\section{Competitive Positioning}
-
-% VISUAL: Competitive positioning matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "2x2 competitive positioning matrix. X-axis: 'Market Focus' from Niche (left) to Broad (right). Y-axis: 'Solution Approach' from Product (bottom) to Platform (top). Plot 8-10 companies as labeled circles of varying sizes (representing market share). Include quadrant labels" -o figures/competitive_positioning.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/competitive_positioning.png}
-\caption{Competitive Positioning Matrix}
-\label{fig:competitive_positioning}
-\end{figure}
-
-[Analyze how competitors are positioned in the market based on key dimensions:]
-
-\subsection{Strategic Groups}
-
-% VISUAL: Strategic group map
-% python skills/scientific-schematics/scripts/generate_schematic.py "Strategic group map with circles representing different strategic groups. X-axis: Geographic Scope (Regional to Global). Y-axis: Product Breadth (Narrow to Broad). Each circle contains multiple company names and is sized by collective market share. 4-5 distinct groups" -o figures/strategic_groups.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/strategic_groups.png}
-\caption{Strategic Group Mapping}
-\label{fig:strategic_groups}
-\end{figure}
-
-[Identify and describe strategic groups within the competitive landscape]
+\end{markettable}
-\section{Competitive Dynamics}
-
-[Analyze competitive behaviors and dynamics:
-- Recent M\&A activity
-- Partnership announcements
-- Product launches
-- Pricing trends
-- Geographic expansion]
-
-\section{Barriers to Entry}
+\begin{assumptionbox}[Interpretation]
+TAM, SAM, and SOM are conditional scenario outputs. They are not a single
+asserted market truth. Explain serviceability filters, capture constraints,
+time horizon, and why the scenarios differ.
+\end{assumptionbox}
-[Analyze barriers that protect incumbents and challenge new entrants:
-- Capital requirements
-- Regulatory barriers
-- Technology barriers
-- Brand and reputation
-- Distribution access
-- Economies of scale]
+\section{Method Reconciliation}
+[Report the absolute gap and gap as a percentage of the methods' midpoint.
+Investigate inconsistent boundaries, denominators, taxes, channels, time
+periods, currencies, and double counting before averaging estimates.]
-% ============================================================================
-% CHAPTER 5: CUSTOMER ANALYSIS & SEGMENTATION (4-5 pages)
-% ============================================================================
-\chapter{Customer Analysis \& Segmentation}
+\section{Sensitivity}
+[Show how results change when the principal assumptions vary. State switching
+values at which a decision would change.]
-\section{Customer Segmentation}
+\chapter{Demand and Customer Evidence}
-% VISUAL: Customer segmentation
-% python skills/scientific-schematics/scripts/generate_schematic.py "Treemap or pie chart showing customer segments. Segment A XX% (large enterprises), Segment B XX% (mid-market), Segment C XX% (SMB), Segment D XX% (other). Size represents market share. Use distinct colors" -o figures/customer_segments.png --doc-type report
+\section{Observed Demand}
+[Report administrative, transactional, official statistical, or filing-based
+evidence with exact definitions and source IDs.]
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/customer_segments.png}
-\caption{Customer Segmentation by Market Share}
-\label{fig:customer_segments}
-\end{figure}
-
-\begin{table}[htbp]
-\centering
-\caption{Customer Segment Analysis}
-\begin{tabular}{@{}lrrrr@{}}
+\section{Survey Evidence}
+\begin{longtable}{@{}p{0.30\textwidth}p{0.62\textwidth}@{}}
\toprule
-\textbf{Segment} & \textbf{Size} & \textbf{Growth} & \textbf{Avg. Deal} & \textbf{CAC} \\
+Disclosure & Detail \\
\midrule
-Large Enterprise & \$X.XX B & XX\% & \$XXX K & \$XX K \\
-\rowcolor{tablealt} Mid-Market & \$X.XX B & XX\% & \$XX K & \$X K \\
-SMB & \$X.XX B & XX\% & \$X K & \$X K \\
-\rowcolor{tablealt} Consumer & \$X.XX B & XX\% & \$XXX & \$XX \\
+\endhead
+Sponsor and fieldwork organization & [Names] \\
+Target population and sampling frame & [Definition] \\
+Probability or non-probability sample & [Method] \\
+Recruitment and mode & [Method, languages, dates] \\
+Unweighted sample and subgroups & [Counts] \\
+Weighting and design effect & [Variables, benchmarks, effect] \\
+Response or participation & [Definition and rate, if available] \\
+Question wording & [Instrument location] \\
+Precision & [Appropriate measure and assumptions] \\
+Limitations & [Coverage, nonresponse, measurement, model error] \\
\bottomrule
-\end{tabular}
-\label{tab:customer_segments}
-\end{table}
-
-\subsection{Segment A: [Large Enterprise]}
-[Detailed segment analysis including:
-- Segment characteristics
-- Buying behavior
-- Key needs and pain points
-- Decision-making process
-- Willingness to pay]
-
-\subsection{Segment B: [Mid-Market]}
-[Detailed segment analysis]
-
-\subsection{Segment C: [SMB]}
-[Detailed segment analysis]
-
-\subsection{Segment D: [Other]}
-[Detailed segment analysis]
-
-\section{Segment Attractiveness}
-
-% VISUAL: Segment attractiveness matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "2x2 segment attractiveness matrix. X-axis: Segment Size (Small to Large). Y-axis: Growth Rate (Low to High). Plot customer segments as circles. Upper-right: 'Priority', Upper-left: 'Invest to Grow', Lower-right: 'Harvest', Lower-left: 'Deprioritize'. Include segment labels" -o figures/segment_attractiveness.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/segment_attractiveness.png}
-\caption{Customer Segment Attractiveness Matrix}
-\label{fig:segment_attractiveness}
-\end{figure}
-
-[Analyze which segments are most attractive for investment and focus]
-
-\section{Customer Needs Analysis}
-
-[Identify and prioritize customer needs by segment:
-- Functional needs
-- Emotional needs
-- Social needs
-- Pain points
-- Unmet needs]
-
-\section{Buying Behavior}
-
-[Analyze how customers buy in this market:
-- Purchase triggers
-- Decision-making process
-- Key influencers
-- Evaluation criteria
-- Purchase channels]
-
-% VISUAL: Customer journey
-% python skills/scientific-schematics/scripts/generate_schematic.py "Customer journey diagram showing 5 stages: Awareness → Consideration → Decision → Implementation → Advocacy. Each stage shows key activities, pain points, and touchpoints. Use horizontal flow with icons for each stage" -o figures/customer_journey.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/customer_journey.png}
-\caption{Customer Journey Map}
-\label{fig:customer_journey}
-\end{figure}
-
-% ============================================================================
-% CHAPTER 6: TECHNOLOGY & INNOVATION LANDSCAPE (4-5 pages)
-% ============================================================================
-\chapter{Technology \& Innovation Landscape}
-
-\section{Current Technology Stack}
-
-[Describe the technology infrastructure and stack commonly used in the market]
-
-\section{Technology Roadmap}
-
-% VISUAL: Technology roadmap
-% python skills/scientific-schematics/scripts/generate_schematic.py "Technology roadmap timeline from 2024 to 2030. Show 3 parallel tracks: Core Technology (blue), Emerging Technology (green), and Enabling Technology (orange). Mark key milestones and technology introductions on each track. Use horizontal timeline format" -o figures/technology_roadmap.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/technology_roadmap.png}
-\caption{Technology Evolution Roadmap (2024-2030)}
-\label{fig:tech_roadmap}
-\end{figure}
-
-[Describe how technology is expected to evolve:
-- Near-term (1-2 years)
-- Medium-term (3-5 years)
-- Long-term (5-10 years)]
-
-\section{Emerging Technologies}
-
-[Analyze emerging technologies that could impact the market:
-- Technology description
-- Current maturity level
-- Expected timeline to mainstream adoption
-- Potential impact on market]
-
-\subsection{Technology 1: [Name]}
-[Detailed analysis]
-
-\subsection{Technology 2: [Name]}
-[Detailed analysis]
-
-\subsection{Technology 3: [Name]}
-[Detailed analysis]
-
-\section{Innovation Trends}
-
-% VISUAL: Innovation matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "Innovation adoption curve or hype cycle diagram showing where key technologies sit. From left to right: Innovation Trigger, Peak of Inflated Expectations, Trough of Disillusionment, Slope of Enlightenment, Plateau of Productivity. Plot 6-8 technologies at different points" -o figures/innovation_curve.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/innovation_curve.png}
-\caption{Technology Adoption Curve / Hype Cycle}
-\label{fig:innovation}
-\end{figure}
-
-[Analyze innovation trends and R\&D activity:
-- R\&D investment levels
-- Patent filing trends
-- Startup activity
-- Corporate innovation initiatives]
-
-\section{Technology Adoption Barriers}
-
-[Identify barriers to technology adoption:
-- Technical complexity
-- Integration challenges
-- Cost barriers
-- Skills gaps
-- Security/privacy concerns]
-
-% ============================================================================
-% CHAPTER 7: REGULATORY & POLICY ENVIRONMENT (3-4 pages)
-% ============================================================================
-\chapter{Regulatory \& Policy Environment}
-
-\section{Current Regulatory Framework}
+\end{longtable}
-[Describe the current regulatory landscape:
-- Key regulations
-- Regulatory bodies
-- Compliance requirements
-- Enforcement mechanisms]
+\section{Interview Evidence}
+[Describe recruitment, consent, dates, roles represented, analysis/coding
+method, saturation limitations, and privacy controls. Present themes as
+qualitative evidence; do not attach population prevalence to them.]
-\section{Regulatory Timeline}
-
-% VISUAL: Regulatory timeline
-% python skills/scientific-schematics/scripts/generate_schematic.py "Regulatory timeline from 2020 to 2028. Show key regulatory milestones as markers on horizontal timeline. Past events in dark blue, future/upcoming in light blue. Include regulation names and effective dates. Mark current date with vertical line" -o figures/regulatory_timeline.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/regulatory_timeline.png}
-\caption{Regulatory Development Timeline}
-\label{fig:regulatory_timeline}
-\end{figure}
-
-[Chronological analysis of regulatory developments]
-
-\section{Regulatory Impact Analysis}
-
-[Analyze how regulations impact the market:
-- Compliance costs
-- Market access implications
-- Competitive implications
-- Product/service requirements]
-
-\section{Policy Trends}
-
-[Identify policy trends that could affect the market:
-- Government priorities
-- Funding initiatives
-- Trade policies
-- Environmental policies]
-
-\section{Regional Regulatory Differences}
-
-[Compare regulatory environments across regions:
-- North America
-- Europe
-- Asia-Pacific
-- Other regions]
+\chapter{Competitive Landscape}
-% ============================================================================
-% CHAPTER 8: RISK ANALYSIS (3-4 pages)
-% ============================================================================
-\chapter{Risk Analysis}
+\section{Relevant Product and Geographic Scope}
+[Explain substitutability, customer perspective, non-price competition,
+channels, geography, dynamic change, and alternate plausible definitions.
+Descriptive market research does not determine a legal antitrust market.]
-\section{Risk Overview}
+\section{Competitor-Feature Matrix}
+[Insert the validated, evidence-linked matrix. Use ``unknown'' when public
+evidence is absent. Keep product edition, geography, and as-of date constant.]
-[Provide overview of key risks facing market participants]
+\section{Shares and Concentration}
+[State the share metric and denominator: revenue, units, capacity, active
+users, or another defensible measure. Explain residual/unknown participants and
+source coverage. If HHI is shown, state the exact market definition and avoid
+turning screening indicators into legal conclusions.]
-\section{Risk Assessment}
+\section{Competitive Dynamics}
+[Separate observed actions from interpretation. Cite filings, regulator
+records, official registries, or attributable public company material.]
-% VISUAL: Risk heatmap
-% python skills/scientific-schematics/scripts/generate_schematic.py "Risk heatmap matrix. X-axis: Impact (Low to Critical). Y-axis: Probability (Unlikely to Very Likely). Plot 10-12 risks as labeled circles. Color code: Green (low risk), Yellow (medium), Orange (high), Red (critical). Include risk labels" -o figures/risk_heatmap.png --doc-type report
+\chapter{Forecast Scenarios}
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/risk_heatmap.png}
-\caption{Risk Assessment Heatmap}
-\label{fig:risk_heatmap}
-\end{figure}
+\section{Historical Series and Revisions}
+[State source series, frequency, seasonal adjustment, vintage/retrieval date,
+revisions, transformations, and any taxonomy or methodology breaks.]
-\begin{table}[htbp]
-\centering
-\caption{Risk Register Summary}
-\begin{tabular}{@{}llccl@{}}
+\section{Scenario Definitions}
+\begin{longtable}{@{}p{0.18\textwidth}p{0.34\textwidth}p{0.38\textwidth}@{}}
\toprule
-\textbf{Risk} & \textbf{Category} & \textbf{Probability} & \textbf{Impact} & \textbf{Rating} \\
+Scenario & Rate path or drivers & Assumptions and evidence \\
\midrule
-Risk 1 & Market & High & High & \riskhigh{} \\
-\rowcolor{tablealt} Risk 2 & Regulatory & Medium & High & \riskhigh{} \\
-Risk 3 & Technology & Medium & Medium & \riskmedium{} \\
-\rowcolor{tablealt} Risk 4 & Competitive & High & Medium & \riskmedium{} \\
-Risk 5 & Operational & Low & High & \riskmedium{} \\
-\rowcolor{tablealt} Risk 6 & Financial & Low & Medium & \risklow{} \\
+\endhead
+Downside & [Path] & [Assumption and source IDs] \\
+Base & [Path] & [Assumption and source IDs] \\
+Upside & [Path] & [Assumption and source IDs] \\
\bottomrule
-\end{tabular}
-\label{tab:risk_register}
-\end{table}
-
-\subsection{Market Risks}
-[Detailed analysis of market-related risks]
-
-\subsection{Competitive Risks}
-[Detailed analysis of competitive risks]
-
-\subsection{Regulatory Risks}
-[Detailed analysis of regulatory risks]
-
-\subsection{Technology Risks}
-[Detailed analysis of technology risks]
-
-\subsection{Operational Risks}
-[Detailed analysis of operational risks]
-
-\subsection{Financial Risks}
-[Detailed analysis of financial risks]
-
-\section{Risk Mitigation Strategies}
+\end{longtable}
-% VISUAL: Risk mitigation matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "Risk mitigation matrix showing risks in left column and corresponding mitigation strategies in right column. Connect risks to mitigations with arrows. Color code by risk severity. Include both prevention and response strategies" -o figures/risk_mitigation.png --doc-type report
+\section{Range and Sensitivity}
+[Report the conditional range by year, endpoint sensitivity, breakpoints, and
+which input dominates. Do not assign scenario probabilities without a
+validated probabilistic basis.]
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/risk_mitigation.png}
-\caption{Risk Mitigation Framework}
-\label{fig:risk_mitigation}
-\end{figure}
+\chapter{Regulation, Risks, and Uncertainty}
-[Describe strategies to mitigate identified risks]
+\section{Regulatory Record}
+[Distinguish enacted, effective, proposed, consulted, stayed, and repealed
+rules. Record jurisdiction, authority, publication date, effective date, and
+primary legal source.]
-\begin{riskbox}[Risk Mitigation Summary]
-\begin{enumerate}
- \item \textbf{[Risk 1]:} [Mitigation strategy]
- \item \textbf{[Risk 2]:} [Mitigation strategy]
- \item \textbf{[Risk 3]:} [Mitigation strategy]
- \item \textbf{[Risk 4]:} [Mitigation strategy]
-\end{enumerate}
-\end{riskbox}
+\section{Risk Register}
+[For each risk, separate evidence, likelihood judgment, impact mechanism,
+early indicators, and mitigation. Avoid false numerical precision.]
-% ============================================================================
-% CHAPTER 9: STRATEGIC OPPORTUNITIES & RECOMMENDATIONS (4-5 pages)
-% ============================================================================
-\chapter{Strategic Opportunities \& Recommendations}
+\chapter{Implications and Options}
-\section{Opportunity Analysis}
+\section{Implications}
+[Link each implication to findings and state what would disconfirm it.]
-% VISUAL: Opportunity matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "2x2 opportunity matrix. X-axis: Market Attractiveness (Low to High). Y-axis: Ability to Win (Low to High). Plot 6-8 opportunities as labeled circles of varying sizes. Upper-right: 'Pursue Aggressively', Upper-left: 'Selective Investment', Lower-right: 'Build Capabilities', Lower-left: 'Avoid'" -o figures/opportunity_matrix.png --doc-type report
+\section{Options}
+[Compare options against explicit objectives, dependencies, costs, risks, and
+decision thresholds.]
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/opportunity_matrix.png}
-\caption{Strategic Opportunity Assessment Matrix}
-\label{fig:opportunity_matrix}
-\end{figure}
-
-[Identify and analyze strategic opportunities in the market]
-
-\subsection{Opportunity 1: [Name]}
-\begin{opportunitybox}[Opportunity: [Name]]
-\textbf{Description:} [Brief description]
-
-\textbf{Market Size:} \marketsize{X.X billion}
-
-\textbf{Growth Rate:} \growthrate{XX.X}
-
-\textbf{Strategic Fit:} \rating{4}
-
-\textbf{Investment Required:} \$XX million
-\end{opportunitybox}
-
-[Detailed analysis of the opportunity]
-
-\subsection{Opportunity 2: [Name]}
-[Detailed analysis]
-
-\subsection{Opportunity 3: [Name]}
-[Detailed analysis]
-
-\section{Strategic Options Analysis}
-
-[Analyze different strategic approaches:
-- Build (organic development)
-- Buy (M\&A)
-- Partner (strategic alliances)
-- Ignore (not pursue)]
-
-\section{Prioritized Recommendations}
-
-% VISUAL: Recommendation priority matrix
-% python skills/scientific-schematics/scripts/generate_schematic.py "Priority matrix showing recommendations. X-axis: Effort/Investment (Low to High). Y-axis: Impact/Value (Low to High). Plot 6-8 recommendations. Upper-left: 'Quick Wins', Upper-right: 'Major Projects', Lower-left: 'Fill-ins', Lower-right: 'Thankless Tasks'. Label each recommendation" -o figures/recommendation_priority.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/recommendation_priority.png}
-\caption{Recommendation Priority Framework}
-\label{fig:recommendations}
-\end{figure}
-
-\begin{recommendationbox}[Strategic Recommendations]
-\textbf{Tier 1: Immediate Priority}
-\begin{enumerate}
- \item \textbf{[Recommendation 1]:} [Detailed action with expected outcome, timeline, and investment]
- \item \textbf{[Recommendation 2]:} [Detailed action]
-\end{enumerate}
-
-\textbf{Tier 2: Near-Term (6-12 months)}
-\begin{enumerate}[start=3]
- \item \textbf{[Recommendation 3]:} [Detailed action]
- \item \textbf{[Recommendation 4]:} [Detailed action]
-\end{enumerate}
-
-\textbf{Tier 3: Medium-Term (1-2 years)}
-\begin{enumerate}[start=5]
- \item \textbf{[Recommendation 5]:} [Detailed action]
- \item \textbf{[Recommendation 6]:} [Detailed action]
-\end{enumerate}
+\begin{recommendationbox}[Recommendations]
+[State recommendations as judgments, not sourced facts. Include dependencies,
+owners, timing, and evidence that would trigger reconsideration.]
\end{recommendationbox}
-\section{Success Factors}
-
-[Identify critical success factors for implementing recommendations:
-- Organizational capabilities
-- Resource requirements
-- Timing considerations
-- External dependencies]
-
-% ============================================================================
-% CHAPTER 10: IMPLEMENTATION ROADMAP (3-4 pages)
-% ============================================================================
-\chapter{Implementation Roadmap}
+\chapter{Limitations}
+[Consolidate evidence gaps, source conflicts, potential double counting,
+currency/base-year conversions, revision exposure, survey error, interview
+limits, competitive-intelligence limits, and forecast/model uncertainty.]
-\section{Implementation Overview}
-
-[Provide overview of implementation approach and timeline]
-
-\section{Phased Implementation Plan}
-
-% VISUAL: Implementation timeline
-% python skills/scientific-schematics/scripts/generate_schematic.py "Gantt chart style implementation timeline showing 4 phases over 24 months. Phase 1: Foundation (months 1-6), Phase 2: Build (months 4-12), Phase 3: Scale (months 10-18), Phase 4: Optimize (months 16-24). Show overlapping phases with key milestones marked. Use different colors for each phase" -o figures/implementation_timeline.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/implementation_timeline.png}
-\caption{Implementation Roadmap Timeline}
-\label{fig:implementation}
-\end{figure}
-
-\subsection{Phase 1: Foundation (Months 1-6)}
-[Detailed activities and deliverables for Phase 1]
-
-\subsection{Phase 2: Build (Months 4-12)}
-[Detailed activities and deliverables for Phase 2]
-
-\subsection{Phase 3: Scale (Months 10-18)}
-[Detailed activities and deliverables for Phase 3]
-
-\subsection{Phase 4: Optimize (Months 16-24)}
-[Detailed activities and deliverables for Phase 4]
-
-\section{Key Milestones}
-
-% VISUAL: Milestone tracker
-% python skills/scientific-schematics/scripts/generate_schematic.py "Milestone tracker showing 8-10 key milestones on a horizontal timeline. Each milestone has a date, name, and status indicator (completed=green checkmark, in-progress=yellow circle, upcoming=gray circle). Group by phase" -o figures/milestone_tracker.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=\textwidth]{../figures/milestone_tracker.png}
-\caption{Key Implementation Milestones}
-\label{fig:milestones}
-\end{figure}
-
-\begin{table}[htbp]
-\centering
-\caption{Implementation Milestones}
-\begin{tabular}{@{}llll@{}}
-\toprule
-\textbf{Milestone} & \textbf{Target Date} & \textbf{Owner} & \textbf{Success Criteria} \\
-\midrule
-Milestone 1 & Month 3 & [Owner] & [Criteria] \\
-\rowcolor{tablealt} Milestone 2 & Month 6 & [Owner] & [Criteria] \\
-Milestone 3 & Month 9 & [Owner] & [Criteria] \\
-\rowcolor{tablealt} Milestone 4 & Month 12 & [Owner] & [Criteria] \\
-Milestone 5 & Month 18 & [Owner] & [Criteria] \\
-\rowcolor{tablealt} Milestone 6 & Month 24 & [Owner] & [Criteria] \\
-\bottomrule
-\end{tabular}
-\label{tab:milestones}
-\end{table}
-
-\section{Resource Requirements}
-
-[Detail resource requirements for implementation:
-- Team structure
-- Budget allocation
-- Technology requirements
-- External support needs]
-
-\section{Governance Structure}
-
-[Define governance for implementation:
-- Decision-making authority
-- Reporting structure
-- Review cadence
-- Escalation paths]
-
-% ============================================================================
-% CHAPTER 11: INVESTMENT THESIS & FINANCIAL PROJECTIONS (3-4 pages)
-% ============================================================================
-\chapter{Investment Thesis \& Financial Projections}
-
-\section{Investment Summary}
-
-[Summarize the investment opportunity:
-- Key value drivers
-- Expected returns
-- Investment timeline
-- Risk-adjusted assessment]
-
-\begin{executivesummarybox}[Investment Thesis]
-The \reporttitle{} market presents a compelling investment opportunity characterized by:
-
-\begin{itemize}
- \item \textbf{Large Market:} \marketsize{XX billion} TAM growing at \growthrate{XX.X} CAGR
- \item \textbf{Favorable Dynamics:} [Key market dynamics]
- \item \textbf{Strong Drivers:} [Key growth drivers]
- \item \textbf{Manageable Risks:} [Risk summary]
- \item \textbf{Clear Path to Value:} [Value creation summary]
-\end{itemize}
-\end{executivesummarybox}
-
-\section{Financial Projections}
-
-% VISUAL: Financial projections
-% python skills/scientific-schematics/scripts/generate_schematic.py "Financial projections chart showing revenue growth over 5 years. Bar chart for revenue with line overlay for growth rate. Three scenarios: Conservative (gray bars), Base Case (blue bars), Optimistic (green bars). Y-axis dual: Revenue ($M) and Growth (%). Include data labels" -o figures/financial_projections.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.9\textwidth]{../figures/financial_projections.png}
-\caption{Financial Projections (5-Year)}
-\label{fig:financials}
-\end{figure}
-
-\begin{table}[htbp]
-\centering
-\caption{Financial Projections Summary}
-\begin{tabular}{@{}lrrrrr@{}}
-\toprule
-\textbf{Metric} & \textbf{Year 1} & \textbf{Year 2} & \textbf{Year 3} & \textbf{Year 4} & \textbf{Year 5} \\
-\midrule
-Revenue (\$M) & \$XX & \$XX & \$XX & \$XX & \$XX \\
-\rowcolor{tablealt} Growth Rate & XX\% & XX\% & XX\% & XX\% & XX\% \\
-Gross Margin & XX\% & XX\% & XX\% & XX\% & XX\% \\
-\rowcolor{tablealt} EBITDA (\$M) & \$XX & \$XX & \$XX & \$XX & \$XX \\
-EBITDA Margin & XX\% & XX\% & XX\% & XX\% & XX\% \\
-\bottomrule
-\end{tabular}
-\label{tab:financials}
-\end{table}
-
-\section{Scenario Analysis}
-
-% VISUAL: Scenario comparison
-% python skills/scientific-schematics/scripts/generate_schematic.py "Scenario comparison chart showing 3 scenarios (Conservative, Base, Optimistic) across key metrics. Use grouped bar chart with metrics on X-axis (Revenue Y5, EBITDA Y5, Market Share, ROI) and values on Y-axis. Color code by scenario" -o figures/scenario_analysis.png --doc-type report
-
-\begin{figure}[htbp]
-\centering
-% \includegraphics[width=0.85\textwidth]{../figures/scenario_analysis.png}
-\caption{Scenario Analysis Comparison}
-\label{fig:scenarios}
-\end{figure}
-
-\subsection{Conservative Scenario}
-[Detailed assumptions and outcomes for conservative case]
-
-\subsection{Base Case Scenario}
-[Detailed assumptions and outcomes for base case]
-
-\subsection{Optimistic Scenario}
-[Detailed assumptions and outcomes for optimistic case]
-
-\section{Key Assumptions}
-
-[Document key assumptions underlying financial projections:
-- Market growth assumptions
-- Pricing assumptions
-- Cost assumptions
-- Competitive assumptions
-- Timing assumptions]
-
-\section{Sensitivity Analysis}
-
-[Analyze sensitivity of projections to key variables:
-- Revenue sensitivity to market growth
-- Margin sensitivity to pricing
-- Returns sensitivity to timing]
-
-\section{Return Expectations}
-
-[Summarize expected returns:
-- ROI projections
-- Payback period
-- IRR estimates
-- Multiple analysis]
-
-% ============================================================================
-% APPENDICES
-% ============================================================================
\appendix
-% ============================================================================
-% APPENDIX A: METHODOLOGY & DATA SOURCES
-% ============================================================================
-\chapter{Methodology \& Data Sources}
-
-\section{Research Methodology}
-
-[Describe the research methodology used:
-- Primary research methods
-- Secondary research sources
-- Data collection timeframe
-- Analytical frameworks applied]
-
-\section{Data Sources}
-
-[List all data sources used in the report:
-- Market research reports
-- Industry databases
-- Government statistics
-- Company reports
-- Expert interviews
-- Academic publications]
-
-\section{Limitations}
-
-[Acknowledge limitations of the analysis:
-- Data availability constraints
-- Methodological limitations
-- Forecast uncertainty
-- Scope limitations]
-
-% ============================================================================
-% APPENDIX B: DETAILED MARKET DATA
-% ============================================================================
-\chapter{Detailed Market Data}
-
-\section{Historical Market Data}
-
-[Provide detailed historical market data tables]
-
-\section{Regional Data Breakdown}
-
-[Provide detailed regional market data]
-
-\section{Segment Data Details}
-
-[Provide detailed segment-level data]
-
-\section{Competitive Data}
-
-[Provide detailed competitive data tables]
-
-% ============================================================================
-% APPENDIX C: COMPANY PROFILES
-% ============================================================================
-\chapter{Company Profiles}
-
-\section{Company A}
-
-\begin{calloutbox}[Company Profile: Company A]
-\textbf{Headquarters:} [Location]
-
-\textbf{Revenue:} \$X.X billion (FY2024)
-
-\textbf{Employees:} X,XXX
-
-\textbf{Market Position:} [Position description]
-
-\textbf{Key Products/Services:} [List]
-
-\textbf{Recent Developments:} [Summary]
-\end{calloutbox}
-
-[Brief narrative description of company strategy and positioning]
-
-\section{Company B}
-[Company profile]
-
-\section{Company C}
-[Company profile]
-
-\section{Company D}
-[Company profile]
+\chapter{Evidence Ledger}
+[Render the complete source ledger: source ID, title, publisher, URL or
+persistent identifier, publication and retrieval dates, geography, unit,
+currency/base, taxonomy, revision status, method/sample, limitations, terms,
+and archive path.]
-\section{Company E}
-[Company profile]
+\chapter{Claims Ledger}
+[Render claim ID, exact claim text, statement type, source IDs, calculation and
+assumption IDs, report location, scope metadata, revision status, and
+confidence label.]
-% ============================================================================
-% REFERENCES
-% ============================================================================
-\newpage
-\bibliographystyle{plainnat}
-\bibliography{../references/references}
+\chapter{Calculations and Assumptions}
+[Include formulas, raw inputs, conversions, coverage keys, denominator IDs,
+scenario paths, sensitivity values, and reconciliation.]
-% Alternative: Manual bibliography if not using BibTeX
-% \begin{thebibliography}{99}
-%
-% \bibitem{source1}
-% Author1, A.B. (2024).
-% Title of report or article.
-% \textit{Publisher/Source}.
-% URL
-%
-% \bibitem{source2}
-% [Continue with all references...]
-%
-% \end{thebibliography}
+\chapter{Research Ethics and Data Handling}
+[Document consent, privacy notices, retention, access controls,
+de-identification, lawful public-source collection, and deletion schedule.
+Confirm that no deceptive collection, PII disclosure, or trade-secret
+acquisition was used.]
-% ============================================================================
-% END OF DOCUMENT
-% ============================================================================
\end{document}
diff --git a/skills/market-research-reports/assets/market_research.sty b/skills/market-research-reports/assets/market_research.sty
index d383941e..2431793e 100644
--- a/skills/market-research-reports/assets/market_research.sty
+++ b/skills/market-research-reports/assets/market_research.sty
@@ -1,564 +1,241 @@
-% market_research.sty - Professional Market Research Report Styling
-% For use with XeLaTeX or LuaLaTeX
-% Style inspired by top consulting firms (McKinsey, BCG, Gartner)
+% market_research.sty - evidence-first market report styling
+% Intended for XeLaTeX or LuaLaTeX; no external images are required.
+\NeedsTeXFormat{LaTeX2e}
+\ProvidesPackage{market_research}[2026/07/23 v1.1 Evidence-first market reports]
-\ProvidesPackage{market_research}[2024/01/01 Market Research Report Style]
-
-% ============================================================================
-% REQUIRED PACKAGES
-% ============================================================================
-
-% Page layout and geometry
\RequirePackage[margin=1in]{geometry}
\RequirePackage{setspace}
-
-% Typography
-\RequirePackage[utf8]{inputenc}
-\RequirePackage[T1]{fontenc}
\RequirePackage{helvet}
-\renewcommand{\familydefault}{\sfdefault}
-
-% Colors and graphics
-\RequirePackage{xcolor}
+\RequirePackage[table]{xcolor}
\RequirePackage{graphicx}
-\RequirePackage{tikz}
-
-% Tables
-\RequirePackage{longtable}
\RequirePackage{booktabs}
-\RequirePackage{multirow}
+\RequirePackage{longtable}
\RequirePackage{array}
-\RequirePackage{colortbl}
-
-% Lists and formatting
\RequirePackage{enumitem}
\RequirePackage{parskip}
-
-% Boxes and callouts
\RequirePackage[most]{tcolorbox}
-
-% Headers and footers
\RequirePackage{fancyhdr}
\RequirePackage{titlesec}
-
-% Hyperlinks and references
\RequirePackage{hyperref}
-\RequirePackage[numbers,sort&compress]{natbib}
-
-% Math (for financial projections)
-\RequirePackage{amsmath}
-
-% Captions
\RequirePackage{caption}
-\RequirePackage{subcaption}
-
-% ============================================================================
-% COLOR DEFINITIONS
-% ============================================================================
-
-% Primary colors (professional blue palette)
-\definecolor{primaryblue}{RGB}{0, 51, 102} % Deep navy blue
-\definecolor{secondaryblue}{RGB}{51, 102, 153} % Medium blue
-\definecolor{lightblue}{RGB}{173, 216, 230} % Light blue for backgrounds
-\definecolor{accentblue}{RGB}{0, 120, 215} % Bright accent blue
-
-% Secondary colors (complementary)
-\definecolor{accentgreen}{RGB}{0, 128, 96} % Teal green
-\definecolor{lightgreen}{RGB}{200, 230, 201} % Light green background
-\definecolor{darkgreen}{RGB}{27, 94, 32} % Dark green
-
-% Warning and risk colors
-\definecolor{warningorange}{RGB}{255, 140, 0} % Orange for warnings
-\definecolor{lightorange}{RGB}{255, 243, 224} % Light orange background
-\definecolor{alertred}{RGB}{198, 40, 40} % Red for critical items
-\definecolor{lightred}{RGB}{255, 235, 238} % Light red background
-
-% Recommendation and action colors
-\definecolor{recommendpurple}{RGB}{103, 58, 183} % Purple for recommendations
-\definecolor{lightpurple}{RGB}{237, 231, 246} % Light purple background
-
-% Neutral colors
-\definecolor{darkgray}{RGB}{66, 66, 66} % Dark gray for text
-\definecolor{mediumgray}{RGB}{117, 117, 117} % Medium gray
-\definecolor{lightgray}{RGB}{240, 240, 240} % Light gray backgrounds
-\definecolor{tablegray}{RGB}{250, 250, 250} % Table row alternating
-\definecolor{tablealt}{RGB}{245, 247, 250} % Alternating table row
-
-% Chart colors (colorblind-friendly palette)
-\definecolor{chart1}{RGB}{0, 114, 178} % Blue
-\definecolor{chart2}{RGB}{230, 159, 0} % Orange
-\definecolor{chart3}{RGB}{0, 158, 115} % Green
-\definecolor{chart4}{RGB}{204, 121, 167} % Pink
-\definecolor{chart5}{RGB}{86, 180, 233} % Sky blue
-\definecolor{chart6}{RGB}{213, 94, 0} % Vermillion
-\definecolor{chart7}{RGB}{240, 228, 66} % Yellow
+\RequirePackage{amsmath}
-% ============================================================================
-% HYPERLINK CONFIGURATION
-% ============================================================================
+\renewcommand{\familydefault}{\sfdefault}
+\setstretch{1.12}
+\setlength{\parskip}{0.45em}
+
+% Colorblind-aware structural palette.
+\definecolor{mrnavy}{RGB}{0,68,100}
+\definecolor{mrblue}{RGB}{0,114,178}
+\definecolor{mrteal}{RGB}{0,128,115}
+\definecolor{mramber}{RGB}{230,159,0}
+\definecolor{mrred}{RGB}{180,52,38}
+\definecolor{mrpurple}{RGB}{97,73,149}
+\definecolor{mrdark}{RGB}{55,55,55}
+\definecolor{mrgray}{RGB}{115,115,115}
+\definecolor{mrlight}{RGB}{245,247,249}
+\definecolor{mrtable}{RGB}{241,245,247}
\hypersetup{
- colorlinks=true,
- linkcolor=primaryblue,
- filecolor=primaryblue,
- urlcolor=accentblue,
- citecolor=secondaryblue,
- pdftitle={Market Research Report},
- pdfauthor={Market Intelligence},
- pdfsubject={Market Analysis},
+ colorlinks=true,
+ linkcolor=mrnavy,
+ urlcolor=mrblue,
+ citecolor=mrteal,
+ pdftitle={Market Research Report},
+ pdfsubject={Evidence-first market analysis}
}
-% ============================================================================
-% CHAPTER AND SECTION FORMATTING
-% ============================================================================
-
-% Chapter formatting - large number with colored title
\titleformat{\chapter}[display]
-{\normalfont\huge\bfseries\color{primaryblue}}
-{\chaptertitlename\ \thechapter}{20pt}{\Huge}
-\titlespacing*{\chapter}{0pt}{-20pt}{40pt}
-
-% Section formatting
+ {\normalfont\huge\bfseries\color{mrnavy}}
+ {\chaptertitlename\ \thechapter}{16pt}{\Huge}
+\titlespacing*{\chapter}{0pt}{-18pt}{32pt}
\titleformat{\section}
-{\normalfont\Large\bfseries\color{primaryblue}}
-{\thesection}{1em}{}
-\titlespacing*{\section}{0pt}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}
-
-% Subsection formatting
+ {\normalfont\Large\bfseries\color{mrnavy}}{\thesection}{0.8em}{}
\titleformat{\subsection}
-{\normalfont\large\bfseries\color{secondaryblue}}
-{\thesubsection}{1em}{}
-
-% Subsubsection formatting
+ {\normalfont\large\bfseries\color{mrblue}}{\thesubsection}{0.8em}{}
\titleformat{\subsubsection}
-{\normalfont\normalsize\bfseries\color{darkgray}}
-{\thesubsubsection}{1em}{}
-
-% Paragraph formatting
-\titleformat{\paragraph}[runin]
-{\normalfont\normalsize\bfseries\color{darkgray}}
-{\theparagraph}{1em}{}
-
-% ============================================================================
-% HEADER AND FOOTER CONFIGURATION
-% ============================================================================
+ {\normalfont\normalsize\bfseries\color{mrdark}}{\thesubsubsection}{0.8em}{}
\pagestyle{fancy}
\fancyhf{}
-\fancyhead[L]{\small\textit{\leftmark}}
-\fancyhead[R]{\small\textit{Market Research Report}}
+\fancyhead[L]{\small\leftmark}
+\fancyhead[R]{\small Evidence-first market report}
\fancyfoot[C]{\thepage}
\renewcommand{\headrulewidth}{0.4pt}
-\renewcommand{\footrulewidth}{0.4pt}
-\renewcommand{\headrule}{\hbox to\headwidth{\color{primaryblue}\leaders\hrule height \headrulewidth\hfill}}
-\renewcommand{\footrule}{\hbox to\headwidth{\color{lightgray}\leaders\hrule height \footrulewidth\hfill}}
-
-% Plain page style for chapter pages
-\fancypagestyle{plain}{
- \fancyhf{}
- \fancyfoot[C]{\thepage}
- \renewcommand{\headrulewidth}{0pt}
- \renewcommand{\footrulewidth}{0.4pt}
-}
-
-% ============================================================================
-% BOX ENVIRONMENTS
-% ============================================================================
-
-% Key Insight Box (Blue) - For major findings and insights
-\newtcolorbox{keyinsightbox}[1][Key Insight]{
- colback=lightblue!30,
- colframe=primaryblue,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=primaryblue,
- boxrule=1pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
-
-% Market Data Box (Green) - For market statistics and data highlights
-\newtcolorbox{marketdatabox}[1][Market Data]{
- colback=lightgreen!50,
- colframe=accentgreen,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=accentgreen,
- boxrule=1pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
-
-% Risk Box (Orange/Warning) - For risk factors and warnings
-\newtcolorbox{riskbox}[1][Risk Factor]{
- colback=lightorange,
- colframe=warningorange,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=warningorange,
- boxrule=1pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
-
-% Critical Risk Box (Red) - For critical/high-severity risks
-\newtcolorbox{criticalriskbox}[1][Critical Risk]{
- colback=lightred,
- colframe=alertred,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=alertred,
- boxrule=1pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
-
-% Recommendation Box (Purple) - For strategic recommendations
-\newtcolorbox{recommendationbox}[1][Strategic Recommendation]{
- colback=lightpurple,
- colframe=recommendpurple,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=recommendpurple,
- boxrule=1pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
-
-% Callout Box (Gray) - For definitions, notes, supplementary info
-\newtcolorbox{calloutbox}[1][Note]{
- colback=lightgray,
- colframe=mediumgray,
- fonttitle=\bfseries\color{darkgray},
- title=#1,
- coltitle=darkgray,
- colbacktitle=lightgray,
- boxrule=0.5pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
+\renewcommand{\footrulewidth}{0pt}
-% Executive Summary Box (Special styling)
-\newtcolorbox{executivesummarybox}[1][Executive Summary]{
- enhanced,
- colback=white,
- colframe=primaryblue,
- fonttitle=\Large\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=primaryblue,
- boxrule=2pt,
- arc=5pt,
- left=15pt,
- right=15pt,
- top=12pt,
- bottom=12pt,
- before skip=15pt,
- after skip=15pt,
- shadow={2mm}{-2mm}{0mm}{black!20},
-}
-
-% Opportunity Box (Teal) - For opportunities and positive findings
-\newtcolorbox{opportunitybox}[1][Opportunity]{
- colback=lightblue!20,
- colframe=accentblue,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=accentblue,
- boxrule=1pt,
- arc=3pt,
- left=10pt,
- right=10pt,
- top=8pt,
- bottom=8pt,
- before skip=12pt,
- after skip=12pt,
-}
-
-% ============================================================================
-% PULL QUOTE ENVIRONMENT
-% ============================================================================
-
-\newtcolorbox{pullquote}{
- enhanced,
- colback=lightgray,
- colframe=lightgray,
- boxrule=0pt,
- borderline west={4pt}{0pt}{primaryblue},
- arc=0pt,
- left=15pt,
- right=15pt,
- top=10pt,
- bottom=10pt,
- before skip=15pt,
- after skip=15pt,
- fontupper=\large\itshape\color{darkgray},
-}
-
-% ============================================================================
-% STATISTIC HIGHLIGHT
-% ============================================================================
-
-\newcommand{\statbox}[2]{%
- \begin{tcolorbox}[
- colback=primaryblue,
- colframe=primaryblue,
- coltext=white,
- arc=5pt,
- boxrule=0pt,
- width=0.3\textwidth,
- halign=center,
- valign=center,
- before skip=10pt,
- after skip=10pt,
- ]
- {\Huge\bfseries #1}\\[5pt]
- {\small #2}
- \end{tcolorbox}
-}
-
-% ============================================================================
-% TABLE STYLING
-% ============================================================================
-
-% Alternating row colors command
-\newcommand{\tablerowcolor}{\rowcolor{tablealt}}
-
-% Table header styling
-\newcommand{\tableheader}[1]{\textbf{\color{white}#1}}
-\newcommand{\tableheaderrow}{\rowcolor{primaryblue}}
-
-% Professional table environment
-\newenvironment{markettable}[2][htbp]{%
- \begin{table}[#1]
- \centering
- \caption{#2}
- \small
-}{%
- \end{table}
-}
-
-% ============================================================================
-% FIGURE STYLING
-% ============================================================================
-
-% Caption formatting
\captionsetup{
- font=small,
- labelfont={bf,color=primaryblue},
- textfont={color=darkgray},
- justification=centering,
- margin=20pt,
+ font=small,
+ labelfont={bf,color=mrnavy},
+ textfont={color=mrdark},
+ justification=raggedright,
+ singlelinecheck=false
}
-% Figure with source attribution
-\newcommand{\figuresource}[1]{%
- \par\vspace{-8pt}
- {\small\textit{Source: #1}}
-}
-
-% ============================================================================
-% LIST STYLING
-% ============================================================================
-
-% Bullet list styling
\setlist[itemize]{
- leftmargin=*,
- label=\textcolor{primaryblue}{\textbullet},
- topsep=5pt,
- itemsep=3pt,
+ leftmargin=*,
+ label=\textcolor{mrblue}{\textbullet},
+ topsep=4pt,
+ itemsep=2pt
}
-
-% Numbered list styling
\setlist[enumerate]{
- leftmargin=*,
- label=\textcolor{primaryblue}{\arabic*.},
- topsep=5pt,
- itemsep=3pt,
-}
-
-% ============================================================================
-% CUSTOM COMMANDS
-% ============================================================================
-
-% Highlight important text
-\newcommand{\highlight}[1]{\textbf{\textcolor{primaryblue}{#1}}}
-
-% Market size with formatting
-\newcommand{\marketsize}[1]{\textbf{\textcolor{accentgreen}{\$#1}}}
-
-% Growth rate with formatting
-\newcommand{\growthrate}[1]{\textbf{\textcolor{chart3}{#1\%}}}
-
-% Risk indicator
-\newcommand{\riskhigh}{\textbf{\textcolor{alertred}{HIGH}}}
-\newcommand{\riskmedium}{\textbf{\textcolor{warningorange}{MEDIUM}}}
-\newcommand{\risklow}{\textbf{\textcolor{accentgreen}{LOW}}}
-
-% Rating stars (1-5)
-\newcommand{\rating}[1]{%
- \foreach \i in {1,...,5}{%
- \ifnum\i>#1
- \textcolor{lightgray}{$\star$}%
- \else
- \textcolor{warningorange}{$\star$}%
- \fi
- }%
+ leftmargin=*,
+ label=\textcolor{mrblue}{\arabic*.},
+ topsep=4pt,
+ itemsep=2pt
+}
+
+\newtcolorbox{evidencebox}[1][Observed evidence]{
+ enhanced,
+ breakable,
+ colback=mrblue!6,
+ colframe=mrnavy,
+ colbacktitle=mrnavy,
+ coltitle=white,
+ fonttitle=\bfseries,
+ title=#1,
+ boxrule=0.9pt,
+ arc=2pt,
+ left=9pt,right=9pt,top=7pt,bottom=7pt
+}
+
+\newtcolorbox{calculationbox}[1][Calculation]{
+ enhanced,
+ breakable,
+ colback=mrteal!7,
+ colframe=mrteal,
+ colbacktitle=mrteal,
+ coltitle=white,
+ fonttitle=\bfseries,
+ title=#1,
+ boxrule=0.9pt,
+ arc=2pt,
+ left=9pt,right=9pt,top=7pt,bottom=7pt
+}
+
+\newtcolorbox{assumptionbox}[1][Assumptions and uncertainty]{
+ enhanced,
+ breakable,
+ colback=mramber!10,
+ colframe=mramber,
+ colbacktitle=mramber,
+ coltitle=black,
+ fonttitle=\bfseries,
+ title=#1,
+ boxrule=0.9pt,
+ arc=2pt,
+ left=9pt,right=9pt,top=7pt,bottom=7pt
+}
+
+\newtcolorbox{limitationbox}[1][Material limitation]{
+ enhanced,
+ breakable,
+ colback=mrred!6,
+ colframe=mrred,
+ colbacktitle=mrred,
+ coltitle=white,
+ fonttitle=\bfseries,
+ title=#1,
+ boxrule=0.9pt,
+ arc=2pt,
+ left=9pt,right=9pt,top=7pt,bottom=7pt
+}
+
+\newtcolorbox{recommendationbox}[1][Recommendation]{
+ enhanced,
+ breakable,
+ colback=mrpurple!6,
+ colframe=mrpurple,
+ colbacktitle=mrpurple,
+ coltitle=white,
+ fonttitle=\bfseries,
+ title=#1,
+ boxrule=0.9pt,
+ arc=2pt,
+ left=9pt,right=9pt,top=7pt,bottom=7pt
+}
+
+\newtcolorbox{calloutbox}[1][Context]{
+ enhanced,
+ breakable,
+ colback=mrlight,
+ colframe=mrgray,
+ colbacktitle=mrlight,
+ coltitle=mrdark,
+ fonttitle=\bfseries,
+ title=#1,
+ boxrule=0.6pt,
+ arc=2pt,
+ left=9pt,right=9pt,top=7pt,bottom=7pt
+}
+
+% Compatibility aliases for reports created with the earlier style.
+\newenvironment{keyinsightbox}[1][Key insight]
+ {\begin{evidencebox}[#1]}{\end{evidencebox}}
+\newenvironment{marketdatabox}[1][Market data]
+ {\begin{calculationbox}[#1]}{\end{calculationbox}}
+\newenvironment{riskbox}[1][Risk]
+ {\begin{limitationbox}[#1]}{\end{limitationbox}}
+\newenvironment{criticalriskbox}[1][Critical risk]
+ {\begin{limitationbox}[#1]}{\end{limitationbox}}
+\newenvironment{executivesummarybox}[1][Executive synopsis]
+ {\begin{evidencebox}[#1]}{\end{evidencebox}}
+\newenvironment{opportunitybox}[1][Opportunity]
+ {\begin{assumptionbox}[#1]}{\end{assumptionbox}}
+\newenvironment{swotbox}[1][Structured assessment]
+ {\begin{calloutbox}[#1]}{\end{calloutbox}}
+\newenvironment{porterbox}[1][Competitive assessment]
+ {\begin{calloutbox}[#1]}{\end{calloutbox}}
+
+\newcommand{\claimref}[1]{\textcolor{mrnavy}{\texttt{#1}}}
+\newcommand{\sourceref}[1]{\textcolor{mrteal}{\texttt{#1}}}
+\newcommand{\calcref}[1]{\textcolor{mrteal}{\texttt{#1}}}
+\newcommand{\assumptionref}[1]{\textcolor{mramber!70!black}{\texttt{#1}}}
+\newcommand{\metricvalue}[1]{\textbf{\textcolor{mrteal}{#1}}}
+\newcommand{\riskhigh}{\textbf{\textcolor{mrred}{HIGH}}}
+\newcommand{\riskmedium}{\textbf{\textcolor{mramber!70!black}{MEDIUM}}}
+\newcommand{\risklow}{\textbf{\textcolor{mrteal}{LOW}}}
+\newcommand{\tablerowcolor}{\rowcolor{mrtable}}
+\newcommand{\figuresource}[1]{%
+ \par\vspace{-6pt}{\footnotesize\textit{Evidence: #1}}%
}
-% Trend indicators
-\newcommand{\trendup}{\textcolor{accentgreen}{$\blacktriangle$}}
-\newcommand{\trenddown}{\textcolor{alertred}{$\blacktriangledown$}}
-\newcommand{\trendflat}{\textcolor{mediumgray}{$\rightarrow$}}
-
-% ============================================================================
-% TITLE PAGE COMMAND
-% ============================================================================
-
-\newcommand{\makemarketreporttitle}[5]{%
- % #1 = Report Title
- % #2 = Subtitle
- % #3 = Hero Image Path
- % #4 = Date
- % #5 = Prepared By
- \begin{titlepage}
- \centering
- \vspace*{1cm}
-
- {\Huge\bfseries\color{primaryblue} #1\\[0.5cm]}
- {\LARGE\bfseries #2\\[2cm]}
-
- \ifx&#3&
- % No image provided
- \vspace{4cm}
- \else
- \includegraphics[width=\textwidth]{#3}\\[2cm]
- \fi
-
- {\Large\bfseries Market Research Report\\[3cm]}
-
- {\large
- \textbf{Date:} #4\\[0.3cm]
- \textbf{Prepared By:} #5\\[0.3cm]
- \textbf{Classification:} Confidential
- }
-
- \vfill
-
- {\footnotesize
- \textit{This report contains market intelligence and strategic analysis. All data sources are cited and independently verifiable.}
- }
-
- \end{titlepage}
+\newenvironment{markettable}[2][htbp]{%
+ \begin{table}[#1]
+ \centering
+ \caption{#2}
+ \small
+}{%
+ \end{table}
+}
+
+\newcommand{\makemarketreporttitle}[4]{%
+ \begin{titlepage}
+ \centering
+ \vspace*{2cm}
+ {\Huge\bfseries\color{mrnavy}#1\par}
+ \vspace{0.7cm}
+ {\Large #2\par}
+ \vfill
+ {\large\textbf{Retrieval cutoff:} #3\par}
+ \vspace{0.25cm}
+ {\large\textbf{Prepared by:} #4\par}
+ \vfill
+ {\footnotesize Estimates and forecasts are conditional on documented evidence
+ and assumptions. This report is not investment, legal, or financial advice.\par}
+ \end{titlepage}
}
-% ============================================================================
-% APPENDIX SECTION COMMAND
-% ============================================================================
-
\newcommand{\appendixsection}[1]{%
- \section*{#1}
- \addcontentsline{toc}{section}{#1}
-}
-
-% ============================================================================
-% FRAMEWORK BOXES
-% ============================================================================
-
-% SWOT Analysis Box
-\newtcolorbox{swotbox}[1][SWOT Analysis]{
- enhanced,
- colback=white,
- colframe=secondaryblue,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=secondaryblue,
- boxrule=1.5pt,
- arc=5pt,
- left=10pt,
- right=10pt,
- top=10pt,
- bottom=10pt,
- before skip=15pt,
- after skip=15pt,
+ \section*{#1}
+ \addcontentsline{toc}{section}{#1}
}
-% Porter's Five Forces Box
-\newtcolorbox{porterbox}[1][Porter's Five Forces]{
- enhanced,
- colback=white,
- colframe=primaryblue,
- fonttitle=\bfseries\color{white},
- title=#1,
- coltitle=white,
- colbacktitle=primaryblue,
- boxrule=1.5pt,
- arc=5pt,
- left=10pt,
- right=10pt,
- top=10pt,
- bottom=10pt,
- before skip=15pt,
- after skip=15pt,
-}
-
-% ============================================================================
-% PAGE LAYOUT ADJUSTMENTS
-% ============================================================================
-
-% Spacing
-\setstretch{1.15}
-\setlength{\parskip}{0.5em}
-
-% Prevent orphans and widows
\clubpenalty=10000
\widowpenalty=10000
-
-% Float placement
\renewcommand{\topfraction}{0.9}
\renewcommand{\bottomfraction}{0.8}
-\renewcommand{\textfraction}{0.07}
-\renewcommand{\floatpagefraction}{0.7}
-
-% ============================================================================
-% END OF STYLE FILE
-% ============================================================================
+\renewcommand{\textfraction}{0.08}
+\renewcommand{\floatpagefraction}{0.75}
\endinput
diff --git a/skills/market-research-reports/assets/market_sizing_scenarios_template.json b/skills/market-research-reports/assets/market_sizing_scenarios_template.json
new file mode 100644
index 00000000..713f2e1f
--- /dev/null
+++ b/skills/market-research-reports/assets/market_sizing_scenarios_template.json
@@ -0,0 +1,129 @@
+{
+ "schema_version": "1.0",
+ "metadata": {
+ "market_id": "synthetic-widget-services",
+ "market_definition": "Annual end-customer spend on the synthetic service in Exampleland",
+ "geography": "Exampleland",
+ "currency": "USD",
+ "base_year": 2025,
+ "price_basis": "nominal",
+ "unit": "USD per year",
+ "taxonomy": "EXAMPLE-INDUSTRY",
+ "taxonomy_version": "2026",
+ "denominator_id": "annual-end-customer-spend",
+ "as_of_date": "2026-07-23"
+ },
+ "top_down": {
+ "components": [
+ {
+ "component_id": "enterprise-spend",
+ "coverage_key": "enterprise-customers",
+ "denominator_id": "annual-end-customer-spend",
+ "value": 60000000,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumption_ids": [
+ "A-PRICE-001"
+ ]
+ },
+ {
+ "component_id": "small-business-spend",
+ "coverage_key": "small-business-customers",
+ "denominator_id": "annual-end-customer-spend",
+ "value": 40000000,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumption_ids": [
+ "A-PRICE-002"
+ ]
+ }
+ ]
+ },
+ "bottom_up": {
+ "components": [
+ {
+ "component_id": "enterprise-build",
+ "coverage_key": "enterprise-customers",
+ "denominator_id": "annual-end-customer-spend",
+ "customer_count": 1000,
+ "annual_quantity_per_customer": 10,
+ "price_per_unit": 6000,
+ "addressable_fraction": 0.8,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumption_ids": [
+ "A-PRICE-001",
+ "A-ADDRESSABLE-001"
+ ]
+ },
+ {
+ "component_id": "small-business-build",
+ "coverage_key": "small-business-customers",
+ "denominator_id": "annual-end-customer-spend",
+ "customer_count": 10000,
+ "annual_quantity_per_customer": 2,
+ "price_per_unit": 2000,
+ "addressable_fraction": 0.9,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumption_ids": [
+ "A-PRICE-002",
+ "A-ADDRESSABLE-002"
+ ]
+ }
+ ]
+ },
+ "scenarios": [
+ {
+ "scenario_id": "downside",
+ "label": "Downside",
+ "serviceable_fraction": 0.35,
+ "obtainable_share": 0.02,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumptions": [
+ "Narrow channel reach",
+ "Slow customer adoption"
+ ]
+ },
+ {
+ "scenario_id": "base",
+ "label": "Base",
+ "serviceable_fraction": 0.5,
+ "obtainable_share": 0.05,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumptions": [
+ "Planned channel reach",
+ "Observed synthetic adoption benchmark"
+ ]
+ },
+ {
+ "scenario_id": "upside",
+ "label": "Upside",
+ "serviceable_fraction": 0.65,
+ "obtainable_share": 0.08,
+ "source_ids": [
+ "S-001",
+ "S-002"
+ ],
+ "assumptions": [
+ "Broader channel reach",
+ "Faster adoption without denominator expansion"
+ ]
+ }
+ ],
+ "reconciliation_tolerance_percent": 20
+}
diff --git a/skills/market-research-reports/assets/report_manifest_template.json b/skills/market-research-reports/assets/report_manifest_template.json
new file mode 100644
index 00000000..a931d8d5
--- /dev/null
+++ b/skills/market-research-reports/assets/report_manifest_template.json
@@ -0,0 +1,27 @@
+{
+ "schema_version": "1.0",
+ "report_id": "synthetic-widget-services",
+ "title": "Synthetic Widget Services Market",
+ "subtitle": "Evidence-first market assessment and scenario analysis",
+ "prepared_for": "Synthetic Example Organization",
+ "prepared_by": "Research Team",
+ "classification": "internal",
+ "market_definition": "Annual end-customer spend on synthetic widget services in Exampleland",
+ "inclusions": [
+ "Recurring synthetic widget service fees",
+ "Usage-based synthetic widget service fees"
+ ],
+ "exclusions": [
+ "Hardware purchases",
+ "Unrelated professional services"
+ ],
+ "geography": "Exampleland",
+ "currency": "USD",
+ "base_year": 2025,
+ "price_basis": "nominal",
+ "taxonomy": "EXAMPLE-INDUSTRY",
+ "taxonomy_version": "2026",
+ "historical_period": "2021-2025",
+ "forecast_period": "2026-2030",
+ "retrieval_cutoff": "2026-07-23"
+}
diff --git a/skills/market-research-reports/assets/source_ledger_template.csv b/skills/market-research-reports/assets/source_ledger_template.csv
new file mode 100644
index 00000000..efe5d136
--- /dev/null
+++ b/skills/market-research-reports/assets/source_ledger_template.csv
@@ -0,0 +1,4 @@
+source_id,title,publisher,url,source_type,publication_date,retrieval_date,geography,currency,base_year,price_basis,measure_type,unit,taxonomy,taxonomy_version,revision_status,method,sample,limitations,license_or_terms,archive_path
+S-001,Synthetic business-count table,Synthetic Fixture Publisher,https://example.invalid/synthetic/business-counts,other,2026-06-30,2026-07-23,Exampleland,,,not-applicable,count,establishments,EXAMPLE-INDUSTRY,2026,final,Synthetic administrative census,,Fixture only; not real-world evidence,Synthetic fixture; no reuse restriction,sources/S-001.txt
+S-002,Synthetic annual-spend survey,Synthetic Fixture Publisher,https://example.invalid/synthetic/annual-spend,survey,2026-06-15,2026-07-23,Exampleland,USD,2025,nominal,flow,USD per customer per year,EXAMPLE-INDUSTRY,2026,final,Synthetic stratified survey,n=1200; probability sample; weighted,Fixture only; sampling and nonresponse uncertainty,Synthetic fixture; no reuse restriction,sources/S-002.txt
+S-003,Synthetic product comparison,Synthetic Fixture Publisher,https://example.invalid/synthetic/product-comparison,other,2026-07-01,2026-07-23,Exampleland,,,not-applicable,not-applicable,not-applicable,EXAMPLE-PRODUCT,2026,current,Synthetic public-document review,,Fixture only; product availability may change,Synthetic fixture; no reuse restriction,sources/S-003.txt
diff --git a/skills/market-research-reports/references/data_analysis_patterns.md b/skills/market-research-reports/references/data_analysis_patterns.md
index f94863b3..3e66c244 100644
--- a/skills/market-research-reports/references/data_analysis_patterns.md
+++ b/skills/market-research-reports/references/data_analysis_patterns.md
@@ -1,548 +1,290 @@
# Data Analysis Patterns for Market Research
-Templates and frameworks for conducting rigorous market analysis.
+## Measurement contract
----
+Define the quantity before collecting numbers:
-## Market Sizing Frameworks
+- product/service inclusion and exclusion;
+- buyer, user, payer, and transaction type;
+- geography and treatment of imports/exports;
+- historical period, forecast horizon, and as-of date;
+- revenue, expenditure, gross output, value added, units, capacity, users, or
+ another measure;
+- stock versus flow;
+- gross versus net, taxes included/excluded, and channel level;
+- currency, exchange-rate convention, base year, and nominal/real basis;
+- industry and product taxonomy with version;
+- denominator ID used in every share or rate.
-### TAM/SAM/SOM Analysis
+If two estimates do not share this contract, they are not directly comparable.
-**Total Addressable Market (TAM)** represents the total revenue opportunity if 100% market share was achieved.
+## TAM, SAM, and SOM
-#### Top-Down Approach
-```
-TAM = Total Industry Revenue (from market research reports)
+Treat all three as conditional scenario constructs.
-Example:
-- Global AI Software Market (2024): $184 billion
-- Source: Gartner, IDC, or similar
-```
+### Definitions
-#### Bottom-Up Approach
-```
-TAM = Number of Potential Customers × Average Revenue per Customer
+- **TAM**: value or volume of all in-scope demand under the stated market
+ definition and time basis.
+- **SAM**: subset of TAM serviceable under explicit product, geography,
+ regulatory, channel, capacity, and customer constraints.
+- **SOM**: subset of SAM obtainable within a stated time horizon under explicit
+ competitive, operational, sales, retention, and capacity assumptions.
-Example:
-- Number of enterprises globally: 400 million
-- Target segment (large enterprises): 50,000
-- Average annual spend on solution: $500,000
-- TAM = 50,000 × $500,000 = $25 billion
-```
+Never present SOM as a guaranteed share or TAM as an objective universal truth.
-**Serviceable Addressable Market (SAM)** represents the portion of TAM that can be served given product/service capabilities.
+### Top-down method
-```
-SAM = TAM × Applicable Segment %
+Use disjoint components:
-Example:
-- TAM: $25 billion
-- Geographic constraint (North America only): 40%
-- Product fit (enterprise only): 60%
-- SAM = $25B × 40% × 60% = $6 billion
+```text
+TAM_top = sum(value_i * in_scope_fraction_i)
```
-**Serviceable Obtainable Market (SOM)** represents realistic market share capture.
+Each component needs a unique coverage key, source IDs, period, unit, and
+denominator. Do not apply a broad percentage to an unrelated aggregate merely
+because the resulting number looks plausible.
-```
-SOM = SAM × Achievable Market Share %
+### Bottom-up method
-Example:
-- SAM: $6 billion
-- Conservative market share (5%): $300 million
-- Base case market share (10%): $600 million
-- Optimistic market share (15%): $900 million
-```
+For a recurring-use market:
-### Growth Rate Calculation
+```text
+component_i =
+ customer_count_i
+ * addressable_fraction_i
+ * annual_quantity_per_customer_i
+ * price_per_unit_i
-#### CAGR (Compound Annual Growth Rate)
+TAM_bottom = sum(component_i)
```
-CAGR = (End Value / Start Value)^(1/n) - 1
-Where n = number of years
+Alternative physical-capacity models may use installed base, utilization,
+replacement cycle, throughput, or transactions. Keep dimensions explicit so
+the resulting unit can be checked.
-Example:
-- 2020 market size: $10 billion
-- 2024 market size: $18 billion
-- n = 4 years
-- CAGR = (18/10)^(1/4) - 1 = 15.8%
-```
+### SAM and SOM
-#### Year-over-Year Growth
+```text
+SAM_s = TAM * serviceable_fraction_s
+SOM_s = SAM_s * obtainable_share_s
```
-YoY Growth = (Current Year - Previous Year) / Previous Year × 100
-Example:
-- 2023: $15 billion
-- 2024: $18 billion
-- YoY Growth = (18-15)/15 × 100 = 20%
+The fractions belong to scenario `s`. At minimum, use distinct downside and
+upside cases; a base case is usually useful. For each case, list assumptions,
+evidence, constraints, and horizon. Do not assign probabilities without a
+validated probabilistic model.
+
+### Preventing double counting
+
+Common failures:
+
+- adding manufacturer revenue to distributor or end-customer spend;
+- adding domestic production, imports, and sales without subtracting exports,
+ inventories, or overlapping channels;
+- summing parent and subsidiary revenue;
+- adding product bundles and their included components;
+- combining gross output and value added;
+- counting the same establishment in multiple segment labels;
+- adding annual transactions to installed-base stock;
+- applying overlapping geography or customer filters independently.
+
+Controls:
+
+1. assign a unique coverage key to every component;
+2. use mutually exclusive, collectively understood segments;
+3. define a single denominator ID;
+4. draw money and product flows through the value chain;
+5. reconcile supply, use, trade, inventory, and channel margins;
+6. show an ``unallocated/unknown'' residual rather than forcing totals;
+7. test the sum against an independent control total.
+
+Supply-use tables distinguish products from industries and the origin/use of
+goods and services. Use the
+[OECD Supply and Use Tables](https://www.oecd.org/en/data/datasets/supply-and-use-tables.html)
+and national accounts methodology when the value chain spans intermediate and
+final demand.
+
+### Reconciliation
+
+Keep methods separate:
+
+```text
+absolute_gap = abs(TAM_top - TAM_bottom)
+midpoint = (TAM_top + TAM_bottom) / 2
+gap_percent = absolute_gap / midpoint
```
----
-
-## Porter's Five Forces Analysis
-
-### Framework Template
-
-For each force, assess: **HIGH**, **MEDIUM**, or **LOW**
-
-#### 1. Threat of New Entrants
-
-**Factors to evaluate:**
-| Factor | Assessment | Notes |
-|--------|------------|-------|
-| Capital requirements | High/Med/Low | $ required to enter |
-| Economies of scale | Strong/Moderate/Weak | Incumbent advantages |
-| Brand loyalty | High/Med/Low | Customer switching cost |
-| Access to distribution | Easy/Moderate/Difficult | Channel availability |
-| Regulatory barriers | High/Med/Low | Licensing, certifications |
-| Proprietary technology | Critical/Important/Minor | IP and know-how |
-| Expected retaliation | Aggressive/Moderate/Passive | Incumbent response |
-
-**Overall Assessment:** [HIGH/MEDIUM/LOW]
-
-**Key Insights:** [Summary of implications]
-
-#### 2. Bargaining Power of Suppliers
-
-**Factors to evaluate:**
-| Factor | Assessment | Notes |
-|--------|------------|-------|
-| Supplier concentration | High/Med/Low | Number of suppliers |
-| Switching costs | High/Med/Low | Cost to change suppliers |
-| Supplier differentiation | High/Med/Low | Uniqueness of inputs |
-| Forward integration threat | High/Med/Low | Can suppliers compete? |
-| Importance to supplier | Critical/Important/Minor | Your share of their revenue |
-| Substitute inputs | Many/Some/Few | Alternatives available |
-
-**Overall Assessment:** [HIGH/MEDIUM/LOW]
-
-#### 3. Bargaining Power of Buyers
-
-**Factors to evaluate:**
-| Factor | Assessment | Notes |
-|--------|------------|-------|
-| Buyer concentration | High/Med/Low | Few large vs. many small |
-| Purchase volume | Large/Medium/Small | Relative importance |
-| Switching costs | Low/Med/High | Cost to change vendors |
-| Price sensitivity | High/Med/Low | Focus on price vs. value |
-| Backward integration threat | High/Med/Low | Can buyers self-supply? |
-| Information availability | Full/Partial/Limited | Market transparency |
-
-**Overall Assessment:** [HIGH/MEDIUM/LOW]
-
-#### 4. Threat of Substitutes
-
-**Factors to evaluate:**
-| Factor | Assessment | Notes |
-|--------|------------|-------|
-| Substitute availability | Many/Some/Few | Number of alternatives |
-| Price-performance ratio | Better/Same/Worse | Value comparison |
-| Switching costs | Low/Med/High | Friction to substitute |
-| Buyer propensity to switch | High/Med/Low | Willingness to change |
-| Perceived differentiation | Low/Med/High | Unique value |
-
-**Overall Assessment:** [HIGH/MEDIUM/LOW]
-
-#### 5. Competitive Rivalry
-
-**Factors to evaluate:**
-| Factor | Assessment | Notes |
-|--------|------------|-------|
-| Number of competitors | Many/Several/Few | Market fragmentation |
-| Industry growth | Slow/Moderate/Fast | Growth rate impact |
-| Fixed costs | High/Med/Low | Pressure to fill capacity |
-| Product differentiation | Low/Med/High | Commoditization level |
-| Exit barriers | High/Med/Low | Difficulty leaving market |
-| Strategic stakes | High/Med/Low | Importance to competitors |
-
-**Overall Assessment:** [HIGH/MEDIUM/LOW]
-
-### Five Forces Summary Table
-
-| Force | Rating | Key Drivers | Implications |
-|-------|--------|-------------|--------------|
-| New Entrants | [H/M/L] | [Top factors] | [Strategic impact] |
-| Supplier Power | [H/M/L] | [Top factors] | [Strategic impact] |
-| Buyer Power | [H/M/L] | [Top factors] | [Strategic impact] |
-| Substitutes | [H/M/L] | [Top factors] | [Strategic impact] |
-| Rivalry | [H/M/L] | [Top factors] | [Strategic impact] |
-
-**Overall Industry Attractiveness:** [ATTRACTIVE / MODERATE / UNATTRACTIVE]
-
----
-
-## PESTLE Analysis
-
-### Framework Template
-
-#### Political Factors
+Investigate gaps in this order:
-| Factor | Current State | Trend | Impact | Time Horizon |
-|--------|---------------|-------|--------|--------------|
-| Government stability | | ↑ ↓ → | H/M/L | Short/Med/Long |
-| Trade policies | | ↑ ↓ → | H/M/L | |
-| Tax regulations | | ↑ ↓ → | H/M/L | |
-| Government support | | ↑ ↓ → | H/M/L | |
-| Political relations | | ↑ ↓ → | H/M/L | |
+1. definition and denominator;
+2. geography, period, currency, and price basis;
+3. taxonomy and segment concordance;
+4. gross/net, taxes, channel margins, imports/exports;
+5. missing or duplicate coverage;
+6. source revision and sample limitations;
+7. price, volume, penetration, and utilization assumptions.
-**Key Political Implications:** [Summary]
-
-#### Economic Factors
-
-| Factor | Current State | Trend | Impact | Time Horizon |
-|--------|---------------|-------|--------|--------------|
-| GDP growth | X.X% | ↑ ↓ → | H/M/L | |
-| Interest rates | X.X% | ↑ ↓ → | H/M/L | |
-| Inflation | X.X% | ↑ ↓ → | H/M/L | |
-| Exchange rates | | ↑ ↓ → | H/M/L | |
-| Consumer spending | | ↑ ↓ → | H/M/L | |
-| Unemployment | X.X% | ↑ ↓ → | H/M/L | |
+Do not average the methods until their scopes are demonstrably compatible. If
+uncertainty remains, report both or retain a range.
-**Key Economic Implications:** [Summary]
+## Growth and forecasts
-#### Social Factors
+### Historical growth
-| Factor | Current State | Trend | Impact | Time Horizon |
-|--------|---------------|-------|--------|--------------|
-| Demographics | | ↑ ↓ → | H/M/L | |
-| Cultural attitudes | | ↑ ↓ → | H/M/L | |
-| Consumer behavior | | ↑ ↓ → | H/M/L | |
-| Education levels | | ↑ ↓ → | H/M/L | |
-| Health consciousness | | ↑ ↓ → | H/M/L | |
-| Work-life balance | | ↑ ↓ → | H/M/L | |
-
-**Key Social Implications:** [Summary]
-
-#### Technological Factors
-
-| Factor | Current State | Trend | Impact | Time Horizon |
-|--------|---------------|-------|--------|--------------|
-| R&D activity | | ↑ ↓ → | H/M/L | |
-| Technology adoption | | ↑ ↓ → | H/M/L | |
-| Automation | | ↑ ↓ → | H/M/L | |
-| Digital infrastructure | | ↑ ↓ → | H/M/L | |
-| Innovation rate | | ↑ ↓ → | H/M/L | |
-| Disruptive tech | | ↑ ↓ → | H/M/L | |
-
-**Key Technological Implications:** [Summary]
-
-#### Legal Factors
-
-| Factor | Current State | Trend | Impact | Time Horizon |
-|--------|---------------|-------|--------|--------------|
-| Industry regulations | | ↑ ↓ → | H/M/L | |
-| Data protection | | ↑ ↓ → | H/M/L | |
-| Employment law | | ↑ ↓ → | H/M/L | |
-| Consumer protection | | ↑ ↓ → | H/M/L | |
-| IP rights | | ↑ ↓ → | H/M/L | |
-| Antitrust | | ↑ ↓ → | H/M/L | |
-
-**Key Legal Implications:** [Summary]
-
-#### Environmental Factors
-
-| Factor | Current State | Trend | Impact | Time Horizon |
-|--------|---------------|-------|--------|--------------|
-| Climate change | | ↑ ↓ → | H/M/L | |
-| Sustainability reqs | | ↑ ↓ → | H/M/L | |
-| Resource availability | | ↑ ↓ → | H/M/L | |
-| Waste management | | ↑ ↓ → | H/M/L | |
-| Carbon regulations | | ↑ ↓ → | H/M/L | |
-| Environmental awareness | | ↑ ↓ → | H/M/L | |
-
-**Key Environmental Implications:** [Summary]
-
----
-
-## SWOT Analysis
-
-### Framework Template
-
-#### Strengths (Internal, Positive)
-| Strength | Evidence | Strategic Value |
-|----------|----------|-----------------|
-| [Strength 1] | [Data/proof] | High/Med/Low |
-| [Strength 2] | [Data/proof] | High/Med/Low |
-| [Strength 3] | [Data/proof] | High/Med/Low |
-
-**Core Strengths Summary:** [2-3 sentence synthesis]
-
-#### Weaknesses (Internal, Negative)
-| Weakness | Evidence | Severity |
-|----------|----------|----------|
-| [Weakness 1] | [Data/proof] | Critical/Moderate/Minor |
-| [Weakness 2] | [Data/proof] | Critical/Moderate/Minor |
-| [Weakness 3] | [Data/proof] | Critical/Moderate/Minor |
-
-**Key Vulnerabilities Summary:** [2-3 sentence synthesis]
-
-#### Opportunities (External, Positive)
-| Opportunity | Size/Potential | Timeframe |
-|-------------|----------------|-----------|
-| [Opportunity 1] | $X / High/Med/Low | Short/Med/Long |
-| [Opportunity 2] | $X / High/Med/Low | Short/Med/Long |
-| [Opportunity 3] | $X / High/Med/Low | Short/Med/Long |
-
-**Priority Opportunities Summary:** [2-3 sentence synthesis]
-
-#### Threats (External, Negative)
-| Threat | Likelihood | Impact |
-|--------|------------|--------|
-| [Threat 1] | High/Med/Low | High/Med/Low |
-| [Threat 2] | High/Med/Low | High/Med/Low |
-| [Threat 3] | High/Med/Low | High/Med/Low |
-
-**Critical Threats Summary:** [2-3 sentence synthesis]
-
-### SWOT Strategy Matrix
-
-| | **Strengths** | **Weaknesses** |
-|---|---------------|----------------|
-| **Opportunities** | **SO Strategies** (use strengths to capture opportunities) | **WO Strategies** (overcome weaknesses to capture opportunities) |
-| **Threats** | **ST Strategies** (use strengths to mitigate threats) | **WT Strategies** (minimize weaknesses and avoid threats) |
-
----
-
-## BCG Growth-Share Matrix
-
-### Framework Template
+```text
+YoY_t = value_t / value_(t-1) - 1
+CAGR = (end / start)^(1 / periods) - 1
+```
-**Axes:**
-- X-axis: Relative Market Share (High → Low, logarithmic scale)
-- Y-axis: Market Growth Rate (High → Low, typically 10% as midpoint)
+CAGR compresses the path. Always show start/end values and period count. It is
+undefined when the start is nonpositive and can hide volatility, breaks, and
+revisions.
-### Quadrant Definitions
+### Scenario forecast
-| Quadrant | Growth | Share | Characteristics | Strategy |
-|----------|--------|-------|-----------------|----------|
-| **Stars** | High | High | Market leaders in growing markets | Invest to maintain position |
-| **Cash Cows** | Low | High | Market leaders in mature markets | Harvest for cash flow |
-| **Question Marks** | High | Low | Small share in growing markets | Invest selectively or divest |
-| **Dogs** | Low | Low | Small share in mature markets | Divest or minimize investment |
+```text
+value_(t+1,s) = value_(t,s) * (1 + growth_rate_(t,s))
+```
-### Product/Business Unit Analysis
+Build rate paths from named drivers rather than copying a paid headline
+forecast. Separate:
-| Product/BU | Market Growth | Relative Share | Quadrant | Recommended Strategy |
-|------------|---------------|----------------|----------|---------------------|
-| [Product A] | X.X% | X.X | Star/Cow/QM/Dog | [Strategy] |
-| [Product B] | X.X% | X.X | Star/Cow/QM/Dog | [Strategy] |
-| [Product C] | X.X% | X.X | Star/Cow/QM/Dog | [Strategy] |
+- historical observed period;
+- nowcast or estimate period;
+- conditional forecast period.
-### Portfolio Balance Assessment
+For each scenario, state demand, price, supply, regulation, competition,
+capacity, and timing assumptions. Use different paths, not merely different
+labels.
-| Quadrant | Number of Products | Revenue % | Investment Priority |
-|----------|-------------------|-----------|---------------------|
-| Stars | X | X% | High |
-| Cash Cows | X | X% | Maintain |
-| Question Marks | X | X% | Selective |
-| Dogs | X | X% | Low/Divest |
+### Sensitivity
----
+One-way sensitivity varies one input while holding others fixed. Report:
-## Value Chain Analysis
+- tested range and rationale;
+- resulting endpoints;
+- switching value where the decision changes;
+- nonlinearities or constraints;
+- interactions omitted by one-way analysis.
-### Framework Template
+Scenario analysis explores coherent joint states. It is not a confidence
+interval. Statistical prediction intervals require a specified model, error
+process, diagnostics, and coverage interpretation.
-#### Primary Activities
+The 2023
+[OMB Circular A-4](https://www.whitehouse.gov/wp-content/uploads/2023/11/CircularA-4.pdf)
+provides primary guidance on characterizing uncertainty, sensitivity, and
+transparent assumptions. The
+[UK Green Book 2026](https://www.gov.uk/government/publications/the-green-book-appraisal-and-evaluation-in-central-government/the-green-book-2026)
+provides additional public-sector appraisal guidance. Adapt principles
+proportionately; do not imply that a market report is a regulatory appraisal.
-| Activity | Description | Value Created | Cost | Competitive Position |
-|----------|-------------|---------------|------|---------------------|
-| **Inbound Logistics** | Receiving, storing, inventory | | $X | Strong/Average/Weak |
-| **Operations** | Manufacturing, assembly | | $X | Strong/Average/Weak |
-| **Outbound Logistics** | Distribution, delivery | | $X | Strong/Average/Weak |
-| **Marketing & Sales** | Promotion, sales force | | $X | Strong/Average/Weak |
-| **Service** | Installation, support, repair | | $X | Strong/Average/Weak |
+## Units, currencies, and price bases
-#### Support Activities
+### Nominal and real
-| Activity | Description | Value Created | Cost | Competitive Position |
-|----------|-------------|---------------|------|---------------------|
-| **Infrastructure** | Management, finance, legal | | $X | Strong/Average/Weak |
-| **HR Management** | Recruiting, training, comp | | $X | Strong/Average/Weak |
-| **Technology Dev** | R&D, process improvement | | $X | Strong/Average/Weak |
-| **Procurement** | Purchasing, supplier mgmt | | $X | Strong/Average/Weak |
+- **Nominal/current-price** values reflect prices in each period.
+- **Real/constant-price** values remove price change using an identified
+ deflator and base/reference year.
+- Never combine nominal and real values in one total or growth rate.
+- Match nominal values to nominal assumptions and real values to real
+ assumptions.
-### Value Chain Margin Analysis
+Record:
-```
-Total Revenue: $XXX
-- Inbound Logistics: ($XX)
-- Operations: ($XX)
-- Outbound Logistics: ($XX)
-- Marketing & Sales: ($XX)
-- Service: ($XX)
-- Support Activities: ($XX)
-= Margin: $XX (X%)
+```text
+real_value_base_year = nominal_value_t * price_index_base / price_index_t
```
-### Competitive Comparison
+Identify the index, geography, category, vintage, and whether it is appropriate
+for the market. A broad CPI may be unsuitable for a specialized B2B input.
-| Activity | Company | Industry Avg | Best-in-Class | Gap |
-|----------|---------|--------------|---------------|-----|
-| [Activity] | X% | Y% | Z% | +/-X% |
+### Chained measures
----
+Chained-dollar components may not add to published aggregates. BEA's
+[chained-dollar guidance](https://www.bea.gov/resources/methodologies/chained-dollar-indexes)
+explains why. Use published contributions to growth or current-dollar
+composition rather than forcing additivity.
-## Competitive Positioning Analysis
+### Currency conversion
-### Framework Template
+Record:
-#### Positioning Dimensions
+- source and target currency;
+- spot, period-average, or period-end convention;
+- rate date/period and source;
+- order of currency conversion and deflation;
+- effects of high inflation or multiple exchange-rate regimes.
-Common positioning dimension pairs:
-- Price vs. Quality
-- Market Focus (Niche vs. Broad)
-- Solution Type (Product vs. Platform)
-- Geographic Scope (Regional vs. Global)
-- Customer Focus (Enterprise vs. SMB vs. Consumer)
-- Innovation Level (Leader vs. Follower)
+Do not mix converted flows using period-end rates with balances using averages
+without explanation.
-#### Competitor Mapping
+### Stock and flow
-| Competitor | Dimension 1 Score (1-10) | Dimension 2 Score (1-10) | Market Share | Notes |
-|------------|-------------------------|-------------------------|--------------|-------|
-| Company A | X | X | X% | [Position description] |
-| Company B | X | X | X% | [Position description] |
-| Company C | X | X | X% | [Position description] |
+A stock is measured at a point in time; a flow over an interval. Installed
+base, employees on a date, and capacity are stocks. Revenue, transactions, and
+shipments during a year are flows. A stock-to-flow conversion requires an
+explicit turnover, utilization, or replacement-cycle assumption.
-#### Strategic Group Identification
+## Shares and concentration
-| Strategic Group | Companies | Characteristics | Market Share |
-|-----------------|-----------|-----------------|--------------|
-| Group 1: [Name] | A, B, C | [Description] | X% |
-| Group 2: [Name] | D, E | [Description] | X% |
-| Group 3: [Name] | F, G, H | [Description] | X% |
+```text
+share_i = in_scope_measure_i / same_scope_total
+HHI = sum((100 * share_i)^2)
+CR4 = sum(four_largest_shares)
+```
----
+Before computing:
-## Risk Assessment Framework
+- define product and geographic scope;
+- use one share metric and denominator;
+- include the same period and channel level;
+- account for unknown/residual firms;
+- disclose whether values are revenue, units, capacity, or active users;
+- avoid false precision when company and total estimates use different methods.
-### Risk Identification
+The [2023 U.S. Merger Guidelines](https://www.ftc.gov/system/files/ftc_gov/pdf/2023_merger_guidelines_final_12.18.2023.pdf)
+describe HHI as one indicator in case-specific merger analysis. The
+[2024 EU Market Definition Notice](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=OJ:C_202401645)
+addresses product/geographic scope, non-price parameters, dynamic and digital
+markets, alternate share metrics, and evidence. A market report's HHI is
+descriptive and is not a legal conclusion.
-#### Risk Categories
-1. **Market Risks**: Demand changes, price pressure, market shifts
-2. **Competitive Risks**: New entrants, competitor moves, disruption
-3. **Regulatory Risks**: New regulations, compliance requirements
-4. **Technology Risks**: Obsolescence, security, integration
-5. **Operational Risks**: Supply chain, quality, capacity
-6. **Financial Risks**: Currency, interest rates, credit
-7. **Reputational Risks**: Brand damage, social media, ethics
+## Survey and interview synthesis
-### Risk Assessment Matrix
+### Survey estimate
-| Risk ID | Risk Description | Category | Probability | Impact | Score | Priority |
-|---------|------------------|----------|-------------|--------|-------|----------|
-| R1 | [Description] | Market | 1-5 | 1-5 | P×I | H/M/L |
-| R2 | [Description] | Competitive | 1-5 | 1-5 | P×I | H/M/L |
+For a probability sample, report the design-based or model-based estimator,
+weights, design effect, and appropriate uncertainty. Do not infer population
+precision from sample size alone.
-**Scoring Guide:**
-- Probability: 1=Very Unlikely, 2=Unlikely, 3=Possible, 4=Likely, 5=Very Likely
-- Impact: 1=Minimal, 2=Minor, 3=Moderate, 4=Major, 5=Severe
-- Priority: Score 15-25=High, 8-14=Medium, 1-7=Low
+For a non-probability sample, disclose recruitment and model assumptions. Use
+careful labels such as ``among respondents'' unless a validated adjustment
+supports broader inference.
-### Risk Mitigation Planning
+### Interview themes
-| Risk ID | Risk | Mitigation Strategy | Owner | Timeline | Cost |
-|---------|------|---------------------|-------|----------|------|
-| R1 | [Risk] | [Prevention + Response] | [Name] | [Date] | $X |
+Use a structured coding frame:
----
+```text
+theme_id | definition | inclusion rule | exclusion rule |
+supporting excerpts | disconfirming excerpts | roles represented
+```
-## Financial Analysis Patterns
+Report a theme as qualitative evidence. Do not translate mention counts into
+market prevalence.
-### Revenue Projection Model
+## Confidence labels
-```
-Year N Revenue = Year N-1 Revenue × (1 + Growth Rate)
+Confidence is an analyst assessment, not a substitute for uncertainty:
-Or bottom-up:
-Revenue = Customers × Revenue per Customer × Retention Rate
- + New Customers × Revenue per Customer × (1 - Churn Rate)
-```
+- **High**: directly observed, well-defined primary evidence with compatible
+ scope and low material revision risk.
+- **Medium**: triangulated evidence with manageable assumptions or limitations.
+- **Low**: sparse, conflicting, indirect, modeled, or scope-mismatched evidence.
+- **Not assessed**: opinion or recommendation where an evidence-confidence
+ label is inappropriate.
-### Scenario Analysis Template
-
-| Metric | Conservative | Base Case | Optimistic |
-|--------|--------------|-----------|------------|
-| Market Growth | X% | Y% | Z% |
-| Market Share | X% | Y% | Z% |
-| Pricing | $X | $Y | $Z |
-| Gross Margin | X% | Y% | Z% |
-| **Revenue Y5** | $X | $Y | $Z |
-| **EBITDA Y5** | $X | $Y | $Z |
-
-### Key Financial Metrics
-
-| Metric | Formula | Target |
-|--------|---------|--------|
-| Gross Margin | (Revenue - COGS) / Revenue | X% |
-| EBITDA Margin | EBITDA / Revenue | X% |
-| Customer Acquisition Cost | Sales & Marketing / New Customers | $X |
-| Lifetime Value | ARPU × Gross Margin × Lifetime | $X |
-| LTV/CAC Ratio | LTV / CAC | >3x |
-| Payback Period | CAC / (ARPU × Gross Margin × 12) | <X months |
-
----
-
-## Data Collection Checklist
-
-### Market Size Data
-- [ ] Current market size (with year and source)
-- [ ] Historical market size (5-10 years)
-- [ ] Market growth projections (5-10 years)
-- [ ] CAGR (historical and projected)
-- [ ] Regional breakdown
-- [ ] Segment breakdown
-
-### Competitive Data
-- [ ] Market share by company (top 10)
-- [ ] Revenue by competitor
-- [ ] Growth rates by competitor
-- [ ] Strategic moves (M&A, partnerships, launches)
-- [ ] Pricing information
-- [ ] Product/service offerings
-
-### Customer Data
-- [ ] Customer segments and sizes
-- [ ] Segment growth rates
-- [ ] Average deal size by segment
-- [ ] Customer acquisition cost
-- [ ] Customer lifetime value
-- [ ] Churn rates
-
-### Industry Data
-- [ ] Key industry trends
-- [ ] Regulatory developments
-- [ ] Technology trends
-- [ ] Economic indicators
-- [ ] Demographic trends
-
----
-
-## Research Sources
-
-### Primary Research
-- Customer interviews
-- Expert interviews
-- Surveys
-- Focus groups
-
-### Secondary Research
-- Market research reports (Gartner, Forrester, IDC, McKinsey)
-- Industry associations
-- Government statistics
-- Company annual reports
-- SEC filings (10-K, 10-Q)
-- Earnings call transcripts
-- Trade publications
-- Academic journals
-- News articles
-
-### Data Validation
-- Cross-reference multiple sources
-- Check date currency (prefer <2 years old)
-- Verify methodology
-- Note confidence levels
-- Document assumptions
+Always state the reasons. Multiple low-quality sources do not automatically
+produce high confidence.
diff --git a/skills/market-research-reports/references/evidence_model.md b/skills/market-research-reports/references/evidence_model.md
new file mode 100644
index 00000000..e4ca3bb7
--- /dev/null
+++ b/skills/market-research-reports/references/evidence_model.md
@@ -0,0 +1,148 @@
+# Evidence Model and Citation Integrity
+
+This model makes a report auditable at claim level. A bibliography is necessary
+but insufficient: each material claim must map to the exact source records,
+calculation, and assumptions that support it.
+
+## Statement classes
+
+Label every material statement as one of:
+
+1. **Quantitative fact** — a value directly represented by a cited source.
+2. **Quantitative estimate** — a source's or analyst's uncertain estimate.
+3. **Qualitative fact** — an attributable event, policy, feature, or statement.
+4. **Calculation** — deterministic transformation of cited inputs.
+5. **Forecast** — conditional future path based on stated assumptions.
+6. **Opinion** — attributed respondent or analyst judgment.
+7. **Recommendation** — decision advice derived from findings and objectives.
+
+Do not rewrite an estimate as a fact, a scenario as a prediction, an interview
+theme as prevalence, or a recommendation as an evidence claim.
+
+## Source record
+
+Give each source a stable ID such as `S-001`. Record:
+
+- title, publisher/author, URL or persistent identifier;
+- source type and original data producer;
+- publication date and retrieval date;
+- archived local snapshot path, if legally permitted;
+- geography and covered population;
+- currency, base year, and nominal/real/current/constant/chained basis;
+- stock, flow, count, share, rate, price, index, or mixed measure;
+- unit and denominator;
+- industry/product taxonomy and version;
+- preliminary/revised/final/vintage/current status;
+- collection or estimation method;
+- survey frame, mode, sample, weighting, and response information when relevant;
+- limitations, suppression, imputation, breaks, and known revisions;
+- license, terms, and attribution requirements.
+
+For an aggregator, record both the delivery platform and original producer. For
+example, a FRED series should retain its original agency/source metadata; FRED
+availability does not erase third-party rights or methodology.
+
+## Claim record
+
+Give each claim a stable ID such as `C-014`. Record:
+
+- exact claim text;
+- statement class;
+- one or more source IDs;
+- report location;
+- as-of date and geography;
+- currency/base year/price basis, measure type, unit, and denominator;
+- taxonomy and version;
+- revision status;
+- calculation ID and assumption IDs where applicable;
+- a calibrated confidence label and reasons;
+- limitations or conflicts material to interpretation.
+
+One citation at the end of a paragraph does not automatically support every
+sentence in the paragraph. Split compound claims when different sources support
+different components.
+
+## Source hierarchy
+
+Use fitness for the claim, not prestige alone. A practical default:
+
+1. primary law, regulator decision, official filing, or official statistic;
+2. original company filing or attributable first-party operating disclosure;
+3. transparent survey or study with inspectable methods;
+4. peer-reviewed or institutional research using identifiable primary data;
+5. industry association data with disclosed coverage and methods;
+6. reputable secondary synthesis;
+7. paid market estimate with inspectable scope/method and lawful access;
+8. news or commentary for leads and attributable events, not unsupported size
+ estimates.
+
+The best source can differ by claim. A company filing is authoritative about
+reported company revenue but not automatically about total market size. An
+official industry total may be authoritative but too broad for the product
+market being studied.
+
+## Conflicting evidence
+
+Never choose the most convenient number silently.
+
+1. Compare definitions, period, geography, currency, price basis, unit,
+ denominator, taxonomy, sample, and revision vintage.
+2. Determine whether values are genuinely conflicting or merely different
+ measures.
+3. Prefer the source closest to the primary observation and fit to the claim.
+4. If both remain plausible, retain a range or parallel estimates.
+5. Document the conflict, decision rule, and sensitivity to the choice.
+6. Do not average incompatible estimates.
+
+## Revisions and vintages
+
+- Record retrieval date for every online source.
+- Record a dataset vintage or release identifier when available.
+- Preserve the original input snapshot or checksum when terms permit.
+- Mark preliminary data and expected revisions.
+- On refresh, compare new and prior values; do not overwrite silently.
+- Use archived/vintage systems where needed for reproducibility.
+- For sources that expose only the latest version, preserve the retrieved file
+ and state that historical versions are not supplied by the API.
+
+## Calculation lineage
+
+Each calculation record should identify:
+
+- formula and calculation ID;
+- exact input fields and source IDs;
+- exclusions and coverage keys;
+- conversions, exchange-rate source/date, and deflator/index;
+- rounding policy;
+- intermediate values;
+- output unit and denominator;
+- assumptions and sensitivity values;
+- software/script version or command used.
+
+Do not cite a calculated result as if it appeared verbatim in a source.
+
+## Source integrity failures to avoid
+
+- fabricated citations, URLs, access dates, quotes, or paid figures;
+- citing a search-result snippet instead of the underlying source;
+- citation laundering through an aggregator or secondary article;
+- using a source outside its geographic, temporal, or definitional scope;
+- omitting a correction, restatement, or revision;
+- attributing a denominator from one source to a numerator from another without
+ reconciliation;
+- claiming that multiple citations are independent when they reproduce one
+ underlying estimate;
+- treating absence of public evidence as evidence of absence.
+
+## Minimum audit
+
+Before release:
+
+1. validate the source ledger;
+2. audit every factual, estimate, calculation, and forecast claim;
+3. resolve missing source IDs;
+4. review unused sources and citation clusters;
+5. spot-check every headline number against the archived source;
+6. reproduce market-size and forecast outputs from local inputs;
+7. rerun unit/currency/base-year consistency checks;
+8. retain unresolved conflicts and limitations in the report.
diff --git a/skills/market-research-reports/references/methods_and_ethics.md b/skills/market-research-reports/references/methods_and_ethics.md
new file mode 100644
index 00000000..9ec34275
--- /dev/null
+++ b/skills/market-research-reports/references/methods_and_ethics.md
@@ -0,0 +1,162 @@
+# Research Methods, Privacy, and Ethics
+
+## Primary research decision
+
+Conduct interviews or surveys only when the research question cannot be
+answered adequately with existing lawful evidence. Define the purpose,
+population, data fields, retention period, and reporting plan before
+recruitment.
+
+Do not use research as disguised selling, lead generation, political
+campaigning, or a way to obtain confidential competitor information.
+Apply the current
+[AAPOR Code of Professional Ethics and Practices](https://aapor.org/standards-and-ethics/),
+revised in June 2026, alongside the disclosure standards below.
+
+## Survey evidence
+
+Follow the [AAPOR Disclosure Standards](https://aapor.org/standards-and-ethics/disclosure-standards/)
+for any survey claim. Record:
+
+- sponsor, funder, and fieldwork organization;
+- research objective and target population;
+- probability or non-probability design;
+- sampling frame, selection, recruitment, eligibility, and incentives;
+- mode, language, instrument, exact wording, ordering, and field dates;
+- unweighted sample sizes overall and for reported subgroups;
+- weighting variables, benchmark sources, trimming, calibration, and design
+ effects;
+- dispositions, response/cooperation/participation rates and definitions;
+- imputation, exclusions, attention checks, coding, and quality controls;
+- appropriate precision measure and assumptions;
+- coverage, nonresponse, measurement, processing, and model limitations.
+
+Do not:
+
+- report a conventional margin of sampling error for a non-probability sample
+ unless a defensible model and its assumptions are fully disclosed;
+- equate a large sample with representativeness;
+- describe opt-in respondents as a random sample;
+- compare waves after changing question wording, mode, population, or weighting
+ without analyzing the break;
+- report subgroup estimates with undisclosed small bases;
+- claim causality from a descriptive cross-sectional survey.
+
+The FCSM's
+[Best Practices for Nonresponse Bias Reporting](https://statspolicy.gov/assets/fcsm/files/docs/FCSM%20NRBA%20Report%20062623.pdf)
+supports reporting standard response rates and examining key subgroups. A high
+response rate does not by itself eliminate bias, and a lower rate does not by
+itself prove bias; analyze the mechanism and available benchmarks.
+
+## Interviews and focus groups
+
+Record:
+
+- recruitment criteria and source;
+- role categories represented and material gaps;
+- consent script, recording permission, incentive, and withdrawal process;
+- interview dates, mode, duration, moderator, and guide version;
+- coding method, number of coders, disagreements, and use of software;
+- whether themes were expected, emergent, divergent, or disconfirming;
+- limitations from purposive recruitment, sponsor effects, social desirability,
+ and nonresponse.
+
+Quotes require permission and de-identification appropriate to the context.
+Paraphrases must not change meaning. Never attach percentages or population
+prevalence to qualitative themes.
+
+## Privacy and data minimization
+
+Collect only data needed for the stated purpose. Before collection:
+
+1. identify applicable privacy, employment, recording, consumer, and research
+ rules in every jurisdiction;
+2. provide a clear notice and obtain appropriate consent;
+3. avoid sensitive data unless necessary, lawful, and specifically protected;
+4. separate contact details from research responses;
+5. define role-based access, encryption, retention, deletion, and incident
+ handling;
+6. assess re-identification risk from combinations of role, employer,
+ geography, quotes, and rare attributes;
+7. aggregate or suppress small groups;
+8. document any processor or platform and cross-border transfer.
+
+Never place names, email addresses, phone numbers, account identifiers, raw IP
+addresses, private messages, recordings, or other direct identifiers in the
+report evidence ledger. A source ID should identify a controlled record, not a
+person.
+
+The [ICO data minimisation guidance](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/data-protection-principles/a-guide-to-the-data-protection-principles/data-minimisation)
+is a useful primary reference where UK GDPR applies. Apply the governing law in
+the actual jurisdiction rather than assuming one framework is universal.
+
+## Lawful customer and competitor research
+
+Permitted evidence may include public filings, regulator records, official
+registries, public product documentation, published pricing, lawful public
+procurement records, consented research, and licensed databases used within
+their terms.
+
+Do not:
+
+- impersonate a customer, employee, regulator, journalist, investor, or
+ prospective hire;
+- misstate identity or purpose to gain access;
+- evade authentication, access controls, paywalls, technical restrictions,
+ robots policies, or contractual limits;
+- solicit or accept trade secrets, source code, credentials, nonpublic pricing,
+ customer lists, roadmaps, bids, or confidential documents;
+- use leaked, stolen, inadvertently exposed, or unlawfully obtained material;
+- collect personal profiles unrelated to the research purpose;
+- infer protected or sensitive attributes;
+- contact employees in a manner that pressures them to breach duties;
+- turn absence of a public feature statement into a definitive ``no.''
+
+Use `unknown` when lawful public evidence is insufficient. Keep screenshots or
+snapshots only when terms allow, and record product edition, geography, account
+tier, and as-of date.
+
+## Competition and antitrust framing
+
+Competitive analysis is descriptive unless qualified counsel performs a legal
+assessment. The
+[2023 U.S. Merger Guidelines](https://www.ftc.gov/system/files/ftc_gov/pdf/2023_merger_guidelines_final_12.18.2023.pdf)
+and the
+[2024 European Commission Market Definition Notice](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=OJ:C_202401645)
+show why product/geographic market definition, shares, concentration, entry,
+dynamic competition, and evidence are case-specific.
+
+Rules:
+
+- do not equate a TAM category with a relevant antitrust market;
+- state the share denominator and why it reflects competitive reality;
+- test alternate product and geographic boundaries;
+- consider non-price competition, multi-sided platforms, zero-price services,
+ innovation, capacity, active users, imports, and prospective entry where
+ relevant;
+- report unknown participants and residual share;
+- treat HHI and concentration ratios as descriptive screening measures, not a
+ legal conclusion;
+- do not label a firm a monopoly, dominant, anticompetitive, or collusive
+ without appropriately sourced legal findings or qualified legal analysis.
+
+## Conflicts and sponsor influence
+
+Disclose the sponsor, funder, analyst role, material commercial interests, and
+constraints on publication. A sponsor may set the question but must not dictate
+the evidence, remove unfavorable results, or suppress material limitations.
+Keep a record of deviations from the analysis plan.
+
+## Decision-use boundary
+
+A market report may inform planning, but it does not guarantee outcomes and
+must not present itself as:
+
+- investment advice or a solicitation to transact;
+- legal, antitrust, tax, accounting, or regulatory advice;
+- a fairness opinion, valuation opinion, or assurance engagement;
+- confirmation that a market figure is true merely because it appears in a
+ paid report.
+
+For high-stakes decisions, obtain qualified domain, legal, financial, privacy,
+and statistical review as appropriate.
diff --git a/skills/market-research-reports/references/official_data_sources.md b/skills/market-research-reports/references/official_data_sources.md
new file mode 100644
index 00000000..4689e1f6
--- /dev/null
+++ b/skills/market-research-reports/references/official_data_sources.md
@@ -0,0 +1,196 @@
+# Official Data and Filing Sources
+
+Verified against first-party guidance on 2026-07-23. API rules can change:
+recheck the linked terms and limits before automated or high-volume use. The
+bundled scripts do not call these services and do not require API keys.
+
+## Routing by claim
+
+Start with the original authority most fit for the claim:
+
+- company financials and risk disclosures: the jurisdiction's official filing
+ system, then the filed document;
+- establishment, employment, prices, production, trade, population, and GDP:
+ the responsible national statistical office or central bank;
+- rules, approvals, enforcement, licenses, and consultations: the responsible
+ regulator or official legal gazette;
+- cross-country indicators: the original national source when comparability is
+ not required; otherwise an international harmonized dataset with metadata;
+- classifications: the current official NAICS, NACE, ISIC, product, trade, or
+ sector taxonomy and its correspondence tables.
+
+Do not treat an aggregator as an independent corroborating source when it
+reproduces the same underlying series.
+
+## United States
+
+### SEC EDGAR and company filings
+
+- [SEC Developer Resources](https://www.sec.gov/about/developer-resources)
+ documents company submissions and extracted XBRL data APIs.
+- [Accessing EDGAR Data](https://www.sec.gov/search-filings/edgar-search-assistance/accessing-edgar-data)
+ requires a declared user agent and states a current maximum of 10 requests per
+ second across the user's machines. Download only what is needed.
+- EDGAR filings can be corrected or removed after acceptance. Record accession
+ number, form, filing date, reporting period, amendment status, exact table or
+ XBRL fact, units, and retrieval date.
+- Consolidated company revenue is not automatically market revenue. Remove
+ out-of-scope products/geographies and avoid summing parent/subsidiary or
+ channel/end-customer values twice.
+
+### U.S. Census Bureau
+
+- The [Census Data API User Guide](https://www.census.gov/data/developers/guidance/api-user-guide.html)
+ links data to a geographic boundary and a dataset vintage.
+- As revised 2026-05-14, the
+ [query-limits page](https://www.census.gov/data/developers/guidance/api-user-guide.Query_Limits.html)
+ permits up to 50 variables per query and requires a key for all data queries.
+ The [key page](https://www.census.gov/data/developers/guidance/api-user-guide.API_Key.html)
+ describes free registration. Never place a key in a report, source ledger, or
+ bundled script.
+- Use program-specific methodology, margins of error, universe, geography, and
+ vintage. ACS estimates, Population Estimates, and decennial counts are not
+ interchangeable.
+- The [2022 Economic Census methodology](https://www.census.gov/programs-surveys/economic-census/year/2022/technical-documentation/methodology.html)
+ defines the target population, sampling frame, exclusions, administrative
+ data, imputation, disclosure avoidance, and product collection.
+- The [NAICS site](https://www.census.gov/naics) identifies 2022 NAICS as the
+ current published structure while a 2027 revision process is underway. Store
+ the version used.
+
+### Bureau of Labor Statistics
+
+The [BLS API FAQ](https://www.bls.gov/developers/api_faqs.htm), last modified
+2023-08-30, documents:
+
+- registered v2: 500 queries/day, 50 series/query, 20 years/query;
+- unregistered v1: 25 queries/day, 25 series/query, 10 years/query;
+- both: 50 requests per 10 seconds;
+- v2 registration renewal at least annually;
+- v1 returns observations and footnotes without descriptive metadata.
+
+Record series ID, survey/program, seasonal adjustment, units, frequency,
+footnotes, publication date, and revision status. Consult the program's
+methodology and release calendar rather than relying on the API response alone.
+
+### Bureau of Economic Analysis
+
+The [BEA API User Guide](https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf),
+dated 2026-04-20, requires a registered UserID and documents three rolling
+per-minute limits:
+
+- 100 requests;
+- 100 MB retrieved;
+- 30 errors.
+
+BEA returns HTTP 429 and a `Retry-After` header when throttled. The guide warns
+that limits may change. Query metadata methods before data, restrict years and
+dimensions, and avoid broad `ALL` requests. Record current versus chained
+dollars, reference year, table/line code, frequency, seasonality, and release
+vintage. Chained-dollar components may not be additive; use published
+contributions or current-dollar shares where appropriate.
+
+### Federal Reserve and FRED/ALFRED
+
+- [FRED API documentation](https://fred.stlouisfed.org/docs/api/fred/) describes
+ v2 bulk release history and v1 series-level FRED/ALFRED access.
+- A registered key is required under the
+ [FRED API Terms](https://fred.stlouisfed.org/docs/api/terms_of_use.html).
+ The reviewed terms do not state one fixed numerical request ceiling; they
+ reserve the right to impose or change limits.
+- The terms warn that third parties may own series and impose additional
+ restrictions. Follow the original producer's rights and attribution.
+- FRED normally presents latest values; ALFRED preserves real-time vintages.
+ Record source, release, series ID, frequency, units, seasonal adjustment,
+ notes, and vintage dates.
+
+## International and harmonized sources
+
+### World Bank
+
+The [Indicators API documentation](https://datahelpdesk.worldbank.org/knowledgebase/articles/889392-about-the-indicators-api-documentation)
+states that v2 is current, v1 is discontinued, and API authentication is not
+required. Preserve indicator code, database/source, source note, source
+organization, unit, income/region classification vintage, and retrieval date.
+The [WDI catalog](https://datacatalog.worldbank.org/search/dataset/0037712/world-development-indicators)
+publishes metadata and revision-history resources. A World Bank indicator may
+originate with a national agency or another international organization; retain
+that lineage.
+
+### International Monetary Fund
+
+The [IMF Data API page](https://data.imf.org/en/Resource-Pages/IMF-API) states
+that IMF data are available through SDMX 2.1 and SDMX 3.0 APIs. Use the
+dataset's data structure, codelists, unit, scale, frequency, observation status,
+and methodological metadata. Do not assume similarly named indicators across
+IMF datasets have identical definitions.
+
+### OECD
+
+The [OECD Data Explorer API guide](https://www.oecd.org/en/data/insights/data-explainers/2024/09/api.html),
+published 2025-04-30, describes the SDMX API, free access subject to OECD terms,
+and rate limiting without publishing one universal numerical ceiling on that
+page. It warns that omitting a dataflow version selects the latest version and
+that later structures may not be backward compatible. Store agency, dataset,
+dataflow version, dimensions, codes, attributes, and query.
+
+### Eurostat
+
+The [Eurostat API introduction](https://ec.europa.eu/eurostat/web/user-guides/data-browser/api-data-access/api-introduction)
+documents Statistics, SDMX 2.1, SDMX 3.0, catalogue, and asynchronous services.
+It states that datasets are updated twice daily when changes are available and
+that the database contains only the latest version, without past-version
+documentation. Preserve the retrieved file and update timestamp when a
+reproducible vintage matters.
+
+The [ESS quality and metadata handbook](https://ec.europa.eu/eurostat/web/products-manuals-and-guidelines/-/ks-gq-21-021)
+is a standard for reporting source, process, quality, and metadata. Record flags,
+breaks, seasonal adjustment, units, NUTS/geography version, and dataset code.
+
+### Other national statistical agencies
+
+Use the relevant country's official agency before secondary compilations.
+Examples of current first-party interfaces:
+
+- [Statistics Canada Web Data Service](https://www.statcan.gc.ca/en/developers/wds/user-guide)
+ provides data and metadata. Guide revision 1.6 (2025-01-24) documents a
+ 50-request/second server limit and 25-request/second individual IP limit, and
+ possible HTTP 409 responses during update windows.
+- The [UK ONS Developer Hub](https://developer.ons.gov.uk/) describes an open,
+ no-key beta API. It warns that breaking changes can occur; store dataset,
+ edition, and version because new versions reflect corrections, revisions, or
+ new data.
+
+For any country, confirm:
+
+1. the official statistics producer and legal mandate;
+2. release calendar, methodology, quality statement, and revision policy;
+3. classification and geography versions;
+4. API/download terms and current operational limits;
+5. whether the dataset is official, experimental, modeled, or an administrative
+ extract.
+
+## Industry and product classifications
+
+- [NAICS](https://www.census.gov/naics) classifies establishments by primary
+ economic activity; it is not itself a product-market definition.
+- [NACE Rev. 2.1](https://ec.europa.eu/eurostat/web/products-eurostat-news/w/wdn-20250624-1)
+ began feeding European statistics from 2025. Use the 2025 manual and
+ correspondence tables when comparing Rev. 2 and Rev. 2.1.
+- Product classifications (NAPCS, CPA, PRODCOM, CPC, HS/CN) may fit market
+ outputs better than an establishment-based industry code.
+- A concordance can be one-to-many or many-to-many. Never apply it as a
+ lossless conversion without weights and uncertainty.
+
+## API handling rules
+
+- Use APIs only during research, with user-approved network access.
+- Keep credentials outside reports and scripts; never commit keys.
+- Respect official terms, user-agent requirements, rate limits, retries, and
+ bulk-download guidance.
+- Cache lawful downloads, record the exact query and retrieval time, and avoid
+ repeatedly requesting unchanged data.
+- Validate response status, metadata, units, flags, suppression, and missing
+ values before analysis.
+- Treat current limits in this file as a dated snapshot, not a permanent
+ entitlement.
diff --git a/skills/market-research-reports/references/report_structure_guide.md b/skills/market-research-reports/references/report_structure_guide.md
index 8dd41077..fc9465fb 100644
--- a/skills/market-research-reports/references/report_structure_guide.md
+++ b/skills/market-research-reports/references/report_structure_guide.md
@@ -1,999 +1,283 @@
-# Market Research Report Structure Guide
+# Market Research Report Structure
-Detailed guidance for writing each section of a comprehensive market research report.
+Match the report to the decision and available evidence. There is no required
+page count, chapter count, figure count, or output format. Omit irrelevant
+modules and expand methods/limitations when uncertainty is high.
----
+## Front matter
-## Front Matter
+### Title and scope
-### Cover Page
+Include:
-**Purpose:** Create a strong first impression and communicate report scope.
+- market and geography;
+- historical and forecast periods;
+- retrieval cutoff;
+- report version and classification;
+- sponsor, author, and material conflicts;
+- explicit statement that the report is not investment, legal, or financial
+ advice.
-**Required Elements:**
-- Report title (clear, specific to market being analyzed)
-- Subtitle (e.g., "Comprehensive Market Analysis Report")
-- Hero visualization (executive summary infographic or market-relevant image)
-- Date of publication
-- Prepared by / Author organization
-- Classification (Confidential, Internal Use, Public)
-- Report type identifier
+Do not use logos, layouts, or wording that imply affiliation with another firm.
-**Best Practices:**
-- Title should include market name and geography if relevant
-- Use professional, high-quality hero image
-- Keep design clean and uncluttered
-- Include version number if applicable
+### Executive synopsis
----
+Write last. It should stand alone and contain:
-### Table of Contents
+1. decision context;
+2. formal market boundary in one sentence;
+3. highest-confidence findings with claim IDs;
+4. top-down and bottom-up scenario range;
+5. forecast scenario range and principal sensitivity;
+6. material conflicts and limitations;
+7. implications or options clearly labeled as judgment.
-**Auto-generated in LaTeX.** Ensure all chapters, sections, and subsections use proper commands for inclusion.
+Never introduce a metric in the synopsis that is absent from the evidence and
+claims ledgers.
-**Include:**
-- List of Figures (all visualizations with page numbers)
-- List of Tables (all data tables with page numbers)
+## 1. Scope and definitions
----
+Define:
-### Executive Summary (2-3 pages)
+- product/service inclusion and exclusion;
+- customer, payer, user, and transaction;
+- value-chain level;
+- geography, imports/exports, and channels;
+- time basis and as-of date;
+- measure, unit, and denominator;
+- stock/flow and gross/net treatment;
+- currency, base year, and nominal/real basis;
+- industry and product classifications with versions;
+- adjacent markets that are excluded.
-**Purpose:** Provide a standalone summary that allows busy executives to understand key findings without reading the full report.
+Explain alternate plausible definitions and why one was selected. An industry
+classification is not automatically a product market or an antitrust market.
-**Required Sections:**
+## 2. Evidence and methods
-#### Market Snapshot Box
-Key metrics displayed prominently:
-- Current market size with year
-- Projected market size with year
-- CAGR (compound annual growth rate)
-- Largest segment and market share
-- Fastest growing region and growth rate
-- Key adoption/penetration metrics
+Describe:
-#### Investment Thesis / Why This Matters
-3-5 bullet points explaining:
-- Why this market is attractive
-- Key factors driving opportunity
-- Timing considerations
-- Risk-adjusted assessment
+- source hierarchy and search cutoff;
+- original data producers and aggregator lineage;
+- exact claim-source mapping;
+- archived snapshots and revision handling;
+- extraction, cleaning, joins, conversions, and calculations;
+- source conflicts and reconciliation rules;
+- confidence labels;
+- primary-research methods and privacy controls;
+- missing evidence and analysis deviations.
-#### Key Findings Summary
-Organized by theme:
-- Market Dynamics (2-3 points)
-- Competitive Landscape (2-3 points)
-- Growth Drivers (2-3 points)
-- Risk Factors (2-3 points)
+Summarize the source ledger by source type and revision status. Do not inflate
+source count by counting mirrors or derivative articles as independent.
-#### Strategic Recommendations
-Top 5 actionable recommendations, each with:
-- Clear action statement
-- Expected outcome
-- Priority level (immediate, near-term, medium-term)
+## 3. Market size
-**Visual Requirements:**
-- 1-2 visuals maximum
-- Executive summary infographic strongly recommended
-- Key metrics visualization
+### Top-down
-**Writing Guidelines:**
-- Write this section LAST after completing all analysis
-- Every statement should be supported by analysis in the main report
-- Use specific numbers, not vague qualifiers
-- Lead with most important findings
-- Keep paragraphs short (2-4 sentences)
+Show:
----
+- control total and definition;
+- disjoint components and coverage keys;
+- in-scope fractions;
+- channel/tax/trade adjustments;
+- source IDs and limitations;
+- resulting TAM scenarios.
-## Core Analysis Chapters
+### Bottom-up
-### Chapter 1: Market Overview & Definition (4-5 pages)
+Show:
-**Purpose:** Establish clear boundaries and context for the analysis.
+- population or installed base;
+- customer segments;
+- annual units or transactions;
+- price/spend assumptions;
+- addressable fractions;
+- source and assumption IDs;
+- resulting TAM scenarios.
-#### Section 1.1: Market Definition
+### SAM and SOM
-**Content Requirements:**
-- Precise definition of the market being analyzed
-- Products/services included in scope
-- Products/services explicitly excluded
-- Industry classification codes (NAICS, SIC, GICS if applicable)
-- Relationship to adjacent markets
+For each scenario, state:
-**Writing Approach:**
-- Begin with a clear, one-paragraph definition
-- Use a callout box to highlight the formal definition
-- Explain the rationale for scope decisions
-- Address common misconceptions about market boundaries
-
-#### Section 1.2: Scope and Boundaries
-
-**Cover:**
-- Geographic scope (global, regional, specific countries)
-- Product/service scope with specific categories
-- Time horizon (historical period + forecast period)
-- Customer segments included
-
-#### Section 1.3: Industry Ecosystem
-
-**Content Requirements:**
-- Value chain from inputs to end users
-- Key stakeholders at each stage
-- Relationships and dependencies between stakeholders
-- Information flows
-- Money flows
-- Power dynamics
-
-**Required Visual:** Industry ecosystem/value chain diagram
-
-**Writing Approach:**
-- Start with overview of the ecosystem
-- Describe each stakeholder category in detail
-- Explain how value is created and captured
-- Identify where power concentrates in the value chain
-
-#### Section 1.4: Market Structure
-
-**Content Requirements:**
-- Market concentration analysis (HHI, CR4, CR8)
-- Industry lifecycle stage assessment
-- Market fragmentation analysis
-- Vertical integration analysis
-
-#### Section 1.5: Historical Context
-
-**Content Requirements:**
-- When the market emerged
-- Key milestones in market development
-- Major disruptions and shifts
-- Evolution of competitive dynamics
-- How customer needs have changed
-
-**Required Visuals (2 total):**
-1. Industry ecosystem diagram
-2. Market structure or industry lifecycle diagram
-
----
-
-### Chapter 2: Market Size & Growth Analysis (6-8 pages)
-
-**Purpose:** Provide comprehensive quantitative analysis of market opportunity.
-
-#### Section 2.1: Total Addressable Market (TAM)
-
-**Content Requirements:**
-- Current market size with source and methodology
-- Historical market size (5-10 years back)
-- Projected market size (5-10 years forward)
-- Year-over-year growth rates
-- CAGR (historical and projected)
-
-**Data Table Required:**
-Year-by-year market projections table showing:
-- Year
-- Market size (USD)
-- YoY growth rate
-- Cumulative CAGR
+- serviceability filters;
+- capture-share assumptions;
+- time horizon;
+- capacity, channel, sales-cycle, retention, and competition constraints;
+- source evidence and analyst assumptions.
-**Writing Approach:**
-- State the bottom line first (total opportunity)
-- Provide historical context
-- Explain projection methodology
-- State key assumptions
-- Cite multiple sources where possible
+Present TAM/SAM/SOM as conditional scenarios. Do not select one estimate merely
+because it is the midpoint.
-#### Section 2.2: Serviceable Addressable Market (SAM)
+### Reconciliation and sensitivity
-**Content Requirements:**
-- Definition of SAM for this market
-- SAM calculation methodology
-- Segment breakdown within SAM
-- Growth rates by segment
-
-**Data Table Required:**
-Segment analysis table showing:
-- Segment name
-- 2024 value
-- 2034 value
-- CAGR
-- Market share
-
-#### Section 2.3: Serviceable Obtainable Market (SOM)
-
-**Content Requirements:**
-- Realistic market share scenarios
-- Conservative estimate with assumptions
-- Base case estimate with assumptions
-- Optimistic estimate with assumptions
-- Factors affecting market share capture
-
-**Required Visual:** TAM/SAM/SOM concentric circles diagram
-
-#### Section 2.4: Regional Market Analysis
-
-**Content Requirements:**
-- Market size by region
-- Growth rates by region
-- Regional market share
-- Regional drivers and differences
-- Detailed analysis of top 3-4 regions
-
-**Required Visual:** Regional breakdown chart (pie or treemap)
-
-**Regions to cover:**
-- North America (with US/Canada breakdown if relevant)
-- Europe (with key country breakdown)
-- Asia-Pacific (with China, Japan, India focus)
-- Latin America
-- Middle East & Africa
-
-#### Section 2.5: Segment Analysis
-
-**Content Requirements:**
-- Definition of market segments
-- Size of each segment
-- Growth rate of each segment
-- Key drivers for each segment
-- Competitive dynamics by segment
-
-**Required Visual:** Segment growth comparison chart
-
-**Required Visuals (4 total):**
-1. Market growth trajectory chart
-2. TAM/SAM/SOM diagram
-3. Regional breakdown chart
-4. Segment growth comparison chart
-
----
-
-### Chapter 3: Industry Drivers & Trends (5-6 pages)
-
-**Purpose:** Identify and analyze factors driving market growth and evolution.
-
-#### Section 3.1: Primary Growth Drivers
+Report:
-**Content Requirements:**
-- Identification of 5-10 key growth drivers
-- Quantified impact assessment for each
-- Timeline for impact
-- Evidence and data supporting each driver
-
-**For each driver, include:**
-- Clear description
-- Mechanism of impact on market
-- Quantified impact estimate
-- Timeline (immediate, 1-3 years, 3-5 years)
-- Supporting data/evidence
-
-**Required Visual:** Driver impact matrix (probability vs. impact)
-
-#### Section 3.2: PESTLE Analysis
-
-Comprehensive analysis of external factors:
-
-**Political:**
-- Government policies affecting the market
-- Political stability in key markets
-- Trade policies and tariffs
-- Government support programs
-
-**Economic:**
-- Economic growth trends
-- Interest rate environment
-- Inflation impacts
-- Currency effects
-- Consumer spending trends
-
-**Social:**
-- Demographic trends
-- Cultural shifts
-- Consumer behavior changes
-- Workforce trends
-- Health and wellness trends
-
-**Technological:**
-- Enabling technologies
-- Digital transformation
-- Automation trends
-- Technology adoption curves
-
-**Legal:**
-- Regulatory requirements
-- Compliance costs
-- Intellectual property considerations
-- Employment regulations
-
-**Environmental:**
-- Sustainability requirements
-- Environmental regulations
-- Climate impacts
-- Resource availability
-
-**Required Visual:** PESTLE analysis diagram
-
-#### Section 3.3: Emerging Trends
-
-**Content Requirements:**
-- Identification of 5-8 emerging trends
-- Timeline for each trend
-- Expected impact on market
-- Companies/regions leading each trend
-
-**Required Visual:** Trends timeline or radar chart
-
-#### Section 3.4: Growth Inhibitors
-
-**Content Requirements:**
-- Factors slowing market growth
-- Barriers to adoption
-- Resource constraints
-- Competitive pressures
-- Regulatory hurdles
-
-**Required Visuals (3 total):**
-1. Driver impact matrix
-2. PESTLE analysis diagram
-3. Trends timeline
-
----
-
-### Chapter 4: Competitive Landscape (6-8 pages)
-
-**Purpose:** Provide comprehensive analysis of competitive dynamics.
-
-#### Section 4.1: Market Structure Analysis
-
-**Content Requirements:**
-- Number of competitors
-- Market concentration (HHI index)
-- CR4 and CR8 ratios
-- Market fragmentation assessment
-- Competitive intensity rating
-
-#### Section 4.2: Porter's Five Forces Analysis
-
-**For each force, provide:**
-- Rating: High / Medium / Low
-- Key factors driving the rating
-- Supporting evidence
-- Strategic implications
-
-**Forces:**
-1. Threat of New Entrants
-2. Bargaining Power of Suppliers
-3. Bargaining Power of Buyers
-4. Threat of Substitutes
-5. Competitive Rivalry
-
-**Required Visual:** Porter's Five Forces diagram
-
-**Writing Approach:**
-- Rate each force clearly
-- Provide 3-5 supporting factors per force
-- Include data where available
-- Discuss strategic implications
-
-#### Section 4.3: Market Share Analysis
-
-**Content Requirements:**
-- Top 10 companies by market share
-- Market share trends (3-5 year view)
-- Share gains/losses by company
-- Regional market share variations
-
-**Required Visual:** Market share pie chart or bar chart
-
-**Data Table Required:**
-Top 10 companies showing:
-- Rank
-- Company name
-- Revenue/market size
-- Market share %
-- YoY growth/trend
-
-#### Section 4.4: Competitive Positioning
-
-**Content Requirements:**
-- Key dimensions of competition
-- Positioning of major players
-- Competitive advantages by company
-- Strategic moves and announcements
-
-**Required Visual:** Competitive positioning matrix (2x2)
-
-**Common positioning dimensions:**
-- Market focus (niche vs. broad)
-- Solution approach (product vs. platform)
-- Price positioning (premium vs. value)
-- Geographic focus (regional vs. global)
-- Customer focus (enterprise vs. SMB)
+- absolute and percentage gap between methods;
+- definition, denominator, and coverage-key comparison;
+- corrections for double counting;
+- remaining unexplained difference;
+- sensitivity to major counts, price, penetration, serviceability, and capture;
+- switching values that change a decision.
-#### Section 4.5: Strategic Groups
+## 4. Demand and customer evidence
-**Content Requirements:**
-- Identification of strategic groups
-- Companies in each group
-- Mobility barriers between groups
-- Competitive dynamics within groups
-
-**Required Visual:** Strategic group map
-
-#### Section 4.6: Competitive Dynamics
-
-**Content Requirements:**
-- Recent M&A activity
-- Partnership announcements
-- Product launches
-- Pricing trends
-- Geographic expansion
-
-#### Section 4.7: Barriers to Entry
+Separate:
-**Content Requirements:**
-- Capital requirements
-- Regulatory barriers
-- Technology barriers
-- Brand and reputation
-- Distribution access
-- Economies of scale
-- Switching costs
+- official/administrative or transactional evidence;
+- published survey evidence;
+- original survey evidence;
+- interview/focus-group themes;
+- analyst interpretation.
-**Required Visuals (4 total):**
-1. Porter's Five Forces diagram
-2. Market share chart
-3. Competitive positioning matrix
-4. Strategic group map
-
----
-
-### Chapter 5: Customer Analysis & Segmentation (4-5 pages)
+For survey claims, include population, frame, sample method, mode, dates,
+unweighted sample, weighting, response/participation, wording, precision, and
+limitations. For interviews, include recruitment, consent, roles, mode, dates,
+coding, divergent views, and limits to generalization.
-**Purpose:** Understand customer needs, behaviors, and segment attractiveness.
+## 5. Market dynamics
-#### Section 5.1: Customer Segmentation
-
-**Content Requirements:**
-- Definition of customer segments
-- Segment sizes and market share
-- Segment characteristics
-- Segment growth rates
-
-**Required Visual:** Customer segmentation breakdown
-
-**Common segmentation approaches:**
-- By company size (Enterprise, Mid-market, SMB, Consumer)
-- By industry vertical
-- By geography
-- By buying behavior
-- By needs/use cases
-
-#### Section 5.2: Segment Attractiveness Analysis
-
-**Content Requirements:**
-- Attractiveness criteria
-- Segment scoring/ranking
-- Investment implications
-- Prioritization recommendations
-
-**Required Visual:** Segment attractiveness matrix
-
-**Attractiveness factors:**
-- Segment size
-- Growth rate
-- Profitability
-- Competitive intensity
-- Accessibility
-- Strategic fit
-
-#### Section 5.3: Customer Needs Analysis
-
-**For each segment, identify:**
-- Functional needs (what the product must do)
-- Emotional needs (how it makes them feel)
-- Social needs (how it affects their relationships)
-- Key pain points
-- Unmet needs
+For each driver or inhibitor:
-#### Section 5.4: Buying Behavior
+- state the mechanism;
+- identify observed evidence versus assumption;
+- quantify only with a defensible calculation;
+- define time horizon and leading indicators;
+- include disconfirming evidence;
+- state how it changes a scenario input.
-**Content Requirements:**
-- Purchase triggers
-- Decision-making process
-- Key decision makers and influencers
-- Evaluation criteria
-- Purchase channels
-- Buying cycle length
-- Price sensitivity
+Frameworks such as PESTLE or SWOT may organize questions but are not evidence.
+Use them only when useful, and do not force a fixed number of factors or scores.
-#### Section 5.5: Customer Journey
+## 6. Competitive landscape
-**Required Visual:** Customer journey map
+### Scope
-**Journey stages to cover:**
-1. Awareness
-2. Consideration
-3. Decision
-4. Implementation/Onboarding
-5. Usage
-6. Advocacy/Renewal
+Define the product and geographic basis from the customer perspective. Consider
+substitutability, non-price dimensions, channels, imports, digital/multi-sided
+features, innovation, and dynamic change where relevant.
-**Required Visuals (3 total):**
-1. Customer segmentation breakdown
-2. Segment attractiveness matrix
-3. Customer journey map
+### Competitor set
----
+State inclusion rules. Distinguish:
-### Chapter 6: Technology & Innovation Landscape (4-5 pages)
+- current direct competitors;
+- adjacent/substitute providers;
+- potential entrants;
+- channel partners or suppliers;
+- unknown/private participants.
-**Purpose:** Analyze technology trends and innovation dynamics.
+### Feature and positioning evidence
-#### Section 6.1: Current Technology Stack
-
-**Content Requirements:**
-- Core technologies in use
-- Infrastructure requirements
-- Integration landscape
-- Technology maturity levels
+Use the validated matrix with product edition, geography, date, status, and
+source IDs. Publish scoring rules for any positioning map. Use `unknown` when
+evidence is absent.
-#### Section 6.2: Technology Roadmap
+### Shares and concentration
-**Content Requirements:**
-- Near-term evolution (1-2 years)
-- Medium-term evolution (3-5 years)
-- Long-term evolution (5-10 years)
-- Key milestones and inflection points
+State numerator and denominator, metric, period, coverage, residual share, and
+alternate definitions. Treat HHI/CRn as descriptive screens. Do not make legal
+antitrust conclusions.
-**Required Visual:** Technology roadmap diagram
+## 7. Forecast scenarios
-#### Section 6.3: Emerging Technologies
+### Historical basis
-**For each emerging technology, cover:**
-- Technology description
-- Current maturity level (TRL or similar)
-- Expected timeline to mainstream
-- Potential impact on market
-- Leading companies/regions
+Show series IDs, units, frequency, seasonal adjustment, revisions, taxonomy
+breaks, transformations, and vintage.
-**Common emerging technologies to assess:**
-- Artificial intelligence/ML
-- Cloud computing
-- IoT/Connected devices
-- Blockchain
-- Automation/Robotics
-- Domain-specific technologies
+### Scenario design
-#### Section 6.4: Innovation Trends
+For each named scenario, document:
-**Content Requirements:**
-- R&D investment levels in industry
-- Patent filing trends
-- Startup activity and funding
-- Corporate innovation initiatives
-- University/research partnerships
+- annual rate path or driver equations;
+- demand, price, supply, regulation, competition, and capacity assumptions;
+- evidence and assumption IDs;
+- constraints and internal consistency;
+- conditions that would make the scenario obsolete.
-**Required Visual:** Innovation/adoption curve or hype cycle
+Do not assign probabilities without a defensible probabilistic model. Do not
+call scenario bounds confidence or prediction intervals.
-#### Section 6.5: Technology Adoption Barriers
+### Sensitivity
-**Content Requirements:**
-- Technical complexity
-- Integration challenges
-- Cost barriers
-- Skills gaps
-- Security/privacy concerns
-- Change management challenges
+Report endpoints under stated input shifts, rank influential assumptions, and
+identify decision thresholds. If interactions matter, add coherent combined
+scenarios rather than relying only on one-way sensitivity.
-**Required Visuals (2 total):**
-1. Technology roadmap diagram
-2. Innovation/adoption curve
+## 8. Regulation and policy
----
+Use primary regulator and legal sources. Record:
-### Chapter 7: Regulatory & Policy Environment (3-4 pages)
+- jurisdiction and authority;
+- instrument or docket identifier;
+- publication, adoption, and effective dates;
+- enacted/proposed/stayed/repealed status;
+- affected products and entities;
+- evidence-backed market mechanism;
+- uncertainty and need for legal review.
-**Purpose:** Analyze regulatory framework and policy impacts.
+Do not present a policy proposal as effective law or compliance interpretation
+as legal advice.
-#### Section 7.1: Current Regulatory Framework
+## 9. Risks, implications, and options
-**Content Requirements:**
-- Key regulations affecting the market
-- Regulatory bodies and their roles
-- Compliance requirements
-- Enforcement mechanisms
-- Penalties for non-compliance
+Separate:
-#### Section 7.2: Regulatory Timeline
+- observed risk indicator;
+- likelihood judgment;
+- impact mechanism;
+- exposure and time horizon;
+- early-warning measure;
+- mitigation or option;
+- residual uncertainty.
-**Required Visual:** Regulatory timeline
+Tie recommendations to explicit objectives and findings. Include dependencies,
+trade-offs, owner, timing, and evidence that would trigger revision. A
+recommendation is judgment, not a sourced fact.
-**Content Requirements:**
-- Historical regulatory milestones
-- Recent regulatory changes
-- Upcoming regulations
-- Expected future developments
+## 10. Limitations
-#### Section 7.3: Regulatory Impact Analysis
+Consolidate:
-**Content Requirements:**
-- Compliance costs
-- Market access implications
-- Competitive implications
-- Product/service requirements
-- Operating restrictions
+- data gaps and source conflicts;
+- paid or inaccessible evidence not verified;
+- classification and scope mismatch;
+- currency/base-year and conversion limits;
+- stock/flow or denominator uncertainty;
+- revisions and historical breaks;
+- imputation, suppression, survey, and interview limitations;
+- competitor evidence gaps;
+- forecast/model uncertainty;
+- sponsor and analyst conflicts.
-#### Section 7.4: Policy Trends
+## Appendices
-**Content Requirements:**
-- Government priorities
-- Funding initiatives
-- Trade policies
-- Environmental policies
-- Industry-specific policies
+Include as needed:
-#### Section 7.5: Regional Regulatory Differences
+- source/evidence ledger;
+- claims ledger;
+- calculation and assumption register;
+- unit/currency/base-year conversion table;
+- market-sizing inputs and outputs;
+- forecast and sensitivity inputs and outputs;
+- competitor-feature matrix;
+- survey instrument and methodology disclosure;
+- interview guide and de-identified coding framework;
+- revision log;
+- machine-readable local files.
-**Content Requirements:**
-- Comparison of regulations by region
-- Harmonization efforts
-- Key differences to navigate
-- Best practices for compliance
+## Release gate
-**Required Visuals (1 total):**
-1. Regulatory timeline
-
----
-
-### Chapter 8: Risk Analysis (3-4 pages)
-
-**Purpose:** Identify, assess, and propose mitigations for key risks.
-
-#### Section 8.1: Risk Overview
-
-**Content Requirements:**
-- Risk categories covered
-- Risk assessment methodology
-- Overall risk profile assessment
-
-#### Section 8.2: Risk Assessment
-
-**Required Visual:** Risk heatmap (probability vs. impact)
-
-**Risk categories to cover:**
-- Market risks
-- Competitive risks
-- Regulatory risks
-- Technology risks
-- Operational risks
-- Financial risks
-- Reputational risks
-
-**For each risk, include:**
-- Risk description
-- Probability rating (Low/Medium/High)
-- Impact rating (Low/Medium/High)
-- Overall risk rating
-- Contributing factors
-- Early warning indicators
-
-**Data Table Required:**
-Risk register showing:
-- Risk name
-- Category
-- Probability
-- Impact
-- Overall rating
-- Owner
-
-#### Section 8.3: Detailed Risk Analysis
-
-Provide detailed analysis of top 5-10 risks, including:
-- Full description of the risk
-- Scenarios that could trigger it
-- Potential consequences
-- Affected stakeholders
-- Timeline considerations
-
-#### Section 8.4: Risk Mitigation Strategies
-
-**Required Visual:** Risk mitigation matrix
-
-**For each major risk, provide:**
-- Prevention strategies
-- Detection mechanisms
-- Response plans
-- Recovery approaches
-- Contingency plans
-
-**Required Visuals (2 total):**
-1. Risk heatmap
-2. Risk mitigation matrix
-
----
-
-## Strategic Recommendations Chapters
-
-### Chapter 9: Strategic Opportunities & Recommendations (4-5 pages)
-
-**Purpose:** Synthesize analysis into actionable strategic guidance.
-
-#### Section 9.1: Opportunity Analysis
-
-**Required Visual:** Opportunity matrix (attractiveness vs. ability to win)
-
-**Content Requirements:**
-- Identification of 5-8 strategic opportunities
-- Sizing of each opportunity
-- Attractiveness assessment
-- Ability to win assessment
-- Prioritization
-
-#### Section 9.2: Detailed Opportunity Analysis
-
-For each top opportunity, provide:
-- Description and scope
-- Market size potential
-- Growth trajectory
-- Key success factors
-- Required capabilities
-- Investment requirements
-- Expected returns
-- Timeline to value
-
-#### Section 9.3: Strategic Options Analysis
-
-**Content Requirements:**
-- Build (organic development) options
-- Buy (M&A) options
-- Partner (strategic alliances) options
-- Decision framework for each opportunity
-
-#### Section 9.4: Prioritized Recommendations
-
-**Required Visual:** Recommendation priority matrix (impact vs. effort)
-
-**Structure recommendations in tiers:**
-
-**Tier 1: Immediate Priority**
-- Actions to take in next 0-6 months
-- Quick wins with high impact
-- Foundation-setting activities
-
-**Tier 2: Near-Term (6-12 months)**
-- Build on Tier 1 actions
-- Larger investments
-- Capability development
-
-**Tier 3: Medium-Term (1-2 years)**
-- Strategic initiatives
-- Major investments
-- Transformational changes
-
-**For each recommendation:**
-- Clear action statement
-- Rationale (why this matters)
-- Expected outcome
-- Investment required
-- Timeline
-- Success metrics
-- Dependencies
-
-#### Section 9.5: Success Factors
-
-**Content Requirements:**
-- Critical success factors for implementation
-- Organizational capabilities required
-- Resource requirements
-- External dependencies
-- Timing considerations
-
-**Required Visuals (3 total):**
-1. Opportunity matrix
-2. Strategic options framework
-3. Recommendation priority matrix
-
----
-
-### Chapter 10: Implementation Roadmap (3-4 pages)
-
-**Purpose:** Provide actionable implementation guidance.
-
-#### Section 10.1: Implementation Overview
-
-**Content Requirements:**
-- Phased approach description
-- Overall timeline
-- Key dependencies
-- Critical path items
-
-#### Section 10.2: Phased Implementation Plan
-
-**Required Visual:** Implementation timeline/Gantt chart
-
-**For each phase:**
-- Phase name and duration
-- Objectives
-- Key activities
-- Deliverables
-- Resources required
-- Dependencies
-- Success criteria
-
-**Typical phases:**
-- Phase 1: Foundation (months 1-6)
-- Phase 2: Build (months 4-12)
-- Phase 3: Scale (months 10-18)
-- Phase 4: Optimize (months 16-24)
-
-#### Section 10.3: Key Milestones
-
-**Required Visual:** Milestone tracker
-
-**Data Table Required:**
-Milestone table showing:
-- Milestone name
-- Target date
-- Owner
-- Success criteria
-- Dependencies
-
-#### Section 10.4: Resource Requirements
-
-**Content Requirements:**
-- Team structure and roles
-- Budget allocation by phase
-- Technology requirements
-- External support needs
-- Training requirements
-
-#### Section 10.5: Governance Structure
-
-**Content Requirements:**
-- Decision-making authority
-- Reporting structure
-- Review cadence
-- Escalation paths
-- Change management process
-
-**Required Visuals (2 total):**
-1. Implementation timeline/Gantt
-2. Milestone tracker
-
----
-
-### Chapter 11: Investment Thesis & Financial Projections (3-4 pages)
-
-**Purpose:** Provide financial framework for decision-making.
-
-#### Section 11.1: Investment Summary
-
-**Content Requirements:**
-- Summary of investment opportunity
-- Key value drivers
-- Expected returns
-- Investment timeline
-- Risk-adjusted assessment
-
-#### Section 11.2: Financial Projections
-
-**Required Visual:** Financial projections chart
-
-**Data Table Required:**
-5-year projections showing:
-- Revenue
-- Growth rate
-- Gross margin
-- EBITDA
-- EBITDA margin
-- Key operating metrics
-
-#### Section 11.3: Scenario Analysis
-
-**Required Visual:** Scenario comparison chart
-
-**Three scenarios:**
-- Conservative: Lower growth, higher costs
-- Base Case: Expected performance
-- Optimistic: Favorable conditions
-
-**For each scenario:**
-- Key assumptions
-- Revenue projections
-- Profitability projections
-- Investment requirements
-- Return metrics
-
-#### Section 11.4: Key Assumptions
-
-**Document all assumptions:**
-- Market growth assumptions
-- Market share assumptions
-- Pricing assumptions
-- Cost assumptions
-- Timing assumptions
-- Competitive assumptions
-
-#### Section 11.5: Sensitivity Analysis
-
-**Content Requirements:**
-- Key variables affecting returns
-- Sensitivity to market growth
-- Sensitivity to pricing
-- Sensitivity to timing
-- Break-even analysis
-
-#### Section 11.6: Return Expectations
-
-**Content Requirements:**
-- ROI projections
-- Payback period
-- IRR estimates
-- NPV analysis
-- Multiple analysis (if applicable)
-
-**Required Visuals (2 total):**
-1. Financial projections chart
-2. Scenario comparison chart
-
----
-
-## Back Matter
-
-### Appendix A: Methodology & Data Sources
-
-**Content Requirements:**
-- Research methodology description
-- Primary research methods
-- Secondary research sources
-- Data collection timeframe
-- Analytical frameworks used
-- Limitations and assumptions
-
-### Appendix B: Detailed Market Data
-
-**Content Requirements:**
-- Comprehensive data tables
-- Year-by-year market data
-- Regional breakdowns
-- Segment details
-- Historical data series
-
-### Appendix C: Company Profiles
-
-**For each major company:**
-- Company overview
-- Headquarters and key locations
-- Revenue and employee count
-- Market position
-- Key products/services
-- Recent developments
-- Strategic focus
-
-### References/Bibliography
-
-**All sources cited:**
-- Market research reports
-- Industry publications
-- Government data
-- Company reports
-- Academic sources
-- News articles
-
----
-
-## Quality Checklist
-
-Before finalizing, verify:
-
-- [ ] All required sections are complete
-- [ ] All data points have sources
-- [ ] All 25-30 visuals are included
-- [ ] Executive summary captures key findings
-- [ ] Recommendations are actionable
-- [ ] Financial projections are internally consistent
-- [ ] No placeholder content remains
-- [ ] Page count exceeds 50 pages
-- [ ] Table of contents is accurate
-- [ ] All cross-references work
-- [ ] Bibliography is complete
+- Scope and denominator are explicit and consistent.
+- Every factual or quantitative claim maps to source IDs.
+- Calculations map to inputs and assumptions.
+- Publication/retrieval dates and revisions are recorded.
+- Monetary values identify currency, base year, and price basis.
+- Stock/flow, units, taxonomy, and denominator are explicit.
+- Top-down/bottom-up methods are reconciled without double counting.
+- TAM/SAM/SOM and forecasts are conditional scenarios with sensitivity.
+- Survey and interview evidence carries full method and privacy disclosures.
+- Competitor evidence is lawful, dated, and does not infer `no` from `unknown`.
+- Conflicts and limitations remain visible.
+- No unsupported paid-market figures, fabricated citations, PII, trade secrets,
+ deceptive collection, brand impersonation, or investment-advice framing.
diff --git a/skills/market-research-reports/references/sources.md b/skills/market-research-reports/references/sources.md
new file mode 100644
index 00000000..bff4ae07
--- /dev/null
+++ b/skills/market-research-reports/references/sources.md
@@ -0,0 +1,73 @@
+# Dated Source Ledger
+
+Research cutoff and retrieval date: **2026-07-23**.
+
+Sources were located and checked with focused `parallel-cli search` queries and
+canonical-page `parallel-cli extract` calls. Only first-party or primary
+methodological sources are listed below. Dates are publication, document, or
+last-revised dates stated by the source; `not stated` is used rather than
+guessing.
+
+## Corporate filings and U.S. official data
+
+| ID | Authority | Source and date | Use |
+|---|---|---|---|
+| SRC-SEC-ACCESS | U.S. SEC | [Accessing EDGAR Data](https://www.sec.gov/search-filings/edgar-search-assistance/accessing-edgar-data), published 2021-03-23; updated 2024-06-26 | EDGAR history, corrections, declared user agent, 10 requests/second fair-access limit |
+| SRC-SEC-DEV | U.S. SEC | [Developer Resources](https://www.sec.gov/about/developer-resources), updated 2025-03-10 | Submissions and XBRL APIs; fair-access overview |
+| SRC-CENSUS-API | U.S. Census Bureau | [Census Data API User Guide](https://www.census.gov/data/developers/guidance/api-user-guide.html), dated 2026-05-12; revised 2026-05-14 | Geography/vintage concepts and API navigation |
+| SRC-CENSUS-LIMIT | U.S. Census Bureau | [Query Limits](https://www.census.gov/data/developers/guidance/api-user-guide.Query_Limits.html), revised 2026-05-14 | 50 variables/query; key required for data queries |
+| SRC-CENSUS-KEY | U.S. Census Bureau | [API Key](https://www.census.gov/data/developers/guidance/api-user-guide.API_Key.html), revised 2026-05-14 | Current free key-registration guidance |
+| SRC-EC-METHOD | U.S. Census Bureau | [2022 Economic Census Methodology](https://www.census.gov/programs-surveys/economic-census/year/2022/technical-documentation/methodology.html), updated 2026-04-10 | Population, frame, NAICS scope, collection, administrative data, imputation, disclosure avoidance |
+| SRC-NAICS | U.S. Census Bureau | [NAICS](https://www.census.gov/naics), revised 2026-07-23 | Current 2022 structure and 2027 revision process |
+| SRC-BLS-API | U.S. Bureau of Labor Statistics | [Public Data API FAQ](https://www.bls.gov/developers/api_faqs.htm), modified 2023-08-30 | Registration, daily/rate/series/year limits, metadata behavior |
+| SRC-BEA-API | U.S. Bureau of Economic Analysis | [BEA API User Guide](https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf), 2026-04-20 | UserID, metadata calls, 100 requests/minute, 100 MB/minute, 30 errors/minute, HTTP 429/retry |
+| SRC-BEA-CHAIN | U.S. Bureau of Economic Analysis | [Chained-Dollar Indexes: Issues and Tips](https://www.bea.gov/resources/methodologies/chained-dollar-indexes), published 2003-11; page modified 2018-05-30 | Real/current measures, chain weighting, non-additivity |
+| SRC-FRED-API | Federal Reserve Bank of St. Louis | [FRED API](https://fred.stlouisfed.org/docs/api/fred/), date not stated | v1 series/ALFRED access; v2 bulk release history; metadata and vintage endpoints |
+| SRC-FRED-TERMS | Federal Reserve Bank of St. Louis | [FRED API Terms](https://fred.stlouisfed.org/docs/api/terms_of_use.html), date not stated | Key requirement, changeable limits, application notice, third-party rights |
+
+## International and national statistical systems
+
+| ID | Authority | Source and date | Use |
+|---|---|---|---|
+| SRC-WB-API | World Bank | [Indicators API Documentation](https://datahelpdesk.worldbank.org/knowledgebase/articles/889392-about-the-indicators-api-documentation), date not stated | v2 current; v1 discontinued; no API authentication; source metadata |
+| SRC-WB-WDI | World Bank | [World Development Indicators catalog](https://datacatalog.worldbank.org/search/dataset/0037712/world-development-indicators), updated 2026-07-22 | Metadata, classifications, and revision-history resources |
+| SRC-IMF-API | International Monetary Fund | [IMF Data APIs](https://data.imf.org/en/Resource-Pages/IMF-API), page dated 2026 | SDMX 2.1 and 3.0 access |
+| SRC-IMF-SDMX | International Monetary Fund | [IMF SDMX Central Web Services Guide](https://dsbb.imf.org/content/pdfs/IMFSDMXCentralWebServicesGuide.pdf), updated 2025-05 | Structures, codelists, schemas, and SDMX services |
+| SRC-OECD-API | OECD | [OECD data via API](https://www.oecd.org/en/data/insights/data-explainers/2024/09/api.html), 2025-04-30 | SDMX syntax, dataflow version warning, formats, terms, nonnumeric rate-limiting statement |
+| SRC-OECD-SUT | OECD | [Supply and Use Tables](https://www.oecd.org/en/data/datasets/supply-and-use-tables.html), date not stated | Product/industry supply-use framework and origin/use of goods and services |
+| SRC-EUROSTAT-API | Eurostat | [API Introduction](https://ec.europa.eu/eurostat/web/user-guides/data-browser/api-data-access/api-introduction), date not stated | Statistics/SDMX services, formats, twice-daily updates, latest-version-only caveat |
+| SRC-ESS-QUALITY | Eurostat | [ESS Handbook for Quality and Metadata Reports](https://ec.europa.eu/eurostat/web/products-manuals-and-guidelines/-/ks-gq-21-021), 2021-12-09 | Standardized quality and metadata reporting |
+| SRC-NACE | Eurostat | [NACE Rev. 2.1 manual announcement](https://ec.europa.eu/eurostat/web/products-eurostat-news/w/wdn-20250624-1), 2025-06-24 | Current NACE manual, principles, explanatory notes, correspondence tables |
+| SRC-STATCAN-WDS | Statistics Canada | [Web Data Service User Guide](https://www.statcan.gc.ca/en/developers/wds/user-guide), revision 1.6 dated 2025-01-24 | Data/metadata service, update window, 50 server and 25 per-IP requests/second |
+| SRC-ONS-API | UK Office for National Statistics | [ONS Developer Hub](https://developer.ons.gov.uk/), date not stated; beta | Open/no-key API; dataset/edition/version and breaking-change warning |
+
+## Market definition, uncertainty, and research methods
+
+| ID | Authority | Source and date | Use |
+|---|---|---|---|
+| SRC-US-MERGER | U.S. DOJ and FTC | [2023 Merger Guidelines](https://www.ftc.gov/system/files/ftc_gov/pdf/2023_merger_guidelines_final_12.18.2023.pdf), 2023-12-18 | Relevant markets, shares, HHI, evidence, dynamic and potential competition |
+| SRC-EU-MARKET | European Commission | [Market Definition Notice](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=OJ:C_202401645), 2024-02-22 | Product/geographic scope, non-price competition, digital/dynamic markets, alternate share metrics, evidence |
+| SRC-OMB-A4 | U.S. Office of Management and Budget | [Circular A-4](https://www.whitehouse.gov/wp-content/uploads/2023/11/CircularA-4.pdf), 2023-11-09 | Evidence quality, uncertainty, sensitivity, assumptions, transparent presentation |
+| SRC-GREENBOOK | UK HM Treasury | [The Green Book 2026](https://www.gov.uk/government/publications/the-green-book-appraisal-and-evaluation-in-central-government/the-green-book-2026), 2026-03-10 | Appraisal, options, uncertainty, evidence, and transparent assumptions |
+| SRC-AAPOR-CODE | American Association for Public Opinion Research | [Code of Professional Ethics and Practices](https://aapor.org/standards-and-ethics/), revised 2026-06 | Current participant, privacy, sponsor, public, integrity, and disclosure duties |
+| SRC-AAPOR-DISC | American Association for Public Opinion Research | [Disclosure Standards](https://aapor.org/standards-and-ethics/disclosure-standards/), code approved 2021-04; page published 2022-12-02 | Sponsor, instrument, population, sample, mode, dates, weighting, precision, limitations, privacy |
+| SRC-AAPOR-BEST | AAPOR | [Best Practices for Survey Research](https://aapor.org/standards-and-ethics/best-practices/), page published 2023-01-11 | Survey design, probability/non-probability samples, wording, weighting, reporting |
+| SRC-FCSM-NR | Federal Committee on Statistical Methodology | [Best Practices for Nonresponse Bias Reporting](https://statspolicy.gov/assets/fcsm/files/docs/FCSM%20NRBA%20Report%20062623.pdf), 2023-06 | Response-rate and subgroup nonresponse-bias reporting |
+| SRC-ICSP-QUALITY | Interagency Council on Statistical Policy | [Principles for Modernizing Production of Federal Statistics](https://statspolicy.gov/assets/fcsm/files/docs/Principles-2.pdf), 2018 | Quality, transparency, and limitations for statistical/non-statistical integrated data |
+| SRC-FORCE11 | FORCE11 | [Joint Declaration of Data Citation Principles](https://force11.org/group/joint-declaration-of-data-citation-principles-final), 2014; page date not stated | Importance, credit, evidence, unique identification, access, persistence, specificity |
+| SRC-ICO-MIN | UK Information Commissioner's Office | [Data minimisation](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/data-protection-principles/a-guide-to-the-data-protection-principles/data-minimisation), updated 2025-09-09 | Collecting data adequate, relevant, and limited to purpose where UK GDPR applies |
+
+## Research query record
+
+Focused search/extract objectives covered:
+
+- SEC EDGAR, Census, BLS, BEA, FRED access, metadata, terms, and limits;
+- World Bank, IMF, OECD, Eurostat, Statistics Canada, and ONS APIs;
+- NAICS/NACE versions and classification correspondence;
+- supply-use/economic-census methods for sizing and double-count prevention;
+- U.S. and EU competition/market-definition guidance;
+- OMB and HM Treasury forecast uncertainty and sensitivity;
+- AAPOR/FCSM survey disclosure and nonresponse;
+- data citation, provenance, metadata quality, privacy, and ethical collection.
+
+No Parallel search JSON artifacts are included in the skill.
diff --git a/skills/market-research-reports/references/visual_generation_guide.md b/skills/market-research-reports/references/visual_generation_guide.md
index 2897f90b..a10d294e 100644
--- a/skills/market-research-reports/references/visual_generation_guide.md
+++ b/skills/market-research-reports/references/visual_generation_guide.md
@@ -1,1077 +1,158 @@
-# Visual Generation Guide for Market Research Reports
+# Evidence-Led Tables and Visuals
-Complete prompts and guidance for generating visualizations in market research reports.
+Visuals are optional. Add one only when it answers an analytical question more
+clearly than prose or a small table. Do not generate a fixed count, create
+decorative cover imagery by default, or call another skill or external image
+service.
----
+## Required data contract
-## Overview
+Before creating a chart, define:
-Market research reports should start with **5-6 essential visuals** to establish the analytical framework. Additional visuals can be generated as needed when writing specific sections. This guide provides ready-to-use prompts for the `scientific-schematics` and `generate-image` skills.
+- claim IDs the visual supports;
+- input source IDs and calculation ID;
+- geography, population, and coverage;
+- observed/estimated/forecast status;
+- period and retrieval cutoff;
+- currency, base year, and price basis;
+- stock/flow/count/share/rate/price/index;
+- units and denominator;
+- taxonomy and version;
+- revision status;
+- suppression, missing values, and material limitations.
-### Core Visuals (Generate First - Priority 1-6)
+Build visuals from the validated local data, never from an image prompt that
+contains unsupported numbers.
-Start every market report by generating these 5-6 core visuals:
+## Choose the smallest useful display
-1. **Market Growth Trajectory Chart** - Shows market size trends
-2. **TAM/SAM/SOM Diagram** - Market opportunity breakdown
-3. **Porter's Five Forces** - Competitive dynamics framework
-4. **Competitive Positioning Matrix** - Strategic positioning
-5. **Risk Heatmap** - Risk assessment visualization
-6. **Executive Summary Infographic** (optional) - Report overview
+| Analytical question | Preferred display |
+|---|---|
+| Exact values and metadata | Table |
+| Change over ordered time | Line or point chart |
+| Category comparison | Ordered dot or bar chart |
+| Composition with few categories | Stacked bar |
+| Distribution | Histogram, box plot, or interval plot |
+| Scenario uncertainty over time | Directly labeled range/ribbon plus paths |
+| Top-down vs bottom-up reconciliation | Side-by-side bridge or comparison table |
+| Feature availability | Evidence-linked matrix |
+| Relationship between two quantities | Scatterplot with units and caveats |
+| Process or value chain | Simple flow diagram based on verified entities |
-### Extended Visuals (Generate as Needed - Priority 7+)
+Avoid pie/donut charts for many categories, dual axes, 3-D effects, area scaling
+without explanation, radar charts for precise comparison, and unlabeled
+quadrant scores.
-Additional visuals can be generated during writing when specific sections require visual support:
-- Regional breakdown charts
-- Segment analysis
-- Customer journey maps
-- Technology roadmaps
-- Regulatory timelines
-- Financial projections
-- Implementation timelines
+## Historical and forecast data
-### Tool Selection
+- Separate observed and forecast periods with a clear boundary.
+- Use different line styles as well as color.
+- Label scenarios as conditional; do not label the outer paths as a confidence
+ interval.
+- Show revisions or vintage when they materially change the historical path.
+- Do not splice incompatible series without a break marker and explanation.
+- If a historical source ends before the forecast base year, identify the
+ bridge estimate.
-| Visual Type | Tool | Rationale |
-|-------------|------|-----------|
-| Charts (bar, line, pie) | scientific-schematics | Precise data representation |
-| Diagrams (flow, structure) | scientific-schematics | Clear technical layouts |
-| Matrices (2x2, positioning) | scientific-schematics | Strategic frameworks |
-| Timelines | scientific-schematics | Sequential information |
-| Infographics | generate-image | Creative visual synthesis |
-| Conceptual illustrations | generate-image | Abstract concepts |
+## TAM/SAM/SOM
----
+Prefer a table or nested bar chart to concentric circles because area can imply
+precision and proportionality poorly.
-## Visual Naming Convention
+Show:
-### Core Visuals (Generate First)
-```
-figures/
-├── 01_market_growth_trajectory.png # PRIORITY 1
-├── 02_tam_sam_som.png # PRIORITY 2
-├── 03_porters_five_forces.png # PRIORITY 3
-├── 04_competitive_positioning.png # PRIORITY 4
-├── 05_risk_heatmap.png # PRIORITY 5
-└── 06_exec_summary_infographic.png # PRIORITY 6 (optional)
-```
-
-### Extended Visuals (Generate as Needed)
-```
-figures/
-├── 07_industry_ecosystem.png
-├── 08_regional_breakdown.png
-├── 09_segment_growth.png
-├── 10_driver_impact_matrix.png
-├── 11_pestle_analysis.png
-├── 12_trends_timeline.png
-├── 13_market_share.png
-├── 14_strategic_groups.png
-├── 15_customer_segments.png
-├── 16_segment_attractiveness.png
-├── 17_customer_journey.png
-├── 18_technology_roadmap.png
-├── 19_innovation_curve.png
-├── 20_regulatory_timeline.png
-├── 21_risk_mitigation.png
-├── 22_opportunity_matrix.png
-├── 23_recommendation_priority.png
-├── 24_implementation_timeline.png
-├── 25_milestone_tracker.png
-├── 26_financial_projections.png
-└── 27_scenario_analysis.png
-```
-
----
-
-## CORE VISUALS (Priority 1-6) - Generate These First
-
-### Priority 1: Market Growth Trajectory Chart
-
-**Tool:** scientific-schematics
-
-**Purpose:** Foundation visual showing historical and projected market size
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Bar chart market growth 2020 to 2034. Historical bars 2020-2024 in dark blue, projected bars 2025-2034 in light blue. Y-axis billions USD, X-axis years. CAGR annotation. Data labels on each bar. Vertical dashed line between 2024 and 2025. Title: Market Growth Trajectory. Professional white background" \
- -o figures/01_market_growth_trajectory.png --doc-type report
-```
-
----
-
-### Priority 2: TAM/SAM/SOM Diagram
-
-**Tool:** scientific-schematics
-
-**Purpose:** Market opportunity sizing visualization
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "TAM SAM SOM concentric circles. Outer circle TAM Total Addressable Market. Middle circle SAM Serviceable Addressable Market. Inner circle SOM Serviceable Obtainable Market. Each labeled with acronym, full name, placeholder for dollar value. Arrows pointing to each with descriptions. Blue gradient darkest outer to lightest inner. White background professional appearance" \
- -o figures/02_tam_sam_som.png --doc-type report
-```
-
----
-
-### Priority 3: Porter's Five Forces Diagram
-
-**Tool:** scientific-schematics
-
-**Purpose:** Competitive dynamics framework
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Porter's Five Forces diagram. Center box Competitive Rivalry with rating. Four surrounding boxes with arrows to center: Top Threat of New Entrants, Left Bargaining Power Suppliers, Right Bargaining Power Buyers, Bottom Threat of Substitutes. Color code HIGH red, MEDIUM yellow, LOW green. Include 2-3 key factors per box. Professional appearance" \
- -o figures/03_porters_five_forces.png --doc-type report
-```
-
----
-
-### Priority 4: Competitive Positioning Matrix
-
-**Tool:** scientific-schematics
-
-**Purpose:** Strategic positioning of key market players
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 competitive positioning matrix. X-axis Market Focus Niche to Broad. Y-axis Solution Approach Product to Platform. Quadrants: Upper-right Platform Leaders, Upper-left Niche Platforms, Lower-right Product Leaders, Lower-left Specialists. Plot 8-10 company circles with names. Circle size = market share. Legend for sizes. Professional appearance" \
- -o figures/04_competitive_positioning.png --doc-type report
-```
-
----
-
-### Priority 5: Risk Heatmap
-
-**Tool:** scientific-schematics
-
-**Purpose:** Visual risk assessment matrix
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Risk heatmap matrix. X-axis Impact Low Medium High Critical. Y-axis Probability Unlikely Possible Likely Very Likely. Cell colors: Green low risk, Yellow medium, Orange high, Red critical. Plot 10-12 numbered risks R1 R2 etc as labeled points. Legend with risk names. Professional clear" \
- -o figures/05_risk_heatmap.png --doc-type report
-```
-
----
-
-### Priority 6: Executive Summary Infographic (Optional)
-
-**Tool:** generate-image
-
-**Purpose:** High-level visual synthesis for cover or executive summary
-
-**Command:**
-```bash
-python skills/generate-image/scripts/generate_image.py \
- "Executive summary infographic for market research, one page layout, central large metric showing market size, four quadrants showing growth rate key players top segments regional leaders, modern flat design, professional blue and green color scheme, clean white background, corporate business aesthetic" \
- --output figures/06_exec_summary_infographic.png
-```
-
----
-
-## EXTENDED VISUALS - Generate During Writing as Needed
-
-The following visuals can be generated when writing specific chapters that require them.
-
----
-
-## Front Matter Visuals
-
-### Extended: Cover Image / Hero Visual
-
-**Tool:** generate-image
-
-**Prompt:**
-```
-Professional executive summary infographic for [MARKET NAME] market research report.
-Modern data visualization style showing key metrics: market size, growth rate, key players.
-Blue and green color scheme matching corporate design.
-Clean minimalist design with icons.
-High resolution, publication quality.
-No text overlays, image only.
-```
-
-**Command:**
-```bash
-python skills/generate-image/scripts/generate_image.py \
- "Professional executive summary infographic for [MARKET] market research report, modern data visualization style, key metrics display, blue and green corporate color scheme, clean minimalist design with icons, high resolution publication quality" \
- --output figures/01_cover_image.png
-```
-
-### 2. Executive Summary Infographic
-
-**Tool:** generate-image
-
-**Prompt:**
-```
-One-page executive summary infographic showing:
-- Large central metric: $XX billion market size
-- Four quadrants with: Growth Rate, Key Players, Top Segments, Regional Leaders
-- Modern flat design with data visualization elements
-- Professional blue (#003366) and green (#008060) color scheme
-- Clean white background
-- Business/corporate aesthetic
-```
-
-**Command:**
-```bash
-python skills/generate-image/scripts/generate_image.py \
- "Executive summary infographic for market research, one page layout, central large metric showing market size, four quadrants showing growth rate key players top segments regional leaders, modern flat design, professional blue and green color scheme, clean white background, corporate business aesthetic" \
- --output figures/02_exec_summary_infographic.png
-```
-
----
-
-## Chapter 1: Market Overview Visuals
-
-### 3. Industry Ecosystem Diagram
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Industry ecosystem value chain diagram showing horizontal flow from left to right:
-[Suppliers/Inputs] → [Manufacturers/Processors] → [Distributors/Channels] → [End Users/Customers]
-
-At each stage, show 3-4 example player types in smaller boxes below.
-Use arrows to show product/service flow (solid) and money flow (dashed).
-Include regulatory bodies as oversight layer above the chain.
-Professional blue color scheme.
-Clean white background.
-All text clearly readable.
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Industry ecosystem value chain diagram. Horizontal flow left to right: Suppliers box → Manufacturers box → Distributors box → End Users box. Below each main box show 3-4 smaller boxes with example player types. Solid arrows for product flow, dashed arrows for money flow. Regulatory oversight layer above. Professional blue color scheme, white background, clear labels" \
- -o figures/03_industry_ecosystem.png --doc-type report
-```
-
-### 4. Market Structure Diagram
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Market structure diagram showing concentric rectangles:
-- Center: Core Market (labeled with market name)
-- Second layer: Adjacent Markets (labeled with 4-5 adjacent market names)
-- Third layer: Enabling Technologies (labeled with key technologies)
-- Outer layer: Regulatory Framework
-
-Use different shades of blue for each layer.
-Include small icons or labels for key elements.
-Professional appearance.
-```
+- top-down and bottom-up TAM separately;
+- SAM filters and retained share;
+- SOM capture share and horizon;
+- downside/base/upside values;
+- reconciliation gap;
+- denominator and coverage keys;
+- sensitivity to principal assumptions.
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Market structure diagram with concentric rectangles. Center: Core Market [MARKET NAME]. Second layer: Adjacent Markets with 4-5 labels. Third layer: Enabling Technologies with key tech labels. Outer layer: Regulatory Framework. Different blue shades for each layer, professional appearance, clear labels" \
- -o figures/03b_market_structure.png --doc-type report
-```
-
----
-
-## Chapter 2: Market Size & Growth Visuals
-
-### 5. Market Growth Trajectory Chart
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Bar chart showing market growth from 2020 to 2034.
-Historical years (2020-2024): Dark blue bars
-Projected years (2025-2034): Light blue bars
-Y-axis: Market size in billions USD (0 to $XXX)
-X-axis: Years
-Include CAGR annotation showing "XX.X% CAGR (2024-2034)"
-Data labels on top of each bar
-Vertical dashed line separating historical from projected
-Title: "[MARKET NAME] Market Growth Trajectory"
-Professional appearance, white background
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Bar chart market growth 2020 to 2034. Historical bars 2020-2024 in dark blue, projected bars 2025-2034 in light blue. Y-axis billions USD, X-axis years. CAGR annotation XX.X% (2024-2034). Data labels on each bar. Vertical dashed line between 2024 and 2025. Title: Market Growth Trajectory. Professional white background" \
- -o figures/04_market_growth_trajectory.png --doc-type report
-```
+The caption must say that outputs are conditional scenarios.
-### 6. TAM/SAM/SOM Diagram
+## Competitive evidence
-**Tool:** scientific-schematics
+### Feature matrix
-**Prompt:**
-```
-TAM SAM SOM concentric circles diagram:
-- Outer circle: TAM (Total Addressable Market) - $XXX billion
-- Middle circle: SAM (Serviceable Addressable Market) - $XX billion
-- Inner circle: SOM (Serviceable Obtainable Market) - $X billion
+Use statuses `yes`, `partial`, `no`, `unknown`, and `not-applicable`. Each cell
+must map to source IDs and a common product scope, geography, and as-of date.
+Do not treat `unknown` as `no`.
-Each circle labeled with:
-- Acronym in bold
-- Full name
-- Dollar value
+### Market shares
-Arrows pointing to each circle with descriptions
-Use blue color gradient (darkest for TAM, lightest for SOM)
-Professional appearance
-White background
-```
+Use bars rather than a crowded pie. State:
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "TAM SAM SOM concentric circles. Outer circle TAM Total Addressable Market [VALUE]B. Middle circle SAM Serviceable Addressable Market [VALUE]B. Inner circle SOM Serviceable Obtainable Market [VALUE]B. Each labeled with acronym, full name, dollar value. Arrows pointing to each with descriptions. Blue gradient darkest outer to lightest inner. White background professional" \
- -o figures/05_tam_sam_som.png --doc-type report
-```
+- relevant product/geographic scope;
+- share metric and denominator;
+- period;
+- unknown/residual share;
+- whether values are reported, estimated, or calculated;
+- source IDs for numerator and total.
-### 7. Regional Market Breakdown
+If scope uncertainty is material, show alternate definitions instead of one
+authoritative-looking chart.
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Pie chart OR treemap showing regional market breakdown:
-- North America: XX% ($X.XB) - Dark blue
-- Europe: XX% ($X.XB) - Medium blue
-- Asia-Pacific: XX% ($X.XB) - Teal
-- Latin America: X% ($X.XB) - Light blue
-- Middle East & Africa: X% ($X.XB) - Gray blue
+### Positioning maps
-Include both percentage and dollar value for each region
-Legend on right side
-Title: "Market Size by Region (2024)"
-Professional appearance
-```
+Use only with measurable, defined axes. Publish the scoring rule, evidence per
+point, treatment of unknown values, and sensitivity to axis choice. Do not place
+firms based on impression alone.
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Pie chart regional market breakdown. North America XX% dark blue, Europe XX% medium blue, Asia-Pacific XX% teal, Latin America XX% light blue, Middle East Africa XX% gray blue. Show percentage and dollar value for each slice. Legend on right. Title: Market Size by Region 2024. Professional appearance" \
- -o figures/06_regional_breakdown.png --doc-type report
-```
+## Survey evidence
+
+Display weighted estimates only with:
-### 8. Segment Growth Comparison
+- unweighted sample base;
+- target population and frame;
+- field dates and mode;
+- weighting statement;
+- appropriate uncertainty or an explicit reason it is unavailable;
+- wording or instrument link;
+- non-probability label where applicable.
+
+Do not imply that overlapping intervals prove equivalence or that nonoverlap is
+the only test of a meaningful difference.
-**Tool:** scientific-schematics
+## Regulatory timelines
-**Prompt:**
-```
-Horizontal bar chart comparing segment growth rates:
-- Y-axis: Segment names (5-7 segments)
-- X-axis: CAGR percentage (0% to 30%)
-- Bars colored by growth rate: Green (highest) to blue (lowest)
-- Data labels showing exact percentage on each bar
-- Sort segments from highest to lowest growth
-- Title: "Segment Growth Rate Comparison (CAGR 2024-2034)"
-- Include average line or marker
-```
+Distinguish:
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Horizontal bar chart segment growth comparison. Y-axis 5-7 segment names, X-axis CAGR percentage 0-30%. Bars colored green highest to blue lowest. Data labels with exact percentages. Sorted highest to lowest. Title: Segment Growth Rate Comparison CAGR 2024-2034. Include market average line" \
- -o figures/07_segment_growth.png --doc-type report
-```
+- announced or consulted;
+- enacted/adopted;
+- effective;
+- stayed, repealed, or superseded.
----
+Use the official publication and effective dates, not a news article date.
-## Chapter 3: Industry Drivers & Trends Visuals
+## Accessibility
-### 9. Driver Impact Matrix
+- Do not rely on color alone.
+- Use direct labels where possible.
+- Ensure meaningful reading order and alt text.
+- Keep text legible at final output size.
+- Use patterns or line styles for scenarios.
+- Avoid red/green-only encodings.
+- Provide the underlying table or data file.
-**Tool:** scientific-schematics
+## Caption template
-**Prompt:**
+```text
+[What the display shows]. Geography: [scope]. Period: [period].
+Measure: [unit, denominator, stock/flow]. Currency/base: [if applicable].
+Observed through [date]; conditional scenarios thereafter.
+Sources: [S-...]. Calculation: [CALC-...]. Retrieval cutoff: [date].
+Limitations: [material caveat].
```
-2x2 matrix for market driver assessment:
-- X-axis: Impact on Market (Low → High)
-- Y-axis: Probability of Occurrence (Low → High)
-- Upper-right quadrant: "CRITICAL DRIVERS" (red/orange background)
-- Upper-left quadrant: "MONITOR" (yellow background)
-- Lower-right quadrant: "WATCH CAREFULLY" (yellow background)
-- Lower-left quadrant: "LOWER PRIORITY" (green background)
-
-Plot 8-10 drivers as labeled circles:
-- Size of circle represents current market impact
-- Position based on ratings
-
-Include legend for circle sizes
-Professional appearance with clear labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 matrix driver impact assessment. X-axis Impact Low to High, Y-axis Probability Low to High. Quadrants: Upper-right CRITICAL DRIVERS red, Upper-left MONITOR yellow, Lower-right WATCH CAREFULLY yellow, Lower-left LOWER PRIORITY green. Plot 8-10 labeled driver circles at appropriate positions. Circle size indicates current impact. Professional clear labels" \
- -o figures/08_driver_impact_matrix.png --doc-type report
-```
-
-### 10. PESTLE Analysis Diagram
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-PESTLE analysis hexagonal diagram:
-- Center hexagon: "[MARKET NAME]"
-- Six surrounding hexagons connected to center:
- - Political (red/orange)
- - Economic (blue)
- - Social (green)
- - Technological (orange)
- - Legal (purple)
- - Environmental (teal)
-
-Each outer hexagon contains 2-3 key bullet points
-Connecting lines between center and outer hexagons
-Professional appearance
-Clear, readable text in each hexagon
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "PESTLE hexagonal diagram. Center hexagon labeled MARKET. Six surrounding hexagons: Political red, Economic blue, Social green, Technological orange, Legal purple, Environmental teal. Each outer hexagon has 2-3 bullet points of key factors. Lines connecting center to each. Professional appearance clear readable text" \
- -o figures/09_pestle_analysis.png --doc-type report
-```
-
-### 11. Industry Trends Timeline
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Horizontal timeline showing emerging trends from 2024 to 2030:
-- Main horizontal axis with year markers
-- Plot 6-8 trends at different points on timeline
-- Each trend shown with:
- - Icon or symbol
- - Trend name
- - Brief 3-5 word description below
-
-Color-code by trend category:
-- Technology trends: Blue
-- Market trends: Green
-- Regulatory trends: Orange
-
-Include "Current" marker at 2024
-Professional appearance with clear labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Horizontal timeline 2024 to 2030. Plot 6-8 emerging trends at different years. Each trend with icon, name, brief description. Color code: Technology trends blue, Market trends green, Regulatory trends orange. Current marker at 2024. Professional clear labels" \
- -o figures/10_trends_timeline.png --doc-type report
-```
-
----
-
-## Chapter 4: Competitive Landscape Visuals
-
-### 12. Porter's Five Forces Diagram
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Porter's Five Forces diagram with center and four surrounding boxes:
-
-Center box: "Competitive Rivalry" with rating [HIGH/MEDIUM/LOW]
-
-Surrounding boxes connected by arrows:
-- Top: "Threat of New Entrants" [RATING]
-- Left: "Bargaining Power of Suppliers" [RATING]
-- Right: "Bargaining Power of Buyers" [RATING]
-- Bottom: "Threat of Substitutes" [RATING]
-
-Color-code ratings:
-- HIGH: Red/orange background
-- MEDIUM: Yellow background
-- LOW: Green background
-
-Arrows pointing toward center
-Include key factors as bullet points in each box
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Porter's Five Forces diagram. Center box Competitive Rivalry [RATING]. Four surrounding boxes with arrows to center: Top Threat of New Entrants [RATING], Left Bargaining Power Suppliers [RATING], Right Bargaining Power Buyers [RATING], Bottom Threat of Substitutes [RATING]. Color code HIGH red, MEDIUM yellow, LOW green. Include 2-3 key factors per box. Professional appearance" \
- -o figures/11_porters_five_forces.png --doc-type report
-```
-
-### 13. Market Share Chart
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Pie chart or donut chart showing market share:
-- Top 10 companies with distinct colors
-- Company A: XX% (largest slice, dark blue)
-- Company B: XX% (medium blue)
-- [Continue for top 10]
-- Others: XX% (gray)
-
-Include:
-- Percentage labels on each slice
-- Company names in legend or on slices
-- Total market size annotation
-- Title: "Market Share by Company (2024)"
-
-Professional appearance
-Colorblind-friendly palette
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Pie chart market share top 10 companies. Company A XX% dark blue, Company B XX% medium blue, [list companies and shares], Others XX% gray. Percentage labels on slices. Legend with company names. Total market size annotation. Title: Market Share by Company 2024. Colorblind-friendly colors professional" \
- -o figures/12_market_share.png --doc-type report
-```
-
-### 14. Competitive Positioning Matrix
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-2x2 competitive positioning matrix:
-- X-axis: Market Focus (Niche ← → Broad)
-- Y-axis: Solution Approach (Product ← → Platform)
-
-Quadrant labels:
-- Upper-right: "Platform Leaders"
-- Upper-left: "Niche Platforms"
-- Lower-right: "Product Leaders"
-- Lower-left: "Specialists"
-
-Plot 8-10 companies as labeled circles:
-- Circle size represents market share
-- Position based on strategy
-
-Include legend for circle sizes
-Company name labels
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 competitive positioning matrix. X-axis Market Focus Niche to Broad. Y-axis Solution Approach Product to Platform. Quadrants: Upper-right Platform Leaders, Upper-left Niche Platforms, Lower-right Product Leaders, Lower-left Specialists. Plot 8-10 company circles with names. Circle size = market share. Legend for sizes. Professional" \
- -o figures/13_competitive_positioning.png --doc-type report
-```
-
-### 15. Strategic Group Map
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Strategic group map showing competitor clusters:
-- X-axis: Geographic Scope (Regional ← → Global)
-- Y-axis: Product Breadth (Narrow ← → Broad)
-
-Draw 4-5 oval "bubbles" representing strategic groups:
-- Each bubble contains 2-4 company names
-- Bubble size represents collective market share of group
-- Different colors for each strategic group
-
-Label each strategic group:
-- "Global Generalists"
-- "Regional Specialists"
-- "Focused Innovators"
-- etc.
-
-Professional appearance
-Clear company name labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Strategic group map. X-axis Geographic Scope Regional to Global. Y-axis Product Breadth Narrow to Broad. Draw 4-5 oval bubbles for strategic groups. Each bubble contains 2-4 company names. Bubble size = collective market share. Label groups: Global Generalists, Regional Specialists, Focused Innovators etc. Different colors per group. Professional clear labels" \
- -o figures/14_strategic_groups.png --doc-type report
-```
-
----
-
-## Chapter 5: Customer Analysis Visuals
-
-### 16. Customer Segmentation Breakdown
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Treemap or pie chart showing customer segments:
-- Large Enterprise: XX% (dark blue)
-- Mid-Market: XX% (medium blue)
-- SMB: XX% (light blue)
-- Consumer: XX% (teal)
-
-Size represents market share
-Include for each segment:
-- Segment name
-- Percentage
-- Dollar value
-
-Title: "Customer Segmentation by Market Share"
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Treemap customer segmentation. Large Enterprise XX% dark blue, Mid-Market XX% medium blue, SMB XX% light blue, Consumer XX% teal. Each segment shows name percentage dollar value. Title: Customer Segmentation by Market Share. Professional appearance" \
- -o figures/15_customer_segments.png --doc-type report
-```
-
-### 17. Segment Attractiveness Matrix
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-2x2 segment attractiveness matrix:
-- X-axis: Segment Size (Small ← → Large)
-- Y-axis: Growth Rate (Low ← → High)
-
-Quadrant labels and actions:
-- Upper-right: "PRIORITY - Invest Heavily"
-- Upper-left: "INVEST TO GROW"
-- Lower-right: "HARVEST"
-- Lower-left: "DEPRIORITIZE"
-
-Plot customer segments as labeled circles
-Circle size represents profitability
-Different colors for each segment
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 segment attractiveness matrix. X-axis Segment Size Small to Large. Y-axis Growth Rate Low to High. Quadrants: Upper-right PRIORITY Invest Heavily, Upper-left INVEST TO GROW, Lower-right HARVEST, Lower-left DEPRIORITIZE. Plot customer segments as circles. Circle size = profitability. Different colors. Professional" \
- -o figures/16_segment_attractiveness.png --doc-type report
-```
-
-### 18. Customer Journey Map
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Customer journey horizontal flowchart showing 5-6 stages:
-Awareness → Consideration → Decision → Implementation → Usage → Advocacy
-
-For each stage, show three rows:
-1. Key Activities (what customer does)
-2. Pain Points (challenges faced)
-3. Touchpoints (how they interact)
-
-Use icons for each stage
-Color gradient from light to dark as journey progresses
-Professional appearance
-Clear labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Customer journey horizontal flowchart. 5 stages left to right: Awareness, Consideration, Decision, Implementation, Usage, Advocacy. Each stage shows Key Activities, Pain Points, Touchpoints in rows below. Icons for each stage. Color gradient light to dark. Professional clear labels" \
- -o figures/17_customer_journey.png --doc-type report
-```
-
----
-
-## Chapter 6: Technology Landscape Visuals
-
-### 19. Technology Roadmap
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Technology roadmap timeline from 2024 to 2030:
-Three parallel horizontal tracks:
-1. Core Technology (blue) - current foundation
-2. Emerging Technology (green) - developing capabilities
-3. Enabling Technology (orange) - infrastructure/support
-
-Each track shows milestones and technology introductions as markers
-Vertical lines connect related technologies across tracks
-Timeline markers for each year
-Technology names labeled at introduction points
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Technology roadmap 2024 to 2030. Three parallel horizontal tracks: Core Technology blue, Emerging Technology green, Enabling Technology orange. Milestones and tech introductions marked on each track. Vertical lines connect related tech. Year markers. Technology names labeled. Professional appearance" \
- -o figures/18_technology_roadmap.png --doc-type report
-```
-
-### 20. Innovation/Adoption Curve
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Gartner Hype Cycle or Technology Adoption Curve:
-Five phases from left to right:
-1. Innovation Trigger (rising)
-2. Peak of Inflated Expectations (peak)
-3. Trough of Disillusionment (bottom)
-4. Slope of Enlightenment (rising)
-5. Plateau of Productivity (stable)
-
-Plot 6-8 technologies at different positions on the curve
-Each technology labeled with name
-Color-code by technology category
-Professional appearance
-Clear axis labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Gartner Hype Cycle curve. Five phases: Innovation Trigger rising, Peak of Inflated Expectations at top, Trough of Disillusionment at bottom, Slope of Enlightenment rising, Plateau of Productivity stable. Plot 6-8 technologies on curve with labels. Color by category. Professional clear labels" \
- -o figures/19_innovation_curve.png --doc-type report
-```
-
----
-
-## Chapter 7: Regulatory Environment Visuals
-
-### 21. Regulatory Timeline
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Regulatory timeline from 2020 to 2028:
-Horizontal timeline with year markers
-Mark key regulatory events:
-- Past regulations (dark blue markers, solid)
-- Current regulations (green marker at current year)
-- Upcoming regulations (light blue markers, dashed)
-
-Each marker shows:
-- Regulation name
-- Effective date
-- Brief description (5-7 words)
-
-Vertical "NOW" line at current year (2024)
-Group by region if multiple jurisdictions
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Regulatory timeline 2020 to 2028. Past regulations dark blue solid markers, current green marker, upcoming light blue dashed. Each shows regulation name, date, brief description. Vertical NOW line at 2024. Professional appearance clear labels" \
- -o figures/20_regulatory_timeline.png --doc-type report
-```
-
----
-
-## Chapter 8: Risk Analysis Visuals
-
-### 22. Risk Heatmap
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Risk assessment heatmap/matrix:
-- X-axis: Impact (Low → Medium → High → Critical)
-- Y-axis: Probability (Unlikely → Possible → Likely → Very Likely)
-
-Color gradient for cells:
-- Green: Low risk (low probability, low impact)
-- Yellow: Medium risk
-- Orange: High risk
-- Red: Critical risk (high probability, high impact)
-
-Plot 10-12 risks as labeled points/circles in appropriate cells
-Risk labels should be clearly readable
-Include risk numbers (R1, R2, etc.)
-Legend linking numbers to risk names
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Risk heatmap matrix. X-axis Impact Low Medium High Critical. Y-axis Probability Unlikely Possible Likely Very Likely. Cell colors: Green low risk, Yellow medium, Orange high, Red critical. Plot 10-12 numbered risks R1 R2 etc as labeled points. Legend with risk names. Professional clear" \
- -o figures/21_risk_heatmap.png --doc-type report
-```
-
-### 23. Risk Mitigation Framework
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Risk mitigation diagram showing risks and their mitigations:
-Left column: Risks (in red/orange boxes)
-Right column: Mitigation Strategies (in green/blue boxes)
-
-Connect each risk to its mitigation(s) with arrows
-Group risks by category (Market, Regulatory, Technology, etc.)
-Include both prevention and response strategies
-
-Risk severity indicated by box color intensity
-Professional appearance
-Clear labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Risk mitigation diagram. Left column risks in orange/red boxes. Right column mitigation strategies in green/blue boxes. Arrows connecting risks to mitigations. Group by category. Risk severity by color intensity. Include prevention and response. Professional clear labels" \
- -o figures/22_risk_mitigation.png --doc-type report
-```
-
----
-
-## Chapter 9: Strategic Recommendations Visuals
-
-### 24. Opportunity Matrix
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-2x2 opportunity assessment matrix:
-- X-axis: Market Attractiveness (Low ← → High)
-- Y-axis: Ability to Win (Low ← → High)
-
-Quadrant labels and strategies:
-- Upper-right: "PURSUE AGGRESSIVELY" (green)
-- Upper-left: "BUILD CAPABILITIES" (yellow)
-- Lower-right: "SELECTIVE INVESTMENT" (yellow)
-- Lower-left: "AVOID/DIVEST" (red)
-
-Plot 6-8 opportunities as labeled circles
-Circle size represents opportunity size ($)
-Include opportunity names
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 opportunity matrix. X-axis Market Attractiveness Low to High. Y-axis Ability to Win Low to High. Quadrants: Upper-right PURSUE AGGRESSIVELY green, Upper-left BUILD CAPABILITIES yellow, Lower-right SELECTIVE INVESTMENT yellow, Lower-left AVOID red. Plot 6-8 opportunity circles with labels. Size = opportunity value. Professional" \
- -o figures/23_opportunity_matrix.png --doc-type report
-```
-
-### 25. Recommendation Priority Matrix
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-2x2 priority matrix for recommendations:
-- X-axis: Effort/Investment (Low ← → High)
-- Y-axis: Impact/Value (Low ← → High)
-
-Quadrant labels:
-- Upper-left: "QUICK WINS" (green) - Do First
-- Upper-right: "MAJOR PROJECTS" (blue) - Plan Carefully
-- Lower-left: "FILL-INS" (gray) - Do If Time
-- Lower-right: "THANKLESS TASKS" (red) - Avoid
-
-Plot 6-8 recommendations as labeled points
-Number recommendations by priority
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "2x2 priority matrix. X-axis Effort Low to High. Y-axis Impact Low to High. Quadrants: Upper-left QUICK WINS green Do First, Upper-right MAJOR PROJECTS blue Plan Carefully, Lower-left FILL-INS gray Do If Time, Lower-right THANKLESS TASKS red Avoid. Plot 6-8 numbered recommendations. Professional" \
- -o figures/24_recommendation_priority.png --doc-type report
-```
-
----
-
-## Chapter 10: Implementation Roadmap Visuals
-
-### 26. Implementation Timeline/Gantt
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Gantt chart style implementation timeline over 24 months:
-Four phases shown as horizontal bars:
-- Phase 1: Foundation (Months 1-6) - Dark blue
-- Phase 2: Build (Months 4-12) - Medium blue
-- Phase 3: Scale (Months 10-18) - Teal
-- Phase 4: Optimize (Months 16-24) - Light blue
-
-Phases overlap as shown in dates
-Key milestones marked as diamonds on timeline
-Month markers on X-axis
-Phase names on Y-axis
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Gantt chart implementation 24 months. Phase 1 Foundation months 1-6 dark blue. Phase 2 Build months 4-12 medium blue. Phase 3 Scale months 10-18 teal. Phase 4 Optimize months 16-24 light blue. Overlapping bars. Key milestones as diamonds. Month markers X-axis. Professional" \
- -o figures/25_implementation_timeline.png --doc-type report
-```
-
-### 27. Milestone Tracker
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Milestone tracker showing 8-10 key milestones on horizontal timeline:
-Each milestone shows:
-- Date/Month
-- Milestone name
-- Status indicator:
- - Completed: Green checkmark ✓
- - In Progress: Yellow circle ○
- - Upcoming: Gray circle ○
-
-Group milestones by phase
-Connect milestones with timeline line
-Include phase labels above timeline
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Milestone tracker horizontal timeline 8-10 milestones. Each shows date, name, status: Completed green check, In Progress yellow circle, Upcoming gray circle. Group by phase. Phase labels above. Connected timeline line. Professional" \
- -o figures/26_milestone_tracker.png --doc-type report
-```
-
----
-
-## Chapter 11: Investment Thesis Visuals
-
-### 28. Financial Projections Chart
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Combined bar and line chart showing 5-year financial projections:
-- Bar chart: Revenue by year (primary Y-axis, in $M)
-- Line chart: Growth rate overlay (secondary Y-axis, in %)
-
-Three scenarios shown:
-- Conservative: Gray bars
-- Base Case: Blue bars
-- Optimistic: Green bars
-
-X-axis: Year 1 through Year 5
-Include data labels on bars
-Legend for scenarios and growth line
-Title: "Financial Projections (5-Year)"
-Professional appearance
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Combined bar and line chart 5-year projections. Bar chart revenue primary Y-axis dollars. Line chart growth rate secondary Y-axis percent. Three scenarios: Conservative gray, Base Case blue, Optimistic green. X-axis Year 1-5. Data labels. Legend. Title Financial Projections 5-Year. Professional" \
- -o figures/27_financial_projections.png --doc-type report
-```
-
-### 29. Scenario Analysis Comparison
-
-**Tool:** scientific-schematics
-
-**Prompt:**
-```
-Grouped bar chart comparing three scenarios across key metrics:
-X-axis: Metrics (Revenue Y5, EBITDA Y5, Market Share, ROI)
-Y-axis: Value (scale appropriate for each metric)
-
-Three bars per metric:
-- Conservative: Gray
-- Base Case: Blue
-- Optimistic: Green
-
-Data labels on each bar
-Legend for scenarios
-Title: "Scenario Analysis Comparison"
-Professional appearance
-Clear metric labels
-```
-
-**Command:**
-```bash
-python skills/scientific-schematics/scripts/generate_schematic.py \
- "Grouped bar chart scenario comparison. X-axis metrics: Revenue Y5, EBITDA Y5, Market Share, ROI. Three bars per metric: Conservative gray, Base Case blue, Optimistic green. Data labels. Legend. Title Scenario Analysis Comparison. Professional clear labels" \
- -o figures/28_scenario_analysis.png --doc-type report
-```
-
----
-
-## Batch Generation Script
-
-For convenience, use the `generate_market_visuals.py` script to batch generate visuals:
-
-```bash
-# Generate core 5-6 visuals only (recommended for starting reports)
-python skills/market-research-reports/scripts/generate_market_visuals.py \
- --topic "Electric Vehicle Charging Infrastructure" \
- --output-dir figures/
-
-# Generate all 27 visuals (core + extended, for comprehensive coverage)
-python skills/market-research-reports/scripts/generate_market_visuals.py \
- --topic "Electric Vehicle Charging Infrastructure" \
- --output-dir figures/ \
- --all
-
-# Skip already generated files
-python skills/market-research-reports/scripts/generate_market_visuals.py \
- --topic "Your Market" \
- --output-dir figures/ \
- --skip-existing
-```
-
-**Default behavior**: Generates only the 5-6 core priority visuals. Use `--all` flag if you need comprehensive visual coverage for all sections.
-
----
-
-## Quality Checklist
-Before including visuals in the report, verify:
+## Visual audit
-- [ ] All text is readable at intended size
-- [ ] Colors are consistent across all visuals
-- [ ] Color scheme is colorblind-friendly
-- [ ] Data labels are accurate
-- [ ] Legends are clear and complete
-- [ ] Titles are descriptive
-- [ ] Sources are noted where applicable
-- [ ] Resolution is 300 DPI or higher
-- [ ] File format is PNG
-- [ ] Naming convention is followed
+- Every plotted value is reproducible from a local table.
+- All source and calculation IDs exist.
+- Units, denominators, dates, and price bases are visible.
+- Axis starts, scales, truncation, and sorting do not mislead.
+- Missing/suppressed values are not rendered as zero.
+- Forecast and historical data are visibly distinct.
+- Rounding is consistent with evidence precision.
+- The visual works in grayscale and with screen readers.
+- The report does not require any figure to be considered complete.
diff --git a/skills/market-research-reports/scripts/_common.py b/skills/market-research-reports/scripts/_common.py
new file mode 100644
index 00000000..2f8f9af7
--- /dev/null
+++ b/skills/market-research-reports/scripts/_common.py
@@ -0,0 +1,312 @@
+#!/usr/bin/env python3
+"""Shared, dependency-free validation helpers for local market-research CLIs."""
+
+from __future__ import annotations
+
+import csv
+import json
+import math
+import os
+import re
+import tempfile
+from datetime import date
+from pathlib import Path
+from typing import Any, Iterable
+
+MAX_FILE_BYTES = 5 * 1024 * 1024
+MAX_ROWS = 10_000
+MAX_CELL_CHARS = 20_000
+MAX_IDENTIFIER_CHARS = 96
+
+IDENTIFIER_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._:-]{0,95}$")
+CURRENCY_RE = re.compile(r"^[A-Z]{3}$")
+
+
+class ValidationError(ValueError):
+ """A deterministic, user-correctable input validation error."""
+
+
+def safe_input_path(raw_path: str | Path, suffixes: Iterable[str]) -> Path:
+ """Resolve a bounded regular local file and reject symlink inputs."""
+ path = Path(raw_path).expanduser()
+ if path.is_symlink():
+ raise ValidationError(f"symlink inputs are not allowed: {path}")
+ try:
+ resolved = path.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise ValidationError(f"input file does not exist: {path}") from exc
+ if not resolved.is_file():
+ raise ValidationError(f"input path is not a regular file: {resolved}")
+ allowed = {suffix.lower() for suffix in suffixes}
+ if resolved.suffix.lower() not in allowed:
+ choices = ", ".join(sorted(allowed))
+ raise ValidationError(f"expected one of [{choices}], got: {resolved.suffix}")
+ size = resolved.stat().st_size
+ if size > MAX_FILE_BYTES:
+ raise ValidationError(
+ f"input exceeds {MAX_FILE_BYTES} bytes: {resolved} ({size} bytes)"
+ )
+ return resolved
+
+
+def safe_output_path(
+ raw_path: str | Path, suffix: str, *, force: bool = False
+) -> Path:
+ """Resolve an output in an existing directory without implicit overwrites."""
+ path = Path(raw_path).expanduser()
+ if path.suffix.lower() != suffix.lower():
+ raise ValidationError(f"output must use {suffix}: {path}")
+ try:
+ parent = path.parent.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise ValidationError(f"output parent does not exist: {path.parent}") from exc
+ if not parent.is_dir():
+ raise ValidationError(f"output parent is not a directory: {parent}")
+ resolved = parent / path.name
+ if resolved.is_symlink():
+ raise ValidationError(f"symlink outputs are not allowed: {resolved}")
+ if resolved.exists():
+ if not resolved.is_file():
+ raise ValidationError(f"output is not a regular file: {resolved}")
+ if not force:
+ raise ValidationError(
+ f"output already exists; pass --force to replace it: {resolved}"
+ )
+ return resolved
+
+
+def read_json(raw_path: str | Path) -> Any:
+ """Read one bounded UTF-8 JSON document."""
+ path = safe_input_path(raw_path, {".json"})
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ return json.load(handle)
+ except UnicodeDecodeError as exc:
+ raise ValidationError(f"JSON must be UTF-8: {path}") from exc
+ except json.JSONDecodeError as exc:
+ raise ValidationError(
+ f"invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}"
+ ) from exc
+
+
+def read_csv_records(
+ raw_path: str | Path,
+ *,
+ required_fields: Iterable[str],
+ max_rows: int = MAX_ROWS,
+) -> list[dict[str, str]]:
+ """Read strict UTF-8 CSV records with unique headers and bounded cells."""
+ path = safe_input_path(raw_path, {".csv"})
+ required = tuple(required_fields)
+ try:
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
+ reader = csv.DictReader(handle)
+ headers = reader.fieldnames
+ if not headers:
+ raise ValidationError(f"CSV has no header: {path}")
+ normalized = [header.strip() for header in headers]
+ if any(not header for header in normalized):
+ raise ValidationError("CSV headers must not be blank")
+ if len(normalized) != len(set(normalized)):
+ raise ValidationError("CSV headers must be unique")
+ missing = sorted(set(required) - set(normalized))
+ if missing:
+ raise ValidationError(
+ f"CSV is missing required columns: {', '.join(missing)}"
+ )
+ reader.fieldnames = normalized
+ records: list[dict[str, str]] = []
+ for line_number, row in enumerate(reader, start=2):
+ if line_number - 1 > max_rows:
+ raise ValidationError(f"CSV exceeds {max_rows} data rows")
+ if None in row:
+ raise ValidationError(
+ f"row {line_number} has more cells than the header"
+ )
+ cleaned: dict[str, str] = {}
+ for key, value in row.items():
+ cell = "" if value is None else value.strip()
+ if "\x00" in cell:
+ raise ValidationError(
+ f"row {line_number}, column {key} contains a NUL byte"
+ )
+ if len(cell) > MAX_CELL_CHARS:
+ raise ValidationError(
+ f"row {line_number}, column {key} exceeds "
+ f"{MAX_CELL_CHARS} characters"
+ )
+ cleaned[key] = cell
+ if any(cleaned.values()):
+ records.append(cleaned)
+ except UnicodeDecodeError as exc:
+ raise ValidationError(f"CSV must be UTF-8: {path}") from exc
+ except csv.Error as exc:
+ raise ValidationError(f"invalid CSV: {exc}") from exc
+ if not records:
+ raise ValidationError("CSV must contain at least one data row")
+ return records
+
+
+def require_object(value: Any, context: str) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise ValidationError(f"{context} must be a JSON object")
+ return value
+
+
+def require_list(
+ value: Any,
+ context: str,
+ *,
+ minimum: int = 0,
+ maximum: int = MAX_ROWS,
+) -> list[Any]:
+ if not isinstance(value, list):
+ raise ValidationError(f"{context} must be a JSON array")
+ if not minimum <= len(value) <= maximum:
+ raise ValidationError(
+ f"{context} must contain between {minimum} and {maximum} items"
+ )
+ return value
+
+
+def require_text(
+ value: Any,
+ context: str,
+ *,
+ allow_empty: bool = False,
+ maximum: int = MAX_CELL_CHARS,
+) -> str:
+ if not isinstance(value, str):
+ raise ValidationError(f"{context} must be a string")
+ text = value.strip()
+ if not allow_empty and not text:
+ raise ValidationError(f"{context} must not be empty")
+ if len(text) > maximum:
+ raise ValidationError(f"{context} exceeds {maximum} characters")
+ if "\x00" in text:
+ raise ValidationError(f"{context} contains a NUL byte")
+ return text
+
+
+def require_identifier(value: Any, context: str) -> str:
+ identifier = require_text(
+ value, context, maximum=MAX_IDENTIFIER_CHARS, allow_empty=False
+ )
+ if not IDENTIFIER_RE.fullmatch(identifier):
+ raise ValidationError(
+ f"{context} must match {IDENTIFIER_RE.pattern}: {identifier!r}"
+ )
+ return identifier
+
+
+def require_unique_identifiers(values: Iterable[str], context: str) -> None:
+ seen: set[str] = set()
+ duplicates: set[str] = set()
+ for value in values:
+ if value in seen:
+ duplicates.add(value)
+ seen.add(value)
+ if duplicates:
+ raise ValidationError(
+ f"{context} contains duplicate IDs: {', '.join(sorted(duplicates))}"
+ )
+
+
+def parse_iso_date(value: Any, context: str) -> str:
+ text = require_text(value, context, maximum=10)
+ try:
+ date.fromisoformat(text)
+ except ValueError as exc:
+ raise ValidationError(f"{context} must be YYYY-MM-DD: {text!r}") from exc
+ return text
+
+
+def parse_year(value: Any, context: str) -> int:
+ if isinstance(value, bool):
+ raise ValidationError(f"{context} must be an integer year")
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError) as exc:
+ raise ValidationError(f"{context} must be an integer year") from exc
+ if not 1800 <= parsed <= 2200:
+ raise ValidationError(f"{context} must be between 1800 and 2200")
+ return parsed
+
+
+def parse_number(
+ value: Any,
+ context: str,
+ *,
+ minimum: float,
+ maximum: float,
+) -> float:
+ if isinstance(value, bool):
+ raise ValidationError(f"{context} must be numeric")
+ try:
+ number = float(value)
+ except (TypeError, ValueError) as exc:
+ raise ValidationError(f"{context} must be numeric") from exc
+ if not math.isfinite(number):
+ raise ValidationError(f"{context} must be finite")
+ if not minimum <= number <= maximum:
+ raise ValidationError(
+ f"{context} must be between {minimum} and {maximum}: {number}"
+ )
+ return number
+
+
+def parse_fraction(value: Any, context: str) -> float:
+ return parse_number(value, context, minimum=0.0, maximum=1.0)
+
+
+def parse_currency(value: Any, context: str, *, allow_empty: bool = False) -> str:
+ text = require_text(value, context, allow_empty=allow_empty, maximum=3).upper()
+ if not text and allow_empty:
+ return ""
+ if not CURRENCY_RE.fullmatch(text):
+ raise ValidationError(f"{context} must be a three-letter currency code")
+ return text
+
+
+def split_ids(value: Any, context: str, *, allow_empty: bool = False) -> list[str]:
+ text = require_text(value, context, allow_empty=allow_empty)
+ if not text:
+ return []
+ identifiers = [part.strip() for part in text.split(";")]
+ if any(not part for part in identifiers):
+ raise ValidationError(f"{context} contains an empty semicolon-delimited ID")
+ parsed = [require_identifier(part, context) for part in identifiers]
+ require_unique_identifiers(parsed, context)
+ return parsed
+
+
+def write_json_report(
+ data: Any, output: str | Path | None, *, force: bool = False
+) -> None:
+ """Print JSON or atomically write it to an explicitly selected local file."""
+ serialized = json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
+ if output is None:
+ print(serialized, end="")
+ return
+ destination = safe_output_path(output, ".json", force=force)
+ temporary_name: str | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=destination.parent,
+ prefix=f".{destination.name}.",
+ suffix=".tmp",
+ delete=False,
+ ) as handle:
+ handle.write(serialized)
+ temporary_name = handle.name
+ os.replace(temporary_name, destination)
+ finally:
+ if temporary_name and Path(temporary_name).exists():
+ Path(temporary_name).unlink()
+
+
+def error_exit(exc: ValidationError) -> int:
+ print(f"ERROR: {exc}", file=os.sys.stderr)
+ return 2
diff --git a/skills/market-research-reports/scripts/audit_claim_citations.py b/skills/market-research-reports/scripts/audit_claim_citations.py
new file mode 100644
index 00000000..57514a06
--- /dev/null
+++ b/skills/market-research-reports/scripts/audit_claim_citations.py
@@ -0,0 +1,326 @@
+#!/usr/bin/env python3
+"""Audit claim-to-source mappings in local CSV ledgers."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ MAX_ROWS,
+ ValidationError,
+ error_exit,
+ parse_currency,
+ parse_iso_date,
+ parse_year,
+ read_csv_records,
+ read_json,
+ require_identifier,
+ require_list,
+ require_object,
+ require_text,
+ require_unique_identifiers,
+ split_ids,
+ write_json_report,
+)
+
+CLAIM_FIELDS = (
+ "claim_id",
+ "claim_text",
+ "claim_type",
+ "source_ids",
+ "calculation_id",
+ "assumption_ids",
+ "location",
+ "as_of_date",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "unit",
+ "taxonomy",
+ "taxonomy_version",
+ "revision_status",
+ "confidence",
+ "notes",
+)
+CLAIM_TYPES = {
+ "quantitative_fact",
+ "quantitative_estimate",
+ "calculation",
+ "forecast",
+ "qualitative_fact",
+ "opinion",
+ "recommendation",
+}
+QUANTITATIVE_TYPES = {
+ "quantitative_fact",
+ "quantitative_estimate",
+ "calculation",
+ "forecast",
+}
+EVIDENCE_REQUIRED_TYPES = CLAIM_TYPES - {"opinion", "recommendation"}
+REVISION_STATUSES = {
+ "preliminary",
+ "revised",
+ "final",
+ "current",
+ "vintage",
+ "unknown",
+ "not-applicable",
+}
+CONFIDENCE_LEVELS = {"high", "medium", "low", "not-assessed"}
+MEASURE_TYPES = {
+ "stock",
+ "flow",
+ "index",
+ "share",
+ "count",
+ "rate",
+ "price",
+ "not-applicable",
+}
+
+
+def _load_sources(path: str | Path) -> list[dict[str, Any]]:
+ suffix = Path(path).suffix.lower()
+ if suffix == ".csv":
+ return read_csv_records(
+ path,
+ required_fields=("source_id", "publication_date", "retrieval_date"),
+ )
+ if suffix == ".json":
+ payload = read_json(path)
+ raw = (
+ require_list(
+ payload.get("sources"), "sources", minimum=1, maximum=MAX_ROWS
+ )
+ if isinstance(payload, dict)
+ else require_list(payload, "sources", minimum=1, maximum=MAX_ROWS)
+ )
+ return [
+ require_object(record, f"sources[{index}]")
+ for index, record in enumerate(raw)
+ ]
+ raise ValidationError("source ledger must be .csv or .json")
+
+
+def _source_index(records: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ index: dict[str, dict[str, Any]] = {}
+ for position, record in enumerate(records):
+ context = f"sources[{position}]"
+ source_id = require_identifier(record.get("source_id"), f"{context}.source_id")
+ if source_id in index:
+ raise ValidationError(f"duplicate source_id: {source_id}")
+ publication = require_text(
+ record.get("publication_date"), f"{context}.publication_date", maximum=10
+ )
+ if publication != "not-stated":
+ if len(publication) == 4:
+ parse_year(publication, f"{context}.publication_date")
+ else:
+ parse_iso_date(publication, f"{context}.publication_date")
+ parse_iso_date(record.get("retrieval_date"), f"{context}.retrieval_date")
+ index[source_id] = record
+ return index
+
+
+def audit(
+ claims: list[dict[str, str]], sources: list[dict[str, Any]]
+) -> dict[str, Any]:
+ source_index = _source_index(sources)
+ errors: list[str] = []
+ warnings: list[str] = []
+ claim_ids: list[str] = []
+ cited_source_ids: set[str] = set()
+ type_counts: dict[str, int] = {}
+ uncited_claims: list[str] = []
+
+ for row_number, claim in enumerate(claims, start=2):
+ context = f"claim row {row_number}"
+ try:
+ claim_id = require_identifier(claim["claim_id"], f"{context}.claim_id")
+ claim_ids.append(claim_id)
+ claim_text = require_text(claim["claim_text"], f"{context}.claim_text")
+ if any(marker in claim_text.upper() for marker in ("[TBD]", "[TODO]")):
+ warnings.append(f"{claim_id}: claim text contains a placeholder")
+
+ claim_type = require_text(
+ claim["claim_type"], f"{context}.claim_type", maximum=30
+ )
+ if claim_type not in CLAIM_TYPES:
+ raise ValidationError(
+ f"{context}.claim_type must be one of "
+ f"{', '.join(sorted(CLAIM_TYPES))}"
+ )
+ type_counts[claim_type] = type_counts.get(claim_type, 0) + 1
+
+ source_ids = split_ids(
+ claim["source_ids"], f"{context}.source_ids", allow_empty=True
+ )
+ cited_source_ids.update(source_ids)
+ if claim_type in EVIDENCE_REQUIRED_TYPES and not source_ids:
+ uncited_claims.append(claim_id)
+ raise ValidationError(
+ f"{context}: {claim_type} requires at least one source_id"
+ )
+ missing_sources = sorted(set(source_ids) - set(source_index))
+ if missing_sources:
+ raise ValidationError(
+ f"{context}: source IDs are absent from the ledger: "
+ f"{', '.join(missing_sources)}"
+ )
+
+ calculation_id = require_text(
+ claim["calculation_id"],
+ f"{context}.calculation_id",
+ allow_empty=True,
+ maximum=96,
+ )
+ if calculation_id:
+ require_identifier(calculation_id, f"{context}.calculation_id")
+ assumption_ids = split_ids(
+ claim["assumption_ids"],
+ f"{context}.assumption_ids",
+ allow_empty=True,
+ )
+ if claim_type in {"calculation", "forecast"} and not calculation_id:
+ raise ValidationError(
+ f"{context}: {claim_type} requires calculation_id"
+ )
+ if claim_type == "forecast" and not assumption_ids:
+ raise ValidationError(
+ f"{context}: forecast requires assumption_ids"
+ )
+
+ require_text(claim["location"], f"{context}.location")
+ parse_iso_date(claim["as_of_date"], f"{context}.as_of_date")
+ require_text(claim["geography"], f"{context}.geography")
+ currency = parse_currency(
+ claim["currency"], f"{context}.currency", allow_empty=True
+ )
+ base_year = require_text(
+ claim["base_year"],
+ f"{context}.base_year",
+ allow_empty=True,
+ maximum=4,
+ )
+ if base_year:
+ parse_year(base_year, f"{context}.base_year")
+ price_basis = require_text(
+ claim["price_basis"], f"{context}.price_basis", maximum=20
+ )
+ if price_basis not in {
+ "nominal",
+ "real",
+ "current",
+ "constant",
+ "not-applicable",
+ }:
+ raise ValidationError(
+ f"{context}.price_basis has an unsupported value"
+ )
+ if currency and (not base_year or price_basis == "not-applicable"):
+ raise ValidationError(
+ f"{context}: monetary claims require base_year and price_basis"
+ )
+
+ measure_type = require_text(
+ claim["measure_type"], f"{context}.measure_type", maximum=20
+ )
+ if measure_type not in MEASURE_TYPES:
+ raise ValidationError(
+ f"{context}.measure_type has an unsupported value"
+ )
+ unit = require_text(claim["unit"], f"{context}.unit")
+ if claim_type in QUANTITATIVE_TYPES and (
+ measure_type == "not-applicable" or unit == "not-applicable"
+ ):
+ raise ValidationError(
+ f"{context}: quantitative claims require an explicit unit "
+ "and measure_type"
+ )
+
+ require_text(
+ claim["taxonomy"], f"{context}.taxonomy", allow_empty=True
+ )
+ require_text(
+ claim["taxonomy_version"],
+ f"{context}.taxonomy_version",
+ allow_empty=True,
+ )
+ revision_status = require_text(
+ claim["revision_status"],
+ f"{context}.revision_status",
+ maximum=20,
+ )
+ if revision_status not in REVISION_STATUSES:
+ raise ValidationError(
+ f"{context}.revision_status has an unsupported value"
+ )
+ confidence = require_text(
+ claim["confidence"], f"{context}.confidence", maximum=20
+ )
+ if confidence not in CONFIDENCE_LEVELS:
+ raise ValidationError(
+ f"{context}.confidence must be one of "
+ f"{', '.join(sorted(CONFIDENCE_LEVELS))}"
+ )
+ require_text(claim["notes"], f"{context}.notes", allow_empty=True)
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ try:
+ require_unique_identifiers(claim_ids, "claim ledger")
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ unused_sources = sorted(set(source_index) - cited_source_ids)
+ if unused_sources:
+ warnings.append(
+ f"{len(unused_sources)} source ledger entries are not mapped to a claim"
+ )
+ return {
+ "valid": not errors,
+ "claim_count": len(claims),
+ "source_count": len(source_index),
+ "claim_type_counts": dict(sorted(type_counts.items())),
+ "cited_source_count": len(cited_source_ids),
+ "uncited_claim_ids": sorted(set(uncited_claims)),
+ "unused_source_ids": unused_sources,
+ "warnings": warnings,
+ "errors": errors,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Audit a strict local claims CSV against a local source ledger. "
+ "Every evidence claim must map to explicit source IDs."
+ )
+ )
+ parser.add_argument("claims", help="Local .csv claims ledger")
+ parser.add_argument("sources", help="Local .csv or .json source ledger")
+ parser.add_argument("--output", help="Optional local .json audit report")
+ parser.add_argument(
+ "--force", action="store_true", help="Replace an existing --output file"
+ )
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ claims = read_csv_records(args.claims, required_fields=CLAIM_FIELDS)
+ report = audit(claims, _load_sources(args.sources))
+ write_json_report(report, args.output, force=args.force)
+ return 0 if report["valid"] else 1
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/scripts/calculate_market_sizing.py b/skills/market-research-reports/scripts/calculate_market_sizing.py
new file mode 100644
index 00000000..24d181ee
--- /dev/null
+++ b/skills/market-research-reports/scripts/calculate_market_sizing.py
@@ -0,0 +1,389 @@
+#!/usr/bin/env python3
+"""Calculate bounded TAM/SAM/SOM scenarios and reconcile two sizing methods."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ ValidationError,
+ error_exit,
+ parse_currency,
+ parse_fraction,
+ parse_iso_date,
+ parse_number,
+ parse_year,
+ read_json,
+ require_identifier,
+ require_list,
+ require_object,
+ require_text,
+ require_unique_identifiers,
+ write_json_report,
+)
+
+MAX_COMPONENTS = 1_000
+MAX_SCENARIOS = 20
+MAX_VALUE = 1e18
+
+
+def _identifier_array(
+ value: Any, context: str, *, minimum: int = 0
+) -> list[str]:
+ items = require_list(value, context, minimum=minimum, maximum=100)
+ parsed = [
+ require_identifier(item, f"{context}[{index}]")
+ for index, item in enumerate(items)
+ ]
+ require_unique_identifiers(parsed, context)
+ return parsed
+
+
+def _metadata(payload: dict[str, Any]) -> dict[str, Any]:
+ raw = require_object(payload.get("metadata"), "metadata")
+ required = (
+ "market_id",
+ "market_definition",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "unit",
+ "taxonomy",
+ "taxonomy_version",
+ "denominator_id",
+ "as_of_date",
+ )
+ missing = [field for field in required if field not in raw]
+ if missing:
+ raise ValidationError(f"metadata is missing: {', '.join(missing)}")
+ price_basis = require_text(raw["price_basis"], "metadata.price_basis", maximum=20)
+ if price_basis not in {"nominal", "real", "current", "constant"}:
+ raise ValidationError(
+ "metadata.price_basis must be nominal, real, current, or constant"
+ )
+ return {
+ "market_id": require_identifier(raw["market_id"], "metadata.market_id"),
+ "market_definition": require_text(
+ raw["market_definition"], "metadata.market_definition"
+ ),
+ "geography": require_text(raw["geography"], "metadata.geography"),
+ "currency": parse_currency(raw["currency"], "metadata.currency"),
+ "base_year": parse_year(raw["base_year"], "metadata.base_year"),
+ "price_basis": price_basis,
+ "unit": require_text(raw["unit"], "metadata.unit", maximum=80),
+ "taxonomy": require_text(raw["taxonomy"], "metadata.taxonomy"),
+ "taxonomy_version": require_text(
+ raw["taxonomy_version"], "metadata.taxonomy_version"
+ ),
+ "denominator_id": require_identifier(
+ raw["denominator_id"], "metadata.denominator_id"
+ ),
+ "as_of_date": parse_iso_date(raw["as_of_date"], "metadata.as_of_date"),
+ }
+
+
+def _top_down(payload: dict[str, Any], denominator_id: str) -> tuple[float, list[str]]:
+ section = require_object(payload.get("top_down"), "top_down")
+ components = require_list(
+ section.get("components"),
+ "top_down.components",
+ minimum=1,
+ maximum=MAX_COMPONENTS,
+ )
+ component_ids: list[str] = []
+ coverage_keys: list[str] = []
+ total = 0.0
+ for index, item in enumerate(components):
+ row = require_object(item, f"top_down.components[{index}]")
+ component_id = require_identifier(
+ row.get("component_id"),
+ f"top_down.components[{index}].component_id",
+ )
+ component_ids.append(component_id)
+ coverage_key = require_identifier(
+ row.get("coverage_key"),
+ f"top_down.components[{index}].coverage_key",
+ )
+ coverage_keys.append(coverage_key)
+ row_denominator = require_identifier(
+ row.get("denominator_id"),
+ f"top_down.components[{index}].denominator_id",
+ )
+ if row_denominator != denominator_id:
+ raise ValidationError(
+ f"top_down component {component_id} uses denominator "
+ f"{row_denominator!r}; expected {denominator_id!r}"
+ )
+ value = parse_number(
+ row.get("value"),
+ f"top_down.components[{index}].value",
+ minimum=0.0,
+ maximum=MAX_VALUE,
+ )
+ _identifier_array(
+ row.get("source_ids"),
+ f"top_down.components[{index}].source_ids",
+ minimum=1,
+ )
+ _identifier_array(
+ row.get("assumption_ids", []),
+ f"top_down.components[{index}].assumption_ids",
+ )
+ total += value
+ if total > MAX_VALUE:
+ raise ValidationError("top_down TAM exceeds the supported numeric bound")
+ require_unique_identifiers(component_ids, "top_down component IDs")
+ require_unique_identifiers(
+ coverage_keys,
+ "top_down coverage keys (duplicate coverage can double count the market)",
+ )
+ return total, coverage_keys
+
+
+def _bottom_up(
+ payload: dict[str, Any], denominator_id: str
+) -> tuple[float, list[str]]:
+ section = require_object(payload.get("bottom_up"), "bottom_up")
+ components = require_list(
+ section.get("components"),
+ "bottom_up.components",
+ minimum=1,
+ maximum=MAX_COMPONENTS,
+ )
+ component_ids: list[str] = []
+ coverage_keys: list[str] = []
+ total = 0.0
+ for index, item in enumerate(components):
+ row = require_object(item, f"bottom_up.components[{index}]")
+ component_id = require_identifier(
+ row.get("component_id"),
+ f"bottom_up.components[{index}].component_id",
+ )
+ component_ids.append(component_id)
+ coverage_key = require_identifier(
+ row.get("coverage_key"),
+ f"bottom_up.components[{index}].coverage_key",
+ )
+ coverage_keys.append(coverage_key)
+ row_denominator = require_identifier(
+ row.get("denominator_id"),
+ f"bottom_up.components[{index}].denominator_id",
+ )
+ if row_denominator != denominator_id:
+ raise ValidationError(
+ f"bottom_up component {component_id} uses denominator "
+ f"{row_denominator!r}; expected {denominator_id!r}"
+ )
+ customers = parse_number(
+ row.get("customer_count"),
+ f"bottom_up.components[{index}].customer_count",
+ minimum=0.0,
+ maximum=1e15,
+ )
+ annual_quantity = parse_number(
+ row.get("annual_quantity_per_customer"),
+ f"bottom_up.components[{index}].annual_quantity_per_customer",
+ minimum=0.0,
+ maximum=1e12,
+ )
+ price = parse_number(
+ row.get("price_per_unit"),
+ f"bottom_up.components[{index}].price_per_unit",
+ minimum=0.0,
+ maximum=1e15,
+ )
+ addressable_fraction = parse_fraction(
+ row.get("addressable_fraction"),
+ f"bottom_up.components[{index}].addressable_fraction",
+ )
+ _identifier_array(
+ row.get("source_ids"),
+ f"bottom_up.components[{index}].source_ids",
+ minimum=1,
+ )
+ _identifier_array(
+ row.get("assumption_ids", []),
+ f"bottom_up.components[{index}].assumption_ids",
+ )
+ component_value = customers * annual_quantity * price * addressable_fraction
+ if component_value > MAX_VALUE:
+ raise ValidationError(
+ f"bottom_up component {component_id} exceeds the numeric bound"
+ )
+ total += component_value
+ if total > MAX_VALUE:
+ raise ValidationError("bottom_up TAM exceeds the supported numeric bound")
+ require_unique_identifiers(component_ids, "bottom_up component IDs")
+ require_unique_identifiers(
+ coverage_keys,
+ "bottom_up coverage keys (duplicate coverage can double count the market)",
+ )
+ return total, coverage_keys
+
+
+def _scenarios(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ raw_scenarios = require_list(
+ payload.get("scenarios"),
+ "scenarios",
+ minimum=2,
+ maximum=MAX_SCENARIOS,
+ )
+ scenarios: list[dict[str, Any]] = []
+ scenario_ids: list[str] = []
+ parameter_pairs: list[tuple[float, float]] = []
+ for index, item in enumerate(raw_scenarios):
+ row = require_object(item, f"scenarios[{index}]")
+ scenario_id = require_identifier(
+ row.get("scenario_id"), f"scenarios[{index}].scenario_id"
+ )
+ scenario_ids.append(scenario_id)
+ serviceable = parse_fraction(
+ row.get("serviceable_fraction"),
+ f"scenarios[{index}].serviceable_fraction",
+ )
+ obtainable = parse_fraction(
+ row.get("obtainable_share"),
+ f"scenarios[{index}].obtainable_share",
+ )
+ parameter_pairs.append((serviceable, obtainable))
+ assumptions = require_list(
+ row.get("assumptions"),
+ f"scenarios[{index}].assumptions",
+ minimum=1,
+ maximum=100,
+ )
+ parsed_assumptions = [
+ require_text(value, f"scenarios[{index}].assumptions[{position}]")
+ for position, value in enumerate(assumptions)
+ ]
+ scenarios.append(
+ {
+ "scenario_id": scenario_id,
+ "label": require_text(
+ row.get("label"), f"scenarios[{index}].label", maximum=120
+ ),
+ "serviceable_fraction": serviceable,
+ "obtainable_share": obtainable,
+ "source_ids": _identifier_array(
+ row.get("source_ids", []),
+ f"scenarios[{index}].source_ids",
+ ),
+ "assumptions": parsed_assumptions,
+ }
+ )
+ require_unique_identifiers(scenario_ids, "scenario IDs")
+ if len(set(parameter_pairs)) < 2:
+ raise ValidationError(
+ "at least two scenarios must use different sizing assumptions"
+ )
+ return scenarios
+
+
+def calculate(payload: dict[str, Any]) -> dict[str, Any]:
+ schema_version = require_text(
+ payload.get("schema_version"), "schema_version", maximum=10
+ )
+ if schema_version != "1.0":
+ raise ValidationError("schema_version must be '1.0'")
+ metadata = _metadata(payload)
+ top_down_tam, top_keys = _top_down(payload, metadata["denominator_id"])
+ bottom_up_tam, bottom_keys = _bottom_up(payload, metadata["denominator_id"])
+ scenarios = _scenarios(payload)
+ tolerance = parse_number(
+ payload.get("reconciliation_tolerance_percent", 20.0),
+ "reconciliation_tolerance_percent",
+ minimum=0.0,
+ maximum=100.0,
+ )
+
+ midpoint = (top_down_tam + bottom_up_tam) / 2.0
+ reconciliation_percent = (
+ 0.0
+ if midpoint == 0.0
+ else abs(top_down_tam - bottom_up_tam) / midpoint * 100.0
+ )
+ warnings: list[str] = []
+ if reconciliation_percent > tolerance:
+ warnings.append(
+ "top-down and bottom-up TAM estimates exceed the stated "
+ "reconciliation tolerance; investigate scope, denominators, and assumptions"
+ )
+ if set(top_keys) != set(bottom_keys):
+ warnings.append(
+ "the methods use different coverage-key sets; explain the scope difference "
+ "before treating them as direct reconciliation estimates"
+ )
+
+ scenario_results: list[dict[str, Any]] = []
+ for scenario in scenarios:
+ methods: dict[str, dict[str, float]] = {}
+ for method, tam in (
+ ("top_down", top_down_tam),
+ ("bottom_up", bottom_up_tam),
+ ):
+ sam = tam * scenario["serviceable_fraction"]
+ som = sam * scenario["obtainable_share"]
+ methods[method] = {"tam": tam, "sam": sam, "som": som}
+ scenario_results.append({**scenario, "methods": methods})
+
+ all_som = [
+ result["methods"][method]["som"]
+ for result in scenario_results
+ for method in ("top_down", "bottom_up")
+ ]
+ return {
+ "schema_version": "1.0",
+ "metadata": metadata,
+ "method_estimates": {
+ "top_down_tam": top_down_tam,
+ "bottom_up_tam": bottom_up_tam,
+ },
+ "reconciliation": {
+ "absolute_difference": abs(top_down_tam - bottom_up_tam),
+ "difference_percent_of_midpoint": reconciliation_percent,
+ "tolerance_percent": tolerance,
+ "within_tolerance": reconciliation_percent <= tolerance,
+ },
+ "scenario_results": scenario_results,
+ "som_range_across_methods_and_scenarios": {
+ "minimum": min(all_som),
+ "maximum": max(all_som),
+ },
+ "warnings": warnings,
+ "interpretation": (
+ "These are conditional scenario calculations, not a single asserted "
+ "market truth."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Calculate local top-down and bottom-up TAM/SAM/SOM scenarios, "
+ "detect duplicate coverage keys, and report reconciliation."
+ )
+ )
+ parser.add_argument("input", help="Local .json market-sizing input")
+ parser.add_argument("--output", help="Optional local .json result")
+ parser.add_argument(
+ "--force", action="store_true", help="Replace an existing --output file"
+ )
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ payload = require_object(read_json(args.input), "root")
+ write_json_report(calculate(payload), args.output, force=args.force)
+ return 0
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/scripts/check_unit_consistency.py b/skills/market-research-reports/scripts/check_unit_consistency.py
new file mode 100644
index 00000000..e31f9b0e
--- /dev/null
+++ b/skills/market-research-reports/scripts/check_unit_consistency.py
@@ -0,0 +1,217 @@
+#!/usr/bin/env python3
+"""Check units, currency, base year, taxonomy, and denominator consistency."""
+
+from __future__ import annotations
+
+import argparse
+import re
+from typing import Any
+
+from _common import (
+ ValidationError,
+ error_exit,
+ parse_currency,
+ parse_number,
+ parse_year,
+ read_csv_records,
+ require_identifier,
+ require_text,
+ require_unique_identifiers,
+ write_json_report,
+)
+
+REQUIRED_FIELDS = (
+ "record_id",
+ "comparison_group",
+ "value",
+ "unit",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "geography",
+ "period",
+ "taxonomy",
+ "taxonomy_version",
+ "denominator_id",
+ "source_id",
+)
+PRICE_BASES = {
+ "nominal",
+ "real",
+ "current",
+ "constant",
+ "chained",
+ "not-applicable",
+}
+MEASURE_TYPES = {"stock", "flow", "index", "share", "count", "rate", "price"}
+PERIOD_RE = re.compile(
+ r"^(?:\d{4}|\d{4}-Q[1-4]|\d{4}-M(?:0[1-9]|1[0-2])|\d{4}-\d{2}-\d{2})$"
+)
+CONSISTENCY_FIELDS = (
+ "unit",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "geography",
+ "taxonomy",
+ "taxonomy_version",
+ "denominator_id",
+)
+
+
+def check(rows: list[dict[str, str]]) -> dict[str, Any]:
+ errors: list[str] = []
+ record_ids: list[str] = []
+ groups: dict[str, dict[str, set[str]]] = {}
+
+ for row_number, row in enumerate(rows, start=2):
+ context = f"row {row_number}"
+ try:
+ record_id = require_identifier(row["record_id"], f"{context}.record_id")
+ record_ids.append(record_id)
+ group = require_identifier(
+ row["comparison_group"], f"{context}.comparison_group"
+ )
+ parse_number(
+ row["value"],
+ f"{context}.value",
+ minimum=-1e18,
+ maximum=1e18,
+ )
+ unit = require_text(row["unit"], f"{context}.unit", maximum=80)
+ currency = parse_currency(
+ row["currency"], f"{context}.currency", allow_empty=True
+ )
+ base_year = require_text(
+ row["base_year"],
+ f"{context}.base_year",
+ allow_empty=True,
+ maximum=4,
+ )
+ if base_year:
+ parse_year(base_year, f"{context}.base_year")
+ price_basis = require_text(
+ row["price_basis"], f"{context}.price_basis", maximum=20
+ )
+ if price_basis not in PRICE_BASES:
+ raise ValidationError(
+ f"{context}.price_basis must be one of "
+ f"{', '.join(sorted(PRICE_BASES))}"
+ )
+ if currency and (not base_year or price_basis == "not-applicable"):
+ raise ValidationError(
+ f"{context}: monetary rows require base_year and price_basis"
+ )
+ if not currency and price_basis != "not-applicable":
+ raise ValidationError(
+ f"{context}: non-monetary rows must use price_basis "
+ "'not-applicable'"
+ )
+
+ measure_type = require_text(
+ row["measure_type"], f"{context}.measure_type", maximum=20
+ )
+ if measure_type not in MEASURE_TYPES:
+ raise ValidationError(
+ f"{context}.measure_type must be one of "
+ f"{', '.join(sorted(MEASURE_TYPES))}"
+ )
+ geography = require_text(
+ row["geography"], f"{context}.geography", maximum=200
+ )
+ period = require_text(row["period"], f"{context}.period", maximum=10)
+ if not PERIOD_RE.fullmatch(period):
+ raise ValidationError(
+ f"{context}.period must be YYYY, YYYY-Qn, YYYY-Mnn, "
+ "or YYYY-MM-DD"
+ )
+ taxonomy = require_text(
+ row["taxonomy"], f"{context}.taxonomy", allow_empty=True
+ )
+ taxonomy_version = require_text(
+ row["taxonomy_version"],
+ f"{context}.taxonomy_version",
+ allow_empty=True,
+ )
+ denominator_id = require_identifier(
+ row["denominator_id"], f"{context}.denominator_id"
+ )
+ require_identifier(row["source_id"], f"{context}.source_id")
+
+ normalized = {
+ "unit": unit,
+ "currency": currency,
+ "base_year": base_year,
+ "price_basis": price_basis,
+ "measure_type": measure_type,
+ "geography": geography,
+ "taxonomy": taxonomy,
+ "taxonomy_version": taxonomy_version,
+ "denominator_id": denominator_id,
+ }
+ group_values = groups.setdefault(
+ group, {field: set() for field in CONSISTENCY_FIELDS}
+ )
+ for field, value in normalized.items():
+ group_values[field].add(value)
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ try:
+ require_unique_identifiers(record_ids, "record IDs")
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ mismatches: dict[str, dict[str, list[str]]] = {}
+ for group, values in sorted(groups.items()):
+ group_mismatches = {
+ field: sorted(observed)
+ for field, observed in values.items()
+ if len(observed) > 1
+ }
+ if group_mismatches:
+ mismatches[group] = group_mismatches
+ errors.append(
+ f"comparison group {group!r} mixes: "
+ + ", ".join(sorted(group_mismatches))
+ )
+
+ return {
+ "valid": not errors,
+ "record_count": len(rows),
+ "comparison_group_count": len(groups),
+ "mismatches": mismatches,
+ "errors": errors,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Check a local CSV for internally comparable units, currencies, base "
+ "years, price bases, measure types, geographies, taxonomies, and "
+ "denominators."
+ )
+ )
+ parser.add_argument("input", help="Local .csv consistency input")
+ parser.add_argument("--output", help="Optional local .json report")
+ parser.add_argument(
+ "--force", action="store_true", help="Replace an existing --output file"
+ )
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ report = check(read_csv_records(args.input, required_fields=REQUIRED_FIELDS))
+ write_json_report(report, args.output, force=args.force)
+ return 0 if report["valid"] else 1
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/scripts/forecast_sensitivity.py b/skills/market-research-reports/scripts/forecast_sensitivity.py
new file mode 100644
index 00000000..439891f4
--- /dev/null
+++ b/skills/market-research-reports/scripts/forecast_sensitivity.py
@@ -0,0 +1,326 @@
+#!/usr/bin/env python3
+"""Generate deterministic scenario forecasts and one-way growth sensitivity."""
+
+from __future__ import annotations
+
+import argparse
+from typing import Any
+
+from _common import (
+ ValidationError,
+ error_exit,
+ parse_currency,
+ parse_iso_date,
+ parse_number,
+ parse_year,
+ read_json,
+ require_identifier,
+ require_list,
+ require_object,
+ require_text,
+ require_unique_identifiers,
+ write_json_report,
+)
+
+MAX_VALUE = 1e18
+MAX_HORIZON = 50
+MAX_SCENARIOS = 20
+
+
+def _identifiers(value: Any, context: str, *, minimum: int = 0) -> list[str]:
+ items = require_list(value, context, minimum=minimum, maximum=100)
+ parsed = [
+ require_identifier(item, f"{context}[{index}]")
+ for index, item in enumerate(items)
+ ]
+ require_unique_identifiers(parsed, context)
+ return parsed
+
+
+def _integer(value: Any, context: str, minimum: int, maximum: int) -> int:
+ if type(value) is not int:
+ raise ValidationError(f"{context} must be an integer")
+ if not minimum <= value <= maximum:
+ raise ValidationError(f"{context} must be between {minimum} and {maximum}")
+ return value
+
+
+def _metadata(payload: dict[str, Any]) -> dict[str, Any]:
+ raw = require_object(payload.get("metadata"), "metadata")
+ required = (
+ "series_id",
+ "description",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "unit",
+ "measure_type",
+ "as_of_date",
+ "source_ids",
+ )
+ missing = [field for field in required if field not in raw]
+ if missing:
+ raise ValidationError(f"metadata is missing: {', '.join(missing)}")
+ currency = parse_currency(raw["currency"], "metadata.currency", allow_empty=True)
+ base_year_text = require_text(
+ raw["base_year"], "metadata.base_year", allow_empty=True, maximum=4
+ )
+ base_year: int | None = None
+ if base_year_text:
+ base_year = parse_year(base_year_text, "metadata.base_year")
+ price_basis = require_text(raw["price_basis"], "metadata.price_basis", maximum=20)
+ if price_basis not in {
+ "nominal",
+ "real",
+ "current",
+ "constant",
+ "not-applicable",
+ }:
+ raise ValidationError("metadata.price_basis has an unsupported value")
+ if currency and (base_year is None or price_basis == "not-applicable"):
+ raise ValidationError(
+ "monetary forecasts require currency, base_year, and price_basis"
+ )
+ measure_type = require_text(
+ raw["measure_type"], "metadata.measure_type", maximum=20
+ )
+ if measure_type not in {"stock", "flow", "index", "share", "count", "rate", "price"}:
+ raise ValidationError("metadata.measure_type has an unsupported value")
+ return {
+ "series_id": require_identifier(raw["series_id"], "metadata.series_id"),
+ "description": require_text(raw["description"], "metadata.description"),
+ "geography": require_text(raw["geography"], "metadata.geography"),
+ "currency": currency,
+ "base_year": base_year,
+ "price_basis": price_basis,
+ "unit": require_text(raw["unit"], "metadata.unit", maximum=80),
+ "measure_type": measure_type,
+ "as_of_date": parse_iso_date(raw["as_of_date"], "metadata.as_of_date"),
+ "source_ids": _identifiers(
+ raw["source_ids"], "metadata.source_ids", minimum=1
+ ),
+ }
+
+
+def _rate_path(value: Any, context: str, horizon: int) -> list[float]:
+ items = require_list(value, context, minimum=horizon, maximum=horizon)
+ return [
+ parse_number(
+ item,
+ f"{context}[{index}]",
+ minimum=-0.99,
+ maximum=10.0,
+ )
+ for index, item in enumerate(items)
+ ]
+
+
+def _project(
+ start_year: int, start_value: float, rates: list[float]
+) -> list[dict[str, float | int]]:
+ observations: list[dict[str, float | int]] = [
+ {"year": start_year, "value": start_value}
+ ]
+ value = start_value
+ for offset, rate in enumerate(rates, start=1):
+ value *= 1.0 + rate
+ if value > MAX_VALUE:
+ raise ValidationError("forecast exceeds the supported numeric bound")
+ observations.append(
+ {"year": start_year + offset, "value": value, "growth_rate": rate}
+ )
+ return observations
+
+
+def _cagr(start: float, end: float, periods: int) -> float | None:
+ if periods <= 0 or start <= 0.0 or end < 0.0:
+ return None
+ return (end / start) ** (1.0 / periods) - 1.0
+
+
+def forecast(payload: dict[str, Any]) -> dict[str, Any]:
+ schema_version = require_text(
+ payload.get("schema_version"), "schema_version", maximum=10
+ )
+ if schema_version != "1.0":
+ raise ValidationError("schema_version must be '1.0'")
+ metadata = _metadata(payload)
+ start_year = parse_year(payload.get("start_year"), "start_year")
+ start_value = parse_number(
+ payload.get("start_value"),
+ "start_value",
+ minimum=0.0,
+ maximum=MAX_VALUE,
+ )
+ horizon = _integer(
+ payload.get("horizon_years"),
+ "horizon_years",
+ minimum=1,
+ maximum=MAX_HORIZON,
+ )
+
+ raw_scenarios = require_list(
+ payload.get("scenarios"),
+ "scenarios",
+ minimum=2,
+ maximum=MAX_SCENARIOS,
+ )
+ scenario_ids: list[str] = []
+ unique_paths: set[tuple[float, ...]] = set()
+ scenario_results: list[dict[str, Any]] = []
+ scenario_rates: dict[str, list[float]] = {}
+ for index, item in enumerate(raw_scenarios):
+ row = require_object(item, f"scenarios[{index}]")
+ if "probability" in row:
+ raise ValidationError(
+ f"scenarios[{index}].probability is not accepted; do not assign "
+ "probabilities without a separately validated probabilistic model"
+ )
+ scenario_id = require_identifier(
+ row.get("scenario_id"), f"scenarios[{index}].scenario_id"
+ )
+ scenario_ids.append(scenario_id)
+ rates = _rate_path(
+ row.get("annual_growth_rates"),
+ f"scenarios[{index}].annual_growth_rates",
+ horizon,
+ )
+ unique_paths.add(tuple(rates))
+ scenario_rates[scenario_id] = rates
+ assumptions = require_list(
+ row.get("assumptions"),
+ f"scenarios[{index}].assumptions",
+ minimum=1,
+ maximum=100,
+ )
+ observations = _project(start_year, start_value, rates)
+ scenario_results.append(
+ {
+ "scenario_id": scenario_id,
+ "label": require_text(
+ row.get("label"), f"scenarios[{index}].label", maximum=120
+ ),
+ "source_ids": _identifiers(
+ row.get("source_ids", []),
+ f"scenarios[{index}].source_ids",
+ ),
+ "assumptions": [
+ require_text(
+ assumption,
+ f"scenarios[{index}].assumptions[{position}]",
+ )
+ for position, assumption in enumerate(assumptions)
+ ],
+ "annual_growth_rates": rates,
+ "observations": observations,
+ "endpoint": observations[-1]["value"],
+ "cagr": _cagr(start_value, float(observations[-1]["value"]), horizon),
+ }
+ )
+ require_unique_identifiers(scenario_ids, "scenario IDs")
+ if len(unique_paths) < 2:
+ raise ValidationError("at least two scenarios must use different rate paths")
+
+ sensitivity = require_object(payload.get("sensitivity"), "sensitivity")
+ base_scenario_id = require_identifier(
+ sensitivity.get("base_scenario_id"), "sensitivity.base_scenario_id"
+ )
+ if base_scenario_id not in scenario_rates:
+ raise ValidationError(
+ "sensitivity.base_scenario_id must reference one of the scenarios"
+ )
+ shifts_raw = require_list(
+ sensitivity.get("growth_rate_shifts"),
+ "sensitivity.growth_rate_shifts",
+ minimum=2,
+ maximum=21,
+ )
+ shifts = [
+ parse_number(
+ value,
+ f"sensitivity.growth_rate_shifts[{index}]",
+ minimum=-0.5,
+ maximum=0.5,
+ )
+ for index, value in enumerate(shifts_raw)
+ ]
+ if len(shifts) != len(set(shifts)):
+ raise ValidationError("sensitivity.growth_rate_shifts must be unique")
+ sensitivity_results: list[dict[str, Any]] = []
+ for shift in sorted(shifts):
+ shifted_rates = [rate + shift for rate in scenario_rates[base_scenario_id]]
+ if any(rate < -0.99 or rate > 10.0 for rate in shifted_rates):
+ raise ValidationError(
+ f"sensitivity shift {shift} produces an out-of-bounds growth rate"
+ )
+ observations = _project(start_year, start_value, shifted_rates)
+ sensitivity_results.append(
+ {
+ "growth_rate_shift": shift,
+ "annual_growth_rates": shifted_rates,
+ "endpoint": observations[-1]["value"],
+ "observations": observations,
+ }
+ )
+
+ ranges: list[dict[str, float | int]] = []
+ for offset in range(horizon + 1):
+ values = [
+ float(result["observations"][offset]["value"])
+ for result in scenario_results
+ ]
+ ranges.append(
+ {
+ "year": start_year + offset,
+ "minimum": min(values),
+ "maximum": max(values),
+ }
+ )
+
+ return {
+ "schema_version": "1.0",
+ "metadata": metadata,
+ "start_year": start_year,
+ "start_value": start_value,
+ "horizon_years": horizon,
+ "scenarios": scenario_results,
+ "scenario_range_by_year": ranges,
+ "sensitivity": {
+ "base_scenario_id": base_scenario_id,
+ "results": sensitivity_results,
+ },
+ "interpretation": (
+ "Ranges are conditional on documented scenarios and are not confidence "
+ "intervals or assigned probabilities."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Generate bounded local scenario forecasts and one-way growth-rate "
+ "sensitivity. No network or random sampling is used."
+ )
+ )
+ parser.add_argument("input", help="Local .json forecast input")
+ parser.add_argument("--output", help="Optional local .json result")
+ parser.add_argument(
+ "--force", action="store_true", help="Replace an existing --output file"
+ )
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ payload = require_object(read_json(args.input), "root")
+ write_json_report(forecast(payload), args.output, force=args.force)
+ return 0
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/scripts/generate_market_visuals.py b/skills/market-research-reports/scripts/generate_market_visuals.py
deleted file mode 100755
index c2278949..00000000
--- a/skills/market-research-reports/scripts/generate_market_visuals.py
+++ /dev/null
@@ -1,529 +0,0 @@
-#!/usr/bin/env python3
-"""
-Market Research Report Visual Generator
-
-Batch generates visuals for a market research report using
-scientific-schematics and generate-image skills.
-
-Default behavior: Generate 5-6 core visuals only
-Use --all flag to generate all 28 extended visuals
-
-Usage:
- # Generate core 5-6 visuals (recommended for starting a report)
- python generate_market_visuals.py --topic "Electric Vehicle Charging" --output-dir figures/
-
- # Generate all 28 visuals (for comprehensive coverage)
- python generate_market_visuals.py --topic "AI in Healthcare" --output-dir figures/ --all
-
- # Skip existing files
- python generate_market_visuals.py --topic "Topic" --output-dir figures/ --skip-existing
-"""
-
-import argparse
-import os
-import subprocess
-import sys
-from pathlib import Path
-
-
-# Visual definitions with prompts
-# Each tuple: (filename, tool, prompt_template, is_core)
-# is_core=True for the 5-6 essential visuals to generate first
-
-CORE_VISUALS = [
- # Priority 1: Market Growth Trajectory
- (
- "01_market_growth_trajectory.png",
- "scientific-schematics",
- "Bar chart {topic} market growth 2020 to 2034. Historical bars 2020-2024 in dark blue, "
- "projected bars 2025-2034 in light blue. Y-axis billions USD, X-axis years. "
- "CAGR annotation. Data labels on each bar. Vertical dashed line "
- "between 2024 and 2025. Title: Market Growth Trajectory. Professional white background"
- ),
-
- # Priority 2: TAM/SAM/SOM
- (
- "02_tam_sam_som.png",
- "scientific-schematics",
- "TAM SAM SOM concentric circles for {topic} market. Outer circle TAM Total Addressable "
- "Market. Middle circle SAM Serviceable Addressable Market. Inner circle SOM Serviceable "
- "Obtainable Market. Each labeled with acronym, full name. "
- "Blue gradient darkest outer to lightest inner. White background professional appearance"
- ),
-
- # Priority 3: Porter's Five Forces
- (
- "03_porters_five_forces.png",
- "scientific-schematics",
- "Porter's Five Forces diagram for {topic}. Center box Competitive Rivalry with rating. "
- "Four surrounding boxes with arrows to center: Top Threat of New Entrants, "
- "Left Bargaining Power Suppliers, Right Bargaining Power Buyers, "
- "Bottom Threat of Substitutes. Color code HIGH red, MEDIUM yellow, LOW green. "
- "Include 2-3 key factors per box. Professional appearance"
- ),
-
- # Priority 4: Competitive Positioning Matrix
- (
- "04_competitive_positioning.png",
- "scientific-schematics",
- "2x2 competitive positioning matrix {topic}. X-axis Market Focus Niche to Broad. "
- "Y-axis Solution Approach Product to Platform. Quadrants: Upper-right Platform Leaders, "
- "Upper-left Niche Platforms, Lower-right Product Leaders, Lower-left Specialists. "
- "Plot 8-10 company circles with names. Circle size = market share. "
- "Legend for sizes. Professional appearance"
- ),
-
- # Priority 5: Risk Heatmap
- (
- "05_risk_heatmap.png",
- "scientific-schematics",
- "Risk heatmap matrix {topic}. X-axis Impact Low Medium High Critical. "
- "Y-axis Probability Unlikely Possible Likely Very Likely. "
- "Cell colors: Green low risk, Yellow medium, Orange high, Red critical. "
- "Plot 10-12 numbered risks R1 R2 etc as labeled points. "
- "Legend with risk names. Professional clear"
- ),
-
- # Priority 6: Executive Summary Infographic (Optional)
- (
- "06_exec_summary_infographic.png",
- "generate-image",
- "Executive summary infographic for {topic} market research, one page layout, "
- "central large metric showing market size, four quadrants showing growth rate "
- "key players top segments regional leaders, modern flat design, professional "
- "blue and green color scheme, clean white background, corporate business aesthetic"
- ),
-]
-
-EXTENDED_VISUALS = [
- # Industry Ecosystem
- (
- "07_industry_ecosystem.png",
- "scientific-schematics",
- "Industry ecosystem value chain diagram for {topic} market. Horizontal flow left "
- "to right: Suppliers box → Manufacturers box → Distributors box → End Users box. "
- "Below each main box show 3-4 smaller boxes with example player types. Solid arrows "
- "for product flow, dashed arrows for money flow. Regulatory oversight layer above. "
- "Professional blue color scheme, white background, clear labels"
- ),
-
- # Regional Breakdown
- (
- "08_regional_breakdown.png",
- "scientific-schematics",
- "scientific-schematics",
- "Pie chart regional market breakdown for {topic}. North America 40% dark blue, "
- "Europe 28% medium blue, Asia-Pacific 22% teal, Latin America 6% light blue, "
- "Middle East Africa 4% gray blue. Show percentage for each slice. Legend on right. "
- "Title: Market Size by Region. Professional appearance"
- ),
-
- # Segment Growth
- (
- "09_segment_growth.png",
- "scientific-schematics",
- "Horizontal bar chart {topic} segment growth comparison. Y-axis 5-6 segment names, "
- "X-axis CAGR percentage 0-30%. Bars colored green highest to blue lowest. "
- "Data labels with percentages. Sorted highest to lowest. "
- "Title: Segment Growth Rate Comparison. Include market average line"
- ),
-
- # Driver Impact Matrix
- (
- "10_driver_impact_matrix.png",
- "scientific-schematics",
- "2x2 matrix driver impact assessment for {topic}. X-axis Impact Low to High, "
- "Y-axis Probability Low to High. Quadrants: Upper-right CRITICAL DRIVERS red, "
- "Upper-left MONITOR yellow, Lower-right WATCH CAREFULLY yellow, "
- "Lower-left LOWER PRIORITY green. Plot 8 labeled driver circles at positions. "
- "Circle size indicates current impact. Professional clear labels"
- ),
-
- # PESTLE Analysis
- (
- "11_pestle_analysis.png",
- "scientific-schematics",
- "PESTLE hexagonal diagram for {topic} market. Center hexagon labeled Market Analysis. "
- "Six surrounding hexagons: Political red, Economic blue, Social green, "
- "Technological orange, Legal purple, Environmental teal. Each outer hexagon "
- "has 2-3 bullet points of key factors. Lines connecting center to each. "
- "Professional appearance clear readable text"
- ),
-
- # Trends Timeline
- (
- "12_trends_timeline.png",
- "scientific-schematics",
- "Horizontal timeline {topic} trends 2024 to 2030. Plot 6-8 emerging trends at "
- "different years. Each trend with icon, name, brief description. Color code: "
- "Technology trends blue, Market trends green, Regulatory trends orange. "
- "Current marker at 2024. Professional clear labels"
- ),
-
- # Market Share Chart
- (
- "13_market_share.png",
- "scientific-schematics",
- "Pie chart market share {topic} top 10 companies. Company A 18% dark blue, "
- "Company B 15% medium blue, Company C 12% teal, Company D 10% light blue, "
- "5 more companies 5-8% each various blues, Others 15% gray. "
- "Percentage labels on slices. Legend with company names. "
- "Title: Market Share by Company. Colorblind-friendly colors professional"
- ),
-
- # Strategic Groups Map
- (
- "14_strategic_groups.png",
- "scientific-schematics",
- "Strategic group map {topic}. X-axis Geographic Scope Regional to Global. "
- "Y-axis Product Breadth Narrow to Broad. Draw 4-5 oval bubbles for strategic groups. "
- "Each bubble contains 2-4 company names. Bubble size = collective market share. "
- "Label groups: Global Generalists, Regional Specialists, Focused Innovators. "
- "Different colors per group. Professional clear labels"
- ),
-
- # Customer Segments
- (
- "15_customer_segments.png",
- "scientific-schematics",
- "Treemap customer segmentation {topic}. Large Enterprise 45% dark blue, "
- "Mid-Market 30% medium blue, SMB 18% light blue, Consumer 7% teal. "
- "Each segment shows name and percentage. Title: Customer Segmentation by Market Share. "
- "Professional appearance clear labels"
- ),
- (
- "16_segment_attractiveness.png",
- "scientific-schematics",
- "2x2 segment attractiveness matrix {topic}. X-axis Segment Size Small to Large. "
- "Y-axis Growth Rate Low to High. Quadrants: Upper-right PRIORITY Invest Heavily green, "
- "Upper-left INVEST TO GROW yellow, Lower-right HARVEST orange, "
- "Lower-left DEPRIORITIZE gray. Plot customer segments as circles. "
- "Circle size = profitability. Different colors. Professional"
- ),
- (
- "17_customer_journey.png",
- "scientific-schematics",
- "Customer journey horizontal flowchart {topic}. 5 stages left to right: Awareness, "
- "Consideration, Decision, Implementation, Advocacy. Each stage shows Key Activities, "
- "Pain Points, Touchpoints in rows below. Icons for each stage. "
- "Color gradient light to dark. Professional clear labels"
- ),
-
- # Technology Roadmap
- (
- "18_technology_roadmap.png",
- "scientific-schematics",
- "Technology roadmap {topic} 2024 to 2030. Three parallel horizontal tracks: "
- "Core Technology blue, Emerging Technology green, Enabling Technology orange. "
- "Milestones and tech introductions marked on each track. Vertical lines connect "
- "related tech. Year markers. Technology names labeled. Professional appearance"
- ),
- (
- "19_innovation_curve.png",
- "scientific-schematics",
- "Gartner Hype Cycle curve for {topic} technologies. Five phases: Innovation Trigger "
- "rising, Peak of Inflated Expectations at top, Trough of Disillusionment at bottom, "
- "Slope of Enlightenment rising, Plateau of Productivity stable. "
- "Plot 6-8 technologies on curve with labels. Color by category. Professional clear labels"
- ),
-
- # Regulatory Timeline
- (
- "20_regulatory_timeline.png",
- "scientific-schematics",
- "Regulatory timeline {topic} 2020 to 2028. Past regulations dark blue solid markers, "
- "current green marker, upcoming light blue dashed. Each shows regulation name, date, "
- "brief description. Vertical NOW line at 2024. Professional appearance clear labels"
- ),
-
- # Risk Mitigation Matrix
- (
- "21_risk_mitigation.png",
- "scientific-schematics",
- "Risk mitigation diagram {topic}. Left column risks in orange/red boxes. "
- "Right column mitigation strategies in green/blue boxes. Arrows connecting "
- "risks to mitigations. Group by category. Risk severity by color intensity. "
- "Include prevention and response. Professional clear labels"
- ),
-
- # Opportunity Matrix
- (
- "22_opportunity_matrix.png",
- "scientific-schematics",
- "2x2 opportunity matrix {topic}. X-axis Market Attractiveness Low to High. "
- "Y-axis Ability to Win Low to High. Quadrants: Upper-right PURSUE AGGRESSIVELY green, "
- "Upper-left BUILD CAPABILITIES yellow, Lower-right SELECTIVE INVESTMENT yellow, "
- "Lower-left AVOID red. Plot 6-8 opportunity circles with labels. "
- "Size = opportunity value. Professional"
- ),
-
- # Recommendation Priority Matrix
- (
- "23_recommendation_priority.png",
- "scientific-schematics",
- "2x2 priority matrix {topic} recommendations. X-axis Effort Low to High. "
- "Y-axis Impact Low to High. Quadrants: Upper-left QUICK WINS green Do First, "
- "Upper-right MAJOR PROJECTS blue Plan Carefully, Lower-left FILL-INS gray Do If Time, "
- "Lower-right THANKLESS TASKS red Avoid. Plot 6-8 numbered recommendations. Professional"
- ),
-
- # Implementation Timeline
- (
- "24_implementation_timeline.png",
- "scientific-schematics",
- "Gantt chart implementation {topic} 24 months. Phase 1 Foundation months 1-6 dark blue. "
- "Phase 2 Build months 4-12 medium blue. Phase 3 Scale months 10-18 teal. "
- "Phase 4 Optimize months 16-24 light blue. Overlapping bars. "
- "Key milestones as diamonds. Month markers X-axis. Professional"
- ),
-
- # Milestone Tracker
- (
- "25_milestone_tracker.png",
- "scientific-schematics",
- "Milestone tracker {topic} horizontal timeline 8-10 milestones. "
- "Each shows date, name, status: Completed green check, In Progress yellow circle, "
- "Upcoming gray circle. Group by phase. Phase labels above. "
- "Connected timeline line. Professional"
- ),
-
- # Financial Projections
- (
- "26_financial_projections.png",
- "scientific-schematics",
- "Combined bar and line chart {topic} 5-year projections. Bar chart revenue "
- "primary Y-axis dollars. Line chart growth rate secondary Y-axis percent. "
- "Three scenarios: Conservative gray, Base Case blue, Optimistic green. "
- "X-axis Year 1-5. Data labels. Legend. Title Financial Projections 5-Year. Professional"
- ),
-
- # Scenario Analysis
- (
- "27_scenario_analysis.png",
- "scientific-schematics",
- "Grouped bar chart {topic} scenario comparison. X-axis metrics: Revenue Y5, "
- "EBITDA Y5, Market Share, ROI. Three bars per metric: Conservative gray, "
- "Base Case blue, Optimistic green. Data labels. Legend. "
- "Title Scenario Analysis Comparison. Professional clear labels"
- ),
-]
-
-
-def get_script_path(tool: str) -> Path:
- """Get the path to the appropriate generation script."""
- base_path = Path(__file__).parent.parent.parent # skills directory
-
- if tool == "scientific-schematics":
- return base_path / "scientific-schematics" / "scripts" / "generate_schematic.py"
- elif tool == "generate-image":
- return base_path / "generate-image" / "scripts" / "generate_image.py"
- else:
- raise ValueError(f"Unknown tool: {tool}")
-
-
-def generate_visual(
- filename: str,
- tool: str,
- prompt: str,
- output_dir: Path,
- topic: str,
- skip_existing: bool = False,
- verbose: bool = False
-) -> bool:
- """Generate a single visual using the appropriate tool."""
- output_path = output_dir / filename
-
- # Skip if exists and skip_existing is True
- if skip_existing and output_path.exists():
- if verbose:
- print(f" [SKIP] {filename} already exists")
- return True
-
- # Format prompt with topic
- formatted_prompt = prompt.format(topic=topic)
-
- # Get script path
- script_path = get_script_path(tool)
-
- if not script_path.exists():
- print(f" [ERROR] Script not found: {script_path}")
- return False
-
- # Build command
- if tool == "scientific-schematics":
- cmd = [
- sys.executable,
- str(script_path),
- formatted_prompt,
- "-o", str(output_path),
- "--doc-type", "report"
- ]
- else: # generate-image
- cmd = [
- sys.executable,
- str(script_path),
- formatted_prompt,
- "--output", str(output_path)
- ]
-
- if verbose:
- print(f" [GEN] {filename}")
- print(f" Tool: {tool}")
- print(f" Prompt: {formatted_prompt[:80]}...")
-
- try:
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=120 # 2 minute timeout per image
- )
-
- if result.returncode == 0:
- if verbose:
- print(f" [OK] {filename} generated successfully")
- return True
- else:
- print(f" [ERROR] {filename} failed:")
- if result.stderr:
- print(f" {result.stderr[:200]}")
- return False
-
- except subprocess.TimeoutExpired:
- print(f" [TIMEOUT] {filename} generation timed out")
- return False
- except Exception as e:
- print(f" [ERROR] {filename}: {str(e)}")
- return False
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Generate visuals for a market research report (default: 5-6 core visuals)"
- )
- parser.add_argument(
- "--topic", "-t",
- required=True,
- help="Market topic (e.g., 'Electric Vehicle Charging Infrastructure')"
- )
- parser.add_argument(
- "--output-dir", "-o",
- default="figures",
- help="Output directory for generated images (default: figures)"
- )
- parser.add_argument(
- "--all", "-a",
- action="store_true",
- help="Generate all 27 extended visuals (default: only core 5-6)"
- )
- parser.add_argument(
- "--skip-existing", "-s",
- action="store_true",
- help="Skip generation if file already exists"
- )
- parser.add_argument(
- "--verbose", "-v",
- action="store_true",
- help="Show detailed output"
- )
- parser.add_argument(
- "--dry-run",
- action="store_true",
- help="Show what would be generated without actually generating"
- )
- parser.add_argument(
- "--only",
- type=str,
- help="Only generate visuals matching this pattern (e.g., '01_', 'porter')"
- )
-
- args = parser.parse_args()
-
- # Create output directory
- output_dir = Path(args.output_dir)
- if not args.dry_run:
- output_dir.mkdir(parents=True, exist_ok=True)
-
- print(f"\n{'='*60}")
- print(f"Market Research Visual Generator")
- print(f"{'='*60}")
- print(f"Topic: {args.topic}")
- print(f"Output Directory: {output_dir.absolute()}")
- print(f"Mode: {'All Visuals (27)' if args.all else 'Core Visuals Only (5-6)'}")
- print(f"Skip Existing: {args.skip_existing}")
- print(f"{'='*60}\n")
-
- # Select visual set based on --all flag
- if args.all:
- visuals_to_generate = CORE_VISUALS + EXTENDED_VISUALS
- print("Generating ALL visuals (core + extended)\n")
- else:
- visuals_to_generate = CORE_VISUALS
- print("Generating CORE visuals only (use --all for extended set)\n")
-
- # Filter visuals if --only specified
- if args.only:
- pattern = args.only.lower()
- visuals_to_generate = [
- v for v in VISUALS
- if pattern in v[0].lower() or pattern in v[2].lower()
- ]
- print(f"Filtered to {len(visuals_to_generate)} visuals matching '{args.only}'\n")
-
- if args.dry_run:
- print("DRY RUN - The following visuals would be generated:\n")
- for filename, tool, prompt in visuals_to_generate:
- formatted = prompt.format(topic=args.topic)
- print(f" {filename}")
- print(f" Tool: {tool}")
- print(f" Prompt: {formatted[:60]}...")
- print()
- return
-
- # Generate all visuals
- total = len(visuals_to_generate)
- success = 0
- failed = 0
- skipped = 0
-
- for i, (filename, tool, prompt) in enumerate(visuals_to_generate, 1):
- print(f"\n[{i}/{total}] Generating {filename}...")
-
- result = generate_visual(
- filename=filename,
- tool=tool,
- prompt=prompt,
- output_dir=output_dir,
- topic=args.topic,
- skip_existing=args.skip_existing,
- verbose=args.verbose
- )
-
- if result:
- if args.skip_existing and (output_dir / filename).exists():
- skipped += 1
- else:
- success += 1
- else:
- failed += 1
-
- # Print summary
- print(f"\n{'='*60}")
- print(f"Generation Complete")
- print(f"{'='*60}")
- print(f"Total: {total}")
- print(f"Success: {success}")
- print(f"Skipped: {skipped}")
- print(f"Failed: {failed}")
- print(f"{'='*60}")
-
- if failed > 0:
- print(f"\nWARNING: {failed} visuals failed to generate.")
- print("Check the output above for error details.")
- print("You may need to generate failed visuals manually.")
-
- print(f"\nOutput directory: {output_dir.absolute()}")
-
-
-if __name__ == "__main__":
- main()
diff --git a/skills/market-research-reports/scripts/generate_report_scaffold.py b/skills/market-research-reports/scripts/generate_report_scaffold.py
new file mode 100644
index 00000000..c3e8688f
--- /dev/null
+++ b/skills/market-research-reports/scripts/generate_report_scaffold.py
@@ -0,0 +1,444 @@
+#!/usr/bin/env python3
+"""Generate a bounded local evidence-first market-report workspace."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import json
+import re
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ ValidationError,
+ error_exit,
+ parse_currency,
+ parse_iso_date,
+ parse_year,
+ read_json,
+ require_identifier,
+ require_list,
+ require_object,
+ require_text,
+ write_json_report,
+)
+
+PERIOD_RE = re.compile(r"^\d{4}-\d{4}$")
+SOURCE_FIELDS = (
+ "source_id",
+ "title",
+ "publisher",
+ "url",
+ "source_type",
+ "publication_date",
+ "retrieval_date",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "unit",
+ "taxonomy",
+ "taxonomy_version",
+ "revision_status",
+ "method",
+ "sample",
+ "limitations",
+ "license_or_terms",
+ "archive_path",
+)
+CLAIM_FIELDS = (
+ "claim_id",
+ "claim_text",
+ "claim_type",
+ "source_ids",
+ "calculation_id",
+ "assumption_ids",
+ "location",
+ "as_of_date",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "unit",
+ "taxonomy",
+ "taxonomy_version",
+ "revision_status",
+ "confidence",
+ "notes",
+)
+COMPETITOR_FIELDS = (
+ "competitor_id",
+ "competitor_name",
+ "feature_id",
+ "feature_name",
+ "status",
+ "evidence_source_ids",
+ "as_of_date",
+ "geography",
+ "product_scope",
+ "notes",
+)
+CONSISTENCY_FIELDS = (
+ "record_id",
+ "comparison_group",
+ "value",
+ "unit",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "geography",
+ "period",
+ "taxonomy",
+ "taxonomy_version",
+ "denominator_id",
+ "source_id",
+)
+ASSUMPTION_FIELDS = (
+ "assumption_id",
+ "description",
+ "downside_value",
+ "base_value",
+ "upside_value",
+ "unit",
+ "source_ids",
+ "rationale",
+)
+
+
+def _string_list(value: Any, context: str) -> list[str]:
+ items = require_list(value, context, minimum=1, maximum=100)
+ return [
+ require_text(item, f"{context}[{index}]", maximum=500)
+ for index, item in enumerate(items)
+ ]
+
+
+def _period(value: Any, context: str) -> str:
+ text = require_text(value, context, maximum=9)
+ if not PERIOD_RE.fullmatch(text):
+ raise ValidationError(f"{context} must be YYYY-YYYY")
+ start, end = (int(part) for part in text.split("-"))
+ if start > end:
+ raise ValidationError(f"{context} start year must not exceed end year")
+ parse_year(start, context)
+ parse_year(end, context)
+ return text
+
+
+def validate_manifest(payload: dict[str, Any]) -> dict[str, Any]:
+ required = (
+ "schema_version",
+ "report_id",
+ "title",
+ "subtitle",
+ "prepared_for",
+ "prepared_by",
+ "classification",
+ "market_definition",
+ "inclusions",
+ "exclusions",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "taxonomy",
+ "taxonomy_version",
+ "historical_period",
+ "forecast_period",
+ "retrieval_cutoff",
+ )
+ missing = [field for field in required if field not in payload]
+ if missing:
+ raise ValidationError(f"manifest is missing: {', '.join(missing)}")
+ if require_text(payload["schema_version"], "schema_version", maximum=10) != "1.0":
+ raise ValidationError("schema_version must be '1.0'")
+ classification = require_text(
+ payload["classification"], "classification", maximum=20
+ )
+ if classification not in {"public", "internal", "confidential"}:
+ raise ValidationError(
+ "classification must be public, internal, or confidential"
+ )
+ price_basis = require_text(payload["price_basis"], "price_basis", maximum=20)
+ if price_basis not in {"nominal", "real", "current", "constant"}:
+ raise ValidationError(
+ "price_basis must be nominal, real, current, or constant"
+ )
+ historical = _period(payload["historical_period"], "historical_period")
+ forecast = _period(payload["forecast_period"], "forecast_period")
+ if int(forecast.split("-")[0]) <= int(historical.split("-")[0]):
+ raise ValidationError(
+ "forecast_period must begin after the historical period begins"
+ )
+ return {
+ "schema_version": "1.0",
+ "report_id": require_identifier(payload["report_id"], "report_id"),
+ "title": require_text(payload["title"], "title", maximum=200),
+ "subtitle": require_text(payload["subtitle"], "subtitle", maximum=300),
+ "prepared_for": require_text(
+ payload["prepared_for"], "prepared_for", maximum=200
+ ),
+ "prepared_by": require_text(
+ payload["prepared_by"], "prepared_by", maximum=200
+ ),
+ "classification": classification,
+ "market_definition": require_text(
+ payload["market_definition"], "market_definition", maximum=2_000
+ ),
+ "inclusions": _string_list(payload["inclusions"], "inclusions"),
+ "exclusions": _string_list(payload["exclusions"], "exclusions"),
+ "geography": require_text(payload["geography"], "geography", maximum=200),
+ "currency": parse_currency(payload["currency"], "currency"),
+ "base_year": parse_year(payload["base_year"], "base_year"),
+ "price_basis": price_basis,
+ "taxonomy": require_text(payload["taxonomy"], "taxonomy", maximum=100),
+ "taxonomy_version": require_text(
+ payload["taxonomy_version"], "taxonomy_version", maximum=100
+ ),
+ "historical_period": historical,
+ "forecast_period": forecast,
+ "retrieval_cutoff": parse_iso_date(
+ payload["retrieval_cutoff"], "retrieval_cutoff"
+ ),
+ }
+
+
+def _safe_new_directory(raw_path: str | Path) -> Path:
+ path = Path(raw_path).expanduser()
+ if path.exists() or path.is_symlink():
+ raise ValidationError(f"output directory already exists: {path}")
+ try:
+ parent = path.parent.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise ValidationError(f"output parent does not exist: {path.parent}") from exc
+ if not parent.is_dir():
+ raise ValidationError(f"output parent is not a directory: {parent}")
+ if path.name in {"", ".", ".."}:
+ raise ValidationError("output directory name is invalid")
+ return parent / path.name
+
+
+def _write_csv_header(path: Path, fields: tuple[str, ...]) -> None:
+ with path.open("w", encoding="utf-8", newline="") as handle:
+ csv.writer(handle, lineterminator="\n").writerow(fields)
+
+
+def _one_line(value: str) -> str:
+ return " ".join(value.split())
+
+
+def generate(manifest: dict[str, Any], output_dir: str | Path) -> dict[str, Any]:
+ destination = _safe_new_directory(output_dir)
+ destination.mkdir(mode=0o755)
+ (destination / "data").mkdir()
+ (destination / "analysis").mkdir()
+ (destination / "sources").mkdir()
+
+ with (destination / "manifest.json").open("w", encoding="utf-8") as handle:
+ json.dump(manifest, handle, indent=2, sort_keys=True, ensure_ascii=False)
+ handle.write("\n")
+
+ inclusions = "\n".join(f"- {item}" for item in manifest["inclusions"])
+ exclusions = "\n".join(f"- {item}" for item in manifest["exclusions"])
+ report = f"""# {_one_line(manifest["title"])}
+
+{_one_line(manifest["subtitle"])}
+
+Prepared for: {_one_line(manifest["prepared_for"])}
+Prepared by: {_one_line(manifest["prepared_by"])}
+Retrieval cutoff: {manifest["retrieval_cutoff"]}
+Classification: {manifest["classification"]}
+
+> This report separates sourced facts, calculations, assumptions, forecasts, and
+> recommendations. Inline claim IDs map to `data/claims.csv`; source IDs map to
+> `data/source_ledger.csv`. It is not investment, legal, or financial advice.
+
+## Executive synopsis
+
+State only findings supported by claim IDs. Present market-size and forecast
+results as scenario ranges, not as a single certain value.
+
+## 1. Scope and market definition
+
+**Definition:** {manifest["market_definition"]}
+
+**Geography:** {manifest["geography"]}
+**Currency/base:** {manifest["currency"]}, {manifest["price_basis"]},
+base year {manifest["base_year"]}
+**Taxonomy:** {manifest["taxonomy"]} {manifest["taxonomy_version"]}
+**Historical period:** {manifest["historical_period"]}
+**Forecast period:** {manifest["forecast_period"]}
+
+### Included
+{inclusions}
+
+### Excluded
+{exclusions}
+
+## 2. Evidence and methodology
+
+Describe source hierarchy, retrieval dates, revisions, conflicts, conversions,
+survey methods, and limitations.
+
+## 3. Market sizing and reconciliation
+
+Report top-down and bottom-up TAM estimates separately. Show denominator,
+coverage keys, excluded categories, SAM filters, SOM capture assumptions,
+scenario range, sensitivity, and reconciliation gap.
+
+## 4. Demand and customer evidence
+
+Separate observed demand, survey estimates, interview themes, and analyst
+interpretation. Do not generalize qualitative interviews to a population.
+
+## 5. Competitive landscape
+
+Define product and geographic scope before calculating shares or concentration.
+Use the evidence-linked competitor matrix; label unknowns.
+
+## 6. Forecast scenarios
+
+Describe each conditional scenario, rate path, assumptions, drivers, inhibitors,
+and sensitivity. Do not label scenario ranges as confidence intervals.
+
+## 7. Regulation, risks, and uncertainties
+
+Distinguish enacted rules, proposed rules, analyst judgments, and legal advice.
+
+## 8. Implications and options
+
+Keep recommendations distinct from sourced findings. State dependencies,
+decision thresholds, and disconfirming evidence.
+
+## Limitations
+
+List missing data, source conflicts, taxonomy breaks, revisions, sampling and
+nonresponse issues, model limitations, and residual uncertainty.
+
+## References
+
+Render references from `data/source_ledger.csv`; do not cite unmapped sources.
+"""
+ (destination / "report.md").write_text(report, encoding="utf-8")
+
+ _write_csv_header(destination / "data" / "source_ledger.csv", SOURCE_FIELDS)
+ _write_csv_header(destination / "data" / "claims.csv", CLAIM_FIELDS)
+ _write_csv_header(
+ destination / "data" / "competitor_feature_matrix.csv", COMPETITOR_FIELDS
+ )
+ _write_csv_header(
+ destination / "data" / "consistency_input.csv", CONSISTENCY_FIELDS
+ )
+ _write_csv_header(destination / "data" / "assumptions.csv", ASSUMPTION_FIELDS)
+
+ sizing = {
+ "schema_version": "1.0",
+ "metadata": {
+ "market_id": manifest["report_id"],
+ "market_definition": manifest["market_definition"],
+ "geography": manifest["geography"],
+ "currency": manifest["currency"],
+ "base_year": manifest["base_year"],
+ "price_basis": manifest["price_basis"],
+ "unit": f"{manifest['currency']} per year",
+ "taxonomy": manifest["taxonomy"],
+ "taxonomy_version": manifest["taxonomy_version"],
+ "denominator_id": "define-denominator",
+ "as_of_date": manifest["retrieval_cutoff"],
+ },
+ "top_down": {"components": []},
+ "bottom_up": {"components": []},
+ "scenarios": [],
+ "reconciliation_tolerance_percent": 20.0,
+ }
+ forecast = {
+ "schema_version": "1.0",
+ "metadata": {
+ "series_id": "define-series",
+ "description": "Replace with the forecast measure",
+ "geography": manifest["geography"],
+ "currency": manifest["currency"],
+ "base_year": str(manifest["base_year"]),
+ "price_basis": manifest["price_basis"],
+ "unit": f"{manifest['currency']} per year",
+ "measure_type": "flow",
+ "as_of_date": manifest["retrieval_cutoff"],
+ "source_ids": [],
+ },
+ "start_year": int(manifest["historical_period"].split("-")[1]),
+ "start_value": 0,
+ "horizon_years": 5,
+ "scenarios": [],
+ "sensitivity": {
+ "base_scenario_id": "base",
+ "growth_rate_shifts": [-0.02, 0.0, 0.02],
+ },
+ }
+ for name, payload in (
+ ("market_sizing.json", sizing),
+ ("forecast_sensitivity.json", forecast),
+ ):
+ with (destination / "analysis" / name).open("w", encoding="utf-8") as handle:
+ json.dump(payload, handle, indent=2, sort_keys=True, ensure_ascii=False)
+ handle.write("\n")
+
+ checklist = """# Review checklist
+
+- [ ] Scope, inclusions, exclusions, geography, period, taxonomy, and denominator are explicit.
+- [ ] Every factual or quantitative claim maps to source IDs.
+- [ ] Publication and retrieval dates, revisions, units, currencies, and base years are recorded.
+- [ ] Top-down and bottom-up sizing use compatible definitions and disjoint coverage keys.
+- [ ] TAM/SAM/SOM are presented as conditional scenarios with sensitivity.
+- [ ] Forecast ranges are labeled as scenarios, not confidence intervals.
+- [ ] Survey sample, frame, mode, field dates, weighting, response, and limitations are disclosed.
+- [ ] Competitor claims use public, lawful evidence and identify unknowns.
+- [ ] No PII, trade secrets, deceptive collection, or unsupported paid-market figures appear.
+- [ ] Findings, assumptions, calculations, forecasts, opinions, and recommendations remain distinct.
+- [ ] The report states that it is not investment, legal, or financial advice.
+"""
+ (destination / "review_checklist.md").write_text(checklist, encoding="utf-8")
+
+ created = sorted(
+ str(path.relative_to(destination))
+ for path in destination.rglob("*")
+ if path.is_file()
+ )
+ return {
+ "created": True,
+ "output_directory": str(destination),
+ "files": created,
+ "next_step": (
+ "Populate the empty ledgers and scenario files, then run the bundled "
+ "validators before drafting conclusions."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Generate a new local Markdown market-report scaffold and strict "
+ "evidence/analysis input files. Existing directories are never overwritten."
+ )
+ )
+ parser.add_argument("manifest", help="Local .json report manifest")
+ parser.add_argument("output_dir", help="New local output directory")
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ manifest = validate_manifest(require_object(read_json(args.manifest), "root"))
+ write_json_report(generate(manifest, args.output_dir), None)
+ return 0
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/scripts/validate_competitor_matrix.py b/skills/market-research-reports/scripts/validate_competitor_matrix.py
new file mode 100644
index 00000000..22456557
--- /dev/null
+++ b/skills/market-research-reports/scripts/validate_competitor_matrix.py
@@ -0,0 +1,223 @@
+#!/usr/bin/env python3
+"""Validate a complete, evidence-linked competitor-feature matrix CSV."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ MAX_ROWS,
+ ValidationError,
+ error_exit,
+ parse_iso_date,
+ read_csv_records,
+ read_json,
+ require_identifier,
+ require_list,
+ require_object,
+ require_text,
+ split_ids,
+ write_json_report,
+)
+
+REQUIRED_FIELDS = (
+ "competitor_id",
+ "competitor_name",
+ "feature_id",
+ "feature_name",
+ "status",
+ "evidence_source_ids",
+ "as_of_date",
+ "geography",
+ "product_scope",
+ "notes",
+)
+STATUSES = {"yes", "no", "partial", "unknown", "not-applicable"}
+
+
+def _source_ids(path: str | Path) -> set[str]:
+ if Path(path).suffix.lower() == ".csv":
+ records: list[dict[str, Any]] = read_csv_records(
+ path, required_fields=("source_id",)
+ )
+ elif Path(path).suffix.lower() == ".json":
+ payload = read_json(path)
+ if isinstance(payload, dict):
+ raw = require_list(
+ payload.get("sources"), "sources", minimum=1, maximum=MAX_ROWS
+ )
+ else:
+ raw = require_list(payload, "sources", minimum=1, maximum=MAX_ROWS)
+ records = [
+ require_object(record, f"sources[{index}]")
+ for index, record in enumerate(raw)
+ ]
+ else:
+ raise ValidationError("source ledger must be .csv or .json")
+ identifiers: set[str] = set()
+ for index, record in enumerate(records):
+ source_id = require_identifier(
+ record.get("source_id"), f"sources[{index}].source_id"
+ )
+ if source_id in identifiers:
+ raise ValidationError(f"duplicate source_id in ledger: {source_id}")
+ identifiers.add(source_id)
+ return identifiers
+
+
+def validate(
+ rows: list[dict[str, str]], known_source_ids: set[str] | None = None
+) -> dict[str, Any]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ competitors: dict[str, str] = {}
+ features: dict[str, str] = {}
+ pairs: set[tuple[str, str]] = set()
+ scope_values: set[tuple[str, str, str]] = set()
+ cited_ids: set[str] = set()
+ status_counts: dict[str, int] = {}
+
+ for index, row in enumerate(rows, start=2):
+ context = f"row {index}"
+ try:
+ competitor_id = require_identifier(
+ row["competitor_id"], f"{context}.competitor_id"
+ )
+ competitor_name = require_text(
+ row["competitor_name"], f"{context}.competitor_name", maximum=200
+ )
+ existing_competitor = competitors.get(competitor_id)
+ if existing_competitor and existing_competitor != competitor_name:
+ raise ValidationError(
+ f"{context}: competitor_id {competitor_id} has inconsistent names"
+ )
+ competitors[competitor_id] = competitor_name
+
+ feature_id = require_identifier(row["feature_id"], f"{context}.feature_id")
+ feature_name = require_text(
+ row["feature_name"], f"{context}.feature_name", maximum=200
+ )
+ existing_feature = features.get(feature_id)
+ if existing_feature and existing_feature != feature_name:
+ raise ValidationError(
+ f"{context}: feature_id {feature_id} has inconsistent names"
+ )
+ features[feature_id] = feature_name
+
+ pair = (competitor_id, feature_id)
+ if pair in pairs:
+ raise ValidationError(
+ f"{context}: duplicate competitor-feature pair "
+ f"{competitor_id}/{feature_id}"
+ )
+ pairs.add(pair)
+
+ status = require_text(row["status"], f"{context}.status", maximum=20)
+ if status not in STATUSES:
+ raise ValidationError(
+ f"{context}.status must be one of {', '.join(sorted(STATUSES))}"
+ )
+ status_counts[status] = status_counts.get(status, 0) + 1
+ evidence_ids = split_ids(
+ row["evidence_source_ids"],
+ f"{context}.evidence_source_ids",
+ allow_empty=True,
+ )
+ if status not in {"unknown", "not-applicable"} and not evidence_ids:
+ raise ValidationError(
+ f"{context}: status {status!r} requires evidence_source_ids"
+ )
+ cited_ids.update(evidence_ids)
+
+ as_of_date = parse_iso_date(row["as_of_date"], f"{context}.as_of_date")
+ geography = require_text(
+ row["geography"], f"{context}.geography", maximum=200
+ )
+ product_scope = require_text(
+ row["product_scope"], f"{context}.product_scope", maximum=500
+ )
+ scope_values.add((as_of_date, geography, product_scope))
+ require_text(row["notes"], f"{context}.notes", allow_empty=True)
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ expected_pairs = {
+ (competitor_id, feature_id)
+ for competitor_id in competitors
+ for feature_id in features
+ }
+ missing_pairs = sorted(expected_pairs - pairs)
+ if missing_pairs:
+ preview = ", ".join(f"{a}/{b}" for a, b in missing_pairs[:20])
+ suffix = "" if len(missing_pairs) <= 20 else ", ..."
+ errors.append(
+ f"matrix is incomplete; missing {len(missing_pairs)} pairs: "
+ f"{preview}{suffix}"
+ )
+ if len(scope_values) > 1:
+ errors.append(
+ "matrix rows use inconsistent as_of_date/geography/product_scope values"
+ )
+
+ missing_sources: list[str] = []
+ if known_source_ids is None:
+ warnings.append(
+ "evidence IDs were syntax-checked but not cross-checked; pass "
+ "--source-ledger for referential integrity"
+ )
+ else:
+ missing_sources = sorted(cited_ids - known_source_ids)
+ if missing_sources:
+ errors.append(
+ "evidence IDs missing from source ledger: "
+ + ", ".join(missing_sources)
+ )
+
+ return {
+ "valid": not errors,
+ "row_count": len(rows),
+ "competitor_count": len(competitors),
+ "feature_count": len(features),
+ "expected_pair_count": len(expected_pairs),
+ "status_counts": dict(sorted(status_counts.items())),
+ "cited_source_count": len(cited_ids),
+ "warnings": warnings,
+ "errors": errors,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate a strict local competitor-feature matrix for complete coverage, "
+ "consistent scope, and evidence links."
+ )
+ )
+ parser.add_argument("matrix", help="Local .csv competitor matrix")
+ parser.add_argument(
+ "--source-ledger",
+ help="Optional local .csv/.json source ledger for ID cross-checking",
+ )
+ parser.add_argument("--output", help="Optional local .json validation report")
+ parser.add_argument(
+ "--force", action="store_true", help="Replace an existing --output file"
+ )
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ rows = read_csv_records(args.matrix, required_fields=REQUIRED_FIELDS)
+ known = _source_ids(args.source_ledger) if args.source_ledger else None
+ report = validate(rows, known)
+ write_json_report(report, args.output, force=args.force)
+ return 0 if report["valid"] else 1
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/scripts/validate_evidence_ledger.py b/skills/market-research-reports/scripts/validate_evidence_ledger.py
new file mode 100644
index 00000000..fe666804
--- /dev/null
+++ b/skills/market-research-reports/scripts/validate_evidence_ledger.py
@@ -0,0 +1,291 @@
+#!/usr/bin/env python3
+"""Validate a local market-research source/evidence ledger."""
+
+from __future__ import annotations
+
+import argparse
+from datetime import date
+from pathlib import Path, PurePosixPath
+from typing import Any
+from urllib.parse import urlsplit
+
+from _common import (
+ MAX_ROWS,
+ ValidationError,
+ error_exit,
+ parse_currency,
+ parse_iso_date,
+ parse_year,
+ read_csv_records,
+ read_json,
+ require_identifier,
+ require_list,
+ require_object,
+ require_text,
+ require_unique_identifiers,
+ write_json_report,
+)
+
+REQUIRED_FIELDS = (
+ "source_id",
+ "title",
+ "publisher",
+ "url",
+ "source_type",
+ "publication_date",
+ "retrieval_date",
+ "geography",
+ "currency",
+ "base_year",
+ "price_basis",
+ "measure_type",
+ "unit",
+ "taxonomy",
+ "taxonomy_version",
+ "revision_status",
+ "method",
+ "sample",
+ "limitations",
+ "license_or_terms",
+ "archive_path",
+)
+
+SOURCE_TYPES = {
+ "official_statistics",
+ "regulator_filing",
+ "company_filing",
+ "survey",
+ "interview",
+ "academic",
+ "industry_association",
+ "paid_secondary",
+ "news",
+ "methodological_guidance",
+ "other",
+}
+PRICE_BASES = {
+ "nominal",
+ "real",
+ "current",
+ "constant",
+ "chained",
+ "mixed",
+ "not-applicable",
+}
+MEASURE_TYPES = {
+ "stock",
+ "flow",
+ "index",
+ "share",
+ "count",
+ "rate",
+ "price",
+ "mixed",
+ "not-applicable",
+}
+REVISION_STATUSES = {
+ "preliminary",
+ "revised",
+ "final",
+ "current",
+ "vintage",
+ "unknown",
+ "not-applicable",
+}
+
+
+def _publication_date(value: Any, context: str) -> str:
+ text = require_text(value, context, maximum=10)
+ if text == "not-stated":
+ return text
+ if len(text) == 4:
+ parse_year(text, context)
+ return text
+ return parse_iso_date(text, context)
+
+
+def _url(value: Any, context: str) -> str:
+ text = require_text(value, context, maximum=2_048)
+ parsed = urlsplit(text)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise ValidationError(f"{context} must be an absolute HTTP(S) URL")
+ if parsed.username or parsed.password:
+ raise ValidationError(f"{context} must not contain embedded credentials")
+ return text
+
+
+def _archive_path(value: Any, context: str) -> str:
+ text = require_text(value, context, allow_empty=True, maximum=1_024)
+ if not text:
+ return ""
+ path = PurePosixPath(text)
+ if path.is_absolute() or ".." in path.parts:
+ raise ValidationError(
+ f"{context} must be a relative path without parent traversal"
+ )
+ return text
+
+
+def _load_records(path: str | Path) -> list[dict[str, Any]]:
+ suffix = Path(path).suffix.lower()
+ if suffix == ".csv":
+ return read_csv_records(path, required_fields=REQUIRED_FIELDS)
+ if suffix == ".json":
+ payload = read_json(path)
+ if isinstance(payload, dict):
+ records = require_list(
+ payload.get("sources"), "sources", minimum=1, maximum=MAX_ROWS
+ )
+ else:
+ records = require_list(payload, "source ledger", minimum=1, maximum=MAX_ROWS)
+ return [require_object(row, f"sources[{index}]") for index, row in enumerate(records)]
+ raise ValidationError("input must be .csv or .json")
+
+
+def validate_records(records: list[dict[str, Any]]) -> dict[str, Any]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ valid_ids: list[str] = []
+ type_counts: dict[str, int] = {}
+
+ for index, record in enumerate(records, start=1):
+ context = f"record {index}"
+ missing = [field for field in REQUIRED_FIELDS if field not in record]
+ if missing:
+ errors.append(f"{context}: missing fields: {', '.join(missing)}")
+ continue
+ try:
+ source_id = require_identifier(record["source_id"], f"{context}.source_id")
+ valid_ids.append(source_id)
+ require_text(record["title"], f"{context}.title")
+ require_text(record["publisher"], f"{context}.publisher")
+ _url(record["url"], f"{context}.url")
+
+ source_type = require_text(
+ record["source_type"], f"{context}.source_type", maximum=40
+ )
+ if source_type not in SOURCE_TYPES:
+ raise ValidationError(
+ f"{context}.source_type must be one of "
+ f"{', '.join(sorted(SOURCE_TYPES))}"
+ )
+ type_counts[source_type] = type_counts.get(source_type, 0) + 1
+
+ publication = _publication_date(
+ record["publication_date"], f"{context}.publication_date"
+ )
+ retrieval = parse_iso_date(
+ record["retrieval_date"], f"{context}.retrieval_date"
+ )
+ if len(publication) == 10 and date.fromisoformat(retrieval) < date.fromisoformat(
+ publication
+ ):
+ raise ValidationError(
+ f"{context}.retrieval_date precedes publication_date"
+ )
+ if publication == "not-stated":
+ warnings.append(f"{source_id}: publication date is not stated")
+
+ require_text(record["geography"], f"{context}.geography")
+ currency = parse_currency(
+ record["currency"], f"{context}.currency", allow_empty=True
+ )
+ base_year_raw = require_text(
+ record["base_year"], f"{context}.base_year", allow_empty=True, maximum=4
+ )
+ if base_year_raw:
+ parse_year(base_year_raw, f"{context}.base_year")
+
+ price_basis = require_text(
+ record["price_basis"], f"{context}.price_basis", maximum=20
+ )
+ if price_basis not in PRICE_BASES:
+ raise ValidationError(
+ f"{context}.price_basis must be one of "
+ f"{', '.join(sorted(PRICE_BASES))}"
+ )
+ if currency and (not base_year_raw or price_basis == "not-applicable"):
+ raise ValidationError(
+ f"{context}: monetary evidence requires base_year and price_basis"
+ )
+
+ measure_type = require_text(
+ record["measure_type"], f"{context}.measure_type", maximum=20
+ )
+ if measure_type not in MEASURE_TYPES:
+ raise ValidationError(
+ f"{context}.measure_type must be one of "
+ f"{', '.join(sorted(MEASURE_TYPES))}"
+ )
+ require_text(record["unit"], f"{context}.unit")
+ require_text(
+ record["taxonomy"], f"{context}.taxonomy", allow_empty=True
+ )
+ require_text(
+ record["taxonomy_version"],
+ f"{context}.taxonomy_version",
+ allow_empty=True,
+ )
+
+ revision_status = require_text(
+ record["revision_status"], f"{context}.revision_status", maximum=20
+ )
+ if revision_status not in REVISION_STATUSES:
+ raise ValidationError(
+ f"{context}.revision_status must be one of "
+ f"{', '.join(sorted(REVISION_STATUSES))}"
+ )
+ if revision_status == "unknown":
+ warnings.append(f"{source_id}: revision status is unknown")
+
+ require_text(record["method"], f"{context}.method")
+ require_text(record["sample"], f"{context}.sample", allow_empty=True)
+ require_text(record["limitations"], f"{context}.limitations")
+ require_text(
+ record["license_or_terms"], f"{context}.license_or_terms"
+ )
+ _archive_path(record["archive_path"], f"{context}.archive_path")
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ try:
+ require_unique_identifiers(valid_ids, "source ledger")
+ except ValidationError as exc:
+ errors.append(str(exc))
+
+ return {
+ "valid": not errors,
+ "source_count": len(records),
+ "source_type_counts": dict(sorted(type_counts.items())),
+ "warnings": warnings,
+ "errors": errors,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate a strict local CSV/JSON evidence ledger. "
+ "No network requests are made."
+ )
+ )
+ parser.add_argument("ledger", help="Local .csv or .json source ledger")
+ parser.add_argument("--output", help="Optional local .json validation report")
+ parser.add_argument(
+ "--force", action="store_true", help="Replace an existing --output file"
+ )
+ return parser
+
+
+def main() -> int:
+ args = build_parser().parse_args()
+ try:
+ report = validate_records(_load_records(args.ledger))
+ write_json_report(report, args.output, force=args.force)
+ return 0 if report["valid"] else 1
+ except ValidationError as exc:
+ return error_exit(exc)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/market-research-reports/tests/fixtures/README.md b/skills/market-research-reports/tests/fixtures/README.md
new file mode 100644
index 00000000..b168212a
--- /dev/null
+++ b/skills/market-research-reports/tests/fixtures/README.md
@@ -0,0 +1,7 @@
+# Synthetic fixtures
+
+The tests use the seven populated templates in `../../assets/` as valid
+synthetic fixtures and mutate in-memory copies to exercise failure cases.
+
+All entities, values, classifications, and `example.invalid` URLs are fictional.
+They must not be used as real market evidence.
diff --git a/skills/market-research-reports/tests/test_scripts.py b/skills/market-research-reports/tests/test_scripts.py
new file mode 100644
index 00000000..a6474291
--- /dev/null
+++ b/skills/market-research-reports/tests/test_scripts.py
@@ -0,0 +1,188 @@
+"""Synthetic, dependency-free tests for the bundled local CLIs."""
+
+from __future__ import annotations
+
+import copy
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+ASSETS = SKILL_ROOT / "assets"
+sys.path.insert(0, str(SCRIPTS))
+
+from _common import ValidationError, read_csv_records # noqa: E402
+from audit_claim_citations import ( # noqa: E402
+ CLAIM_FIELDS,
+ _load_sources,
+ audit,
+)
+from calculate_market_sizing import calculate # noqa: E402
+from check_unit_consistency import ( # noqa: E402
+ REQUIRED_FIELDS as CONSISTENCY_FIELDS,
+ check,
+)
+from forecast_sensitivity import forecast # noqa: E402
+from generate_report_scaffold import ( # noqa: E402
+ generate,
+ validate_manifest,
+)
+from validate_competitor_matrix import ( # noqa: E402
+ REQUIRED_FIELDS as COMPETITOR_FIELDS,
+ validate as validate_competitors,
+)
+from validate_evidence_ledger import _load_records, validate_records # noqa: E402
+
+
+def load_json(name: str) -> dict:
+ with (ASSETS / name).open("r", encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+class EvidenceLedgerTests(unittest.TestCase):
+ def test_synthetic_source_ledger_is_valid(self) -> None:
+ report = validate_records(
+ _load_records(ASSETS / "source_ledger_template.csv")
+ )
+ self.assertTrue(report["valid"], report["errors"])
+ self.assertEqual(report["source_count"], 3)
+
+ def test_duplicate_source_id_fails(self) -> None:
+ records = _load_records(ASSETS / "source_ledger_template.csv")
+ records.append(copy.deepcopy(records[0]))
+ report = validate_records(records)
+ self.assertFalse(report["valid"])
+ self.assertTrue(any("duplicate" in error for error in report["errors"]))
+
+
+class MarketSizingTests(unittest.TestCase):
+ def test_synthetic_sizing_reconciles_and_returns_scenarios(self) -> None:
+ result = calculate(load_json("market_sizing_scenarios_template.json"))
+ self.assertEqual(result["method_estimates"]["top_down_tam"], 100_000_000)
+ self.assertEqual(result["method_estimates"]["bottom_up_tam"], 84_000_000)
+ self.assertEqual(len(result["scenario_results"]), 3)
+ self.assertTrue(result["reconciliation"]["within_tolerance"])
+
+ def test_duplicate_coverage_key_is_rejected(self) -> None:
+ payload = load_json("market_sizing_scenarios_template.json")
+ payload["top_down"]["components"][1]["coverage_key"] = (
+ payload["top_down"]["components"][0]["coverage_key"]
+ )
+ with self.assertRaisesRegex(ValidationError, "duplicate"):
+ calculate(payload)
+
+ def test_inconsistent_denominator_is_rejected(self) -> None:
+ payload = load_json("market_sizing_scenarios_template.json")
+ payload["bottom_up"]["components"][0]["denominator_id"] = "other-denominator"
+ with self.assertRaisesRegex(ValidationError, "denominator"):
+ calculate(payload)
+
+
+class ForecastTests(unittest.TestCase):
+ def test_synthetic_forecast_returns_range_and_sensitivity(self) -> None:
+ result = forecast(load_json("forecast_sensitivity_template.json"))
+ self.assertEqual(len(result["scenarios"]), 3)
+ self.assertEqual(len(result["scenario_range_by_year"]), 6)
+ upside = next(
+ item for item in result["scenarios"] if item["scenario_id"] == "upside"
+ )
+ self.assertAlmostEqual(upside["endpoint"], 146_932_807.68, places=2)
+ self.assertEqual(len(result["sensitivity"]["results"]), 5)
+
+ def test_unvalidated_probability_is_rejected(self) -> None:
+ payload = load_json("forecast_sensitivity_template.json")
+ payload["scenarios"][0]["probability"] = 0.2
+ with self.assertRaisesRegex(ValidationError, "probability"):
+ forecast(payload)
+
+ def test_horizon_rejects_float_string_and_boolean_values(self) -> None:
+ for invalid in (5.0, "5", True):
+ with self.subTest(invalid=invalid):
+ payload = load_json("forecast_sensitivity_template.json")
+ payload["horizon_years"] = invalid
+ with self.assertRaisesRegex(ValidationError, "integer"):
+ forecast(payload)
+
+
+class CompetitorMatrixTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.rows = read_csv_records(
+ ASSETS / "competitor_feature_matrix_template.csv",
+ required_fields=COMPETITOR_FIELDS,
+ )
+ self.source_ids = {
+ record["source_id"]
+ for record in _load_records(ASSETS / "source_ledger_template.csv")
+ }
+
+ def test_complete_synthetic_matrix_is_valid(self) -> None:
+ report = validate_competitors(self.rows, self.source_ids)
+ self.assertTrue(report["valid"], report["errors"])
+ self.assertEqual(report["expected_pair_count"], 4)
+
+ def test_incomplete_matrix_fails(self) -> None:
+ report = validate_competitors(self.rows[:-1], self.source_ids)
+ self.assertFalse(report["valid"])
+ self.assertTrue(any("incomplete" in error for error in report["errors"]))
+
+
+class ClaimAuditTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.claims = read_csv_records(
+ ASSETS / "claims_ledger_template.csv", required_fields=CLAIM_FIELDS
+ )
+ self.sources = _load_sources(ASSETS / "source_ledger_template.csv")
+
+ def test_synthetic_claims_are_fully_mapped(self) -> None:
+ report = audit(self.claims, self.sources)
+ self.assertTrue(report["valid"], report["errors"])
+ self.assertEqual(report["uncited_claim_ids"], [])
+
+ def test_uncited_forecast_fails(self) -> None:
+ claims = copy.deepcopy(self.claims)
+ claims[2]["source_ids"] = ""
+ report = audit(claims, self.sources)
+ self.assertFalse(report["valid"])
+ self.assertIn("C-003", report["uncited_claim_ids"])
+
+
+class ConsistencyTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.rows = read_csv_records(
+ ASSETS / "consistency_check_template.csv",
+ required_fields=CONSISTENCY_FIELDS,
+ )
+
+ def test_synthetic_comparison_group_is_consistent(self) -> None:
+ report = check(self.rows)
+ self.assertTrue(report["valid"], report["errors"])
+
+ def test_mixed_currency_fails(self) -> None:
+ rows = copy.deepcopy(self.rows)
+ rows[1]["currency"] = "EUR"
+ report = check(rows)
+ self.assertFalse(report["valid"])
+ self.assertIn("annual-market-spend", report["mismatches"])
+
+
+class ScaffoldTests(unittest.TestCase):
+ def test_scaffold_creates_only_expected_local_files(self) -> None:
+ manifest = validate_manifest(load_json("report_manifest_template.json"))
+ with tempfile.TemporaryDirectory() as temporary:
+ output = Path(temporary) / "report-workspace"
+ result = generate(manifest, output)
+ self.assertTrue(result["created"])
+ self.assertTrue((output / "report.md").is_file())
+ self.assertTrue((output / "data" / "source_ledger.csv").is_file())
+ self.assertTrue(
+ (output / "analysis" / "market_sizing.json").is_file()
+ )
+ with self.assertRaisesRegex(ValidationError, "already exists"):
+ generate(manifest, output)
+
+
+if __name__ == "__main__":
+ unittest.main()