Skip to content

Fix multiline template string#756

Merged
elie222 merged 3 commits intomainfrom
fix/templates
Sep 7, 2025
Merged

Fix multiline template string#756
elie222 merged 3 commits intomainfrom
fix/templates

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 7, 2025

Summary by CodeRabbit

  • New Features
    • Added exported helpers and a structured AI-argument response type; AI rule-arg generation now returns validated object results.
  • Bug Fixes
    • Improved template-variable detection (including multiline) and adjusted env parsing to handle empty log scopes more predictably.
  • Refactor
    • Centralized template-variable pattern and unified its use across UI and utilities.
  • Tests
    • Expanded coverage for fully/partially dynamic-field detection.
  • Chores
    • Bumped app version to v2.9.2.

@vercel
Copy link

vercel bot commented Sep 7, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 7, 2025 7:42pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 7, 2025

Walkthrough

Adds a shared TEMPLATE_VARIABLE_PATTERN constant and switches template detection/splitting to use it across template utilities, risk helpers, and RuleForm; exports two new risk helpers with tests; converts AI argument generation from text to object-based responses and adjusts related types and retry policy; tweaks env transform and bumps version to v2.9.2.

Changes

Cohort / File(s) Summary
Template pattern + utils
apps/web/utils/template.ts, apps/web/utils/risk.ts
Add and export TEMPLATE_VARIABLE_PATTERN; hasVariables uses new RegExp(TEMPLATE_VARIABLE_PATTERN); add/export isFullyDynamicField and isPartiallyDynamicField in risk.ts using the shared pattern.
UI: RuleForm
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
Replace hard-coded regex and split /(\{\{.*?\}\})/g with RegExp(TEMPLATE_VARIABLE_PATTERN); remove explicit inline enabled: boolean type annotation on toggle handler.
AI: choose-rule generation
apps/web/utils/ai/choose-rule/ai-choose-args.ts, apps/web/utils/ai/choose-rule/choose-args.ts
Switch from text-based to object-based generation (createGenerateObject / generateObject), add ActionArgResponse export/type, change aiGenerateArgs return type, increase retry policy (maxRetries:3, delayMs:1000), change prompt composition to use printConditions/printStaticConditions; import type in choose-args.ts and remove local type alias.
Tests
apps/web/utils/risk.test.ts
Add tests covering isFullyDynamicField and isPartiallyDynamicField for single/multi-line, partial/full, and malformed cases.
Env transform
apps/web/env.ts
Change NEXT_PUBLIC_LOG_SCOPES transform to return undefined for falsy values and split non-empty values (no longer returns [""] for empty string).
Metadata
version.txt
Bump version from v2.9.1 to v2.9.2.

Sequence Diagram(s)

sequenceDiagram
  participant UI as RuleForm / Caller
  participant AI as LLM service
  participant GEN as ai-choose-args.generateObject
  participant COM as choose-args.combineActionsWithAiArgs

  rect #EDF8F2
    UI->>GEN: request generateObject(prompt, schema)
    note right of GEN: retries (maxRetries:3, delayMs:1000)
    GEN->>AI: send schema-based request
    AI-->>GEN: object response (aiResponse.object)
    GEN->>UI: return ActionArgResponse | undefined
  end

  rect #FFF7E6
    UI->>COM: combineActionsWithAiArgs(actions, result, draft)
    COM->>UI: returns actions with AI args applied
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I twitch my whiskers at tidy regex lore,
One pattern to match, not hard-coded anymore.
AI learns objects, retries a bit more,
Tests hop in, envs cleaned, version bumped for sure.
Carrots for constants! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/templates

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.

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: 0

🧹 Nitpick comments (5)
apps/web/utils/template.ts (2)

1-2: Good multiline fix; export precompiled regex literals to avoid new RegExp and allocations

Align with guideline “Use regular expression literals rather than the RegExp constructor” and provide shared, precompiled variants for test/split/anchored use. This also silences the static tool’s “regexp-from-variable” warning.

Apply:

 // Regex pattern to match template variables like {{variable}} including multi-line
-export const TEMPLATE_VARIABLE_PATTERN = "\\{\\{[\\s\\S]*?\\}\\}";
+export const TEMPLATE_VARIABLE_PATTERN = "\\{\\{[\\s\\S]*?\\}\\}";
+// Precompiled regexes (prefer literals over RegExp constructor)
+export const TEMPLATE_VARIABLE_RE = /\{\{[\s\S]*?\}\}/;
+export const TEMPLATE_VARIABLE_SPLIT_RE = /(\{\{[\s\S]*?\}\})/g;
+export const TEMPLATE_VARIABLE_ANCHORED_RE = /^\{\{[\s\S]*?\}\}$/;

6-6: Use the shared literal instead of constructing RegExp per call

Avoids per-call allocations and follows the regex-literal guideline.

-export const hasVariables = (text: string | undefined | null) =>
-  text ? new RegExp(TEMPLATE_VARIABLE_PATTERN).test(text) : false;
+export const hasVariables = (text: string | undefined | null) =>
+  text ? TEMPLATE_VARIABLE_RE.test(text) : false;
apps/web/utils/risk.ts (1)

4-4: Reuse precompiled regexes instead of new RegExp

Removes repeated RegExp construction on hot paths and keeps logic centralized in template utils.

-import { TEMPLATE_VARIABLE_PATTERN } from "@/utils/template";
+import {
+  TEMPLATE_VARIABLE_RE,
+  TEMPLATE_VARIABLE_ANCHORED_RE,
+} from "@/utils/template";
@@
 function isFullyDynamicField(field: string) {
-  return new RegExp(`^${TEMPLATE_VARIABLE_PATTERN}$`).test(field);
+  return TEMPLATE_VARIABLE_ANCHORED_RE.test(field);
 }
 
 function isPartiallyDynamicField(field: string) {
-  return new RegExp(TEMPLATE_VARIABLE_PATTERN).test(field);
+  return TEMPLATE_VARIABLE_RE.test(field);
 }

Also applies to: 169-174

apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (2)

56-56: Avoid constructing the RegExp in render; import a shared split regex

Keeps render cheap and consistent with utils.

-import { hasVariables, TEMPLATE_VARIABLE_PATTERN } from "@/utils/template";
+import { hasVariables, TEMPLATE_VARIABLE_SPLIT_RE } from "@/utils/template";
@@
-                        .split(
-                          new RegExp(`(${TEMPLATE_VARIABLE_PATTERN})`, "g"),
-                        )
+                        .split(TEMPLATE_VARIABLE_SPLIT_RE)

Also applies to: 1315-1317


1294-1301: Optional UX: preserve current label value when toggling AI

Avoids clearing the user’s input when flipping the switch.

 onChange={(enabled) => {
-  setValue(
-    `actions.${index}.${field.name}`,
-    enabled
-      ? { value: "", ai: true }
-      : { value: "", ai: false },
-  );
+  const current = watch(`actions.${index}.${field.name}.value`) || "";
+  setValue(`actions.${index}.${field.name}`, { value: current, ai: enabled });
 }}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between baae770 and a363021.

