Skip to content

fix(guild-automation): post-merge stabilization for execution and locking - #179

Merged
LucasSantana-Dev merged 3 commits into
mainfrom
fix/pr171-postmerge-stabilization
Mar 12, 2026
Merged

LucasSantana-Dev merged 3 commits into
mainfrom
fix/pr171-postmerge-stabilization

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Mar 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Validation

  • npm run test --workspace=packages/backend -- tests/integration/routes/guildAutomation.test.ts
  • npm run type:check --workspace=packages/backend
  • npm run test --workspace=packages/bot -- src/functions/management/commands/guildconfig.spec.ts src/utils/guildAutomation/applyPlan.spec.ts src/utils/guildAutomation/captureGuildState.spec.ts

Summary by CodeRabbit

  • New Features

    • Guild automation apply/reconcile endpoints now execute real mutations with captured state, plan validation, and persisted run outcomes (completed, blocked, failed).
    • Enhanced role/channel reconciliation using ID-first matching with deterministic fallback; persists remapped IDs to prevent drift loops.
  • Bug Fixes

    • Guild automation execution locking now uses Redis with fail-closed behavior—explicitly surfaces infrastructure failures as 503 errors.

@vercel

vercel Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Mar 12, 2026 4:23pm

Request Review

@netlify

netlify Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for regal-bunny-0c8efe ready!

Name Link
🔨 Latest commit 844b38d
🔍 Latest deploy log https://app.netlify.com/projects/regal-bunny-0c8efe/deploys/69b2e849a5ddf400083dff65
😎 Deploy Preview https://deploy-preview-179--regal-bunny-0c8efe.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This change introduces a shared execution pipeline for guild automation's apply/reconcile flows, replacing in-memory locks with Redis token-based distributed locks, adding ID-first role/channel matching with deterministic fallback, and introducing specialized error handling for infrastructure failures.

Changes

Cohort / File(s) Summary
Documentation
CHANGELOG.md, README.md
Updated changelog and README to document new execution pipeline (capture → plan → apply), Redis-backed locking with fail-closed behavior, ID-first entity matching with persistent ID remapping, and execution status tracking (completed/blocked/failed).
Guild Automation Execution Service
packages/backend/src/services/GuildAutomationExecutionService.ts
New comprehensive service implementing the execution pipeline: captures guild state (roles, channels, onboarding, moderation, messages, reaction roles), applies desired configurations with role/channel creation/update/deletion, manages ID remapping for drift prevention, handles module-specific updates, and returns diagnostics with remapped manifest. Includes Discord API wrapper, state transformation, and protection flag handling.
Guild Automation Routes & Integration
packages/backend/src/routes/guildAutomation.ts, packages/backend/tests/integration/routes/guildAutomation.test.ts
Updated routes to derive actualState by validating body input or capturing current state, delegates execution to new service via executor callbacks, maps domain-specific errors (manifest not found, capture required, lock unavailable, execution failed) to appropriate HTTP responses, and added integration tests for execution pipeline, state capture, and error handling.
Guild Automation Core Service
packages/shared/src/services/guildAutomation/service.ts
Refactored locking from in-memory to Redis token-based (acquireLock returns string token, releaseLock accepts token), introduced error types (GuildAutomationManifestNotFoundError, GuildAutomationCaptureRequiredError), added resolveActualState helper for manifest derivation, extended createApplyRun with optional executor function enabling custom execution logic with diagnostics and manifest remapping.
Guild Automation Types
packages/shared/src/services/guildAutomation/types.ts
Strengthened GuildAutomationStatus type safety by replacing string types with union types (AutomationRunType, AutomationRunStatus, AutomationModule, DriftSeverity) for latestRun and drift severity fields.
Redis Client Infrastructure
packages/shared/src/services/redis/client.ts, packages/shared/src/services/redis/types.ts
Added two new public Redis methods: setNxPx (atomic set with existence check and TTL) and delIfValueMatches (Lua-scripted deletion with value verification) to support distributed lock token management with error handling and guards for missing client.
Error Framework
packages/shared/src/types/errors/guildAutomation.ts, packages/shared/src/types/errors/index.ts, packages/shared/src/types/errors/errors.spec.ts
Introduced structured error hierarchy: base GuildAutomationError with code/retryable/context, plus five specialized subclasses (InvalidManifestPayload, ManifestNotFound, CaptureRequired, ApplyLocked, LockUnavailable) with predefined messages, error codes, and contextual guildId. Exported error codes map and type union; added unit tests.
Bot Module Refactoring
packages/bot/src/functions/automod/commands/index.ts, packages/bot/src/functions/moderation/commands/index.ts
Updated module specifiers from 'path' and 'url' to 'node:path' and 'node:url' for Node.js built-in modules.
Guild Automation Apply Plan
packages/bot/src/utils/guildAutomation/applyPlan.ts
Refactored applyRolesAndChannels logic by extracting helpers (syncRoles, syncChannels, deleteUnmanagedEntities), introduced ApplyContext type for unified parameter passing, created modular handlers (handleOnboardingModule, handleRolesModule, etc.) replacing inline logic, and consolidated control flow through new handler delegation pattern.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Route as Routes/guildAutomation
    participant Service as GuildAutomationExecutionService
    participant Discord as Discord API
    participant DB as Database
    participant Redis as Redis

    Client->>Route: PUT /plan or /apply or /reconcile
    Note over Route: Validate request

    alt actualState in body
        Route->>Route: Use provided actualState
    else actualState missing
        Route->>Service: captureGuildAutomationState(guildId)
        Service->>Discord: Fetch roles, channels, onboarding, etc.
        Service->>DB: Query moderation, messages, reaction roles
        Service->>Service: Transform to GuildAutomationManifestDocument
        Service-->>Route: Return captured state
    end

    Route->>Redis: acquireLock(guildId)
    alt Lock acquired
        Redis-->>Route: Return token
        Route->>Service: executeApplyPlan(plan, desired, actual, allowProtected)
        
        Service->>Service: Apply onboarding module
        Service->>Service: Apply roles module (ID-first matching)
        Service->>Discord: Create/update/delete roles
        Service->>Service: Apply channels module
        Service->>Discord: Create/update/delete channels
        Service->>Service: Apply moderation, messages, reaction roles
        Service->>DB: Persist remapped manifest IDs
        
        Service-->>Route: Return { diagnostics, remappedManifest }
        Route->>DB: Update run with results
        Route->>Redis: releaseLock(token)
    else Lock unavailable
        Route-->>Client: 503 Service Unavailable
    end
    
    Route-->>Client: Return run with status (completed/blocked/failed)
Loading
sequenceDiagram
    participant Redis as Redis Lock
    participant Service as Shared Service
    
    Note over Redis,Service: Lock Acquisition Flow
    
    Service->>Redis: setNxPx(key: lockKey, value: token, ttl: 30s)
    alt Lock set successfully
        Redis-->>Service: true
        Service->>Service: Proceed with operation
    else Key already exists
        Redis-->>Service: false
        Service-->>Service: Throw GuildAutomationLockUnavailableError
    end
    
    Note over Redis,Service: Lock Release Flow
    
    Service->>Redis: delIfValueMatches(key: lockKey, expectedValue: token)
    alt Value matches token
        Redis-->>Service: true (key deleted)
    else Value doesn't match or key missing
        Redis-->>Service: false
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

backend, shared, bot, infra, size/xl

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: post-merge stabilization involving Redis-backed distributed locks and execution pipeline integration for guild automation apply/reconcile workflows.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/pr171-postmerge-stabilization
📝 Coding Plan for PR comments
  • Generate coding plan

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
10.8% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@coderabbitai coderabbitai Bot added the infra label Mar 12, 2026
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
11.4% Coverage on New Code (required ≥ 80%)
9.2% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@LucasSantana-Dev
LucasSantana-Dev merged commit 06b3c5e into main Mar 12, 2026
13 of 15 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/pr171-postmerge-stabilization branch March 12, 2026 16:27
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…king (#179)

* fix(shared): harden guild automation locks and domain errors

* fix(backend): execute automation apply and reconcile mutations

* refactor(bot): reduce automation apply complexity and update docs

This branch was successfully deployed

1 active deployment
Preview — 844b38d6 Deployed Mar 12, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant