#compdef loki

function _loki {
    local context state state_descr line
    typeset -A opt_args

    _arguments -C \
        '1: :_loki_commands' \
        '*::arg:->args'

    case $state in
        (args)
            case $line[1] in
                start|quick)
                    _loki_start
                    ;;
                council)
                    _loki_council
                    ;;
                compound)
                    _loki_compound
                    ;;
                provider)
                    _loki_provider
                    ;;
                memory)
                    _loki_memory
                    ;;
                plan)
                    _loki_plan
                    ;;
                export)
                    _arguments '--sarif[Write findings.sarif for a run]'
                    ;;
                control)
                    _arguments \
                        '--port[Port for the control plane server]:port:' \
                        '--json[Output as JSON]' \
                        '--repo[Repository to backfill]:repo:_files -/' \
                        '1:subcommand:(serve status help)'
                    ;;
                config)
                    _loki_config
                    ;;
                dashboard)
                    _loki_dashboard
                    ;;
                sandbox)
                    _loki_sandbox
                    ;;
                notify)
                    _loki_notify
                    ;;
                enterprise)
                    _loki_enterprise
                    ;;
                projects)
                    _loki_projects
                    ;;
                telemetry)
                    _loki_telemetry
                    ;;
                agent)
                    _loki_agent
                    ;;
                estimate)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '--model[Model whose rough prior to use]:model:' \
                        '--provider[Provider whose default model is used]:provider:' \
                        '--help[Show help]'
                    ;;
                status)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '--badge[Print verified deploy badge]' \
                        '--probe[Re-probe last deploy health URL]' \
                        '--help[Show help]'
                    ;;
                doctor)
                    _arguments \
                        '--json[Output machine-readable JSON]' \
                        '(-q --quiet)'{-q,--quiet}'[Print only failed and warned checks plus the summary]' \
                        '--fix[Create state dirs and a default config; offer claude install and login]' \
                        '--yes[With --fix: run the claude install and login without asking]' \
                        '--help[Show help]'
                    ;;
                chat)
                    _arguments \
                        '--attach[Attach to a running session]' \
                        '--tui[Use the terminal UI]' \
                        '--help[Show help]'
                    ;;
                agents)
                    _arguments \
                        '1:subcommand:(list new show export)' \
                        '--claude[Export to .claude/agents]' \
                        '--user[Use the user-level agents directory]' \
                        '--help[Show help]'
                    ;;
                models)
                    _arguments \
                        '--local[Show local models]' \
                        '--json[Output machine-readable JSON]' \
                        '--help[Show help]'
                    ;;
                setup)
                    _arguments \
                        '--yes[Non-interactive defaults]' \
                        '--check[Report only]' \
                        '--help[Show help]'
                    ;;
                route)
                    _arguments \
                        '1:verb:(start quick)' \
                        '--json[Output machine-readable JSON]' \
                        '--provider[AI provider]:provider name:(claude cline codex aider opencode)' \
                        '--model[Model or route override]:model:' \
                        '--no-pr[Skip the pull request]' \
                        '--max-cost[Spend cap in USD]:amount:' \
                        '--help[Show help]'
                    ;;
                edit)
                    _arguments \
                        '--verify[Run verification after the edit]' \
                        '--commit[Commit the edit]' \
                        '--dry-run[Describe the change only]' \
                        '--help[Show help]' \
                        '*:file:_files'
                    ;;
                reset)
                    _loki_reset
                    ;;
                logs)
                    _arguments \
                        '--follow[Follow logs in real-time]' \
                        '-f[Follow logs in real-time]' \
                        '--tail[Number of lines to show]:number:' \
                        '-n[Number of lines to show]:number:' \
                        '--all[Show all lines]' \
                        '-a[Show all lines]' \
                        '--help[Show help]' \
                        '-h[Show help]'
                    ;;
                issue)
                    _loki_issue
                    ;;
                metrics)
                    _arguments \
                        '--json[Machine-readable JSON output]' \
                        '--last[Analyze last N sessions]:number:' \
                        '--save[Write report to METRICS.md]' \
                        '--share[Upload report as GitHub Gist]' \
                        '--help[Show help]' \
                        '1:subcommand:(prometheus)'
                    ;;
                report)
                    _arguments \
                        '--json[Machine-readable JSON output]' \
                        '--since[Window for kpis (Nd or YYYY-MM-DD)]:since:' \
                        '--efficiency[Include efficiency totals]' \
                        '--help[Show help]' \
                        '1:subcommand:(session metrics cost kpis export share dogfood)'
                    ;;
                share)
                    _arguments \
                        '--private[Create a secret gist]' \
                        '--format[Report format]:format:(text markdown html)' \
                        '--help[Show help]'
                    ;;
                proof)
                    _arguments \
                        '--yes[Skip redaction-preview confirmation]' \
                        '--private[Create a secret gist when sharing]' \
                        '--hosted[Hosted publishing (coming in R9)]' \
                        '--dry-run[Scan and list what share would publish; publishes nothing]' \
                        '--help[Show help]' \
                        '1:subcommand:(list show open share badge md bundle)'
                    ;;
                completions)
                    _arguments '1:shell:(bash zsh install)'
                    ;;
                version)
                    _arguments '--json[Print version, runtime and install path as JSON]' '--help[Show help]'
                    ;;
                monitor)
                    _directories
                    ;;
                context|ctx)
                    _loki_context
                    ;;
                code)
                    _loki_code
                    ;;
                deploy)
                    _arguments \
                        '--dir[Project directory to scan]:directory:_directories' \
                        '--no-clip[Do not copy the command to the clipboard]' \
                        '--execute[Run the deploy command if the receipt gate passes]' \
                        '--canary[With --execute: staged rollout (Vercel promote, Fly canary)]' \
                        '--env-file[With --execute: push KEY=VALUE env via Vercel, Fly, Netlify or Cloudflare (names-only record)]:env file:_files' \
                        '--domain[With --execute: attach a custom domain and prove TLS with openssl]:hostname:' \
                        '--allow-unanchored[Proceed when the receipt records no baseline]' \
                        '--health-url[Health probe URL]:url:' \
                        '--auto-rollback[Roll back on a failed health probe]' \
                        '--help[Show help]'
                    ;;
                verify-pr)
                    _arguments \
                        '--out[Result directory]:dir:_files -/' \
                        '--json[Print the verdict object on stdout]' \
                        '--help[Show help]'
                    ;;
                verify)
                    _arguments \
                        '--pubkey[Check against this public key only]:key file:_files' \
                        '--sign-deploy[Sign a loki.deploy/1 deploy record in place]:record:_files' \
                        '--sign-provenance[Sign a loki.provenance/1 doc in place]:doc:_files' \
                        '--url[Verify the live provenance doc served at URL]:url:' \
                        '--expect-sha[Require the provenance head_sha to equal SHA]:sha:' \
                        '--receipt[Cited receipt file for a deploy record]:receipt:_files' \
                        '--max-age[Reject a receipt older than DUR]:duration:' \
                        '--require-exogenous[Exit 4 when a VERIFIED receipt has no agent-independent passing check]' \
                        '--explain[List each gate as exogenous or agent-influenced with the evidence it read]' \
                        '--json[Print the verdict and gates as JSON on stdout]' \
                        '--seal-composite[Sign a workspace composite]:run dir:_directories' \
                        '--help[Show help]' \
                        '*:receipt or deploy record:_files'
                    ;;
            esac
            ;;
    esac
}

