Skip to content

Add self-improvement analysis module (Phase 1) - #186

Merged
jwbron merged 7 commits into
mainfrom
egg/self-improvement-phase1
Feb 7, 2026
Merged

jwbron merged 7 commits into
mainfrom
egg/self-improvement-phase1

Conversation

@james-in-a-box

@james-in-a-box james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements Phase 1 of the self-improvement cycle (#153):

  • Unified log collector abstraction with LogCollector ABC and RunLog dataclass
  • GHA log collector that downloads and extracts workflow run logs via gh api
  • Local log collector that reads from existing container_logging.py infrastructure
  • Nightly workflow (self-improvement.yml) that runs analysis at 2 AM UTC
  • Configurable constants for bot identity, metrics storage, and workflows to analyze
  • Summary and JSON output formats for analysis results

What's Included

Component Location Description
Module structure sandbox/egg_lib/self_improvement/ New package following egg conventions
Base classes collectors/base.py LogCollector ABC, RunLog dataclass
GHA collector collectors/gha.py GitHub Actions log collection with ZIP extraction
Local collector collectors/local.py Local container log collection
Config config.py Configurable constants (bot username, workflows)
Analyzer analyze.py Main orchestrator with CLI interface
Workflow .github/workflows/self-improvement.yml Nightly analysis job
Metrics metrics/self-improvement-metrics.json Initialized metrics storage
Tests tests/sandbox/test_self_improvement.py 20 tests covering all components

Usage

# Run analysis locally
PYTHONPATH=sandbox python -m egg_lib.self_improvement.analyze --source local --since-hours 24

# Run with GHA source
PYTHONPATH=sandbox python -m egg_lib.self_improvement.analyze --source gha --output json

Next Steps (Phase 2)

  • Detection engine with YAML-based rules
  • Automated issue creation with fingerprint deduplication
  • Claude-powered analysis via egg --exec

Issue: #153

Test plan:

  • All 20 tests pass (pytest tests/sandbox/test_self_improvement.py)
  • mypy strict mode passes
  • ruff linting passes
  • Manually trigger workflow via workflow_dispatch to verify GHA integration

Authored-by: egg

Implement the foundation for egg's self-improvement cycle:
- Unified log collector abstraction with GHA and local collectors
- Nightly GitHub Actions workflow for automated analysis
- Summary and JSON output formats for run analysis
- Comprehensive test suite (20 tests)

This enables egg to monitor its own runs and detect patterns
for continuous improvement. Phase 2 will add detection rules
and automated issue creation.

Issue: #153

Authored-by: egg

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: Add self-improvement analysis module (Phase 1)

Good foundation for the self-improvement system. The code is well-organized with clear abstractions. A few issues to address:

Issues

1. Local collector import may fail in GHA context (sandbox/egg_lib/self_improvement/collectors/local.py:12)

The import from ...container_logging import CONTAINER_LOGS_DIR creates a hard dependency on the container_logging module. When running in GHA (where LocalLogCollector isn't used), this import still runs at module load time. If the module structure changes or has side effects, this could cause issues. Consider lazy importing inside the class or catching ImportError.

2. Status inference is too aggressive (sandbox/egg_lib/self_improvement/collectors/local.py:139-167)

The _infer_status method will mark runs as "failure" if logs contain common words like "error" or "failed" anywhere, including in legitimate output (e.g., "fixed the error", "tests that previously failed"). This will produce false negatives on success rate. Consider:

  • Checking for error patterns at line starts (e.g., ^Error:)
  • Looking for exit code indicators if available
  • Using more specific patterns like Traceback \(most recent call last\)

3. Workflow runs analysis twice (.github/workflows/self-improvement.yml:44-86)

The workflow runs the analysis twice (once for summary, once for JSON). This doubles API calls to GitHub. Consider modifying analyze.py to output both formats in a single run, or run once and post-process the JSON into summary.

4. Missing error handling for gh api pagination (sandbox/egg_lib/self_improvement/collectors/gha.py:85-91)

When --paginate returns multiple JSON arrays (one per page), the current parsing joins them but doesn't handle potential malformed responses between pages. A single corrupt page could break the entire collection. Consider wrapping individual page parsing in try/except.

Minor suggestions

  • analyze.py:352-354: The generic except Exception as e could hide specific errors. Consider catching subprocess/IO errors explicitly.
  • config.py:21-24: EGG_WORKFLOWS could be loaded from an env var for flexibility (e.g., testing with other workflows).
  • The tests are comprehensive - good coverage of edge cases.

Overall this is solid work for Phase 1. The collector abstraction will make it easy to add new sources.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

@jwbron

jwbron commented Feb 7, 2026

Copy link
Copy Markdown
Owner

@james-in-a-box address the above feedback and fix lint check failures

- Fix lint errors: use datetime.UTC alias, pytest.raises, import ordering
- Use lazy import for container_logging to avoid GHA context issues
- Improve status inference with line-start patterns to avoid false positives
- Add --output both option to avoid running analysis twice in workflow
- Add pagination error handling with warnings for malformed pages
- Use specific exception types in analyze.py
- Support EGG_WORKFLOWS env var for configuration flexibility
@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all review feedback:

Issues Fixed

1. Local collector import - Changed to lazy import with fallback. The container_logging module is now imported only when needed, avoiding issues in GHA context.

2. Status inference too aggressive - Rewrote _infer_status() to use regex patterns that match at line starts only. Phrases like "fixed the error" or "tests that previously failed" no longer trigger false failures.

3. Workflow runs analysis twice - Added --output both option with --json-file parameter. The workflow now runs analysis once and writes both formats in a single pass, eliminating duplicate API calls.

4. Pagination error handling - Added try/except per page with warning logging. Malformed pages are skipped while continuing to process remaining pages.

Minor Suggestions

  • Changed generic except Exception to except (OSError, subprocess.SubprocessError) in analyze.py
  • Added EGG_WORKFLOWS env var support for flexibility (comma-separated list overrides defaults)

Lint Fixes

  • Replaced timezone.utc with datetime.UTC alias
  • Replaced assert False with pytest.raises()
  • Fixed import ordering

All 20 tests pass, ruff check passes, mypy strict passes.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg finished successfully. View run logs

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

Solid Phase 1 implementation. The modular design with the LogCollector ABC and RunLog dataclass provides a clean foundation for collecting logs from different sources. A few items to consider:

Issues

1. Subprocess exception type mismatch (analyze.py:348)

The exception handler catches subprocess.SubprocessError, but subprocess.run() can also raise FileNotFoundError (e.g., if gh CLI is not installed). The current handler would let that propagate uncaught.

except (OSError, subprocess.SubprocessError) as e:

Consider catching OSError as well, or just use a broader exception type since this is a CLI entrypoint.

2. Log file path handling in LocalLogCollector (collectors/local.py:843-846)

When loading log files, the code checks if log_path.exists() but the path in the index may be a relative path stored as a string. If log_file_path is relative, Path(log_file_path) won't resolve correctly when run from a different working directory. Should use absolute paths or resolve relative to logs_dir.

3. No handling for malformed timestamps (collectors/gha.py:647-650)

If updated_at_str is present but malformed (not valid ISO format), datetime.fromisoformat() will raise ValueError which isn't caught. The created_at_str parsing has the same issue but is at least guaranteed to exist if the run was included after filtering.

Minor Suggestions

  • generate_summary() and generate_json() duplicate the statistics calculation (lines 226-230 and 303-305). Consider extracting to a helper if Phase 2 adds more output formats.

  • The # type: ignore[arg-type] at line 671 suggests the status Literal narrowing isn't being recognized. Could simplify by using status: StatusType = ... pattern similar to local.py.

Overall this is well-structured with good test coverage. The separation between collectors and the analyzer makes it easy to add new log sources in Phase 2.

— Authored by egg

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

Solid Phase 1 implementation. The modular design with the LogCollector ABC and RunLog dataclass provides a clean foundation for collecting logs from different sources. A few items to consider:

Issues

1. Subprocess exception type mismatch (analyze.py:348)

The exception handler catches subprocess.SubprocessError, but subprocess.run() can also raise FileNotFoundError (e.g., if gh CLI is not installed). The current handler would let that propagate uncaught.

except (OSError, subprocess.SubprocessError) as e:

Consider catching OSError as well, or just use a broader exception type since this is a CLI entrypoint.

2. Log file path handling in LocalLogCollector (collectors/local.py:843-846)

When loading log files, the code checks if log_path.exists() but the path in the index may be a relative path stored as a string. If log_file_path is relative, Path(log_file_path) won't resolve correctly when run from a different working directory. Should use absolute paths or resolve relative to logs_dir.

3. No handling for malformed timestamps (collectors/gha.py:647-650)

If updated_at_str is present but malformed (not valid ISO format), datetime.fromisoformat() will raise ValueError which isn't caught. The created_at_str parsing has the same issue but is at least guaranteed to exist if the run was included after filtering.

Minor Suggestions

  • generate_summary() and generate_json() duplicate the statistics calculation (lines 226-230 and 303-305). Consider extracting to a helper if Phase 2 adds more output formats.

  • The # type: ignore[arg-type] at line 671 suggests the status Literal narrowing isn't being recognized. Could simplify by using status: StatusType = ... pattern similar to local.py.

Overall this is well-structured with good test coverage. The separation between collectors and the analyzer makes it easy to add new log sources in Phase 2.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

@jwbron

jwbron commented Feb 7, 2026

Copy link
Copy Markdown
Owner

@james-in-a-box address the above feedback. Be sure to pull in main.

- Fix log file path handling in LocalLogCollector: resolve relative paths
  against logs_dir to handle cases where index stores relative paths
- Add error handling for malformed timestamps in GHA collector: wrap
  datetime.fromisoformat() calls in try/except to skip runs with invalid
  created_at and gracefully handle invalid updated_at

Note: OSError already covers FileNotFoundError (it's a subclass), so the
subprocess exception handling in analyze.py was already correct.

Authored-by: egg
@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressed second round of review feedback:

Issues Fixed

1. Log file path handling in LocalLogCollector (collectors/local.py:136-140)

Added resolution of relative paths against logs_dir. If log_file_path is relative, it's now resolved to an absolute path before checking existence.

2. Malformed timestamp handling in GHA collector (collectors/gha.py:182-194)

Added try/except around datetime.fromisoformat() calls:

  • Runs with malformed created_at are skipped (return None)
  • Malformed updated_at is gracefully handled (completed_at stays None)

Note on Subprocess Exception Types

The review mentioned that subprocess.run() can raise FileNotFoundError (e.g., if gh CLI is not installed). The current handler already catches this because FileNotFoundError is a subclass of OSError. The existing (OSError, subprocess.SubprocessError) catch is correct.

All 20 tests pass, mypy strict mode passes, ruff check passes.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg finished successfully. View run logs

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

This is a well-structured Phase 1 implementation of the self-improvement analysis module. The code follows existing patterns in the codebase and provides a solid foundation for future phases.

Strengths

  • Clean ABC-based architecture with LogCollector and unified RunLog dataclass
  • Good test coverage with 20 tests covering all components
  • Proper timezone handling with UTC-aware datetimes
  • Reasonable error handling that avoids swallowing errors silently
  • Environment-based configuration for customization

Issues to Address

1. Security: Potential path traversal in local collector (collectors/local.py:856-858)

if not log_path.is_absolute():
    log_path = self.logs_dir / log_path

The log file path from the index is used without validation. If the index file were tampered with, a malicious path like ../../etc/passwd could be read. Consider validating that the resolved path remains within self.logs_dir:

log_path = (self.logs_dir / log_path).resolve()
if not log_path.is_relative_to(self.logs_dir):
    continue  # Skip suspicious paths

2. Correctness: --paginate with --jq may produce malformed JSON (collectors/gha.py:541-553)

The current code handles this by catching json.JSONDecodeError per line, but --paginate can also output concatenated JSON arrays without newlines between them. A safer approach would be to use gh api --paginate --jq '.workflow_runs[]' (note []) which would produce one object per line, or avoid --jq and parse the full response.

The current code may work but is fragile. Consider testing with repos that have many workflow runs to verify pagination behavior.

3. Correctness: Silent failure when logs unavailable (collectors/gha.py:627-629)

When logs can't be downloaded (e.g., run still in progress), the function returns None and the run is silently skipped. This is reasonable for in-progress runs but may hide other failures. Consider logging a debug message when skipping, especially for completed runs that fail to download.

Minor Suggestions

  • The # type: ignore[arg-type] on line 680 suggests the status variable could be typed more precisely. Consider using a helper function that returns Literal["success", "failure", "cancelled", "running"] to avoid the ignore comment.

  • In analyze.py:361-367, when --output both is used without --json-file, the JSON is printed to stdout mixed with the summary. This could confuse downstream parsing. Consider printing to stderr or requiring --json-file when using both.

Workflow Review

The GitHub Actions workflow looks correct:

  • Minimal permissions (contents: read, actions: read)
  • Uses app token for GH_TOKEN
  • Artifact upload with reasonable retention

No blocking issues, but the path traversal concern (item #1) should be addressed before merge.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

@jwbron

jwbron commented Feb 7, 2026

Copy link
Copy Markdown
Owner

@james-in-a-box fix lint issues

Reformatted ArgumentParser description to single line format.

Authored-by: egg
@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the ruff format issue in analyze.py. The ArgumentParser description line was reformatted to match ruff's expected single-line format.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg finished successfully. View run logs

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg is investigating the Lint check failure...

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

Well-structured implementation of the self-improvement analysis module. The abstraction layer for log collectors is clean and extensible. I have one correctness concern and several minor suggestions.

Blocking Issue

local.py:174 - Incorrect completed_at assignment

completed_at=timestamp,  # Local logs don't track completion separately

This uses the same timestamp for both started_at and completed_at, which will produce incorrect duration metrics. The local log index doesn't capture completion time, so this should be None rather than a misleading value:

completed_at=None,  # Local logs don't track completion time

The comment even acknowledges the limitation, but the code still assigns a value that will be interpreted as "run completed instantly" rather than "completion time unknown."

Suggestions (non-blocking)

  1. gha.py:569-575 - Silent failure on JSON parse errors

    The warning is printed to stderr, but if multiple pages fail parsing, we might lose significant data without the caller knowing. Consider returning a status or raising if all pages fail.

  2. local.py:857 - contextlib.suppress(OSError) is overly broad

    This silently swallows file read errors. At minimum, consider logging a warning for debugging purposes:

    except OSError as e:
        import sys
        print(f"Warning: Failed to read log file {log_path}: {e}", file=sys.stderr)
  3. config.py:941 - Relative path for METRICS_DIR

    METRICS_DIR = Path("metrics") is relative to CWD, which may vary depending on how the module is invoked. Consider using an absolute path or making it configurable.

  4. analyze.py:359-361 - File write without error handling

    The JSON file write could fail (permissions, disk full), but errors aren't caught:

    with open(args.json_file, "w") as f:
        f.write(json_output)

    Consider wrapping in try/except or letting the exception propagate with a clearer message.

Nits

  • gha.py:676 - The # type: ignore[arg-type] comment suggests a type mismatch. Consider adding a cast() or restructuring to satisfy the type checker cleanly.

Overall, solid foundation for Phase 1. The collector abstraction will scale well for Phase 2.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

Quote $GITHUB_STEP_SUMMARY and group redirects to satisfy SC2086 and
SC2129 shellcheck rules.

Authored-by: egg

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-Review: Changes since 5d85165302a1db07fb14f7cb38941a3e1d9dd782

New Changes

The only change in this commit is shellcheck compliance in .github/workflows/self-improvement.yml:

  • Grouped multiple echo statements into single redirection blocks (SC2129)
  • Quoted $GITHUB_STEP_SUMMARY variable (SC2086)

This change looks good.

Unaddressed Issues from Previous Review

Two issues from my previous review at commit 5d85165 were not addressed:

1. [Blocking] Incorrect completed_at assignment (collectors/local.py:151)

completed_at=timestamp,  # Local logs don't track completion separately

This still assigns the same timestamp to both started_at and completed_at, producing incorrect duration metrics (all runs appear to complete instantly). The comment acknowledges the limitation, but the code should use None instead of a misleading value:

completed_at=None,  # Local logs don't track completion time

2. [Security] Path traversal in local collector (collectors/local.py:136-142)

The log file path from the index is used without validation. If the index file were tampered with, a malicious path like ../../etc/passwd could be read. Add validation:

log_path = (self.logs_dir / log_path).resolve()
if not log_path.is_relative_to(self.logs_dir):
    continue  # Skip suspicious paths

Please address these two items before merge.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg autofix completed. View run logs

@jwbron

jwbron commented Feb 7, 2026

Copy link
Copy Markdown
Owner

@james-in-a-box address the feedback in the above review

- Set completed_at=None instead of timestamp since local logs don't
  track completion time (prevents misleading duration metrics)
- Add path traversal protection by resolving paths and validating
  they remain within logs_dir before reading

Authored-by: egg

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed both issues from the re-review:

1. Incorrect completed_at assignment - Changed to completed_at=None so duration metrics correctly show "unknown" rather than "instant completion" for local runs.

2. Path traversal protection - Added validation to resolve paths to canonical form and verify they remain within logs_dir before reading. Malicious paths like ../../etc/passwd are now skipped.

All 20 tests pass, linting passes.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg finished successfully. View run logs

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-Review Summary

No new commits since my last review at de55d5feebd0fbf95450f9c45bc38d019b68d7ca.

Verification

The two blocking issues from my previous review have been addressed:

  1. completed_at assignment (local.py:151) - Now correctly set to None for local runs, avoiding misleading duration metrics.

  2. Path traversal protection (local.py:136-142) - Added resolve() + is_relative_to() validation to prevent reading files outside logs_dir.

No further changes needed. Ready for human review and merge.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

Without pipefail, a failure in the analysis script is masked by
tee's exit code, causing the step to report success even when the
analysis fails.

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-Review Summary

Reviewed changes since de55d5feebd0fbf95450f9c45bc38d019b68d7ca.

New Change

The only new change is the addition of set -o pipefail in .github/workflows/self-improvement.yml:

run: |
  set -o pipefail

This is a good fix. Without pipefail, failures in the analysis script would be masked by tee's exit code, causing the step to incorrectly report success.

Verification of Previously Raised Issues

Both blocking issues from my previous review have been addressed:

  1. completed_at assignment (collectors/local.py:151) - Now correctly set to None for local runs, avoiding misleading duration metrics.

  2. Path traversal protection (collectors/local.py:136-142) - Added resolve() + is_relative_to() validation to prevent reading files outside logs_dir.

No blocking issues. Ready for human review and merge.

— Authored by egg

@james-in-a-box

james-in-a-box Bot commented Feb 7, 2026

Copy link
Copy Markdown
Contributor Author

egg review completed. View run logs

@jwbron
jwbron merged commit cfab1ba into main Feb 7, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant