Imported from eai-support/eai (
resources/gofer/system-skills/1_gofer_research/SKILL.md). Install upstream withnpx skills add eai-support/eai --skill 1_gofer_research. Copyright stays with the author.
Workspace Preflight
Before doing stage/helper work:
- Resolve the repository root.
- Check the core Gofer sentinels:
.specify/.gofer-version.specify/commands/0_gofer_start.md.specify/templates/spec-template.md.specify/templates/loop-contract-template.json.specify/templates/working-backwards-prfaq-template.md.specify/templates/business-owner-summary-template.md.specify/templates/cto-architecture-summary-template.md.specify/templates/ciso-security-summary-template.md.specify/templates/stakeholder-review-index-template.md.specify/scripts/bash/create-new-feature.sh.specify/scripts/node/parse-stage-command.mjs.specify/scripts/node/gofer-loop-audit.mjs.specify/scripts/hooks/post-tool-use.mjs.specify/scripts/powershell/install-optional-tools.ps1.specify/templates/gofer-model-policy.yaml.specify/memory/gofer-model-policy.yaml.specify/specs/.specify/memory/
- Check host-specific repo-owned files when relevant:
- Claude:
AGENTS.md,CLAUDE.md,.claude/settings.json - Codex:
AGENTS.md - Copilot:
.github/copilot-instructions.md - VS Code extension mirrors Claude/Copilot/Gemini resources itself and should still keep the core scaffold healthy
- Claude:
- If the repo already has the workspace checker script, prefer running:
node .specify/scripts/node/gofer-workspace-check.mjs --host codex --json
- If the workspace is missing or stale, ask exactly:
- "This repo is missing or stale for Gofer. Initialize/update it now?"
- If the user says yes, run the Gofer workspace bootstrap helper and then resume this command from the top.
- If the user says no, stop and explain that Gofer stage/helper work depends on the repo-owned scaffold.
description: Deep codebase and technology research for feature implementation
Gofer Research
EAI Platform Session Preflight
Before any Gofer stage/helper command does pipeline work:
- Treat durable delivery as EAI Platform delivery by default, with Azure second and every other stack only by explicit exception.
- Run
eai whoamiand confirm the EAI CLI is installed, the user is logged in, and an active tenant is visible. - If
eaiis missing,eai whoamifails, the token is expired, or no active tenant is available, stop and run/gofer:eai-first-runor ask the user to approve login/setup before continuing. - For EAI app delivery, do not continue into research, specification, planning,
tasks, implementation, or validation until
.specify/specs/{feature}/eai-preflight.mdrecords login, tenant, template, app-readiness, and next-action evidence. - Do not write tokens, secrets, private tenant IDs, or local
.envvalues into Gofer artifacts; record only product-safe readiness status and evidence.
Token And Cost Policy
Before spawning agents, calling tools, or loading large files:
- Treat
.specify/memory/gofer-model-policy.yamlas the repo-owned source of truth for simple, medium, hard, and arbiter model routing. If it is missing, run/gofer:bootstrap-workspacebefore continuing. - Use the cheapest capable model first.
- Claude: Haiku for scouting/extraction; Sonnet for normal implementation, synthesis, validation, and security; Opus for high-risk arbitration or release-critical failures.
- Codex/OpenAI: GPT mini for simple coding; GPT nano only for locate/classify/summarize/mechanical work; GPT-5.3-Codex or flagship GPT for tool-heavy coding, architecture, and release-critical validation.
- Gemini: Flash-Lite for cheap large-context scan/summarize; Flash for default research synthesis; Pro for large-context architecture or high-risk arbitration.
- Copilot: prefer Auto for simple and default work; ask the user before choosing a paid/high-tier picker model for hard security, architecture, or release gates.
- Keep raw tool output out of the main conversation context. Save stable findings to
.specify/specs/{feature}/context-bundle.md, then work from summaries. - Use provider prompt/context caching only for stable, non-secret prefixes: Gofer scaffold, AGENTS/CLAUDE/Copilot instructions, constitution, repo map, stage contracts, and validation rubric.
- Before continuing after large research, planning, implementation, or validation bursts, checkpoint the durable artifacts and compact/clear/resume context when the host supports it.
- Escalate model tier only when a cheaper pass is low-confidence, contradictory, security-sensitive, or blocking release quality.
User Input
$ARGUMENTS
You MUST consider the user input before proceeding (if not empty).
Execution Profile And Public Risk Labels
Classify the request before spawning agents. Choose exactly one effective
execution profile. This is a per-run depth decision: it controls research
depth, agent fanout, and artifact production for this feature. It does not
change the repo's broader workflow/content family, such as the optional VS Code
gofer.workflowProfile setting.
Use repository-neutral labels only: docs-only, single-repo-code,
cross-repo, api-contract, auth-security, data-model, infra-config,
release-critical, broad-fanout, unknown-blast-radius, or unknown.
- fast: docs-only, small clarification work, or clearly bounded low-risk single-repo work. Use one locator/summarizer, keep existing required artifacts concise, and skip optional councils unless evidence contradicts the request.
- standard: ordinary single-repository feature work. Standard is the catch-all for work that is not fast, full, or dynamic.
- full: bounded high-risk work such as known cross-repo impact, API contracts, auth/security, data model, infra/config, release risk, or migration risk. Use specialist fan-out, explicit evidence, blast-radius notes, and richer test/release obligations.
- dynamic: explicit dynamic workflow requests, workspace-wide audits/sweeps/migrations, unknown blast radius, broad fanout, or work spanning more than three repos/workstreams. Do not launch broad shard fanout during research; identify shard candidates and confirmation gates first.
Use this priority order so profiles are mutually exclusive and collectively
exhaustive: dynamic first, then full, then fast, then standard as the catch-all.
Users may request a deeper profile. Do not run below the computed
profileFloor without explicit approval.
Record the decision in .specify/specs/{feature}/execution-profile.md with
frontmatter fields: classificationVersion, requestedProfile,
profileFloor, effectiveProfile, riskLabels, overrideStatus,
requiresConfirmation, and classificationReason. If dynamic is selected by
the classifier but was not explicitly requested, set requiresConfirmation: true and stop for confirmation before broad fanout work.
Artifact-churn rule: preserve existing required artifacts, but do not create large optional diagrams, councils, issue lists, workflow DAGs, or extended reports unless the classified risk or user request justifies them. Mark weak claims as inferred or unknown instead of inventing certainty.
Outline
This is the first stage of the unified Gofer pipeline. Your job is to:
- Check context health
- Understand what the user wants to build
- Research the codebase to find where it should be implemented
- Identify patterns, existing code, and integration points
- Document technology decisions, business scenarios, and architecture options
- Prepare any supporting review context needed before specification begins
Output:
.specify/specs/{feature}/research.md.specify/specs/{feature}/goal-ledger.json.specify/specs/{feature}/loop-contract.json.specify/specs/{feature}/working-backwards-prfaq.md.specify/specs/{feature}/prfaq-history/01-research.md.specify/specs/{feature}/business-owner-summary.md(draft; mark missing inputs pending).specify/specs/{feature}/stakeholder-review-index.md.specify/specs/{feature}/proposal-review.md(optional supporting review context).specify/specs/{feature}/journeys/base-journey.md(application delivery default).specify/specs/{feature}/eai-preflight.md(EAI app delivery default).specify/specs/{feature}/ui-preview-brief.md(application delivery default).specify/specs/{feature}/context-bundle.md(EnterpriseAI profile only).specify/specs/{feature}/reuse-scan.md(EnterpriseAI profile only)
Step 0: Context Health Check
Before starting research, assess context window health:
.specify/scripts/bash/check-context-health.sh
- If < 50%: Proceed normally
- If 50-70%: Consider compacting after this stage completes
- If > 70%: Start a new session with a handoff summary
Research is typically the heaviest context stage - monitor usage.
Step 0.5: Load Discovery Context (If Available)
Check if discovery.md exists for this feature:
ls -la .specify/specs/{feature}/discovery.md 2>/dev/null
ls -la .specify/specs/{feature}/eai-preflight.md 2>/dev/null
If discovery.md exists:
-
Load the discovery findings to inform research focus:
- Problem Statement → Focus research on solving this specific problem
- Target Users → Research UX patterns appropriate for these users
- Value Proposition → Research metrics and measurement approaches
- Competitive Analysis → If researched, focus on differentiation
- Application Classification → Determine whether a four-step AI-augmented app journey is required
- AI-Augmented Journey → If app delivery, preserve the four-step-or-fewer journey as the scope spine for research
- EAI Preflight → If present, preserve CLI install/login/tenant/template/app readiness decisions and do not re-ask for information already confirmed
- Shared numbered-stage contract → if non-app, preserve the current shared stages without adding app-only preview or service-fit requirements
-
Use discovery to guide agent prompts:
- Codebase Locator: Focus on areas related to the discovered problem
- Codebase Analyzer: Analyze patterns relevant to target users
- Pattern Finder: Find examples that deliver similar value
- AI Pattern Finder: Find existing chatbot, voice, accessibility, translation, contextual prefill, recommendation, validation, or human-review patterns that can support each journey step
-
Load discovery memories via MemoryManager if available:
Category: 'discovery' Tags: ['#feature-{id}']
If no discovery.md exists, proceed with standard research flow.
Step 1: Get Feature Context
If no feature description provided in $ARGUMENTS:
- Ask: "What feature or change would you like to work on?"
- Wait for user response
Once you have the feature description:
- Generate a short name (2-4 words) for the feature
- Run
.specify/scripts/bash/create-new-feature.sh --json "$DESCRIPTION"with--short-name "your-short-name"to create the feature directory - Parse JSON output for FEATURE_DIR and BRANCH_NAME
Step 2: Spawn Parallel Research Agents
CRITICAL: You MUST launch these agents using the Task tool. Do NOT perform this research work inline in the main context. The main context should only orchestrate and review agent outputs.
Agent 1: Codebase Locator
Task: subagent_type="codebase-locator", model="haiku"
Prompt: "Find all code related to [FEATURE AREA] in this codebase.
Identify: entry points, related files, directory structure, key classes/functions.
Focus on: [specific aspects from user's description]"
Agent 2: Codebase Analyzer
Task: subagent_type="codebase-analyzer", model="sonnet"
Prompt: "Analyze how [RELATED FUNCTIONALITY] is implemented in this codebase.
Explain: architecture patterns, data flow, key abstractions.
Focus on: [how similar features work]"
Agent 3: Pattern Finder
Task: subagent_type="codebase-pattern-finder", model="haiku"
Prompt: "Find examples of [PATTERN TYPE] in this codebase.
Show: similar implementations we should model after.
Include: file paths, code snippets, conventions used."
Run all three agents in parallel for maximum efficiency in standard/full mode. In fast mode, collapse this into one concise locator/summarizer unless the feature touches a full-depth risk label. In dynamic mode, do not start broad fanout yet; have these agents identify candidate shards, unresolved ownership, and evidence needed before P3 builds the workflow DAG.
Step 2.5: Multi-Perspective Research (Optional)
After the core research agents complete, optionally run additional perspective strategies for deeper analysis. Skip this step if the feature is straightforward or time-constrained. For dynamic mode, use this step to test the proposed shard boundaries and stop conditions, not to execute the shards.
Strategy #6: Research Perspective Multiplier
When the feature involves complex integration or unfamiliar territory, spawn 5 perspective agents:
Task: subagent_type="research-perspective-multiplier", model="haiku"
Prompt: "Research [TOPIC] from perspective [1-5].
Perspective 1: Existing codebase patterns
Perspective 2: Open-source project approaches
Perspective 3: Latest documentation/guides
Perspective 4: Anti-patterns to avoid
Perspective 5: Emerging approaches
Context: [summary of feature and existing research findings]"
Run all 5 perspectives in parallel, then synthesize with judge:
Task: subagent_type="multi-perspective-judge", model="opus"
Prompt: "Judge verdict type: research synthesis.
Synthesize these 5 research perspectives into a unified recommendation.
[paste all 5 agent outputs]"
Strategy #9: Dependency Evaluator
When the research proposes new dependencies, evaluate each one:
Task: subagent_type="research-dependency-evaluator", model="haiku"
Prompt: "Evaluate [LIBRARY NAME] from perspective [1-3].
Perspective 1: Evaluate the proposed library
Perspective 2: Find alternatives
Perspective 3: Estimate building without it
Needed functionality: [what we need from it]"
Run all 3 perspectives in parallel, then synthesize with judge:
Task: subagent_type="multi-perspective-judge", model="opus"
Prompt: "Judge verdict type: dependency decision.
Decide whether to adopt, find alternative, or build in-house.
[paste all 3 agent outputs]"
Strategy #20: Technology Horizon Scanner
For features touching evolving technology areas:
Task: subagent_type="research-horizon-scanner", model="haiku"
Prompt: "Scan for emerging alternatives and approaches relevant to [TOPIC].
Current approach: [what we're considering]
Tech stack: [relevant technologies]"
This is a single agent — no judge synthesis needed. Include findings in the research document.
Step 3: Technology Research
While waiting for agents, research any technology questions:
-
Identify unknowns from the feature description:
- New libraries or frameworks needed?
- Integration patterns to research?
- Best practices to follow?
-
Research each unknown (use WebSearch if needed):
- Decision: [what to use]
- Rationale: [why chosen]
- Alternatives: [what else considered]
Step 3.5: Competitive Analysis Stage Flag (Optional, Run-Level)
Before drafting research.md, resolve competitive-analysis behavior for the
run:
- Treat competitive analysis as an explicit stage flag:
includeCompetitiveAnalysis(alias:competitiveAnalysisEnabled). - Default for
workflowProfile=enterpriseai:includeCompetitiveAnalysis=true. - Allow per-run override to disable competitive analysis without blocking the rest of the pipeline.
- Always generate
business-analysis.mdfor EnterpriseAI runs. - Always generate
market-analysis.mdfor EnterpriseAI runs. - When competitive analysis is disabled:
- Record
competitiveAnalysisEnabled=falsein research outputs. - Keep
market-analysis.mdas a baseline traceability artifact with disabled-state messaging (no comparative metrics). - Continue to
/2_gofer_specifynormally (no stage failure).
- Record
When enabled, market-analysis.md must include:
- At least 3 alternatives.
- Explicit EnterpriseAI-selected direction rationale.
- Traceability indicators for downstream
spec.mdandplan.mdreferences.
Step 3.6: Context Bundle and Reuse-Before-Create Scan
The standard Gofer workflow is the public default. When workflowProfile is
explicitly enterpriseai, generate:
{FEATURE_DIR}/context-bundle.md- Feature summary and approved business scenario.
- Application classification: app delivery or non-app work, with rationale.
- Four-step-or-fewer AI-augmented journey summary when app delivery applies.
- AI-readable blocks bridge summary: external/internal/hybrid profile choice, package lane, coupling status, public-readiness target, and block porting posture.
- Relevant existing specs, code paths, platform references, and API surfaces.
- EAI preflight summary: CLI version, login/account status, tenant readiness,
template initialization state, app enrollment readiness, block catalog
readiness, and next action. Do not include tokens, secrets, tenant-private
payloads, or
.env.localvalues. - EnterpriseAI object types, tenant assumptions, deployment target, and validation criteria.
- A compact "what the next agent needs" section to avoid dumping entire source files into later stages.
{FEATURE_DIR}/reuse-scan.md- Existing object types, APIs/events, workflows, modules, specs, and reference implementations that may satisfy the need.
- Existing AI assistance capabilities: chat, voice, accessibility, translation, contextual prefill, recommendation, validation, completion checks, audit logging, and escalation.
- Existing UI block/package assets, Storybook story IDs, theme override points, and source-platform dependencies that affect reuse, porting, or decoupling.
- EAI Platform/Azure stack fit for every app-delivery capability. Treat EAI Platform services as primary evidence, Azure as the preferred supporting substrate, and unrelated app stacks as exceptions only.
- Decision for each candidate: reuse, extend, or create new.
- Rationale, evidence path, and stakeholder/architecture owner if a new platform concept is recommended.
{FEATURE_DIR}/ui-preview-brief.md(application delivery only)- MVP preview scope: target users, must-have screens, target workflow, and the smallest useful UI slice to show first.
- Package profile: selected external/internal/hybrid profile choice, package lane, coupling status, public-readiness target, and why that lane is appropriate for this feature.
- EAI App Template constraint map: which approved template blocks or layout patterns the preview should use before any create-new UI concept is considered.
- Block catalog evidence: run
eai --describe,eai blocks list,eai blocks describe <id>for each candidate, andeai resources schema --format json; record stable block IDs, required resources, data/action bindings, Storybook story IDs, theme override points, package lane, coupling status, and any custom-block exception that needs approval. - Block porting and source-platform decoupling evidence: identify whether each selected block is reused as-is, ported into a package lane, or blocked by source-platform coupling; define the adapter/resource-schema boundary for any decoupling work.
- Public-readiness evidence: for external or hybrid profiles, capture package exports, consumer-facing constraints, accessibility/theming expectations, and what still prevents public consumption.
- Branding inputs: whether client styling, logos, colors, copy tone, or other corporate-brand artifacts must be applied.
- Preview validation plan: what screenshot, browser-render, or Playwright-style self-review evidence must exist before Gofer presents the preview to the stakeholder.
- Non-app runs MUST skip this artifact and record "Not applicable" in
research.md.
{FEATURE_DIR}/eai-preflight.md(EAI app delivery only, created by/0_gofer_startwhen possible and updated here when missing or stale)- Verify the safe public EAI source set used for research:
https://eai-support.github.io/eai/docs/overview,https://eai-support.github.io/eai/docs/api-reference,https://eai-support.github.io/eai/registry/,https://eai-support.github.io/eai/scenarios, andhttps://github.com/eai-support/eai-app-template. - Record whether
eai --describefound the expected scaffolding, authentication, tenant, app, resource schema, workflow readiness, block catalog, diagnostics, Gofer-refresh, and template-check commands. - Record whether
eai update --checkreports the installed CLI is current or requires an upgrade before app delivery proceeds. - Record whether the app template markers exist:
src/eai.config/object-types.ts,src/eai.config/register.ts,.env.example,.npmrc, andpackage.json. - Record whether the current repo is ready for
eai verify, needseai init <app-name>, or must avoid scaffolding because it is a non-empty non-EAI repo. - Record whether
eai template check --format jsonandeai gofer refresh --check --format jsonsucceed, report drift, or returnE001because the repo is not yet an EAI app project. - Record the app stack policy decision: EAI Platform including the EAI app template first, Azure second, or approved non-EAI exception.
- Record the selected package profile and block-catalog readiness evidence
from
eai blocks list,eai blocks readiness, and selectedeai blocks describe <id>calls. - Record resource provisioning state, object-type publish state, schema/storage health state, workflow readiness, last completed gate, blocked gate, and next recovery command so later stages inherit the real platform lifecycle instead of guessing.
- Use
.specify/references/platform/eai-repo-contract.mdand.specify/references/platform/eai-error-catalog.yamlwhenever recovery, command ordering, or drift handling is unclear. - Record only product-safe status labels such as
ready,account_required,login_required,tenant_required,operator_required,template_required,user_confirmation_required, ornot_applicable.
- Verify the safe public EAI source set used for research:
Do not recommend a new EnterpriseAI object type, API/event, workflow, or module until the reuse-before-create scan is complete. Do not recommend a non-EAI app runtime, database, hosting platform, or primary service as the default app substrate; use it only as an explicit integration/migration reference or approved exception after the EAI Platform/Azure fit has been evaluated.
Step 4: Synthesize Findings
Once all agents complete:
- Compile findings from all sources
- Identify key integration points in the codebase
- Document patterns to follow from existing code
- Note constraints and considerations
- Distill business scenario options and architecture recommendations for user review before specification
Structured Discovery Outputs (MANDATORY)
research.md MUST include all of the following in explicit sections:
- Structured Problem Statement
- Problem summary
- Current state friction
- Desired EnterpriseAI-oriented outcome
- Structured Target Persona
- Primary persona name/role
- Skill level (novice/intermediate/advanced)
- Primary needs and constraints
- Structured Value Proposition
- Primary value delivered
- Quantified or measurable goal
- Why this should be EnterpriseAI-first
- Application-Delivery Gate Summary (app delivery only)
- Preview-first rationale and the smallest useful MVP to show first
- EAI App Template reuse constraints and any approved extension gaps
- External/internal/hybrid profile choice, package lane, coupling status, public-readiness target, block-porting needs, and source-platform decoupling status
- Candidate capability-discovery inputs for the later service-fit gate
- Non-app runs must explicitly state "Not applicable"
- Goal Ledger Seed
- Goal IDs, business outcomes, metrics, targets, owners, and confidence
- Delivery states for any capability that starts mock/hybrid before going live
- Re-loop triggers for objective drift, assumption expiry, contract drift, UX scope changes, and post-validation code/test movement
- Loop Contract Seed
- Initialize
{FEATURE_DIR}/loop-contract.jsonif it is missing:node .specify/scripts/node/gofer-loop-audit.mjs --feature-dir {FEATURE_DIR} --stage 1_research --init --json - Align the loop objective, maximum iterations, evaluation commands, success criteria, stop conditions, and human escalation rules with the research risk profile.
- Keep the default contract for ordinary work, but tighten it for release-critical, security, data, auth, platform, or cross-repo work.
- Initialize
Novice Walkthrough Guardrail (MANDATORY)
Assume a novice user can read only in-repo/generated artifacts.
- Do not require external docs to understand or act on research output.
- Explain terms and recommendations in plain language before advanced details.
Step 4.5: Generate Research Visuals (Persona Pack — US4)
After synthesis, dispatch the visual writers in parallel to produce the
research-stage visuals. These run AFTER research findings are compiled so they
can cite real integration points and capability mentions, but BEFORE
research.md is finalized so the writers can append cross-references to the
generated artefacts.
Run two sub-agents concurrently:
-
visual-c4-writer(Context level only at this stage)- Inputs:
<feature_dir>/research.md(working draft)<feature_dir>/discovery.md(if present)- Template:
.specify/templates/visuals/c4-context-template.md
- Output:
<feature_dir>/visuals/c4-context.md - Required: Mermaid
C4Contextblock with named external systems and at least one Person; plain-language preamble ≥30 ≤200 words.
- Inputs:
-
visual-heatmap-writer(Capability heatmap)- Inputs:
<feature_dir>/research.md(working draft)- Template:
.specify/templates/visuals/capability-heatmap-template.md
- Output:
<feature_dir>/visuals/capability-heatmap.md - Required: Mermaid
quadrantChartplacing each capability on maturity × strategic-value axes plus tabular complement listing touched / extended / replaced capabilities.
- Inputs:
Both writers must honour the ≥30 ≤200 word plain-language preamble rule
(NFR-010). If a renderer fails downstream, the mermaid-tabular-fallback.mjs
helper provides a markdown-table replacement without losing information.
Cross-reference the generated artefacts from research.md (Step 5) under a new
## Visuals section.
Step 5: Generate Research Document
Write to {FEATURE_DIR}/research.md:
---
date: [ISO timestamp]
researcher: Gofer
feature: '[Feature Name]'
status: complete
---
# Research: [Feature Name]
## Feature Summary
[Brief description of what we're building]
## Goal Ledger Seed
Reference `.specify/specs/{feature}/goal-ledger.json` and capture:
- Goal IDs with business outcomes, metrics, targets, owners, and confidence
- Delivery-state discipline (`mock`, `hybrid`, `live`) for each risky capability
- Re-loop triggers that should reopen `/2_gofer_specify`, `/3_gofer_plan`,
`/4_gofer_tasks`, or `/6_gofer_validate`
## Loop Contract Seed
Reference `.specify/specs/{feature}/loop-contract.json` and capture:
- The current feature objective in one measurable sentence
- Evaluation commands that must pass before implementation and validation close
- Maximum check-repair iterations before human escalation
- Stop conditions that define when Gofer should stop looping
## Structured Discovery Output
### Problem Statement
- **Problem**: [What is not working today]
- **Current State Friction**: [Where users lose time/quality]
- **Desired EnterpriseAI Outcome**: [What success looks like in EAI terms]
### Target Persona
- **Primary Persona**: [Name/role]
- **Skill Level**: [novice/intermediate/advanced]
- **Top Needs**: [Need 1, Need 2, Need 3]
- **Constraints**: [Constraints that shape delivery]
### Value Proposition
- **Primary Value**: [Core value delivered]
- **Measurable Goal**: [Quantified target]
- **EnterpriseAI-First Rationale**: [Why EAI is the primary fit]
- **EAI Platform/Azure Stack Fit**: [EAI services and Azure capabilities to use;
exceptions only if approved]
## Context Bundle Summary
- **Relevant Specs**: [Existing specs to carry forward]
- **Relevant Code Paths**: [Files/directories and why they matter]
- **EnterpriseAI Object Types**: [Known or candidate object types]
- **EAI Platform Services and Azure Capabilities**: [Primary platform services,
supporting Azure services, and any blocked capabilities]
- **Tenant and Deployment Assumptions**: [Tenant, identity, runtime, target environment]
- **Validation Criteria**: [Business, security, data, architecture, and operational checks]
## Reuse-Before-Create Scan
| Candidate | Existing Evidence | Decision | Rationale | Owner |
| --------- | ----------------- | -------- | --------- | ----- |
| [Object type/API/workflow/module/spec] | [Path or reference] | Reuse/Extend/Create New | [Why] | [Owner] |
## Business Scenario Analysis
### Scenario Options Considered
| Scenario | User/Business Fit | Delivery Trade-off | Recommendation |
| ---------- | ----------------- | ------------------ | -------------- |
| [Option 1] | [Why it fits] | [Cost/complexity] | [Adopt/defer] |
| [Option 2] | [Why it fits] | [Cost/complexity] | [Adopt/defer] |
### Recommended Scenario
[Which scenario should move forward into specification and why]
## Codebase Analysis
### Where to Implement
| Component | Location | Purpose |
| ------------- | ----------------- | -------------- |
| [Component 1] | `path/to/file.ts` | [What it does] |
| [Component 2] | `path/to/dir/` | [What it does] |
### Existing Patterns to Follow
#### Pattern 1: [Name]
Found in: `path/to/example.ts:45-67`
```typescript
// Example code showing the pattern
```
Why relevant: [Explanation]
Pattern 2: [Name]
...
Integration Points
- [Integration 1]: How to connect with existing code
- [Integration 2]: ...
Related Code
path/file.ts:123- [Description]path/other.ts:45- [Description]
Technology Decisions
Decision 1: [Topic]
- Choice: [What we'll use]
- Rationale: [Why]
- Alternatives considered: [What else]
Decision 2: [Topic]
...
Recommended Architecture Direction
Recommended Architecture
[Plain-language summary of the architecture direction this feature should use]
Architecture Options Considered
| Option | Why choose it | Why not choose it now |
|---|---|---|
| [Option 1] | [Benefit] | [Trade-off] |
| [Option 2] | [Benefit] | [Trade-off] |
Constraints & Considerations
- [Constraint 1]: [Impact on implementation]
Open Questions
- [Question needing user input]
- [Another question]
Recommendations
- [Key recommendation for implementation]
- [Another recommendation]
---
## Step 5.5: Generate Supporting Proposal Review Document
Write to `{FEATURE_DIR}/proposal-review.md`:
````markdown
---
feature: '[Feature Name]'
created: [ISO timestamp]
status: supporting_context
recommendedScenario: '[short label]'
recommendedArchitecture: '[short label]'
selectedOption: ''
approvedBy: ''
approvedAt: ''
---
# Proposal Review: [Feature Name]
## What We Found
[Short, evidence-backed summary of the research findings]
## Business Scenarios Considered
| Scenario | User Value | Delivery Trade-off | Recommendation |
| -------- | ---------- | ------------------ | -------------- |
| [Option 1] | [Value] | [Trade-off] | [Adopt/defer] |
| [Option 2] | [Value] | [Trade-off] | [Adopt/defer] |
## Recommended Business Scenario
[What should be specified next and why]
## Technology Architecture Recommendation
### Recommended Architecture
[Plain-language architecture direction]
### Architecture Options
| Option | Why choose it | Why not choose it now |
| ------ | ------------- | --------------------- |
| [Option 1] | [Benefit] | [Trade-off] |
| [Option 2] | [Benefit] | [Trade-off] |
## Key Decisions and Why
- [Decision]: [Rationale]
- [Decision]: [Rationale]
## What Can Change Before Specification
- Scope changes the user may request
- Architecture changes the user may request
- Options that can be revisited before writing spec.md
## Open Questions
- [ ] [Question needing user input]
- [ ] [Another question]
## User Feedback and Overrides
- Pending user review
## Approval
- Status: supporting_context
- Next action: carry any user feedback into `/2_gofer_specify`
Step 6: Review, Discuss, and Hand Off To Specification
Before presenting the handoff, update the stakeholder-facing product release PR/FAQ artifacts:
- Create or update
{FEATURE_DIR}/working-backwards-prfaq.mdfrom.specify/templates/working-backwards-prfaq-template.md.- Fill the Press Release with the best current customer problem, launch promise, customer benefit, and "How To Get Started" story from research.
- Fill External FAQ with researched customer/process evidence and mark
unknown claims as
Pending research validationinstead of inventing them. - Fill Internal FAQ Business Owner and CTO sections with research options, platform constraints, and architecture trade-offs.
- Write an immutable snapshot to
{FEATURE_DIR}/prfaq-history/01-research.md. - Create or update
{FEATURE_DIR}/business-owner-summary.mdfrom.specify/templates/business-owner-summary-template.mdusingproblem-brief.md,discovery.md,research.md, value-stream, and ROI evidence when present. Ifspec-summary.mdorbusiness-metrics.mddoes not exist yet, keep the relevant rows and mark statusPending /2 or /7a. - Update
{FEATURE_DIR}/stakeholder-review-index.mdfrom.specify/templates/stakeholder-review-index-template.mdand mark the Business Owner and CTO review asks that should be answered before or during/2_gofer_specify.
After saving research.md, goal-ledger.json, proposal-review.md, and the
PR/FAQ review artifacts:
-
Present summary to user:
- What was found
- Business scenarios considered
- Recommended business scenario
- Recommended architecture direction
- Options and trade-offs
- Any open questions needing input
-
Ask focused follow-up questions only if needed:
- Clarify the preferred business scenario if the research found real alternatives
- Clarify the preferred architecture direction if the trade-off is still ambiguous
- Confirm whether the user wants to stop after research or continue into specification
-
Run architecture questions one-by-one (MANDATORY when architecture options exist):
- Ask exactly ONE architecture question at a time using AskUserQuestion
- After each answer, ask whether the user wants to discuss that question before locking the answer
- If the user asks clarifying questions, answer them first, then re-ask the same question for a final decision
- Record the final answer in
proposal-review.mdbefore moving to the next question - Never bundle multiple architecture decisions into a single prompt
Suggested order:
- Confirm preferred architecture option
- Confirm the key trade-off priority (speed, flexibility, reliability, cost)
- Confirm non-negotiable constraints/integration boundaries
-
If the user requests changes:
- Update
proposal-review.mdwith the feedback inUser Feedback and Overrides - Set
status: revised_supporting_contextif the recommendation must change - Revise the recommendation before continuing
- Update
-
If the user wants to stop after research:
- End after summarizing the current findings
- Do not auto-chain until the user explicitly asks to continue
-
Signal completion:
✓ Research complete: {FEATURE_DIR}/research.md
✓ Goal ledger seeded: {FEATURE_DIR}/goal-ledger.json
✓ Loop contract seeded: {FEATURE_DIR}/loop-contract.json
✓ Working Backwards PR/FAQ updated: {FEATURE_DIR}/working-backwards-prfaq.md
✓ PR/FAQ research snapshot: {FEATURE_DIR}/prfaq-history/01-research.md
✓ Business Owner summary draft: {FEATURE_DIR}/business-owner-summary.md
✓ Stakeholder review index updated: {FEATURE_DIR}/stakeholder-review-index.md
✓ Supporting review context ready: {FEATURE_DIR}/proposal-review.md
Key findings:
- [Finding 1]
- [Finding 2]
AUTO-CHAIN (DEFAULT): Unless the user explicitly asks to stop after
research, invoke the Skill tool with skill="/2_gofer_specify" immediately
after the research summary and any critical clarification answers are captured.
Step 6.5: Brownfield/Legacy Analysis (For Existing Codebases)
When working in an existing codebase, add this section to research.md:
## Brownfield Analysis
### Constraints & Limitations
| Constraint Type | Description | Impact on Implementation |
| ----------------- | ----------------------------------------- | ------------------------------ |
| Framework | [e.g., React 17 - no concurrent features] | [How this limits our approach] |
| Database | [e.g., PostgreSQL 12, existing schema] | [Schema constraints] |
| API Compatibility | [e.g., Must maintain v1 endpoints] | [Backward compatibility needs] |
| Performance | [e.g., Response time < 200ms] | [Optimization requirements] |
### Technical Debt to Avoid
The following patterns are deprecated or problematic - do NOT use:
| Pattern | Found In | Why Avoid | Use Instead |
| ------------- | ----------------- | --------- | -------------------- |
| [Old pattern] | `path/to/file.ts` | [Reason] | [Preferred approach] |
### Areas Requiring Extra Caution
- **[Area 1]**: [Why it's fragile and what to watch for]
- **[Area 2]**: [Known issues or gotchas]
### Integration Requirements
| Existing Service | Integration Method | Notes |
| ---------------- | ------------------ | ------------------------------ |
| [Service 1] | [API/Import/Event] | [Authentication, format, etc.] |
### Downstream Dependencies
Code that depends on areas we're modifying:
- `path/to/dependent.ts:45` - [What it depends on]
- `path/to/consumer.ts:123` - [What it expects]
Brownfield Checklist
Before modifying existing code:
- Understand current behavior (read and trace code flow)
- Document what must NOT change (protected boundaries)
- Identify downstream dependencies
- Add characterization tests if modifying complex logic
- Plan rollback strategy for risky changes
Step 6.5: Journey Variant Generation (Optional)
If a base journey exists at
.specify/specs/{feature}/journeys/base-journey.md:
Generate industry variants to discover innovative approaches from other domains.
Generate Variant Count
Pick a random number between 10-50:
VARIANT_COUNT=$((RANDOM % 41 + 10))
echo "Generating $VARIANT_COUNT industry variants"
Load Industry Templates
Read .specify/templates/journey/industry-variants.yaml for industry-specific
patterns.
Generate Variants
For each variant, create a file at:
.specify/specs/{feature}/journeys/variants/{industry}-{number}.md
Example: healthcare-1.md, retail-2.md, finance-1.md
Distribute proportionally across 10 industries:
- retail, healthcare, finance, education, hospitality
- logistics, manufacturing, legal, real_estate, entertainment
Each variant should include:
---
id: {feature}-{industry}-{number}
baseJourneyId: {feature}-journey
industry: {industry}
variantNumber: {number}
created: {ISO-timestamp}
---
# Journey Variant: {Industry} #{number}
## Base Journey Reference
Based on: [base-journey.md](../base-journey.md)
## Industry Context
{Description of how this industry typically handles similar journeys}
## Adaptations
{How the base journey is adapted for this industry}
1. **Step N adapted**: {How step N changes in this industry}
2. **Actor change**: {Different actors in this industry context}
## Innovation Insights
Key innovations from {industry} that could apply to your feature:
1. **{Innovation 1}**: {Description and how it could be applied}
2. **{Innovation 2}**: {Description and how it could be applied}
## Modified Diagram
```mermaid
sequenceDiagram
{Industry-specific sequence diagram}
```
Potential Application
How these insights could enhance your feature:
- {Specific suggestion 1}
- {Specific suggestion 2}
### Document Innovation Summary
Add an "Innovation Insights" section to `research.md`:
```markdown
## Innovation Insights (from Industry Variants)
Generated {N} journey variants across 10 industries.
### Top Innovations to Consider
| Industry | Innovation | Application Potential |
|----------|------------|----------------------|
| Healthcare | AI symptom checker | Could add AI-powered input validation |
| Finance | Real-time fraud detection | Could add anomaly detection |
| Retail | Personalized recommendations | Could add user-specific suggestions |
### Variant Summary
| Industry | Count | Key Patterns |
|----------|-------|--------------|
| Retail | 5 | Cart recovery, recommendations |
| Healthcare | 4 | Patient portal, telehealth |
| ... | ... | ... |
Skip Conditions
Skip variant generation if:
- No base journey exists (user skipped journey mapping)
- Feature is purely technical (no user-facing journey)
- Context window is at Warning level (>50%)
Step 7: Observability Logging
At stage completion, log metrics:
.specify/scripts/bash/log-stage.sh 1_research --complete --tokens [N] --compactions [N]
This tracks:
- Stage duration
- Token usage
- Compaction events
- Quality metrics snapshot
Logs to: .specify/logs/pipeline.jsonl
Important Notes
- All output goes to
.specify/specs/{feature}/- not thoughts/shared/ - Run agents in parallel for efficiency
- Include specific file paths and line numbers for all references
- Structured Problem Statement + Persona + Value Proposition are required in
research.md - Research must remain usable by novices without external docs
- Research should inform specification directly - focus on what helps users
discuss the business scenario and architecture before
spec.mdis written - Maximum 5 open questions - make informed decisions for the rest
- Use
proposal-review.mdas optional supporting context, not as a blocking stage - Log stage completion for observability tracking
Optional Helpers: Vocabulary Extraction and Zoom-Out
If the operator explicitly requests the vocabulary selector after
research.md exists, run gofer:vocabulary inline and write
.specify/specs/{feature}/glossary.md using the same artifact contract as the
standalone helper.
If the operator explicitly requests the zoom-out selector after research.md
exists, run gofer:zoom-out inline and write
.specify/specs/{feature}/zoom-out-report.md using the same artifact contract
as the standalone helper.
If research.md is missing, continue the stage normally and report that the
helper was not run.
These selectors are optional and do not change stage progress, routing, or pipeline state.