function _loki_commands {
    local -a commands
    commands=(
        'start:Start Loki Mode'
        'quick:Quick single-task mode'
        'quickstart:Guided first build from your idea'
        'monitor:Monitor Docker Compose services with auto-fix'
        'demo:Interactive 60-second demo'
        'tour:Offline sample receipt replay (no key, no spend)'
        'welcome:Friendly first-run opener (what Loki is, next steps)'
        'init:Interactive PRD builder'
        'stop:Stop execution'
        'pause:Pause execution'
        'resume:Resume execution'
        'cancel:Cancel the active Loki 10 run'
        'steer:Steer a running build with a note (needs LOKI_PROMPT_INJECTION=1)'
        'status:Show status'
        'next:Run the right next step for the current build'
        'ship:Finish the build (gates + PR advice) in one command'
        'why:Explain why the last run did what it did'
        'dashboard:Dashboard commands'
        'web:Start the web app surface'
        'logs:View session logs'
        'serve:Start API server'
        'api:API server commands'
        'sandbox:Docker sandbox commands'
        'docker:Run Loki in a Docker container'
        'notify:Notification commands'
        'import:Import GitHub issues'
        'issue:GitHub issue commands'
        'github:GitHub integration commands'
        'config:Config commands'
        'provider:Provider commands'
        'reset:Reset session state'
        'memory:Memory commands'
        'compound:Knowledge compounding commands'
        'checkpoint:Snapshot and restore session state'
        'cp:Snapshot and restore session state (alias of checkpoint)'
        'council:Completion council commands'
        'dogfood:Self-development statistics'
        'projects:Project registry commands'
        'enterprise:Enterprise feature commands'
        'secrets:Secrets and API key management'
        'cockpit:Live cockpit view of a running build'
        'secure:Secure-by-default gate (findings and waivers)'
        'own:Finish-and-own ownership handoff'
        'backup:Back up dashboard state (verified archive)'
        'restore:Restore dashboard state from a verified backup archive'
        'telemetry:OpenTelemetry management'
        'agent:Agent type dispatch'
        'doctor:Check system prerequisites'
        'watchdog:Watchdog process supervision'
        'docs:Documentation commands'
        'onboard:Analyze repo and generate CLAUDE.md'
        'metrics:Session productivity report'
        'share:Share session report as GitHub Gist'
        'proof:Inspect/share proof-of-run artifacts'
        'outcomes:What happened to the work AFTER the receipt (reverted/reworked/survived)'
        'preview:Preview the locally-running app'
        'deploy:Deploy the built product (CI/CD-aware)'
        'context:Context window management'
        'ctx:Context window management (alias)'
        'code:Codebase intelligence'
        'web:Start the web dashboard'
        'plan:Preview the build plan for a spec'
        'report:Reporting commands (cost, kpis, share)'
        'cost:Show cost of recent runs (--detail for cache + trend)'
        'estimate:Estimate run cost from run history (--json, --model, --provider)'
        'kpis:Key performance indicators'
        'stats:Session statistics'
        'preview:Open the running app preview'
        'deploy:Advisory deploy command (print-only)'
        'docker:Run Loki in a Docker container'
        'mcp:MCP server commands'
        'merge:Green-only serial merge queue'
        'acp:Agent Client Protocol agent over stdio'
        'magic:Spec-driven component generation'
        'assets:Export/import shareable team assets'
        'spec:Living spec drift detection'
        'intent:Does the spec still say what was actually wanted'
        'verify:Deterministic PR verification'
        'keys:Export the receipt-signing public key'
        'grill:Interrogate a spec before building'
        'trust:Visible trust trajectory'
        'trust-metrics:Trust metrics report'
        'why:Explain the last build outcome'
        'heal:Legacy system healing'
        'modernize:Modernize a legacy system'
        'migrate:Migration commands'
        'analyze:Analyze a codebase'
        'compliance:Compliance reporting'
        'crash:Crash report management'
        'otel:OpenTelemetry management'
        'wiki:Wiki commands'
        'answer:Start a follow-up run from a BLOCKED run with your answer'
        'verify-pr:Verify a PR against its linked issue in a sandbox'
        'queue:Overnight issue queue with a morning digest'
        'issues:Run every open issue in a repo and open PRs'
        'undo:Show what undoing a run would do (read-only plan; --dry-run adds the diffstat; --list shows recent runs)'
        'chat:Interactive chat session (run, attach)'
        'route:Print the engine, provider and model route without running'
        'edit:Make a scoped edit to files'
        'setup:First-run wizard for tools, provider, model route and spend cap'
        'models:List models and routes (--local for local models)'
        'agents:List, scaffold, show and export agent definitions'
        'diff:Show what the last run changed'
        'control:Control plane (preview, LOKI_CONTROL=1)'
        'workspace:Multi-project workspaces (preview, LOKI_WORKSPACES=1)'
        'backlog:Run every matching open issue, N in parallel'
        'explain:Explain Loki concepts'
        'optimize:Optimization commands'
        'review:Code review commands'
        'export:Export session data'
        'test:Run tests'
        'ci:CI helpers'
        'watch:Watch mode'
        'audit:Audit commands'
        'syslog:System log commands'
        'cluster:Cluster commands'
        'failover:Failover commands'
        'remote:Remote execution commands'
        'worktree:Git worktree commands'
        'wt:Git worktree commands (alias)'
        'trigger:Trigger commands'
        'cleanup:Clean up Loki state'
        'rollback:Roll back a change'
        'update:Update Loki Mode'
        'self-update:Update Loki Mode'
        'setup-skill:Set up the Claude Code skill'
        'quickstart:Quickstart guide'
        'sentrux:Sentrux integration'
        'state:Inspect run state'
        'template:PRD template commands'
        'ultracode:Ultra code review'
        'voice:Voice commands'
        'bench:Run benchmarks'
        'open:Open a project resource'
        'rc:Release candidate commands'
        'version:Show version (--json for machine-readable)'
        'completions:Output shell completions'
        'help:Show help'
    )
    _describe -t commands 'loki command' commands
}

function _loki_start {
    # Rule: list every flag bin/loki routes (Bun/engine10 ones such as --model, --max-cost, --spec, --no-pr too), not only cmd_start's own.
    _arguments \
        '--provider[AI provider]:provider name:(claude cline codex aider opencode)' \
        '--parallel[Parallel mode]' \
        '--brief[Zero-config brief mode]:brief text:' \
        '--worktree[Git worktree isolation]' \
        '--pr[Worktree plus auto-create PR]' \
        '--ship[Worktree plus PR plus auto-merge]' \
        '--detach[Run in background (implies --worktree)]' \
        '--workspace[Run a loki.yaml workspace for the brief]:workspace name:' \
        '--deploy[Deploy after a VERIFIED run via loki deploy --execute]' \
        '--health-url[With --deploy: health probe URL]:url:' \
        '--auto-rollback[With --deploy: roll back on a failed health probe]' \
        '--destination[With --deploy: preview, staging or production]:destination:(preview staging production)' \
        '--canary[With --deploy: canary rollout]' \
        '--domain[With --deploy: attach this domain and prove TLS]:hostname:' \
        '--env-file[With --deploy: env file pushed to the provider]:file:_files' \
        '--background[Background mode]' \
        '--bg[Background mode]' \
        '--simple[Force simple complexity]' \
        '--complex[Force complex complexity]' \
        '--github[Enable GitHub issue import]' \
        '--no-dashboard[Disable web dashboard]' \
        '--sandbox[Run in Docker sandbox]' \
        '--skip-memory[Skip loading memory context]' \
        '--spec[Run against an edited spec file]:spec file:_files' \
        '--spec-first[Write an editable spec, then stop]' \
        '--yes[Skip confirmation prompts]' \
        '-y[Skip confirmation prompts]' \
        '--budget[Cost budget limit in USD]:amount:' \
        '--cost[Opt-in cost profile]:profile:(lean off)' \
        '--model[Model or route override]:model:' \
        '--max-cost[Spend cap in USD]:amount:' \
        '--no-pr[Build and verify without opening a pull request]' \
        '--explain-route[Print the route without running]' \
        '--max-iterations[Max iterations]:number:' \
        '--attempts[Independent attempts in worktrees, 1-5]:number:(1 2 3 4 5)' \
        '*:spec file:_loki_spec_files'
}

# Bias spec completion toward the file shapes Loki accepts (.md/.json/.txt/
# .yaml/.yml), while still offering directories so the user can navigate into a
# subfolder. Mirrors the bash completion. Makes the most-common command
# tab-driven and typo-proof, cutting "PRD file not found" mistakes.
function _loki_spec_files {
    _alternative \
        'specs:spec file:_files -g "*.(md|json|txt|yaml|yml)"' \
        'dirs:directory:_files -/'
}

function _loki_council {
    local -a council_cmds
    council_cmds=(
        'status:Council status'
        'verdicts:Show verdicts'
        'convergence:Check convergence'
        'force-review:Force a manual review'
        'report:Generate report'
        'config:Council configuration'
        'help:Council help'
    )
    _describe -t council_cmds 'council subcommand' council_cmds
}

function _loki_compound {
    local -a cmds
    cmds=(
        'list:List solutions by category'
        'show:Show solutions in a category'
        'search:Search across solutions'
        'run:Trigger compounding manually'
        'stats:Show solution statistics'
        'help:Compound help'
    )
    _describe -t cmds 'compound subcommand' cmds
}

function _loki_provider {
    local -a cmds
    cmds=(
        'show:Display current provider'
        'set:Set default provider'
        'list:List available providers (--json: name, tier, installed, version)'
        'info:Get provider information (--json: capability contract)'
        'matrix:Show the capability matrix'
        'help:Provider help'
    )
    _describe -t cmds 'provider subcommand' cmds
}

function _loki_plan {
    _arguments \
        '--json[Machine-readable JSON output]' \
        '--verbose[Detailed per-iteration breakdown]' \
        '--spec[Write editable acceptance criteria to .loki/specs/<slug>.md]' \
        '--requirements[Print the last run requirement-to-check map (read-only)]' \
        '*:prd file:_files'
}

function _loki_memory {
    local -a cmds
    cmds=(
        'list:List all learnings'
        'show:Display specific type'
        'search:Search learnings'
        'stats:Show statistics'
        'export:Export learnings'
        'clear:Clear learnings'
        'dedupe:Remove duplicates'
        'index:Memory index'
        'timeline:Memory timeline'
        'consolidate:Consolidate memory'
        'economics:Token economics'
        'retrieve:Retrieve relevant memory'
        'episode:Manage episodes'
        'pattern:Manage patterns'
        'skill:Manage skills'
        'vectors:Vector search'
        'lessons:List PR lessons (--json)'
        'learn:Learn from a merged PR'
        'forget:Delete a PR lesson'
        'help:Memory help'
    )
    _describe -t cmds 'memory subcommand' cmds
}

function _loki_config {
    local -a cmds
    cmds=(
        'show:Display current config'
        'init:Initialize config file'
        'edit:Edit in default editor'
        'path:Show config file path'
        'help:Config help'
    )
    _describe -t cmds 'config subcommand' cmds
}

function _loki_dashboard {
    local -a cmds
    cmds=(
        'start:Start dashboard server'
        'stop:Stop dashboard server'
        'status:Get dashboard status'
        'url:Get dashboard URL'
        'open:Open dashboard in browser'
        'help:Dashboard help'
    )
    _describe -t cmds 'dashboard subcommand' cmds
}

function _loki_sandbox {
    local -a cmds
    cmds=(
        'start:Start sandbox container'
        'stop:Stop sandbox'
        'status:Check status'
        'logs:View logs'
        'shell:Open interactive shell'
        'build:Build sandbox image'
        'help:Sandbox help'
    )
    _describe -t cmds 'sandbox subcommand' cmds
}

function _loki_notify {
    local -a cmds
    cmds=(
        'test:Test all channels'
        'slack:Send to Slack'
        'discord:Send to Discord'
        'webhook:Send to webhook'
        'status:Show configuration'
        'help:Notify help'
    )
    _describe -t cmds 'notify subcommand' cmds
}

function _loki_enterprise {
    local -a cmds
    cmds=(
        'status:Show enterprise status'
        'token:Manage API tokens'
        'audit:Audit log commands'
        'help:Enterprise help'
    )
    _describe -t cmds 'enterprise subcommand' cmds
}

function _loki_projects {
    local -a cmds
    cmds=(
        'list:List registered projects'
        'show:Show project details'
        'register:Register new project'
        'add:Alias for register'
        'remove:Unregister a project'
        'discover:Auto-discover projects'
        'sync:Sync project data'
        'health:Check project health'
        'help:Projects help'
    )
    _describe -t cmds 'projects subcommand' cmds
}

function _loki_telemetry {
    local -a cmds
    cmds=(
        'status:Show telemetry config'
        'enable:Enable OTEL'
        'disable:Disable OTEL for current project'
        'stop:Permanently opt out across all sessions'
        'start:Remove persistent opt-out'
        'help:Telemetry help'
    )
    _describe -t cmds 'telemetry subcommand' cmds
}

function _loki_agent {
    local -a cmds
    cmds=(
        'list:List agent types'
        'info:Show agent type details'
        'run:Run agent with prompt'
        'start:Start agent in background'
        'help:Agent help'
    )
    _describe -t cmds 'agent subcommand' cmds
}

function _loki_reset {
    local -a cmds
    cmds=(
        'all:Reset all state'
        'retries:Reset retry counter'
        'failed:Clear failed task queue'
        'help:Reset help'
    )
    _describe -t cmds 'reset subcommand' cmds
}

function _loki_issue {
    _arguments \
        '--repo[Specify repository]:repo:' \
        '--start[Start after generating PRD]' \
        '--dry-run[Preview without saving]' \
        '--output[Custom output path]:file:_files' \
        '1:subcommand:(parse view)'
}

function _loki_context {
    local -a cmds
    cmds=(
        'show:Show context window usage breakdown'
        'files:List files in context with token estimates'
        'tools:Show tool token usage per origin'
        'add:Add file to context'
        'clear:Clear accumulated context'
        'help:Context help'
    )
    _describe -t cmds 'context subcommand' cmds

    case $line[1] in
        add)
            _files
            ;;
    esac
}

function _loki_code {
    local -a cmds
    cmds=(
        'overview:Generate workspace overview'
        'symbols:Search for symbols'
        'deps:Show dependency graph'
        'hotspots:Find code hotspots'
        'diff:Show colored diff'
        'help:Code help'
    )
    _describe -t cmds 'code subcommand' cmds

    case $line[1] in
        overview)
            _arguments \
                '--silent[Compact output]' \
                '*:directory:_directories'
            ;;
        deps)
            _files
            ;;
        hotspots)
            _arguments \
                '--top[Number of results]:number:'
            ;;
        symbols)
            ;;
    esac
}

_loki "$@"
