From 8ada7aa67b7a0b29e41bb941985197e01cc6a042 Mon Sep 17 00:00:00 2001 From: dhaan-ish Date: Mon, 12 Jan 2026 20:31:54 +0530 Subject: [PATCH 1/2] feat: rev-spec for python-uv and poetry --- python/poetry/reverse-arch.md | 149 +++++++++++++++++++ python/poetry/reverse-spec.md | 133 +++++++++++++++++ python/uv/reverse-arch.md | 263 ++++++++++++++++++++++++++++++++++ python/uv/reverse-spec.md | 180 +++++++++++++++++++++++ 4 files changed, 725 insertions(+) create mode 100644 python/poetry/reverse-arch.md create mode 100644 python/poetry/reverse-spec.md create mode 100644 python/uv/reverse-arch.md create mode 100644 python/uv/reverse-spec.md diff --git a/python/poetry/reverse-arch.md b/python/poetry/reverse-arch.md new file mode 100644 index 0000000..aa9e0b7 --- /dev/null +++ b/python/poetry/reverse-arch.md @@ -0,0 +1,149 @@ +# Rule: Reverse-Engineering a Technical Spec from Existing Python/Poetry Code + +## Role +Act as a **Senior Technical Architect** specializing in Python ecosystems who can extract architecture, patterns, and technical decisions into a clear document. + +## Goal +Analyze an existing Python codebase managed with **Poetry** and produce a **Technical Specification Document (TSD)** through a **multi-turn conversation**. + +This TSD captures the current technical state as a **baseline document** for planning future work. + +## Process + +1. **Map & Analyze:** Identify tech stack, patterns, and dependencies. +2. **Confidence Check:** Categorize findings by confidence level. +3. **Ask Clarifying Questions:** Present targeted questions. **STOP and wait.** +4. **Generate TSD:** After answers, produce the final TSD. + +--- + +## Step 1: Analyze the Codebase + +### 1.1 Tech Stack (Poetry Focus) + +| What to Find | Where to Look | +|--------------|---------------| +| **Python Version** | `pyproject.toml` (`python = "^3.11"`) | +| **Package Manager** | `poetry.lock` confirms Poetry | +| **Framework** | Dependencies (FastAPI, Django, Flask) | +| **Key Libraries** | `[tool.poetry.dependencies]` | +| **Dev Tools** | `[tool.poetry.group.dev.dependencies]` | +| **Plugins** | `[tool.poetry.plugins]` section | + +### 1.2 Project Structure + +Identify the layout pattern: +- **Flat Layout:** Package in root +- **Src Layout:** Package under `src/` +- **Layered:** `api/`, `services/`, `models/` +- **Domain-Driven:** `orders/`, `users/` + +### 1.3 Architectural Patterns + +- **Style:** Monolith, Microservice, Serverless? +- **API:** REST, GraphQL, gRPC? +- **Async:** asyncio, sync, mixed? +- **Data Access:** Repository, Active Record, raw queries? + +### 1.4 External Integrations + +| Type | Look For | +|------|----------| +| **HTTP Clients** | `httpx`, `requests`, `aiohttp` | +| **Databases** | SQLAlchemy, Django ORM, asyncpg | +| **Queues** | Celery, RQ, Kafka | +| **Cloud** | boto3, google-cloud-*, azure-* | + +### 1.5 Poetry-Specific Observations + +- **Dependency Groups:** `[tool.poetry.group.*]` for dev, test, docs +- **Extras:** `[tool.poetry.extras]` for optional features +- **Scripts:** `[tool.poetry.scripts]` entry points +- **Plugins:** Custom Poetry plugins in use +- **Source Repositories:** Private PyPI or alternative sources + +--- + +## Step 2: Confidence Check + +| Category | Description | Action | +|----------|-------------|--------| +| **Verified** | Confirmed by code/config | Document directly | +| **Needs Confirmation** | Scope/intent unclear | Ask question | +| **Assumed** | Cannot determine | State assumption | + +--- + +## Step 3: Ask Clarifying Questions + +### Example Format + +```markdown +### A. Scope + +1. **Deployment:** Found `Dockerfile` and `serverless.yml`. Document: + A. Container only (production) + B. Serverless only + C. Both with contexts + +### B. Intent + +2. **Dependency Groups:** Using `dev`, `test`, `docs` groups. Document: + A. All groups with purposes + B. Only production dependencies + C. Production + dev workflow + +### C. Accuracy + +3. **Package Layout:** Uses src layout. Is this team standard? + A. Yes, src layout is standard + B. No, flat layout preferred + C. Document as-is +``` + +--- + +## Step 4: Generate TSD + +### TSD Structure + +1. **Service Overview** — Name, purpose, relationships +2. **Tech Stack** — Python, framework, DB, libraries with versions +3. **Project Structure** — Directory tree with explanations +4. **Architecture** — Style, patterns, request flow +5. **External Dependencies** — Table: Name, Type, Purpose +6. **Configuration** — Environment variables, secrets management +7. **Development Workflow** + ```bash + poetry install # Install dependencies + poetry run pytest # Run tests + poetry run myapp # Run application + poetry add # Add dependency + poetry add -G dev # Add dev dependency + ``` +8. **Constraints** — Technical limitations, boundaries +9. **Assumptions** — Stated assumptions + +### Guidelines +- **Be Concise:** Reference document, not tutorial +- **Version Numbers Matter:** Critical for brownfield systems +- **State the Baseline:** Documents *current* state + +--- + +## Output + +- **Format:** Markdown +- **Filename:** `TSD-[service-name].md` + +--- + +## Final Instructions + +1. **DO NOT** generate TSD until questions are answered +2. **Start** with analysis summary and confidence check +3. **END first response** with clarifying questions +4. If user says "skip questions", proceed with stated assumptions + +--- +# End of reverse-arch.md (Python/Poetry) diff --git a/python/poetry/reverse-spec.md b/python/poetry/reverse-spec.md new file mode 100644 index 0000000..a18b780 --- /dev/null +++ b/python/poetry/reverse-spec.md @@ -0,0 +1,133 @@ +# Rule: Reverse-Engineering a PRD from Existing Python/Poetry Code + +## Role +Act as a **Senior Technical Architect** specializing in Python ecosystems who can read code and translate implementation details into clear, user-centric product requirements. + +## Goal +Analyze an existing Python codebase managed with **Poetry** and produce a **Product Requirements Document (PRD)** through a **multi-turn conversation**. + +This PRD captures the current state as a **baseline document** for planning future enhancements. + +## Process + +1. **Map & Analyze:** Explore the codebase. Extract implemented behavior. +2. **Confidence Check:** Categorize findings by confidence. Identify what needs confirmation. +3. **Ask Clarifying Questions:** Present targeted questions. **STOP and wait for answers.** +4. **Generate PRD:** After receiving answers, produce the final PRD. + +--- + +## Step 1: Analyze the Codebase + +### Poetry-Specific Files to Examine + +| File/Pattern | What to Look For | +|--------------|------------------| +| `pyproject.toml` | `[tool.poetry]` section, dependencies, scripts, plugins | +| `poetry.lock` | Locked dependency versions | +| `src/` or package dirs | Main application code | +| `tests/` | Test files describing expected behavior | +| `.env`, `.env.example` | Environment variables, feature flags | +| `Dockerfile` | Containerization and deployment hints | + +### What to Extract + +#### 1.1 Features & Capabilities +- What the system does today +- CLI commands (check `[tool.poetry.scripts]`) +- API endpoints (FastAPI, Flask, Django routes) +- Key workflows and user roles + +#### 1.2 Business Logic & Constraints +- Domain rules in code (e.g., "Order total must be > $0") +- User-facing constraints (e.g., "Max upload 10MB") +- State transitions and validation rules + +#### 1.3 Integration Points +- External APIs (`httpx`, `requests` usage) +- Databases, message queues, cloud services + +#### 1.4 Observations +- Hardcoded values representing business rules +- Feature flags and optional dependencies (`[tool.poetry.extras]`) + +--- + +## Step 2: Confidence Check + +| Category | Description | Action | +|----------|-------------|--------| +| **Verified** | Confirmed by code, tests, or config | Document directly | +| **Needs Confirmation** | Intent unclear | Ask a question | +| **Assumed** | Cannot determine from code | State assumption | + +--- + +## Step 3: Ask Clarifying Questions + +Format questions with: +- **Numbered questions** +- **Multiple-choice options** based on code patterns +- **File references** for context + +### Example Format + +```markdown +### A. Scope + +1. **CLI Commands:** Found `myapp` and `myapp-admin` in `[tool.poetry.scripts]`. Document: + A. Both commands + B. Only `myapp` (primary) + C. Other: _______ + +### B. Intent + +2. **Rate Limit (100/min):** In `api/middleware.py`: + A. Business rule (document as constraint) + B. Technical default (document as limitation) + C. Internal detail (do not document) + +### C. Accuracy + +3. **User Roles:** Found Admin, Editor, Viewer in `auth/`. Complete? + A. Yes, document these three + B. No, additional roles: _______ +``` + +--- + +## Step 4: Generate PRD + +### PRD Structure + +1. **System Summary** — Purpose and primary function +2. **User Roles & Permissions** — Who uses it and capabilities +3. **Functional Requirements** — Grouped by feature, numbered +4. **Business Rules** — Domain rules and validation +5. **System Constraints** — Technical limitations affecting UX +6. **Edge Cases & Error Handling** — Boundary behaviors +7. **Assumptions** — Stated assumptions + +### Guidelines +- **Be Explicit:** "Users cannot delete admins" > "Manage permissions" +- **Describe Behavior, Not Code:** "Validates email format" > "`validate()` uses regex" +- **State the Baseline:** Documents *current* behavior + +--- + +## Output + +- **Format:** Markdown +- **Filename:** `PRD-[service-name].md` + +--- + +## Final Instructions + +1. **DO NOT** generate PRD until questions are answered +2. **Start** with analysis summary and confidence check +3. **End first response** with clarifying questions +4. If user says "skip questions", proceed with stated assumptions + +--- +# End of reverse-spec.md (Python/Poetry) diff --git a/python/uv/reverse-arch.md b/python/uv/reverse-arch.md new file mode 100644 index 0000000..6214c11 --- /dev/null +++ b/python/uv/reverse-arch.md @@ -0,0 +1,263 @@ +# Rule: Reverse-Engineering a Technical Spec from Existing Python/uv Code + +## Role +Act as a **Senior Technical Architect** specializing in Python ecosystems who can read code and extract the underlying architecture, patterns, and technical decisions into a clear, maintainable document. + +## Goal +To analyze an existing ("brownfield") Python codebase managed with **uv** and produce a **lean, developer-focused** Technical Specification Document (TSD) through a **multi-turn conversation**. + +This TSD serves as a **baseline document** that captures the current technical state of the system. It is intended to be used alongside a PRD (generated via `reverse-spec.md`) as context for planning future enhancements, bug fixes, or refactors—not for identifying problems to fix in the current implementation. + +## Process + +1. **Map & Analyze:** Explore the codebase structure. Identify the tech stack, architectural patterns, and external dependencies. +2. **Confidence Check:** Categorize findings by documentation confidence. Identify what needs user confirmation. +3. **Ask Clarifying Questions:** Present targeted questions to ensure accurate documentation. **STOP and wait for answers.** +4. **Generate TSD:** After receiving user answers, produce the final Technical Specification Document. + +**Important:** This is a multi-turn workflow. Steps 1-3 happen in the first response. Step 4 happens only after the user responds. + +--- + +## Step 1: Analyze the Codebase + +Examine project artifacts with special attention to Python and uv-specific configurations. + +### 1.1 Tech Stack (Python/uv Focus) + +| What to Find | Where to Look | +|--------------|---------------| +| **Python Version** | `.python-version`, `pyproject.toml` (`requires-python`) | +| **Package Manager** | `uv.lock` presence confirms uv usage | +| **Framework** | `pyproject.toml` dependencies (FastAPI, Django, Flask, etc.) | +| **Database** | Dependencies (SQLAlchemy, asyncpg, Django ORM, etc.) | +| **Key Libraries** | `[project.dependencies]` and `[project.optional-dependencies]` | +| **Dev Tools** | `[tool.ruff]`, `[tool.mypy]`, `[tool.pytest]` sections | + +Extract: +- **Python Version:** (e.g., Python 3.11, 3.12) +- **Framework & Version:** (e.g., FastAPI 0.109, Django 5.0) +- **Database(s):** Type and purpose (e.g., PostgreSQL for primary, Redis for caching) +- **Key Libraries:** Only significant ones (e.g., Pydantic, Celery, httpx) + +### 1.2 Project Structure + +Map the directory layout and identify the organizational pattern: + +``` +project/ +├── pyproject.toml # Project configuration +├── uv.lock # Locked dependencies +├── .python-version # Python version +├── src/ +│ └── package_name/ # Source code (src layout) +│ ├── __init__.py +│ ├── main.py # Entry point +│ ├── api/ # API layer +│ ├── core/ # Business logic +│ ├── models/ # Data models +│ └── services/ # External integrations +├── tests/ # Test suite +├── scripts/ # Utility scripts +└── docs/ # Documentation +``` + +Identify the convention: +- **Flat Layout:** Package directly in root +- **Src Layout:** Package under `src/` directory +- **Layered:** Organized by technical layer (api/, services/, models/) +- **Domain-Driven:** Organized by domain (orders/, users/, products/) +- **Feature-Sliced:** Organized by feature (auth/, checkout/, dashboard/) + +### 1.3 Architectural Patterns + +- **Overall Style:** Monolith, Modular Monolith, Microservice, Serverless (AWS Lambda, etc.)? +- **API Style:** REST, GraphQL, gRPC, WebSocket? +- **Async Patterns:** asyncio, sync, mixed? +- **Data Access:** Repository pattern, Active Record, raw queries? +- **Dependency Injection:** Manual, dependency-injector, FastAPI Depends? + +**Request Flow Example:** +``` +HTTP Request → FastAPI Router → Depends (auth/validation) + → Service Layer → Repository → Database + → Response Model → HTTP Response +``` + +### 1.4 External Integrations + +| Integration Type | What to Look For | +|------------------|------------------| +| **HTTP Clients** | `httpx`, `requests`, `aiohttp` usage | +| **Databases** | SQLAlchemy engines, connection strings, migrations (Alembic) | +| **Message Queues** | Celery, RQ, Kafka, RabbitMQ clients | +| **Cloud SDKs** | boto3 (AWS), google-cloud-*, azure-* | +| **Caching** | Redis clients, in-memory caches | +| **Monitoring** | Sentry, OpenTelemetry, Prometheus | + +### 1.5 Infrastructure & Deployment + +- **Containerization:** `Dockerfile`, `docker-compose.yml` +- **CI/CD:** `.github/workflows/`, `.gitlab-ci.yml`, etc. +- **Environment Config:** `.env` files, `pydantic-settings` usage +- **Scripts:** `[project.scripts]` entry points in `pyproject.toml` + +### 1.6 uv-Specific Observations + +- **Workspace:** Is this a uv workspace with multiple packages? +- **Lock File:** `uv.lock` present and up to date? +- **Scripts:** Custom scripts defined in `pyproject.toml`? +- **Python Pin:** `.python-version` file present? +- **Virtual Environment:** `.venv/` managed by uv? + +--- + +## Step 2: Confidence Check + +Before documenting, categorize your findings by confidence level: + +| Category | Description | Action | +|----------|-------------|--------| +| **Verified** | Clearly confirmed by code, config, or infrastructure files. | Document directly. | +| **Needs Confirmation** | Pattern exists, but scope or intent is unclear. | Ask a clarifying question. | +| **Assumed** | Cannot determine from code; will use reasonable assumption. | State assumption; ask user to correct if wrong. | + +The purpose of this step is to ensure the TSD accurately reflects the system—not to audit or critique the architecture. + +--- + +## Step 3: Ask Clarifying Questions + +Ask questions to ensure documentation accuracy. Focus on **scope and intent**, not on identifying issues. + +### Question Categories + +| Category | Focus | +|----------|-------| +| **A. Scope** | "Should I document this component?" "Is this in scope for the baseline?" | +| **B. Intent** | "Is this pattern intentional?" "Is this the current standard?" | +| **C. Accuracy** | "I see X and Y coexisting. Which should I document as primary?" | + +### Formatting Requirements +- **Number all questions.** +- **Provide multiple-choice options** based on patterns found in code. +- **Reference specific files** to give context. + +### Example Format (Python/uv Context) + +```markdown +Based on my analysis, I need to confirm the following before documenting: + +### A. Scope + +1. **Deployment Targets:** I see both `Dockerfile` and AWS Lambda handlers (`lambda_handler.py`). For this baseline TSD: + A. Document container deployment only (primary target). + B. Document Lambda deployment only. + C. Document both with their respective purposes. + +2. **Database Migrations:** Alembic is configured in `alembic/`. Should the TSD: + A. Document migration patterns and commands. + B. Omit migrations (operational detail). + C. Document with a brief reference. + +### B. Intent + +3. **Dual Database:** I see both PostgreSQL (`database/pg.py`) and SQLite (`database/sqlite.py`). For documentation: + A. PostgreSQL is production—document only PostgreSQL. + B. Both are valid—document both with contexts. + C. SQLite is for testing only—document PostgreSQL as primary. + +4. **Async vs Sync:** The codebase uses both `async def` and regular `def` functions. Is this: + A. Intentional hybrid approach (document both patterns). + B. Migration in progress—async is the target (document async as standard). + C. Sync is legacy—document async as the current pattern. + +### C. Accuracy + +5. **Package Layout:** The project uses src layout (`src/mypackage/`). Is this the standard for this team? + A. Yes, src layout is the standard. + B. No, this is legacy—flat layout is preferred. + C. Document as-is without recommendation. + +6. **Dependency Management:** uv is used with `uv.lock`. Any other tools in use? + A. uv only—document uv commands. + B. uv + pip for some workflows. + C. Other: _______. +``` + +--- + +## Step 4: Generate TSD + +After receiving answers, generate the Technical Specification Document. + +### TSD Structure + +1. **Service Overview** + - Name, purpose (1-2 sentences), and relationship to other services. + +2. **Tech Stack** + - Python version, framework, database, and key libraries with versions. + - Package manager: uv (with relevant commands). + +3. **Project Structure** + - Directory tree with brief explanations of each top-level folder. + - Layout pattern (src layout, flat, etc.). + +4. **Architecture** + - Architectural style and key patterns. + - Simplified request flow (text or ASCII diagram). + +5. **External Dependencies** + - Table of integrations: Name, Type (API/Queue/DB), Purpose. + +6. **Configuration & Environment** + - Key environment variables and their purpose. + - Configuration management (pydantic-settings, etc.). + +7. **Development Workflow** + - uv commands for setup, running, testing. + - Example commands: + ```bash + uv sync # Install dependencies + uv run pytest # Run tests + uv run myapp # Run application + uv add # Add dependency + ``` + +8. **Constraints & Limitations** + - Known technical constraints (e.g., "Python 3.11+ required"). + - System boundaries and limitations. + +9. **Assumptions** + - Stated assumptions made during documentation. + +### Guidelines +- **Be Concise:** This is a reference document, not a tutorial. +- **Focus on "What":** Describe the current architecture, not recommendations. +- **Version Numbers Matter:** Include versions—they are critical context for brownfield systems. +- **State the Baseline:** This TSD documents *current* state, not ideal or future state. +- **Link to PRD:** Reference the companion PRD for functional context. + +--- + +## Output + +- **Format:** Markdown (`.md`) +- **Filename:** `TSD-[service-name].md` +- **Location:** Same directory as the companion PRD. + +--- + +## Final Instructions + +1. **DO NOT** generate the TSD until you have asked clarifying questions AND received answers. +2. **Start** by mapping the repo structure and identifying the tech stack. +3. **ALWAYS** present analysis summary (Step 1) and confidence check (Step 2) in your first response. +4. **ALWAYS** end your first response with clarifying questions (Step 3). +5. **AFTER** receiving answers, generate the complete TSD (Step 4). +6. If the user says "skip questions", proceed directly to Step 4, stating your assumptions. + +--- + +# End of reverse-arch.md (Python/uv) diff --git a/python/uv/reverse-spec.md b/python/uv/reverse-spec.md new file mode 100644 index 0000000..02c4028 --- /dev/null +++ b/python/uv/reverse-spec.md @@ -0,0 +1,180 @@ +# Rule: Reverse-Engineering a PRD from Existing Python/uv Code + +## Role +Act as a **Senior Technical Architect** specializing in Python ecosystems who can read code and translate implementation details into clear, user-centric product requirements. + +## Goal +To analyze an existing ("brownfield") Python codebase managed with **uv** and produce a **concise, product-focused** Product Requirements Document (PRD) through a **multi-turn conversation**. + +This PRD serves as a **baseline document** that captures the current state of the system. It is intended to be used alongside a Technical Specification Document (TSD) as context for planning future enhancements, bug fixes, or refactors—not for identifying problems to fix in the current implementation. + +> **Note:** For existing systems, technical constraints often dictate product behavior (e.g., "reports update daily" due to batch jobs). These constraints **should** be captured if they impact the user experience. + +## Process + +1. **Map & Analyze:** Explore the codebase structure. Extract a structured summary of *implemented* behavior. +2. **Confidence Check:** Categorize findings by documentation confidence. Identify what needs user confirmation before documenting. +3. **Ask Clarifying Questions:** Present targeted questions to ensure the documentation is accurate. **STOP and wait for answers.** +4. **Generate PRD:** After receiving user answers, produce the final PRD document. + +**Important:** This is a multi-turn workflow. Steps 1-3 happen in the first response. Step 4 happens only after the user responds. + +--- + +## Step 1: Analyze the Codebase + +Examine project artifacts with special attention to Python and uv-specific files. + +### Python/uv-Specific Files to Examine + +| File/Pattern | What to Look For | +|--------------|------------------| +| `pyproject.toml` | Project metadata, dependencies, scripts, entry points, tool configurations | +| `uv.lock` | Locked dependency versions, resolution details | +| `.python-version` | Python version constraint | +| `src/` or package directories | Main application code | +| `tests/` | Test files describing expected behavior | +| `scripts/` or CLI entry points | User-facing commands and utilities | +| `.env`, `.env.example` | Environment variables, feature flags | +| `Dockerfile`, `docker-compose.yml` | Containerization hints about deployment | +| `README.md`, `docs/` | Existing documentation | + +### What to Extract + +#### 1.1 Features & Capabilities +- What the system *actually* does today. +- CLI commands (check `[project.scripts]` in `pyproject.toml`). +- API endpoints (FastAPI, Flask, Django routes). +- Key workflows (start to finish). +- User roles (inferred from auth middleware or permissions logic). + +#### 1.2 Business Logic & Constraints +- Domain rules embedded in code (e.g., "Order total must be > $0"). +- **User-Facing Technical Constraints:** (e.g., "Data syncs every 24h" or "Max file upload is 10MB"). +- State transitions (e.g., Pending -> Approved -> Shipped). +- Validation rules in Pydantic models, dataclasses, or form validators. + +#### 1.3 Integration Points +- External APIs called (check `httpx`, `requests`, `aiohttp` usage). +- Database connections (SQLAlchemy, asyncpg, psycopg, etc.). +- Message queues (Celery, RQ, Kafka clients). +- Cloud services (AWS SDK, GCP clients, Azure SDK). + +#### 1.4 Observations +- Code comments indicating business context. +- Hardcoded values (magic numbers) that represent business rules. +- Feature flags (environment variables, configuration toggles). +- Optional dependencies in `pyproject.toml` that indicate feature sets. + +--- + +## Step 2: Confidence Check + +Before documenting, categorize your findings by confidence level: + +| Category | Description | Action | +|----------|-------------|--------| +| **Verified** | Clearly confirmed by code, tests, or config. | Document directly. | +| **Needs Confirmation** | Code exists, but intent or scope is unclear. | Ask a clarifying question. | +| **Assumed** | Cannot determine from code; will use reasonable assumption. | State assumption; ask user to correct if wrong. | + +The purpose of this step is to ensure the PRD accurately reflects the system—not to identify problems or gaps to fix. + +--- + +## Step 3: Ask Clarifying Questions + +Ask questions to ensure documentation accuracy. Focus on **scope and intent**, not on identifying issues. + +### Question Categories + +| Category | Focus | +|----------|-------| +| **A. Scope** | "Should I document feature X?" "Is this workflow in scope for the baseline?" | +| **B. Intent** | "Is this limit a business rule or a technical default?" "Is this the intended behavior?" | +| **C. Accuracy** | "The code does X. Is this correct, or should I document it differently?" | + +### Formatting Requirements +- **Number all questions.** +- **Provide multiple-choice options** based on patterns found in code. +- **Reference specific files** to give context. + +### Example Format (Python/uv Context) + +```markdown +Based on my analysis, I need to confirm the following before documenting: + +### A. Scope + +1. **CLI Commands:** I found three commands in `[project.scripts]`: `myapp`, `myapp-admin`, and `myapp-migrate`. For this baseline PRD: + A. Document all three commands. + B. Document only `myapp` (primary user-facing command). + C. Document `myapp` and `myapp-admin` (exclude migration tools). + +2. **Optional Dependencies:** The project has `[project.optional-dependencies]` for "dev", "test", and "ml". Should the PRD: + A. Document only the core functionality. + B. Document the ML features as part of the product. + C. Document all optional feature sets. + +### B. Intent + +3. **Rate Limiting:** In `api/middleware.py`, I found a rate limit of `100` requests per minute. For documentation: + A. This is a business rule (document as a system constraint). + B. This is a technical default (document as a limitation). + C. This should not be documented (internal implementation detail). + +4. **Async Processing:** Tasks are queued via Celery in `tasks/`. Is this: + A. Core product behavior (document the async nature). + B. Implementation detail (document only the user-facing result). + +### C. Accuracy + +5. **User Roles:** Based on `auth/permissions.py`, I identified roles: Admin, Editor, Viewer. Is this complete? + A. Complete—document these three. + B. Incomplete—there are additional roles: _______. +``` + +--- + +## Step 4: Generate PRD + +After receiving answers, generate the PRD. + +### PRD Structure + +1. **System Summary** — What the system is and its primary purpose. +2. **User Roles & Permissions** — Who uses the system and what they can do. +3. **Functional Requirements** — Grouped by feature area, numbered for reference. +4. **Business Rules** — Domain rules and validation logic. +5. **System Constraints** — Technical limitations that affect user experience. +6. **Edge Cases & Error Handling** — How the system handles boundaries and failures. +7. **Assumptions** — Stated assumptions made during documentation. + +### Guidelines +- **Be Explicit:** "Users cannot delete admins" is better than "Manage permissions." +- **Cite Sources:** (Optional) Reference files for key rules (e.g., "See `auth/permissions.py`"). +- **Describe Behavior, Not Code:** Good: "System validates email format." Bad: "`UserUtil.validate()` uses regex." +- **State the Baseline:** This PRD documents *current* behavior, not ideal or future state. + +--- + +## Output + +- **Format:** Markdown (`.md`) +- **Filename:** `PRD-[service-name].md` +- **Location:** Same directory as the companion TSD. + +--- + +## Final Instructions + +1. **DO NOT** generate the PRD until you have asked clarifying questions AND received answers. +2. **Start** by mapping the repo if it is large or unfamiliar. +3. **ALWAYS** present analysis summary (Step 1) and confidence check (Step 2) in your first response. +4. **ALWAYS** end your first response with clarifying questions (Step 3). +5. **AFTER** receiving answers, generate the complete PRD (Step 4). +6. If the user says "skip questions", proceed directly to Step 4, stating your assumptions. + +--- + +# End of reverse-spec.md (Python/uv) From 389f8fd37ac0254a1094b36e690803afe887425a Mon Sep 17 00:00:00 2001 From: dhaan-ish Date: Mon, 12 Jan 2026 20:36:49 +0530 Subject: [PATCH 2/2] feat: rev-spec for golang --- go/reverse-arch.md | 169 +++++++++++++++++++++++++++++++++++++++++++++ go/reverse-spec.md | 137 ++++++++++++++++++++++++++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 go/reverse-arch.md create mode 100644 go/reverse-spec.md diff --git a/go/reverse-arch.md b/go/reverse-arch.md new file mode 100644 index 0000000..2e3b08f --- /dev/null +++ b/go/reverse-arch.md @@ -0,0 +1,169 @@ +# Rule: Reverse-Engineering a Technical Spec from Existing Go Code + +## Role +Act as a **Senior Technical Architect** specializing in Go ecosystems who can extract architecture, patterns, and technical decisions into a clear document. + +## Goal +Analyze an existing Go codebase using **Go modules** and produce a **Technical Specification Document (TSD)** through a **multi-turn conversation**. + +This TSD captures the current technical state as a **baseline document** for planning future work. + +## Process + +1. **Map & Analyze:** Identify tech stack, patterns, and dependencies. +2. **Confidence Check:** Categorize findings by confidence level. +3. **Ask Clarifying Questions:** Present targeted questions. **STOP and wait.** +4. **Generate TSD:** After answers, produce the final TSD. + +--- + +## Step 1: Analyze the Codebase + +### 1.1 Tech Stack (Go Modules Focus) + +| What to Find | Where to Look | +|--------------|---------------| +| **Go Version** | `go.mod` (`go 1.21`) | +| **Module Path** | `go.mod` (`module github.com/org/repo`) | +| **Dependencies** | `go.mod` require blocks | +| **Framework** | Gin, Echo, Chi, Fiber, stdlib `net/http` | +| **Database** | GORM, sqlx, pgx, database/sql | + +### 1.2 Project Structure + +Standard Go project layout: +``` +project/ +├── go.mod # Module definition +├── go.sum # Dependency checksums +├── main.go # Entry point (simple projects) +├── cmd/ # CLI entry points +│ ├── server/ # Server binary +│ └── cli/ # CLI tool +├── internal/ # Private packages +│ ├── handler/ # HTTP/gRPC handlers +│ ├── service/ # Business logic +│ ├── repository/ # Data access +│ └── model/ # Domain models +├── pkg/ # Public reusable packages +├── api/ # API definitions (OpenAPI, Proto) +└── configs/ # Configuration files +``` + +Identify the pattern: +- **Flat:** Single package, simple projects +- **Standard Layout:** `cmd/`, `internal/`, `pkg/` +- **Domain-Driven:** Packages by domain (`order/`, `user/`) +- **Hexagonal:** `adapters/`, `ports/`, `domain/` + +### 1.3 Architectural Patterns + +- **Style:** Monolith, Microservice, Serverless (AWS Lambda)? +- **API:** REST, gRPC, GraphQL? +- **Concurrency:** Goroutines, channels, worker pools? +- **Data Access:** Repository pattern, direct queries? +- **DI:** Wire, fx, manual injection? + +### 1.4 External Integrations + +| Type | Look For | +|------|----------| +| **HTTP Clients** | `net/http`, `resty`, custom clients | +| **Databases** | GORM, sqlx, pgx, mongodb-driver | +| **Queues** | Kafka, NATS, RabbitMQ clients | +| **Cloud** | aws-sdk-go, google-cloud-go | +| **Observability** | OpenTelemetry, Prometheus, Zap/Zerolog | + +### 1.5 Go-Specific Observations + +- **Build Tags:** `//go:build` for conditional compilation +- **Generate Directives:** `//go:generate` for code generation +- **Interfaces:** Key interfaces defining contracts +- **Error Handling:** Custom error types, wrapping patterns +- **Testing:** Table-driven tests, mocks, test fixtures + +--- + +## Step 2: Confidence Check + +| Category | Description | Action | +|----------|-------------|--------| +| **Verified** | Confirmed by code/config | Document directly | +| **Needs Confirmation** | Scope/intent unclear | Ask question | +| **Assumed** | Cannot determine | State assumption | + +--- + +## Step 3: Ask Clarifying Questions + +### Example Format + +```markdown +### A. Scope + +1. **Binaries:** Found `cmd/server/` and `cmd/migrate/`. Document: + A. Both binaries + B. Server only (primary) + C. Server + migration as operational tool + +### B. Intent + +2. **gRPC + REST:** Both `api/grpc/` and `api/http/` exist: + A. Both are primary (document both) + B. gRPC is internal, REST is public + C. REST is legacy, gRPC is standard + +### C. Accuracy + +3. **Database Pattern:** Using repository pattern in `internal/repository/`: + A. Yes, repository is the standard + B. Mixed—some direct queries exist + C. Document as-is +``` + +--- + +## Step 4: Generate TSD + +### TSD Structure + +1. **Service Overview** — Name, purpose, relationships +2. **Tech Stack** — Go version, framework, DB, key libraries +3. **Project Structure** — Directory tree with explanations +4. **Architecture** — Style, patterns, request flow +5. **External Dependencies** — Table: Name, Type, Purpose +6. **Configuration** — Environment variables, config files +7. **Development Workflow** + ```bash + go mod download # Download dependencies + go build ./cmd/server # Build server binary + go test ./... # Run all tests + go run ./cmd/server # Run server + go generate ./... # Run code generators + ``` +8. **Constraints** — Go version requirements, CGO needs +9. **Assumptions** — Stated assumptions + +### Guidelines +- **Be Concise:** Reference document, not tutorial +- **Version Numbers Matter:** Critical for brownfield systems +- **State the Baseline:** Documents *current* state + +--- + +## Output + +- **Format:** Markdown +- **Filename:** `TSD-[service-name].md` + +--- + +## Final Instructions + +1. **DO NOT** generate TSD until questions are answered +2. **Start** with analysis summary and confidence check +3. **END first response** with clarifying questions +4. If user says "skip questions", proceed with stated assumptions + +--- +# End of reverse-arch.md (Go) diff --git a/go/reverse-spec.md b/go/reverse-spec.md new file mode 100644 index 0000000..af88c7c --- /dev/null +++ b/go/reverse-spec.md @@ -0,0 +1,137 @@ +# Rule: Reverse-Engineering a PRD from Existing Go Code + +## Role +Act as a **Senior Technical Architect** specializing in Go ecosystems who can read code and translate implementation details into clear, user-centric product requirements. + +## Goal +Analyze an existing Go codebase using **Go modules** and produce a **Product Requirements Document (PRD)** through a **multi-turn conversation**. + +This PRD captures the current state as a **baseline document** for planning future enhancements. + +## Process + +1. **Map & Analyze:** Explore the codebase. Extract implemented behavior. +2. **Confidence Check:** Categorize findings by confidence. Identify what needs confirmation. +3. **Ask Clarifying Questions:** Present targeted questions. **STOP and wait for answers.** +4. **Generate PRD:** After receiving answers, produce the final PRD. + +--- + +## Step 1: Analyze the Codebase + +### Go-Specific Files to Examine + +| File/Pattern | What to Look For | +|--------------|------------------| +| `go.mod` | Module path, Go version, dependencies | +| `go.sum` | Locked dependency versions | +| `cmd/` | CLI entry points and commands | +| `internal/` | Private application code | +| `pkg/` | Public reusable packages | +| `api/` | API definitions (OpenAPI, Proto files) | +| `configs/`, `.env` | Configuration and environment variables | +| `Dockerfile`, `Makefile` | Build and deployment hints | + +### What to Extract + +#### 1.1 Features & Capabilities +- What the system does today +- CLI commands (check `cmd/` subdirectories) +- API endpoints (HTTP handlers, gRPC services) +- Key workflows and user roles + +#### 1.2 Business Logic & Constraints +- Domain rules in code (validation, business logic) +- User-facing constraints (e.g., "Max upload 10MB") +- State transitions and validation rules + +#### 1.3 Integration Points +- External APIs (`net/http` clients, gRPC clients) +- Databases (database/sql, GORM, sqlx, pgx) +- Message queues (Kafka, NATS, RabbitMQ clients) + +#### 1.4 Observations +- Hardcoded values representing business rules +- Feature flags and build tags +- Interface definitions indicating capabilities + +--- + +## Step 2: Confidence Check + +| Category | Description | Action | +|----------|-------------|--------| +| **Verified** | Confirmed by code, tests, or config | Document directly | +| **Needs Confirmation** | Intent unclear | Ask a question | +| **Assumed** | Cannot determine from code | State assumption | + +--- + +## Step 3: Ask Clarifying Questions + +Format questions with: +- **Numbered questions** +- **Multiple-choice options** based on code patterns +- **File references** for context + +### Example Format + +```markdown +### A. Scope + +1. **CLI Commands:** Found `cmd/server/` and `cmd/cli/`. Document: + A. Both commands + B. Only server (primary) + C. Other: _______ + +### B. Intent + +2. **Rate Limit (100/min):** In `internal/middleware/ratelimit.go`: + A. Business rule (document as constraint) + B. Technical default (document as limitation) + C. Internal detail (do not document) + +### C. Accuracy + +3. **User Roles:** Found Admin, User, Guest in `internal/auth/`. Complete? + A. Yes, document these three + B. No, additional roles: _______ +``` + +--- + +## Step 4: Generate PRD + +### PRD Structure + +1. **System Summary** — Purpose and primary function +2. **User Roles & Permissions** — Who uses it and capabilities +3. **Functional Requirements** — Grouped by feature, numbered +4. **Business Rules** — Domain rules and validation +5. **System Constraints** — Technical limitations affecting UX +6. **Edge Cases & Error Handling** — Boundary behaviors +7. **Assumptions** — Stated assumptions + +### Guidelines +- **Be Explicit:** "Users cannot delete admins" > "Manage permissions" +- **Describe Behavior, Not Code:** "Validates email format" > "`Validate()` uses regex" +- **State the Baseline:** Documents *current* behavior + +--- + +## Output + +- **Format:** Markdown +- **Filename:** `PRD-[service-name].md` + +--- + +## Final Instructions + +1. **DO NOT** generate PRD until questions are answered +2. **Start** with analysis summary and confidence check +3. **End first response** with clarifying questions +4. If user says "skip questions", proceed with stated assumptions + +--- +# End of reverse-spec.md (Go)