diff --git a/.github/agents/database.agent.md b/.github/agents/database.agent.md new file mode 100644 index 00000000..764dab35 --- /dev/null +++ b/.github/agents/database.agent.md @@ -0,0 +1,41 @@ +# Database Agent + +## Role +You are a MariaDB/MySQL specialist analyzing database interactions in the XC_VM codebase. + +## Expertise +- Query optimization (EXPLAIN analysis, index suggestions) +- Schema design review (normalization, data types, constraints) +- N+1 query detection +- Transaction safety and deadlock prevention +- Connection management and pooling +- Migration safety (ALTER TABLE on large tables, online DDL) + +## XC_VM Context +- Database: MariaDB (MySQL-compatible) +- Access layer: Custom PDO wrapper (`src/core/Database/Database.php`) +- Query style: Prepared statements with `?` placeholders +- Common pattern: `$db->query('SELECT ... WHERE id = ?;', $rID)` +- Global instance: `global $db` (legacy), constructor injection (new code) +- No ORM — all queries are raw SQL + +## Focus Areas +- Identify missing indexes on frequently queried columns +- Detect N+1 patterns (loops with queries inside) +- Flag unsafe operations: `ALTER TABLE` without `ALGORITHM=INPLACE`, missing transactions for multi-statement operations +- Review `JOIN` efficiency and suggest alternatives +- Identify queries that could benefit from Redis caching +- Flag SQL injection risks in dynamic query construction + +## Do NOT +- Suggest switching to an ORM +- Recommend PostgreSQL or other database engines +- Discuss application architecture (use @architect for that) +- Propose schema changes without migration safety analysis + +## Required Output +- EXPLAIN output interpretation for slow queries +- Concrete index recommendations with DDL statements +- Identification of N+1 patterns with fix suggestions +- Transaction boundary recommendations +- Estimated impact of suggested changes diff --git a/.github/agents/migrator.agent.md b/.github/agents/migrator.agent.md new file mode 100644 index 00000000..513f6390 --- /dev/null +++ b/.github/agents/migrator.agent.md @@ -0,0 +1,40 @@ +# Legacy Migrator Agent + +## Role +You are a senior PHP engineer specializing in legacy code modernization. Your job is to safely transform legacy XC_VM code into the target architecture defined in ARCHITECTURE.md. + +## Expertise +- Extracting methods from god-objects (CoreUtilities, admin_api.php) into domain services +- Replacing `global $db`, `$rSettings`, `$rUserInfo` with constructor injection +- Moving raw SQL from admin pages into Repository classes +- Consolidating duplicated code (admin/ vs reseller/ patterns) +- Preserving backward compatibility during migration + +## Process +1. Read ARCHITECTURE.md for target patterns +2. Analyze the legacy code to understand current dependencies +3. Identify all call sites before moving/renaming anything +4. Propose a step-by-step migration plan +5. Execute changes preserving the `$r` variable naming convention +6. Verify syntax with `php -l` after each file change + +## Rules +- Every migration step must be backward-compatible +- Do NOT introduce namespaces, Composer, or PSR-4 autoloading +- Do NOT change multiple subsystems at once — one context per migration +- Preserve K&R brace style, tab indentation, `$r` prefix convention +- Mark incomplete migrations: `// @migration-in-progress` +- Always grep for old method/class names to find ALL call sites before deletion +- Run `php -l` syntax check on every changed file + +## Do NOT +- Rewrite files from scratch when incremental migration is possible +- Introduce abstractions not mandated by ARCHITECTURE.md +- Skip call-site analysis ("it's probably only used here") +- Leave orphaned methods in god-objects after extraction + +## Required Output +- Migration plan with specific file paths +- Before/after code for each changed file +- List of all affected call sites +- Syntax verification results diff --git a/.github/instructions/architecture-rules.instructions.md b/.github/instructions/architecture-rules.instructions.md new file mode 100644 index 00000000..ae244f8c --- /dev/null +++ b/.github/instructions/architecture-rules.instructions.md @@ -0,0 +1,55 @@ +--- +description: "Use when creating or modifying services, repositories, controllers, modules, or any domain/core code. Enforces XC_VM architectural rules from ARCHITECTURE.md." +--- +# Architecture Rules — XC_VM + +## Layer Pattern +Every domain context follows: **Controller → Service → Repository → Database** + +``` +public/Controllers/Admin/StreamController.php → presentation +domain/Stream/StreamService.php → business logic +domain/Stream/StreamRepository.php → data access +core/Database/Database.php → infrastructure +``` + +## Dependency Direction (strict) + +| Layer | Can depend on | CANNOT depend on | +|-------|---------------|------------------| +| `public/` | `domain/` (Service+Repository), `core/` | `streaming/`, `modules/` directly | +| `domain/` | `core/` (Database, Cache, Events) | `public/`, `streaming/`, `modules/`, `infrastructure/` | +| `core/` | Only other `core/` subdirectories | Everything else | +| `streaming/` | `core/` (subset), `domain/` (read-only) | `public/`, `modules/` | +| `modules/` | `domain/`, `core/` | Other modules, `public/`, `streaming/` | + +## Constructor Injection +- `ServiceContainer` is used ONLY in bootstrap (composition root) +- After bootstrap, all dependencies are passed via constructor +- No service may call `$container->get()` inside its methods +- Legacy exceptions marked with `// @legacy-container` + +## File Consolidation Rules +- Do NOT create separate file if class has < 150 lines AND < 5 public methods +- Small Repository + Service in same context → combine in one file +- Service with 1-2 methods → merge into nearest related context +- Separate files only when class > 150 lines OR ≥ 5 public methods OR used from 3+ contexts + +## Module Boundaries +- Module = isolated directory under `src/modules/` +- Removing a module must NOT break the system (graceful degradation) +- Modules depend on `domain/` and `core/`, never on other modules +- Core never depends on modules + +## Decision Filters (from ARCHITECTURE.md) +Before any architectural decision, apply: +1. Can a contributor understand it in 5 minutes? → if no, simplify +2. Does it break the streaming hot path? → if yes, reject +3. Can it be isolated as a module? → if no, justify why + +If a decision improves "code beauty" but raises the entry barrier → reject it. + +## Multi-Build Awareness +- **MAIN build**: full admin + streaming +- **LoadBalancer build**: streaming subset only, admin dirs stripped +- Code in `domain/` used by streaming must NOT pull admin-only dependencies diff --git a/.github/instructions/bash-scripts.instructions.md b/.github/instructions/bash-scripts.instructions.md new file mode 100644 index 00000000..1642499b --- /dev/null +++ b/.github/instructions/bash-scripts.instructions.md @@ -0,0 +1,33 @@ +--- +description: "Use when writing or editing shell scripts in tools/, src/bin/, or src/infrastructure/. Covers bash conventions for XC_VM." +applyTo: "**/*.sh" +--- +# Bash Script Conventions — XC_VM + +## Required Header +```bash +#!/bin/bash +set -euo pipefail +``` + +## Style +- Indent with 4 spaces (not tabs — unlike PHP) +- Quote all variables: `"$var"` not `$var` +- Use `[[ ]]` for conditionals, not `[ ]` +- Use `$()` for command substitution, not backticks + +## Error Handling +- `set -e` — exit on first error +- `set -u` — treat unset variables as error +- `set -o pipefail` — catch errors in pipes +- Use `trap` for cleanup on exit when creating temp files + +## Security +- Never pass secrets via command-line arguments (visible in `ps`) +- Use environment variables or files with restricted permissions (0600) +- Validate external input before using in commands +- Avoid `eval` unless absolutely necessary + +## Paths +- Use absolute paths for system binaries: `/usr/bin/php8.2`, `/usr/sbin/nginx` +- Reference project root via variable, not hardcoded paths diff --git a/.github/instructions/code-review-extensions.md b/.github/instructions/code-review.instructions.md similarity index 73% rename from .github/instructions/code-review-extensions.md rename to .github/instructions/code-review.instructions.md index 66b8a782..4e9501b5 100644 --- a/.github/instructions/code-review-extensions.md +++ b/.github/instructions/code-review.instructions.md @@ -1,6 +1,56 @@ -# Code Review — Extensions and Templates +--- +description: "Use when performing structured multi-agent code review, security audit, performance analysis, or quality review of PHP code. Covers finding templates, severity matrix, deduplication rules." +--- +# XC_VM Structured Code Review (Pragmatic Mode) -This companion document provides concrete templates and rules to extend the base `.github/instructions/code-review.md` process. +This repository uses a structured multi-agent review process. + +Execution order is mandatory: + +1. Architect +2. Security Auditor +3. Performance Analyst +4. Code Reviewer +5. Final Verdict + +The system must: +- Assume untrusted input. +- Assume internet exposure. +- Assume production deployment. +- Avoid unrealistic theoretical attacks. +- Focus on practical, real-world risk. + +Agents must: +- Avoid repeating findings. +- Clearly label severity: Low / Medium / High. +- Provide realistic mitigation steps. +- Avoid exaggerated conclusions. +- Avoid generic praise. + +Output format is mandatory: + +--- + +## 1. Architectural Analysis +... + +## 2. Security Analysis +... + +## 3. Performance Analysis +... + +## 4. Code Quality Review +... + +## 5. Final Verdict +- Overall Risk Level: +- Production Ready: +- Refactor Priority: +- Blocking Issues: +``` + +--- ## Example finding template (required) - **Title:** Short descriptive title @@ -38,7 +88,7 @@ When assigning severity, include brief justification mapping to the matrix. Recommended format: include the above as a JSON code block at the end of each finding to aid automation. Example: -``` +```json { "title": "SQL injection in getUser()", "file": "src/auth/User.php#L210", @@ -55,7 +105,3 @@ Recommended format: include the above as a JSON code block at the end of each fi ## Examples and expectations - Include one worked example (one High severity finding) in reviews produced by the system during onboarding runs to demonstrate the required level of detail and patch quality. - ---- - -If you prefer, I can re-run and attempt to patch the original `code-review.md` to integrate these extensions in-place; currently I created this companion file to avoid modifying the original file directly. \ No newline at end of file diff --git a/.github/instructions/makefile-build.instructions.md b/.github/instructions/makefile-build.instructions.md new file mode 100644 index 00000000..f5cb5d69 --- /dev/null +++ b/.github/instructions/makefile-build.instructions.md @@ -0,0 +1,21 @@ +--- +description: "Use when editing the Makefile, understanding build targets, or working with MAIN vs LoadBalancer build configurations." +applyTo: "Makefile" +--- +# Makefile & Build — XC_VM + +## Build Variants +- **MAIN** (`xc_vm.tar.gz`): Full application — admin panel + streaming + all modules +- **LoadBalancer** (`loadbalancer.tar.gz`): Streaming-only subset — admin dirs stripped +- **Installer** (`XC_VM.zip`): Distribution package with install script + +## Key Variables +- `MAIN_DIR = ./src` — full application source +- `LB_DIRS` — subset of directories included in LoadBalancer build +- `LB_DIRS_TO_REMOVE` — admin-only paths stripped from LB builds + +## Rules +- Any new directory under `src/` that is streaming-relevant must be added to `LB_DIRS` +- Any new admin-only directory must be added to `LB_DIRS_TO_REMOVE` +- Version hashes are generated into the archives +- Do NOT change archive naming convention without updating CI workflows diff --git a/.github/instructions/migration-patterns.instructions.md b/.github/instructions/migration-patterns.instructions.md new file mode 100644 index 00000000..afbae130 --- /dev/null +++ b/.github/instructions/migration-patterns.instructions.md @@ -0,0 +1,86 @@ +--- +description: "Use when migrating legacy code to services, replacing global variables, extracting logic from god-objects, or refactoring admin pages. Covers safe migration patterns for XC_VM." +--- +# Migration Patterns — XC_VM + +## Strategy +Iterative refactoring. Each step must be backward-compatible. No big-bang rewrites. + +## Replacing Global Variables + +### Pattern: Wrap global access in a service method + +```php +// BEFORE (legacy): +global $db; +$rStreams = $db->query('SELECT * FROM streams WHERE id = ?;', $rID); + +// AFTER (migrated): +// In StreamRepository: +class StreamRepository { + public function __construct(private Database $db) {} + public function getById(int $id): ?array { + return $this->db->query('SELECT * FROM streams WHERE id = ?;', $id); + } +} +``` + +### Migration order for globals: +1. `$db` → inject `Database` via constructor into Repository classes +2. `$rSettings` → inject via constructor or use `ConfigLoader::get()` +3. `$rUserInfo` → inject via `SessionManager` or pass as parameter +4. `$rServers` → inject via `ServerRepository` + +### Safety rules: +- Do NOT remove `global $xxx` from a file until ALL usages in that file are replaced +- Mark partial migrations: `// @migration-in-progress — $rSettings still used on line 45` +- Test the file after each global removal (php -l at minimum) + +## Extracting from God-Objects + +### Pattern: One method group → one Service + +```php +// CoreUtilities had: getStreamInfo(), updateStream(), deleteStream(), ... +// Extract to: domain/Stream/StreamService.php + +// Then replace call sites: +// BEFORE: CoreUtilities::getStreamInfo($id) +// AFTER: StreamService::getById($id) (or instance method via DI) +``` + +### Extraction checklist: +1. Identify method cluster by domain (all stream-related, all user-related, etc.) +2. Create Service + Repository in `src/domain/{Context}/` +3. Move methods, preserving signatures initially +4. Update all call sites (grep for old method name) +5. Remove from god-object +6. Run `php -l` on all changed files + +## Admin Page Migration + +### Pattern: Extract SQL from presentation + +```php +// BEFORE (in admin/streams.php): +global $db; +$rStreams = $db->query('SELECT * FROM streams;'); +foreach ($rStreams as $rStream) { + echo "