convex-helpers-patterns
Guide for convex-helpers library patterns including Triggers, Row-Level Security (RLS), Relationship helpers, Custom Functions, Rate Limiting, and Workpool. Use when implementing automatic side effects, access control, relationship traversal, auth wrappers, or concurrency management. Activates for triggers setup, RLS implementation, custom function wrappers, or convex-helpers integration tasks.
What this skill does
# Convex Helpers Library Patterns
## Overview
The `convex-helpers` library provides battle-tested patterns for common Convex development needs. This skill covers Triggers (automatic side effects), Row-Level Security, Relationship helpers, Custom Functions, Rate Limiting, and Workpool for concurrency control.
## Installation
```bash
npm install convex-helpers @convex-dev/workpool
```
## TypeScript: NEVER Use `any` Type
**CRITICAL RULE:** This codebase has `@typescript-eslint/no-explicit-any` enabled. Using `any` will cause build failures.
## When to Use This Skill
Use this skill when:
- Implementing automatic side effects on document changes (Triggers)
- Adding declarative access control (Row-Level Security)
- Traversing relationships between documents
- Creating reusable authenticated function wrappers
- Implementing rate limiting
- Managing concurrent writes with Workpool
- Building custom function builders
## Key Patterns Overview
| Pattern | Use Case |
| ------------------------ | ------------------------------------------------------ |
| **Triggers** | Run code automatically on document changes |
| **Row-Level Security** | Declarative access control at the database layer |
| **Relationship Helpers** | Simplified traversal of document relations |
| **Custom Functions** | Wrap queries/mutations with auth, logging, etc. |
| **Rate Limiter** | Application-level rate limiting |
| **Workpool** | Fan-out parallel jobs, serialize conflicting mutations |
| **Migrations** | Schema migrations with state tracking |
## Triggers (Automatic Side Effects)
Triggers run code automatically when documents change. They execute atomically within the same transaction as the mutation.
### Setting Up Triggers
```typescript
// convex/functions.ts
import { mutation as rawMutation } from "./_generated/server";
import { Triggers } from "convex-helpers/server/triggers";
import {
customCtx,
customMutation,
} from "convex-helpers/server/customFunctions";
import { DataModel } from "./_generated/dataModel";
const triggers = new Triggers<DataModel>();
// 1. Compute fullName on every user change
triggers.register("users", async (ctx, change) => {
if (change.newDoc) {
const fullName = `${change.newDoc.firstName} ${change.newDoc.lastName}`;
if (change.newDoc.fullName !== fullName) {
await ctx.db.patch(change.id, { fullName });
}
}
});
// 2. Keep denormalized count (careful: single doc = write contention)
triggers.register("users", async (ctx, change) => {
const countDoc = (await ctx.db.query("userCount").unique())!;
if (change.operation === "insert") {
await ctx.db.patch(countDoc._id, { count: countDoc.count + 1 });
} else if (change.operation === "delete") {
await ctx.db.patch(countDoc._id, { count: countDoc.count - 1 });
}
});
// 3. Cascading deletes
triggers.register("users", async (ctx, change) => {
if (change.operation === "delete") {
const messages = await ctx.db
.query("messages")
.withIndex("by_author", (q) => q.eq("authorId", change.id))
.collect();
for (const msg of messages) {
await ctx.db.delete(msg._id);
}
}
});
// Export wrapped mutation that runs triggers
export const mutation = customMutation(rawMutation, customCtx(triggers.wrapDB));
```
### Trigger Change Object
```typescript
interface Change<Doc> {
id: Id<TableName>;
operation: "insert" | "update" | "delete";
oldDoc: Doc | null; // null for inserts
newDoc: Doc | null; // null for deletes
}
```
### Trigger Warnings
> **Warning:** Triggers run inside the same transaction as the mutation. Writing to hot-spot documents (e.g., global counters) inside triggers will cause OCC conflicts under load. Use sharding or Workpool for high-contention writes.
## Row-Level Security (RLS)
Declarative access control at the database layer. RLS wraps the database context to enforce rules on every read and write.
### Setting Up RLS
```typescript
// convex/functions.ts
import {
Rules,
wrapDatabaseReader,
wrapDatabaseWriter,
} from "convex-helpers/server/rowLevelSecurity";
import {
customCtx,
customQuery,
customMutation,
} from "convex-helpers/server/customFunctions";
import { query, mutation } from "./_generated/server";
import { QueryCtx } from "./_generated/server";
import { DataModel } from "./_generated/dataModel";
async function rlsRules(ctx: QueryCtx) {
const identity = await ctx.auth.getUserIdentity();
return {
users: {
read: async (_, user) => {
// Unauthenticated users can only read users over 18
if (!identity && user.age < 18) return false;
return true;
},
insert: async () => true,
modify: async (_, user) => {
if (!identity) throw new Error("Must be authenticated");
// Users can only modify their own record
return user.tokenIdentifier === identity.tokenIdentifier;
},
},
messages: {
read: async (_, message) => {
// Only read messages in conversations you're a member of
const conversation = await ctx.db.get(message.conversationId);
return conversation?.members.includes(identity?.subject ?? "") ?? false;
},
modify: async (_, message) => {
// Only modify your own messages
return message.authorId === identity?.subject;
},
},
// Table with no restrictions
publicPosts: {
read: async () => true,
insert: async () => true,
modify: async () => true,
},
} satisfies Rules<QueryCtx, DataModel>;
}
// Wrap query/mutation with RLS
export const queryWithRLS = customQuery(
query,
customCtx(async (ctx) => ({
db: wrapDatabaseReader(ctx, ctx.db, await rlsRules(ctx)),
}))
);
export const mutationWithRLS = customMutation(
mutation,
customCtx(async (ctx) => ({
db: wrapDatabaseWriter(ctx, ctx.db, await rlsRules(ctx)),
}))
);
```
### Using RLS-Wrapped Functions
```typescript
// convex/messages.ts
import { queryWithRLS, mutationWithRLS } from "./functions";
import { v } from "convex/values";
// This query automatically enforces RLS rules
export const list = queryWithRLS({
args: { conversationId: v.id("conversations") },
returns: v.array(
v.object({
_id: v.id("messages"),
_creationTime: v.number(),
content: v.string(),
authorId: v.string(),
})
),
handler: async (ctx, args) => {
// RLS automatically filters out unauthorized messages
return await ctx.db
.query("messages")
.withIndex("by_conversation", (q) =>
q.eq("conversationId", args.conversationId)
)
.collect();
},
});
// This mutation automatically enforces RLS rules
export const update = mutationWithRLS({
args: { messageId: v.id("messages"), content: v.string() },
returns: v.null(),
handler: async (ctx, args) => {
// RLS checks if user can modify this message
await ctx.db.patch(args.messageId, { content: args.content });
return null;
},
});
```
## Relationship Helpers
Simplify traversing relationships without manual lookups.
### Available Helpers
```typescript
import {
getAll,
getOneFrom,
getManyFrom,
getManyVia,
} from "convex-helpers/server/relationships";
```
### One-to-One Relationship
```typescript
// Get single related document via back reference
const profile = await getOneFrom(
ctx.db,
"profiles", // target table
"userId", // index field
user._id // value to match
);
```
### One-to-Many (by ID array)
```typescript
// Load multiple documents by IDs
const users = await getAll(ctx.db, userIds);
// Returns array of documents in same order as IDs (null for missing)
```
### One-to-Many (via index)
```typescript
// Get all posts by author
const posts = await getManyFrom(
ctx.db,
"posts", // target table
"by_authorId", // index name
authRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.