Skip to content

implement a "self-improvement cycle" for egg #153

Closed

Description

@jwbron

Implement a "Self-Improvement Cycle" for Egg

Problem Statement

Egg currently lacks systematic introspection capabilities. When running as a GitHub Action or in local containers, there's no automated mechanism to:

  • Detect errors and tool failures
  • Identify inefficient patterns in tool usage
  • Catch undesirable agent behaviors
  • Correlate issues across runs to find systemic problems
  • Automatically create issues for detected problems

This means issues go unnoticed until a human manually reviews logs or notices degraded performance.

Vision

A self-healing and self-improving system where egg:

  1. Monitors itself by analyzing GitHub Actions outputs and container logs
  2. Detects issues across multiple categories (errors, inefficiencies, behavior problems)
  3. Opens issues automatically for detected problems with actionable recommendations
  4. Tracks improvements to measure if fixes are effective
  5. Learns patterns to prevent recurring issues

Analysis of Existing Infrastructure

What We Already Have

Component Location Description
Structured Logging shared/egg_logging/ JSON logging with trace correlation (trace_id, span_id, task_id)
Container Log Persistence sandbox/egg_lib/container_logging.py Saves logs to ~/.cache/egg/container-logs/, maintains correlation index
Log Index log-index.json Maps task_id → container_id, thread_ts → task_id
GitHub Workflows .github/workflows/ on-mention.yml, on-pull-request.yml, test.yml
Metrics Command sandbox/.claude/commands/show-metrics.md Basic /show-metrics slash command for activity reports
GHA Log Capture action/entrypoint.sh Pipes container output to tee and writes to GITHUB_STEP_SUMMARY

Key Insight: Exec-Based Analysis Architecture

From the ADR, egg already uses an event-driven analysis pattern:

Host service syncs/triggers → egg --exec spawns ephemeral container
→ Analysis script + claude --print → Generates notifications
→ Container auto-removed

This same pattern can be applied to self-improvement analysis.


Proposed Solution: Nightly Self-Improvement Analyzer

Log Collection Strategy: Unified Abstraction

We'll use a unified log collector that works in both environments:

Environment Primary Source How It Works
GitHub Actions GHA workflow logs via gh api Fetches /repos/{owner}/{repo}/actions/runs/{run_id}/logs
Local (egg --exec) Container logs via container_logging.py Reads from ~/.cache/egg/container-logs/ and log-index.json

Benefits:

  • GHA-first: Simplifies collection in CI — logs are already available via API, retention handled by GitHub
  • Local support preserved: Developers running egg --exec locally still get log persistence and can run self-improvement analysis manually
  • Single analysis engine: Same detection rules and analysis code works on both sources
  • Unified output format: Both collectors produce the same structured format for the analysis engine

Implementation:

# sandbox/egg-tasks/self-improvement/collectors/base.py
class LogCollector(ABC):
    @abstractmethod
    def collect(self, since: datetime) -> list[RunLog]:
        """Collect logs since the given timestamp."""
        pass

# sandbox/egg-tasks/self-improvement/collectors/gha.py
class GHALogCollector(LogCollector):
    """Collects logs from GitHub Actions via gh api."""
    
# sandbox/egg-tasks/self-improvement/collectors/local.py  
class LocalLogCollector(LogCollector):
    """Collects logs from local container log persistence."""

Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                     Self-Improvement Cycle (Nightly)                     │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                         Log Collection Layer                             │
│  ┌─────────────────────────┐      ┌─────────────────────────┐          │
│  │  GHA Log Collector      │      │  Local Log Collector    │          │
│  │  (gh api)               │      │  (container_logging.py) │          │
│  └───────────┬─────────────┘      └───────────┬─────────────┘          │
│              └────────────────┬───────────────┘                         │
│                               ▼                                         │
│              ┌────────────────────────────────┐                         │
│              │  Unified RunLog Format         │                         │
│              └────────────────────────────────┘                         │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
         ┌──────────────────────────┼──────────────────────────┐
         │                          │                          │
         ▼                          ▼                          ▼
┌─────────────────┐      ┌─────────────────┐      ┌─────────────────┐
│  Error          │      │  Inefficiency   │      │  Behavior       │
│  Detection      │      │  Detection      │      │  Detection      │
└────────┬────────┘      └────────┬────────┘      └────────┬────────┘
         │                        │                        │
         └────────────────────────┴────────────────────────┘
                                  │
                                  ▼
┌──────────────────────────────────────────────────────────────────────┐
│                         Output Actions                                │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌───────────┐│
│  │ Create       │  │ Update       │  │ Send Slack   │  │ Track     ││
│  │ GitHub Issue │  │ Metrics JSON │  │ Notification │  │ Trends    ││
│  └──────────────┘  └──────────────┘  └──────────────┘  └───────────┘│
└──────────────────────────────────────────────────────────────────────┘

Components

1. Unified Log Collector

Base Interface (sandbox/egg-tasks/self-improvement/collectors/base.py)

@dataclass
class RunLog:
    """Unified log format for analysis."""
    run_id: str                    # GHA run ID or container ID
    source: Literal["gha", "local"]
    started_at: datetime
    completed_at: datetime | None
    status: Literal["success", "failure", "cancelled", "running"]
    trigger: str                   # e.g., "issue_comment", "pull_request", "exec"
    logs: str                      # Raw log content
    metadata: dict                 # Additional context (PR number, task_id, etc.)

GHA Collector (sandbox/egg-tasks/self-improvement/collectors/gha.py)

  • Uses gh api to fetch recent workflow runs
  • Downloads log archives and extracts content
  • Parses ::error:: and ::warning:: annotations

Local Collector (sandbox/egg-tasks/self-improvement/collectors/local.py)

  • Reads from log-index.json for recent entries
  • Loads corresponding .log files from ~/.cache/egg/container-logs/
  • Parses structured JSON logs for tool calls, errors, timings

PR History Collector (sandbox/egg-tasks/self-improvement/collectors/prs.py)

  • Fetches PRs created/reviewed by egg via gh api
  • Tracks review cycles, feedback patterns, merge rates

2. Analysis Categories

Each category should have dedicated detection logic:

Category What to Detect Signals Severity
Environment Errors Tool failures, sidecar issues, gateway errors Exit codes, error logs, connection failures HIGH
Excessive Iteration Too many PR feedback cycles, repeated attempts PR comment counts, push frequency, repeated errors MEDIUM
Tool Inefficiencies Wasted tokens, redundant calls, failed searches Token counts, duplicate tool calls, empty results LOW-MEDIUM
Bad Behavior Lazy responses, skipping plans, workarounds Short responses, missing steps, rule violations MEDIUM
Performance Issues Slow responses, timeouts, resource exhaustion Duration metrics, timeout errors, memory warnings MEDIUM

3. Detection Rules

Error Detection Rules:

environment_errors:
  - pattern: "gateway.*connection refused"
    severity: HIGH
    issue_title: "Gateway sidecar connection failures detected"
    
  - pattern: "docker.*permission denied"
    severity: HIGH
    issue_title: "Docker permission issues in container"
    
  - pattern: "gh.*authentication.*failed"
    severity: HIGH
    issue_title: "GitHub authentication failures"

tool_failures:
  - pattern: "Read tool.*file not found"
    threshold: 3  # per run
    severity: MEDIUM
    issue_title: "Excessive file read failures"
    
  - pattern: "Bash.*exit code [1-9]"
    threshold: 5
    severity: MEDIUM
    issue_title: "Frequent bash command failures"

Inefficiency Detection Rules:

token_waste:
  - condition: "duplicate_tool_calls > 3"
    severity: LOW
    issue_title: "Duplicate tool calls detected"
    
  - condition: "empty_search_results > 5"
    severity: LOW
    issue_title: "Inefficient search patterns"
    
  - condition: "context_exceeded_retries > 2"
    severity: MEDIUM
    issue_title: "Context window management issues"

excessive_iteration:
  - condition: "pr_review_cycles > 4"
    severity: MEDIUM
    issue_title: "PR requiring too many review cycles"
    
  - condition: "same_error_repeated > 3"
    severity: MEDIUM
    issue_title: "Repeated failures on same issue"

Behavior Detection Rules:

quality_issues:
  - pattern: "TODO|FIXME|skip.*for now"
    in: "agent_responses"
    severity: LOW
    issue_title: "Agent deferring work inappropriately"
    
  - condition: "response_length < 100 AND task_complexity > medium"
    severity: MEDIUM
    issue_title: "Potentially lazy response to complex task"
    
  - pattern: "I cannot|I'm unable|I don't have access"
    threshold: 3
    severity: LOW
    issue_title: "Agent capability limitations hit frequently"

