-
Notifications
You must be signed in to change notification settings - Fork 37
feat: Add per-repository auto-push control for multi-repo sessions (RHOAIENG-37639) #457
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Fixes a bug where AgenticSessions remained stuck in "Running" phase when
their Jobs exceeded activeDeadlineSeconds and were terminated by Kubernetes.
The operator's monitorJob function now checks Job status conditions for
JobFailed type with DeadlineExceeded reason. When detected, it:
- Updates session phase to "Failed"
- Preserves the DeadlineExceeded reason in session conditions
- Sets completion time
- Cleans up Job and related resources
This ensures the UI accurately reflects timed-out sessions instead of
displaying them as perpetually running. Users can view the specific
failure reason ("DeadlineExceeded") in the session details modal under
Reconciliation Conditions.
Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Updated `agenticsessions-crd.yaml` to support per-repository git
configuration and auto-push settings.
The repos array items now support both legacy and new structures for
backwards compatibility:
New Structure (Preferred):
- input: Object with url and branch for source repository
- output: Optional object with url and branch for push target (e.g., fork)
- autoPush: Boolean flag (default: false) for per-repo auto-push control
Legacy Structure (Deprecated):
- url: Direct repository URL (marked as deprecated)
- branch: Direct branch name (marked as deprecated)
Key Features
- Per-repo granularity: Each repository can now have its own auto-push
setting
- Fork support: Explicit output configuration for pushing to a different
repository than the source
- Backwards compatible: Old sessions with {url, branch} format will
continue to work
- Overrides session-level default: Per-repo autoPush overrides the
session-level autoPushOnComplete flag
- YAML validated: Schema passes both Python YAML parser and kubectl
validation
Example Usage:
New format:
```yaml
spec:
repos:
- input:
url: "https://github.com/org/repo"
branch: "main"
output:
url: "https://github.com/user/fork"
branch: "feature-branch"
autoPush: true
```
Legacy format (still supported):
```yaml
spec:
repos:
- url: "https://github.com/org/repo"
branch: "main"
```
Update backend type system to support new repo format with separate input/output configuration and per-repo autoPush flags while maintaining full backwards compatibility with legacy format. Changes: - Add RepoLocation type for git repository locations (input/output) - Update SimpleRepo to support both legacy (url/branch) and new (input/output/autoPush) formats - Add NormalizeRepo() method to convert legacy to new format with validation - Add ToMapForCR() method to convert SimpleRepo to CR map format - Update session creation to normalize repos before storing in CR - Update repo parsing to handle both formats in parseSpec() - Add ParseRepoMap() helper for parsing CR maps to SimpleRepo - Add comprehensive unit tests (28 test cases) covering: - Legacy format normalization - New format validation - Round-trip conversions - Error handling for empty URLs - Backwards compatibility Backwards Compatibility: - Legacy repos (url/branch) continue to work unchanged - Repos are normalized to new format during creation - Both formats supported when reading from CRs - Per-repo autoPush defaults to session-level autoPushOnComplete Related to RHOAIENG-37639 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Refactor repository configuration parsing to support both legacy and new formats with better error handling and testability. Changes: - Extract parseRepoConfig() function for testable parsing logic - Add JSON tags to repoConfig/repoLocation for correct serialization - Fix REPOS_JSON env var to marshal parsed repos with autoPush flags - Add defaultBranch constant to eliminate magic strings - Add comprehensive validation and error logging with context - Refactor tests to call production code instead of duplicating logic - Add edge case tests for empty URLs, mixed formats, invalid types Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
…ncement Completes RHOAIENG-37639 runner implementation for reliable git push operations. Adds autoPush flag extraction from REPOS_JSON and injects git push instructions into Claude's system prompt when autoPush is enabled. Changes: - Extract autoPush flag from REPOS_JSON in _get_repos_config() * Defaults to False when not specified (safe default) * Preserves backward compatibility with repos without autoPush field - Enforce autoPush flag in _push_results_if_any() * Skip git push operations for repos with autoPush=false * Log skip decisions for debugging - Add system prompt enhancement in _build_workspace_context_prompt() * Inject "Git Operations - IMPORTANT" section when any repo has autoPush=true * Include step-by-step commit/push instructions * List repos with autoPush enabled * Provide git push best practices (retry logic, verification) - Improve error logging in _get_repos_config() exception handler - Add comprehensive docstring to _build_workspace_context_prompt() Testing: - Added TestGetReposConfig class (8 tests) * autoPush extraction (true/false/missing) * Mixed autoPush flags * Edge cases (empty, invalid JSON, legacy format) - Added TestSystemPromptInjection class (4 tests) * Git instructions appear when autoPush=true * Git instructions omitted when autoPush=false * Correct repo list generation * Empty repos edge case - Added TestPushBehavior class (3 tests) * Push skipped when autoPush=false * Push executed when autoPush=true * Mixed autoPush settings in multi-repo scenarios - All tests use mocks to avoid external dependencies - Standalone verify_autopush.py for manual verification Root Cause Fix: This addresses the primary issue from RHOAIENG-37639 - Claude Code doesn't push changes because the system prompt doesn't instruct it to commit and push when done. The system prompt enhancement ensures Claude receives explicit instructions to commit and push for repos with autoPush=true, matching the behavior of Claude Code Web. Integration Points: - Operator passes autoPush flag via REPOS_JSON environment variable - Runner extracts flag and uses it to control push behavior - System prompt dynamically adapts based on autoPush settings Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Frontend type updates to support structured SessionRepo format with input/output separation for fork workflows. Type Changes: - Add RepoLocation type for input/output configuration - Update SessionRepo to structured format with input/output/autoPush - Add pushed flag to ReconciledRepo status - Mark autoPushOnComplete as deprecated in favor of per-repo autoPush Component Updates: - OverviewTab: Use repo.input/output properties, fix push button logic - page.tsx: Extract repo name from repo.input.url - repositories-accordion: Use structured SessionRepo type Utilities Added: - getRepoDisplayName(): DRY extraction of repo name logic - hasValidOutputConfig(): Validates output differs from input - DEFAULT_BRANCH constant Bug Fix: - OverviewTab push button now validates output config differs from input instead of just checking existence (line 471) Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Implement frontend UI for per-repository auto-push control with new SessionRepo structure (input/output/autoPush). This completes the frontend portion of the multi-repo auto-push feature. Changes: - Update SessionRepo types to use input/output structure - Add per-repo auto-push toggle in repository dialog - Add visual indicators (green badges) for auto-push status - Replace session-level checkbox with "default for new repos" setting - Add advanced options for output repository configuration - Show output summary when advanced options collapsed - Fix TypeScript import issue in types/api/sessions.ts Key Features: - Per-repository auto-push control via checkbox in repo dialog - Visual badges show which repos will auto-push in repository list - Session-level "default auto-push" setting inherited by new repos - Advanced options support push to different fork/branch - Output destination displayed inline when configured - ARIA attributes for accessibility (aria-expanded) Technical Notes: - Frontend uses clean types only (no backward compatibility) - Backend computes autoPushOnComplete from per-repo flags - All repos can be removed (consistent with optional schema) - Optional chaining used consistently for safety - Zod schema validates new SessionRepo structure Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Implement one-time migration of all AgenticSessions from legacy repo
format to new v2 structure on operator startup. Migration runs before
watches start and is fully idempotent.
Migration Logic:
- Converts {url, branch} → {input: {url, branch}, autoPush: false}
- Checks ALL repos per session (handles mixed formats)
- Skips active sessions (Running/Creating phases)
- Validates migrated data before updating CRs
- Adds annotation "ambient-code.io/repos-migrated: v2"
- Returns nil even with errors (logs failures, continues startup)
Safety Features:
- Idempotent: annotation prevents duplicate migrations
- Defensive: phase check skips in-flight sessions
- Resilient: individual failures don't block other sessions
- Validated: comprehensive checks before CR updates
- Logged: detailed progress and error reporting
Implementation:
- migration.go: MigrateAllSessions(), sessionNeedsMigration(),
migrateSession(), addMigrationAnnotation()
- main.go: calls migration before starting watchers
- migration_test.go: 12 comprehensive tests covering happy
paths, error scenarios, edge cases, and idempotency
Test Coverage:
- Empty cluster, single/multiple sessions, multiple namespaces
- Legacy format, v2 format, already migrated, mixed formats
- Invalid repo formats, missing fields, partial failures
- Active sessions, sessions without repos, idempotency
Code Review Changes:
- Check ALL repos (not just first) for mixed-format detection
- Add phase check to skip Running/Creating sessions
- Add validation of migrated data before CR update
- Return nil on errors (resilient startup, failures logged)
- Add error path test coverage (4 new tests)
Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push
Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
TestingPart 1: Prepare Test Environment for Migration
Part 2: Deploy Platform and Verify Migration
Part 3: Test New Multi-Repo Functionality
|
This comment has been minimized.
This comment has been minimized.
…-37639)
Critical improvements:
- Add type safety check in migration logic to prevent panics
- Document security model for operator privilege usage
Major improvements:
- Add Kubernetes Events for migration tracking (visible in kubectl describe)
- Add backend validation preventing identical input/output repo configs
- Add inline error display in repository dialog for validation errors
Minor improvements:
- Replace magic "main" strings with DEFAULT_BRANCH constant across codebase
- Document migration annotations in AgenticSession CRD
- Add annotation tracking for active sessions skipped during migration
Enhancements:
- Add test coverage for mixed v1/v2 repo format edge case
- Enhance Claude system prompt with explicit "DO NOT push" list
Files modified:
- operator/internal/handlers/migration.go
- operator/internal/handlers/migration_test.go
- backend/types/{common,session}.go + tests
- backend/handlers/{content,repo_seed}.go
- frontend/src/app/projects/[name]/sessions/new/repository-dialog.tsx
- manifests/base/crds/agenticsessions-crd.yaml
- runners/claude-code-runner/wrapper.py
Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push
Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Claude Code ReviewSummaryThis PR implements per-repository auto-push functionality for multi-repo sessions, migrating from a single session-level Overall Assessment: ✅ Approved with minor recommendations Issues by Severity🚫 Blocker IssuesNone - This PR is ready to merge. 🔴 Critical Issues1. Migration Security Model - Service Account Usage The migration uses the operator's service account to update CRs across all namespaces: sessionList, err := config.DynamicClient.Resource(gvr).List(ctx, metav1.ListOptions{})Analysis: While the PR description mentions this is intentional for operator startup, this violates the principle from CLAUDE.md:
However, this is acceptable because:
Recommendation: Document this exception in ADR-0002 (User Token Authentication) as a specific exception for operator-initiated migrations at startup. 🟡 Major Issues1. Error Handling - Migration Swallows Individual Errors // Note: We return nil even with errors to allow operator startup to continue.
return nilIssue: Individual migration failures are logged but don't prevent operator startup. This could leave some sessions in an inconsistent state. Recommendation: Add a status condition or metric to track migration failures so operators can identify and manually fix sessions that failed to migrate. Consider: // Add condition to failed sessions
updateSessionCondition(session, "MigrationFailed", "True", err.Error())2. Type Safety - Direct Type Assertions Without Checking Multiple direct type assertions without the if inputMap, hasInput := repoMap["input"].(map[string]interface{}); hasInput {Analysis: This is acceptable because if url, ok := inputMap["url"].(string); ok { // ✅ GoodRecommendation: Verify all type assertions in parseRepoConfig follow the safe pattern. 3. Frontend Type Definition - Deprecated Field Still Present /**
* @deprecated Use per-repo autoPush flags in SessionRepo instead.
*/
autoPushOnComplete?: boolean;Issue: While properly deprecated, keeping this field could confuse developers about which field to use. Recommendation: Add runtime validation to warn if 🔵 Minor Issues1. Code Quality - Makefile Color Output Changes The Makefile now uses Recommendation: Consider splitting unrelated Makefile improvements into a separate PR for cleaner git history. 2. Test Coverage - No Frontend Unit Tests The PR adds extensive backend (314 lines) and operator (628 lines) tests, but no frontend component tests for the repository dialog UI changes. Recommendation: Add Cypress or Jest tests for:
3. Documentation - Missing ADR Update This is a significant feature change (per-repo auto-push control) but doesn't update any ADRs. Recommendation: Add a new ADR (e.g.,
4. Logging - Inconsistent Log Levels log.Printf("ERROR: Failed to check migration status for session %s/%s: %v", namespace, name, err)Issue: Uses string prefix "ERROR:" instead of structured logging with log levels. Recommendation: Use a structured logger (e.g., logr or zap) for consistent log levels: logger.Error(err, "Failed to check migration status", "namespace", namespace, "name", name)5. Resource Management - No OwnerReferences on Migration Events Events created during migration don't have OwnerReferences set: event := &corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s.%s", session.GetName(), metav1.Now().Format("20060102150405")),
Namespace: session.GetNamespace(),
},
// No OwnerReferences!Issue: Events won't be automatically cleaned up when the session is deleted. Recommendation: Add OwnerReferences to migration events: event.OwnerReferences = []metav1.OwnerReference{{
APIVersion: session.GetAPIVersion(),
Kind: session.GetKind(),
Name: session.GetName(),
UID: session.GetUID(),
}}Positive Highlights🌟 Exceptional Work:
RecommendationsPriority 1 (Before Merge)
Priority 2 (Follow-up PR)
Priority 3 (Nice to Have)
Final VerdictThis is high-quality work that demonstrates:
The identified issues are minor and don't block merging. The migration strategy is sound, the implementation is defensive, and the test coverage is excellent. Recommendation: Approve and merge. Address Priority 1 items in follow-up commits if desired. Generated with Claude Code 🔍 View AI decision process (logs available for 90 days) 📋 View memory system files loaded (click to expand)What Amber Loaded for Code ReviewAmber automatically loaded these repository standards from the memory system:
Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines. |
Addressed reviewer feedback before merge: 1. Critical: Document migration security exception in ADR-0002 - Added operator exception section explaining startup migration privilege model - Links to detailed security documentation in migration.go - Clarifies when operator service account is acceptable vs user tokens 2. Major: Audit all type assertions for safety - Verified all type assertions use safe two-value pattern with ok checks - Confirmed optional fields handle missing values correctly - Frontend TypeScript uses proper optional chaining 3. Major: Enhance migration failure tracking with structured logging - Added prominent header/footer separators for visibility - Separated active session skips from already-migrated skips in counters - Added detailed breakdown: total, migrated, skipped, active skipped, errors - Success/warning indicators (✅/⚠) based on error count - Clear messaging for error recovery on next restart Files modified: - docs/adr/0002-user-token-authentication.md (operator exception documented) - operator/internal/handlers/migration.go (enhanced logging, separate counters) Deferred to follow-up PRs: - Frontend type deprecation warnings (technical debt, non-blocking) - Frontend unit tests for repository dialog (test coverage improvement) - ADR for per-repo auto-push design (documentation) - Structured logging conversion (codebase-wide refactor) - OwnerReferences on Event objects (resource lifecycle enhancement) All operator tests pass. Migration logging verified in test output. Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Claude Code ReviewSummaryThis PR implements per-repository auto-push control for multi-repo sessions, replacing the single session-level Overall Assessment: The code quality is excellent, with strong adherence to project patterns, comprehensive testing (956 new test lines), and thoughtful security considerations. A few minor issues need attention before merge. Issues by Severity🚫 Blocker IssuesNone - Code is safe to merge after addressing critical issues below. 🔴 Critical Issues1. Migration Uses Service Account Without User Context (
|
Implemented 4 critical issues identified in code review: 1. Defensive Type Checking (migration.go:180-186) - Added validation before loop to catch type errors early - Validates first element type with clearer error messages - Prevents confusing errors during migration 2. Output Validation in ParseRepoMap (helpers.go:118-135) - Added validation that output differs from input (URL or branch) - Prevents git push failures from identical input/output configs - Matches validation already present in NormalizeRepo 3. URL Sanitization for Display (repository-dialog.tsx, utils/repo.ts) - Added sanitizeUrlForDisplay() utility function - Redacts embedded credentials (username/password) with asterisks - Applied to output URL display to prevent token exposure in UI 4. Duplicate Import Cleanup (wrapper.py:88,101) - Removed duplicate 're' imports inside _sanitize_user_context() - Module-level import at line 12 already provides re module - Cleaned up both user_id and user_name validation sections Files modified: - operator/internal/handlers/migration.go (defensive type check) - backend/handlers/helpers.go (output validation) - frontend/src/utils/repo.ts (sanitization utility) - frontend/src/app/projects/[name]/sessions/new/repository-dialog.tsx (use sanitization) - runners/claude-code-runner/wrapper.py (remove duplicate imports) All operator and backend tests pass. Changes focus only on code directly related to per-repo auto-push feature (no fix creep). Deferred to follow-up PR (Priority 2 & 3 per reviewer): - Standardize error event recording in migration - Add comprehensive ParseRepoMap unit tests - Document naming conventions - Add loading state to auto-push checkbox Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Claude Code ReviewSummaryOverall Assessment: STRONG APPROVAL ✅ This PR implements per-repository auto-push control with exceptional quality. The implementation demonstrates outstanding adherence to project standards, comprehensive testing (956 new test lines), excellent error handling, and thoughtful security practices. The V1→V2 migration is safely designed with proper idempotency and edge case handling. Key Strengths:
Issues by Severity🚫 Blocker IssuesNone - Code is production-ready. 🔴 Critical IssuesNone - No critical violations of project standards found. 🟡 Major IssuesNone - Implementation follows all established patterns from CLAUDE.md. 🔵 Minor Issues1. Error Message Consistency (Low Priority)Location: // Current (inconsistent):
return SimpleRepo{}, fmt.Errorf("cannot normalize repo with empty input.url")
return SimpleRepo{}, fmt.Errorf("cannot normalize repo with empty url")
// Suggested (consistent):
return SimpleRepo{}, fmt.Errorf("failed to normalize repo: empty input URL")
return SimpleRepo{}, fmt.Errorf("failed to normalize repo: empty URL")Impact: Minor - consistency improvement only Positive Highlights1. 🏆 Exceptional Test Coverage
2. 🔐 Security ExcellenceToken Handling:
RBAC & Authorization:
3. 💎 Code QualityBackend (Go):
Frontend (TypeScript):
Operator (Go):
4. 🛠️ Migration Safety// Excellent defensive coding:
// 1. Idempotency check
if annotations[MigrationAnnotation] == MigrationVersion {
continue
}
// 2. Active session protection
if phase == "Running" || phase == "Creating" {
// Skip and annotate
}
// 3. Validation before update
// Comprehensive validation of migrated data
// 4. Non-fatal errors
return nil // Allow operator startup to continue5. 📦 Backward Compatibility
6. 🎨 UI/UX Excellence
RecommendationsPriority 1: Address Before MergeNone - Code is ready to merge as-is. Priority 2: Consider for Follow-Up PR
Priority 3: Future Enhancements
Security Checklist
Performance AnalysisMigration Performance:
Architecture ReviewData Model Evolution: # Before (v1):
repos:
- url: "https://github.com/org/repo.git"
branch: "main"
# After (v2):
repos:
- input:
url: "https://github.com/org/repo.git"
branch: "main"
autoPush: false
output: # Optional for fork workflows
url: "https://github.com/user/fork.git"
branch: "feature-branch"Benefits:
Final VerdictScore: 9.5/10
Recommendation: ✅ APPROVE FOR MERGE This PR represents exceptional engineering quality. The minor recommendations are purely enhancements and should not block merge. All critical project standards from CLAUDE.md, security-standards.md, and pattern files are properly followed. Files Reviewed: 27 files (+4,357/-426 lines) 🔍 View AI decision process (logs available for 90 days) 📋 View memory system files loaded (click to expand)What Amber Loaded for Code ReviewAmber automatically loaded these repository standards from the memory system:
Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines. |
Resolved conflict in Makefile: - Kept printf style for consistency with existing code - Added pod waiting logic from main - Added retry loops for health checks from main
Claude Code ReviewSummaryThis PR implements per-repository auto-push control for multi-repo sessions (RHOAIENG-37639). Overall assessment: well-executed PR with strong code quality, comprehensive testing, and thoughtful migration strategy. However, there are several security, architecture, and code quality issues that should be addressed before merge. Issues by SeverityBlocker Issues1. Migration Uses Operator Service Account Without RBAC Validation
2. Panic Risk in Migration Type Assertions
Critical Issues3. Migration Validation Order
4. Inconsistent Error Handling
5. Missing Token Redaction
6. NormalizeRepo Behavior Undocumented
Major Issues7. Frontend Type Safety: Verify no any types in repository-dialog.tsx Minor Issues10. Makefile terminal detection Positive Highlights✅ Excellent test coverage: 956 new lines RecommendationsPriority 1 (Must Fix):
Priority 2 (Should Fix): Priority 3 (Follow-up): Overall: 8/10 - Excellent implementation with security/validation gaps Generated with Claude Code 🔍 View AI decision process (logs available for 90 days) 📋 View memory system files loaded (click to expand)What Amber Loaded for Code ReviewAmber automatically loaded these repository standards from the memory system:
Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines. |
Fix misleading documentation in NormalizeRepo function that incorrectly stated autoPush is always set to false. The actual implementation uses the sessionDefaultAutoPush parameter value. CHANGES MADE: - Update NormalizeRepo documentation to accurately reflect that autoPush uses the sessionDefaultAutoPush parameter, not a hardcoded false value REVIEW FEEDBACK NOT IMPLEMENTED (with rationale): 1. Blocker 1 - Migration RBAC Validation: RATIONALE: Migration intentionally uses operator service account at startup (standard K8s operator pattern). Operator already has RBAC to reconcile CRs it owns. Adding per-session RBAC would be redundant and violate operator design patterns. Security model is documented in migration.go:35-42. 2. Blocker 2 - Panic Risk in repos[0]: RATIONALE: False positive. Code at migration.go:182 explicitly checks len(repos) > 0 before accessing repos[0] on line 183. No panic risk. 3. Critical 3 - Migration Validation Order: RATIONALE: migratedRepos is a local slice, not persisted until after validation passes (lines 283-306). K8s CR update only happens at line 326 if all validation succeeds. Migration is atomic - all-or-nothing. 4. Critical 4 - Inconsistent Error Handling: RATIONALE: Function signature is (bool, error) where bool indicates "needs migration". Returning (false, nil) for "no spec" or "no repos" is correct - these are not error conditions, just "doesn't need migration" states. Error return is reserved for actual failures. 5. Critical 5 - Missing Token Redaction: RATIONALE: No token logging exists in provisionRunnerTokenForSession. Function only logs metadata (SA names, secret names). Adding token length logging would be redundant when no tokens are logged. ENHANCEMENTS ACKNOWLEDGED (for follow-up): - Active session age validation for stuck sessions - Integration migration tests - CRD validation for autoPush field - Migration user documentation Part of RHOAIENG-37639: Multi-repo support with per-repo auto-push Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Claude Code ReviewSummaryThis PR implements per-repository auto-push functionality for multi-repo sessions (RHOAIENG-37639). The implementation is comprehensive and well-architected, spanning frontend UI, backend API, operator migration, and runner execution. The code quality is high with extensive test coverage (956 new test lines), defensive error handling, and strong backward compatibility guarantees. Overall Assessment: APPROVE with minor recommendations The implementation follows project patterns well, includes thorough testing, and addresses the root cause (missing git push instructions in system prompt). The v1→v2 migration is safe, idempotent, and well-documented. Issues by Severity🚫 Blocker IssuesNone - This PR is ready to merge. 🔴 Critical IssuesNone - All critical patterns followed correctly. 🟡 Major Issues1. Frontend: Missing Loading State on Auto-Push Checkbox (repository-dialog.tsx:110-120)The auto-push checkbox doesn't show a loading/disabled state during save operations, which could allow users to toggle it multiple times during network latency. Recommendation: Add Rationale: Prevents race conditions and provides visual feedback during async operations. 2. Backend: ParseRepoMap Needs Comprehensive Unit Tests (handlers/helpers.go:79-151)The Recommendation: Add
Rationale: This function is critical for CR parsing and is exported for testing, indicating intent for test coverage. 3. Operator: Event Recording Should Follow Standardized Pattern (migration.go:356-387)Migration events are recorded with inline Event struct creation. The codebase likely has (or should have) a standardized event recording utility. Recommendation: Extract event recording to a shared utility function like
Rationale: DRY principle, easier to maintain event formatting consistency across operator. 🔵 Minor Issues1. Frontend: Type Deprecation Warnings Missing (types/api/sessions.ts)The Recommendation: Add deprecation warnings: /**
* @deprecated Use per-repo autoPush instead. This field is computed from repo flags.
*/
autoPushOnComplete?: boolean;Rationale: Helps developers understand the migration path when using autocomplete. 2. Backend: Inconsistent Naming Conventions (types/session.go:140)Function named Recommendation: Consider renaming to func (r *SimpleRepo) ToV2Format(sessionDefaultAutoPush bool) (SimpleRepo, error)Rationale: More idiomatic Go naming for transformation methods. 3. Operator: Migration Could Use Structured Logging (migration.go:45-160)Migration uses unstructured Recommendation: Consider migrating to structured logging in a follow-up PR: logger.Info("Migrating session", "namespace", namespace, "name", name)
logger.Error(err, "Migration failed", "namespace", namespace, "name", name)Rationale: Easier to parse logs programmatically, better observability in production. 4. Runner: Duplicate Import Removed But Consider Module-Level Organization (wrapper.py:88,101)The duplicate Recommendation: Extract common regex patterns to module-level constants: _USER_ID_PATTERN = re.compile(r'[^a-zA-Z0-9@._-]')
_CONTROL_CHARS_PATTERN = re.compile(r'[\x00-\x1f\x7f-\x9f]')Rationale: Improves performance (compile once) and makes patterns reusable. Positive Highlights✅ Excellent Architecture & Design
✅ Documentation & Maintainability
✅ Follows Project Patterns
RecommendationsHigh Priority (Address Before Merge)None - All critical issues resolved in latest commits. Medium Priority (Address in Follow-up PR)
Low Priority (Technical Debt)
Code Quality Metrics
Final VerdictLGTM 🎉 This PR demonstrates excellent engineering practices:
The minor issues identified are polish items that can be addressed in follow-up PRs without blocking this substantial feature. Recommendation: Merge when ready. Follow-up PRs can address the minor improvements suggested above. Generated with Claude Code 🔍 View AI decision process (logs available for 90 days) 📋 View memory system files loaded (click to expand)What Amber Loaded for Code ReviewAmber automatically loaded these repository standards from the memory system:
Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines. |
|
@adalton please rebase from main. Unfortunately we have some conflicts that need to resolve before we merge. Thank you! Also, please feel free to add a https://github.com/ambient-code/platform/milestones Release target milestone when we're feeling comfortable with targeting a release. Thanks! |
- Resolved conflicts in Makefile (echo vs printf, backend pod label) - Resolved conflicts in content.go (added pathutil import) - Resolved conflicts in sessions_test.go (kept main's comprehensive test suite) - Resolved conflicts in repositories-accordion.tsx (kept main's uploadedFiles feature)
- Standardize Makefile to use echo consistently (removed 115 printf statements) - Fix repositories-accordion.tsx to use SessionRepo type and correct property access - Prevents runtime error from undefined repo.url access Fixes identified in code review after merging main branch. The Makefile now consistently uses @echo instead of mixed @printf "%b\n" statements for better CI compatibility. The repositories accordion now properly uses SessionRepo type with repo.input.url instead of custom Repository type with repo.url. Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Claude Code ReviewSummaryThis PR implements per-repository auto-push control for multi-repo sessions. The implementation is comprehensive, well-tested, and follows established patterns. The code quality is excellent with strong type safety, defensive programming, and comprehensive test coverage (956 new test lines). The migration strategy is well-designed and safe. Issues by Severity🚫 Blocker IssuesNone - This PR is ready for merge from a code quality and security perspective. 🔴 Critical IssuesNone - All critical security patterns are correctly implemented. 🟡 Major IssuesNone - The implementation follows all established patterns correctly. 🔵 Minor Issues
Positive HighlightsExcellent Security Practices✅ Migration security model: Lines 35-44 in migration.go provide clear documentation of the security rationale. Active sessions are correctly skipped to avoid interference. ✅ Type-safe unstructured access: Migration code consistently uses ✅ Defensive validation: Comprehensive validation before CR updates (migration.go:283-306) ✅ No token logging: All backend and operator code correctly avoids logging sensitive data Code Quality Excellence✅ Comprehensive testing: 956 new test lines across:
✅ Idempotent migration: Migration correctly checks for existing annotations and v2 format (migration.go:98-125) ✅ Error handling patterns: All error handling follows established patterns:
✅ Type safety: Frontend uses proper TypeScript types with no Architecture Adherence✅ Backend patterns:
✅ Frontend patterns:
✅ Operator patterns:
RecommendationsPriority 1 (Before Merge) - COMPLETED ✅All critical items have been addressed. No blockers. Priority 2 (Post-Merge Enhancements)
Priority 3 (Future Considerations)
Testing CoverageExcellent test coverage:
Test scenarios covered:
Code Quality Metrics
Final AssessmentAPPROVE ✅ This is an exemplary PR that demonstrates:
The per-repository auto-push feature is well-implemented, thoroughly tested, and ready for production deployment. The migration strategy is safe, idempotent, and properly handles edge cases. Review generated by Claude Code using project memory system (CLAUDE.md, context files, and pattern catalogs) 🔍 View AI decision process (logs available for 90 days) 📋 View memory system files loaded (click to expand)What Amber Loaded for Code ReviewAmber automatically loaded these repository standards from the memory system:
Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines. |
@bobbravo2 Sorry it took a while to get this done. I'll check the milestones tomorrow AM. |
Summary
Implements per-repository auto-push functionality for multi-repo sessions, replacing the single session-level
autoPushOnCompleteflag with granular per-repo control.Users can now independently configure which repositories should auto-push on session completion.
Resolves: RHOAIENG-37639
What Changed
Frontend (NextJS + Shadcn UI)
SessionRepowithinput/output/autoPushstructureBackend (Go)
SimpleReposupportsInput,Output,AutoPushfieldsautoPushOnCompletecomputation from per-repo flagsOperator (Go)
{url, branch}->{input: {url, branch}, autoPush: false}ambient-code.io/repos-migrated: v2Runner (Python)
autoPush: truetest_repo_autopush.pyCRD Updates
{url, branch}(v1) and{input, output, autoPush}(v2)Key Features
Migration Details
The operator performs a one-time automatic migration on startup:
Before (v1 format):
Migration is:
Breaking Changes
None - Full backward compatibility maintained:
Code Quality
Files Changed
27 files changed, +3,996 insertions, -658 deletions
Major additions:
Updated:
Documentation
Generated with https://claude.com/claude-code
Co-Authored-By: Claude Sonnet 4.5 [email protected]