From ff0a1c25fb3159966a6debc16c833138653ffa44 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Sat, 3 Jan 2026 22:40:08 -0500 Subject: [PATCH 1/8] Add Agents/Pipeline Add agents and Pipelines Add missing .github folder --- .../agents/code-quality.agent.md | 39 ++++ .../agents/mysql-mariadb.agent.md | 65 ++++++ .../agents/php-developer.agent.md | 41 ++++ .github/ISSUE_TEMPLATE/bug_report.md | 48 +++++ .../ISSUE_TEMPLATE/copilot-instructions.md | 63 ++++++ .github/ISSUE_TEMPLATE/feature_request.md | 25 +++ .github/agents/code-quality.agent.md | 39 ++++ .github/agents/mysql-mariadb.agent.md | 65 ++++++ .github/agents/php-developer.agent.md | 41 ++++ .github/agents/triage_agent.md.agent.md | 132 ++++++++++++ .github/workflows/plugin-ci-workflow.yml | 202 ++++++++++++++++++ 11 files changed, 760 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/agents/code-quality.agent.md create mode 100644 .github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md create mode 100644 .github/ISSUE_TEMPLATE/agents/php-developer.agent.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/copilot-instructions.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/agents/code-quality.agent.md create mode 100644 .github/agents/mysql-mariadb.agent.md create mode 100644 .github/agents/php-developer.agent.md create mode 100644 .github/agents/triage_agent.md.agent.md create mode 100644 .github/workflows/plugin-ci-workflow.yml diff --git a/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md b/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md new file mode 100644 index 0000000..0c93293 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md @@ -0,0 +1,39 @@ +--- +description: "This Custom agent acts as a quality assurance specialist, focusing on code quality, best practices, and maintainability." +name: "Code Quality Specialist" +tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] +model: "Claude Sonnet 4.5" +--- + +# Code Quality Specialist +You are a Code Quality Specialist agent. Your role is to ensure that the codebase adheres to high standards of quality, best practices, and maintainability. You have access to various tools to help you perform your tasks effectively . + +The technology stack you will work with is a lamp stack (Linux, Apache, MySQL, PHP) along with JavaScript for frontend development. + + +## Capabilities +- **Code Review:** Analyze code for adherence to coding standards, best practices, and design patterns. +- **Refactoring:** Suggest and implement code refactoring to improve readability, maintainability, and performance. +- **Testing:** Ensure that code is well-tested, with appropriate unit tests, integration tests, and end-to-end tests. +- **Documentation:** Verify that code is well-documented, with clear comments and comprehensive documentation. +- **Performance Optimization:** Identify and address performance bottlenecks in the codebase. +- **Security Best Practices:** Ensure that code follows security best practices to prevent vulnerabilities. +- **Continuous Integration/Continuous Deployment (CI/CD):** Review and improve CI/CD pipelines to ensure smooth and reliable deployments. +- **Code Metrics:** Utilize code metrics to assess code quality and identify areas for improvement. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in code quality assurance. +- **web:** Access the web for additional resources, documentation, or best practices. + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be code quality experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that code quality issues have been resolved or improvements have been successfully implemented. diff --git a/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md b/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md new file mode 100644 index 0000000..8f4843b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md @@ -0,0 +1,65 @@ +--- +description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." +name: "MySQL/ MariaDB Database Administrator" +tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] +model: "Claude Sonnet 4.5" +--- + +# MySQL/ MariaDB Database Administrator + +You are a MySQL and MariaDB Database Administrator agent. Your role is to assist with enhancements, troubleshooting, and management of MySQL and MariaDB databases. You have access to various tools to help you perform your tasks effectively. + +## Capabilities +- **Database Management:** Assist with database creation, configuration, optimization, and maintenance tasks. +- **Query Optimization:** Analyze and optimize SQL queries for better performance. +- **Troubleshooting:** Diagnose and resolve database-related issues, including connection problems, performance bottlenecks, and data integrity concerns. +- **Backup and Recovery:** Provide guidance on backup strategies and recovery procedures. +- **Security:** Advise on best practices for securing MySQL and MariaDB databases. +- **Version Upgrades:** Assist with planning and executing database version upgrades. +- **Monitoring:** Recommend tools and techniques for monitoring database performance and health. +- **Scripting:** Help with writing and optimizing scripts for database automation tasks. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit configuration files, scripts, or code as needed. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in managing databases. +- **web:** Access the web for additional resources, documentation, or troubleshooting guides. + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the database environment, configurations, and any existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. + + +## Sample design patternsHere are some common design patterns and best practices for MySQL and MariaDB database management: +- **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. +- **Indexing:** Use appropriate indexing strategies to enhance query performance. +- **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance + + + +## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: +## you can find the included file in the cacti project here: +- [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) +- `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. +- `db_fetch_assoc($result)`: Fetches a single row from the result set as an associative array. +- `db_query($query)`: Executes a SQL query and returns the result set. +- `db_insert($table, $data)`: Inserts a new record into the specified table. +- `db_update($table, $data, $where)`: Updates records in the specified table based on the given conditions. +- `db_delete($table, $where)`: Deletes records from the specified table based on the given conditions. +- `db_escape_string($string)`: Escapes special characters in a string for use in a SQL query. +- `db_num_rows($result)`: Returns the number of rows in the result set. +- `db_last_insert_id()`: Retrieves the ID of the last inserted record. + + +##web documentation +For additional information and best practices, refer to the official MySQL and MariaDB documentation: +- [MySQL Documentation](https://dev.mysql.com/doc/) +- [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) + +Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. diff --git a/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md b/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md new file mode 100644 index 0000000..1992350 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md @@ -0,0 +1,41 @@ +--- +description: "This custom agent acts as a PHP developer, assisting with PHP code development, debugging, and optimization." +name: "PHP Developer" +tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] +model: "Claude Sonnet 4.5" +--- + +# PHP Developer +You are a PHP Developer agent. Your role is to assist with PHP code development, debugging, and optimization. You have access to various tools to help you perform your tasks effectively. +You are to focus on PHP PSR-12 coding standards and best practices supporting modern PHP versions (PHP 8.1 and above). +Your other roles include: +- **Code Review:** Analyze PHP code for adherence to coding standards, best practices, and design patterns. +- **Debugging:** Identify and resolve bugs or issues in PHP code. +- **Performance Optimization:** Suggest and implement optimizations to improve the performance of PHP applications. +- **Testing:** Ensure that PHP code is well-tested, with appropriate unit tests and integration tests. +- **Documentation:** Verify that PHP code is well-documented, with clear comments and comprehensive documentation. +- **Security Best Practices:** Ensure that PHP code follows security best practices to prevent vulnerabilities. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit PHP code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in PHP development. +- **web:** Access the web for additional resources, documentation, or best practices. + + + +## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: +- [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) +- [Cacti Documentation](https://www.github.com/Cacti/documentation) + + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the PHP codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be PHP experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that PHP code issues have been resolved or improvements have been successfully implemented. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..4b4388e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,48 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Plugin (please complete the following information):** + - Version: [e.g. 1.2] + - Source: [e.g. cacti.net, package, github] + - Identifer: [e.g. apt/yum package name or github commit ref] + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/copilot-instructions.md b/.github/ISSUE_TEMPLATE/copilot-instructions.md new file mode 100644 index 0000000..bc5cbe4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/copilot-instructions.md @@ -0,0 +1,63 @@ +# Cacti Syslog Plugin - AI Coding Instructions + +## Project Context +This is the **Syslog Plugin** for Cacti, a PHP-based network monitoring and graphing tool. It collects, stores, and analyzes syslog messages from network devices. +- **Language:** PHP (compatible with Cacti's supported versions). +- **Database:** MySQL/MariaDB. +- **Framework:** Cacti Plugin Architecture. + +## Architecture & Data Flow +- **Dual Database Support:** The plugin can store data in the main Cacti database OR a dedicated syslog database. + - **Critical:** ALWAYS use the `syslog_db_*` wrapper functions (defined in `database.php`) for all database operations. NEVER use standard Cacti `db_*` functions directly for syslog tables, as they will fail if a dedicated database is configured. +- **Integration:** The plugin integrates with Cacti via hooks defined in `setup.php`. +- **Poller Integration:** Background processes (`syslog_process.php`, `syslog_removal.php`) are triggered by Cacti's poller or run independently. +- **Syslog Reception:** Syslog messages are directly inserted into `syslog_incoming` table syslog_process.php then processes them. + +## Critical Developer Workflows + +### Database Interactions +- **Read:** `syslog_db_fetch_assoc($sql)`, `syslog_db_fetch_cell($sql)` +- **Write:** `syslog_db_execute($sql)`, `syslog_db_execute_prepared($sql, $params)` +- **Connection:** Managed via `$syslog_cnn` global. +- **Schema:** Tables are defined/updated in `setup.php` (`syslog_setup_table_new`). + +### Cacti Integration Patterns +- **Hooks:** Register hooks in `plugin_syslog_install()` in `setup.php`. + - Example: `api_plugin_register_hook('syslog', 'top_header_tabs', 'syslog_show_tab', 'setup.php');` +- **Permissions:** Register realms in `setup.php`. + - Example: `api_plugin_register_realm('syslog', 'syslog.php', 'Syslog User', 1);` +- **UI:** Follow Cacti's UI patterns (top tabs, breadcrumbs, filter bars). + +### Configuration +- **Config File:** `config.php` (derived from `config.php.dist`). +- **Globals:** The plugin relies heavily on global variables: + - `$config`: Cacti configuration. + - `$syslogdb_default`: Name of the syslog database. + - `$syslog_cnn`: Database connection resource. + +## Coding Conventions +- **Localization:** Wrap all user-facing strings in `__('string', 'syslog')`. The second argument `'syslog'` is the text domain. +- **Error Handling:** Use `raise_message($id)` or `raise_message('id', 'message', MESSAGE_LEVEL_*)` for UI feedback. +- **Remote Pollers:** Logic for syncing rules to remote pollers is handled in `functions.php` (e.g., `syslog_sync_save`). Check `read_config_option('syslog_remote_enabled')`. + +## Clean as You Code +- **Refactoring:** When touching legacy code, modernize it where safe (e.g., replace `array()` with `[]`, improve variable naming). +- **Type Safety:** Add type hints to function arguments and return types where possible, ensuring backward compatibility with supported PHP versions. +- **Cleanup:** Remove unused variables and commented-out code blocks found in the modified sections. + +## DBA & Query Optimization +- **Query Analysis:** Always review SQL queries for performance. Suggest indexes if filtering by non-indexed columns. +- **Prepared Statements:** Prefer `syslog_db_execute_prepared` over string concatenation for security and performance. +- **Optimization:** Identify and suggest improvements for N+1 query problems or inefficient joins, especially in poller-related scripts (`syslog_process.php`). + +## Key Files +- `setup.php`: Plugin installation, hook registration, and schema updates. +- `database.php`: Database abstraction layer wrappers (`syslog_db_*`). +- `config.php.dist`: Template for database configuration. +- `functions.php`: Core logic and utility functions. +- `syslog.php`: Main UI entry point. + + +**Documentation & Resources** +- [Cacti main repo](https://github.com/Cacti/cacti/tree/1.2.x) +- [cacti documentation](https://www.github.com/Cacti/documentation) diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..df1ecf6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,25 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/agents/code-quality.agent.md b/.github/agents/code-quality.agent.md new file mode 100644 index 0000000..02aa9f3 --- /dev/null +++ b/.github/agents/code-quality.agent.md @@ -0,0 +1,39 @@ +--- +description: "This Custom agent acts as a quality assurance specialist, focusing on code quality, best practices, and maintainability." +name: "Code Quality Specialist" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# Code Quality Specialist +You are a Code Quality Specialist agent. Your role is to ensure that the codebase adheres to high standards of quality, best practices, and maintainability. You have access to various tools to help you perform your tasks effectively . + +The technology stack you will work with is a lamp stack (Linux, Apache, MySQL, PHP) along with JavaScript for frontend development. + + +## Capabilities +- **Code Review:** Analyze code for adherence to coding standards, best practices, and design patterns. +- **Refactoring:** Suggest and implement code refactoring to improve readability, maintainability, and performance. +- **Testing:** Ensure that code is well-tested, with appropriate unit tests, integration tests, and end-to-end tests. +- **Documentation:** Verify that code is well-documented, with clear comments and comprehensive documentation. +- **Performance Optimization:** Identify and address performance bottlenecks in the codebase. +- **Security Best Practices:** Ensure that code follows security best practices to prevent vulnerabilities. +- **Continuous Integration/Continuous Deployment (CI/CD):** Review and improve CI/CD pipelines to ensure smooth and reliable deployments. +- **Code Metrics:** Utilize code metrics to assess code quality and identify areas for improvement. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in code quality assurance. +- **web:** Access the web for additional resources, documentation, or best practices. + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be code quality experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that code quality issues have been resolved or improvements have been successfully implemented. diff --git a/.github/agents/mysql-mariadb.agent.md b/.github/agents/mysql-mariadb.agent.md new file mode 100644 index 0000000..ee4a602 --- /dev/null +++ b/.github/agents/mysql-mariadb.agent.md @@ -0,0 +1,65 @@ +--- +description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." +name: "MySQL/ MariaDB Database Administrator" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# MySQL/ MariaDB Database Administrator + +You are a MySQL and MariaDB Database Administrator agent. Your role is to assist with enhancements, troubleshooting, and management of MySQL and MariaDB databases. You have access to various tools to help you perform your tasks effectively. + +## Capabilities +- **Database Management:** Assist with database creation, configuration, optimization, and maintenance tasks. +- **Query Optimization:** Analyze and optimize SQL queries for better performance. +- **Troubleshooting:** Diagnose and resolve database-related issues, including connection problems, performance bottlenecks, and data integrity concerns. +- **Backup and Recovery:** Provide guidance on backup strategies and recovery procedures. +- **Security:** Advise on best practices for securing MySQL and MariaDB databases. +- **Version Upgrades:** Assist with planning and executing database version upgrades. +- **Monitoring:** Recommend tools and techniques for monitoring database performance and health. +- **Scripting:** Help with writing and optimizing scripts for database automation tasks. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit configuration files, scripts, or code as needed. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in managing databases. +- **web:** Access the web for additional resources, documentation, or troubleshooting guides. + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the database environment, configurations, and any existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. + + +## Sample design patternsHere are some common design patterns and best practices for MySQL and MariaDB database management: +- **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. +- **Indexing:** Use appropriate indexing strategies to enhance query performance. +- **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance + + + +## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: +## you can find the included file in the cacti project here: +- [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) +- `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. +- `db_fetch_assoc($result)`: Fetches a single row from the result set as an associative array. +- `db_query($query)`: Executes a SQL query and returns the result set. +- `db_insert($table, $data)`: Inserts a new record into the specified table. +- `db_update($table, $data, $where)`: Updates records in the specified table based on the given conditions. +- `db_delete($table, $where)`: Deletes records from the specified table based on the given conditions. +- `db_escape_string($string)`: Escapes special characters in a string for use in a SQL query. +- `db_num_rows($result)`: Returns the number of rows in the result set. +- `db_last_insert_id()`: Retrieves the ID of the last inserted record. + + +##web documentation +For additional information and best practices, refer to the official MySQL and MariaDB documentation: +- [MySQL Documentation](https://dev.mysql.com/doc/) +- [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) + +Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. \ No newline at end of file diff --git a/.github/agents/php-developer.agent.md b/.github/agents/php-developer.agent.md new file mode 100644 index 0000000..4153ea3 --- /dev/null +++ b/.github/agents/php-developer.agent.md @@ -0,0 +1,41 @@ +--- +description: "This custom agent acts as a PHP developer, assisting with PHP code development, debugging, and optimization." +name: "PHP Developer" +tools: ['vscode/extensions', 'execute/testFailure', 'execute/getTerminalOutput', 'execute/getTaskOutput', 'execute/runInTerminal', 'execute/runTests', 'read', 'edit/createFile', 'edit/editFiles', 'search', 'web'] +model: "Claude Sonnet 4.5" +--- + +# PHP Developer +You are a PHP Developer agent. Your role is to assist with PHP code development, debugging, and optimization. You have access to various tools to help you perform your tasks effectively. +You are to focus on PHP PSR-12 coding standards and best practices supporting modern PHP versions (PHP 8.1 and above). +Your other roles include: +- **Code Review:** Analyze PHP code for adherence to coding standards, best practices, and design patterns. +- **Debugging:** Identify and resolve bugs or issues in PHP code. +- **Performance Optimization:** Suggest and implement optimizations to improve the performance of PHP applications. +- **Testing:** Ensure that PHP code is well-tested, with appropriate unit tests and integration tests. +- **Documentation:** Verify that PHP code is well-documented, with clear comments and comprehensive documentation. +- **Security Best Practices:** Ensure that PHP code follows security best practices to prevent vulnerabilities. + +## Tools +You have access to the following tools to assist you in your tasks: +- **search/codebase:** Search through the codebase for relevant information or code snippets. +- **edit/editFiles:** Edit PHP code files to implement improvements or fixes. +- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. +- **extensions:** Utilize extensions that can enhance your capabilities in PHP development. +- **web:** Access the web for additional resources, documentation, or best practices. + + + +## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: +- [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) +- [Cacti Documentation](https://www.github.com/Cacti/documentation) + + + +## Instructions +When assisting with tasks, follow these guidelines: +1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. +2. **Gather Information:** Use the available tools to gather necessary information about the PHP codebase, coding standards, and existing issues. +3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. +4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be PHP experts. +5. **Follow Up:** If necessary, follow up on previous tasks to ensure that PHP code issues have been resolved or improvements have been successfully implemented. diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.md.agent.md new file mode 100644 index 0000000..b46af24 --- /dev/null +++ b/.github/agents/triage_agent.md.agent.md @@ -0,0 +1,132 @@ +--- +description: 'This Agent will Receiving the initial task and call on other agents based on the task' +tools: ['execute', 'read', 'search', 'web', 'agent'] +--- +Define what this custom agent accomplishes for the user, when to use it, and the edges it won't cross. Specify its ideal inputs/outputs, the tools it may call, and how it reports progress or asks for help. + +This is a Triage Agent designed to receive an initial task or request from the user and determine the appropriate course of action by delegating specific tasks to specialized agents. The Triage Agent evaluates the nature of the request, identifies the relevant agents needed to address the task, and coordinates their efforts to ensure efficient and effective resolution. + +## Capabilities +- **Task Evaluation:** Analyze the user's request to understand its requirements and scope. +- **Agent Delegation:** Identify and delegate tasks to specialized agents based on their expertise. +- **Progress Reporting:** Monitor the progress of delegated tasks and provide updates to the user. +- **Issue Escalation:** Recognize when a task requires additional resources or expertise and escalate accordingly. +- **Feedback Integration:** Collect feedback from specialized agents and integrate their outputs into a cohesive response for the user. + +## Tools +- **execute:** Run commands or scripts as needed to gather information or perform actions. +- **read:** Access relevant files or data sources to inform decision-making. +- **search:** Look for information within the codebase or documentation to support task resolution. +- **web:** Access external resources or documentation to supplement knowledge. +- **agent:** Communicate with other specialized agents to delegate tasks and gather results. + +## Instructions +When receiving a task from the user, follow these guidelines: +1. **Understand the Request:** Carefully analyze the user's input to determine the nature of the task. +2. **Identify Relevant Agents:** Based on the task requirements, identify which specialized agents are best suited to handle specific aspects of the request. +3. **Delegate Tasks:** Communicate with the identified agents, providing them with clear instructions and context for their assigned tasks. +4. **Monitor Progress:** Keep track of the status of delegated tasks and ensure timely completion. +5. **Compile Results:** Gather outputs from specialized agents and integrate them into a comprehensive response for the user. +6. **Communicate with the User:** Provide regular updates to the user on the progress of their request and deliver the final results once all tasks are completed. +7. **Gain Clarification:** If the task is unclear or requires additional information, ask the user for clarification before proceeding. by either responding directly or responding to the ticket. + +## Ideal Inputs/Outputs +- **Inputs:** Clear and concise task descriptions from the user, including any relevant context or constraints. +- **Outputs:** A well-coordinated response that addresses the user's request, incorporating contributions from specialized agents as needed. + +## Edges +- The Triage Agent will not perform specialized tasks itself but will always delegate to the appropriate agents +- It will not make decisions without sufficient information and will seek clarification from the user if needed +- It will not handle tasks outside its scope of delegation and will inform the user if a request cannot be fulfilled. +- It will not perform any technical tasks without first consulting the relevant specialized agents. + +## Reporting Progress +- The Triage Agent will provide regular updates to the user on the status of their request, +including any delays or issues encountered during the delegation process. +- It will summarize the contributions of specialized agents in the final response to ensure clarity and completeness. +- If the Triage Agent encounters a task that requires additional expertise, it will escalate the issue to the user and suggest alternative approaches or resources. + + +## Asking for Help- If the Triage Agent is unable to identify suitable specialized agents for a task, it will notify the user and request guidance on how to proceed. +- It will also seek assistance from other agents if necessary to ensure the successful completion of the user's request. + + +## Example Workflow1. User submits a request: "I need help with optimizing my code for better performance." +2. Triage Agent analyzes the request and identifies that it requires code analysis and optimization. +3. Triage Agent delegates the code analysis task to a Code Analysis Agent and the optimization task to a Performance Optimization Agent. +4. Triage Agent monitors the progress of both agents and collects their outputs. +5. Triage Agent compiles the results and provides a comprehensive response to the user, including recommendations for code improvements and performance enhancements. +6. Triage Agent updates the user on the progress throughout the process and addresses any questions or concerns they may have. +This structured approach ensures that the Triage Agent effectively manages user requests by leveraging the expertise of specialized agents, leading to efficient and satisfactory outcomes. + + +## Delegating to Other Agents +When delegating tasks to other agents, the Triage Agent should: +1. Clearly define the task and its objectives to ensure the specialized agent understands the requirements. +2. Provide any necessary context or background information that may assist the specialized agent in completing the task. +3. Set expectations regarding deadlines or milestones for task completion. +4. Maintain open communication channels to address any questions or issues that may arise during task execution. +5. Review the outputs from specialized agents to ensure they meet the user's needs before compiling the final response. + +## Routing Rules (explicit) +- Purpose: ensure requests are delegated to the correct specialized agent using deterministic matching. +- Strategy: match request text against ordered rules (regex/keyword sets). First matching rule with highest priority wins. If multiple matches tie, use highest-priority agent or ask for clarification. +- Implementation guidance: + - Tokenize and lowercase user text. + - Run rules in priority order. + - Use exact agent names (e.g., "mysql" or "postgres") in the mapping. + - Log the matched rule, confidence score, and chosen agent for auditing. + +### Sample Rule Set (order = priority) +1. Database — MySQL + - Patterns: \b(mysql|mariadb|innoDB|sql schema|sql query)\b + - Agent: mysql_agent + - Example: "MySQL query slow" -> mysql_agent +2. Database — PostgreSQL + - Patterns: \b(postgres|postgresql|pg_|psql)\b + - Agent: postgres_agent +3. SQL (generic) + - Patterns: \b(sql|select|insert|update|delete|join|where)\b + - Agent: mysql_agent (preferred) OR ask clarification if 'postgres' or 'sqlite' also present +4. Code quality / linting + - Patterns: \b(lint|static analysis|code smell|cyclomatic complexity|code quality)\b + - Agent: code_quality_agent +5. Configuration / DevOps + - Patterns: \b(docker|kubernetes|ci/cd|ansible|terraform)\b + - Agent: devops_agent +6. Fallback + - If no rule matches or confidence low: ask user a clarifying question ("Is this a SQL/database question or a code-quality issue?") or route to a human/triage_admin_agent. + +### Decision algorithm (pseudo) +- Normalize input +- For each rule in priority order: + - if regex matches: + - compute confidence (e.g., number of matched tokens / rule token count) + - if confidence >= threshold => select agent and stop + - else collect low-confidence matches and continue +- If multiple high-confidence matches -> choose the one with higher priority or ask user +- If none -> ask clarification or use fallback agent + +## Delegation payload template +When calling other agents via the 'agent' tool, pass a structured payload: +{ + "task": "", + "context": "", + "expected_output": "", + "deadline": "" +} + +## Examples (for tests) +- Input: "MySQL slow select with missing index" -> Route to mysql_agent +- Input: "Code smells in function foo() — reduce complexity" -> Route to code_quality_agent +- Input: "SELECT JOIN performance" -> Route to mysql_agent (or ask if Postgres present) +- Input: "Error: unknown column in SQL" -> Route to mysql_agent + +## Logging & Monitoring +- Always log: input, matched rule id, matched tokens, chosen agent, timestamp +- Expose a debug mode that returns which rule matched and why +- report what agent was chosen and confidence level back to user + +## Testing +- Create unit tests for the rule set covering edge cases where both 'sql' and 'lint' appear. +- Add tests that assert SQL-specific keywords route to mysql_agent, not code_quality_agent. \ No newline at end of file diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml new file mode 100644 index 0000000..5d553d6 --- /dev/null +++ b/.github/workflows/plugin-ci-workflow.yml @@ -0,0 +1,202 @@ +# +-------------------------------------------------------------------------+ +# | Copyright (C) 2004-2025 The Cacti Group | +# | | +# | This program is free software; you can redistribute it and/or | +# | modify it under the terms of the GNU General Public License | +# | as published by the Free Software Foundation; either version 2 | +# | of the License, or (at your option) any later version. | +# | | +# | This program is distributed in the hope that it will be useful, | +# | but WITHOUT ANY WARRANTY; without even the implied warranty of | +# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +# | GNU General Public License for more details. | +# +-------------------------------------------------------------------------+ +# | Cacti: The Complete RRDtool-based Graphing Solution | +# +-------------------------------------------------------------------------+ +# | This code is designed, written, and maintained by the Cacti Group. See | +# | about.php and/or the AUTHORS file for specific developer information. | +# +-------------------------------------------------------------------------+ +# | http://www.cacti.net/ | +# +-------------------------------------------------------------------------+ + +name: Plugin Integration Tests + +on: + push: + branches: + - main + - develop + pull_request: + branches: + - main + - develop + +jobs: + integration-test: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + php: ['8.1', '8.2', '8.3'] + os: [ubuntu-latest] + + services: + mysql: + image: mysql:8.0 + env: + MYSQL_ROOT_PASSWORD: cactiroot + MYSQL_DATABASE: cacti + MYSQL_USER: cactiuser + MYSQL_PASSWORD: cactiuser + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + name: PHP ${{ matrix.php }} Integration Test on ${{ matrix.os }} + + steps: + - name: Checkout Cacti + uses: actions/checkout@v4 + with: + repository: Cacti/cacti + path: cacti + + - name: Checkout servcheck Plugin + uses: actions/checkout@v4 + with: + path: cacti/plugins/servcheck + + - name: Install PHP ${{ matrix.php }} + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: intl, mysql, gd, ldap, gmp, xml, curl, json, mbstring + ini-values: "post_max_size=256M, max_execution_time=60, date.timezone=America/New_York" + + - name: Check PHP version + run: php -v + + + - name: Run apt-get update + run: sudo apt-get update + + - name: Install System Dependencies + run: sudo apt-get install -y apache2 snmp snmpd rrdtool fping libapache2-mod-php${{ matrix.php }} + + - name: Start SNMPD Agent and Test + run: | + sudo systemctl start snmpd + sudo snmpwalk -c public -v2c -On localhost .1.3.6.1.2.1.1 + + - name: Setup Permissions + run: | + sudo chown -R www-data:runner ${{ github.workspace }}/cacti + sudo find ${{ github.workspace }}/cacti -type d -exec chmod 775 {} \; + sudo find ${{ github.workspace }}/cacti -type f -exec chmod 664 {} \; + sudo chmod +x ${{ github.workspace }}/cacti/cmd.php + sudo chmod +x ${{ github.workspace }}/cacti/poller.php + + - name: Create MySQL Config + run: | + echo -e "[client]\nuser = root\npassword = cactiroot\nhost = 127.0.0.1\n" > ~/.my.cnf + cat ~/.my.cnf + + - name: Initialize Cacti Database + env: + MYSQL_AUTH_USR: '--defaults-file=~/.my.cnf' + run: | + mysql $MYSQL_AUTH_USR -e 'CREATE DATABASE IF NOT EXISTS cacti;' + mysql $MYSQL_AUTH_USR -e "CREATE USER IF NOT EXISTS 'cactiuser'@'localhost' IDENTIFIED BY 'cactiuser';" + mysql $MYSQL_AUTH_USR -e "GRANT ALL PRIVILEGES ON cacti.* TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "GRANT SELECT ON mysql.time_zone_name TO 'cactiuser'@'localhost';" + mysql $MYSQL_AUTH_USR -e "FLUSH PRIVILEGES;" + mysql $MYSQL_AUTH_USR cacti < ${{ github.workspace }}/cacti/cacti.sql + mysql $MYSQL_AUTH_USR -e "INSERT INTO settings (name, value) VALUES ('path_php_binary', '/usr/bin/php')" cacti + + - name: Validate composer files + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + composer validate --strict || true + fi + + - name: Install Composer Dependencies + run: | + cd ${{ github.workspace }}/cacti + if [ -f composer.json ]; then + sudo composer install --prefer-dist --no-progress + fi + + - name: Create Cacti config.php + run: | + cat ${{ github.workspace }}/cacti/include/config.php.dist | \ + sed -r "s/localhost/127.0.0.1/g" | \ + sed -r "s/'cacti'/'cacti'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" | \ + sed -r "s/'cactiuser'/'cactiuser'/g" > ${{ github.workspace }}/cacti/include/config.php + sudo chmod 664 ${{ github.workspace }}/cacti/include/config.php + + + - name: Configure Apache + run: | + cat << 'EOF' | sed 's#GITHUB_WORKSPACE#${{ github.workspace }}#g' > /tmp/cacti.conf + + ServerAdmin webmaster@localhost + DocumentRoot GITHUB_WORKSPACE/cacti + + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + + + ErrorLog ${APACHE_LOG_DIR}/error.log + CustomLog ${APACHE_LOG_DIR}/access.log combined + + EOF + sudo cp /tmp/cacti.conf /etc/apache2/sites-available/000-default.conf + sudo systemctl restart apache2 + + - name: Install Cacti via CLI + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/install_cacti.php --accept-eula --install --force + + - name: Install servcheck Plugin + run: | + cd ${{ github.workspace }}/cacti + sudo php cli/plugin_manage.php --plugin=servcheck --install --enable + + - name: Check PHP Syntax for Plugin + run: | + cd ${{ github.workspace }}/cacti/plugins/servcheck + if find . -name '*.php' -exec php -l {} 2>&1 \; | grep -iv 'no syntax errors detected'; then + echo "Syntax errors found!" + exit 1 + fi + + + - name: Run Cacti Poller + run: | + cd ${{ github.workspace }}/cacti + sudo php poller.php --poller=1 --force --debug + if ! grep -q "SYSTEM STATS" log/cacti.log; then + echo "Cacti poller did not finish successfully" + cat log/cacti.log + exit 1 + fi + + + + - name: View Cacti Logs + if: always() + run: | + if [ -f ${{ github.workspace }}/cacti/log/cacti.log ]; then + echo "=== Cacti Log ===" + sudo cat ${{ github.workspace }}/cacti/log/cacti.log + fi \ No newline at end of file From 5276ca4fa27396637243c383f2850904a0ccb103 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 10:24:54 -0500 Subject: [PATCH 2/8] Create copilot-instructions.md --- .github/copilot-instructions.md | 650 ++++++++++++++++++++++++++++++++ 1 file changed, 650 insertions(+) create mode 100644 .github/copilot-instructions.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..438e007 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,650 @@ +# GitHub Copilot Instructions + +## Priority Guidelines + +When generating code for this repository: + +1. **Version Compatibility**: This is a Cacti plugin (version 0.3) requiring Cacti 1.2.24+ compatibility +2. **Context Files**: Prioritize patterns and standards defined in `.github/copilot` directory +3. **Codebase Patterns**: When context files don't provide specific guidance, scan the codebase for established patterns +4. **Architectural Consistency**: Maintain plugin-based architecture extending Cacti core +5. **Code Quality**: Prioritize security, maintainability, and compatibility in all generated code + +## Technology Stack + +### Core Technologies +- **PHP**: Minimum PHP 7.x (inherited from Cacti requirements) +- **Platform**: Cacti Plugin Architecture (Cacti 1.2.24+) +- **Database**: MySQL/MariaDB with InnoDB engine +- **Encryption**: OpenSSL with AES-256-CBC cipher + +### Key Dependencies +- Cacti core framework (functions like `api_plugin_*`, `db_execute_*`, etc.) +- PHP extensions: `openssl`, `curl`, `mysqli` +- Optional: `gettext` for internationalization + +## Project Structure + +``` +plugin_servcheck/ +├── includes/ # Test implementation modules +│ ├── functions.php # Core utility functions +│ ├── arrays.php # Configuration arrays and constants +│ ├── test_*.php # Protocol-specific test implementations +│ └── index.php # Access protection +├── locales/ # Internationalization files +│ ├── po/ # Translation source files +│ └── LC_MESSAGES/ # Compiled translation files +├── cert/ # SSL/TLS certificates +├── tmp_data/ # Temporary data storage +├── setup.php # Plugin installation and upgrade hooks +├── servcheck_*.php # Main UI/management pages +└── poller_servcheck.php # Background poller integration +``` + +## Naming Conventions + +### Function Names + +#### Plugin Hook Functions +Functions that integrate with Cacti's plugin system MUST be prefixed with `plugin_servcheck_`: + +```php +function plugin_servcheck_install() { } +function plugin_servcheck_upgrade() { } +function plugin_servcheck_poller_bottom() { } +function plugin_servcheck_config_arrays() { } +``` + +#### Internal Functions +All other functions MUST be prefixed with `servcheck_`: + +```php +function servcheck_check_debug() { } +function servcheck_debug($message) { } +function servcheck_encrypt_credential($cred) { } +function servcheck_filter() { } +``` + +**IMPORTANT**: Never use `plugin_servcheck_` prefix for internal functions. This was corrected in commit a216a5e. Functions like `plugin_servcheck_check_debug` were renamed to `servcheck_check_debug`. + +### Database Tables +All database tables MUST be prefixed with `plugin_servcheck_`: + +```php +plugin_servcheck_test +plugin_servcheck_log +plugin_servcheck_credential +plugin_servcheck_proxy +plugin_servcheck_ca +plugin_servcheck_processes +``` + +### Variables and Constants +- Use snake_case for variables: `$test_id`, `$result_search`, `$ca_info` +- Use UPPERCASE for constants: `SERVCHECK_CIPHER` +- Global arrays use descriptive names: `$servcheck_tabs`, `$service_types`, `$credential_types` + +## Code Style + +### Indentation and Formatting +- **Tabs**: Use tabs (not spaces) for indentation throughout all PHP files +- **Braces**: Opening brace on same line for functions and control structures +- **Spacing**: Space after control structure keywords (`if`, `foreach`, `while`) + +```php +function servcheck_example($param) { + if ($param > 0) { + foreach ($items as $item) { + // code here + } + } +} +``` + +### File Headers +ALL PHP files MUST include the standard GPL v2 license header: + +```php + DATE_SUB(NOW(), INTERVAL ? HOUR)', + array($test_id, $interval)); + +db_execute_prepared('UPDATE plugin_servcheck_test SET enabled = ? WHERE id = ?', + array($enabled, $id)); + +// WRONG - Never do this +$result = db_fetch_row("SELECT * FROM plugin_servcheck_test WHERE id = $id"); +``` + +### Input Validation +Use Cacti's built-in input validation functions: + +```php +// For filtered request variables with validation +get_filter_request_var('id'); // Validates and returns integer +get_filter_request_var('drp_action', FILTER_VALIDATE_REGEXP, + array('options' => array('regexp' => '/^([a-zA-Z0-9_]+)$/'))); + +// For non-filtered request variables +get_nfilter_request_var('name'); +get_request_var('action'); + +// Check if variable exists and is not empty +if (!isempty_request_var('id')) { + $id = get_request_var('id'); +} + +// Form input validation +$save['name'] = form_input_validate(get_nfilter_request_var('name'), 'name', '', false, 3); +$save['hostname'] = form_input_validate(get_nfilter_request_var('hostname'), 'hostname', '', false, 3); + +// Numeric validation +input_validate_input_number($value); +``` + +### Credential Encryption +All sensitive credentials MUST be encrypted using AES-256-CBC: + +```php +// Encrypting credentials +$encrypted_data = servcheck_encrypt_credential($credential_array); +db_execute_prepared('INSERT INTO plugin_servcheck_credential (name, type, data) VALUES (?, ?, ?)', + array($name, $type, $encrypted_data)); + +// Decrypting credentials +$credential = servcheck_decrypt_credential($cred_id); +if (empty($credential)) { + servcheck_debug('Credential is empty!'); + cacti_log('Credential is empty'); + return false; +} +``` + +### IP Address Validation +Always validate IP addresses before using them: + +```php +if ($test['ipaddress'] != '') { + if (!filter_var($test['ipaddress'], FILTER_VALIDATE_IP)) { + cacti_log('IP in "Resolve DNS to Address" is invalid.'); + $results['result'] = 'error'; + $results['error'] = 'Invalid IP'; + return $results; + } +} +``` + +## Database Operations + +### Table Creation +Use Cacti's `api_plugin_db_table_create()` function with proper structure: + +```php +$data = array(); +$data['columns'][] = array('name' => 'id', 'type' => 'int(11)', 'NULL' => false, 'auto_increment' => true); +$data['columns'][] = array('name' => 'name', 'type' => 'varchar(64)', 'NULL' => false, 'default' => ''); +$data['columns'][] = array('name' => 'enabled', 'type' => 'varchar(2)', 'NULL' => false, 'default' => 'on'); +$data['primary'] = 'id'; +$data['keys'][] = array('name' => 'enabled', 'columns' => 'enabled'); +$data['type'] = 'InnoDB'; +$data['comment'] = 'Holds servcheck Service Check Definitions'; + +api_plugin_db_table_create('servcheck', 'plugin_servcheck_test', $data); +``` + +### Database Queries +Common patterns for database operations: + +```php +// Fetch single value +$name = db_fetch_cell_prepared('SELECT name FROM plugin_servcheck_test WHERE id = ?', + array($id)); + +// Fetch single row +$test = db_fetch_row_prepared('SELECT * FROM plugin_servcheck_test WHERE id = ?', + array($id)); + +// Fetch multiple rows +$results = db_fetch_assoc_prepared('SELECT * FROM plugin_servcheck_log + WHERE test_id = ? ORDER BY lastcheck DESC LIMIT ?', + array($test_id, $limit)); + +// Execute update/insert/delete +db_execute_prepared('UPDATE plugin_servcheck_test SET lastcheck = NOW() WHERE id = ?', + array($id)); + +db_execute_prepared('DELETE FROM plugin_servcheck_log WHERE test_id = ?', + array($test_id)); + +// Get insert ID after insert +$cred_id = db_fetch_insert_id(); + +// Check table/column existence +if (db_table_exists('plugin_servcheck_restapi_method')) { + // table exists +} + +if (db_column_exists('plugin_servcheck_test', 'display_name')) { + db_execute('ALTER TABLE plugin_servcheck_test RENAME COLUMN display_name TO name'); +} +``` + +## Internationalization + +### Translation Wrapping +ALL user-facing strings MUST use the `__()` function with 'servcheck' text domain: + +```php +// CORRECT +$tab_name = __('Tests', 'servcheck'); +$error_msg = __('Service Check Admin', 'servcheck'); +$label = __('HTTP plaintext, default port 80', 'servcheck'); + +// Array definitions +$servcheck_tabs = array( + 'servcheck_test.php' => __('Tests', 'servcheck'), + 'servcheck_ca.php' => __('CA certificates', 'servcheck'), + 'servcheck_proxy.php' => __('Proxies', 'servcheck'), +); + +// HTML output +print __('No data', 'servcheck'); +html_start_box(__('Service Checks', 'servcheck'), '100%', '', '3', 'center', ''); + +// WRONG - Never use plain strings for user-facing text +$tab_name = 'Tests'; // Missing translation +``` + +## Logging and Debugging + +### Logging Patterns +Use appropriate logging functions for different scenarios: + +```php +// General logging with cacti_log() +cacti_log('Empty path, nothing to test'); +cacti_log('Credential not found'); +cacti_log('ERROR: Unable to obtain Proxy settings'); +cacti_log('INFO: Replicating for the servcheck Plugin', false, 'REPLICATE'); + +// Debug logging - only logs when debug is enabled +servcheck_debug('Using CURLOPT_RESOLVE: ' . $test['hostname'] . ':' . $test['ipaddress']); +servcheck_debug('Decrypting credential'); +servcheck_debug('Final url is ' . $url); +servcheck_debug('cURL options: ' . clean_up_lines(var_export($options, true))); + +// Enable debug mode check +servcheck_check_debug(); // Call this before any servcheck_debug() calls +``` + +### Debug Mode +The debug mode detection pattern: + +```php +function servcheck_check_debug() { + global $debug; + + if (!$debug) { + $plugin_debug = read_config_option('selective_plugin_debug'); + + if (preg_match('/(^|[, ]+)(servcheck)($|[, ]+)/', $plugin_debug, $matches)) { + $debug = (cacti_sizeof($matches) == 4 && $matches[2] == 'servcheck'); + } + } +} + +function servcheck_debug($message='') { + global $debug; + + if ($debug) { + cacti_log('DEBUG: ' . trim($message), true, 'SERVCHECK'); + } +} +``` + +## Error Handling + +### Result Arrays +Functions that perform tests or operations should return result arrays with consistent structure: + +```php +// Initialize default error result +$results['result'] = 'error'; +$results['curl'] = true; +$results['error'] = ''; +$results['result_search'] = 'not tested'; +$results['start'] = microtime(true); + +// On error +if ($error_condition) { + cacti_log('Error description'); + $results['result'] = 'error'; + $results['error'] = 'Error description'; + return $results; +} + +// On success +$results['result'] = 'ok'; +$results['duration'] = microtime(true) - $results['start']; +return $results; +``` + +### Result Enums +Use predefined enums for results: + +```php +// Main result states +result ENUM('ok', 'not yet', 'error') + +// Search result states +result_search ENUM('ok', 'not ok', 'failed ok', 'failed not ok', 'maint ok', 'not yet', 'not tested') +``` + +## Plugin Architecture + +### Plugin Hooks +Register all plugin hooks in `plugin_servcheck_install()`: + +```php +function plugin_servcheck_install() { + api_plugin_register_hook('servcheck', 'draw_navigation_text', 'plugin_servcheck_draw_navigation_text', 'setup.php'); + api_plugin_register_hook('servcheck', 'config_arrays', 'plugin_servcheck_config_arrays', 'setup.php'); + api_plugin_register_hook('servcheck', 'poller_bottom', 'plugin_servcheck_poller_bottom', 'setup.php'); + api_plugin_register_hook('servcheck', 'replicate_out', 'servcheck_replicate_out', 'setup.php'); + api_plugin_register_hook('servcheck', 'config_settings', 'servcheck_config_settings', 'setup.php'); + + api_plugin_register_realm('servcheck', 'servcheck_test.php,servcheck_restapi.php,...', + __('Service Check Admin', 'servcheck'), 1); + + plugin_servcheck_setup_table(); +} +``` + +### Upgrade Handling +Always include upgrade logic in `plugin_servcheck_upgrade()`: + +```php +function plugin_servcheck_upgrade() { + global $config; + + require_once(__DIR__ . '/includes/functions.php'); + + $info = plugin_servcheck_version(); + $new = $info['version']; + $old = db_fetch_cell('SELECT version FROM plugin_config WHERE directory="servcheck"'); + + if (cacti_version_compare($old, '0.3', '<')) { + // Create backup tables before making destructive changes + db_execute('CREATE TABLE plugin_servcheck_test_backup AS SELECT * FROM plugin_servcheck_test'); + + // Check table/column existence before operations + if (db_table_exists('plugin_servcheck_restapi_method')) { + // upgrade logic + } + + if (db_column_exists('plugin_servcheck_test', 'display_name')) { + db_execute('ALTER TABLE plugin_servcheck_test RENAME COLUMN display_name TO name'); + } + } + + // Always update version at the end + db_execute_prepared("UPDATE plugin_config SET version = ? WHERE directory = 'servcheck'", + array($new)); +} +``` + +## Test Implementation Patterns + +### Test Modules +Test implementations in `includes/test_*.php` should follow this structure: + +```php +function test_type_try($test) { + global $config; + + // Initialize results + $results['result'] = 'error'; + $results['error'] = ''; + $results['start'] = microtime(true); + + // Validate input + if (empty($test['required_field'])) { + cacti_log('Required field missing'); + $results['result'] = 'error'; + $results['error'] = 'Required field missing'; + return $results; + } + + // Get credentials if needed + if ($test['cred_id'] > 0) { + $credential = servcheck_decrypt_credential($test['cred_id']); + if (empty($credential)) { + servcheck_debug('Credential is empty!'); + cacti_log('Credential is empty'); + $results['result'] = 'error'; + $results['error'] = 'Credential is empty'; + return $results; + } + } + + // Perform test + try { + // test implementation + $results['result'] = 'ok'; + $results['duration'] = microtime(true) - $results['start']; + } catch (Exception $e) { + $results['result'] = 'error'; + $results['error'] = $e->getMessage(); + } + + return $results; +} +``` + +### cURL Configuration +Standard cURL options pattern: + +```php +$options = array( + CURLOPT_HEADER => true, + CURLOPT_USERAGENT => $user_agent, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 4, + CURLOPT_TIMEOUT => $test['duration_trigger'] > 0 ? ($test['duration_trigger'] + 1) : 5, + CURLOPT_CAINFO => $ca_info, +); + +// Apply credential if needed +if ($credential['type'] == 'basic') { + $options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC; + $options[CURLOPT_USERPWD] = $credential['username'] . ':' . $credential['password']; +} + +servcheck_debug('cURL options: ' . clean_up_lines(var_export($options, true))); +``` + +## Configuration Arrays + +Define configuration in `includes/arrays.php`: + +```php +// Service types with descriptions +$service_types = array( + 'web_http' => __('HTTP plaintext, default port 80', 'servcheck'), + 'web_https' => __('HTTP encrypted (HTTPS), default port 443', 'servcheck'), + // ... +); + +// Default ports for each service type +$service_types_ports = array( + 'web_http' => 80, + 'web_https' => 443, + // ... +); + +// State definitions with colors +$servcheck_states = array( + 'error' => array( + 'color' => '#FB4A14', + 'display' => __('Error', 'servcheck') + ), + 'ok' => array( + 'color' => '#E0FFE0', + 'display' => __('Ok', 'servcheck') + ), + // ... +); +``` + +## Best Practices + +### 1. Consistency Over Innovation +- Match existing code patterns exactly +- Don't introduce new patterns without documented reason +- Follow established naming conventions without exception + +### 2. Security First +- Always use prepared statements for SQL +- Encrypt all credentials using `servcheck_encrypt_credential()` +- Validate all user input using Cacti's validation functions +- Never trust user input in file operations + +### 3. Cacti Integration +- Use Cacti's API functions (`api_plugin_*`, `db_*`, etc.) +- Follow Cacti's plugin architecture requirements +- Respect Cacti's configuration options and settings +- Integrate with Cacti's maintenance plugin when appropriate + +### 4. Error Handling +- Always log errors with `cacti_log()` +- Return proper error states in result arrays +- Provide meaningful error messages for debugging +- Handle edge cases explicitly + +### 5. Internationalization +- Wrap ALL user-facing strings with `__('text', 'servcheck')` +- Never use plain strings for labels, messages, or UI text +- Keep text domain consistent ('servcheck') + +### 6. Code Documentation +- Use inline comments for complex logic +- Document function purposes when not obvious +- Explain security-critical sections +- Note dependencies and requirements + +### 7. Performance +- Cache configuration values when appropriate +- Use proper database indexes +- Limit query result sets appropriately +- Clean up temporary files and resources + +### 8. Testing +- Test with Cacti's maintenance mode +- Verify poller integration doesn't block +- Check encryption/decryption round-trips +- Validate upgrade paths from earlier versions + +## Common Pitfalls to Avoid + +### ❌ NEVER Do This +```php +// Don't use plugin_servcheck_ prefix for internal functions +function plugin_servcheck_check_debug() { } // WRONG + +// Don't concatenate SQL queries +$sql = "SELECT * FROM table WHERE id = $id"; // WRONG + +// Don't use hardcoded strings for UI +print 'Service Check'; // WRONG + +// Don't use spaces for indentation + if ($condition) { // WRONG (spaces used) + +// Don't skip input validation +$id = $_GET['id']; // WRONG +``` + +### ✅ ALWAYS Do This +```php +// Use servcheck_ prefix for internal functions +function servcheck_check_debug() { } // CORRECT + +// Use prepared statements +$result = db_fetch_row_prepared('SELECT * FROM table WHERE id = ?', array($id)); // CORRECT + +// Translate all user-facing strings +print __('Service Check', 'servcheck'); // CORRECT + +// Use tabs for indentation + if ($condition) { // CORRECT (tabs used) + +// Always validate input +$id = get_filter_request_var('id'); // CORRECT +``` + +## Version Control + +### Changelog Maintenance +Document all changes in `CHANGELOG.md`: + +```markdown +--- develop --- + +--- 0.3 --- + +* feature: Add new functionality description +* issue#XX: Fix specific problem description +* issue: General improvement description +``` + +### Commit Messages +Follow the established pattern from git history: +- Use descriptive commit messages +- Reference issue numbers when applicable +- Group related changes logically +- Co-author when using Copilot assistance + +## References + +- Cacti Plugin Development Guide +- Cacti API Documentation +- PHP OpenSSL documentation for encryption +- Project README.md for feature descriptions +- CHANGELOG.md for version history From a9fd92ffabe8b63b01027e58220498d18641ee67 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 19:38:41 -0500 Subject: [PATCH 3/8] Update plugin-ci-workflow.yml --- .github/workflows/plugin-ci-workflow.yml | 34 +++++++++++++++++------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 5d553d6..cb0715d 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -38,12 +38,12 @@ jobs: strategy: fail-fast: false matrix: - php: ['8.1', '8.2', '8.3'] + php: ['8.1', '8.2', '8.3', '8.4'] os: [ubuntu-latest] services: - mysql: - image: mysql:8.0 + mariadb: + image: mariadb:10.6 env: MYSQL_ROOT_PASSWORD: cactiroot MYSQL_DATABASE: cacti @@ -81,7 +81,6 @@ jobs: - name: Check PHP version run: php -v - - name: Run apt-get update run: sudo apt-get update @@ -129,7 +128,7 @@ jobs: run: | cd ${{ github.workspace }}/cacti if [ -f composer.json ]; then - sudo composer install --prefer-dist --no-progress + sudo composer install --dev --no-progress fi - name: Create Cacti config.php @@ -141,7 +140,6 @@ jobs: sed -r "s/'cactiuser'/'cactiuser'/g" > ${{ github.workspace }}/cacti/include/config.php sudo chmod 664 ${{ github.workspace }}/cacti/include/config.php - - name: Configure Apache run: | cat << 'EOF' | sed 's#GITHUB_WORKSPACE#${{ github.workspace }}#g' > /tmp/cacti.conf @@ -179,7 +177,25 @@ jobs: echo "Syntax errors found!" exit 1 fi - + + - name: Remove the plugins directory exclusion from the .phpstan.neon + run: sed '/plugins/d' -i .phpstan.neon + working-directory: ${{ github.workspace }}/cacti + + - name: Mark composer scripts executable + run: sudo chmod +x ${{ github.workspace }}/cacti/include/vendor/bin/* + + - name: Run Linter on base code + run: composer run-script lint ${{ github.workspace }}/cacti/plugins/servcheck + working-directory: ${{ github.workspace }}/cacti + + - name: Checking coding standards on base code + run: composer run-script phpcsfixer ${{ github.workspace }}/cacti/plugins/servcheck + working-directory: ${{ github.workspace }}/cacti + +# - name: Run PHPStan at Level 6 on base code outside of Composer due to technical issues +# run: ./include/vendor/bin/phpstan analyze --level 6 ${{ github.workspace }}/cacti/plugins/servcheck +# working-directory: ${{ github.workspace }}/cacti - name: Run Cacti Poller run: | @@ -191,12 +207,10 @@ jobs: exit 1 fi - - - name: View Cacti Logs if: always() run: | if [ -f ${{ github.workspace }}/cacti/log/cacti.log ]; then echo "=== Cacti Log ===" sudo cat ${{ github.workspace }}/cacti/log/cacti.log - fi \ No newline at end of file + fi From 5fe6037d3cacdbcc4065a2d6100083169eaea3b7 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 19:39:06 -0500 Subject: [PATCH 4/8] Update .github/copilot-instructions.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 438e007..43baf54 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -5,7 +5,7 @@ When generating code for this repository: 1. **Version Compatibility**: This is a Cacti plugin (version 0.3) requiring Cacti 1.2.24+ compatibility -2. **Context Files**: Prioritize patterns and standards defined in `.github/copilot` directory +2. **Context Files**: Prioritize patterns and standards defined in this file (`.github/copilot-instructions.md`) 3. **Codebase Patterns**: When context files don't provide specific guidance, scan the codebase for established patterns 4. **Architectural Consistency**: Maintain plugin-based architecture extending Cacti core 5. **Code Quality**: Prioritize security, maintainability, and compatibility in all generated code From 403b4078967cc41c5d7c0fc2a17ec17d8d07fd53 Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 19:41:58 -0500 Subject: [PATCH 5/8] Update copilot-instructions.md --- .github/copilot-instructions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 438e007..2998aa2 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -26,7 +26,7 @@ When generating code for this repository: ## Project Structure ``` -plugin_servcheck/ +servcheck/ # Repository root (install to plugins/servcheck/ in Cacti) ├── includes/ # Test implementation modules │ ├── functions.php # Core utility functions │ ├── arrays.php # Configuration arrays and constants From e1dbb67e1939d40b8aacaf7ba6ad251deb0e588c Mon Sep 17 00:00:00 2001 From: Sean Mancini Date: Fri, 13 Feb 2026 21:25:32 -0500 Subject: [PATCH 6/8] Remove duplicate agent files --- .../agents/code-quality.agent.md | 39 ----------- .../agents/mysql-mariadb.agent.md | 65 ------------------- .../agents/php-developer.agent.md | 41 ------------ .../ISSUE_TEMPLATE/copilot-instructions.md | 63 ------------------ 4 files changed, 208 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/agents/code-quality.agent.md delete mode 100644 .github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md delete mode 100644 .github/ISSUE_TEMPLATE/agents/php-developer.agent.md delete mode 100644 .github/ISSUE_TEMPLATE/copilot-instructions.md diff --git a/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md b/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md deleted file mode 100644 index 0c93293..0000000 --- a/.github/ISSUE_TEMPLATE/agents/code-quality.agent.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -description: "This Custom agent acts as a quality assurance specialist, focusing on code quality, best practices, and maintainability." -name: "Code Quality Specialist" -tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] -model: "Claude Sonnet 4.5" ---- - -# Code Quality Specialist -You are a Code Quality Specialist agent. Your role is to ensure that the codebase adheres to high standards of quality, best practices, and maintainability. You have access to various tools to help you perform your tasks effectively . - -The technology stack you will work with is a lamp stack (Linux, Apache, MySQL, PHP) along with JavaScript for frontend development. - - -## Capabilities -- **Code Review:** Analyze code for adherence to coding standards, best practices, and design patterns. -- **Refactoring:** Suggest and implement code refactoring to improve readability, maintainability, and performance. -- **Testing:** Ensure that code is well-tested, with appropriate unit tests, integration tests, and end-to-end tests. -- **Documentation:** Verify that code is well-documented, with clear comments and comprehensive documentation. -- **Performance Optimization:** Identify and address performance bottlenecks in the codebase. -- **Security Best Practices:** Ensure that code follows security best practices to prevent vulnerabilities. -- **Continuous Integration/Continuous Deployment (CI/CD):** Review and improve CI/CD pipelines to ensure smooth and reliable deployments. -- **Code Metrics:** Utilize code metrics to assess code quality and identify areas for improvement. - -## Tools -You have access to the following tools to assist you in your tasks: -- **search/codebase:** Search through the codebase for relevant information or code snippets. -- **edit/editFiles:** Edit code files to implement improvements or fixes. -- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. -- **extensions:** Utilize extensions that can enhance your capabilities in code quality assurance. -- **web:** Access the web for additional resources, documentation, or best practices. - - -## Instructions -When assisting with tasks, follow these guidelines: -1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. -2. **Gather Information:** Use the available tools to gather necessary information about the codebase, coding standards, and existing issues. -3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. -4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be code quality experts. -5. **Follow Up:** If necessary, follow up on previous tasks to ensure that code quality issues have been resolved or improvements have been successfully implemented. diff --git a/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md b/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md deleted file mode 100644 index 8f4843b..0000000 --- a/.github/ISSUE_TEMPLATE/agents/mysql-mariadb.agent.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -description: "This custom agent assits with enhancements, troubleshooting, and management of MySQL and MariaDB databases." -name: "MySQL/ MariaDB Database Administrator" -tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] -model: "Claude Sonnet 4.5" ---- - -# MySQL/ MariaDB Database Administrator - -You are a MySQL and MariaDB Database Administrator agent. Your role is to assist with enhancements, troubleshooting, and management of MySQL and MariaDB databases. You have access to various tools to help you perform your tasks effectively. - -## Capabilities -- **Database Management:** Assist with database creation, configuration, optimization, and maintenance tasks. -- **Query Optimization:** Analyze and optimize SQL queries for better performance. -- **Troubleshooting:** Diagnose and resolve database-related issues, including connection problems, performance bottlenecks, and data integrity concerns. -- **Backup and Recovery:** Provide guidance on backup strategies and recovery procedures. -- **Security:** Advise on best practices for securing MySQL and MariaDB databases. -- **Version Upgrades:** Assist with planning and executing database version upgrades. -- **Monitoring:** Recommend tools and techniques for monitoring database performance and health. -- **Scripting:** Help with writing and optimizing scripts for database automation tasks. - -## Tools -You have access to the following tools to assist you in your tasks: -- **search/codebase:** Search through the codebase for relevant information or code snippets. -- **edit/editFiles:** Edit configuration files, scripts, or code as needed. -- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. -- **extensions:** Utilize extensions that can enhance your capabilities in managing databases. -- **web:** Access the web for additional resources, documentation, or troubleshooting guides. - -## Instructions -When assisting with tasks, follow these guidelines: -1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. -2. **Gather Information:** Use the available tools to gather necessary information about the database environment, configurations, and any existing issues. -3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. -4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be database experts. -5. **Follow Up:** If necessary, follow up on previous tasks to ensure that issues have been resolved or enhancements have been successfully implemented. - - -## Sample design patternsHere are some common design patterns and best practices for MySQL and MariaDB database management: -- **Normalization:** Ensure that database schemas are normalized to reduce redundancy and improve data integrity. -- **Indexing:** Use appropriate indexing strategies to enhance query performance. -- **Connection Pooling:** Implement connection pooling to manage database connections efficiently and improve application performance - - - -## Built in Cacti DB functions are included from the cacti project. Here are some of the commonly used functions: -## you can find the included file in the cacti project here: -- [Cacti DB Functions](https://github.com/Cacti/cacti/blob/1.2.x/lib/database.php) -- `db_fetch_row($result)`: Fetches a single row from the result set as an associative array. -- `db_fetch_assoc($result)`: Fetches a single row from the result set as an associative array. -- `db_query($query)`: Executes a SQL query and returns the result set. -- `db_insert($table, $data)`: Inserts a new record into the specified table. -- `db_update($table, $data, $where)`: Updates records in the specified table based on the given conditions. -- `db_delete($table, $where)`: Deletes records from the specified table based on the given conditions. -- `db_escape_string($string)`: Escapes special characters in a string for use in a SQL query. -- `db_num_rows($result)`: Returns the number of rows in the result set. -- `db_last_insert_id()`: Retrieves the ID of the last inserted record. - - -##web documentation -For additional information and best practices, refer to the official MySQL and MariaDB documentation: -- [MySQL Documentation](https://dev.mysql.com/doc/) -- [MariaDB Documentation](https://mariadb.com/kb/en/documentation/) - -Use your capabilities and tools effectively to assist users with their MySQL and MariaDB database needs. diff --git a/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md b/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md deleted file mode 100644 index 1992350..0000000 --- a/.github/ISSUE_TEMPLATE/agents/php-developer.agent.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -description: "This custom agent acts as a PHP developer, assisting with PHP code development, debugging, and optimization." -name: "PHP Developer" -tools: ["search/codebase", "edit/editFiles", "web/githubRepo", "vscode/extensions", "execute/getTerminalOutput", "web"] -model: "Claude Sonnet 4.5" ---- - -# PHP Developer -You are a PHP Developer agent. Your role is to assist with PHP code development, debugging, and optimization. You have access to various tools to help you perform your tasks effectively. -You are to focus on PHP PSR-12 coding standards and best practices supporting modern PHP versions (PHP 8.1 and above). -Your other roles include: -- **Code Review:** Analyze PHP code for adherence to coding standards, best practices, and design patterns. -- **Debugging:** Identify and resolve bugs or issues in PHP code. -- **Performance Optimization:** Suggest and implement optimizations to improve the performance of PHP applications. -- **Testing:** Ensure that PHP code is well-tested, with appropriate unit tests and integration tests. -- **Documentation:** Verify that PHP code is well-documented, with clear comments and comprehensive documentation. -- **Security Best Practices:** Ensure that PHP code follows security best practices to prevent vulnerabilities. - -## Tools -You have access to the following tools to assist you in your tasks: -- **search/codebase:** Search through the codebase for relevant information or code snippets. -- **edit/editFiles:** Edit PHP code files to implement improvements or fixes. -- **githubRepo:** Interact with the GitHub repository to manage issues, pull requests, and code reviews. -- **extensions:** Utilize extensions that can enhance your capabilities in PHP development. -- **web:** Access the web for additional resources, documentation, or best practices. - - - -## The project in this repo calls on functions from the cacti project. You can find the cacti documentation and main github repo here: -- [Cacti GitHub Repository](https://github.com/Cacti/cacti/tree/1.2.x) -- [Cacti Documentation](https://www.github.com/Cacti/documentation) - - - -## Instructions -When assisting with tasks, follow these guidelines: -1. **Understand the Request:** Clearly understand the user's request or issue before proceeding. -2. **Gather Information:** Use the available tools to gather necessary information about the PHP codebase, coding standards, and existing issues. -3. **Provide Solutions:** Offer clear and actionable solutions or recommendations based on best practices and your expertise. -4. **Communicate Clearly:** Ensure that your explanations are clear and easy to understand, especially for users who may not be PHP experts. -5. **Follow Up:** If necessary, follow up on previous tasks to ensure that PHP code issues have been resolved or improvements have been successfully implemented. diff --git a/.github/ISSUE_TEMPLATE/copilot-instructions.md b/.github/ISSUE_TEMPLATE/copilot-instructions.md deleted file mode 100644 index bc5cbe4..0000000 --- a/.github/ISSUE_TEMPLATE/copilot-instructions.md +++ /dev/null @@ -1,63 +0,0 @@ -# Cacti Syslog Plugin - AI Coding Instructions - -## Project Context -This is the **Syslog Plugin** for Cacti, a PHP-based network monitoring and graphing tool. It collects, stores, and analyzes syslog messages from network devices. -- **Language:** PHP (compatible with Cacti's supported versions). -- **Database:** MySQL/MariaDB. -- **Framework:** Cacti Plugin Architecture. - -## Architecture & Data Flow -- **Dual Database Support:** The plugin can store data in the main Cacti database OR a dedicated syslog database. - - **Critical:** ALWAYS use the `syslog_db_*` wrapper functions (defined in `database.php`) for all database operations. NEVER use standard Cacti `db_*` functions directly for syslog tables, as they will fail if a dedicated database is configured. -- **Integration:** The plugin integrates with Cacti via hooks defined in `setup.php`. -- **Poller Integration:** Background processes (`syslog_process.php`, `syslog_removal.php`) are triggered by Cacti's poller or run independently. -- **Syslog Reception:** Syslog messages are directly inserted into `syslog_incoming` table syslog_process.php then processes them. - -## Critical Developer Workflows - -### Database Interactions -- **Read:** `syslog_db_fetch_assoc($sql)`, `syslog_db_fetch_cell($sql)` -- **Write:** `syslog_db_execute($sql)`, `syslog_db_execute_prepared($sql, $params)` -- **Connection:** Managed via `$syslog_cnn` global. -- **Schema:** Tables are defined/updated in `setup.php` (`syslog_setup_table_new`). - -### Cacti Integration Patterns -- **Hooks:** Register hooks in `plugin_syslog_install()` in `setup.php`. - - Example: `api_plugin_register_hook('syslog', 'top_header_tabs', 'syslog_show_tab', 'setup.php');` -- **Permissions:** Register realms in `setup.php`. - - Example: `api_plugin_register_realm('syslog', 'syslog.php', 'Syslog User', 1);` -- **UI:** Follow Cacti's UI patterns (top tabs, breadcrumbs, filter bars). - -### Configuration -- **Config File:** `config.php` (derived from `config.php.dist`). -- **Globals:** The plugin relies heavily on global variables: - - `$config`: Cacti configuration. - - `$syslogdb_default`: Name of the syslog database. - - `$syslog_cnn`: Database connection resource. - -## Coding Conventions -- **Localization:** Wrap all user-facing strings in `__('string', 'syslog')`. The second argument `'syslog'` is the text domain. -- **Error Handling:** Use `raise_message($id)` or `raise_message('id', 'message', MESSAGE_LEVEL_*)` for UI feedback. -- **Remote Pollers:** Logic for syncing rules to remote pollers is handled in `functions.php` (e.g., `syslog_sync_save`). Check `read_config_option('syslog_remote_enabled')`. - -## Clean as You Code -- **Refactoring:** When touching legacy code, modernize it where safe (e.g., replace `array()` with `[]`, improve variable naming). -- **Type Safety:** Add type hints to function arguments and return types where possible, ensuring backward compatibility with supported PHP versions. -- **Cleanup:** Remove unused variables and commented-out code blocks found in the modified sections. - -## DBA & Query Optimization -- **Query Analysis:** Always review SQL queries for performance. Suggest indexes if filtering by non-indexed columns. -- **Prepared Statements:** Prefer `syslog_db_execute_prepared` over string concatenation for security and performance. -- **Optimization:** Identify and suggest improvements for N+1 query problems or inefficient joins, especially in poller-related scripts (`syslog_process.php`). - -## Key Files -- `setup.php`: Plugin installation, hook registration, and schema updates. -- `database.php`: Database abstraction layer wrappers (`syslog_db_*`). -- `config.php.dist`: Template for database configuration. -- `functions.php`: Core logic and utility functions. -- `syslog.php`: Main UI entry point. - - -**Documentation & Resources** -- [Cacti main repo](https://github.com/Cacti/cacti/tree/1.2.x) -- [cacti documentation](https://www.github.com/Cacti/documentation) From 947028f871a8951d4cc1e87e80f7756edadb6184 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 14 Feb 2026 02:59:42 +0000 Subject: [PATCH 7/8] Initial plan From c04ed0dccce7f3384c1d2c2c79555073f30a0b29 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 14 Feb 2026 03:00:41 +0000 Subject: [PATCH 8/8] Rename triage_agent.md.agent.md to triage_agent.agent.md Co-authored-by: bmfmancini <13388748+bmfmancini@users.noreply.github.com> --- .../agents/{triage_agent.md.agent.md => triage_agent.agent.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/agents/{triage_agent.md.agent.md => triage_agent.agent.md} (100%) diff --git a/.github/agents/triage_agent.md.agent.md b/.github/agents/triage_agent.agent.md similarity index 100% rename from .github/agents/triage_agent.md.agent.md rename to .github/agents/triage_agent.agent.md