Repository navigation
Add self-improvement analysis module (Phase 1) - #186
Conversation
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
There was a problem hiding this comment.
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 genericexcept Exception as ecould hide specific errors. Consider catching subprocess/IO errors explicitly.config.py:21-24:EGG_WORKFLOWScould 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
|
egg review completed. View run logs |
|
@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
|
Addressed all review feedback: Issues Fixed1. Local collector import - Changed to lazy import with fallback. The 2. Status inference too aggressive - Rewrote 3. Workflow runs analysis twice - Added 4. Pagination error handling - Added try/except per page with warning logging. Malformed pages are skipped while continuing to process remaining pages. Minor Suggestions
Lint Fixes
All 20 tests pass, ruff check passes, mypy strict passes. — Authored by egg |
|
egg finished successfully. View run logs |
There was a problem hiding this comment.
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()andgenerate_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 thestatusLiteral narrowing isn't being recognized. Could simplify by usingstatus: StatusType = ...pattern similar tolocal.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
There was a problem hiding this comment.
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()andgenerate_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 thestatusLiteral narrowing isn't being recognized. Could simplify by usingstatus: StatusType = ...pattern similar tolocal.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
|
egg review completed. View run logs |
|
@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
|
Addressed second round of review feedback: Issues Fixed1. Log file path handling in LocalLogCollector ( Added resolution of relative paths against 2. Malformed timestamp handling in GHA collector ( Added try/except around
Note on Subprocess Exception TypesThe review mentioned that All 20 tests pass, mypy strict mode passes, ruff check passes. — Authored by egg |
|
egg finished successfully. View run logs |
There was a problem hiding this comment.
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
LogCollectorand unifiedRunLogdataclass - 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_pathThe 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 paths2. 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 thestatusvariable could be typed more precisely. Consider using a helper function that returnsLiteral["success", "failure", "cancelled", "running"]to avoid the ignore comment. -
In
analyze.py:361-367, when--output bothis 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-filewhen usingboth.
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
|
egg review completed. View run logs |
|
@james-in-a-box fix lint issues |
Reformatted ArgumentParser description to single line format. Authored-by: egg
|
Fixed the ruff format issue in — Authored by egg |
|
egg finished successfully. View run logs |
|
egg is investigating the Lint check failure... |
There was a problem hiding this comment.
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 separatelyThis 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 timeThe 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)
-
gha.py:569-575- Silent failure on JSON parse errorsThe 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.
-
local.py:857-contextlib.suppress(OSError)is overly broadThis 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)
-
config.py:941- Relative path forMETRICS_DIRMETRICS_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. -
analyze.py:359-361- File write without error handlingThe 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 acast()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
|
egg review completed. View run logs |
Quote $GITHUB_STEP_SUMMARY and group redirects to satisfy SC2086 and SC2129 shellcheck rules. Authored-by: egg
There was a problem hiding this comment.
Re-Review: Changes since 5d85165302a1db07fb14f7cb38941a3e1d9dd782
New Changes
The only change in this commit is shellcheck compliance in .github/workflows/self-improvement.yml:
- Grouped multiple
echostatements into single redirection blocks (SC2129) - Quoted
$GITHUB_STEP_SUMMARYvariable (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 separatelyThis 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 time2. [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 pathsPlease address these two items before merge.
— Authored by egg
|
egg review completed. View run logs |
|
egg autofix completed. View run logs |
|
@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
There was a problem hiding this comment.
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
|
egg finished successfully. View run logs |
There was a problem hiding this comment.
Re-Review Summary
No new commits since my last review at de55d5feebd0fbf95450f9c45bc38d019b68d7ca.
Verification
The two blocking issues from my previous review have been addressed:
-
completed_atassignment (local.py:151) - Now correctly set toNonefor local runs, avoiding misleading duration metrics. -
Path traversal protection (
local.py:136-142) - Addedresolve()+is_relative_to()validation to prevent reading files outsidelogs_dir.
No further changes needed. Ready for human review and merge.
— Authored by egg
|
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.
There was a problem hiding this comment.
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 pipefailThis 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:
-
completed_atassignment (collectors/local.py:151) - Now correctly set toNonefor local runs, avoiding misleading duration metrics. -
Path traversal protection (
collectors/local.py:136-142) - Addedresolve()+is_relative_to()validation to prevent reading files outsidelogs_dir.
No blocking issues. Ready for human review and merge.
— Authored by egg
|
egg review completed. View run logs |
Summary
Implements Phase 1 of the self-improvement cycle (#153):
LogCollectorABC andRunLogdataclassgh apicontainer_logging.pyinfrastructureself-improvement.yml) that runs analysis at 2 AM UTCWhat's Included
sandbox/egg_lib/self_improvement/collectors/base.pyLogCollectorABC,RunLogdataclasscollectors/gha.pycollectors/local.pyconfig.pyanalyze.py.github/workflows/self-improvement.ymlmetrics/self-improvement-metrics.jsontests/sandbox/test_self_improvement.pyUsage
Next Steps (Phase 2)
egg --execIssue: #153
Test plan:
pytest tests/sandbox/test_self_improvement.py)workflow_dispatchto verify GHA integrationAuthored-by: egg