Skip to content

Feat/ads optimization role#15

Open
GYFX35 wants to merge 17 commits intomainfrom
feat/ads-optimization-role
Open

Feat/ads optimization role#15
GYFX35 wants to merge 17 commits intomainfrom
feat/ads-optimization-role

Conversation

@GYFX35
Copy link
Copy Markdown
Owner

@GYFX35 GYFX35 commented Aug 18, 2025

Summary by Sourcery

Create a full-stack AI agent web application with multiple specialized roles, including a new ads optimization feature, complete with frontend interface, Flask backend, and containerized deployment support

New Features:

  • Add Flask backend with an /api/execute endpoint supporting 15+ AI assistant roles (developer, debugger, marketer, system analyzer, designer, educator, cybersecurity, business, public services, git helper, scam tracker, automation, astronaut, medical, and ads optimization)
  • Introduce a web-based frontend (HTML/CSS/JS) providing a grid UI to interact with each AI role
  • Implement ads optimization agent to generate ad copy and keyword suggestions for a given product or service

Build:

  • Add Dockerfile and Procfile to containerize the app with Gunicorn
  • Include backend requirements.txt and .gitignore for project setup

Documentation:

  • Overhaul README with detailed feature list, usage instructions, setup, and deployment guides

This commit introduces a significant redesign of the frontend user interface.

The main changes include:
- Restructured the layout from a single column to a responsive two-column grid for the agent sections.
- Implemented a new, cleaner color palette and a modern system font stack to improve aesthetics and readability.
- Refined the styling of all UI elements (buttons, inputs, etc.) with a more modern design, including subtle shadows and improved spacing.
I can now:
- Find royalty-free images and videos for you.
- Generate CSS code for simple animations, like a fade-in effect.
This change gives me a new "Educator" capability.

When you have a question, I can now provide a helpful search query to get you started on your research. This gives you a simple and effective way to look up topics.

I've updated the user interface to make this new feature available and added the necessary backend logic to support it.
…ialist.

If you give me a website URL, I can analyze its HTTP headers and report on the presence of key security headers. I've also updated our interface so you can select this new capability.
…plication for deployment.

With this update, I can now help you generate a business plan outline and suggest SEO keyword research queries.

To get the application ready for deployment, I have:
- Added `gunicorn` to `requirements.txt`.
- Created a `Dockerfile` for containerization.
- Added deployment instructions to your `README.md`.
…d added a new capability. I can now provide you with curated links to authoritative resources on various topics.

To get the application ready for deployment, I:
- Added a `Procfile` for Heroku.
- Pinned all dependencies in `requirements.txt` to ensure reproducible builds.
- Added Heroku deployment instructions to the `README.md`.
I can now take a branch name and commit message you provide and generate a shell script for you to review and run locally. The script will include the necessary commands to create a new branch, add all your changes, commit with your message, and push the new branch to origin.

This provides a safe, advisory way for me to help automate common tasks, while you maintain full control over running the commands.
This commit introduces two major improvements to the frontend UI:

1.  **Loading State Management:**
    - A full-page overlay with a spinner is now shown during API requests.
    - All agent buttons are disabled while a request is in progress to prevent multiple submissions.

2.  **Code Readability:**
    - The backend now returns code in a structured JSON format.
    - The frontend parses this response and applies a custom, regex-based syntax highlighter to HTML and CSS code blocks, improving readability.
This adds a temporary `index.html` file to the root of the repository. This is to test the GitHub Pages deployment by providing a file in the location where GitHub Pages expects to find one, which should resolve the 404 error.
…ew agent roles, improves the UI, and prepares your application for deployment.

Here are the specific changes I made:

New Agents:
- Business Developer
- Public Services
- Git Helper
- Cybersecurity Analyst
- Educator
- Designer

Improvements:
- I completed a full UI redesign for a modern look and feel.
- I added interactive loading states.
- I implemented custom syntax highlighting for code.

