diff --git a/.github/DEMOFLOW3.md b/.github/DEMOFLOW3.md new file mode 100644 index 0000000..4ad0b58 --- /dev/null +++ b/.github/DEMOFLOW3.md @@ -0,0 +1,171 @@ +# Demo - Agentic Coding Workflow + +**Pre-requisites:** +- [ ] Fork and clone the repo +- [ ] Copy this file to an ignored location like `.vscode/DEMOFLOW3.md` and open it there +- [ ] Create a GitHub issue in your forked repo with title: "Refactor superhero comparison feature to use a Backend API instead of Frontend logic", and make sure it's issue #21 - if not, update the prompts below accordingly +- [ ] No local changes, clean working tree +- [ ] Make sure Agent Skills are enabled (with the chat.useAgentSkills setting) +- [ ] Verify GitHub MCP and Playwright MCP are properly configured in mcp.json before starting: [.vscode/mcp.json](../.vscode/mcp.json) +- [ ] npx playwright install in frontend folder +- [ ] Start backend and frontend dev servers. + +## What We'll Cover +We will implement a feature from idea to production using an agentic coding workflow with GitHub Copilot. +The feature is to refactor the superhero comparison logic to use a backend API instead of frontend logic. +Let's see the feature as it's currently implemented. + +
+ +```mermaid +graph TD + A[01 GitHub MCP - Get Issue] --> B[02 Plan with Subagent] + B --> D1["03a Backend Impl
API Endpoint"] + B --> D2["03b Frontend Refactor
Consume API"] + + D1 --> E[04 Monitor in AgentHQ] + D2 --> E + + E --> F[05 Validate E2E Tests] + F --> G[06 Review - Security Skill] + G --> H[07 Local Code Review] + H --> I[08 Add Documentation] + I --> QA[09 QA - Test Feature] + QA --> J[10 Create PR via MCP] + J --> K[11 CI/CD Code Review] + + style D1 fill:#b39ddb,stroke:#333 + style D2 fill:#b39ddb,stroke:#333 + style E fill:#b39ddb,stroke:#333 + style I fill:#b39ddb,stroke:#333 + style QA fill:#b39ddb,stroke:#333 + style K fill:#b39ddb,stroke:#333 +``` + +
+ +- [ ] **01 GitHub MCP**: List issues in GitHub using MCP +Issue name: Refactor superhero comparison feature to use a Backend API instead of Frontend logic +- [ ] **02 Create a Plan**: Create a step by step plan (with separate instructions for FE and BE) to implement the feature using Copilot subagent to do research before drafting the plan. +Save the plan to use in later steps. +Note: this allows for better, more concise context and plan quality. + + **Sample Prompt (use Plan mode):** + ``` + Using subagents for research, analyze GitHub issue #21 "Refactor superhero comparison feature to use a Backend API instead of Frontend logic". + + Create a detailed implementation plan that should include: + Phase 1. Backend: New /api/superheroes/compare endpoint + Validate Backend tests pass + Phase 2. Frontend: Refactor to consume the new API, keep UI unchanged + Validate Frontend tests pass + Add e2e tests to verify functionality + ``` + + 📄 **Backup Plan Document**: [prompts/15-refactor-be-fe-feature-plan.md](prompts/15-refactor-be-fe-feature-plan.md) + + +- [ ] **03 Implement Feature using Background Agents FE/BE**: Implement the feature using Background Agents (FE + BE in parallel) + +**Backend Prompt (GPT-5.2-Codex - click "Send to Background"):** +📄 Note: Use the plan created in step 2 as context: +1. Switch to Agent + GPT-5.2-Codex +2. Enter Prompt: +``` +Implement ONLY Phase 1 of the plan: +Add superhero comparison API endpoint: + +Create a GET endpoint at: +/api/superheroes/compare?id1=&id2= +in backend/src/server.ts +``` +3. Run in the background. + +**Frontend Prompt (GPT-4.1 - click "Send to Background"):**. +📄 Note: Use the plan created in step 2 as context. +1. Switch to Agent + GPT-4.1 +2. Add App.js to context (if not already) +3. Enter Prompt: +``` +Implement ONLY Phase 2 of the plan: +Refactor frontend to call new /api/superheroes/compare endpoint +instead of current logic +Keep UI unchanged. +``` +4. Run in the background. + +- [ ] **04 Track in AgentHQ**: Look at the AGENT SESSIONS tab and track progress of the background agents +- [ ] **05 Validate Tests**: Run tests and verify all implementations work correctly. +- [ ] **06 API Security Review Skill**: Trigger the `api-security-review` skill to review the new comparison API (no need to fix) +Skill location: `.github/skills/api-security-review/SKILL.md` + +**Prompt:** +``` +Using the `api-security-review` skill, +Perform a security review of the new /api/superheroes/compare endpoint +in backend/src/server.ts +``` + +NOTE: To verify skill is activated, you should see in Copilot output: +``` +1. Searched for files matching **/skills/**, 1 match +2. Read SKILL.md file +``` + +- [ ] **07 Local Code Review**: +Use Copilot in VS Code to perform a local code review (no need to fix) +- [ ] **08 Add Documentation**: +Add documentation for the new comparison API + +**Background Agent (CLI)** +Click "Send to Background" button with this prompt: +``` +Add JSDoc documentation for the superhero comparison API: +1. backend/src/server.ts - Document the /api/superheroes/compare endpoint +2. Update backend README with API usage examples +3. Add inline comments explaining comparison logic +``` + + +2. **Demo points:** + 1. Show the worktree/session created + 2. Show the files modified + 3. Review the generated documentation +- [ ] **09 QA - Test Feature**: Use Playwright MCP to test the feature is working as described in issue. + +**Prompt (Playwright-Tester mode):** +``` +Use Playwright MCP to test the feature is working as described in issue #21 in GitHub. +``` + +- [ ] **10 Create PR with MCP**: +Use GitHub MCP to create a Pull Request for the changes made in the feature implementation. +**Prompt:** +``` +Create a PR for issue #21 +Use the following details (add title and description): +- Linked Issue: #21 +- Reviewers: @ofirn +- Assignees: @yoelcommit +``` +- [ ] **11 Automated Code Review in GH CI**: Use Copilot to perform an automated code review in GitHub CI + + +--- + +**Key Tips & Best Practices:** +- [ ] Context: Start a NEW session for every new task/topic! +- [ ] Customize: via instructions, prompts, agents, skills +- [ ] Skills: Build and use custom skills to extend Copilot capabilities +- [ ] Agent: Use (or build) MCPs where it makes sense +- [ ] Agent: Never "Accept" until happy with result +- [ ] Agent: Restore Checkpoint +- [ ] Agent: TDD (Test Driven Dev) as Agent stop condition and feedback loop +- [ ] Agent: should run CLI commands to close feedback loop +- [ ] Coding Agent: delegate to a background agent in the cloud +- [ ] Coding Agent: Break large tasks into smaller sub-tasks +- [ ] Plan: Use subagents for research +- [ ] Review: Use AI for reviewing code, not just generating it +- [ ] CLI: For a terminal-native experience & cross-project workspaces +- [ ] Monitor: Use AgentHQ to monitor and manage background agents +- [ ] Models: Choosing the right models: https://docs.github.com/en/copilot/reference/ai-models/model-comparison \ No newline at end of file diff --git a/.github/prompts/10-BE-refactor-add-compare-api.md b/.github/prompts/10-BE-refactor-add-compare-api.md deleted file mode 100644 index 334eac5..0000000 --- a/.github/prompts/10-BE-refactor-add-compare-api.md +++ /dev/null @@ -1,83 +0,0 @@ -# Refactor: Step 1 - Add BE Compare API Endpoint - -# New Chat: GPT-5 - -Original "lazier" spec prompt -``` -Add a new comparison API in the backend under src/server.ts, under path "/api/superheroes/compare?id1=x&id2=y". -It should get two superhero IDs as request arguments (id1, id2) and return who's stronger in each of the 6 categories (ordered "intelligence", "strength", "speed", "durability", "power", "combat") and a final decision on which super hero wins the overall comparison, in JSON format. -Allow for a tie if each wins 3 categories out of 6. -Unit tests should be generated for the new API under "/tests/server.test.ts", and pass along with all existing tests. -``` - -More robust spec prompt (optimized for GPT-5): -``` -# Role and Objective -Implement a new comparison API endpoint in the backend that compares two superheroes based on specific attributes across standardized categories. - -Begin with a concise checklist (3-7 bullets) of what you will do; keep items conceptual, not implementation-level. - -# Instructions -- Create a new GET endpoint at `superheroes/compare?id1=&id2=` in `src/server.ts`. -- The endpoint must accept two request query parameters: `id1` and `id2`, corresponding to superhero IDs. -- For each of the following categories, compare the corresponding attributes between the two superheroes: "intelligence", "strength", "speed", "durability", "power", "combat". - - For each category, record which superhero has the higher value, or "tie" if they are equal. -- Compose and return a JSON response structured with: - - The IDs compared (`id1`, `id2`). - - A `categories` array (ordered: "intelligence", "strength", "speed", "durability", "power", "combat"), each containing: - - `name`: category name - - `winner`: 1, 2, or "tie" (depending on which superhero is superior in the category) - - `id1_value`: Value for id1. - - `id2_value`: Value for id2. - - An `overall_winner`: 1, 2, or "tie" (whichever wins more categories, or "tie" if each has 3 wins). -- If either superhero ID is missing or invalid, respond with a JSON error matching the provided format and include `status: "invalid_request"`. - -# Context -- API location: `src/server.ts` -- Related test file: `/tests/server.test.ts` - -# Reasoning and Validation -- Set reasoning_effort=medium for balanced coverage and efficiency. -- After each major step (input validation, data fetch, comparison, response), briefly validate completion or correctness before proceeding to the next step. If validation fails, self-correct. - -# Output Format -Successful response: -```json -{ - "id1": , - "id2": , - "categories": [ - { - "name": "strength", - "winner": 1 | 2 | "tie", - "id1_value": , - "id2_value": - }, - // ... one object for each category in the specified order - ], - "overall_winner": 1 | 2 | "tie" -} -``` -Error response (e.g., missing or invalid IDs): -```json -{ - "error": , - "status": "invalid_request" -} -``` - -# Testing -- Add or update tests in `/tests/server.test.ts` for all success and error cases for the new comparison endpoint. Ensure all existing tests continue to pass. -- If editing code: (1) state assumptions, (2) create/run minimal tests where possible, (3) produce ready-to-review diffs, (4) follow repo style. - -# Stop Conditions -- Endpoint fully implemented, tested, documented, and covered by unit tests. - -``` - ---- -Let's run a quick check ourselves in our Simple Browser: -Cmd + Shift + P: Simple Browser -``` -http://localhost:3000/api/superheroes/compare?id1=1&id2=2 -``` \ No newline at end of file diff --git a/.github/prompts/10-FE-refactor-compare-via-api.md b/.github/prompts/10-FE-refactor-compare-via-api.md deleted file mode 100644 index e272852..0000000 --- a/.github/prompts/10-FE-refactor-compare-via-api.md +++ /dev/null @@ -1,45 +0,0 @@ -# Frontend Refactor: Compare Superheroes via API - -# New Chat: Sonnet 4 - -Refactor superheros comparison logic in the frontend, to use a dedicated API endpoint for comparison instead of JavaScript logic. -Keep the UI as it is and don't change anything in the view. - -Make changes only in /frontend folder, don't touch /backend - -The backend API is at: -``` -/api/superheroes/compare?id1=1&id2=2 -``` -where id1 and id2 are superhero ids. - -It returns the comparison result in the following format: -```json -{ - "id1": , - "id2": , - "categories": [ - { - "name": "strength", - "winner": 1 | 2 | "tie", - "id1_value": , - "id2_value": - }, - // ... one object for each category in the specified order - ], - "overall_winner": 1 | 2 | "tie" -} -``` - -Clean up all redundant code, dependencies and comments following the refactor! - -Stop condition: -Run all e2e Playwrite tests to ensure the comparison feature works as expected using this command: -npx playwright test --reporter=line - ---- -Let's run a quick check ourselves in our Simple Browser: -Cmd + Shift + P: Simple Browser -``` -http://localhost:3001 -``` \ No newline at end of file diff --git a/.github/prompts/15-refactor-be-fe-feature-plan.md b/.github/prompts/15-refactor-be-fe-feature-plan.md new file mode 100644 index 0000000..dee439f --- /dev/null +++ b/.github/prompts/15-refactor-be-fe-feature-plan.md @@ -0,0 +1,35 @@ +# Plan: Refactor Superhero Comparison to Backend API +Move the winner calculation logic from App.js to a new /api/superheroes/compare endpoint in server.ts, keeping the existing UI unchanged while all tests continue passing. + +## Phase 1: Backend — Add Compare Endpoint +Add GET /api/superheroes/compare endpoint in server.ts, Extract id1 and id2 from query params, validate both are provided and numeric (return 400 if invalid), fetch both heroes (return 404 if not found), calculate per-category winners and overall winner, return JSON response per spec. + +Add backend tests in server.test.ts: Test success case (valid comparison), 400 for missing/invalid params, 404 for non-existent heroes, and tie scenario. + +Validate backend tests pass: Run npm test in backend to ensure all existing and new tests pass. + +## Phase 2: Frontend — Consume New API +Add new state variables in App.js:10: Add comparisonResult, isComparing, and comparisonError state hooks. + +Refactor compareHeroes function at App.js:36-40: Replace local logic with fetch('/api/superheroes/compare?id1=X&id2=Y'), handle loading/error states. + +Update ComparisonView component at App.js:69-133: Map comparisonResult.categories to render stat comparisons, use comparisonResult.overall_winner for winner display, add loading spinner and error message UI. + +Remove calculateWinner function at App.js:46-66: Delete this function once API integration is complete. + +The frontend needs to be updated to handle numeric hero IDs from the API response. +See lines 76-86 in App.js:76-86. The getScoreFromCategories function is checking for category.winner as a string value like 'hero1' or 'hero2', but the API will be returning numeric IDs (1, 2, 3, etc.) for the winner field. + +Validate frontend tests pass: Run npx playwright test in frontend to ensure hero-comparison.spec.ts and winner-calculation.spec.ts still pass. + +## Phase 3: E2E Tests — API Integration +Create frontend/tests/comparison-api.spec.ts: Add E2E tests that verify the compare API is called when comparing heroes, mock API responses to test error handling, and validate the full flow from selection to comparison result. +Add tests that check the correct score calculation. A-Bomb vs Bane should yield Bane as the overall winner Score: 2-4. Ant-Man vs A-Bomb should yield a tie Score: 3-3. + +Run full E2E suite: Execute all Playwright tests to confirm no regressions across hero-table.spec.ts, hero-selection.spec.ts, and API integration tests. + +## Questions / Considerations + +Loading State: Display a spinner/skeleton while awaiting API response, or disable the compare button? Recommend spinner overlay on comparison view. + +API Base URL Configuration: Hardcode /api/superheroes/compare or use an environment variable for flexibility? Recommend env var REACT_APP_API_URL for production deployability. \ No newline at end of file diff --git a/.github/skills/api-security-review/SKILL.md b/.github/skills/api-security-review/SKILL.md new file mode 100644 index 0000000..19340a7 --- /dev/null +++ b/.github/skills/api-security-review/SKILL.md @@ -0,0 +1,33 @@ +--- +name: api-security-review +description: Security review skill for REST APIs - checks authentication, authorization, input validation, rate limiting, and logging. Triggered automatically for security-sensitive code changes. +--- +# Security Review + +## Overview + +Dedicated security review for code handling authentication, authorization, user input, APIs, databases, or credentials. + +# Role and Objective +- Conduct a comprehensive security review of the REST API to identify and mitigate risks. + +# Process Checklist +- Begin with a concise checklist (3-7 bullets) of the main security areas to review before proceeding. + +# Instructions +- Verify that all API endpoints are secured with proper authentication and authorization mechanisms. +- Ensure user inputs are validated and sanitized to prevent injection attacks and other vulnerabilities. +- Confirm implementation of rate limiting and throttling to protect against abuse. +- Check for robust logging and monitoring of security-related events. + +# Validation Step +- After reviewing each security area, briefly validate whether the controls are sufficient and note any necessary self-corrections or next steps. + +# Output Format +- Provide actionable recommendations and a summary of findings for each area reviewed, ensuring outputs are clear and structured. + +# Verbosity +- Use clear, concise explanations for identified risks and remediation steps. + +# Stop Conditions +- Review concludes when all checklist items are addressed and recommendations are documented. If any item cannot be fully validated, clearly state the limitation and suggest next steps. diff --git a/.gitignore b/.gitignore index fc73ee4..a9b34fd 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,6 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -test-results/ \ No newline at end of file +test-results/ +.vscode/ +.vscode/mcp.json