---
name: researcher
description: Researches codebase, project state, and external knowledge using local search, SF database queries, and web search. Use when investigating an unfamiliar subsystem, understanding project milestones and requirements, or gathering evidence for planning. Produces structured research reports.
---

<objective>
Research a topic using four complementary information sources, in priority order:
1. **Native LSP tool + local search** (`lsp`, `rg`, `find`, `ls`) — use FIRST for code exploration
2. **sift** (hybrid BM25+vector local search) — use when LSP/rg is not enough
3. **SF project state tools** — use DB-backed SF query tools for milestones, requirements, and decisions
4. **Web search** — use for external documentation and current information

This skill is the first step before planning — it produces the evidence base that drives good decisions. Without research, agents plan from assumptions; with this skill, they plan from evidence.
</objective>

<read_only_discipline>

This is a **read-only** skill. Research produces a report; it does not modify the repo, the database, or external state.

Strictly prohibited while running this skill:

- File creation, modification, or deletion (no `Write`, `Edit`, `NotebookEdit`, `touch`, `rm`, `mv`, `cp`).
- Bash redirects or heredocs that write files: `>`, `>>`, `tee`, `cat <<EOF > file`, `python -c "open(...).write(...)"`. The shell back-door does not bypass the read-only contract.
- Direct DB access: do not run `sqlite3 .sf/sf.db` or load SQLite from ad-hoc scripts. Use SF query tools exposed by the runtime; the engine owns the WAL connection.
- Git write operations: `add`, `commit`, `push`, `merge`, `rebase`, `checkout -b`, `branch -d`.
- Package installs: `npm install`, `pip install`, `cargo add`.
- Spawning subagents that perform any of the above on the researcher's behalf — the prohibition applies to delegated actions as well.

The single allowed write is the research report itself, written via the parent agent's tools after this skill returns its findings — not by the researcher mid-skill. Communicate findings as a structured report in the response, not by writing intermediate scratch files.

If a research question genuinely requires a write to answer (e.g., "does X actually work?" requires running a script), surface that as a finding labelled "requires execution" so the parent can dispatch a `worker` subagent — do not perform the write yourself.

</read_only_discipline>

<quick_start>

**Native code intelligence — USE FIRST for code exploration:**
```bash
# Workspace symbol search
lsp action=symbols query=resolveSubagentLaunchSpec

# Document symbols
lsp action=symbols file=src/resources/extensions/sf/subagent/index.ts

# Go to definition at a line/symbol
lsp action=definition file=src/resources/extensions/sf/subagent/index.ts line=42 symbol=resolveSubagentLaunchSpec

# Find references/callers
lsp action=references file=src/resources/extensions/sf/subagent/index.ts line=42 symbol=resolveSubagentLaunchSpec
lsp action=incoming_calls file=src/resources/extensions/sf/subagent/index.ts line=42 symbol=resolveSubagentLaunchSpec

# Fast text/file search
rg -n "codebase_search|resolveSubagentLaunchSpec" src packages
rg --files src/resources/extensions/sf/skills
```

**Local code search — `sift_search` tool (Sift hybrid BM25+vector):**
```json
// Best all-around preset (strongest recall + structural reranking)
{"query": "authentication middleware token validation", "strategy": "page-index-hybrid", "limit": 5}

// Path-heavy query (filename, module, symbol intent)
{"query": "write gate registration handler", "strategy": "path-hybrid", "limit": 5}

// Agentic multi-turn research for complex exploration
{"query": "trace the cache invalidation path across all layers", "agent": true, "agentMode": "graph", "plannerStrategy": "model-driven"}

// Fast lexical-only fallback
{"query": "sift_request_factory", "strategy": "bm25", "limit": 10}
```

**GitHub code search — remote-only fallback, not local repo search:**
When the repository is checked out locally, do not use GitHub `/search/code` for
that repo. Use `git grep` for tracked-file global search, `rg` for broader
worktree text search, plus `lsp`, `sift_search`, or `codebase_search` instead.
GitHub's `code_search` bucket is small and separate from normal REST/GraphQL
quotas. Use GitHub code search only for repositories that are not on disk,
dedupe repeated queries, and treat `403` rate-limit responses as a signal to
wait for reset or continue with local evidence.

**SF project state queries:**
Use the runtime query tools instead of opening `.sf/sf.db` directly:

- `milestone_status` — read milestone, slice, and task status inside an agent session.
- `sf headless query` — get the full DB-backed project snapshot when running from the shell.
- `/inspect db` — inspect schema/version diagnostics when the user asks for database health.

**Web search — use the search-the-web tool directly for current information.**
</quick_start>

<workflow>

## Step 1: Clarify the research goal

Before searching, identify what you need to know:
- **Code exploration** (finding functions, types, references) → use native `lsp` first, then `rg`
- **Project state** (milestones, slices, tasks, requirements) → use SF DB-backed query tools
- **Current external information** → use web search
- **All of the above** → combine all four sources

## Step 2: Explore code with native LSP (priority)

Use the built-in `lsp` tool for symbol-aware navigation:

```bash
# Find where a function or type is defined
lsp action=symbols query=MyFunction
lsp action=definition file=src/my-file.ts line=42 symbol=MyFunction

# Find all callers/references to a symbol
lsp action=references file=src/my-file.ts line=42 symbol=MyFunction
lsp action=incoming_calls file=src/my-file.ts line=42 symbol=MyFunction

# Read a specific file
read file=src/my-file.ts

# Grep-like search across the codebase
rg -n "TODO.*auth" src packages
```

## Step 3: Supplement with `sift_search` (when LSP/rg is not enough)

Use `sift_search` when you need semantic/hybrid search, agentic multi-turn exploration,
or explicit strategy control:

```json
// Hybrid search for conceptual matches
{"query": "authentication middleware token validation", "strategy": "page-index-hybrid", "limit": 5}

// Agentic research for complex cross-cutting concerns
{"query": "how does the dispatch loop handle retries and timeouts", "agent": true, "agentMode": "graph"}
```

## Step 4: Query SF project state

The SF database contains the canonical project state, but agents should inspect it through SF's runtime tools so they do not contend with the single-writer WAL connection:

```bash
# Full state snapshot from shell
sf headless query

# In an agent session, call the DB-backed `milestone_status` tool
# with milestoneId=M001 when you need a focused milestone snapshot.
```

## Step 5: Web search for external information

Use `search-the-web` for documentation, tutorials, or current best practices:

```bash
search_the_web "Next.js 15 app router migration guide"
```

## Step 6: Synthesize into a research report

Write findings to the appropriate artifact:
- Milestone research → `.sf/milestones/{mid}/{mid}-RESEARCH.md`
- Slice research → `.sf/milestones/{mid}/slices/{sid}/{sid}-RESEARCH.md`
- Ad-hoc research → `.sf/research/{topic}.md`

**Research report structure:**
```markdown
# Research: {topic}

## Goal
What question are we answering?

## SF Project State
What does the SF DB say? (milestones, requirements, decisions relevant to this topic)

## Codebase Evidence
What did sift find? (key file:line references)

## External Knowledge
What did web search reveal?

## Findings
Bullet points of the most important discoveries

## Gaps
What is still unknown or needs verification?

## Recommendations
What should the agent do next?
```
</workflow>

<success_criteria>
- Research report written to the correct artifact path
- At least one SF DB query executed and cited
- At least one `sift_search` or `codebase_search` executed and cited
- Findings are specific (file:line or table:row references), not generic
- Gaps identified honestly — what you could not determine
</success_criteria>

<reference_guides>

### Useful SF DB queries

```sql
-- All milestones with completion status
SELECT id, title, status, completed_at FROM milestones ORDER BY id;

-- All slices for a milestone
SELECT id, title, status, risk FROM slices WHERE milestone_id='M001' ORDER BY sequence;

-- Tasks with verification status
SELECT t.id, t.title, t.status, t.verification_status
FROM tasks t WHERE t.milestone_id='M001' AND t.slice_id='S01';

-- Open requirements
SELECT id, class, description FROM requirements WHERE status IN ('active','pending');

-- Decisions by scope
SELECT id, scope, decision FROM decisions WHERE scope='architecture' ORDER BY seq DESC;

-- Memory entries
SELECT id, category, content FROM memories ORDER BY seq DESC LIMIT 20;
```

### sift_search strategies

| Strategy | When to use |
|---|---|
| `page-index-hybrid` | **Default / best all-around.** BM25 + phrase + path-fuzzy + segment-fuzzy + vector with structural reranking. Strongest recall for conceptual discovery. |
| `path-hybrid` | Filename, path fragment, module, or symbol stem queries. Deterministic path-sensitive reranking. |
| `bm25` | Fast lexical-only. Use when speed matters or query is exact keyword. |
| `vector` | Semantic-only. Use when lexical matches are sparse but meaning matters. |
| `page-index-llm` | Heavier semantic pass on top of page-index shortlist. Slower, deeper recall. |
| `page-index-jina` | Jina-embedding semantic pass on page-index shortlist. |
| `page-index-gemma` | Gemma-embedding semantic pass on page-index shortlist. |
| `path-fuzzy` | Approximate filename/path recovery. Narrow but typo-tolerant. |
| `segment-fuzzy` | Snippet-bearing line/segment evidence. Useful when downstream tools need snippet support. |

### Agent mode options

| Option | Values | When to use |
|---|---|---|
| `agent` | `true` / `false` | Enable multi-turn autonomous search. Default: `false`. |
| `agentMode` | `linear` / `graph` | `linear`: bounded linear planning (default). `graph`: bounded graph exploration for disconnected code regions. |
| `plannerStrategy` | `heuristic` / `model-driven` | `heuristic`: rule-based planning (faster). `model-driven`: LLM-guided planning (slower, more thorough). |

### DB schema reference

- `milestones` — id, title, status, vision, success_criteria (JSON), completed_at
- `slices` — milestone_id, id, title, status, risk, goal, success_criteria
- `tasks` — milestone_id, slice_id, id, title, status, one_liner, narrative, verification_result
- `requirements` — id, class, status, description, why, source, primary_owner, validation
- `decisions` — seq, id, scope, decision, choice, rationale, revisable, made_by
- `artifacts` — path, artifact_type, milestone_id, slice_id, task_id
- `memories` — id, category, content, confidence
</reference_guides>