Deployment:
- I added a Dockerfile and Procfile.
- I pinned the project dependencies.
- I updated the README with deployment instructions.
I've added a new "Scam Tracker" capability. Now, when you provide a URL, I can perform a series of heuristic checks to identify potential red flags, including:
- Checking it against a list of common URL shorteners.
- Checking for suspicious Top-Level Domains (TLDs).
- Checking for common scam-related keywords in the URL string.

I will then report any flags I find. To implement this, I updated the frontend UI, added a new `scam_tracker_agent` function to the backend, and updated the documentation.
…tter fulfill your requests for "programming" and "web pages designing". Specifically, I can now:

- Generate a simple script when you ask for a "python script".
- Provide a sample CSS color scheme when you ask for a "color palette".
I've learned a new skill and can now provide you with safe, example scripts and data for a few specialized areas.

For instance, I can generate:
- An aerospace pre-flight checklist.
- A basic Python ROS script for robotics.
- Sample CAN bus data for automotive.

Please note that these examples are for educational purposes only and are not intended for use in real-world systems.
This change introduces a new "Astronaut" role to the AI agent for educational examples related to aerospace.

The Astronaut agent can:
- Generate a sample EVA spacesuit checklist.
- Generate a sample Python drone control script.

This feature is for educational purposes only and does not interact with real-world systems.

This includes updates to the frontend UI, a new `astronaut_agent` function in the backend, and updated documentation.
…I assistant.

The application is built with a Python Flask backend and a simple HTML/CSS/JS frontend. It provides a user interface for you to interact with various AI agents, each designed for a specific task.

The initial implementation includes the following agent roles:
- Software Engineer: Generates static websites and simple Python scripts.
- Debugger: Performs basic linting on HTML/CSS code.
- Marketer: Creates templated social media posts.
- System Analyzer: Finds broken links on a website.
- Designer: Finds creative assets and generates CSS.
- Educator: Provides search links for queries.
- Cybersecurity Analyst: Checks for security headers on a website.
- Business Developer: Generates business plan outlines.
- Public Services: Provides links to authoritative resources.
- Git Helper: Generates git commands as a shell script.
- Scam Tracker: Analyzes URLs for scam-related red flags.
- Automation & Specialized Domains: Provides educational example scripts for robotics, aerospace, etc.
- Medical Information: Provides a search link to an authoritative medical source with a prominent disclaimer.

The project includes a `Dockerfile` and a `Procfile` for easy deployment to containerized environments or platforms like Heroku. A detailed `README.md` is also included with setup, usage, and deployment instructions.
…I assistant.

The application is built with a Python Flask backend and a simple HTML/CSS/JS frontend. It provides a user interface for you to interact with various AI agents, each designed for a specific task.

The initial implementation includes the following agent roles:
- Software Engineer: Generates static websites and simple Python scripts.
- Debugger: Performs basic linting on HTML/CSS code.
- Marketer: Creates templated social media posts.
- System Analyzer: Finds broken links on a website.
- Designer: Finds creative assets and generates CSS.
- Educator: Provides search links for queries.
- Cybersecurity Analyst: Checks for security headers on a website.
- Business Developer: Generates business plan outlines.
- Public Services: Provides links to authoritative resources.
- Git Helper: Generates git commands as a shell script.
- Scam Tracker: Analyzes URLs for scam-related red flags.
- Automation & Specialized Domains: Provides educational example scripts for robotics, aerospace, etc.
- Medical Information: Provides a search link to an authoritative medical source with a prominent disclaimer.

The project includes a `Dockerfile` and a `Procfile` for easy deployment to containerized environments or platforms like Heroku. A detailed `README.md` is also included with setup, usage, and deployment instructions.
This commit introduces a new "Ads Optimization" role to the AI agent.

The new role provides users with suggestions for ad copy and keywords based on a given product or service.

The changes include:
- A new `optimize_ads_agent` function in `backend/main.py`.
- An `elif` block in the `execute` function to handle the new role.
- A new agent section in `frontend/templates/index.html` for the UI.
- JavaScript logic in `frontend/static/js/script.js` to connect the frontend to the backend.
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Aug 18, 2025

Reviewer's Guide

This PR introduces a full-stack multi-role AI Agent application: it restructures documentation, implements a unified backend /api/execute dispatcher with multiple agent handlers (including the new ads optimization role), builds a dynamic frontend interface to interact with each role, and adds containerization and deployment scaffolding.

Sequence diagram for unified agent request handling in backend

sequenceDiagram
    actor User
    participant Frontend
    participant Backend
    User->>Frontend: Select agent role and submit input
    Frontend->>Backend: POST /api/execute {role, prompt}
    alt Role is 'ads_optimization'
        Backend->>Backend: optimize_ads_agent(prompt)
    else Other role
        Backend->>Backend: <role>_agent(prompt)
    end
    Backend-->>Frontend: JSON response
    Frontend-->>User: Display agent response
Loading

Class diagram for agent dispatcher and handlers in backend

classDiagram
    class FlaskApp {
      +route /api/execute
      +render_template()
    }
    class AgentDispatcher {
      +execute(command)
    }
    class AgentHandler {
      +generate_website(prompt)
      +debug_code(prompt)
      +generate_social_media_post(prompt)
      +analyze_website(prompt)
      +designer_agent(prompt)
      +educator_agent(prompt)
      +cybersecurity_agent(prompt)
      +business_agent(prompt)
      +public_services_agent(prompt)
      +git_helper_agent(prompt)
      +scam_tracker_agent(prompt)
      +automation_agent(prompt)
      +medical_agent(prompt)
      +optimize_ads_agent(prompt)
    }
    FlaskApp --> AgentDispatcher
    AgentDispatcher --> AgentHandler
    AgentHandler <|.. optimize_ads_agent
    AgentHandler <|.. generate_website
    AgentHandler <|.. debug_code
    AgentHandler <|.. generate_social_media_post
    AgentHandler <|.. analyze_website
    AgentHandler <|.. designer_agent
    AgentHandler <|.. educator_agent
    AgentHandler <|.. cybersecurity_agent
    AgentHandler <|.. business_agent
    AgentHandler <|.. public_services_agent
    AgentHandler <|.. git_helper_agent
    AgentHandler <|.. scam_tracker_agent
    AgentHandler <|.. automation_agent
    AgentHandler <|.. medical_agent
Loading

File-Level Changes

Change Details Files
Overhauled project documentation
  • Expanded README to describe project overview and multi-role features
  • Added usage instructions per agent and examples
  • Included setup, installation, and deployment guides (Docker, Heroku)
README.md
Implemented backend execution endpoint with multi-role dispatch
  • Added Flask /api/execute route that routes requests by role
  • Integrated 15+ agent functions with structured text and code responses, including new ads_optimization handler
  • Added backend dependencies and Heroku Procfile
backend/main.py
backend/requirements.txt
Procfile
Built frontend UI with dynamic agent interactions
  • Created HTML template with grid-based agent sections, including Ads Optimization
  • Styled layout, components, and loader in CSS
  • Added JS event listeners and sendCommand logic for each role, handling code/text responses
frontend/templates/index.html
frontend/static/css/style.css
frontend/static/js/script.js
Configured containerization and deployment scaffolding
  • Added Dockerfile for building and running the app in a container
  • Provided root index.html for GitHub Pages deployment test
  • Included a .gitignore to exclude transient files
Dockerfile
index.html
.gitignore

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@guardrails
Copy link
Copy Markdown

guardrails bot commented Aug 18, 2025

⚠️ We detected 3 security issues in this pull request:

Insecure Access Control (1)
Severity Details Docs
High Title: Missing User Instruction
FROM python:3.11-slim
📚

