<?php

namespace Slipstream\Console\Commands;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Str;
use Parallax\Console\Command;
use RuntimeException;
use Throwable;

/**
 * The real Slipstream Agent loop. Runs on a Worker: claims queued tasks,
 * prepares a git workspace (clone or init), branches — into an isolated
 * worktree per task by default — hands the task to a coding agent (Claude
 * Code, Codex, or a custom command), streams the output back as task logs,
 * commits whatever changed, and reports the result.
 */
class AgentRun extends Command
{
    protected $signature = 'agent
        {--url= : Slipstream Cloud base URL (defaults to SLIPSTREAM_URL)}
        {--token= : Worker bearer token (defaults to SLIPSTREAM_WORKER_TOKEN env)}
        {--driver=claude : Executor: claude, codex, or custom (see --exec)}
        {--exec= : Custom executor command template; {prompt} is replaced with the task prompt}
        {--workdir= : Base directory for project workspaces (default ~/.slipstream-agent)}
        {--task-timeout=1800 : Max seconds per task execution}
        {--limit=0 : Stop after N tasks (0 = unlimited)}
        {--once : Exit when the queue is drained}';

    protected $aliases = ['slipstream:agent'];

    protected $description = 'Run the Slipstream Agent: claim tasks, execute them with a coding agent, report back';

    protected string $url;

    protected string $token;

    protected string $workdir;

    protected int $taskTimeout;

    protected string $logBuffer = '';

    protected float $lastFlush = 0;

    protected float $lastBeat = 0;

    /** Extra git env for the current task (e.g. GIT_SSH_COMMAND for a deploy key). */
    protected array $taskGitEnv = [];

    protected ?string $sshKeyFile = null;

    /** Partial stream-json line carried between output callbacks. */
    protected string $streamBuffer = '';

    /** Operator-granted per-task elevation (permission prompts disabled). */
    protected bool $taskElevated = false;

    /** Tool calls the executor was denied during the current task. */
    protected int $permissionDenials = 0;

    public function handle(): int
    {
        $url = $this->option('url') ?: config('parallax.services.slipstream.url');
        $this->token = $this->option('token') ?: (config('parallax.services.slipstream.worker_token') ?: '');
        $this->workdir = rtrim($this->option('workdir') ?: (($_SERVER['HOME'] ?? sys_get_temp_dir()).'/slipstream-agent'), '/');
        $this->taskTimeout = (int) $this->option('task-timeout');

        if (! $url) {
            $this->error('Pass --url= or set SLIPSTREAM_URL to your Slipstream Cloud host.');

            return static::FAILURE;
        }

        $this->url = preg_replace('#/api$#i', '', rtrim($url, '/'));

        if (! $this->token) {
            $this->error('Pass --token= (or set SLIPSTREAM_WORKER_TOKEN) from the Worker detail page.');

            return static::FAILURE;
        }

        try {
            $this->executorTemplate();
        } catch (RuntimeException $e) {
            $this->error($e->getMessage());

            return static::FAILURE;
        }

        @mkdir($this->workdir, 0755, true);

        $response = $this->http()->post("{$this->url}/api/worker/register", [
            'capabilities' => [
                'agent' => 'slipstream-agent/0.1',
                'driver' => $this->option('driver'),
                'php' => PHP_VERSION,
            ],
            'metadata' => [
                'hostname' => gethostname(),
                'workdir' => $this->workdir,
            ],
        ]);

        if ($response->failed()) {
            $this->error("Register failed ({$response->status()}): ".$response->body());

            return static::FAILURE;
        }

        $worker = $response->json('worker');
        $this->info("Registered as worker #{$worker['id']} ({$worker['name']}) — driver: {$this->option('driver')}.");

        $handled = 0;
        $limit = (int) $this->option('limit');

        while (true) {
            if (! $this->heartbeat()) {
                if ($this->option('once')) {
                    return static::FAILURE;
                }

                sleep(5);

                continue;
            }

            $response = $this->http()->get("{$this->url}/api/worker/tasks/next");

            if ($response->failed()) {
                $this->error("Task poll failed ({$response->status()}).");

                return static::FAILURE;
            }

            $task = $response->json('task');

            if (! $task) {
                if ($this->option('once')) {
                    $this->info('Queue drained. Exiting.');

                    return static::SUCCESS;
                }

                sleep(5);

                continue;
            }

            try {
                $this->executeTask($task);
            } catch (Throwable $e) {
                // Belt and braces: executeTask fails the task itself on error,
                // but never let one task take the whole agent down.
                $message = $this->redactCredentials($e->getMessage());
                $this->error("Task #{$task['id']} crashed the runner: {$message}");
            }

            if ($limit > 0 && ++$handled >= $limit) {
                $this->info("Reached --limit={$limit}. Exiting.");

                return static::SUCCESS;
            }
        }
    }

