Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
30 changes: 0 additions & 30 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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\<string, Illuminate\\Contracts\\JsonSchema\\JsonSchema\> but returns array\<string, Illuminate\\JsonSchema\\Types\\StringType\>\.$#'
identifier: return.type
Expand Down
3 changes: 0 additions & 3 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 1 addition & 2 deletions src/Ai/Agents/ExceptionInvestigatorAgent.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use LaravelPlus\DigDeep\Ai\Tools\ListSourceFilesTool;
use LaravelPlus\DigDeep\Ai\Tools\ReadSourceFileTool;
use Override;
use Stringable;

#[MaxSteps(6)]
#[MaxTokens(2048)]
Expand All @@ -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.
Expand Down
3 changes: 1 addition & 2 deletions src/Ai/Agents/QueryFixerAgent.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use LaravelPlus\DigDeep\Ai\Tools\ListSourceFilesTool;
use LaravelPlus\DigDeep\Ai\Tools\ReadSourceFileTool;
use Override;
use Stringable;

#[MaxSteps(6)]
#[MaxTokens(2048)]
Expand All @@ -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.
Expand Down
5 changes: 2 additions & 3 deletions src/Ai/Tools/ListSourceFilesTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Override;
use Stringable;

final class ListSourceFilesTool implements Tool
{
Expand All @@ -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.';
}
Expand All @@ -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']);

Expand Down
5 changes: 2 additions & 3 deletions src/Ai/Tools/ReadSourceFileTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Override;
use Stringable;

final class ReadSourceFileTool implements Tool
{
Expand All @@ -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).';
}
Expand All @@ -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']);

Expand Down
5 changes: 2 additions & 3 deletions src/Ai/Tools/WriteSourceFileTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Override;
use Stringable;

final class WriteSourceFileTool implements Tool
{
Expand All @@ -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.';
}
Expand All @@ -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']);

Expand Down
4 changes: 2 additions & 2 deletions src/Collectors/CommandCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
4 changes: 1 addition & 3 deletions src/Collectors/InertiaCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)) {
Expand Down
8 changes: 1 addition & 7 deletions src/Collectors/LogCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use Illuminate\Log\Events\MessageLogged;
use Illuminate\Support\Facades\Event;
use LaravelPlus\DigDeep\Support\Redactor;
use Throwable;

final class LogCollector
{
Expand All @@ -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[] = [
Expand Down
8 changes: 3 additions & 5 deletions src/Collectors/QueryCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,15 @@ final class QueryCollector
/** @var array<int, array{sql: string, bindings: array<mixed>, 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
{
DB::listen(function ($query): 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,
Expand All @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/DigDeep.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
12 changes: 4 additions & 8 deletions src/Http/Controllers/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public function trigger(Request $request): JsonResponse
]);
}

$route = $subRequest->route();
$route = app('request')->route();

if ($route) {
$this->collector->setRoute([
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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 = <<<PROMPT
Expand Down Expand Up @@ -1076,10 +1076,6 @@ private function computeExportPerformance(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);
Expand All @@ -1091,6 +1087,6 @@ private function percentile(array $sorted, float $p): float
*/
private function hasAiSdk(): bool
{
return trait_exists(Promptable::class);
return DigDeep::$aiSdkAvailable ?? trait_exists(Promptable::class);
}
}
22 changes: 2 additions & 20 deletions src/Http/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -624,10 +624,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);
Expand Down Expand Up @@ -674,22 +670,8 @@ public function logs(): View
*/
private function parseLogFile(string $path, int $maxEntries): array
{
// Read file in chunks from the end to avoid memory issues with large files
$handle = fopen($path, 'rb');
if (! $handle) {
return [];
}

fseek($handle, 0, SEEK_END);
$fileSize = ftell($handle);
$chunkSize = min($fileSize, 2 * 1024 * 1024); // Read max 2MB from end
fseek($handle, max(0, $fileSize - $chunkSize));
$content = fread($handle, $chunkSize);
fclose($handle);

if (! $content) {
return [];
}
// Read at most the last 2MB to avoid memory issues with large files
$content = (string) file_get_contents($path, false, null, max(0, filesize($path) - 2 * 1024 * 1024));

$entryPattern = '/^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (?:\w+)\.(\w+): (.+)/m';
preg_match_all($entryPattern, $content, $matches, PREG_OFFSET_CAPTURE);
Expand Down
Loading
Loading