Skip to content

Comments

Rule history#497

Merged
elie222 merged 4 commits intomainfrom
feat/rules-management-overhaul
Jun 10, 2025
Merged

Rule history#497
elie222 merged 4 commits intomainfrom
feat/rules-management-overhaul

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jun 9, 2025

Part of the move over to a different rule model

Summary by CodeRabbit

  • New Features

    • Introduced version history tracking for rules, enabling users to see previous versions and changes over time.
    • Added metadata to rule history, including trigger type (manual, AI, or system) and prompt text used for rule generation.
  • Enhancements

    • Rule creation and update actions now automatically record detailed change history for improved traceability.
    • Added support for tracking rule changes triggered by system actions and reply tracking features.

@vercel
Copy link

vercel bot commented Jun 9, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Jun 10, 2025 11:01am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 9, 2025

Caution

Review failed

The pull request is closed.

"""

Walkthrough

A rule versioning system is introduced by adding a RuleHistory model to the schema, enabling tracking of rule changes over time. Rule creation and update functions are updated to record history entries with a trigger type. Related utility functions and action handlers are modified to support this versioning and trigger type propagation. The cold email blocker rule is extended with a promptText field.

Changes

File(s) Change Summary
apps/web/prisma/schema.prisma Added promptText and history fields to Rule; introduced new RuleHistory model with versioning fields.
apps/web/prisma/migrations/20250609204102_rule_history/*.sql Added migration to add promptText column to Rule and create RuleHistory table with indexes and constraints.
apps/web/utils/rule/rule-history.ts Added createRuleHistory function and RuleHistoryTrigger type for recording rule history snapshots.
apps/web/utils/rule/rule.ts Updated rule creation/update functions to accept and propagate triggerType; call createRuleHistory.
apps/web/utils/actions/rule.ts Registered after callbacks in rule actions to record history entries with trigger type after create/update.
apps/web/utils/reply-tracker/enable.ts Passed triggerType: "system_creation" when creating a new reply required rule.
apps/web/app/(app)/[emailAccountId]/assistant/Rules.tsx Added promptText property initialized to null in coldEmailBlockerRule object.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ActionHandler
    participant RuleService
    participant RuleHistoryService
    participant Database

    User->>ActionHandler: Create or Update Rule
    ActionHandler->>RuleService: safeCreateRule / safeUpdateRule (with triggerType)
    RuleService->>Database: Create/Update Rule
    RuleService->>RuleHistoryService: createRuleHistory(rule, triggerType)
    RuleHistoryService->>Database: Insert RuleHistory entry
    RuleService->>ActionHandler: Return Rule
    ActionHandler->>User: Return Result
Loading

Possibly related PRs

Poem

In the warren where rules are spun,
Now every change is carefully done—
A snapshot is saved, a version preserved,
So history’s lessons are never unnerved.
With trigger types clear and actions tracked,
The bunny hops forward—no knowledge lacked!
🐇✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d0f1a8b and e799b19.

📒 Files selected for processing (1)
  • version.txt (1 hunks)

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/web/utils/rule/rule-history.ts (1)

32-49: Ensure serialization captures all relevant fields.

The current serialization manually selects specific fields from actions and categoryFilters. Consider whether this approach will scale well if new fields are added to these models in the future.

Consider documenting which fields are intentionally excluded or adding a comment about maintaining this serialization when the schema evolves.

apps/web/utils/rule/rule.ts (1)

231-247: Consider adding history tracking to rule action updates.

The updateRuleActions function modifies rule behavior but doesn't track history. Consider whether action-only updates should also be tracked for a complete audit trail.

If you want to track action updates, you could add the triggerType parameter and history tracking:

export async function updateRuleActions({
  ruleId,
  actions,
+ triggerType = "manual_update",
}: {
  ruleId: string;
  actions: CreateOrUpdateRuleSchemaWithCategories["actions"];
+ triggerType?: "ai_update" | "manual_update" | "system_update";
}) {
- return prisma.rule.update({
+ const rule = await prisma.rule.update({
    where: { id: ruleId },
    data: {
      actions: {
        deleteMany: {},
        createMany: { data: mapActionFields(actions) },
      },
    },
+   include: { actions: true, categoryFilters: true, group: true },
  });
+ 
+ await createRuleHistory({ rule, triggerType });
+ return rule;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7482eed and 4805b71.

📒 Files selected for processing (5)
  • apps/web/prisma/schema.prisma (2 hunks)
  • apps/web/utils/actions/rule.ts (3 hunks)
  • apps/web/utils/reply-tracker/enable.ts (1 hunks)
  • apps/web/utils/rule/rule-history.ts (1 hunks)
  • apps/web/utils/rule/rule.ts (9 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
apps/web/utils/actions/rule.ts (1)
apps/web/utils/rule/rule-history.ts (1)
  • createRuleHistory (15-73)
apps/web/utils/rule/rule-history.ts (1)
apps/web/utils/ai/rule/create-prompt-from-rule.ts (1)
  • RuleWithRelations (9-23)
apps/web/utils/rule/rule.ts (2)
apps/web/utils/ai/rule/create-rule-schema.ts (1)
  • CreateOrUpdateRuleSchemaWithCategories (126-129)
apps/web/utils/rule/rule-history.ts (1)
  • createRuleHistory (15-73)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (14)
apps/web/utils/reply-tracker/enable.ts (1)

116-116: LGTM! Clean integration with rule history system.

The addition of triggerType: "system_creation" correctly categorizes this as a system-generated rule creation, which aligns with the new rule history tracking functionality.

apps/web/utils/actions/rule.ts (3)

46-46: LGTM! Proper import for rule history functionality.


114-117: Excellent use of after() for non-blocking history tracking.

The rule creation history is properly tracked without blocking the main response. The "manual_creation" trigger type correctly categorizes user-initiated rule creation.


246-252: Consistent pattern for rule update history tracking.

Good implementation following the same pattern as rule creation, using "manual_update" trigger type to properly categorize user-initiated updates.

apps/web/utils/rule/rule-history.ts (2)

4-10: Well-defined trigger type enum with clear semantics.

The RuleHistoryTrigger union type comprehensively covers all rule change scenarios with descriptive names and helpful comments.


51-73: Comprehensive rule state capture with proper field mapping.

The function correctly maps all rule fields to the history record, maintaining a complete snapshot of the rule state at the time of change.

apps/web/prisma/schema.prisma (2)

253-255: Good additions to Rule model for history tracking.

The promptText field provides useful context, and the history relation is properly configured for one-to-many relationship with cascade behavior.


279-306: Well-designed RuleHistory model with comprehensive state capture.

The model effectively captures complete rule snapshots with appropriate:

  • Versioning strategy with unique constraint on [ruleId, version]
  • Efficient indexing on [ruleId, createdAt] for chronological queries
  • JSON fields for complex relations (actions, categoryFilters)
  • Cascade delete to maintain referential integrity

The use of String for triggerType (vs enum) provides flexibility while the TypeScript union type maintains type safety at the application level.

apps/web/utils/rule/rule.ts (6)

14-14: LGTM: Clean import addition for history tracking.

The import is correctly placed and follows the existing import organization pattern.


37-37: Well-designed parameter addition with sensible defaults.

The optional triggerType parameter with a default value of "ai_creation" maintains backwards compatibility while providing semantic clarity about the rule creation origin.

Also applies to: 43-43


87-87: Consistent parameter design for update operations.

The parameter follows the same pattern as the creation functions, with appropriate default value "ai_update" for update operations.

Also applies to: 93-93


111-111: Appropriate fallback behavior in duplicate name scenario.

Setting triggerType: "ai_creation" when falling back to creating a new rule (instead of updating) is semantically correct since a new rule is being created.


177-181: Proper history tracking implementation for rule creation.

The history tracking is correctly placed after the successful rule creation and properly awaited. The rule object includes all necessary relations for complete history tracking.


222-228: Well-implemented history tracking for rule updates.

The update operation correctly includes related entities and the history tracking is properly executed after the successful database update.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
apps/web/prisma/migrations/20250609204102_rule_history/migration.sql (2)

10-10: Constrain triggerType values
triggerType is free-text, which risks invalid entries. Define a Postgres ENUM or add a CHECK constraint listing allowed types (manual_creation, manual_update, system_creation, etc.).


24-25: Provide defaults for JSONB columns
To avoid null checks in application code, default actions and categoryFilters to an empty array ([]) or object ({}):

-   "actions" JSONB NOT NULL,
-   "categoryFilters" JSONB,
+   "actions" JSONB NOT NULL DEFAULT '[]',
+   "categoryFilters" JSONB NOT NULL DEFAULT '[]',
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 22aab63 and d0f1a8b.

📒 Files selected for processing (2)
  • apps/web/prisma/migrations/20250609204102_rule_history/migration.sql (1 hunks)
  • apps/web/utils/rule/rule-history.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/utils/rule/rule-history.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
apps/web/prisma/migrations/20250609204102_rule_history/migration.sql (3)

2-2: Ensure backward compatibility for promptText addition
Adding promptText as a nullable column is correct, but you may need to backfill existing Rule rows or provide a client-side default to avoid unexpected NULL values in reads.


31-34: Indexes align with query patterns and uniqueness requirements
The index on (ruleId, createdAt) optimizes history lookups, and the unique index on (ruleId, version) enforces version integrity.


37-37: Foreign key cascade rules are appropriate
Cascading deletes/updates on RuleHistory.ruleId ensure referential integrity when parent rules change or are removed.

@elie222 elie222 merged commit d9f4454 into main Jun 10, 2025
5 of 7 checks passed
@elie222 elie222 deleted the feat/rules-management-overhaul branch December 18, 2025 23:04
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