📒 Files selected for processing (4)
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (3 hunks)
  • apps/web/utils/risk.ts (2 hunks)
  • apps/web/utils/template.ts (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (17)
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • version.txt
  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • version.txt
  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/risk.ts
  • apps/web/utils/template.ts
  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
**/*.{html,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx
🧠 Learnings (1)
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Keep related AI functions co-located; extract shared logic into utilities; document complex AI logic with clear comments

Applied to files:

  • apps/web/utils/risk.ts
🧬 Code graph analysis (2)
apps/web/utils/risk.ts (1)
apps/web/utils/template.ts (1)
  • TEMPLATE_VARIABLE_PATTERN (2-2)
apps/web/app/(app)/[emailAccountId]/assistant/RuleForm.tsx (1)
apps/web/utils/template.ts (1)
  • TEMPLATE_VARIABLE_PATTERN (2-2)
🪛 ast-grep (0.38.6)
apps/web/utils/risk.ts

[warning] 172-172: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(TEMPLATE_VARIABLE_PATTERN)
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

apps/web/utils/template.ts

[warning] 5-5: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(TEMPLATE_VARIABLE_PATTERN)
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🔇 Additional comments (1)
version.txt (1)

1-1: Version bump looks good

Matches the scope of the PR.

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: 0

🧹 Nitpick comments (5)
apps/web/utils/risk.ts (2)

4-4: Prefer exporting a precompiled RegExp (or at least compile once) instead of passing a pattern string around.

Static analysis flagged constructing a RegExp from a variable. The pattern is constant and trusted, but per guidelines use a regex literal or a shared precompiled RegExp to avoid runtime recompilation and to silence the warning.

Preferred (in apps/web/utils/template.ts):

// export a RegExp, not a string
export const TEMPLATE_VARIABLE_RE = /\{\{[\s\S]*?\}\}/;

Then here:

-import { TEMPLATE_VARIABLE_PATTERN } from "@/utils/template";
+import { TEMPLATE_VARIABLE_RE } from "@/utils/template";

And in isPartiallyDynamicField:

-  return new RegExp(TEMPLATE_VARIABLE_PATTERN).test(field);
+  return TEMPLATE_VARIABLE_RE.test(field);

If you want a minimal local change in this file only, precompile once at module scope:

// near the top of the file
const TEMPLATE_VARIABLE_RE = new RegExp(TEMPLATE_VARIABLE_PATTERN);

and update isPartiallyDynamicField to use it (see diff below).


173-175: Avoid creating a new RegExp on every call.

This is on a hot path for risk checks. Precompile once and reuse.

Apply:

-export function isPartiallyDynamicField(field: string) {
-  return new RegExp(TEMPLATE_VARIABLE_PATTERN).test(field);
-}
+// add at module scope (see note above) and then:
+export function isPartiallyDynamicField(field: string) {
+  return TEMPLATE_VARIABLE_RE.test(field);
+}
apps/web/utils/risk.test.ts (3)

79-92: Fix misleading test name: expected level is “low,” not “medium.”

The title says “medium” but assertions expect “low.” Rename for clarity.

-      name: "returns medium risk for dynamic recipient without automation",
+      name: "returns low risk for dynamic recipient without automation",

94-107: Fix misleading test name: expected level is “low,” not “medium.”

Same mismatch here.

-      name: "returns medium risk for dynamic cc/bcc without automation",
+      name: "returns low risk for dynamic cc/bcc without automation",

226-284: Nice coverage on fully-dynamic edge cases. Consider adding a trailing/leading whitespace case.

Add a case like " {{name}} " to pin the trim behavior explicitly.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a363021 and 445457a.

📒 Files selected for processing (2)
  • apps/web/utils/risk.test.ts (2 hunks)
  • apps/web/utils/risk.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

Include security tests in your test suites to verify authentication, authorization, and error handling.

Files:

  • apps/web/utils/risk.test.ts
**/*.test.{ts,js,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

**/*.test.{ts,js,tsx,jsx}: Tests are colocated next to the tested file (e.g., dir/format.ts and dir/format.test.ts)
Use vi.mock("server-only", () => ({})); to mock the server-only module in tests
Mock @/utils/prisma in tests using vi.mock("@/utils/prisma") and use the provided prisma mock
Mock external dependencies in tests
Clean up mocks between tests
Do not mock the Logger

Files:

  • apps/web/utils/risk.test.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/risk.test.ts
  • apps/web/utils/risk.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.

Files:

  • apps/web/utils/risk.test.ts
🧠 Learnings (2)
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI code paths (e.g., return unchanged when no AI processing is needed)

Applied to files:

  • apps/web/utils/risk.test.ts
📚 Learning: 2025-06-23T12:27:30.570Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/__mocks__/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.

Applied to files:

  • apps/web/utils/risk.test.ts
🧬 Code graph analysis (2)
apps/web/utils/risk.test.ts (1)
apps/web/utils/risk.ts (2)
  • isFullyDynamicField (168-171)
  • isPartiallyDynamicField (173-175)
apps/web/utils/risk.ts (1)
apps/web/utils/template.ts (1)
  • TEMPLATE_VARIABLE_PATTERN (2-2)
🪛 ast-grep (0.38.6)
apps/web/utils/risk.ts

[warning] 173-173: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(TEMPLATE_VARIABLE_PATTERN)
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🔇 Additional comments (3)
apps/web/utils/risk.ts (1)

167-171: LGTM: simpler, newline-safe “fully dynamic” check.

The trim + startsWith/endsWith approach matches multi-line templates and aligns with the updated tests (e.g., multiple tokens but the whole string is templated).

apps/web/utils/risk.test.ts (2)

2-7: LGTM: exporting and testing the helpers is a good move.

Coverage now directly validates both “fully” and “partially” dynamic detection.


286-353: LGTM: partially-dynamic detection covers multi-line and malformed cases well.

No changes needed.

@elie222
Copy link
Owner Author

elie222 commented Sep 7, 2025

@claude review

@claude
Copy link

claude bot commented Sep 7, 2025

Claude encountered an error —— View job


I'll analyze this and get back to you.

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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web/utils/ai/choose-rule/choose-args.ts (1)

74-83: Harden against AI failure: catch and continue with existing actions/draft.

If aiGenerateArgs throws after retries, we should degrade gracefully (like the draft path above) instead of failing the whole flow.

-  const result = await aiGenerateArgs({
-    email: getEmailForLLM(message),
-    emailAccount,
-    selectedRule,
-    parameters,
-    modelType,
-  });
-
-  return combineActionsWithAiArgs(selectedRule.actions, result, draft);
+  let result: ActionArgResponse | undefined;
+  try {
+    result = await aiGenerateArgs({
+      email: getEmailForLLM(message),
+      emailAccount,
+      selectedRule,
+      parameters,
+      modelType,
+    });
+  } catch (error) {
+    logger.error("Failed to generate AI args", {
+      email: emailAccount.email,
+      threadId: message.threadId,
+      error,
+    });
+  }
+  return combineActionsWithAiArgs(selectedRule.actions, result, draft);
apps/web/utils/ai/choose-rule/ai-choose-args.ts (1)

92-110: Retry policy: also retry on transient HTTP errors (429/5xx) in addition to InvalidArgumentError.

This improves resilience without masking persistent schema issues.

-  const aiResponse = await withRetry(
+  const aiResponse = await withRetry(
     () =>
       generateObject({
         ...modelOptions,
         system,
         prompt,
         schemaDescription: "The arguments for the rule",
         schema: z.object(
           Object.fromEntries(
             parameters.map((p) => [`${p.type}-${p.actionId}`, p.parameters]),
           ),
         ),
       }),
     {
-      retryIf: (error: unknown) => InvalidArgumentError.isInstance(error),
+      retryIf: (error: unknown) =>
+        InvalidArgumentError.isInstance(error) || isTransientError(error),
       maxRetries: 3,
       delayMs: 1000,
     },
   );

Add below in this file:

function isTransientError(error: unknown): boolean {
  const status =
    (error as any)?.status ??
    (error as any)?.cause?.status ??
    (error as any)?.response?.status;
  return typeof status === "number" && [408, 429, 500, 502, 503, 504].includes(status);
}
🧹 Nitpick comments (3)
apps/web/env.ts (1)

170-173: Trim and de-dupe scopes when splitting (keep your undefined behavior).

Your guard correctly maps "" → undefined. To avoid tokens like " api, debug " or empty entries, trim and filter on split.

-      .transform((value) => {
-        if (!value) return;
-        return value.split(",");
-      }),
+      .transform((value) => {
+        if (!value) return;
+        return value
+          .split(",")
+          .map((s) => s.trim())
+          .filter(Boolean);
+      }),
apps/web/utils/ai/choose-rule/choose-args.ts (1)

82-83: Reuse shared TEMPLATE_VARIABLE_PATTERN in parseTemplate to avoid regex drift.

Other modules moved to a shared pattern. Keep this in sync and also preserve whitespace/newlines in prompts with a single-pass replace. Also replaces forEach with for...of per guidelines.

TypeScript (outside the shown hunk):

import { TEMPLATE_VARIABLE_PATTERN } from "@/utils/template";

export function parseTemplate(template: string): {
  aiPrompts: string[];
  fixedParts: string[];
} {
  const regex = new RegExp(TEMPLATE_VARIABLE_PATTERN, "g");
  const aiPrompts: string[] = [];
  const fixedParts: string[] = [];
  let lastIndex = 0;

  for (const m of template.matchAll(regex)) {
    const start = m.index ?? 0;
    fixedParts.push(template.slice(lastIndex, start));
    // m[0] is the full "{{...}}", slice off braces and trim
    aiPrompts.push(m[0].slice(2, -2).trim());
    lastIndex = start + m[0].length;
  }
  fixedParts.push(template.slice(lastIndex));
  return { aiPrompts, fixedParts };
}

// When building the zod .describe() template:
const templateWithVars = value.replace(
  new RegExp(TEMPLATE_VARIABLE_PATTERN, "g"),
  (_match) => {
    idx += 1;
    const prompt = aiPrompts[idx - 1]!;
    return `{{var${idx}: ${prompt}}}`;
  },
);
apps/web/utils/ai/choose-rule/ai-choose-args.ts (1)

112-120: Tighten log wording.

“No tool call found” is from the tools API; here we expect an object. Change to “No object returned”.

-  if (!result) {
-    logger.warn("No tool call found", {
+  if (!result) {
+    logger.warn("No object returned", {
       ...loggerOptions,
       aiResponse,
     });
     return;
   }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 445457a and a86718a.

📒 Files selected for processing (3)
  • apps/web/env.ts (1 hunks)
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts (6 hunks)
  • apps/web/utils/ai/choose-rule/choose-args.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/env.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
apps/web/**/{.env.example,env.ts,turbo.json}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Add environment variables to .env.example, env.ts, and turbo.json

Files:

  • apps/web/env.ts
apps/web/**/{.env.example,env.ts}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Client-side environment variables: Prefix with NEXT_PUBLIC_

Files:

  • apps/web/env.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/env.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
apps/web/env.ts

📄 CodeRabbit inference engine (.cursor/rules/environment-variables.mdc)

apps/web/env.ts: When adding a new environment variable, add it to apps/web/env.ts in the appropriate section: use server for server-only variables, and for client-side variables, use the client section and also add to experimental__runtimeEnv.
Client-side environment variables must be prefixed with NEXT_PUBLIC_ and added to both the client and experimental__runtimeEnv sections in apps/web/env.ts.

Files:

  • apps/web/env.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/env.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/env.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/env.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/env.ts
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
apps/web/utils/{ai,llms}/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/llm.mdc)

apps/web/utils/{ai,llms}/**/*.ts: Place LLM-related implementation code under apps/web/utils/ai or apps/web/utils/llms
Keep system and user prompts separate; system defines role/task, user contains data/context
Always validate LLM responses with a specific Zod schema
Use descriptive scoped loggers per feature and log inputs/outputs with appropriate levels and context
Implement early returns for invalid inputs and use proper error types with logging
Add fallbacks for AI failures and include retry logic for transient errors using withRetry
Format prompts with XML-like tags; remove excessive whitespace; truncate overly long inputs; keep formatting consistent
Use TypeScript types for all parameters/returns and define interfaces for complex IO structures
Keep related AI functions co-located; extract shared logic into utilities; document complex AI logic with clear comments
Call LLMs via createGenerateObject; pass system, prompt, and a Zod schema; return the validated result.object
Derive model options using getModel(...) and pass them to createGenerateObject and the generate call

Files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
🧠 Learnings (8)
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/**/{.env.example,env.ts} : Client-side environment variables: Prefix with `NEXT_PUBLIC_`

Applied to files:

  • apps/web/env.ts
📚 Learning: 2025-07-18T15:04:50.520Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/environment-variables.mdc:0-0
Timestamp: 2025-07-18T15:04:50.520Z
Learning: Applies to apps/web/env.ts : Client-side environment variables must be prefixed with `NEXT_PUBLIC_` and added to both the `client` and `experimental__runtimeEnv` sections in `apps/web/env.ts`.

Applied to files:

  • apps/web/env.ts
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Call LLMs via createGenerateObject; pass system, prompt, and a Zod schema; return the validated result.object

Applied to files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Derive model options using getModel(...) and pass them to createGenerateObject and the generate call

Applied to files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Keep related AI functions co-located; extract shared logic into utilities; document complex AI logic with clear comments

Applied to files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
  • apps/web/utils/ai/choose-rule/choose-args.ts
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Add fallbacks for AI failures and include retry logic for transient errors using withRetry

Applied to files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Always validate LLM responses with a specific Zod schema

Applied to files:

  • apps/web/utils/ai/choose-rule/ai-choose-args.ts
📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.419Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI code paths (e.g., return unchanged when no AI processing is needed)

Applied to files:

  • apps/web/utils/ai/choose-rule/choose-args.ts
🧬 Code graph analysis (1)
apps/web/utils/ai/choose-rule/ai-choose-args.ts (2)
apps/web/utils/llms/index.ts (2)
  • createGenerateObject (118-166)
  • withRetry (298-337)
apps/web/utils/stringify-email.ts (1)
  • stringifyEmail (4-27)
🔇 Additional comments (3)
apps/web/utils/ai/choose-rule/choose-args.ts (1)

12-15: Type import alignment — LGTM.

apps/web/utils/ai/choose-rule/ai-choose-args.ts (2)

38-44: Response shape — LGTM.

Clear contract keyed by ${type}-${actionId} with per-field varN maps.


165-198: No action needed—conditionalOperator is a required, defaulted field on Rule and thus always present on RuleWithActions.

@elie222 elie222 merged commit 4e4e378 into main Sep 7, 2025
13 checks passed
@elie222 elie222 deleted the fix/templates branch September 7, 2025 19:44
@coderabbitai coderabbitai bot mentioned this pull request Oct 21, 2025
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

Comments