    protected function executeTask(array $task): void
    {
        $branch = 'slipstream/task-'.$task['id'];
        $useWorktree = (bool) ($task['context']['use_worktree'] ?? false);
        $this->taskElevated = (bool) ($task['context']['allow_elevated'] ?? false);
        $this->permissionDenials = 0;
        $this->logBuffer = '';

        $this->info("Task #{$task['id']}: {$task['title']}".($useWorktree ? ' (worktree)' : '').($this->taskElevated ? ' (elevated)' : ''));

        $this->prepareSshKey($task);

        try {
            $base = $this->prepareWorkspace($task);

            if ($useWorktree) {
                $cwd = $this->addWorktree($base, $task, $branch);
            } else {
                $cwd = $base;
                $this->git($cwd, ['checkout', '-B', $branch]);
            }

            $start = $this->http()->post("{$this->url}/api/worker/tasks/{$task['id']}/start", [
                'branch_name' => $branch,
            ]);

            if ($start->failed()) {
                // The task moved on without us (cancelled, or the sweep requeued
                // it to another worker). Executing anyway would double-run it.
                $this->warn("Task #{$task['id']}: cloud refused start ({$start->status()}) — skipping.");

                return;
            }

            // A previous run (shared workspace, or a reclaimed worktree) may
            // have left proposals behind; they belong to that run, not this one.
            @unlink($cwd.'/.slipstream/proposals.jsonl');

            $this->bufferLog($task, "Workspace: {$cwd}".($useWorktree ? ' (isolated worktree)' : ''));
            $this->bufferLog($task, "Branch: {$branch}");
            $this->bufferLog($task, "Executor: {$this->option('driver')}".($this->taskElevated ? ' (elevated: permission prompts disabled)' : ''));

            $exitCode = $this->runExecutor($task, $cwd);

            if ($this->permissionDenials > 0) {
                $this->bufferLog($task, "⚠ {$this->permissionDenials} permission denial(s) during this run — the result may be incomplete. Grant elevated access and requeue if work is missing.");
            }

            $this->flushLog($task, force: true);

            if ($exitCode !== 0) {
                // Leave the worktree in place so the failure can be inspected.
                if ($useWorktree) {
                    $this->bufferLog($task, "Worktree kept for inspection: {$cwd}");
                }

                $this->flushLog($task, force: true);

                $this->report($task, 'fail', [
                    'message' => "Executor exited with code {$exitCode}.",
                    'output' => [
                        'driver' => $this->option('driver'),
                        'exit_code' => $exitCode,
                        'elevated' => $this->taskElevated,
                        'permission_denials' => $this->permissionDenials,
                        'worktree' => $useWorktree,
                    ],
                ]);

                $this->error("Task #{$task['id']} failed (exit {$exitCode}).");

                return;
            }

            // Consume proposals before committing so the file never lands in
            // the repo — the hand-back channel is API traffic, not code.
            $proposals = $this->handOffProposals($task, $cwd);

            $commit = $this->commitChanges($task, $cwd);

            $pushed = $this->pushBranch($task, $cwd, $branch);

            if ($useWorktree) {
                $this->removeWorktree($base, $cwd, $task);
            }

            $this->report($task, 'complete', [
                'message' => $commit
                    ? "Completed. Committed {$commit['sha']} ({$commit['summary']})".($pushed ? " and pushed {$branch}." : " — NOT pushed; the work only exists on this worker (branch {$branch}).")
                    : 'Completed. Executor made no file changes (or committed them itself).',
                'branch_name' => $branch,
                'output' => [
                    'driver' => $this->option('driver'),
                    'exit_code' => $exitCode,
                    'commit' => $commit['sha'] ?? null,
                    'summary' => $commit['summary'] ?? null,
                    'pushed' => $pushed,
                    'worktree' => $useWorktree,
                    'elevated' => $this->taskElevated,
                    'permission_denials' => $this->permissionDenials,
                    'proposals' => $proposals,
                ],
            ]);

            $this->info("Task #{$task['id']} completed".($commit ? " — {$commit['sha']}" : '').'.');
        } catch (Throwable $e) {
            $this->flushLog($task, force: true);
            $message = $this->redactCredentials($e->getMessage());

            $this->report($task, 'fail', [
                'message' => 'Runner error: '.$message,
            ]);

            $this->error("Task #{$task['id']} failed: {$message}");
        } finally {
            $this->cleanupSshKey();
        }
    }

    /**
     * The hand-back channel. The executor must not perform operational
     * follow-ups (deploys, migrations, server config) itself; it writes them
     * to .slipstream/proposals.jsonl instead, and each one becomes a proposed
     * task in the cloud, gated on operator approval. The file is consumed
     * before commitChanges so it never reaches the repo.
     */
    protected function handOffProposals(array $task, string $cwd): int
    {
        $path = $cwd.'/.slipstream/proposals.jsonl';

        if (! is_file($path)) {
            return 0;
        }

        $lines = array_values(array_filter(array_map('trim', file($path))));

        @unlink($path);
        @rmdir(dirname($path)); // no-op unless the executor left it empty

        $sent = 0;

        foreach (array_slice($lines, 0, 10) as $line) {
            $proposal = json_decode($line, true);

            if (! is_array($proposal) || empty($proposal['title'])) {
                $this->bufferLog($task, 'Skipped a malformed proposal line from the executor.');

                continue;
            }

            $response = $this->http()->post("{$this->url}/api/worker/tasks", [
                'title' => (string) $proposal['title'],
                'description' => isset($proposal['description']) ? (string) $proposal['description'] : null,
                'task_id' => $task['id'],
                // Cloud actions pass through untouched; the cloud validates.
                ...(isset($proposal['action']) ? ['action' => $proposal['action']] : []),
                ...(isset($proposal['action_params']) && is_array($proposal['action_params']) ? ['action_params' => $proposal['action_params']] : []),
            ]);

            if ($response->successful()) {
                $sent++;
                $this->bufferLog($task, "↗ Proposed follow-up task #{$response->json('task.id')}: {$proposal['title']} — awaiting operator approval.");
            } else {
                $this->bufferLog($task, "Cloud rejected proposal ({$response->status()}): {$proposal['title']}");
            }
        }

        if (count($lines) > 10) {
            $this->bufferLog($task, 'Proposal cap reached — only the first 10 were sent.');
        }

        if ($sent || count($lines)) {
            $this->flushLog($task, force: true);
        }

        return $sent;
    }

    /**
     * Deliver a terminal task state and shout when the cloud disagrees — a 409
     * here means the task was requeued or cancelled while we worked, and the
     * result of this run is about to be discarded.
     */
    protected function report(array $task, string $action, array $payload): void
    {
        $response = $this->http()->post("{$this->url}/api/worker/tasks/{$task['id']}/{$action}", $payload);

        if ($response->failed()) {
            $this->warn("Task #{$task['id']}: cloud rejected {$action} ({$response->status()}: ".trim((string) $response->body()).')');
        }
    }

    /**
     * When the cloud resolved the remote to an SSH deploy key, drop the private
     * key into a locked-down temp identity file and point git at it via
     * GIT_SSH_COMMAND. The key material never lands in .git/config and never
     * gets logged; the file is removed once the task finishes.
     */
    protected function prepareSshKey(array $task): void
    {
        $this->taskGitEnv = [];
        $this->sshKeyFile = null;

        $key = $task['context']['ssh_key'] ?? null;

        if (! $key) {
            return;
        }

        $dir = $this->workdir.'/.keys';
        @mkdir($dir, 0700, true);

        $path = $dir.'/task-'.$task['id'];
        file_put_contents($path, rtrim($key)."\n");
        chmod($path, 0600);

        $this->sshKeyFile = $path;
        $this->taskGitEnv = [
            // IdentitiesOnly pins our key; -F /dev/null ignores any host ssh
            // config; accept-new trusts the host on first use; BatchMode fails
            // fast instead of prompting on a headless worker.
            'GIT_SSH_COMMAND' => 'ssh -i '.escapeshellarg($path).' -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o BatchMode=yes -F /dev/null',
        ];
    }

    protected function cleanupSshKey(): void
    {
        if ($this->sshKeyFile && is_file($this->sshKeyFile)) {
            @unlink($this->sshKeyFile);
        }

        $this->sshKeyFile = null;
        $this->taskGitEnv = [];
    }

    /**
     * Check the task branch out into its own worktree next to the project
     * workspace, so parallel tasks (and a second agent on the same box) never
     * fight over one checkout. A requeued task reclaims its old path.
     */
    protected function addWorktree(string $base, array $task, string $branch): string
    {
        $path = $this->workdir.'/worktrees/task-'.$task['id'];

        @mkdir(dirname($path), 0755, true);

        if (is_dir($path)) {
            Process::path($base)->run(['git', 'worktree', 'remove', '--force', $path]);
        }

        Process::path($base)->run(['git', 'worktree', 'prune']);

        // -B can't reset a branch the base checkout is sitting on (e.g. a
        // requeued task that previously ran in-place); detach it first.
        $current = trim(Process::path($base)->run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])->output());

        if ($current === $branch) {
            $this->git($base, ['checkout', '--detach']);
        }

        $this->git($base, ['worktree', 'add', '-B', $branch, $path]);

        return $path;
    }

    /**
     * The branch (and its commits) live in the shared repo, so the checkout
     * itself is disposable once the work is committed and pushed.
     */
    protected function removeWorktree(string $base, string $path, array $task): void
    {
        $result = Process::path($base)->run(['git', 'worktree', 'remove', '--force', $path]);

        if ($result->successful()) {
            $this->bufferLog($task, 'Worktree cleaned up.');
        } else {
            $this->bufferLog($task, "Worktree cleanup failed (left at {$path}): ".trim($result->errorOutput()));
        }

        $this->flushLog($task, force: true);
    }

    /**
     * One persistent workspace per project so successive tasks build on each
     * other; clone when the project has a repo, otherwise init a fresh one.
     */
    protected function prepareWorkspace(array $task): string
    {
        $context = $task['context'] ?? [];
        $projectId = $context['project']['id'] ?? null;
        $repoUrl = $context['repo_url'] ?? null;
        // Private repos clone over an authenticated URL; the token never lands
        // in remote config (we reset origin below) and never gets logged.
        $fetchUrl = $context['fetch_url'] ?? $repoUrl;

        $dir = $this->workdir.'/'.($projectId ? "project-{$projectId}" : "task-{$task['id']}");

        if (! is_dir($dir.'/.git')) {
            if ($repoUrl) {
                $this->line("  Cloning {$repoUrl}...");
                $this->git($this->workdir, ['clone', $fetchUrl, $dir]);

                if ($fetchUrl !== $repoUrl) {
                    // Keep the clean, credential-free URL in .git/config.
                    $this->git($dir, ['remote', 'set-url', 'origin', $repoUrl]);
                }
            } else {
                @mkdir($dir, 0755, true);
                $this->git($dir, ['init']);
                $this->git($dir, ['commit', '--allow-empty', '-m', 'Slipstream workspace init'], identity: true);
            }
        } elseif ($fetchUrl) {
            // Best effort freshen; offline/dirty states shouldn't kill the run.
            // Fetch from the (possibly authenticated) URL directly so a private
            // origin doesn't fail auth.
            Process::path($dir)->env($this->gitEnv())->run(['git', 'fetch', '--prune', $fetchUrl]);
        }

        return $dir;
    }

    protected function runExecutor(array $task, string $cwd): int
    {
        $command = str_replace('{prompt}', escapeshellarg($this->buildPrompt($task)), $this->executorTemplate());

        $this->lastFlush = microtime(true);
        $this->streamBuffer = '';

        // start() + a wait loop instead of run(): a thinking model can go
        // minutes without a byte of output, and the callback-only heartbeat
        // let the cloud's stale-worker sweep requeue tasks mid-run. Here
        // presence is kept fresh on a clock, independent of executor chatter.
        $process = Process::path($cwd)
            ->timeout($this->taskTimeout)
            ->start($command, function (string $type, string $output) use ($task) {
                $this->ingestExecutorOutput($task, $type, $output);
            });

        $startedAt = microtime(true);
        $killed = false;

        while ($process->running()) {
            $this->heartbeat(rateLimited: true);
            $this->flushLog($task);

            if (! $killed && (microtime(true) - $startedAt) > $this->taskTimeout) {
                $process->signal(9);
                $killed = true;
                $this->bufferLog($task, "Executor killed after {$this->taskTimeout}s (--task-timeout).");
            }

            usleep(250_000);
        }

        try {
            $result = $process->wait();
            $exitCode = $result->exitCode() ?? 1;
        } catch (Throwable $e) {
            $exitCode = 1;
        }

        // A final partial line (no trailing newline) still holds the result event.
        if (trim($this->streamBuffer) !== '') {
            $this->ingestExecutorOutput($task, 'out', "\n");
        }

        return $killed ? 124 : $exitCode;
    }

    /**
     * Route executor output into the task log. Stream-json stdout is narrated
     * into human-readable chatter; stderr and non-JSON drivers pass through raw.
     */
    protected function ingestExecutorOutput(array $task, string $type, string $output): void
    {
        if ($type !== 'out' || ! str_contains($this->executorTemplate(), 'stream-json')) {
            $this->output->write($output);
            $this->logBuffer .= $output;
        } else {
            $this->streamBuffer .= $output;

            while (($pos = strpos($this->streamBuffer, "\n")) !== false) {
                $line = substr($this->streamBuffer, 0, $pos);
                $this->streamBuffer = substr($this->streamBuffer, $pos + 1);

                foreach ($this->narrateStreamEvent($line) as $narrated) {
                    $this->output->writeln($narrated);
                    $this->logBuffer .= $narrated."\n";
                }
            }
        }

        $this->flushLog($task);
        $this->heartbeat(rateLimited: true);
    }

    /**
     * Turn one Claude Code stream-json event into the running commentary a
     * human wants to read: what the agent said, which tools it reached for,
     * and the final result — not a wall of raw JSON.
     */
    protected function narrateStreamEvent(string $line): array
    {
        if (trim($line) === '') {
            return [];
        }

        $event = json_decode($line, true);

        if (! is_array($event)) {
            return [rtrim($line)]; // not JSON (warning, banner) — pass through
        }

        switch ($event['type'] ?? '') {
            case 'system':
                if (($event['subtype'] ?? '') === 'init') {
                    return ['⚡ Session started ('.($event['model'] ?? 'claude').')'];
                }

                return [];

            case 'assistant':
                $lines = [];

                foreach ($event['message']['content'] ?? [] as $block) {
                    if (($block['type'] ?? '') === 'text' && trim($block['text'] ?? '') !== '') {
                        $lines[] = trim($block['text']);
                    }

                    if (($block['type'] ?? '') === 'tool_use') {
                        $lines[] = '⏺ '.($block['name'] ?? 'tool').'('.$this->summarizeToolInput($block['input'] ?? []).')';
                    }
                }

                return $lines;

            case 'user':
                // Tool results echo back through 'user' events. Surface the ones
                // where the harness denied the tool — that's the agent asking for
                // access it doesn't have, and exactly what the operator needs to
                // see to grant elevation.
                $lines = [];

                foreach ($event['message']['content'] ?? [] as $block) {
                    if (($block['type'] ?? '') !== 'tool_result' || ! ($block['is_error'] ?? false)) {
                        continue;
                    }

                    $text = is_array($block['content'] ?? null)
                        ? implode(' ', array_column($block['content'], 'text'))
                        : (string) ($block['content'] ?? '');

                    if (preg_match('/permission|approv|haven\'t granted|not allowed|denied/i', $text)) {
                        $this->permissionDenials++;
                        $lines[] = '🔒 Denied: '.Str::limit(str_replace("\n", ' ', trim($text)), 200);
                    }
                }

                return $lines;

            case 'result':
                $duration = isset($event['duration_ms']) ? gmdate('i\m s\s', (int) ($event['duration_ms'] / 1000)) : null;
                $turns = $event['num_turns'] ?? null;
                $meta = implode(', ', array_filter([$duration, $turns ? "{$turns} turns" : null]));

                $prefix = ($event['is_error'] ?? false) ? '✗ Executor error' : '✓ Executor finished';

                return array_filter([
                    $prefix.($meta ? " ({$meta})" : ''),
                    trim((string) ($event['result'] ?? '')) ?: null,
                ]);
        }

        // Tool results and unknown event types are noise at this altitude.
        return [];
    }

    /** The one input field that identifies what a tool call touched. */
    protected function summarizeToolInput(array $input): string
    {
        foreach (['file_path', 'path', 'command', 'pattern', 'url', 'description', 'prompt'] as $key) {
            if (filled($input[$key] ?? null)) {
                return Str::limit(str_replace("\n", ' ', (string) $input[$key]), 100);
            }
        }

        return '';
    }

    protected function buildPrompt(array $task): string
    {
        $context = $task['context'] ?? [];

        $lines = array_filter([
            'You are the Slipstream Agent working in the current directory, a git checkout on a dedicated branch.',
            ($context['project']['name'] ?? null) ? 'Project: '.$context['project']['name'] : null,
            ($context['workstream']['name'] ?? null) ? 'Workstream: '.$context['workstream']['name'] : null,
            "Task #{$task['id']}: {$task['title']}",
            $task['description'] ?: null,
            'Make focused changes for this task only. Stay inside this repository. '
                .'You may commit as you go; any uncommitted changes will be committed automatically when you finish.',
            'You do not deploy; you request deployment. Never perform operational work yourself — no deploys, '
                .'no migrations against live environments, no server/DNS/certificate changes, no third-party '
                .'service configuration. When this task calls for such a step, hand it back to Slipstream: append '
                .'one JSON object per line to .slipstream/proposals.jsonl with keys "title" and "description" '
                .'(state what needs to happen and why; the operator decides whether and how it runs). '
                .'For work Slipstream can do itself via the operator\'s integrations, add an action: to create '
                .'a remote repository, include "action": "repo.create" and "action_params": {"name": "<repo-name>"} '
                .'— approval then executes it in the cloud instantly. Do not commit that file.',
            $this->taskElevated
                ? null
                : 'You may be denied permission for some tools (e.g. shell commands). If that blocks the task, do NOT '
                    .'describe the work as done — finish what you can with the tools you have, then state plainly which '
                    .'steps you could not perform and why, so the operator can grant elevated access and requeue.',
        ]);

        return implode("\n\n", $lines);
    }

    /**
     * Push the task branch when the cloud handed us a token-authenticated
     * push URL. The URL never goes into remote config and never gets logged.
     */
    protected function pushBranch(array $task, string $cwd, string $branch): bool
    {
        $pushUrl = $task['context']['push_url'] ?? null;

        if (! $pushUrl) {
            // Say so loudly: without a push the branch lives only on this box,
            // which reads as "the agent did nothing" from the cloud UI.
            $this->bufferLog($task, 'No git credentials resolved — branch not pushed. Add a PAT, deploy key, or git integration so work reaches the remote.');
            $this->flushLog($task, force: true);

            return false;
        }

        $this->bufferLog($task, 'Pushing branch to remote...');

        $result = Process::path($cwd)
            ->timeout(120)
            ->env($this->gitEnv())
            ->run(['git', 'push', '--force-with-lease', $pushUrl, "HEAD:refs/heads/{$branch}"]);

        if (! $result->successful()) {
            $error = str_replace($pushUrl, '<push-url>', trim($result->errorOutput() ?: $result->output()));
            $this->bufferLog($task, "Push failed: {$error}");
            $this->flushLog($task, force: true);

            return false;
        }

        $this->bufferLog($task, "Pushed {$branch} to origin.");
        $this->flushLog($task, force: true);

        return true;
    }

    protected function commitChanges(array $task, string $cwd): ?array
    {
        $dirty = trim(Process::path($cwd)->run(['git', 'status', '--porcelain'])->output());

        if ($dirty === '') {
            return null;
        }

        $this->git($cwd, ['add', '-A']);
        $this->git($cwd, ['commit', '-m', "Task #{$task['id']}: {$task['title']}"], identity: true);

        $sha = trim(Process::path($cwd)->run(['git', 'rev-parse', '--short', 'HEAD'])->output());
        $stat = trim(Process::path($cwd)->run(['git', 'show', '--stat', '--format=', 'HEAD'])->output());
        $summary = trim((string) last(explode("\n", $stat)));

        $this->bufferLog($task, "Committed {$sha}: {$summary}");
        $this->flushLog($task, force: true);

        return ['sha' => $sha, 'summary' => $summary];
    }

    protected function git(string $cwd, array $args, bool $identity = false): void
    {
        $command = array_merge(
            ['git'],
            $identity ? ['-c', 'user.name=Slipstream Agent', '-c', 'user.email=agent@slipstream.dev'] : [],
            $args
        );

        $result = Process::path($cwd)->env($this->gitEnv())->run($command);

        if (! $result->successful()) {
            $command = $this->redactCredentials(implode(' ', $args));
            $output = $this->redactCredentials(trim($result->errorOutput() ?: $result->output()));

            throw new RuntimeException("git {$command} failed: {$output}");
        }
    }

    /** Keep authenticated HTTPS remotes out of console and cloud error logs. */
    protected function redactCredentials(string $value): string
    {
        $value = preg_replace('#(https?://)[^/@\s]+@#i', '$1<credentials>@', $value) ?? $value;

        return preg_replace('#([?&][^=\s&]+)=[^&\s]+#', '$1=<redacted>', $value) ?? $value;
    }

    /**
     * A headless worker has no one to answer a credential prompt, so make git
     * fail fast instead of blocking forever on "Username for 'https://...'".
     */
    protected function gitEnv(): array
    {
        return [
            'GIT_TERMINAL_PROMPT' => '0',
            'GIT_ASKPASS' => 'echo',
            'GCM_INTERACTIVE' => 'never',
            ...$this->taskGitEnv,
        ];
    }

    protected function executorTemplate(): string
    {
        if ($this->option('exec')) {
            return $this->option('exec');
        }

        return match ($this->option('driver')) {
            // stream-json (not text): print mode buffers text output until the
            // run ends, which starved the cloud of logs AND heartbeats — the
            // stale sweep then requeued healthy long-running tasks. The event
            // stream also gives the frontend real running commentary.
            //
            // Default permissions allow edits but deny the shell; an operator
            // grant (task.allow_elevated) lifts the prompts for that one task.
            'claude' => 'claude -p {prompt} --output-format stream-json --verbose '
                .($this->taskElevated ? '--dangerously-skip-permissions' : '--permission-mode acceptEdits'),
            'codex' => $this->taskElevated
                ? 'codex exec --dangerously-bypass-approvals-and-sandbox {prompt}'
                : 'codex exec --full-auto {prompt}',
            'custom' => throw new RuntimeException('--driver=custom requires --exec with a {prompt} placeholder.'),
            default => throw new RuntimeException("Unknown driver '{$this->option('driver')}'. Use claude, codex, or custom."),
        };
    }

    protected function bufferLog(array $task, string $line): void
    {
        $this->logBuffer .= $line."\n";
        $this->flushLog($task);
    }

    /**
     * Batch log lines so long executor runs don't turn into an API call per line.
     */
    protected function flushLog(array $task, bool $force = false): void
    {
        $due = (microtime(true) - $this->lastFlush) > 3 || strlen($this->logBuffer) > 4000;

        if (! $this->logBuffer || (! $force && ! $due)) {
            return;
        }

        $chunk = rtrim($this->logBuffer);
        $this->logBuffer = '';
        $this->lastFlush = microtime(true);

        if ($chunk !== '') {
            $this->http()->post("{$this->url}/api/worker/tasks/{$task['id']}/log", [
                'message' => $chunk,
            ]);
        }
    }

    protected function heartbeat(bool $rateLimited = false): bool
    {
        if ($rateLimited && (microtime(true) - $this->lastBeat) < 60) {
            return true;
        }

        $this->lastBeat = microtime(true);

        $response = $this->http()->post("{$this->url}/api/worker/heartbeat");

        if ($response->failed()) {
            $this->warn("Heartbeat failed ({$response->status()}).");

            return false;
        }

        return true;
    }

    protected function http(): PendingRequest
    {
        return Http::withToken($this->token)
            ->withOptions(['verify' => (bool) config('parallax.ssl_verify', true)])
            ->timeout(30)
            ->acceptJson();
    }
}
