# VM Improver
# Analyzes inspection reports and proposes improvements to the OpenProse VM
#
# Usage:
#   prose run @openprose/lib/vm-improver
#
# Inputs:
#   inspection_path: Path to inspection binding (e.g., .prose/runs/.../bindings/inspection.md)
#   prose_repo: Path to prose submodule (default: current project's prose/)
#
# Output: One or more PRs to the prose repo, or proposals if no git access

input inspection_path: "Path to inspection output (bindings/inspection.md)"
input prose_repo: "Path to prose skill directory (e.g., prose/skills/open-prose)"

# ============================================================
# Agents
# ============================================================

agent analyst:
  model: opus
  prompt: """
    You analyze OpenProse inspection reports for VM improvement opportunities.

    Look for evidence of:
    - Execution inefficiencies (too many steps, redundant spawns)
    - Context bloat (VM passing full values instead of references)
    - State management issues (missing bindings, path errors)
    - Error handling gaps (uncaught failures, unclear errors)
    - Missing features that would help this class of program
    - Spec ambiguities that led to incorrect execution

    Be concrete. Reference specific inspection findings.
  """

agent researcher:
  model: sonnet
  prompt: """
    You explore the OpenProse VM codebase to understand how to fix issues.
    Read files, understand structure, find the right places to change.
  """

agent implementer:
  model: opus
  prompt: """
    You implement improvements to the OpenProse VM.

    Rules:
    - Follow existing style exactly
    - Make minimal, focused changes
    - One logical change per PR
    - Update all affected files (spec, state backends, etc.)
  """

agent pr_author:
  model: sonnet
  prompt: """
    You create branches and pull requests with clear descriptions.
    Explain the problem, the solution, and how to test it.
  """

# ============================================================
# Phase 1: Analyze Inspection for VM Issues
# ============================================================

let analysis = session: analyst
  prompt: """
    Read the inspection report and identify VM improvement opportunities.

    Inspection: {inspection_path}

    For each opportunity, specify:
    - category: efficiency | context | state | error | feature | spec
    - description: what's wrong
    - severity: low | medium | high
    - evidence: quote from inspection that shows this
    - hypothesis: what VM behavior likely caused this

    Return JSON:
    {
      "target_run": "run ID that was inspected",
      "opportunities": [...],
      "priority_order": [indices sorted by impact]
    }

    If the inspection shows clean execution with no issues, return empty opportunities.
  """
  context: inspection_path

if **no actionable opportunities found**:
  output result = {
    status: "no-improvements-needed",
    analysis: analysis,
    message: "Inspection showed clean VM execution"
  }

# ============================================================
# Phase 2: Research VM Codebase
# ============================================================

let research = session: researcher
  prompt: """
    For each opportunity, find the relevant VM code.

    Prose repo: {prose_repo}
    Opportunities: {analysis.opportunities}

    Key files to check:
    - prose.md (main VM spec)
    - state/filesystem.md, state/sqlite.md, state/postgres.md
    - primitives/session.md
    - compiler.md
    - SKILL.md

    Return JSON:
    {
      "findings": [
        {
          "opportunity_index": N,
          "relevant_files": ["path/to/file.md"],
          "current_behavior": "how it works now",
          "change_location": "specific section or line range"
        }
      ]
    }
  """
  context: { analysis, prose_repo }

# ============================================================
# Phase 3: User Selection
# ============================================================

input selection: """
  ## VM Improvement Opportunities

  Based on inspection of: {analysis.target_run}

  ### Opportunities Found:
  {analysis.opportunities}

  ### Research:
  {research.findings}

  ---

  Which improvements should I implement as PRs?
  - List by number (e.g., "1, 3")
  - Or "all" for everything
  - Or "none" to skip
"""

if **user selected none or wants to skip**:
  output result = {
    status: "skipped",
    analysis: analysis,
    research: research
  }

let selected = session "Parse selection"
  prompt: "Extract selected opportunity indices from user input"
  context: { selection, analysis }

# ============================================================
# Phase 4: Implement Changes
# ============================================================

let implementations = selected | map:
  session: implementer
    prompt: """
      Implement this VM improvement.

      Opportunity: {analysis.opportunities[item]}
      Research: {research.findings[item]}
      Prose repo: {prose_repo}

      1. Read the current file content
      2. Design the minimal change
      3. Write the improved content

      Return JSON:
      {
        "opportunity_index": N,
        "branch_name": "vm/short-description",
        "title": "PR title",
        "files": [
          {
            "path": "relative/path.md",
            "action": "modify",
            "description": "what changed"
          }
        ],
        "summary": "2-3 sentence explanation"
      }

      Actually write the changes to the files.
    """
    context: item
    permissions:
      read: ["{prose_repo}/**"]
      write: ["{prose_repo}/**"]

# ============================================================
# Phase 5: Create PRs
# ============================================================

let prs = implementations | map:
  session: pr_author
    prompt: """
      Create a PR for this VM improvement.

      Implementation: {item}
      Prose repo: {prose_repo}

      Steps:
      1. cd to prose repo
      2. Create branch: {item.branch_name}
      3. Stage changed files
      4. Commit with clear message
      5. Push branch
      6. Create PR via gh cli

      PR body should include:
      - Problem: what inspection revealed
      - Solution: what this changes
      - Testing: how to verify

      Return: { pr_url, branch, title }
    """
    context: item
    permissions:
      bash: allow

# ============================================================
# Output
# ============================================================

output result = {
  status: "complete",
  target_run: analysis.target_run,
  opportunities_found: analysis.opportunities,
  opportunities_implemented: implementations,
  prs_created: prs
}
