reverse-engineer
Performs deep codebase analysis to generate 11 comprehensive documentation files. Adapts output based on the selected route -- Greenfield extracts business logic only (tech-agnostic), Brownfield extracts business logic + technical implementation (tech-prescriptive). Step 2 of 6 in reverse engineering. Use when asked to reverse engineer the codebase, extract business logic, or generate comprehensive documentation.
What this skill does
# Reverse Engineer (Route-Aware)
**Step 2 of 6** in the Reverse Engineering to Spec-Driven Development process.
The 6-step process: 1. Analyze, 2. Reverse Engineer (this skill), 3. Create Specs, 4. Gap Analysis, 5. Implementation Planning, 6. Implementation.
**Estimated Time:** 30-45 minutes
**Prerequisites:** Step 1 completed (`analysis-report.md` and route selection in `.stackshift-state.json`)
**Output:** 11 documentation files in `docs/reverse-engineering/`
**Route-Dependent Behavior:**
- **Greenfield:** Extract business logic only (framework-agnostic)
- **Brownfield:** Extract business logic + technical implementation details
Output is the same regardless of implementation framework (Spec Kit, BMAD, or BMAD Auto-Pilot). The framework choice only affects what happens after Step 2.
---
## Configuration Check
**Guard: Verify state file exists before proceeding.**
```bash
if [ ! -f .stackshift-state.json ]; then
echo "ERROR: .stackshift-state.json not found."
echo "Step 1 (Initial Analysis) must be completed first. Run /stackshift.analyze to begin."
exit 1
fi
DETECTION_TYPE=$(cat .stackshift-state.json | jq -r '.detection_type')
ROUTE=$(cat .stackshift-state.json | jq -r '.route')
if [ "$DETECTION_TYPE" = "null" ] || [ -z "$DETECTION_TYPE" ]; then
echo "ERROR: detection_type missing from state file. Re-run /stackshift.analyze."
exit 1
fi
if [ "$ROUTE" = "null" ] || [ -z "$ROUTE" ]; then
echo "ERROR: route missing from state file. Re-run /stackshift.analyze."
exit 1
fi
echo "Detection: $DETECTION_TYPE"
echo "Route: $ROUTE"
SPEC_OUTPUT=$(cat .stackshift-state.json | jq -r '.config.spec_output_location // "."')
echo "Writing specs to: $SPEC_OUTPUT"
if [ "$SPEC_OUTPUT" != "." ]; then
mkdir -p "$SPEC_OUTPUT/docs/reverse-engineering"
mkdir -p "$SPEC_OUTPUT/.specify/memory/specifications"
fi
```
**State file structure:**
```json
{
"detection_type": "monorepo-service",
"route": "greenfield",
"implementation_framework": "speckit",
"config": {
"spec_output_location": "~/git/my-new-app",
"build_location": "~/git/my-new-app",
"target_stack": "Next.js 15..."
}
}
```
**Capture commit hash for incremental updates:**
```bash
COMMIT_HASH=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
COMMIT_DATE=$(git log -1 --format=%ci 2>/dev/null || date -u +"%Y-%m-%d %H:%M:%S")
echo "Pinning docs to commit: $COMMIT_HASH"
```
**Extraction approach based on detection + route:**
| Detection Type | + Greenfield | + Brownfield |
|----------------|--------------|--------------|
| **Monorepo Service** | Business logic only (tech-agnostic) | Full implementation + shared packages (tech-prescriptive) |
| **Nx App** | Business logic only (framework-agnostic) | Full Nx/Angular implementation details |
| **Generic App** | Business logic only | Full implementation |
- `detection_type` determines WHAT patterns to look for (shared packages, Nx project config, monorepo structure, etc.)
- `route` determines HOW to document them (tech-agnostic vs tech-prescriptive)
---
## Phase 1: Deep Codebase Analysis
Use the Task tool with `subagent_type=stackshift:stackshift-code-analyzer:AGENT` to perform analysis. If the agent is unavailable, fall back to the Explore agent.
**Error recovery:** If a subagent fails or returns empty results for a sub-phase, retry once with the Explore agent. If the retry also fails, record the gap with an `[ANALYSIS INCOMPLETE]` marker and continue with remaining sub-phases.
**Missing components:** If a sub-phase finds no relevant code (e.g., no frontend in a backend-only service), document the absence in the corresponding output file rather than skipping the sub-phase.
Launch sub-phases 1.1 through 1.6 in parallel using separate subagent invocations. Collect all results before proceeding to Phase 2.
#### 1.1 Backend Analysis
- Find all API endpoints and record their method, route, auth requirements, parameters, and purpose.
- Catalog every data model including schemas, types, interfaces, and field definitions.
- Inventory all configuration sources: env vars, config files, and settings.
- Map every external integration: APIs, services, and databases.
- Extract business logic from services, utilities, and algorithms.
#### 1.2 Frontend Analysis
- List all pages and routes with their purpose and auth requirements.
- Catalog all components by category: layout, form, and UI components.
- Document state management: store structure and global state patterns.
- Map the API client layer: how the frontend calls the backend.
- Extract styling patterns: design system, themes, and component styles.
#### 1.3 Infrastructure Analysis
- Document deployment configuration: IaC tools, cloud provider, and services.
- Map CI/CD pipelines and workflows.
- Catalog database setup: type, schema, and migrations.
- Identify storage systems: object storage, file systems, and caching.
#### 1.4 Testing Analysis
- Locate all test files and identify the testing frameworks in use.
- Classify tests by type: unit, integration, and E2E.
- Estimate coverage percentages by module.
- Catalog test data: mocks, fixtures, and seed data.
#### 1.5 Business Context Analysis
- Read README, CONTRIBUTING, and any marketing or landing pages.
- Extract package descriptions and repository metadata.
- Identify comment patterns indicating user-facing features.
- Collect error messages and user-facing strings for persona inference.
- Analyze naming conventions to reveal domain concepts.
- Examine git history for decision archaeology.
#### 1.6 Decision Archaeology
- Inspect dependency manifests (package.json, go.mod, requirements.txt) for technology choices.
- Analyze config files (tsconfig, eslint, prettier) for design philosophy.
- Review CI/CD configuration for deployment decisions.
- Run git blame on key architectural files to identify decision points.
- Collect comments with "why" explanations (TODO, HACK, FIXME, NOTE).
- Look for rejected alternatives visible in git history or comments.
**Progress signal:** After all sub-phases complete, log: "Phase 1 complete: Analysis gathered for [list which sub-phases produced results]."
---
## Phase 2: Generate Documentation
Create `docs/reverse-engineering/` directory and generate all 11 documentation files. For each file, apply the greenfield or brownfield variant as described in `operations/output-file-specs.md`. Read that file now for the detailed per-file specifications.
If `.stackshift-docs-meta.json` already exists, overwrite it completely with fresh metadata.
### Step 2.1: Write metadata file FIRST
```bash
COMMIT_HASH=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
COMMIT_DATE=$(git log -1 --format=%ci 2>/dev/null || date -u +"%Y-%m-%d %H:%M:%S")
GENERATED_AT=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
```
Write `docs/reverse-engineering/.stackshift-docs-meta.json`:
```json
{
"commit_hash": "<COMMIT_HASH>",
"commit_date": "<COMMIT_DATE>",
"generated_at": "<GENERATED_AT>",
"doc_count": 11,
"route": "<greenfield|brownfield>",
"docs": {
"functional-specification.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"integration-points.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"configuration-reference.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"data-architecture.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"operations-guide.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"technical-debt-analysis.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"observability-requirements.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"visual-design-system.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"test-documentation.md": { "generated_at": "<GENERATED_AT>", "commit_hash": "<COMMIT_HASH>" },
"business-context.md": { "generated_at": "<GENERATED_AT>",Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.