diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3baf7ba..f555e21 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -60,4 +60,4 @@ jobs: extensions: pdo_sqlite coverage: pcov - run: composer update --prefer-dist --no-interaction --no-progress - - run: vendor/bin/pest --coverage + - run: vendor/bin/pest --coverage --min=100 diff --git a/CHANGELOG.md b/CHANGELOG.md index 44bd68a..3d3d32c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ All notable changes are documented here. The format follows [Keep a Changelog](h - One config-driven redactor (`redact.keys`, `redact.headers`) now also covers SQL bindings, log context, response bodies and HTTP client bodies. `DIGDEEP_CAPTURE_RESPONSE_BODIES=false` turns response body capture off. ### Fixed +- On-demand profiles (trigger, replay, MCP `profile-url`) record the matched route; unknown URLs are stored as 404, not 500. +- The logs page no longer errors on an empty log file; `ai-investigate` handles trace frames without a function. +- Query callers are detected when the app's own path contains `digdeep`. - Streamed and binary responses (downloads, SSE) are no longer profiled. New `sample_rate` option (`DIGDEEP_SAMPLE_RATE`) profiles only a share of requests. - `max_profile_size_kb` is enforced: oversized profiles drop their largest sections until they fit. Collectors keep at most `limits.max_entries` entries and shorten long strings. Pruning runs on a lottery (`prune_lottery`) and deletes in chunks. - Listeners are registered once per worker, so Octane/FrankenPHP no longer pile up listeners or leak data between requests. @@ -22,6 +25,7 @@ All notable changes are documented here. The format follows [Keep a Changelog](h - Profiling no longer errors on non-Laravel responses with status >= 400. ### Changed +- Test suite covers 100% of `src/`, enforced in CI. `laravel/ai` is a dev dependency so the AI features are tested. - Classes moved to `Http\Controllers`, `Http\Middleware` and `Console\Commands`. - Migrations publishable via the `digdeep-migrations` tag. diff --git a/composer.json b/composer.json index eeffcc1..4bbba1d 100644 --- a/composer.json +++ b/composer.json @@ -45,7 +45,8 @@ }, "require-dev": { "larastan/larastan": "^3.13", - "laravel/mcp": "^0.5", + "laravel/ai": "^1.3", + "laravel/mcp": "^1.0", "laravel/pint": "^1.32", "orchestra/testbench": "^10.0|^11.0", "pestphp/pest": "^4.0|^5.0" diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 5dc278c..0be35a8 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -48,24 +48,6 @@ parameters: count: 1 path: src/DigDeepCollector.php - - - message: '#^Call to an undefined method LaravelPlus\\DigDeep\\Ai\\Agents\\ExceptionInvestigatorAgent\:\:prompt\(\)\.$#' - identifier: method.notFound - count: 1 - path: src/Http/Controllers/ApiController.php - - - - message: '#^Call to an undefined method LaravelPlus\\DigDeep\\Ai\\Agents\\QueryFixerAgent\:\:prompt\(\)\.$#' - identifier: method.notFound - count: 1 - path: src/Http/Controllers/ApiController.php - - - - message: '#^Instantiated class Laravel\\Ai\\Tools\\Request not found\.$#' - identifier: class.notFound - count: 1 - path: src/Http/Controllers/ApiController.php - - message: '#^Parameter \#1 \$view of function view expects view\-string\|null, string given\.$#' identifier: argument.type @@ -84,12 +66,6 @@ parameters: count: 15 path: src/Http/Controllers/DashboardController.php - - - message: '#^Comparison operation "\>" between int\<1, max\> and 0 is always true\.$#' - identifier: greater.alwaysTrue - count: 1 - path: src/Http/Middleware/ProfileRequest.php - - message: '#^Parameter \#1 \$view of function view expects view\-string\|null, string given\.$#' identifier: argument.type @@ -132,12 +108,6 @@ parameters: count: 1 path: src/Mcp/Tools/ListProfiles.php - - - message: '#^If condition is always true\.$#' - identifier: if.alwaysTrue - count: 1 - path: src/Mcp/Tools/ProfileUrl.php - - message: '#^Method LaravelPlus\\DigDeep\\Mcp\\Tools\\ProfileUrl\:\:schema\(\) should return array\ but returns array\\.$#' identifier: return.type diff --git a/phpstan.neon.dist b/phpstan.neon.dist index e4cb5e0..cf78068 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -9,6 +9,3 @@ parameters: paths: - src - routes - excludePaths: - # laravel/ai is optional and not installed in dev; these classes only load when it is - - src/Ai diff --git a/src/Ai/Agents/ExceptionInvestigatorAgent.php b/src/Ai/Agents/ExceptionInvestigatorAgent.php index 95d8a71..071497b 100644 --- a/src/Ai/Agents/ExceptionInvestigatorAgent.php +++ b/src/Ai/Agents/ExceptionInvestigatorAgent.php @@ -15,7 +15,6 @@ use LaravelPlus\DigDeep\Ai\Tools\ListSourceFilesTool; use LaravelPlus\DigDeep\Ai\Tools\ReadSourceFileTool; use Override; -use Stringable; #[MaxSteps(6)] #[MaxTokens(2048)] @@ -27,7 +26,7 @@ final class ExceptionInvestigatorAgent implements Agent, HasStructuredOutput, Ha * Get the instructions that the agent should follow. */ #[Override] - public function instructions(): Stringable|string + public function instructions(): string { return <<<'INSTRUCTIONS' You are a Laravel exception debugging expert embedded in a profiling tool. diff --git a/src/Ai/Agents/QueryFixerAgent.php b/src/Ai/Agents/QueryFixerAgent.php index 58cde83..4c843fd 100644 --- a/src/Ai/Agents/QueryFixerAgent.php +++ b/src/Ai/Agents/QueryFixerAgent.php @@ -15,7 +15,6 @@ use LaravelPlus\DigDeep\Ai\Tools\ListSourceFilesTool; use LaravelPlus\DigDeep\Ai\Tools\ReadSourceFileTool; use Override; -use Stringable; #[MaxSteps(6)] #[MaxTokens(2048)] @@ -27,7 +26,7 @@ final class QueryFixerAgent implements Agent, HasStructuredOutput, HasTools * Get the instructions that the agent should follow. */ #[Override] - public function instructions(): Stringable|string + public function instructions(): string { return <<<'INSTRUCTIONS' You are a Laravel Eloquent and database performance expert embedded in a profiling tool. diff --git a/src/Ai/Tools/ListSourceFilesTool.php b/src/Ai/Tools/ListSourceFilesTool.php index bd13bbd..79884f1 100644 --- a/src/Ai/Tools/ListSourceFilesTool.php +++ b/src/Ai/Tools/ListSourceFilesTool.php @@ -8,7 +8,6 @@ use Laravel\Ai\Contracts\Tool; use Laravel\Ai\Tools\Request; use Override; -use Stringable; final class ListSourceFilesTool implements Tool { @@ -18,7 +17,7 @@ final class ListSourceFilesTool implements Tool * Get the description of the tool's purpose. */ #[Override] - public function description(): Stringable|string + public function description(): string { return 'List PHP files in a directory to locate the right model, controller, or service file. Useful when you are unsure of the exact filename.'; } @@ -27,7 +26,7 @@ public function description(): Stringable|string * Execute the tool. */ #[Override] - public function handle(Request $request): Stringable|string + public function handle(Request $request): string { $dir = $this->sanitizePath($request['directory']); diff --git a/src/Ai/Tools/ReadSourceFileTool.php b/src/Ai/Tools/ReadSourceFileTool.php index 8f63f4e..9277f47 100644 --- a/src/Ai/Tools/ReadSourceFileTool.php +++ b/src/Ai/Tools/ReadSourceFileTool.php @@ -8,7 +8,6 @@ use Laravel\Ai\Contracts\Tool; use Laravel\Ai\Tools\Request; use Override; -use Stringable; final class ReadSourceFileTool implements Tool { @@ -20,7 +19,7 @@ final class ReadSourceFileTool implements Tool * Get the description of the tool's purpose. */ #[Override] - public function description(): Stringable|string + public function description(): string { return 'Read a PHP or JS source file from the application to understand the code causing the query issue. Provide the path relative to the application root (e.g. app/Models/Hotel.php).'; } @@ -29,7 +28,7 @@ public function description(): Stringable|string * Execute the tool. */ #[Override] - public function handle(Request $request): Stringable|string + public function handle(Request $request): string { $path = $this->sanitizePath($request['path']); diff --git a/src/Ai/Tools/WriteSourceFileTool.php b/src/Ai/Tools/WriteSourceFileTool.php index 3653fa5..ee5c47d 100644 --- a/src/Ai/Tools/WriteSourceFileTool.php +++ b/src/Ai/Tools/WriteSourceFileTool.php @@ -8,7 +8,6 @@ use Laravel\Ai\Contracts\Tool; use Laravel\Ai\Tools\Request; use Override; -use Stringable; final class WriteSourceFileTool implements Tool { @@ -18,7 +17,7 @@ final class WriteSourceFileTool implements Tool * Get the description of the tool's purpose. */ #[Override] - public function description(): Stringable|string + public function description(): string { return 'Apply a targeted fix to a PHP source file by replacing an exact code snippet. The old_code must match exactly what is in the file.'; } @@ -27,7 +26,7 @@ public function description(): Stringable|string * Execute the tool. */ #[Override] - public function handle(Request $request): Stringable|string + public function handle(Request $request): string { $path = $this->sanitizePath($request['path']); diff --git a/src/Collectors/CommandCollector.php b/src/Collectors/CommandCollector.php index 58d4111..c50269a 100644 --- a/src/Collectors/CommandCollector.php +++ b/src/Collectors/CommandCollector.php @@ -19,11 +19,11 @@ final class CommandCollector public function listen(): void { Event::listen(CommandStarting::class, function (CommandStarting $event): void { - $this->pending[$event->command ?? 'unknown'] = microtime(true); + $this->pending[$event->command] = microtime(true); }); Event::listen(CommandFinished::class, function (CommandFinished $event): void { - $command = $event->command ?? 'unknown'; + $command = $event->command; $startTime = $this->pending[$command] ?? null; $durationMs = $startTime !== null ? (microtime(true) - $startTime) * 1000 : 0; diff --git a/src/Collectors/InertiaCollector.php b/src/Collectors/InertiaCollector.php index dfa5e6a..69a73ae 100644 --- a/src/Collectors/InertiaCollector.php +++ b/src/Collectors/InertiaCollector.php @@ -77,7 +77,7 @@ private function truncateProps(array $props, int $maxDepth = 3, int $currentDept array_slice($value, 0, 10) ); $result[$key][] = '... '.(count($value) - 10).' more items'; - } elseif (is_array($value)) { + } else { $result[$key] = $this->truncateProps($value, $maxDepth, $currentDepth + 1); } } elseif (is_string($value) && mb_strlen($value) > 500) { @@ -103,8 +103,6 @@ private function summarizeProps(array $props): array } else { $summary[$key] = "array[{$count}]"; } - } elseif (is_object($value)) { - $summary[$key] = get_class($value); } elseif (is_string($value)) { $summary[$key] = 'string('.mb_strlen($value).')'; } elseif (is_bool($value)) { diff --git a/src/Collectors/LogCollector.php b/src/Collectors/LogCollector.php index 6405a92..79795d8 100644 --- a/src/Collectors/LogCollector.php +++ b/src/Collectors/LogCollector.php @@ -7,7 +7,6 @@ use Illuminate\Log\Events\MessageLogged; use Illuminate\Support\Facades\Event; use LaravelPlus\DigDeep\Support\Redactor; -use Throwable; final class LogCollector { @@ -22,12 +21,7 @@ public function listen(): void $contextStr = ''; if (! empty($event->context)) { - try { - $encoded = json_encode(Redactor::keys($event->context), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); - $contextStr = $encoded !== false ? $encoded : ''; - } catch (Throwable) { - $contextStr = ''; - } + $contextStr = json_encode(Redactor::keys($event->context), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: ''; } $this->logs[] = [ diff --git a/src/Collectors/QueryCollector.php b/src/Collectors/QueryCollector.php index 893443f..8d26094 100644 --- a/src/Collectors/QueryCollector.php +++ b/src/Collectors/QueryCollector.php @@ -12,7 +12,7 @@ final class QueryCollector /** @var array, time_ms: float, start_offset_ms: float, caller: string}> */ private array $queries = []; - public function __construct(private float $requestStartTime = 0.0) {} + public function __construct(private float $requestStartTime) {} public function listen(): void { @@ -20,9 +20,7 @@ public function listen(): void $caller = $this->findCaller(); // DB::listen fires after the query completes; subtract duration to get start offset - $startOffsetMs = $this->requestStartTime > 0 - ? max(0.0, (microtime(true) - $this->requestStartTime) * 1000 - $query->time) - : 0.0; + $startOffsetMs = max(0.0, (microtime(true) - $this->requestStartTime) * 1000 - $query->time); $this->queries[] = [ 'sql' => $query->sql, @@ -49,7 +47,7 @@ private function findCaller(): string return ! empty($file) && ! str_contains($file, '/vendor/') - && ! str_contains($file, '/digdeep/'); + && ! str_starts_with($file, dirname(__DIR__).DIRECTORY_SEPARATOR); }); return $frame !== null diff --git a/src/DigDeep.php b/src/DigDeep.php index e9c6bef..0f7eecf 100644 --- a/src/DigDeep.php +++ b/src/DigDeep.php @@ -23,6 +23,9 @@ final class DigDeep */ private static array $fixtures = []; + /** Forces the laravel/ai availability check; exists only so tests can simulate a missing SDK. */ + public static ?bool $aiSdkAvailable = null; + /** * Register the DigDeep authentication callback. */ diff --git a/src/Http/Controllers/ApiController.php b/src/Http/Controllers/ApiController.php index f7b2afe..aeba56f 100644 --- a/src/Http/Controllers/ApiController.php +++ b/src/Http/Controllers/ApiController.php @@ -86,7 +86,7 @@ public function trigger(Request $request): JsonResponse ]); } - $route = $subRequest->route(); + $route = app('request')->route(); if ($route) { $this->collector->setRoute([ @@ -211,7 +211,7 @@ public function replay(string $id): JsonResponse ]); } - $route = $subRequest->route(); + $route = app('request')->route(); if ($route) { $this->collector->setRoute([ 'name' => $route->getName(), @@ -404,7 +404,7 @@ public function aiInvestigateException(Request $request): JsonResponse $file = $request->input('file', ''); $line = $request->input('line', ''); $trace = collect($request->input('trace', [])) - ->map(fn (array $f): string => ($f['file'] ?? '').':'.($f['line'] ?? '').' → '.($f['class'] ?? '').($f['function'] ? '::'.$f['function'].'()' : '')) + ->map(fn (array $f): string => ($f['file'] ?? '').':'.($f['line'] ?? '').' → '.($f['class'] ?? '').(isset($f['function']) ? '::'.$f['function'].'()' : '')) ->implode("\n"); $prompt = << 0 ? $middlewareDuration / count($middlewareList) : 0; + $perMiddleware = $middlewareDuration / count($middlewareList); $middlewareCollector->recordMiddleware($name, $perMiddleware, true); } } @@ -200,42 +200,32 @@ private function collectSession(Request $request): array return []; } - try { - $session = $request->session(); + $data = []; - if (! $session->isStarted()) { - return []; + foreach ($request->session()->all() as $key => $value) { + if (str_starts_with((string) $key, '_')) { + continue; } - $data = []; - - foreach ($session->all() as $key => $value) { - if (str_starts_with((string) $key, '_')) { - continue; - } - - if (Redactor::isSensitiveKey((string) $key)) { - $data[(string) $key] = ['type' => gettype($value), 'value' => '[redacted]']; - - continue; - } + if (Redactor::isSensitiveKey((string) $key)) { + $data[(string) $key] = ['type' => gettype($value), 'value' => '[redacted]']; - if (is_array($value)) { - $value = Redactor::keys($value); - } + continue; + } - $data[(string) $key] = [ - 'type' => gettype($value), - 'value' => is_scalar($value) - ? (string) $value - : mb_substr((string) json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 0, 200), - ]; + if (is_array($value)) { + $value = Redactor::keys($value); } - return $data; - } catch (Throwable) { - return []; + $data[(string) $key] = [ + 'type' => gettype($value), + 'value' => is_scalar($value) + ? (string) $value + : mb_substr((string) json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 0, 200), + ]; } + + return $data; } private function redactBody(Request $request, string $contentType): string diff --git a/src/Mcp/Tools/GetPerformance.php b/src/Mcp/Tools/GetPerformance.php index 5bb58a0..032c96c 100644 --- a/src/Mcp/Tools/GetPerformance.php +++ b/src/Mcp/Tools/GetPerformance.php @@ -158,10 +158,6 @@ private function computeGlobalPerformance(array $profiles): array private function percentile(array $sorted, float $p): float { - if (empty($sorted)) { - return 0.0; - } - $idx = (int) ceil(count($sorted) * $p) - 1; return round($sorted[max(0, $idx)], 1); diff --git a/src/Mcp/Tools/GetSlowestRoutes.php b/src/Mcp/Tools/GetSlowestRoutes.php index 8f444c6..544ec3c 100644 --- a/src/Mcp/Tools/GetSlowestRoutes.php +++ b/src/Mcp/Tools/GetSlowestRoutes.php @@ -82,10 +82,6 @@ public function schema(JsonSchema $schema): array private function percentile(array $sorted, float $p): float { - if (empty($sorted)) { - return 0.0; - } - $idx = (int) ceil(count($sorted) * $p) - 1; return round($sorted[max(0, $idx)], 1); diff --git a/src/Mcp/Tools/ProfileUrl.php b/src/Mcp/Tools/ProfileUrl.php index ff522af..13f91fb 100644 --- a/src/Mcp/Tools/ProfileUrl.php +++ b/src/Mcp/Tools/ProfileUrl.php @@ -49,7 +49,7 @@ public function handle(Request $request): Response ); $routeData = []; - $matchedRoute = app('router')->getRoutes()->match($httpRequest); + $matchedRoute = app('request')->route(); if ($matchedRoute) { $routeData = [ 'name' => $matchedRoute->getName(), diff --git a/src/Storage/DigDeepStorage.php b/src/Storage/DigDeepStorage.php index c01d852..9c5f687 100644 --- a/src/Storage/DigDeepStorage.php +++ b/src/Storage/DigDeepStorage.php @@ -295,19 +295,6 @@ public function stats(): array COALESCE(MAX(query_count), 0) as most_queries ')->first(); - if (! $result) { - return [ - 'total' => 0, - 'avg_duration' => 0, - 'min_duration' => 0, - 'max_duration' => 0, - 'avg_queries' => 0, - 'avg_memory' => 0, - 'slowest_duration' => 0, - 'most_queries' => 0, - ]; - } - return $result->toArray(); } diff --git a/tests/Feature/AiTest.php b/tests/Feature/AiTest.php new file mode 100644 index 0000000..026e6db --- /dev/null +++ b/tests/Feature/AiTest.php @@ -0,0 +1,165 @@ +setBasePath($root); + + return $root; +} + +afterEach(function (): void { + foreach (glob(sys_get_temp_dir().'/digdeep-ai-*') as $dir) { + File::deleteDirectory($dir); + } +}); + +$fix = ['analysis' => 'A', 'suggestion' => 'S', 'file_path' => 'app/Models/Hotel.php', 'old_code' => 'o', 'new_code' => 'n']; +$investigation = ['analysis' => 'A', 'root_cause' => 'R', 'suggestion' => 'S', 'file_path' => null, 'old_code' => null, 'new_code' => null]; + +it('suggests a query fix through the agent', function (?string $key) use ($fix): void { + config(['digdeep.ai_key' => $key, 'digdeep.ai_provider' => 'anthropic']); + QueryFixerAgent::fake([$fix]); + + $this->postJson('/digdeep/api/ai-suggest', ['sql' => 'select * from hotels', 'issue' => 'slow', 'time_ms' => 12.34, 'caller' => 'app/Models/Hotel.php:3']) + ->assertOk() + ->assertJson($fix); + + QueryFixerAgent::assertPrompted(fn ($prompt): bool => str_contains($prompt->prompt, 'took 12.3ms')); + expect(config('ai.providers.anthropic.key'))->toBe($key); +})->with([null, 'secret-key']); + +it('investigates an exception through the agent', function (?string $key) use ($investigation): void { + config(['digdeep.ai_key' => $key]); + ExceptionInvestigatorAgent::fake([$investigation]); + + $this->postJson('/digdeep/api/ai-investigate', [ + 'class' => 'RuntimeException', + 'message' => 'boom', + 'file' => 'app/X.php', + 'line' => 4, + 'trace' => [['file' => 'app/X.php', 'line' => 4, 'class' => 'X', 'function' => 'run'], ['file' => 'app/Y.php']], + ])->assertOk()->assertJson($investigation); + + ExceptionInvestigatorAgent::assertPrompted(fn ($prompt): bool => str_contains($prompt->prompt, 'app/X.php:4 → X::run()')); +})->with([null, 'secret-key']); + +it('reports agent failures as 500', function (string $uri, array $payload, string $agent): void { + $agent::fake(fn () => throw new RuntimeException('provider down')); + + $this->postJson($uri, $payload)->assertStatus(500)->assertJsonPath('error', 'provider down'); +})->with([ + 'suggest' => ['/digdeep/api/ai-suggest', ['sql' => 'select 1', 'issue' => 'n1'], QueryFixerAgent::class], + 'investigate' => ['/digdeep/api/ai-investigate', ['class' => 'E', 'message' => 'm'], ExceptionInvestigatorAgent::class], +]); + +it('returns 501 from the investigate endpoint when nothing is configured', function (): void { + DigDeep::$aiSdkAvailable = false; + + $this->postJson('/digdeep/api/ai-investigate', ['class' => 'E', 'message' => 'm'])->assertStatus(501); +}); + +it('calls the provider directly when laravel/ai is unavailable', function (string $uri, array $payload, string $provider, string $host, array $ok, string $text): void { + DigDeep::$aiSdkAvailable = false; + config(['digdeep.ai_key' => 'k', 'digdeep.ai_provider' => $provider, 'digdeep.ai_model' => null]); + Http::fake(["{$host}/*" => Http::response($ok)]); + + $this->postJson($uri, $payload)->assertOk()->assertJsonPath('suggestion', $text); +})->with(function () { + $suggest = ['/digdeep/api/ai-suggest', ['sql' => 'select 1', 'issue' => 'duplicate']]; + $investigate = ['/digdeep/api/ai-investigate', ['class' => 'E', 'message' => 'm']]; + $anthropic = ['anthropic', 'api.anthropic.com', ['content' => [['text' => 'hi']]], 'hi']; + $openai = ['openai', 'api.openai.com', ['choices' => [['message' => ['content' => 'yo']]]], 'yo']; + + return [ + 'suggest anthropic' => [...$suggest, ...$anthropic], + 'suggest openai' => [...$suggest, ...$openai], + 'investigate anthropic' => [...$investigate, ...$anthropic], + 'investigate openai' => [...$investigate, ...$openai], + ]; +}); + +it('surfaces direct provider errors', function (string $provider, string $host, array $body, string $message): void { + DigDeep::$aiSdkAvailable = false; + config(['digdeep.ai_key' => 'k', 'digdeep.ai_provider' => $provider]); + Http::fake(["{$host}/*" => Http::response($body, 500)]); + + $this->postJson('/digdeep/api/ai-suggest', ['sql' => 'select 1', 'issue' => 'n1']) + ->assertStatus(500)->assertJsonPath('error', $message); +})->with([ + ['anthropic', 'api.anthropic.com', ['error' => ['message' => 'bad key']], 'bad key'], + ['anthropic', 'api.anthropic.com', [], 'Anthropic API request failed.'], + ['openai', 'api.openai.com', ['error' => ['message' => 'bad key']], 'bad key'], + ['openai', 'api.openai.com', [], 'OpenAI API request failed.'], +]); + +it('applies a fix to an app file', function (): void { + $root = sandbox(); + config(['digdeep.code_actions' => true]); + + $this->postJson('/digdeep/api/ai-apply', ['file_path' => 'app/Models/Hotel.php', 'old_code' => 'class Hotel', 'new_code' => 'final class Hotel']) + ->assertOk()->assertJsonPath('status', 'ok'); + + expect(File::get($root.'/app/Models/Hotel.php'))->toContain('final class Hotel'); +}); + +it('rejects fixes it cannot apply', function (string $path, string $old): void { + sandbox(); + config(['digdeep.code_actions' => true]); + + $this->postJson('/digdeep/api/ai-apply', ['file_path' => $path, 'old_code' => $old, 'new_code' => 'z']) + ->assertStatus(422)->assertJsonStructure(['error']); +})->with([ + 'outside app' => ['config/app.php', 'a'], + 'traversal' => ['app/../.env', 'a'], + 'missing file' => ['app/Nope.php', 'a'], + 'old code absent' => ['app/Models/Hotel.php', 'not there'], +]); + +it('lists, reads and guards source files', function (): void { + sandbox(); + $list = new ListSourceFilesTool; + $read = new ReadSourceFileTool; + + expect((string) $list->handle(new ToolRequest(['directory' => '/app/Models/'])))->toBe('app/Models/Hotel.php') + ->and((string) $list->handle(new ToolRequest(['directory' => 'app/Empty'])))->toBe('No PHP files found in app/Empty') + ->and((string) $list->handle(new ToolRequest(['directory' => 'app/Nope'])))->toBe('Error: Directory not found: app/Nope') + ->and((string) $list->handle(new ToolRequest(['directory' => 'config'])))->toStartWith('Error: Only app/') + ->and((string) $read->handle(new ToolRequest(['path' => 'app/Models/Hotel.php'])))->toContain('2: class Hotel {}') + ->and((string) $read->handle(new ToolRequest(['path' => 'app/Nope.php'])))->toBe('Error: File not found: app/Nope.php') + ->and((string) $read->handle(new ToolRequest(['path' => 'app/Big.php'])))->toStartWith('Error: File is too large') + ->and((string) $read->handle(new ToolRequest(['path' => '.env'])))->toStartWith('Error: Access denied'); +}); + +it('describes agents and tools to the model', function (): void { + $schema = new JsonSchemaTypeFactory; + + foreach ([new QueryFixerAgent, new ExceptionInvestigatorAgent] as $agent) { + expect((string) $agent->instructions())->not->toBeEmpty() + ->and([...$agent->tools()])->toHaveCount(2) + ->and($agent->schema($schema))->toHaveKey('analysis'); + } + + foreach ([new ListSourceFilesTool, new ReadSourceFileTool, new WriteSourceFileTool] as $tool) { + expect((string) $tool->description())->not->toBeEmpty() + ->and($tool->schema($schema))->not->toBeEmpty(); + } +}); diff --git a/tests/Feature/ApiTest.php b/tests/Feature/ApiTest.php index fe4cc9f..762b7a3 100644 --- a/tests/Feature/ApiTest.php +++ b/tests/Feature/ApiTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Support\Facades\Route; +use LaravelPlus\DigDeep\DigDeep; use LaravelPlus\DigDeep\Models\DigDeepProfile; beforeEach(function (): void { @@ -79,5 +80,129 @@ }); it('returns 501 from ai endpoints when nothing is configured', function (): void { + DigDeep::$aiSdkAvailable = false; $this->postJson('/digdeep/api/ai-suggest', ['sql' => 'select 1', 'issue' => 'slow'])->assertStatus(501); }); + +it('prefixes a missing leading slash and profiles failing routes', function (): void { + Route::get('/boom', fn () => throw new RuntimeException('boom')); + + $this->postJson('/digdeep/api/trigger', ['url' => 'boom'])->assertOk()->assertJsonPath('status_code', 500); + + expect(DigDeepProfile::query()->where('url', '/boom')->first()->data['exception']['message'] ?? null)->toBe('boom'); +}); + +it('records exceptions that escape the kernel while triggering and replaying', function (): void { + $boom = $this->profile('/boom', fn () => throw new RuntimeException('boom'))->id; + $this->withoutExceptionHandling(); + + $this->postJson('/digdeep/api/trigger', ['url' => '/boom'])->assertOk()->assertJsonPath('status_code', 500); + $this->postJson("/digdeep/api/profile/{$boom}/replay")->assertOk()->assertJsonPath('original_id', $boom); +}); + +it('replays a failing route', function (): void { + $boom = $this->profile('/boom', fn () => throw new RuntimeException('boom'))->id; + + $this->postJson("/digdeep/api/profile/{$boom}/replay")->assertOk(); +}); + +it('answers 404 for unknown profiles', function (string $method, string $uri): void { + $this->{$method}("/digdeep/api/{$uri}")->assertNotFound(); +})->with([ + ['get', 'profile/nope/export'], + ['postJson', 'profile/nope/replay'], + ['get', 'html-export?template=profile&id=nope'], +]); + +it('rejects invalid explain requests', function (string $sql, string $error): void { + $this->postJson('/digdeep/api/explain', ['sql' => $sql])->assertStatus(400)->assertJsonPath('error', $error); +})->with([ + 'empty' => ['', 'No SQL provided'], + 'too long' => ['select '.str_repeat('1,', 5001).'1', 'SQL query exceeds maximum length'], + 'not a select' => ['pragma table_info(x)', 'EXPLAIN only supports SELECT queries'], + 'dangerous' => ['select 1; drop table users', 'SQL query contains disallowed keywords'], +]); + +it('explains a select, caches the plan and reports sql errors', function (): void { + $first = $this->postJson('/digdeep/api/explain', ['sql' => 'select 1'])->assertOk(); + $second = $this->postJson('/digdeep/api/explain', ['sql' => 'select 1'])->assertOk(); + + expect($first->json('plan'))->not->toBeEmpty() + ->and($first->json('cached'))->toBeNull() + ->and($second->json('cached'))->toBeTrue(); + + $this->postJson('/digdeep/api/explain', ['sql' => 'select * from missing_table'])->assertStatus(400)->assertJsonStructure(['error']); +}); + +it('filters profiles by criteria, cursor and page', function (): void { + $this->profile('/boom', fn () => throw new RuntimeException('boom')); + + $this->getJson('/digdeep/api/profiles?has_errors=1&status_min=500&per_page=1') + ->assertOk()->assertJsonPath('total', 1)->assertJsonPath('has_more', false); + $this->getJson('/digdeep/api/profiles?after=2999-01-01')->assertJsonPath('profiles', []); +}); + +it('narrows trends and performance by route and range', function (string $range): void { + $this->profile('/boom', fn () => throw new RuntimeException('boom')); + + $this->getJson("/digdeep/api/trends?route=/boom&range={$range}")->assertOk()->assertJsonPath('stats.count', 1); + $this->getJson("/digdeep/api/performance?range={$range}")->assertOk()->assertJsonPath('global.total', 2); +})->with(['hour', 'day', 'week']); + +it('validates bulk actions', function (array $payload, int $status): void { + $this->postJson('/digdeep/api/bulk', $payload + ['ids' => [$this->id]])->assertStatus($status); +})->with([ + 'blank tag' => [['action' => 'tag', 'tag' => ''], 400], + 'unknown action' => [['action' => 'explode'], 400], +]); + +it('rejects bulk export without ids or matches, and html export without an id', function (): void { + $this->postJson('/digdeep/api/bulk-export', ['ids' => []])->assertStatus(400); + $this->postJson('/digdeep/api/bulk-export', ['ids' => ['nope']])->assertNotFound(); + $this->get('/digdeep/api/html-export?template=profile')->assertStatus(400); +}); + +it('exports html from an empty store and with failing profiles', function (): void { + $this->profile('/boom', fn () => throw new RuntimeException('boom')); + $this->get('/digdeep/api/html-export?template=dashboard')->assertOk(); + $this->get('/digdeep/api/html-export?template=performance')->assertOk(); + + DigDeepProfile::query()->delete(); + $this->get('/digdeep/api/html-export?template=dashboard')->assertOk(); +}); + +it('records the matched route for on-demand and replayed profiles', function (): void { + Route::get('/target', fn () => 'ok')->name('target.show'); + + $new = $this->postJson('/digdeep/api/trigger', ['url' => '/target'])->json('profile_id'); + $replayed = $this->postJson('/digdeep/api/profile/'.$new.'/replay')->json('profile_id'); + + foreach ([$new, $replayed] as $id) { + expect(DigDeepProfile::query()->find($id)->data['route']['name'])->toBe('target.show'); + } +}); + +it('streams bulk exports', function (): void { + $json = json_decode($this->postJson('/digdeep/api/bulk-export', ['ids' => [$this->id]])->streamedContent(), true); + + expect($json['count'])->toBe(1); +}); + +it('runs artisan commands, blocks dangerous ones and reports failures', function (): void { + config(['digdeep.code_actions' => true]); + + $root = sys_get_temp_dir().'/digdeep-artisan-'.uniqid(); + mkdir($root); + file_put_contents($root.'/artisan', 'app->setBasePath($root); + + $this->postJson('/digdeep/api/run-command', ['command' => 'php artisan make:thing "two words"']) + ->assertOk()->assertJson(['exit_code' => 0, 'output' => 'make:thing two words']); + unlink($root.'/artisan'); + rmdir($root); + + $this->postJson('/digdeep/api/run-command', ['command' => 'tinker'])->assertJsonPath('exit_code', 1); + + $this->app->setBasePath('/nonexistent-digdeep-dir'); + $this->postJson('/digdeep/api/run-command', ['command' => 'list'])->assertJsonPath('exit_code', 1); +}); diff --git a/tests/Feature/DashboardTest.php b/tests/Feature/DashboardTest.php index 1b3aab2..a4a77f4 100644 --- a/tests/Feature/DashboardTest.php +++ b/tests/Feature/DashboardTest.php @@ -3,6 +3,9 @@ declare(strict_types=1); use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Route; +use LaravelPlus\DigDeep\Storage\DigDeepStorage; beforeEach(function (): void { $this->profile = $this->profile('/orders', function () { @@ -36,3 +39,55 @@ it('rejects log path traversal', function (): void { $this->get('/digdeep/logs?file=../../.env')->assertOk()->assertDontSee('APP_KEY'); }); + +/** Store a profile with every kind of data the dashboard pages know how to summarise. */ +function richProfile(string $id, array $overrides = []): void +{ + app(DigDeepStorage::class)->store($id, array_replace_recursive([ + 'request' => ['method' => 'POST', 'url' => '/items/42'], + 'response' => ['status_code' => 500, 'headers' => []], + 'route' => ['name' => 'items.store', 'action' => 'ItemController@store', 'middleware' => ['web']], + 'performance' => ['duration_ms' => 1200, 'memory_peak_mb' => 80, 'query_count' => 30, 'query_time_ms' => 300], + 'queries' => [ + ['sql' => 'select * from items where id = 1; drop table items', 'time_ms' => 9, 'caller' => 'app/A.php:1'], + ['sql' => 'insert into items (a) values (1)', 'time_ms' => 1, 'caller' => 'app/A.php:2'], + ['sql' => 'update items set a = 2', 'time_ms' => 1, 'caller' => 'app/A.php:3'], + ['sql' => 'create table x (id int)', 'time_ms' => 1, 'caller' => 'app/A.php:4'], + ['sql' => 'pragma table_info(items)', 'time_ms' => 1, 'caller' => 'app/A.php:5'], + ], + 'cache' => [ + ['type' => 'hit', 'key' => 'user:1'], + ['type' => 'miss', 'key' => 'config.a'], + ['type' => 'miss', 'key' => 'config.a'], + ['type' => 'write', 'key' => 'plain'], + ], + 'exception' => ['class' => 'RuntimeException', 'message' => 'boom', 'code' => 0, 'file' => 'app/A.php', 'line' => 1, 'trace' => [], 'previous' => null], + 'lifecycle' => ['phases' => [['name' => 'boot', 'duration_ms' => 1]]], + ], $overrides)); +} + +it('summarises rich profiles across the analysis pages', function (string $uri): void { + richProfile('r1'); + richProfile('r2', ['request' => ['method' => 'GET', 'url' => '/items/7'], 'response' => ['status_code' => 200, 'headers' => ['x-content-type-options' => 'nosniff']], 'route' => ['name' => null, 'action' => null, 'middleware' => []], 'performance' => ['duration_ms' => 5], 'exception' => null, 'lifecycle' => ['phases' => []]]); + richProfile('r3', ['request' => ['url' => '/items/9'], 'route' => ['name' => null, 'action' => 'ItemController@store', 'middleware' => ['csrf']]]); + richProfile('r4', ['request' => ['url' => '/items'], 'route' => ['name' => null, 'action' => null]]); + richProfile('r5', ['request' => ['url' => '/items/42'], 'exception' => null]); + richProfile('r6', ['request' => ['url' => '/items/43'], 'exception' => null, 'response' => ['status_code' => 500]]); + Route::post('/items', fn () => 'ok')->name('items.store'); + Route::get('/items/{item}', fn () => 'ok'); + + $this->get($uri)->assertOk(); +})->with(['/digdeep', '/digdeep/pipeline', '/digdeep/security', '/digdeep/audits', '/digdeep/errors', '/digdeep/database', '/digdeep/cache', '/digdeep/performance']); + +it('lists, reads and tolerates empty log files', function (): void { + $dir = storage_path('logs'); + File::ensureDirectoryExists($dir); + File::put("$dir/digdeep-test.log", "[2026-01-01 10:00:00] testing.ERROR: Boom {\"a\":1}\n[stacktrace]\n#0 x\n[2026-01-01 10:00:01] testing.INFO: plain\n"); + File::put("$dir/digdeep-empty.log", ''); + + $this->get('/digdeep/logs?file=digdeep-test.log')->assertOk()->assertSee('Boom')->assertSee('plain'); + $this->get('/digdeep/logs?file=digdeep-empty.log')->assertOk(); + $this->get('/digdeep/logs')->assertOk(); + + File::delete(["$dir/digdeep-test.log", "$dir/digdeep-empty.log"]); +}); diff --git a/tests/Feature/DatabaseTest.php b/tests/Feature/DatabaseTest.php index abce8bd..c8cd569 100644 --- a/tests/Feature/DatabaseTest.php +++ b/tests/Feature/DatabaseTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Support\Facades\Schema; use LaravelPlus\DigDeep\Analyzers\QueryAnalyzer; it('reads the schema through the driver-agnostic Schema API', function (): void { @@ -25,3 +26,9 @@ it('renders the database page', function (): void { $this->get('/digdeep/database')->assertOk(); }); + +it('returns an empty schema when introspection fails', function (): void { + Schema::shouldReceive('getTables')->andThrow(new RuntimeException('no introspection')); + + expect(QueryAnalyzer::schema())->toBe([]); +}); diff --git a/tests/Feature/McpTest.php b/tests/Feature/McpTest.php index cbe7d11..bc6c980 100644 --- a/tests/Feature/McpTest.php +++ b/tests/Feature/McpTest.php @@ -2,7 +2,11 @@ declare(strict_types=1); +use Illuminate\JsonSchema\JsonSchemaTypeFactory; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Route; +use LaravelPlus\DigDeep\Mcp\Resources\DigDeepConfig; +use LaravelPlus\DigDeep\Mcp\Resources\DigDeepOverview; use LaravelPlus\DigDeep\Mcp\Servers\DigDeepServer; use LaravelPlus\DigDeep\Mcp\Tools\AnalyzeQueries; use LaravelPlus\DigDeep\Mcp\Tools\GetPerformance; @@ -12,6 +16,7 @@ use LaravelPlus\DigDeep\Mcp\Tools\GetTrends; use LaravelPlus\DigDeep\Mcp\Tools\ListProfiles; use LaravelPlus\DigDeep\Mcp\Tools\ProfileUrl; +use LaravelPlus\DigDeep\Models\DigDeepProfile; beforeEach(function (): void { $this->id = $this->profile('/orders')->id; @@ -37,3 +42,70 @@ DigDeepServer::tool(ProfileUrl::class, ['url' => '/mcp-target'])->assertOk()->assertSee('200'); }); + +it('serves the overview and config resources', function (): void { + DigDeepServer::resource(DigDeepOverview::class)->assertOk()->assertSee('DigDeep Profiler'); + DigDeepServer::resource(DigDeepConfig::class)->assertOk()->assertSee('thresholds'); +}); + +it('reports missing parameters and profiles', function (string $tool, array $args, string $message): void { + DigDeepServer::tool($tool, $args)->assertHasErrors([$message]); +})->with([ + 'get without id' => [GetProfile::class, ['id' => ''], 'The "id" parameter is required.'], + 'get unknown' => [GetProfile::class, ['id' => 'nope'], 'Profile not found: nope'], + 'analyze without id' => [AnalyzeQueries::class, ['id' => ''], 'The "id" parameter is required.'], + 'analyze unknown' => [AnalyzeQueries::class, ['id' => 'nope'], 'Profile not found: nope'], + 'profile without url' => [ProfileUrl::class, ['url' => ''], 'The "url" parameter is required.'], +]); + +it('analyzes a profile with and without queries', function (): void { + DigDeepServer::tool(AnalyzeQueries::class, ['id' => $this->id])->assertSee('"query_count":0'); + + $id = $this->profile('/q', function () { + DB::select('select * from digdeep_profiles'); + + return 'ok'; + })->id; + + DigDeepServer::tool(AnalyzeQueries::class, ['id' => $id])->assertSee('hints'); +}); + +it('filters profiles, trends and performance', function (): void { + $this->profile('/boom', fn () => throw new RuntimeException('boom')); + + DigDeepServer::tool(ListProfiles::class, ['status_min' => 500, 'method' => 'GET', 'limit' => 1])->assertSee('"count":1'); + + foreach (['hour', 'day', 'week'] as $range) { + DigDeepServer::tool(GetTrends::class, ['route' => 'boom', 'range' => $range])->assertSee('/boom'); + DigDeepServer::tool(GetPerformance::class, ['range' => $range])->assertSee('"total":2'); + } +}); + +it('profiles a url that blows up and uses the requested method', function (): void { + Route::post('/mcp-boom', fn () => throw new RuntimeException('kaput')); + $this->withoutExceptionHandling(); + + DigDeepServer::tool(ProfileUrl::class, ['url' => '/mcp-boom', 'method' => 'post'])->assertOk()->assertSee('500')->assertSee('POST'); +}); + +it('profiles a url that matches no route', function (): void { + DigDeepServer::tool(ProfileUrl::class, ['url' => '/nowhere'])->assertOk()->assertSee('"status_code":404'); +}); + +it('describes the input of every tool', function (string $tool): void { + expect(app($tool)->schema(new JsonSchemaTypeFactory))->toBeArray(); +})->with([ListProfiles::class, GetStats::class, GetProfile::class, AnalyzeQueries::class, GetTrends::class, GetPerformance::class, GetSlowestRoutes::class, ProfileUrl::class]); + +it('reports empty performance without profiles', function (): void { + DigDeepProfile::query()->delete(); + + DigDeepServer::tool(GetPerformance::class)->assertSee('"global":[]'); +}); + +it('includes the matched route when profiling a url', function (): void { + Route::get('/mcp-named', fn () => 'ok')->name('mcp.named'); + + DigDeepServer::tool(ProfileUrl::class, ['url' => '/mcp-named'])->assertOk(); + + expect(DigDeepProfile::query()->where('url', '/mcp-named')->first()->data['route']['name'])->toBe('mcp.named'); +}); diff --git a/tests/Feature/ProfilingTest.php b/tests/Feature/ProfilingTest.php index 4eac504..3d48f16 100644 --- a/tests/Feature/ProfilingTest.php +++ b/tests/Feature/ProfilingTest.php @@ -2,17 +2,31 @@ declare(strict_types=1); +use Illuminate\Auth\GenericUser; +use Illuminate\Console\Events\CommandFinished; +use Illuminate\Console\Events\CommandStarting; +use Illuminate\Console\Events\ScheduledTaskFinished; +use Illuminate\Console\Events\ScheduledTaskStarting; +use Illuminate\Console\Scheduling\Schedule; +use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Events\QueryExecuted; +use Illuminate\Notifications\Notifiable; +use Illuminate\Notifications\Notification; +use Illuminate\Queue\Events\JobQueued; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Notification as NotificationFacade; use Illuminate\Support\Facades\Route; +use Illuminate\Support\Facades\View; use LaravelPlus\DigDeep\DigDeep; use LaravelPlus\DigDeep\DigDeepCollector; use LaravelPlus\DigDeep\Models\DigDeepProfile; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\HttpFoundation\Response; it('records request, response and performance', function (): void { @@ -168,3 +182,186 @@ $this->get('/sampled'); expect(DigDeepProfile::query()->where('url', '/sampled')->count())->toBe(1); }); + +it('records the exception and rethrows when the pipeline throws', function (): void { + Route::get('/kaboom', fn () => throw new RuntimeException('kaput')); + $this->withoutExceptionHandling(); + + expect(fn () => $this->get('/kaboom'))->toThrow(RuntimeException::class, 'kaput'); +}); + +it('captures request bodies without leaking unscrubbable ones', function (string $type, string $body, string $expected): void { + Route::post('/b2', fn () => 'ok'); + $this->call('POST', '/b2', $type === 'application/x-www-form-urlencoded' ? ['a' => 1, 'password' => 'x'] : [], server: ['CONTENT_TYPE' => $type], content: $body); + + expect(DigDeepProfile::query()->where('url', '/b2')->first()->data['request']['body'])->toContain($expected); +})->with([ + 'json' => ['application/json', '{"a":1,"password":"x"}', '"a":1'], + 'json scalar' => ['application/json', '"str"', '[body omitted]'], + 'text' => ['text/plain', 'hello', '[body omitted]'], + 'form' => ['application/x-www-form-urlencoded', 'a=1&password=x', '"a":1'], +]); + +it('records middleware and session data on web routes', function (): void { + Route::get('/web', function () { + session(['cart' => ['a' => 1], 'token' => 'abc', 'name' => 'n', 'obj' => new ArrayObject([1])]); + + return 'ok'; + })->middleware(['web', 'throttle:60,1']); + $this->get('/web'); + + $data = DigDeepProfile::query()->where('url', '/web')->first()->data; + + expect($data['session']['token']['value'])->toBe('[redacted]') + ->and($data['session']['name']['value'])->toBe('n') + ->and($data['session'])->toHaveKeys(['cart', 'obj']) + ->and($data['route']['middleware'])->toContain('web'); +}); + +it('never breaks the response when the debugbar fails to render', function (): void { + View::composer('digdeep::debugbar', fn () => throw new RuntimeException('view down')); + Route::get('/page', fn () => response('x')->header('Content-Type', 'text/html')); + + $this->get('/page')->assertOk()->assertDontSee('__dd'); +}); + +it('leaves html without a body tag untouched', function (): void { + Route::get('/frag', fn () => response('

x

')->header('Content-Type', 'text/html')); + + $this->get('/frag')->assertOk()->assertDontSee('__dd'); +}); + +it('collects commands, mail, jobs, notifications, scheduled tasks and model deletes', function (): void { + config(['mail.default' => 'array', 'queue.default' => 'sync']); + + $notifiable = new class extends Model + { + use Notifiable; + + protected $guarded = []; + }; + $notifiable->id = 7; + $notification = new class extends Notification + { + public function via(): array + { + return [CollectorTestChannel::class]; + } + }; + + $data = $this->profile('/everything', function () use ($notifiable, $notification) { + $io = [new ArrayInput([]), new NullOutput]; + event(new CommandStarting('about', ...$io)); + event(new CommandFinished('about', ...[...$io, 0])); + event(new CommandFinished('other', ...[...$io, 1])); + Mail::raw('hello', fn ($m) => $m->to('a@example.test')->to('b@example.test')); + event(new JobQueued('sync', 'emails', 1, new stdClass, '{}', null)); + event(new JobQueued('sync', null, 2, 'LegacyJob', '{}', null)); + $notifiable->notify($notification); + NotificationFacade::route('collector-test', 'x')->notify($notification); + + $schedule = app(Schedule::class); + $event = $schedule->command('about'); + event(new ScheduledTaskFinished($event, 0.1)); + event(new ScheduledTaskStarting($event)); + event(new ScheduledTaskFinished($event, 0.1)); + event(new ScheduledTaskStarting($schedule->call(fn () => null))); + + DigDeepProfile::query()->create(['id' => 'tmp', 'method' => 'GET', 'url' => '/tmp', 'data' => []])->delete(); + event('composing: nothing', ['not a view']); + event('custom.event', [1, 'text', new stdClass]); + event('custom.empty', [1]); + Log::info('bad utf8', ['v' => "\xB1\x31"]); + + return 'ok'; + })->data; + + expect($data['commands'][0])->toMatchArray(['command' => 'about', 'exit_code' => 0]) + ->and($data['commands'][1])->toMatchArray(['command' => 'other', 'exit_code' => 1, 'duration_ms' => 0]) + ->and($data['mail'][0])->toMatchArray(['to' => 'a@example.test, b@example.test', 'subject' => '(no subject)']) + ->and(collect($data['jobs'])->pluck('queue')->all())->toBe(['emails', 'default']) + ->and($data['jobs'][1]['job'])->toBe('LegacyJob') + ->and(collect($data['notifications'])->pluck('notifiable')->all())->toContain($notifiable::class.':7') + ->and(collect($data['notifications'])->pluck('sent')->unique()->all())->toBe([true]) + ->and($data['scheduled_tasks'])->toHaveCount(2) + ->and($data['scheduled_tasks'][0]['duration_s'])->not->toBeNull() + ->and(collect($data['models'])->firstWhere('class', DigDeepProfile::class)['deleted'])->toBe(1); +}); + +class CollectorTestChannel +{ + public function send(): void {} +} + +it('summarises inertia pages from json and html responses', function (): void { + $page = ['component' => 'Users/Index', 'url' => '/users', 'version' => 'v1', 'props' => [ + 'users' => array_fill(0, 12, ['name' => 'x']), + 'flags' => ['a' => 1], + 'rows' => [['a' => 1]], + 'name' => str_repeat('x', 600), + 'ok' => true, + 'nothing' => null, + 'count' => 3, + 'deep' => ['l1' => ['l2' => ['l3' => 1]]], + ]]; + + $json = $this->profile('/inertia-json', fn () => response()->json($page)->header('X-Inertia', 'true'))->data['inertia']; + $html = $this->profile('/inertia-html', fn () => response('
'))->data['inertia']; + + expect($json['component'])->toBe('Users/Index') + ->and($json['props'])->toMatchArray(['users' => 'array[12] of objects', 'flags' => 'array[1]', 'name' => 'string(600)', 'ok' => 'true', 'nothing' => 'null', 'count' => '3']) + ->and($json['props_raw']['users'])->toHaveCount(11) + ->and($json['props_raw']['name'])->toEndWith('(truncated)') + ->and($json['props_raw']['deep']['l1']['l2'])->toBe(['...' => 'truncated']) + ->and($html)->toBe($json); +}); + +it('ignores inertia-looking responses that are not pages', function (): void { + $data = $this->profile('/inertia-bad', fn () => response('not json')->header('X-Inertia', 'true'))->data; + $bad = $this->profile('/inertia-bad-html', fn () => response('
'))->data; + + expect($data['inertia'])->toBe([])->and($bad['inertia'])->toBe([]); +}); + +it('records the authenticated user and ignores unknown lifecycle phases', function (mixed $user, mixed $expected): void { + $collector = app(DigDeepCollector::class); + $collector->startRequest(); + $collector->markLifecyclePhase('unknown'); + $collector->setAuthUser($user); + + expect($collector->finishRequest()['request']['auth_user'] ?? null)->toBe($expected); +})->with([ + 'none' => [null, null], + 'scalar' => ['guest-7', 'guest-7'], + 'object' => [new stdClass, null], + 'authenticatable' => [new GenericUser(['id' => 3, 'name' => 'N', 'email' => 'e@example.test']), ['id' => 3, 'name' => 'N', 'email' => 'e@example.test']], +]); + +it('exposes the ajax and pages scopes', function (): void { + $this->profile('/page'); + $this->profile('/json', fn () => ['a' => 1]); + $this->getJson('/json'); + + expect(DigDeepProfile::query()->pages()->count())->toBe(2) + ->and(DigDeepProfile::query()->ajax()->count())->toBe(1); +}); + +it('names the calling file for queries issued outside vendor and package code', function (): void { + $file = sys_get_temp_dir().'/DigDeepCaller.php'; + file_put_contents($file, " Illuminate\\Support\\Facades\\DB::select('select 1');\n"); + + $data = $this->profile('/caller', require $file)->data; + unlink($file); + + expect($data['queries'][0]['caller'])->toBe('DigDeepCaller.php:3'); +}); + +it('reports the app file that ran a query as its caller', function (): void { + $data = $this->profile('/caller', function () { + DB::select('select 1'); + + return 'ok'; + })->data; + + expect($data['queries'][0]['caller'])->toStartWith('ProfilingTest.php:'); +}); diff --git a/tests/Feature/SecurityTest.php b/tests/Feature/SecurityTest.php index b1a32e8..dd2158b 100644 --- a/tests/Feature/SecurityTest.php +++ b/tests/Feature/SecurityTest.php @@ -5,7 +5,9 @@ use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Route; use LaravelPlus\DigDeep\DigDeep; +use LaravelPlus\DigDeep\DigDeepServiceProvider; use LaravelPlus\DigDeep\Models\DigDeepProfile; +use LaravelPlus\DigDeep\Storage\DigDeepStorage; function asProduction(): void { @@ -53,6 +55,7 @@ function asProduction(): void }); it('reports 501 instead of crashing when AI is used without laravel/ai', function (): void { + DigDeep::$aiSdkAvailable = false; config(['digdeep.code_actions' => true]); $this->postJson('/digdeep/api/ai-apply', ['file_path' => 'app/X.php', 'old_code' => 'a', 'new_code' => 'b']) @@ -99,6 +102,7 @@ function asProduction(): void }); it('falls back to the default model when DIGDEEP_AI_MODEL is unset', function (): void { + DigDeep::$aiSdkAvailable = false; config(['digdeep.ai_key' => 'test-key', 'digdeep.ai_provider' => 'anthropic', 'digdeep.ai_model' => null]); Http::fake(['api.anthropic.com/*' => Http::response(['content' => [['text' => 'PROBLEM: x']]])]); @@ -106,3 +110,22 @@ function asProduction(): void Http::assertSent(fn ($request): bool => $request['model'] === 'claude-haiku-4-5-20251001'); }); + +it('denies everyone outside local when no auth callback is registered', function (): void { + (new ReflectionProperty(DigDeep::class, 'authUsing'))->setValue(null, null); + asProduction(); + + $this->get('/digdeep')->assertNotFound(); +}); + +it('registers nothing when disabled', function (): void { + $this->app['config']->set('digdeep.enabled', false); + $provider = new DigDeepServiceProvider($this->app); + $this->app->forgetInstance(DigDeepStorage::class); + unset($this->app[DigDeepStorage::class]); + + $provider->register(); + $provider->boot(); + + expect($this->app->bound(DigDeepStorage::class))->toBeFalse(); +}); diff --git a/tests/Feature/StorageTest.php b/tests/Feature/StorageTest.php index 25e9cd2..5f9e6dc 100644 --- a/tests/Feature/StorageTest.php +++ b/tests/Feature/StorageTest.php @@ -53,7 +53,7 @@ function storeProfile(string $id, array $overrides = []): void Event::assertDispatched(ThresholdExceeded::class); }); -it('filters by status, method, route and tag', function (): void { +it('filters by status, duration, date, method, route and tag', function (): void { storeProfile('ok'); storeProfile('err', ['request' => ['method' => 'POST', 'url' => '/orders'], 'response' => ['status_code' => 500]]); app(DigDeepStorage::class)->updateTags('err', 'checkout'); @@ -64,7 +64,12 @@ function storeProfile(string $id, array $overrides = []): void expect($ids(['status_min' => 500]))->toBe(['err']) ->and($ids(['method' => 'post']))->toBe(['err']) ->and($ids(['route' => 'orders']))->toBe(['err']) - ->and($ids(['tag' => 'checkout']))->toBe(['err']); + ->and($ids(['tag' => 'checkout']))->toBe(['err']) + ->and($ids(['status_max' => 200]))->toBe(['ok']) + ->and($ids(['duration_min' => 20]))->toBe([]) + ->and($ids(['duration_max' => 20]))->toHaveCount(2) + ->and($ids(['date_from' => '2999-01-01']))->toBe([]) + ->and($ids(['date_to' => '2000-01-01']))->toBe([]); }); it('bulk tags, bulk deletes and clears', function (): void { @@ -97,6 +102,29 @@ function storeProfile(string $id, array $overrides = []): void expect(strlen(json_encode(app(DigDeepStorage::class)->find('big')['data'])))->toBeLessThan(50_000); }); +it('shortens oversized bodies without dropping anything else', function (): void { + config(['digdeep.max_profile_size_kb' => 2]); + + storeProfile('chatty', ['response' => ['body' => str_repeat('x', 5_000)]]); + + $data = app(DigDeepStorage::class)->find('chatty')['data']; + + expect($data['response']['body'])->toEndWith('... [truncated]') + ->and($data)->not->toHaveKey('_dropped'); +}); + +it('skips disabled thresholds', function (): void { + config(['digdeep.thresholds' => ['duration_ms' => null, 'query_count' => 0]]); + + storeProfile('p', ['performance' => ['duration_ms' => 99999, 'query_count' => 999]]); + + expect(app(DigDeepStorage::class)->find('p')['tags'])->toBeEmpty(); +}); + +it('reports zeroed stats when empty', function (): void { + expect(app(DigDeepStorage::class)->stats())->toMatchArray(['total' => 0, 'avg_duration' => 0]); +}); + it('empties the largest sections until the profile fits', function (): void { config(['digdeep.max_profile_size_kb' => 4]); diff --git a/tests/TestCase.php b/tests/TestCase.php index 4d14dea..a235d29 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -6,6 +6,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Route; +use Laravel\Ai\AiServiceProvider; use Laravel\Mcp\Server\McpServiceProvider; use LaravelPlus\DigDeep\DigDeep; use LaravelPlus\DigDeep\DigDeepServiceProvider; @@ -26,6 +27,13 @@ protected function setUp(): void DigDeep::auth(fn (): bool => false); } + protected function tearDown(): void + { + DigDeep::$aiSdkAvailable = null; + + parent::tearDown(); + } + /** Laravel 12 calls it ValidateCsrfToken, 13 renamed it PreventRequestForgery. */ protected function withoutCsrf(): static { @@ -48,7 +56,7 @@ protected function profile(string $uri = '/probe', ?\Closure $action = null, str protected function getPackageProviders($app): array { - return [McpServiceProvider::class, DigDeepServiceProvider::class]; + return [AiServiceProvider::class, McpServiceProvider::class, DigDeepServiceProvider::class]; } protected function defineEnvironment($app): void diff --git a/tests/Unit/QueryAnalyzerTest.php b/tests/Unit/QueryAnalyzerTest.php index 6fa04f8..8191302 100644 --- a/tests/Unit/QueryAnalyzerTest.php +++ b/tests/Unit/QueryAnalyzerTest.php @@ -63,3 +63,17 @@ function q(string $sql, string $caller = 'app/Http/Controllers/PostController.ph expect($types)->toContain('n_plus_one', 'select_star'); }); + +it('reports each unindexed column once, as a missing_index hint', function (): void { + $schema = [[ + 'name' => 'users', + 'columns' => [['name' => 'id', 'pk' => true], ['name' => 'email', 'pk' => false]], + 'indexes' => [], + ]]; + $queries = [q('select id from users where email = ?'), q('select id from users where email = ? and id = ?')]; + + $hints = QueryAnalyzer::generateHints($queries, $schema); + + expect($hints)->toHaveCount(1) + ->and($hints[0])->toMatchArray(['type' => 'missing_index', 'message' => "Column 'users.email' used in WHERE but not indexed"]); +});