Repository navigation
Description
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:
- Monitors itself by analyzing GitHub Actions outputs and container logs
- Detects issues across multiple categories (errors, inefficiencies, behavior problems)
- Opens issues automatically for detected problems with actionable recommendations
- Tracks improvements to measure if fixes are effective
- 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 --execlocally 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 apito 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.jsonfor recent entries - Loads corresponding
.logfiles 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:
-
Unified Log Collector Framework
- Base
LogCollectorabstract class withRunLogdataclass GHALogCollectorimplementation usinggh apiLocalLogCollectorimplementation using existingcontainer_logging.py- Both produce identical
RunLogformat
- Base
-
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
-
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:
-
Rule-Based Detection
- YAML rule definitions for each category
- Pattern matching on logs
- Threshold-based alerts
-
Claude-Powered Analysis
- Send collected data to Claude for deeper analysis
- Generate actionable recommendations
- Identify patterns humans might miss
-
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:
-
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
- Daily metrics written to
-
Weekly Summary Report
- Markdown summary posted to configured location (Slack or issue)
- Trend visualization (improvement velocity)
- Highlights of resolved vs new issues
-
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:
-
Cross-Run Correlation
- Identify systemic issues across multiple runs
- Cluster similar failures
- Root cause analysis
-
Predictive Detection
- Learn patterns that predict failures
- Proactive warnings before issues occur
- Resource optimization recommendations
-
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
- Log Sanitization: Remove sensitive data (tokens, keys) before analysis
- Issue Content: Don't include raw logs in public issues — link to run instead
- API Rate Limits: Respect GitHub API limits in data collection
- 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
- ADR: Autonomous Software Engineer - Continuous Improvement Strategy section
- Log Persistence Documentation
- Container Logging Implementation
Activity
jwbron commentedon Feb 6, 2026
@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.
james-in-a-box commentedon Feb 6, 2026
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:
2. Proposed Architecture
A nightly self-improvement analyzer with:
3. Detection Categories
Detailed rules for catching:
4. Implementation Plan
Four-phase approach:
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
james-in-a-box commentedon Feb 6, 2026
egg finished successfully. View run logs
jwbron commentedon Feb 6, 2026
@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.
james-in-a-box commentedon Feb 6, 2026
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:
tee "$LOG_FILE"inaction/entrypoint.sh:110-111GITHUB_STEP_SUMMARY(truncated to 500KB)egg_loggingwith trace/span IDs, task IDs, etc.What we'd need to enable GHA-only collection:
GITHUB_STEP_SUMMARYcaptures full structured logs (or use artifacts for larger logs)::error::and::warning::annotations for surfacing issues in the GHA UIgh apican fetch workflow run logs viaGET /repos/{owner}/{repo}/actions/runs/{run_id}/logsBenefits of this approach:
~/.cache/egg/container-logs/)run_id,job_id, triggering event contextgh apiprovides structured access to runs, jobs, steps, annotationslog-index.json, Docker log capture, file locking logicRecommended Adjustments to the Plan
Given this simplification, I'd revise the architecture:
Phase 1 Changes
Remove:
collect_logs.py) — not neededlog-index.jsonparsing — not neededKeep/Modify:
Add:
::error::/::warning::annotations in sandbox for automatic surfacingSimplified Data Flow
Other Plan Observations
Strengths:
Areas to clarify:
Metrics storage — Where do historical metrics live? Options:
metrics/daily-metrics.json)Self-referential analysis — The analyzer runs as egg. If egg is broken, can it analyze itself? Consider:
Deduplication — How do we avoid creating duplicate issues for the same problem across runs? Suggest:
[Self-Improvement]prefix + similar title before creatingScope of first implementation — The detection rules are comprehensive but could be overwhelming. Suggest starting with:
Questions for @jwbron
Container log persistence — Can we deprecate
container_logging.pyentirely once GHA-only is working? It's only useful for localegg --execruns currently.Metrics storage preference — JSON file in repo vs. separate mechanism?
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
james-in-a-box commentedon Feb 6, 2026
egg finished successfully. View run logs
jwbron commentedon Feb 6, 2026
@james-in-a-box
Address the feedback in the above comment.
james-in-a-box commentedon Feb 6, 2026
Issue Updated: Addressing Feedback
I've updated the issue to address the feedback:
1. Local Compatibility (Keep container log persistence)
Decision: Keep
container_logging.pyfor local runs.The plan now uses a unified log collector abstraction with two implementations:
GHALogCollector— Usesgh apito fetch workflow run logs (primary for CI)LocalLogCollector— Uses existingcontainer_logging.pyandlog-index.json(foregg --execruns)Both collectors produce the same
RunLogformat, so the analysis engine works identically on either source. This means:egg --exechistory2. Metrics Storage (JSON in repo)
Decision: Store metrics in
metrics/self-improvement-metrics.jsonBenefits:
3. Single Phased Effort
Decision: Keep as one issue with clear phase boundaries.
The implementation plan now has four phases:
This allows incremental delivery while keeping the effort focused as a single cohesive feature.
— Authored by egg
james-in-a-box commentedon Feb 6, 2026
egg finished successfully. View run logs
jwbron commentedon Feb 6, 2026
@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.
james-in-a-box commentedon Feb 6, 2026
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/1.2 Implement Unified Log Collector
File:
collectors/base.pyFile:
collectors/gha.pysubprocessto callgh api /repos/{owner}/{repo}/actions/runsgh api .../runs/{id}/logs(returns zip)::error::and::warning::annotationsFile:
collectors/local.py~/.cache/egg/container-logs/log-index.json.logfiles referenced in the indexegg_loggingoutput1.3 Create Basic Analysis Runner
File:
analyze.py1.4 Create Nightly Workflow
File:
.github/workflows/self-improvement.yml1.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 structureLogCollectorABC andRunLogdataclassGHALogCollectorimplementationLocalLogCollectorimplementationanalyze.pyrunner.github/workflows/self-improvement.ymlmetrics/self-improvement-metrics.jsoninitializedPhase 2: Detection Engine (Week 2-3)
2.1 Create Detection Rule Engine
File:
detect.py2.2 Create Rule Definition Files
File:
rules/errors.yamlFile:
rules/inefficiency.yamlFile:
rules/behavior.yaml2.3 Implement Issue Creator with Deduplication
File:
issue_creator.py{chr(10).join(detection.evidence[:5])}
2.4 Add Claude-Powered Analysis (Optional Enhancement)
File:
claude_analyzer.pyPhase 2 Deliverables Checklist
DetectionEngineclass with rule loadingrules/errors.yamlwith error detection rulesrules/inefficiency.yamlwith inefficiency rulesrules/behavior.yamlwith behavior rulesissue_creator.pywith deduplicationclaude_analyzer.pyfor AI-powered analysisPhase 3: Metrics & Tracking (Week 3-4)
3.1 Implement Metrics Collection
File:
metrics.py3.2 Update Workflow to Commit Metrics
Update
.github/workflows/self-improvement.yml:3.3 Implement Weekly Summary Report
File:
weekly_report.pyPhase 3 Deliverables Checklist
metrics.pywithDailyMetricscollectionweekly_report.pyfor weekly summariesPhase 4: Advanced Analysis (Week 4+)
4.1 Cross-Run Correlation
4.2 PR Feedback Analysis
File:
collectors/prs.py4.3 Improvement Velocity Tracking
Phase 4 Deliverables Checklist
collectors/prs.pyfor PR analysisTesting Strategy
Unit Tests
Integration Tests
Manual Testing
--source localworkflow_dispatchSuccess Criteria
Implementation Order
Each phase should be a separate PR for easier review.
— Authored by egg
james-in-a-box commentedon Feb 6, 2026
Summary
I've added a comprehensive implementation plan for the self-improvement cycle above. The plan includes:
Four Phased Approach
Key Design Decisions
GHALogCollectorfor CI,LocalLogCollectorforegg --exec, same analysis engine for bothmetrics/self-improvement-metrics.jsonwith git history for trendsWhat's Included
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
james-in-a-box commentedon Feb 6, 2026
egg finished successfully. View run logs
jwbron commentedon Feb 6, 2026
@james-in-a-box review this plan: #153 (comment)
james-in-a-box commentedon Feb 6, 2026
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 supportsandbox/egg_lib/container_logging.pyhandles log persistence with file locking, symlinks, and correlation indexaction/entrypoint.shcaptures logs viateeand writes toGITHUB_STEP_SUMMARY2. Unified Collector Abstraction
The dual-collector approach (
GHALogCollector+LocalLogCollector) with a sharedRunLoginterface 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.
1. Module Location:
sandbox/egg-tasks/Doesn't ExistThe plan proposes
sandbox/egg-tasks/self-improvement/butegg-tasks/doesn't exist in the codebase. Options:sandbox/egg-tasks/as a new convention for analysis/utility scriptssandbox/egg_lib/self_improvement/alongside existing modulestools/self-improvement/directoryRecommendation: 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:
This is correct, but the implementation sketch in
gha.pydoesn'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 filesEach job gets its own log file inside the ZIP. The collector needs to:
RunLog.logs3. Missing
osImport inanalyze.pySketchThe
osmodule isn't imported. Minor, but worth noting.4. Workflow Needs Python Dependencies
The workflow uses:
But there's no
pip installstep. The analysis script importsyaml(for rule loading) which isn't in stdlib. Either:pip install pyyamlstepRecommendation: Add a minimal
requirements.txtand 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:
metricsbranch that never gets PRsmetrics/daily/2025-02-06.json6. Issue Deduplication Search is Fragile
The
in:titlesearch 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
In private mode, only
api.anthropic.comis allowed. TheclaudeCLI makes API calls which should work, but the plan should note this constraint.8. PR Collector Author Filter
Hardcodes the bot name. Should be configurable or derived from environment (
$EGG_BOT_USERNAMEor 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:This provides immediate visibility before the nightly analyzer runs.
2. Add Run Metadata to Logs
The
RunLog.metadatafield should capture:on-mention.ymlvson-pull-request.yml)Currently
action/entrypoint.shcaptures some of this inGITHUB_STEP_SUMMARYbut not in a structured, parseable format.3. Consider Using GitHub Actions Artifacts
For larger logs, instead of relying solely on
gh api .../logs:4. Add Dry-Run Mode
For testing, the workflow should support:
5. Severity Escalation
The plan tracks occurrence counts but doesn't escalate severity based on frequency. Consider:
📋 Implementation Order Recommendation
The plan's phased approach is good, but I'd suggest reordering some items:
GHALogCollector(no local collector yet)This lets you validate the collection and detection pipeline before adding issue creation, reducing risk of spammy/incorrect issues.
Summary
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
2 remaining items
james-in-a-box commentedon Feb 6, 2026
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:
2. GHA Log ZIP Extraction ✅
Updated
GHALogCollectorimplementation with proper ZIP handling:3. Fixed Missing Import ✅
4. Python Dependencies ✅
Updated workflow with dependency installation:
5. Merge Conflicts → Non-Issue ✅
Per feedback, merge conflicts for
metrics/self-improvement-metrics.jsoncan be autofixed. No changes needed.6. Improved Issue Deduplication with Fingerprinting ✅
{chr(10).join(detection.evidence[:5])}
7. Claude Analyzer → Use egg --exec ✅
Critical change: Claude analysis must go through
egg --exec, not direct CLI calls.8. Configurable Bot Author Name ✅
Updated PR collector:
Suggested Improvements Incorporated
1. Structured GHA Annotations ✅
Will add to error handling in sandbox:
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-runflag to analyze.py and passed through to issue creator.4. Severity Escalation ✅
Added to detection engine:
Updated Implementation Order
Following the recommended reordering:
GHALogCollectorReady to Implement
The plan is now updated with all feedback incorporated. Ready to begin Phase 1a/1b implementation.
— Authored by egg
james-in-a-box commentedon Feb 6, 2026
egg finished successfully. View run logs
jwbron commentedon Feb 6, 2026
@james-in-a-box go ahead and implement phase 1 of this plan and open a pr #153 (comment)
Add self-improvement analysis module (Phase 1)
james-in-a-box commentedon Feb 7, 2026
egg finished successfully. View run logs
jwbron commentedon Feb 7, 2026
@james-in-a-box phase 1 has been implemented. Move forward with phase 2 and create a PR #153 (comment)
Add self-improvement analysis module (Phase 1) (#186)
james-in-a-box commentedon Feb 7, 2026
egg run failed (exit code: unknown). View run logs
jwbron commentedon Feb 7, 2026
@james-in-a-box phase 1 has been implemented. Move forward with phase 2 and create a PR #153 (comment)
Add self-improvement detection and issue creation (Phase 2)
james-in-a-box commentedon Feb 7, 2026
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
sandbox/egg_lib/self_improvement/detection/)Phase 2b: Issue Creation with Fingerprint Deduplication
sandbox/egg_lib/self_improvement/output/)self-improvement:high,self-improvement:medium, etc.)Updated Analyzer
--detect,--create-issues,--dry-run,--min-severityUpdated Workflow
create_issues,dry_run,min_severityissues: writepermissionpyyamldependency for rule parsingTest 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
james-in-a-box commentedon Feb 7, 2026
egg finished successfully. View run logs
Add self-improvement detection and issue creation (Phase 2) (#205)
jwbron commentedon Feb 9, 2026
This has been partly implemented but was disabled. See #289