### Install Dependencies and Setup Local Dev
Source: https://github.com/composiohq/trustclaw/blob/main/README.md
Commands to install project dependencies, copy the environment example, push database schema, and start the local development server.
```bash
pnpm install
cp .env.example .env # fill in DATABASE_URL, BETTER_AUTH_SECRET, COMPOSIO_API_KEY
pnpm prisma db push # apply schema (Postgres + pgvector required)
pnpm dev # http://localhost:3000
```
--------------------------------
### Set Up Environment Variables
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
Copy the example environment file and fill in the required variables. Ensure you have a Postgres database with pgvector installed, generate a secret key for BETTER_AUTH_SECRET, and obtain a COMPOSIO_API_KEY.
```bash
cp .env.example .env
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
Install all necessary project dependencies using pnpm.
```bash
pnpm install
```
--------------------------------
### Deploy TrustClaw to Vercel
Source: https://github.com/composiohq/trustclaw/blob/main/cli/README.md
Clone the repository, install dependencies, and run the deploy command. The CLI handles the entire deployment process, including Vercel project setup, database provisioning, and secret generation.
```bash
git clone https://github.com/ComposioHQ/trustclaw && cd trustclaw
pnpm install
npx @composio/trustclaw deploy
```
--------------------------------
### Apply Database Schema and Start Dev Server
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
Push the Prisma schema to your database and start the development server. The application will be accessible at http://localhost:3000.
```bash
pnpm prisma db push
pnpm dev
```
--------------------------------
### tRPC Query Example
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Use tRPC queries for data fetching. Import `trpc` from `~/clients/trpc` and use the `useQuery` hook.
```typescript
import { trpc } from "~/clients/trpc";
const { data, isLoading, error } = trpc.health.ping.useQuery();
```
--------------------------------
### tRPC Queries
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Example of how to perform a simple tRPC query to fetch data. Use `trpc.health.ping.useQuery()` for health checks.
```APIDOC
## tRPC Queries
### Description
This demonstrates how to use tRPC to make a query to the backend. The `useQuery` hook is used for fetching data.
### Method
tRPC Query Hook
### Endpoint
N/A (tRPC)
### Parameters
None directly for the hook, but the procedure might accept inputs.
### Request Example
```typescript
import { trpc } from "~/clients/trpc";
const { data, isLoading, error } = trpc.health.ping.useQuery();
```
### Response
#### Success Response
- **data** (any) - The data returned from the query.
- **isLoading** (boolean) - Indicates if the query is currently loading.
- **error** (any) - Any error that occurred during the query.
```
--------------------------------
### Prisma Standard Query Example
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Access the Prisma client via `ctx.prisma` within tRPC procedures for standard database queries. Use Prisma's typed API for type safety.
```typescript
const items = await ctx.prisma.item.findMany({
where: { userId, archived: false },
select: { id: true, name: true },
orderBy: { createdAt: "desc" },
});
```
--------------------------------
### tRPC Subscription Client Setup
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Configure tRPC client to route subscriptions via `httpSubscriptionLink` using `splitLink`. Ensure the URL and transformer are correctly set.
```typescript
// Client setup (in trpc client config) - route subscriptions separately
import { splitLink, httpSubscriptionLink, httpBatchStreamLink } from "@trpc/client";
splitLink({
condition: (op) => op.type === "subscription",
true: httpSubscriptionLink({ url: getBaseUrl() + "/api/trpc", transformer: SuperJSON }),
false: httpBatchStreamLink({ url: getBaseUrl() + "/api/trpc", transformer: SuperJSON }),
});
```
--------------------------------
### tRPC Infinite Queries
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Example of using tRPC for infinite queries, suitable for paginated lists. `trpc.items.list.useInfiniteQuery` fetches items with pagination.
```APIDOC
## tRPC Infinite Queries
### Description
This shows how to implement infinite scrolling or pagination using tRPC's `useInfiniteQuery` hook. It's ideal for fetching large lists of items.
### Method
tRPC Infinite Query Hook
### Endpoint
N/A (tRPC)
### Parameters
- **input** (object) - Optional input for the query, e.g., `{ limit: 50 }`.
- **options** (object) - Configuration for the query, including `getNextPageParam`.
- **getNextPageParam** (function) - Function to determine the next page's cursor.
### Request Example
```typescript
import { trpc } from "~/clients/trpc";
const { data, isLoading, error, hasNextPage, fetchNextPage } =
trpc.items.list.useInfiniteQuery(
{ limit: 50 },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
```
### Response
- **data** (object) - Contains the fetched pages of data.
- **isLoading** (boolean) - Indicates if data is currently being loaded.
- **error** (any) - Any error that occurred.
- **hasNextPage** (boolean) - Whether there are more pages to fetch.
- **fetchNextPage** (function) - Function to trigger fetching the next page.
```
--------------------------------
### tRPC Infinite Query Example
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Implement tRPC infinite queries for paginated data. Use `useInfiniteQuery` and provide `getNextPageParam` to handle fetching subsequent pages.
```typescript
import { trpc } from "~/clients/trpc";
const { data, isLoading, error, hasNextPage, fetchNextPage } =
trpc.items.list.useInfiniteQuery(
{ limit: 50 },
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
```
--------------------------------
### Skeleton Component for Loading States
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Implement skeleton components mirroring the layout of the main component for loading states. This example shows a UserCardSkeleton using components from ~/components/ui/skeleton.
```typescript
import { Skeleton } from "~/components/ui/skeleton";
export function UserCardSkeleton() {
return (
);
}
```
--------------------------------
### tRPC Mutations
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Example of performing a tRPC mutation to create or modify data. `trpc.items.create.useMutation` is used for creating new items.
```APIDOC
## tRPC Mutations
### Description
This illustrates how to use tRPC mutations for operations that change data on the server, such as creating, updating, or deleting records. It includes an example of invalidating a query cache upon successful mutation.
### Method
tRPC Mutation Hook
### Endpoint
N/A (tRPC)
### Parameters
- **mutation options** (object) - Callbacks like `onSuccess` for handling mutation results.
### Request Example
```typescript
import { trpc } from "~/clients/trpc";
const utils = trpc.useUtils();
const createItem = trpc.items.create.useMutation({
onSuccess: () => {
void utils.items.list.invalidate();
},
});
// usage
// await createItem.mutateAsync({ name: "New Item" });
```
### Response
- **mutateAsync** (function) - Function to trigger the mutation asynchronously.
- **onSuccess** (callback) - Function executed upon successful mutation.
```
--------------------------------
### Getting Session in Server Components
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Retrieve session information in server components using authServer.getSession(). Check the status for 'authenticated' and access user and session details.
```typescript
import { authServer } from "~/clients/auth/server";
// Get session with detailed status
const result = await authServer.getSession();
if (result.status === "authenticated") {
const { user, session } = result.session;
}
```
--------------------------------
### tRPC Mutation Example
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Perform data modifications with tRPC mutations. Use `useMutation` and `invalidate` related queries on success to refresh data.
```typescript
import { trpc } from "~/clients/trpc";
const utils = trpc.useUtils();
const createItem = trpc.items.create.useMutation({
onSuccess: () => {
void utils.items.list.invalidate();
},
});
// usage
//await createItem.mutateAsync({ name: "New Item" });
```
--------------------------------
### Pass Session Data from Server Component Props
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
When rendering data available on the server, such as session information, pass it as props from server components instead of client-side fetching. This example shows how to retrieve session data and pass user email and name to a Dashboard component.
```typescript
// page.tsx (server component)
import { authServer } from "~/clients/auth/server";
export default async function Page() {
const result = await authServer.getSession();
if (result.status !== "authenticated") return null;
const { user, session } = result.session;
return (
);
}
```
--------------------------------
### tRPC Mutation Error Handling with Toast Notifications
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Handle tRPC mutation errors using 'trpcToastOnError' or 'showTrpcErrorToast' for typed error messages. Use 'mutateAsync' for consistent async/await error handling and avoid silent failures. This example demonstrates error handling with a try/catch block.
```typescript
const utils = trpc.useUtils();
const createItem = trpc.items.create.useMutation({
onError: trpcToastOnError,
onSuccess: () => void utils.items.list.invalidate(),
});
// With try/catch for custom logic
try {
await createItem.mutateAsync({ name: "New Item" });
showSuccessToast("Item created");
} catch (error) {
showTrpcErrorToast(error);
}
```
--------------------------------
### Deploy TrustClaw with CLI
Source: https://github.com/composiohq/trustclaw/blob/main/README.md
Use the TrustClaw CLI to deploy your own instance. Ensure you have a Vercel account, GitHub account, and a Composio API key.
```bash
npx @composio/trustclaw deploy
```
--------------------------------
### Common Development Commands
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
A list of pnpm commands for common development tasks, including running the dev server, type checking, linting, formatting, and building the project.
```bash
pnpm dev # dev server with hot reload
pnpm typecheck # TypeScript
pnpm lint # ESLint
pnpm format:write # Prettier
pnpm build # production build
```
--------------------------------
### tRPC Subscriptions (SSE)
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Documentation for setting up and consuming tRPC subscriptions using Server-Sent Events (SSE) for real-time data streams.
```APIDOC
## tRPC Subscriptions (SSE)
### Description
This section covers the implementation of real-time data streaming using tRPC subscriptions, which are typically handled over Server-Sent Events (SSE). It includes client setup and server-side procedure definition.
### Client Setup
#### Description
Configure the tRPC client to route subscription requests to a separate endpoint using `splitLink`.
#### Code Example
```typescript
// Client setup (in trpc client config)
import { splitLink, httpSubscriptionLink, httpBatchStreamLink } from "@trpc/client";
splitLink({
condition: (op) => op.type === "subscription",
true: httpSubscriptionLink({ url: getBaseUrl() + "/api/trpc", transformer: SuperJSON }),
false: httpBatchStreamLink({ url: getBaseUrl() + "/api/trpc", transformer: SuperJSON }),
});
```
### Server-Side Procedure Definition
#### Description
Define a subscription procedure on the server using `observable` to emit real-time events.
#### Code Example
```typescript
// Server - define a subscription procedure with observable
import { observable } from "@trpc/server/observable";
export const chat = protectedProcedure
.input(chatInput)
.subscription(({ input, ctx }) => {
return observable((emit) => {
const abortController = new AbortController();
runStream({ input, emit, signal: abortController.signal })
.catch((error) => {
emit.next({ type: "error", message: error.message });
emit.complete();
});
return () => abortController.abort(); // cleanup on unsubscribe
});
});
```
### Client-Side Consumption
#### Description
Consume subscription data on the client using the `useSubscription` hook, with options to control its activation and handle incoming data or errors.
#### Code Example
```typescript
// Client - consume with useSubscription (controlled via enabled flag)
const [isActive, setIsActive] = useState(false);
trpc.domain.procedure.useSubscription(input, {
enabled: isActive,
onData: (event) => { /* handle streaming events */ },
onError: (err) => { /* handle errors */ },
});
```
```
--------------------------------
### Test Deploy Flow
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
If changes affect the deploy flow, test it end-to-end using the `pnpm cli:deploy` command against a new Vercel project.
```bash
pnpm cli:deploy
```
--------------------------------
### Clone the TrustClaw Repository
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
Clone your forked repository to your local machine. Replace `` with your GitHub username.
```bash
git clone https://github.com//trustclaw && cd trustclaw
```
--------------------------------
### Username/Password Sign-in
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Perform a username and password sign-in using authClient.signIn.username. Specify the username, password, and an optional callbackURL for redirection after successful authentication.
```typescript
import { authClient } from "~/clients/auth/react";
await authClient.signIn.username({
username: "user",
password: "password",
callbackURL: "/dashboard",
});
```
--------------------------------
### Implement Responsive Layouts with Tailwind CSS
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Use Tailwind's responsive prefixes (sm:, md:, lg:) to build mobile-first layouts that adapt to different screen sizes. Ensure base styles are for mobile, then progressively enhance for larger screens.
```typescript
// WRONG - desktop-only fixed layout
...
// CORRECT - stacks on mobile, side-by-side on desktop
...
// Responsive grid
// Responsive padding/spacing
// Hide/show elements by breakpoint
Full LabelShort
// Responsive text
```
--------------------------------
### TrustClaw Agent Directory Structure
Source: https://github.com/composiohq/trustclaw/blob/main/src/server/api/routers/trustclaw/agent/CLAUDE.md
Provides an overview of the agent's directory structure, highlighting key files and their functionalities for context management, compaction, and tool definitions.
```text
agent/
├── setup.ts # prepareAgentRun() - builds agent, tools, context
├── index.ts # Re-exports prepareAgentRun, types, cron-utils
├── types.ts # ReconstructedMessage, JsonValue, ToolResultOutput
├── strip-tool-echoes.ts # Strips echoed tool results from assistant text
├── system-prompt.ts # Builds system prompt from identity + soul + user + memory
├── error-parser.ts # Parses Composio/Anthropic errors into user-friendly messages
│
├── context/ # Context window management
│ ├── build-context.ts # DB loading, message reconstruction, post-response orchestration
│ ├── context-window.ts # Maps model IDs → context window size (200K for all Claude 4.x)
│ ├── token-estimation.ts # chars/4 heuristic, shouldCompact()
│ └── context-pruning.ts # 2-phase pruning: soft trim then hard clear of tool results
│
├── compaction/ # Context compaction (summarization when context overflows)
│ ├── run-compaction.ts # Cut point algorithm, LLM summarization, DB persistence
│ └── prompts.ts # Summarization prompts, message serialization, tool failure tracking
│
└── tools/ # Agent tool definitions (one tool per file + sibling .schema.ts)
├── index.ts # createCustomTools()
├── memory-save.ts / .schema.ts # Save a memory (pgvector + OpenAI embeddings)
├── memory-search.ts / .schema.ts # Cosine-similarity search over memories
├── schedule.ts / .schema.ts # Create/list/delete cron jobs
└── cron-utils.ts # computeNextRunAt(), validateCronExpression()
```
--------------------------------
### TrustClaw Agent Architecture Overview
Source: https://github.com/composiohq/trustclaw/blob/main/src/server/api/routers/trustclaw/agent/CLAUDE.md
This diagram outlines the flow of a user message through the TrustClaw agent, from initial loading and context building to LLM interaction and post-response tasks.
```text
User message (web / telegram / cron)
│
▼
┌─────────────────────────────────────────────────┐
│ setup.ts - prepareAgentRun() │
│ │
│ 1. Load instance from DB │
│ 2. Build system prompt │
│ 3. Load messages (compaction-aware) ◄─── context/build-context.ts
│ 4. Prune context (trim/clear old tools) ◄─── context/context-pruning.ts
│ 5. Save user message to DB │
│ 6. Init Composio session + tools │
│ 7. Create ToolLoopAgent with Anthropic ◄─── Vercel AI SDK
│ (memory_save / memory_search tools │
│ backed by pgvector + OpenAI embeddings) │
│ 8. Return agent + messages to caller │
│ (caller runs agent.stream() or .generate()) │
│ 9. Update assistant message in DB (onFinish) │
│ 10. Fire-and-forget post-response tasks: │
│ a. Memory flush (if approaching limit) ◄── compaction/memory-flush.ts
│ b. Compaction (if over limit) ◄─── compaction/run-compaction.ts
└─────────────────────────────────────────────────┘
```
--------------------------------
### Next.js Repo Structure
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Details the directory structure for the Next.js project, highlighting key folders like `app`, `clients`, `components`, and `server`. It specifies the purpose of subdirectories such as `api`, `auth`, `trpc`, and `routers`.
```text
src/
├── app/ # Next.js App Router
│ ├── api/
│ │ ├── auth/[...all]/ # Better Auth route handler
│ │ └── trpc/ # tRPC route handler
│ ├── (authenticated)/ # Protected routes (redirects to /login if no session)
│ │ └── dashboard/ # Main authenticated area
│ │ ├── page.tsx
│ │ ├── settings/
│ │ └── ...
│ └── /
│ ├── page.tsx # Page component
│ ├── layout.tsx # Optional layout
│ └── _components/
│ ├── .tsx # Page-specific components
│ ├── .schema.ts # Optional form schema
│ └── .skeleton.tsx # Optional skeleton
├── clients/ # Clients (trpc, auth)
├── components/
│ ├── ui/ # Base shadcn primitives
│ └── core/ # Shared core components
└── server/
├── auth.ts # Better Auth server config
├── api/
│ ├── trpc.ts # Procedure definitions
│ ├── root.ts # Root router
│ └── routers/
│ └── trustclaw/
│ ├── index.ts # Router definition
│ ├── .ts # Procedure implementation
│ └── .schema.ts # Zod schemas (input, output)
```
--------------------------------
### Run Pre-submission Checks
Source: https://github.com/composiohq/trustclaw/blob/main/CONTRIBUTING.md
Execute a combined type check and linting process before submitting a pull request.
```bash
pnpm check
```
--------------------------------
### tRPC Backend Structure
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Illustrates the backend architecture using tRPC within a Next.js application. It shows how tRPC handles data fetching, mutations, and business logic, with Composio SDK calls integrated into tRPC procedures.
```text
┌─────────────────────────────────────────────────────────┐
│ Next.js Dashboard │
├─────────────────────────────────────────────────────────┤
│ tRPC Client │ Better Auth Client │
│ ~/clients/trpc │ ~/clients/auth │
└──────────┬────────────┴──────────────┬──────────────────┘
│ │
▼ ▼
┌──────────────────────┐ ┌─────────────────────────────┐
│ tRPC Server │ │ Better Auth Server │
│ (Next.js API) │ │ src/server/auth.ts │
│ │ │ + username/password │
└──────────────────────┘ └─────────────────────────────┘
```
--------------------------------
### External SDK Clients
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Information on using external SDK clients for features requiring direct integration with third-party services.
```APIDOC
## External SDK Clients
### Description
This section outlines the usage of external SDK clients, which are available for integrating with services like Composio, Telegram, and Redis. These clients are intended for use within tRPC procedures on the server-side.
### Location
`src/server/clients/`
### Available Clients
- `composio.ts`: For interacting with the Composio API (`@composio/core`). Uses the global `COMPOSIO_API_KEY` from environment variables.
- `telegram.ts`: Helper for the Telegram Bot API.
- `redis.ts`: Redis client, supporting resumable streams, streaming state, and abort flags.
- `db.ts`: Prisma client instance.
### Usage Guidelines
- Import and use these clients exclusively within tRPC procedures.
- Client files export helper functions, not raw SDK instances.
- API keys are sourced from environment variables (validated via `~/env`) or from the database for per-instance keys.
```
--------------------------------
### Import tRPC RouterOutputs for Prop Types
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Import 'RouterOutputs' from '~/clients/trpc' to define prop types for tRPC query results. This avoids creating separate 'types' files for props.
```typescript
import type { RouterOutputs } from "~/clients/trpc";
type Tool = RouterOutputs["tools"]["getList"]["items"][number];
```
--------------------------------
### Per-Instance Job Execution
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
This process handles the execution of jobs for a specific instance. It loads jobs, validates them, and then runs the AI agent in the background. Locks are released individually after execution.
```typescript
POST /execute (instance X: jobs A,B) \
+---> POST /execute (instance Y: job C) /
|
| 1. Loads all jobs, validates fencing tokens
| 2. Returns 202 immediately
| 3. Combines prompts into one agent message
| 4. Runs agent once via after() (background)
| 5. Releases each job's lock individually (own nextRunAt)
v
runAgent() -> Telegram delivery (if linked)
```
--------------------------------
### Import and Use Lucide React Icons with Shadcn Button
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Import icons from 'lucide-react' and use them within shadcn Button components. Ensure only 'lucide-react' is used for icons.
```typescript
import { Plus, Trash2, Settings, ChevronRight } from "lucide-react";
```
--------------------------------
### Prisma Raw SQL for Vector Insertion
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Use `$queryRaw` for inserting data with vector embeddings, as standard Prisma API does not support `VECTOR` types. Ensure embeddings are formatted as strings.
```sql
// Insert with embedding (void query - no validation needed)
const embeddingString = `[${embedding.join(",")}]`;
await prisma.$queryRaw`
INSERT INTO composio_claw_memory (id, "instanceId", content, embedding, "createdAt")
VALUES (${id}, ${instanceId}, ${content}, ${embeddingString}::vector, NOW())
`;
```
--------------------------------
### Prisma Raw SQL for Cosine Similarity Search
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Perform cosine similarity searches using `$queryRaw` with pgvector. Always parse the results using a Zod schema for runtime validation.
```sql
// Cosine similarity search - wrap result with z.array().parse()
const results = z.array(memoryRow).parse(
await prisma.$queryRaw`
SELECT id, content, 1 - (embedding <=> ${queryEmbedding}::vector) AS similarity
FROM composio_claw_memory
WHERE "instanceId" = ${instanceId}
ORDER BY embedding <=> ${queryEmbedding}::vector
LIMIT ${maxResults}
`,
);
```
--------------------------------
### Local Testing Script: Make Job Due
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
This command sets a job's `nextRunAt` timestamp to the past, making it eligible for execution by the cron system. You can specify a relative time like '5 minutes ago'.
```bash
# Make a job due by setting nextRunAt to the past
./scripts/test-cron.sh make-due
./scripts/test-cron.sh make-due "5 minutes ago"
```
--------------------------------
### Format Dates and Times with Moment.js
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Utilize the `moment` library for all date formatting and parsing tasks. Avoid using raw `Date` methods or `Intl.DateTimeFormat` for consistency and reliability.
```typescript
// WRONG - raw Date methods
date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric" }).format(date);
// CORRECT - moment.js
moment(date).format("HH:mm:ss");
moment(date).format("MMM D, YYYY h:mm A");
moment(date).fromNow(); // "2 hours ago"
```
--------------------------------
### Prisma Database Access
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Guidance on using Prisma for database operations, including schema changes and raw SQL queries for specific features like pgvector.
```APIDOC
## Database (Prisma)
### Description
This section details how to interact with the database using Prisma. It covers schema management, accessing the Prisma client within tRPC procedures, and executing raw SQL queries, particularly for vector operations with pgvector.
### Schema Changes
#### Description
For development, use `npx prisma db push` to apply schema changes directly. Ensure the `DATABASE_URL` is correctly configured.
### Prisma in tRPC Context
#### Description
Access the Prisma client instance within tRPC procedures via the context object (`ctx.prisma`).
### Standard Queries
#### Description
Utilize Prisma's typed API for standard database queries like `findMany`, `findUnique`, etc.
#### Code Example
```typescript
const items = await ctx.prisma.item.findMany({
where: { userId, archived: false },
select: { id: true, name: true },
orderBy: { createdAt: "desc" },
});
```
### Raw SQL for pgvector
#### Description
For operations involving pgvector (e.g., vector embeddings), use `$queryRaw` as standard Prisma API might not support specific vector types. Always validate results with Zod schemas for runtime safety.
#### Zod Schema Definition Example
```typescript
// In the .schema.ts file - define a Zod schema for the row shape
export const memoryRow = z.object({
id: z.string(),
content: z.string(),
similarity: z.number(),
});
export type MemoryRow = z.infer;
```
#### Insert with Embedding Example
```typescript
const embeddingString = `[${embedding.join(",")}]`;
await prisma.$queryRaw`
INSERT INTO composio_claw_memory (id, "instanceId", content, embedding, "createdAt")
VALUES (${id}, ${instanceId}, ${content}, ${embeddingString}::vector, NOW())
`;
```
#### Cosine Similarity Search Example
```typescript
const results = z.array(memoryRow).parse(
await prisma.$queryRaw`
SELECT id, content, 1 - (embedding <=> ${queryEmbedding}::vector) AS similarity
FROM composio_claw_memory
WHERE "instanceId" = ${instanceId}
ORDER BY embedding <=> ${queryEmbedding}::vector
LIMIT ${maxResults}
`,
);
```
```
--------------------------------
### Import tRPC Mutation Schemas
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Import input schemas for tRPC mutations from their respective '.schema.ts' files in the 'server/api/routers/' directory. This ensures type safety for mutation inputs.
```typescript
import {
createItemInput,
type CreateItemInput,
} from "~/server/api/routers/items/createItem.schema";
```
--------------------------------
### Local Testing Script: List Jobs
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
Use this command to list all cron jobs and their current status (RUNNING, DUE, SCHEDULED, ERRORED, IDLE). This is useful for identifying job IDs before performing other operations.
```bash
# List all jobs and their status (RUNNING/DUE/SCHEDULED/ERRORED/IDLE)
./scripts/test-cron.sh list
```
--------------------------------
### tRPC Subscription Server Implementation
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Define a tRPC subscription procedure on the server using `observable`. Handle streaming events and errors, and ensure cleanup on unsubscribe.
```typescript
// Server - define a subscription procedure with observable
import { observable } from "@trpc/server/observable";
export const chat = protectedProcedure
.input(chatInput)
.subscription (({ input, ctx }) => {
return observable((emit) => {
const abortController = new AbortController();
runStream({ input, emit, signal: abortController.signal })
.catch((error) => {
emit.next({ type: "error", message: error.message });
emit.complete();
});
return () => abortController.abort(); // cleanup on unsubscribe
});
});
```
--------------------------------
### Securely Access Environment Variables
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Always use the `env` helper from `~/env` for type-safe and validated access to environment variables. Only use `process.env` directly in root config files where the helper is unavailable.
```typescript
// WRONG - no validation, no type safety
const key = process.env.COMPOSIO_API_KEY;
// CORRECT - validated and typed
import { env } from "~/env";
const key = env.COMPOSIO_API_KEY;
```
--------------------------------
### TrustClaw Memory Flush Mechanism
Source: https://github.com/composiohq/trustclaw/blob/main/src/server/api/routers/trustclaw/agent/CLAUDE.md
Explains the memory flush process, which runs before compaction to persist recent conversation facts to the pgvector store using `memory_save` and `memory_search` tools.
```text
Memories are stored in the `composio_claw_memory` table with 1024-dim vectors from OpenAI's `text-embedding-3-large` model. Flush failure is non-fatal - the next compaction cycle will retry.
```
--------------------------------
### Use Theme-Aware Colors with shadcn UI
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Avoid hardcoded Tailwind color classes. Instead, use shadcn theme variables (e.g., `bg-muted`, `text-foreground`) for colors that automatically adapt to light/dark modes.
```typescript
// WRONG - hardcoded colors
// CORRECT - theme-aware colors
// Common patterns:
// bg-background, bg-card, bg-muted, bg-accent, bg-popover, bg-destructive
// text-foreground, text-muted-foreground, text-primary-foreground, text-destructive
// border-border, border-input
// ring-ring
```
--------------------------------
### Local Testing Script: Trigger Cron with Fake Time
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
Allows triggering the cron process with a specified fake time, useful for testing time-sensitive schedules without altering the system clock or database. This option is only effective in development.
```bash
# Trigger with a fake time (dev only - ignored in production)
./scripts/test-cron.sh trigger --now "2025-06-15T09:00:00Z"
```
--------------------------------
### Cron Job Database Schema Fields
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
These are the key fields within the `CronJob` model in the Prisma schema, relevant to the cron system's operation and state tracking.
```prisma
id, instanceId, expression, prompt, timezone, enabled,
lastRunAt, nextRunAt, lockedAt, lockedBy, lastError
```
--------------------------------
### Cron Job Claiming and Dispatch Logic
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
This logic is executed by the Vercel Cron job. It atomically updates the database to claim due and stale-locked jobs, assigns them to the current invocation, groups them by instance, and dispatches them for execution.
```typescript
GET /api/cron/trustclaw (route.ts)
|
| 1. Atomic UPDATE ... RETURNING claims due + stale-locked jobs
| 2. Sets lockedAt/lockedBy, clears nextRunAt (prevents re-pick)
| 3. Groups claimed jobs by instanceId
| 4. Dispatches one fetch() per instance with all jobIds
| 5. Returns { dispatched: N, instances: M } in ~1s
|
+---> POST /execute (instance X: jobs A,B) \
+---> POST /execute (instance Y: job C) /
```
--------------------------------
### TrustClaw Context Pruning Strategy
Source: https://github.com/composiohq/trustclaw/blob/main/src/server/api/routers/trustclaw/agent/CLAUDE.md
Details the two-phase context pruning strategy (soft trim and hard clear) used before LLM calls to manage token usage based on character count thresholds.
```text
Phase | Trigger | Action
|-------|---------|--------|
| Soft trim | Context chars > 30% of window | Tool results > 4KB: keep first 1500 + `...[trimmed]...` + last 1500 chars
| Hard clear | Context chars > 50% of window | Replace oldest tool results (> 50KB total) with `[Old tool result content cleared]`
Protected zone: last 3 assistant turns are never pruned.
```
--------------------------------
### Prisma Zod Schema for Raw SQL Results
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Define Zod schemas for raw SQL query results to ensure runtime validation. This is crucial for `$queryRaw` as TypeScript generics offer only compile-time safety.
```typescript
// In the .schema.ts file - define a Zod schema for the row shape
export const memoryRow = z.object({
id: z.string(),
content: z.string(),
similarity: z.number(),
});
export type MemoryRow = z.infer;
```
--------------------------------
### Local Testing Script: Trigger Cron
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
Manually triggers the cron job processing. Ensure the development server is running when using this command.
```bash
# Trigger the cron (with dev server running)
./scripts/test-cron.sh trigger
```
--------------------------------
### Local Testing Script: Check Job Status
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
Retrieves detailed status information for a specific cron job, including its lock state, error messages, and relevant timestamps.
```bash
# Check a job's full status (lock state, error, timestamps)
./scripts/test-cron.sh status
```
--------------------------------
### Prefetching tRPC Queries in Server Components
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Prefetch tRPC queries in a page.tsx server component to warm the cache. Use void for fire-and-forget prefetching without blocking render. Consume cached data in client components via trpcServer.HydrateClient.
```typescript
// page.tsx (server component)
import { trpcServer } from "~/clients/trpc/server";
export default async function DashboardPage() {
// void = fire-and-forget, warms cache without blocking render
void trpcServer.api.tools.getList.prefetch();
return (
{/* trpc.*.useQuery picks up cached data, or shows loading if still fetching */}
);
}
```
--------------------------------
### Accessing Session in Client Components
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Access session data in client components using authClient.useSession(). Better Auth manages client session state internally. The user and session are available in the data property.
```typescript
import { authClient } from "~/clients/auth/react";
// Access session (Better Auth manages state internally)
const { data } = authClient.useSession();
const user = data?.user;
const session = data?.session;
```
--------------------------------
### Sign Out
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Log the user out using the authClient.signOut() function. This will clear the current session.
```typescript
import { authClient } from "~/clients/auth/react";
await authClient.signOut();
```
--------------------------------
### tRPC Subscription Client Usage
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Consume tRPC subscriptions on the client using `useSubscription`. Control the subscription's active state with the `enabled` flag and handle incoming data and errors.
```typescript
// Client - consume with useSubscription (controlled via enabled flag)
const [isActive, setIsActive] = useState(false);
trpc.domain.procedure.useSubscription(input, {
enabled: isActive,
onData: (event) => { /* handle streaming events */ },
onError: (err) => { /* handle errors */ },
});
```
--------------------------------
### Local Testing Script: Force Unlock Job
Source: https://github.com/composiohq/trustclaw/blob/main/src/app/api/cron/trustclaw/CLAUDE.md
Use this command to manually release the lock on a cron job, which is helpful for recovering stuck or unresponsive jobs.
```bash
# Force-unlock a stuck job
./scripts/test-cron.sh unlock
```
--------------------------------
### ErrorBoundary for Client Component Crashes
Source: https://github.com/composiohq/trustclaw/blob/main/CLAUDE.md
Use ErrorBoundary to catch runtime crashes in client components. Wrap potentially problematic subtrees to prevent page-wide failures. An optional fallback prop allows for custom error UI.
```typescript
import { ErrorBoundary } from "~/components/core/error-boundary";
// In a page or layout wrapping client components
// With custom fallback
Failed to load tools.}>
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.