rule_violations:
  - pattern: "Co-Authored-By: Claude"
    severity: LOW
    issue_title: "Commit attribution rules violated"
    
  - pattern: "git push.*--force"
    severity: HIGH
    issue_title: "Force push attempted"

4. Automated Issue Creation

When issues are detected, automatically create GitHub issues using:

gh issue create \
  --title "[Self-Improvement] {issue_title}" \
  --body "{detailed_analysis}" \
  --label "self-improvement,automated,{severity}"

Issue Body Template:

## Summary
{one_line_summary}

## Detection Details
- **Category:** {category}
- **Severity:** {severity}
- **Detected:** {timestamp}
- **Frequency:** {occurrence_count} times in last {time_period}

## Evidence
{log_excerpts_or_links}

## Recommended Actions
{claude_generated_recommendations}

## Related Runs
{links_to_github_action_runs}

---
*This issue was automatically created by the egg self-improvement analyzer.*

Deduplication Strategy:

  • Before creating an issue, search for open issues with [Self-Improvement] prefix and similar title
  • If found, update existing issue with new occurrence count and latest evidence
  • Only create new issue if no matching open issue exists

5. Metrics & Trending (JSON in Repo)

Metrics are stored as a JSON file in the repository for simplicity and version history:

Location: metrics/self-improvement-metrics.json

Structure:

{
  "last_updated": "2026-02-06T02:00:00Z",
  "daily_metrics": [
    {
      "date": "2026-02-06",
      "source": "gha",
      "metrics": {
        "total_runs": 45,
        "successful_runs": 42,
        "failed_runs": 3,
        "avg_duration_seconds": 180,
        "tool_calls": {
          "total": 1250,
          "failed": 45,
          "duplicate": 12
        },
        "prs": {
          "created": 8,
          "merged": 6,
          "avg_review_cycles": 1.5
        },
        "issues_detected": {
          "high": 0,
          "medium": 2,
          "low": 5
        }
      }
    }
  ],
  "weekly_summary": {
    "week_of": "2026-02-03",
    "improvement_velocity": {
      "issue_count_delta": -3,
      "success_rate_delta": 0.05
    }
  }
}

Benefits of JSON in repo:

  • Version controlled — can see how metrics change over time
  • No external dependencies — works in all environments
  • Easy to read and update programmatically
  • Can be visualized with simple tooling

Implementation Plan (Single Phased Effort)

Phase 1: Foundation

Deliverables:

  1. Unified Log Collector Framework

    • Base LogCollector abstract class with RunLog dataclass
    • GHALogCollector implementation using gh api
    • LocalLogCollector implementation using existing container_logging.py
    • Both produce identical RunLog format
  2. Basic Analysis Runner

    • Main script that instantiates appropriate collector based on environment
    • Parses logs and produces structured output
    • Works both in GHA and locally via egg --exec
  3. Nightly Workflow

    • GitHub Action on schedule (2 AM UTC)
    • Runs data collection and outputs summary
    • Posts summary to GITHUB_STEP_SUMMARY

Files to Create:

sandbox/egg-tasks/self-improvement/
├── __init__.py
├── analyze.py                    # Main analysis orchestrator
├── collectors/
│   ├── __init__.py
│   ├── base.py                   # LogCollector ABC, RunLog dataclass
│   ├── gha.py                    # GitHub Actions log collector
│   ├── local.py                  # Local container log collector
│   └── prs.py                    # PR history collector
└── rules/
    └── (empty, to be added in Phase 2)

.github/workflows/
└── self-improvement.yml          # Nightly analysis workflow

metrics/
└── self-improvement-metrics.json # Metrics storage (initially empty array)

Phase 2: Detection Engine

Deliverables:

  1. Rule-Based Detection

    • YAML rule definitions for each category
    • Pattern matching on logs
    • Threshold-based alerts
  2. Claude-Powered Analysis

    • Send collected data to Claude for deeper analysis
    • Generate actionable recommendations
    • Identify patterns humans might miss
  3. Issue Creation

    • Auto-create GitHub issues for detected problems
    • Proper labeling and categorization
    • Deduplication (search before create, update existing)

Files to Create/Update:

sandbox/egg-tasks/self-improvement/
├── detect.py                     # Detection engine
├── issue_creator.py              # GitHub issue creation with dedup
├── rules/
│   ├── errors.yaml               # Error detection rules
│   ├── inefficiency.yaml         # Inefficiency rules
│   └── behavior.yaml             # Behavior rules

Phase 3: Metrics & Improvement Tracking

Deliverables:

  1. Metrics Collection & Storage

    • Daily metrics written to metrics/self-improvement-metrics.json
    • Auto-commit metrics updates via the nightly workflow
    • Historical trend data preserved in git history
  2. Weekly Summary Report

    • Markdown summary posted to configured location (Slack or issue)
    • Trend visualization (improvement velocity)
    • Highlights of resolved vs new issues
  3. Feedback Loop

    • Track if created issues get resolved
    • Measure if fixes reduce issue recurrence
    • Adjust detection thresholds based on noise (false positive tracking)

Phase 4: Advanced Analysis

Deliverables:

  1. Cross-Run Correlation

    • Identify systemic issues across multiple runs
    • Cluster similar failures
    • Root cause analysis
  2. Predictive Detection

    • Learn patterns that predict failures
    • Proactive warnings before issues occur
    • Resource optimization recommendations
  3. Self-Healing Actions

    • Automatic fixes for known issues (e.g., retry transient failures)
    • Configuration adjustments
    • Rule updates based on learnings

Success Criteria

Metric Target Measurement
Issue Detection Rate >80% of real issues caught Manual review of missed issues
False Positive Rate <20% of created issues Track closed-as-not-an-issue
Mean Time to Detection <24 hours Time from occurrence to issue creation
Resolution Rate >70% of auto-created issues fixed Track issue closures
Improvement Velocity Decreasing issue counts over time Weekly metric comparison

Security Considerations

  1. Log Sanitization: Remove sensitive data (tokens, keys) before analysis
  2. Issue Content: Don't include raw logs in public issues — link to run instead
  3. API Rate Limits: Respect GitHub API limits in data collection
  4. Token Scope: Ensure analysis has minimal required permissions

Dependencies

  • Existing Infrastructure: Leverages container_logging.py, structured logging, GHA log capture
  • GitHub API Access: Requires workflow permissions for issue creation
  • Claude API: For intelligent analysis (already available)
  • Storage: Metrics stored in metrics/self-improvement-metrics.json

Key Decisions Made

Question Decision Rationale
Container log persistence Keep for local compatibility Developers running egg --exec locally need log persistence; GHA runs use gh api instead
Metrics storage JSON file in repo (metrics/self-improvement-metrics.json) Simple, version-controlled, no external dependencies
Implementation approach Single phased effort Coherent feature with clear phase boundaries; allows incremental delivery while maintaining focus

References

Activity

  1. jwbron commented on Feb 6, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box let's flesh this issue out a bit more. Update it to be more comprehensive, putting together an analysis and basic plan of how we can accomplish this.

  2. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    I've updated the issue with a comprehensive analysis and implementation plan for the self-improvement cycle.

    Summary of Changes

    The issue now includes:

    1. Analysis of Existing Infrastructure

    Documented what we already have that can be leveraged:

    • Structured logging with trace correlation
    • Container log persistence and indexing
    • GitHub workflow infrastructure
    • Existing analyzer patterns from the ADR

    2. Proposed Architecture

    A nightly self-improvement analyzer with:

    • Data Collection Layer: Collectors for GitHub Actions, container logs, and PR history
    • Analysis Engine: Detection for errors, inefficiencies, behavior issues, and patterns
    • Output Actions: Auto-create issues, track metrics, send notifications

    3. Detection Categories

    Detailed rules for catching:

    • Environment errors (gateway failures, Docker issues, auth problems)
    • Excessive iteration (too many PR cycles, repeated failures)
    • Tool inefficiencies (wasted tokens, duplicate calls)
    • Bad behavior (lazy responses, rule violations)

    4. Implementation Plan

    Four-phase approach:

    1. Week 1-2: Foundation (collectors, basic workflow)
    2. Week 2-3: Detection engine (rules, Claude analysis, issue creation)
    3. Week 3-4: Metrics & tracking (dashboards, improvement velocity)
    4. Week 4+: Advanced analysis (cross-run correlation, predictive detection)

    5. Success Criteria & Open Questions

    Clear metrics for measuring success, plus key decisions that need input.

    The plan leverages the existing exec-based analysis pattern from the ADR, so it fits naturally into the current architecture.

    — Authored by egg

  3. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  4. jwbron commented on Feb 6, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box review this plan. One potential simplification is that we could just ensure all logs are output into the github actions jobs, so to collect logs we just need to collect gha logs.

  5. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    Plan Review: Self-Improvement Cycle

    I've reviewed the plan and the existing codebase. Here's my analysis:

    The Proposed Simplification: GHA-Only Log Collection

    Your suggestion is sound. Consolidating on GHA logs as the single source of truth would significantly simplify the architecture. Here's why this works:

    Current state:

    • Container logs are already captured via tee "$LOG_FILE" in action/entrypoint.sh:110-111
    • The full log is written to GITHUB_STEP_SUMMARY (truncated to 500KB)
    • Logs are structured JSON from egg_logging with trace/span IDs, task IDs, etc.

    What we'd need to enable GHA-only collection:

    1. Ensure GITHUB_STEP_SUMMARY captures full structured logs (or use artifacts for larger logs)
    2. Add ::error:: and ::warning:: annotations for surfacing issues in the GHA UI
    3. The existing gh api can fetch workflow run logs via GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs

    Benefits of this approach:

    • Single data source — No need to maintain separate container log persistence (~/.cache/egg/container-logs/)
    • Retention handled by GitHub — GHA logs are retained per org settings (default 90 days)
    • Already correlated — Each GHA run has run_id, job_id, triggering event context
    • API access — gh api provides structured access to runs, jobs, steps, annotations
    • Eliminates complexity — No need for log-index.json, Docker log capture, file locking logic

    Recommended Adjustments to the Plan

    Given this simplification, I'd revise the architecture:

    Phase 1 Changes

    Remove:

    • Container Log Collector (collect_logs.py) — not needed
    • log-index.json parsing — not needed

    Keep/Modify:

    • GitHub Actions Data Collector → primary data source
    • PR History Collector → still useful for review cycle analysis

    Add:

    • Emit structured metrics to GHA step summary in a parseable format (e.g., JSON block at end of run)
    • Add ::error:: / ::warning:: annotations in sandbox for automatic surfacing

    Simplified Data Flow

    ┌─────────────────────────────────────────────────────────────┐
    │              Nightly Self-Improvement Workflow               │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  Collect: gh api /repos/{owner}/{repo}/actions/runs        │
    │  - Filter to egg-triggered runs (last 24h)                  │
    │  - Fetch logs, annotations, job statuses                    │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  Analyze: Parse logs for patterns                           │
    │  - Error patterns (gateway failures, tool errors)           │
    │  - Inefficiency signals (duplicate calls, empty results)    │
    │  - Behavior issues (rule violations)                        │
    └─────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  Act: Create issues, update metrics                         │
    └─────────────────────────────────────────────────────────────┘
    

    Other Plan Observations

    Strengths:

    • Detection categories are well-defined (errors, inefficiencies, behavior, patterns)
    • Issue templating is good
    • Phased rollout is sensible

    Areas to clarify:

    1. Metrics storage — Where do historical metrics live? Options:

      • A JSON file in the repo (metrics/daily-metrics.json)
      • GitHub wiki
      • A separate tracking issue that gets updated
    2. Self-referential analysis — The analyzer runs as egg. If egg is broken, can it analyze itself? Consider:

      • Graceful degradation if the analyzer run itself fails
      • Fallback notification (Slack) if issue creation fails
    3. Deduplication — How do we avoid creating duplicate issues for the same problem across runs? Suggest:

      • Search for open issues with [Self-Improvement] prefix + similar title before creating
      • Update existing issue with new occurrence count instead of creating duplicate
    4. Scope of first implementation — The detection rules are comprehensive but could be overwhelming. Suggest starting with:

      • HIGH severity errors only (gateway failures, auth issues)
      • One inefficiency pattern (excessive PR cycles)
      • Build out detection rules iteratively based on what we find

    Questions for @jwbron

    1. Container log persistence — Can we deprecate container_logging.py entirely once GHA-only is working? It's only useful for local egg --exec runs currently.

    2. Metrics storage preference — JSON file in repo vs. separate mechanism?

    3. Priority — Should this be tackled as a single effort, or broken into smaller issues (e.g., "Add GHA annotations for errors", "Create nightly analyzer workflow", "Add automated issue creation")?


    — Authored by egg

  6. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  7. jwbron commented on Feb 6, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box

    1. we need to keep some compatibility with running this locally. Your call on whether it's useful for that
    2. let's just keep this as a json in repo for now
    3. this should be a single but phased effort

    Address the feedback in the above comment.

  8. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    Issue Updated: Addressing Feedback

    I've updated the issue to address the feedback:

    1. Local Compatibility (Keep container log persistence)

    Decision: Keep container_logging.py for local runs.

    The plan now uses a unified log collector abstraction with two implementations:

    • GHALogCollector — Uses gh api to fetch workflow run logs (primary for CI)
    • LocalLogCollector — Uses existing container_logging.py and log-index.json (for egg --exec runs)

    Both collectors produce the same RunLog format, so the analysis engine works identically on either source. This means:

    • Developers can run self-improvement analysis locally on their egg --exec history
    • GHA runs get the simplicity of API-based log collection
    • No code duplication — same detection rules, same analysis logic

    2. Metrics Storage (JSON in repo)

    Decision: Store metrics in metrics/self-improvement-metrics.json

    Benefits:

    • Version controlled — git history shows metric trends over time
    • No external dependencies — works in all environments
    • Simple to update and read programmatically
    • Nightly workflow can auto-commit metric updates

    3. Single Phased Effort

    Decision: Keep as one issue with clear phase boundaries.

    The implementation plan now has four phases:

    1. Foundation — Unified collectors, basic runner, nightly workflow
    2. Detection Engine — YAML rules, Claude analysis, issue creation with dedup
    3. Metrics & Tracking — Metrics storage, weekly reports, feedback loop
    4. Advanced Analysis — Cross-run correlation, predictive detection, self-healing

    This allows incremental delivery while keeping the effort focused as a single cohesive feature.


    — Authored by egg

  9. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  10. jwbron commented on Feb 6, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box go ahead and put together a plan of action for this. Add it here if you can, or open a PR.

  11. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    Implementation Plan: Self-Improvement Cycle

    Based on the issue discussion and codebase analysis, here's a detailed implementation plan with specific deliverables for each phase.


    Phase 1: Foundation (Week 1-2)

    1.1 Create Self-Improvement Module Structure

    Location: sandbox/egg-tasks/self-improvement/

    sandbox/egg-tasks/self-improvement/
    ├── __init__.py
    ├── analyze.py                    # Main orchestrator
    ├── collectors/
    │   ├── __init__.py
    │   ├── base.py                   # LogCollector ABC, RunLog dataclass
    │   ├── gha.py                    # GitHub Actions log collector
    │   ├── local.py                  # Local container log collector
    │   └── prs.py                    # PR history collector
    ├── rules/
    │   └── __init__.py               # Empty, populated in Phase 2
    └── config.py                     # Configuration constants
    

    1.2 Implement Unified Log Collector

    File: collectors/base.py

    from abc import ABC, abstractmethod
    from dataclasses import dataclass, field
    from datetime import datetime
    from typing import Literal
    
    @dataclass
    class RunLog:
        """Unified log format for analysis."""
        run_id: str
        source: Literal["gha", "local"]
        started_at: datetime
        completed_at: datetime | None
        status: Literal["success", "failure", "cancelled", "running"]
        trigger: str
        logs: str
        metadata: dict = field(default_factory=dict)
    
    class LogCollector(ABC):
        @abstractmethod
        def collect(self, since: datetime) -> list[RunLog]:
            """Collect logs since the given timestamp."""
            pass

    File: collectors/gha.py

    • Uses subprocess to call gh api /repos/{owner}/{repo}/actions/runs
    • Filters to egg-triggered runs (on-mention.yml, on-pull-request.yml)
    • Downloads run logs via gh api .../runs/{id}/logs (returns zip)
    • Extracts and parses log content
    • Detects ::error:: and ::warning:: annotations

    File: collectors/local.py

    • Reads from existing ~/.cache/egg/container-logs/log-index.json
    • Loads .log files referenced in the index
    • Parses structured JSON lines from egg_logging output
    • Falls back gracefully if no local logs exist

    1.3 Create Basic Analysis Runner

    File: analyze.py

    #!/usr/bin/env python3
    """Self-improvement analysis orchestrator."""
    
    import argparse
    from datetime import datetime, timedelta
    from collectors.gha import GHALogCollector
    from collectors.local import LocalLogCollector
    
    def main():
        parser = argparse.ArgumentParser()
        parser.add_argument("--source", choices=["gha", "local", "auto"], default="auto")
        parser.add_argument("--since-hours", type=int, default=24)
        parser.add_argument("--output", choices=["summary", "json"], default="summary")
        args = parser.parse_args()
        
        # Select collector based on environment
        if args.source == "auto":
            collector = GHALogCollector() if os.getenv("GITHUB_ACTIONS") else LocalLogCollector()
        elif args.source == "gha":
            collector = GHALogCollector()
        else:
            collector = LocalLogCollector()
        
        since = datetime.now() - timedelta(hours=args.since_hours)
        runs = collector.collect(since)
        
        # Basic analysis output
        print(f"Collected {len(runs)} runs since {since}")
        for run in runs:
            print(f"  - {run.run_id}: {run.status} ({run.trigger})")
    
    if __name__ == "__main__":
        main()

    1.4 Create Nightly Workflow

    File: .github/workflows/self-improvement.yml

    name: "egg: Self-Improvement Analysis"
    
    on:
      schedule:
        - cron: '0 2 * * *'  # 2 AM UTC daily
      workflow_dispatch:      # Manual trigger for testing
    
    jobs:
      analyze:
        name: Analyze egg runs
        runs-on: ubuntu-latest
        permissions:
          contents: write
          issues: write
          actions: read
    
        steps:
          - name: Checkout
            uses: actions/checkout@v4
            with:
              persist-credentials: true  # Needed for metrics commit
    
          - name: Generate bot token
            id: bot-token
            uses: actions/create-github-app-token@v1
            with:
              app-id: ${{ secrets.BOT_APP_ID }}
              private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }}
    
          - name: Set up Python
            uses: actions/setup-python@v5
            with:
              python-version: '3.11'
    
          - name: Run analysis
            env:
              GH_TOKEN: ${{ steps.bot-token.outputs.token }}
            run: |
              python sandbox/egg-tasks/self-improvement/analyze.py \
                --source gha \
                --since-hours 24 \
                --output summary
    
          - name: Write to step summary
            run: echo "Analysis complete" >> $GITHUB_STEP_SUMMARY

    1.5 Initialize Metrics Storage

    File: metrics/self-improvement-metrics.json

    {
      "schema_version": "1.0",
      "last_updated": null,
      "daily_metrics": [],
      "weekly_summary": null
    }

    Phase 1 Deliverables Checklist

    • sandbox/egg-tasks/self-improvement/ module structure
    • LogCollector ABC and RunLog dataclass
    • GHALogCollector implementation
    • LocalLogCollector implementation
    • Basic analyze.py runner
    • .github/workflows/self-improvement.yml
    • metrics/self-improvement-metrics.json initialized

    Phase 2: Detection Engine (Week 2-3)

    2.1 Create Detection Rule Engine

    File: detect.py

    """Detection engine for identifying issues in egg runs."""
    
    from dataclasses import dataclass
    from enum import Enum
    import re
    import yaml
    from collectors.base import RunLog
    
    class Severity(Enum):
        LOW = "low"
        MEDIUM = "medium"
        HIGH = "high"
    
    @dataclass
    class Detection:
        category: str
        severity: Severity
        title: str
        description: str
        evidence: list[str]
        run_ids: list[str]
        occurrence_count: int
    
    class DetectionEngine:
        def __init__(self, rules_dir: str = "rules/"):
            self.rules = self._load_rules(rules_dir)
        
        def analyze(self, runs: list[RunLog]) -> list[Detection]:
            detections = []
            for rule_set in self.rules:
                detections.extend(self._apply_rules(runs, rule_set))
            return self._deduplicate(detections)

    2.2 Create Rule Definition Files

    File: rules/errors.yaml

    category: environment_errors
    rules:
      - name: gateway_connection_failure
        pattern: "gateway.*connection refused|egg-gateway.*ECONNREFUSED"
        severity: HIGH
        title: "Gateway sidecar connection failures detected"
        recommendation: "Check gateway container health and network configuration"
    
      - name: github_auth_failure
        pattern: "gh.*401|authentication.*failed|Bad credentials"
        severity: HIGH
        title: "GitHub authentication failures"
        recommendation: "Verify bot token and app credentials"
    
      - name: docker_permission
        pattern: "docker.*permission denied|Cannot connect to the Docker daemon"
        severity: HIGH
        title: "Docker permission issues"
        recommendation: "Check Docker socket permissions in container"
    
      - name: tool_read_failures
        pattern: "Read tool.*file not found|No such file or directory"
        threshold: 3
        severity: MEDIUM
        title: "Excessive file read failures"
        recommendation: "Improve file path validation or codebase exploration"

    File: rules/inefficiency.yaml

    category: inefficiency
    rules:
      - name: excessive_pr_cycles
        type: metric
        condition: "pr_review_cycles > 4"
        severity: MEDIUM
        title: "PR requiring too many review cycles"
        recommendation: "Improve initial PR quality or clarify requirements upfront"
    
      - name: repeated_errors
        type: pattern_frequency
        pattern: "error|Error|ERROR"
        threshold: 10
        per_run: true
        severity: MEDIUM
        title: "High error rate in single run"
        recommendation: "Investigate root cause of repeated failures"

    File: rules/behavior.yaml

    category: behavior
    rules:
      - name: attribution_violation
        pattern: "Co-Authored-By: Claude|claude.ai/claude-code"
        severity: LOW
        title: "Commit attribution rules violated"
        recommendation: "Remove Claude attribution from commits per CLAUDE.md rules"
    
      - name: force_push_attempted
        pattern: "git push.*--force|push -f"
        severity: HIGH
        title: "Force push attempted"
        recommendation: "Force push is blocked by gateway; ensure egg uses safe git practices"
    
      - name: lazy_response
        type: response_analysis
        condition: "response_length < 100 AND task_has_code_changes"
        severity: MEDIUM
        title: "Potentially incomplete response to code task"
        recommendation: "Investigate if task was properly completed"

    2.3 Implement Issue Creator with Deduplication

    File: issue_creator.py

    """Creates GitHub issues for detected problems with deduplication."""
    
    import subprocess
    import json
    from detect import Detection, Severity
    
    LABEL_PREFIX = "self-improvement"
    TITLE_PREFIX = "[Self-Improvement]"
    
    def find_existing_issue(title: str, repo: str) -> int | None:
        """Search for open issues with matching title."""
        search_query = f"repo:{repo} is:issue is:open in:title {TITLE_PREFIX}"
        result = subprocess.run(
            ["gh", "issue", "list", "--search", search_query, "--json", "number,title"],
            capture_output=True, text=True
        )
        if result.returncode == 0:
            issues = json.loads(result.stdout)
            for issue in issues:
                if title in issue["title"]:
                    return issue["number"]
        return None
    
    def create_or_update_issue(detection: Detection, repo: str) -> str:
        """Create new issue or update existing one with new occurrence."""
        full_title = f"{TITLE_PREFIX} {detection.title}"
        existing = find_existing_issue(detection.title, repo)
        
        if existing:
            # Add comment to existing issue with new occurrence
            comment = f"**New occurrence detected** ({detection.occurrence_count} total)\n\n"
            comment += f"Run IDs: {', '.join(detection.run_ids[-5:])}\n\n"
            comment += "Evidence:\n```\n" + "\n".join(detection.evidence[-3:]) + "\n```"
            subprocess.run(["gh", "issue", "comment", str(existing), "--body", comment])
            return f"Updated issue #{existing}"
        else:
            # Create new issue
            body = create_issue_body(detection)
            labels = f"{LABEL_PREFIX},{LABEL_PREFIX}-{detection.severity.value},automated"
            result = subprocess.run(
                ["gh", "issue", "create", "--title", full_title, "--body", body, "--label", labels],
                capture_output=True, text=True
            )
            return result.stdout.strip()
    
    def create_issue_body(detection: Detection) -> str:
        return f"""## Summary
    {detection.description}
    
    ## Detection Details
    - **Category:** {detection.category}
    - **Severity:** {detection.severity.value.upper()}
    - **Occurrences:** {detection.occurrence_count}
    
    ## Evidence

    {chr(10).join(detection.evidence[:5])}

    
    ## Affected Runs
    {chr(10).join(f"- {rid}" for rid in detection.run_ids[:10])}
    
    ## Recommended Actions
    {detection.recommendation if hasattr(detection, 'recommendation') else 'Investigate and address the root cause.'}
    
    ---
    *This issue was automatically created by the egg self-improvement analyzer.*
    """
    

    2.4 Add Claude-Powered Analysis (Optional Enhancement)

    File: claude_analyzer.py

    """Use Claude to analyze patterns and generate recommendations."""
    
    def analyze_with_claude(runs: list[RunLog], detections: list[Detection]) -> str:
        """Send summary to Claude for deeper analysis."""
        prompt = f"""Analyze these egg agent run logs and detected issues.
    
    Runs analyzed: {len(runs)}
    Issues detected: {len(detections)}
    
    Detections:
    {format_detections(detections)}
    
    Sample log excerpts:
    {format_log_samples(runs)}
    
    Provide:
    1. Root cause analysis for the most critical issues
    2. Patterns you notice across runs
    3. Specific recommendations for improvement
    4. Any issues the automated detection may have missed
    """
        # Use claude CLI or API
        result = subprocess.run(
            ["claude", "--print", "-p", prompt],
            capture_output=True, text=True
        )
        return result.stdout

    Phase 2 Deliverables Checklist

    • DetectionEngine class with rule loading
    • rules/errors.yaml with error detection rules
    • rules/inefficiency.yaml with inefficiency rules
    • rules/behavior.yaml with behavior rules
    • issue_creator.py with deduplication
    • Update workflow to run detection and create issues
    • (Optional) claude_analyzer.py for AI-powered analysis

    Phase 3: Metrics & Tracking (Week 3-4)

    3.1 Implement Metrics Collection

    File: metrics.py

    """Metrics collection and storage."""
    
    import json
    from datetime import datetime, date
    from pathlib import Path
    from dataclasses import dataclass, asdict
    from collectors.base import RunLog
    from detect import Detection, Severity
    
    METRICS_FILE = Path("metrics/self-improvement-metrics.json")
    
    @dataclass
    class DailyMetrics:
        date: str
        source: str
        total_runs: int
        successful_runs: int
        failed_runs: int
        avg_duration_seconds: float
        tool_calls: dict
        prs: dict
        issues_detected: dict
    
    def collect_daily_metrics(runs: list[RunLog], detections: list[Detection]) -> DailyMetrics:
        """Aggregate metrics from runs."""
        successful = sum(1 for r in runs if r.status == "success")
        failed = sum(1 for r in runs if r.status == "failure")
        
        return DailyMetrics(
            date=date.today().isoformat(),
            source=runs[0].source if runs else "unknown",
            total_runs=len(runs),
            successful_runs=successful,
            failed_runs=failed,
            avg_duration_seconds=calculate_avg_duration(runs),
            tool_calls=extract_tool_metrics(runs),
            prs=extract_pr_metrics(runs),
            issues_detected={
                "high": sum(1 for d in detections if d.severity == Severity.HIGH),
                "medium": sum(1 for d in detections if d.severity == Severity.MEDIUM),
                "low": sum(1 for d in detections if d.severity == Severity.LOW),
            }
        )
    
    def save_metrics(metrics: DailyMetrics):
        """Append daily metrics to the JSON file."""
        data = json.loads(METRICS_FILE.read_text())
        data["daily_metrics"].append(asdict(metrics))
        data["last_updated"] = datetime.now().isoformat()
        
        # Keep last 90 days
        if len(data["daily_metrics"]) > 90:
            data["daily_metrics"] = data["daily_metrics"][-90:]
        
        METRICS_FILE.write_text(json.dumps(data, indent=2))

    3.2 Update Workflow to Commit Metrics

    Update .github/workflows/self-improvement.yml:

          - name: Run analysis and collect metrics
            env:
              GH_TOKEN: ${{ steps.bot-token.outputs.token }}
            run: |
              python sandbox/egg-tasks/self-improvement/analyze.py \
                --source gha \
                --since-hours 24 \
                --collect-metrics \
                --create-issues
    
          - name: Commit metrics update
            run: |
              git config user.name "egg"
              git config user.email "egg@localhost"
              git add metrics/self-improvement-metrics.json
              if git diff --cached --quiet; then
                echo "No metrics changes to commit"
              else
                git commit -m "Update self-improvement metrics for $(date +%Y-%m-%d)"
                git push
              fi

    3.3 Implement Weekly Summary Report

    File: weekly_report.py

    """Generate weekly summary reports."""
    
    def generate_weekly_report(metrics_file: Path) -> str:
        data = json.loads(metrics_file.read_text())
        week_metrics = data["daily_metrics"][-7:]
        
        total_runs = sum(m["total_runs"] for m in week_metrics)
        total_success = sum(m["successful_runs"] for m in week_metrics)
        success_rate = (total_success / total_runs * 100) if total_runs else 0
        
        issues_created = sum(
            m["issues_detected"]["high"] + m["issues_detected"]["medium"]
            for m in week_metrics
        )
        
        return f"""## Weekly Self-Improvement Report
    
    **Week of:** {week_metrics[0]["date"]} to {week_metrics[-1]["date"]}
    
    ### Summary
    | Metric | Value |
    |--------|-------|
    | Total runs | {total_runs} |
    | Success rate | {success_rate:.1f}% |
    | Issues detected | {issues_created} |
    
    ### Trends
    {calculate_trends(data)}
    
    ### Top Issues This Week
    {format_top_issues()}
    
    ---
    *Generated by egg self-improvement analyzer*
    """

    Phase 3 Deliverables Checklist

    • metrics.py with DailyMetrics collection
    • Auto-commit metrics in workflow
    • weekly_report.py for weekly summaries
    • Add weekly report posting (Slack or issue comment)
    • Track issue resolution rate

    Phase 4: Advanced Analysis (Week 4+)

    4.1 Cross-Run Correlation

    • Identify patterns that span multiple runs
    • Cluster similar failures to find systemic issues
    • Track which changes resolve recurring issues

    4.2 PR Feedback Analysis

    File: collectors/prs.py

    """Analyze PR history for patterns."""
    
    def collect_pr_history(since: datetime) -> list[PRInfo]:
        """Fetch PRs created by egg and analyze feedback patterns."""
        result = subprocess.run([
            "gh", "pr", "list",
            "--author", "james-in-a-box[bot]",
            "--state", "all",
            "--json", "number,title,state,reviews,comments,createdAt,mergedAt,closedAt"
        ], capture_output=True, text=True)
        
        prs = json.loads(result.stdout)
        return [
            PRInfo(
                number=pr["number"],
                review_cycles=count_review_cycles(pr),
                time_to_merge=calculate_time_to_merge(pr),
                feedback_themes=extract_feedback_themes(pr),
            )
            for pr in prs
            if parse_date(pr["createdAt"]) > since
        ]

    4.3 Improvement Velocity Tracking

    def calculate_improvement_velocity(metrics: list[DailyMetrics]) -> dict:
        """Calculate week-over-week improvement."""
        if len(metrics) < 14:
            return {"status": "insufficient_data"}
        
        this_week = metrics[-7:]
        last_week = metrics[-14:-7]
        
        return {
            "success_rate_delta": avg_success_rate(this_week) - avg_success_rate(last_week),
            "issue_count_delta": sum_issues(this_week) - sum_issues(last_week),
            "avg_duration_delta": avg_duration(this_week) - avg_duration(last_week),
            "trend": "improving" if all_positive([...]) else "needs_attention"
        }

    Phase 4 Deliverables Checklist

    • collectors/prs.py for PR analysis
    • Cross-run correlation analysis
    • Improvement velocity metrics
    • Feedback theme extraction
    • Self-healing suggestions

    Testing Strategy

    Unit Tests

    tests/sandbox/egg-tasks/self-improvement/
    ├── test_collectors.py      # Test log parsing and collection
    ├── test_detect.py          # Test rule matching and detection
    ├── test_issue_creator.py   # Test deduplication logic
    └── test_metrics.py         # Test metrics aggregation
    

    Integration Tests

    • Mock GHA API responses for collector testing
    • Test full analysis pipeline with sample logs
    • Verify issue creation/update logic

    Manual Testing

    • Run analysis locally with --source local
    • Trigger workflow manually via workflow_dispatch
    • Review created issues for quality

    Success Criteria

    Metric Target How to Measure
    Detection accuracy >80% real issues caught Manual review of missed issues
    False positive rate <20% Track issues closed as not-an-issue
    Time to detection <24 hours Timestamp comparison
    Issue resolution rate >70% Track issue closures
    Improvement velocity Decreasing issue counts Weekly metric comparison

    Implementation Order

    1. Start with Phase 1 — get basic collection and workflow running
    2. Phase 2 detection — start with HIGH severity rules only
    3. Phase 3 metrics — begin tracking once detection is stable
    4. Phase 4 advanced — build on top of working foundation

    Each phase should be a separate PR for easier review.

    — Authored by egg

  12. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    Summary

    I've added a comprehensive implementation plan for the self-improvement cycle above. The plan includes:

    Four Phased Approach

    Phase Timeline Focus
    Phase 1: Foundation Week 1-2 Unified log collectors, basic runner, nightly workflow
    Phase 2: Detection Week 2-3 YAML rule engine, issue creation with dedup, Claude analysis
    Phase 3: Metrics Week 3-4 Daily metrics, auto-commit, weekly reports
    Phase 4: Advanced Week 4+ Cross-run correlation, PR feedback analysis, improvement velocity

    Key Design Decisions

    1. Unified collector abstraction — GHALogCollector for CI, LocalLogCollector for egg --exec, same analysis engine for both
    2. YAML-based rules — Easy to add/modify detection rules without code changes
    3. Metrics in repo — metrics/self-improvement-metrics.json with git history for trends
    4. Deduplication — Search before create, update existing issues with new occurrences

    What's Included

    • Complete module structure with file paths
    • Code sketches for all major components
    • Workflow YAML for nightly analysis
    • Detection rule examples for errors, inefficiency, and behavior
    • Testing strategy and success criteria

    Next Steps

    Ready to begin implementation when you approve. I recommend tackling Phase 1 first in a separate PR, then building incrementally.

    — Authored by egg

  13. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  14. jwbron commented on Feb 6, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box review this plan: #153 (comment)

  15. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    Plan Review: Self-Improvement Cycle Implementation

    I've reviewed the implementation plan against the existing codebase. Overall this is a solid, well-structured plan. Below are my findings, concerns, and recommendations.


    ✅ What the Plan Gets Right

    1. Accurate Infrastructure Assessment
    The plan correctly identifies the existing infrastructure:

    • shared/egg_logging/ v0.2.0 is production-ready with JSON formatting, context propagation, and OpenTelemetry W3C Trace Context support
    • sandbox/egg_lib/container_logging.py handles log persistence with file locking, symlinks, and correlation index
    • action/entrypoint.sh captures logs via tee and writes to GITHUB_STEP_SUMMARY

    2. Unified Collector Abstraction
    The dual-collector approach (GHALogCollector + LocalLogCollector) with a shared RunLog interface is the right design. This preserves local development workflows while optimizing for GHA as the primary production source.

    3. Phased Delivery
    Breaking into 4 phases with incremental complexity is appropriate. Starting with HIGH severity rules only in Phase 2 is sensible scope control.

    4. YAML-Based Rules
    Externalizing detection rules to YAML makes the system maintainable and extensible without code changes.


    ⚠️ Issues and Concerns

    1. Module Location: sandbox/egg-tasks/ Doesn't Exist

    The plan proposes sandbox/egg-tasks/self-improvement/ but egg-tasks/ doesn't exist in the codebase. Options:

    • Option A: Create sandbox/egg-tasks/ as a new convention for analysis/utility scripts
    • Option B: Place in sandbox/egg_lib/self_improvement/ alongside existing modules
    • Option C: Create a top-level tools/self-improvement/ directory

    Recommendation: Option B (sandbox/egg_lib/self_improvement/) - follows existing Python module conventions and is already on PYTHONPATH.

    2. GHA Log Download Returns ZIP, Not Raw Logs

    The plan states:

    Downloads run logs via gh api .../runs/{id}/logs (returns zip)

    This is correct, but the implementation sketch in gha.py doesn't show ZIP extraction. The actual flow:

    gh api /repos/{owner}/{repo}/actions/runs/{id}/logs > logs.zip
    unzip logs.zip -d logs/
    # Parse individual job log files

    Each job gets its own log file inside the ZIP. The collector needs to:

    1. Download the ZIP
    2. Extract to a temp directory
    3. Parse each job's log file
    4. Aggregate into RunLog.logs

    3. Missing os Import in analyze.py Sketch

    collector = GHALogCollector() if os.getenv("GITHUB_ACTIONS") else LocalLogCollector()

    The os module isn't imported. Minor, but worth noting.

    4. Workflow Needs Python Dependencies

    The workflow uses:

    - name: Run analysis
      run: python sandbox/egg-tasks/self-improvement/analyze.py

    But there's no pip install step. The analysis script imports yaml (for rule loading) which isn't in stdlib. Either:

    • Add pip install pyyaml step
    • Or bundle rules as Python dicts (less maintainable)

    Recommendation: Add a minimal requirements.txt and install step.

    5. Metrics Commit May Create Merge Conflicts

    The workflow auto-commits to metrics/self-improvement-metrics.json. If the nightly workflow runs while a PR is open that also modifies this file, you'll get merge conflicts.

    Recommendations:

    • Use a dedicated metrics branch that never gets PRs
    • Or append-only design with dated files: metrics/daily/2025-02-06.json
    • Or use GitHub Wiki/Gist instead of repo file

    6. Issue Deduplication Search is Fragile

    search_query = f"repo:{repo} is:issue is:open in:title {TITLE_PREFIX}"

    The in:title search matches substrings. If two detections have similar titles (e.g., "Gateway connection failures" vs "Gateway connection timeout"), false matches could occur.

    Recommendation: Use exact title matching with --search "in:title \"[Self-Improvement] {exact_title}\"" or better, add a unique hash/fingerprint to the issue body and search by that.

    7. Claude Analyzer Won't Work in Private Mode

    result = subprocess.run(
        ["claude", "--print", "-p", prompt],
        capture_output=True, text=True
    )

    In private mode, only api.anthropic.com is allowed. The claude CLI makes API calls which should work, but the plan should note this constraint.

    8. PR Collector Author Filter

    "gh", "pr", "list", "--author", "james-in-a-box[bot]"

    Hardcodes the bot name. Should be configurable or derived from environment ($EGG_BOT_USERNAME or similar).


    🔧 Suggested Improvements

    1. Add Structured Annotations in Sandbox

    Currently errors are just logged. Adding ::error:: and ::warning:: annotations in the sandbox would make issues visible in the GHA UI immediately:

    # In egg_lib or sandbox error handlers
    if os.getenv("GITHUB_ACTIONS"):
        print(f"::error file={file},line={line}::{message}")

    This provides immediate visibility before the nightly analyzer runs.

    2. Add Run Metadata to Logs

    The RunLog.metadata field should capture:

    • Workflow name (on-mention.yml vs on-pull-request.yml)
    • Trigger event (issue_comment, pull_request, workflow_dispatch)
    • PR/Issue number
    • Repository

    Currently action/entrypoint.sh captures some of this in GITHUB_STEP_SUMMARY but not in a structured, parseable format.

    3. Consider Using GitHub Actions Artifacts

    For larger logs, instead of relying solely on gh api .../logs:

    • Upload a structured JSON summary as an artifact
    • Include token counts, tool call metrics, errors
    • Artifacts are easier to parse than raw logs

    4. Add Dry-Run Mode

    For testing, the workflow should support:

    with:
      dry-run: true  # Don't create issues, just report what would be created

    5. Severity Escalation

    The plan tracks occurrence counts but doesn't escalate severity based on frequency. Consider:

    • 1-2 occurrences: Create issue at defined severity
    • 3-5 occurrences: Bump to MEDIUM if LOW
    • 6+ occurrences: Bump to HIGH

    📋 Implementation Order Recommendation

    The plan's phased approach is good, but I'd suggest reordering some items:

    1. Phase 1a: Create module structure + basic GHALogCollector (no local collector yet)
    2. Phase 1b: Add nightly workflow with summary-only output (no issue creation)
    3. Phase 2a: Add HIGH severity error detection only (3-4 rules)
    4. Phase 2b: Add issue creation with deduplication
    5. Phase 2c: Expand to MEDIUM severity + inefficiency rules
    6. Phase 3: Metrics (only after detection is stable)
    7. Phase 4: Advanced analysis

    This lets you validate the collection and detection pipeline before adding issue creation, reducing risk of spammy/incorrect issues.


    Summary

    Aspect Assessment
    Architecture ✅ Sound
    Phasing ✅ Appropriate
    Existing infrastructure usage ✅ Accurate
    Implementation details ⚠️ Some gaps (ZIP handling, deps, dedup)
    Risk management ⚠️ Needs dry-run mode before production

    Overall: Plan is solid and ready for implementation with the noted adjustments. The unified collector abstraction and YAML rules approach will make this maintainable long-term.


    — Authored by egg

  16. 2 remaining items

  17. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    Updated Implementation Plan: Addressing Review Feedback

    I've incorporated all the feedback from the review. Here are the changes and clarifications:


    Feedback Addressed

    1. Module Location → Option B ✅

    Decision: Place in sandbox/egg_lib/self_improvement/ (following existing Python module conventions, already on PYTHONPATH)

    Updated structure:

    sandbox/egg_lib/self_improvement/
    ├── __init__.py
    ├── analyze.py                    # Main orchestrator
    ├── collectors/
    │   ├── __init__.py
    │   ├── base.py                   # LogCollector ABC, RunLog dataclass
    │   ├── gha.py                    # GitHub Actions log collector
    │   ├── local.py                  # Local container log collector
    │   └── prs.py                    # PR history collector
    ├── detection/
    │   ├── __init__.py
    │   ├── engine.py                 # Detection engine
    │   └── rules/                    # YAML rule files
    │       ├── errors.yaml
    │       ├── inefficiency.yaml
    │       └── behavior.yaml
    ├── output/
    │   ├── __init__.py
    │   ├── issue_creator.py          # GitHub issue creation with dedup
    │   └── metrics.py                # Metrics collection
    └── config.py                     # Configuration constants
    

    2. GHA Log ZIP Extraction ✅

    Updated GHALogCollector implementation with proper ZIP handling:

    # sandbox/egg_lib/self_improvement/collectors/gha.py
    import os
    import subprocess
    import tempfile
    import zipfile
    from datetime import datetime
    from .base import LogCollector, RunLog
    
    class GHALogCollector(LogCollector):
        """Collects logs from GitHub Actions via gh api."""
        
        def __init__(self, repo: str | None = None):
            self.repo = repo or self._get_repo()
        
        def _get_repo(self) -> str:
            result = subprocess.run(
                ["gh", "repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"],
                capture_output=True, text=True, check=True
            )
            return result.stdout.strip()
        
        def collect(self, since: datetime) -> list[RunLog]:
            runs = self._fetch_workflow_runs(since)
            return [self._process_run(run) for run in runs]
        
        def _fetch_workflow_runs(self, since: datetime) -> list[dict]:
            """Fetch recent workflow runs via gh api."""
            result = subprocess.run([
                "gh", "api", f"/repos/{self.repo}/actions/runs",
                "--jq", ".workflow_runs",
                "-q", f'.[] | select(.created_at >= "{since.isoformat()}")'
            ], capture_output=True, text=True)
            # Parse and filter to egg-triggered workflows
            return self._parse_runs(result.stdout)
        
        def _process_run(self, run: dict) -> RunLog:
            """Download and extract logs for a single run."""
            with tempfile.TemporaryDirectory() as tmpdir:
                zip_path = os.path.join(tmpdir, "logs.zip")
                extract_dir = os.path.join(tmpdir, "logs")
                
                # Download logs ZIP
                subprocess.run([
                    "gh", "api",
                    f"/repos/{self.repo}/actions/runs/{run['id']}/logs",
                    "--output", zip_path
                ], check=True)
                
                # Extract ZIP
                with zipfile.ZipFile(zip_path, 'r') as zf:
                    zf.extractall(extract_dir)
                
                # Parse and aggregate all job logs
                logs = self._aggregate_job_logs(extract_dir)
                
                return RunLog(
                    run_id=str(run['id']),
                    source="gha",
                    started_at=datetime.fromisoformat(run['created_at'].replace('Z', '+00:00')),
                    completed_at=datetime.fromisoformat(run['updated_at'].replace('Z', '+00:00')) if run.get('updated_at') else None,
                    status=run['conclusion'] or run['status'],
                    trigger=run['event'],
                    logs=logs,
                    metadata={
                        "workflow": run['name'],
                        "head_branch": run.get('head_branch'),
                        "run_number": run.get('run_number'),
                        "html_url": run.get('html_url'),
                    }
                )
        
        def _aggregate_job_logs(self, extract_dir: str) -> str:
            """Combine all job log files into a single string."""
            all_logs = []
            for root, dirs, files in os.walk(extract_dir):
                for file in sorted(files):
                    if file.endswith('.txt'):
                        path = os.path.join(root, file)
                        with open(path, 'r') as f:
                            all_logs.append(f"=== {file} ===\n{f.read()}")
            return "\n\n".join(all_logs)

    3. Fixed Missing Import ✅

    # sandbox/egg_lib/self_improvement/analyze.py
    #!/usr/bin/env python3
    """Self-improvement analysis orchestrator."""
    
    import argparse
    import os
    from datetime import datetime, timedelta
    
    from .collectors.gha import GHALogCollector
    from .collectors.local import LocalLogCollector
    
    def main():
        parser = argparse.ArgumentParser(description="Analyze egg runs for self-improvement")
        parser.add_argument("--source", choices=["gha", "local", "auto"], default="auto")
        parser.add_argument("--since-hours", type=int, default=24)
        parser.add_argument("--output", choices=["summary", "json"], default="summary")
        parser.add_argument("--collect-metrics", action="store_true")
        parser.add_argument("--create-issues", action="store_true")
        parser.add_argument("--dry-run", action="store_true", help="Don't create issues, just report")
        args = parser.parse_args()
        
        # Select collector based on environment
        if args.source == "auto":
            collector = GHALogCollector() if os.getenv("GITHUB_ACTIONS") else LocalLogCollector()
        elif args.source == "gha":
            collector = GHALogCollector()
        else:
            collector = LocalLogCollector()
        
        since = datetime.now() - timedelta(hours=args.since_hours)
        runs = collector.collect(since)
        
        print(f"Collected {len(runs)} runs since {since}")
        for run in runs:
            print(f"  - {run.run_id}: {run.status} ({run.trigger})")
    
    if __name__ == "__main__":
        main()

    4. Python Dependencies ✅

    Updated workflow with dependency installation:

          - name: Set up Python
            uses: actions/setup-python@v5
            with:
              python-version: '3.11'
    
          - name: Install dependencies
            run: pip install pyyaml
    
          - name: Run analysis
            env:
              GH_TOKEN: ${{ steps.bot-token.outputs.token }}
            run: |
              python -m egg_lib.self_improvement.analyze \
                --source gha \
                --since-hours 24 \
                --output summary

    5. Merge Conflicts → Non-Issue ✅

    Per feedback, merge conflicts for metrics/self-improvement-metrics.json can be autofixed. No changes needed.

    6. Improved Issue Deduplication with Fingerprinting ✅

    # sandbox/egg_lib/self_improvement/output/issue_creator.py
    import hashlib
    import json
    import subprocess
    from ..detection.engine import Detection, Severity
    
    LABEL_PREFIX = "self-improvement"
    TITLE_PREFIX = "[Self-Improvement]"
    FINGERPRINT_PREFIX = "<!-- fingerprint:"
    
    def generate_fingerprint(detection: Detection) -> str:
        """Generate unique fingerprint for deduplication."""
        content = f"{detection.category}:{detection.title}"
        return hashlib.sha256(content.encode()).hexdigest()[:12]
    
    def find_existing_issue(detection: Detection, repo: str) -> int | None:
        """Search for open issues with matching fingerprint."""
        fingerprint = generate_fingerprint(detection)
        
        # Search for issues with our fingerprint in the body
        result = subprocess.run([
            "gh", "issue", "list",
            "--repo", repo,
            "--label", LABEL_PREFIX,
            "--state", "open",
            "--json", "number,body",
            "--limit", "100"
        ], capture_output=True, text=True)
        
        if result.returncode == 0:
            issues = json.loads(result.stdout)
            for issue in issues:
                if f"{FINGERPRINT_PREFIX}{fingerprint}-->" in issue.get("body", ""):
                    return issue["number"]
        return None
    
    def create_issue_body(detection: Detection) -> str:
        fingerprint = generate_fingerprint(detection)
        return f"""{FINGERPRINT_PREFIX}{fingerprint}-->
    
    ## Summary
    {detection.description}
    
    ## Detection Details
    - **Category:** {detection.category}
    - **Severity:** {detection.severity.value.upper()}
    - **Occurrences:** {detection.occurrence_count}
    - **Fingerprint:** `{fingerprint}`
    
    ## Evidence

    {chr(10).join(detection.evidence[:5])}

    
    ## Affected Runs
    {chr(10).join(f"- {rid}" for rid in detection.run_ids[:10])}
    
    ## Recommended Actions
    {getattr(detection, 'recommendation', 'Investigate and address the root cause.')}
    
    ---
    *This issue was automatically created by the egg self-improvement analyzer.*
    
    — Authored by egg
    """
    

    7. Claude Analyzer → Use egg --exec ✅

    Critical change: Claude analysis must go through egg --exec, not direct CLI calls.

    # sandbox/egg_lib/self_improvement/output/claude_analyzer.py
    """Use Claude via egg --exec for deeper analysis."""
    
    import subprocess
    import tempfile
    import os
    from pathlib import Path
    
    def analyze_with_claude(runs: list, detections: list, dry_run: bool = False) -> str:
        """
        Spawn egg --exec to analyze patterns and generate recommendations.
        
        This uses the proper egg workflow which:
        - Respects network mode constraints
        - Uses the gateway sidecar for any git/gh operations
        - Follows all egg policies
        """
        # Create analysis prompt file
        prompt = create_analysis_prompt(runs, detections)
        
        # Write prompt to a temp file in sharing directory
        prompt_path = Path.home() / "sharing" / "self-improvement-prompt.md"
        prompt_path.write_text(prompt)
        
        if dry_run:
            return f"[DRY RUN] Would analyze with prompt at {prompt_path}"
        
        # Spawn egg --exec with the analysis task
        # egg --exec handles all the container setup, networking, and credentials
        result = subprocess.run([
            "egg", "--exec",
            "--task", f"Analyze the self-improvement data at {prompt_path} and provide recommendations. Write your analysis to ~/sharing/self-improvement-analysis.md"
        ], capture_output=True, text=True)
        
        if result.returncode != 0:
            return f"Analysis failed: {result.stderr}"
        
        # Read the analysis output
        output_path = Path.home() / "sharing" / "self-improvement-analysis.md"
        if output_path.exists():
            return output_path.read_text()
        
        return "Analysis completed but no output file found."
    
    def create_analysis_prompt(runs: list, detections: list) -> str:
        return f"""# Self-Improvement Analysis Request
    
    ## Context
    Analyze these egg agent run logs and detected issues.
    
    - Runs analyzed: {len(runs)}
    - Issues detected: {len(detections)}
    
    ## Detections
    {format_detections(detections)}
    
    ## Sample Log Excerpts
    {format_log_samples(runs)}
    
    ## Your Task
    Provide:
    1. Root cause analysis for the most critical issues
    2. Patterns you notice across runs
    3. Specific recommendations for improvement
    4. Any issues the automated detection may have missed
    
    Write your analysis in a clear, actionable format.
    """

    8. Configurable Bot Author Name ✅

    # sandbox/egg_lib/self_improvement/config.py
    """Configuration for self-improvement analysis."""
    
    import os
    
    # Bot identity - configurable via environment
    BOT_USERNAME = os.getenv("EGG_BOT_USERNAME", "james-in-a-box[bot]")
    BOT_EMAIL = os.getenv("EGG_BOT_EMAIL", "egg@localhost")
    
    # Metrics storage
    METRICS_FILE = "metrics/self-improvement-metrics.json"
    
    # Issue creation
    ISSUE_LABEL_PREFIX = "self-improvement"
    ISSUE_TITLE_PREFIX = "[Self-Improvement]"
    
    # Analysis defaults
    DEFAULT_SINCE_HOURS = 24
    DEFAULT_LOG_RETENTION_DAYS = 90

    Updated PR collector:

    # sandbox/egg_lib/self_improvement/collectors/prs.py
    from ..config import BOT_USERNAME
    
    def collect_pr_history(since: datetime) -> list:
        result = subprocess.run([
            "gh", "pr", "list",
            "--author", BOT_USERNAME,  # Now configurable
            "--state", "all",
            "--json", "number,title,state,reviews,comments,createdAt,mergedAt,closedAt"
        ], capture_output=True, text=True)
        # ...

    Suggested Improvements Incorporated

    1. Structured GHA Annotations ✅

    Will add to error handling in sandbox:

    # Added to egg_lib error handlers
    def emit_gha_annotation(level: str, message: str, file: str = None, line: int = None):
        """Emit GitHub Actions annotation for immediate visibility."""
        if not os.getenv("GITHUB_ACTIONS"):
            return
        
        location = ""
        if file:
            location += f" file={file}"
        if line:
            location += f",line={line}"
        
        print(f"::{level}{location}::{message}")

    2. Enhanced Run Metadata ✅

    Already included in the updated GHALogCollector - captures workflow name, branch, run number, and HTML URL.

    3. Dry-Run Mode ✅

    Added --dry-run flag to analyze.py and passed through to issue creator.

    4. Severity Escalation ✅

    Added to detection engine:

    def escalate_severity(detection: Detection) -> Detection:
        """Escalate severity based on occurrence frequency."""
        if detection.occurrence_count >= 6:
            if detection.severity == Severity.LOW:
                detection.severity = Severity.HIGH
            elif detection.severity == Severity.MEDIUM:
                detection.severity = Severity.HIGH
        elif detection.occurrence_count >= 3:
            if detection.severity == Severity.LOW:
                detection.severity = Severity.MEDIUM
        return detection

    Updated Implementation Order

    Following the recommended reordering:

    Step Phase Description Deliverable
    1a Foundation Module structure + GHALogCollector PR #1
    1b Foundation Nightly workflow with summary-only output PR #1
    2a Detection HIGH severity error detection (3-4 rules) PR #2
    2b Detection Issue creation with fingerprint dedup PR #2
    2c Detection MEDIUM severity + inefficiency rules PR #3
    3 Metrics Daily metrics, auto-commit, weekly reports PR #4
    4 Advanced Cross-run correlation, PR feedback, velocity Future

    Ready to Implement

    The plan is now updated with all feedback incorporated. Ready to begin Phase 1a/1b implementation.

    — Authored by egg

  18. james-in-a-box commented on Feb 6, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  19. jwbron commented on Feb 6, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box go ahead and implement phase 1 of this plan and open a pr #153 (comment)

  20. james-in-a-box commented on Feb 7, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  21. jwbron commented on Feb 7, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box phase 1 has been implemented. Move forward with phase 2 and create a PR #153 (comment)

  22. james-in-a-box commented on Feb 7, 2026

    @james-in-a-box
    Contributor

    egg run failed (exit code: unknown). View run logs

  23. jwbron commented on Feb 7, 2026

    @jwbron
    OwnerAuthor

    @james-in-a-box phase 1 has been implemented. Move forward with phase 2 and create a PR #153 (comment)

  24. james-in-a-box commented on Feb 7, 2026

    @james-in-a-box
    Contributor

    Phase 2 Implementation Complete

    I've implemented Phase 2 of the self-improvement cycle as defined in the updated plan. PR #205 is ready for review.

    What was implemented

    Phase 2a: HIGH Severity Error Detection

    • Created detection engine with YAML-based rules (sandbox/egg_lib/self_improvement/detection/)
    • Added HIGH severity rules for:
      • Gateway sidecar connection failures
      • Docker permission issues
      • GitHub authentication failures
      • API rate limiting
      • Git push failures
    • Added MEDIUM severity rules for:
      • Excessive file read failures
      • Frequent bash command failures
      • Network proxy blocks
      • Connection timeouts
    • Implemented severity escalation (LOW→MEDIUM at 3 occurrences, MEDIUM→HIGH at 6 occurrences)

    Phase 2b: Issue Creation with Fingerprint Deduplication

    • Created issue creator with fingerprint-based deduplication (sandbox/egg_lib/self_improvement/output/)
    • Fingerprints are SHA-256 hashes of category + rule_id, embedded in issue body
    • Existing issues are updated with new occurrence comments rather than creating duplicates
    • Issues include evidence, affected runs, and recommended actions
    • Severity-based labels (self-improvement:high, self-improvement:medium, etc.)

    Updated Analyzer

    • New CLI flags: --detect, --create-issues, --dry-run, --min-severity
    • Detection summary included in human-readable output
    • Detection data included in JSON output

    Updated Workflow

    • New inputs: create_issues, dry_run, min_severity
    • Added issues: write permission
    • Installs pyyaml dependency for rule parsing

    Test Results

    All 43 tests pass (24 new tests added for Phase 2 functionality).

    Next Steps (Phase 2c and beyond)

    After this PR is merged, Phase 2c would add MEDIUM severity and inefficiency rules. Phase 3 would add metrics tracking, and Phase 4 would add advanced cross-run correlation analysis.


    — Authored by egg

  25. james-in-a-box commented on Feb 7, 2026

    @james-in-a-box
    Contributor

    egg finished successfully. View run logs

  26. jwbron commented on Feb 9, 2026

    @jwbron
    OwnerAuthor

    This has been partly implemented but was disabled. See #289

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions