@ersinkoc
{ "task": "comprehensive_repository_analysis", "objective": "Conduct exhaustive analysis of entire codebase to identify, prioritize, fix, and document ALL verifiable bugs, security vulnerabilities, and critical issues across any technology stack", "analysis_phases": [ { "phase": 1, "name": "Repository Discovery & Mapping", "steps": [ { "step": "1.1", "title": "Architecture & Structure Analysis", "actions": [ "Map complete directory structure (src/, lib/, tests/, docs/, config/, scripts/, build/, deploy/)", "Identify all technology stacks and frameworks in use", "Parse dependency manifests (package.json, requirements.txt, go.mod, pom.xml, Gemfile, Cargo.toml, composer.json)", "Document entry points, main execution paths, and module boundaries", "Analyze build systems (Webpack, Gradle, Maven, Make, CMake)", "Review CI/CD configurations (GitHub Actions, GitLab CI, Jenkins, CircleCI)", "Examine existing documentation (README, CONTRIBUTING, API specs, architecture diagrams)" ] }, { "step": "1.2", "title": "Development Environment Inventory", "actions": [ "Identify testing frameworks (Jest, Mocha, pytest, PHPUnit, Go test, JUnit, RSpec, xUnit)", "Review linter/formatter configs (ESLint, Prettier, Black, Flake8, RuboCop, golangci-lint, Checkstyle)", "Scan for inline issue markers (TODO, FIXME, HACK, XXX, BUG, NOTE)", "Analyze git history for problematic patterns and recent hotfixes", "Extract existing test coverage reports and metrics", "Identify code analysis tools already in use (SonarQube, CodeClimate, etc.)" ] } ] }, { "phase": 2, "name": "Systematic Bug Discovery", "bug_categories": [ { "category": "CRITICAL", "severity": "P0", "types": [ "SQL Injection vulnerabilities", "Cross-Site Scripting (XSS) flaws", "Cross-Site Request Forgery (CSRF) vulnerabilities", "Authentication/Authorization bypass", "Remote Code Execution (RCE) risks", "Data corruption or permanent data loss", "System crashes, deadlocks, or infinite loops", "Memory leaks and resource exhaustion", "Insecure cryptographic implementations", "Hardcoded secrets or credentials" ] }, { "category": "FUNCTIONAL", "severity": "P1-P2", "types": [ "Logic errors (incorrect conditionals, wrong calculations, off-by-one errors)", "State management issues (race conditions, stale state, improper mutations)", "Incorrect API contracts or request/response mappings", "Missing or insufficient input validation", "Broken business logic or workflow violations", "Incorrect data transformations or serialization", "Type mismatches or unsafe type coercions", "Incorrect exception handling or error propagation" ] }, { "category": "INTEGRATION", "severity": "P2", "types": [ "Incorrect external API usage or outdated endpoints", "Database query errors, SQL syntax issues, or N+1 problems", "Message queue handling failures (RabbitMQ, Kafka, SQS)", "File system operation errors (permissions, path traversal)", "Network communication issues (timeouts, retries, connection pooling)", "Cache inconsistency or invalidation problems", "Third-party library misuse or version incompatibilities" ] }, { "category": "EDGE_CASES", "severity": "P2-P3", "types": [ "Null/undefined/nil/None pointer dereferences", "Empty array/list/collection handling", "Zero or negative value edge cases", "Boundary conditions (max/min integers, string length limits)", "Missing error handling or swallowed exceptions", "Timeout and retry logic failures", "Concurrent access issues without proper locking", "Overflow/underflow in numeric operations" ] }, { "category": "CODE_QUALITY", "severity": "P3-P4", "types": [ "Deprecated API usage", "Dead code or unreachable code paths", "Circular dependencies", "Performance bottlenecks (inefficient algorithms, redundant operations)", "Missing or incorrect type annotations", "Inconsistent error handling patterns", "Resource leaks (file handles, database connections, network sockets)", "Improper logging (sensitive data exposure, insufficient context)" ] } ], "discovery_methods": [ "Static code analysis using language-specific tools", "Pattern matching for common anti-patterns and code smells", "Dependency vulnerability scanning (npm audit, pip-audit, bundle-audit, cargo audit)", "Control flow and data flow analysis", "Dead code detection", "Configuration validation against best practices", "Documentation-to-implementation cross-verification", "Security-focused code review" ] }, { "phase": 3, "name": "Bug Documentation & Prioritization", "bug_report_schema": { "bug_id": "Sequential identifier (BUG-001, BUG-002, etc.)", "severity": { "type": "enum", "values": [ "CRITICAL", "HIGH", "MEDIUM", "LOW" ], "description": "Bug severity level" }, "category": { "type": "enum", "values": [ "SECURITY", "FUNCTIONAL", "PERFORMANCE", "INTEGRATION", "CODE_QUALITY" ], "description": "Bug classification" }, "location": { "files": [ "Array of affected file paths with line numbers" ], "component": "Module/Service/Feature name", "function": "Specific function or method name" }, "description": { "current_behavior": "What's broken or wrong", "expected_behavior": "What should happen instead", "root_cause": "Technical explanation of why it's broken" }, "impact_assessment": { "user_impact": "Effect on end users (data loss, security exposure, UX degradation)", "system_impact": "Effect on system (performance, stability, scalability)", "business_impact": "Effect on business (compliance, revenue, reputation, legal)" }, "reproduction": { "steps": [ "Step-by-step instructions to reproduce" ], "test_data": "Sample data or conditions needed", "actual_result": "What happens when reproduced", "expected_result": "What should happen" }, "verification": { "code_snippet": "Demonstrative code showing the bug", "test_case": "Test that would fail due to this bug", "logs_or_metrics": "Evidence from logs or monitoring" }, "dependencies": { "related_bugs": [ "Array of related BUG-IDs" ], "blocking_issues": [ "Array of bugs that must be fixed first" ], "blocked_by": [ "External factors preventing fix" ] }, "metadata": { "discovered_date": "ISO 8601 timestamp", "discovered_by": "Tool or method used", "cve_id": "If applicable, CVE identifier", "cwe_id": "If applicable, CWE identifier" } }, "prioritization_matrix": { "criteria": [ { "factor": "severity", "weight": 0.4, "scale": "CRITICAL=100, HIGH=70, MEDIUM=40, LOW=10" }, { "factor": "user_impact", "weight": 0.3, "scale": "All users=100, Many=70, Some=40, Few=10" }, { "factor": "fix_complexity", "weight": 0.15, "scale": "Simple=100, Medium=60, Complex=20" }, { "factor": "regression_risk", "weight": 0.15, "scale": "Low=100, Medium=60, High=20" } ], "formula": "priority_score = Σ(factor_value × weight)" } }, { "phase": 4, "name": "Fix Implementation", "fix_workflow": [ { "step": 1, "action": "Create isolated fix branch", "naming": "fix/BUG-{id}-{short-description}" }, { "step": 2, "action": "Write failing test FIRST", "rationale": "Test-Driven Development ensures fix is verifiable" }, { "step": 3, "action": "Implement minimal, focused fix", "principle": "Smallest change that correctly resolves the issue" }, { "step": 4, "action": "Verify test now passes", "validation": "Run specific test and related test suite" }, { "step": 5, "action": "Run full regression test suite", "validation": "Ensure no existing functionality breaks" }, { "step": 6, "action": "Update documentation", "scope": "API docs, inline comments, changelog" } ], "fix_principles": [ "MINIMAL_CHANGE: Make the smallest change that correctly fixes the issue", "NO_SCOPE_CREEP: Avoid unrelated refactoring or feature additions", "BACKWARDS_COMPATIBLE: Preserve existing API contracts unless bug itself is breaking", "FOLLOW_CONVENTIONS: Adhere to project's existing code style and patterns", "DEFENSIVE_PROGRAMMING: Add guards to prevent similar bugs in the future", "EXPLICIT_OVER_IMPLICIT: Make intent clear through code structure and comments", "FAIL_FAST: Validate inputs early and fail with clear error messages" ], "code_review_checklist": [ "Fix addresses root cause, not just symptoms", "All edge cases are properly handled", "Error messages are clear, actionable, and don't expose sensitive info", "Performance impact is acceptable (no O(n²) where O(n) suffices)", "Security implications thoroughly considered", "No new compiler warnings or linting errors", "Changes are covered by tests", "Documentation is updated and accurate", "Breaking changes are clearly marked and justified", "Dependencies are up-to-date and secure" ] }, { "phase": 5, "name": "Testing & Validation", "test_requirements": { "mandatory_tests_per_fix": [ { "type": "unit_test", "description": "Isolated test for the specific bug fix", "coverage": "Must cover the exact code path that was broken" }, { "type": "integration_test", "description": "Test if bug involves multiple components", "coverage": "End-to-end flow through affected systems" }, { "type": "regression_test", "description": "Ensure fix doesn't break existing functionality", "coverage": "All related features and code paths" }, { "type": "edge_case_tests", "description": "Cover boundary conditions and corner cases", "coverage": "Null values, empty inputs, limits, error conditions" } ] }, "test_structure_template": { "description": "Language-agnostic test structure", "template": [ "describe('BUG-{ID}: {description}', () => {", " test('reproduces original bug', () => {", " // This test demonstrates the bug existed", " // Should fail before fix, pass after", " });", "", " test('verifies fix resolves issue', () => {", " // This test proves correct behavior after fix", " });", "", " test('handles edge case: {case}', () => {", " // Additional coverage for related scenarios", " });", "});" ] }, "validation_steps": [ { "step": "Run full test suite", "commands": { "javascript": "npm test", "python": "pytest", "go": "go test ./...", "java": "mvn test", "ruby": "bundle exec rspec", "rust": "cargo test", "php": "phpunit" } }, { "step": "Measure code coverage", "tools": [ "Istanbul/NYC", "Coverage.py", "JaCoCo", "SimpleCov", "Tarpaulin" ] }, { "step": "Run static analysis", "tools": [ "ESLint", "Pylint", "golangci-lint", "SpotBugs", "Clippy" ] }, { "step": "Performance benchmarking", "condition": "If fix affects hot paths or critical operations" }, { "step": "Security scanning", "tools": [ "Snyk", "OWASP Dependency-Check", "Trivy", "Bandit" ] } ] }, { "phase": 6, "name": "Documentation & Reporting", "fix_documentation_requirements": [ "Update inline code comments explaining the fix and why it was necessary", "Revise API documentation if behavior changed", "Update CHANGELOG.md with bug fix entry", "Create or update troubleshooting guides", "Document any workarounds for deferred/unfixed issues", "Add migration notes if fix requires user action" ], "executive_summary_template": { "title": "Bug Fix Report - {repository_name}", "metadata": { "date": "ISO 8601 date", "analyzer": "Tool/Person name", "repository": "Full repository path", "commit_hash": "Git commit SHA", "duration": "Analysis duration in hours" }, "overview": { "total_bugs_found": "integer", "total_bugs_fixed": "integer", "bugs_deferred": "integer", "test_coverage_before": "percentage", "test_coverage_after": "percentage", "files_analyzed": "integer", "lines_of_code": "integer" }, "critical_findings": [ "Top 3-5 most critical bugs found and their fixes" ], "fix_summary_by_category": { "security": "count", "functional": "count", "performance": "count", "integration": "count", "code_quality": "count" }, "detailed_fix_table": { "columns": [ "BUG-ID", "File", "Line", "Category", "Severity", "Description", "Status", "Test Added" ], "format": "Markdown table or CSV" }, "risk_assessment": { "remaining_high_priority": [ "List of unfixed critical issues" ], "recommended_next_steps": [ "Prioritized action items" ], "technical_debt": [ "Summary of identified tech debt" ], "breaking_changes": [ "Any backwards-incompatible fixes" ] }, "testing_results": { "test_command": "Exact command used to run tests", "tests_passed": "X out of Y", "tests_failed": "count with reasons", "tests_added": "count", "coverage_delta": "+X% or -X%" } }, "deliverables_checklist": [ "All bugs documented in standardized format", "Fixes implemented with minimal scope", "Test suite updated and passing", "Documentation updated (code, API, user guides)", "Code review completed and approved", "Performance impact assessed and acceptable", "Security review conducted for security-related fixes", "Deployment notes and rollback plan prepared", "Changelog updated with user-facing changes", "Stakeholders notified of critical fixes" ] }, { "phase": 7, "name": "Continuous Improvement", "pattern_analysis": { "objectives": [ "Identify recurring bug patterns across codebase", "Detect architectural issues enabling bugs", "Find gaps in testing strategy", "Highlight areas with technical debt" ], "outputs": [ "Common bug pattern report", "Preventive measure recommendations", "Tooling improvement suggestions", "Architectural refactoring proposals" ] }, "monitoring_recommendations": { "metrics_to_track": [ "Bug discovery rate over time", "Time to resolution by severity", "Regression rate (bugs reintroduced)", "Test coverage percentage", "Code churn in bug-prone areas", "Dependency vulnerability count" ], "alerting_rules": [ "Critical security vulnerabilities in dependencies", "Test suite failures", "Code coverage drops below threshold", "Performance degradation in key operations" ], "logging_improvements": [ "Add structured logging where missing", "Include correlation IDs for request tracing", "Log security-relevant events", "Ensure error logs include stack traces and context" ] } } ], "constraints_and_best_practices": [ "NEVER compromise security for simplicity or convenience", "MAINTAIN complete audit trail of all changes", "FOLLOW semantic versioning if fixes change public API", "RESPECT rate limits when testing external services", "USE feature flags for high-risk or gradual rollout fixes", "DOCUMENT all assumptions made during analysis", "CONSIDER rollback strategy for every fix", "PREFER backwards-compatible fixes when possible", "AVOID introducing new dependencies without justification", "TEST in multiple environments when applicable" ], "output_formats": [ { "format": "markdown", "purpose": "Human-readable documentation and reports", "filename_pattern": "bug_report_{date}.md" }, { "format": "json", "purpose": "Machine-readable for automated processing", "filename_pattern": "bug_data_{date}.json", "schema": "Follow bug_report_schema defined in Phase 3" }, { "format": "csv", "purpose": "Import into bug tracking systems (Jira, GitHub Issues)", "filename_pattern": "bugs_{date}.csv", "columns": [ "BUG-ID", "Severity", "Category", "File", "Line", "Description", "Status" ] }, { "format": "yaml", "purpose": "Configuration-friendly format for CI/CD integration", "filename_pattern": "bug_config_{date}.yaml" } ], "special_considerations": { "monorepos": "Analyze each package/workspace separately with cross-package dependency tracking", "microservices": "Consider inter-service contracts, API compatibility, and distributed tracing", "legacy_code": "Balance fix risk vs benefit; prioritize high-impact, low-risk fixes", "third_party_dependencies": "Report vulnerabilities upstream; consider alternatives if unmaintained", "high_traffic_systems": "Consider deployment strategies (blue-green, canary) for fixes", "regulated_industries": "Ensure compliance requirements met (HIPAA, PCI-DSS, SOC2, GDPR)", "open_source_projects": "Follow contribution guidelines; engage with maintainers before large changes" }, "success_criteria": { "quantitative": [ "All CRITICAL and HIGH severity bugs addressed", "Test coverage increased by at least X%", "Zero security vulnerabilities in dependencies", "All tests passing", "Code quality metrics improved (cyclomatic complexity, maintainability index)" ], "qualitative": [ "Codebase is more maintainable", "Documentation is clear and comprehensive", "Team can confidently deploy fixes", "Future bug prevention mechanisms in place", "Development velocity improved" ] }}
{ "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Transform Subject 1 (male) and Subject 2 (male) into adrenaline-junkie urban explorers atop a massive skyscraper. The image is a high-energy, wide-angle POV selfie taken by Subject 1, capturing both men precariously perched on the edge of a rooftop ledge with a dizzying vertical drop to the city streets below. Adhere strictly to a cinematic 1:1 aspect ratio.", "details": { "year": "Present Day", "genre": "GoPro", "location": "The rooftop ledge of a 100-story skyscraper in a dense metropolis.", "lighting": [ "Golden hour sunlight", "Direct harsh flares", "Natural outdoor exposure" ], "camera_angle": "Extreme wide-angle fisheye POV (selfie angle), high distortion on the edges, tilting downwards to show the street far below.", "emotion": [ "Exhilarated", "Fearless", "Adrenaline-fueled" ], "color_palette": [ "Sky blue", "Sunset orange", "Concrete grey", "Vivid sportswear neons" ], "atmosphere": [ "Vertigo-inducing", "Windy", "Epic", "Dangerous" ], "environmental_elements": "Tiny cars visible on the grid-like streets below, lens flare artifacts, birds flying beneath the subjects, wind blowing their clothes.", "subject1": { "costume": "A technical windbreaker jacket, fingerless grip gloves, and a backward baseball cap.", "subject_expression": "A wide, shouting grin of pure excitement, looking into the lens.", "subject_action": "Holding the camera arm extended (selfie style) while leaning out over the void." }, "negative_prompt": { "exclude_visuals": [ "ground level view", "interiors", "studio lighting", "tripod stability", "bokeh", "flat lens" ], "exclude_styles": [ "oil painting", "sketch", "vintage film", "studio portrait" ], "exclude_colors": [ "sepia", "monochrome" ], "exclude_objects": [ "safety railings", "fences" ] }, "subject2": { "costume": "A hooded athletic vest, cargo joggers, and climbing shoes.", "subject_expression": "Intense focus mixed with a daredevil smirk.", "subject_action": "Balancing on one leg on the very edge of the cornice, throwing a 'peace' sign towards the camera." } }}
{ "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness but render them as charming, handcrafted clay models. Transform Subject 1 (male) and Subject 2 (female) into miniature adventurers resting on the cap of a giant red mushroom. The scene should look like a freeze-frame from a high-budget stop-motion film, complete with visible thumbprints on the clay surfaces and uneven, sculpted textures.", "details": { "year": "Timeless Whimsy", "genre": "Claymation", "location": "A macro-scale forest floor, centered on top of a large, red Fly Agaric mushroom with white spots.", "lighting": [ "Soft studio lighting", "Warm key light", "Simulated rim lighting to highlight clay edges" ], "camera_angle": "Slight high-angle macro shot with a shallow depth of field to simulate a miniature set.", "emotion": [ "Joyful", "Cozy", "Wonder" ], "color_palette": [ "Vibrant red", "moss green", "canary yellow", "earthy brown", "sky blue" ], "atmosphere": [ "Playful", "Handcrafted", "Tactile", "Charming" ], "environmental_elements": "Oversized blades of grass made of flattened green clay, a snail with a spiral shell made of rolled play-dough, and cotton-ball clouds in the background.", "subject1": { "costume": "A textured hiker's vest made of matte clay, a plaid shirt with painted lines, and chunky brown boots.", "subject_expression": "A wide, friendly grin with slightly exaggerated, rounded features.", "subject_action": "Sitting on the edge of the mushroom, dangling his legs and pointing at a clay butterfly." }, "negative_prompt": { "exclude_visuals": [ "photorealistic skin", "human proportions", "hair strands", "digital gloss" ], "exclude_styles": [ "CGI", "2D cartoon", "sketch", "anime", "watercolor" ], "exclude_colors": [ "neon", "grayscale", "dark moody tones" ], "exclude_objects": [ "modern technology", "cars", "buildings" ] }, "subject2": { "costume": "A yellow raincoat with a smooth, glossy finish and oversized red rain boots.", "subject_expression": "A cheerful look with sculpted laugh lines and bright eyes.", "subject_action": "Kneeling on the mushroom cap, holding a giant, sculpted blueberry with both hands." } }}
{ "prompt": "You will perform an image edit using the person from the provided photo as the main subject. The face must remain clear and unaltered. Transform the subject into a solitary figure on a mist-shrouded wooden pier at dawn, evoking the melancholic beauty of an early 20th-century artistic photograph. The image should have the textural quality and muted tones of an aged platinum print, with the subject gazing contemplatively out to a calm, grey sea.", "details": { "year": "1905", "genre": "Early 20th Century Artistic Photography / Melancholic Realism", "location": "A desolate, mist-shrouded wooden pier stretching into a calm, grey sea at dawn, with only distant, blurred shapes of sailing ships.", "lighting": "Soft, diffused early morning light breaking through heavy mist, creating a luminous, ethereal glow with subtle shadows.", "camera_angle": "Medium-wide shot from a slightly low angle, emphasizing the subject's solitude against the vastness of the misty sea and pier.", "emotion": "Profound contemplation and quiet melancholy, tinged with a sense of enduring solitude.", "costume": "A heavy, dark wool overcoat, a slightly rumpled white shirt with a dark tie, and a weathered cap pulled low, suggesting a thoughtful individual.", "color_palette": "Muted sepia tones with hints of faded slate grey and soft ivory, mimicking an aged silver gelatin print with subtle hand-tinted quality.", "atmosphere": "A hauntingly still, almost dreamlike atmosphere, imbued with the quiet weight of memory and the vastness of the sea. A profound sense of introspection and bygone days.", "subject_expression": "A distant, reflective gaze fixed on the horizon, eyes hinting at unseen burdens or deep thoughts.", "subject_action": "Standing perfectly still, hands clasped behind his back, a faint wisp of breath visible in the cool air.", "environmental_elements": "Dense, rolling sea mist clinging to the wooden pilings of the pier, a few distant, blurred seagulls, and the faint, rhythmic lapping of unseen waves against the shore." }}
{ "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve his core likeness. The scene depicts Subject 1 as a beleaguered Victorian time traveler checking a complicated brass chronometer in a dense, misty prehistoric jungle. The image must be ultra-photorealistic and highly detailed, capturing the texture of fraying velvet, sweating skin, and wet tropical leaves. Use cinematic lighting with dappled sunlight breaking through the canopy to illuminate the subject. The style is that of a high-budget movie, shot on Arri Alexa with a shallow depth of field.", "details": { "year": "The Late Cretaceous Period (via 1890)", "genre": "Cinematic Photorealism", "location": "A dense, humid jungle floor with giant ferns and ancient cycads.", "lighting": [ "Dappled sunlight filtering through canopy", "Atmospheric volumetric fog", "High contrast shadows" ], "camera_angle": "Eye-level close-up with focus on the face and device.", "emotion": [ "Panic", "Urgency", "Disbelief" ], "color_palette": [ "Deep emerald greens", "Muddy browns", "Tarnished brass gold", "Rich burgundy" ], "atmosphere": [ "Humid", "Dangerous", "Claustrophobic", "Sweltering" ], "environmental_elements": "Giant fern fronds, hovering prehistoric insects, rising steam from the damp ground, a blurred massive shape moving in the background.", "subject1": { "costume": "A torn and muddy three-piece Victorian velvet suit, a loose cravat, and brass steampunk goggles around the neck.", "subject_expression": "Wide-eyed desperation, sweat beading on the forehead.", "subject_action": "Frantically tapping the glass dial of a glowing, smoking brass chronometer held in his hand." }, "negative_prompt": { "exclude_visuals": [ "modern buildings", "paved roads", "digital watches", "sneakers", "plastic" ], "exclude_styles": [ "cartoon", "sketch", "oil painting", "anime", "low resolution" ], "exclude_colors": [ "neon blue", "hot pink" ], "exclude_objects": [ "cars", "modern weaponry" ] } }}
#version 1.0root{details,prompt:str}: details{atmosphere,camera_angle:str,color_palette,emotion,environmental_elements:str,genre:str,lighting,location:str,subject1,subject2,year:str}: atmosphere[4]: Playful,Dreamlike,Digital frontier,Calm isolation camera_angle: "High-angle isometric view, emphasizing the island's isolation and the blocky aesthetics, 1:1 cinematic aspect ratio." color_palette[4]: Saturated primary colors,vibrant greens and blues for the island,deep purples and blacks for the void,pixelated orange accents emotion[4]: Wonder,Curiosity,Discovery,Serenity environmental_elements: "Blocky, geometric trees with glowing leaves, pixelated waterfalls cascading into the void, floating abstract digital dust motes, subtle grid lines on the void's floor." genre: Voxel Art lighting[3]: Emissive light from the voxels themselves,"soft, diffuse ambient light from the digital void",subtle rim lighting on the blocky figures location: "A solitary, blocky floating island made of glowing voxels, suspended in an infinite digital void, with sparse, geometric trees and structures." subject1{costume:str,subject_action:str,subject_expression:str}: costume: "Low-polygon adventurer tunic and trousers in muted greens and browns, a blocky utility belt with voxel tools, simple, chunky voxel boots." subject_action: "Standing with one hand lightly resting on a large, blocky, glowing data crystal embedded in the island." subject_expression: "A subtle, curious expression, eyes wide with wonder at the digital landscape." subject2{costume:str,subject_action:str,subject_expression:str}: costume: "A vibrant, pixelated explorer jumpsuit in electric blue, with contrasting orange accents, chunky voxel goggles pushed up on her head, a small blocky digital compass attached to her wrist." subject_action: "Leaning forward slightly, arm outstretched, pointing excitedly towards a cluster of particularly vibrant voxel flora at the island's edge." subject_expression: "An excited, joyful expression, mouth slightly open in awe." year: "Retro-Futuristic, 8-bit aesthetic" prompt: "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Imagine Subject 1 (male) and Subject 2 (female) as blocky, low-polygon explorers discovering a vibrant, floating voxel island in a vast digital void. Subject 1 is contemplative, while Subject 2 is eagerly pointing out a new discovery amidst the pixelated flora."
{ "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Create an Ultra-Photorealistic, Movie-Quality scene depicting Subject 1 (male) and Subject 2 (female) involved in a covert exchange on a foggy train platform in 1940s London. The image must be photorealistic, featuring cinematic lighting and highly detailed textures of wool and steam. The aesthetic should look like it was shot on Arri Alexa with a cinematic depth of field, capturing the tension and romance of a noir thriller.", "details": { "year": "1944", "genre": "Cinematic Photorealism", "location": "A dimly lit, steam-filled railway platform in London at night, with the blurred silhouette of a locomotive in the background.", "lighting": [ "Dramatic chiaroscuro", "Volumetric lighting through steam", "Cold atmospheric backlight", "Warm tungsten practical light from a station lamp" ], "camera_angle": "Over-the-shoulder close-up shot, focusing on the faces and the subtle hand exchange.", "emotion": [ "Secretive", "Urgent", "Melancholic", "Tense" ], "color_palette": [ "Steel blue", "Charcoal grey", "Sepia highlights", "Deep crimson" ], "atmosphere": [ "Noir", "Mysterious", "Cinematic", "Foggy" ], "environmental_elements": "Thick billowing steam from the train engine, wet cobblestones reflecting light, vintage leather suitcases in the periphery.", "subject1": { "costume": "A textured heavy wool trench coat, a fedora hat slightly tipped forward, and leather gloves.", "subject_expression": "Stoic and alert, eyes darting to the side to check for surveillance.", "subject_action": "Discreetly slipping a small, sealed envelope into Subject 2's hand." }, "negative_prompt": { "exclude_visuals": [ "bright daylight", "modern technology", "smartphones", "digital watches", "modern architecture" ], "exclude_styles": [ "cartoon", "3d render", "anime", "oil painting", "sketch", "low resolution" ], "exclude_colors": [ "neon green", "fluorescent pink", "oversaturated colors" ], "exclude_objects": [ "cars", "airplanes", "plastic" ] }, "subject2": { "costume": "A tailored 1940s skirt suit with a fur collar, a pillbox hat with a small mesh veil, and red lipstick.", "subject_expression": "Anxious but composed, biting her lip slightly, looking intently at Subject 1.", "subject_action": "Grasping Subject 1's hand tightly while receiving the envelope, pulling her coat closer." } }}
{ "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Create an Ultra-Photorealistic, Movie-Quality scene depicting Subject 1 (male) and Subject 2 (female) as covert spies meeting on a foggy, iron bridge during the Cold War. The image must look like a frame from a high-budget blockbuster movie shot on Arri Alexa. Use cinematic lighting to create deep shadows and highlights. The scene is highly detailed with a shallow depth of field. Subject 1 is handing off a secret package to Subject 2. The composition adheres to a cinematic 1:1 aspect ratio.", "details": { "year": "1962", "genre": "Cinematic Photorealism", "location": "The Glienicke Bridge at midnight, obscured by thick river fog and illuminated by dim, yellow streetlamps.", "lighting": [ "Volumetric fog lighting", "Noir style chiaroscuro", "Rim lighting on silhouettes", "Soft yellow tungsten glow" ], "camera_angle": "Eye-level medium closeup with a shallow depth of field to isolate the subjects from the misty background.", "emotion": [ "Suspenseful", "Urgent", "Clandestine" ], "color_palette": [ "Steel blue", "Fog gray", "Tungsten amber", "Deep black", "Vibrant crimson" ], "atmosphere": [ "Cold", "Tense", "Cinematic", "Mysterious" ], "environmental_elements": "Swirling mist rising from the water below, damp iron railings, the distant blurred headlights of a vintage checkpoint vehicle.", "subject1": { "costume": "A textured charcoal wool peacoat with the collar turned up against the wind.", "subject_expression": "Anxious, with sweat glistening on his brow and eyes darting nervously.", "subject_action": "Subtly sliding a leather dossier across the railing towards Subject 2." }, "negative_prompt": { "exclude_visuals": [ "daylight", "sunshine", "modern cars", "cell phones", "neon signs" ], "exclude_styles": [ "cartoon", "3D render", "sketch", "anime", "impressionist" ], "exclude_colors": [ "neon green", "hot pink", "pastel colors" ], "exclude_objects": [ "umbrellas", "crowds", "modern architecture" ] }, "subject2": { "costume": "A classic beige trench coat belted at the waist and a red hat.", "subject_expression": "Stoic and composed, with a piercing, calculating gaze.", "subject_action": "Reaching out with a black leather-gloved hand to intercept the dossier while looking over her shoulder." } }}
{ "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve his core likeness. Transform Subject 1 (male) into a Victorian time traveler who has just materialized in a dense, prehistoric jungle. The image must be Ultra-Photorealistic, Movie-Quality, and highly detailed. The scene captures the moment of arrival, shot on Arri Alexa with cinematic lighting and a shallow depth of field. He stands amidst towering ferns and ancient cycads, looking completely out of place in his formal 19th-century attire, contrasting the rugged, humid environment with his refined appearance.", "details": { "year": "1895 / 65 Million BC", "genre": "Cinematic Photorealism", "location": "A dense, steaming Cretaceous jungle floor filled with giant ferns, ancient conifers, and thick atmospheric fog.", "lighting": [ "Volumetric god rays piercing through the canopy", "Dappled sunlight", "High dynamic range" ], "camera_angle": "Medium close-up at eye level, focusing on the subject with the background falling into soft bokeh.", "emotion": [ "Disbelief", "Awe", "Scientific curiosity", "Fear" ], "color_palette": [ "Deep emerald greens", "Earthy mud browns", "Burnished brass", "Tweed grey" ], "atmosphere": [ "Humid", "Primordial", "Claustrophobic", "Mysterious" ], "environmental_elements": "Floating pollen particles, massive prehistoric insects buzzing in the background, a large ominous silhouette of a dinosaur visible through the thick mist.", "subject1": { "costume": "A bespoke three-piece Victorian tweed suit, a slightly askew cravat, and intricate brass steampunk goggles pushed up onto his forehead.", "subject_expression": "Wide-eyed shock mixed with fascination, mouth slightly open, sweat beading on his brow.", "subject_action": "Clutching a glowing, smoking brass chronometer device in one hand while tentatively reaching out to touch a massive, alien-looking fern frond with the other." }, "negative_prompt": { "exclude_visuals": [ "modern buildings", "paved roads", "cars", "cell phones", "contemporary fashion", "cleanliness" ], "exclude_styles": [ "cartoon", "3D render", "illustration", "painting", "low resolution", "blur", "sketch" ], "exclude_colors": [ "neon", "pastel pinks", "artificial brights" ], "exclude_objects": [ "spaceships", "aliens", "modern weapons" ] } }}
{ "prompt": "You will perform an image edit transforming the male subject into a fugitive netrunner in a gritty, high-tech future. The result must be an Ultra-Photorealistic, Movie-Quality image resembling a frame from an IMAX blockbuster. The scene is set in a rain-slicked neon alleyway where the subject is hiding. Ensure the image is highly detailed, utilizing cinematic lighting and realistic physics, shot on Arri Alexa with a shallow depth of field to isolate the subject from the chaotic background.", "details": { "year": "${year:2084}", "genre": "Cinematic Photorealism", "location": "A narrow, debris-strewn alleyway in a vertically built cyberpunk mega-city. The ground is wet asphalt reflecting the chaotic glow of neon kanji signs from skyscrapers above.", "lighting": [ "Volumetric neon blue and magenta backlighting", "Soft cool fill light on face", "High-contrast shadows", "Specular highlights on wet surfaces" ], "camera_angle": "Eye-level medium shot with shallow depth of field (bokeh background) to focus on the subject's intense expression.", "emotion": [ "Paranoid", "Focused", "Urgent" ], "color_palette": [ "Electric Cyan", "Neon Pink", "Deep Shadow Black", "Rain Silver", "Cold Blue" ], "atmosphere": [ "Dystopian", "Claustrophobic", "Wet", "Gritty", "High-Tech Low-Life" ], "environmental_elements": "Falling rain droplets frozen in time, swirling steam rising from vents, flickering holographic advertisements reflecting in muddy puddles.", "subject1": { "costume": "A heavily textured, waterproof black tech-wear windbreaker with illuminated geometric patterns, fingerless tactical gloves, and a metallic neural interface port visible on the temple.", "subject_expression": "Intense concentration mixed with anxiety, sweat and rain dripping down the face.", "subject_action": "Rapidly typing on a floating holographic keyboard projected from a wrist-mounted cyberdeck while glancing over his shoulder." }, "negative_prompt": { "exclude_visuals": [ "daylight", "sunshine", "blue sky", "clean surfaces", "dryness", "warm lighting" ], "exclude_styles": [ "cartoon", "anime", "3D render", "painting", "low resolution", "blurry", "sketch" ], "exclude_colors": [ "warm sepia", "pastels", "bright white", "beige" ], "exclude_objects": [ "cars", "trees", "pets", "flowers" ] } }}
{ "title": "The Aether Prince at the Crystal Gala", "description": "A breathtaking cinematic shot of a regal nobleman standing on the balcony of a translucent palace hovering above the clouds.", "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve his core likeness. Transform Subject 1 (male) into a high-society aristocrat attending a royal ball inside a floating crystal palace. He stands near a transparent balustrade, with the grand ballroom behind him and a sea of clouds stretching out to the horizon. The image must be ultra-photorealistic, utilizing cinematic lighting to capture the refraction of light through the crystal structures. The scene is highly detailed, shot on Arri Alexa, featuring a shallow depth of field that blurs the dancing guests in the background while keeping the subject sharpness pristine.", "details": { "year": "Timeless Fantasy Era", "genre": "Cinematic Photorealism", "location": "A grand ballroom constructed entirely of diamond and glass, floating high in the stratosphere at sunset.", "lighting": [ "Golden hour sunlight refracting through crystal prisms", "Soft volumetric glow", "Caustic reflections" ], "camera_angle": "Medium shot at eye level, capturing the subject against the vast sky.", "emotion": [ "Regal", "Contemplative", "Serene" ], "color_palette": [ "Champagne gold", "prismatic white", "sky blue", "sunset orange" ], "atmosphere": [ "Opulent", "Ethereal", "Majestic", "Airy" ], "environmental_elements": "Floating anti-gravity chandeliers, clouds drifting past open arches, blurred silhouettes of dancers in formal wear.", "subject1": { "costume": "A futuristic formal white tuxedo with intricate gold filigree embroidery and a silk sash.", "subject_expression": "A calm, confident gaze with a hint of aristocratic detachment.", "subject_action": "Resting one hand elegantly on the crystal railing, holding a flute of sparkling nectar." }, "negative_prompt": { "exclude_visuals": [ "darkness", "dirt", "grime", "industrial machinery", "ground level terrain" ], "exclude_styles": [ "cartoon", "sketch", "oil painting", "anime", "CGI 3D render look" ], "exclude_colors": [ "neon green", "muddy brown", "pitch black" ], "exclude_objects": [ "cars", "modern streetlights", "weapons" ] } }}
{ "title": "Shadows of the Blue Note", "description": "A tense, high-stakes meeting between a weary detective and a glamorous informant in a smoky 1950s jazz lounge.", "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Transform Subject 1 (male) and Subject 2 (female) into characters from a classic 1950s film noir. Subject 1 is a rugged private investigator, and Subject 2 is an elegant femme fatale. They are seated at a secluded booth in a dimly lit, smoke-filled jazz club. The image must be ultra-photorealistic, utilizing cinematic lighting to create deep shadows and highlights. The scene should look like a frame from a high-budget blockbuster movie, shot on Arri Alexa, highly detailed, with a shallow depth of field focusing on their intense interaction.", "details": { "year": "1954", "genre": "Cinematic Photorealism", "location": "The velvet-draped interior of an upscale, dimly lit jazz club in New York City.", "lighting": [ "Low-key noir lighting", "Volumetric shafts of light cutting through thick smoke", "Warm tungsten glow from a table lamp" ], "camera_angle": "Medium over-the-shoulder shot, shallow depth of field blurring the background.", "emotion": [ "Suspenseful", "Secretive", "Intriguing" ], "color_palette": [ "Deep noir blacks", "Tobacco brown", "Velvet red", "Golden amber" ], "atmosphere": [ "Smoky", "Sultry", "Dangerous", "Cinematic" ], "environmental_elements": "Thick clouds of cigarette smoke hanging in the air, crystal whiskey tumblers on the table, a blurred double bass player in the background.", "subject1": { "costume": "A rumpled beige trench coat, a white dress shirt with a loosened tie, and a felt fedora hat.", "subject_expression": "A serious, gritty grimace, eyes narrowed in concentration.", "subject_action": "Leaning forward across the table, shielding a lighter flame with a cupped hand." }, "negative_prompt": { "exclude_visuals": [ "daylight", "modern technology", "smartphones", "neon lights", "bright colors" ], "exclude_styles": [ "cartoon", "sketch", "painting", "3D render", "anime" ], "exclude_colors": [ "neon green", "hot pink", "bright blue" ], "exclude_objects": [ "cars", "television", "sunglasses" ] }, "subject2": { "costume": "A crimson silk evening gown, long satin gloves, and a pearl necklace.", "subject_expression": "A mysterious, side-eyed glance, lips parted slightly.", "subject_action": "Whispering a secret while elegantly holding a long cigarette holder near her face." } }}
{ "title": "Echoes of the Rust Age", "description": "Two survivors navigate a treacherous landscape composed entirely of discarded technology and rusted metal.", "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Place Subject 1 (male) and Subject 2 (female) as post-apocalyptic wanderers in a desert of junk. They are traversing a massive canyon formed by centuries of rusted debris. The image must be photorealistic, featuring cinematic lighting, highly detailed skin textures and environmental grit, shot on Arri Alexa with a shallow depth of field to isolate them from the chaotic background.", "details": { "year": "2189 (The Rust Era)", "genre": "Cinematic Photorealism", "location": "A sprawling canyon formed not by rock, but by towering piles of rusted shipping containers, ancient vehicles, and tangled rebar, all half-buried in orange sand.", "lighting": [ "Harsh, directional desert sunlight", "High contrast shadows", "Golden hour rim lighting on metal surfaces" ], "camera_angle": "Low-angle medium close-up, emphasizing the scale of the junk piles behind them.", "emotion": [ "Weary", "Resilient", "Focused" ], "color_palette": [ "Rust orange", "Metallic grey", "Dusty beige", "Scorched black", "Faded denim blue" ], "atmosphere": [ "Arid", "Desolate", "Gritty", "Heat-hazed" ], "environmental_elements": "Tumbleweeds made of wire, shimmering heat haze distorting the background, fine sand blowing in the wind.", "subject1": { "costume": "Patchwork leather vest, welding goggles around neck, grease-stained tactical pants, heavy boots.", "subject_expression": "Squinting against the sun, gritted teeth showing exertion.", "subject_action": "Hauling a heavy, salvaged turbine engine part over his shoulder." }, "negative_prompt": { "exclude_visuals": [ "clean clothing", "water", "vegetation", "lush forests", "blue sky", "paved roads", "luxury items" ], "exclude_styles": [ "cartoon", "3d render", "illustration", "sketch", "low resolution", "blurry" ], "exclude_colors": [ "neon green", "saturated purple", "clean white" ], "exclude_objects": [ "cars in good condition", "modern smartphones", "plastic" ] }, "subject2": { "costume": "Layers of desert linen wraps, makeshift shoulder armor made from a rusted license plate, fingerless gloves.", "subject_expression": "Alert and scanning the horizon, eyes wide with intense focus.", "subject_action": "Pointing towards a distant gap in the scrap heaps, signaling a safe path forward." } }}
{ "title": "Corsairs of the Crimson Void", "description": "A high-octane cinematic moment capturing a legendary space pirate and his quartermaster commanding a starship through a debris field during a daring escape.", "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Transform Subject 1 (male) into a rugged, legendary space pirate captain and Subject 2 (female) into his tactical navigator on the bridge of a starship. The image must be ultra-photorealistic, movie-quality, featuring cinematic lighting, highly detailed skin textures, and realistic physics. Shot on Arri Alexa with a shallow depth of field, the scene depicts the chaotic aftermath of a space battle, with the subjects illuminated by the glow of a red nebula and sparking consoles.", "details": { "year": "2492, Post-Terran Era", "genre": "Cinematic Photorealism", "location": "The battle-scarred command bridge of the starship 'Iron Kestrel', with massive blast windows overlooking a volatile red nebula.", "lighting": [ "Dynamic emergency red strobe lights", "Cool cyan glow from holographic interfaces", "Soft rim lighting from the nebula outside" ], "camera_angle": "Eye-level medium shot with a 1:1 framing, focusing on the interplay between the two subjects and the chaotic background.", "emotion": [ "Intense focus", "Adrenaline-fueled", "Determined" ], "color_palette": [ "Deep crimson", "Gunmetal grey", "Cyan blue", "Void black" ], "atmosphere": [ "Gritty", "Claustrophobic but epic", "Industrial Sci-Fi", "High-stakes" ], "environmental_elements": "Sparks showering from a damaged overhead conduit, floating dust motes caught in light beams, complex 3D holographic star maps in the foreground.", "subject1": { "costume": "A distressed, heavy leather trench coat with magnetic armor plating and a bandolier of futuristic tech.", "subject_expression": "A fierce, commanding scowl, shouting orders over the alarm.", "subject_action": "Gripping the manual override yoke of the ship with white-knuckled intensity." }, "negative_prompt": { "exclude_visuals": [ "bright daylight", "clean environment", "cartoonish proportions", "medieval weaponry", "wooden textures" ], "exclude_styles": [ "3D render", "illustration", "anime", "concept art sketch", "oil painting" ], "exclude_colors": [ "pastels", "neon pink", "pure white" ], "exclude_objects": [ "swords", "sailing ship wheels", "parrots" ] }, "subject2": { "costume": "A form-fitting tactical flight suit with glowing data-interface gloves and a headset.", "subject_expression": "Sharp, calculating, and unphased by the chaos.", "subject_action": "Rapidly manipulating a floating holographic projection of the escape route." } }}
{ "title": "Whispers in Light Trails", "description": "A cinematic long-exposure capture of a 1950s noir scene, contrasting the stillness of a detective with the kinetic energy of a jazz club.", "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Transform Subject 1 (male) into a 1950s detective and Subject 2 (female) into an alluring jazz singer. Utilize a Long Exposure artistic style where time seems to bleed. Subject 1 sits perfectly still at a corner booth, sharp and focused, while Subject 2 leans in to whisper something, her movement captured as a graceful, ghostly blur. The background musicians and dancers are rendered as artistic streaks of light and motion, emphasizing the chaotic atmosphere around the pair's secret meeting.", "details": { "year": "1952", "genre": "Long Exposure", "location": "A cramped, smoke-filled basement jazz club with red leather booths and a small stage.", "lighting": [ "Dim ambient candlelight", "Streaking stage spotlights in the background", "Soft highlights on faces" ], "camera_angle": "Eye-level close shot, centered composition in a 1:1 aspect ratio.", "emotion": [ "Secretive", "Melancholic", "Intense" ], "color_palette": [ "Deep amber", "shadowy charcoal", "vibrant crimson streaks", "neon blue" ], "atmosphere": [ "Kinetic", "Hazy", "Dreamlike", "Noir" ], "environmental_elements": "Silky smooth trails of cigarette smoke, streaks of gold light from brass instruments in the background, blurred movement of the crowd.", "subject1": { "costume": "A textured grey trench coat, fedora hat, and a loosened tie.", "subject_expression": "Stoic and intense, eyes locked forward.", "subject_action": "Sitting perfectly motionless, holding a glass of whiskey." }, "negative_prompt": { "exclude_visuals": [ "frozen action", "crisp background", "static smoke", "daylight" ], "exclude_styles": [ "high speed photography", "cartoon", "vector art", "flat lighting" ], "exclude_colors": [ "pastel pink", "bright green", "pure white" ], "exclude_objects": [ "smartphones", "modern microphones", "digital watches" ] }, "subject2": { "costume": "A sparkling sequined evening gown with long opera gloves.", "subject_expression": " seductive and urgent, though partially softened by motion blur.", "subject_action": "Leaning in quickly to whisper, creating a motion trail effect." } }}
{ "title": "The Aether Workshop", "description": "A vibrant, nostalgic snapshot of two inventors collaborating on a clockwork masterpiece in a sun-drenched steampunk atelier.", "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness. Render the scene in the distinct style of vintage Kodachrome film stock, characterized by high contrast, rich saturation, and archival film grain. Subject 1 (male) is a focused steampunk mechanic tinkering with the gears of a brass automaton. Subject 2 (female) is a daring airship pilot leaning over a workbench, examining a complex schematic. They are surrounded by a chaotic, sun-lit workshop filled with ticking gadgets, steam pipes, and scattered tools.", "details": { "year": "Alternate 1890s", "genre": "Kodachrome", "location": "A high-ceilinged, cluttered attic workshop with large arched windows overlooking a smoggy industrial city.", "lighting": [ "Hard, warm sunlight streaming through dusty glass", "High contrast shadows typical of slide film", "Golden hour glow" ], "camera_angle": "Eye-level medium shot, creating an intimate, documentary feel. 1:1 cinematic composition.", "emotion": [ "Focused", "Collaborative", "Inventive" ], "color_palette": [ "Polished brass gold", "Deep mahogany brown", "Vibrant iconic Kodachrome red", "Oxidized copper teal" ], "atmosphere": [ "Nostalgic", "Warm", "Dusty", "Tactile" ], "environmental_elements": "Floating dust motes catching the light, steam venting softly from a copper pipe, blueprints pinned to walls, piles of cogs and springs.", "subject1": { "costume": "A grease-stained white shirt with rolled sleeves, a heavy leather apron, and brass welding goggles resting on his forehead.", "subject_expression": " intense concentration, brow furrowed as he adjusts a delicate mechanism.", "subject_action": "Holding a fine screwdriver and tweaking a golden gear inside a robotic arm." }, "negative_prompt": { "exclude_visuals": [ "neon lights", "digital displays", "plastic materials", "modern sleekness", "blue hues" ], "exclude_styles": [ "digital painting", "3D render", "anime", "black and white", "sepia only", "low saturation" ], "exclude_colors": [ "fluorescent green", "hot pink" ], "exclude_objects": [ "computers", "smartphones", "modern cars" ] }, "subject2": { "costume": "A brown leather aviator jacket with a shearling collar, a vibrant red silk scarf, and canvas trousers.", "subject_expression": "Curious and analytical, pointing out a specific detail on the machine.", "subject_action": "Leaning one hand on the workbench while holding a rolled-up blue schematic in the other." } }}
{ "title": "Whispers of Noir", "description": "A gritty, cinematic portrait of a hard-boiled detective waiting for a lead in a hazy, underground jazz lounge.", "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve the core likeness. Transform Subject 1 (male) into a weary 1950s private investigator seated in a plush velvet booth within a smoke-filled jazz club. Render the image as an ultra-photorealistic movie still, utilizing cinematic lighting that emphasizes the texture of his skin and the swirling smoke around him. The image must be highly detailed, shot on Arri Alexa with a shallow depth of field to blur the band in the background, adhering to a 1:1 aspect ratio.", "details": { "year": "1954", "genre": "Cinematic Photorealism", "location": "The Blue Velvet Lounge, a subterranean club with mahogany walls and dim table lamps.", "lighting": [ "Chiaroscuro", "Warm table lamp glow", "Cool blue backlighting from the stage", "Volumetric light beams through smoke" ], "camera_angle": "Eye-level medium close-up, focusing intensely on the subject's face.", "emotion": [ "Suspicion", "World-weariness", "Focused" ], "color_palette": [ "Whiskey amber", "Velvet red", "Deep shadow black", "Tobacco smoke grey" ], "atmosphere": [ "Sultry", "Tense", "Claustrophobic", "Vintage" ], "environmental_elements": "Thick clouds of cigarette smoke hanging in the air, a crystal tumbler of amber liquid on the table, blurred silhouettes of musicians in the background.", "subject1": { "costume": "A textured charcoal trench coat over a rumpled suit, with a loose tie and a fedora tilted slightly forward.", "subject_expression": "A piercing, cynical gaze with narrowed eyes and a tight jaw.", "subject_action": "Resting one hand near a half-empty glass of whiskey, leaning slightly into the light." }, "negative_prompt": { "exclude_visuals": [ "bright daylight", "modern technology", "cell phones", "neon signs", "clean air" ], "exclude_styles": [ "cartoon", "3d render", "anime", "sketch", "painting" ], "exclude_colors": [ "neon green", "hot pink", "pure white" ], "exclude_objects": [ "cars", "digital watches", "second person" ] } }}
{ "title": "The Midnight Informant", "description": "A tense, film noir moment featuring a female private investigator waiting for a lead in a hazy, underground jazz club.", "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve her core likeness. Transform the subject (female) into a sharp-witted 1950s private investigator seated in a booth at a dimly lit, smoke-filled jazz club. The image must be Ultra-Photorealistic and Movie-Quality, evoking the golden age of Film Noir. Use dramatic lighting to highlight skin texture and fabric details. Keywords: photorealistic, cinematic lighting, highly detailed, shot on Arri Alexa, depth of field, volumetric fog, realistic physics.", "details": { "year": "1954", "genre": "Cinematic Photorealism", "location": "The Velvet Note, a crowded, subterranean jazz lounge in Chicago with red velvet booths and a small stage in the hazy background.", "lighting": [ "Chiaroscuro", "Volumetric shafts of light cutting through smoke", "Warm tungsten table lamps", "Rim lighting on hair" ], "camera_angle": "Eye-level medium close-up, shallow depth of field focusing strictly on the subject's eyes.", "emotion": [ "Suspicious", "Alert", "Melancholic" ], "color_palette": [ "Deep shadow black", "Amber gold", "Burgundy red", "Tobacco brown" ], "atmosphere": [ "Sultry", "Mysterious", "Claustrophobic", "Noir" ], "environmental_elements": "Thick swirls of cigarette smoke filling the air, a half-empty glass of amber whiskey on the table, blurred silhouette of a double bass player in the background.", "subject1": { "costume": "A structured beige trench coat worn over a dark cocktail dress, leather gloves, and a wide-brimmed fedora tilted slightly forward.", "subject_expression": "A piercing, guarded gaze, eyes scanning the room, lips pressed in a tight line.", "subject_action": "One hand rests on a manila folder on the table, the other hovers near her whiskey glass." }, "negative_prompt": { "exclude_visuals": [ "daylight", "modern technology", "smartphones", "casual clothing", "bright sunshine", "blue skies" ], "exclude_styles": [ "cartoon", "3D render", "anime", "sketch", "impressionism", "oversaturated" ], "exclude_colors": [ "Neon green", "Hot pink", "Cyan" ], "exclude_objects": [ "cars", "weapons drawn", "animals" ] } }}
{ "title": "The Midnight Melody Mystery", "description": "A charming, animated noir scene where a gruff detective questions a glamorous jazz singer in a stylized 1950s club.", "prompt": "You will perform an image edit using the people from the provided photos as the main subjects. Preserve their core likeness but stylized. Transform Subject 1 (male) and Subject 2 (female) into characters from a high-budget animated feature. Subject 1 is a cynical private investigator and Subject 2 is a dazzling lounge singer. They are seated at a curved velvet booth in a smoky, art-deco jazz club. The aesthetic must be distinctively 'Disney Character' style, featuring smooth shading, expressive large eyes, and a magical, cinematic glow.", "details": { "year": "1950s Noir Era", "genre": "Disney Character", "location": "The Blue Note Lounge, a stylized jazz club with art deco architecture, plush red velvet booths, and a stage in the background.", "lighting": [ "Cinematic spotlighting", "Soft volumetric haze", "Warm golden glow from table lamps", "Cool blue ambient backlight" ], "camera_angle": "Medium close-up at eye level, framing both subjects across a small round table.", "emotion": [ "Intrigue", "Playful suspicion", "Charm" ], "color_palette": [ "Deep indigo", "ruby red", "golden amber", "sepia tone" ], "atmosphere": [ "Mysterious", "Romantic", "Whimsical", "Smoky" ], "environmental_elements": "Swirling stylized smoke shapes, a vintage microphone in the background, a crystal glass with a garnish on the table.", "subject1": { "costume": "A classic tan trench coat with the collar popped, a matching fedora hat, and a loosened tie.", "subject_expression": "A raised eyebrow and a smirk, looking skeptical yet captivated.", "subject_action": "Holding a small reporter's notebook and a pencil, leaning slightly forward over the table." }, "negative_prompt": { "exclude_visuals": [ "photorealism", "gritty textures", "blood", "gore", "dirt", "noise" ], "exclude_styles": [ "anime", "cyberpunk", "sketch", "horror", "watercolor" ], "exclude_colors": [ "neon green", "hot pink" ], "exclude_objects": [ "smartphones", "modern technology", "cars" ] }, "subject2": { "costume": "A sparkling, floor-length red evening gown with white opera-length gloves and a pearl necklace.", "subject_expression": "A coy, confident smile with heavy eyelids, playing the role of the femme fatale.", "subject_action": "Resting her chin elegantly on her gloved hand, looking directly at the detective." } }}
{ "title": "The Gravedigger's Vigil", "description": "A haunting portrait of a lone Victorian figure standing watch over a misty, decrepit cemetery at midnight.", "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve his core likeness. Transform Subject 1 (male) into a solemn Victorian gravedigger standing amidst a sprawling, fog-choked necropolis. He holds a rusted lantern that casts long, uncanny shadows against the moss-covered mausoleums behind him. The composition adheres to a cinematic 1:1 aspect ratio, framing him tightly against the decaying iron gates.", "details": { "year": "1888", "genre": "Gothic Horror", "location": "An overgrown, crumbling cemetery gate with twisted iron bars and weeping angel statues.", "lighting": [ "Pale, cold moonlight cutting through fog", "Flickering, warm amber candlelight from a lantern", "Deep, abyssal shadows" ], "camera_angle": "Eye-level medium shot, creating a direct and confronting connection with the viewer.", "emotion": [ "Foreboding", "Solitary", "Melancholic" ], "color_palette": [ "Obsidian black", "slate gray", "pale moonlight blue", "sepia tone", "muted moss green" ], "atmosphere": [ "Eerie", "Cold", "Silent", "Supernatural", "Decaying" ], "environmental_elements": "Swirling ground mist that obscures the feet, twisted dead oak trees silhouetted against the moon, a lone crow perched on a headstone.", "subject1": { "costume": "A tattered, ankle-length black velvet frock coat, a weathered top hat, and worn leather gloves.", "subject_expression": "A somber, pale visage with a piercing, weary gaze staring into the darkness.", "subject_action": "Raising a lantern high with the right hand while gripping the handle of a spade with the left." }, "negative_prompt": { "exclude_visuals": [ "sunlight", "blooming flowers", "blue sky", "modern infrastructure", "smiling", "lens flare" ], "exclude_styles": [ "cartoon", "cyberpunk", "high fantasy", "anime", "watercolor", "bright pop art" ], "exclude_colors": [ "neon", "pastel pink", "vibrant orange", "saturated red" ], "exclude_objects": [ "cars", "smartphones", "plastic", "streetlights" ] } }}
{ "title": "Terminal Drift", "description": "A haunting visualization of a lone traveler stuck in an infinite, empty airport terminal that defies logic.", "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve her core likeness. Transform Subject 1 (female) into a solitary figure standing in an endless, windowless airport terminal. The surrounding space is a repetitive hallway of beige walls, low ceilings, and patterned carpet. There are no exits, only the endless stretch of artificial lighting and empty waiting chairs. The composition should adhere to a cinematic 1:1 aspect ratio.", "details": { "year": "Indeterminate 1990s", "genre": "Liminal Space", "location": "A vast, curving airport corridor with no windows, endless beige walls, and complex patterned carpet.", "lighting": [ "Flat fluorescent overheads", "Uniform artificial glow", "No natural light source" ], "camera_angle": "Wide shot, symmetrical center-framed composition.", "emotion": [ "Disassociation", "Unease", "Solitude" ], "color_palette": [ "Beige", "Muted Teal", "Faded Maroon", "Off-white" ], "atmosphere": [ "Uncanny", "Sterile", "Silent", "Timeless" ], "environmental_elements": "Rows of empty connected waiting chairs, commercial carpeting with a confusing pattern, generic signage with indecipherable text.", "subject1": { "costume": "A slightly oversized pastel sweater and loose trousers, appearing mundane and timeless.", "subject_expression": "A vacant, glazed-over stare, looking slightly past the camera into the void.", "subject_action": "Standing perfectly still, arms hanging loosely at her sides, holding a generic roller suitcase." }, "negative_prompt": { "exclude_visuals": [ "crowds", "sunlight", "deep shadows", "dirt", "clutter", "windows looking outside", "lens flare" ], "exclude_styles": [ "high contrast", "action movie", "vibrant saturation", "cyberpunk", "horror gore" ], "exclude_colors": [ "neon red", "pitch black", "vibrant green" ], "exclude_objects": [ "airplanes", "trash", "blood", "animals" ] } }}
{ "title": "Wings of the Dust Bowl", "description": "A daring 1930s female aviator stands confident on a wind-swept airfield at sunset, ready to cross the Atlantic.", "prompt": "You will perform an image edit using the provided photo to create a frame worthy of a historical epic. Transform the female subject into a pioneer aviator from the 1930s. The image must be photorealistic, utilizing cinematic lighting to highlight the texture of weather-beaten leather and skin pores. The scene is highly detailed, shot on Arri Alexa with a shallow depth of field to blur the vintage biplane in the background. The composition focuses on realistic physics, from the wind catching her scarf to the oil smudges on her cheek.", "details": { "year": "1933", "genre": "Cinematic Photorealism", "location": "A dusty, remote airfield in the Midwest with the blurred metallic nose of a vintage propeller plane in the background.", "lighting": [ "Golden hour sunset", "Strong rim lighting", "Volumetric light rays through dust", "High contrast warm tones" ], "camera_angle": "Eye-level close-up shot using an 85mm portrait lens.", "emotion": [ "Determined", "Adventurous", "Confident" ], "color_palette": [ "Burnt orange", "Leather brown", "Metallic silver", "Sunset gold", "Sepia" ], "atmosphere": [ "Nostalgic", "Gritty", "Windy", "Epic" ], "environmental_elements": "Swirling dust particles caught in the light, a spinning propeller motion blur in the distance, tall dry grass blowing in the wind.", "subject1": { "costume": "A distressed vintage brown leather bomber jacket with a shearling collar, a white silk aviator scarf blowing in the wind, and brass flight goggles resting on her forehead.", "subject_expression": "A subtle, confident smirk with eyes squinting slightly against the setting sun.", "subject_action": "Adjusting a leather glove on her hand while gazing toward the horizon." }, "negative_prompt": { "exclude_visuals": [ "modern jets", "paved runway", "smartphones", "digital watches", "clear blue sky", "plastic textures" ], "exclude_styles": [ "cartoon", "3D render", "anime", "painting", "sketch", "black and white" ], "exclude_colors": [ "neon green", "electric blue", "hot pink" ], "exclude_objects": [ "modern buildings", "cars" ] } }}
{ "title": "The Last Adagio", "description": "A hauntingly beautiful scene of a solitary ballerina performing in a flooded, abandoned grand library.", "prompt": "You will perform an image edit using the provided subject. Transform Subject 1 (female) into a survivor in a post-apocalyptic world. She is in a massive, decaying library where the floor is flooded with water. Light spills through the collapsed ceiling, illuminating dust motes and water reflections. The image must be photorealistic, utilizing cinematic lighting, highly detailed textures, shot on Arri Alexa with a shallow depth of field to focus on the subject while the background falls into soft bokeh.", "details": { "year": "Post-Collapse Era", "genre": "Cinematic Photorealism", "location": "A grand, abandoned library with towering shelves, crumbling architecture, and a floor flooded with still, reflective water.", "lighting": [ "God rays entering from a collapsed roof", "Soft reflected light from the water", "High contrast cinematic shadows" ], "camera_angle": "Low angle, wide shot, capturing the reflection in the water.", "emotion": [ "Melancholic", "Graceful", "Solitary" ], "color_palette": [ "Desaturated concrete greys", "Muted teal water", "Vibrant crimson", "Dusty gold light" ], "atmosphere": [ "Ethereal", "Lonely", "Quiet", "Majestic" ], "environmental_elements": "Floating pages from old books, dust particles dancing in light shafts, ripples in the water.", "subject1": { "costume": "A distressed, dirty white ballet leotard paired with pristine red gloves.", "subject_expression": "Serene, eyes closed, lost in the movement.", "subject_action": "dancing" }, "negative_prompt": { "exclude_visuals": [ "bright sunshine", "clean environment", "modern technology", "spectators" ], "exclude_styles": [ "cartoon", "painting", "sketch", "3D render" ], "exclude_colors": [ "neon green", "bright orange" ], "exclude_objects": [ "cars", "animals", "phones" ] } }}
{ "title": "Crimson Waltz in the Rain", "description": "A visually stunning, cinematic moment of a woman finding joy in solitude, dancing on a rain-slicked European street at twilight.", "prompt": "You will perform an image edit creating an Ultra-Photorealistic masterpiece. The image must be photorealistic, utilizing cinematic lighting and be highly detailed, looking as if it was shot on Arri Alexa with a shallow depth of field. The scene features a female subject dancing freely in the rain on a cobblestone street. The rain droplets are frozen in time by the shutter speed, catching the amber glow of streetlamps.", "details": { "year": "Timeless Modern", "genre": "Cinematic Photorealism", "location": "A narrow, empty cobblestone street in Paris at dusk, wet with rain, reflecting the warm glow of vintage streetlamps and shop windows.", "lighting": [ "Cinematic rim lighting", "Warm amber streetlights", "Soft blue ambient twilight", "Volumetric fog" ], "camera_angle": "Eye-level medium shot, emphasizing the subject's movement against the bokeh background.", "emotion": [ "Liberated", "Joyful", "Serene" ], "color_palette": [ "Deep obsidian", "Amber gold", "Rainy blue", "Vibrant crimson" ], "atmosphere": [ "Romantic", "Melancholic yet joyful", "Atmospheric", "Wet" ], "environmental_elements": "Rain falling diagonally, puddles reflecting lights on the ground, mist swirling around ankles.", "subject1": { "costume": "red hat", "subject_expression": "Eyes closed in pure bliss, a soft smile on her lips, raindrops on her cheeks.", "subject_action": "dancing" }, "negative_prompt": { "exclude_visuals": [ "bright daylight", "dry pavement", "crowds", "vehicles", "sunglasses" ], "exclude_styles": [ "cartoon", "3D render", "illustration", "oil painting", "sketch" ], "exclude_colors": [ "neon green", "hot pink" ], "exclude_objects": [ "umbrellas", "modern cars", "trash cans" ] } }}
{ "title": "Manhattan Mirage", "description": "A high-octane, cinematic moment capturing a woman's confident stride through a steam-filled New York intersection during golden hour.", "prompt": "You will perform an image edit using the provided photo. Create an Ultra-Photorealistic image of the female subject. The style is highly detailed, resembling a frame shot on Arri Alexa with a cinematic 1:1 aspect ratio. Apply heavy depth of field to blur the busy background while keeping the subject sharp. Use cinematic lighting with strong backlight. The subject is wearing a red mini skirt and is walking on the street.", "details": { "year": "1999", "genre": "Cinematic Photorealism", "location": "A gritty, bustling New York City intersection at sunset, with steam rising from manholes and blurred yellow taxis in the background.", "lighting": [ "Golden hour backlight", "Lens flares", "High contrast volumetric lighting" ], "camera_angle": "Low-angle tracking shot, centered composition.", "emotion": [ "Confident", "Empowered", "Aloof" ], "color_palette": [ "Crimson red", "Asphalt grey", "Golden yellow", "Deep black" ], "atmosphere": [ "Urban", "Dynamic", "Cinematic", "Energetic" ], "environmental_elements": "Steam plumes rising from the ground, motion-blurred traffic, flying pigeons, wet pavement reflecting the sunset.", "subject1": { "costume": "red mini skirt", "subject_expression": "A fierce, confident gaze with slightly parted lips, perhaps wearing vintage sunglasses.", "subject_action": "walking on the street" }, "negative_prompt": { "exclude_visuals": [ "empty streets", "studio background", "overexposed sky", "static pose" ], "exclude_styles": [ "cartoon", "3D render", "illustration", "anime", "sketch" ], "exclude_colors": [ "neon green", "pastel pink" ], "exclude_objects": [ "smartphones", "modern cars", "futuristic gadgets" ] } }}
{ "title": "The Glass Doppelgänger", "description": "A high-octane psychological thriller scene where a woman is engaged in a visceral physical combat with her own sentient reflection emerging from a shattered surface.", "prompt": "You will perform an image edit using the provided photo to create a high-budget movie frame. The scene features the subject in a fierce life-or-death struggle against a supernatural mirror entity. The image must be Ultra-Photorealistic, utilizing cinematic lighting and highly detailed textures. The style is that of a blockbuster film, shot on Arri Alexa with a shallow depth of field to emphasize the intensity. Ensure realistic physics for the flying glass shards.", "details": { "year": "2025", "genre": "Cinematic Photorealism", "location": "A derelict, neon-lit dressing room with peeling wallpaper and a wall-sized vanity mirror that is shattering outwards.", "lighting": [ "Volumetric stage lighting from above", "Flickering fluorescent buzz", "Dramatic rim lighting highlighting sweat and glass texture" ], "camera_angle": "Dynamic low-angle medium shot, slightly Dutch tilted to enhance the chaos.", "emotion": [ "Ferocity", "Desperation", "Adrenaline" ], "color_palette": [ "Electric cyan", "Gritty concrete grey", "Deep shadowy blacks", "Metallic silver" ], "atmosphere": [ "Violent", "Surreal", "Claustrophobic", "Kinetic" ], "environmental_elements": "Thousands of micro-shards of glass suspended in the air (bullet-time effect), dust motes dancing in the light beams, overturned furniture.", "subject1": { "costume": "crop top, mini skirt", "subject_expression": "A primal scream of exertion, eyes wide with intensity.", "subject_action": "fighting with mirror" }, "negative_prompt": { "exclude_visuals": [ "cartoonish effects", "low resolution", "blurry textures", "static pose", "calm demeanor" ], "exclude_styles": [ "3D render", "illustration", "painting", "anime" ], "exclude_colors": [ "pastel pinks", "sunshine yellow" ], "exclude_objects": [ "magical glowing orbs", "wands", "animals" ] } }}
{ "title": "Phantom Strike", "description": "An intense, high-octane action shot of a lone warrior battling supernatural entities in a decayed industrial setting.", "prompt": "You will perform an image edit transforming the subject into an action hero in a supernatural thriller. The image must be photorealistic, highly detailed, and emulate a frame shot on Arri Alexa with cinematic lighting and a shallow depth of field. The scene depicts the female subject in a derelict, flooded subway tunnel, engaged in mortal combat. She is fighting with shadows that seem to manifest as physical, smoky tendrils extending from the darkness. The lighting is dramatic, highlighting the texture of her skin and the splashing water.", "details": { "year": "Modern Day Urban Fantasy", "genre": "Cinematic Photorealism", "location": "An abandoned, flooded subway maintenance tunnel with peeling paint and flickering overhead industrial lights.", "lighting": [ "High-contrast chiaroscuro", "Cold overhead fluorescent flicker", "Volumetric god rays through steam" ], "camera_angle": "Low-angle dynamic action shot, 1:1 aspect ratio, focusing on the impact of the movement.", "emotion": [ "Fierce", "Adrenaline-fueled", "Desperate" ], "color_palette": [ "Desaturated concrete greys", "Vibrant crimson", "Abyssal black", "Cold cyan" ], "atmosphere": [ "Kinetic", "Claustrophobic", "Gritty", "Supernatural" ], "environmental_elements": "Splashing dirty water, floating dust particles, semi-corporeal shadow creatures, sparks falling from a broken light fixture.", "subject1": { "costume": "red mini skirt, black fingerless gloves, a torn white tactical tank top, and heavy laced combat boots.", "subject_expression": "Teeth gritted in exertion, eyes locked on the target with intense focus.", "subject_action": "fighting with shadows" }, "negative_prompt": { "exclude_visuals": [ "sunlight", "blue skies", "static poses", "smiling", "cleanliness" ], "exclude_styles": [ "cartoon", "anime", "3D render", "oil painting", "sketch" ], "exclude_colors": [ "pastel pink", "warm orange", "spring green" ], "exclude_objects": [ "guns", "swords", "modern vehicles", "bystanders" ] } }}
{ "title": "Terminal Velocity", "description": "A high-stakes action frame capturing a woman sprinting through a crumbling industrial tunnel amidst sparks and chaos.", "prompt": "You will perform an image edit to create an Ultra-Photorealistic, Movie-Quality action shot. The result must be photorealistic, highly detailed, and feature cinematic lighting. Emulate the look of a blockbuster film shot on Arri Alexa with a shallow depth of field. Depict Subject 1 sprinting towards the camera in a dark, collapsing industrial tunnel, surrounded by flying sparks and falling debris.", "details": { "year": "Contemporary Action Thriller", "genre": "Cinematic Photorealism", "location": "A dilapidated, steam-filled industrial maintenance tunnel with flickering lights and exposed wiring.", "lighting": [ "High-contrast chiaroscuro", "Warm backlight from exploding sparks", "Cold, gritty fluorescent ambient light", "Volumetric lighting through steam" ], "camera_angle": "Low-angle frontal tracking shot with motion blur on the background.", "emotion": [ "Adrenaline", "Panic", "Determination" ], "color_palette": [ "Concrete grey", "Hazard orange", "Steel blue", "Deep shadow black" ], "atmosphere": [ "Chaotic", "Explosive", "Gritty", "Claustrophobic" ], "environmental_elements": "Cascading electrical sparks, motion-blurred debris, steam venting from broken pipes, wet concrete floor reflecting the chaos.", "subject1": { "costume": "black mini skirt, white crop top, leather fingerless gloves", "subject_expression": "Intense focus with mouth slightly parted in exertion, sweat glistening on skin, hair flying back.", "subject_action": "running" }, "negative_prompt": { "exclude_visuals": [ "sunlight", "calm environment", "clean surfaces", "smiling", "standing still" ], "exclude_styles": [ "cartoon", "3d render", "illustration", "sketch", "low resolution" ], "exclude_colors": [ "pastel pink", "vibrant green", "soft colors" ], "exclude_objects": [ "trees", "sky", "animals", "vehicles" ] } }}
{ "title": "Alpine Freefall", "description": "A high-octane, wide-angle action shot capturing the exhilarating rush of a freestyle skier mid-descent on a steep mountain peak.", "prompt": "You will perform an image edit using the person from the provided photo as the main subject. Preserve her core likeness. Create a hyper-realistic GoPro selfie-style image of Subject 1 speeding down a high-altitude ski slope. The image should feature the signature fisheye distortion, capturing the curvature of the horizon and the intense speed of the descent, with the subject holding the camera pole to frame herself against the dropping vertical drop.", "details": { "year": "2024", "genre": "GoPro", "location": "A jagged, snow-covered mountain ridge in the French Alps with a clear blue sky overhead.", "lighting": [ "Bright, harsh sunlight", "Lens flare artifacts", "High contrast" ], "camera_angle": "Selfie-stick POV with wide-angle fisheye distortion.", "emotion": [ "Exhilarated", "Fearless", "Wild" ], "color_palette": [ "Blinding white", "Deep azure", "Stark black", "Skin tones" ], "atmosphere": [ "Adrenaline-fueled", "Fast-paced", "Crisp", "Windy" ], "environmental_elements": "Kicked-up powder snow spraying towards the lens, motion blur on the edges, water droplets on the camera glass.", "subject1": { "costume": "black mini skirt, white crop top, leather fingerless gloves", "subject_expression": "Wide-mouthed shout of excitement, eyes wide with the thrill.", "subject_action": "ski" }, "negative_prompt": { "exclude_visuals": [ "studio lighting", "calm", "static pose", "indoor settings", "trees" ], "exclude_styles": [ "oil painting", "sketch", "warm vintage", "soft focus" ], "exclude_colors": [ "sepia", "muted tones", "pastel" ], "exclude_objects": [ "ski lift", "crowd", "buildings" ] } }}
# COMPREHENSIVE TYPESCRIPT CODEBASE REVIEWYou are an expert TypeScript code reviewer with 20+ years of experience in enterprise software development, security auditing, and performance optimization. Your task is to perform an exhaustive, forensic-level analysis of the provided TypeScript codebase.## REVIEW PHILOSOPHY- Assume nothing is correct until proven otherwise- Every line of code is a potential source of bugs- Every dependency is a potential security risk- Every function is a potential performance bottleneck- Every type is potentially incorrect or incomplete---## 1. TYPE SYSTEM ANALYSIS### 1.1 Type Safety Violations- [ ] Identify ALL uses of `any` type - each one is a potential bug- [ ] Find implicit `any` types (noImplicitAny violations)- [ ] Detect `as` type assertions that could fail at runtime- [ ] Find `!` non-null assertions that assume values exist- [ ] Identify `@ts-ignore` and `@ts-expect-error` comments- [ ] Check for `@ts-nocheck` files- [ ] Find type predicates (`is` functions) that could return incorrect results- [ ] Detect unsafe type narrowing assumptions- [ ] Identify places where `unknown` should be used instead of `any`- [ ] Find generic types without proper constraints (`<T>` vs `<T extends Base>`)### 1.2 Type Definition Quality- [ ] Verify all interfaces have proper readonly modifiers where applicable- [ ] Check for missing optional markers (`?`) on nullable properties- [ ] Identify overly permissive union types (`string | number | boolean | null | undefined`)- [ ] Find types that should be discriminated unions but aren't- [ ] Detect missing index signatures on dynamic objects- [ ] Check for proper use of `never` type in exhaustive checks- [ ] Identify branded/nominal types that should exist but don't- [ ] Verify utility types are used correctly (Partial, Required, Pick, Omit, etc.)- [ ] Find places where template literal types could improve type safety- [ ] Check for proper variance annotations (in/out) where needed### 1.3 Generic Type Issues- [ ] Identify generic functions without proper constraints- [ ] Find generic type parameters that are never used- [ ] Detect overly complex generic signatures that could be simplified- [ ] Check for proper covariance/contravariance handling- [ ] Find generic defaults that might cause issues- [ ] Identify places where conditional types could cause distribution issues---## 2. NULL/UNDEFINED HANDLING### 2.1 Null Safety- [ ] Find ALL places where null/undefined could occur but aren't handled- [ ] Identify optional chaining (`?.`) that should have fallback values- [ ] Detect nullish coalescing (`??`) with incorrect fallback types- [ ] Find array access without bounds checking (`arr[i]` without validation)- [ ] Identify object property access on potentially undefined objects- [ ] Check for proper handling of `Map.get()` return values (undefined)- [ ] Find `JSON.parse()` calls without null checks- [ ] Detect `document.querySelector()` without null handling- [ ] Identify `Array.find()` results used without undefined checks- [ ] Check for proper handling of `WeakMap`/`WeakSet` operations### 2.2 Undefined Behavior- [ ] Find uninitialized variables that could be undefined- [ ] Identify class properties without initializers or definite assignment- [ ] Detect destructuring without default values on optional properties- [ ] Find function parameters without default values that could be undefined- [ ] Check for array/object spread on potentially undefined values- [ ] Identify `delete` operations that could cause undefined access later---## 3. ERROR HANDLING ANALYSIS### 3.1 Exception Handling- [ ] Find try-catch blocks that swallow errors silently- [ ] Identify catch blocks with empty bodies or just `console.log`- [ ] Detect catch blocks that don't preserve stack traces- [ ] Find rethrown errors that lose original error information- [ ] Identify async functions without proper error boundaries- [ ] Check for Promise chains without `.catch()` handlers- [ ] Find `Promise.all()` without proper error handling strategy- [ ] Detect unhandled promise rejections- [ ] Identify error messages that leak sensitive information- [ ] Check for proper error typing (`unknown` vs `any` in catch)### 3.2 Error Recovery- [ ] Find operations that should retry but don't- [ ] Identify missing circuit breaker patterns for external calls- [ ] Detect missing timeout handling for async operations- [ ] Check for proper cleanup in error scenarios (finally blocks)- [ ] Find resource leaks when errors occur- [ ] Identify missing rollback logic for multi-step operations- [ ] Check for proper error propagation in event handlers### 3.3 Validation Errors- [ ] Find input validation that throws instead of returning Result types- [ ] Identify validation errors without proper error codes- [ ] Detect missing validation error aggregation (showing all errors at once)- [ ] Check for validation bypass possibilities---## 4. ASYNC/AWAIT & CONCURRENCY### 4.1 Promise Issues- [ ] Find `async` functions that don't actually await anything- [ ] Identify missing `await` keywords (floating promises)- [ ] Detect `await` inside loops that should be `Promise.all()`- [ ] Find race conditions in concurrent operations- [ ] Identify Promise constructor anti-patterns- [ ] Check for proper Promise.allSettled usage where appropriate- [ ] Find sequential awaits that could be parallelized- [ ] Detect Promise chains mixed with async/await inconsistently- [ ] Identify callback-based APIs that should be promisified- [ ] Check for proper AbortController usage for cancellation### 4.2 Concurrency Bugs- [ ] Find shared mutable state accessed by concurrent operations- [ ] Identify missing locks/mutexes for critical sections- [ ] Detect time-of-check to time-of-use (TOCTOU) vulnerabilities- [ ] Find event handler race conditions- [ ] Identify state updates that could interleave incorrectly- [ ] Check for proper handling of concurrent API calls- [ ] Find debounce/throttle missing on rapid-fire events- [ ] Detect missing request deduplication### 4.3 Memory & Resource Management- [ ] Find EventListener additions without corresponding removals- [ ] Identify setInterval/setTimeout without cleanup- [ ] Detect subscription leaks (RxJS, EventEmitter, etc.)- [ ] Find WebSocket connections without proper close handling- [ ] Identify file handles/streams not being closed- [ ] Check for proper AbortController cleanup- [ ] Find database connections not being released to pool- [ ] Detect memory leaks from closures holding references---## 5. SECURITY VULNERABILITIES### 5.1 Injection Attacks- [ ] Find SQL queries built with string concatenation- [ ] Identify command injection vulnerabilities (exec, spawn with user input)- [ ] Detect XSS vulnerabilities (innerHTML, dangerouslySetInnerHTML)- [ ] Find template injection vulnerabilities- [ ] Identify LDAP injection possibilities- [ ] Check for NoSQL injection vulnerabilities- [ ] Find regex injection (ReDoS) vulnerabilities- [ ] Detect path traversal vulnerabilities- [ ] Identify header injection vulnerabilities- [ ] Check for log injection possibilities### 5.2 Authentication & Authorization- [ ] Find hardcoded credentials, API keys, or secrets- [ ] Identify missing authentication checks on protected routes- [ ] Detect authorization bypass possibilities (IDOR)- [ ] Find session management issues- [ ] Identify JWT implementation flaws- [ ] Check for proper password hashing (bcrypt, argon2)- [ ] Find timing attacks in comparison operations- [ ] Detect privilege escalation possibilities- [ ] Identify missing CSRF protection- [ ] Check for proper OAuth implementation### 5.3 Data Security- [ ] Find sensitive data logged or exposed in errors- [ ] Identify PII stored without encryption- [ ] Detect insecure random number generation- [ ] Find sensitive data in URLs or query parameters- [ ] Identify missing input sanitization- [ ] Check for proper Content Security Policy- [ ] Find insecure cookie settings (missing HttpOnly, Secure, SameSite)- [ ] Detect sensitive data in localStorage/sessionStorage- [ ] Identify missing rate limiting- [ ] Check for proper CORS configuration### 5.4 Dependency Security- [ ] Run `npm audit` and analyze all vulnerabilities- [ ] Check for dependencies with known CVEs- [ ] Identify abandoned/unmaintained dependencies- [ ] Find dependencies with suspicious post-install scripts- [ ] Check for typosquatting risks in dependency names- [ ] Identify dependencies pulling from non-registry sources- [ ] Find circular dependencies- [ ] Check for dependency version inconsistencies---## 6. PERFORMANCE ANALYSIS### 6.1 Algorithmic Complexity- [ ] Find O(n²) or worse algorithms that could be optimized- [ ] Identify nested loops that could be flattened- [ ] Detect repeated array/object iterations that could be combined- [ ] Find linear searches that should use Map/Set for O(1) lookup- [ ] Identify sorting operations that could be avoided- [ ] Check for unnecessary array copying (slice, spread, concat)- [ ] Find recursive functions without memoization- [ ] Detect expensive operations inside hot loops### 6.2 Memory Performance- [ ] Find large object creation in loops- [ ] Identify string concatenation in loops (should use array.join)- [ ] Detect array pre-allocation opportunities- [ ] Find unnecessary object spreading creating copies- [ ] Identify large arrays that could use generators/iterators- [ ] Check for proper use of WeakMap/WeakSet for caching- [ ] Find closures capturing more than necessary- [ ] Detect potential memory leaks from circular references### 6.3 Runtime Performance- [ ] Find synchronous file operations (fs.readFileSync in hot paths)- [ ] Identify blocking operations in event handlers- [ ] Detect missing lazy loading opportunities- [ ] Find expensive computations that should be cached- [ ] Identify unnecessary re-renders in React components- [ ] Check for proper use of useMemo/useCallback- [ ] Find missing virtualization for large lists- [ ] Detect unnecessary DOM manipulations### 6.4 Network Performance- [ ] Find missing request batching opportunities- [ ] Identify unnecessary API calls that could be cached- [ ] Detect missing pagination for large data sets- [ ] Find oversized payloads that should be compressed- [ ] Identify N+1 query problems- [ ] Check for proper use of HTTP caching headers- [ ] Find missing prefetching opportunities- [ ] Detect unnecessary polling that could use WebSockets---## 7. CODE QUALITY ISSUES### 7.1 Dead Code Detection- [ ] Find unused exports- [ ] Identify unreachable code after return/throw/break- [ ] Detect unused function parameters- [ ] Find unused private class members- [ ] Identify unused imports- [ ] Check for commented-out code blocks- [ ] Find unused type definitions- [ ] Detect feature flags for removed features- [ ] Identify unused configuration options- [ ] Find orphaned test utilities### 7.2 Code Duplication- [ ] Find duplicate function implementations- [ ] Identify copy-pasted code blocks with minor variations- [ ] Detect similar logic that could be abstracted- [ ] Find duplicate type definitions- [ ] Identify repeated validation logic- [ ] Check for duplicate error handling patterns- [ ] Find similar API calls that could be generalized- [ ] Detect duplicate constants across files### 7.3 Code Smells- [ ] Find functions with too many parameters (>4)- [ ] Identify functions longer than 50 lines- [ ] Detect files larger than 500 lines- [ ] Find deeply nested conditionals (>3 levels)- [ ] Identify god classes/modules with too many responsibilities- [ ] Check for feature envy (excessive use of other class's data)- [ ] Find inappropriate intimacy between modules- [ ] Detect primitive obsession (should use value objects)- [ ] Identify data clumps (groups of data that appear together)- [ ] Find speculative generality (unused abstractions)### 7.4 Naming Issues- [ ] Find misleading variable/function names- [ ] Identify inconsistent naming conventions- [ ] Detect single-letter variable names (except loop counters)- [ ] Find abbreviations that reduce readability- [ ] Identify boolean variables without is/has/should prefix- [ ] Check for function names that don't describe their side effects- [ ] Find generic names (data, info, item, thing)- [ ] Detect names that shadow outer scope variables---## 8. ARCHITECTURE & DESIGN### 8.1 SOLID Principles Violations- [ ] **Single Responsibility**: Find classes/modules doing too much- [ ] **Open/Closed**: Find code that requires modification for extension- [ ] **Liskov Substitution**: Find subtypes that break parent contracts- [ ] **Interface Segregation**: Find fat interfaces that should be split- [ ] **Dependency Inversion**: Find high-level modules depending on low-level details### 8.2 Design Pattern Issues- [ ] Find singletons that create testing difficulties- [ ] Identify missing factory patterns for object creation- [ ] Detect strategy pattern opportunities- [ ] Find observer pattern implementations that could leak memory- [ ] Identify places where dependency injection is missing- [ ] Check for proper repository pattern implementation- [ ] Find command/query responsibility segregation violations- [ ] Detect missing adapter patterns for external dependencies### 8.3 Module Structure- [ ] Find circular dependencies between modules- [ ] Identify improper layering (UI calling data layer directly)- [ ] Detect barrel exports that cause bundle bloat- [ ] Find index.ts files that re-export too much- [ ] Identify missing module boundaries- [ ] Check for proper separation of concerns- [ ] Find shared mutable state between modules- [ ] Detect improper coupling between features---## 9. DEPENDENCY ANALYSIS### 9.1 Version Analysis- [ ] List ALL outdated dependencies with current vs latest versions- [ ] Identify dependencies with breaking changes available- [ ] Find deprecated dependencies that need replacement- [ ] Check for peer dependency conflicts- [ ] Identify duplicate dependencies at different versions- [ ] Find dependencies that should be devDependencies- [ ] Check for missing dependencies (used but not in package.json)- [ ] Identify phantom dependencies (using transitive deps directly)### 9.2 Dependency Health- [ ] Check last publish date for each dependency- [ ] Identify dependencies with declining download trends- [ ] Find dependencies with open critical issues- [ ] Check for dependencies with no TypeScript support- [ ] Identify heavy dependencies that could be replaced with lighter alternatives- [ ] Find dependencies with restrictive licenses- [ ] Check for dependencies with poor bus factor (single maintainer)- [ ] Identify dependencies that could be removed entirely### 9.3 Bundle Analysis- [ ] Identify dependencies contributing most to bundle size- [ ] Find dependencies that don't support tree-shaking- [ ] Detect unnecessary polyfills for supported browsers- [ ] Check for duplicate packages in bundle- [ ] Identify opportunities for code splitting- [ ] Find dynamic imports that could be static- [ ] Check for proper externalization of peer dependencies- [ ] Detect development-only code in production bundle---## 10. TESTING GAPS### 10.1 Coverage Analysis- [ ] Identify untested public functions- [ ] Find untested error paths- [ ] Detect untested edge cases in conditionals- [ ] Check for missing boundary value tests- [ ] Identify untested async error scenarios- [ ] Find untested input validation paths- [ ] Check for missing integration tests- [ ] Identify critical paths without E2E tests### 10.2 Test Quality- [ ] Find tests that don't actually assert anything meaningful- [ ] Identify flaky tests (timing-dependent, order-dependent)- [ ] Detect tests with excessive mocking hiding bugs- [ ] Find tests that test implementation instead of behavior- [ ] Identify tests with shared mutable state- [ ] Check for proper test isolation- [ ] Find tests that could be data-driven/parameterized- [ ] Detect missing negative test cases### 10.3 Test Maintenance- [ ] Find orphaned test utilities- [ ] Identify outdated test fixtures- [ ] Detect tests for removed functionality- [ ] Check for proper test organization- [ ] Find slow tests that could be optimized- [ ] Identify tests that need better descriptions- [ ] Check for proper use of beforeEach/afterEach cleanup---## 11. CONFIGURATION & ENVIRONMENT### 11.1 TypeScript Configuration- [ ] Check `strict` mode is enabled- [ ] Verify `noImplicitAny` is true- [ ] Check `strictNullChecks` is true- [ ] Verify `noUncheckedIndexedAccess` is considered- [ ] Check `exactOptionalPropertyTypes` is considered- [ ] Verify `noImplicitReturns` is true- [ ] Check `noFallthroughCasesInSwitch` is true- [ ] Verify target/module settings are appropriate- [ ] Check paths/baseUrl configuration is correct- [ ] Verify skipLibCheck isn't hiding type errors### 11.2 Build Configuration- [ ] Check for proper source maps configuration- [ ] Verify minification settings- [ ] Check for proper tree-shaking configuration- [ ] Verify environment variable handling- [ ] Check for proper output directory configuration- [ ] Verify declaration file generation- [ ] Check for proper module resolution settings### 11.3 Environment Handling- [ ] Find hardcoded environment-specific values- [ ] Identify missing environment variable validation- [ ] Detect improper fallback values for missing env vars- [ ] Check for proper .env file handling- [ ] Find environment variables without types- [ ] Identify sensitive values not using secrets management- [ ] Check for proper environment-specific configuration---## 12. DOCUMENTATION GAPS### 12.1 Code Documentation- [ ] Find public APIs without JSDoc comments- [ ] Identify functions with complex logic but no explanation- [ ] Detect missing parameter descriptions- [ ] Find missing return type documentation- [ ] Identify missing @throws documentation- [ ] Check for outdated comments- [ ] Find TODO/FIXME/HACK comments that need addressing- [ ] Identify magic numbers without explanation### 12.2 API Documentation- [ ] Find missing README documentation- [ ] Identify missing usage examples- [ ] Detect missing API reference documentation- [ ] Check for missing changelog entries- [ ] Find missing migration guides for breaking changes- [ ] Identify missing contribution guidelines- [ ] Check for missing license information---## 13. EDGE CASES CHECKLIST### 13.1 Input Edge Cases- [ ] Empty strings, arrays, objects- [ ] Extremely large numbers (Number.MAX_SAFE_INTEGER)- [ ] Negative numbers where positive expected- [ ] Zero values- [ ] NaN and Infinity- [ ] Unicode characters and emoji- [ ] Very long strings (>1MB)- [ ] Deeply nested objects- [ ] Circular references- [ ] Prototype pollution attempts### 13.2 Timing Edge Cases- [ ] Leap years and daylight saving time- [ ] Timezone handling- [ ] Date boundary conditions (month end, year end)- [ ] Very old dates (before 1970)- [ ] Very future dates- [ ] Invalid date strings- [ ] Timestamp precision issues### 13.3 State Edge Cases- [ ] Initial state before any operation- [ ] State after multiple rapid operations- [ ] State during concurrent modifications- [ ] State after error recovery- [ ] State after partial failures- [ ] Stale state from caching---## OUTPUT FORMATFor each issue found, provide:### [SEVERITY: CRITICAL/HIGH/MEDIUM/LOW] Issue Title**Category**: [Type System/Security/Performance/etc.]**File**: path/to/file.ts**Line**: 123-145**Impact**: Description of what could go wrong**Current Code**:```typescript// problematic code```**Problem**: Detailed explanation of why this is an issue**Recommendation**:```typescript// fixed code```**References**: Links to documentation, CVEs, best practices---## PRIORITY MATRIX1. **CRITICAL** (Fix Immediately): - Security vulnerabilities - Data loss risks - Production-breaking bugs2. **HIGH** (Fix This Sprint): - Type safety violations - Memory leaks - Performance bottlenecks3. **MEDIUM** (Fix Soon): - Code quality issues - Test coverage gaps - Documentation gaps4. **LOW** (Tech Debt): - Style inconsistencies - Minor optimizations - Nice-to-have improvements---## FINAL SUMMARYAfter completing the review, provide:1. **Executive Summary**: 2-3 paragraphs overview2. **Risk Assessment**: Overall risk level with justification3. **Top 10 Critical Issues**: Prioritized list4. **Recommended Action Plan**: Phased approach to fixes5. **Estimated Effort**: Time estimates for remediation6. **Metrics**: - Total issues found by severity - Code health score (1-10) - Security score (1-10) - Maintainability score (1-10)
# COMPREHENSIVE PHP CODEBASE REVIEWYou are an expert PHP code reviewer with 20+ years of experience in enterprise web development, security auditing, performance optimization, and legacy system modernization. Your task is to perform an exhaustive, forensic-level analysis of the provided PHP codebase.## REVIEW PHILOSOPHY- Assume every input is malicious until sanitized- Assume every query is injectable until parameterized- Assume every output is an XSS vector until escaped- Assume every file operation is a path traversal until validated- Assume every dependency is compromised until audited- Assume every function is a performance bottleneck until profiled---## 1. TYPE SYSTEM ANALYSIS (PHP 7.4+/8.x)### 1.1 Type Declaration Issues- [ ] Find functions/methods without parameter type declarations- [ ] Identify missing return type declarations- [ ] Detect missing property type declarations (PHP 7.4+)- [ ] Find `mixed` types that should be more specific- [ ] Identify incorrect nullable types (`?Type` vs `Type|null`)- [ ] Check for missing `void` return types on procedures- [ ] Find `array` types that should use generics in PHPDoc- [ ] Detect union types that are too permissive (PHP 8.0+)- [ ] Identify intersection types opportunities (PHP 8.1+)- [ ] Check for proper `never` return type usage (PHP 8.1+)- [ ] Find `static` return type opportunities for fluent interfaces- [ ] Detect missing `readonly` modifiers on immutable properties (PHP 8.1+)- [ ] Identify `readonly` classes opportunities (PHP 8.2+)- [ ] Check for proper enum usage instead of constants (PHP 8.1+)### 1.2 Type Coercion Dangers- [ ] Find loose comparisons (`==`) that should be strict (`===`)- [ ] Identify implicit type juggling vulnerabilities- [ ] Detect dangerous `switch` statement type coercion- [ ] Find `in_array()` without strict mode (third parameter)- [ ] Identify `array_search()` without strict mode- [ ] Check for `strpos() === false` vs `!== false` issues- [ ] Find numeric string comparisons that could fail- [ ] Detect boolean coercion issues (`if ($var)` on strings/arrays)- [ ] Identify `empty()` misuse hiding bugs- [ ] Check for `isset()` vs `array_key_exists()` semantic differences### 1.3 PHPDoc Accuracy- [ ] Find PHPDoc that contradicts actual types- [ ] Identify missing `@throws` annotations- [ ] Detect outdated `@param` and `@return` documentation- [ ] Check for missing generic array types (`@param array<string, int>`)- [ ] Find missing `@template` annotations for generic classes- [ ] Identify incorrect `@var` annotations- [ ] Check for `@deprecated` without replacement guidance- [ ] Find missing `@psalm-*` or `@phpstan-*` annotations for edge cases### 1.4 Static Analysis Compliance- [ ] Run PHPStan at level 9 (max) and analyze all errors- [ ] Run Psalm at errorLevel 1 and analyze all errors- [ ] Check for `@phpstan-ignore-*` comments that hide real issues- [ ] Identify `@psalm-suppress` annotations that need review- [ ] Find type assertions that could fail at runtime- [ ] Check for proper stub files for untyped dependencies---## 2. NULL SAFETY & ERROR HANDLING### 2.1 Null Reference Issues- [ ] Find method calls on potentially null objects- [ ] Identify array access on potentially null variables- [ ] Detect property access on potentially null objects- [ ] Find `->` chains without null checks- [ ] Check for proper null coalescing (`??`) usage- [ ] Identify nullsafe operator (`?->`) opportunities (PHP 8.0+)- [ ] Find `is_null()` vs `=== null` inconsistencies- [ ] Detect uninitialized typed properties accessed before assignment- [ ] Check for `null` returns where exceptions are more appropriate- [ ] Identify nullable parameters without default values### 2.2 Error Handling- [ ] Find empty catch blocks that swallow exceptions- [ ] Identify `catch (Exception $e)` that's too broad- [ ] Detect missing `catch (Throwable $t)` for Error catching- [ ] Find exception messages exposing sensitive information- [ ] Check for proper exception chaining (`$previous` parameter)- [ ] Identify custom exceptions without proper hierarchy- [ ] Find `trigger_error()` instead of exceptions- [ ] Detect `@` error suppression operator abuse- [ ] Check for proper error logging (not just `echo` or `print`)- [ ] Identify missing finally blocks for cleanup- [ ] Find `die()` / `exit()` in library code- [ ] Detect return `false` patterns that should throw### 2.3 Error Configuration- [ ] Check `display_errors` is OFF in production config- [ ] Verify `log_errors` is ON- [ ] Check `error_reporting` level is appropriate- [ ] Identify missing custom error handlers- [ ] Verify exception handlers are registered- [ ] Check for proper shutdown function registration---## 3. SECURITY VULNERABILITIES### 3.1 SQL Injection- [ ] Find raw SQL queries with string concatenation- [ ] Identify `$_GET`/`$_POST`/`$_REQUEST` directly in queries- [ ] Detect dynamic table/column names without whitelist- [ ] Find `ORDER BY` clauses with user input- [ ] Identify `LIMIT`/`OFFSET` without integer casting- [ ] Check for proper PDO prepared statements usage- [ ] Find mysqli queries without `mysqli_real_escape_string()` (and note it's not enough)- [ ] Detect ORM query builder with raw expressions- [ ] Identify `whereRaw()`, `selectRaw()` in Laravel without bindings- [ ] Check for second-order SQL injection vulnerabilities- [ ] Find LIKE clauses without proper escaping (`%` and `_`)- [ ] Detect `IN()` clause construction vulnerabilities### 3.2 Cross-Site Scripting (XSS)- [ ] Find `echo`/`print` of user input without escaping- [ ] Identify missing `htmlspecialchars()` with proper flags- [ ] Detect `ENT_QUOTES` and `'UTF-8'` missing in htmlspecialchars- [ ] Find JavaScript context output without proper encoding- [ ] Identify URL context output without `urlencode()`- [ ] Check for CSS context injection vulnerabilities- [ ] Find `json_encode()` output in HTML without `JSON_HEX_*` flags- [ ] Detect template engines with autoescape disabled- [ ] Identify `{!! $var !!}` (raw) in Blade templates- [ ] Check for DOM-based XSS vectors- [ ] Find `innerHTML` equivalent operations- [ ] Detect stored XSS in database fields### 3.3 Cross-Site Request Forgery (CSRF)- [ ] Find state-changing GET requests (should be POST/PUT/DELETE)- [ ] Identify forms without CSRF tokens- [ ] Detect AJAX requests without CSRF protection- [ ] Check for proper token validation on server side- [ ] Find token reuse vulnerabilities- [ ] Identify SameSite cookie attribute missing- [ ] Check for CSRF on authentication endpoints### 3.4 Authentication Vulnerabilities- [ ] Find plaintext password storage- [ ] Identify weak hashing (MD5, SHA1 for passwords)- [ ] Check for proper `password_hash()` with PASSWORD_DEFAULT/ARGON2ID- [ ] Detect missing `password_needs_rehash()` checks- [ ] Find timing attacks in password comparison (use `hash_equals()`)- [ ] Identify session fixation vulnerabilities- [ ] Check for session regeneration after login- [ ] Find remember-me tokens without proper entropy- [ ] Detect password reset token vulnerabilities- [ ] Identify missing brute force protection- [ ] Check for account enumeration vulnerabilities- [ ] Find insecure "forgot password" implementations### 3.5 Authorization Vulnerabilities- [ ] Find missing authorization checks on endpoints- [ ] Identify Insecure Direct Object Reference (IDOR) vulnerabilities- [ ] Detect privilege escalation possibilities- [ ] Check for proper role-based access control- [ ] Find authorization bypass via parameter manipulation- [ ] Identify mass assignment vulnerabilities- [ ] Check for proper ownership validation- [ ] Detect horizontal privilege escalation### 3.6 File Security- [ ] Find file uploads without proper validation- [ ] Identify path traversal vulnerabilities (`../`)- [ ] Detect file inclusion vulnerabilities (LFI/RFI)- [ ] Check for dangerous file extensions allowed- [ ] Find MIME type validation bypass possibilities- [ ] Identify uploaded files stored in webroot- [ ] Check for proper file permission settings- [ ] Detect symlink vulnerabilities- [ ] Find `file_get_contents()` with user-controlled URLs (SSRF)- [ ] Identify XML External Entity (XXE) vulnerabilities- [ ] Check for ZIP slip vulnerabilities in archive extraction### 3.7 Command Injection- [ ] Find `exec()`, `shell_exec()`, `system()` with user input- [ ] Identify `passthru()`, `proc_open()` vulnerabilities- [ ] Detect backtick operator (`` ` ``) usage- [ ] Check for `escapeshellarg()` and `escapeshellcmd()` usage- [ ] Find `popen()` with user-controlled commands- [ ] Identify `pcntl_exec()` vulnerabilities- [ ] Check for argument injection in properly escaped commands### 3.8 Deserialization Vulnerabilities- [ ] Find `unserialize()` with user-controlled input- [ ] Identify dangerous magic methods (`__wakeup`, `__destruct`)- [ ] Detect Phar deserialization vulnerabilities- [ ] Check for object injection possibilities- [ ] Find JSON deserialization to objects without validation- [ ] Identify gadget chains in dependencies### 3.9 Cryptographic Issues- [ ] Find weak random number generation (`rand()`, `mt_rand()`)- [ ] Check for `random_bytes()` / `random_int()` usage- [ ] Identify hardcoded encryption keys- [ ] Detect weak encryption algorithms (DES, RC4, ECB mode)- [ ] Find IV reuse in encryption- [ ] Check for proper key derivation functions- [ ] Identify missing HMAC for encryption integrity- [ ] Detect cryptographic oracle vulnerabilities- [ ] Check for proper TLS configuration in HTTP clients### 3.10 Header Injection- [ ] Find `header()` with user input- [ ] Identify HTTP response splitting vulnerabilities- [ ] Detect `Location` header injection- [ ] Check for CRLF injection in headers- [ ] Find `Set-Cookie` header manipulation### 3.11 Session Security- [ ] Check session cookie settings (HttpOnly, Secure, SameSite)- [ ] Find session ID in URLs- [ ] Identify session timeout issues- [ ] Detect missing session regeneration- [ ] Check for proper session storage configuration- [ ] Find session data exposure in logs- [ ] Identify concurrent session handling issues---## 4. DATABASE INTERACTIONS### 4.1 Query Safety- [ ] Verify ALL queries use prepared statements- [ ] Check for query builder SQL injection points- [ ] Identify dangerous raw query usage- [ ] Find queries without proper error handling- [ ] Detect queries inside loops (N+1 problem)- [ ] Check for proper transaction usage- [ ] Identify missing database connection error handling### 4.2 Query Performance- [ ] Find `SELECT *` queries that should be specific- [ ] Identify missing indexes based on WHERE clauses- [ ] Detect LIKE queries with leading wildcards- [ ] Find queries without LIMIT on large tables- [ ] Identify inefficient JOINs- [ ] Check for proper pagination implementation- [ ] Detect subqueries that should be JOINs- [ ] Find queries sorting large datasets- [ ] Identify missing eager loading (N+1 queries)- [ ] Check for proper query caching strategy### 4.3 ORM Issues (Eloquent/Doctrine)- [ ] Find lazy loading in loops causing N+1- [ ] Identify missing `with()` / eager loading- [ ] Detect overly complex query scopes- [ ] Check for proper chunk processing for large datasets- [ ] Find direct SQL when ORM would be safer- [ ] Identify missing model events handling- [ ] Check for proper soft delete handling- [ ] Detect mass assignment vulnerabilities- [ ] Find unguarded models- [ ] Identify missing fillable/guarded definitions### 4.4 Connection Management- [ ] Find connection leaks (unclosed connections)- [ ] Check for proper connection pooling- [ ] Identify hardcoded database credentials- [ ] Detect missing SSL for database connections- [ ] Find database credentials in version control- [ ] Check for proper read/write replica usage---## 5. INPUT VALIDATION & SANITIZATION### 5.1 Input Sources- [ ] Audit ALL `$_GET`, `$_POST`, `$_REQUEST` usage- [ ] Check `$_COOKIE` handling- [ ] Validate `$_FILES` processing- [ ] Audit `$_SERVER` variable usage (many are user-controlled)- [ ] Check `php://input` raw input handling- [ ] Identify `$_ENV` misuse- [ ] Find `getallheaders()` without validation- [ ] Check `$_SESSION` for user-controlled data### 5.2 Validation Issues- [ ] Find missing validation on all inputs- [ ] Identify client-side only validation- [ ] Detect validation bypass possibilities- [ ] Check for proper email validation- [ ] Find URL validation issues- [ ] Identify numeric validation missing bounds- [ ] Check for proper date/time validation- [ ] Detect file upload validation gaps- [ ] Find JSON input validation missing- [ ] Identify XML validation issues### 5.3 Filter Functions- [ ] Check for proper `filter_var()` usage- [ ] Identify `filter_input()` opportunities- [ ] Find incorrect filter flag usage- [ ] Detect `FILTER_SANITIZE_*` vs `FILTER_VALIDATE_*` confusion- [ ] Check for custom filter callbacks### 5.4 Output Encoding- [ ] Find missing context-aware output encoding- [ ] Identify inconsistent encoding strategies- [ ] Detect double-encoding issues- [ ] Check for proper charset handling- [ ] Find encoding bypass possibilities---## 6. PERFORMANCE ANALYSIS### 6.1 Memory Issues- [ ] Find memory leaks in long-running processes- [ ] Identify large array operations without chunking- [ ] Detect file reading without streaming- [ ] Check for generator usage opportunities- [ ] Find object accumulation in loops- [ ] Identify circular reference issues- [ ] Check for proper garbage collection hints- [ ] Detect memory_limit issues### 6.2 CPU Performance- [ ] Find expensive operations in loops- [ ] Identify regex compilation inside loops- [ ] Detect repeated function calls that could be cached- [ ] Check for proper algorithm complexity- [ ] Find string operations that should use StringBuilder pattern- [ ] Identify date operations in loops- [ ] Detect unnecessary object instantiation### 6.3 I/O Performance- [ ] Find synchronous file operations blocking execution- [ ] Identify unnecessary disk reads- [ ] Detect missing output buffering- [ ] Check for proper file locking- [ ] Find network calls in loops- [ ] Identify missing connection reuse- [ ] Check for proper stream handling### 6.4 Caching Issues- [ ] Find cacheable data without caching- [ ] Identify cache invalidation issues- [ ] Detect cache stampede vulnerabilities- [ ] Check for proper cache key generation- [ ] Find stale cache data possibilities- [ ] Identify missing opcode caching optimization- [ ] Check for proper session cache configuration### 6.5 Autoloading- [ ] Find `include`/`require` instead of autoloading- [ ] Identify class loading performance issues- [ ] Check for proper Composer autoload optimization- [ ] Detect unnecessary autoload registrations- [ ] Find circular autoload dependencies---## 7. ASYNC & CONCURRENCY### 7.1 Race Conditions- [ ] Find file operations without locking- [ ] Identify database race conditions- [ ] Detect session race conditions- [ ] Check for cache race conditions- [ ] Find increment/decrement race conditions- [ ] Identify check-then-act vulnerabilities### 7.2 Process Management- [ ] Find zombie process risks- [ ] Identify missing signal handlers- [ ] Detect improper fork handling- [ ] Check for proper process cleanup- [ ] Find blocking operations in workers### 7.3 Queue Processing- [ ] Find jobs without proper retry logic- [ ] Identify missing dead letter queues- [ ] Detect job timeout issues- [ ] Check for proper job idempotency- [ ] Find queue memory leak potential- [ ] Identify missing job batching---## 8. CODE QUALITY### 8.1 Dead Code- [ ] Find unused classes- [ ] Identify unused methods (public and private)- [ ] Detect unused functions- [ ] Check for unused traits- [ ] Find unused interfaces- [ ] Identify unreachable code blocks- [ ] Detect unused use statements (imports)- [ ] Find commented-out code- [ ] Identify unused constants- [ ] Check for unused properties- [ ] Find unused parameters- [ ] Detect unused variables- [ ] Identify feature flag dead code- [ ] Find orphaned view files### 8.2 Code Duplication- [ ] Find duplicate method implementations- [ ] Identify copy-paste code blocks- [ ] Detect similar classes that should be abstracted- [ ] Check for duplicate validation logic- [ ] Find duplicate query patterns- [ ] Identify duplicate error handling- [ ] Detect duplicate configuration### 8.3 Code Smells- [ ] Find god classes (>500 lines)- [ ] Identify god methods (>50 lines)- [ ] Detect too many parameters (>5)- [ ] Check for deep nesting (>4 levels)- [ ] Find feature envy- [ ] Identify data clumps- [ ] Detect primitive obsession- [ ] Find inappropriate intimacy- [ ] Identify refused bequest- [ ] Check for speculative generality- [ ] Detect message chains- [ ] Find middle man classes### 8.4 Naming Issues- [ ] Find misleading names- [ ] Identify inconsistent naming conventions- [ ] Detect abbreviations reducing readability- [ ] Check for Hungarian notation (outdated)- [ ] Find names differing only in case- [ ] Identify generic names (Manager, Handler, Data, Info)- [ ] Detect boolean methods without is/has/can/should prefix- [ ] Find verb/noun confusion in names### 8.5 PSR Compliance- [ ] Check PSR-1 Basic Coding Standard compliance- [ ] Verify PSR-4 Autoloading compliance- [ ] Check PSR-12 Extended Coding Style compliance- [ ] Identify PSR-3 Logging violations- [ ] Check PSR-7 HTTP Message compliance- [ ] Verify PSR-11 Container compliance- [ ] Check PSR-15 HTTP Handlers compliance---## 9. ARCHITECTURE & DESIGN### 9.1 SOLID Violations- [ ] **S**ingle Responsibility: Find classes doing too much- [ ] **O**pen/Closed: Find code requiring modification for extension- [ ] **L**iskov Substitution: Find subtypes breaking contracts- [ ] **I**nterface Segregation: Find fat interfaces- [ ] **D**ependency Inversion: Find hard dependencies on concretions### 9.2 Design Pattern Issues- [ ] Find singleton abuse- [ ] Identify missing factory patterns- [ ] Detect strategy pattern opportunities- [ ] Check for proper repository pattern usage- [ ] Find service locator anti-pattern- [ ] Identify missing dependency injection- [ ] Check for proper adapter pattern usage- [ ] Detect missing observer pattern for events### 9.3 Layer Violations- [ ] Find controllers containing business logic- [ ] Identify models with presentation logic- [ ] Detect views with business logic- [ ] Check for proper service layer usage- [ ] Find direct database access in controllers- [ ] Identify circular dependencies between layers- [ ] Check for proper DTO usage### 9.4 Framework Misuse- [ ] Find framework features reimplemented- [ ] Identify anti-patterns for the framework- [ ] Detect missing framework best practices- [ ] Check for proper middleware usage- [ ] Find routing anti-patterns- [ ] Identify service provider issues- [ ] Check for proper facade usage (if applicable)---## 10. DEPENDENCY ANALYSIS### 10.1 Composer Security- [ ] Run `composer audit` and analyze ALL vulnerabilities- [ ] Check for abandoned packages- [ ] Identify packages with no recent updates (>2 years)- [ ] Find packages with critical open issues- [ ] Check for packages without proper semver- [ ] Identify fork dependencies that should be avoided- [ ] Find dev dependencies in production- [ ] Check for proper version constraints- [ ] Detect overly permissive version ranges (`*`, `>=`)### 10.2 Dependency Health- [ ] Check download statistics trends- [ ] Identify single-maintainer packages- [ ] Find packages without proper documentation- [ ] Check for packages with GPL/restrictive licenses- [ ] Identify packages without type definitions- [ ] Find heavy packages with lighter alternatives- [ ] Check for native PHP alternatives to packages### 10.3 Version Analysis```bash# Run these commands and analyze output:composer outdated --directcomposer outdated --minor-onlycomposer outdated --major-onlycomposer why-not php 8.3 # Check PHP version compatibility```- [ ] List ALL outdated dependencies- [ ] Identify breaking changes in updates- [ ] Check PHP version compatibility- [ ] Find extension dependencies- [ ] Identify platform requirements issues### 10.4 Autoload Optimization- [ ] Check for `composer dump-autoload --optimize`- [ ] Identify classmap vs PSR-4 performance- [ ] Find unnecessary files in autoload- [ ] Check for proper autoload-dev separation---## 11. TESTING GAPS### 11.1 Coverage Analysis- [ ] Find untested public methods- [ ] Identify untested error paths- [ ] Detect untested edge cases- [ ] Check for missing boundary tests- [ ] Find untested security-critical code- [ ] Identify missing integration tests- [ ] Check for E2E test coverage- [ ] Find untested API endpoints### 11.2 Test Quality- [ ] Find tests without assertions- [ ] Identify tests with multiple concerns- [ ] Detect tests dependent on external services- [ ] Check for proper test isolation- [ ] Find tests with hardcoded dates/times- [ ] Identify flaky tests- [ ] Detect tests with excessive mocking- [ ] Find tests testing implementation### 11.3 Test Organization- [ ] Check for proper test naming- [ ] Identify missing test documentation- [ ] Find orphaned test helpers- [ ] Detect test code duplication- [ ] Check for proper setUp/tearDown usage- [ ] Identify missing data providers---## 12. CONFIGURATION & ENVIRONMENT### 12.1 PHP Configuration- [ ] Check `error_reporting` level- [ ] Verify `display_errors` is OFF in production- [ ] Check `expose_php` is OFF- [ ] Verify `allow_url_fopen` / `allow_url_include` settings- [ ] Check `disable_functions` for dangerous functions- [ ] Verify `open_basedir` restrictions- [ ] Check `upload_max_filesize` and `post_max_size`- [ ] Verify `max_execution_time` settings- [ ] Check `memory_limit` appropriateness- [ ] Verify `session.*` settings are secure- [ ] Check OPcache configuration- [ ] Verify `realpath_cache_size` settings### 12.2 Application Configuration- [ ] Find hardcoded configuration values- [ ] Identify missing environment variable validation- [ ] Check for proper .env handling- [ ] Find secrets in version control- [ ] Detect debug mode in production- [ ] Check for proper config caching- [ ] Identify environment-specific code in source### 12.3 Server Configuration- [ ] Check for index.php as only entry point- [ ] Verify .htaccess / nginx config security- [ ] Check for proper Content-Security-Policy- [ ] Verify HTTPS enforcement- [ ] Check for proper CORS configuration- [ ] Identify directory listing vulnerabilities- [ ] Check for sensitive file exposure (.git, .env, etc.)---## 13. FRAMEWORK-SPECIFIC (LARAVEL)### 13.1 Security- [ ] Check for `$guarded = []` without `$fillable`- [ ] Find `{!! !!}` raw output in Blade- [ ] Identify disabled CSRF for routes- [ ] Check for proper authorization policies- [ ] Find direct model binding without scoping- [ ] Detect missing rate limiting- [ ] Check for proper API authentication### 13.2 Performance- [ ] Find missing eager loading with()- [ ] Identify chunking opportunities for large datasets- [ ] Check for proper queue usage- [ ] Find missing cache usage- [ ] Detect N+1 queries with debugbar- [ ] Check for config:cache and route:cache usage- [ ] Identify view caching opportunities### 13.3 Best Practices- [ ] Find business logic in controllers- [ ] Identify missing form requests- [ ] Check for proper resource usage- [ ] Find direct Eloquent in controllers (should use repositories)- [ ] Detect missing events for side effects- [ ] Check for proper job usage- [ ] Identify missing observers---## 14. FRAMEWORK-SPECIFIC (SYMFONY)### 14.1 Security- [ ] Check security.yaml configuration- [ ] Verify firewall configuration- [ ] Check for proper voter usage- [ ] Identify missing CSRF protection- [ ] Check for parameter injection vulnerabilities- [ ] Verify password encoder configuration### 14.2 Performance- [ ] Check for proper DI container compilation- [ ] Identify missing cache warmup- [ ] Check for autowiring performance- [ ] Find Doctrine hydration issues- [ ] Identify missing Doctrine caching- [ ] Check for proper serializer usage### 14.3 Best Practices- [ ] Find services that should be private- [ ] Identify missing interfaces for services- [ ] Check for proper event dispatcher usage- [ ] Find logic in controllers- [ ] Detect missing DTOs- [ ] Check for proper messenger usage---## 15. API SECURITY### 15.1 Authentication- [ ] Check JWT implementation security- [ ] Verify OAuth implementation- [ ] Check for API key exposure- [ ] Identify missing token expiration- [ ] Find refresh token vulnerabilities- [ ] Check for proper token storage### 15.2 Rate Limiting- [ ] Find endpoints without rate limiting- [ ] Identify bypassable rate limiting- [ ] Check for proper rate limit headers- [ ] Detect DDoS vulnerabilities### 15.3 Input/Output- [ ] Find missing request validation- [ ] Identify excessive data exposure in responses- [ ] Check for proper error responses (no stack traces)- [ ] Detect mass assignment in API- [ ] Find missing pagination limits- [ ] Check for proper HTTP status codes---## 16. EDGE CASES CHECKLIST### 16.1 String Edge Cases- [ ] Empty strings- [ ] Very long strings (>1MB)- [ ] Unicode characters (emoji, RTL, zero-width)- [ ] Null bytes in strings- [ ] Newlines and special characters- [ ] Multi-byte character handling- [ ] String encoding mismatches### 16.2 Numeric Edge Cases- [ ] Zero values- [ ] Negative numbers- [ ] Very large numbers (PHP_INT_MAX)- [ ] Floating point precision issues- [ ] Numeric strings ("123" vs 123)- [ ] Scientific notation- [ ] NAN and INF### 16.3 Array Edge Cases- [ ] Empty arrays- [ ] Single element arrays- [ ] Associative vs indexed arrays- [ ] Sparse arrays (missing keys)- [ ] Deeply nested arrays- [ ] Large arrays (memory)- [ ] Array key type juggling### 16.4 Date/Time Edge Cases- [ ] Timezone handling- [ ] Daylight saving time transitions- [ ] Leap years and February 29- [ ] Month boundaries (31st)- [ ] Year boundaries- [ ] Unix timestamp limits (2038 problem on 32-bit)- [ ] Invalid date strings- [ ] Different date formats### 16.5 File Edge Cases- [ ] Files with spaces in names- [ ] Files with unicode names- [ ] Very long file paths- [ ] Special characters in filenames- [ ] Files with no extension- [ ] Empty files- [ ] Binary files treated as text- [ ] File permission issues### 16.6 HTTP Edge Cases- [ ] Missing headers- [ ] Duplicate headers- [ ] Very large headers- [ ] Invalid content types- [ ] Chunked transfer encoding- [ ] Connection timeouts- [ ] Redirect loops### 16.7 Database Edge Cases- [ ] NULL values in columns- [ ] Empty string vs NULL- [ ] Very long text fields- [ ] Concurrent modifications- [ ] Transaction timeouts- [ ] Connection pool exhaustion- [ ] Character set mismatches---## OUTPUT FORMATFor each issue found, provide:### [SEVERITY: CRITICAL/HIGH/MEDIUM/LOW] Issue Title**Category**: [Security/Performance/Type Safety/etc.]**File**: path/to/file.php**Line**: 123-145**CWE/CVE**: (if applicable)**Impact**: Description of what could go wrong**Current Code**:```php// problematic code```**Problem**: Detailed explanation of why this is an issue**Recommendation**:```php// fixed code```**References**: Links to documentation, OWASP, PHP manual```---## PRIORITY MATRIX1. **CRITICAL** (Fix Within 24 Hours): - SQL Injection - Remote Code Execution - Authentication Bypass - Arbitrary File Upload/Read/Write2. **HIGH** (Fix This Week): - XSS Vulnerabilities - CSRF Issues - Authorization Flaws - Sensitive Data Exposure - Insecure Deserialization3. **MEDIUM** (Fix This Sprint): - Type Safety Issues - Performance Problems - Missing Validation - Configuration Issues4. **LOW** (Technical Debt): - Code Quality Issues - Documentation Gaps - Style Inconsistencies - Minor Optimizations---## AUTOMATED TOOL COMMANDSRun these and include output analysis:```bash# Security Scanningcomposer audit./vendor/bin/phpstan analyse --level=9./vendor/bin/psalm --show-info=true# Code Quality./vendor/bin/phpcs --standard=PSR12./vendor/bin/php-cs-fixer fix --dry-run --diff./vendor/bin/phpmd src text cleancode,codesize,controversial,design,naming,unusedcode# Dependency Analysiscomposer outdated --directcomposer depends --tree# Dead Code Detection./vendor/bin/phpdcd src# Copy-Paste Detection./vendor/bin/phpcpd src# Complexity Analysis./vendor/bin/phpmetrics --report-html=report src```---## FINAL SUMMARYAfter completing the review, provide:1. **Executive Summary**: 2-3 paragraphs overview2. **Risk Assessment**: Overall risk level (Critical/High/Medium/Low)3. **OWASP Top 10 Coverage**: Which vulnerabilities were found4. **Top 10 Critical Issues**: Prioritized list5. **Dependency Health Report**: Summary of package status6. **Technical Debt Estimate**: Hours/days to remediate7. **Recommended Action Plan**: Phased approach8. **Metrics Dashboard**: - Total issues by severity - Security score (1-10) - Code quality score (1-10) - Test coverage percentage - Dependency health score (1-10) - PHP version compatibility status
{ "title": "The Solar Priestess of Amun", "description": "A stunning, stylized portrait of a woman transformed into an Ancient Egyptian priestess, blending photorealism with the texture of tomb paintings.", "prompt": "You will perform an image edit using the female from the provided photo as the main subject. Preserve her core likeness. Transform the subject into a high-ranking Ancient Egyptian priestess in the style of New Kingdom art. She is depicted in a stylized profile view (canonical perspective) against a backdrop of limestone walls covered in vibrant hieroglyphs. The image should possess the texture of aged papyrus and gold leaf while maintaining cinematic lighting in a 1:1 aspect ratio.", "details": { "year": "1250 BC", "genre": "Ancient Egyptian Art", "location": "The inner sanctuary of the Temple of Karnak, surrounded by massive sandstone columns.", "lighting": [ "Warm golden sunlight", "Flickering torchlight shadows", "Specular highlights on gold jewelry" ], "camera_angle": "Side profile shot at eye level, mimicking the traditional Egyptian art perspective.", "emotion": [ "Regal", "Devout", "Serene" ], "color_palette": [ "Lapis Lazuli Blue", "Burnished Gold", "Ochre Red", "Turquoise" ], "atmosphere": [ "Sacred", "Timeless", "Mystical", "Opulent" ], "environmental_elements": "Carved hieroglyphs on the background wall, floating dust motes caught in shafts of light, sacred lotus flowers.", "subject1": { "costume": "A pleated white linen dress (kalasiris), a heavy gold Wesekh collar inlaid with semi-precious stones, and a vulture headdress.", "subject_expression": "A stoic, commanding gaze looking forward.", "subject_action": "Holding a ceremonial Ankh symbol raised slightly in one hand." }, "negative_prompt": { "exclude_visuals": [ "modern fashion", "denim", "digital technology", "cars" ], "exclude_styles": [ "3D render", "anime", "impressionism", "cyberpunk" ], "exclude_colors": [ "neon green", "electric purple" ], "exclude_objects": [ "eyeglasses", "watches", "modern buildings" ] } }}
You are a senior software architect specializing in codebase health and technical debt elimination.Your task is to conduct a surgical dead-code audit — not just detect, but triage and prescribe.────────────────────────────────────────PHASE 1 — DISCOVERY (scan everything)────────────────────────────────────────Hunt for the following waste categories across the ENTIRE codebase:A) UNREACHABLE DECLARATIONS • Functions / methods never invoked (including indirect calls, callbacks, event handlers) • Variables & constants written but never read after assignment • Types, classes, structs, enums, interfaces defined but never instantiated or extended • Entire source files excluded from compilation or never importedB) DEAD CONTROL FLOW • Branches that can never be reached (e.g. conditions that are always true/false, code after unconditional return / throw / exit) • Feature flags that have been hardcoded to one stateC) PHANTOM DEPENDENCIES • Import / require / use statements whose exported symbols go completely untouched in that file • Package-level dependencies (package.json, go.mod, Cargo.toml, etc.) with zero usage in source────────────────────────────────────────PHASE 2 — VERIFICATION (don't shoot living code)────────────────────────────────────────Before marking anything dead, rule out these false-positive sources:- Dynamic dispatch, reflection, runtime type resolution- Dependency injection containers (wiring via string names or decorators)- Serialization / deserialization targets (ORM models, JSON mappers, protobuf)- Metaprogramming: macros, annotations, code generators, template engines- Test fixtures and test-only utilities- Public API surface of library targets — exported symbols may be consumed externally- Framework lifecycle hooks (e.g. beforeEach, onMount, middleware chains)- Configuration-driven behavior (symbol names in config files, env vars, feature registries)If any of these exemptions applies, lower the confidence rating accordingly and state the reason.────────────────────────────────────────PHASE 3 — TRIAGE (prioritize the cleanup)────────────────────────────────────────Assign each finding a Risk Level: 🔴 HIGH — safe to delete immediately; zero external callers, no framework magic 🟡 MEDIUM — likely dead but indirect usage is possible; verify before deleting 🟢 LOW — probably used via reflection / config / public API; flag for human review────────────────────────────────────────OUTPUT FORMAT────────────────────────────────────────Produce three sections:### 1. Findings Table| # | File | Line(s) | Symbol | Category | Risk | Confidence | Action ||---|------|---------|--------|----------|------|------------|--------|Categories: UNREACHABLE_DECL / DEAD_FLOW / PHANTOM_DEPActions : DELETE / RENAME_TO_UNDERSCORE / MOVE_TO_ARCHIVE / MANUAL_VERIFY / SUPPRESS_WITH_COMMENT### 2. Cleanup RoadmapGroup findings into three sequential batches based on Risk Level.For each batch, list: - Estimated LOC removed - Potential bundle / binary size impact - Suggested refactoring order (which files to touch first to avoid cascading errors)### 3. Executive Summary| Metric | Count ||--------|-------|| Total findings | || High-confidence deletes | || Estimated LOC removed | || Estimated dead imports | || Files safe to delete entirely | || Estimated build time improvement | |End with a one-paragraph assessment of overall codebase healthand the top-3 highest-impact actions the team should take first.
# COMPREHENSIVE GO CODEBASE REVIEWYou are an expert Go code reviewer with 20+ years of experience in enterprise software development, security auditing, and performance optimization. Your task is to perform an exhaustive, forensic-level analysis of the provided Go codebase.## REVIEW PHILOSOPHY- Assume nothing is correct until proven otherwise- Every line of code is a potential source of bugs- Every dependency is a potential security risk- Every function is a potential performance bottleneck- Every goroutine is a potential deadlock or race condition- Every error return is potentially mishandled---## 1. TYPE SYSTEM & INTERFACE ANALYSIS### 1.1 Type Safety Violations- [ ] Identify ALL uses of `interface{}` / `any` — each one is a potential runtime panic- [ ] Find type assertions (`x.(Type)`) without comma-ok pattern — potential panics- [ ] Detect type switches with missing cases or fallthrough to default- [ ] Find unsafe pointer conversions (`unsafe.Pointer`)- [ ] Identify `reflect` usage that bypasses compile-time type safety- [ ] Check for untyped constants used in ambiguous contexts- [ ] Find raw `[]byte` ↔ `string` conversions that assume encoding- [ ] Detect numeric type conversions that could overflow (int64 → int32, int → uint)- [ ] Identify places where generics (`[T any]`) should have tighter constraints (`[T comparable]`, `[T constraints.Ordered]`)- [ ] Find `map` access without comma-ok pattern where zero value is meaningful### 1.2 Interface Design Quality- [ ] Find "fat" interfaces that violate Interface Segregation Principle (>3-5 methods)- [ ] Identify interfaces defined at the implementation side (should be at consumer side)- [ ] Detect interfaces that accept concrete types instead of interfaces- [ ] Check for missing `io.Closer` interface implementation where cleanup is needed- [ ] Find interfaces that embed too many other interfaces- [ ] Identify missing `Stringer` (`String() string`) implementations for debug/log types- [ ] Check for proper `error` interface implementations (custom error types)- [ ] Find unexported interfaces that should be exported for extensibility- [ ] Detect interfaces with methods that accept/return concrete types instead of interfaces- [ ] Identify missing `MarshalJSON`/`UnmarshalJSON` for types with custom serialization needs### 1.3 Struct Design Issues- [ ] Find structs with exported fields that should have accessor methods- [ ] Identify struct fields missing `json`, `yaml`, `db` tags- [ ] Detect structs that are not safe for concurrent access but lack documentation- [ ] Check for structs with padding issues (field ordering for memory alignment)- [ ] Find embedded structs that expose unwanted methods- [ ] Identify structs that should implement `sync.Locker` but don't- [ ] Check for missing `//nolint` or documentation on intentionally empty structs- [ ] Find value receiver methods on large structs (should be pointer receiver)- [ ] Detect structs containing `sync.Mutex` passed by value (should be pointer or non-copyable)- [ ] Identify missing struct validation methods (`Validate() error`)### 1.4 Generic Type Issues (Go 1.18+)- [ ] Find generic functions without proper constraints- [ ] Identify generic type parameters that are never used- [ ] Detect overly complex generic signatures that could be simplified- [ ] Check for proper use of `comparable`, `constraints.Ordered` etc.- [ ] Find places where generics are used but interfaces would suffice- [ ] Identify type parameter constraints that are too broad (`any` where narrower works)---## 2. NIL / ZERO VALUE HANDLING### 2.1 Nil Safety- [ ] Find ALL places where nil pointer dereference could occur- [ ] Identify nil slice/map operations that could panic (`map[key]` on nil map writes)- [ ] Detect nil channel operations (send/receive on nil channel blocks forever)- [ ] Find nil function/closure calls without checks- [ ] Identify nil interface comparisons with subtle behavior (`error(nil) != nil`)- [ ] Check for nil receiver methods that don't handle nil gracefully- [ ] Find `*Type` return values without nil documentation- [ ] Detect places where `new()` is used but `&Type{}` is clearer- [ ] Identify typed nil interface issues (assigning `(*T)(nil)` to `error` interface)- [ ] Check for nil slice vs empty slice inconsistencies (especially in JSON marshaling)### 2.2 Zero Value Behavior- [ ] Find structs where zero value is not usable (missing constructors/`New` functions)- [ ] Identify maps used without `make()` initialization- [ ] Detect channels used without `make()` initialization- [ ] Find numeric zero values that should be checked (division by zero, slice indexing)- [ ] Identify boolean zero values (`false`) in configs where explicit default needed- [ ] Check for string zero values (`""`) confused with "not set"- [ ] Find time.Time zero value issues (year 0001 instead of "not set")- [ ] Detect `sync.WaitGroup` / `sync.Once` / `sync.Mutex` used before initialization- [ ] Identify slice operations on zero-length slices without length checks---## 3. ERROR HANDLING ANALYSIS### 3.1 Error Handling Patterns- [ ] Find ALL places where errors are ignored (blank identifier `_` or no check)- [ ] Identify `if err != nil` blocks that just `return err` without wrapping context- [ ] Detect error wrapping without `%w` verb (breaks `errors.Is`/`errors.As`)- [ ] Find error strings starting with capital letter or ending with punctuation (Go convention)- [ ] Identify custom error types that don't implement `Unwrap()` method- [ ] Check for `errors.Is()` / `errors.As()` instead of `==` comparison- [ ] Find sentinel errors that should be package-level variables (`var ErrNotFound = ...`)- [ ] Detect error handling in deferred functions that shadow outer errors- [ ] Identify panic recovery (`recover()`) in wrong places or missing entirely- [ ] Check for proper error type hierarchy and categorization### 3.2 Panic & Recovery- [ ] Find `panic()` calls in library code (should return errors instead)- [ ] Identify missing `recover()` in goroutines (unrecovered panic kills process)- [ ] Detect `log.Fatal()` / `os.Exit()` in library code (only acceptable in `main`)- [ ] Find index out of range possibilities without bounds checking- [ ] Identify `panic` in `init()` functions without clear documentation- [ ] Check for proper panic recovery in HTTP handlers / middleware- [ ] Find `must` pattern functions without clear naming convention- [ ] Detect panics in hot paths where error return is feasible### 3.3 Error Wrapping & Context- [ ] Find error messages that don't include contextual information (which operation, which input)- [ ] Identify error wrapping that creates excessively deep chains- [ ] Detect inconsistent error wrapping style across the codebase- [ ] Check for `fmt.Errorf("...: %w", err)` with proper verb usage- [ ] Find places where structured errors (error types) should replace string errors- [ ] Identify missing stack trace information in critical error paths- [ ] Check for error messages that leak sensitive information (passwords, tokens, PII)---## 4. CONCURRENCY & GOROUTINES### 4.1 Goroutine Management- [ ] Find goroutine leaks (goroutines started but never terminated)- [ ] Identify goroutines without proper shutdown mechanism (context cancellation)- [ ] Detect goroutines launched in loops without controlling concurrency- [ ] Find fire-and-forget goroutines without error reporting- [ ] Identify goroutines that outlive the function that created them- [ ] Check for `go func()` capturing loop variables (Go <1.22 issue)- [ ] Find goroutine pools that grow unbounded- [ ] Detect goroutines without `recover()` for panic safety- [ ] Identify missing `sync.WaitGroup` for goroutine completion tracking- [ ] Check for proper use of `errgroup.Group` for error-propagating goroutine groups### 4.2 Channel Issues- [ ] Find unbuffered channels that could cause deadlocks- [ ] Identify channels that are never closed (potential goroutine leaks)- [ ] Detect double-close on channels (runtime panic)- [ ] Find send on closed channel (runtime panic)- [ ] Identify missing `select` with `default` for non-blocking operations- [ ] Check for missing `context.Done()` case in select statements- [ ] Find channel direction missing in function signatures (`chan T` vs `<-chan T` vs `chan<- T`)- [ ] Detect channels used as mutexes where `sync.Mutex` is clearer- [ ] Identify channel buffer sizes that are arbitrary without justification- [ ] Check for fan-out/fan-in patterns without proper coordination### 4.3 Race Conditions & Synchronization- [ ] Find shared mutable state accessed without synchronization- [ ] Identify `sync.Map` used where regular `map` + `sync.RWMutex` is better (or vice versa)- [ ] Detect lock ordering issues that could cause deadlocks- [ ] Find `sync.Mutex` that should be `sync.RWMutex` for read-heavy workloads- [ ] Identify atomic operations that should be used instead of mutex for simple counters- [ ] Check for `sync.Once` used correctly (especially with errors)- [ ] Find data races in struct field access from multiple goroutines- [ ] Detect time-of-check to time-of-use (TOCTOU) vulnerabilities- [ ] Identify lock held during I/O operations (blocking under lock)- [ ] Check for proper use of `sync.Pool` (object resetting, Put after Get)- [ ] Find missing `go vet -race` / `-race` flag testing evidence- [ ] Detect `sync.Cond` misuse (missing broadcast/signal)### 4.4 Context Usage- [ ] Find functions accepting `context.Context` not as first parameter- [ ] Identify `context.Background()` used where parent context should be propagated- [ ] Detect `context.TODO()` left in production code- [ ] Find context cancellation not being checked in long-running operations- [ ] Identify context values used for passing request-scoped data inappropriately- [ ] Check for context leaks (missing cancel function calls)- [ ] Find `context.WithTimeout`/`WithDeadline` without `defer cancel()`- [ ] Detect context stored in structs (should be passed as parameter)---## 5. RESOURCE MANAGEMENT### 5.1 Defer & Cleanup- [ ] Find `defer` inside loops (defers don't run until function returns)- [ ] Identify `defer` with captured loop variables- [ ] Detect missing `defer` for resource cleanup (file handles, connections, locks)- [ ] Find `defer` order issues (LIFO behavior not accounted for)- [ ] Identify `defer` on methods that could fail silently (`defer f.Close()` — error ignored)- [ ] Check for `defer` with named return values interaction (late binding)- [ ] Find resources opened but never closed (file descriptors, HTTP response bodies)- [ ] Detect `http.Response.Body` not being closed after read- [ ] Identify database rows/statements not being closed### 5.2 Memory Management- [ ] Find large allocations in hot paths- [ ] Identify slice capacity hints missing (`make([]T, 0, expectedSize)`)- [ ] Detect string builder not used for string concatenation in loops- [ ] Find `append()` growing slices without capacity pre-allocation- [ ] Identify byte slice to string conversion in hot paths (allocation)- [ ] Check for proper use of `sync.Pool` for frequently allocated objects- [ ] Find large structs passed by value instead of pointer- [ ] Detect slice reslicing that prevents garbage collection of underlying array- [ ] Identify `map` that grows but never shrinks (memory leak pattern)- [ ] Check for proper buffer reuse in I/O operations (`bufio`, `bytes.Buffer`)### 5.3 File & I/O Resources- [ ] Find `os.Open` / `os.Create` without `defer f.Close()`- [ ] Identify `io.ReadAll` on potentially large inputs (OOM risk)- [ ] Detect missing `bufio.Scanner` / `bufio.Reader` for large file reading- [ ] Find temporary files not cleaned up- [ ] Identify `os.TempDir()` usage without proper cleanup- [ ] Check for file permissions too permissive (0777, 0666)- [ ] Find missing `fsync` for critical writes- [ ] Detect race conditions on file operations---## 6. SECURITY VULNERABILITIES### 6.1 Injection Attacks- [ ] Find SQL queries built with `fmt.Sprintf` instead of parameterized queries- [ ] Identify command injection via `exec.Command` with user input- [ ] Detect path traversal vulnerabilities (`filepath.Join` with user input without `filepath.Clean`)- [ ] Find template injection in `html/template` or `text/template`- [ ] Identify log injection possibilities (user input in log messages without sanitization)- [ ] Check for LDAP injection vulnerabilities- [ ] Find header injection in HTTP responses- [ ] Detect SSRF vulnerabilities (user-controlled URLs in HTTP requests)- [ ] Identify deserialization attacks via `encoding/gob`, `encoding/json` with `interface{}`- [ ] Check for regex injection (ReDoS) with user-provided patterns### 6.2 Authentication & Authorization- [ ] Find hardcoded credentials, API keys, or secrets in source code- [ ] Identify missing authentication middleware on protected endpoints- [ ] Detect authorization bypass possibilities (IDOR vulnerabilities)- [ ] Find JWT implementation flaws (algorithm confusion, missing validation)- [ ] Identify timing attacks in comparison operations (use `crypto/subtle.ConstantTimeCompare`)- [ ] Check for proper password hashing (`bcrypt`, `argon2`, NOT `md5`/`sha256`)- [ ] Find session tokens with insufficient entropy- [ ] Detect privilege escalation via role/permission bypass- [ ] Identify missing CSRF protection on state-changing endpoints- [ ] Check for proper OAuth2 implementation (state parameter, PKCE)### 6.3 Cryptographic Issues- [ ] Find use of `math/rand` instead of `crypto/rand` for security purposes- [ ] Identify weak hash algorithms (`md5`, `sha1`) for security-sensitive operations- [ ] Detect hardcoded encryption keys or IVs- [ ] Find ECB mode usage (should use GCM, CTR, or CBC with proper IV)- [ ] Identify missing TLS configuration or insecure `InsecureSkipVerify: true`- [ ] Check for proper certificate validation- [ ] Find deprecated crypto packages or algorithms- [ ] Detect nonce reuse in encryption- [ ] Identify HMAC comparison without constant-time comparison### 6.4 Input Validation & Sanitization- [ ] Find missing input length/size limits- [ ] Identify `io.ReadAll` without `io.LimitReader` (denial of service)- [ ] Detect missing Content-Type validation on uploads- [ ] Find integer overflow/underflow in size calculations- [ ] Identify missing URL validation before HTTP requests- [ ] Check for proper handling of multipart form data limits- [ ] Find missing rate limiting on public endpoints- [ ] Detect unvalidated redirects (open redirect vulnerability)- [ ] Identify user input used in file paths without sanitization- [ ] Check for proper CORS configuration### 6.5 Data Security- [ ] Find sensitive data in logs (passwords, tokens, PII)- [ ] Identify PII stored without encryption at rest- [ ] Detect sensitive data in URL query parameters- [ ] Find sensitive data in error messages returned to clients- [ ] Identify missing `Secure`, `HttpOnly`, `SameSite` cookie flags- [ ] Check for sensitive data in environment variables logged at startup- [ ] Find API responses that leak internal implementation details- [ ] Detect missing response headers (CSP, HSTS, X-Frame-Options)---## 7. PERFORMANCE ANALYSIS### 7.1 Algorithmic Complexity- [ ] Find O(n²) or worse algorithms that could be optimized- [ ] Identify nested loops that could be flattened- [ ] Detect repeated slice/map iterations that could be combined- [ ] Find linear searches that should use `map` for O(1) lookup- [ ] Identify sorting operations that could be avoided with a heap/priority queue- [ ] Check for unnecessary slice copying (`append`, spread)- [ ] Find recursive functions without memoization- [ ] Detect expensive operations inside hot loops### 7.2 Go-Specific Performance- [ ] Find excessive allocations detectable by escape analysis (`go build -gcflags="-m"`)- [ ] Identify interface boxing in hot paths (causes allocation)- [ ] Detect excessive use of `fmt.Sprintf` where `strconv` functions are faster- [ ] Find `reflect` usage in hot paths- [ ] Identify `defer` in tight loops (overhead per iteration)- [ ] Check for string → []byte → string conversions that could be avoided- [ ] Find JSON marshaling/unmarshaling in hot paths (consider code-gen alternatives)- [ ] Detect map iteration where order matters (Go maps are unordered)- [ ] Identify `time.Now()` calls in tight loops (syscall overhead)- [ ] Check for proper use of `sync.Pool` in allocation-heavy code- [ ] Find `regexp.Compile` called repeatedly (should be package-level `var`)- [ ] Detect `append` without pre-allocated capacity in known-size operations### 7.3 I/O Performance- [ ] Find synchronous I/O in goroutine-heavy code that could block- [ ] Identify missing connection pooling for database/HTTP clients- [ ] Detect missing buffered I/O (`bufio.Reader`/`bufio.Writer`)- [ ] Find `http.Client` without timeout configuration- [ ] Identify missing `http.Client` reuse (creating new client per request)- [ ] Check for `http.DefaultClient` usage (no timeout by default)- [ ] Find database queries without `LIMIT` clause- [ ] Detect N+1 query problems in data fetching- [ ] Identify missing prepared statements for repeated queries- [ ] Check for missing response body draining before close (`io.Copy(io.Discard, resp.Body)`)### 7.4 Memory Performance- [ ] Find large struct copying on each function call (pass by pointer)- [ ] Identify slice backing array leaks (sub-slicing prevents GC)- [ ] Detect `map` growing indefinitely without cleanup/eviction- [ ] Find string concatenation in loops (use `strings.Builder`)- [ ] Identify closure capturing large objects unnecessarily- [ ] Check for proper `bytes.Buffer` reuse- [ ] Find `ioutil.ReadAll` (deprecated and unbounded reads)- [ ] Detect pprof/benchmark evidence missing for performance claims---## 8. CODE QUALITY ISSUES### 8.1 Dead Code Detection- [ ] Find unused exported functions/methods/types- [ ] Identify unreachable code after `return`/`panic`/`os.Exit`- [ ] Detect unused function parameters- [ ] Find unused struct fields- [ ] Identify unused imports (should be caught by compiler, but check generated code)- [ ] Check for commented-out code blocks- [ ] Find unused type definitions- [ ] Detect unused constants/variables- [ ] Identify build-tagged code that's never compiled- [ ] Find orphaned test helper functions### 8.2 Code Duplication- [ ] Find duplicate function implementations across packages- [ ] Identify copy-pasted code blocks with minor variations- [ ] Detect similar logic that could be abstracted into shared functions- [ ] Find duplicate struct definitions- [ ] Identify repeated error handling boilerplate that could be middleware- [ ] Check for duplicate validation logic- [ ] Find similar HTTP handler patterns that could be generalized- [ ] Detect duplicate constants across packages### 8.3 Code Smells- [ ] Find functions longer than 50 lines- [ ] Identify files larger than 500 lines (split into multiple files)- [ ] Detect deeply nested conditionals (>3 levels) — use early returns- [ ] Find functions with too many parameters (>5) — use options pattern or config struct- [ ] Identify God packages with too many responsibilities- [ ] Check for `init()` functions with side effects (hard to test, order-dependent)- [ ] Find `switch` statements that should be polymorphism (interface dispatch)- [ ] Detect boolean parameters (use options or separate functions)- [ ] Identify data clumps (groups of parameters that appear together)- [ ] Find speculative generality (unused abstractions/interfaces)### 8.4 Go Idioms & Style- [ ] Find non-idiomatic error handling (not following `if err != nil` pattern)- [ ] Identify getters with `Get` prefix (Go convention: `Name()` not `GetName()`)- [ ] Detect unexported types returned from exported functions- [ ] Find package names that stutter (`http.HTTPClient` → `http.Client`)- [ ] Identify `else` blocks after `if-return` (should be flat)- [ ] Check for proper use of `iota` for enumerations- [ ] Find exported functions without documentation comments- [ ] Detect `var` declarations where `:=` is cleaner (and vice versa)- [ ] Identify missing package-level documentation (`// Package foo ...`)- [ ] Check for proper receiver naming (short, consistent: `s` for `Server`, not `this`/`self`)- [ ] Find single-method interface names not ending in `-er` (`Reader`, `Writer`, `Closer`)- [ ] Detect naked returns in non-trivial functions---## 9. ARCHITECTURE & DESIGN### 9.1 Package Structure- [ ] Find circular dependencies between packages (`go vet ./...` won't compile but check indirect)- [ ] Identify `internal/` packages missing where they should exist- [ ] Detect "everything in one package" anti-pattern- [ ] Find improper package layering (business logic importing HTTP handlers)- [ ] Identify missing clean architecture boundaries (domain, service, repository layers)- [ ] Check for proper `cmd/` structure for multiple binaries- [ ] Find shared mutable global state across packages- [ ] Detect `pkg/` directory misuse- [ ] Identify missing dependency injection (constructors accepting interfaces)- [ ] Check for proper separation between API definition and implementation### 9.2 SOLID Principles- [ ] **Single Responsibility**: Find packages/files doing too much- [ ] **Open/Closed**: Find code requiring modification for extension (missing interfaces/plugins)- [ ] **Liskov Substitution**: Find interface implementations that violate contracts- [ ] **Interface Segregation**: Find fat interfaces that should be split- [ ] **Dependency Inversion**: Find concrete type dependencies where interfaces should be used### 9.3 Design Patterns- [ ] Find missing `Functional Options` pattern for configurable types- [ ] Identify `New*` constructor functions that should accept `Option` funcs- [ ] Detect missing middleware pattern for cross-cutting concerns- [ ] Find observer/pubsub implementations that could leak goroutines- [ ] Identify missing `Repository` pattern for data access- [ ] Check for proper `Builder` pattern for complex object construction- [ ] Find missing `Strategy` pattern opportunities (behavior variation via interface)- [ ] Detect global state that should use dependency injection### 9.4 API Design- [ ] Find HTTP handlers that do business logic directly (should delegate to service layer)- [ ] Identify missing request/response validation middleware- [ ] Detect inconsistent REST API conventions across endpoints- [ ] Find gRPC service definitions without proper error codes- [ ] Identify missing API versioning strategy- [ ] Check for proper HTTP status code usage- [ ] Find missing health check / readiness endpoints- [ ] Detect overly chatty APIs (N+1 endpoints that should be batched)---## 10. DEPENDENCY ANALYSIS### 10.1 Module & Version Analysis- [ ] Run `go list -m -u all` — identify all outdated dependencies- [ ] Check `go.sum` consistency (`go mod verify`)- [ ] Find replace directives left in `go.mod`- [ ] Identify dependencies with known CVEs (`govulncheck ./...`)- [ ] Check for unused dependencies (`go mod tidy` changes)- [ ] Find vendored dependencies that are outdated- [ ] Identify indirect dependencies that should be direct- [ ] Check for Go version in `go.mod` matching CI/deployment target- [ ] Find `//go:build ignore` files with dependency imports### 10.2 Dependency Health- [ ] Check last commit date for each dependency- [ ] Identify archived/unmaintained dependencies- [ ] Find dependencies with open critical issues- [ ] Check for dependencies using `unsafe` package extensively- [ ] Identify heavy dependencies that could be replaced with stdlib- [ ] Find dependencies with restrictive licenses (GPL in MIT project)- [ ] Check for dependencies with CGO requirements (portability concern)- [ ] Identify dependencies pulling in massive transitive trees- [ ] Find forked dependencies without upstream tracking### 10.3 CGO Considerations- [ ] Check if CGO is required and if `CGO_ENABLED=0` build is possible- [ ] Find CGO code without proper memory management- [ ] Identify CGO calls in hot paths (overhead of Go→C boundary crossing)- [ ] Check for CGO dependencies that break cross-compilation- [ ] Find CGO code that doesn't handle C errors properly- [ ] Detect potential memory leaks across CGO boundary---## 11. TESTING GAPS### 11.1 Coverage Analysis- [ ] Run `go test -coverprofile` — identify untested packages and functions- [ ] Find untested error paths (especially error returns)- [ ] Detect untested edge cases in conditionals- [ ] Check for missing boundary value tests- [ ] Identify untested concurrent scenarios- [ ] Find untested input validation paths- [ ] Check for missing integration tests (database, HTTP, gRPC)- [ ] Identify critical paths without benchmark tests (`*testing.B`)### 11.2 Test Quality- [ ] Find tests that don't use `t.Helper()` for test helper functions- [ ] Identify table-driven tests that should exist but don't- [ ] Detect tests with excessive mocking hiding real bugs- [ ] Find tests that test implementation instead of behavior- [ ] Identify tests with shared mutable state (run order dependent)- [ ] Check for `t.Parallel()` usage where safe- [ ] Find flaky tests (timing-dependent, file-system dependent)- [ ] Detect missing subtests (`t.Run("name", ...)`)- [ ] Identify missing `testdata/` files for golden tests- [ ] Check for `httptest.NewServer` cleanup (missing `defer server.Close()`)### 11.3 Test Infrastructure- [ ] Find missing `TestMain` for setup/teardown- [ ] Identify missing build tags for integration tests (`//go:build integration`)- [ ] Detect missing race condition tests (`go test -race`)- [ ] Check for missing fuzz tests (`Fuzz*` functions — Go 1.18+)- [ ] Find missing example tests (`Example*` functions for godoc)- [ ] Identify missing benchmark comparison baselines- [ ] Check for proper test fixture management- [ ] Find tests relying on external services without mocks/stubs---## 12. CONFIGURATION & BUILD### 12.1 Go Module Configuration- [ ] Check Go version in `go.mod` is appropriate- [ ] Verify `go.sum` is committed and consistent- [ ] Check for proper module path naming- [ ] Find replace directives that shouldn't be in published modules- [ ] Identify retract directives needed for broken versions- [ ] Check for proper module boundaries (when to split)- [ ] Verify `//go:generate` directives are documented and reproducible### 12.2 Build Configuration- [ ] Check for proper `ldflags` for version embedding- [ ] Verify `CGO_ENABLED` setting is intentional- [ ] Find build tags used correctly (`//go:build`)- [ ] Check for proper cross-compilation setup- [ ] Identify missing `go vet` / `staticcheck` / `golangci-lint` in CI- [ ] Verify Docker multi-stage build for minimal image size- [ ] Check for proper `.goreleaser.yml` configuration if applicable- [ ] Find hardcoded `GOOS`/`GOARCH` where build tags should be used### 12.3 Environment & Configuration- [ ] Find hardcoded environment-specific values (URLs, ports, paths)- [ ] Identify missing environment variable validation at startup- [ ] Detect improper fallback values for missing configuration- [ ] Check for proper config struct with validation tags- [ ] Find sensitive values not using secrets management- [ ] Identify missing feature flags / toggles for gradual rollout- [ ] Check for proper signal handling (`SIGTERM`, `SIGINT`) for graceful shutdown- [ ] Find missing health check endpoints (`/healthz`, `/readyz`)---## 13. HTTP & NETWORK SPECIFIC### 13.1 HTTP Server Issues- [ ] Find `http.ListenAndServe` without timeouts (use custom `http.Server`)- [ ] Identify missing `ReadTimeout`, `WriteTimeout`, `IdleTimeout` on server- [ ] Detect missing `http.MaxBytesReader` on request bodies- [ ] Find response headers not set (Content-Type, Cache-Control, Security headers)- [ ] Identify missing graceful shutdown with `server.Shutdown(ctx)`- [ ] Check for proper middleware chaining order- [ ] Find missing request ID / correlation ID propagation- [ ] Detect missing access logging middleware- [ ] Identify missing panic recovery middleware- [ ] Check for proper handler error response consistency### 13.2 HTTP Client Issues- [ ] Find `http.DefaultClient` usage (no timeout)- [ ] Identify `http.Response.Body` not closed after use- [ ] Detect missing retry logic with exponential backoff- [ ] Find missing `context.Context` propagation in HTTP calls- [ ] Identify connection pool exhaustion risks (missing `MaxIdleConns` tuning)- [ ] Check for proper TLS configuration on client- [ ] Find missing `io.LimitReader` on response body reads- [ ] Detect DNS caching issues in long-running processes### 13.3 Database Issues- [ ] Find `database/sql` connections not using connection pool properly- [ ] Identify missing `SetMaxOpenConns`, `SetMaxIdleConns`, `SetConnMaxLifetime`- [ ] Detect SQL injection via string concatenation- [ ] Find missing transaction rollback on error (`defer tx.Rollback()`)- [ ] Identify `rows.Close()` missing after `db.Query()`- [ ] Check for `rows.Err()` check after iteration- [ ] Find missing prepared statement caching- [ ] Detect context not passed to database operations- [ ] Identify missing database migration versioning---## 14. DOCUMENTATION & MAINTAINABILITY### 14.1 Code Documentation- [ ] Find exported functions/types/constants without godoc comments- [ ] Identify functions with complex logic but no explanation- [ ] Detect missing package-level documentation (`// Package foo ...`)- [ ] Check for outdated comments that no longer match code- [ ] Find TODO/FIXME/HACK/XXX comments that need addressing- [ ] Identify magic numbers without named constants- [ ] Check for missing examples in godoc (`Example*` functions)- [ ] Find missing error documentation (what errors can be returned)### 14.2 Project Documentation- [ ] Find missing README with usage, installation, API docs- [ ] Identify missing CHANGELOG- [ ] Detect missing CONTRIBUTING guide- [ ] Check for missing architecture decision records (ADRs)- [ ] Find missing API documentation (OpenAPI/Swagger, protobuf docs)- [ ] Identify missing deployment/operations documentation- [ ] Check for missing LICENSE file---## 15. EDGE CASES CHECKLIST### 15.1 Input Edge Cases- [ ] Empty strings, slices, maps- [ ] `math.MaxInt64`, `math.MinInt64`, overflow boundaries- [ ] Negative numbers where positive expected- [ ] Zero values for all types- [ ] `math.NaN()` and `math.Inf()` in float operations- [ ] Unicode characters and emoji in string processing- [ ] Very large inputs (>1GB files, millions of records)- [ ] Deeply nested JSON structures- [ ] Malformed input data (truncated JSON, broken UTF-8)- [ ] Concurrent access from multiple goroutines### 15.2 Timing Edge Cases- [ ] Leap years and daylight saving time transitions- [ ] Timezone handling (`time.UTC` vs `time.Local` inconsistencies)- [ ] `time.Ticker` / `time.Timer` not stopped (goroutine leak)- [ ] Monotonic clock vs wall clock (`time.Now()` uses monotonic for duration)- [ ] Very old timestamps (before Unix epoch)- [ ] Nanosecond precision issues in comparisons- [ ] `time.After()` in select statements (creates new channel each iteration — leak)### 15.3 Platform Edge Cases- [ ] File path handling across OS (`filepath.Join` vs `path.Join`)- [ ] Line ending differences (`\n` vs `\r\n`)- [ ] File system case sensitivity differences- [ ] Maximum path length constraints- [ ] Endianness assumptions in binary protocols- [ ] Signal handling differences across OS---## OUTPUT FORMATFor each issue found, provide:### [SEVERITY: CRITICAL/HIGH/MEDIUM/LOW] Issue Title**Category**: [Type Safety/Security/Concurrency/Performance/etc.]**File**: path/to/file.go**Line**: 123-145**Impact**: Description of what could go wrong**Current Code**:```go// problematic code```**Problem**: Detailed explanation of why this is an issue**Recommendation**:```go// fixed code```**References**: Links to documentation, Go blog posts, CVEs, best practices---## PRIORITY MATRIX1. **CRITICAL** (Fix Immediately): - Security vulnerabilities (injection, auth bypass) - Data loss / corruption risks - Race conditions causing panics in production - Goroutine leaks causing OOM2. **HIGH** (Fix This Sprint): - Nil pointer dereferences - Ignored errors in critical paths - Missing context cancellation - Resource leaks (connections, file handles)3. **MEDIUM** (Fix Soon): - Code quality / idiom violations - Test coverage gaps - Performance issues in non-hot paths - Documentation gaps4. **LOW** (Tech Debt): - Style inconsistencies - Minor optimizations - Nice-to-have abstractions - Naming improvements---## STATIC ANALYSIS TOOLS TO RUNBefore manual review, run these tools and include findings:```bash# Compiler checksgo build ./...go vet ./...# Race detectorgo test -race ./...# Vulnerability checkgovulncheck ./...# Linter suite (comprehensive)golangci-lint run --enable-all ./...# Dead code detectiondeadcode ./...# Unused exportsunused ./...# Security scannergosec ./...# Complexity analysisgocyclo -over 15 .# Escape analysisgo build -gcflags="-m -m" ./... 2>&1 | grep "escapes to heap"# Test coveragego test -coverprofile=coverage.out ./...go tool cover -func=coverage.out```---## FINAL SUMMARYAfter completing the review, provide:1. **Executive Summary**: 2-3 paragraphs overview2. **Risk Assessment**: Overall risk level with justification3. **Top 10 Critical Issues**: Prioritized list4. **Recommended Action Plan**: Phased approach to fixes5. **Estimated Effort**: Time estimates for remediation6. **Metrics**: - Total issues found by severity - Code health score (1-10) - Security score (1-10) - Concurrency safety score (1-10) - Maintainability score (1-10) - Test coverage percentage
# COMPREHENSIVE PYTHON CODEBASE REVIEWYou are an expert Python code reviewer with 20+ years of experience in enterprise software development, security auditing, and performance optimization. Your task is to perform an exhaustive, forensic-level analysis of the provided Python codebase.## REVIEW PHILOSOPHY- Assume nothing is correct until proven otherwise- Every line of code is a potential source of bugs- Every dependency is a potential security risk- Every function is a potential performance bottleneck- Every mutable default is a ticking time bomb- Every `except` block is potentially swallowing critical errors- Dynamic typing means runtime surprises — treat every untyped function as suspect---## 1. TYPE SYSTEM & TYPE HINTS ANALYSIS### 1.1 Type Annotation Coverage- [ ] Identify ALL functions/methods missing type hints (parameters and return types)- [ ] Find `Any` type usage — each one bypasses type checking entirely- [ ] Detect `# type: ignore` comments — each one is hiding a potential bug- [ ] Find `cast()` calls that could fail at runtime- [ ] Identify `TYPE_CHECKING` imports used incorrectly (circular import hacks)- [ ] Check for `__all__` missing in public modules- [ ] Find `Union` types that should be narrower- [ ] Detect `Optional` parameters without `None` default values- [ ] Identify `dict`, `list`, `tuple` used without generic subscript (`dict[str, int]`)- [ ] Check for `TypeVar` without proper bounds or constraints### 1.2 Type Correctness- [ ] Find `isinstance()` checks that miss subtypes or union members- [ ] Identify `type()` comparison instead of `isinstance()` (breaks inheritance)- [ ] Detect `hasattr()` used for type checking instead of protocols/ABCs- [ ] Find string-based type references that could break (`"ClassName"` forward refs)- [ ] Identify `typing.Protocol` that should exist but doesn't- [ ] Check for `@overload` decorators missing for polymorphic functions- [ ] Find `TypedDict` with missing `total=False` for optional keys- [ ] Detect `NamedTuple` fields without types- [ ] Identify `dataclass` fields with mutable default values (use `field(default_factory=...)`)- [ ] Check for `Literal` types that should be used for string enums### 1.3 Runtime Type Validation- [ ] Find public API functions without runtime input validation- [ ] Identify missing Pydantic/attrs/dataclass validation at boundaries- [ ] Detect `json.loads()` results used without schema validation- [ ] Find API request/response bodies without model validation- [ ] Identify environment variables used without type coercion and validation- [ ] Check for proper use of `TypeGuard` for type narrowing functions- [ ] Find places where `typing.assert_type()` (3.11+) should be used---## 2. NONE / SENTINEL HANDLING### 2.1 None Safety- [ ] Find ALL places where `None` could occur but isn't handled- [ ] Identify `dict.get()` return values used without None checks- [ ] Detect `dict[key]` access that could raise `KeyError`- [ ] Find `list[index]` access without bounds checking (`IndexError`)- [ ] Identify `re.match()` / `re.search()` results used without None checks- [ ] Check for `next(iterator)` without default parameter (`StopIteration`)- [ ] Find `os.environ.get()` used without fallback where value is required- [ ] Detect attribute access on potentially None objects- [ ] Identify `Optional[T]` return types where callers don't check for None- [ ] Find chained attribute access (`a.b.c.d`) without intermediate None checks### 2.2 Mutable Default Arguments- [ ] Find ALL mutable default parameters (`def foo(items=[])`) — CRITICAL BUG- [ ] Identify `def foo(data={})` — shared dict across calls- [ ] Detect `def foo(callbacks=[])` — list accumulates across calls- [ ] Find `def foo(config=SomeClass())` — shared instance- [ ] Check for mutable class-level attributes shared across instances- [ ] Identify `dataclass` fields with mutable defaults (need `field(default_factory=...)`)### 2.3 Sentinel Values- [ ] Find `None` used as sentinel where a dedicated sentinel object should be used- [ ] Identify functions where `None` is both a valid value and "not provided"- [ ] Detect `""` or `0` or `False` used as sentinel (conflicts with legitimate values)- [ ] Find `_MISSING = object()` sentinels without proper `__repr__`---## 3. ERROR HANDLING ANALYSIS### 3.1 Exception Handling Patterns- [ ] Find bare `except:` clauses — catches `SystemExit`, `KeyboardInterrupt`, `GeneratorExit`- [ ] Identify `except Exception:` that swallows errors silently- [ ] Detect `except` blocks with only `pass` — silent failure- [ ] Find `except` blocks that catch too broadly (`except (Exception, BaseException):`)- [ ] Identify `except` blocks that don't log or re-raise- [ ] Check for `except Exception as e:` where `e` is never used- [ ] Find `raise` without `from` losing original traceback (`raise NewError from original`)- [ ] Detect exception handling in `__del__` (dangerous — interpreter may be shutting down)- [ ] Identify `try` blocks that are too large (should be minimal)- [ ] Check for proper exception chaining with `__cause__` and `__context__`### 3.2 Custom Exceptions- [ ] Find raw `Exception` / `ValueError` / `RuntimeError` raised instead of custom types- [ ] Identify missing exception hierarchy for the project- [ ] Detect exception classes without proper `__init__` (losing args)- [ ] Find error messages that leak sensitive information- [ ] Identify missing `__str__` / `__repr__` on custom exceptions- [ ] Check for proper exception module organization (`exceptions.py`)### 3.3 Context Managers & Cleanup- [ ] Find resource acquisition without `with` statement (files, locks, connections)- [ ] Identify `open()` without `with` — potential file handle leak- [ ] Detect `__enter__` / `__exit__` implementations that don't handle exceptions properly- [ ] Find `__exit__` returning `True` (suppressing exceptions) without clear intent- [ ] Identify missing `contextlib.suppress()` for expected exceptions- [ ] Check for nested `with` statements that could use `contextlib.ExitStack`- [ ] Find database transactions without proper commit/rollback in context manager- [ ] Detect `tempfile.NamedTemporaryFile` without cleanup- [ ] Identify `threading.Lock` acquisition without `with` statement---## 4. ASYNC / CONCURRENCY### 4.1 Asyncio Issues- [ ] Find `async` functions that never `await` (should be regular functions)- [ ] Identify missing `await` on coroutines (coroutine never executed — just created)- [ ] Detect `asyncio.run()` called from within running event loop- [ ] Find blocking calls inside `async` functions (`time.sleep`, sync I/O, CPU-bound)- [ ] Identify `loop.run_in_executor()` missing for blocking operations in async code- [ ] Check for `asyncio.gather()` without `return_exceptions=True` where appropriate- [ ] Find `asyncio.create_task()` without storing reference (task could be GC'd)- [ ] Detect `async for` / `async with` misuse- [ ] Identify missing `asyncio.shield()` for operations that shouldn't be cancelled- [ ] Check for proper `asyncio.TaskGroup` usage (Python 3.11+)- [ ] Find event loop created per-request instead of reusing- [ ] Detect `asyncio.wait()` without proper `return_when` parameter### 4.2 Threading Issues- [ ] Find shared mutable state without `threading.Lock`- [ ] Identify GIL assumptions for thread safety (only protects Python bytecode, not C extensions)- [ ] Detect `threading.Thread` started without `daemon=True` or proper join- [ ] Find thread-local storage misuse (`threading.local()`)- [ ] Identify missing `threading.Event` for thread coordination- [ ] Check for deadlock risks (multiple locks acquired in different orders)- [ ] Find `queue.Queue` timeout handling missing- [ ] Detect thread pool (`ThreadPoolExecutor`) without `max_workers` limit- [ ] Identify non-thread-safe operations on shared collections- [ ] Check for proper `concurrent.futures` usage with error handling### 4.3 Multiprocessing Issues- [ ] Find objects that can't be pickled passed to multiprocessing- [ ] Identify `multiprocessing.Pool` without proper `close()`/`join()`- [ ] Detect shared state between processes without `multiprocessing.Manager` or `Value`/`Array`- [ ] Find `fork` mode issues on macOS (use `spawn` instead)- [ ] Identify missing `if __name__ == "__main__":` guard for multiprocessing- [ ] Check for large objects being serialized/deserialized between processes- [ ] Find zombie processes not being reaped### 4.4 Race Conditions- [ ] Find check-then-act patterns without synchronization- [ ] Identify file operations with TOCTOU vulnerabilities- [ ] Detect counter increments without atomic operations- [ ] Find cache operations (read-modify-write) without locking- [ ] Identify signal handler race conditions- [ ] Check for `dict`/`list` modifications during iteration from another thread---## 5. RESOURCE MANAGEMENT### 5.1 Memory Management- [ ] Find large data structures kept in memory unnecessarily- [ ] Identify generators/iterators not used where they should be (loading all into list)- [ ] Detect `list(huge_generator)` materializing unnecessarily- [ ] Find circular references preventing garbage collection- [ ] Identify `__del__` methods that could prevent GC (prevent reference cycles from being collected)- [ ] Check for large global variables that persist for process lifetime- [ ] Find string concatenation in loops (`+=`) instead of `"".join()` or `io.StringIO`- [ ] Detect `copy.deepcopy()` on large objects in hot paths- [ ] Identify `pandas.DataFrame` copies where in-place operations suffice- [ ] Check for `__slots__` missing on classes with many instances- [ ] Find caches (`dict`, `lru_cache`) without size limits — unbounded memory growth- [ ] Detect `functools.lru_cache` on methods (holds reference to `self` — memory leak)### 5.2 File & I/O Resources- [ ] Find `open()` without `with` statement- [ ] Identify missing file encoding specification (`open(f, encoding="utf-8")`)- [ ] Detect `read()` on potentially huge files (use `readline()` or chunked reading)- [ ] Find temporary files not cleaned up (`tempfile` without context manager)- [ ] Identify file descriptors not being closed in error paths- [ ] Check for missing `flush()` / `fsync()` for critical writes- [ ] Find `os.path` usage where `pathlib.Path` is cleaner- [ ] Detect file permissions too permissive (`os.chmod(path, 0o777)`)### 5.3 Network & Connection Resources- [ ] Find HTTP sessions not reused (`requests.get()` per call instead of `Session`)- [ ] Identify database connections not returned to pool- [ ] Detect socket connections without timeout- [ ] Find missing `finally` / context manager for connection cleanup- [ ] Identify connection pool exhaustion risks- [ ] Check for DNS resolution caching issues in long-running processes- [ ] Find `urllib`/`requests` without timeout parameter (hangs indefinitely)---## 6. SECURITY VULNERABILITIES### 6.1 Injection Attacks- [ ] Find SQL queries built with f-strings or `%` formatting (SQL injection)- [ ] Identify `os.system()` / `subprocess.call(shell=True)` with user input (command injection)- [ ] Detect `eval()` / `exec()` usage — CRITICAL security risk- [ ] Find `pickle.loads()` on untrusted data (arbitrary code execution)- [ ] Identify `yaml.load()` without `Loader=SafeLoader` (code execution)- [ ] Check for `jinja2` templates without autoescape (XSS)- [ ] Find `xml.etree` / `xml.dom` without defusing (XXE attacks) — use `defusedxml`- [ ] Detect `__import__()` / `importlib` with user-controlled module names- [ ] Identify `input()` in Python 2 (evaluates expressions) — if maintaining legacy code- [ ] Find `marshal.loads()` on untrusted data- [ ] Check for `shelve` / `dbm` with user-controlled keys- [ ] Detect path traversal via `os.path.join()` with user input without validation- [ ] Identify SSRF via user-controlled URLs in `requests.get()`- [ ] Find `ast.literal_eval()` used as sanitization (not sufficient for all cases)### 6.2 Authentication & Authorization- [ ] Find hardcoded credentials, API keys, tokens, or secrets in source code- [ ] Identify missing authentication decorators on protected views/endpoints- [ ] Detect authorization bypass possibilities (IDOR)- [ ] Find JWT implementation flaws (algorithm confusion, missing expiry validation)- [ ] Identify timing attacks in string comparison (`==` vs `hmac.compare_digest`)- [ ] Check for proper password hashing (`bcrypt`, `argon2` — NOT `hashlib.md5/sha256`)- [ ] Find session tokens with insufficient entropy (`random` vs `secrets`)- [ ] Detect privilege escalation paths- [ ] Identify missing CSRF protection (Django `@csrf_exempt` overuse, Flask-WTF missing)- [ ] Check for proper OAuth2 implementation### 6.3 Cryptographic Issues- [ ] Find `random` module used for security purposes (use `secrets` module)- [ ] Identify weak hash algorithms (`md5`, `sha1`) for security operations- [ ] Detect hardcoded encryption keys/IVs/salts- [ ] Find ECB mode usage in encryption- [ ] Identify `ssl` context with `check_hostname=False` or custom `verify=False`- [ ] Check for `requests.get(url, verify=False)` — disables TLS verification- [ ] Find deprecated crypto libraries (`PyCrypto` → use `cryptography` or `PyCryptodome`)- [ ] Detect insufficient key lengths- [ ] Identify missing HMAC for message authentication### 6.4 Data Security- [ ] Find sensitive data in logs (`logging.info(f"Password: {password}")`)- [ ] Identify PII in exception messages or tracebacks- [ ] Detect sensitive data in URL query parameters- [ ] Find `DEBUG = True` in production configuration- [ ] Identify Django `SECRET_KEY` hardcoded or committed- [ ] Check for `ALLOWED_HOSTS = ["*"]` in Django- [ ] Find sensitive data serialized to JSON responses- [ ] Detect missing security headers (CSP, HSTS, X-Frame-Options)- [ ] Identify `CORS_ALLOW_ALL_ORIGINS = True` in production- [ ] Check for proper cookie flags (`secure`, `httponly`, `samesite`)### 6.5 Dependency Security- [ ] Run `pip audit` / `safety check` — analyze all vulnerabilities- [ ] Check for dependencies with known CVEs- [ ] Identify abandoned/unmaintained dependencies (last commit >2 years)- [ ] Find dependencies installed from non-PyPI sources (git URLs, local paths)- [ ] Check for unpinned dependency versions (`requests` vs `requests==2.31.0`)- [ ] Identify `setup.py` with `install_requires` using `>=` without upper bound- [ ] Find typosquatting risks in dependency names- [ ] Check for `requirements.txt` vs `pyproject.toml` consistency- [ ] Detect `pip install --trusted-host` or `--index-url` pointing to non-HTTPS sources---## 7. PERFORMANCE ANALYSIS### 7.1 Algorithmic Complexity- [ ] Find O(n²) or worse algorithms (`for x in list: if x in other_list`)- [ ] Identify `list` used for membership testing where `set` gives O(1)- [ ] Detect nested loops that could be flattened with `itertools`- [ ] Find repeated iterations that could be combined into single pass- [ ] Identify sorting operations that could be avoided (`heapq` for top-k)- [ ] Check for unnecessary list copies (`sorted()` vs `.sort()`)- [ ] Find recursive functions without memoization (`@functools.lru_cache`)- [ ] Detect quadratic string operations (`str += str` in loop)### 7.2 Python-Specific Performance- [ ] Find list comprehension opportunities replacing `for` + `append`- [ ] Identify `dict`/`set` comprehension opportunities- [ ] Detect generator expressions that should replace list comprehensions (memory)- [ ] Find `in` operator on `list` where `set` lookup is O(1)- [ ] Identify `global` variable access in hot loops (slower than local)- [ ] Check for attribute access in tight loops (`self.x` — cache to local variable)- [ ] Find `len()` called repeatedly in loops instead of caching- [ ] Detect `try/except` in hot path where `if` check is faster (LBYL vs EAFP trade-off)- [ ] Identify `re.compile()` called inside functions instead of module level- [ ] Check for `datetime.now()` called in tight loops- [ ] Find `json.dumps()`/`json.loads()` in hot paths (consider `orjson`/`ujson`)- [ ] Detect f-string formatting in logging calls that execute even when level is disabled- [ ] Identify `**kwargs` unpacking in hot paths (dict creation overhead)- [ ] Find unnecessary `list()` wrapping of iterators that are only iterated once### 7.3 I/O Performance- [ ] Find synchronous I/O in async code paths- [ ] Identify missing connection pooling (`requests.Session`, `aiohttp.ClientSession`)- [ ] Detect missing buffered I/O for large file operations- [ ] Find N+1 query problems in ORM usage (Django `select_related`/`prefetch_related`)- [ ] Identify missing database query optimization (missing indexes, full table scans)- [ ] Check for `pandas.read_csv()` without `dtype` specification (slow type inference)- [ ] Find missing pagination for large querysets- [ ] Detect `os.listdir()` / `os.walk()` on huge directories without filtering- [ ] Identify missing `__slots__` on data classes with millions of instances- [ ] Check for proper use of `mmap` for large file processing### 7.4 GIL & CPU-Bound Performance- [ ] Find CPU-bound code running in threads (GIL prevents true parallelism)- [ ] Identify missing `multiprocessing` for CPU-bound tasks- [ ] Detect NumPy operations that release GIL not being parallelized- [ ] Find `ProcessPoolExecutor` opportunities for CPU-intensive operations- [ ] Identify C extension / Cython / Rust (PyO3) opportunities for hot loops- [ ] Check for proper `asyncio.to_thread()` usage for blocking I/O in async code---## 8. CODE QUALITY ISSUES### 8.1 Dead Code Detection- [ ] Find unused imports (run `autoflake` or `ruff` check)- [ ] Identify unreachable code after `return`/`raise`/`sys.exit()`- [ ] Detect unused function parameters- [ ] Find unused class attributes/methods- [ ] Identify unused variables (especially in comprehensions)- [ ] Check for commented-out code blocks- [ ] Find unused exception variables in `except` clauses- [ ] Detect feature flags for removed features- [ ] Identify unused `__init__.py` imports- [ ] Find orphaned test utilities/fixtures### 8.2 Code Duplication- [ ] Find duplicate function implementations across modules- [ ] Identify copy-pasted code blocks with minor variations- [ ] Detect similar logic that could be abstracted into shared utilities- [ ] Find duplicate class definitions- [ ] Identify repeated validation logic that could be decorators/middleware- [ ] Check for duplicate error handling patterns- [ ] Find similar API endpoint implementations that could be generalized- [ ] Detect duplicate constants across modules### 8.3 Code Smells- [ ] Find functions longer than 50 lines- [ ] Identify files larger than 500 lines- [ ] Detect deeply nested conditionals (>3 levels) — use early returns / guard clauses- [ ] Find functions with too many parameters (>5) — use dataclass/TypedDict config- [ ] Identify God classes/modules with too many responsibilities- [ ] Check for `if/elif/elif/...` chains that should be dict dispatch or match/case- [ ] Find boolean parameters that should be separate functions or enums- [ ] Detect `*args, **kwargs` passthrough that hides actual API- [ ] Identify data clumps (groups of parameters that appear together)- [ ] Find speculative generality (ABC/Protocol not actually subclassed)### 8.4 Python Idioms & Style- [ ] Find non-Pythonic patterns (`range(len(x))` instead of `enumerate`)- [ ] Identify `dict.keys()` used unnecessarily (`if key in dict` works directly)- [ ] Detect manual loop variable tracking instead of `enumerate()`- [ ] Find `type(x) == SomeType` instead of `isinstance(x, SomeType)`- [ ] Identify `== True` / `== False` / `== None` instead of `is`- [ ] Check for `not x in y` instead of `x not in y`- [ ] Find `lambda` assigned to variable (use `def` instead)- [ ] Detect `map()`/`filter()` where comprehension is clearer- [ ] Identify `from module import *` (pollutes namespace)- [ ] Check for `except:` without exception type (catches everything including SystemExit)- [ ] Find `__init__.py` with too much code (should be minimal re-exports)- [ ] Detect `print()` statements used for debugging (use `logging`)- [ ] Identify string formatting inconsistency (f-strings vs `.format()` vs `%`)- [ ] Check for `os.path` when `pathlib` is cleaner- [ ] Find `dict()` constructor where `{}` literal is idiomatic- [ ] Detect `if len(x) == 0:` instead of `if not x:`### 8.5 Naming Issues- [ ] Find variables not following `snake_case` convention- [ ] Identify classes not following `PascalCase` convention- [ ] Detect constants not following `UPPER_SNAKE_CASE` convention- [ ] Find misleading variable/function names- [ ] Identify single-letter variable names (except `i`, `j`, `k`, `x`, `y`, `_`)- [ ] Check for names that shadow builtins (`id`, `type`, `list`, `dict`, `input`, `open`, `file`, `format`, `range`, `map`, `filter`, `set`, `str`, `int`)- [ ] Find private attributes without leading underscore where appropriate- [ ] Detect overly abbreviated names that reduce readability- [ ] Identify `cls` not used for classmethod first parameter- [ ] Check for `self` not used as first parameter in instance methods---## 9. ARCHITECTURE & DESIGN### 9.1 Module & Package Structure- [ ] Find circular imports between modules- [ ] Identify import cycles hidden by lazy imports- [ ] Detect monolithic modules that should be split into packages- [ ] Find improper layering (views importing models directly, bypassing services)- [ ] Identify missing `__init__.py` public API definition- [ ] Check for proper separation: domain, service, repository, API layers- [ ] Find shared mutable global state across modules- [ ] Detect relative imports where absolute should be used (or vice versa)- [ ] Identify `sys.path` manipulation hacks- [ ] Check for proper namespace package usage### 9.2 SOLID Principles- [ ] **Single Responsibility**: Find modules/classes doing too much- [ ] **Open/Closed**: Find code requiring modification for extension (missing plugin/hook system)- [ ] **Liskov Substitution**: Find subclasses that break parent class contracts- [ ] **Interface Segregation**: Find ABCs/Protocols with too many required methods- [ ] **Dependency Inversion**: Find concrete class dependencies where Protocol/ABC should be used### 9.3 Design Patterns- [ ] Find missing Factory pattern for complex object creation- [ ] Identify missing Strategy pattern (behavior variation via callable/Protocol)- [ ] Detect missing Repository pattern for data access abstraction- [ ] Find Singleton anti-pattern (use dependency injection instead)- [ ] Identify missing Decorator pattern for cross-cutting concerns- [ ] Check for proper Observer/Event pattern (not hardcoding notifications)- [ ] Find missing Builder pattern for complex configuration- [ ] Detect missing Command pattern for undoable/queueable operations- [ ] Identify places where `__init_subclass__` or metaclass could reduce boilerplate- [ ] Check for proper use of ABC vs Protocol (nominal vs structural typing)### 9.4 Framework-Specific (Django/Flask/FastAPI)- [ ] Find fat views/routes with business logic (should be in service layer)- [ ] Identify missing middleware for cross-cutting concerns- [ ] Detect N+1 queries in ORM usage- [ ] Find raw SQL where ORM query is sufficient (and vice versa)- [ ] Identify missing database migrations- [ ] Check for proper serializer/schema validation at API boundaries- [ ] Find missing rate limiting on public endpoints- [ ] Detect missing API versioning strategy- [ ] Identify missing health check / readiness endpoints- [ ] Check for proper signal/hook usage instead of monkeypatching---## 10. DEPENDENCY ANALYSIS### 10.1 Version & Compatibility Analysis- [ ] Check all dependencies for available updates- [ ] Find unpinned versions in `requirements.txt` / `pyproject.toml`- [ ] Identify `>=` without upper bound constraints- [ ] Check Python version compatibility (`python_requires` in `pyproject.toml`)- [ ] Find conflicting dependency versions- [ ] Identify dependencies that should be in `dev` / `test` groups only- [ ] Check for `requirements.txt` generated from `pip freeze` with unnecessary transitive deps- [ ] Find missing `extras_require` / optional dependency groups- [ ] Detect `setup.py` that should be migrated to `pyproject.toml`### 10.2 Dependency Health- [ ] Check last release date for each dependency- [ ] Identify archived/unmaintained dependencies- [ ] Find dependencies with open critical security issues- [ ] Check for dependencies without type stubs (`py.typed` or `types-*` packages)- [ ] Identify heavy dependencies that could be replaced with stdlib- [ ] Find dependencies with restrictive licenses (GPL in MIT project)- [ ] Check for dependencies with native C extensions (portability concern)- [ ] Identify dependencies pulling massive transitive trees- [ ] Find vendored code that should be a proper dependency### 10.3 Virtual Environment & Packaging- [ ] Check for proper `pyproject.toml` configuration- [ ] Verify `setup.cfg` / `setup.py` is modern and complete- [ ] Find missing `py.typed` marker for typed packages- [ ] Check for proper entry points / console scripts- [ ] Identify missing `MANIFEST.in` for sdist packaging- [ ] Verify proper build backend (`setuptools`, `hatchling`, `flit`, `poetry`)- [ ] Check for `pip install -e .` compatibility (editable installs)- [ ] Find Docker images not using multi-stage builds for Python---## 11. TESTING GAPS### 11.1 Coverage Analysis- [ ] Run `pytest --cov` — identify untested modules and functions- [ ] Find untested error/exception paths- [ ] Detect untested edge cases in conditionals- [ ] Check for missing boundary value tests- [ ] Identify untested async code paths- [ ] Find untested input validation scenarios- [ ] Check for missing integration tests (database, HTTP, external services)- [ ] Identify critical business logic without property-based tests (`hypothesis`)### 11.2 Test Quality- [ ] Find tests that don't assert anything meaningful (`assert True`)- [ ] Identify tests with excessive mocking hiding real bugs- [ ] Detect tests that test implementation instead of behavior- [ ] Find tests with shared mutable state (execution order dependent)- [ ] Identify missing `pytest.mark.parametrize` for data-driven tests- [ ] Check for flaky tests (timing-dependent, network-dependent)- [ ] Find `@pytest.fixture` with wrong scope (leaking state between tests)- [ ] Detect tests that modify global state without cleanup- [ ] Identify `unittest.mock.patch` that mocks too broadly- [ ] Check for `monkeypatch` cleanup in pytest fixtures- [ ] Find missing `conftest.py` organization- [ ] Detect `assert x == y` on floats without `pytest.approx()`### 11.3 Test Infrastructure- [ ] Find missing `conftest.py` for shared fixtures- [ ] Identify missing test markers (`@pytest.mark.slow`, `@pytest.mark.integration`)- [ ] Detect missing `pytest.ini` / `pyproject.toml [tool.pytest]` configuration- [ ] Check for proper test database/fixture management- [ ] Find tests relying on external services without mocks (fragile)- [ ] Identify missing `factory_boy` or `faker` for test data generation- [ ] Check for proper `vcr`/`responses`/`httpx_mock` for HTTP mocking- [ ] Find missing snapshot/golden testing for complex outputs- [ ] Detect missing type checking in CI (`mypy --strict` or `pyright`)- [ ] Identify missing `pre-commit` hooks configuration---## 12. CONFIGURATION & ENVIRONMENT### 12.1 Python Configuration- [ ] Check `pyproject.toml` is properly configured- [ ] Verify `mypy` / `pyright` configuration with strict mode- [ ] Check `ruff` / `flake8` configuration with appropriate rules- [ ] Verify `black` / `ruff format` configuration for consistent formatting- [ ] Check `isort` / `ruff` import sorting configuration- [ ] Verify Python version pinning (`.python-version`, `Dockerfile`)- [ ] Check for proper `__init__.py` structure in all packages- [ ] Find `sys.path` manipulation that should be proper package installs### 12.2 Environment Handling- [ ] Find hardcoded environment-specific values (URLs, ports, paths, database URLs)- [ ] Identify missing environment variable validation at startup- [ ] Detect improper fallback values for missing config- [ ] Check for proper `.env` file handling (`python-dotenv`, `pydantic-settings`)- [ ] Find sensitive values not using secrets management- [ ] Identify `DEBUG=True` accessible in production- [ ] Check for proper logging configuration (level, format, handlers)- [ ] Find `print()` statements that should be `logging`### 12.3 Deployment Configuration- [ ] Check Dockerfile follows best practices (non-root user, multi-stage, layer caching)- [ ] Verify WSGI/ASGI server configuration (gunicorn workers, uvicorn settings)- [ ] Find missing health check endpoints- [ ] Check for proper signal handling (`SIGTERM`, `SIGINT`) for graceful shutdown- [ ] Identify missing process manager configuration (supervisor, systemd)- [ ] Verify database migration is part of deployment pipeline- [ ] Check for proper static file serving configuration- [ ] Find missing monitoring/observability setup (metrics, tracing, structured logging)---## 13. PYTHON VERSION & COMPATIBILITY### 13.1 Deprecation & Migration- [ ] Find `typing.Dict`, `typing.List`, `typing.Tuple` (use `dict`, `list`, `tuple` from 3.9+)- [ ] Identify `typing.Optional[X]` that could be `X | None` (3.10+)- [ ] Detect `typing.Union[X, Y]` that could be `X | Y` (3.10+)- [ ] Find `@abstractmethod` without `ABC` base class- [ ] Identify removed functions/modules for target Python version- [ ] Check for `asyncio.get_event_loop()` deprecation (3.10+)- [ ] Find `importlib.resources` usage compatible with target version- [ ] Detect `match/case` usage if supporting <3.10- [ ] Identify `ExceptionGroup` usage if supporting <3.11- [ ] Check for `tomllib` usage if supporting <3.11### 13.2 Future-Proofing- [ ] Find code that will break with future Python versions- [ ] Identify pending deprecation warnings- [ ] Check for `__future__` imports that should be added- [ ] Detect patterns that will be obsoleted by upcoming PEPs- [ ] Identify `pkg_resources` usage (deprecated — use `importlib.metadata`)- [ ] Find `distutils` usage (removed in 3.12)---## 14. EDGE CASES CHECKLIST### 14.1 Input Edge Cases- [ ] Empty strings, lists, dicts, sets- [ ] Very large numbers (arbitrary precision in Python, but memory limits)- [ ] Negative numbers where positive expected- [ ] Zero values (division, indexing, slicing)- [ ] `float('nan')`, `float('inf')`, `-float('inf')`- [ ] Unicode characters, emoji, zero-width characters in string processing- [ ] Very long strings (memory exhaustion)- [ ] Deeply nested data structures (recursion limit: `sys.getrecursionlimit()`)- [ ] `bytes` vs `str` confusion (especially in Python 3)- [ ] Dictionary with unhashable keys (runtime TypeError)### 14.2 Timing Edge Cases- [ ] Leap years, DST transitions (`pytz` vs `zoneinfo` handling)- [ ] Timezone-naive vs timezone-aware datetime mixing- [ ] `datetime.utcnow()` deprecated in 3.12 (use `datetime.now(UTC)`)- [ ] `time.time()` precision differences across platforms- [ ] `timedelta` overflow with very large values- [ ] Calendar edge cases (February 29, month boundaries)- [ ] `dateutil.parser.parse()` ambiguous date formats### 14.3 Platform Edge Cases- [ ] File path handling across OS (`pathlib.Path` vs raw strings)- [ ] Line ending differences (`\n` vs `\r\n`)- [ ] File system case sensitivity differences- [ ] Maximum path length constraints (Windows 260 chars)- [ ] Locale-dependent string operations (`str.lower()` with Turkish locale)- [ ] Process/thread limits on different platforms- [ ] Signal handling differences (Windows vs Unix)---## OUTPUT FORMATFor each issue found, provide:### [SEVERITY: CRITICAL/HIGH/MEDIUM/LOW] Issue Title**Category**: [Type Safety/Security/Performance/Concurrency/etc.]**File**: path/to/file.py**Line**: 123-145**Impact**: Description of what could go wrong**Current Code**:```python# problematic code```**Problem**: Detailed explanation of why this is an issue**Recommendation**:```python# fixed code```**References**: Links to PEPs, documentation, CVEs, best practices---## PRIORITY MATRIX1. **CRITICAL** (Fix Immediately): - Security vulnerabilities (injection, `eval`, `pickle` on untrusted data) - Data loss / corruption risks - `eval()` / `exec()` with user input - Hardcoded secrets in source code2. **HIGH** (Fix This Sprint): - Mutable default arguments - Bare `except:` clauses - Missing `await` on coroutines - Resource leaks (unclosed files, connections) - Race conditions in threaded code3. **MEDIUM** (Fix Soon): - Missing type hints on public APIs - Code quality / idiom violations - Test coverage gaps - Performance issues in non-hot paths4. **LOW** (Tech Debt): - Style inconsistencies - Minor optimizations - Documentation gaps - Naming improvements---## STATIC ANALYSIS TOOLS TO RUNBefore manual review, run these tools and include findings:```bash# Type checking (strict mode)mypy --strict .# orpyright --pythonversion 3.12 .# Linting (comprehensive)ruff check --select ALL .# orflake8 --max-complexity 10 .pylint --enable=all .# Security scanningbandit -r . -llpip-auditsafety check# Dead code detectionvulture .# Complexity analysisradon cc . -a -ncradon mi . -nc# Import analysisimportlint .# or check circular imports:pydeps --noshow --cluster .# Dependency analysispipdeptree --warn silencedeptry .# Test coveragepytest --cov=. --cov-report=term-missing --cov-fail-under=80# Format checkruff format --check .# orblack --check .# Type coveragemypy --html-report typecoverage .```---## FINAL SUMMARYAfter completing the review, provide:1. **Executive Summary**: 2-3 paragraphs overview2. **Risk Assessment**: Overall risk level with justification3. **Top 10 Critical Issues**: Prioritized list4. **Recommended Action Plan**: Phased approach to fixes5. **Estimated Effort**: Time estimates for remediation6. **Metrics**: - Total issues found by severity - Code health score (1-10) - Security score (1-10) - Type safety score (1-10) - Maintainability score (1-10) - Test coverage percentage