refactor(agents): move prescriptive content from knowledge-base to rules (#26925)
* refactor(agents): move prescriptive content from knowledge-base to rules - Create architecture-page-level-auth.md for Next.js auth checks - Create data-prefer-select-over-include.md for Prisma query optimization - Create performance-dayjs-usage.md for Day.js performance guidelines - Create quality-avoid-barrel-imports.md for import best practices - Update knowledge-base.md to reference rules directory - Remove duplicated prescriptive content from knowledge-base.md Co-Authored-By: [email protected] <[email protected]> * chore(agents): remove redundant rules reference from knowledge-base Co-Authored-By: [email protected] <[email protected]> * docs: add agents/rules reference to AGENTS.md extended documentation Co-Authored-By: [email protected] <[email protected]> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
9affeef99e
commit
f691258a5c
6 files changed
+194
-124
No files matched your search
@@ -233,6 +233,7 @@ import { ProfileRepository } from "@calcom/features/profile/repositories/Profile
|
||||
For detailed information, see the `agents/` directory:
|
||||
|
||||
- **[agents/README.md](agents/README.md)** - Architecture overview and patterns
|
||||
- **[agents/rules/](agents/rules/)** - Modular engineering rules (performance, architecture, data layer, etc.)
|
||||
- **[agents/commands.md](agents/commands.md)** - Complete command reference
|
||||
- **[agents/knowledge-base.md](agents/knowledge-base.md)** - Domain knowledge and best practices
|
||||
- **[agents/coding-standards.md](agents/coding-standards.md)** - Coding standards with examples
|
||||
@@ -306,59 +306,6 @@ export function useFeatureOptIn() {
|
||||
|
||||
This separation ensures that `packages/features` remains portable and can be used by other apps (like `apps/api/v2`) without pulling in web-specific dependencies like tRPC React hooks.
|
||||
|
||||
## Basic Performance Guidelines
|
||||
|
||||
- Aim for O(n) or O(n log n) complexity, avoid O(n²)
|
||||
- Use database-level filtering instead of JavaScript filtering
|
||||
- Consider pagination for large datasets
|
||||
- Use database transactions for related operations
|
||||
|
||||
## When querying database
|
||||
|
||||
Prefer Select over Include:
|
||||
|
||||
```typescript
|
||||
// ✅ Good - Use select for performance and security
|
||||
const booking = await prisma.booking.findFirst({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ❌ Bad - Include fetches all fields
|
||||
const booking = await prisma.booking.findFirst({
|
||||
include: {
|
||||
user: true, // This gets ALL user fields
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Avoid barrel imports
|
||||
|
||||
```typescript
|
||||
// ❌ Bad - Avoid importing from index.ts barrel files
|
||||
import { BookingService, UserService } from "./services";
|
||||
|
||||
// ✅ Good - Import directly from source files
|
||||
import { BookingService } from "./services/BookingService";
|
||||
import { UserService } from "./services/UserService";
|
||||
|
||||
|
||||
// ❌ Bad
|
||||
import { Button } from "@calcom/ui";
|
||||
|
||||
// ✅ Good - Import directly from source files
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
```
|
||||
|
||||
## File Naming Conventions
|
||||
|
||||
### Repository Files
|
||||
@@ -376,74 +323,3 @@ import { Button } from "@calcom/ui/components/button";
|
||||
- **Types**: PascalCase with `.types.ts` suffix (e.g., `Booking.types.ts`)
|
||||
- **Tests**: Same as source file + `.test.ts` or `.spec.ts`
|
||||
- **Avoid**: Dot-suffixes like `.service.ts`, `.repository.ts` (except for tests, types, specs)
|
||||
|
||||
## When using Day.js
|
||||
|
||||
```typescript
|
||||
// ⚠️ Slow in performance-critical code (loops)
|
||||
dates.map((date) => dayjs(date).add(1, "day").format());
|
||||
|
||||
// ✅ Better - Use .utc() for performance
|
||||
dates.map((date) => dayjs.utc(date).add(1, "day").format());
|
||||
|
||||
// ✅ Best - Use native Date when possible
|
||||
dates.map((date) => new Date(date.valueOf() + 24 * 60 * 60 * 1000));
|
||||
```
|
||||
|
||||
## Next.js App Directory: Authorisation Checks in Pages
|
||||
|
||||
This can include checking session.user exists or session.org etc.
|
||||
|
||||
### TL;DR:
|
||||
|
||||
Don’t put permission checks in layout.tsx! Always put them directly inside your page.tsx or relevant server components for every restricted route.
|
||||
|
||||
|
||||
### Why Not to Use Layouts for Permission Checks
|
||||
|
||||
* Layouts don’t intercept all requests: If a user navigates directly or refreshes a protected route, layout checks might be skipped, exposing sensitive content.
|
||||
* APIs and server actions bypass layouts: Sensitive operations running on the server can’t be guarded by checks in the layout.
|
||||
* Risk of data leaks: Only page/server-level checks ensure that unauthorized users never get protected data.
|
||||
|
||||
### ✅ How To Secure Routes (The Right Way)
|
||||
|
||||
* Check permissions inside page.tsx or the actual server component.
|
||||
* Perform all session/user/role validation before querying or rendering sensitive content.
|
||||
* Redirect or return nothing to unauthorized users, before running restricted code.
|
||||
|
||||
### 🛠️ Example: Page-Level Permission Check
|
||||
|
||||
|
||||
```tsx
|
||||
// app/admin/page.tsx
|
||||
|
||||
import { redirect } from "next/navigation";
|
||||
import { getUserSession } from "@/lib/auth";
|
||||
|
||||
export default async function AdminPage() {
|
||||
const session = await getUserSession();
|
||||
|
||||
if (!session || session.user.role !== "admin") {
|
||||
redirect("/"); // Or show an error
|
||||
}
|
||||
|
||||
// Protected content here
|
||||
return <div>Welcome, Admin!</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### 🧠 Key Reminders
|
||||
|
||||
* Put permission guards in every restricted page.tsx.
|
||||
* Never assume layouts are secure for guarding data.
|
||||
* Validate users before any sensitive queries or rendering.
|
||||
|
||||
|
||||
## Avoid using Dayjs if you don’t need to be strictly tz aware.
|
||||
|
||||
When doing logic like Dayjs.startOf(".."), you can instead use date-fns' `startOfMonth(dateObj)` / `endOfDay(dateObj)`;
|
||||
When doing logic that depends on Browser locale, use i18n.language (prefer to deconstruct) like: `const { i18n: { language } } = useLocale();`, in combination with built-in Intl.
|
||||
|
||||
Note that with Date, you’re dealing with System time, so it’s not suited to everywhere (such as in the Booker, where instead we’ll likely migrate to Temporal) - but in most cases the above are suitable.
|
||||
|
||||
The main reason for doing so is that Dayjs uses a useful, but highly risky plugin system, which has led us to create `@calcom/dayjs` - this is heavy however, because it pre-loads ALL plugins, including locale handling. It's a non-ideal solution to a problem that unfortunately exists due to Dayjs.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Page-Level Authorization Checks in Next.js
|
||||
impact: CRITICAL
|
||||
impactDescription: Prevents unauthorized access to sensitive data
|
||||
tags: security, nextjs, authorization, architecture
|
||||
---
|
||||
|
||||
## Page-Level Authorization Checks in Next.js
|
||||
|
||||
**Impact: CRITICAL (Prevents unauthorized access to sensitive data)**
|
||||
|
||||
Authorization checks must be performed in `page.tsx` or server components, never in `layout.tsx`. Layouts don't intercept all requests and can be bypassed.
|
||||
|
||||
**Incorrect (auth checks in layout):**
|
||||
|
||||
```tsx
|
||||
// app/admin/layout.tsx - DON'T DO THIS
|
||||
export default async function AdminLayout({ children }) {
|
||||
const session = await getUserSession();
|
||||
if (!session?.user.role === "admin") {
|
||||
redirect("/");
|
||||
}
|
||||
return <div>{children}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (auth checks in page):**
|
||||
|
||||
```tsx
|
||||
// app/admin/page.tsx
|
||||
import { redirect } from "next/navigation";
|
||||
import { getUserSession } from "@/lib/auth";
|
||||
|
||||
export default async function AdminPage() {
|
||||
const session = await getUserSession();
|
||||
|
||||
if (!session || session.user.role !== "admin") {
|
||||
redirect("/"); // Or show an error
|
||||
}
|
||||
|
||||
// Protected content here
|
||||
return <div>Welcome, Admin!</div>;
|
||||
}
|
||||
```
|
||||
|
||||
**Why layouts are unsafe for auth:**
|
||||
- Layouts don't intercept all requests (direct navigation, refreshes)
|
||||
- APIs and server actions bypass layouts entirely
|
||||
- Risk of data leaks if layout check is skipped
|
||||
|
||||
**Key rules:**
|
||||
- Check permissions inside every restricted `page.tsx`
|
||||
- Validate session/user/role before querying sensitive data
|
||||
- Redirect or return nothing to unauthorized users before running restricted code
|
||||
|
||||
Reference: [Next.js Security Best Practices](https://nextjs.org/docs/app/building-your-application/authentication)
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Prefer Select Over Include in Prisma Queries
|
||||
impact: HIGH
|
||||
impactDescription: Reduces data transfer and improves query performance
|
||||
tags: prisma, database, performance, security
|
||||
---
|
||||
|
||||
## Prefer Select Over Include in Prisma Queries
|
||||
|
||||
**Impact: HIGH (Reduces data transfer and improves query performance)**
|
||||
|
||||
Using `select` instead of `include` in Prisma queries fetches only the fields you need, improving performance and preventing accidental exposure of sensitive data.
|
||||
|
||||
**Incorrect (using include fetches all fields):**
|
||||
|
||||
```typescript
|
||||
const booking = await prisma.booking.findFirst({
|
||||
include: {
|
||||
user: true, // This gets ALL user fields including sensitive ones
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**Correct (using select for specific fields):**
|
||||
|
||||
```typescript
|
||||
const booking = await prisma.booking.findFirst({
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- **Performance**: Smaller payloads, faster queries
|
||||
- **Security**: Prevents accidental exposure of sensitive fields (e.g., `credential.key`)
|
||||
- **Clarity**: Makes data requirements explicit
|
||||
|
||||
**Exception:** Use `include` only when you genuinely need all fields from a relation, which is rare.
|
||||
|
||||
Reference: [Cal.com Engineering Standards](https://cal.com/blog/engineering-in-2026-and-beyond)
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
title: Day.js Performance Guidelines
|
||||
impact: HIGH
|
||||
impactDescription: Significant performance improvement in date-heavy operations
|
||||
tags: performance, dates, dayjs
|
||||
---
|
||||
|
||||
## Day.js Performance Guidelines
|
||||
|
||||
**Impact: HIGH (Significant performance improvement in date-heavy operations)**
|
||||
|
||||
Day.js with the `@calcom/dayjs` wrapper is heavy because it pre-loads all plugins including locale handling. Use alternatives when strict timezone awareness isn't required.
|
||||
|
||||
**Incorrect (using Day.js unnecessarily):**
|
||||
|
||||
```typescript
|
||||
// Slow in performance-critical code (loops)
|
||||
dates.map((date) => dayjs(date).add(1, "day").format());
|
||||
|
||||
// Using Dayjs for simple date operations
|
||||
const startOfMonth = dayjs().startOf("month");
|
||||
```
|
||||
|
||||
**Correct (using performant alternatives):**
|
||||
|
||||
```typescript
|
||||
// Use .utc() for better performance when timezone doesn't matter
|
||||
dates.map((date) => dayjs.utc(date).add(1, "day").format());
|
||||
|
||||
// Use native Date when possible
|
||||
dates.map((date) => new Date(date.valueOf() + 24 * 60 * 60 * 1000));
|
||||
|
||||
// Use date-fns for simple operations
|
||||
import { startOfMonth, endOfDay } from "date-fns";
|
||||
const monthStart = startOfMonth(dateObj);
|
||||
const dayEnd = endOfDay(dateObj);
|
||||
|
||||
// For browser locale, use Intl with i18n
|
||||
const { i18n: { language } } = useLocale();
|
||||
new Intl.DateTimeFormat(language).format(date);
|
||||
```
|
||||
|
||||
**When to use Day.js:**
|
||||
- When you need strict timezone awareness (e.g., in the Booker)
|
||||
- When working with complex timezone conversions
|
||||
- When the performance impact is negligible (non-loop operations)
|
||||
|
||||
**When to avoid Day.js:**
|
||||
- Simple date arithmetic
|
||||
- Date formatting without timezone concerns
|
||||
- Performance-critical loops over dates
|
||||
|
||||
Reference: [Cal.com Engineering Standards](https://cal.com/blog/engineering-in-2026-and-beyond)
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Avoid Barrel Imports
|
||||
impact: MEDIUM
|
||||
impactDescription: Improves tree-shaking and reduces bundle size
|
||||
tags: imports, performance, bundling
|
||||
---
|
||||
|
||||
## Avoid Barrel Imports
|
||||
|
||||
**Impact: MEDIUM (Improves tree-shaking and reduces bundle size)**
|
||||
|
||||
Barrel files (index.ts that re-export from multiple modules) can hurt tree-shaking and increase bundle sizes. Import directly from source files instead.
|
||||
|
||||
**Incorrect (importing from barrel files):**
|
||||
|
||||
```typescript
|
||||
// Importing from index.ts barrel files
|
||||
import { BookingService, UserService } from "./services";
|
||||
|
||||
// Importing from @calcom/ui barrel
|
||||
import { Button } from "@calcom/ui";
|
||||
```
|
||||
|
||||
**Correct (importing directly from source):**
|
||||
|
||||
```typescript
|
||||
// Import directly from source files
|
||||
import { BookingService } from "./services/BookingService";
|
||||
import { UserService } from "./services/UserService";
|
||||
|
||||
// Import directly from component path
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
```
|
||||
|
||||
Reference: [Cal.com Engineering Standards](https://cal.com/blog/engineering-in-2026-and-beyond)
|
||||
Reference in new issue
Block a user