More info on how to fix Insecure Access Control in Dockerfile.


Vulnerable Libraries (2)
Severity Details
High pkg:pypi/werkzeug@2.3.8 (t) upgrade to: 3.0.3
High pkg:pypi/flask@2.2.2 (t) upgrade to: 2.3.2

More info on how to fix Vulnerable Libraries in Python.


👉 Go to the dashboard for detailed results.

📥 Happy? Share your feedback with us.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • User controlled data in methods like innerHTML, outerHTML or document.write is an anti-pattern that can lead to XSS vulnerabilities (link)
  • User controlled data in a code.innerHTML is an anti-pattern that can lead to XSS vulnerabilities (link)
  • HTML generation does not escape user-provided content. (link)
  • Sanitization uses URL encoding for shell commands. (link)
  • Frontend uses 'medical_info' role, backend expects 'medical'. (link)

General comments:

  • Replace the long if/elif chain in execute() with a mapping of role names to handler functions to improve scalability.
  • Ensure that role identifiers are consistent between the frontend (e.g. 'medical_info') and backend (expects 'medical') to prevent silent failures.
  • Consider using a battle-tested syntax highlighting library instead of custom regexes to ensure robust multi-language support.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Replace the long if/elif chain in execute() with a mapping of role names to handler functions to improve scalability.
- Ensure that role identifiers are consistent between the frontend (e.g. 'medical_info') and backend (expects 'medical') to prevent silent failures.
- Consider using a battle-tested syntax highlighting library instead of custom regexes to ensure robust multi-language support.

## Individual Comments

### Comment 1
<location> `backend/main.py:64` </location>
<code_context>
+    }
+    return jsonify(response)
+
+def generate_website(prompt):
+    import datetime
+
+    # New: Check for Python script request
+    if 'python script' in prompt.lower():
+        script_prompt = prompt.lower().replace('python script to', '').strip()
+        py_script = f"""
+# This is a Python script generated by the AI Agent.
+# Your request was: '{script_prompt}'
+
+def main():
+    # A simple example: print "Hello, World!"
+    print("Hello, World!")
+
+if __name__ == "__main__":
+    main()
+"""
+        return {
+            "type": "code_single",
+            "payload": {
</code_context>

<issue_to_address>
Python script generation is hardcoded and not dynamic.

The generated script does not adapt to different prompts and always outputs the same code. Please consider implementing logic to generate scripts based on the user's request, or notify users when only a static template is provided.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    if 'python script' in prompt.lower():
        script_prompt = prompt.lower().replace('python script to', '').strip()
        py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'

def main():
    # A simple example: print "Hello, World!"
    print("Hello, World!")

if __name__ == "__main__":
    main()
"""
        return {
            "type": "code_single",
            "payload": {
                "language": "python",
                "filename": "script.py",
                "content": py_script.strip()
            }
        }
=======
    if 'python script' in prompt.lower():
        script_prompt = prompt.lower().replace('python script to', '').strip()
        # Basic dynamic generation for demonstration
        if "print" in script_prompt:
            # Extract message to print
            import re
            match = re.search(r'print\s+[\'"](.+)[\'"]', script_prompt)
            if match:
                message = match.group(1)
            else:
                # Fallback to generic message
                message = "Hello, World!"
            py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'

def main():
    print("{message}")

if __name__ == "__main__":
    main()
"""
            notify = None
        elif "add" in script_prompt and "numbers" in script_prompt:
            py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'

def main():
    a = 2
    b = 3
    print("Sum:", a + b)

if __name__ == "__main__":
    main()
"""
            notify = None
        else:
            # Static template with notification
            py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'
# NOTE: Only a static template was provided. Please specify your request more clearly for dynamic generation.

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()
"""
            notify = "Only a static template was provided. Please specify your request more clearly for dynamic generation."

        payload = {
            "language": "python",
            "filename": "script.py",
            "content": py_script.strip()
        }
        if notify:
            payload["notification"] = notify
        return {
            "type": "code_single",
            "payload": payload
        }
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `backend/main.py:119` </location>
<code_context>
+    footer_content = structure.get('footer', '')
+
+    main_content = ""
+    for section in structure['sections']:
+        main_content += f"    <section>\n"
+        main_content += f"      <h2>{section.get('title', '')}</h2>\n"
+        if 'text' in section['content']:
+            main_content += f"      <p>{section['content']['text']}</p>\n"
+        if 'images' in section['content']:
+            try:
+                num_images = int(section['content']['images'])
+                for i in range(num_images):
+                    main_content += f"      <img src='https://via.placeholder.com/150' alt='placeholder image {i+1}'>\n"
+            except ValueError:
+                pass # Ignore if 'images' is not a number
+        main_content += f"    </section>\n"
+
+    html_content = f"""
</code_context>

<issue_to_address>
HTML generation does not escape user-provided content.

Directly inserting user content into HTML without escaping can allow HTML injection. Please escape all user-provided values before rendering.
</issue_to_address>

### Comment 3
<location> `backend/main.py:209` </location>
<code_context>
+    else:
+        lang = 'CSS'
+        # CSS checks
+        if code.count('{') != code.count('}'):
+            errors.append("Mismatched curly braces {}.")
+
+        lines = code.split('\n')
+        in_block = False
+        for i, line in enumerate(lines):
+            line = line.strip()
+            if '{' in line:
</code_context>

<issue_to_address>
CSS semicolon check may produce false positives.

Refine the semicolon check to exclude comments and closing braces, reducing false positives.
</issue_to_address>

### Comment 4
<location> `backend/main.py:514` </location>
<code_context>
+
+    return "Sorry, I don't have specific resources for that topic yet. Please try 'climate change', 'agriculture', or 'biodiversity'."
+
+def git_helper_agent(prompt):
+    """
+    Generates a shell script for Git commands based on user input.
+    """
+    branch = prompt.get('branch', 'new-feature')
+    commit_message = prompt.get('commitMessage', 'New changes')
+    repo_url = "https://github.com/gyfx35/AI-services" # Hardcoded for safety
+
+    # Basic validation
+    if not branch or not commit_message:
+        return "Error: Branch name and commit message are required."
+
+    # Sanitize inputs to prevent command injection
+    safe_branch = quote(branch)
+    safe_commit_message = quote(commit_message)
+
</code_context>

<issue_to_address>
Sanitization uses URL encoding for shell commands.

URL encoding is not sufficient for shell command sanitization. Use shlex.quote or a shell-specific escaping method to better protect against command injection.
</issue_to_address>

### Comment 5
<location> `frontend/static/js/script.js:95` </location>
<code_context>
+        sendCommand('astronaut', input);
+    });
+
+    medicalBtn.addEventListener('click', () => {
+        const input = document.getElementById('medical-input').value;
+        sendCommand('medical_info', input);
+    });
+
</code_context>

<issue_to_address>
Frontend uses 'medical_info' role, backend expects 'medical'.

This role mismatch will block medical queries. Please align the role names across frontend and backend.
</issue_to_address>

## Security Issues

### Issue 1
<location> `frontend/static/js/script.js:166` </location>

<issue_to_address>
**security (javascript.browser.security.insecure-document-method):** User controlled data in methods like `innerHTML`, `outerHTML` or `document.write` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

### Issue 2
<location> `frontend/static/js/script.js:166` </location>

<issue_to_address>
**security (javascript.browser.security.insecure-innerhtml):** User controlled data in a `code.innerHTML` is an anti-pattern that can lead to XSS vulnerabilities

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +68 to +88
if 'python script' in prompt.lower():
script_prompt = prompt.lower().replace('python script to', '').strip()
py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'

def main():
# A simple example: print "Hello, World!"
print("Hello, World!")

if __name__ == "__main__":
main()
"""
return {
"type": "code_single",
"payload": {
"language": "python",
"filename": "script.py",
"content": py_script.strip()
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Python script generation is hardcoded and not dynamic.

The generated script does not adapt to different prompts and always outputs the same code. Please consider implementing logic to generate scripts based on the user's request, or notify users when only a static template is provided.

Suggested change
if 'python script' in prompt.lower():
script_prompt = prompt.lower().replace('python script to', '').strip()
py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'
def main():
# A simple example: print "Hello, World!"
print("Hello, World!")
if __name__ == "__main__":
main()
"""
return {
"type": "code_single",
"payload": {
"language": "python",
"filename": "script.py",
"content": py_script.strip()
}
}
if 'python script' in prompt.lower():
script_prompt = prompt.lower().replace('python script to', '').strip()
# Basic dynamic generation for demonstration
if "print" in script_prompt:
# Extract message to print
import re
match = re.search(r'print\s+[\'"](.+)[\'"]', script_prompt)
if match:
message = match.group(1)
else:
# Fallback to generic message
message = "Hello, World!"
py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'
def main():
print("{message}")
if __name__ == "__main__":
main()
"""
notify = None
elif "add" in script_prompt and "numbers" in script_prompt:
py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'
def main():
a = 2
b = 3
print("Sum:", a + b)
if __name__ == "__main__":
main()
"""
notify = None
else:
# Static template with notification
py_script = f"""
# This is a Python script generated by the AI Agent.
# Your request was: '{script_prompt}'
# NOTE: Only a static template was provided. Please specify your request more clearly for dynamic generation.
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
"""
notify = "Only a static template was provided. Please specify your request more clearly for dynamic generation."
payload = {
"language": "python",
"filename": "script.py",
"content": py_script.strip()
}
if notify:
payload["notification"] = notify
return {
"type": "code_single",
"payload": payload
}

Comment on lines +119 to +128
for section in structure['sections']:
main_content += f" <section>\n"
main_content += f" <h2>{section.get('title', '')}</h2>\n"
if 'text' in section['content']:
main_content += f" <p>{section['content']['text']}</p>\n"
if 'images' in section['content']:
try:
num_images = int(section['content']['images'])
for i in range(num_images):
main_content += f" <img src='https://via.placeholder.com/150' alt='placeholder image {i+1}'>\n"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 issue (security): HTML generation does not escape user-provided content.

Directly inserting user content into HTML without escaping can allow HTML injection. Please escape all user-provided values before rendering.

Comment on lines +209 to +214
if code.count('{') != code.count('}'):
errors.append("Mismatched curly braces {}.")

lines = code.split('\n')
in_block = False
for i, line in enumerate(lines):
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: CSS semicolon check may produce false positives.

Refine the semicolon check to exclude comments and closing braces, reducing false positives.

Comment on lines +514 to +523
def git_helper_agent(prompt):
"""
Generates a shell script for Git commands based on user input.
"""
branch = prompt.get('branch', 'new-feature')
commit_message = prompt.get('commitMessage', 'New changes')
repo_url = "https://github.com/gyfx35/AI-services" # Hardcoded for safety

# Basic validation
if not branch or not commit_message:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 issue (security): Sanitization uses URL encoding for shell commands.

URL encoding is not sufficient for shell command sanitization. Use shlex.quote or a shell-specific escaping method to better protect against command injection.

Comment on lines +95 to +97
medicalBtn.addEventListener('click', () => {
const input = document.getElementById('medical-input').value;
sendCommand('medical_info', input);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Frontend uses 'medical_info' role, backend expects 'medical'.

This role mismatch will block medical queries. Please align the role names across frontend and backend.

Comment on lines +174 to +187
function highlight(code, language) {
let highlightedCode = code;
if (language === 'html') {
highlightedCode = highlightedCode.replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Highlight tags
highlightedCode = highlightedCode.replace(/(&lt;\/?[\w\s="/.':;#-/?&]+&gt;)/g, '<span class="hl-tag">$1</span>');
} else if (language === 'css') {
// Highlight selectors
highlightedCode = highlightedCode.replace(/(^|[\s\S]*?})([\s\S]*?)(?={)/g, '$1<span class="hl-selector">$2</span>');
// Highlight properties
highlightedCode = highlightedCode.replace(/([a-zA-Z-]+)(?=:)/g, '<span class="hl-property">$1</span>');
}
return highlightedCode;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Avoid function declarations, favouring function assignment expressions, inside blocks. (avoid-function-declarations-in-blocks)

ExplanationFunction declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers. Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you should use function expressions, which create functions in-scope.

Comment on lines +347 to +370
if 'animation' in prompt or 'script' in prompt:
if 'fade in' in prompt:
css_snippet = """
/* CSS for a fade-in animation */
.fade-in {
animation: fadeIn 1s ease-in-out;
}

@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
return {
"type": "code_single",
"payload": {
"language": "css",
"content": css_snippet.strip()
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Merge nested if conditions (merge-nested-ifs)

Suggested change
if 'animation' in prompt or 'script' in prompt:
if 'fade in' in prompt:
css_snippet = """
/* CSS for a fade-in animation */
.fade-in {
animation: fadeIn 1s ease-in-out;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
return {
"type": "code_single",
"payload": {
"language": "css",
"content": css_snippet.strip()
}
}
if ('animation' in prompt or 'script' in prompt) and 'fade in' in prompt:
css_snippet = """
/* CSS for a fade-in animation */
.fade-in {
animation: fadeIn 1s ease-in-out;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
"""
return {
"type": "code_single",
"payload": {
"language": "css",
"content": css_snippet.strip()
}
}


ExplanationToo much nesting can make code difficult to understand, and this is especially
true in Python, where there are no brackets to help out with the delineation of
different nesting levels.

Reading deeply nested code is confusing, since you have to keep track of which
conditions relate to which levels. We therefore strive to reduce nesting where
possible, and the situation where two if conditions can be combined using
and is an easy win.

Comment on lines +273 to +280
else:
message = f"Found {len(broken_links)} broken links on {url}:\n\n"
for link in broken_links:
query = f"'{link}' on page '{url}' is a broken link"
search_url = f"https://www.google.com/search?q={quote(query)}"
message += f"- Broken Link: {link}\n"
message += f" Suggested Search: {search_url}\n\n"
return message
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): We've found these issues:

Suggested change
else:
message = f"Found {len(broken_links)} broken links on {url}:\n\n"
for link in broken_links:
query = f"'{link}' on page '{url}' is a broken link"
search_url = f"https://www.google.com/search?q={quote(query)}"
message += f"- Broken Link: {link}\n"
message += f" Suggested Search: {search_url}\n\n"
return message
message = f"Found {len(broken_links)} broken links on {url}:\n\n"
for link in broken_links:
query = f"'{link}' on page '{url}' is a broken link"
search_url = f"https://www.google.com/search?q={quote(query)}"
message += f"- Broken Link: {link}\n"
message += f" Suggested Search: {search_url}\n\n"
return message

Comment on lines +500 to +506
found_topic = None
for topic in resources.keys():
if topic in prompt:
found_topic = topic
break

if found_topic:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): We've found these issues:

Suggested change
found_topic = None
for topic in resources.keys():
if topic in prompt:
found_topic = topic
break
if found_topic:
if found_topic := next(
(topic for topic in resources if topic in prompt), None
):

# 2. Check for suspicious TLDs
suspicious_tlds = ['.xyz', '.top', '.loan', '.stream', '.gdn', '.mom']
if parsed_url.hostname and any(parsed_url.hostname.endswith(tld) for tld in suspicious_tlds):
red_flags.append(f"URL uses a suspicious Top-Level Domain (TLD) that is common in scams.")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): We've found these issues:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant