PHPackages                             iazaran/trace-replay - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. iazaran/trace-replay

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

iazaran/trace-replay
====================

Enterprise-ready process tracking, replay, and AI-assisted debugging for Laravel applications.

1.3.0(2w ago)103910—7.1%5MITPHPPHP ^8.2CI passing

Since Apr 3Pushed 2w ago1 watchersCompare

[ Source](https://github.com/iazaran/trace-replay)[ Packagist](https://packagist.org/packages/iazaran/trace-replay)[ Docs](https://iazaran.github.io/trace-replay/)[ RSS](/packages/iazaran-trace-replay/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (8)Dependencies (12)Versions (10)Used By (0)

TraceReplay
===========

[](#tracereplay)

> **Production-conscious step-level tracing, deterministic HTTP replay, and AI-ready debugging for Laravel.**

[![Latest Version](https://camo.githubusercontent.com/3c85b5fad853007dd3b71c2fdc38f90b8a50d5fcd53d2fcaf9d737a61d3d5b37/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f69617a6172616e2f74726163652d7265706c6179)](https://packagist.org/packages/iazaran/trace-replay)[![PHP](https://camo.githubusercontent.com/187240af044d09d5b14a1d9d9ebdf3f7a993e4c7bc09bdb46b4ba661a891bf5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d626c7565)](https://php.net)[![Laravel](https://camo.githubusercontent.com/3c947bde5893eab66cfda333d4d46780b85eb09acdb216efe9330b2e77532c5f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302532302537432532303131253230253743253230313225323025374325323031332d726564)](https://laravel.com)[![License: MIT](https://camo.githubusercontent.com/5caa455d8debc46fb23abbadb45a733a937f3910a73fc875c2f7820468e1bb54/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e)](LICENSE)[![Tests](https://github.com/iazaran/trace-replay/actions/workflows/test.yml/badge.svg)](https://github.com/iazaran/trace-replay/actions/workflows/test.yml)[![Code Analysis](https://github.com/iazaran/trace-replay/actions/workflows/code-analysis.yml/badge.svg)](https://github.com/iazaran/trace-replay/actions/workflows/code-analysis.yml)

TraceReplay is not a standard error logger. It is a full-fledged **execution tracer** that captures every step of your complex workflows, reconstructs them with a waterfall timeline, and offers one-click AI debugging when things go wrong.

[![TraceReplay](art/preview.png)](art/preview.png)

---

Why TraceReplay?
----------------

[](#why-tracereplay)

- **See business workflows as steps**, not just requests, queries, and exceptions scattered across separate tools.
- **Replay captured HTTP requests safely** with mutating methods blocked by default and JSON diffs for response changes.
- **Debug failures with AI-ready context** while masking sensitive fields before payloads are stored.

---

✨ Key Features
--------------

[](#-key-features)

FeatureTraceReplayTelescopeDebugbarClockworkManual step instrumentation✅❌❌❌Waterfall timeline UI✅❌✅✅Deterministic HTTP replay✅❌❌❌Visual JSON diff on replay✅❌❌❌AI fix-prompt generator✅❌❌❌OpenAI / Anthropic / Ollama✅❌❌❌Cache &amp; HTTP tracking✅✅✅✅Mail &amp; Notification tracking✅❌❌❌DB query tracking per step✅✅✅✅Memory tracking per step✅❌✅✅Peak memory tracking✅✅❌❌Livewire Hydrate Tracing✅❌❌❌PII / sensitive-field masking✅❌❌❌Queue-job auto-tracing✅✅❌❌Artisan-command auto-tracing✅✅❌❌Probabilistic Sampling✅❌❌❌Dashboard auth &amp; Gate gate✅✅❌N/AMulti-tenant scoping✅❌❌❌W3C Traceparent support✅❌❌❌Octane Compatible✅✅❌❌---

🛠 Installation
--------------

[](#-installation)

```
composer require iazaran/trace-replay
```

Quick install:

```
php artisan trace-replay:install
php artisan migrate
```

Or publish the config manually:

```
php artisan vendor:publish --tag=trace-replay-config
```

Run migrations:

```
php artisan migrate
```

> **Note:** Migrations run automatically without publishing. They use `json` columns and `decimal` precision for timings, compatible with MySQL 5.7+, MariaDB, PostgreSQL, and SQLite.
>
> ⚠️ **Important When Updating:** Package migrations do not execute automatically upon `composer update`. Whenever you update TraceReplay to a newer version, you must run `php artisan migrate` to ensure any newly introduced schema changes are applied. Review [`UPGRADE.md`](UPGRADE.md) for behavioral changes between versions, especially around replay safety, job payload capture, and workspace ID scoping.

#### Publishing Views

[](#publishing-views)

To customize the dashboard UI:

```
php artisan vendor:publish --tag=trace-replay-views
```

This copies the Blade templates to `resources/views/vendor/trace-replay/` where you can customize the layout, colors, or add your own branding.

#### Recommended: Enable HTTP Middleware

[](#recommended-enable-http-middleware)

To automatically trace all HTTP requests, add the TraceMiddleware to your application. This provides instant visibility into every request without manual instrumentation.

For Laravel 10 (`app/Http/Kernel.php`):

```
protected $middlewareGroups = [
    'web' => [
        // ...
        \TraceReplay\Http\Middleware\TraceMiddleware::class,
    ],
];
```

For Laravel 11+ (`bootstrap/app.php`):

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\TraceReplay\Http\Middleware\TraceMiddleware::class);
})
```

---

⚙️ Configuration
----------------

[](#️-configuration)

Open `config/trace-replay.php`. Key options include:

```
return [
    'enabled' => env('TRACE_REPLAY_ENABLED', true),

    // 0.1 = trace 10% of requests/jobs/commands
    'sample_rate' => env('TRACE_REPLAY_SAMPLE_RATE', 1.0),

    // Disable on low-cost production servers if query-log overhead is too high
    'track_db_queries' => env('TRACE_REPLAY_TRACK_DB', true),

    // Truncate captured JSON fields after 64 KB by default
    'max_payload_size' => env('TRACE_REPLAY_MAX_PAYLOAD_SIZE', 65536),

    // Automatically mask these keys in payloads, headers, and URL query strings
    'mask_fields' => ['password', 'token', 'api_key', 'authorization', 'cookie', 'secret'],

    // Query bindings can contain PII; keep disabled in production unless needed
    'track_db_query_bindings' => env('TRACE_REPLAY_TRACK_DB_BINDINGS', false),

    // Dashboard security: add a Gate for tighter production access
    'middleware' => ['web', 'auth'],
    'route_prefix' => env('TRACE_REPLAY_ROUTE_PREFIX', 'trace-replay'),

    // Replay safety: mutating methods are blocked and override hosts are restricted
    'replay' => [
        'allow_mutating_methods' => env('TRACE_REPLAY_REPLAY_MUTATING', false),
        'allowed_hosts' => array_filter(explode(',', env('TRACE_REPLAY_REPLAY_ALLOWED_HOSTS', ''))),
    ],

    // Agent/MCP API is disabled until this token is set
    'api' => [
        'token' => env('TRACE_REPLAY_API_TOKEN'),
        'middleware' => ['api'],
        'route_prefix' => env('TRACE_REPLAY_API_ROUTE_PREFIX', 'api/trace-replay'),
        'max_steps' => env('TRACE_REPLAY_API_MAX_STEPS', 500),
    ],

    // AI Troubleshooting (Drivers: openai, anthropic, ollama)
    'ai' => [
        'driver' => env('TRACE_REPLAY_AI_DRIVER', 'openai'),
        'api_key' => env('TRACE_REPLAY_AI_KEY'),
        'model' => env('TRACE_REPLAY_AI_MODEL', 'gpt-4o'),
        'base_url' => env('TRACE_REPLAY_AI_BASE_URL'),
    ],

    // Async batch persistence via queue (Reduces overhead)
    'queue' => [
        'enabled' => env('TRACE_REPLAY_QUEUE_ENABLED', false),
    ],

    // Auto-tracing
    'auto_trace' => [
        'jobs'     => true,
        'commands' => false,
        'livewire' => true,
        'capture_job_payload' => false,
    ],
];
```

For low-cost production servers, start with sampling instead of tracing every request:

```
TRACE_REPLAY_SAMPLE_RATE=0.05
TRACE_REPLAY_TRACK_DB=false
TRACE_REPLAY_MAX_PAYLOAD_SIZE=16384
```

Laravel 11+ applications do not always define an `api` middleware group. If your app does not, replace `trace-replay.api.middleware` with middleware that exists in your project, such as `['throttle:api']`.

---

🚀 Usage
-------

[](#-usage)

### Manual Instrumentation

[](#manual-instrumentation)

Wrap any complex logic in `TraceReplay::step()` — each callback's return value is passed through transparently.

```
use TraceReplay\Facades\TraceReplay;

class BookingService
{
    public function handleBooking(array $payload): void
    {
        TraceReplay::start('Flight Booking', ['channel' => 'web']);

        try {
            $inventory = TraceReplay::step('Validate Inventory', function () use ($payload) {
                return Inventory::check($payload['flight_id']);
            });

            TraceReplay::checkpoint('Inventory validated', ['seats_left' => $inventory->seats]);

            TraceReplay::context(['user_tier' => auth()->user()->tier]);

            TraceReplay::step('Charge Credit Card', function () use ($payload) {
                return PaymentGateway::charge($payload['amount']);
            });

            TraceReplay::end('success');

        } catch (\Exception $e) {
            TraceReplay::end('error');
            throw $e;
        }
    }
}
```

**API Reference:**

MethodDescription`TraceReplay::start(name, tags[])`Start a new trace; returns `Trace` or `null` if disabled/sampled-out`TraceReplay::step(label, callable, extra[])`Wrap callable, record timing, memory, DB queries, errors`TraceReplay::measure(label, callable)`Alias for `step()` — semantic clarity for benchmarks`TraceReplay::checkpoint(label, state[])`Record a zero-overhead breadcrumb (no callable)`TraceReplay::context(array)`Merge data into the next step's `state_snapshot``TraceReplay::end(status)`Finalise trace; status: `success` or `error``TraceReplay::getCurrentTrace()`Returns the active `Trace` model (or `null`)`TraceReplay::setWorkspaceId(id)`Scope subsequent traces to a workspace`TraceReplay::setProjectId(id)`Scope subsequent traces to a project---

### Testing Helper

[](#testing-helper)

Use `TraceReplay::fake()` to verify your instrumentation in tests without hitting the database:

```
use TraceReplay\Facades\TraceReplay;

public function test_booking_records_steps()
{
    $fake = TraceReplay::fake();

    $this->post('/book', ['flight_id' => 123]);

    $fake->assertTraceStarted('Flight Booking');
    $fake->assertStepRecorded('Validate Inventory');
    $fake->assertStepRecorded('Charge Credit Card');
    $fake->assertCheckpointRecorded('Inventory validated');
    $fake->assertTraceEnded('success');
    $fake->assertTraceCount(1);
}
```

**Available assertions:**

AssertionDescription`assertTraceStarted(name)`Assert a trace with the given name was started`assertNoTraceStarted()`Assert no trace was started at all`assertTraceCount(n)`Assert exactly `n` traces were started`assertStepRecorded(label)`Assert a step with the given label was recorded`assertCheckpointRecorded(label)`Assert a checkpoint with the given label was recorded`assertStepCount(n, traceName?)`Assert exactly `n` steps in total (or in a named trace)`assertTraceEnded(status)`Assert a trace with the given final status exists---

### Auto Queue-Job Tracing

[](#auto-queue-job-tracing)

Queue jobs are automatically traced when `auto_trace.jobs` is enabled (default: `true`). No manual listener registration is needed — the service provider wires everything up.

To disable, set `TRACE_REPLAY_AUTO_TRACE_JOBS=false` in your `.env`.

Job payloads are not captured by default because queue payloads often contain sensitive application data. To opt in:

```
TRACE_REPLAY_CAPTURE_JOB_PAYLOAD=true
```

---

### Auto Artisan-Command Tracing

[](#auto-artisan-command-tracing)

Artisan commands can be auto-traced by enabling `auto_trace.commands`:

```
TRACE_REPLAY_AUTO_TRACE_COMMANDS=true
```

Internal commands like `queue:work`, `horizon`, and `trace-replay:prune` are excluded by default (see `auto_trace.exclude_commands` in the config).

---

### Debug Bar Component

[](#debug-bar-component)

Drop the `` Blade component into your layout for instant in-page trace inspection:

```
{{-- resources/views/layouts/app.blade.php --}}
@if(config('app.debug'))

@endif
```

---

🎨 The Dashboard
---------------

[](#-the-dashboard)

Access the built-in dashboard at `https://your-app.com/trace-replay`.

[![Dashboard](art/dashboard.png)](art/dashboard.png)

**Features:**

- **Waterfall timeline** — visual bars show each step's exact duration relative to the total trace
- **Live stats** — auto-refreshing counters (total traces, failed, avg duration)
- **Search &amp; filter** — filter by name, IP, user ID; toggle failed-only view
- **Date range filter** — quickly filter traces by today, yesterday, last 7 days, or last 30 days
- **Step inspector** — syntax-highlighted JSON for request payload, response payload, and state snapshot
- **Replay engine** — re-execute any HTTP step and view a structural JSON diff
- **AI Fix Prompt** — one-click prompt ready for Cursor, ChatGPT, or Claude

[![Trace Details](art/details.png)](art/details.png)

### Securing the Dashboard

[](#securing-the-dashboard)

Add authentication or authorization middleware in `config/trace-replay.php`:

```
'middleware' => ['web', 'auth', 'can:view-trace-replay'],
```

Then define the gate:

```
// app/Providers/AuthServiceProvider.php
Gate::define('view-trace-replay', function ($user) {
    return in_array($user->email, config('trace-replay.admin_emails', []));
});
```

Or use IP allowlisting (exact match, comma-separated via env):

```
TRACE_REPLAY_ALLOWED_IPS=203.0.113.5,10.0.0.1
```

---

### Replay Safety

[](#replay-safety)

HTTP replay is intentionally conservative:

- Non-GET methods are blocked unless `TRACE_REPLAY_REPLAY_MUTATING=true`.
- `override_url` can only target the originally recorded host by default.
- Set `TRACE_REPLAY_REPLAY_ALLOWED_HOSTS=staging.example.com,*.internal.test` to allow explicit replay targets.
- Sensitive request headers such as `Authorization`, cookies, CSRF tokens, and forwarded headers are stripped before replay.

---

### Failure Notifications

[](#failure-notifications)

When `trace-replay.notifications.on_failure` is enabled, mail/Slack notifications are dispatched through a queued job after the response so slow webhooks do not add latency to failed requests.

---

🤖 AI Debugging
--------------

[](#-ai-debugging)

For any failed trace the dashboard shows an **AI Fix Prompt** button that generates a structured markdown prompt including:

- Full execution timeline with timing and DB stats
- The exact error message, file, line, and first 20 stack frames
- Request/response payloads (sensitive fields masked)
- Step-by-step state snapshots

### No API Key Required

[](#no-api-key-required)

The AI prompt feature works **without any API key**. Copy the generated prompt and paste it into ChatGPT, Claude, or any other AI assistant.

### Optional: Direct AI Integration

[](#optional-direct-ai-integration)

For a seamless experience, configure an AI driver to get answers directly in the dashboard:

```
# OpenAI (default)
TRACE_REPLAY_AI_DRIVER=openai
TRACE_REPLAY_AI_KEY=sk-your-openai-key
TRACE_REPLAY_AI_MODEL=gpt-4o

# Or Anthropic Claude
TRACE_REPLAY_AI_DRIVER=anthropic
TRACE_REPLAY_AI_KEY=sk-ant-your-key
TRACE_REPLAY_AI_MODEL=claude-3-5-sonnet-latest

# Or Ollama (local, no API key needed)
TRACE_REPLAY_AI_DRIVER=ollama
TRACE_REPLAY_AI_MODEL=llama3
TRACE_REPLAY_AI_BASE_URL=http://localhost:11434/api/generate
```

With a key configured, clicking **"Ask AI"** sends the prompt to your chosen AI provider and displays the response in the dashboard.

---

🤖 MCP / AI-Agent JSON-RPC API
-----------------------------

[](#-mcp--ai-agent-json-rpc-api)

TraceReplay exposes a JSON-RPC 2.0 endpoint at `POST /api/trace-replay/mcp` for autonomous AI agents.

The API is disabled until `TRACE_REPLAY_API_TOKEN` is configured. Send requests with:

```
Authorization: Bearer your-token
```

**Available methods:**

MethodParamsReturns`list_traces``limit`, `status`, `filter_by_error`Paginated trace summaries`get_trace_context``trace_id`, `step_limit`Trace context with capped steps`generate_fix_prompt``trace_id`Markdown debugging prompt`trigger_replay``trace_id`Replay result + JSON diffExample request:

```
{
  "jsonrpc": "2.0",
  "method": "generate_fix_prompt",
  "params": { "trace_id": "9b12f7e4-..." },
  "id": 1
}
```

`step_limit` defaults to `trace-replay.api.max_steps` (`500`) and is capped at that value to keep large traces from producing oversized API responses.

---

🧹 Data Retention
----------------

[](#-data-retention)

Automatically prune old traces with the built-in Artisan command. Add to your scheduler:

```
// app/Console/Kernel.php
$schedule->command('trace-replay:prune --days=30')->daily();
```

Options:

```
php artisan trace-replay:prune --days=30                # Delete traces older than 30 days
php artisan trace-replay:prune --days=30 --dry-run      # Preview what would be deleted
php artisan trace-replay:prune --days=7 --status=error  # Only prune error traces
```

Set `TRACE_REPLAY_RETENTION_DAYS` to choose the default window. If `retention_days` is `null`, the prune command exits without deleting data unless `--days` is passed.

---

🩺 Diagnostics
-------------

[](#-diagnostics)

Check production-readiness settings with:

```
php artisan trace-replay:doctor
```

The command reports dashboard protection, API token status, sample rate, retention, replay safety, query binding capture, and whether the trace tables exist.

---

📤 Export
--------

[](#-export)

Export a trace to JSON or CSV for archiving or external analysis:

```
php artisan trace-replay:export {id} --format=json
php artisan trace-replay:export {id} --format=csv
php artisan trace-replay:export {id} --format=json --output=/tmp/trace.json
php artisan trace-replay:export --status=error --format=json  # Export all error traces
```

---

🧪 Testing
---------

[](#-testing)

```
composer install
composer test
composer format:test
```

The test suite covers:

- Trace lifecycle (start, step, checkpoint, context, end, duration precision)
- Error capturing, step ordering, DB query tracking
- Model scopes (`failed`, `successful`, `search`)
- Model accessors (`error_step`, `total_db_queries`, `total_memory_usage`, `completion_percentage`)
- `PayloadMasker` — recursive PII field redaction, case-insensitivity
- `AiPromptService` — prompt generation, OpenAI integration (mocked), null-safety
- Queue batch persistence, Livewire hydration testing, and mail execution tracking
- `ReplayService` — HTTP replay and JSON diff
- Dashboard — index, filters, search, show, stats, export, replay, AI prompt
- MCP API — REST endpoints and JSON-RPC (all methods + error handling)
- Middleware — TraceMiddleware (route skipping, disabled config), AuthMiddleware (IP allow/block)
- Artisan `trace-replay:prune` (delete, dry-run, status filter, validation)
- Artisan `trace-replay:export` (JSON, CSV, file output, status filter, validation)
- `TraceReplayFake` — assertions for started/count/steps/checkpoints/ended
- Log call tracking per step
- `NotificationService` — error\_reason array/string serialisation safety
- Blade components — TraceBar rendering with enabled/disabled states

---

🛡️ License
----------

[](#️-license)

The MIT License (MIT). See [LICENSE](LICENSE) for details.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance96

Actively maintained with recent releases

Popularity35

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Total

8

Last Release

19d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/10566709?v=4)[Ismael Azaran](/maintainers/iazaran)[@iazaran](https://github.com/iazaran)

---

Top Contributors

[![iazaran](https://avatars.githubusercontent.com/u/10566709?v=4)](https://github.com/iazaran "iazaran (60 commits)")

---

Tags

aiapidebugginglaravelphpreplaysaastracinglaravelmonitoringaidebugginglaravel-packagetracingreplayobservabilitydistributed-tracing

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/iazaran-trace-replay/health.svg)

```
[![Health](https://phpackages.com/badges/iazaran-trace-replay/health.svg)](https://phpackages.com/packages/iazaran-trace-replay)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.4k](/packages/larastan-larastan)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

76318.2M110](/packages/laravel-mcp)[laravel/ai

The official AI SDK for Laravel.

9782.1M153](/packages/laravel-ai)[spatie/laravel-health

Monitor the health of a Laravel application

88011.3M149](/packages/spatie-laravel-health)[api-platform/laravel

API Platform support for Laravel

59156.3k10](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
