
Why
- 509 installs
- 2.5k repo stars
- Updated August 5, 2026
- cursor/plugins
Clarify the underlying reason for a feature, change, or bugfix before committing scope so agents and humans align on intent instead of jumping straight to implementation.
About
The why skill from cursor/plugins prompts deliberate rationale discovery before execution: articulate the problem, expected outcome, and reason a task matters so Cursor agents and developers scope work correctly, avoid solution-first drift, and leave a traceable decision trail for later review.
- Intent-first questioning before coding
- Reduces scope creep from unclear goals
- Aligns agent actions with user motivation
- Supports decision documentation
- Pairs with planning and review flows
Why by the numbers
- 509 all-time installs (skills.sh)
- Ranked #756 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/cursor/plugins --skill whyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 509 |
|---|---|
| repo stars | ★ 2.5k |
| Last updated | August 5, 2026 |
| Repository | cursor/plugins ↗ |
What it does
Clarify the underlying reason for a feature, change, or bugfix before committing scope so agents and humans align on intent instead of jumping straight to implementation.
Files
Why
Investigate the motivation and intent behind code. Why was it built this way? What edge cases were considered? What product, business, or operational constraints shaped the design? What alternatives were rejected, and why?
Companion to the how skill. how answers what the code does and how it works. why answers what forces led to its shape.
How this skill works
Historical context spreads across seven evidence categories: source control history, issue or ticket tracking, long-form documents, real-time team chat, infrastructure observability, error or exception tracking, and product analytics warehouses. You cannot predict from the question alone which one holds the answer, so the skill enumerates available MCPs at run time, maps each to a category, queries all seven in parallel, then synthesizes with explicit confidence calibration. Null results from searched categories are first-class evidence about how the decision was made; report them alongside positive findings. The default is coverage, not minimalism.
Operating Posture
Operate as a careful, cautious, precise investigator. Think like a detective piecing together a historical case from fragmentary records. When the record is thin, say so.
Concretely:
- Evidence before narrative. Collect the pieces first, then see what story they support. Never pick a story and recruit the evidence that fits it.
- Precision over polish. Prefer the exact quote and citation over a smooth paraphrase. A reader should be able to follow any claim back to its source and verify it in under a minute.
- Consider what you haven't seen. The evidence you find is a sample, not the whole truth. Before concluding, ask what you would expect to see if an alternative explanation were true, and whether you looked for it.
- Name the gaps. If a thread goes cold, a source isn't searchable, or a question has no answer, document the gap. Don't paper it over with an authoritative-sounding guess.
- Hedge on purpose. When evidence is indirect, your language should signal it ("appears to", "likely", "suggests"). Confidence-matching phrasing is a feature of the output, not a stylistic choice the synthesizer may override.
- No shortcut by code-reading. The code tells you what it does, rarely why it exists. Resist inferring intent from code shape.
This posture is the working method, not a disclaimer.
Core Epistemics
This skill builds a patchwork understanding from fragmented historical evidence. Tickets go stale. Chat threads get deleted. Commit messages lie. People change their minds between the PR description and the implementation. The original author may have left the company.
Be ruthlessly honest about what you know versus what you're inferring. The goal is not a satisfying story; it is to surface evidence, calibrate confidence, and let the user decide.
Principles:
- Cite everything. Every claim about intent should reference a specific commit hash, PR number, ticket ID, doc URL, chat permalink, or code comment. If you can't cite it, it's inference, not fact, and must be labeled as such.
- Prefer "appears to" over "because". Hedge when evidence is indirect. Reserve confident language for direct, explicit evidence.
- Surface contradictions. If two sources disagree, show both. Don't quietly pick the one that fits your narrative.
- Acknowledge gaps. If a question has no answer in any source you searched, say so. An honest "we couldn't find out why" beats a confident guess.
- Multiple hypotheses are valid. When the evidence fits several stories, present them all with the evidence for each. Let the user triangulate.
- Beware rationalization. Code that makes sense today may have been written for reasons that no longer apply, or for no good reason at all. Don't retrofit intent.
Read references/epistemics.md for the full confidence framework and phrasing guide. The synthesizer must follow it.
Step 1. Understand the Target and the Question
Parse what the user is asking. The target is usually a chunk of code, a pattern, a feature, or a named design decision. The question is usually one of:
- "Why was X designed this way?" Design rationale.
- "Why do we do X instead of Y?" Tradeoff or alternatives.
- "What edge cases motivated this?" Defensive reasoning.
- "What business or product constraint led to this?" External forcing function.
- "Why does this code still exist?" Dead-code territory.
- "What's the history of X?" Broad archaeological sweep.
If the target is vague ("why do we do it this way?" with no clear referent), make your best guess from conversation context (open files, recent edits, cursor location, what was just discussed). State your interpretation briefly so the user can redirect if you're off, then proceed.
Step 2. Establish the Code Anchor
Before spawning investigators, anchor the investigation in concrete code. You need:
- The relevant file path(s) and line range(s)
- The key symbols (function names, class names, constants)
- An initial commit list. The last few commits touching the target.
- PR numbers from merge commits (pattern
(#1234)in the subject line)
Build this inline. It's cheap, and every investigator needs it.
# Blame target lines for last-touch commits
git blame -L <start>,<end> <file>
# Full file history, with patches, through renames
git log --follow -p -- <file>
# Last N commits touching the file, PR numbers visible
git log --oneline -20 -- <file>
# Extract PR numbers from a commit message
git log -1 --format=%B <commit>Pull PR bodies and discussion via gh for any substantive commits:
gh pr view <number> --json title,body,author,createdAt,mergedAt,labels,closingIssuesReferences,comments,reviewsCapture this as seed context (file paths, symbols, commits, PR numbers, linked ticket IDs). Pass it to the investigators so they don't rediscover it.
Step 3. Spawn Parallel Investigators (default posture)
Default to the full parallel investigation. Each evidence category lives in a different kind of system, and you cannot tell from the question alone which one holds the answer without looking. So look across every available category, in parallel, by default.
Discovery
Before spawning investigators, list the available MCPs from the Cursor environment. Use the available-tools map when present. Otherwise inspect the mcps/ directory Cursor exposes for enabled MCP servers.
Map each available MCP to one evidence category:
1. Source control history 2. Issue / ticket tracker 3. Long-form documents 4. Real-time team chat 5. Infrastructure observability 6. Error / exception tracking 7. Product analytics warehouse
Source control is always available through git and gh. For the other six, classify using the MCP name, server instructions, tool names, and resource descriptors. If an MCP could fit more than one category, choose the one matching its primary evidence. Record ambiguous cases in the coverage map.
Aim for a complete coverage map, not a minimal one. A null result from an issue tracker is evidence the decision was not ticketed, a useful fact in itself. Document the null, don't skip the search.
Launch all matching investigators in a single message so they run concurrently. One investigator per category lets each specialize in one tool's query vocabulary and result shape. Don't ask one agent to cover multiple MCPs.
Subagent config (each):
subagent_type:generalPurposemodel: your configured why-investigators model (defaultcomposer-2.5-fast)readonly:false(agent mode). Do not use readonly/Ask mode. It strips MCP access, which disables MCP-backed investigators entirely. The source control investigator would be safe in readonly, but keep modes uniform. Investigators still shouldn't write anything. That's a posture, not a sandbox.
Each investigator gets: 1. The base prompt from references/investigator-prompt.md 2. The category playbook references/sources/<source>.md for the selected MCP, adapted from the examples in references/source-playbook.md 3. The cross-cutting references/sources/incident-postmortem.md if the target code looks defensive (null checks, retry logic, timeout handling, rate limiting, feature flags, egress guards, OOM handlers) 4. The code anchor from Step 2 (file paths, symbols, commit hashes, PR numbers, ticket IDs) 5. The user's original question
Investigator roster. One per available evidence category
Spawn one investigator per category that has a matching MCP. Each owns exactly one tool or MCP.
Each entry lists what the category physically contains and the kind of "why" it uniquely surfaces. Use it to know what to expect back, how to name a gap when a category returns empty, and (only in the rare provably-irrelevant case) to justify a skip. Every category overlaps, but each owns a kind of evidence the others cannot recover.
1. Source control investigator. Git history, gh for PRs, code comments, tests. Always spawn; the only guaranteed source. Best at surfacing implementation-time rationale captured during review. PR descriptions stating the problem, review threads debating alternatives, inline comments encoding non-obvious constraints, test names that encode motivating edge cases, and commit messages linking tickets or incidents. Most trustworthy because it ties directly to the diff that shipped.
2. Issue / ticket tracker investigator (e.g. Linear, Jira, GitHub Issues, Plane, Shortcut MCP). Tickets, project docs, status updates, spec attachments. Best at surfacing the product or business forcing function. Customer requests ("Acme needs X for their SOC2 audit"), compliance deadlines, parent-initiative framing ("Q3 enterprise readiness"), ticket-level scope changes, and labels that categorize the motivation (customer:*, incident-followup, compliance, perf-regression). Strongest when the why is external to engineering.
3. Long-form documents investigator (e.g. Notion, Confluence, Google Docs, Coda MCP). PRDs, specs, RFCs, design docs, ADRs, postmortems, team pages, meeting notes. Best at surfacing long-form design rationale. Problem statements, explicit "alternatives considered" and "rejected approaches" sections, strategy documents that set priorities, ADRs with finalized decisions, and postmortem action items that tie directly to code. Where the why is written out before it becomes code.
4. Real-time team chat investigator (e.g. Slack, Discord, Microsoft Teams, Mattermost MCP). Feature-name and symbol searches, PR URL mentions, incident channels (#sev-*, #incident-*), author-handle activity around the ship date. Best at surfacing real-time deliberation that never reached a doc. Fire-drill decisions during incidents, Q&A between the PR author and reviewers, casual "we decided X because Y" threads, and rationale for small changes that didn't warrant a PRD. Especially important when the source control, ticket, and doc paper trail is thin.
5. Infrastructure observability investigator (e.g. Datadog, New Relic, Honeycomb, Grafana, Splunk MCP). Metrics, monitors, dashboards, logs, APM traces, formal incidents. Infra/runtime view. Best at surfacing infrastructure and runtime reality that motivated the code. Monitor thresholds whose numbers match code constants, metric spikes in the window right before a PR merge, dashboards created as postmortem action items, incident timelines that reference the target. Strongest when the target reacts to an infra signal (timeouts, retries, rate limits, circuit breakers).
6. Error / exception tracking investigator (e.g. Sentry, Rollbar, Bugsnag, Airbrake MCP). Issues, events, stack traces, releases. Best at surfacing the specific exceptions and error trajectories that motivated defensive or corrective code. Stack traces that pass through the target function, issues whose first-seen/last-seen windows bracket the PR ship date, release correlations that show an error stopping at a specific version. Strongest for catch blocks, null guards, type checks, retries, and other defenses.
7. Product analytics warehouse investigator (e.g. Databricks, Snowflake, BigQuery, ClickHouse, dbt, Redshift MCP). Product-analytics events, experiment and feature-flag exposure tables, usage and billing events, query history, warehouse telemetry. Product/data view. Complements infrastructure observability by covering user behavior and data reality around the ship date rather than infra metrics. Best at surfacing product and data reality that shaped the code. Feature-usage trajectories (a step-function ramp from zero is strong evidence that this PR launched it), experiment/flag exposure data tied to ship decisions, pre-ship distributions that reveal where a threshold constant came from (e.g., limit = 128 * 1024 matching the p99 of an upload-size column), and data-pipeline scale evidence for migrations/backfills. Strongest for flag-gated code, experiment-driven ships, data migrations, and "where did this number come from" questions.
When to skip an investigator
Only skip with an explicit, written justification that goes in the final "Sources Consulted" section. Two valid reasons:
- No MCP is available for that category in this environment. Flag this as a gap, not a choice. Example: "Real-time team chat skipped. No matching MCP available, so the conversational record was not searchable."
- The source is provably irrelevant, not just "probably irrelevant." A high bar. Example: "Error / exception tracking skipped. Target is a build-time script with no runtime code path." Not "probably not in error tracking, it's a feature not an error."
"It's pure feature code, error tracking won't have anything" is not sufficient, and neither is "I doubt long-form docs would have this." Run the search; let the null result speak. The cost of an investigator returning empty is one subagent. The cost of missing a design doc that actually exists is a wrong answer.
If your scope assessment suggests a single-commit trivial target where the PR description already contains the complete answer, you may answer inline only after confirming all seven available category searches would be redundant. Say so explicitly. This should be rare.
Step 4. Synthesize
Spawn one synthesizer subagent:
subagent_type:generalPurposemodel: your configured why-synthesizer model (defaultclaude-opus-4-8-thinking-xhigh)readonly:false(agent mode). The synthesizer's quality check spot-verifies citations, which can require MCP access. Readonly/Ask mode strips MCPs and defeats that.
The synthesizer gets: 1. The investigator findings, including any null results and any categories skipped with justification 2. The code anchor from Step 2 (file paths, symbols, commit hashes, PR numbers, ticket IDs) 3. The user's original question 4. The epistemics framework from references/epistemics.md 5. The synthesizer prompt template from references/synthesizer-prompt.md
Its job is the final output: a confidence-weighted, evidence-cited narrative with clearly separated "what we know" and "what we're inferring" sections, plus honest acknowledgment of gaps and null-result sources.
Step 5. Present
Take the synthesizer's output and present it to the user. You may lightly edit for clarity or add context from the conversation, but do not rewrite the confidence language. The epistemic framing is the product. Dropping the hedges to sound more authoritative is the exact failure mode this skill exists to prevent.
Output Format
The final output uses this structure. Adapt as needed, but keep the confidence separation intact.
The Question. Restate what the user asked, concisely.
The Code in Question. File paths, line ranges, and key symbols. One or two lines so the reader is anchored.
What We Found (direct evidence). Claims with explicit citations (PR #, ticket ID, doc URL, chat permalink, commit hash, code comment with file:line). Each bullet is a thing we have textual evidence for. Use present tense and quote or paraphrase the source.
What We Can Reasonably Infer. Claims well-supported by indirect evidence or combinations of signals, but not explicitly stated anywhere. Each bullet must explain the inference chain: "Given A and B, it's likely that C." Use hedged language ("appears to", "likely", "suggests").
Competing Hypotheses. If the evidence fits multiple stories, list them. For each, give the hypothesis, the evidence for it, and the evidence against it. Don't force a winner when the record doesn't support one. (Skip this section if there's a clear answer.)
What We Don't Know. Explicit gaps. Questions the user asked that the evidence didn't answer. Sources we searched and came up empty. Be specific. "We searched the issue tracker for 'rate limit' and found no ticket discussing this specific threshold" is more useful than "we don't know why."
Sources Consulted. One line per investigator, including the ones that returned nothing. The reader should see at a glance (a) which MCPs were queried, (b) which came back empty, and (c) which were skipped and why. This coverage map lets the user judge breadth and redirect if something obvious was missed.
Format each line as: - <Source>: <what was searched>. <what was found, or "no relevant results," or "skipped. reason">.
Example:
- Source control (git/gh):
git log --follow backend/retry.ts, PRs #49074, #47812. Found PR #49074 introduced exponential backoff and linked ENG-4421. - Issue tracker (Linear): searched for "retry" and ENG-4421. Found ENG-4421 parent issue but no discussion of backoff parameters.
- Long-form docs (Notion): searched for "retry policy," "backend retries," "ENG-4421." No relevant results.
- Real-time team chat (Slack): skipped. No matching MCP available in this environment. Gap: conversational record not searched.
- Infrastructure observability (Datadog): searched for
retry_countmetric and monitors around 2024-08-14. Found monitor "Upstream 5xx rate > 1%" created same day as PR #49074. - Error / exception tracking (Sentry): searched for issues first-seen in Aug 2024 with stack through
retry.ts. Found issue SENTRY-3821 spiking in the week before the PR. - Product analytics warehouse (Databricks): queried
<your_analytics_db>.<schema>.stg_backend_upstream_retryfor the 30-day window around 2024-08-14. Daily failure-classified event count fell from ~1.2k/day pre-PR to <50/day post-PR. Also checkedsystem.query.historyfor relevant migration queries. None found.
After the Sources Consulted block, if the user's why question is a precursor to actually changing this code, convert the lineage findings into a Preserve / Change / Avoid / Risk constraint set suitable for planning the change.
Common Failure Modes to Avoid
- Confident storytelling. A plausible narrative built from thin evidence. A bullet with no citation goes in "inferred" or "hypotheses," not "what we found."
- Citing the code as evidence for its own intent. "Handles the null case because it checks for null" is mechanics, not motivation. Motivation comes from an external source (PR discussion, ticket, comment, conversation) or is labeled as inference.
- Recency bias. Assuming the most recent commit is authoritative. The current shape is often the accretion of many earlier decisions. Trace back.
- Sycophantic agreement. If the user suggests a reason ("I assume this is for performance?"), treat it as a hypothesis and check the evidence independently, don't just confirm it.
- Skipping the gaps section. An honest accounting of what you couldn't find out is part of the value.
- Skipping investigators by anticipation. Deciding up front that "long-form docs probably don't have this" or "this isn't an error tracking thing" without searching. The default-to-all-seven posture prevents this. A null result is a data point; a skipped search is a blind spot.
- Collapsing investigators into one agent. Each MCP has its own query vocabulary, result shape, and pitfalls; pooling them dilutes specialization and makes coverage harder to reason about. Always one investigator per category.
Reference Files
references/epistemics.md. Confidence tiers and phrasing guide. The synthesizer must follow it.references/investigator-prompt.md. Base prompt template for investigator subagents.references/source-playbook.md. Index pointing at the category playbooks below.references/sources/*.md. One self-contained example playbook per category, plus cross-cuttingincident-postmortem.md. Give an investigator the single file that matches its category and adapt it to the available MCP.references/synthesizer-prompt.md. Prompt template for the synthesizer subagent, including the output format.
Epistemics
How to reason about confidence when evidence is historical, fragmentary, and sometimes contradictory, and how to communicate it without flattening it into false certainty.
Code doesn't carry its own motivation. You can read what code does; you can't read why it exists. That lives in commits, PRs, tickets, docs, and conversations, all incomplete, biased, and sometimes missing entirely. Pretending otherwise produces confident-sounding guesses that mislead the user.
Confidence Tiers
Every claim in the final output must sit in one of these tiers. The tier determines which output section the claim goes in and how it's phrased.
1. Direct
An explicit, textual citation that answers the question. Not "the code does X so the author must have wanted X." Something an author actually wrote that says why.
Examples:
- A PR description that says "this fixes the bug where users with >1000 items couldn't paginate"
- A ticket that says "we're adding this because customer Acme requested it in their security review"
- A code comment that says "// clamp to 100 because the upstream API rejects larger values"
- A design doc that says "we chose option A over option B because we need persistence across restarts"
- A chat message from the author saying "switching to this approach since the old one was flaky in tests"
Phrasing: confident, present tense. "This exists because X." Cite the source.
2. Supported
Multiple pieces of indirect evidence converge. No single source states it explicitly, but the pattern across sources makes it likely.
Examples:
- The PR title says "improve performance," the ticket is labeled "perf," and the surrounding commits all touch the same hot path
- Multiple tests were added alongside the change, all exercising edge cases with very large inputs
- The author's other PRs from the same week all mention the same incident in their descriptions
Phrasing: confident but clearly derived. "The evidence points strongly to X: [the specific pieces]." Cite multiple sources.
3. Inferred
A reasonable reading of the context, but nothing explicitly supports it. The reader should understand this is your interpretation, not a fact from the record.
Examples:
- The PR doesn't say why, but given the error was happening in production (per the incident channel timing) and the fix was rushed (merged the same day), it was likely a hotfix.
- The function name suggests retry logic; the retry count is 3; this matches the team's general convention of "3 retries" seen elsewhere in the codebase.
Phrasing: hedged. "It appears", "likely", "suggests", "is consistent with", "one reading is". Make the inference chain explicit: "Given A and B, C seems likely because D."
4. Speculative
A plausible hypothesis, but the evidence is thin and other explanations fit equally well. Presenting these is valuable, but mark them clearly as guesses.
Examples:
- "This might be a workaround for a browser bug that's since been fixed, but we found no contemporary evidence of that."
- "It's possible this threshold was chosen to match an SLA commitment, but no SLA doc references it."
Phrasing: explicitly speculative. "One possibility is X, but we have no direct evidence." Usually lives in the "Competing Hypotheses" section alongside other possibilities.
5. Unknown
You looked and couldn't find out. A valid and important outcome. Document it.
Phrasing: "We searched X, Y, and Z and found no evidence of why." Be specific about what you searched. "We couldn't find out" is less useful than "we searched the ticket tracker with keywords A and B, scanned the 6 PRs that touched this file since 2023, and grep'd the repo for string literals matching the threshold; none surfaced a rationale."
Phrasing Guide
Words that carry confidence. Use carefully
These imply Direct or Supported confidence. Don't use them for inferences.
- "because". Implies a causal claim with evidence
- "the reason is". Same
- "was designed to". Claims author intent
- "fixes", "addresses", "solves". Claims the change achieved its goal
- "the team decided". Claims a group decision happened
If you're using these, you should have a citation immediately adjacent.
Words that hedge. Use for inferences
- "appears to"
- "seems to"
- "likely"
- "suggests"
- "is consistent with"
- "one reading is"
- "plausibly"
- "may have been"
- "the evidence points toward"
These signal that you're interpreting, not reporting. Use them liberally in the "What We Can Reasonably Infer" section.
Words to avoid
- "obviously". If it were obvious, the user wouldn't be asking
- "clearly". Almost always precedes a claim that isn't clear
- "of course". Same
- "just" (as in "it's just X for performance"). Dismissive and usually hides uncertainty
- "I think" / "I believe". You're synthesizing evidence, not giving a personal opinion. Use "the evidence suggests" instead.
Avoid rationalization
Code that "makes sense" today may have been written for reasons that no longer apply, or that were wrong when they were written. Don't retrofit a clean rationale onto messy history.
Resist the urge to:
- Assume the author did the "right" thing and work backward to justify it
- Assume a consistent pattern across the codebase was intentional when it might be copy-paste
- Turn an absence of evidence into evidence of absence ("no one mentioned security concerns, so it must not have been a concern")
The Sycophancy Trap
Users often phrase why questions with an embedded hypothesis: "Why do we do it this way, I assume it's for performance?" Don't simply confirm it. Treat it as one candidate among others and check the evidence independently. If the evidence supports it, say so with citations; if not, say so and present what the evidence does support.
The user's guess is a prompt for investigation, not a conclusion to validate.
When Evidence Contradicts
If two sources disagree (the PR description says one thing, the ticket says another), surface both. Don't pick the one that fits a tidier narrative. A typical pattern:
- The ticket says "we need this for customer X's compliance requirement"
- The PR says "cleaning up tech debt in this area"
Both may be true (the ticket motivated the work, the PR is the author's framing of it), or one may be wrong. Present both with their citations and let the user make the call.
When Evidence Is Missing
An honest "we don't know" is one of the most valuable outputs this skill can produce. The user now knows:
- The answer isn't in the obvious places
- They'll need to ask a human (the original author, the product owner, the team lead) to find out
- Or they can decide the question isn't worth pursuing further
Failing to mark a gap and filling it with a confident guess actively harms the user; they'll act on the guess.
When you hit a gap, name it concretely:
- What question you were trying to answer
- What sources you searched
- What you searched for in each
- What you found (nothing, or only tangentially related material)
Calibration Check Before Finalizing
Before delivering the output, the synthesizer should review every claim in "What We Found" and "What We Can Reasonably Infer" and ask:
1. Does this claim have a citation? If not, either add one or move it to "Inferred" / "Hypotheses". 2. Is the phrasing calibrated to the tier? (A Direct claim can use "because"; an Inferred claim cannot.) 3. Am I treating the code itself as evidence for its own intent? If so, that's not evidence. Remove or reclassify. 4. Does the output include a "What We Don't Know" section? If no gaps are mentioned, that's suspicious. Either the evidence was unusually complete or something is being swept under the rug.
Investigator Prompt Template
Build each investigator's prompt from this template; fill in the placeholders. Append the single category playbook sources/<source>.md matching this investigator's evidence category (see source-playbook.md for the index). If the target code looks defensive (null checks, retry logic, timeout handling, rate limiting, feature flags, egress guards, OOM handlers), also append sources/incident-postmortem.md for the incident-flavored queries to run inside its own source.
---
You are investigating the historical context and motivation behind a piece of code. A separate synthesizer combines your findings with other investigators' into a final answer, so gather evidence accurately rather than writing prose.
Other investigators search different sources in parallel. Don't try to cover everything. Focus on your assigned source and go deep.
Operating Posture
Work like a careful, cautious, precise investigator. Don't produce a narrative; surface evidence and describe it accurately, including the parts that don't fit a tidy story. The more boring and exact your output, the more useful it is. A single verbatim quote with a precise citation beats a paragraph of plausible-sounding summary.
- Quote, don't paraphrase when the exact wording matters. Citations should let the reader jump to the source and confirm the claim in seconds.
- Go wide before going deep. Cast a broad first net so you don't miss related context. Only then narrow in.
- Track what you searched, not just what you found. An absence is only useful if the reader knows what was looked for. Record queries verbatim.
- Resist the story. If three pieces of evidence line up neatly and a fourth contradicts them, the contradiction is the most interesting finding. Don't file it away.
- Consider the counterfactual. Before reporting a finding as strong, ask whether you would expect to find it if your current reading were wrong, and how the evidence would differ.
- Never invent. If you're tempted to round a partial finding up into a confident statement, stop and label it partial. The synthesizer is counting on your output being accurate.
The Question
{QUESTION}
The Code Anchor
Target files: {FILES_WITH_LINE_RANGES}
Key symbols: {SYMBOLS}
Initial commits touching this code (most recent first): {COMMIT_LIST}
PR numbers extracted from commit messages: {PR_NUMBERS}
Ticket IDs mentioned in commits or PR bodies (if any): {TICKET_IDS}
Your Assigned Source
{SOURCE_NAME}
{SOURCE_PLAYBOOK_SECTION}
Investigation Instructions
Gather evidence; don't answer the question directly. The synthesizer weighs the evidence and forms conclusions. Follow this loop:
1. Cast a wide net first. Start broad so you don't miss related context, then narrow in on specific items. 2. Read the whole thing. Read any PR, ticket, doc, or thread fully, not just the title or summary. The key evidence is often buried in a comment, a subtask, or a follow-up. 3. Follow links within your assigned source. If a PR references another PR or commit, pull it. If a ticket links a parent or sibling, pull it. If a doc links another doc, pull it. Stay inside your assigned source. When you spot a cross-source reference, do NOT chase it yourself. Record it under "Additional Leads" so the investigator assigned to that source can pick it up. The one-investigator-per-category design depends on this; chasing cross-source links duplicates work and confuses scope. 4. Capture quotes verbatim with their location (PR number, ticket ID, URL, commit hash, file:line). The synthesizer needs to cite this precisely. 5. Note absences. If you searched for something and came up empty, that's also a finding. Record what you searched for and what you didn't find. 6. Watch for contradictions. If two items in your source disagree, record both. Don't suppress the inconvenient one.
Don't synthesize or form a final opinion on "the why." Collect the raw material honestly and completely; the synthesizer does the reasoning.
Epistemic Discipline
- Don't confuse mechanics with motivation. A commit changing
limit = 50tolimit = 100shows the change, not necessarily why. Look for the explanation in the commit message, PR description, linked ticket, or review comments. - Don't infer intent from code style. "The author chose a functional approach" is an observation about code, not evidence of intent. Claim intent only when the author stated it.
- Preserve uncertainty. If the evidence is ambiguous, say so. If one reading is more plausible but not certain, say that. Don't collapse ambiguity to look decisive.
- No silent substitutions. If the question is about feature X and you only find evidence about feature Y, don't present Y's evidence as if it answers X.
Output Format
Return your findings in this structure. The synthesizer will read it directly.
Source
Which source you investigated (source control, issue / ticket tracker, long-form documents, real-time team chat, infrastructure observability, error / exception tracking, product analytics warehouse, code comments, etc.).
What I Searched
The queries you ran, the items you opened, the places you looked. Be specific. This tells the synthesizer how thorough the investigation was and what might still be unsearched.
Direct Evidence Found
For each piece that explicitly addresses the question:
- What it says: verbatim quote or accurate paraphrase
- Where it's from: PR #123, ticket ID, doc URL, chat permalink, commit hash, or file:line
- Author and date (if available)
- Relevance: one sentence on how it bears on the question
Indirect / Circumstantial Evidence
Items that don't explicitly answer the question but bear on it. For each:
- What it is: brief description
- Where it's from: location
- What it suggests: what a careful reader might infer, and why. Name the inference chain.
- Alternative readings: if the same evidence could support a different interpretation, note it
Contradictions
Two items that disagree with each other, with both citations.
Gaps
What you searched for and didn't find. Be specific: "Searched the issue tracker for [query] across [time range]. No matching issues." These absences are valuable data.
Additional Leads
Anything that suggests further investigation in a different source. For example, if a PR references a chat thread that wasn't in your source, note it so the real-time team chat investigator or a follow-up pass can pursue it.
What You're Not Doing
- Writing the final answer. The synthesizer does that.
- Picking sides in contradictions. Surface them.
- Speculating beyond what the evidence supports. A hunch with no evidence isn't evidence.
- Reading the code itself to figure out intent. You may read the code to understand what the target is, but don't confuse "what the code does" with "why."
Source playbooks
The why skill spawns one investigator per available evidence category, each reading a single source-specific playbook below. The playbooks are concrete examples for common MCPs; adapt them for a different MCP in the same category.
| Category | Playbook | Example MCP it documents |
|---|---|---|
| Source control history | `code-archaeology.md` | git, gh |
| Issue / ticket tracker | `linear.md` | Linear (adapt for Jira, GitHub Issues, Plane, Shortcut) |
| Long-form documents | `notion.md` | Notion (adapt for Confluence, Google Docs, Coda) |
| Real-time team chat | `slack.md` | Slack (adapt for Discord, Microsoft Teams, Mattermost) |
| Infrastructure observability | `datadog.md` | Datadog (adapt for New Relic, Honeycomb, Grafana, Splunk) |
| Error / exception tracking | `sentry.md` | Sentry (adapt for Rollbar, Bugsnag, Airbrake) |
| Product analytics warehouse | `databricks.md` | Databricks SQL (adapt for Snowflake, BigQuery, ClickHouse, dbt) |
Cross-cutting:
- `incident-postmortem.md`. Add this if the target code looks defensive (null checks, retry, timeout, rate limit, feature flag, egress guard, OOM handler).
Code Archaeology (git + in-repo)
What this source contains
- Commit history (messages, dates, authors, diffs)
- PR descriptions, review comments, and discussion threads (via
gh) - Inline code comments, TODOs, FIXMEs, deprecation notes
- ADRs (architectural decision records) if the repo keeps them
- Tests. Names and assertions often encode the edge cases that motivated a change
- Related files modified in the same commits (co-change signal)
- CHANGELOG entries, release notes in the repo
- Issue/ticket IDs mentioned in commit messages and PR bodies
The most trustworthy source, tied directly to the code, and the most complete. Everything that went through the repo should be here.
How to search it
Expand the seed commit list:
# Full history of the file through renames
git log --follow --oneline -- <file>
# Pickaxe: commits that added or removed this exact text
git log -S '<exact_string_from_code>' -- <file>
# Or for patterns:
git log -G '<regex>' -- <file>
# Who wrote each line and when
git blame -L <start>,<end> <file>
# The full diff of a specific commit
git show <hash>
# Commits between two points affecting this file
git log <old>..<new> -p -- <file>For each substantive commit, pull the PR context:
# Find the PR number from the merge commit or branch
git log -1 --format=%B <hash>
# Full PR context: body, review comments, linked issues
gh pr view <number> --json title,body,author,createdAt,mergedAt,labels,closingIssuesReferences,comments,reviews,files
# The --json reviews and comments fields are where the real signal isLook for out-of-band docs:
# ADRs often live in docs/adr/ or similar
rg -l -i 'architecture.decision' --glob '*.md'
# TODOs and FIXMEs near the target
rg -n -C2 '(TODO|FIXME|HACK|XXX|NOTE)' <target_file>
# Related tests. Names often encode the "why"
rg -l '<symbol>' --glob '*test*'What good evidence looks like here
- A PR description that explains the problem being solved, not just the change ("This fixes the pagination bug that caused X")
- A long review thread where alternatives were debated
- An inline comment near the target line that explains a non-obvious constraint
- A test named
test_handles_edge_case_when_Xthat reveals an edge case motivating the code - A commit message that references a ticket or incident ID
- A CHANGELOG entry that summarizes the user-visible rationale
Common pitfalls
- Squash-merge flatlands. If the repo squashes PRs, individual commits in the branch history are lost. Fall back to PR body and comments.
- Misleading commit messages. "Small refactor" sometimes hides an intentional behavior change. Look at the diff, not the message.
- Cargo-culted patterns. The author may have copied a pattern without understanding why. Check if the pattern originated earlier in the codebase and investigate that commit.
- Bot commits and auto-merges. Dependabot, Renovate, and automated backports usually don't carry motivation. Skip them when trying to find intent.
- Treating code as evidence of intent. The code itself isn't evidence for why it exists. Evidence comes from commit messages, PRs, comments, tests, docs. Don't cite "the function is named X" as evidence of intent.
What to return
Every commit/PR/comment that bears on the question, with:
- The exact text (quoted)
- The hash / PR number / file:line
- Author and date
- Whether it's direct (explicitly addresses the question) or circumstantial
Databricks Analytics & System Tables
What this source contains
Databricks is the product-analytics, data-pipeline, and warehouse-telemetry layer. It complements Datadog: Datadog is the infra/runtime view, Databricks is the product/data view (what users did, which experiments ran, how feature usage evolved, where a threshold constant came from).
- Product analytics events.
your_warehouse.events.analytics_track_event(raw) and typed, deduplicated per-event dbt models in<your_analytics_db>.<schema>.<table>. User behavior: feature invocations, clicks, accepts/rejects, submissions, client-reported errors. - Usage & billing events.
your_warehouse.events.usage_event/<your_analytics_db>.<schema>.stg_usage_events;your_warehouse.events.raw_model_event/<your_analytics_db>.<schema>.stg_raw_model_events. For cost- or volume-driven decisions. - Experiment / feature-flag data. Exposure and outcome tables. Schema is company-specific. Probe with
SHOW TABLESbefore assuming names. - System tables.
system.query.history,system.compute.warehouses,system.billing.*,system.access.audit. Answer "was this query expensive?", "how often did anyone run this?", "when did warehouse load spike?" - dbt lineage. Models in
<your_analytics_db>.<schema>reveal what pipelines depend on a table/field; upstream changes frequently motivate consumer-code changes. - Databricks notebooks. Exploratory analyses engineers wrote before code changes. Not queryable via the SQL MCP. If you suspect the rationale lives in a notebook, name it as a gap.
How to search it
Use the Databricks SQL MCP. Primary tool: execute_sql_read_only. If it returns a statement_id, poll with poll_sql_result rather than re-running.
Orient before querying. Schemas are company-specific; probe before trusting a table name:
SHOW TABLES IN <your_analytics_db>.<schema> LIKE '*<keyword>*';
DESCRIBE TABLE <your_analytics_db>.<schema>.stg_<event>;Time-bound every query. These tables are huge and unconstrained scans time out. Filter on _timestamp (events) or start_time (system.query.history) with a window bracketing the ship date, typically ~30 days before and after, wider only for strong reason.
Prefer typed dbt models over the raw table. <your_analytics_db>.<schema>.<table> is deduplicated, typed, and liquid-clustered; your_warehouse.events.analytics_track_event has duplicates and untyped properties_json. Model-name pattern: stg_<source>_<event_name_with_underscores>, where <source> is app, backend, website, or cli. See the databricks-use-dbt-models skill for the full mapping. Drop to the raw table only when there's no dbt model yet, or you need events from inside the dbt refresh lag.
Column conventions on the typed dbt models (knowing these avoids a DESCRIBE round-trip):
_timestamp,_id,_auth_id,_request_id,event_name. Standard on every modelproperties_<name>. Typed, underscore-cased event properties (properties_entrypoint,properties_size_bytes, …)context_team_id,context_client_version,context_country,context_client_os. Pre-extracted client context
Investigation patterns that tend to pay off
Pick the table + column combination that matches the target:
1. Event usage trajectory. Daily counts on the relevant stg_* model across a ±30d window around the PR merge. A step function from zero to steady volume within a day or two of the merge is strong circumstantial evidence the PR launched the feature. A decay to zero suggests a deprecation or deletion. 2. Guard-rail / defensive-check origin. Distribution (median / p99 / max) of the relevant properties_<name> column in the 14 days before the PR. A p99 that matches the target's threshold constant suggests the number was chosen from data. 3. Experiment / feature-flag lookup. SHOW TABLES ... LIKE '*experiment*' to find the exposure table, then pull exposure counts by variant for the relevant flag key near the PR date. 4. Query-history evidence for migrations, backfills, or perf rewrites. system.query.history filtered by statement_text ILIKE '%<table_or_symbol>%' with a tight start_time window surfaces the expensive queries that likely motivated the change (sort by total_duration_ms or aggregate SUM(read_bytes), COUNT(*)). 5. dbt lineage. If the target reads from or writes into a <your_analytics_db>.<schema> model, the model's own git history (in this repo) often carries the rationale. Hand that lead back to the git investigator rather than chasing it yourself.
What good evidence looks like here
Beyond the pattern shapes above:
- An error-classifying event's count drops to near zero in the days after a defensive-code PR. Suggests the PR resolved that error class
- An exposure table row names the target's feature-flag key with a "shipped" / "concluded" decision around the PR ship date
Common pitfalls
- Instrumented ≠ caused. An event's existence means someone cared enough to log it, not that the target code exists because of it. Pair with a PR/commit citation from the git investigator before claiming causation.
- Silent instrumentation changes. A step function in event volume may mean a new event started being logged, not that user behavior changed. Check for instrumentation PRs in the same window before reading the ramp as a feature-launch signal.
- Schema drift. Event properties evolve; a column on the typed dbt model today may not have existed when the target was written. Older data may carry the property only inside raw
properties_json. - dbt refresh lag.
<your_analytics_db>.<schema>.*is rebuilt on a schedule (often hourly/daily). For events from the last few hours, fall back toyour_warehouse.events.*and deduplicate by_id. - Company-specific tables. Experiment, feature-flag, billing, and usage tables vary. Reporting a result from a table whose existence you never confirmed is a classic failure mode. Probe with
SHOW TABLES/DESCRIBE TABLEfirst. - Retention cliff. If the relevant window predates the table's retention or the dbt model's creation date, that's a gap, not a null result. Name it explicitly so the synthesizer doesn't read "no results" as "no activity."
- Notebooks aren't queryable. The SQL MCP can't see Databricks notebooks. If you suspect the rationale lives in one, return a gap.
What to return
For each relevant finding:
- Type (product event / experiment exposure / usage or billing event / system-table row / dbt model)
- Fully-qualified table name and the exact query you ran
- Time window queried
- Compact numeric summary (counts, percentiles, first/last-seen timestamps). Don't dump raw rows.
- Temporal correlation with the target's ship date (e.g., "first row 2024-08-15; PR #49074 merged 2024-08-14")
- Relevance + strength: direct / circumstantial / weak
Datadog Telemetry
What this source contains
Datadog holds the runtime record: what actually happened in production, as opposed to what was planned or discussed.
- Metrics. Counters, gauges, histograms instrumented by the team. A metric's presence is itself evidence: someone thought this number worth watching.
- Monitors & alerts. Conditions the team decided warranted waking someone up. A monitor firing on
rate_limit_hit > 10/minis direct evidence the team worried about that threshold. - Dashboards. Curated views. The charts tell you what the team considers important for a subsystem.
- APM traces & spans. Request-level runtime data. Useful for "why is this slow" / "why is there a timeout here" questions.
- Logs. High-volume event records. Often contain the error conditions that motivated defensive code.
- Incidents. Formal incident records with timelines and linked postmortems.
- Notebooks. Exploratory investigations; often contain hypotheses and analyses.
Datadog answers "what was the production reality around the time this code was written?", which often explains the code's shape.
How to search it
Use the Datadog MCP. Start broad, then narrow.
1. Identify the owning service(s).
search_datadog_services (filter by name or team)
search_datadog_service_dependencies (see upstream/downstream)2. Dashboards and monitors first. They tell you what the team cares about.
search_datadog_dashboards (query: feature name, service name, symbol)
search_datadog_monitors (same queries)When a dashboard or monitor covers the target, note its queries and watched thresholds. The threshold is frequently the answer to "why is this clamped at N?"
3. Metrics around the target.
search_datadog_metrics (by name pattern, e.g., the feature or symbol)
get_datadog_metric_context (metadata: description, units, tags)
get_datadog_metric (timeseries; "was there a spike around the PR date?")Correlating a metric's trajectory with the target's add/change date is strong supporting evidence: "the payment_timeout metric spiked 2023-11-03, and the retry logic merged 2023-11-06."
4. Logs. Narrow, don't dump.
search_datadog_logs (raw log patterns near the target, set use_log_patterns=true)
analyze_datadog_logs (SQL-style aggregations, only when you need counts)Search with symbols, error strings, or feature names. Strongly prefer time-bounded queries (e.g., 30 days before/after the change). Log volume is huge; unconstrained searches waste time and may time out.
5. APM spans and traces.
aggregate_spans (stats: "how often does this endpoint fail?")
search_datadog_spans (inspect individual spans)
get_datadog_trace (a specific trace ID)Useful for timeouts, retries, slow paths, and cross-service behavior.
6. Incidents.
search_datadog_incidents (by title, team, date range)
get_datadog_incident (full detail for a specific incident)If the target looks defensive, search for incidents around the time it was added. An incident whose timeline includes "added defensive check for X" is near-direct evidence.
What good evidence looks like here
- A monitor whose query and threshold match the constraint the code enforces (code clamps to 100; monitor alerts when requests exceed 100/min)
- A dashboard created by the target's author, with widgets that correspond to what the code measures or guards against
- A metric showing a production spike immediately before the code was merged, and stable values after
- An incident record referencing the target code, the same symbols, or the same error strings
- Logs showing a specific error pattern the defensive code would prevent, timestamped in the window before the change
Common pitfalls
- Correlation is not causation. A spike before a PR and stabilization after is suggestive, not definitive. Other changes may have landed in the same window. Check neighboring PRs.
- Overfitting to the chart you found. Datadog visualizations are made by humans and reflect that human's framing. A chart named "retry success rate" is evidence the team cared about retry success, not that it's why a specific line of code exists.
- Vanished telemetry. Metrics can be renamed, deleted, or have short retention. If you can't find data from the relevant window, that's a gap, not a null result.
- Noise at scale. Searching logs for a common string returns thousands of matches. Narrow by service, tag, and time aggressively. Use
analyze_datadog_logsto aggregate rather than dumping raw logs. - Instrumented != caused. A metric's existence tells you someone cared enough to measure something, not that the code was added because of it. Cross-reference with commit/PR dates.
What to return
For each relevant item:
- Type (dashboard / monitor / metric / log pattern / trace / incident / notebook)
- Title or name
- Link or identifier (dashboard ID, monitor ID, metric name, incident ID)
- Owner/author and created/modified date
- The specific condition, query, or quote that bears on the question (verbatim where possible)
- Relevance: what this suggests about the target code, and how strong the connection is
Incident & Postmortem Context
Not a separate source, a cross-cutting angle. Incidents often motivate defensive code ("we added this check after the X outage"), so if the target looks defensive (null checks, retry logic, timeout handling, rate limiting, feature flags), specifically hunt for incident history across every available source:
- Notion: search for postmortems mentioning the target file, feature, or error string
- Linear: look for tickets labeled
incident,sev-*,postmortem-action-item,reliability - Slack: search
#sev-*and#incident-*channels around the dates the target code was added - Git: commits with messages like "fix for incident", "add defensive check", "revert" followed by "re-apply with..." are strong signals
- Datadog:
search_datadog_incidentsfor formal incident records with timelines; dashboards and monitors created as postmortem action items - Sentry: issues whose first-seen/last-seen window aligns with the target's PR ship date; stack traces through the target
- Databricks: product-analytics events that classify an error condition (client-reported failures, user-visible retry events, etc.) often spike during an incident window. A drop in that event count after the target PR ships is circumstantial support that the target code resolved the user-visible symptom, even when Datadog/Sentry signal is noisy.
If you find an incident link, fetch the full postmortem. Postmortems typically have an "Action Items" section that ties directly to code changes. When multiple sources corroborate (a Datadog incident ID appears in a Linear ticket, which appears in a Notion postmortem, which appears in a Slack thread that links to the target PR, and the Databricks error-event count drops after the fix), the evidence is especially strong.
Worth spending time on when the code's defensive character makes an incident-driven origin plausible. Skip it for code that doesn't look defensive.
Linear Tickets
What this source contains
- Issues describing features, bugs, and their motivation
- Project docs attached to issues (often PRDs or specs)
- Parent/sub-issue relationships (broader initiative → specific tickets)
- Comments on issues (clarifications, scope changes, "why we're doing this" rationale)
- Labels (e.g.,
compliance,customer-request,perf) that signal the type of motivation - Status updates that explain scope changes
- Attachments and linked GitHub PRs
Linear is where the product/business context often lives: the "we're doing this because customer X asked" or "this is for the Q3 compliance initiative" layer.
How to search it
Use the Linear MCP.
1. Start with linked tickets. If the seed commits or PRs reference ticket IDs (e.g., ENG-1234, [BUG-567]), fetch those first with get_issue. Read the full issue including comments. 2. List related issues by keyword. Use list_issues with text search for the feature name, key symbol, or business term. Try multiple phrasings. 3. Walk the issue tree. If you land on a sub-issue, fetch its parent. Sub-issues are tactical; parents often carry the "why." 4. Read project docs. If the issue belongs to a project, use get_project and check attached docs. Project-level documents are where specs and rationale are most often captured. 5. Check labels and milestones. Labels hint at the category of motivation (customer-request, incident-followup, compliance). Milestones tie work to deadlines, which often reveal motivation.
What good evidence looks like here
- An issue description stating the business problem: "Customer Acme needs X because of their SOC2 audit"
- A comment recording a decision: "We decided to go with approach B because approach A would require touching the billing service"
- A parent issue titled like an initiative: "Q3 Enterprise Readiness" or "Reduce Payment Failures"
- An attached PRD or spec
- Labels like
customer:acme,incident-followup,compliance,perf-regression
Common pitfalls
- Scope drift. The ticket the PR references may have been closed and reopened with a different scope. Read the whole history.
- Mechanical templates. Some teams require "Why" sections but fill them with boilerplate. Generic text ("improve user experience") is probably not a real answer.
- Stale tickets. Old tickets often reflect a version of the plan that changed. Check dates and cross-reference with the code's ship date.
- Closed-as-duplicate chains. Follow the duplicate-of relationships back to the canonical ticket.
- Private workspace content. If you can't access an issue, note that as a gap rather than guessing.
What to return
For each relevant ticket:
- Ticket ID and title
- The problem/motivation quoted from the description or comments (not paraphrased; the synthesizer needs the exact text to cite)
- Labels, parent issue, project
- Author, created date, closed date
- Link to the ticket if available
Notion Docs
What this source contains
- PRDs (product requirement documents)
- Technical specs and RFCs
- Architectural decision records (ADRs)
- Meeting notes from design reviews
- Team pages with domain context
- Postmortems from incidents
- Runbooks that may explain defensive code
- Strategy documents that set priorities
Notion is where "why" often lives in long-form before it becomes code. A significant feature usually has a doc.
How to search it
Use the Notion MCP.
1. Keyword searches with `notion-search`. Try:
- The feature name
- Key symbols / class names from the target code
- Author handles (design docs are often authored before the code lands)
- Error strings or user-visible terms
- Time-bounded queries if you know when the code shipped
2. Fetch candidate pages with `notion-fetch`. Read the full content, not the preview; rationale is often buried mid-document. 3. Follow backlinks and child pages. Design docs often have sub-pages for alternatives considered, appendices, or implementation notes. 4. Check related databases. notion-query-data-sources and notion-query-meeting-notes can surface meeting notes that discussed the decision. 5. Search author-specific spaces. If the PR author has a personal notebook (common at some companies), it may hold exploratory thinking that preceded the code.
What good evidence looks like here
- A PRD with a "Problem statement" or "Motivation" section that matches the target code's purpose
- An "Alternatives considered" or "Rejected approaches" section
- A postmortem that names the target code as the fix for a specific incident
- Meeting notes that record "we decided X because Y" and tie to the same author/date range as the PR
- An ADR template filled out non-trivially (status, context, decision, consequences)
Common pitfalls
- Outdated docs. Specs are often written before implementation and not updated; the doc may describe a plan that changed. Cross-check against the actual PR.
- Doc vs. reality drift. A spec may say "we'll do X" but the code actually does Y. Flag the divergence; the synthesizer will surface the contradiction.
- Boilerplate templates. Some orgs require a "Why" section that gets filled with fluff. Look for specificity.
- Unlinked docs. The most relevant doc may not be linked from anywhere. Broad keyword searches help.
- Multiple drafts. If a topic has multiple docs, find the one that was finalized or most recently updated. Check dates.
- Access-restricted pages. If you can't access a page, note it as a gap.
What to return
For each relevant doc:
- Title and URL
- Authors and last-updated date
- The motivation text (verbatim quote), with page/section location
- Relevant linked pages (so the synthesizer can cite them)
- Whether the doc was finalized or draft
Sentry Error History
What this source contains
Sentry is the archive of things that went wrong. For defensive, corrective, or error-handling code, it often holds the direct motivation: the specific exceptions, stack traces, and frequencies that pushed someone to add a check, catch, retry, or fallback.
- Issues. Grouped errors with counts, first/last seen timestamps, affected releases, and comments
- Events. Individual error instances within an issue (stack traces, tags, user context)
- Releases. Deployment records with associated issues (useful for "which version fixed this?")
- Replays. Session recordings of user-facing errors (if enabled)
- Profiles. Performance profiling data (less useful for "why"; more for "how slow")
- Issue comments & assignments. Sometimes contain engineer notes on root cause
The most valuable thing Sentry provides is temporal correlation: "issue X was created 2024-01-02, peaked at 500 events/day, stopped appearing after release v2.14.0 on 2024-01-15, the release that shipped the defensive check."
How to search it
Use the Sentry MCP.
1. Orient. If you don't know the project slug and organization:
find_organizations
find_projects2. Search for issues related to the target.
search_issues (natural language, e.g., "errors in PaymentService timeout", "unhandled exceptions in uploadFile")Good query components: exception class names the target handles, the function or class name of the target, error message strings the target checks for, the file path of the target.
3. Narrow by release and time window.
search_issue_events (filter by release, time, environment, trace ID, tags)
get_issue_tag_values (for an issue, see distribution across versions, users, environments)For a suspected issue, check:
- First seen. When did the error start appearing?
- Last seen. When did it stop? Does it line up with the target's ship date?
- Affected releases. Which versions saw it? Which was the fix?
- Frequency trajectory. Did it spike, then get resolved?
4. Pull the full event for context.
get_sentry_resource (pass a Sentry URL or type+ID)Does the stack trace pass through the target code? Do the tags and breadcrumbs match the conditions the target defends against?
5. Check releases that landed near the target.
find_releases (around the commit date of the target)Cross-reference release version with the PR's merge date.
6. Use Seer sparingly.
analyze_issue_with_seerSeer produces AI root-cause analyses. Useful as a hypothesis generator, but treat them as inference, not authoritative. The actual events and stack traces are the primary evidence; Seer's narrative is secondary.
What good evidence looks like here
- An issue whose first seen is shortly before the target's PR and last seen shortly after, suggesting the target addressed this error
- Stack traces that pass through or land on the target function, showing the exact failure mode being defended against
- A comment on the issue from the PR author describing the fix
- The target's PR description or commit message referencing a Sentry issue URL or ID
- An issue with high event counts that stops after the release containing the target
Common pitfalls
- Grouping drift. Sentry groups errors by fingerprint. Refactors or renames can track the "same" error under a new issue ID. If an issue ends abruptly, the error may have just been regrouped. Check for new issues immediately after.
- Release correlation is noisy. A release contains many commits. An issue stopping at v2.14.0 doesn't prove the target fixed it; another change in the same release might have. Cross-reference with the target's exact commit.
- Silent fixes. Sometimes the error stops because upstream changed, not because of the defensive code. The correlation suggests the fix; it doesn't prove authorship.
- Resolved != fixed. Issues can be marked "resolved" manually without any code change. Treat
resolvedas a human marker, not evidence that code fixed it. - Seer hallucinations. Seer can generate confident-sounding explanations that aren't right. Fall back to the actual events, stack traces, and timestamps when making claims.
- Sampling. Some projects sample events aggressively. A low event count may just mean high sampling, not a rare error. If in doubt, note the gap.
What to return
For each relevant issue:
- Issue ID and title
- Project and organization
- First seen / last seen timestamps
- Event count (and sampling rate if known)
- Affected releases
- A representative stack trace snippet showing relevance to the target (verbatim excerpt, not summary)
- First/last-seen correlation with the target's ship date
- Link to the issue
- Any author comments or resolution notes
Slack Conversations
What this source contains
- Real-time discussions of problems and decisions
- Incident channels where fire-drill decisions were made
- Design discussion threads where tradeoffs were debated
- Questions answered by senior engineers that didn't make it into docs
- Post-merge discussions that explain why something was revisited
- DMs (usually not searchable, scope accordingly)
Slack is frequently where the real decisions got made, especially for smaller changes that didn't warrant a doc. It's also the most ephemeral source: threads get deleted, channels get archived, and search quality degrades over time.
How to search it
Slack MCP tools vary. Check which Slack MCP is available and inspect its tool schema first. It may require mcp_auth. If authentication fails, stop and report the gap.
1. Author-bounded search. Messages from the PR author around the PR merge date. Limits scope dramatically and often hits gold. 2. Keyword search for the feature name and key symbols. Include misspellings and casual phrasings. 3. PR URL search. Slack often links PRs when they're reviewed or discussed. Search for the PR URL (or just /pull/<number>). 4. Error string search. If the code handles a specific error, search for the error string. Incident threads often surface. 5. Channel-scoped search. Narrow to likely channels:
#eng-*. Engineering discussions#proj-*. Project channels#incident-*/#sev-*. Incident channels- Team-specific channels for the owning team
- Design review channels
6. Thread traversal. When you find a relevant message, fetch the whole thread. The decision often lives in the replies.
What good evidence looks like here
- A thread where tradeoffs were explicitly debated ("I was going to use A but B is better because...")
- An incident channel message describing the bug the code prevents
- A question from a reviewer and an authoritative answer from the author or lead
- A reference to a meeting where a decision was made
- A message from a product manager or customer-facing engineer explaining a customer ask
Common pitfalls
- Channel archaeology limits. Very old messages may be gone due to retention policies. If you can't find anything before a certain date, note the retention cliff.
- Unsearched DMs. Many decisions happen in DMs that aren't searchable. You'll miss them; that's a known limitation.
- Speculative jokes as "decisions." Slack is casual. "Lol just do the thing" isn't a decision, even if it preceded the commit. Look for considered discussion.
- Context collapse in single messages. Without the thread, a single message often reads differently than in context. Always fetch threads.
- Auth failures. If the MCP isn't authenticated, stop. Don't make up findings. Report that Slack wasn't searchable.
What to return
For each relevant thread:
- Channel name
- Permalink or thread ID
- Participants
- Date range of the discussion
- The key quotes (verbatim) with attribution
- Context: what thread/incident/discussion this was part of
Synthesizer Prompt Template
Build the synthesizer's prompt from this template; fill in the placeholders.
---
You are answering a "why" question about a piece of code by synthesizing findings from multiple investigators who searched different historical sources (source control, issue / ticket tracker, long-form documents, real-time team chat, infrastructure observability, error / exception tracking, product analytics warehouse, and code comments). Produce a confidence-weighted, evidence-cited narrative that honestly communicates what the evidence supports and what it doesn't.
The Question
{QUESTION}
The Code Anchor
Target files: {FILES_WITH_LINE_RANGES}
Key symbols: {SYMBOLS}
Investigator Findings
{ALL_INVESTIGATOR_FINDINGS}
Sources That Weren't Searched
{SKIPPED_SOURCES_WITH_REASONS}
Epistemics Framework
You MUST follow the framework in references/epistemics.md. Read it in full before writing the output. The key rules:
1. Every claim sits in one of these tiers: Direct, Supported, Inferred, Speculative, Unknown. The tier determines what section the claim goes in and how it's phrased. 2. Every Direct/Supported claim must have a citation (PR #, ticket ID, doc URL, chat permalink, commit hash, or file:line). 3. Inferred and Speculative claims must use hedged language ("appears to", "likely", "suggests", "one possibility is"). 4. Never cite code as evidence for its own intent. 5. Gaps in the evidence must be documented. Don't fill them with plausible-sounding guesses. 6. If the user's question embedded a hypothesis, treat it as a candidate, not a conclusion. Check the evidence independently.
Instructions
1. Read all investigator findings. They gathered raw evidence, not conclusions. You weigh it. 2. Reconcile overlapping findings. Multiple investigators may have cited the same PR, ticket, or doc. Merge into a single, authoritative reference. 3. Identify contradictions. If two items of evidence disagree, don't pick one. Surface both. 4. Calibrate confidence. For each claim, identify the evidence and the tier. State Direct claims plainly with a citation. Hedge Inferred claims and explain the inference. Mark Speculative claims explicitly. Put claims with no evidence in the gaps section. 5. Verify citations by spot-checking. You can read the codebase and call MCP tools to verify citations; do not write files, commit, or modify external state. If you're uncertain a cited item exists or says what's claimed, check it. Don't propagate errors. 6. Don't overreach. The user will act on your output. Better to leave an open question open than to fill it with a confident-sounding guess.
Output Format
Write the output for the user. Use this exact structure:
---
The Question
Restate the user's question in one or two sentences so the answer is anchored.
The Code in Question
File paths, line ranges, key symbols. Two or three lines to orient a reader who lands here cold.
What We Found
Claims with direct evidence, one per bullet. Quote or paraphrase the source and cite precisely. Format each finding like:
- [Direct] {Claim}. Source: PR #123 / ticket ID / file:line. {Brief quote or paraphrase.}
- [Supported] {Claim}. Evidence: {list of items and what each contributes}.
Use [Direct] for single-source, explicit evidence. Use [Supported] when multiple indirect items converge on a conclusion.
What We Can Reasonably Infer
Claims that aren't explicitly stated anywhere but are well-supported by indirect evidence. Make the inference chain visible: "Given A and B, it's likely that C." Use hedged language ("appears to", "likely", "suggests", "is consistent with"). Format:
- [Inferred] {Hedged claim}. Reasoning: {the specific evidence and the inference step}.
If there's nothing to infer, skip this section.
Competing Hypotheses
If the evidence fits multiple stories, present them. Don't force a winner when the record doesn't support one. For each hypothesis:
- Hypothesis: {one-sentence statement}
- Evidence for: {specific items}
- Evidence against or missing: {what would need to be true but isn't, or what counter-signals exist}
Skip this section if there's a single clear answer.
What We Don't Know
Explicit gaps. Things the user asked that the evidence didn't answer. Sources searched that came up empty. Sources that weren't searchable at all, such as a missing real-time team chat MCP.
Be specific. "We searched the issue tracker for [query1], [query2], [query3] and found no issue discussing the rate-limit threshold" is useful. "We don't know why" is not. Include:
- Specific questions that went unanswered
- Searches that returned nothing
- Sources that were unavailable (and why)
- People who would likely know but who you can't ask
Sources Consulted
Bulleted list of what was actually searched, so the user can judge coverage and redirect. Format:
- Source control history: {file paths}, {number of commits reviewed}, PRs #{numbers}, and code comments searched. Or "Not searched. This should not happen because git and
ghare always expected." - Issue / ticket tracker: {ticket IDs and keyword searches}. Or "Not searched. No matching MCP available in this environment."
- Long-form documents: {page titles and search queries}. Or "Not searched. No matching MCP available in this environment."
- Real-time team chat: {channels searched, date ranges, queries}. Or "Not searched. No matching MCP available in this environment."
- Infrastructure observability: {dashboards, monitors, metrics, logs, traces, or incidents searched}. Or "Not searched. No matching MCP available in this environment."
- Error / exception tracking: {issues, events, or releases searched}. Or "Not searched. No matching MCP available in this environment."
- Product analytics warehouse: {fully-qualified tables queried, the time windows, and the numeric summaries (counts, percentiles, first/last-seen timestamps) that bore on the question}. Or "Not searched. No matching MCP available in this environment."
Confidence Summary
One or two sentences summarizing your overall confidence. E.g.:
"The core rationale (A) is well-supported by direct PR and ticket evidence. The specific threshold value (100) is inferred from the surrounding context but not explicitly documented. The question of whether this was driven by a customer request could not be answered. No relevant issue tracker or long-form doc content surfaced, and real-time team chat search was unavailable."
---
Quality Check Before Returning
Before finalizing, review your output against this checklist:
1. Does every claim in "What We Found" have a citation? If not, add one or move the claim to "Inferred" or "Hypotheses." 2. Is the phrasing tier-appropriate? (Direct claims can use "because"; Inferred claims cannot.) 3. Did you surface any contradictions you noticed, or did you quietly pick one? 4. Does the "What We Don't Know" section exist and name specific gaps? If it's empty or missing, be suspicious. Historical investigations almost always have gaps. 5. If the user embedded a hypothesis in their question, did you check it against the evidence rather than rubber-stamping it? 6. Did you cite any code as evidence for its own intent? Remove those. Code is mechanics, not motivation. 7. Is the overall tone calibrated? A confident-sounding answer with weak evidence is the exact failure mode this skill exists to prevent.
If any item fails, revise before returning.
A Final Note
The value of this output comes from its honesty, not its authority. A reader who takes your answer to the original author, an engineering lead, or a product manager should be well-positioned to ask the right follow-up questions. Be clear about what's known, what's inferred, and what's missing. Don't optimize for looking decisive. Optimize for being useful.