Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fec5db744c | ||
|
|
cb75011244 | ||
|
|
18b23886ab | ||
|
|
beb50f4b49 | ||
|
|
623a414b9b | ||
|
|
91c7e44031 | ||
|
|
850fc9c78e | ||
|
|
f5ec0882d5 | ||
|
|
b2e751c5fc | ||
|
|
4c8032bb97 | ||
|
|
2c435a3d7b | ||
|
|
1f990cf66d |
@@ -1,288 +0,0 @@
|
||||
---
|
||||
name: convex-create-component
|
||||
description: Builds reusable Convex components with isolated tables and app-facing APIs. Use for new components, reusable backend modules, integrations, or component boundary work.
|
||||
---
|
||||
|
||||
# Convex Create Component
|
||||
|
||||
Create reusable Convex components with clear boundaries and a small app-facing API.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Creating a new Convex component in an existing app
|
||||
- Extracting reusable backend logic into a component
|
||||
- Building a third-party integration that should own its own tables and workflows
|
||||
- Packaging Convex functionality for reuse across multiple apps
|
||||
|
||||
## When Not to Use
|
||||
|
||||
- One-off business logic that belongs in the main app
|
||||
- Thin utilities that do not need Convex tables or functions
|
||||
- App-level orchestration that should stay in `convex/`
|
||||
- Cases where a normal TypeScript library is enough
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Ask the user what they are building and what the end goal is. If the repo already makes the answer obvious, say so and confirm before proceeding.
|
||||
2. Choose the shape using the decision tree below and read the matching reference file.
|
||||
3. Decide whether a component is justified. Prefer normal app code or a regular library if the feature does not need isolated tables, backend functions, or reusable persistent state.
|
||||
4. Make a short plan for:
|
||||
- what tables the component owns
|
||||
- what public functions it exposes
|
||||
- what data must be passed in from the app (auth, env vars, parent IDs)
|
||||
- what stays in the app as wrappers or HTTP mounts
|
||||
5. Create the component structure with `convex.config.ts`, `schema.ts`, and function files.
|
||||
6. Implement functions using the component's own `./_generated/server` imports, not the app's generated files.
|
||||
7. Wire the component into the app with `app.use(...)`. If the app does not already have `convex/convex.config.ts`, create it.
|
||||
8. Call the component from the app through `components.<name>` using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction`.
|
||||
9. If React clients, HTTP callers, or public APIs need access, create wrapper functions in the app instead of exposing component functions directly.
|
||||
10. Run `npx convex dev` and fix codegen, type, or boundary issues before finishing.
|
||||
|
||||
## Choose the Shape
|
||||
|
||||
Ask the user, then pick one path:
|
||||
|
||||
| Goal | Shape | Reference |
|
||||
| ------------------------------------------------- | ---------------- | ----------------------------------- |
|
||||
| Component for this app only | Local | `references/local-components.md` |
|
||||
| Publish or share across apps | Packaged | `references/packaged-components.md` |
|
||||
| User explicitly needs local + shared library code | Hybrid | `references/hybrid-components.md` |
|
||||
| Not sure | Default to local | `references/local-components.md` |
|
||||
|
||||
Read exactly one reference file before proceeding.
|
||||
|
||||
## Default Approach
|
||||
|
||||
Unless the user explicitly wants an npm package, default to a local component:
|
||||
|
||||
- Put it under `convex/components/<componentName>/`
|
||||
- Define it with `defineComponent(...)` in its own `convex.config.ts`
|
||||
- Install it from the app's `convex/convex.config.ts` with `app.use(...)`
|
||||
- Let `npx convex dev` generate the component's own `_generated/` files
|
||||
|
||||
## Component Skeleton
|
||||
|
||||
A minimal local component with a table and two functions, plus the app wiring.
|
||||
|
||||
```ts
|
||||
// convex/components/notifications/convex.config.ts
|
||||
import { defineComponent } from "convex/server";
|
||||
|
||||
export default defineComponent("notifications");
|
||||
```
|
||||
|
||||
```ts
|
||||
// convex/components/notifications/schema.ts
|
||||
import { defineSchema, defineTable } from "convex/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default defineSchema({
|
||||
notifications: defineTable({
|
||||
userId: v.string(),
|
||||
message: v.string(),
|
||||
read: v.boolean(),
|
||||
}).index("by_user", ["userId"]),
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// convex/components/notifications/lib.ts
|
||||
import { v } from "convex/values";
|
||||
import { mutation, query } from "./_generated/server.js";
|
||||
|
||||
export const send = mutation({
|
||||
args: { userId: v.string(), message: v.string() },
|
||||
returns: v.id("notifications"),
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.insert("notifications", {
|
||||
userId: args.userId,
|
||||
message: args.message,
|
||||
read: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export const listUnread = query({
|
||||
args: { userId: v.string() },
|
||||
returns: v.array(
|
||||
v.object({
|
||||
_id: v.id("notifications"),
|
||||
_creationTime: v.number(),
|
||||
userId: v.string(),
|
||||
message: v.string(),
|
||||
read: v.boolean(),
|
||||
}),
|
||||
),
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db
|
||||
.query("notifications")
|
||||
.withIndex("by_user", (q) => q.eq("userId", args.userId))
|
||||
.filter((q) => q.eq(q.field("read"), false))
|
||||
.collect();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// convex/convex.config.ts
|
||||
import { defineApp } from "convex/server";
|
||||
import notifications from "./components/notifications/convex.config.js";
|
||||
|
||||
const app = defineApp();
|
||||
app.use(notifications);
|
||||
|
||||
export default app;
|
||||
```
|
||||
|
||||
```ts
|
||||
// convex/notifications.ts (app-side wrapper)
|
||||
import { v } from "convex/values";
|
||||
import { mutation, query } from "./_generated/server";
|
||||
import { components } from "./_generated/api";
|
||||
import { getAuthUserId } from "@convex-dev/auth/server";
|
||||
|
||||
export const sendNotification = mutation({
|
||||
args: { message: v.string() },
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) throw new Error("Not authenticated");
|
||||
|
||||
await ctx.runMutation(components.notifications.lib.send, {
|
||||
userId,
|
||||
message: args.message,
|
||||
});
|
||||
return null;
|
||||
},
|
||||
});
|
||||
|
||||
export const myUnread = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) throw new Error("Not authenticated");
|
||||
|
||||
return await ctx.runQuery(components.notifications.lib.listUnread, {
|
||||
userId,
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Note the reference path shape: a function in `convex/components/notifications/lib.ts` is called as `components.notifications.lib.send` from the app.
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- Keep authentication in the app, because `ctx.auth` is not available inside components.
|
||||
- Keep environment access in the app, because component functions cannot read `process.env`.
|
||||
- Pass parent app IDs across the boundary as strings, because `Id` types become plain strings in the app-facing `ComponentApi`.
|
||||
- Do not use `v.id("parentTable")` for app-owned tables inside component args or schema, because the component has no access to the app's table namespace.
|
||||
- Import `query`, `mutation`, and `action` from the component's own `./_generated/server`, not the app's generated files.
|
||||
- Do not expose component functions directly to clients. Create app wrappers when client access is needed, because components are internal and need auth/env wiring the app provides.
|
||||
- If the component defines HTTP handlers, mount the routes in the app's `convex/http.ts`, because components cannot register their own HTTP routes.
|
||||
- If the component needs pagination, use `paginator` from `convex-helpers` instead of built-in `.paginate()`, because `.paginate()` does not work across the component boundary.
|
||||
- Add `args` and `returns` validators to all public component functions, because the component boundary requires explicit type contracts.
|
||||
|
||||
## Patterns
|
||||
|
||||
### Authentication and environment access
|
||||
|
||||
```ts
|
||||
// Bad: component code cannot rely on app auth or env
|
||||
const identity = await ctx.auth.getUserIdentity();
|
||||
const apiKey = process.env.OPENAI_API_KEY;
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: the app resolves auth and env, then passes explicit values
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) throw new Error("Not authenticated");
|
||||
|
||||
await ctx.runAction(components.translator.translate, {
|
||||
userId,
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
text: args.text,
|
||||
});
|
||||
```
|
||||
|
||||
### Client-facing API
|
||||
|
||||
```ts
|
||||
// Bad: assuming a component function is directly callable by clients
|
||||
export const send = components.notifications.send;
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: re-export through an app mutation or query
|
||||
export const sendNotification = mutation({
|
||||
args: { message: v.string() },
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) throw new Error("Not authenticated");
|
||||
|
||||
await ctx.runMutation(components.notifications.lib.send, {
|
||||
userId,
|
||||
message: args.message,
|
||||
});
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### IDs across the boundary
|
||||
|
||||
```ts
|
||||
// Bad: parent app table IDs are not valid component validators
|
||||
args: {
|
||||
userId: v.id("users");
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: treat parent-owned IDs as strings at the boundary
|
||||
args: {
|
||||
userId: v.string();
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Patterns
|
||||
|
||||
For additional patterns including function handles for callbacks, deriving validators from schema, static configuration with a globals table, and class-based client wrappers, see `references/advanced-patterns.md`.
|
||||
|
||||
## Validation
|
||||
|
||||
Try validation in this order:
|
||||
|
||||
1. `npx convex codegen --component-dir convex/components/<name>`
|
||||
2. `npx convex codegen`
|
||||
3. `npx convex dev`
|
||||
|
||||
Important:
|
||||
|
||||
- Fresh repos may fail these commands until `CONVEX_DEPLOYMENT` is configured.
|
||||
- Until codegen runs, component-local `./_generated/*` imports and app-side `components.<name>...` references will not typecheck.
|
||||
- If validation blocks on Convex login or deployment setup, stop and ask the user for that exact step instead of guessing.
|
||||
|
||||
## Reference Files
|
||||
|
||||
Read exactly one of these after the user confirms the goal:
|
||||
|
||||
- `references/local-components.md`
|
||||
- `references/packaged-components.md`
|
||||
- `references/hybrid-components.md`
|
||||
|
||||
Official docs: [Authoring Components](https://docs.convex.dev/components/authoring)
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Asked the user what they want to build and confirmed the shape
|
||||
- [ ] Read the matching reference file
|
||||
- [ ] Confirmed a component is the right abstraction
|
||||
- [ ] Planned tables, public API, boundaries, and app wrappers
|
||||
- [ ] Component lives under `convex/components/<name>/` (or package layout if publishing)
|
||||
- [ ] Component imports from its own `./_generated/server`
|
||||
- [ ] Auth, env access, and HTTP routes stay in the app
|
||||
- [ ] Parent app IDs cross the boundary as `v.string()`
|
||||
- [ ] Public functions have `args` and `returns` validators
|
||||
- [ ] Ran `npx convex dev` and fixed codegen or type issues
|
||||
@@ -1,10 +0,0 @@
|
||||
interface:
|
||||
display_name: "Convex Create Component"
|
||||
short_description: "Design and build reusable Convex components with clear boundaries."
|
||||
icon_small: "./assets/icon.svg"
|
||||
icon_large: "./assets/icon.svg"
|
||||
brand_color: "#14B8A6"
|
||||
default_prompt: "Help me create a Convex component for this feature. First check that a component is actually justified, then design the tables, API surface, and app-facing wrappers before implementing it."
|
||||
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="m21 7.5-2.25-1.313M21 7.5v2.25m0-2.25-2.25 1.313M3 7.5l2.25-1.313M3 7.5l2.25 1.313M3 7.5v2.25m9 3 2.25-1.313M12 12.75l-2.25-1.313M12 12.75V15m0 6.75 2.25-1.313M12 21.75V19.5m0 2.25-2.25-1.313m0-16.875L12 2.25l2.25 1.313M21 14.25v2.25l-2.25 1.313m-13.5 0L3 16.5v-2.25"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 485 B |
@@ -1,134 +0,0 @@
|
||||
# Advanced Component Patterns
|
||||
|
||||
Additional patterns for Convex components that go beyond the basics covered in the main skill file.
|
||||
|
||||
## Function Handles for callbacks
|
||||
|
||||
When the app needs to pass a callback function to the component, use function handles. This is common for components that run app-defined logic on a schedule or in a workflow.
|
||||
|
||||
```ts
|
||||
// App side: create a handle and pass it to the component
|
||||
import { createFunctionHandle } from "convex/server";
|
||||
|
||||
export const startJob = mutation({
|
||||
handler: async (ctx) => {
|
||||
const handle = await createFunctionHandle(internal.myModule.processItem);
|
||||
await ctx.runMutation(components.workpool.enqueue, {
|
||||
callback: handle,
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Component side: accept and invoke the handle
|
||||
import { v } from "convex/values";
|
||||
import type { FunctionHandle } from "convex/server";
|
||||
import { mutation } from "./_generated/server.js";
|
||||
|
||||
export const enqueue = mutation({
|
||||
args: { callback: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
const handle = args.callback as FunctionHandle<"mutation">;
|
||||
await ctx.scheduler.runAfter(0, handle, {});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Deriving validators from schema
|
||||
|
||||
Instead of manually repeating field types in return validators, extend the schema validator:
|
||||
|
||||
```ts
|
||||
import { v } from "convex/values";
|
||||
import schema from "./schema.js";
|
||||
|
||||
const notificationDoc = schema.tables.notifications.validator.extend({
|
||||
_id: v.id("notifications"),
|
||||
_creationTime: v.number(),
|
||||
});
|
||||
|
||||
export const getLatest = query({
|
||||
args: {},
|
||||
returns: v.nullable(notificationDoc),
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db.query("notifications").order("desc").first();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Static configuration with a globals table
|
||||
|
||||
A common pattern for component configuration is a single-document "globals" table:
|
||||
|
||||
```ts
|
||||
// schema.ts
|
||||
export default defineSchema({
|
||||
globals: defineTable({
|
||||
maxRetries: v.number(),
|
||||
webhookUrl: v.optional(v.string()),
|
||||
}),
|
||||
// ... other tables
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// lib.ts
|
||||
export const configure = mutation({
|
||||
args: { maxRetries: v.number(), webhookUrl: v.optional(v.string()) },
|
||||
returns: v.null(),
|
||||
handler: async (ctx, args) => {
|
||||
const existing = await ctx.db.query("globals").first();
|
||||
if (existing) {
|
||||
await ctx.db.patch(existing._id, args);
|
||||
} else {
|
||||
await ctx.db.insert("globals", args);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Class-based client wrappers
|
||||
|
||||
For components with many functions or configuration options, a class-based client provides a cleaner API. This pattern is common in published components.
|
||||
|
||||
```ts
|
||||
// src/client/index.ts
|
||||
import type { GenericMutationCtx, GenericDataModel } from "convex/server";
|
||||
import type { ComponentApi } from "../component/_generated/component.js";
|
||||
|
||||
type MutationCtx = Pick<GenericMutationCtx<GenericDataModel>, "runMutation">;
|
||||
|
||||
export class Notifications {
|
||||
constructor(
|
||||
private component: ComponentApi,
|
||||
private options?: { defaultChannel?: string },
|
||||
) {}
|
||||
|
||||
async send(ctx: MutationCtx, args: { userId: string; message: string }) {
|
||||
return await ctx.runMutation(this.component.lib.send, {
|
||||
...args,
|
||||
channel: this.options?.defaultChannel ?? "default",
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// App usage
|
||||
import { Notifications } from "@convex-dev/notifications";
|
||||
import { components } from "./_generated/api";
|
||||
|
||||
const notifications = new Notifications(components.notifications, {
|
||||
defaultChannel: "alerts",
|
||||
});
|
||||
|
||||
export const send = mutation({
|
||||
args: { message: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await getAuthUserId(ctx);
|
||||
await notifications.send(ctx, { userId, message: args.message });
|
||||
},
|
||||
});
|
||||
```
|
||||
@@ -1,37 +0,0 @@
|
||||
# Hybrid Convex Components
|
||||
|
||||
Read this file only when the user explicitly wants a hybrid setup.
|
||||
|
||||
## What This Means
|
||||
|
||||
A hybrid component combines a local Convex component with shared library code.
|
||||
|
||||
This can help when:
|
||||
|
||||
- the user wants a local install but also shared package logic
|
||||
- the component needs extension points or override hooks
|
||||
- some logic should live in normal TypeScript code outside the component boundary
|
||||
|
||||
## Default Advice
|
||||
|
||||
Treat hybrid as an advanced option, not the default.
|
||||
|
||||
Before choosing it, ask:
|
||||
|
||||
- Why is a plain local component not enough?
|
||||
- Why is a packaged component not enough?
|
||||
- What exactly needs to stay overridable or shared?
|
||||
|
||||
If the answer is vague, fall back to local or packaged.
|
||||
|
||||
## Risks
|
||||
|
||||
- More moving parts
|
||||
- Harder upgrades and backwards compatibility
|
||||
- Easier to blur the component boundary
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] User explicitly needs hybrid behavior
|
||||
- [ ] Local-only and packaged-only options were considered first
|
||||
- [ ] The extension points are clearly defined before coding
|
||||
@@ -1,38 +0,0 @@
|
||||
# Local Convex Components
|
||||
|
||||
Read this file when the component should live inside the current app and does not need to be published as an npm package.
|
||||
|
||||
## When to Choose This
|
||||
|
||||
- The user wants the simplest path
|
||||
- The component only needs to work in this repo
|
||||
- The goal is extracting app logic into a cleaner boundary
|
||||
|
||||
## Default Layout
|
||||
|
||||
Use this structure unless the repo already has a clear alternative pattern:
|
||||
|
||||
```text
|
||||
convex/
|
||||
convex.config.ts
|
||||
components/
|
||||
<name>/
|
||||
convex.config.ts
|
||||
schema.ts
|
||||
<feature>.ts
|
||||
```
|
||||
|
||||
## Workflow Notes
|
||||
|
||||
- Define the component with `defineComponent("<name>")`
|
||||
- Install it from the app with `defineApp()` and `app.use(...)`
|
||||
- Keep auth, env access, public API wrappers, and HTTP route mounting in the app
|
||||
- Let the component own isolated tables and reusable backend workflows
|
||||
- Add app wrappers if clients need to call into the component
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Component is inside `convex/components/<name>/`
|
||||
- [ ] App installs it with `app.use(...)`
|
||||
- [ ] Component owns only its own tables
|
||||
- [ ] App wrappers handle client-facing calls when needed
|
||||
@@ -1,51 +0,0 @@
|
||||
# Packaged Convex Components
|
||||
|
||||
Read this file when the user wants a reusable npm package or a component shared across multiple apps.
|
||||
|
||||
## When to Choose This
|
||||
|
||||
- The user wants to publish the component
|
||||
- The user wants a stable reusable package boundary
|
||||
- The component will be shared across multiple apps or teams
|
||||
|
||||
## Default Approach
|
||||
|
||||
- Prefer starting from `npx create-convex@latest --component` when possible
|
||||
- Keep the official authoring docs as the source of truth for package layout and exports
|
||||
- Validate the bundled package through an example app, not just the source files
|
||||
|
||||
## Build Flow
|
||||
|
||||
When building a packaged component, make sure the bundled output exists before the example app tries to consume it.
|
||||
|
||||
Recommended order:
|
||||
|
||||
1. `npx convex codegen --component-dir ./path/to/component`
|
||||
2. Run the package build command
|
||||
3. Run `npx convex dev --typecheck-components` in the example app
|
||||
|
||||
Do not assume normal app codegen is enough for packaged component workflows.
|
||||
|
||||
## Package Exports
|
||||
|
||||
If publishing to npm, make sure the package exposes the entry points apps need:
|
||||
|
||||
- package root for client helpers, types, or classes
|
||||
- `./convex.config.js` for installing the component
|
||||
- `./_generated/component.js` for the app-facing `ComponentApi` type
|
||||
- `./test` for testing helpers when applicable
|
||||
|
||||
## Testing
|
||||
|
||||
- Use `convex-test` for component logic
|
||||
- Register the component schema and modules with the test instance
|
||||
- Test app-side wrapper code from an example app that installs the package
|
||||
- Export a small helper from `./test` if consumers need easy test registration
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Packaging is actually required
|
||||
- [ ] Build order avoids bundle and codegen races
|
||||
- [ ] Package exports include install and typing entry points
|
||||
- [ ] Example app exercises the packaged component
|
||||
- [ ] Core behavior is covered by tests
|
||||
@@ -1,149 +0,0 @@
|
||||
---
|
||||
name: convex-migration-helper
|
||||
description: Plans Convex schema and data migrations with widen-migrate-narrow and @convex-dev/migrations. Use for breaking schema changes, backfills, table reshaping, or zero-downtime rollouts.
|
||||
---
|
||||
|
||||
# Convex Migration Helper
|
||||
|
||||
Safely migrate Convex schemas and data when making breaking changes.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Adding new required fields to existing tables
|
||||
- Changing field types or structure
|
||||
- Splitting or merging tables
|
||||
- Renaming or deleting fields
|
||||
- Migrating from nested to relational data
|
||||
|
||||
## When Not to Use
|
||||
|
||||
- Greenfield schema with no existing data in production or dev
|
||||
- Adding optional fields that do not need backfilling
|
||||
- Adding new tables with no existing data to migrate
|
||||
- Adding or removing indexes with no correctness concern
|
||||
- Questions about Convex schema design without a migration need
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Schema Validation Drives the Workflow
|
||||
|
||||
Convex will not let you deploy a schema that does not match the data at rest. This is the fundamental constraint that shapes every migration:
|
||||
|
||||
- You cannot add a required field if existing documents don't have it
|
||||
- You cannot change a field's type if existing documents have the old type
|
||||
- You cannot remove a field from the schema if existing documents still have it
|
||||
|
||||
This means migrations follow a predictable pattern: **widen the schema, migrate the data, narrow the schema**.
|
||||
|
||||
### Online Migrations
|
||||
|
||||
Convex migrations run online, meaning the app continues serving requests while data is updated asynchronously in batches. During the migration window, your code must handle both old and new data formats.
|
||||
|
||||
### Prefer New Fields Over Changing Types
|
||||
|
||||
When changing the shape of data, create a new field rather than modifying an existing one. This makes the transition safer and easier to roll back.
|
||||
|
||||
### Don't Delete Data
|
||||
|
||||
Unless you are certain, prefer deprecating fields over deleting them. Mark the field as `v.optional` and add a code comment explaining it is deprecated and why it existed.
|
||||
|
||||
## Safe Changes (No Migration Needed)
|
||||
|
||||
### Adding Optional Field
|
||||
|
||||
```typescript
|
||||
// Before
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
});
|
||||
|
||||
// After - safe, new field is optional
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
bio: v.optional(v.string()),
|
||||
});
|
||||
```
|
||||
|
||||
### Adding New Table
|
||||
|
||||
```typescript
|
||||
posts: defineTable({
|
||||
userId: v.id("users"),
|
||||
title: v.string(),
|
||||
}).index("by_user", ["userId"]);
|
||||
```
|
||||
|
||||
### Adding Index
|
||||
|
||||
```typescript
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
email: v.string(),
|
||||
}).index("by_email", ["email"]);
|
||||
```
|
||||
|
||||
## Breaking Changes: The Deployment Workflow
|
||||
|
||||
Every breaking migration follows the same multi-deploy pattern:
|
||||
|
||||
**Deploy 1 - Widen the schema:**
|
||||
|
||||
1. Update schema to allow both old and new formats (e.g., add optional new field)
|
||||
2. Update code to handle both formats when reading
|
||||
3. Update code to write the new format for new documents
|
||||
4. Deploy
|
||||
|
||||
**Between deploys - Migrate data:**
|
||||
|
||||
5. Run migration to backfill existing documents
|
||||
6. Verify all documents are migrated
|
||||
|
||||
**Deploy 2 - Narrow the schema:**
|
||||
|
||||
7. Update schema to require the new format only
|
||||
8. Remove code that handles the old format
|
||||
9. Deploy
|
||||
|
||||
## Using the Migrations Component
|
||||
|
||||
For any non-trivial migration, use the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component. It handles batching, cursor-based pagination, state tracking, resume from failure, dry runs, and progress monitoring.
|
||||
|
||||
See `references/migrations-component.md` for installation, setup, defining and running migrations, dry runs, status monitoring, and configuration options.
|
||||
|
||||
## Common Migration Patterns
|
||||
|
||||
See `references/migration-patterns.md` for complete patterns with code examples covering:
|
||||
|
||||
- Adding a required field
|
||||
- Deleting a field
|
||||
- Changing a field type
|
||||
- Splitting nested data into a separate table
|
||||
- Cleaning up orphaned documents
|
||||
- Zero-downtime strategies (dual write, dual read)
|
||||
- Small table shortcut (single internalMutation without the component)
|
||||
- Verifying a migration is complete
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Making a field required before migrating data**: Convex rejects the deploy because existing documents lack the field. Always widen the schema first.
|
||||
2. **Using `.collect()` on large tables**: Hits transaction limits or causes timeouts. Use the migrations component for proper batched pagination. `.collect()` is only safe for tables you know are small.
|
||||
3. **Not writing the new format before migrating**: Documents created during the migration window will be missed, leaving unmigrated data after the migration "completes."
|
||||
4. **Skipping the dry run**: Use `dryRun: true` to validate migration logic before committing changes to production data. Catches bugs before they touch real documents.
|
||||
5. **Deleting fields prematurely**: Prefer deprecating with `v.optional` and a comment. Only delete after you are confident the data is no longer needed and no code references it.
|
||||
6. **Using crons for migration batches**: The migrations component handles batching via recursive scheduling internally. Crons require manual cleanup and an extra deploy to remove.
|
||||
|
||||
## Migration Checklist
|
||||
|
||||
- [ ] Identify the breaking change and plan the multi-deploy workflow
|
||||
- [ ] Update schema to allow both old and new formats
|
||||
- [ ] Update code to handle both formats when reading
|
||||
- [ ] Update code to write the new format for new documents
|
||||
- [ ] Deploy widened schema and updated code
|
||||
- [ ] Define migration using the `@convex-dev/migrations` component
|
||||
- [ ] Test with `dryRun: true`
|
||||
- [ ] Run migration and monitor status
|
||||
- [ ] Verify all documents are migrated
|
||||
- [ ] Update schema to require new format only
|
||||
- [ ] Clean up code that handled old format
|
||||
- [ ] Deploy final schema and code
|
||||
- [ ] Remove migration code once confirmed stable
|
||||
@@ -1,10 +0,0 @@
|
||||
interface:
|
||||
display_name: "Convex Migration Helper"
|
||||
short_description: "Plan and run safe Convex schema and data migrations."
|
||||
icon_small: "./assets/icon.svg"
|
||||
icon_large: "./assets/icon.svg"
|
||||
brand_color: "#8B5CF6"
|
||||
default_prompt: "Help me plan and execute this Convex migration safely. Start by identifying the schema change, the existing data shape, and the widen-migrate-narrow path before making edits."
|
||||
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 386 B |
@@ -1,231 +0,0 @@
|
||||
# Migration Patterns Reference
|
||||
|
||||
Common migration patterns, zero-downtime strategies, and verification techniques for Convex schema and data migrations.
|
||||
|
||||
## Adding a Required Field
|
||||
|
||||
```typescript
|
||||
// Deploy 1: Schema allows both states
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
role: v.optional(v.union(v.literal("user"), v.literal("admin"))),
|
||||
});
|
||||
|
||||
// Migration: backfill the field
|
||||
export const addDefaultRole = migrations.define({
|
||||
table: "users",
|
||||
migrateOne: async (ctx, user) => {
|
||||
if (user.role === undefined) {
|
||||
await ctx.db.patch(user._id, { role: "user" });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Deploy 2: After migration completes, make it required
|
||||
users: defineTable({
|
||||
name: v.string(),
|
||||
role: v.union(v.literal("user"), v.literal("admin")),
|
||||
});
|
||||
```
|
||||
|
||||
## Deleting a Field
|
||||
|
||||
Mark the field optional first, migrate data to remove it, then remove from schema:
|
||||
|
||||
```typescript
|
||||
// Deploy 1: Make optional
|
||||
// isPro: v.boolean() --> isPro: v.optional(v.boolean())
|
||||
|
||||
// Migration
|
||||
export const removeIsPro = migrations.define({
|
||||
table: "teams",
|
||||
migrateOne: async (ctx, team) => {
|
||||
if (team.isPro !== undefined) {
|
||||
await ctx.db.patch(team._id, { isPro: undefined });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Deploy 2: Remove isPro from schema entirely
|
||||
```
|
||||
|
||||
## Changing a Field Type
|
||||
|
||||
Prefer creating a new field. You can combine adding and deleting in one migration:
|
||||
|
||||
```typescript
|
||||
// Deploy 1: Add new field, keep old field optional
|
||||
// isPro: v.boolean() --> isPro: v.optional(v.boolean()), plan: v.optional(...)
|
||||
|
||||
// Migration: convert old field to new field
|
||||
export const convertToEnum = migrations.define({
|
||||
table: "teams",
|
||||
migrateOne: async (ctx, team) => {
|
||||
if (team.plan === undefined) {
|
||||
await ctx.db.patch(team._id, {
|
||||
plan: team.isPro ? "pro" : "basic",
|
||||
isPro: undefined,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Deploy 2: Remove isPro from schema, make plan required
|
||||
```
|
||||
|
||||
## Splitting Nested Data Into a Separate Table
|
||||
|
||||
```typescript
|
||||
export const extractPreferences = migrations.define({
|
||||
table: "users",
|
||||
migrateOne: async (ctx, user) => {
|
||||
if (user.preferences === undefined) return;
|
||||
|
||||
const existing = await ctx.db
|
||||
.query("userPreferences")
|
||||
.withIndex("by_user", (q) => q.eq("userId", user._id))
|
||||
.first();
|
||||
|
||||
if (!existing) {
|
||||
await ctx.db.insert("userPreferences", {
|
||||
userId: user._id,
|
||||
...user.preferences,
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.patch(user._id, { preferences: undefined });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Make sure your code is already writing to the new `userPreferences` table for new users before running this migration, so you don't miss documents created during the migration window.
|
||||
|
||||
## Cleaning Up Orphaned Documents
|
||||
|
||||
```typescript
|
||||
export const deleteOrphanedEmbeddings = migrations.define({
|
||||
table: "embeddings",
|
||||
migrateOne: async (ctx, doc) => {
|
||||
const chunk = await ctx.db
|
||||
.query("chunks")
|
||||
.withIndex("by_embedding", (q) => q.eq("embeddingId", doc._id))
|
||||
.first();
|
||||
|
||||
if (!chunk) {
|
||||
await ctx.db.delete(doc._id);
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Zero-Downtime Strategies
|
||||
|
||||
During the migration window, your app must handle both old and new data formats. There are two main strategies.
|
||||
|
||||
### Dual Write (Preferred)
|
||||
|
||||
Write to both old and new structures. Read from the old structure until migration is complete.
|
||||
|
||||
1. Deploy code that writes both formats, reads old format
|
||||
2. Run migration on existing data
|
||||
3. Deploy code that reads new format, still writes both
|
||||
4. Deploy code that only reads and writes new format
|
||||
|
||||
This is preferred because you can safely roll back at any point, the old format is always up to date.
|
||||
|
||||
```typescript
|
||||
// Bad: only writing to new structure before migration is done
|
||||
export const createTeam = mutation({
|
||||
args: { name: v.string(), isPro: v.boolean() },
|
||||
handler: async (ctx, args) => {
|
||||
await ctx.db.insert("teams", {
|
||||
name: args.name,
|
||||
plan: args.isPro ? "pro" : "basic",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Good: writing to both structures during migration
|
||||
export const createTeam = mutation({
|
||||
args: { name: v.string(), isPro: v.boolean() },
|
||||
handler: async (ctx, args) => {
|
||||
const plan = args.isPro ? "pro" : "basic";
|
||||
await ctx.db.insert("teams", {
|
||||
name: args.name,
|
||||
isPro: args.isPro,
|
||||
plan,
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Dual Read
|
||||
|
||||
Read both formats. Write only the new format.
|
||||
|
||||
1. Deploy code that reads both formats (preferring new), writes only new format
|
||||
2. Run migration on existing data
|
||||
3. Deploy code that reads and writes only new format
|
||||
|
||||
This avoids duplicating writes, which is useful when having two copies of data could cause inconsistencies. The downside is that rolling back to before step 1 is harder, since new documents only have the new format.
|
||||
|
||||
```typescript
|
||||
// Good: reading both formats, preferring new
|
||||
function getTeamPlan(team: Doc<"teams">): "basic" | "pro" {
|
||||
if (team.plan !== undefined) return team.plan;
|
||||
return team.isPro ? "pro" : "basic";
|
||||
}
|
||||
```
|
||||
|
||||
## Small Table Shortcut
|
||||
|
||||
For small tables (a few thousand documents at most), you can migrate in a single `internalMutation` without the component:
|
||||
|
||||
```typescript
|
||||
import { internalMutation } from "./_generated/server";
|
||||
|
||||
export const backfillSmallTable = internalMutation({
|
||||
handler: async (ctx) => {
|
||||
const docs = await ctx.db.query("smallConfig").collect();
|
||||
for (const doc of docs) {
|
||||
if (doc.newField === undefined) {
|
||||
await ctx.db.patch(doc._id, { newField: "default" });
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```bash
|
||||
npx convex run migrations:backfillSmallTable
|
||||
```
|
||||
|
||||
Only use `.collect()` when you are certain the table is small. For anything larger, use the migrations component.
|
||||
|
||||
## Verifying a Migration
|
||||
|
||||
Query to check remaining unmigrated documents:
|
||||
|
||||
```typescript
|
||||
import { query } from "./_generated/server";
|
||||
|
||||
export const verifyMigration = query({
|
||||
handler: async (ctx) => {
|
||||
const remaining = await ctx.db
|
||||
.query("users")
|
||||
.filter((q) => q.eq(q.field("role"), undefined))
|
||||
.take(10);
|
||||
|
||||
return {
|
||||
complete: remaining.length === 0,
|
||||
sampleRemaining: remaining.map((u) => u._id),
|
||||
};
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Or use the component's built-in status monitoring:
|
||||
|
||||
```bash
|
||||
npx convex run --component migrations lib:getStatus --watch
|
||||
```
|
||||
@@ -1,169 +0,0 @@
|
||||
# Migrations Component Reference
|
||||
|
||||
Complete guide to the [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component for batched, resumable Convex data migrations.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @convex-dev/migrations
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
```typescript
|
||||
// convex/convex.config.ts
|
||||
import { defineApp } from "convex/server";
|
||||
import migrations from "@convex-dev/migrations/convex.config.js";
|
||||
|
||||
const app = defineApp();
|
||||
app.use(migrations);
|
||||
export default app;
|
||||
```
|
||||
|
||||
```typescript
|
||||
// convex/migrations.ts
|
||||
import { Migrations } from "@convex-dev/migrations";
|
||||
import { components } from "./_generated/api.js";
|
||||
import { DataModel } from "./_generated/dataModel.js";
|
||||
|
||||
export const migrations = new Migrations<DataModel>(components.migrations);
|
||||
export const run = migrations.runner();
|
||||
```
|
||||
|
||||
The `DataModel` type parameter is optional but provides type safety for migration definitions.
|
||||
|
||||
## Define a Migration
|
||||
|
||||
The `migrateOne` function processes a single document. The component handles batching and pagination automatically.
|
||||
|
||||
```typescript
|
||||
// convex/migrations.ts
|
||||
export const addDefaultRole = migrations.define({
|
||||
table: "users",
|
||||
migrateOne: async (ctx, user) => {
|
||||
if (user.role === undefined) {
|
||||
await ctx.db.patch(user._id, { role: "user" });
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Shorthand: if you return an object, it is applied as a patch automatically.
|
||||
|
||||
```typescript
|
||||
export const clearDeprecatedField = migrations.define({
|
||||
table: "users",
|
||||
migrateOne: () => ({ legacyField: undefined }),
|
||||
});
|
||||
```
|
||||
|
||||
## Run a Migration
|
||||
|
||||
From the CLI:
|
||||
|
||||
```bash
|
||||
# Define a one-off runner in convex/migrations.ts:
|
||||
# export const runIt = migrations.runner(internal.migrations.addDefaultRole);
|
||||
npx convex run migrations:runIt
|
||||
|
||||
# Or use the general-purpose runner
|
||||
npx convex run migrations:run '{"fn": "migrations:addDefaultRole"}'
|
||||
```
|
||||
|
||||
Programmatically from another Convex function:
|
||||
|
||||
```typescript
|
||||
await migrations.runOne(ctx, internal.migrations.addDefaultRole);
|
||||
```
|
||||
|
||||
## Run Multiple Migrations in Order
|
||||
|
||||
```typescript
|
||||
export const runAll = migrations.runner([
|
||||
internal.migrations.addDefaultRole,
|
||||
internal.migrations.clearDeprecatedField,
|
||||
internal.migrations.normalizeEmails,
|
||||
]);
|
||||
```
|
||||
|
||||
```bash
|
||||
npx convex run migrations:runAll
|
||||
```
|
||||
|
||||
If one fails, it stops and will not continue to the next. Call it again to retry from where it left off. Completed migrations are skipped automatically.
|
||||
|
||||
## Dry Run
|
||||
|
||||
Test a migration before committing changes:
|
||||
|
||||
```bash
|
||||
npx convex run migrations:runIt '{"dryRun": true}'
|
||||
```
|
||||
|
||||
This runs one batch and then rolls back, so you can see what it would do without changing any data.
|
||||
|
||||
## Check Migration Status
|
||||
|
||||
```bash
|
||||
npx convex run --component migrations lib:getStatus --watch
|
||||
```
|
||||
|
||||
## Cancel a Running Migration
|
||||
|
||||
```bash
|
||||
npx convex run --component migrations lib:cancel '{"name": "migrations:addDefaultRole"}'
|
||||
```
|
||||
|
||||
Or programmatically:
|
||||
|
||||
```typescript
|
||||
await migrations.cancel(ctx, internal.migrations.addDefaultRole);
|
||||
```
|
||||
|
||||
## Run Migrations on Deploy
|
||||
|
||||
Chain migration execution after deploying:
|
||||
|
||||
```bash
|
||||
npx convex deploy --cmd 'npm run build' && npx convex run migrations:runAll --prod
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Custom Batch Size
|
||||
|
||||
If documents are large or the table has heavy write traffic, reduce the batch size to avoid transaction limits or OCC conflicts:
|
||||
|
||||
```typescript
|
||||
export const migrateHeavyTable = migrations.define({
|
||||
table: "largeDocuments",
|
||||
batchSize: 10,
|
||||
migrateOne: async (ctx, doc) => {
|
||||
// migration logic
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Migrate a Subset Using an Index
|
||||
|
||||
Process only matching documents instead of the full table:
|
||||
|
||||
```typescript
|
||||
export const fixEmptyNames = migrations.define({
|
||||
table: "users",
|
||||
customRange: (query) => query.withIndex("by_name", (q) => q.eq("name", "")),
|
||||
migrateOne: () => ({ name: "<unknown>" }),
|
||||
});
|
||||
```
|
||||
|
||||
### Parallelize Within a Batch
|
||||
|
||||
By default each document in a batch is processed serially. Enable parallel processing if your migration logic does not depend on ordering:
|
||||
|
||||
```typescript
|
||||
export const clearField = migrations.define({
|
||||
table: "myTable",
|
||||
parallelize: true,
|
||||
migrateOne: () => ({ optionalField: undefined }),
|
||||
});
|
||||
```
|
||||
@@ -1,143 +0,0 @@
|
||||
---
|
||||
name: convex-performance-audit
|
||||
description: Audits Convex performance for reads, subscriptions, write contention, and function limits. Use for slow features, insights findings, OCC conflicts, or read amplification.
|
||||
---
|
||||
|
||||
# Convex Performance Audit
|
||||
|
||||
Diagnose and fix performance problems in Convex applications, one problem class at a time.
|
||||
|
||||
## When to Use
|
||||
|
||||
- A Convex page or feature feels slow or expensive
|
||||
- `npx convex insights --details` reports high bytes read, documents read, or OCC conflicts
|
||||
- Low-freshness read paths are using reactivity where point-in-time reads would do
|
||||
- OCC conflict errors or excessive mutation retries
|
||||
- High subscription count or slow UI updates
|
||||
- Functions approaching execution or transaction limits
|
||||
- The same performance pattern needs fixing across sibling functions
|
||||
|
||||
## When Not to Use
|
||||
|
||||
- Initial Convex setup, auth setup, or component extraction
|
||||
- Pure schema migrations with no performance goal
|
||||
- One-off micro-optimizations without a user-visible or deployment-visible problem
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Prefer simpler code when scale is small, traffic is modest, or the available signals are weak
|
||||
- Do not recommend digest tables, document splitting, fetch-strategy changes, or migration-heavy rollouts unless there is a measured signal, a clearly unbounded path, or a known hot read/write path
|
||||
- In Convex, a simple scan on a small table is often acceptable. Do not invent structural work just because a pattern is not ideal at large scale
|
||||
|
||||
## First Step: Gather Signals
|
||||
|
||||
Start with the strongest signal available:
|
||||
|
||||
1. If deployment Health insights are already available from the user or the current context, treat them as a first-class source of performance signals.
|
||||
2. If CLI insights are available, run `npx convex insights --details`. Use `--prod`, `--preview-name`, or `--deployment-name` when needed.
|
||||
- If the local repo's Convex CLI is too old to support `insights`, try `npx -y convex@latest insights --details` before giving up.
|
||||
3. If the repo already uses `convex-doctor`, you may treat its findings as hints. Do not require it, and do not treat it as the source of truth.
|
||||
4. If runtime signals are unavailable, audit from code anyway, but keep the guardrails above in mind. Lack of insights is not proof of health, but it is also not proof that a large refactor is warranted.
|
||||
|
||||
## Signal Routing
|
||||
|
||||
After gathering signals, identify the problem class and read the matching reference file.
|
||||
|
||||
| Signal | Reference |
|
||||
| -------------------------------------------------------------- | ----------------------------------------- |
|
||||
| High bytes or documents read, JS filtering, unnecessary joins | `references/hot-path-rules.md` |
|
||||
| OCC conflict errors, write contention, mutation retries | `references/occ-conflicts.md` |
|
||||
| High subscription count, slow UI updates, excessive re-renders | `references/subscription-cost.md` |
|
||||
| Function timeouts, transaction size errors, large payloads | `references/function-budget.md` |
|
||||
| General "it's slow" with no specific signal | Start with `references/hot-path-rules.md` |
|
||||
|
||||
Multiple problem classes can overlap. Read the most relevant reference first, then check the others if symptoms remain.
|
||||
|
||||
## Escalate Larger Fixes
|
||||
|
||||
If the likely fix is invasive, cross-cutting, or migration-heavy, stop and present options before editing.
|
||||
|
||||
Examples:
|
||||
|
||||
- introducing digest or summary tables across multiple flows
|
||||
- splitting documents to isolate frequently-updated fields
|
||||
- reworking pagination or fetch strategy across several screens
|
||||
- switching to a new index or denormalized field that needs migration-safe rollout
|
||||
|
||||
When correctness depends on handling old and new states during a rollout, consult `skills/convex-migration-helper/SKILL.md` for the migration workflow.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Scope the problem
|
||||
|
||||
Pick one concrete user flow from the actual project. Look at the codebase, client pages, and API surface to find the flow that matches the symptom.
|
||||
|
||||
Write down:
|
||||
|
||||
- entrypoint functions
|
||||
- client callsites using `useQuery`, `usePaginatedQuery`, or `useMutation`
|
||||
- tables read
|
||||
- tables written
|
||||
- whether the path is high-read, high-write, or both
|
||||
|
||||
### 2. Trace the full read and write set
|
||||
|
||||
For each function in the path:
|
||||
|
||||
1. Trace every `ctx.db.get()` and `ctx.db.query()`
|
||||
2. Trace every `ctx.db.patch()`, `ctx.db.replace()`, and `ctx.db.insert()`
|
||||
3. Note foreign-key lookups, JS-side filtering, and full-document reads
|
||||
4. Identify all sibling functions touching the same tables
|
||||
5. Identify reactive stats, aggregates, or widgets rendered on the same page
|
||||
|
||||
In Convex, every extra read increases transaction work, and every write can invalidate reactive subscribers. Treat read amplification and invalidation amplification as first-class problems.
|
||||
|
||||
### 3. Apply fixes from the relevant reference
|
||||
|
||||
Read the reference file matching your problem class. Each reference includes specific patterns, code examples, and a recommended fix order.
|
||||
|
||||
Do not stop at the single function named by an insight. Trace sibling readers and writers touching the same tables.
|
||||
|
||||
### 4. Fix sibling functions together
|
||||
|
||||
When one function touching a table has a performance bug, audit sibling functions for the same pattern.
|
||||
|
||||
After finding one problem, inspect both sibling readers and sibling writers for the same table family, including companion digest or summary tables.
|
||||
|
||||
Examples:
|
||||
|
||||
- If one list query switches from full docs to a digest table, inspect the other list queries for that table
|
||||
- If one mutation isolates a frequently-updated field or splits a hot document, inspect the other writers to the same table
|
||||
- If one read path needs a migration-safe rollout for an unbackfilled field, inspect sibling reads for the same rollout risk
|
||||
|
||||
Do not leave one path fixed and another path on the old pattern unless there is a clear product reason.
|
||||
|
||||
### 5. Verify before finishing
|
||||
|
||||
Confirm all of these:
|
||||
|
||||
1. Results are the same as before, no dropped records
|
||||
2. Eliminated reads or writes are no longer in the path where expected
|
||||
3. Fallback behavior works when denormalized or indexed fields are missing
|
||||
4. Frequently-updated fields are isolated from widely-read documents where needed
|
||||
5. Every relevant sibling reader and writer was inspected, not just the original function
|
||||
|
||||
## Reference Files
|
||||
|
||||
- `references/hot-path-rules.md` - Read amplification, invalidation, denormalization, indexes, digest tables
|
||||
- `references/occ-conflicts.md` - Write contention, OCC resolution, hot document splitting
|
||||
- `references/subscription-cost.md` - Reactive query cost, subscription granularity, point-in-time reads
|
||||
- `references/function-budget.md` - Execution limits, transaction size, large documents, payload size
|
||||
|
||||
Also check the official [Convex Best Practices](https://docs.convex.dev/understanding/best-practices/) page for additional patterns covering argument validation, access control, and code organization that may surface during the audit.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Gathered signals from insights, dashboard, or code audit
|
||||
- [ ] Identified the problem class and read the matching reference
|
||||
- [ ] Scoped one concrete user flow or function path
|
||||
- [ ] Traced every read and write in that path
|
||||
- [ ] Identified sibling functions touching the same tables
|
||||
- [ ] Applied fixes from the reference, following the recommended fix order
|
||||
- [ ] Fixed sibling functions consistently
|
||||
- [ ] Verified behavior and confirmed no regressions
|
||||
@@ -1,10 +0,0 @@
|
||||
interface:
|
||||
display_name: "Convex Performance Audit"
|
||||
short_description: "Audit slow Convex reads, subscriptions, OCC conflicts, and limits."
|
||||
icon_small: "./assets/icon.svg"
|
||||
icon_large: "./assets/icon.svg"
|
||||
brand_color: "#EF4444"
|
||||
default_prompt: "Audit this Convex app for performance issues. Start with the strongest signal available, identify the problem class, and suggest the smallest high-impact fix before proposing bigger structural changes."
|
||||
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 0 0 2.25-2.25V6.75a2.25 2.25 0 0 0-2.25-2.25H6.75A2.25 2.25 0 0 0 4.5 6.75v10.5a2.25 2.25 0 0 0 2.25 2.25Zm.75-12h9v9h-9v-9Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 490 B |
@@ -1,232 +0,0 @@
|
||||
# Function Budget
|
||||
|
||||
Use these rules when functions are hitting execution limits, transaction size errors, or returning excessively large payloads to the client.
|
||||
|
||||
## Core Principle
|
||||
|
||||
Convex functions run inside transactions with budgets for time, reads, and writes. Staying well within these limits is not just about avoiding errors, it reduces latency and contention.
|
||||
|
||||
## Limits to Know
|
||||
|
||||
These are the current values from the [Convex limits docs](https://docs.convex.dev/production/state/limits). Check that page for the latest numbers.
|
||||
|
||||
| Resource | Limit |
|
||||
| --------------------------------- | ----------------------------------------------------- |
|
||||
| Query/mutation execution time | 1 second (user code only, excludes DB operations) |
|
||||
| Action execution time | 10 minutes |
|
||||
| Data read per transaction | 16 MiB |
|
||||
| Data written per transaction | 16 MiB |
|
||||
| Documents scanned per transaction | 32,000 (includes documents filtered out by `.filter`) |
|
||||
| Index ranges read per transaction | 4,096 (each `db.get` and `db.query` call) |
|
||||
| Documents written per transaction | 16,000 |
|
||||
| Individual document size | 1 MiB |
|
||||
| Function return value size | 16 MiB |
|
||||
|
||||
## Symptoms
|
||||
|
||||
- "Function execution took too long" errors
|
||||
- "Transaction too large" or read/write set size errors
|
||||
- Slow queries that read many documents
|
||||
- Client receiving large payloads that slow down page load
|
||||
- `npx convex insights --details` showing high bytes read
|
||||
|
||||
## Common Causes
|
||||
|
||||
### Unbounded collection
|
||||
|
||||
A query that calls `.collect()` on a table without a reasonable limit. As the table grows, the query reads more and more documents.
|
||||
|
||||
### Large document reads on hot paths
|
||||
|
||||
Reading documents with large fields (rich text, embedded media references, long arrays) when only a small subset of the data is needed for the current view.
|
||||
|
||||
### Mutation doing too much work
|
||||
|
||||
A single mutation that updates hundreds of documents, backfills data, or rebuilds derived state in one transaction.
|
||||
|
||||
### Returning too much data to the client
|
||||
|
||||
A query returning full documents when the client only needs a few fields.
|
||||
|
||||
## Fix Order
|
||||
|
||||
### 1. Bound your reads
|
||||
|
||||
Never `.collect()` without a limit on a table that can grow unbounded.
|
||||
|
||||
```ts
|
||||
// Bad: unbounded read, breaks as the table grows
|
||||
const messages = await ctx.db.query("messages").collect();
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: paginate or limit
|
||||
const messages = await ctx.db
|
||||
.query("messages")
|
||||
.withIndex("by_channel", (q) => q.eq("channelId", channelId))
|
||||
.order("desc")
|
||||
.take(50);
|
||||
```
|
||||
|
||||
### 2. Read smaller shapes
|
||||
|
||||
If the list page only needs title, author, and date, do not read full documents with rich content fields.
|
||||
|
||||
Use digest or summary tables for hot list pages. See `hot-path-rules.md` for the digest table pattern.
|
||||
|
||||
### 3. Break large mutations into batches
|
||||
|
||||
If a mutation needs to update hundreds of documents, split it into a self-scheduling chain.
|
||||
|
||||
```ts
|
||||
// Bad: one mutation updating every row
|
||||
export const backfillAll = internalMutation({
|
||||
handler: async (ctx) => {
|
||||
const docs = await ctx.db.query("items").collect();
|
||||
for (const doc of docs) {
|
||||
await ctx.db.patch(doc._id, { newField: computeValue(doc) });
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: cursor-based batch processing
|
||||
export const backfillBatch = internalMutation({
|
||||
args: { cursor: v.optional(v.string()), batchSize: v.optional(v.number()) },
|
||||
handler: async (ctx, args) => {
|
||||
const batchSize = args.batchSize ?? 100;
|
||||
const result = await ctx.db
|
||||
.query("items")
|
||||
.paginate({ cursor: args.cursor ?? null, numItems: batchSize });
|
||||
|
||||
for (const doc of result.page) {
|
||||
if (doc.newField === undefined) {
|
||||
await ctx.db.patch(doc._id, { newField: computeValue(doc) });
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.isDone) {
|
||||
await ctx.scheduler.runAfter(0, internal.items.backfillBatch, {
|
||||
cursor: result.continueCursor,
|
||||
batchSize,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### 4. Move heavy work to actions
|
||||
|
||||
Queries and mutations run inside Convex's transactional runtime with strict budgets. If you need to do CPU-intensive computation, call external APIs, or process large files, use an action instead.
|
||||
|
||||
Actions run outside the transaction and can call mutations to write results back.
|
||||
|
||||
```ts
|
||||
// Bad: heavy computation inside a mutation
|
||||
export const processUpload = mutation({
|
||||
handler: async (ctx, args) => {
|
||||
const result = expensiveComputation(args.data);
|
||||
await ctx.db.insert("results", result);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: action for heavy work, mutation for the write
|
||||
export const processUpload = action({
|
||||
handler: async (ctx, args) => {
|
||||
const result = expensiveComputation(args.data);
|
||||
await ctx.runMutation(internal.results.store, { result });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### 5. Trim return values
|
||||
|
||||
Only return what the client needs. If a query fetches full documents but the component only renders a few fields, map the results before returning.
|
||||
|
||||
```ts
|
||||
// Bad: returns full documents including large content fields
|
||||
export const list = query({
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db.query("articles").take(20);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: project to only the fields the client needs
|
||||
export const list = query({
|
||||
handler: async (ctx) => {
|
||||
const articles = await ctx.db.query("articles").take(20);
|
||||
return articles.map((a) => ({
|
||||
_id: a._id,
|
||||
title: a.title,
|
||||
author: a.author,
|
||||
createdAt: a._creationTime,
|
||||
}));
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### 6. Replace `ctx.runQuery` and `ctx.runMutation` with helper functions
|
||||
|
||||
Inside queries and mutations, `ctx.runQuery` and `ctx.runMutation` have overhead compared to calling a plain TypeScript helper function. They run in the same transaction but pay extra per-call cost.
|
||||
|
||||
```ts
|
||||
// Bad: unnecessary overhead from ctx.runQuery inside a mutation
|
||||
export const createProject = mutation({
|
||||
handler: async (ctx, args) => {
|
||||
const user = await ctx.runQuery(api.users.getCurrentUser);
|
||||
await ctx.db.insert("projects", { ...args, ownerId: user._id });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: plain helper function, no extra overhead
|
||||
export const createProject = mutation({
|
||||
handler: async (ctx, args) => {
|
||||
const user = await getCurrentUser(ctx);
|
||||
await ctx.db.insert("projects", { ...args, ownerId: user._id });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Exception: components require `ctx.runQuery`/`ctx.runMutation`. Use them there, but prefer helpers everywhere else.
|
||||
|
||||
### 7. Avoid unnecessary `runAction` calls
|
||||
|
||||
`runAction` from within an action creates a separate function invocation with its own memory and CPU budget. The parent action just sits idle waiting. Replace with a plain TypeScript function call unless you need a different runtime (e.g. calling Node.js code from the Convex runtime).
|
||||
|
||||
```ts
|
||||
// Bad: runAction overhead for no reason
|
||||
export const processItems = action({
|
||||
handler: async (ctx, args) => {
|
||||
for (const item of args.items) {
|
||||
await ctx.runAction(internal.items.processOne, { item });
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: plain function call
|
||||
export const processItems = action({
|
||||
handler: async (ctx, args) => {
|
||||
for (const item of args.items) {
|
||||
await processOneItem(ctx, { item });
|
||||
}
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
1. No function execution or transaction size errors
|
||||
2. `npx convex insights --details` shows reduced bytes read
|
||||
3. Large mutations are batched and self-scheduling
|
||||
4. Client payloads are reasonably sized for the UI they serve
|
||||
5. `ctx.runQuery`/`ctx.runMutation` in queries and mutations replaced with helpers where possible
|
||||
6. Sibling functions with similar patterns were checked
|
||||
@@ -1,369 +0,0 @@
|
||||
# Hot Path Rules
|
||||
|
||||
Use these rules when the top-level workflow points to read amplification, denormalization, index rollout, reactive query cost, or invalidation-heavy writes.
|
||||
|
||||
## Contents
|
||||
|
||||
- Core Principle
|
||||
- Consistency Rule
|
||||
- 1. Push Filters To Storage (indexes, migration rule, redundant indexes)
|
||||
- 2. Minimize Data Sources (denormalization, fallback rule)
|
||||
- 3. Minimize Row Size (digest tables)
|
||||
- 4. Skip No-Op Writes
|
||||
- 5. Match Consistency To Read Patterns (high-read/low-write, high-read/high-write)
|
||||
- Convex-Specific Notes (reactive queries, point-in-time reads, triggers, aggregates, backfills)
|
||||
- Verification
|
||||
|
||||
## Core Principle
|
||||
|
||||
Every byte read or written multiplies with concurrency.
|
||||
|
||||
Think:
|
||||
|
||||
`cost x calls_per_second x 86400`
|
||||
|
||||
In Convex, every write can also fan out into reactive invalidation, replication work, and downstream sync.
|
||||
|
||||
## Consistency Rule
|
||||
|
||||
If you fix a hot-path pattern for one function, audit sibling functions touching the same tables for the same pattern.
|
||||
|
||||
Do this especially for:
|
||||
|
||||
- multiple list queries over the same table
|
||||
- multiple writers to the same table
|
||||
- public browse and search queries over the same records
|
||||
- helper functions reused by more than one endpoint
|
||||
|
||||
## 1. Push Filters To Storage
|
||||
|
||||
Both JavaScript `.filter()` and the Convex query `.filter()` method after a DB scan mean you already paid for the read. The Convex `.filter()` method has the same performance as filtering in JS, it does not push the predicate to the storage layer. Only `.withIndex()` and `.withSearchIndex()` actually reduce the documents scanned.
|
||||
|
||||
Prefer:
|
||||
|
||||
- `withIndex(...)`
|
||||
- `.withSearchIndex(...)` for text search
|
||||
- narrower tables
|
||||
- summary tables
|
||||
|
||||
before accepting a scan-plus-filter pattern.
|
||||
|
||||
```ts
|
||||
// Bad: scans then filters in JavaScript
|
||||
export const listOpen = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const tasks = await ctx.db.query("tasks").collect();
|
||||
return tasks.filter((task) => task.status === "open");
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Also bad: Convex .filter() does not push to storage either
|
||||
export const listOpen = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db
|
||||
.query("tasks")
|
||||
.filter((q) => q.eq(q.field("status"), "open"))
|
||||
.collect();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: use an index so storage does the filtering
|
||||
export const listOpen = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db
|
||||
.query("tasks")
|
||||
.withIndex("by_status", (q) => q.eq("status", "open"))
|
||||
.collect();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Migration rule for indexes
|
||||
|
||||
New indexes on partially backfilled fields can create correctness bugs during rollout.
|
||||
|
||||
Important Convex detail:
|
||||
|
||||
`undefined !== false`
|
||||
|
||||
If an older document is missing a field entirely, it will not match a compound index entry that expects `false`.
|
||||
|
||||
Do not trust old comments saying a field is "not backfilled" or "already backfilled". Verify.
|
||||
|
||||
If correctness depends on handling old and new states during rollout, do not improvise a partial-backfill workaround in the hot path. Use a migration-safe rollout and consult `skills/convex-migration-helper/SKILL.md`.
|
||||
|
||||
```ts
|
||||
// Bad: optional booleans can miss older rows where the field is undefined
|
||||
const projects = await ctx.db
|
||||
.query("projects")
|
||||
.withIndex("by_archived_and_updated", (q) => q.eq("isArchived", false))
|
||||
.order("desc")
|
||||
.take(20);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: switch hot-path reads only after the rollout is migration-safe
|
||||
// See the migration helper skill for dual-read / backfill / cutover patterns.
|
||||
```
|
||||
|
||||
### Check for redundant indexes
|
||||
|
||||
Indexes like `by_foo` and `by_foo_and_bar` are usually redundant. You only need `by_foo_and_bar`, since you can query it with just the `foo` condition and omit `bar`. Extra indexes add storage cost and write overhead on every insert, patch, and delete.
|
||||
|
||||
```ts
|
||||
// Bad: two indexes where one would do
|
||||
defineTable({ team: v.id("teams"), user: v.id("users") })
|
||||
.index("by_team", ["team"])
|
||||
.index("by_team_and_user", ["team", "user"]);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: single compound index serves both query patterns
|
||||
defineTable({ team: v.id("teams"), user: v.id("users") }).index(
|
||||
"by_team_and_user",
|
||||
["team", "user"],
|
||||
);
|
||||
```
|
||||
|
||||
Exception: `.index("by_foo", ["foo"])` is really an index on `foo` + `_creationTime`, while `.index("by_foo_and_bar", ["foo", "bar"])` is on `foo` + `bar` + `_creationTime`. If you need results sorted by `foo` then `_creationTime`, you need the single-field index because the compound one would sort by `bar` first.
|
||||
|
||||
## 2. Minimize Data Sources
|
||||
|
||||
Trace every read.
|
||||
|
||||
If a function resolves a foreign key for a tiny display field and a denormalized copy already exists, prefer the denormalized field on the hot path.
|
||||
|
||||
### When to denormalize
|
||||
|
||||
Denormalize when all of these are true:
|
||||
|
||||
- the path is hot
|
||||
- the joined document is much larger than the field you need
|
||||
- many readers are paying that join cost repeatedly
|
||||
|
||||
Useful mental model:
|
||||
|
||||
`join_cost = rows_per_page x foreign_doc_size x pages_per_second`
|
||||
|
||||
Small-table joins are often fine. Large-document joins for tiny fields on hot list pages are usually not.
|
||||
|
||||
### Fallback rule
|
||||
|
||||
Denormalized data is an optimization. Live data is the correctness path.
|
||||
|
||||
Rules:
|
||||
|
||||
- If the denormalized field is missing or null, fall back to the live read
|
||||
- Do not show placeholders instead of falling back
|
||||
- In lookup maps, only include fully populated entries
|
||||
|
||||
```ts
|
||||
// Bad: missing denormalized data becomes a placeholder and blocks correctness
|
||||
const ownerName = project.ownerName ?? "Unknown owner";
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: denormalized data is an optimization, not the only source of truth
|
||||
const ownerName =
|
||||
project.ownerName ?? (await ctx.db.get(project.ownerId))?.name ?? null;
|
||||
```
|
||||
|
||||
Bad lookup map pattern:
|
||||
|
||||
```ts
|
||||
const ownersById = {
|
||||
[project.ownerId]: { ownerName: null },
|
||||
};
|
||||
```
|
||||
|
||||
That blocks fallback because the map says "I have data" when it does not.
|
||||
|
||||
Good lookup map pattern:
|
||||
|
||||
```ts
|
||||
const ownersById =
|
||||
project.ownerName !== undefined && project.ownerName !== null
|
||||
? { [project.ownerId]: { ownerName: project.ownerName } }
|
||||
: {};
|
||||
```
|
||||
|
||||
### No denormalized copy yet
|
||||
|
||||
Prefer adding fields to an existing summary, companion, or digest table instead of bloating the primary hot-path table.
|
||||
|
||||
If introducing the new field or table requires a staged rollout, backfill, or old/new-shape handling, use the migration helper skill for the rollout plan.
|
||||
|
||||
Rollout order:
|
||||
|
||||
1. Update schema
|
||||
2. Update write path
|
||||
3. Backfill
|
||||
4. Switch read path
|
||||
|
||||
## 3. Minimize Row Size
|
||||
|
||||
Hot list pages should read the smallest document shape that still answers the UI.
|
||||
|
||||
Prefer summary or digest tables over full source tables when:
|
||||
|
||||
- the list page only needs a subset of fields
|
||||
- source documents are large
|
||||
- the query is high volume
|
||||
|
||||
An 800 byte summary row is materially cheaper than a 3 KB full document on a hot page.
|
||||
|
||||
Digest tables are a tradeoff, not a default:
|
||||
|
||||
- Worth it when the path is clearly hot, the source rows are much larger than the UI needs, or many readers are repeatedly paying the same join and payload cost
|
||||
- Probably not worth it when an indexed read on the source table is already cheap enough, the table is still small, or the extra write and migration complexity would dominate the benefit
|
||||
|
||||
```ts
|
||||
// Bad: list page reads source docs, then joins owner data per row
|
||||
const projects = await ctx.db
|
||||
.query("projects")
|
||||
.withIndex("by_public", (q) => q.eq("isPublic", true))
|
||||
.collect();
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: list page reads the smaller digest shape first
|
||||
const projects = await ctx.db
|
||||
.query("projectDigests")
|
||||
.withIndex("by_public_and_updated", (q) => q.eq("isPublic", true))
|
||||
.order("desc")
|
||||
.take(20);
|
||||
```
|
||||
|
||||
## 4. Isolate Frequently-Updated Fields
|
||||
|
||||
Convex already no-ops unchanged writes. The invalidation problem here is real writes hitting documents that many queries subscribe to.
|
||||
|
||||
Move high-churn fields like `lastSeen`, counters, presence, or ephemeral status off widely-read documents when most readers do not need them.
|
||||
|
||||
Apply this across sibling writers too. Splitting one write path does not help much if three other mutations still update the same widely-read document.
|
||||
|
||||
```ts
|
||||
// Bad: every presence heartbeat invalidates subscribers to the whole profile
|
||||
await ctx.db.patch(user._id, {
|
||||
name: args.name,
|
||||
avatarUrl: args.avatarUrl,
|
||||
lastSeen: Date.now(),
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: keep profile reads stable, move heartbeat updates to a separate document
|
||||
await ctx.db.patch(user._id, {
|
||||
name: args.name,
|
||||
avatarUrl: args.avatarUrl,
|
||||
});
|
||||
|
||||
await ctx.db.patch(presence._id, {
|
||||
lastSeen: Date.now(),
|
||||
});
|
||||
```
|
||||
|
||||
## 5. Match Consistency To Read Patterns
|
||||
|
||||
Choose read strategy based on traffic shape.
|
||||
|
||||
### High-read, low-write
|
||||
|
||||
Examples:
|
||||
|
||||
- public browse pages
|
||||
- search results
|
||||
- landing pages
|
||||
- directory listings
|
||||
|
||||
Prefer:
|
||||
|
||||
- point-in-time reads where appropriate
|
||||
- explicit refresh
|
||||
- local state for pagination
|
||||
- caching where appropriate
|
||||
|
||||
Do not treat subscriptions as automatically wrong here. Prefer point-in-time reads only when the product does not need live freshness and the reactive cost is material. See `subscription-cost.md` for detailed patterns.
|
||||
|
||||
### High-read, high-write
|
||||
|
||||
Examples:
|
||||
|
||||
- collaborative editors
|
||||
- live dashboards
|
||||
- presence-heavy views
|
||||
|
||||
Reactive queries may be worth the ongoing cost.
|
||||
|
||||
## Convex-Specific Notes
|
||||
|
||||
### Reactive queries
|
||||
|
||||
Every `ctx.db.get()` and `ctx.db.query()` contributes to the invalidation set for the query.
|
||||
|
||||
On the client:
|
||||
|
||||
- `useQuery` creates a live subscription
|
||||
- `usePaginatedQuery` creates a live subscription per page
|
||||
|
||||
For low-freshness flows, consider a point-in-time read instead of a live subscription only when the product does not need updates pushed automatically.
|
||||
|
||||
### Point-in-time reads
|
||||
|
||||
Framework helpers, server-rendered fetches, or one-shot client reads can avoid ongoing subscription cost when live updates are not useful.
|
||||
|
||||
Use them for:
|
||||
|
||||
- aggregate snapshots
|
||||
- reports
|
||||
- low-churn listings
|
||||
- pages where explicit refresh is fine
|
||||
|
||||
### Triggers and fan-out
|
||||
|
||||
Triggers fire on every write, including writes that did not materially change the document.
|
||||
|
||||
When a write exists only to keep derived state in sync:
|
||||
|
||||
- diff before patching
|
||||
- move expensive non-blocking work to `ctx.scheduler.runAfter` when appropriate
|
||||
|
||||
### Aggregates
|
||||
|
||||
Reactive global counts invalidate frequently on busy tables.
|
||||
|
||||
Prefer:
|
||||
|
||||
- one-shot aggregate fetches
|
||||
- periodic recomputation
|
||||
- precomputed summary rows
|
||||
|
||||
for global stats that do not need live updates every second.
|
||||
|
||||
### Backfills
|
||||
|
||||
For larger backfills, use cursor-based, self-scheduling `internalMutation` jobs or the migrations component.
|
||||
|
||||
Deploy code that can handle both states before running the backfill.
|
||||
|
||||
During the gap:
|
||||
|
||||
- writes should populate the new shape
|
||||
- reads should fall back safely
|
||||
|
||||
## Verification
|
||||
|
||||
Before closing the audit, confirm:
|
||||
|
||||
1. Same results as before, no dropped records
|
||||
2. The removed table or lookup is no longer in the hot-path read set
|
||||
3. Tests or validation cover fallback behavior
|
||||
4. Migration safety is preserved while fields or indexes are unbackfilled
|
||||
5. Sibling functions were fixed consistently
|
||||
@@ -1,114 +0,0 @@
|
||||
# OCC Conflict Resolution
|
||||
|
||||
Use these rules when insights, logs, or dashboard health show OCC (Optimistic Concurrency Control) conflicts, mutation retries, or write contention on hot tables.
|
||||
|
||||
## Core Principle
|
||||
|
||||
Convex uses optimistic concurrency control. When two transactions read or write overlapping data, one succeeds and the other retries automatically. High contention means wasted work and increased latency.
|
||||
|
||||
## Symptoms
|
||||
|
||||
- OCC conflict errors in deployment logs or health page
|
||||
- Mutations retrying multiple times before succeeding
|
||||
- User-visible latency spikes on write-heavy pages
|
||||
- `npx convex insights --details` showing high conflict rates
|
||||
|
||||
## Common Causes
|
||||
|
||||
### Hot documents
|
||||
|
||||
Multiple mutations writing to the same document concurrently. Classic examples: a global counter, a shared settings row, or a "last updated" timestamp on a parent record.
|
||||
|
||||
### Broad read sets causing false conflicts
|
||||
|
||||
A query that scans a large table range creates a broad read set. If any write touches that range, the query's transaction conflicts even if the specific document the query cared about was not modified.
|
||||
|
||||
### Fan-out from triggers or cascading writes
|
||||
|
||||
A single user action triggers multiple mutations that all touch related documents. Each mutation competes with the others.
|
||||
|
||||
Database triggers (e.g. from `convex-helpers`) run inside the same transaction as the mutation that caused them. If a trigger does heavy work, reads extra tables, or writes to many documents, it extends the transaction's read/write set and increases the window for conflicts. Keep trigger logic minimal, or move expensive derived work to a scheduled function.
|
||||
|
||||
### Write-then-read chains
|
||||
|
||||
A mutation writes a document, then a reactive query re-reads it, then another mutation writes it again. Under load, these chains stack up.
|
||||
|
||||
## Fix Order
|
||||
|
||||
### 1. Reduce read set size
|
||||
|
||||
Narrower reads mean fewer false conflicts.
|
||||
|
||||
```ts
|
||||
// Bad: broad scan creates a wide conflict surface
|
||||
const allTasks = await ctx.db.query("tasks").collect();
|
||||
const mine = allTasks.filter((t) => t.ownerId === userId);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: indexed query touches only relevant documents
|
||||
const mine = await ctx.db
|
||||
.query("tasks")
|
||||
.withIndex("by_owner", (q) => q.eq("ownerId", userId))
|
||||
.collect();
|
||||
```
|
||||
|
||||
### 2. Split hot documents
|
||||
|
||||
When many writers target the same document, split the contention point.
|
||||
|
||||
```ts
|
||||
// Bad: every vote increments the same counter document
|
||||
const counter = await ctx.db.get(pollCounterId);
|
||||
await ctx.db.patch(pollCounterId, { count: counter!.count + 1 });
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: shard the counter across multiple documents, aggregate on read
|
||||
const shardIndex = Math.floor(Math.random() * SHARD_COUNT);
|
||||
const shardId = shardIds[shardIndex];
|
||||
const shard = await ctx.db.get(shardId);
|
||||
await ctx.db.patch(shardId, { count: shard!.count + 1 });
|
||||
```
|
||||
|
||||
Aggregate the shards in a query or scheduled job when you need the total.
|
||||
|
||||
### 3. Move non-critical work to scheduled functions
|
||||
|
||||
If a mutation does primary work plus secondary bookkeeping (analytics, non-critical notifications, cache warming), the bookkeeping extends the transaction's lifetime and read/write set.
|
||||
|
||||
```ts
|
||||
// Bad: canonical write and derived work happen in the same transaction
|
||||
await ctx.db.patch(userId, { name: args.name });
|
||||
await ctx.db.insert("userUpdateAnalytics", {
|
||||
userId,
|
||||
kind: "name_changed",
|
||||
name: args.name,
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: keep the primary write small, defer the analytics work
|
||||
await ctx.db.patch(userId, { name: args.name });
|
||||
await ctx.scheduler.runAfter(0, internal.users.recordNameChangeAnalytics, {
|
||||
userId,
|
||||
name: args.name,
|
||||
});
|
||||
```
|
||||
|
||||
### 4. Combine competing writes
|
||||
|
||||
If two mutations must update the same document atomically, consider whether they can be combined into a single mutation call from the client, reducing round trips and conflict windows.
|
||||
|
||||
Do not introduce artificial locks or queues unless the above steps have been tried first.
|
||||
|
||||
## Related: Invalidation Scope
|
||||
|
||||
Splitting hot documents also reduces subscription invalidation, not just OCC contention. If a document is written frequently and read by many queries, those queries re-run on every write even when the fields they care about have not changed. See `subscription-cost.md` section 4 ("Isolate frequently-updated fields") for that pattern.
|
||||
|
||||
## Verification
|
||||
|
||||
1. OCC conflict rate has dropped in insights or dashboard
|
||||
2. Mutation latency is lower and more consistent
|
||||
3. No data correctness regressions from splitting or scheduling changes
|
||||
4. Sibling writers to the same hot documents were fixed consistently
|
||||
@@ -1,252 +0,0 @@
|
||||
# Subscription Cost
|
||||
|
||||
Use these rules when the problem is too many reactive subscriptions, queries invalidating too frequently, or React components re-rendering excessively due to Convex state changes.
|
||||
|
||||
## Core Principle
|
||||
|
||||
Every `useQuery` and `usePaginatedQuery` call creates a live subscription. The server tracks the query's read set and re-executes the query whenever any document in that read set changes. Subscription cost scales with:
|
||||
|
||||
`subscriptions x invalidation_frequency x query_cost`
|
||||
|
||||
Subscriptions are not inherently bad. Convex reactivity is often the right default. The goal is to reduce unnecessary invalidation work, not to eliminate subscriptions on principle.
|
||||
|
||||
## Symptoms
|
||||
|
||||
- Dashboard shows high active subscription count
|
||||
- UI feels sluggish or laggy despite fast individual queries
|
||||
- React profiling shows frequent re-renders from Convex state
|
||||
- Pages with many components each running their own `useQuery`
|
||||
- Paginated lists where every loaded page stays subscribed
|
||||
|
||||
## Common Causes
|
||||
|
||||
### Reactive queries on low-freshness flows
|
||||
|
||||
Some user flows are read-heavy and do not need live updates every time the underlying data changes. In those cases, ongoing subscriptions may cost more than they are worth.
|
||||
|
||||
### Overly broad queries
|
||||
|
||||
A query that returns a large result set invalidates whenever any document in that set changes. The broader the query, the more frequent the invalidation.
|
||||
|
||||
### Too many subscriptions per page
|
||||
|
||||
A page with 20 list items, each running its own `useQuery` to fetch related data, creates 20+ subscriptions per visitor.
|
||||
|
||||
### Paginated queries keeping all pages live
|
||||
|
||||
`usePaginatedQuery` with `loadMore` keeps every loaded page subscribed. On a page where a user has scrolled through 10 pages, all 10 stay reactive.
|
||||
|
||||
### Frequently-updated fields on widely-read documents
|
||||
|
||||
A document that many queries touch gets a frequently-updated field (like `lastSeen`, `lastActiveAt`, or a counter). Every write to that field invalidates every subscription that reads the document, even if those subscriptions never use the field. This is different from OCC conflicts (see `occ-conflicts.md`), which are write-vs-write contention. This is write-vs-subscription: the write succeeds fine, but it forces hundreds of queries to re-run for no reason.
|
||||
|
||||
## Fix Order
|
||||
|
||||
### 1. Use point-in-time reads when live updates are not valuable
|
||||
|
||||
Keep `useQuery` and `usePaginatedQuery` by default when the product benefits from fresh live data.
|
||||
|
||||
Consider a point-in-time read instead when all of these are true:
|
||||
|
||||
- the flow is high-read
|
||||
- the underlying data changes less often than users need to see
|
||||
- explicit refresh, periodic refresh, or a fresh read on navigation is acceptable
|
||||
|
||||
Possible implementations depend on environment:
|
||||
|
||||
- a server-rendered fetch
|
||||
- a framework helper like `fetchQuery`
|
||||
- a point-in-time client read such as `ConvexHttpClient.query()`
|
||||
|
||||
```ts
|
||||
// Reactive by default when fresh live data matters
|
||||
function TeamPresence() {
|
||||
const presence = useQuery(api.teams.livePresence, { teamId });
|
||||
return <PresenceList users={presence} />;
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// Point-in-time read when explicit refresh is acceptable
|
||||
import { ConvexHttpClient } from "convex/browser";
|
||||
|
||||
const client = new ConvexHttpClient(import.meta.env.VITE_CONVEX_URL);
|
||||
|
||||
function SnapshotView() {
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
client.query(api.items.snapshot).then(setItems);
|
||||
}, []);
|
||||
|
||||
return <ItemGrid items={items} />;
|
||||
}
|
||||
```
|
||||
|
||||
Good candidates for point-in-time reads:
|
||||
|
||||
- aggregate snapshots
|
||||
- reports
|
||||
- low-churn listings
|
||||
- flows where explicit refresh is already acceptable
|
||||
|
||||
Keep reactive for:
|
||||
|
||||
- collaborative editing
|
||||
- live dashboards
|
||||
- presence-heavy views
|
||||
- any surface where users expect fresh changes to appear automatically
|
||||
|
||||
### 2. Batch related data into fewer queries
|
||||
|
||||
Instead of N components each fetching their own related data, fetch it in a single query.
|
||||
|
||||
```ts
|
||||
// Bad: each card fetches its own author
|
||||
function ProjectCard({ project }: { project: Project }) {
|
||||
const author = useQuery(api.users.get, { id: project.authorId });
|
||||
return <Card title={project.name} author={author?.name} />;
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: parent query returns projects with author names included
|
||||
function ProjectList() {
|
||||
const projects = useQuery(api.projects.listWithAuthors);
|
||||
return projects?.map((p) => (
|
||||
<Card key={p._id} title={p.name} author={p.authorName} />
|
||||
));
|
||||
}
|
||||
```
|
||||
|
||||
This can use denormalized fields or server-side joins in the query handler. Either way, it is one subscription instead of N.
|
||||
|
||||
This is not automatically better. If the combined query becomes much broader and invalidates much more often, several narrower subscriptions may be the better tradeoff. Optimize for total invalidation cost, not raw subscription count.
|
||||
|
||||
### 3. Use skip to avoid unnecessary subscriptions
|
||||
|
||||
The `"skip"` value prevents a subscription from being created when the arguments are not ready.
|
||||
|
||||
```ts
|
||||
// Bad: subscribes with undefined args, wastes a subscription slot
|
||||
const profile = useQuery(api.users.getProfile, { userId: selectedId! });
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: skip when there is nothing to fetch
|
||||
const profile = useQuery(
|
||||
api.users.getProfile,
|
||||
selectedId ? { userId: selectedId } : "skip",
|
||||
);
|
||||
```
|
||||
|
||||
### 4. Isolate frequently-updated fields into separate documents
|
||||
|
||||
If a document is widely read but has a field that changes often, move that field to a separate document. Queries that do not need the field will no longer be invalidated by its writes.
|
||||
|
||||
```ts
|
||||
// Bad: lastSeen lives on the user doc, every heartbeat invalidates
|
||||
// every query that reads this user
|
||||
const users = defineTable({
|
||||
name: v.string(),
|
||||
email: v.string(),
|
||||
lastSeen: v.number(),
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: lastSeen lives in a separate heartbeat doc
|
||||
const users = defineTable({
|
||||
name: v.string(),
|
||||
email: v.string(),
|
||||
heartbeatId: v.id("heartbeats"),
|
||||
});
|
||||
|
||||
const heartbeats = defineTable({
|
||||
lastSeen: v.number(),
|
||||
});
|
||||
```
|
||||
|
||||
Queries that only need `name` and `email` no longer re-run on every heartbeat. Queries that actually need online status fetch the heartbeat document explicitly.
|
||||
|
||||
For an even further optimization, if you only need a coarse online/offline boolean rather than the exact `lastSeen` timestamp, add a separate presence document with an `isOnline` flag. Update it immediately when a user comes online, and use a cron to batch-mark users offline when their heartbeat goes stale. This way the presence query only invalidates when online status actually changes, not on every heartbeat.
|
||||
|
||||
### 5. Use the aggregate component for counts and sums
|
||||
|
||||
Reactive global counts (`SELECT COUNT(*)` equivalent) invalidate on every insert or delete to the table. The [`@convex-dev/aggregate`](https://www.npmjs.com/package/@convex-dev/aggregate) component maintains denormalized COUNT, SUM, and MAX values efficiently so you do not need a reactive query scanning the full table.
|
||||
|
||||
Use it for leaderboards, totals, "X items" badges, or any stat that would otherwise require scanning many rows reactively.
|
||||
|
||||
If the aggregate component is not appropriate, prefer point-in-time reads for global stats, or precomputed summary rows updated by a cron or trigger, over reactive queries that scan large tables.
|
||||
|
||||
### 6. Narrow query read sets
|
||||
|
||||
Queries that return less data and touch fewer documents invalidate less often.
|
||||
|
||||
```ts
|
||||
// Bad: returns all fields, invalidates on any field change
|
||||
export const list = query({
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db.query("projects").collect();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: use a digest table with only the fields the list needs
|
||||
export const listDigests = query({
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db.query("projectDigests").collect();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Writes to fields not in the digest table do not invalidate the digest query.
|
||||
|
||||
### 7. Remove `Date.now()` from queries
|
||||
|
||||
Using `Date.now()` inside a query defeats Convex's query cache. The cache is invalidated frequently to avoid showing stale time-dependent results, which increases database work even when the underlying data has not changed.
|
||||
|
||||
```ts
|
||||
// Bad: Date.now() defeats query caching and causes frequent re-evaluation
|
||||
const releasedPosts = await ctx.db
|
||||
.query("posts")
|
||||
.withIndex("by_released_at", (q) => q.lte("releasedAt", Date.now()))
|
||||
.take(100);
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: use a boolean field updated by a scheduled function
|
||||
const releasedPosts = await ctx.db
|
||||
.query("posts")
|
||||
.withIndex("by_is_released", (q) => q.eq("isReleased", true))
|
||||
.take(100);
|
||||
```
|
||||
|
||||
If the query must compare against a time value, pass it as an explicit argument from the client and round it to a coarse interval (e.g. the most recent minute) so requests within that window share the same cache entry.
|
||||
|
||||
### 8. Consider pagination strategy
|
||||
|
||||
For long lists where users scroll through many pages:
|
||||
|
||||
- If the data does not need live updates, use point-in-time fetching with manual "load more"
|
||||
- If it does need live updates, accept the subscription cost but limit the number of loaded pages
|
||||
- Consider whether older pages can be unloaded as the user scrolls forward
|
||||
|
||||
### 9. Separate backend cost from UI churn
|
||||
|
||||
If the main problem is loading flash or UI churn when query arguments change, stabilizing the reactive UI behavior may be better than replacing reactivity altogether.
|
||||
|
||||
Treat this as a UX problem first when:
|
||||
|
||||
- the underlying query is already reasonably cheap
|
||||
- the complaint is flicker, loading flashes, or re-render churn
|
||||
- live updates are still desirable once fresh data arrives
|
||||
|
||||
## Verification
|
||||
|
||||
1. Subscription count in dashboard is lower for the affected pages
|
||||
2. UI responsiveness has improved
|
||||
3. React profiling shows fewer unnecessary re-renders
|
||||
4. Surfaces that do not need live updates are not paying for persistent subscriptions unnecessarily
|
||||
5. Sibling pages with similar patterns were updated consistently
|
||||
@@ -1,347 +0,0 @@
|
||||
---
|
||||
name: convex-quickstart
|
||||
description: Creates or adds Convex to an app. Use for new Convex projects, npm create convex@latest, frontend setup, env vars, or the first npx convex dev run.
|
||||
---
|
||||
|
||||
# Convex Quickstart
|
||||
|
||||
Set up a working Convex project as fast as possible.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Starting a brand new project with Convex
|
||||
- Adding Convex to an existing React, Next.js, Vue, Svelte, or other app
|
||||
- Scaffolding a Convex app for prototyping
|
||||
|
||||
## When Not to Use
|
||||
|
||||
- The project already has Convex installed and `convex/` exists - just start building
|
||||
- You only need to add auth to an existing Convex app - use the `convex-setup-auth` skill
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Determine the starting point: new project or existing app
|
||||
2. If new project, pick a template and scaffold with `npm create convex@latest`
|
||||
3. If existing app, install `convex` and wire up the provider
|
||||
4. Run `npx convex dev` to connect a deployment and start the dev loop
|
||||
5. Verify the setup works
|
||||
|
||||
## Path 1: New Project (Recommended)
|
||||
|
||||
Use the official scaffolding tool. It creates a complete project with the frontend framework, Convex backend, and all config wired together.
|
||||
|
||||
### Pick a template
|
||||
|
||||
| Template | Stack |
|
||||
| -------------------------- | ----------------------------------------- |
|
||||
| `react-vite-shadcn` | React + Vite + Tailwind + shadcn/ui |
|
||||
| `nextjs-shadcn` | Next.js App Router + Tailwind + shadcn/ui |
|
||||
| `react-vite-clerk-shadcn` | React + Vite + Clerk auth + shadcn/ui |
|
||||
| `nextjs-clerk` | Next.js + Clerk auth |
|
||||
| `nextjs-convexauth-shadcn` | Next.js + Convex Auth + shadcn/ui |
|
||||
| `nextjs-lucia-shadcn` | Next.js + Lucia auth + shadcn/ui |
|
||||
| `bare` | Convex backend only, no frontend |
|
||||
|
||||
If the user has not specified a preference, default to `react-vite-shadcn` for simple apps or `nextjs-shadcn` for apps that need SSR or API routes.
|
||||
|
||||
You can also use any GitHub repo as a template:
|
||||
|
||||
```bash
|
||||
npm create convex@latest my-app -- -t owner/repo
|
||||
npm create convex@latest my-app -- -t owner/repo#branch
|
||||
```
|
||||
|
||||
### Scaffold the project
|
||||
|
||||
Always pass the project name and template flag to avoid interactive prompts:
|
||||
|
||||
```bash
|
||||
npm create convex@latest my-app -- -t react-vite-shadcn
|
||||
cd my-app
|
||||
npm install
|
||||
```
|
||||
|
||||
The scaffolding tool creates files but does not run `npm install`, so you must run it yourself.
|
||||
|
||||
To scaffold in the current directory (if it is empty):
|
||||
|
||||
```bash
|
||||
npm create convex@latest . -- -t react-vite-shadcn
|
||||
npm install
|
||||
```
|
||||
|
||||
### Start the dev loop
|
||||
|
||||
`npx convex dev` is a long-running watcher process that syncs backend code to a Convex deployment on every save. It also requires authentication on first run (browser-based OAuth). Both of these make it unsuitable for an agent to run directly.
|
||||
|
||||
**Ask the user to run this themselves:**
|
||||
|
||||
Tell the user to run `npx convex dev` in their terminal. On first run it will prompt them to log in or develop anonymously. Once running, it will:
|
||||
|
||||
- Create a Convex project and dev deployment
|
||||
- Write the deployment URL to `.env.local`
|
||||
- Create the `convex/` directory with generated types
|
||||
- Watch for changes and sync continuously
|
||||
|
||||
The user should keep `npx convex dev` running in the background while you work on code. The watcher will automatically pick up any files you create or edit in `convex/`.
|
||||
|
||||
**Exception - cloud or headless agents:** Environments that cannot open a browser for interactive login should use Agent Mode (see below) to run anonymously without user interaction.
|
||||
|
||||
### Start the frontend
|
||||
|
||||
The user should also run the frontend dev server in a separate terminal:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Vite apps serve on `http://localhost:5173`, Next.js on `http://localhost:3000`.
|
||||
|
||||
### What you get
|
||||
|
||||
After scaffolding, the project structure looks like:
|
||||
|
||||
```
|
||||
my-app/
|
||||
convex/ # Backend functions and schema
|
||||
_generated/ # Auto-generated types (check this into git)
|
||||
schema.ts # Database schema (if template includes one)
|
||||
src/ # Frontend code (or app/ for Next.js)
|
||||
package.json
|
||||
.env.local # CONVEX_URL / VITE_CONVEX_URL / NEXT_PUBLIC_CONVEX_URL
|
||||
```
|
||||
|
||||
The template already has:
|
||||
|
||||
- `ConvexProvider` wired into the app root
|
||||
- Correct env var names for the framework
|
||||
- Tailwind and shadcn/ui ready (for shadcn templates)
|
||||
- Auth provider configured (for auth templates)
|
||||
|
||||
Proceed to adding schema, functions, and UI.
|
||||
|
||||
## Path 2: Add Convex to an Existing App
|
||||
|
||||
Use this when the user already has a frontend project and wants to add Convex as the backend.
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
npm install convex
|
||||
```
|
||||
|
||||
### Initialize and start dev loop
|
||||
|
||||
Ask the user to run `npx convex dev` in their terminal. This handles login, creates the `convex/` directory, writes the deployment URL to `.env.local`, and starts the file watcher. See the notes in Path 1 about why the agent should not run this directly.
|
||||
|
||||
### Wire up the provider
|
||||
|
||||
The Convex client must wrap the app at the root. The setup varies by framework.
|
||||
|
||||
Create the `ConvexReactClient` at module scope, not inside a component:
|
||||
|
||||
```tsx
|
||||
// Bad: re-creates the client on every render
|
||||
function App() {
|
||||
const convex = new ConvexReactClient(
|
||||
import.meta.env.VITE_CONVEX_URL as string,
|
||||
);
|
||||
return <ConvexProvider client={convex}>...</ConvexProvider>;
|
||||
}
|
||||
|
||||
// Good: created once at module scope
|
||||
const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string);
|
||||
function App() {
|
||||
return <ConvexProvider client={convex}>...</ConvexProvider>;
|
||||
}
|
||||
```
|
||||
|
||||
#### React (Vite)
|
||||
|
||||
```tsx
|
||||
// src/main.tsx
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { ConvexProvider, ConvexReactClient } from "convex/react";
|
||||
import App from "./App";
|
||||
|
||||
const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string);
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<ConvexProvider client={convex}>
|
||||
<App />
|
||||
</ConvexProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
```
|
||||
|
||||
#### Next.js (App Router)
|
||||
|
||||
```tsx
|
||||
// app/ConvexClientProvider.tsx
|
||||
"use client";
|
||||
|
||||
import { ConvexProvider, ConvexReactClient } from "convex/react";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);
|
||||
|
||||
export function ConvexClientProvider({ children }: { children: ReactNode }) {
|
||||
return <ConvexProvider client={convex}>{children}</ConvexProvider>;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// app/layout.tsx
|
||||
import { ConvexClientProvider } from "./ConvexClientProvider";
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<ConvexClientProvider>{children}</ConvexClientProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Other frameworks
|
||||
|
||||
For Vue, Svelte, React Native, TanStack Start, Remix, and others, follow the matching quickstart guide:
|
||||
|
||||
- [Vue](https://docs.convex.dev/quickstart/vue)
|
||||
- [Svelte](https://docs.convex.dev/quickstart/svelte)
|
||||
- [React Native](https://docs.convex.dev/quickstart/react-native)
|
||||
- [TanStack Start](https://docs.convex.dev/quickstart/tanstack-start)
|
||||
- [Remix](https://docs.convex.dev/quickstart/remix)
|
||||
- [Node.js (no frontend)](https://docs.convex.dev/quickstart/nodejs)
|
||||
|
||||
### Environment variables
|
||||
|
||||
The env var name depends on the framework:
|
||||
|
||||
| Framework | Variable |
|
||||
| ------------ | ------------------------ |
|
||||
| Vite | `VITE_CONVEX_URL` |
|
||||
| Next.js | `NEXT_PUBLIC_CONVEX_URL` |
|
||||
| Remix | `CONVEX_URL` |
|
||||
| React Native | `EXPO_PUBLIC_CONVEX_URL` |
|
||||
|
||||
`npx convex dev` writes the correct variable to `.env.local` automatically.
|
||||
|
||||
## Agent Mode (Cloud and Headless Agents)
|
||||
|
||||
When running in a cloud or headless agent environment where interactive browser login is not possible, set `CONVEX_AGENT_MODE=anonymous` to use a local anonymous deployment.
|
||||
|
||||
Add `CONVEX_AGENT_MODE=anonymous` to `.env.local`, or set it inline:
|
||||
|
||||
```bash
|
||||
CONVEX_AGENT_MODE=anonymous npx convex dev
|
||||
```
|
||||
|
||||
This runs a local Convex backend on the VM without requiring authentication, and avoids conflicting with the user's personal dev deployment.
|
||||
|
||||
## Verify the Setup
|
||||
|
||||
After setup, confirm everything is working:
|
||||
|
||||
1. The user confirms `npx convex dev` is running without errors
|
||||
2. The `convex/_generated/` directory exists and has `api.ts` and `server.ts`
|
||||
3. `.env.local` contains the deployment URL
|
||||
|
||||
## Writing Your First Function
|
||||
|
||||
Once the project is set up, create a schema and a query to verify the full loop works.
|
||||
|
||||
`convex/schema.ts`:
|
||||
|
||||
```ts
|
||||
import { defineSchema, defineTable } from "convex/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default defineSchema({
|
||||
tasks: defineTable({
|
||||
text: v.string(),
|
||||
completed: v.boolean(),
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
`convex/tasks.ts`:
|
||||
|
||||
```ts
|
||||
import { query, mutation } from "./_generated/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export const list = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
return await ctx.db.query("tasks").collect();
|
||||
},
|
||||
});
|
||||
|
||||
export const create = mutation({
|
||||
args: { text: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
await ctx.db.insert("tasks", { text: args.text, completed: false });
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Use in a React component (adjust the import path based on your file location relative to `convex/`):
|
||||
|
||||
```tsx
|
||||
import { useQuery, useMutation } from "convex/react";
|
||||
import { api } from "../convex/_generated/api";
|
||||
|
||||
function Tasks() {
|
||||
const tasks = useQuery(api.tasks.list);
|
||||
const create = useMutation(api.tasks.create);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => create({ text: "New task" })}>Add</button>
|
||||
{tasks?.map((t) => (
|
||||
<div key={t._id}>{t.text}</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Development vs Production
|
||||
|
||||
Always use `npx convex dev` during development. It runs against your personal dev deployment and syncs code on save.
|
||||
|
||||
When ready to ship, deploy to production:
|
||||
|
||||
```bash
|
||||
npx convex deploy
|
||||
```
|
||||
|
||||
This pushes to the production deployment, which is separate from dev. Do not use `deploy` during development.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Add authentication: use the `convex-setup-auth` skill
|
||||
- Design your schema: see [Schema docs](https://docs.convex.dev/database/schemas)
|
||||
- Build components: use the `convex-create-component` skill
|
||||
- Plan a migration: use the `convex-migration-helper` skill
|
||||
- Add file storage: see [File Storage docs](https://docs.convex.dev/file-storage)
|
||||
- Set up cron jobs: see [Scheduling docs](https://docs.convex.dev/scheduling)
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Determined starting point: new project or existing app
|
||||
- [ ] If new project: scaffolded with `npm create convex@latest` using appropriate template
|
||||
- [ ] If existing app: installed `convex` and wired up the provider
|
||||
- [ ] User has `npx convex dev` running and connected to a deployment
|
||||
- [ ] `convex/_generated/` directory exists with types
|
||||
- [ ] `.env.local` has the deployment URL
|
||||
- [ ] Verified a basic query/mutation round-trip works
|
||||
@@ -1,10 +0,0 @@
|
||||
interface:
|
||||
display_name: "Convex Quickstart"
|
||||
short_description: "Start a new Convex app or add Convex to an existing frontend."
|
||||
icon_small: "./assets/icon.svg"
|
||||
icon_large: "./assets/icon.svg"
|
||||
brand_color: "#F97316"
|
||||
default_prompt: "Set up Convex for this project as fast as possible. First decide whether this is a new app or an existing app, then scaffold or integrate Convex and verify the setup works."
|
||||
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -1,4 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M15.91 11.672a.375.375 0 0 1 0 .656l-5.603 3.113a.375.375 0 0 1-.557-.328V8.887c0-.286.307-.466.557-.327l5.603 3.112Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 435 B |
@@ -1,150 +0,0 @@
|
||||
---
|
||||
name: convex-setup-auth
|
||||
description: Sets up Convex auth, identity mapping, and access control. Use for login, auth providers, users tables, protected functions, or roles in a Convex app.
|
||||
---
|
||||
|
||||
# Convex Authentication Setup
|
||||
|
||||
Implement secure authentication in Convex with user management and access control.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Setting up authentication for the first time
|
||||
- Implementing user management (users table, identity mapping)
|
||||
- Creating authentication helper functions
|
||||
- Setting up auth providers (Convex Auth, Clerk, WorkOS AuthKit, Auth0, custom JWT)
|
||||
|
||||
## When Not to Use
|
||||
|
||||
- Auth for a non-Convex backend
|
||||
- Pure OAuth/OIDC documentation without a Convex implementation
|
||||
- Debugging unrelated bugs that happen to surface near auth code
|
||||
- The auth provider is already fully configured and the user only needs a one-line fix
|
||||
|
||||
## First Step: Choose the Auth Provider
|
||||
|
||||
Convex supports multiple authentication approaches. Do not assume a provider.
|
||||
|
||||
Before writing setup code:
|
||||
|
||||
1. Ask the user which auth solution they want, unless the repository already makes it obvious
|
||||
2. If the repo already uses a provider, continue with that provider unless the user wants to switch
|
||||
3. If the user has not chosen a provider and the repo does not make it obvious, ask before proceeding
|
||||
|
||||
Common options:
|
||||
|
||||
- [Convex Auth](https://docs.convex.dev/auth/convex-auth) - good default when the user wants auth handled directly in Convex
|
||||
- [Clerk](https://docs.convex.dev/auth/clerk) - use when the app already uses Clerk or the user wants Clerk's hosted auth features
|
||||
- [WorkOS AuthKit](https://docs.convex.dev/auth/authkit/) - use when the app already uses WorkOS or the user wants AuthKit specifically
|
||||
- [Auth0](https://docs.convex.dev/auth/auth0) - use when the app already uses Auth0
|
||||
- Custom JWT provider - use when integrating an existing auth system not covered above
|
||||
|
||||
Look for signals in the repo before asking:
|
||||
|
||||
- Dependencies such as `@clerk/*`, `@workos-inc/*`, `@auth0/*`, or Convex Auth packages
|
||||
- Existing files such as `convex/auth.config.ts`, auth middleware, provider wrappers, or login components
|
||||
- Environment variables that clearly point at a provider
|
||||
|
||||
## After Choosing a Provider
|
||||
|
||||
Read the provider's official guide and the matching local reference file:
|
||||
|
||||
- Convex Auth: [official docs](https://docs.convex.dev/auth/convex-auth), then `references/convex-auth.md`
|
||||
- Clerk: [official docs](https://docs.convex.dev/auth/clerk), then `references/clerk.md`
|
||||
- WorkOS AuthKit: [official docs](https://docs.convex.dev/auth/authkit/), then `references/workos-authkit.md`
|
||||
- Auth0: [official docs](https://docs.convex.dev/auth/auth0), then `references/auth0.md`
|
||||
|
||||
The local reference files contain the concrete workflow, expected files and env vars, gotchas, and validation checks.
|
||||
|
||||
Use those sources for:
|
||||
|
||||
- package installation
|
||||
- client provider wiring
|
||||
- environment variables
|
||||
- `convex/auth.config.ts` setup
|
||||
- login and logout UI patterns
|
||||
- framework-specific setup for React, Vite, or Next.js
|
||||
|
||||
For shared auth behavior, use the official Convex docs as the source of truth:
|
||||
|
||||
- [Auth in Functions](https://docs.convex.dev/auth/functions-auth) for `ctx.auth.getUserIdentity()`
|
||||
- [Storing Users in the Convex Database](https://docs.convex.dev/auth/database-auth) for optional app-level user storage
|
||||
- [Authentication](https://docs.convex.dev/auth) for general auth and authorization guidance
|
||||
- [Convex Auth Authorization](https://labs.convex.dev/auth/authz) when the provider is Convex Auth
|
||||
|
||||
Prefer official docs over recalled steps, because provider CLIs and Convex Auth internals change between versions. Inventing setup from memory risks outdated patterns.
|
||||
For third-party providers, only add app-level user storage if the app actually needs user documents in Convex. Not every app needs a `users` table.
|
||||
For Convex Auth, follow the Convex Auth docs and built-in auth tables rather than adding a parallel `users` table plus `storeUser` flow, because Convex Auth already manages user records internally.
|
||||
After running provider initialization commands, verify generated files and complete the post-init wiring steps the provider reference calls out. Initialization commands rarely finish the entire integration.
|
||||
|
||||
## Core Pattern: Protecting Backend Functions
|
||||
|
||||
The most common auth task is checking identity in Convex functions.
|
||||
|
||||
```ts
|
||||
// Bad: trusting a client-provided userId
|
||||
export const getMyProfile = query({
|
||||
args: { userId: v.id("users") },
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db.get(args.userId);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
// Good: verifying identity server-side
|
||||
export const getMyProfile = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const identity = await ctx.auth.getUserIdentity();
|
||||
if (!identity) throw new Error("Not authenticated");
|
||||
|
||||
return await ctx.db
|
||||
.query("users")
|
||||
.withIndex("by_tokenIdentifier", (q) =>
|
||||
q.eq("tokenIdentifier", identity.tokenIdentifier),
|
||||
)
|
||||
.unique();
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Determine the provider, either by asking the user or inferring from the repo
|
||||
2. Ask whether the user wants local-only setup or production-ready setup now
|
||||
3. Read the matching provider reference file
|
||||
4. Follow the official provider docs for current setup details
|
||||
5. Follow the official Convex docs for shared backend auth behavior, user storage, and authorization patterns
|
||||
6. Only add app-level user storage if the docs and app requirements call for it
|
||||
7. Add authorization checks for ownership, roles, or team access only where the app needs them
|
||||
8. Verify login state, protected queries, environment variables, and production configuration if requested
|
||||
|
||||
If the flow blocks on interactive provider or deployment setup, ask the user explicitly for the exact human step needed, then continue after they complete it.
|
||||
For UI-facing auth flows, offer to validate the real sign-up or sign-in flow after setup is done.
|
||||
If the environment has browser automation tools, you can use them.
|
||||
If it does not, give the user a short manual validation checklist instead.
|
||||
|
||||
## Reference Files
|
||||
|
||||
### Provider References
|
||||
|
||||
- `references/convex-auth.md`
|
||||
- `references/clerk.md`
|
||||
- `references/workos-authkit.md`
|
||||
- `references/auth0.md`
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Chosen the correct auth provider before writing setup code
|
||||
- [ ] Read the relevant provider reference file
|
||||
- [ ] Asked whether the user wants local-only setup or production-ready setup
|
||||
- [ ] Used the official provider docs for provider-specific wiring
|
||||
- [ ] Used the official Convex docs for shared auth behavior and authorization patterns
|
||||
- [ ] Only added app-level user storage if the app actually needs it
|
||||
- [ ] Did not invent a cross-provider `users` table or `storeUser` flow for Convex Auth
|
||||
- [ ] Added authentication checks in protected backend functions
|
||||
- [ ] Added authorization checks where the app actually needs them
|
||||
- [ ] Clear error messages ("Not authenticated", "Unauthorized")
|
||||
- [ ] Client auth provider configured for the chosen provider
|
||||
- [ ] If requested, production auth setup is covered too
|
||||
@@ -1,10 +0,0 @@
|
||||
interface:
|
||||
display_name: "Convex Setup Auth"
|
||||
short_description: "Set up Convex auth, user identity mapping, and access control."
|
||||
icon_small: "./assets/icon.svg"
|
||||
icon_large: "./assets/icon.svg"
|
||||
brand_color: "#2563EB"
|
||||
default_prompt: "Set up authentication for this Convex app. Figure out the provider first, then wire up the user model, identity mapping, and access control with the smallest solid implementation."
|
||||
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 394 B |
@@ -1,116 +0,0 @@
|
||||
# Auth0
|
||||
|
||||
Official docs:
|
||||
|
||||
- https://docs.convex.dev/auth/auth0
|
||||
- https://auth0.github.io/auth0-cli/
|
||||
- https://auth0.github.io/auth0-cli/auth0_apps_create.html
|
||||
|
||||
Use this when the app already uses Auth0 or the user wants Auth0 specifically.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Confirm the user wants Auth0
|
||||
2. Determine the app framework and whether Auth0 is already partly set up
|
||||
3. Ask whether the user wants local-only setup or production-ready setup now
|
||||
4. Read the official Convex and Auth0 guides before making changes
|
||||
5. Ask whether they want the fastest setup path by installing the Auth0 CLI
|
||||
6. If they agree, install the Auth0 CLI and do as much of the Auth0 app setup as possible through the CLI
|
||||
7. If they do not want the CLI path, use the Auth0 dashboard path instead
|
||||
8. Complete the relevant Auth0 frontend quickstart if the app does not already have Auth0 wired up
|
||||
9. Configure `convex/auth.config.ts` with the Auth0 domain and client ID
|
||||
10. Set environment variables for local and production environments
|
||||
11. Wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0`
|
||||
12. Gate Convex-backed UI with Convex auth state
|
||||
13. Try to verify Convex reports the user as authenticated after Auth0 login
|
||||
14. If the refresh-token path fails, stop improvising and send the user back to the official docs
|
||||
15. If the user wants production-ready setup, make sure the production Auth0 tenant and env vars are also covered
|
||||
|
||||
## What To Do
|
||||
|
||||
- Read the official Convex and Auth0 guide before writing setup code
|
||||
- Prefer the Auth0 CLI path for mechanical setup if the user is willing to install it, but do not present it as a fully validated end-to-end path yet
|
||||
- Ask the user directly: "The fastest path is to install the Auth0 CLI so I can do more of this for you. If you want, I can install it and then only ask you to log in when needed. Would you like me to do that?"
|
||||
- Make sure the app has already completed the relevant Auth0 quickstart for its frontend
|
||||
- Use the official examples for `Auth0Provider` and `ConvexProviderWithAuth0`
|
||||
- If the Auth0 login or refresh flow starts failing in a way that is not clearly explained by the docs, say that plainly and fall back to the official docs instead of pretending the flow is validated
|
||||
|
||||
## Key Setup Areas
|
||||
|
||||
- install the Auth0 SDK for the app's framework
|
||||
- configure `convex/auth.config.ts` with the Auth0 domain and client ID
|
||||
- set environment variables for local and production environments
|
||||
- wrap the app with `Auth0Provider` and `ConvexProviderWithAuth0`
|
||||
- use Convex auth state when gating Convex-backed UI
|
||||
|
||||
## Files and Env Vars To Expect
|
||||
|
||||
- `convex/auth.config.ts`
|
||||
- frontend app entry or provider wrapper
|
||||
- Auth0 CLI install docs: `https://auth0.github.io/auth0-cli/`
|
||||
- Auth0 environment variables commonly include:
|
||||
- `AUTH0_DOMAIN`
|
||||
- `AUTH0_CLIENT_ID`
|
||||
- `VITE_AUTH0_DOMAIN`
|
||||
- `VITE_AUTH0_CLIENT_ID`
|
||||
|
||||
## Concrete Steps
|
||||
|
||||
1. Start by reading `https://docs.convex.dev/auth/auth0` and the relevant Auth0 quickstart for the app's framework
|
||||
2. Ask whether the user wants the Auth0 CLI path
|
||||
3. If yes, install Auth0 CLI and have the user authenticate it with `auth0 login`
|
||||
4. Use `auth0 apps create` with SPA settings, callback URL, logout URL, and web origins if creating a new app
|
||||
5. If not using the CLI path, complete the relevant Auth0 frontend quickstart and create the Auth0 app in the dashboard
|
||||
6. Get the Auth0 domain and client ID from the CLI output or the Auth0 dashboard
|
||||
7. Install the Auth0 SDK for the app's framework
|
||||
8. Create or update `convex/auth.config.ts` with the Auth0 domain and client ID
|
||||
9. Set frontend and backend environment variables
|
||||
10. Wrap the app in `Auth0Provider`
|
||||
11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithAuth0`
|
||||
12. Run the normal Convex dev or deploy flow after backend config changes
|
||||
13. Try the official provider config shown in the Convex docs
|
||||
14. If login works but Convex auth or token refresh fails in a way you cannot clearly resolve, stop and tell the user to follow the official docs manually for now
|
||||
15. Only claim success if the user can sign in and Convex recognizes the authenticated session
|
||||
16. If the user wants production-ready setup, configure the production Auth0 tenant values and production environment variables too
|
||||
|
||||
## Gotchas
|
||||
|
||||
- The Convex docs assume the Auth0 side is already set up, so do not skip the Auth0 quickstart if the app is starting from scratch
|
||||
- The Auth0 CLI is often the fastest path for a fresh setup, but it still requires the user to authenticate the CLI to their Auth0 tenant
|
||||
- If the user agrees to install the Auth0 CLI, do the mechanical setup yourself instead of bouncing them through the dashboard
|
||||
- If login succeeds but Convex still reports unauthenticated, double-check `convex/auth.config.ts` and whether the backend config was synced
|
||||
- We were able to automate Auth0 app creation and Convex config wiring, but we did not fully validate the refresh-token path end to end
|
||||
- In validation, the documented `useRefreshTokens={true}` and `cacheLocation="localstorage"` setup hit refresh-token failures, so do not present that path as settled
|
||||
- If you hit Auth0 errors like `Unknown or invalid refresh token`, do not keep inventing fixes indefinitely, send the user back to the official docs and explain that this path is still under investigation
|
||||
- Keep dev and prod tenants separate if the project uses different Auth0 environments
|
||||
- Do not confuse "Auth0 login works" with "Convex can validate the Auth0 token". Both need to work.
|
||||
- If the repo already uses Auth0, preserve existing redirect and tenant configuration unless the user asked to change it.
|
||||
- Do not assume the local Auth0 tenant settings match production. Verify the production domain, client ID, and callback URLs separately.
|
||||
- For local dev, make sure the Auth0 app settings match the app's real local port for callback URLs, logout URLs, and web origins
|
||||
|
||||
## Production
|
||||
|
||||
- Ask whether the user wants dev-only setup or production-ready setup
|
||||
- If the answer is production-ready, make sure the production Auth0 tenant values, callback URLs, and Convex deployment config are all covered
|
||||
- Verify production environment variables and redirect settings before calling the task complete
|
||||
- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly.
|
||||
|
||||
## Validation
|
||||
|
||||
- Verify the user can complete the Auth0 login flow
|
||||
- Verify Convex-authenticated UI renders only after Convex auth state is ready
|
||||
- Verify protected Convex queries succeed after login
|
||||
- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions
|
||||
- Verify the Auth0 app settings match the real local callback and logout URLs during development
|
||||
- If the Auth0 refresh-token path fails, mark the setup as not fully validated and direct the user to the official docs instead of claiming the skill completed successfully
|
||||
- If production-ready setup was requested, verify the production Auth0 configuration is also covered
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Confirm the user wants Auth0
|
||||
- [ ] Ask whether the user wants local-only setup or production-ready setup
|
||||
- [ ] Complete the relevant Auth0 frontend setup
|
||||
- [ ] Configure `convex/auth.config.ts`
|
||||
- [ ] Set environment variables
|
||||
- [ ] Verify Convex authenticated state after login, or explicitly tell the user this path is still under investigation and send them to the official docs
|
||||
- [ ] If requested, configure the production deployment too
|
||||
@@ -1,113 +0,0 @@
|
||||
# Clerk
|
||||
|
||||
Official docs:
|
||||
|
||||
- https://docs.convex.dev/auth/clerk
|
||||
- https://clerk.com/docs/guides/development/integrations/databases/convex
|
||||
|
||||
Use this when the app already uses Clerk or the user wants Clerk's hosted auth features.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Confirm the user wants Clerk
|
||||
2. Make sure the user has a Clerk account and a Clerk application
|
||||
3. Determine the app framework:
|
||||
- React
|
||||
- Next.js
|
||||
- TanStack Start
|
||||
4. Ask whether the user wants local-only setup or production-ready setup now
|
||||
5. Gather the Clerk keys and the Clerk Frontend API URL
|
||||
6. Follow the correct framework section in the official docs
|
||||
7. Complete the backend and client wiring
|
||||
8. Verify Convex reports the user as authenticated after login
|
||||
9. If the user wants production-ready setup, make sure the production Clerk config is also covered
|
||||
|
||||
## What To Do
|
||||
|
||||
- Read the official Convex and Clerk guide before writing setup code
|
||||
- If the user does not already have Clerk set up, send them to `https://dashboard.clerk.com/sign-up` to create an account and `https://dashboard.clerk.com/apps/new` to create an application
|
||||
- Send the user to `https://dashboard.clerk.com/apps/setup/convex` if the Convex integration is not already active
|
||||
- Match the guide to the app's framework, usually React, Next.js, or TanStack Start
|
||||
- Use the official examples for `ConvexProviderWithClerk`, `ClerkProvider`, and `useAuth`
|
||||
|
||||
## Key Setup Areas
|
||||
|
||||
- install the Clerk SDK for the framework in use
|
||||
- configure `convex/auth.config.ts` with the Clerk issuer domain
|
||||
- set the required Clerk environment variables
|
||||
- wrap the app with `ClerkProvider` and `ConvexProviderWithClerk`
|
||||
- use Convex auth-aware UI patterns such as `Authenticated`, `Unauthenticated`, and `AuthLoading`
|
||||
|
||||
## Files and Env Vars To Expect
|
||||
|
||||
- `convex/auth.config.ts`
|
||||
- React or Vite client entry such as `src/main.tsx`
|
||||
- Next.js client wrapper for Convex if using App Router
|
||||
- Clerk account sign-up page: `https://dashboard.clerk.com/sign-up`
|
||||
- Clerk app creation page: `https://dashboard.clerk.com/apps/new`
|
||||
- Clerk Convex integration page: `https://dashboard.clerk.com/apps/setup/convex`
|
||||
- Clerk API keys page: `https://dashboard.clerk.com/last-active?path=api-keys`
|
||||
- Clerk environment variables:
|
||||
- `CLERK_JWT_ISSUER_DOMAIN` for Convex backend validation in the Convex docs
|
||||
- `CLERK_FRONTEND_API_URL` in the Clerk docs
|
||||
- `VITE_CLERK_PUBLISHABLE_KEY` for Vite apps
|
||||
- `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` for Next.js apps
|
||||
- `CLERK_SECRET_KEY` for Next.js server-side Clerk setup where required
|
||||
|
||||
`CLERK_JWT_ISSUER_DOMAIN` and `CLERK_FRONTEND_API_URL` refer to the same Clerk Frontend API URL value. Do not treat them as two different URLs.
|
||||
|
||||
## Concrete Steps
|
||||
|
||||
1. If needed, create a Clerk account at `https://dashboard.clerk.com/sign-up`
|
||||
2. If needed, create a Clerk application at `https://dashboard.clerk.com/apps/new`
|
||||
3. Open `https://dashboard.clerk.com/last-active?path=api-keys` and copy the publishable key, plus the secret key for Next.js where needed
|
||||
4. Open `https://dashboard.clerk.com/apps/setup/convex`
|
||||
5. Activate the Convex integration in Clerk if it is not already active
|
||||
6. Copy the Clerk Frontend API URL shown there
|
||||
7. Install the Clerk package for the app's framework
|
||||
8. Create or update `convex/auth.config.ts` so Convex validates Clerk tokens
|
||||
9. Set the publishable key in the frontend environment
|
||||
10. Set the issuer domain or Frontend API URL so Convex can validate the JWT
|
||||
11. Replace plain `ConvexProvider` wiring with `ConvexProviderWithClerk`
|
||||
12. Wrap the app in `ClerkProvider`
|
||||
13. Use Convex auth helpers for authenticated rendering
|
||||
14. Run the normal Convex dev or deploy flow after updating backend auth config
|
||||
15. If the user wants production-ready setup, configure the production Clerk values and production issuer domain too
|
||||
|
||||
## Gotchas
|
||||
|
||||
- Prefer `useConvexAuth()` over raw Clerk auth state when deciding whether Convex-authenticated UI can render
|
||||
- For Next.js, keep server and client boundaries in mind when creating the Convex provider wrapper
|
||||
- After changing `convex/auth.config.ts`, run the normal Convex dev or deploy flow so the backend picks up the new config
|
||||
- Do not stop at "Clerk login works". The important check is that Convex also sees the session and can authenticate requests.
|
||||
- If the repo already uses Clerk, preserve its existing auth flow unless the user asked to change it.
|
||||
- Do not assume the same Clerk values work for both dev and production. Check the production issuer domain and publishable key separately.
|
||||
- The Convex setup page is where you get the Clerk Frontend API URL for Convex. Keep using the Clerk API keys page for the publishable key and the secret key.
|
||||
- If Convex says no auth provider matched the token, first confirm the Clerk Convex integration was activated at `https://dashboard.clerk.com/apps/setup/convex`
|
||||
- After activating the Clerk Convex integration, sign out completely and sign back in before retesting. An old Clerk session can keep using a token that Convex rejects.
|
||||
|
||||
## Production
|
||||
|
||||
- Ask whether the user wants dev-only setup or production-ready setup
|
||||
- If the answer is production-ready, make sure production Clerk keys and issuer configuration are included
|
||||
- Verify production redirect URLs and any production Clerk domain values before calling the task complete
|
||||
- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly.
|
||||
|
||||
## Validation
|
||||
|
||||
- Verify the user can sign in with Clerk
|
||||
- If the Clerk integration was just activated, verify after a full Clerk sign-out and fresh sign-in
|
||||
- Verify `useConvexAuth()` reaches the authenticated state after Clerk login
|
||||
- Verify protected Convex queries run successfully inside authenticated UI
|
||||
- Verify `ctx.auth.getUserIdentity()` is non-null in protected backend functions
|
||||
- If production-ready setup was requested, verify the production Clerk configuration is also covered
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Confirm the user wants Clerk
|
||||
- [ ] Ask whether the user wants local-only setup or production-ready setup
|
||||
- [ ] Follow the correct framework section in the official guide
|
||||
- [ ] Set Clerk environment variables
|
||||
- [ ] Configure `convex/auth.config.ts`
|
||||
- [ ] Verify Convex authenticated state after login
|
||||
- [ ] If requested, configure the production deployment too
|
||||
@@ -1,143 +0,0 @@
|
||||
# Convex Auth
|
||||
|
||||
Official docs: https://docs.convex.dev/auth/convex-auth
|
||||
Setup guide: https://labs.convex.dev/auth/setup
|
||||
|
||||
Use this when the user wants auth handled directly in Convex rather than through a third-party provider.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Confirm the user wants Convex Auth specifically
|
||||
2. Determine which sign-in methods the app needs:
|
||||
- magic links or OTPs
|
||||
- OAuth providers
|
||||
- passwords and password reset
|
||||
3. Ask whether the user wants local-only setup or production-ready setup now
|
||||
4. Read the Convex Auth setup guide before writing code
|
||||
5. Make sure the project has a configured Convex deployment:
|
||||
- run `npx convex dev` first if `CONVEX_DEPLOYMENT` is not set
|
||||
- if CLI configuration requires interactive human input, stop and ask the user to complete that step before continuing
|
||||
6. Install the auth packages:
|
||||
- `npm install @convex-dev/auth @auth/core@0.37.0`
|
||||
7. Run the initialization command:
|
||||
- `npx @convex-dev/auth`
|
||||
8. Confirm the initializer created:
|
||||
- `convex/auth.config.ts`
|
||||
- `convex/auth.ts`
|
||||
- `convex/http.ts`
|
||||
9. Add the required `authTables` to `convex/schema.ts`
|
||||
10. Replace plain `ConvexProvider` wiring with `ConvexAuthProvider`
|
||||
11. Configure at least one auth method in `convex/auth.ts`
|
||||
12. Run `npx convex dev --once` or the normal dev flow to push the updated schema and generated code
|
||||
13. Verify the client can sign in successfully
|
||||
14. Verify Convex receives authenticated identity in backend functions
|
||||
15. If the user wants production-ready setup, make sure the same auth setup is configured for the production deployment as well
|
||||
16. Only add a `users` table and `storeUser` flow if the app needs app-level user records inside Convex
|
||||
|
||||
## What This Reference Is For
|
||||
|
||||
- choosing Convex Auth as the default provider for a new Convex app
|
||||
- understanding whether the app wants magic links, OTPs, OAuth, or passwords
|
||||
- keeping the setup provider-specific while using the official Convex Auth docs for identity and authorization behavior
|
||||
|
||||
## What To Do
|
||||
|
||||
- Read the Convex Auth setup guide before writing setup code
|
||||
- Follow the setup flow from the docs rather than recreating it from memory
|
||||
- If the app is new, consider starting from the official starter flow instead of hand-wiring everything
|
||||
- Treat `npx @convex-dev/auth` as a required initialization step for existing apps, not an optional extra
|
||||
|
||||
## Concrete Steps
|
||||
|
||||
1. Install `@convex-dev/auth` and `@auth/core@0.37.0`
|
||||
2. Run `npx convex dev` if the project does not already have a configured deployment
|
||||
3. If `npx convex dev` blocks on interactive setup, ask the user explicitly to finish configuring the Convex deployment
|
||||
4. Run `npx @convex-dev/auth`
|
||||
5. Confirm the generated auth setup is present before continuing:
|
||||
- `convex/auth.config.ts`
|
||||
- `convex/auth.ts`
|
||||
- `convex/http.ts`
|
||||
6. Add `authTables` to `convex/schema.ts`
|
||||
7. Replace `ConvexProvider` with `ConvexAuthProvider` in the app entry
|
||||
8. Configure the selected auth methods in `convex/auth.ts`
|
||||
9. Run `npx convex dev --once` or the normal dev flow so the updated schema and auth files are pushed
|
||||
10. Verify login locally
|
||||
11. If the user wants production-ready setup, repeat the required auth configuration against the production deployment
|
||||
|
||||
## Expected Files and Decisions
|
||||
|
||||
- `convex/schema.ts`
|
||||
- frontend app entry such as `src/main.tsx` or the framework-equivalent provider file
|
||||
- generated Convex Auth setup produced by `npx @convex-dev/auth`
|
||||
- an existing configured Convex deployment, or the ability to create one with `npx convex dev`
|
||||
- `convex/auth.ts` starts with `providers: []` until the app configures actual sign-in methods
|
||||
|
||||
- Decide whether the user is creating a new app or adding auth to an existing app
|
||||
- For a new app, prefer the official starter flow instead of rebuilding setup by hand
|
||||
- Decide which auth methods the app needs:
|
||||
- magic links or OTPs
|
||||
- OAuth providers
|
||||
- passwords
|
||||
- Decide whether the user wants local-only setup or production-ready setup now
|
||||
- Decide whether the app actually needs a `users` table inside Convex, or whether provider identity alone is enough
|
||||
|
||||
## Gotchas
|
||||
|
||||
- Do not assume a specific sign-in method. Ask which methods the app needs before wiring UI and backend behavior.
|
||||
- `npx @convex-dev/auth` is important because it initializes the auth setup, including the key material. Do not skip it when adding Convex Auth to an existing project.
|
||||
- `npx @convex-dev/auth` will fail if the project does not already have a configured `CONVEX_DEPLOYMENT`.
|
||||
- `npx convex dev` may require interactive setup for deployment creation or project selection. If that happens, ask the user explicitly for that human step instead of guessing.
|
||||
- `npx @convex-dev/auth` does not finish the whole integration by itself. You still need to add `authTables`, swap in `ConvexAuthProvider`, and configure at least one auth method.
|
||||
- A project can still build even if `convex/auth.ts` still has `providers: []`, so do not treat a successful build as proof that sign-in is fully configured.
|
||||
- Convex Auth does not mean every app needs a `users` table. If the app only needs authentication gates, `ctx.auth.getUserIdentity()` may be enough.
|
||||
- If the app is greenfield, starting from the official starter flow is usually better than partially recreating it by hand.
|
||||
- Do not stop at local dev setup if the user expects production-ready auth. The production deployment needs the auth setup too.
|
||||
- Keep provider-specific setup and Convex Auth authorization behavior in the official docs instead of inventing shared patterns from memory.
|
||||
|
||||
## Production
|
||||
|
||||
- Ask whether the user wants dev-only setup or production-ready setup
|
||||
- If the answer is production-ready, make sure the auth configuration is applied to the production deployment, not just the dev deployment
|
||||
- Verify production-specific redirect URLs, auth method configuration, and deployment settings before calling the task complete
|
||||
- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly.
|
||||
|
||||
## Human Handoff
|
||||
|
||||
If `npx convex dev` or deployment setup requires human input:
|
||||
|
||||
- stop and explain exactly what the user needs to do
|
||||
- say why that step is required
|
||||
- resume the auth setup immediately after the user confirms it is done
|
||||
|
||||
## Validation
|
||||
|
||||
- Verify the user can complete a sign-in flow
|
||||
- Offer to validate sign up, sign out, and sign back in with the configured auth method
|
||||
- If browser automation is available in the environment, you can do this directly
|
||||
- If browser automation is not available, give the user a short manual validation checklist instead
|
||||
- Verify `ctx.auth.getUserIdentity()` returns an identity in protected backend functions
|
||||
- Verify protected UI only renders after Convex-authenticated state is ready
|
||||
- Verify environment variables and redirect settings match the current app environment
|
||||
- Verify `convex/auth.ts` no longer has an empty `providers: []` configuration once the app is meant to support real sign-in
|
||||
- Run `npx convex dev --once` or the normal dev flow after setup changes and confirm Convex codegen and push succeed
|
||||
- If production-ready setup was requested, verify the production deployment is also configured correctly
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Confirm the user wants Convex Auth specifically
|
||||
- [ ] Ask whether the user wants local-only setup or production-ready setup
|
||||
- [ ] Ensure a Convex deployment is configured before running auth initialization
|
||||
- [ ] Install `@convex-dev/auth` and `@auth/core@0.37.0`
|
||||
- [ ] Run `npx convex dev` first if needed
|
||||
- [ ] Run `npx @convex-dev/auth`
|
||||
- [ ] Confirm `convex/auth.config.ts`, `convex/auth.ts`, and `convex/http.ts` were created
|
||||
- [ ] Follow the setup guide for package install and wiring
|
||||
- [ ] Add `authTables` to `convex/schema.ts`
|
||||
- [ ] Replace `ConvexProvider` with `ConvexAuthProvider`
|
||||
- [ ] Configure at least one auth method in `convex/auth.ts`
|
||||
- [ ] Run `npx convex dev --once` or the normal dev flow after setup changes
|
||||
- [ ] Confirm which sign-in methods the app needs
|
||||
- [ ] Verify the client can sign in and the backend receives authenticated identity
|
||||
- [ ] Offer end-to-end validation of sign up, sign out, and sign back in
|
||||
- [ ] If requested, configure the production deployment too
|
||||
- [ ] Only add extra `users` table sync if the app needs app-level user records
|
||||
@@ -1,114 +0,0 @@
|
||||
# WorkOS AuthKit
|
||||
|
||||
Official docs:
|
||||
|
||||
- https://docs.convex.dev/auth/authkit/
|
||||
- https://docs.convex.dev/auth/authkit/add-to-app
|
||||
- https://docs.convex.dev/auth/authkit/auto-provision
|
||||
|
||||
Use this when the app already uses WorkOS or the user wants AuthKit specifically.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Confirm the user wants WorkOS AuthKit
|
||||
2. Determine whether they want:
|
||||
- a Convex-managed WorkOS team
|
||||
- an existing WorkOS team
|
||||
3. Ask whether the user wants local-only setup or production-ready setup now
|
||||
4. Read the official Convex and WorkOS AuthKit guide
|
||||
5. Create or update `convex.json` for the app's framework and real local port
|
||||
6. Follow the correct branch of the setup flow based on that choice
|
||||
7. Configure the required WorkOS environment variables
|
||||
8. Configure `convex/auth.config.ts` for WorkOS-issued JWTs
|
||||
9. Wire the client provider and callback flow
|
||||
10. Verify authenticated requests reach Convex
|
||||
11. If the user wants production-ready setup, make sure the production WorkOS configuration is covered too
|
||||
12. Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex
|
||||
|
||||
## What To Do
|
||||
|
||||
- Read the official Convex and WorkOS AuthKit guide before writing setup code
|
||||
- Determine whether the user wants a Convex-managed WorkOS team or an existing WorkOS team
|
||||
- Treat `convex.json` as a first-class part of the AuthKit setup, not an optional extra
|
||||
- Follow the current setup flow from the docs instead of relying on older examples
|
||||
|
||||
## Key Setup Areas
|
||||
|
||||
- package installation for the app's framework
|
||||
- `convex.json` with the `authKit` section for dev, and preview or prod if needed
|
||||
- environment variables such as `WORKOS_CLIENT_ID`, `WORKOS_API_KEY`, and redirect configuration
|
||||
- `convex/auth.config.ts` wiring for WorkOS-issued JWTs
|
||||
- client provider setup and token flow into Convex
|
||||
- login callback and redirect configuration
|
||||
|
||||
## Files and Env Vars To Expect
|
||||
|
||||
- `convex.json`
|
||||
- `convex/auth.config.ts`
|
||||
- frontend auth provider wiring
|
||||
- callback or redirect route setup where the framework requires it
|
||||
- WorkOS environment variables commonly include:
|
||||
- `WORKOS_CLIENT_ID`
|
||||
- `WORKOS_API_KEY`
|
||||
- `WORKOS_COOKIE_PASSWORD`
|
||||
- `VITE_WORKOS_CLIENT_ID`
|
||||
- `VITE_WORKOS_REDIRECT_URI`
|
||||
- `NEXT_PUBLIC_WORKOS_REDIRECT_URI`
|
||||
|
||||
For a managed WorkOS team, `convex dev` can provision the AuthKit environment and write local env vars such as `VITE_WORKOS_CLIENT_ID` and `VITE_WORKOS_REDIRECT_URI` into `.env.local` for Vite apps.
|
||||
|
||||
## Concrete Steps
|
||||
|
||||
1. Choose Convex-managed or existing WorkOS team
|
||||
2. Create or update `convex.json` with the `authKit` section for the framework in use
|
||||
3. Make sure the dev `redirectUris`, `appHomepageUrl`, `corsOrigins`, and local redirect env vars match the app's actual local port
|
||||
4. For a managed WorkOS team, run `npx convex dev` and follow the interactive onboarding flow
|
||||
5. For an existing WorkOS team, get `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` from the WorkOS dashboard and set them with `npx convex env set`
|
||||
6. Create or update `convex/auth.config.ts` for WorkOS JWT validation
|
||||
7. Run the normal Convex dev or deploy flow so backend config is synced
|
||||
8. Wire the WorkOS client provider in the app
|
||||
9. Configure callback and redirect handling
|
||||
10. Verify the user can sign in and return to the app
|
||||
11. Verify Convex sees the authenticated user after login
|
||||
12. If the user wants production-ready setup, configure the production client ID, API key, redirect URI, and deployment settings too
|
||||
|
||||
## Gotchas
|
||||
|
||||
- The docs split setup between Convex-managed and existing WorkOS teams, so ask which path the user wants if it is not obvious
|
||||
- Keep dev and prod WorkOS configuration separate where the docs call for different client IDs or API keys
|
||||
- Only add `storeUser` or a `users` table if the app needs first-class user rows inside Convex
|
||||
- Do not mix dev and prod WorkOS credentials or redirect URIs
|
||||
- If the repo already contains WorkOS setup, preserve the current tenant model unless the user wants to change it
|
||||
- For managed WorkOS setup, `convex dev` is interactive the first time. In non-interactive terminals, stop and ask the user to complete the onboarding prompts.
|
||||
- `convex.json` is not optional for the managed AuthKit flow. It drives redirect URI, homepage URL, CORS configuration, and local env var generation.
|
||||
- If the frontend starts on a different port than the one in `convex.json`, the hosted WorkOS sign-in flow will point to the wrong callback URL. Update `convex.json`, update the local redirect env var, and run `npx convex dev` again.
|
||||
- Vite can fall off `5173` if other apps are already running. Do not assume the default port still matches the generated AuthKit config.
|
||||
- A successful WorkOS sign-in should redirect back to the local callback route and then reach a Convex-authenticated state. Do not stop at "the hosted WorkOS page loaded."
|
||||
|
||||
## Production
|
||||
|
||||
- Ask whether the user wants dev-only setup or production-ready setup
|
||||
- If the answer is production-ready, make sure the production WorkOS client ID, API key, redirect URI, and Convex deployment config are all covered
|
||||
- Verify the production redirect and callback settings before calling the task complete
|
||||
- Do not silently write a notes file into the repo by default. If the user wants rollout or handoff docs, create one explicitly.
|
||||
|
||||
## Validation
|
||||
|
||||
- Verify the user can complete the login flow and return to the app
|
||||
- Verify the callback URL matches the real frontend port in local dev
|
||||
- Verify Convex receives authenticated requests after login
|
||||
- Verify `convex.json` matches the framework and chosen WorkOS setup path
|
||||
- Verify `convex/auth.config.ts` matches the chosen WorkOS setup path
|
||||
- Verify environment variables differ correctly between local and production where needed
|
||||
- If production-ready setup was requested, verify the production WorkOS configuration is also covered
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Confirm the user wants WorkOS AuthKit
|
||||
- [ ] Ask whether the user wants local-only setup or production-ready setup
|
||||
- [ ] Choose Convex-managed or existing WorkOS team
|
||||
- [ ] Create or update `convex.json`
|
||||
- [ ] Configure WorkOS environment variables
|
||||
- [ ] Configure `convex/auth.config.ts`
|
||||
- [ ] Verify authenticated requests reach Convex after login
|
||||
- [ ] If requested, configure the production deployment too
|
||||
@@ -1,47 +0,0 @@
|
||||
---
|
||||
name: convex
|
||||
description: Routes general Convex requests to the right project skill. Use when the user asks which Convex skill to use or gives an underspecified Convex app task.
|
||||
---
|
||||
|
||||
# Convex
|
||||
|
||||
Use this as the routing skill for Convex work in this repo.
|
||||
|
||||
If a more specific Convex skill clearly matches the request, use that instead.
|
||||
|
||||
## Start Here
|
||||
|
||||
If the project does not already have Convex AI guidance installed, or the existing guidance looks stale, strongly recommend installing it first.
|
||||
|
||||
Preferred:
|
||||
|
||||
```bash
|
||||
npx convex ai-files install
|
||||
```
|
||||
|
||||
This installs or refreshes the managed Convex AI files. It is the recommended starting point for getting the official Convex guidelines in place and following the current Convex AI setup described in the docs:
|
||||
|
||||
- [Convex AI docs](https://docs.convex.dev/ai)
|
||||
|
||||
Simple fallback:
|
||||
|
||||
- [convex_rules.txt](https://convex.link/convex_rules.txt)
|
||||
|
||||
Prefer `npx convex ai-files install` over copying rules by hand when possible.
|
||||
|
||||
## Route to the Right Skill
|
||||
|
||||
After that, use the most specific Convex skill for the task:
|
||||
|
||||
- New project or adding Convex to an app: `convex-quickstart`
|
||||
- Authentication setup: `convex-setup-auth`
|
||||
- Building a reusable Convex component: `convex-create-component`
|
||||
- Planning or running a migration: `convex-migration-helper`
|
||||
- Investigating performance issues: `convex-performance-audit`
|
||||
|
||||
If one of those clearly matches the user's goal, switch to it instead of staying in this skill.
|
||||
|
||||
## When Not to Use
|
||||
|
||||
- The user has already named a more specific Convex workflow
|
||||
- Another Convex skill obviously fits the request better
|
||||
@@ -1,62 +0,0 @@
|
||||
name: ClawSweeper Dispatch
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened, edited, labeled, unlabeled]
|
||||
pull_request_target: # zizmor: ignore[dangerous-triggers] maintainer-owned external dispatch; no checkout or untrusted PR code execution
|
||||
types: [opened, reopened, synchronize, ready_for_review, edited, labeled, unlabeled]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: clawsweeper-dispatch-${{ github.repository }}-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event.action == 'edited' || github.event.action == 'synchronize' || github.event.action == 'ready_for_review' }}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ !(endsWith(github.actor, '[bot]') && (github.event.action == 'labeled' || github.event.action == 'unlabeled')) }}
|
||||
env:
|
||||
HAS_CLAWSWEEPER_APP_PRIVATE_KEY: ${{ secrets.CLAWSWEEPER_APP_PRIVATE_KEY != '' }}
|
||||
CLAWSWEEPER_APP_CLIENT_ID: Iv23liOECG0slfuhz093
|
||||
SUPERSEDES_IN_PROGRESS: ${{ (github.event.action == 'edited' || github.event.action == 'synchronize' || github.event.action == 'ready_for_review') && 'true' || 'false' }}
|
||||
steps:
|
||||
- name: Debounce bursty metadata events
|
||||
if: ${{ github.event.action == 'labeled' || github.event.action == 'unlabeled' }}
|
||||
run: sleep 20
|
||||
|
||||
- name: Create ClawSweeper dispatch token
|
||||
id: token
|
||||
if: ${{ env.HAS_CLAWSWEEPER_APP_PRIVATE_KEY == 'true' }}
|
||||
uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
|
||||
with:
|
||||
client-id: ${{ env.CLAWSWEEPER_APP_CLIENT_ID }}
|
||||
private-key: ${{ secrets.CLAWSWEEPER_APP_PRIVATE_KEY }}
|
||||
owner: openclaw
|
||||
repositories: clawsweeper
|
||||
|
||||
- name: Dispatch exact ClawSweeper review
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.token.outputs.token || secrets.OPENCLAW_GH_TOKEN }}
|
||||
TARGET_REPO: ${{ github.repository }}
|
||||
ITEM_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }}
|
||||
ITEM_KIND: ${{ github.event_name == 'pull_request_target' && 'pull_request' || 'issue' }}
|
||||
SOURCE_EVENT: ${{ github.event_name }}
|
||||
SOURCE_ACTION: ${{ github.event.action }}
|
||||
run: |
|
||||
if [ -z "$GH_TOKEN" ]; then
|
||||
echo "::notice::Skipping ClawSweeper dispatch because no dispatch credential is configured."
|
||||
exit 0
|
||||
fi
|
||||
payload="$(jq -nc \
|
||||
--arg target_repo "$TARGET_REPO" \
|
||||
--argjson item_number "$ITEM_NUMBER" \
|
||||
--arg item_kind "$ITEM_KIND" \
|
||||
--arg source_event "$SOURCE_EVENT" \
|
||||
--arg source_action "$SOURCE_ACTION" \
|
||||
--argjson supersedes_in_progress "$SUPERSEDES_IN_PROGRESS" \
|
||||
'{event_type:"clawsweeper_item",client_payload:{target_repo:$target_repo,item_number:$item_number,item_kind:$item_kind,source_event:$source_event,source_action:$source_action,supersedes_in_progress:$supersedes_in_progress}}')"
|
||||
gh api repos/openclaw/clawsweeper/dispatches \
|
||||
--method POST \
|
||||
--input - <<< "$payload"
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
|
||||
- name: Install Playwright browser
|
||||
if: needs.validate-deploy-request.outputs.run_smoke == 'true'
|
||||
run: bunx playwright install --with-deps chromium webkit
|
||||
run: bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Write authenticated storage state
|
||||
if: needs.validate-deploy-request.outputs.run_smoke == 'true' && env.PLAYWRIGHT_AUTH_STORAGE_STATE_JSON != ''
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
name: Update Convex AI Files
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Midnight Pacific during daylight saving time. GitHub cron uses UTC.
|
||||
- cron: "0 7 * * 1"
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: update-convex-ai-files
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
BUN_VERSION: "1.3.10"
|
||||
UPDATE_BRANCH: automation/update-convex-ai-files
|
||||
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@e3914758a49697077f7bcd190d36582a61667aad
|
||||
with:
|
||||
bun-version: ${{ env.BUN_VERSION }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Update Convex AI files
|
||||
run: |
|
||||
"$(bun pm bin)/convex" ai-files update
|
||||
|
||||
- name: Check Convex AI files status
|
||||
run: |
|
||||
"$(bun pm bin)/convex" ai-files status
|
||||
|
||||
- name: Detect changes
|
||||
id: changes
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -n "$(git status --porcelain)" ]]; then
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Commit and push update branch
|
||||
if: steps.changes.outputs.changed == 'true'
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git checkout -B "$UPDATE_BRANCH"
|
||||
git add AGENTS.md CLAUDE.md .agents/skills convex/_generated/ai/guidelines.md convex/_generated/ai/ai-files.state.json
|
||||
git commit -m "chore: update Convex AI files"
|
||||
git push --force-with-lease origin "$UPDATE_BRANCH"
|
||||
|
||||
- name: Open or update pull request
|
||||
if: steps.changes.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
body_file="$(mktemp)"
|
||||
{
|
||||
printf '%s\n' '## Summary'
|
||||
printf '\n'
|
||||
printf '%s\n' '- refresh Convex-managed AI guidance files'
|
||||
printf '%s\n' '- keep AGENTS.md / CLAUDE.md Convex sections in sync when Convex updates them'
|
||||
printf '%s\n' '- update repo-local Convex developer skills under .agents/skills'
|
||||
printf '\n'
|
||||
printf '%s\n' '## Validation'
|
||||
printf '\n'
|
||||
printf '%s\n' '- `$(bun pm bin)/convex ai-files status`'
|
||||
} > "$body_file"
|
||||
|
||||
if gh pr view "$UPDATE_BRANCH" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
gh pr edit "$UPDATE_BRANCH" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--title "[automation] Update Convex AI files" \
|
||||
--body-file "$body_file"
|
||||
else
|
||||
gh pr create \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--base main \
|
||||
--head "$UPDATE_BRANCH" \
|
||||
--title "[automation] Update Convex AI files" \
|
||||
--body-file "$body_file"
|
||||
fi
|
||||
@@ -10,9 +10,7 @@ dist-ssr
|
||||
*.local
|
||||
.vercel
|
||||
count.txt
|
||||
.env*
|
||||
!.env.local.example
|
||||
!.env.example
|
||||
.env
|
||||
.nitro
|
||||
.tanstack
|
||||
.wrangler
|
||||
@@ -26,15 +24,7 @@ coverage
|
||||
playwright-report
|
||||
test-results
|
||||
.playwright
|
||||
convex/_generated/*
|
||||
!convex/_generated/ai/
|
||||
convex/_generated/ai/*
|
||||
!convex/_generated/ai/guidelines.md
|
||||
!convex/_generated/ai/ai-files.state.json
|
||||
convex/_generated/
|
||||
skills-lock.json
|
||||
*/skills/*
|
||||
!.agents/skills/
|
||||
!.agents/skills/convex*/
|
||||
!.agents/skills/convex*/**
|
||||
skills/*
|
||||
.codex/*
|
||||
skills/*
|
||||
@@ -41,7 +41,6 @@
|
||||
- Before merging any PR, verify TypeScript cleanly with `bunx tsc -p packages/schema/tsconfig.json --noEmit` and `bunx tsc -p packages/clawhub/tsconfig.json --noEmit`; if Convex code changed, also run the repo typecheck path used by deploy so `bunx convex deploy` will not fail on `tsc`.
|
||||
- GitHub comments: for multiline `gh` comments/close messages, use `--body-file`, `--input`, or stdin/heredoc with real newlines; never pass literal `\\n` in shell strings.
|
||||
- Reject PRs that add skills into source code/repo content directly (for example under `skills/` or seed-only additions intended as published skills). Skills must be uploaded/published via CLI.
|
||||
- Repo-local Convex developer skills under `.agents/skills/convex*/` are allowed when they support working on this codebase; keep top-level `skills/` reserved for installed/published skill content and ignored by git.
|
||||
|
||||
## Production Release
|
||||
|
||||
@@ -96,23 +95,3 @@ When working on Convex code, **always read `convex/_generated/ai/guidelines.md`
|
||||
|
||||
Convex agent skills for common tasks can be installed by running `npx convex ai-files install`.
|
||||
<!-- convex-ai-end -->
|
||||
|
||||
## Stat Field Migration Rules
|
||||
|
||||
The `skills` table maintains two parallel sets of stat fields as part of an in-progress field migration:
|
||||
|
||||
| Legacy (nested, `@deprecated`) | Top-level (source of truth, indexable) |
|
||||
|---|---|
|
||||
| `stats.downloads` | `statsDownloads` |
|
||||
| `stats.stars` | `statsStars` |
|
||||
| `stats.installsCurrent` | `statsInstallsCurrent` |
|
||||
| `stats.installsAllTime` | `statsInstallsAllTime` |
|
||||
|
||||
**Rules:**
|
||||
|
||||
- **Always use `readCanonicalStat(skill, field)` (`convex/lib/skillStats.ts`) to read** any of the four migrated fields. It prefers the top-level field and falls back to the nested field for pre-migration documents. Never access `skill.stats.downloads` / `.stars` / `.installsCurrent` / `.installsAllTime` directly.
|
||||
- **Always use `applySkillStatDeltas()` to write** stat deltas. It writes both the top-level and nested fields in the same patch to keep them in sync.
|
||||
- **Both sets of fields must be written together** in any patch that touches stat values (see the return shape of `applySkillStatDeltas`).
|
||||
- **Nested-only reads are acceptable only for** `stats.comments` and `stats.versions` — no top-level field exists for these yet.
|
||||
- The four legacy nested fields are marked `@deprecated` in `statsValidator` (schema.ts). Any IDE access to `skill.stats.downloads` etc. will show a strikethrough warning — treat this as a signal to use `readCanonicalStat()` instead.
|
||||
- When adding new stat fields, follow the same dual-write pattern and add a cursor-based backfill mutation (see `backfillSkillStatFieldsInternal` for an example).
|
||||
|
||||
@@ -2,36 +2,13 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Fixes
|
||||
|
||||
- Moderation: calibrate VirusTotal Code Insight suspicious verdicts so uncorroborated AI-only findings do not keep otherwise clean skills quarantined (#1830, #1841) (thanks @deepujain).
|
||||
|
||||
## 0.11.0 - 2026-04-28
|
||||
|
||||
### Changed
|
||||
|
||||
- Docs: clarify that ClawHub does not support paid skills, per-skill pricing, or paywalled releases (#1752, #1844) (thanks @deepujain).
|
||||
- API docs: clarify how third-party directories can reuse public ClawHub catalog endpoints while respecting rate limits and canonical links (#1825, #1845) (thanks @deepujain).
|
||||
- Packages docs: document the required fields for code-plugin package publish flows (#1802) (thanks @deepujain).
|
||||
- Search: add CJK tokenization support (Chinese/Japanese/Korean) with Intl.Segmenter plus fallback behavior to improve skill query matching (#1596) (thanks @pq-dong).
|
||||
- Stats: centralize migrated skill stat fallback reads through `readCanonicalStat()` and add schema/agent guardrails to discourage direct legacy nested-field access (#1709) (thanks @momothemage).
|
||||
|
||||
### Fixes
|
||||
|
||||
- Packages: use the configured `GITHUB_TOKEN` for trusted-publisher repository identity lookups to avoid anonymous GitHub API rate limits during publish setup (#1820, #1846) (thanks @deepujain).
|
||||
- Packages: keep package search fallback scans bounded, stop scanning after the requested result limit, and keep direct plugin-name matches scoped to the requested package family (OpenClaw #64025).
|
||||
- Moderation: stop flagging declared env vars sent to their intended API while preserving broad env scraping and exfiltration findings (#1803) (thanks @deepujain).
|
||||
- Moderation: stop treating generic webhook integration docs as suspicious unless they include explicit Discord or Slack webhook endpoints (#1716) (thanks @langningchen-openclaw).
|
||||
- Search: increase initial vector candidate pools and align CLI search's default limit with the web UI so high-scoring matches are not missed at small limits (#1375, #1429) (thanks @tjefferson).
|
||||
- Search: fall back to lexical skill search when embedding generation fails instead of returning empty skill results (#1291) (thanks @goulonghui).
|
||||
- Search: rank exact slug matches above longer slugs that merely contain all query tokens (#1130) (thanks @QuinnH496).
|
||||
- Search: widen lexical fallback coverage and scan recently created skills so newly published skills can be found before embeddings rank well (#1185, #1200) (thanks @thirumaleshp).
|
||||
- Search: preserve vector scores across candidate expansion and require all query tokens to match exact-token filters so relevant skills are not crowded out (#1759, #1762) (thanks @LinPower).
|
||||
- Stats maintenance: keep skill stat migration fields synchronized by treating top-level stat fields as canonical during backfill/reconcile fallback reads (#1704) (thanks @momothemage).
|
||||
- Skill install: render OpenClaw CLI commands with the bare slug that the current CLI accepts (#1807).
|
||||
- Skills: keep historical tags out of public skill detail surfaces while preserving manager visibility (#1804) (thanks @deepujain).
|
||||
- Skills moderation: keep hash-based scanner callbacks from overwriting skill-level moderation for older versions (#1805) (thanks @deepujain).
|
||||
- Skills: prevent backport publishes from clobbering `latest` state and guard malformed persisted latest semver values during publish comparisons (#1832) (thanks @momothemage).
|
||||
|
||||
## 0.10.0 - 2026-04-05
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge" alt="MIT License"></a>
|
||||
</p>
|
||||
|
||||
ClawHub is the **public skill registry for OpenClaw**: publish, version, and search text-based agent skills (a `SKILL.md` plus supporting files).
|
||||
ClawHub is the **public skill registry for Clawdbot**: publish, version, and search text-based agent skills (a `SKILL.md` plus supporting files).
|
||||
It's designed for fast browsing + a CLI-friendly API, with moderation hooks and vector search.
|
||||
It also now exposes a native **OpenClaw package catalog** for code plugins and bundle plugins.
|
||||
|
||||
@@ -63,7 +63,6 @@ Common CLI flows:
|
||||
- Inspect without installing: `clawhub inspect <slug>`
|
||||
- Publish/sync skills: `clawhub skill publish <path>`, `clawhub sync`
|
||||
- Publish plugins: `clawhub package publish <source>`
|
||||
- Code-plugin manifests must include `openclaw.compat.pluginApi` and `openclaw.build.openclawVersion`; see [`docs/cli.md`](docs/cli.md) for a minimal example.
|
||||
- Canonicalize owned skills: `clawhub skill rename <slug> <new-slug>`, `clawhub skill merge <source> <target>`
|
||||
|
||||
Docs: [`docs/quickstart.md`](docs/quickstart.md), [`docs/cli.md`](docs/cli.md).
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 0,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "clawhub",
|
||||
@@ -13,15 +12,10 @@
|
||||
"@fontsource/ibm-plex-mono": "^5.2.7",
|
||||
"@fontsource/manrope": "^5.2.8",
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-hover-card": "^1.1.15",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-radio-group": "^1.3.8",
|
||||
"@radix-ui/react-scroll-area": "^1.2.10",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
@@ -31,7 +25,6 @@
|
||||
"@radix-ui/react-toggle-group": "^1.1.11",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@resvg/resvg-wasm": "^2.6.2",
|
||||
"@shikijs/rehype": "^4.0.2",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@tanstack/react-devtools": "0.10.0",
|
||||
"@tanstack/react-router": "1.168.1",
|
||||
@@ -43,7 +36,6 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clawhub-schema": "workspace:*",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"convex": "^1.34.1",
|
||||
"convex-helpers": "^0.1.114",
|
||||
"fflate": "^0.8.2",
|
||||
@@ -51,13 +43,12 @@
|
||||
"ignore": "^7.0.5",
|
||||
"lucide-react": "^0.577.0",
|
||||
"monaco-editor": "^0.55.1",
|
||||
"next": "^16.2.3",
|
||||
"next-themes": "^0.4.6",
|
||||
"nitro": "3.0.260311-beta",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"semver": "^7.7.4",
|
||||
"shiki": "^4.0.2",
|
||||
@@ -65,7 +56,6 @@
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"unist-util-visit": "^5.1.0",
|
||||
"vite-tsconfig-paths": "^6.1.1",
|
||||
"yaml": "^2.8.3",
|
||||
"zod": "^4.3.6",
|
||||
@@ -94,7 +84,7 @@
|
||||
},
|
||||
"packages/clawhub": {
|
||||
"name": "clawhub",
|
||||
"version": "0.11.0",
|
||||
"version": "0.10.0",
|
||||
"bin": {
|
||||
"clawdhub": "bin/clawdhub.js",
|
||||
"clawhub": "bin/clawdhub.js",
|
||||
@@ -479,19 +469,15 @@
|
||||
|
||||
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
|
||||
|
||||
"@radix-ui/react-alert-dialog": ["@radix-ui/react-alert-dialog@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dialog": "1.1.15", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw=="],
|
||||
|
||||
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="],
|
||||
|
||||
"@radix-ui/react-avatar": ["@radix-ui/react-avatar@1.1.11", "", { "dependencies": { "@radix-ui/react-context": "1.1.3", "@radix-ui/react-primitive": "2.1.4", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-is-hydrated": "0.1.0", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0Qk603AHGV28BOBO34p7IgD5m+V5Sg/YovfayABkoDDBM5d3NCx0Mp4gGrjzLGes1jV5eNOE1r3itqOR33VC6Q=="],
|
||||
|
||||
"@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.3.3", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw=="],
|
||||
|
||||
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="],
|
||||
|
||||
"@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
|
||||
|
||||
"@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
"@radix-ui/react-context": ["@radix-ui/react-context@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw=="],
|
||||
|
||||
"@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw=="],
|
||||
|
||||
@@ -505,25 +491,19 @@
|
||||
|
||||
"@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="],
|
||||
|
||||
"@radix-ui/react-hover-card": ["@radix-ui/react-hover-card@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg=="],
|
||||
|
||||
"@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="],
|
||||
|
||||
"@radix-ui/react-label": ["@radix-ui/react-label@2.1.8", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-FmXs37I6hSBVDlO4y764TNz1rLgKwjJMQ0EGte6F3Cb3f4bIuHB/iLa/8I9VKkmOy+gNHq8rql3j686ACVV21A=="],
|
||||
|
||||
"@radix-ui/react-menu": ["@radix-ui/react-menu@2.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg=="],
|
||||
|
||||
"@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-controllable-state": "1.2.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA=="],
|
||||
|
||||
"@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="],
|
||||
|
||||
"@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="],
|
||||
|
||||
"@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="],
|
||||
|
||||
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-radio-group": ["@radix-ui/react-radio-group@1.3.8", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.11", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ=="],
|
||||
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
|
||||
|
||||
"@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA=="],
|
||||
|
||||
@@ -611,8 +591,6 @@
|
||||
|
||||
"@shikijs/primitive": ["@shikijs/primitive@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-M6UMPrSa3fN5ayeJwFVl9qWofl273wtK1VG8ySDZ1mQBfhCpdd8nEx7nPZ/tk7k+TYcpqBZzj/AnwxT9lO+HJw=="],
|
||||
|
||||
"@shikijs/rehype": ["@shikijs/rehype@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2", "@types/hast": "^3.0.4", "hast-util-to-string": "^3.0.1", "shiki": "4.0.2", "unified": "^11.0.5", "unist-util-visit": "^5.1.0" } }, "sha512-cmPlKLD8JeojasNFoY64162ScpEdEdQUMuVodPCrv1nx1z3bjmGwoKWDruQWa/ejSznImlaeB0Ty6Q3zPaVQAA=="],
|
||||
|
||||
"@shikijs/themes": ["@shikijs/themes@4.0.2", "", { "dependencies": { "@shikijs/types": "4.0.2" } }, "sha512-mjCafwt8lJJaVSsQvNVrJumbnnj1RI8jbUKrPKgE6E3OvQKxnuRoBaYC51H4IGHePsGN/QtALglWBU7DoKDFnA=="],
|
||||
|
||||
"@shikijs/types": ["@shikijs/types@4.0.2", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="],
|
||||
@@ -857,8 +835,6 @@
|
||||
|
||||
"clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
|
||||
|
||||
"cmdk": ["cmdk@1.1.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="],
|
||||
|
||||
"comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
|
||||
|
||||
"commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],
|
||||
@@ -985,26 +961,12 @@
|
||||
|
||||
"has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
|
||||
|
||||
"hast-util-from-parse5": ["hast-util-from-parse5@8.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "hastscript": "^9.0.0", "property-information": "^7.0.0", "vfile": "^6.0.0", "vfile-location": "^5.0.0", "web-namespaces": "^2.0.0" } }, "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg=="],
|
||||
|
||||
"hast-util-parse-selector": ["hast-util-parse-selector@4.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A=="],
|
||||
|
||||
"hast-util-raw": ["hast-util-raw@9.1.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-from-parse5": "^8.0.0", "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "parse5": "^7.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw=="],
|
||||
|
||||
"hast-util-sanitize": ["hast-util-sanitize@5.0.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="],
|
||||
|
||||
"hast-util-to-html": ["hast-util-to-html@9.0.5", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.6", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-parse5": ["hast-util-to-parse5@8.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA=="],
|
||||
|
||||
"hast-util-to-string": ["hast-util-to-string@3.0.1", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A=="],
|
||||
|
||||
"hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
|
||||
|
||||
"hastscript": ["hastscript@9.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w=="],
|
||||
|
||||
"hookable": ["hookable@6.1.0", "", {}, "sha512-ZoKZSJgu8voGK2geJS+6YtYjvIzu9AOM/KZXsBxr83uhLL++e9pEv/dlgwgy3dvHg06kTz6JOh1hk3C8Ceiymw=="],
|
||||
|
||||
"html-encoding-sniffer": ["html-encoding-sniffer@6.0.0", "", { "dependencies": { "@exodus/bytes": "^1.6.0" } }, "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg=="],
|
||||
@@ -1321,10 +1283,6 @@
|
||||
|
||||
"regex-utilities": ["regex-utilities@2.3.0", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="],
|
||||
|
||||
"rehype-sanitize": ["rehype-sanitize@6.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="],
|
||||
|
||||
"remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
|
||||
"remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
|
||||
@@ -1483,8 +1441,6 @@
|
||||
|
||||
"vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
|
||||
|
||||
"vfile-location": ["vfile-location@5.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg=="],
|
||||
|
||||
"vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
|
||||
|
||||
"vite": ["vite@8.0.5", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", "postcss": "^8.5.8", "rolldown": "1.0.0-rc.12", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.1.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-nmu43Qvq9UopTRfMx2jOYW5l16pb3iDC1JH6yMuPkpVbzK0k+L7dfsEDH4jRgYFmsg0sTAqkojoZgzLMlwHsCQ=="],
|
||||
@@ -1497,8 +1453,6 @@
|
||||
|
||||
"w3c-xmlserializer": ["w3c-xmlserializer@5.0.0", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA=="],
|
||||
|
||||
"web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="],
|
||||
|
||||
"webidl-conversions": ["webidl-conversions@8.0.1", "", {}, "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ=="],
|
||||
|
||||
"webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],
|
||||
@@ -1537,30 +1491,76 @@
|
||||
|
||||
"@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
|
||||
|
||||
"@radix-ui/react-alert-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
"@radix-ui/react-arrow/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-avatar/@radix-ui/react-context": ["@radix-ui/react-context@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw=="],
|
||||
"@radix-ui/react-collection/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-avatar/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
|
||||
"@radix-ui/react-collection/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-dialog/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-dialog/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-label/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
|
||||
"@radix-ui/react-dismissable-layer/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-dropdown-menu/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-dropdown-menu/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-focus-scope/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-menu/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-menu/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-menu/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-popover/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
"@radix-ui/react-popper/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
"@radix-ui/react-popper/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-portal/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-roving-focus/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-roving-focus/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-scroll-area/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-scroll-area/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-select/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-select/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-select/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-separator/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
|
||||
"@radix-ui/react-switch/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-switch/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-tabs/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-tabs/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-toggle/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-toggle-group/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-toggle-group/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-tooltip/@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
|
||||
|
||||
"@radix-ui/react-tooltip/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@radix-ui/react-tooltip/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-visually-hidden/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.9.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA=="],
|
||||
|
||||
"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.9.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw=="],
|
||||
@@ -1593,12 +1593,8 @@
|
||||
|
||||
"cheerio/whatwg-mimetype": ["whatwg-mimetype@4.0.0", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="],
|
||||
|
||||
"cmdk/@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.4", "", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],
|
||||
|
||||
"dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
|
||||
|
||||
"hast-util-raw/parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="],
|
||||
|
||||
"htmlparser2/entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"next/postcss": ["postcss@8.4.31", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],
|
||||
@@ -1618,5 +1614,31 @@
|
||||
"rolldown/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.12", "", {}, "sha512-HHMwmarRKvoFsJorqYlFeFRzXZqCt2ETQlEDOb9aqssrnVBB1/+xgTGtuTrIk5vzLNX1MjMtTf7W9z3tsSbrxw=="],
|
||||
|
||||
"strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
|
||||
|
||||
"@radix-ui/react-arrow/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-dismissable-layer/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-dropdown-menu/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-focus-scope/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-popper/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-portal/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-roving-focus/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-scroll-area/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-switch/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-tabs/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-toggle-group/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
|
||||
"@radix-ui/react-visually-hidden/@radix-ui/react-primitive/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/styles.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"guidelinesHash": "62d72acb9afcc18f658d88dd772f34b5b1da5fa60ef0402e57a784d97c458e57",
|
||||
"agentsMdSectionHash": "bbf30bd25ceea0aefd279d62e1cb2b4c207fcb712b69adf26f3d02b296ffc7b2",
|
||||
"claudeMdHash": "bbf30bd25ceea0aefd279d62e1cb2b4c207fcb712b69adf26f3d02b296ffc7b2",
|
||||
"agentSkillsSha": "d0fa8085af313029add5740f67198aa42ca60c8d",
|
||||
"installedSkillNames": [
|
||||
"convex",
|
||||
"convex-create-component",
|
||||
"convex-migration-helper",
|
||||
"convex-performance-audit",
|
||||
"convex-quickstart",
|
||||
"convex-setup-auth"
|
||||
]
|
||||
}
|
||||
@@ -1,365 +0,0 @@
|
||||
# Convex guidelines
|
||||
|
||||
## Function guidelines
|
||||
|
||||
### Http endpoint syntax
|
||||
|
||||
- HTTP endpoints are defined in `convex/http.ts` and require an `httpAction` decorator. For example:
|
||||
|
||||
```typescript
|
||||
import { httpRouter } from "convex/server";
|
||||
import { httpAction } from "./_generated/server";
|
||||
const http = httpRouter();
|
||||
http.route({
|
||||
path: "/echo",
|
||||
method: "POST",
|
||||
handler: httpAction(async (ctx, req) => {
|
||||
const body = await req.bytes();
|
||||
return new Response(body, { status: 200 });
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
- HTTP endpoints are always registered at the exact path you specify in the `path` field. For example, if you specify `/api/someRoute`, the endpoint will be registered at `/api/someRoute`.
|
||||
|
||||
### Validators
|
||||
|
||||
- Below is an example of an array validator:
|
||||
|
||||
```typescript
|
||||
import { mutation } from "./_generated/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default mutation({
|
||||
args: {
|
||||
simpleArray: v.array(v.union(v.string(), v.number())),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
//...
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
- Below is an example of a schema with validators that codify a discriminated union type:
|
||||
|
||||
```typescript
|
||||
import { defineSchema, defineTable } from "convex/server";
|
||||
import { v } from "convex/values";
|
||||
|
||||
export default defineSchema({
|
||||
results: defineTable(
|
||||
v.union(
|
||||
v.object({
|
||||
kind: v.literal("error"),
|
||||
errorMessage: v.string(),
|
||||
}),
|
||||
v.object({
|
||||
kind: v.literal("success"),
|
||||
value: v.number(),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
```
|
||||
|
||||
- Here are the valid Convex types along with their respective validators:
|
||||
Convex Type | TS/JS type | Example Usage | Validator for argument validation and schemas | Notes |
|
||||
| ----------- | ------------| -----------------------| -----------------------------------------------| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| Id | string | `doc._id` | `v.id(tableName)` | |
|
||||
| Null | null | `null` | `v.null()` | JavaScript's `undefined` is not a valid Convex value. Functions the return `undefined` or do not return will return `null` when called from a client. Use `null` instead. |
|
||||
| Int64 | bigint | `3n` | `v.int64()` | Int64s only support BigInts between -2^63 and 2^63-1. Convex supports `bigint`s in most modern browsers. |
|
||||
| Float64 | number | `3.1` | `v.number()` | Convex supports all IEEE-754 double-precision floating point numbers (such as NaNs). Inf and NaN are JSON serialized as strings. |
|
||||
| Boolean | boolean | `true` | `v.boolean()` |
|
||||
| String | string | `"abc"` | `v.string()` | Strings are stored as UTF-8 and must be valid Unicode sequences. Strings must be smaller than the 1MB total size limit when encoded as UTF-8. |
|
||||
| Bytes | ArrayBuffer | `new ArrayBuffer(8)` | `v.bytes()` | Convex supports first class bytestrings, passed in as `ArrayBuffer`s. Bytestrings must be smaller than the 1MB total size limit for Convex types. |
|
||||
| Array | Array | `[1, 3.2, "abc"]` | `v.array(values)` | Arrays can have at most 8192 values. |
|
||||
| Object | Object | `{a: "abc"}` | `v.object({property: value})` | Convex only supports "plain old JavaScript objects" (objects that do not have a custom prototype). Objects can have at most 1024 entries. Field names must be nonempty and not start with "$" or "_". |
|
||||
| Record | Record | `{"a": "1", "b": "2"}` | `v.record(keys, values)` | Records are objects at runtime, but can have dynamic keys. Keys must be only ASCII characters, nonempty, and not start with "$" or "\_". |
|
||||
|
||||
### Function registration
|
||||
|
||||
- Use `internalQuery`, `internalMutation`, and `internalAction` to register internal functions. These functions are private and aren't part of an app's API. They can only be called by other Convex functions. These functions are always imported from `./_generated/server`.
|
||||
- Use `query`, `mutation`, and `action` to register public functions. These functions are part of the public API and are exposed to the public Internet. Do NOT use `query`, `mutation`, or `action` to register sensitive internal functions that should be kept private.
|
||||
- You CANNOT register a function through the `api` or `internal` objects.
|
||||
- ALWAYS include argument validators for all Convex functions. This includes all of `query`, `internalQuery`, `mutation`, `internalMutation`, `action`, and `internalAction`.
|
||||
|
||||
### Function calling
|
||||
|
||||
- Use `ctx.runQuery` to call a query from a query, mutation, or action.
|
||||
- Use `ctx.runMutation` to call a mutation from a mutation or action.
|
||||
- Use `ctx.runAction` to call an action from an action.
|
||||
- ONLY call an action from another action if you need to cross runtimes (e.g. from V8 to Node). Otherwise, pull out the shared code into a helper async function and call that directly instead.
|
||||
- Try to use as few calls from actions to queries and mutations as possible. Queries and mutations are transactions, so splitting logic up into multiple calls introduces the risk of race conditions.
|
||||
- All of these calls take in a `FunctionReference`. Do NOT try to pass the callee function directly into one of these calls.
|
||||
- When using `ctx.runQuery`, `ctx.runMutation`, or `ctx.runAction` to call a function in the same file, specify a type annotation on the return value to work around TypeScript circularity limitations. For example,
|
||||
|
||||
```
|
||||
export const f = query({
|
||||
args: { name: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
return "Hello " + args.name;
|
||||
},
|
||||
});
|
||||
|
||||
export const g = query({
|
||||
args: {},
|
||||
handler: async (ctx, args) => {
|
||||
const result: string = await ctx.runQuery(api.example.f, { name: "Bob" });
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Function references
|
||||
|
||||
- Use the `api` object defined by the framework in `convex/_generated/api.ts` to call public functions registered with `query`, `mutation`, or `action`.
|
||||
- Use the `internal` object defined by the framework in `convex/_generated/api.ts` to call internal (or private) functions registered with `internalQuery`, `internalMutation`, or `internalAction`.
|
||||
- Convex uses file-based routing, so a public function defined in `convex/example.ts` named `f` has a function reference of `api.example.f`.
|
||||
- A private function defined in `convex/example.ts` named `g` has a function reference of `internal.example.g`.
|
||||
- Functions can also registered within directories nested within the `convex/` folder. For example, a public function `h` defined in `convex/messages/access.ts` has a function reference of `api.messages.access.h`.
|
||||
|
||||
### Pagination
|
||||
|
||||
- Define pagination using the following syntax:
|
||||
|
||||
```ts
|
||||
import { v } from "convex/values";
|
||||
import { query, mutation } from "./_generated/server";
|
||||
import { paginationOptsValidator } from "convex/server";
|
||||
export const listWithExtraArg = query({
|
||||
args: { paginationOpts: paginationOptsValidator, author: v.string() },
|
||||
handler: async (ctx, args) => {
|
||||
return await ctx.db
|
||||
.query("messages")
|
||||
.withIndex("by_author", (q) => q.eq("author", args.author))
|
||||
.order("desc")
|
||||
.paginate(args.paginationOpts);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Note: `paginationOpts` is an object with the following properties:
|
||||
|
||||
- `numItems`: the maximum number of documents to return (the validator is `v.number()`)
|
||||
- `cursor`: the cursor to use to fetch the next page of documents (the validator is `v.union(v.string(), v.null())`)
|
||||
- A query that ends in `.paginate()` returns an object that has the following properties:
|
||||
- page (contains an array of documents that you fetches)
|
||||
- isDone (a boolean that represents whether or not this is the last page of documents)
|
||||
- continueCursor (a string that represents the cursor to use to fetch the next page of documents)
|
||||
|
||||
## Schema guidelines
|
||||
|
||||
- Always define your schema in `convex/schema.ts`.
|
||||
- Always import the schema definition functions from `convex/server`.
|
||||
- System fields are automatically added to all documents and are prefixed with an underscore. The two system fields that are automatically added to all documents are `_creationTime` which has the validator `v.number()` and `_id` which has the validator `v.id(tableName)`.
|
||||
- Always include all index fields in the index name. For example, if an index is defined as `["field1", "field2"]`, the index name should be "by_field1_and_field2".
|
||||
- Index fields must be queried in the same order they are defined. If you want to be able to query by "field1" then "field2" and by "field2" then "field1", you must create separate indexes.
|
||||
- Do not store unbounded lists as an array field inside a document (e.g. `v.array(v.object({...}))`). As the array grows it will hit the 1MB document size limit, and every update rewrites the entire document. Instead, create a separate table for the child items with a foreign key back to the parent.
|
||||
- Separate high-churn operational data (e.g. heartbeats, online status, typing indicators) from stable profile data. Storing frequently updated fields on a shared document forces every write to contend with reads of the entire document. Instead, create a dedicated table for the high-churn data with a foreign key back to the parent record.
|
||||
|
||||
## Authentication guidelines
|
||||
|
||||
- Convex supports JWT-based authentication through `convex/auth.config.ts`. ALWAYS create this file when using authentication. Without it, `ctx.auth.getUserIdentity()` will always return `null`.
|
||||
- Example `convex/auth.config.ts`:
|
||||
|
||||
```typescript
|
||||
export default {
|
||||
providers: [
|
||||
{
|
||||
domain: "https://your-auth-provider.com",
|
||||
applicationID: "convex",
|
||||
},
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
The `domain` must be the issuer URL of the JWT provider. Convex fetches `{domain}/.well-known/openid-configuration` to discover the JWKS endpoint. The `applicationID` is checked against the JWT `aud` (audience) claim.
|
||||
|
||||
- Use `ctx.auth.getUserIdentity()` to get the authenticated user's identity in any query, mutation, or action. This returns `null` if the user is not authenticated, or a `UserIdentity` object with fields like `subject`, `issuer`, `name`, `email`, etc. The `subject` field is the unique user identifier.
|
||||
- In Convex `UserIdentity`, `tokenIdentifier` is guaranteed and is the canonical stable identifier for the authenticated identity. For any auth-linked database lookup or ownership check, prefer `identity.tokenIdentifier` over `identity.subject`. Do NOT use `identity.subject` alone as a global identity key.
|
||||
- NEVER accept a `userId` or any user identifier as a function argument for authorization purposes. Always derive the user identity server-side via `ctx.auth.getUserIdentity()`.
|
||||
- When using an external auth provider with Convex on the client, use `ConvexProviderWithAuth` instead of `ConvexProvider`:
|
||||
|
||||
```tsx
|
||||
import { ConvexProviderWithAuth, ConvexReactClient } from "convex/react";
|
||||
|
||||
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);
|
||||
|
||||
function App({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<ConvexProviderWithAuth client={convex} useAuth={useYourAuthHook}>
|
||||
{children}
|
||||
</ConvexProviderWithAuth>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useAuth` prop must return `{ isLoading, isAuthenticated, fetchAccessToken }`. Do NOT use plain `ConvexProvider` when authentication is needed — it will not send tokens with requests.
|
||||
|
||||
## Typescript guidelines
|
||||
|
||||
- You can use the helper typescript type `Id` imported from './\_generated/dataModel' to get the type of the id for a given table. For example if there is a table called 'users' you can use `Id<'users'>` to get the type of the id for that table.
|
||||
- Use `Doc<"tableName">` from `./_generated/dataModel` to get the full document type for a table.
|
||||
- Use `QueryCtx`, `MutationCtx`, `ActionCtx` from `./_generated/server` for typing function contexts. NEVER use `any` for ctx parameters — always use the proper context type.
|
||||
- If you need to define a `Record` make sure that you correctly provide the type of the key and value in the type. For example a validator `v.record(v.id('users'), v.string())` would have the type `Record<Id<'users'>, string>`. Below is an example of using `Record` with an `Id` type in a query:
|
||||
|
||||
```ts
|
||||
import { query } from "./_generated/server";
|
||||
import { Doc, Id } from "./_generated/dataModel";
|
||||
|
||||
export const exampleQuery = query({
|
||||
args: { userIds: v.array(v.id("users")) },
|
||||
handler: async (ctx, args) => {
|
||||
const idToUsername: Record<Id<"users">, string> = {};
|
||||
for (const userId of args.userIds) {
|
||||
const user = await ctx.db.get("users", userId);
|
||||
if (user) {
|
||||
idToUsername[user._id] = user.username;
|
||||
}
|
||||
}
|
||||
|
||||
return idToUsername;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
- Be strict with types, particularly around id's of documents. For example, if a function takes in an id for a document in the 'users' table, take in `Id<'users'>` rather than `string`.
|
||||
|
||||
## Full text search guidelines
|
||||
|
||||
- A query for "10 messages in channel '#general' that best match the query 'hello hi' in their body" would look like:
|
||||
|
||||
const messages = await ctx.db
|
||||
.query("messages")
|
||||
.withSearchIndex("search_body", (q) =>
|
||||
q.search("body", "hello hi").eq("channel", "#general"),
|
||||
)
|
||||
.take(10);
|
||||
|
||||
## Query guidelines
|
||||
|
||||
- Do NOT use `filter` in queries. Instead, define an index in the schema and use `withIndex` instead.
|
||||
- If the user does not explicitly tell you to return all results from a query you should ALWAYS return a bounded collection instead. So that is instead of using `.collect()` you should use `.take()` or paginate on database queries. This prevents future performance issues when tables grow in an unbounded way.
|
||||
- Never use `.collect().length` to count rows. Convex has no built-in count operator, so if you need a count that stays efficient at scale, maintain a denormalized counter in a separate document and update it in your mutations.
|
||||
- Convex queries do NOT support `.delete()`. If you need to delete all documents matching a query, use `.take(n)` to read them in batches, iterate over each batch calling `ctx.db.delete(row._id)`, and repeat until no more results are returned.
|
||||
- Convex mutations are transactions with limits on the number of documents read and written. If a mutation needs to process more documents than fit in a single transaction (e.g. bulk deletion on a large table), process a batch with `.take(n)` and then call `ctx.scheduler.runAfter(0, api.myModule.myMutation, args)` to schedule itself to continue. This way each invocation stays within transaction limits.
|
||||
- Use `.unique()` to get a single document from a query. This method will throw an error if there are multiple documents that match the query.
|
||||
- When using async iteration, don't use `.collect()` or `.take(n)` on the result of a query. Instead, use the `for await (const row of query)` syntax.
|
||||
|
||||
### Ordering
|
||||
|
||||
- By default Convex always returns documents in ascending `_creationTime` order.
|
||||
- You can use `.order('asc')` or `.order('desc')` to pick whether a query is in ascending or descending order. If the order isn't specified, it defaults to ascending.
|
||||
- Document queries that use indexes will be ordered based on the columns in the index and can avoid slow table scans.
|
||||
|
||||
## Mutation guidelines
|
||||
|
||||
- Use `ctx.db.replace` to fully replace an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.replace('tasks', taskId, { name: 'Buy milk', completed: false })`
|
||||
- Use `ctx.db.patch` to shallow merge updates into an existing document. This method will throw an error if the document does not exist. Syntax: `await ctx.db.patch('tasks', taskId, { completed: true })`
|
||||
|
||||
## Action guidelines
|
||||
|
||||
- Always add `"use node";` to the top of files containing actions that use Node.js built-in modules.
|
||||
- Never add `"use node";` to a file that also exports queries or mutations. Only actions can run in the Node.js runtime; queries and mutations must stay in the default Convex runtime. If you need Node.js built-ins alongside queries or mutations, put the action in a separate file.
|
||||
- `fetch()` is available in the default Convex runtime. You do NOT need `"use node";` just to use `fetch()`.
|
||||
- Never use `ctx.db` inside of an action. Actions don't have access to the database.
|
||||
- Below is an example of the syntax for an action:
|
||||
|
||||
```ts
|
||||
import { action } from "./_generated/server";
|
||||
|
||||
export const exampleAction = action({
|
||||
args: {},
|
||||
handler: async (ctx, args) => {
|
||||
console.log("This action does not return anything");
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Scheduling guidelines
|
||||
|
||||
### Cron guidelines
|
||||
|
||||
- Only use the `crons.interval` or `crons.cron` methods to schedule cron jobs. Do NOT use the `crons.hourly`, `crons.daily`, or `crons.weekly` helpers.
|
||||
- Both cron methods take in a FunctionReference. Do NOT try to pass the function directly into one of these methods.
|
||||
- Define crons by declaring the top-level `crons` object, calling some methods on it, and then exporting it as default. For example,
|
||||
|
||||
```ts
|
||||
import { cronJobs } from "convex/server";
|
||||
import { internal } from "./_generated/api";
|
||||
import { internalAction } from "./_generated/server";
|
||||
|
||||
const empty = internalAction({
|
||||
args: {},
|
||||
handler: async (ctx, args) => {
|
||||
console.log("empty");
|
||||
},
|
||||
});
|
||||
|
||||
const crons = cronJobs();
|
||||
|
||||
// Run `internal.crons.empty` every two hours.
|
||||
crons.interval("delete inactive users", { hours: 2 }, internal.crons.empty, {});
|
||||
|
||||
export default crons;
|
||||
```
|
||||
|
||||
- You can register Convex functions within `crons.ts` just like any other file.
|
||||
- If a cron calls an internal function, always import the `internal` object from '\_generated/api', even if the internal function is registered in the same file.
|
||||
|
||||
## Testing guidelines
|
||||
|
||||
- Use `convex-test` with `vitest` and `@edge-runtime/vm` to test Convex functions. Always install the latest versions of these packages. Configure vitest with `environment: "edge-runtime"` in `vitest.config.ts`.
|
||||
|
||||
Test files go inside the `convex/` directory. You must pass a module map from `import.meta.glob` to `convexTest`:
|
||||
|
||||
```typescript
|
||||
/// <reference types="vite/client" />
|
||||
import { convexTest } from "convex-test";
|
||||
import { expect, test } from "vitest";
|
||||
import { api } from "./_generated/api";
|
||||
import schema from "./schema";
|
||||
|
||||
const modules = import.meta.glob("./**/*.ts");
|
||||
|
||||
test("some behavior", async () => {
|
||||
const t = convexTest(schema, modules);
|
||||
await t.mutation(api.messages.send, { body: "Hi!", author: "Sarah" });
|
||||
const messages = await t.query(api.messages.list);
|
||||
expect(messages).toMatchObject([{ body: "Hi!", author: "Sarah" }]);
|
||||
});
|
||||
```
|
||||
|
||||
The `modules` argument is required so convex-test can discover and load function files. The `/// <reference types="vite/client" />` directive is needed for TypeScript to recognize `import.meta.glob`.
|
||||
|
||||
## File storage guidelines
|
||||
|
||||
- The `ctx.storage.getUrl()` method returns a signed URL for a given file. It returns `null` if the file doesn't exist.
|
||||
- Do NOT use the deprecated `ctx.storage.getMetadata` call for loading a file's metadata.
|
||||
|
||||
Instead, query the `_storage` system table. For example, you can use `ctx.db.system.get` to get an `Id<"_storage">`.
|
||||
|
||||
```
|
||||
import { query } from "./_generated/server";
|
||||
import { Id } from "./_generated/dataModel";
|
||||
|
||||
type FileMetadata = {
|
||||
_id: Id<"_storage">;
|
||||
_creationTime: number;
|
||||
contentType?: string;
|
||||
sha256: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export const exampleQuery = query({
|
||||
args: { fileId: v.id("_storage") },
|
||||
handler: async (ctx, args) => {
|
||||
const metadata: FileMetadata | null = await ctx.db.system.get("_storage", args.fileId);
|
||||
console.log(metadata);
|
||||
return null;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
- Convex storage stores items as `Blob` objects. You must convert all items to/from a `Blob` when using Convex storage.
|
||||
@@ -91,20 +91,16 @@ import type * as lib_soulPublish from "../lib/soulPublish.js";
|
||||
import type * as lib_staticPublishScan from "../lib/staticPublishScan.js";
|
||||
import type * as lib_tokens from "../lib/tokens.js";
|
||||
import type * as lib_userSearch from "../lib/userSearch.js";
|
||||
import type * as lib_userSkillStats from "../lib/userSkillStats.js";
|
||||
import type * as lib_webhooks from "../lib/webhooks.js";
|
||||
import type * as llmEval from "../llmEval.js";
|
||||
import type * as maintenance from "../maintenance.js";
|
||||
import type * as model_packages_rescans from "../model/packages/rescans.js";
|
||||
import type * as model_rescans_policy from "../model/rescans/policy.js";
|
||||
import type * as model_skills_rescans from "../model/skills/rescans.js";
|
||||
import type * as packagePublishTokens from "../packagePublishTokens.js";
|
||||
import type * as packages from "../packages.js";
|
||||
import type * as publishers from "../publishers.js";
|
||||
import type * as rateLimits from "../rateLimits.js";
|
||||
import type * as rescanRequests from "../rescanRequests.js";
|
||||
import type * as search from "../search.js";
|
||||
import type * as seed from "../seed.js";
|
||||
import type * as seedDemo from "../seedDemo.js";
|
||||
import type * as seedSouls from "../seedSouls.js";
|
||||
import type * as skillStatEvents from "../skillStatEvents.js";
|
||||
import type * as skillTransfers from "../skillTransfers.js";
|
||||
@@ -212,20 +208,16 @@ declare const fullApi: ApiFromModules<{
|
||||
"lib/staticPublishScan": typeof lib_staticPublishScan;
|
||||
"lib/tokens": typeof lib_tokens;
|
||||
"lib/userSearch": typeof lib_userSearch;
|
||||
"lib/userSkillStats": typeof lib_userSkillStats;
|
||||
"lib/webhooks": typeof lib_webhooks;
|
||||
llmEval: typeof llmEval;
|
||||
maintenance: typeof maintenance;
|
||||
"model/packages/rescans": typeof model_packages_rescans;
|
||||
"model/rescans/policy": typeof model_rescans_policy;
|
||||
"model/skills/rescans": typeof model_skills_rescans;
|
||||
packagePublishTokens: typeof packagePublishTokens;
|
||||
packages: typeof packages;
|
||||
publishers: typeof publishers;
|
||||
rateLimits: typeof rateLimits;
|
||||
rescanRequests: typeof rescanRequests;
|
||||
search: typeof search;
|
||||
seed: typeof seed;
|
||||
seedDemo: typeof seedDemo;
|
||||
seedSouls: typeof seedSouls;
|
||||
skillStatEvents: typeof skillStatEvents;
|
||||
skillTransfers: typeof skillTransfers;
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { internal } from "./_generated/api";
|
||||
import { api, internal } from "./_generated/api";
|
||||
|
||||
// Asserts that the internal-only download counters remain internal-only.
|
||||
// Public exposure is prevented at runtime by `internalMutation`; this file
|
||||
// just pins the public references that *should* exist.
|
||||
void internal.downloads.recordDownloadInternal;
|
||||
void internal.soulDownloads.incrementInternal;
|
||||
|
||||
// @ts-expect-error download counters must not be publicly callable
|
||||
void api.downloads.increment;
|
||||
|
||||
// @ts-expect-error soul download counters must not be publicly callable
|
||||
void api.soulDownloads.increment;
|
||||
|
||||
@@ -229,7 +229,7 @@ export async function applyCommentScamResultInternalHandler(
|
||||
ok: true,
|
||||
shouldBan,
|
||||
banned: !banResult.alreadyBanned,
|
||||
alreadyBanned: banResult.alreadyBanned,
|
||||
alreadyBanned: Boolean(banResult.alreadyBanned),
|
||||
protectedRole: false,
|
||||
wouldBan: false,
|
||||
};
|
||||
|
||||
@@ -509,7 +509,7 @@ describe("comments mutations", () => {
|
||||
if (id === "skills:1") {
|
||||
return { _id: "skills:1", softDeletedAt: undefined, moderationStatus: "active" };
|
||||
}
|
||||
if (id.startsWith("comments:reported-")) return reportedComment;
|
||||
if (String(id).startsWith("comments:reported-")) return reportedComment;
|
||||
if (id === "skills:active") {
|
||||
return { _id: "skills:active", softDeletedAt: undefined, moderationStatus: "active" };
|
||||
}
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { seedRescanUxFixturesHandler } from "./devSeed";
|
||||
import { MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE } from "./model/rescans/policy";
|
||||
|
||||
function chainEq(constraints: Record<string, unknown>) {
|
||||
return {
|
||||
eq(field: string, value: unknown) {
|
||||
constraints[field] = value;
|
||||
return chainEq(constraints);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function matches(doc: Record<string, unknown>, constraints: Record<string, unknown>) {
|
||||
return Object.entries(constraints).every(([key, value]) => doc[key] === value);
|
||||
}
|
||||
|
||||
function createDb() {
|
||||
const tables: Record<string, Array<Record<string, unknown> & { _id: string }>> = {};
|
||||
const counters: Record<string, number> = {};
|
||||
|
||||
const list = (table: string) => {
|
||||
tables[table] ??= [];
|
||||
return tables[table];
|
||||
};
|
||||
|
||||
const db = {
|
||||
get: async (id: string) => {
|
||||
const table = id.split(":")[0] ?? "";
|
||||
return list(table).find((doc) => doc._id === id) ?? null;
|
||||
},
|
||||
insert: async (table: string, doc: Record<string, unknown>) => {
|
||||
counters[table] = (counters[table] ?? 0) + 1;
|
||||
const inserted = {
|
||||
_id: `${table}:${counters[table]}`,
|
||||
_creationTime: counters[table],
|
||||
...doc,
|
||||
};
|
||||
list(table).push(inserted);
|
||||
return inserted._id;
|
||||
},
|
||||
patch: async (id: string, patch: Record<string, unknown>) => {
|
||||
const table = id.split(":")[0] ?? "";
|
||||
const doc = list(table).find((candidate) => candidate._id === id);
|
||||
if (doc) Object.assign(doc, patch);
|
||||
},
|
||||
delete: async (id: string) => {
|
||||
const table = id.split(":")[0] ?? "";
|
||||
const rows = list(table);
|
||||
const index = rows.findIndex((doc) => doc._id === id);
|
||||
if (index !== -1) rows.splice(index, 1);
|
||||
},
|
||||
query: (table: string) => ({
|
||||
withIndex: (_name: string, build: (q: ReturnType<typeof chainEq>) => unknown) => {
|
||||
const constraints: Record<string, unknown> = {};
|
||||
build(chainEq(constraints));
|
||||
const matched = () =>
|
||||
list(table).filter((doc) => matches(doc as Record<string, unknown>, constraints));
|
||||
return {
|
||||
collect: async () => matched(),
|
||||
unique: async () => matched()[0] ?? null,
|
||||
order: () => ({
|
||||
collect: async () => matched(),
|
||||
}),
|
||||
};
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
return { db, tables };
|
||||
}
|
||||
|
||||
describe("devSeed rescan UX fixtures", () => {
|
||||
it("seeds flagged local owner inventory and deterministic rescan counts idempotently", async () => {
|
||||
const { db, tables } = createDb();
|
||||
const args = {
|
||||
flaggedSkillStorageId: "storage:skill",
|
||||
flaggedSkillMd: "# Flagged skill",
|
||||
flaggedPluginStorageId: "storage:plugin",
|
||||
flaggedPluginReadme: "# Flagged plugin",
|
||||
scannedPluginStorageId: "storage:scanned-plugin",
|
||||
scannedPluginReadme: "# Scanned plugin",
|
||||
};
|
||||
|
||||
await seedRescanUxFixturesHandler({ db } as never, args as never);
|
||||
await seedRescanUxFixturesHandler({ db } as never, args as never);
|
||||
await seedRescanUxFixturesHandler({ db } as never, { ...args, reset: true } as never);
|
||||
|
||||
expect(tables.users).toHaveLength(1);
|
||||
expect(tables.users?.[0]).toEqual(expect.objectContaining({ handle: "local" }));
|
||||
expect(tables.publishers).toHaveLength(1);
|
||||
expect(tables.skills).toHaveLength(1);
|
||||
expect(tables.skills?.[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
ownerUserId: tables.users?.[0]?._id,
|
||||
ownerPublisherId: tables.publishers?.[0]?._id,
|
||||
moderationStatus: "hidden",
|
||||
moderationVerdict: "malicious",
|
||||
}),
|
||||
);
|
||||
expect(tables.packages).toHaveLength(2);
|
||||
expect(tables.packages?.find((pkg) => pkg.name === "local-flagged-runtime-plugin")).toEqual(
|
||||
expect.objectContaining({
|
||||
ownerUserId: tables.users?.[0]?._id,
|
||||
ownerPublisherId: tables.publishers?.[0]?._id,
|
||||
scanStatus: "malicious",
|
||||
}),
|
||||
);
|
||||
expect(tables.packages?.find((pkg) => pkg.name === "local-scanned-runtime-plugin")).toEqual(
|
||||
expect.objectContaining({
|
||||
ownerUserId: tables.users?.[0]?._id,
|
||||
ownerPublisherId: tables.publishers?.[0]?._id,
|
||||
scanStatus: "suspicious",
|
||||
}),
|
||||
);
|
||||
|
||||
const scannedPackage = tables.packages?.find(
|
||||
(pkg) => pkg.name === "local-scanned-runtime-plugin",
|
||||
);
|
||||
const scannedRelease = tables.packageReleases?.find(
|
||||
(release) => release.packageId === scannedPackage?._id,
|
||||
);
|
||||
expect(scannedRelease).toEqual(
|
||||
expect.objectContaining({
|
||||
sha256hash: "seeded-scanned-plugin-hash",
|
||||
vtAnalysis: expect.objectContaining({ status: "clean" }),
|
||||
llmAnalysis: expect.objectContaining({ status: "suspicious" }),
|
||||
staticScan: expect.objectContaining({ status: "suspicious" }),
|
||||
}),
|
||||
);
|
||||
|
||||
const skillRequests =
|
||||
tables.rescanRequests?.filter((request) => request.targetKind === "skill") ?? [];
|
||||
const pluginRequests =
|
||||
tables.rescanRequests?.filter((request) => request.targetKind === "plugin") ?? [];
|
||||
expect(skillRequests).toHaveLength(1);
|
||||
expect(pluginRequests).toHaveLength(MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,9 @@
|
||||
import { v } from "convex/values";
|
||||
import { internal } from "./_generated/api";
|
||||
import type { Id } from "./_generated/dataModel";
|
||||
import type { ActionCtx, MutationCtx } from "./_generated/server";
|
||||
import { internalMutation as rawInternalMutation } from "./_generated/server";
|
||||
import type { ActionCtx } from "./_generated/server";
|
||||
import { internalAction, internalMutation } from "./functions";
|
||||
import { EMBEDDING_DIMENSIONS } from "./lib/embeddings";
|
||||
import { normalizePackageName } from "./lib/packageRegistry";
|
||||
import { ensurePersonalPublisherForUser } from "./lib/publishers";
|
||||
import { parseClawdisMetadata, parseFrontmatter } from "./lib/skills";
|
||||
import { generateToken, hashToken } from "./lib/tokens";
|
||||
import { MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE } from "./model/rescans/policy";
|
||||
|
||||
type SeedSkillSpec = {
|
||||
slug: string;
|
||||
@@ -31,37 +25,6 @@ type SeedActionResult = {
|
||||
|
||||
type SeedMutationResult = Record<string, unknown>;
|
||||
|
||||
const LOCAL_SEED_HANDLE = "local";
|
||||
const FLAGGED_SKILL_SLUG = "local-flagged-wallet-sync";
|
||||
const FLAGGED_PLUGIN_NAME = "local-flagged-runtime-plugin";
|
||||
const SCANNED_PLUGIN_NAME = "local-scanned-runtime-plugin";
|
||||
const FLAGGED_SKILL_MD = `---
|
||||
name: local-flagged-wallet-sync
|
||||
description: Local dev fixture for flagged dashboard and rescan UI.
|
||||
---
|
||||
|
||||
# Local Flagged Wallet Sync
|
||||
|
||||
This seeded skill is intentionally flagged so local development can exercise owner-only recovery
|
||||
flows, dashboard unavailable states, and rescan request limits.
|
||||
`;
|
||||
const FLAGGED_PLUGIN_README = `# Local Flagged Runtime Plugin
|
||||
|
||||
This seeded plugin is intentionally flagged so local development can exercise plugin owner
|
||||
inventory and cap-exhausted rescan UI.
|
||||
`;
|
||||
const SCANNED_PLUGIN_README = `# Local Scanned Runtime Plugin
|
||||
|
||||
This seeded plugin is public and intentionally has completed scan results so local development can
|
||||
preview plugin scanner detail pages without owner-only visibility.
|
||||
`;
|
||||
|
||||
type RoleHelpFixtureUser = {
|
||||
handle: string;
|
||||
displayName: string;
|
||||
role: "admin" | "user";
|
||||
};
|
||||
|
||||
const SEED_SKILLS: SeedSkillSpec[] = [
|
||||
{
|
||||
slug: "padel",
|
||||
@@ -382,26 +345,6 @@ async function seedNixSkillsHandler(
|
||||
results.push({ slug: spec.slug, ...result });
|
||||
}
|
||||
|
||||
const [flaggedSkillStorageId, flaggedPluginStorageId, scannedPluginStorageId] =
|
||||
await Promise.all([
|
||||
ctx.storage.store(new Blob([FLAGGED_SKILL_MD], { type: "text/markdown" })),
|
||||
ctx.storage.store(new Blob([FLAGGED_PLUGIN_README], { type: "text/markdown" })),
|
||||
ctx.storage.store(new Blob([SCANNED_PLUGIN_README], { type: "text/markdown" })),
|
||||
]);
|
||||
const fixtureResult: SeedMutationResult = await ctx.runMutation(
|
||||
internal.devSeed.seedRescanUxFixturesMutation,
|
||||
{
|
||||
reset: args.reset,
|
||||
flaggedSkillStorageId,
|
||||
flaggedSkillMd: FLAGGED_SKILL_MD,
|
||||
flaggedPluginStorageId,
|
||||
flaggedPluginReadme: FLAGGED_PLUGIN_README,
|
||||
scannedPluginStorageId,
|
||||
scannedPluginReadme: SCANNED_PLUGIN_README,
|
||||
},
|
||||
);
|
||||
results.push({ slug: FLAGGED_SKILL_SLUG, ...fixtureResult });
|
||||
|
||||
return { ok: true, results };
|
||||
}
|
||||
|
||||
@@ -445,724 +388,6 @@ export const seedPadelSkill: ReturnType<typeof internalAction> = internalAction(
|
||||
handler: seedPadelSkillHandler,
|
||||
});
|
||||
|
||||
async function ensureLocalSeedOwner(ctx: MutationCtx) {
|
||||
const now = Date.now();
|
||||
const existingUsers = await ctx.db
|
||||
.query("users")
|
||||
.withIndex("handle", (q) => q.eq("handle", LOCAL_SEED_HANDLE))
|
||||
.collect();
|
||||
|
||||
const userId =
|
||||
existingUsers[0]?._id ??
|
||||
(await ctx.db.insert("users", {
|
||||
handle: LOCAL_SEED_HANDLE,
|
||||
displayName: "Local Dev",
|
||||
role: "admin",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}));
|
||||
const user = await ctx.db.get(userId);
|
||||
if (!user) throw new Error("Local seed user was not created");
|
||||
const publisher = await ensurePersonalPublisherForUser(ctx, user);
|
||||
if (!publisher) throw new Error("Local seed publisher was not created");
|
||||
return { userId, publisherId: publisher._id };
|
||||
}
|
||||
|
||||
async function deleteRescanRequestsForSkillVersion(ctx: MutationCtx, versionId: unknown) {
|
||||
if (!versionId) return;
|
||||
const requests = await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_skill_version", (q) =>
|
||||
q.eq("targetKind", "skill").eq("skillVersionId", versionId as never),
|
||||
)
|
||||
.collect();
|
||||
for (const request of requests) await ctx.db.delete(request._id);
|
||||
}
|
||||
|
||||
async function deleteRescanRequestsForPackageRelease(ctx: MutationCtx, releaseId: unknown) {
|
||||
if (!releaseId) return;
|
||||
const requests = await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_package_release", (q) =>
|
||||
q.eq("targetKind", "plugin").eq("packageReleaseId", releaseId as never),
|
||||
)
|
||||
.collect();
|
||||
for (const request of requests) await ctx.db.delete(request._id);
|
||||
}
|
||||
|
||||
async function deleteSeedSkillFixture(ctx: MutationCtx) {
|
||||
const existing = await findSeedSkillFixture(ctx);
|
||||
if (!existing) return;
|
||||
|
||||
const versions = await ctx.db
|
||||
.query("skillVersions")
|
||||
.withIndex("by_skill", (q) => q.eq("skillId", existing._id))
|
||||
.collect();
|
||||
for (const version of versions) {
|
||||
await deleteRescanRequestsForSkillVersion(ctx, version._id);
|
||||
await ctx.db.delete(version._id);
|
||||
}
|
||||
const embeddings = await ctx.db
|
||||
.query("skillEmbeddings")
|
||||
.withIndex("by_skill", (q) => q.eq("skillId", existing._id))
|
||||
.collect();
|
||||
for (const embedding of embeddings) {
|
||||
const maps = await ctx.db
|
||||
.query("embeddingSkillMap")
|
||||
.withIndex("by_embedding", (q) => q.eq("embeddingId", embedding._id))
|
||||
.collect();
|
||||
for (const map of maps) await ctx.db.delete(map._id);
|
||||
await ctx.db.delete(embedding._id);
|
||||
}
|
||||
await ctx.db.delete(existing._id);
|
||||
}
|
||||
|
||||
async function findSeedSkillFixture(ctx: MutationCtx) {
|
||||
return await ctx.db
|
||||
.query("skills")
|
||||
.withIndex("by_slug", (q) => q.eq("slug", FLAGGED_SKILL_SLUG))
|
||||
.unique();
|
||||
}
|
||||
|
||||
async function deleteSeedPluginFixtureByName(ctx: MutationCtx, name: string) {
|
||||
const existing = await findSeedPluginFixtureByName(ctx, name);
|
||||
if (!existing) return;
|
||||
|
||||
const releases = await ctx.db
|
||||
.query("packageReleases")
|
||||
.withIndex("by_package", (q) => q.eq("packageId", existing._id))
|
||||
.collect();
|
||||
for (const release of releases) {
|
||||
await deleteRescanRequestsForPackageRelease(ctx, release._id);
|
||||
await ctx.db.delete(release._id);
|
||||
}
|
||||
await ctx.db.delete(existing._id);
|
||||
}
|
||||
|
||||
async function deleteSeedPluginFixture(ctx: MutationCtx) {
|
||||
await deleteSeedPluginFixtureByName(ctx, FLAGGED_PLUGIN_NAME);
|
||||
}
|
||||
|
||||
async function deleteScannedPluginFixture(ctx: MutationCtx) {
|
||||
await deleteSeedPluginFixtureByName(ctx, SCANNED_PLUGIN_NAME);
|
||||
}
|
||||
|
||||
async function findSeedPluginFixtureByName(ctx: MutationCtx, name: string) {
|
||||
return await ctx.db
|
||||
.query("packages")
|
||||
.withIndex("by_name", (q) => q.eq("normalizedName", normalizePackageName(name)))
|
||||
.unique();
|
||||
}
|
||||
|
||||
async function findSeedPluginFixture(ctx: MutationCtx) {
|
||||
return await findSeedPluginFixtureByName(ctx, FLAGGED_PLUGIN_NAME);
|
||||
}
|
||||
|
||||
async function findScannedPluginFixture(ctx: MutationCtx) {
|
||||
return await findSeedPluginFixtureByName(ctx, SCANNED_PLUGIN_NAME);
|
||||
}
|
||||
|
||||
function staticMaliciousScan(now: number) {
|
||||
return {
|
||||
status: "malicious" as const,
|
||||
reasonCodes: ["malicious.local_dev_fixture"],
|
||||
findings: [
|
||||
{
|
||||
code: "malicious.local_dev_fixture",
|
||||
severity: "critical" as const,
|
||||
file: "SKILL.md",
|
||||
line: 1,
|
||||
message: "Local dev fixture intentionally flagged for owner recovery testing.",
|
||||
evidence: "seeded fixture",
|
||||
},
|
||||
],
|
||||
summary: "Local dev fixture intentionally flagged as malicious.",
|
||||
engineVersion: "local-dev-fixture",
|
||||
checkedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
function staticSuspiciousScan(now: number) {
|
||||
return {
|
||||
status: "suspicious" as const,
|
||||
reasonCodes: ["suspicious.local_dev_fixture"],
|
||||
findings: [
|
||||
{
|
||||
code: "suspicious.local_dev_fixture",
|
||||
severity: "warn" as const,
|
||||
file: "README.md",
|
||||
line: 3,
|
||||
message: "Local dev fixture exercises scanner evidence UI for a public plugin.",
|
||||
evidence: "runtime plugin requests local tool execution",
|
||||
},
|
||||
],
|
||||
summary: "Local dev fixture completed static analysis with a suspicious finding.",
|
||||
engineVersion: "local-dev-fixture",
|
||||
checkedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
async function insertCompletedRescanRequests(
|
||||
ctx: MutationCtx,
|
||||
params:
|
||||
| {
|
||||
targetKind: "skill";
|
||||
skillId: unknown;
|
||||
skillVersionId: unknown;
|
||||
packageId?: never;
|
||||
packageReleaseId?: never;
|
||||
targetVersion: string;
|
||||
ownerUserId: unknown;
|
||||
ownerPublisherId: unknown;
|
||||
count: number;
|
||||
now: number;
|
||||
}
|
||||
| {
|
||||
targetKind: "plugin";
|
||||
packageId: unknown;
|
||||
packageReleaseId: unknown;
|
||||
skillId?: never;
|
||||
skillVersionId?: never;
|
||||
targetVersion: string;
|
||||
ownerUserId: unknown;
|
||||
ownerPublisherId: unknown;
|
||||
count: number;
|
||||
now: number;
|
||||
},
|
||||
) {
|
||||
for (let index = 0; index < params.count; index += 1) {
|
||||
const createdAt = params.now - (params.count - index) * 60_000;
|
||||
await ctx.db.insert("rescanRequests", {
|
||||
targetKind: params.targetKind,
|
||||
skillId: params.skillId as never,
|
||||
skillVersionId: params.skillVersionId as never,
|
||||
packageId: params.packageId as never,
|
||||
packageReleaseId: params.packageReleaseId as never,
|
||||
targetVersion: params.targetVersion,
|
||||
requestedByUserId: params.ownerUserId as never,
|
||||
ownerUserId: params.ownerUserId as never,
|
||||
ownerPublisherId: params.ownerPublisherId as never,
|
||||
status: "completed",
|
||||
createdAt,
|
||||
updatedAt: createdAt + 30_000,
|
||||
completedAt: createdAt + 30_000,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
type SeedRescanUxFixturesArgs = {
|
||||
reset?: boolean;
|
||||
flaggedSkillStorageId: Id<"_storage">;
|
||||
flaggedSkillMd: string;
|
||||
flaggedPluginStorageId: Id<"_storage">;
|
||||
flaggedPluginReadme: string;
|
||||
scannedPluginStorageId: Id<"_storage">;
|
||||
scannedPluginReadme: string;
|
||||
};
|
||||
|
||||
export async function seedRescanUxFixturesHandler(
|
||||
ctx: MutationCtx,
|
||||
args: SeedRescanUxFixturesArgs,
|
||||
) {
|
||||
const existingSkill = await findSeedSkillFixture(ctx);
|
||||
const existingPlugin = await findSeedPluginFixture(ctx);
|
||||
const existingScannedPlugin = await findScannedPluginFixture(ctx);
|
||||
if (existingSkill && existingPlugin && existingScannedPlugin && !args.reset) {
|
||||
return {
|
||||
ok: true,
|
||||
skipped: true,
|
||||
ownerUserId: existingSkill.ownerUserId,
|
||||
ownerPublisherId: existingSkill.ownerPublisherId ?? existingPlugin.ownerPublisherId,
|
||||
flaggedSkillId: existingSkill._id,
|
||||
flaggedSkillVersionId: existingSkill.latestVersionId,
|
||||
flaggedPluginId: existingPlugin._id,
|
||||
flaggedPluginReleaseId: existingPlugin.latestReleaseId,
|
||||
scannedPluginId: existingScannedPlugin._id,
|
||||
scannedPluginReleaseId: existingScannedPlugin.latestReleaseId,
|
||||
};
|
||||
}
|
||||
|
||||
await deleteSeedSkillFixture(ctx);
|
||||
await deleteSeedPluginFixture(ctx);
|
||||
await deleteScannedPluginFixture(ctx);
|
||||
|
||||
const now = Date.now();
|
||||
const { userId, publisherId } = await ensureLocalSeedOwner(ctx);
|
||||
const staticScan = staticMaliciousScan(now);
|
||||
const scannedStaticScan = staticSuspiciousScan(now);
|
||||
|
||||
const skillId = await ctx.db.insert("skills", {
|
||||
slug: FLAGGED_SKILL_SLUG,
|
||||
displayName: "Local Flagged Wallet Sync",
|
||||
summary: "Seeded flagged skill for local owner inventory and rescan UI testing.",
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
latestVersionId: undefined,
|
||||
tags: {},
|
||||
softDeletedAt: undefined,
|
||||
badges: { redactionApproved: undefined },
|
||||
moderationStatus: "hidden",
|
||||
moderationReason: "scanner.static.malicious",
|
||||
moderationVerdict: "malicious",
|
||||
moderationReasonCodes: ["malicious.local_dev_fixture"],
|
||||
moderationEvidence: staticScan.findings,
|
||||
moderationSummary: staticScan.summary,
|
||||
moderationEngineVersion: staticScan.engineVersion,
|
||||
moderationEvaluatedAt: now,
|
||||
moderationFlags: ["blocked.malware"],
|
||||
isSuspicious: true,
|
||||
statsDownloads: 4,
|
||||
statsStars: 1,
|
||||
statsInstallsCurrent: 0,
|
||||
statsInstallsAllTime: 2,
|
||||
stats: {
|
||||
downloads: 4,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 2,
|
||||
stars: 1,
|
||||
versions: 0,
|
||||
comments: 0,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
const skillVersionId = await ctx.db.insert("skillVersions", {
|
||||
skillId,
|
||||
version: "0.1.0",
|
||||
changelog: "Seeded flagged local version for rescan UI testing.",
|
||||
files: [
|
||||
{
|
||||
path: "SKILL.md",
|
||||
size: args.flaggedSkillMd.length,
|
||||
storageId: args.flaggedSkillStorageId,
|
||||
sha256: "seeded-flagged-skill",
|
||||
contentType: "text/markdown",
|
||||
},
|
||||
],
|
||||
parsed: {
|
||||
frontmatter: {
|
||||
name: FLAGGED_SKILL_SLUG,
|
||||
description: "Local dev fixture for flagged dashboard and rescan UI.",
|
||||
},
|
||||
},
|
||||
createdBy: userId,
|
||||
createdAt: now,
|
||||
softDeletedAt: undefined,
|
||||
sha256hash: "seeded-flagged-skill-hash",
|
||||
vtAnalysis: {
|
||||
status: "malicious",
|
||||
verdict: "malicious",
|
||||
analysis: "Local dev fixture intentionally flagged by VirusTotal.",
|
||||
source: "local-dev-seed",
|
||||
checkedAt: now,
|
||||
},
|
||||
llmAnalysis: {
|
||||
status: "suspicious",
|
||||
verdict: "suspicious",
|
||||
confidence: "high",
|
||||
summary: "Local dev fixture intentionally flagged by OpenClaw.",
|
||||
model: "local-dev-seed",
|
||||
checkedAt: now,
|
||||
},
|
||||
staticScan,
|
||||
});
|
||||
await ctx.db.patch(skillId, {
|
||||
latestVersionId: skillVersionId,
|
||||
moderationSourceVersionId: skillVersionId,
|
||||
tags: { latest: skillVersionId },
|
||||
stats: {
|
||||
downloads: 4,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 2,
|
||||
stars: 1,
|
||||
versions: 1,
|
||||
comments: 0,
|
||||
},
|
||||
updatedAt: now,
|
||||
});
|
||||
await insertCompletedRescanRequests(ctx, {
|
||||
targetKind: "skill",
|
||||
skillId,
|
||||
skillVersionId,
|
||||
targetVersion: "0.1.0",
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
count: 1,
|
||||
now,
|
||||
});
|
||||
|
||||
const packageId = await ctx.db.insert("packages", {
|
||||
name: FLAGGED_PLUGIN_NAME,
|
||||
normalizedName: normalizePackageName(FLAGGED_PLUGIN_NAME),
|
||||
displayName: "Local Flagged Runtime Plugin",
|
||||
summary: "Seeded flagged plugin for local owner inventory and cap-exhausted rescan UI testing.",
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
family: "code-plugin",
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
runtimeId: "local.flagged.runtime",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
latestReleaseId: undefined,
|
||||
latestVersionSummary: undefined,
|
||||
tags: {},
|
||||
capabilityTags: ["dev-tools"],
|
||||
executesCode: true,
|
||||
compatibility: { pluginApiRange: ">=0.1.0" },
|
||||
capabilities: {
|
||||
executesCode: true,
|
||||
runtimeId: "local.flagged.runtime",
|
||||
pluginKind: "runtime",
|
||||
capabilityTags: ["dev-tools"],
|
||||
},
|
||||
verification: {
|
||||
tier: "structural",
|
||||
scope: "artifact-only",
|
||||
summary: "Local dev fixture intentionally flagged.",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
scanStatus: "malicious",
|
||||
},
|
||||
scanStatus: "malicious",
|
||||
stats: { downloads: 2, installs: 0, stars: 0, versions: 0 },
|
||||
softDeletedAt: undefined,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
const packageReleaseId = await ctx.db.insert("packageReleases", {
|
||||
packageId,
|
||||
version: "0.1.0",
|
||||
changelog: "Seeded flagged local release for cap-exhausted rescan UI testing.",
|
||||
summary: "Seeded flagged plugin release.",
|
||||
distTags: ["latest"],
|
||||
files: [
|
||||
{
|
||||
path: "README.md",
|
||||
size: args.flaggedPluginReadme.length,
|
||||
storageId: args.flaggedPluginStorageId,
|
||||
sha256: "seeded-flagged-plugin",
|
||||
contentType: "text/markdown",
|
||||
},
|
||||
],
|
||||
integritySha256: "seeded-flagged-plugin-integrity",
|
||||
extractedPackageJson: {
|
||||
name: FLAGGED_PLUGIN_NAME,
|
||||
version: "0.1.0",
|
||||
},
|
||||
compatibility: { pluginApiRange: ">=0.1.0" },
|
||||
capabilities: {
|
||||
executesCode: true,
|
||||
runtimeId: "local.flagged.runtime",
|
||||
pluginKind: "runtime",
|
||||
capabilityTags: ["dev-tools"],
|
||||
},
|
||||
verification: {
|
||||
tier: "structural",
|
||||
scope: "artifact-only",
|
||||
summary: "Local dev fixture intentionally flagged.",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
scanStatus: "malicious",
|
||||
},
|
||||
sha256hash: "seeded-flagged-plugin-hash",
|
||||
vtAnalysis: {
|
||||
status: "malicious",
|
||||
verdict: "malicious",
|
||||
analysis: "Local dev fixture intentionally flagged by VirusTotal.",
|
||||
source: "local-dev-seed",
|
||||
checkedAt: now,
|
||||
},
|
||||
llmAnalysis: {
|
||||
status: "suspicious",
|
||||
verdict: "suspicious",
|
||||
confidence: "high",
|
||||
summary: "Local dev fixture intentionally flagged by OpenClaw.",
|
||||
model: "local-dev-seed",
|
||||
checkedAt: now,
|
||||
},
|
||||
staticScan,
|
||||
source: { kind: "github", repo: "openclaw/local-dev-fixture", path: "." },
|
||||
createdBy: userId,
|
||||
publishActor: { kind: "user", userId },
|
||||
createdAt: now,
|
||||
softDeletedAt: undefined,
|
||||
});
|
||||
await ctx.db.patch(packageId, {
|
||||
latestReleaseId: packageReleaseId,
|
||||
latestVersionSummary: {
|
||||
version: "0.1.0",
|
||||
createdAt: now,
|
||||
changelog: "Seeded flagged local release for cap-exhausted rescan UI testing.",
|
||||
compatibility: { pluginApiRange: ">=0.1.0" },
|
||||
capabilities: {
|
||||
executesCode: true,
|
||||
runtimeId: "local.flagged.runtime",
|
||||
pluginKind: "runtime",
|
||||
capabilityTags: ["dev-tools"],
|
||||
},
|
||||
verification: {
|
||||
tier: "structural",
|
||||
scope: "artifact-only",
|
||||
summary: "Local dev fixture intentionally flagged.",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
scanStatus: "malicious",
|
||||
},
|
||||
},
|
||||
tags: { latest: packageReleaseId },
|
||||
stats: { downloads: 2, installs: 0, stars: 0, versions: 1 },
|
||||
updatedAt: now,
|
||||
});
|
||||
await insertCompletedRescanRequests(ctx, {
|
||||
targetKind: "plugin",
|
||||
packageId,
|
||||
packageReleaseId,
|
||||
targetVersion: "0.1.0",
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
count: MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE,
|
||||
now,
|
||||
});
|
||||
|
||||
const scannedPackageId = await ctx.db.insert("packages", {
|
||||
name: SCANNED_PLUGIN_NAME,
|
||||
normalizedName: normalizePackageName(SCANNED_PLUGIN_NAME),
|
||||
displayName: "Local Scanned Runtime Plugin",
|
||||
summary: "Seeded public plugin with completed security scans for scanner page previews.",
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
family: "code-plugin",
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
runtimeId: "local.scanned.runtime",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
latestReleaseId: undefined,
|
||||
latestVersionSummary: undefined,
|
||||
tags: {},
|
||||
capabilityTags: ["dev-tools", "security"],
|
||||
executesCode: true,
|
||||
compatibility: { pluginApiRange: ">=0.1.0" },
|
||||
capabilities: {
|
||||
executesCode: true,
|
||||
runtimeId: "local.scanned.runtime",
|
||||
pluginKind: "runtime",
|
||||
capabilityTags: ["dev-tools", "security"],
|
||||
},
|
||||
verification: {
|
||||
tier: "structural",
|
||||
scope: "artifact-only",
|
||||
summary: "Local dev fixture completed security scans with reviewable findings.",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
scanStatus: "suspicious",
|
||||
},
|
||||
scanStatus: "suspicious",
|
||||
stats: { downloads: 7, installs: 1, stars: 1, versions: 0 },
|
||||
softDeletedAt: undefined,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
const scannedPackageReleaseId = await ctx.db.insert("packageReleases", {
|
||||
packageId: scannedPackageId,
|
||||
version: "0.1.0",
|
||||
changelog: "Seeded public scanned release for plugin scanner page previews.",
|
||||
summary: "Seeded scanned plugin release.",
|
||||
distTags: ["latest"],
|
||||
files: [
|
||||
{
|
||||
path: "README.md",
|
||||
size: args.scannedPluginReadme.length,
|
||||
storageId: args.scannedPluginStorageId,
|
||||
sha256: "seeded-scanned-plugin",
|
||||
contentType: "text/markdown",
|
||||
},
|
||||
],
|
||||
integritySha256: "seeded-scanned-plugin-integrity",
|
||||
extractedPackageJson: {
|
||||
name: SCANNED_PLUGIN_NAME,
|
||||
version: "0.1.0",
|
||||
},
|
||||
compatibility: { pluginApiRange: ">=0.1.0" },
|
||||
capabilities: {
|
||||
executesCode: true,
|
||||
runtimeId: "local.scanned.runtime",
|
||||
pluginKind: "runtime",
|
||||
capabilityTags: ["dev-tools", "security"],
|
||||
},
|
||||
verification: {
|
||||
tier: "structural",
|
||||
scope: "artifact-only",
|
||||
summary: "Local dev fixture completed security scans with reviewable findings.",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
scanStatus: "suspicious",
|
||||
},
|
||||
sha256hash: "seeded-scanned-plugin-hash",
|
||||
vtAnalysis: {
|
||||
status: "clean",
|
||||
verdict: "clean",
|
||||
analysis: "Local dev fixture scanned clean by VirusTotal.",
|
||||
source: "local-dev-seed",
|
||||
checkedAt: now,
|
||||
},
|
||||
llmAnalysis: {
|
||||
status: "suspicious",
|
||||
verdict: "suspicious",
|
||||
confidence: "medium",
|
||||
summary: "Local dev fixture flagged for review because it executes local tools.",
|
||||
dimensions: [
|
||||
{
|
||||
name: "execution",
|
||||
label: "Local execution",
|
||||
rating: "concern",
|
||||
detail: "Runtime plugin executes local tooling and should be reviewed before install.",
|
||||
},
|
||||
],
|
||||
guidance: "Review the runtime command surface before trusting this plugin.",
|
||||
findings: "The fixture is intentionally safe, but models a plugin with reviewable behavior.",
|
||||
model: "local-dev-seed",
|
||||
checkedAt: now,
|
||||
},
|
||||
staticScan: scannedStaticScan,
|
||||
source: { kind: "github", repo: "openclaw/local-dev-fixture", path: "." },
|
||||
createdBy: userId,
|
||||
publishActor: { kind: "user", userId },
|
||||
createdAt: now,
|
||||
softDeletedAt: undefined,
|
||||
});
|
||||
await ctx.db.patch(scannedPackageId, {
|
||||
latestReleaseId: scannedPackageReleaseId,
|
||||
latestVersionSummary: {
|
||||
version: "0.1.0",
|
||||
createdAt: now,
|
||||
changelog: "Seeded public scanned release for plugin scanner page previews.",
|
||||
compatibility: { pluginApiRange: ">=0.1.0" },
|
||||
capabilities: {
|
||||
executesCode: true,
|
||||
runtimeId: "local.scanned.runtime",
|
||||
pluginKind: "runtime",
|
||||
capabilityTags: ["dev-tools", "security"],
|
||||
},
|
||||
verification: {
|
||||
tier: "structural",
|
||||
scope: "artifact-only",
|
||||
summary: "Local dev fixture completed security scans with reviewable findings.",
|
||||
sourceRepo: "openclaw/local-dev-fixture",
|
||||
scanStatus: "suspicious",
|
||||
},
|
||||
},
|
||||
tags: { latest: scannedPackageReleaseId },
|
||||
stats: { downloads: 7, installs: 1, stars: 1, versions: 1 },
|
||||
updatedAt: now,
|
||||
});
|
||||
await ctx.db.patch(userId, {
|
||||
publishedSkills: 5,
|
||||
totalStars: 1,
|
||||
totalDownloads: 4,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
flaggedSkillId: skillId,
|
||||
flaggedSkillVersionId: skillVersionId,
|
||||
flaggedPluginId: packageId,
|
||||
flaggedPluginReleaseId: packageReleaseId,
|
||||
scannedPluginId: scannedPackageId,
|
||||
scannedPluginReleaseId: scannedPackageReleaseId,
|
||||
};
|
||||
}
|
||||
|
||||
export const seedRescanUxFixturesMutation = internalMutation({
|
||||
args: {
|
||||
reset: v.optional(v.boolean()),
|
||||
flaggedSkillStorageId: v.id("_storage"),
|
||||
flaggedSkillMd: v.string(),
|
||||
flaggedPluginStorageId: v.id("_storage"),
|
||||
flaggedPluginReadme: v.string(),
|
||||
scannedPluginStorageId: v.id("_storage"),
|
||||
scannedPluginReadme: v.string(),
|
||||
},
|
||||
handler: seedRescanUxFixturesHandler,
|
||||
});
|
||||
|
||||
export const seedCliRoleHelpFixtures = rawInternalMutation({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const now = Date.now();
|
||||
const admin = await upsertRoleHelpFixtureUser(ctx, {
|
||||
handle: "cli-admin",
|
||||
displayName: "CLI Admin",
|
||||
role: "admin",
|
||||
});
|
||||
const user = await upsertRoleHelpFixtureUser(ctx, {
|
||||
handle: "cli-user",
|
||||
displayName: "CLI User",
|
||||
role: "user",
|
||||
});
|
||||
|
||||
const adminToken = await replaceRoleHelpFixtureToken(ctx, admin._id, now);
|
||||
const userToken = await replaceRoleHelpFixtureToken(ctx, user._id, now);
|
||||
return {
|
||||
ok: true,
|
||||
admin: { handle: admin.handle, role: admin.role, token: adminToken },
|
||||
user: { handle: user.handle, role: user.role, token: userToken },
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
async function upsertRoleHelpFixtureUser(ctx: MutationCtx, user: RoleHelpFixtureUser) {
|
||||
const now = Date.now();
|
||||
const existing = await ctx.db
|
||||
.query("users")
|
||||
.withIndex("handle", (q) => q.eq("handle", user.handle))
|
||||
.unique();
|
||||
const patch = {
|
||||
handle: user.handle,
|
||||
displayName: user.displayName,
|
||||
role: user.role,
|
||||
deletedAt: undefined,
|
||||
deactivatedAt: undefined,
|
||||
updatedAt: now,
|
||||
};
|
||||
if (existing) {
|
||||
await ctx.db.patch(existing._id, patch);
|
||||
return { ...existing, ...patch };
|
||||
}
|
||||
const userId = await ctx.db.insert("users", {
|
||||
...patch,
|
||||
createdAt: now,
|
||||
});
|
||||
const created = await ctx.db.get(userId);
|
||||
if (!created) throw new Error(`Failed to create ${user.handle}`);
|
||||
return created;
|
||||
}
|
||||
|
||||
async function replaceRoleHelpFixtureToken(
|
||||
ctx: MutationCtx,
|
||||
userId: Id<"users">,
|
||||
now: number,
|
||||
) {
|
||||
const existingTokens = await ctx.db
|
||||
.query("apiTokens")
|
||||
.withIndex("by_user", (q) => q.eq("userId", userId))
|
||||
.collect();
|
||||
for (const token of existingTokens) {
|
||||
if (token.label === "CLI role help e2e") {
|
||||
await ctx.db.patch(token._id, { revokedAt: now });
|
||||
}
|
||||
}
|
||||
|
||||
const { token, prefix } = generateToken();
|
||||
await ctx.db.insert("apiTokens", {
|
||||
userId,
|
||||
label: "CLI role help e2e",
|
||||
prefix,
|
||||
tokenHash: await hashToken(token),
|
||||
createdAt: now,
|
||||
lastUsedAt: undefined,
|
||||
revokedAt: undefined,
|
||||
});
|
||||
return token;
|
||||
}
|
||||
|
||||
export const seedSkillMutation = internalMutation({
|
||||
args: {
|
||||
reset: v.optional(v.boolean()),
|
||||
@@ -1205,14 +430,26 @@ export const seedSkillMutation = internalMutation({
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const { userId, publisherId } = await ensureLocalSeedOwner(ctx);
|
||||
const existingUsers = await ctx.db
|
||||
.query("users")
|
||||
.withIndex("handle", (q) => q.eq("handle", "local"))
|
||||
.collect();
|
||||
|
||||
const userId =
|
||||
existingUsers[0]?._id ??
|
||||
(await ctx.db.insert("users", {
|
||||
handle: "local",
|
||||
displayName: "Local Dev",
|
||||
role: "admin",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}));
|
||||
|
||||
const skillId = await ctx.db.insert("skills", {
|
||||
slug: args.slug,
|
||||
displayName: args.displayName,
|
||||
summary: args.summary,
|
||||
ownerUserId: userId,
|
||||
ownerPublisherId: publisherId,
|
||||
latestVersionId: undefined,
|
||||
tags: {},
|
||||
softDeletedAt: undefined,
|
||||
@@ -1232,6 +469,12 @@ export const seedSkillMutation = internalMutation({
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await ctx.db.patch(userId, {
|
||||
publishedSkills: 1,
|
||||
totalStars: 0,
|
||||
totalDownloads: 0,
|
||||
});
|
||||
|
||||
const versionId = await ctx.db.insert("skillVersions", {
|
||||
skillId,
|
||||
version: args.version,
|
||||
|
||||
@@ -55,26 +55,6 @@ function findRateLimitCallArgs(mock: ReturnType<typeof vi.fn>) {
|
||||
return mock.mock.calls.map(([, args]) => args).find(isRateLimitArgs);
|
||||
}
|
||||
|
||||
function makeCatalogItem(
|
||||
name: string,
|
||||
options: {
|
||||
family: "code-plugin" | "bundle-plugin" | "skill";
|
||||
updatedAt: number;
|
||||
score?: number;
|
||||
},
|
||||
) {
|
||||
return {
|
||||
name,
|
||||
displayName: name,
|
||||
family: options.family,
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
createdAt: options.updatedAt,
|
||||
updatedAt: options.updatedAt,
|
||||
...(typeof options.score === "number" ? { score: options.score } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeCtx(partial: Record<string, unknown>) {
|
||||
const partialRunQuery =
|
||||
typeof partial.runQuery === "function"
|
||||
@@ -430,9 +410,9 @@ describe("httpApiV1 handlers", () => {
|
||||
|
||||
it("lists skills with resolved tags using batch query", async () => {
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ("cursor" in args || "numItems" in args) {
|
||||
if ("cursor" in args || "limit" in args) {
|
||||
return {
|
||||
page: [
|
||||
items: [
|
||||
{
|
||||
skill: {
|
||||
_id: "skills:1",
|
||||
@@ -468,9 +448,9 @@ describe("httpApiV1 handlers", () => {
|
||||
|
||||
it("batches tag resolution across multiple skills into single query", async () => {
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ("cursor" in args || "numItems" in args) {
|
||||
if ("cursor" in args || "limit" in args) {
|
||||
return {
|
||||
page: [
|
||||
items: [
|
||||
{
|
||||
skill: {
|
||||
_id: "skills:1",
|
||||
@@ -723,25 +703,18 @@ describe("httpApiV1 handlers", () => {
|
||||
});
|
||||
|
||||
it("lists skills supports sort aliases", async () => {
|
||||
const checks: Array<[string, string | null]> = [
|
||||
const checks: Array<[string, string]> = [
|
||||
["rating", "stars"],
|
||||
["installs", "installs"],
|
||||
["installs-all-time", "installs"],
|
||||
["unknown", "updated"],
|
||||
["trending", null],
|
||||
["installs", "installsCurrent"],
|
||||
["installs-all-time", "installsAllTime"],
|
||||
["trending", "trending"],
|
||||
];
|
||||
|
||||
for (const [input, expected] of checks) {
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ("sort" in args || "cursor" in args || "numItems" in args || "limit" in args) {
|
||||
if (expected === null) {
|
||||
expect(args).not.toHaveProperty("sort");
|
||||
} else {
|
||||
expect(args.sort).toBe(expected);
|
||||
}
|
||||
return expected === null
|
||||
? { items: [], nextCursor: null }
|
||||
: { page: [], nextCursor: null };
|
||||
if ("sort" in args || "cursor" in args || "limit" in args) {
|
||||
expect(args.sort).toBe(expected);
|
||||
return { items: [], nextCursor: null };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
@@ -756,9 +729,9 @@ describe("httpApiV1 handlers", () => {
|
||||
|
||||
it("lists skills forwards nonSuspiciousOnly", async () => {
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ("sort" in args || "cursor" in args || "numItems" in args) {
|
||||
if ("sort" in args || "cursor" in args || "limit" in args) {
|
||||
expect(args.nonSuspiciousOnly).toBe(true);
|
||||
return { page: [], nextCursor: null };
|
||||
return { items: [], nextCursor: null };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
@@ -772,9 +745,9 @@ describe("httpApiV1 handlers", () => {
|
||||
|
||||
it("lists skills forwards legacy nonSuspicious alias", async () => {
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ("sort" in args || "cursor" in args || "numItems" in args) {
|
||||
if ("sort" in args || "cursor" in args || "limit" in args) {
|
||||
expect(args.nonSuspiciousOnly).toBe(true);
|
||||
return { page: [], nextCursor: null };
|
||||
return { items: [], nextCursor: null };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
@@ -788,9 +761,9 @@ describe("httpApiV1 handlers", () => {
|
||||
|
||||
it("lists skills prefers canonical nonSuspiciousOnly over legacy alias", async () => {
|
||||
const runQuery = vi.fn(async (_query: unknown, args: Record<string, unknown>) => {
|
||||
if ("sort" in args || "cursor" in args || "numItems" in args) {
|
||||
if ("sort" in args || "cursor" in args || "limit" in args) {
|
||||
expect(args.nonSuspiciousOnly).toBeUndefined();
|
||||
return { page: [], nextCursor: null };
|
||||
return { items: [], nextCursor: null };
|
||||
}
|
||||
return null;
|
||||
});
|
||||
@@ -2134,7 +2107,6 @@ describe("httpApiV1 handlers", () => {
|
||||
expect(response.status).toBe(200);
|
||||
const json = await response.json();
|
||||
expect(json.user.handle).toBe("p");
|
||||
expect(json.user.role).toBeNull();
|
||||
});
|
||||
|
||||
it("delete and undelete require auth", async () => {
|
||||
@@ -2183,86 +2155,6 @@ describe("httpApiV1 handlers", () => {
|
||||
expect(response2.status).toBe(200);
|
||||
});
|
||||
|
||||
it("skill rescan routes authenticated owners to the rescan mutation", async () => {
|
||||
vi.mocked(requireApiTokenUser).mockResolvedValue({
|
||||
userId: "users:1",
|
||||
user: { handle: "p" },
|
||||
} as never);
|
||||
const runMutation = vi.fn(async (_mutation: unknown, args: Record<string, unknown>) => {
|
||||
if ("key" in args) return okRate();
|
||||
return {
|
||||
ok: true,
|
||||
targetKind: "skill",
|
||||
name: args.slug,
|
||||
version: "1.2.3",
|
||||
status: "in_progress",
|
||||
remainingRequests: 2,
|
||||
maxRequests: 3,
|
||||
pendingRequestId: "rescanRequests:1",
|
||||
};
|
||||
});
|
||||
|
||||
const response = await __handlers.skillsPostRouterV1Handler(
|
||||
makeCtx({ runMutation }),
|
||||
new Request("https://example.com/api/v1/skills/demo/rescan", {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer clh_test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toMatchObject({
|
||||
ok: true,
|
||||
targetKind: "skill",
|
||||
name: "demo",
|
||||
remainingRequests: 2,
|
||||
maxRequests: 3,
|
||||
});
|
||||
expect(runMutation).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ actorUserId: "users:1", slug: "demo" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("package rescan routes authenticated owners to the rescan mutation", async () => {
|
||||
vi.mocked(requireApiTokenUser).mockResolvedValue({
|
||||
userId: "users:1",
|
||||
user: { handle: "p" },
|
||||
} as never);
|
||||
const runMutation = vi.fn(async (_mutation: unknown, args: Record<string, unknown>) => {
|
||||
if ("key" in args) return okRate();
|
||||
return {
|
||||
ok: true,
|
||||
targetKind: "package",
|
||||
name: args.name,
|
||||
version: "1.2.3",
|
||||
status: "in_progress",
|
||||
remainingRequests: 2,
|
||||
maxRequests: 3,
|
||||
pendingRequestId: "rescanRequests:1",
|
||||
};
|
||||
});
|
||||
|
||||
const response = await __handlers.packagesPostRouterV1Handler(
|
||||
makeCtx({ runMutation }),
|
||||
new Request("https://example.com/api/v1/packages/%40scope%2Fdemo/rescan", {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer clh_test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toMatchObject({
|
||||
ok: true,
|
||||
targetKind: "package",
|
||||
name: "@scope/demo",
|
||||
});
|
||||
expect(runMutation).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ actorUserId: "users:1", name: "@scope/demo" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("transfer request requires auth", async () => {
|
||||
vi.mocked(requireApiTokenUser).mockRejectedValueOnce(new Error("Unauthorized"));
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
@@ -2600,11 +2492,7 @@ describe("httpApiV1 handlers", () => {
|
||||
});
|
||||
|
||||
it("packages search forwards executesCode and capabilityTag", async () => {
|
||||
const runQuery = vi.fn((_, args: Record<string, unknown>) => {
|
||||
if ("paginationOpts" in args) return { page: [], isDone: true, continueCursor: "" };
|
||||
if ("query" in args) return [];
|
||||
return null;
|
||||
});
|
||||
const runQuery = vi.fn().mockResolvedValue([]);
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
const response = await __handlers.packagesGetRouterV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
@@ -2616,9 +2504,10 @@ describe("httpApiV1 handlers", () => {
|
||||
expect(runQuery).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
query: "test",
|
||||
limit: 5,
|
||||
executesCode: true,
|
||||
capabilityTag: "tools",
|
||||
paginationOpts: { cursor: null, numItems: 50 },
|
||||
}),
|
||||
);
|
||||
expect(findRateLimitCallArgs(runMutation)).toMatchObject({
|
||||
@@ -2646,123 +2535,6 @@ describe("httpApiV1 handlers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("plugins list defaults to plugin package families", async () => {
|
||||
const codePlugin = {
|
||||
name: "code-plugin",
|
||||
displayName: "Code Plugin",
|
||||
family: "code-plugin",
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
createdAt: 20,
|
||||
updatedAt: 200,
|
||||
};
|
||||
const bundlePlugin = {
|
||||
name: "bundle-plugin",
|
||||
displayName: "Bundle Plugin",
|
||||
family: "bundle-plugin",
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
createdAt: 10,
|
||||
updatedAt: 100,
|
||||
};
|
||||
const runQuery = vi.fn((_, args: Record<string, unknown>) => {
|
||||
if (args.family === "code-plugin") {
|
||||
return { page: [codePlugin], isDone: true, continueCursor: "" };
|
||||
}
|
||||
if (args.family === "bundle-plugin") {
|
||||
return { page: [bundlePlugin], isDone: true, continueCursor: "" };
|
||||
}
|
||||
throw new Error(`unexpected family ${String(args.family)}`);
|
||||
});
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
|
||||
const response = await __handlers.listPluginsV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
new Request("https://example.com/api/v1/plugins?limit=7"),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect((await response.json()).items.map((entry: { name: string }) => entry.name)).toEqual([
|
||||
"code-plugin",
|
||||
"bundle-plugin",
|
||||
]);
|
||||
const families = runQuery.mock.calls.map(([, args]) => (args as { family?: string }).family);
|
||||
expect(families).toEqual(["code-plugin", "bundle-plugin"]);
|
||||
for (const [, args] of runQuery.mock.calls) {
|
||||
expect(args).toEqual(
|
||||
expect.objectContaining({
|
||||
paginationOpts: { cursor: null, numItems: 7 },
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("plugins list paginates with separate plugin family cursors", async () => {
|
||||
const codeNewest = makeCatalogItem("code-newest", {
|
||||
family: "code-plugin",
|
||||
updatedAt: 300,
|
||||
});
|
||||
const codeOlder = makeCatalogItem("code-older", {
|
||||
family: "code-plugin",
|
||||
updatedAt: 100,
|
||||
});
|
||||
const bundleMiddle = makeCatalogItem("bundle-middle", {
|
||||
family: "bundle-plugin",
|
||||
updatedAt: 200,
|
||||
});
|
||||
const runQuery = vi.fn((_, args: Record<string, unknown>) => {
|
||||
const pagination = args.paginationOpts as { cursor: string | null };
|
||||
if (args.family === "code-plugin" && pagination.cursor === null) {
|
||||
return { page: [codeNewest], isDone: false, continueCursor: "code-cursor" };
|
||||
}
|
||||
if (args.family === "code-plugin" && pagination.cursor === "code-cursor") {
|
||||
return { page: [codeOlder], isDone: true, continueCursor: "" };
|
||||
}
|
||||
if (args.family === "bundle-plugin" && pagination.cursor === null) {
|
||||
return { page: [bundleMiddle], isDone: true, continueCursor: "" };
|
||||
}
|
||||
throw new Error(`unexpected args ${JSON.stringify(args)}`);
|
||||
});
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
|
||||
const firstResponse = await __handlers.listPluginsV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
new Request("https://example.com/api/v1/plugins?limit=1"),
|
||||
);
|
||||
expect(firstResponse.status).toBe(200);
|
||||
const firstJson = await firstResponse.json();
|
||||
expect(firstJson.items.map((entry: { name: string }) => entry.name)).toEqual(["code-newest"]);
|
||||
expect(firstJson.nextCursor).toMatch(/^pkgplugins:/);
|
||||
|
||||
const secondUrl = new URL("https://example.com/api/v1/plugins");
|
||||
secondUrl.searchParams.set("limit", "1");
|
||||
secondUrl.searchParams.set("cursor", firstJson.nextCursor);
|
||||
const secondResponse = await __handlers.listPluginsV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
new Request(secondUrl),
|
||||
);
|
||||
expect(secondResponse.status).toBe(200);
|
||||
const secondJson = await secondResponse.json();
|
||||
expect(secondJson.items.map((entry: { name: string }) => entry.name)).toEqual([
|
||||
"bundle-middle",
|
||||
]);
|
||||
|
||||
const packageCalls = runQuery.mock.calls
|
||||
.map(([, args]) => args as { family?: string; paginationOpts?: { cursor: string | null } })
|
||||
.filter((args) => args.family === "code-plugin" || args.family === "bundle-plugin");
|
||||
expect(
|
||||
packageCalls.map((args) => ({
|
||||
family: args.family,
|
||||
cursor: args.paginationOpts?.cursor ?? null,
|
||||
})),
|
||||
).toEqual([
|
||||
{ family: "code-plugin", cursor: null },
|
||||
{ family: "bundle-plugin", cursor: null },
|
||||
{ family: "code-plugin", cursor: "code-cursor" },
|
||||
{ family: "bundle-plugin", cursor: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it("packages search supports family=skill on the generic route", async () => {
|
||||
const runQuery = vi.fn().mockResolvedValue([]);
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
@@ -2781,114 +2553,6 @@ describe("httpApiV1 handlers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("plugins search defaults to plugin package families", async () => {
|
||||
const runQuery = vi.fn((_, args: Record<string, unknown>) => {
|
||||
if (args.family === "code-plugin") {
|
||||
return {
|
||||
page: [
|
||||
{
|
||||
name: "weather-code",
|
||||
displayName: "Weather Code",
|
||||
family: "code-plugin",
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
createdAt: 10,
|
||||
updatedAt: 100,
|
||||
},
|
||||
],
|
||||
isDone: true,
|
||||
continueCursor: "",
|
||||
};
|
||||
}
|
||||
if (args.family === "bundle-plugin") {
|
||||
return {
|
||||
page: [
|
||||
{
|
||||
name: "weather-bundle",
|
||||
displayName: "Weather Bundle",
|
||||
family: "bundle-plugin",
|
||||
channel: "community",
|
||||
isOfficial: false,
|
||||
createdAt: 20,
|
||||
updatedAt: 200,
|
||||
},
|
||||
],
|
||||
isDone: true,
|
||||
continueCursor: "",
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected family ${String(args.family)}`);
|
||||
});
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
|
||||
const response = await __handlers.pluginsGetRouterV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
new Request("https://example.com/api/v1/plugins/search?q=weather&limit=7"),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(
|
||||
(await response.json()).results.map(
|
||||
(entry: { package: { name: string } }) => entry.package.name,
|
||||
),
|
||||
).toEqual(["weather-bundle", "weather-code"]);
|
||||
const families = runQuery.mock.calls.map(([, args]) => (args as { family?: string }).family);
|
||||
expect(families).toEqual(["code-plugin", "bundle-plugin"]);
|
||||
for (const [, args] of runQuery.mock.calls) {
|
||||
expect(args).toEqual(
|
||||
expect.objectContaining({
|
||||
paginationOpts: { cursor: null, numItems: 50 },
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("plugins search dedupes and sorts results from both plugin families", async () => {
|
||||
const runQuery = vi.fn((_, args: Record<string, unknown>) => {
|
||||
if (args.family === "code-plugin") {
|
||||
return {
|
||||
page: [
|
||||
makeCatalogItem("shared-plugin", { family: "code-plugin", updatedAt: 100 }),
|
||||
makeCatalogItem("plugin-code", { family: "code-plugin", updatedAt: 50 }),
|
||||
],
|
||||
isDone: true,
|
||||
continueCursor: "",
|
||||
};
|
||||
}
|
||||
if (args.family === "bundle-plugin") {
|
||||
return {
|
||||
page: [
|
||||
makeCatalogItem("plugin-bundle", { family: "bundle-plugin", updatedAt: 80 }),
|
||||
makeCatalogItem("shared-plugin", { family: "bundle-plugin", updatedAt: 60 }),
|
||||
],
|
||||
isDone: true,
|
||||
continueCursor: "",
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected family ${String(args.family)}`);
|
||||
});
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
|
||||
const response = await __handlers.pluginsGetRouterV1Handler(
|
||||
makeCtx({ runQuery, runMutation }),
|
||||
new Request("https://example.com/api/v1/plugins/search?q=plugin&limit=3"),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(
|
||||
(await response.json()).results.map(
|
||||
(entry: { score: number; package: { family: string; name: string } }) => ({
|
||||
family: entry.package.family,
|
||||
name: entry.package.name,
|
||||
}),
|
||||
),
|
||||
).toEqual([
|
||||
{ family: "bundle-plugin", name: "plugin-bundle" },
|
||||
{ family: "code-plugin", name: "plugin-code" },
|
||||
{ family: "code-plugin", name: "shared-plugin" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("packages list forwards viewerUserId for authenticated private package browsing", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:owner" as never);
|
||||
const runQuery = vi.fn().mockResolvedValue({ page: [], isDone: true, continueCursor: "" });
|
||||
@@ -2912,12 +2576,7 @@ describe("httpApiV1 handlers", () => {
|
||||
|
||||
it("packages search forwards viewerUserId for authenticated private package search", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:owner" as never);
|
||||
const runQuery = vi.fn((_, args: Record<string, unknown>) => {
|
||||
if ("userId" in args) return { _id: args.userId };
|
||||
if ("paginationOpts" in args) return { page: [], isDone: true, continueCursor: "" };
|
||||
if ("query" in args) return [];
|
||||
return null;
|
||||
});
|
||||
const runQuery = vi.fn().mockResolvedValue([]);
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
|
||||
const response = await __handlers.packagesGetRouterV1Handler(
|
||||
@@ -2929,9 +2588,9 @@ describe("httpApiV1 handlers", () => {
|
||||
expect(runQuery).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
query: "secret",
|
||||
channel: "private",
|
||||
viewerUserId: "users:owner",
|
||||
paginationOpts: { cursor: null, numItems: 50 },
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2963,8 +2622,7 @@ describe("httpApiV1 handlers", () => {
|
||||
if (query === internal.users.getByIdInternal) {
|
||||
throw new Error("Table mismatch");
|
||||
}
|
||||
if ("paginationOpts" in args) return { page: [], isDone: true, continueCursor: "" };
|
||||
if ("query" in args) return [];
|
||||
if ("query" in args && args.query === "secret") return [];
|
||||
return null;
|
||||
});
|
||||
const runMutation = vi.fn().mockResolvedValue(okRate());
|
||||
@@ -2982,9 +2640,9 @@ describe("httpApiV1 handlers", () => {
|
||||
expect(runQuery).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
query: "secret",
|
||||
channel: "community",
|
||||
viewerUserId: undefined,
|
||||
paginationOpts: { cursor: null, numItems: 50 },
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -4415,34 +4073,6 @@ describe("httpApiV1 handlers", () => {
|
||||
expect(setCall?.[1]).not.toHaveProperty("environment");
|
||||
});
|
||||
|
||||
it("deletes a package", async () => {
|
||||
vi.mocked(requireApiTokenUser).mockResolvedValue({
|
||||
userId: "users:1",
|
||||
user: { _id: "users:1", handle: "p" },
|
||||
} as never);
|
||||
const runMutation = vi.fn(async (_mutation: unknown, args: Record<string, unknown>) => {
|
||||
if ("key" in args) return okRate();
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
const response = await __handlers.packagesDeleteRouterV1Handler(
|
||||
makeCtx({ runMutation }),
|
||||
new Request("https://example.com/api/v1/packages/%40openclaw%2Fdemo-plugin", {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: "Bearer clh_test" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(runMutation).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
userId: "users:1",
|
||||
name: "@openclaw/demo-plugin",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("deletes trusted publisher config for a package", async () => {
|
||||
vi.mocked(requireApiTokenUser).mockResolvedValue({
|
||||
userId: "users:1",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server";
|
||||
import {
|
||||
PackagePublishRequestSchema,
|
||||
PackageTrustedPublisherUpsertRequestSchema,
|
||||
@@ -8,7 +9,6 @@ import { api, internal } from "../_generated/api";
|
||||
import type { Doc, Id } from "../_generated/dataModel";
|
||||
import type { ActionCtx } from "../_generated/server";
|
||||
import { getOptionalApiTokenUserId } from "../lib/apiTokenAuth";
|
||||
import { getOptionalActiveAuthUserIdFromAction } from "../lib/access";
|
||||
import {
|
||||
fetchGitHubRepositoryIdentity,
|
||||
verifyGitHubActionsTrustedPublishJwt,
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
requireApiTokenUserOrResponse,
|
||||
requirePackagePublishAuthOrResponse,
|
||||
safeTextFileResponse,
|
||||
softDeleteErrorToResponse,
|
||||
text,
|
||||
toOptionalNumber,
|
||||
} from "./shared";
|
||||
@@ -62,8 +61,6 @@ const internalRefs = internal as unknown as {
|
||||
getReleaseByPackageAndVersionInternal: unknown;
|
||||
getReleaseByIdInternal: unknown;
|
||||
insertAuditLogInternal: unknown;
|
||||
requestRescanForApiTokenInternal: unknown;
|
||||
softDeletePackageInternal: unknown;
|
||||
};
|
||||
packagePublishTokens: {
|
||||
createInternal: unknown;
|
||||
@@ -91,8 +88,12 @@ async function getOptionalViewerUserIdForRequest(ctx: ActionCtx, request: Reques
|
||||
const apiTokenUserId = await getOptionalApiTokenUserId(ctx, request);
|
||||
if (apiTokenUserId) return apiTokenUserId;
|
||||
try {
|
||||
const userId = (await getOptionalActiveAuthUserIdFromAction(ctx)) ?? null;
|
||||
const userId = (await getAuthUserId(ctx)) ?? null;
|
||||
if (!userId) return null;
|
||||
const user = await runQueryRef<Doc<"users"> | null>(ctx, internal.users.getByIdInternal, {
|
||||
userId,
|
||||
});
|
||||
if (!user || user.deletedAt || user.deactivatedAt) return null;
|
||||
return userId;
|
||||
} catch {
|
||||
// Public package reads should degrade to anonymous when cookie-backed auth is stale.
|
||||
@@ -251,11 +252,6 @@ type UnifiedCatalogCursorState = {
|
||||
skills: CatalogSourceCursorState;
|
||||
};
|
||||
|
||||
type PluginCatalogCursorState = {
|
||||
codePlugins: CatalogSourceCursorState;
|
||||
bundlePlugins: CatalogSourceCursorState;
|
||||
};
|
||||
|
||||
type CatalogPageResult = {
|
||||
page: CatalogListItem[];
|
||||
isDone: boolean;
|
||||
@@ -270,7 +266,6 @@ type CatalogSourceState = {
|
||||
};
|
||||
|
||||
const UNIFIED_CATALOG_CURSOR_PREFIX = "pkgcatalog:";
|
||||
const PLUGIN_CATALOG_CURSOR_PREFIX = "pkgplugins:";
|
||||
|
||||
function defaultCatalogSourceCursorState(): CatalogSourceCursorState {
|
||||
return { cursor: null, offset: 0, pageSize: null, done: false };
|
||||
@@ -311,42 +306,6 @@ function decodeUnifiedCatalogCursor(raw: string | null | undefined): UnifiedCata
|
||||
}
|
||||
}
|
||||
|
||||
function encodePluginCatalogCursor(state: PluginCatalogCursorState) {
|
||||
return `${PLUGIN_CATALOG_CURSOR_PREFIX}${JSON.stringify(state)}`;
|
||||
}
|
||||
|
||||
function decodePluginCatalogCursor(raw: string | null | undefined): PluginCatalogCursorState {
|
||||
const normalize = (
|
||||
input: Partial<CatalogSourceCursorState> | undefined,
|
||||
): CatalogSourceCursorState => ({
|
||||
cursor: typeof input?.cursor === "string" ? input.cursor : null,
|
||||
offset: typeof input?.offset === "number" && input.offset > 0 ? input.offset : 0,
|
||||
pageSize: typeof input?.pageSize === "number" && input.pageSize > 0 ? input.pageSize : null,
|
||||
done: input?.done === true,
|
||||
});
|
||||
|
||||
if (!raw?.startsWith(PLUGIN_CATALOG_CURSOR_PREFIX)) {
|
||||
return {
|
||||
codePlugins: { ...defaultCatalogSourceCursorState(), cursor: raw ?? null },
|
||||
bundlePlugins: defaultCatalogSourceCursorState(),
|
||||
};
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
raw.slice(PLUGIN_CATALOG_CURSOR_PREFIX.length),
|
||||
) as Partial<PluginCatalogCursorState>;
|
||||
return {
|
||||
codePlugins: normalize(parsed.codePlugins),
|
||||
bundlePlugins: normalize(parsed.bundlePlugins),
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
codePlugins: defaultCatalogSourceCursorState(),
|
||||
bundlePlugins: defaultCatalogSourceCursorState(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function initCatalogSource(state: CatalogSourceCursorState): CatalogSourceState {
|
||||
return {
|
||||
state: { ...state },
|
||||
@@ -363,7 +322,7 @@ function finalizeCatalogSource(source: CatalogSourceState): CatalogSourceCursorS
|
||||
cursor: source.pageCursor,
|
||||
offset: source.index,
|
||||
pageSize: source.state.pageSize,
|
||||
done: false,
|
||||
done: source.page.isDone,
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -411,100 +370,6 @@ function compareCatalogItems(a: CatalogListItem, b: CatalogListItem) {
|
||||
return a.name.localeCompare(b.name);
|
||||
}
|
||||
|
||||
const HTTP_PACKAGE_SEARCH_PAGE_SIZE = 50;
|
||||
const HTTP_PACKAGE_SEARCH_SCAN_PAGES = 20;
|
||||
|
||||
function catalogSearchScore(item: CatalogListItem, queryText: string) {
|
||||
const needle = queryText.toLowerCase();
|
||||
const name = item.name.toLowerCase();
|
||||
const display = item.displayName.toLowerCase();
|
||||
const runtimeId = item.runtimeId?.toLowerCase() ?? "";
|
||||
const summary = (item.summary ?? "").toLowerCase();
|
||||
let score = 0;
|
||||
|
||||
if (name === needle) score += 200;
|
||||
else if (name.startsWith(needle)) score += 120;
|
||||
else if (name.includes(needle)) score += 80;
|
||||
|
||||
if (display === needle) score += 150;
|
||||
else if (display.startsWith(needle)) score += 70;
|
||||
else if (display.includes(needle)) score += 40;
|
||||
|
||||
if (runtimeId === needle) score += 180;
|
||||
else if (runtimeId.startsWith(needle)) score += 90;
|
||||
else if (runtimeId.includes(needle)) score += 45;
|
||||
|
||||
if (summary.includes(needle)) score += 20;
|
||||
if ((item.capabilityTags ?? []).some((entry) => entry.toLowerCase().includes(needle))) {
|
||||
score += 12;
|
||||
}
|
||||
if (item.isOfficial) score += 5;
|
||||
return score;
|
||||
}
|
||||
|
||||
function compareCatalogSearchEntries(a: CatalogSearchEntry, b: CatalogSearchEntry) {
|
||||
return (
|
||||
b.score - a.score ||
|
||||
Number(b.package.isOfficial) - Number(a.package.isOfficial) ||
|
||||
compareCatalogItems(a.package, b.package)
|
||||
);
|
||||
}
|
||||
|
||||
async function searchPackageCatalogByListing(
|
||||
ctx: ActionCtx,
|
||||
args: {
|
||||
query: string;
|
||||
limit: number;
|
||||
family?: "skill" | "code-plugin" | "bundle-plugin";
|
||||
channel?: "official" | "community" | "private";
|
||||
isOfficial?: boolean;
|
||||
executesCode?: boolean;
|
||||
capabilityTag?: string;
|
||||
viewerUserId?: Id<"users">;
|
||||
},
|
||||
): Promise<CatalogSearchEntry[]> {
|
||||
const queryText = args.query.trim().toLowerCase();
|
||||
if (!queryText) return [];
|
||||
|
||||
const matches: CatalogSearchEntry[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | null = null;
|
||||
let done = false;
|
||||
let loops = 0;
|
||||
|
||||
while (!done && loops < HTTP_PACKAGE_SEARCH_SCAN_PAGES) {
|
||||
loops += 1;
|
||||
const result: {
|
||||
page: CatalogListItem[];
|
||||
isDone: boolean;
|
||||
continueCursor: string | null;
|
||||
} = await runQueryRef(ctx, internalRefs.packages.listPageForViewerInternal, {
|
||||
family: args.family,
|
||||
channel: args.channel,
|
||||
isOfficial: args.isOfficial,
|
||||
executesCode: args.executesCode,
|
||||
capabilityTag: args.capabilityTag,
|
||||
viewerUserId: args.viewerUserId,
|
||||
paginationOpts: { cursor, numItems: HTTP_PACKAGE_SEARCH_PAGE_SIZE },
|
||||
});
|
||||
|
||||
for (const item of result.page) {
|
||||
const key = `${item.family}:${item.name}`;
|
||||
if (seen.has(key)) continue;
|
||||
const score = catalogSearchScore(item, queryText);
|
||||
if (score <= 0) continue;
|
||||
seen.add(key);
|
||||
matches.push({ score, package: item });
|
||||
}
|
||||
|
||||
done = result.isDone;
|
||||
cursor = result.continueCursor;
|
||||
if (!cursor && !done) break;
|
||||
}
|
||||
|
||||
return matches.sort(compareCatalogSearchEntries).slice(0, args.limit);
|
||||
}
|
||||
|
||||
async function resolveSkillTags(
|
||||
ctx: ActionCtx,
|
||||
tags: Record<string, Id<"skillVersions">>,
|
||||
@@ -637,7 +502,7 @@ async function listPackages(
|
||||
ctx: ActionCtx,
|
||||
request: Request,
|
||||
family?: PackageListQueryArgs["family"],
|
||||
options?: { includeSkills?: boolean; pluginFamilies?: Array<"code-plugin" | "bundle-plugin"> },
|
||||
options?: { includeSkills?: boolean },
|
||||
) {
|
||||
const rate = await applyRateLimit(ctx, request, "read");
|
||||
if (!rate.ok) return rate.response;
|
||||
@@ -764,84 +629,6 @@ async function listPackages(
|
||||
);
|
||||
}
|
||||
|
||||
if (!effectiveFamily && options?.pluginFamilies?.length) {
|
||||
const decodedCursor = decodePluginCatalogCursor(cursor);
|
||||
const codePluginSource = initCatalogSource(decodedCursor.codePlugins);
|
||||
const bundlePluginSource = initCatalogSource(decodedCursor.bundlePlugins);
|
||||
const pageSize = limit;
|
||||
const items: CatalogListItem[] = [];
|
||||
const fetchPluginPage = async (
|
||||
pluginFamily: "code-plugin" | "bundle-plugin",
|
||||
pageCursor: string | null,
|
||||
numItems: number,
|
||||
) => {
|
||||
const result = await runQueryRef<{
|
||||
page: CatalogListItem[];
|
||||
isDone: boolean;
|
||||
continueCursor: string | null;
|
||||
}>(ctx, internalRefs.packages.listPageForViewerInternal, {
|
||||
family: pluginFamily,
|
||||
channel,
|
||||
isOfficial,
|
||||
executesCode,
|
||||
capabilityTag,
|
||||
viewerUserId: viewerUserId ?? undefined,
|
||||
paginationOpts: { cursor: pageCursor, numItems },
|
||||
});
|
||||
return {
|
||||
page: result.page,
|
||||
isDone: result.isDone,
|
||||
continueCursor: result.continueCursor ?? "",
|
||||
};
|
||||
};
|
||||
|
||||
while (items.length < limit) {
|
||||
const [codePluginCandidate, bundlePluginCandidate] = await Promise.all([
|
||||
options.pluginFamilies.includes("code-plugin")
|
||||
? ensureCatalogSourcePage(codePluginSource, pageSize, (pageCursor, numItems) =>
|
||||
fetchPluginPage("code-plugin", pageCursor, numItems),
|
||||
)
|
||||
: Promise.resolve(null),
|
||||
options.pluginFamilies.includes("bundle-plugin")
|
||||
? ensureCatalogSourcePage(bundlePluginSource, pageSize, (pageCursor, numItems) =>
|
||||
fetchPluginPage("bundle-plugin", pageCursor, numItems),
|
||||
)
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
|
||||
if (!codePluginCandidate && !bundlePluginCandidate) break;
|
||||
if (
|
||||
!bundlePluginCandidate ||
|
||||
(codePluginCandidate &&
|
||||
compareCatalogItems(codePluginCandidate, bundlePluginCandidate) <= 0)
|
||||
) {
|
||||
items.push(codePluginCandidate!);
|
||||
codePluginSource.index += 1;
|
||||
} else {
|
||||
items.push(bundlePluginCandidate);
|
||||
bundlePluginSource.index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const nextState = {
|
||||
codePlugins: finalizeCatalogSource(codePluginSource),
|
||||
bundlePlugins: finalizeCatalogSource(bundlePluginSource),
|
||||
};
|
||||
const isDoneAll =
|
||||
nextState.codePlugins.done &&
|
||||
nextState.codePlugins.offset === 0 &&
|
||||
nextState.bundlePlugins.done &&
|
||||
nextState.bundlePlugins.offset === 0;
|
||||
return json(
|
||||
{
|
||||
items,
|
||||
nextCursor: isDoneAll ? null : encodePluginCatalogCursor(nextState),
|
||||
},
|
||||
200,
|
||||
rate.headers,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runQueryRef<{
|
||||
page: unknown[];
|
||||
isDone: boolean;
|
||||
@@ -867,10 +654,7 @@ export async function listPackagesV1Handler(ctx: ActionCtx, request: Request) {
|
||||
}
|
||||
|
||||
export async function listPluginsV1Handler(ctx: ActionCtx, request: Request) {
|
||||
return await listPackages(ctx, request, undefined, {
|
||||
includeSkills: false,
|
||||
pluginFamilies: ["code-plugin", "bundle-plugin"],
|
||||
});
|
||||
return await listPackages(ctx, request, undefined, { includeSkills: false });
|
||||
}
|
||||
|
||||
export async function listCodePluginsV1Handler(ctx: ActionCtx, request: Request) {
|
||||
@@ -1037,31 +821,6 @@ export async function mintPublishTokenV1Handler(ctx: ActionCtx, request: Request
|
||||
|
||||
export async function packagesPostRouterV1Handler(ctx: ActionCtx, request: Request) {
|
||||
const segments = getPathSegments(request, "/api/v1/packages/");
|
||||
if (segments[1] === "rescan" && segments.length === 2) {
|
||||
const rate = await applyRateLimit(ctx, request, "write");
|
||||
if (!rate.ok) return rate.response;
|
||||
const auth = await requireApiTokenUserOrResponse(ctx, request, rate.headers);
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
try {
|
||||
const result = await runMutationRef(
|
||||
ctx,
|
||||
internalRefs.packages.requestRescanForApiTokenInternal,
|
||||
{
|
||||
actorUserId: auth.userId,
|
||||
name: segments[0]!,
|
||||
},
|
||||
);
|
||||
return json(result, 200, rate.headers);
|
||||
} catch (error) {
|
||||
return text(
|
||||
error instanceof Error ? error.message : "Rescan request failed",
|
||||
400,
|
||||
rate.headers,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (segments[1] !== "trusted-publisher" || segments.length !== 2) {
|
||||
return text("Not found", 404);
|
||||
}
|
||||
@@ -1111,27 +870,14 @@ export async function packagesPostRouterV1Handler(ctx: ActionCtx, request: Reque
|
||||
|
||||
export async function packagesDeleteRouterV1Handler(ctx: ActionCtx, request: Request) {
|
||||
const segments = getPathSegments(request, "/api/v1/packages/");
|
||||
if (segments[1] !== "trusted-publisher" || segments.length !== 2) {
|
||||
return text("Not found", 404);
|
||||
}
|
||||
const rate = await applyRateLimit(ctx, request, "write");
|
||||
if (!rate.ok) return rate.response;
|
||||
const auth = await requireApiTokenUserOrResponse(ctx, request, rate.headers);
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
if (segments.length === 1) {
|
||||
try {
|
||||
await runMutationRef(ctx, internalRefs.packages.softDeletePackageInternal, {
|
||||
userId: auth.userId,
|
||||
name: segments[0]!,
|
||||
});
|
||||
return json({ ok: true }, 200, rate.headers);
|
||||
} catch (error) {
|
||||
return softDeleteErrorToResponse("package", error, rate.headers);
|
||||
}
|
||||
}
|
||||
|
||||
if (segments[1] !== "trusted-publisher" || segments.length !== 2) {
|
||||
return text("Not found", 404, rate.headers);
|
||||
}
|
||||
|
||||
try {
|
||||
await runMutationRef(ctx, internalRefs.packages.deleteTrustedPublisherForUserInternal, {
|
||||
actorUserId: auth.userId,
|
||||
@@ -1267,7 +1013,7 @@ async function getSkillVersionForRequest(
|
||||
async function searchPackages(
|
||||
ctx: ActionCtx,
|
||||
request: Request,
|
||||
options?: { includeSkills?: boolean; pluginFamilies?: Array<"code-plugin" | "bundle-plugin"> },
|
||||
options?: { includeSkills?: boolean },
|
||||
) {
|
||||
const rate = await applyRateLimit(ctx, request, "read");
|
||||
if (!rate.ok) return rate.response;
|
||||
@@ -1310,34 +1056,10 @@ async function searchPackages(
|
||||
},
|
||||
);
|
||||
} else if (family || !includeSkills) {
|
||||
if (!family && options?.pluginFamilies?.length) {
|
||||
const pluginResults = await Promise.all(
|
||||
options.pluginFamilies.map((pluginFamily) =>
|
||||
searchPackageCatalogByListing(ctx, {
|
||||
query: queryText,
|
||||
limit,
|
||||
family: pluginFamily,
|
||||
channel,
|
||||
isOfficial,
|
||||
executesCode,
|
||||
capabilityTag,
|
||||
viewerUserId: viewerUserId ?? undefined,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const seen = new Set<string>();
|
||||
results = pluginResults
|
||||
.flat()
|
||||
.filter((entry) => {
|
||||
const key = `${entry.package.family}:${entry.package.name}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
})
|
||||
.sort(compareCatalogSearchEntries)
|
||||
.slice(0, limit);
|
||||
} else {
|
||||
results = await searchPackageCatalogByListing(ctx, {
|
||||
results = await runQueryRef<CatalogSearchEntry[]>(
|
||||
ctx,
|
||||
internalRefs.packages.searchForViewerInternal,
|
||||
{
|
||||
query: queryText,
|
||||
limit,
|
||||
family,
|
||||
@@ -1346,11 +1068,11 @@ async function searchPackages(
|
||||
executesCode,
|
||||
capabilityTag,
|
||||
viewerUserId: viewerUserId ?? undefined,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
} else {
|
||||
const [packageResults, skillResults] = await Promise.all([
|
||||
searchPackageCatalogByListing(ctx, {
|
||||
runQueryRef<CatalogSearchEntry[]>(ctx, internalRefs.packages.searchForViewerInternal, {
|
||||
query: queryText,
|
||||
limit,
|
||||
channel,
|
||||
@@ -1376,7 +1098,12 @@ async function searchPackages(
|
||||
seen.add(key);
|
||||
return true;
|
||||
})
|
||||
.sort(compareCatalogSearchEntries)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
b.score - a.score ||
|
||||
Number(b.package.isOfficial) - Number(a.package.isOfficial) ||
|
||||
compareCatalogItems(a.package, b.package),
|
||||
)
|
||||
.slice(0, limit);
|
||||
}
|
||||
return json({ results }, 200, rate.headers);
|
||||
@@ -1686,10 +1413,7 @@ export async function pluginsGetRouterV1Handler(ctx: ActionCtx, request: Request
|
||||
const segments = getPathSegments(request, "/api/v1/plugins/");
|
||||
if (segments.length === 0) return text("Not found", 404);
|
||||
if (segments[0] === "search" && new URL(request.url).searchParams.has("q")) {
|
||||
return await searchPackages(ctx, request, {
|
||||
includeSkills: false,
|
||||
pluginFamilies: ["code-plugin", "bundle-plugin"],
|
||||
});
|
||||
return await searchPackages(ctx, request, { includeSkills: false });
|
||||
}
|
||||
return text("Not found", 404);
|
||||
}
|
||||
|
||||
@@ -331,7 +331,7 @@ export function parsePublishBody(body: unknown) {
|
||||
}
|
||||
|
||||
export function softDeleteErrorToResponse(
|
||||
entity: "skill" | "soul" | "package",
|
||||
entity: "skill" | "soul",
|
||||
error: unknown,
|
||||
headers: HeadersInit,
|
||||
) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { normalizeTextContentType } from "clawhub-schema";
|
||||
import { api, internal } from "../_generated/api";
|
||||
import { normalizeTextContentType } from "clawhub-schema";
|
||||
import type { Doc, Id } from "../_generated/dataModel";
|
||||
import type { ActionCtx } from "../_generated/server";
|
||||
import { getOptionalApiTokenUserId, requireApiTokenUser } from "../lib/apiTokenAuth";
|
||||
@@ -231,16 +231,6 @@ type SkillSecuritySnapshot = {
|
||||
};
|
||||
};
|
||||
|
||||
const internalRefs = internal as unknown as {
|
||||
skills: {
|
||||
requestRescanForApiTokenInternal: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
async function runMutationRef<T>(ctx: ActionCtx, ref: unknown, args: unknown): Promise<T> {
|
||||
return (await ctx.runMutation(ref as never, args as never)) as T;
|
||||
}
|
||||
|
||||
function isDefinitiveSecurityStatus(
|
||||
status: NormalizedSecurityStatus | null | undefined,
|
||||
): status is "clean" | "suspicious" | "malicious" {
|
||||
@@ -287,7 +277,9 @@ function mergeSecurityStatuses(statuses: NormalizedSecurityStatus[]) {
|
||||
);
|
||||
}
|
||||
|
||||
function hasLlmDimensionWarnings(dimensions: LlmEvalDimension[] | undefined) {
|
||||
function hasLlmDimensionWarnings(
|
||||
dimensions: LlmEvalDimension[] | undefined,
|
||||
) {
|
||||
if (!Array.isArray(dimensions)) return false;
|
||||
return dimensions.some((dimension) => {
|
||||
if (!dimension || typeof dimension !== "object") return false;
|
||||
@@ -446,8 +438,6 @@ type SkillListSort =
|
||||
| "installsAllTime"
|
||||
| "trending";
|
||||
|
||||
type PublicListSort = "updated" | "downloads" | "stars" | "installs";
|
||||
|
||||
function parseListSort(value: string | null): SkillListSort {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
if (normalized === "downloads") return "downloads";
|
||||
@@ -467,12 +457,6 @@ function parseListSort(value: string | null): SkillListSort {
|
||||
return "updated";
|
||||
}
|
||||
|
||||
function toPublicListSort(sort: Exclude<SkillListSort, "trending">): PublicListSort {
|
||||
if (sort === "updated") return "updated";
|
||||
if (sort === "downloads" || sort === "stars") return sort;
|
||||
return "installs";
|
||||
}
|
||||
|
||||
export async function listSkillsV1Handler(ctx: ActionCtx, request: Request) {
|
||||
const rate = await applyRateLimit(ctx, request, "read");
|
||||
if (!rate.ok) return rate.response;
|
||||
@@ -487,24 +471,12 @@ export async function listSkillsV1Handler(ctx: ActionCtx, request: Request) {
|
||||
url.searchParams.get("nonSuspicious"),
|
||||
);
|
||||
|
||||
let result: ListSkillsResult;
|
||||
if (sort === "trending") {
|
||||
result = (await ctx.runQuery(api.skills.listPublicTrendingPage, {
|
||||
limit,
|
||||
nonSuspiciousOnly: nonSuspiciousOnly || undefined,
|
||||
})) as ListSkillsResult;
|
||||
} else {
|
||||
const pageResult = (await ctx.runQuery(api.skills.listPublicPageV4, {
|
||||
cursor,
|
||||
numItems: limit,
|
||||
sort: toPublicListSort(sort),
|
||||
nonSuspiciousOnly: nonSuspiciousOnly || undefined,
|
||||
})) as { page?: ListSkillsResult["items"]; nextCursor?: string | null };
|
||||
result = {
|
||||
items: pageResult.page ?? [],
|
||||
nextCursor: pageResult.nextCursor ?? null,
|
||||
};
|
||||
}
|
||||
const result = (await ctx.runQuery(api.skills.listPublicPage, {
|
||||
limit,
|
||||
cursor,
|
||||
sort,
|
||||
nonSuspiciousOnly: nonSuspiciousOnly || undefined,
|
||||
})) as ListSkillsResult;
|
||||
|
||||
// Batch resolve all tags in a single query instead of N queries
|
||||
const resolvedTagsList = await resolveTagsBatch(
|
||||
@@ -732,7 +704,7 @@ export async function skillsGetRouterV1Handler(ctx: ActionCtx, request: Request)
|
||||
summary: mod.summary,
|
||||
engineVersion: mod.engineVersion,
|
||||
updatedAt: mod.updatedAt,
|
||||
evidence: sanitizeEvidence(mod.evidence, isOwner || isStaff),
|
||||
evidence: sanitizeEvidence(mod.evidence, Boolean(isOwner || isStaff)),
|
||||
legacyReason: isOwner || isStaff ? mod.reason : null,
|
||||
}
|
||||
: null,
|
||||
@@ -1175,29 +1147,6 @@ export async function skillsPostRouterV1Handler(ctx: ActionCtx, request: Request
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.length === 2 && action === "rescan") {
|
||||
if (!slug) return text("Slug required", 400, rate.headers);
|
||||
const auth = await requireApiTokenUserOrResponse(ctx, request, rate.headers);
|
||||
if (!auth.ok) return auth.response;
|
||||
try {
|
||||
const result = await runMutationRef(
|
||||
ctx,
|
||||
internalRefs.skills.requestRescanForApiTokenInternal,
|
||||
{
|
||||
actorUserId: auth.userId,
|
||||
slug,
|
||||
},
|
||||
);
|
||||
return json(result, 200, rate.headers);
|
||||
} catch (error) {
|
||||
return text(
|
||||
error instanceof Error ? error.message : "Rescan request failed",
|
||||
400,
|
||||
rate.headers,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (action === "transfer") {
|
||||
return handleSkillsTransferPost(ctx, request, segments, rate.headers);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ export async function whoamiV1Handler(ctx: ActionCtx, request: Request) {
|
||||
handle: user.handle ?? null,
|
||||
displayName: user.displayName ?? null,
|
||||
image: user.image ?? null,
|
||||
role: user.role ?? null,
|
||||
},
|
||||
},
|
||||
200,
|
||||
|
||||
@@ -5,61 +5,17 @@ import type { ActionCtx, MutationCtx, QueryCtx } from "../_generated/server";
|
||||
|
||||
export type Role = "admin" | "moderator" | "user";
|
||||
|
||||
const DEV_IMPERSONATE_LOCAL_HANDLE = "local";
|
||||
|
||||
function readEnv(name: string) {
|
||||
const value = process.env[name]?.trim();
|
||||
return value ? value : undefined;
|
||||
}
|
||||
|
||||
function isDevImpersonationAllowed() {
|
||||
const requestedHandle = readEnv("CLAW_HUB_DEV_IMPERSONATE_USER_HANDLE");
|
||||
if (requestedHandle !== DEV_IMPERSONATE_LOCAL_HANDLE) return false;
|
||||
|
||||
const deployment = readEnv("CONVEX_DEPLOYMENT") ?? "";
|
||||
if (deployment.startsWith("prod:") || deployment.includes("production")) return false;
|
||||
return (
|
||||
deployment.startsWith("anonymous:") ||
|
||||
deployment.startsWith("dev:") ||
|
||||
deployment.startsWith("local:") ||
|
||||
readEnv("CLAW_HUB_ENABLE_DEV_IMPERSONATION") === "1"
|
||||
);
|
||||
}
|
||||
|
||||
async function getDevImpersonatedUserId(
|
||||
ctx: Pick<MutationCtx | QueryCtx, "db">,
|
||||
): Promise<Id<"users"> | undefined> {
|
||||
if (!isDevImpersonationAllowed()) return undefined;
|
||||
const user = await ctx.db
|
||||
.query("users")
|
||||
.withIndex("handle", (q) => q.eq("handle", DEV_IMPERSONATE_LOCAL_HANDLE))
|
||||
.unique();
|
||||
if (!user || user.deletedAt || user.deactivatedAt) return undefined;
|
||||
return user._id;
|
||||
}
|
||||
|
||||
async function getDevImpersonatedUserIdFromAction(
|
||||
ctx: ActionCtx,
|
||||
): Promise<Id<"users"> | undefined> {
|
||||
if (!isDevImpersonationAllowed()) return undefined;
|
||||
const user = await ctx.runQuery(internal.users.getByHandleInternal, {
|
||||
handle: DEV_IMPERSONATE_LOCAL_HANDLE,
|
||||
});
|
||||
if (!user || user.deletedAt || user.deactivatedAt) return undefined;
|
||||
return user._id;
|
||||
}
|
||||
|
||||
export async function getOptionalActiveAuthUserId(
|
||||
ctx: MutationCtx | QueryCtx,
|
||||
): Promise<Id<"users"> | undefined> {
|
||||
try {
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) return await getDevImpersonatedUserId(ctx);
|
||||
if (!userId) return undefined;
|
||||
const user = await ctx.db.get(userId);
|
||||
if (!user || user.deletedAt || user.deactivatedAt) return undefined;
|
||||
return userId;
|
||||
} catch {
|
||||
return await getDevImpersonatedUserId(ctx);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,23 +24,17 @@ export async function getOptionalActiveAuthUserIdFromAction(
|
||||
): Promise<Id<"users"> | undefined> {
|
||||
try {
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) return await getDevImpersonatedUserIdFromAction(ctx);
|
||||
if (!userId) return undefined;
|
||||
const user = await ctx.runQuery(internal.users.getByIdInternal, { userId });
|
||||
if (!user || user.deletedAt || user.deactivatedAt) return undefined;
|
||||
return userId;
|
||||
} catch {
|
||||
return await getDevImpersonatedUserIdFromAction(ctx);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireUser(ctx: MutationCtx | QueryCtx) {
|
||||
let userId: Id<"users"> | null | undefined = null;
|
||||
try {
|
||||
userId = await getAuthUserId(ctx);
|
||||
} catch {
|
||||
userId = null;
|
||||
}
|
||||
userId ??= await getDevImpersonatedUserId(ctx);
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) throw new Error("Unauthorized");
|
||||
let user: Doc<"users"> | null;
|
||||
try {
|
||||
@@ -99,13 +49,7 @@ export async function requireUser(ctx: MutationCtx | QueryCtx) {
|
||||
export async function requireUserFromAction(
|
||||
ctx: ActionCtx,
|
||||
): Promise<{ userId: Id<"users">; user: Doc<"users"> }> {
|
||||
let userId: Id<"users"> | null | undefined = null;
|
||||
try {
|
||||
userId = await getAuthUserId(ctx);
|
||||
} catch {
|
||||
userId = null;
|
||||
}
|
||||
userId ??= await getDevImpersonatedUserIdFromAction(ctx);
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) throw new Error("Unauthorized");
|
||||
let user: Doc<"users"> | null;
|
||||
try {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { Scheduler } from "convex/server";
|
||||
|
||||
export function scheduleNextBatchIfNeeded(
|
||||
export function scheduleNextBatchIfNeeded<TArgs extends { cursor?: string }>(
|
||||
scheduler: Scheduler,
|
||||
fn: unknown,
|
||||
args: { cursor?: string } & Record<string, unknown>,
|
||||
args: TArgs,
|
||||
isDone: boolean,
|
||||
continueCursor: string | null,
|
||||
) {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/* @vitest-environment node */
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
extractWorkflowFilenameFromWorkflowRef,
|
||||
fetchGitHubRepositoryIdentity,
|
||||
verifyGitHubActionsTrustedPublishJwt,
|
||||
type TrustedGitHubActionsPublisher,
|
||||
} from "./githubActionsOidc";
|
||||
@@ -31,10 +30,6 @@ const signingKeyPairPromise = crypto.subtle.generateKey(
|
||||
["sign", "verify"],
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("extractWorkflowFilenameFromWorkflowRef", () => {
|
||||
it("extracts the workflow filename from workflow_ref", () => {
|
||||
expect(
|
||||
@@ -46,57 +41,6 @@ describe("extractWorkflowFilenameFromWorkflowRef", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchGitHubRepositoryIdentity", () => {
|
||||
it("uses GITHUB_TOKEN for repository lookup when configured", async () => {
|
||||
vi.stubEnv("GITHUB_TOKEN", "ghs_test_token");
|
||||
const fetchMock = vi.fn(async () =>
|
||||
Response.json({
|
||||
id: 123,
|
||||
full_name: "openclaw/clawhub",
|
||||
owner: { login: "openclaw", id: 456 },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(fetchGitHubRepositoryIdentity("openclaw/clawhub", fetchMock)).resolves.toEqual({
|
||||
repository: "openclaw/clawhub",
|
||||
repositoryId: "123",
|
||||
repositoryOwner: "openclaw",
|
||||
repositoryOwnerId: "456",
|
||||
});
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://api.github.com/repos/openclaw/clawhub",
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
Accept: "application/vnd.github+json",
|
||||
Authorization: "Bearer ghs_test_token",
|
||||
"User-Agent": "clawhub/package-trusted-publisher",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("omits Authorization for repository lookup when GITHUB_TOKEN is blank", async () => {
|
||||
vi.stubEnv("GITHUB_TOKEN", " ");
|
||||
const fetchMock = vi.fn(async () =>
|
||||
Response.json({
|
||||
id: 123,
|
||||
full_name: "openclaw/clawhub",
|
||||
owner: { login: "openclaw", id: 456 },
|
||||
}),
|
||||
);
|
||||
|
||||
await fetchGitHubRepositoryIdentity("openclaw/clawhub", fetchMock);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith("https://api.github.com/repos/openclaw/clawhub", {
|
||||
headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": "clawhub/package-trusted-publisher",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyGitHubActionsTrustedPublishJwt", () => {
|
||||
it("accepts a valid GitHub Actions token", async () => {
|
||||
const { token, jwks } = await createSignedToken({
|
||||
|
||||
@@ -217,7 +217,10 @@ export async function fetchGitHubRepositoryIdentity(
|
||||
throw new Error(`Invalid GitHub repository: ${repository}`);
|
||||
}
|
||||
const response = await fetchImpl(`https://api.github.com/repos/${normalizedRepository}`, {
|
||||
headers: buildGitHubRepositoryLookupHeaders(),
|
||||
headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": "clawhub/package-trusted-publisher",
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
@@ -239,18 +242,6 @@ export async function fetchGitHubRepositoryIdentity(
|
||||
};
|
||||
}
|
||||
|
||||
function buildGitHubRepositoryLookupHeaders() {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": "clawhub/package-trusted-publisher",
|
||||
};
|
||||
const token = process.env.GITHUB_TOKEN?.trim();
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function normalizeGitHubRepository(repository: string) {
|
||||
const trimmed = repository
|
||||
.trim()
|
||||
@@ -288,8 +279,8 @@ function decodeJwt(jwt: string) {
|
||||
const parts = jwt.trim().split(".");
|
||||
if (parts.length !== 3) throw new Error("Invalid GitHub OIDC token format");
|
||||
const [encodedHeader, encodedPayload, encodedSignature] = parts;
|
||||
const header = parseJsonSegment(encodedHeader, "header") as JwtHeader;
|
||||
const payload = parseJsonSegment(encodedPayload, "payload") as JwtPayload;
|
||||
const header = parseJsonSegment<JwtHeader>(encodedHeader, "header");
|
||||
const payload = parseJsonSegment<JwtPayload>(encodedPayload, "payload");
|
||||
return {
|
||||
header,
|
||||
payload,
|
||||
@@ -298,9 +289,9 @@ function decodeJwt(jwt: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonSegment(segment: string, label: string): unknown {
|
||||
function parseJsonSegment<T>(segment: string, label: string) {
|
||||
try {
|
||||
return JSON.parse(new TextDecoder().decode(base64UrlToBytes(segment)));
|
||||
return JSON.parse(new TextDecoder().decode(base64UrlToBytes(segment))) as T;
|
||||
} catch {
|
||||
throw new Error(`Invalid GitHub OIDC ${label}`);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("deriveModerationFlags", () => {
|
||||
skill: {
|
||||
slug: "test",
|
||||
displayName: "Test",
|
||||
summary: "Send data to https://discord.com/api/webhooks/123/token",
|
||||
summary: "Send data to discord.gg/xyz",
|
||||
},
|
||||
parsed: { frontmatter: {} },
|
||||
files: [],
|
||||
@@ -44,19 +44,6 @@ describe("deriveModerationFlags", () => {
|
||||
expect(flags).toContain("suspicious.webhook");
|
||||
});
|
||||
|
||||
test("does not flag generic webhook integrations", () => {
|
||||
const flags = deriveModerationFlags({
|
||||
skill: {
|
||||
slug: "wordpress-api",
|
||||
displayName: "WordPress API",
|
||||
summary: "Manage WordPress REST API webhooks and Zapier callbacks.",
|
||||
},
|
||||
parsed: { frontmatter: {} },
|
||||
files: [],
|
||||
});
|
||||
expect(flags).not.toContain("suspicious.webhook");
|
||||
});
|
||||
|
||||
test("flags slack webhooks", () => {
|
||||
const flags = deriveModerationFlags({
|
||||
skill: {
|
||||
@@ -207,8 +194,7 @@ describe("deriveModerationFlags", () => {
|
||||
skill: {
|
||||
slug: "test",
|
||||
displayName: "Test",
|
||||
summary:
|
||||
"Malware stealer that posts to discord.gg/hook via curl | bash from bit.ly",
|
||||
summary: "Malware stealer that posts to discord.gg webhooks via curl | bash from bit.ly",
|
||||
},
|
||||
parsed: { frontmatter: {} },
|
||||
files: [],
|
||||
|
||||
@@ -11,12 +11,8 @@ const FLAG_RULES: Array<{ flag: string; pattern: RegExp }> = [
|
||||
// Malicious intent keywords
|
||||
{ flag: "suspicious.keyword", pattern: /(malware|stealer|phish|phishing|keylogger)/i },
|
||||
|
||||
// Data exfiltration patterns - flag explicit Discord/Slack webhook endpoints,
|
||||
// not legitimate integrations that mention generic webhook support.
|
||||
{
|
||||
flag: "suspicious.webhook",
|
||||
pattern: /(discord\.gg\/|discord\.com\/api\/webhooks|discordapp\.com\/api\/webhooks|hooks\.slack)/i,
|
||||
},
|
||||
// Data exfiltration patterns - webhooks are unusual in skills
|
||||
{ flag: "suspicious.webhook", pattern: /(discord\.gg|webhook|hooks\.slack)/i },
|
||||
|
||||
// Arbitrary code execution - curl | bash is dangerous
|
||||
{ flag: "suspicious.script", pattern: /(curl[^\n]+\|\s*(sh|bash))/i },
|
||||
|
||||
@@ -23,57 +23,6 @@ describe("moderationEngine", () => {
|
||||
expect(result.status).toBe("clean");
|
||||
});
|
||||
|
||||
it("flags hardcoded API secrets in skill documentation and redacts every evidence copy", () => {
|
||||
const exposedSecret = "ak_live_1234567890abcdefSECRET";
|
||||
const result = runStaticModerationScan({
|
||||
slug: "seo-admin",
|
||||
displayName: "SEO Admin",
|
||||
summary: "Manage production SEO content",
|
||||
frontmatter: {},
|
||||
metadata: {},
|
||||
files: [{ path: "SKILL.md", size: 256 }],
|
||||
fileContents: [
|
||||
{
|
||||
path: "SKILL.md",
|
||||
content: [
|
||||
"# SEO Admin",
|
||||
"Production endpoint: https://example.com/admin/api",
|
||||
`API secret: ${exposedSecret} # rotate ${exposedSecret}`,
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.reasonCodes).toContain("suspicious.exposed_secret_literal");
|
||||
expect(result.status).toBe("suspicious");
|
||||
expect(result.findings[0]?.evidence).toContain("[REDACTED]");
|
||||
expect(result.findings[0]?.evidence).not.toContain(exposedSecret);
|
||||
});
|
||||
|
||||
it("does not flag placeholder or env-var secret examples", () => {
|
||||
const result = runStaticModerationScan({
|
||||
slug: "demo",
|
||||
displayName: "Demo",
|
||||
summary: "A normal integration skill",
|
||||
frontmatter: {},
|
||||
metadata: {},
|
||||
files: [{ path: "SKILL.md", size: 128 }],
|
||||
fileContents: [
|
||||
{
|
||||
path: "SKILL.md",
|
||||
content: [
|
||||
"Set `API secret: your-secret-here` before running the sample.",
|
||||
"const api_key = process.env.PROVIDER_API_KEY;",
|
||||
"api_secret = os.environ['PROVIDER_API_SECRET']",
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.reasonCodes).not.toContain("suspicious.exposed_secret_literal");
|
||||
expect(result.status).toBe("clean");
|
||||
});
|
||||
|
||||
it("flags dynamic eval usage as suspicious", () => {
|
||||
const result = runStaticModerationScan({
|
||||
slug: "demo",
|
||||
@@ -89,18 +38,13 @@ describe("moderationEngine", () => {
|
||||
expect(result.status).toBe("suspicious");
|
||||
});
|
||||
|
||||
it("does not flag declared env vars sent to the intended API", () => {
|
||||
it("flags process.env + fetch as suspicious (not malicious)", () => {
|
||||
const result = runStaticModerationScan({
|
||||
slug: "todoist",
|
||||
displayName: "Todoist",
|
||||
summary: "Manage tasks via the Todoist API",
|
||||
frontmatter: {},
|
||||
metadata: {
|
||||
requires: {
|
||||
env: ["TODOIST_KEY"],
|
||||
},
|
||||
primaryEnv: "TODOIST_KEY",
|
||||
},
|
||||
metadata: {},
|
||||
files: [{ path: "index.ts", size: 128 }],
|
||||
fileContents: [
|
||||
{
|
||||
@@ -111,88 +55,8 @@ describe("moderationEngine", () => {
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.reasonCodes).not.toContain("suspicious.env_credential_access");
|
||||
expect(result.status).toBe("clean");
|
||||
});
|
||||
|
||||
it("still flags undeclared env vars sent over the network", () => {
|
||||
const result = runStaticModerationScan({
|
||||
slug: "todoist",
|
||||
displayName: "Todoist",
|
||||
summary: "Manage tasks via the Todoist API",
|
||||
frontmatter: {},
|
||||
metadata: {
|
||||
requires: {
|
||||
env: ["TODOIST_KEY"],
|
||||
},
|
||||
},
|
||||
files: [{ path: "index.ts", size: 128 }],
|
||||
fileContents: [
|
||||
{
|
||||
path: "index.ts",
|
||||
content:
|
||||
"const key = process.env.OPENAI_API_KEY;\nconst res = await fetch(url, { headers: { Authorization: key } });",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.reasonCodes).toContain("suspicious.env_credential_access");
|
||||
expect(result.status).toBe("suspicious");
|
||||
});
|
||||
|
||||
it("still flags broad env access even when one env var is declared", () => {
|
||||
const result = runStaticModerationScan({
|
||||
slug: "todoist",
|
||||
displayName: "Todoist",
|
||||
summary: "Manage tasks via the Todoist API",
|
||||
frontmatter: {},
|
||||
metadata: {
|
||||
requires: {
|
||||
env: ["TODOIST_KEY"],
|
||||
},
|
||||
},
|
||||
files: [{ path: "index.ts", size: 128 }],
|
||||
fileContents: [
|
||||
{
|
||||
path: "index.ts",
|
||||
content:
|
||||
"const headers = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.endsWith('_KEY')));\nconst res = await fetch(url, { headers });",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.reasonCodes).toContain("suspicious.env_credential_access");
|
||||
expect(result.status).toBe("suspicious");
|
||||
});
|
||||
|
||||
it("keeps exfiltration findings when file reads are paired with network sends", () => {
|
||||
const result = runStaticModerationScan({
|
||||
slug: "todoist",
|
||||
displayName: "Todoist",
|
||||
summary: "Manage tasks via the Todoist API",
|
||||
frontmatter: {},
|
||||
metadata: {
|
||||
requires: {
|
||||
env: ["TODOIST_KEY"],
|
||||
},
|
||||
},
|
||||
files: [{ path: "index.ts", size: 256 }],
|
||||
fileContents: [
|
||||
{
|
||||
path: "index.ts",
|
||||
content: [
|
||||
"const key = process.env.TODOIST_KEY;",
|
||||
"const secret = readFileSync('/tmp/secret.txt', 'utf8');",
|
||||
"const res = await fetch(url, {",
|
||||
" headers: { Authorization: key },",
|
||||
" body: secret,",
|
||||
"});",
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.reasonCodes).toContain("suspicious.potential_exfiltration");
|
||||
expect(result.reasonCodes).not.toContain("malicious.env_harvesting");
|
||||
expect(result.status).toBe("suspicious");
|
||||
});
|
||||
|
||||
@@ -578,60 +442,4 @@ describe("moderationEngine", () => {
|
||||
expect(snapshot.reasonCodes).toContain("suspicious.env_credential_access");
|
||||
expect(snapshot.reasonCodes).toContain("suspicious.vt_suspicious");
|
||||
});
|
||||
|
||||
it("does not let uncorroborated VT Code Insight suspicious override clean local scans", () => {
|
||||
const snapshot = buildModerationSnapshot({
|
||||
staticScan: {
|
||||
status: "clean",
|
||||
reasonCodes: [],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
vtAnalysis: {
|
||||
status: "suspicious",
|
||||
scanner: "code_insight",
|
||||
source: "VirusTotal Code Insight",
|
||||
engineStats: {
|
||||
malicious: 0,
|
||||
suspicious: 0,
|
||||
harmless: 12,
|
||||
undetected: 54,
|
||||
},
|
||||
},
|
||||
llmStatus: "clean",
|
||||
});
|
||||
|
||||
expect(snapshot.verdict).toBe("clean");
|
||||
expect(snapshot.reasonCodes).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps VT Code Insight suspicious when AV engines also report suspicious", () => {
|
||||
const snapshot = buildModerationSnapshot({
|
||||
staticScan: {
|
||||
status: "clean",
|
||||
reasonCodes: [],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
vtAnalysis: {
|
||||
status: "suspicious",
|
||||
scanner: "code_insight",
|
||||
source: "VirusTotal Code Insight",
|
||||
engineStats: {
|
||||
malicious: 0,
|
||||
suspicious: 1,
|
||||
harmless: 12,
|
||||
undetected: 53,
|
||||
},
|
||||
},
|
||||
llmStatus: "clean",
|
||||
});
|
||||
|
||||
expect(snapshot.verdict).toBe("suspicious");
|
||||
expect(snapshot.reasonCodes).toContain("suspicious.vt_suspicious");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,22 +13,6 @@ import {
|
||||
} from "./moderationReasonCodes";
|
||||
|
||||
type TextFile = { path: string; content: string };
|
||||
type VirusTotalEngineStats = {
|
||||
malicious?: number;
|
||||
suspicious?: number;
|
||||
undetected?: number;
|
||||
harmless?: number;
|
||||
};
|
||||
|
||||
type VirusTotalAnalysis = {
|
||||
status?: string;
|
||||
scanner?: string;
|
||||
source?: string;
|
||||
engineStats?: VirusTotalEngineStats;
|
||||
metadata?: {
|
||||
stats?: VirusTotalEngineStats;
|
||||
};
|
||||
};
|
||||
|
||||
export type StaticScanInput = {
|
||||
slug: string;
|
||||
@@ -74,10 +58,6 @@ const HARDCODED_CONNECTION_ID_PATTERN =
|
||||
/["']connection_id["']\s*:\s*["'][0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}["']/i;
|
||||
const GOOGLE_SHEETS_SPREADSHEET_URL_PATTERN =
|
||||
/https?:\/\/[^\s"'`]*\/spreadsheets\/([A-Za-z0-9_-]{20,})\/[^\s"'`]*/i;
|
||||
const SECRET_ASSIGNMENT_PATTERN =
|
||||
/\b(?:api[_\s-]?(?:secret|key)|secret[_\s-]?key|access[_\s-]?token|auth[_\s-]?token|bearer[_\s-]?token|password)\b\s*[:=]\s*["'`]?([A-Za-z0-9][A-Za-z0-9._~+/=-]{15,})["'`]?/i;
|
||||
const AUTH_HEADER_SECRET_PATTERN =
|
||||
/\b(?:authorization|x-api-key|x-api-secret)\b\s*[:=]\s*(?:Bearer\s+)?["'`]?([A-Za-z0-9][A-Za-z0-9._~+/=-]{15,})["'`]?/i;
|
||||
|
||||
function hasMaliciousInstallPrompt(content: string) {
|
||||
const hasTerminalInstruction =
|
||||
@@ -107,31 +87,6 @@ function looksLikePlaceholderIdentifier(identifier: string) {
|
||||
return /^[A-Z0-9_]+$/.test(identifier) || /(your|example|placeholder)/i.test(identifier);
|
||||
}
|
||||
|
||||
function looksLikePlaceholderSecret(secret: string) {
|
||||
const normalized = secret.trim().toLowerCase();
|
||||
if (!normalized) return true;
|
||||
if (/^(?:x+|_+|-+|\*+|\.{3})$/.test(normalized)) return true;
|
||||
if (/process\.env\.|os\.environ[.[]|getenv\s*\(/.test(normalized)) return true;
|
||||
return /(your|example|placeholder|change-?me|replace|redacted|dummy|sample|test-token|token-here|secret-here|api-key-here)/i.test(
|
||||
normalized,
|
||||
);
|
||||
}
|
||||
|
||||
function findHardcodedSecret(content: string) {
|
||||
const lines = content.split("\n");
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
const match = line.match(SECRET_ASSIGNMENT_PATTERN) ?? line.match(AUTH_HEADER_SECRET_PATTERN);
|
||||
const secret = match?.[1];
|
||||
if (!secret || looksLikePlaceholderSecret(secret)) continue;
|
||||
return {
|
||||
line: i + 1,
|
||||
text: line.replaceAll(secret, "[REDACTED]"),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addFinding(
|
||||
findings: ModerationFinding[],
|
||||
finding: Omit<ModerationFinding, "evidence"> & { evidence: string },
|
||||
@@ -157,81 +112,7 @@ function findLineAtIndex(content: string, index: number) {
|
||||
return { line, text: content.slice(lineStart, lineEnd) };
|
||||
}
|
||||
|
||||
function normalizeEnvName(value: unknown) {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed.toUpperCase() : undefined;
|
||||
}
|
||||
|
||||
function addDeclaredEnvName(names: Set<string>, value: unknown) {
|
||||
const normalized = normalizeEnvName(value);
|
||||
if (normalized) names.add(normalized);
|
||||
}
|
||||
|
||||
function addDeclaredEnvNamesFromList(names: Set<string>, value: unknown) {
|
||||
if (!Array.isArray(value)) return;
|
||||
for (const entry of value) {
|
||||
if (typeof entry === "string") {
|
||||
addDeclaredEnvName(names, entry);
|
||||
continue;
|
||||
}
|
||||
if (entry && typeof entry === "object" && !Array.isArray(entry)) {
|
||||
addDeclaredEnvName(names, (entry as { name?: unknown }).name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collectDeclaredEnvNames(input: { frontmatter: Record<string, unknown>; metadata?: unknown }) {
|
||||
const names = new Set<string>();
|
||||
const sources: unknown[] = [input.frontmatter, input.metadata];
|
||||
|
||||
for (const source of sources) {
|
||||
if (!source || typeof source !== "object" || Array.isArray(source)) continue;
|
||||
const record = source as Record<string, unknown>;
|
||||
const requires =
|
||||
record.requires && typeof record.requires === "object" && !Array.isArray(record.requires)
|
||||
? (record.requires as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
addDeclaredEnvName(names, record.primaryEnv);
|
||||
addDeclaredEnvNamesFromList(names, record.envVars);
|
||||
addDeclaredEnvNamesFromList(names, record.env);
|
||||
addDeclaredEnvNamesFromList(names, requires?.env);
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
function collectReferencedEnvNames(content: string) {
|
||||
const names = new Set<string>();
|
||||
const patterns = [
|
||||
/process\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
|
||||
/process\.env\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g,
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
for (const match of content.matchAll(pattern)) {
|
||||
addDeclaredEnvName(names, match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
function hasBroadEnvAccess(content: string) {
|
||||
return (
|
||||
/Object\.(?:keys|values|entries)\s*\(\s*process\.env\s*\)/.test(content) ||
|
||||
/process\.env(?!\s*(?:\.|\[))/.test(content) ||
|
||||
/process\.env\[\s*[^"'`\]]/.test(content)
|
||||
);
|
||||
}
|
||||
|
||||
function scanCodeFile(
|
||||
path: string,
|
||||
content: string,
|
||||
findings: ModerationFinding[],
|
||||
declaredEnvNames: Set<string>,
|
||||
) {
|
||||
function scanCodeFile(path: string, content: string, findings: ModerationFinding[]) {
|
||||
if (!CODE_EXTENSION.test(path)) return;
|
||||
|
||||
const hasChildProcess = /child_process/.test(content);
|
||||
@@ -304,23 +185,15 @@ function scanCodeFile(
|
||||
|
||||
const hasProcessEnv = /process\.env/.test(content);
|
||||
if (hasProcessEnv && hasNetworkSend) {
|
||||
const referencedEnvNames = collectReferencedEnvNames(content);
|
||||
const accessesOnlyDeclaredEnvNames =
|
||||
referencedEnvNames.size > 0 &&
|
||||
[...referencedEnvNames].every((name) => declaredEnvNames.has(name)) &&
|
||||
!hasBroadEnvAccess(content);
|
||||
|
||||
if (!accessesOnlyDeclaredEnvNames) {
|
||||
const match = findFirstLine(content, /process\.env/);
|
||||
addFinding(findings, {
|
||||
code: REASON_CODES.CREDENTIAL_HARVEST,
|
||||
severity: "critical",
|
||||
file: path,
|
||||
line: match.line,
|
||||
message: "Environment variable access combined with network send.",
|
||||
evidence: match.text,
|
||||
});
|
||||
}
|
||||
const match = findFirstLine(content, /process\.env/);
|
||||
addFinding(findings, {
|
||||
code: REASON_CODES.CREDENTIAL_HARVEST,
|
||||
severity: "critical",
|
||||
file: path,
|
||||
line: match.line,
|
||||
message: "Environment variable access combined with network send.",
|
||||
evidence: match.text,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -342,18 +215,6 @@ function scanCodeFile(
|
||||
function scanMarkdownFile(path: string, content: string, findings: ModerationFinding[]) {
|
||||
if (!MARKDOWN_EXTENSION.test(path)) return;
|
||||
|
||||
const secretMatch = findHardcodedSecret(content);
|
||||
if (secretMatch) {
|
||||
addFinding(findings, {
|
||||
code: REASON_CODES.EXPOSED_SECRET_LITERAL,
|
||||
severity: "critical",
|
||||
file: path,
|
||||
line: secretMatch.line,
|
||||
message: "Documentation appears to expose a hardcoded API secret or token.",
|
||||
evidence: secretMatch.text,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasMaliciousInstallPrompt(content)) {
|
||||
const match = findFirstLine(
|
||||
content,
|
||||
@@ -469,42 +330,11 @@ function dedupeEvidence(evidence: ModerationFinding[]) {
|
||||
return out.slice(0, 40);
|
||||
}
|
||||
|
||||
function isStaticScanClean(staticScan: StaticScanResult | undefined) {
|
||||
// Older moderation records can predate static scan persistence; absence means
|
||||
// there are no static findings available to corroborate an external signal.
|
||||
return !staticScan || staticScan.reasonCodes.length === 0 || staticScan.status === "clean";
|
||||
}
|
||||
|
||||
function isAvEngineStatsClean(stats: VirusTotalEngineStats | undefined) {
|
||||
if (!stats) return false;
|
||||
return (stats.malicious ?? 0) === 0 && (stats.suspicious ?? 0) === 0;
|
||||
}
|
||||
|
||||
function getVtEngineStats(analysis: VirusTotalAnalysis | undefined) {
|
||||
return analysis?.engineStats ?? analysis?.metadata?.stats;
|
||||
}
|
||||
|
||||
function isUncorroboratedVtCodeInsightSuspicious(params: {
|
||||
vtAnalysis?: VirusTotalAnalysis;
|
||||
staticScan?: StaticScanResult;
|
||||
llmStatus?: string;
|
||||
}) {
|
||||
if (params.vtAnalysis?.scanner !== "code_insight") return false;
|
||||
if (!isExternalScannerClean(params.llmStatus)) return false;
|
||||
if (!isStaticScanClean(params.staticScan)) return false;
|
||||
return isAvEngineStatsClean(getVtEngineStats(params.vtAnalysis));
|
||||
}
|
||||
|
||||
function addScannerStatusReason(
|
||||
reasonCodes: string[],
|
||||
scanner: "vt" | "llm",
|
||||
status?: string,
|
||||
options: { suppressSuspicious?: boolean } = {},
|
||||
) {
|
||||
function addScannerStatusReason(reasonCodes: string[], scanner: "vt" | "llm", status?: string) {
|
||||
const normalized = status?.trim().toLowerCase();
|
||||
if (normalized === "malicious") {
|
||||
reasonCodes.push(`malicious.${scanner}_malicious`);
|
||||
} else if (normalized === "suspicious" && !options.suppressSuspicious) {
|
||||
} else if (normalized === "suspicious") {
|
||||
reasonCodes.push(`suspicious.${scanner}_suspicious`);
|
||||
}
|
||||
}
|
||||
@@ -512,10 +342,9 @@ function addScannerStatusReason(
|
||||
export function runStaticModerationScan(input: StaticScanInput): StaticScanResult {
|
||||
const findings: ModerationFinding[] = [];
|
||||
const files = [...input.fileContents].sort((a, b) => a.path.localeCompare(b.path));
|
||||
const declaredEnvNames = collectDeclaredEnvNames(input);
|
||||
|
||||
for (const file of files) {
|
||||
scanCodeFile(file.path, file.content, findings, declaredEnvNames);
|
||||
scanCodeFile(file.path, file.content, findings);
|
||||
scanMarkdownFile(file.path, file.content, findings);
|
||||
scanManifestFile(file.path, file.content, findings);
|
||||
}
|
||||
@@ -581,7 +410,6 @@ function isExternalScannerClean(status: string | undefined): boolean {
|
||||
|
||||
export function buildModerationSnapshot(params: {
|
||||
staticScan?: StaticScanResult;
|
||||
vtAnalysis?: VirusTotalAnalysis;
|
||||
vtStatus?: string;
|
||||
llmStatus?: string;
|
||||
sourceVersionId?: Id<"skillVersions">;
|
||||
@@ -599,14 +427,7 @@ export function buildModerationSnapshot(params: {
|
||||
}
|
||||
|
||||
const reasonCodes = [...staticCodes];
|
||||
const vtStatus = params.vtStatus ?? params.vtAnalysis?.status;
|
||||
addScannerStatusReason(reasonCodes, "vt", vtStatus, {
|
||||
suppressSuspicious: isUncorroboratedVtCodeInsightSuspicious({
|
||||
vtAnalysis: params.vtAnalysis,
|
||||
staticScan: params.staticScan,
|
||||
llmStatus: params.llmStatus,
|
||||
}),
|
||||
});
|
||||
addScannerStatusReason(reasonCodes, "vt", params.vtStatus);
|
||||
addScannerStatusReason(reasonCodes, "llm", params.llmStatus);
|
||||
|
||||
const normalizedCodes = normalizeReasonCodes(reasonCodes);
|
||||
|
||||
@@ -12,14 +12,13 @@ export type ModerationFinding = {
|
||||
evidence: string;
|
||||
};
|
||||
|
||||
export const MODERATION_ENGINE_VERSION = "v2.4.2";
|
||||
export const MODERATION_ENGINE_VERSION = "v2.4.0";
|
||||
|
||||
export const REASON_CODES = {
|
||||
DANGEROUS_EXEC: "suspicious.dangerous_exec",
|
||||
DYNAMIC_CODE: "suspicious.dynamic_code_execution",
|
||||
GENERATED_SOURCE_TEMPLATE: "suspicious.generated_source_template_injection",
|
||||
EXPOSED_RESOURCE_IDENTIFIER: "suspicious.exposed_resource_identifier",
|
||||
EXPOSED_SECRET_LITERAL: "suspicious.exposed_secret_literal",
|
||||
CREDENTIAL_HARVEST: "suspicious.env_credential_access",
|
||||
EXFILTRATION: "suspicious.potential_exfiltration",
|
||||
OBFUSCATED_CODE: "suspicious.obfuscated_code",
|
||||
|
||||
@@ -144,13 +144,13 @@ export async function deletePackageSearchDigests(
|
||||
}
|
||||
}
|
||||
|
||||
function hasDigestChanged(
|
||||
existing: Record<string, unknown>,
|
||||
fields: Record<string, unknown>,
|
||||
): boolean {
|
||||
function hasDigestChanged<
|
||||
TExisting extends Record<string, unknown>,
|
||||
TFields extends Record<string, unknown>,
|
||||
>(existing: TExisting, fields: TFields): boolean {
|
||||
for (const key of Object.keys(fields)) {
|
||||
const oldValue = existing[key];
|
||||
const newValue = fields[key];
|
||||
const oldValue = (existing as Record<string, unknown>)[key];
|
||||
const newValue = (fields as Record<string, unknown>)[key];
|
||||
if (oldValue === newValue) continue;
|
||||
if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) return true;
|
||||
}
|
||||
|
||||
@@ -77,34 +77,6 @@ export function isPublisherRoleAllowed(role: PublisherRole, allowed: PublisherRo
|
||||
return allowed.some((candidate) => ranks[role] >= ranks[candidate]);
|
||||
}
|
||||
|
||||
export type OwnedResourceActor = {
|
||||
_id: Id<"users">;
|
||||
role?: Doc<"users">["role"];
|
||||
};
|
||||
|
||||
export async function assertCanManageOwnedResource(
|
||||
ctx: DbCtx,
|
||||
params: {
|
||||
actor: OwnedResourceActor;
|
||||
ownerUserId: Id<"users">;
|
||||
ownerPublisherId?: Id<"publishers"> | null;
|
||||
allowedPublisherRoles?: PublisherRole[];
|
||||
allowPlatformAdmin?: boolean;
|
||||
},
|
||||
) {
|
||||
if (params.allowPlatformAdmin && params.actor.role === "admin") return;
|
||||
if (params.ownerUserId === params.actor._id) return;
|
||||
if (!params.ownerPublisherId) throw new ConvexError("Forbidden");
|
||||
|
||||
const membership = await getPublisherMembership(ctx, params.ownerPublisherId, params.actor._id);
|
||||
if (
|
||||
!membership ||
|
||||
!isPublisherRoleAllowed(membership.role, params.allowedPublisherRoles ?? ["admin"])
|
||||
) {
|
||||
throw new ConvexError("Forbidden");
|
||||
}
|
||||
}
|
||||
|
||||
export async function getPublisherByHandle(ctx: DbCtx, handle: string | undefined | null) {
|
||||
const normalized = normalizePublisherHandle(handle);
|
||||
if (!normalized) return null;
|
||||
|
||||
@@ -13,18 +13,17 @@ describe("searchText", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("matchesExactTokens requires every query token to prefix-match", () => {
|
||||
it("matchesExactTokens requires at least one query token to prefix-match", () => {
|
||||
const queryTokens = tokenize("Remind Me");
|
||||
expect(matchesExactTokens(queryTokens, ["Remind Me", "/remind-me", "Short summary"])).toBe(
|
||||
true,
|
||||
);
|
||||
// "Reminder" starts with "remind", but no token matches "me".
|
||||
// "Reminder" starts with "remind", so it matches with prefix matching
|
||||
expect(matchesExactTokens(queryTokens, ["Reminder tool", "/reminder", "Short summary"])).toBe(
|
||||
false,
|
||||
);
|
||||
expect(matchesExactTokens(queryTokens, ["Remind tool", "/remind", "Short summary"])).toBe(
|
||||
false,
|
||||
true,
|
||||
);
|
||||
// Matches because "remind" token is present
|
||||
expect(matchesExactTokens(queryTokens, ["Remind tool", "/remind", "Short summary"])).toBe(true);
|
||||
// No matching tokens at all
|
||||
expect(matchesExactTokens(queryTokens, ["Other tool", "/other", "Short summary"])).toBe(false);
|
||||
});
|
||||
|
||||
@@ -115,9 +115,7 @@ export function tokenize(value: string): string[] {
|
||||
|
||||
const tokens: string[] = [];
|
||||
|
||||
const parts = normalized.split(
|
||||
/([^\u4e00-\u9fff\u3400-\u4dbf\u3041-\u3096\u30a1-\u30fa\uac00-\ud7af]+)/g,
|
||||
);
|
||||
const parts = normalized.split(/([^\u4e00-\u9fff\u3400-\u4dbf\u3041-\u3096\u30a1-\u30fa\uac00-\ud7af]+)/g);
|
||||
|
||||
for (const part of parts) {
|
||||
if (!part.trim()) continue;
|
||||
@@ -143,8 +141,8 @@ export function matchesExactTokens(
|
||||
if (!text) return false;
|
||||
const textTokens = tokenize(text);
|
||||
if (textTokens.length === 0) return false;
|
||||
// Require every query token to prefix-match so partial matches do not crowd out better results.
|
||||
return queryTokens.every((queryToken) =>
|
||||
// Require at least one token to prefix-match, allowing vector similarity to determine relevance
|
||||
return queryTokens.some((queryToken) =>
|
||||
textTokens.some((textToken) => textToken.startsWith(queryToken)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,34 +10,18 @@ type SkillStatDeltas = {
|
||||
installsAllTime?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Read the canonical value of a migrated stat field from a skill document.
|
||||
*
|
||||
* Top-level fields (`statsDownloads`, etc.) are the source of truth — they are
|
||||
* indexable and kept up-to-date by the event pipeline. The nested `stats.*`
|
||||
* fields are only used as a fallback for pre-migration documents where the
|
||||
* top-level field is still `undefined`.
|
||||
*
|
||||
* All code that reads a migrated stat value should go through this function
|
||||
* rather than accessing `skill.stats.*` directly.
|
||||
*/
|
||||
export function readCanonicalStat(
|
||||
skill: Doc<"skills">,
|
||||
field: "downloads" | "stars" | "installsCurrent" | "installsAllTime",
|
||||
): number {
|
||||
const topLevelKey = `stats${field[0].toUpperCase()}${field.slice(1)}` as
|
||||
| "statsDownloads"
|
||||
| "statsStars"
|
||||
| "statsInstallsCurrent"
|
||||
| "statsInstallsAllTime";
|
||||
return typeof skill[topLevelKey] === "number" ? skill[topLevelKey]! : (skill.stats[field] ?? 0);
|
||||
}
|
||||
|
||||
export function applySkillStatDeltas(skill: Doc<"skills">, deltas: SkillStatDeltas) {
|
||||
const currentDownloads = readCanonicalStat(skill, "downloads");
|
||||
const currentStars = readCanonicalStat(skill, "stars");
|
||||
const currentInstallsCurrent = readCanonicalStat(skill, "installsCurrent");
|
||||
const currentInstallsAllTime = readCanonicalStat(skill, "installsAllTime");
|
||||
const currentDownloads =
|
||||
typeof skill.statsDownloads === "number" ? skill.statsDownloads : skill.stats.downloads;
|
||||
const currentStars = typeof skill.statsStars === "number" ? skill.statsStars : skill.stats.stars;
|
||||
const currentInstallsCurrent =
|
||||
typeof skill.statsInstallsCurrent === "number"
|
||||
? skill.statsInstallsCurrent
|
||||
: (skill.stats.installsCurrent ?? 0);
|
||||
const currentInstallsAllTime =
|
||||
typeof skill.statsInstallsAllTime === "number"
|
||||
? skill.statsInstallsAllTime
|
||||
: (skill.stats.installsAllTime ?? 0);
|
||||
|
||||
const currentComments = skill.stats.comments;
|
||||
const nextDownloads = Math.max(0, currentDownloads + (deltas.downloads ?? 0));
|
||||
|
||||
@@ -372,7 +372,7 @@ function parseDependencyDeclarations(input: unknown): Array<{
|
||||
version?: string;
|
||||
url?: string;
|
||||
repository?: string;
|
||||
} = { name: obj.name.trim(), type: depType };
|
||||
} = { name: String(obj.name).trim(), type: depType };
|
||||
if (typeof obj.version === "string") decl.version = obj.version.trim();
|
||||
if (typeof obj.url === "string") decl.url = obj.url.trim();
|
||||
if (typeof obj.repository === "string") decl.repository = obj.repository.trim();
|
||||
@@ -432,7 +432,7 @@ function parseFrontmatterLevelDeclarations(
|
||||
|
||||
// Parse primaryEnv from top-level frontmatter
|
||||
if (typeof frontmatter.primaryEnv === "string") {
|
||||
metadata.primaryEnv = frontmatter.primaryEnv.trim();
|
||||
metadata.primaryEnv = String(frontmatter.primaryEnv).trim();
|
||||
}
|
||||
|
||||
const envVars = parseEnvVarDeclarations(frontmatter.env);
|
||||
@@ -441,13 +441,13 @@ function parseFrontmatterLevelDeclarations(
|
||||
const dependencies = parseDependencyDeclarations(frontmatter.dependencies);
|
||||
if (dependencies.length > 0) metadata.dependencies = dependencies;
|
||||
|
||||
if (typeof frontmatter.author === "string") metadata.author = frontmatter.author.trim();
|
||||
if (typeof frontmatter.author === "string") metadata.author = String(frontmatter.author).trim();
|
||||
|
||||
const links = parseSkillLinks(frontmatter.links);
|
||||
if (links) metadata.links = links;
|
||||
|
||||
if (typeof frontmatter.homepage === "string") {
|
||||
metadata.homepage = frontmatter.homepage.trim();
|
||||
metadata.homepage = String(frontmatter.homepage).trim();
|
||||
}
|
||||
|
||||
return Object.keys(metadata).length > 0
|
||||
|
||||
@@ -23,7 +23,6 @@ vi.mock("./_generated/api", () => ({
|
||||
nominateEmptySkillSpammersInternal: Symbol("nominateEmptySkillSpammersInternal"),
|
||||
},
|
||||
skills: {
|
||||
backfillLatestSkillModerationInternal: Symbol("skills.backfillLatestSkillModerationInternal"),
|
||||
getVersionByIdInternal: Symbol("skills.getVersionByIdInternal"),
|
||||
getOwnerSkillActivityInternal: Symbol("skills.getOwnerSkillActivityInternal"),
|
||||
},
|
||||
|
||||
@@ -1965,20 +1965,6 @@ export const backfillLatestVersionSummaryInternal = internalMutation({
|
||||
},
|
||||
});
|
||||
|
||||
// Repair stale skill-level moderation that was sourced from a non-latest version.
|
||||
// Run once after deploying the latest-version moderation fix:
|
||||
// npx convex run maintenance:backfillLatestSkillModeration --prod
|
||||
export const backfillLatestSkillModeration: ReturnType<typeof action> = action({
|
||||
args: {
|
||||
batchSize: v.optional(v.number()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { user } = await requireUserFromAction(ctx);
|
||||
assertRole(user, ["admin"]);
|
||||
return await ctx.runMutation(internal.skills.backfillLatestSkillModerationInternal, args);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Backfill `isSuspicious` on all skills. Cursor-based paginated mutation
|
||||
* that self-schedules until done.
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { ConvexError } from "convex/values";
|
||||
import type { Doc, Id } from "../../_generated/dataModel";
|
||||
import type { MutationCtx, QueryCtx } from "../../_generated/server";
|
||||
import type { OwnedResourceActor } from "../../lib/publishers";
|
||||
|
||||
export async function getLatestPackageRescanTarget(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
packageId: Id<"packages">,
|
||||
) {
|
||||
const pkg = await ctx.db.get(packageId);
|
||||
if (!pkg || pkg.softDeletedAt || pkg.family === "skill") {
|
||||
throw new ConvexError("Plugin not found");
|
||||
}
|
||||
if (!pkg.latestReleaseId) throw new ConvexError("Plugin has no published release");
|
||||
const release = await ctx.db.get(pkg.latestReleaseId);
|
||||
if (!release || release.softDeletedAt) throw new ConvexError("Latest plugin release not found");
|
||||
return { pkg, release };
|
||||
}
|
||||
|
||||
export async function insertPackageRescanRequest(
|
||||
ctx: Pick<MutationCtx, "db">,
|
||||
actor: OwnedResourceActor,
|
||||
target: {
|
||||
pkg: Doc<"packages">;
|
||||
release: Doc<"packageReleases">;
|
||||
},
|
||||
) {
|
||||
const now = Date.now();
|
||||
return await ctx.db.insert("rescanRequests", {
|
||||
targetKind: "plugin",
|
||||
packageId: target.pkg._id,
|
||||
packageReleaseId: target.release._id,
|
||||
targetVersion: target.release.version,
|
||||
requestedByUserId: actor._id,
|
||||
ownerUserId: target.pkg.ownerUserId,
|
||||
ownerPublisherId: target.pkg.ownerPublisherId,
|
||||
status: "in_progress",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
import { ConvexError } from "convex/values";
|
||||
import type { Doc, Id } from "../../_generated/dataModel";
|
||||
import type { MutationCtx, QueryCtx } from "../../_generated/server";
|
||||
|
||||
export const MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE = 3;
|
||||
const ACTIVE_RESCAN_STATUS = "in_progress" as const;
|
||||
const NON_TERMINAL_SCAN_STATUSES = new Set(["loading", "not_found", "pending"]);
|
||||
const FAILED_SCAN_STATUSES = new Set(["error", "failed", "stale"]);
|
||||
|
||||
export type RescanTarget =
|
||||
| {
|
||||
kind: "skill";
|
||||
artifactId: Id<"skillVersions">;
|
||||
}
|
||||
| {
|
||||
kind: "plugin";
|
||||
artifactId: Id<"packageReleases">;
|
||||
};
|
||||
|
||||
export function serializeRescanRequest(request: Doc<"rescanRequests"> | null) {
|
||||
if (!request) return null;
|
||||
return {
|
||||
_id: request._id,
|
||||
targetKind: request.targetKind,
|
||||
targetVersion: request.targetVersion,
|
||||
requestedByUserId: request.requestedByUserId,
|
||||
status: request.status,
|
||||
error: request.error,
|
||||
createdAt: request.createdAt,
|
||||
updatedAt: request.updatedAt,
|
||||
completedAt: request.completedAt,
|
||||
};
|
||||
}
|
||||
|
||||
type ScanSignal = {
|
||||
status: string;
|
||||
checkedAt: number;
|
||||
};
|
||||
|
||||
export type RescanScanState = {
|
||||
staticScan?: ScanSignal;
|
||||
vtAnalysis?: ScanSignal;
|
||||
llmAnalysis?: ScanSignal;
|
||||
};
|
||||
|
||||
function freshTerminalSignal(signal: ScanSignal | undefined, requestedAt: number) {
|
||||
if (!signal || signal.checkedAt < requestedAt) return null;
|
||||
const status = signal.status.trim().toLowerCase();
|
||||
if (NON_TERMINAL_SCAN_STATUSES.has(status)) return null;
|
||||
return status;
|
||||
}
|
||||
|
||||
function terminalRequestStatusForScanState(
|
||||
scanState: RescanScanState,
|
||||
requestedAt: number,
|
||||
): "completed" | "failed" | null {
|
||||
const statuses = [
|
||||
freshTerminalSignal(scanState.staticScan, requestedAt),
|
||||
freshTerminalSignal(scanState.vtAnalysis, requestedAt),
|
||||
freshTerminalSignal(scanState.llmAnalysis, requestedAt),
|
||||
];
|
||||
if (statuses.some((status) => status === null)) return null;
|
||||
if (statuses.some((status) => FAILED_SCAN_STATUSES.has(status!))) return "failed";
|
||||
return "completed";
|
||||
}
|
||||
|
||||
export async function listRequestsForTarget(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
target: RescanTarget,
|
||||
) {
|
||||
if (target.kind === "skill") {
|
||||
return await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_skill_version", (q) =>
|
||||
q.eq("targetKind", "skill").eq("skillVersionId", target.artifactId),
|
||||
)
|
||||
.order("desc")
|
||||
.take(MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE + 1);
|
||||
}
|
||||
|
||||
return await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_package_release", (q) =>
|
||||
q.eq("targetKind", "plugin").eq("packageReleaseId", target.artifactId),
|
||||
)
|
||||
.order("desc")
|
||||
.take(MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE + 1);
|
||||
}
|
||||
|
||||
export async function getInProgressRequestForTarget(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
target: RescanTarget,
|
||||
) {
|
||||
if (target.kind === "skill") {
|
||||
return await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_skill_version_status", (q) =>
|
||||
q
|
||||
.eq("targetKind", "skill")
|
||||
.eq("skillVersionId", target.artifactId)
|
||||
.eq("status", ACTIVE_RESCAN_STATUS),
|
||||
)
|
||||
.order("desc")
|
||||
.first();
|
||||
}
|
||||
|
||||
return await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_package_release_status", (q) =>
|
||||
q
|
||||
.eq("targetKind", "plugin")
|
||||
.eq("packageReleaseId", target.artifactId)
|
||||
.eq("status", ACTIVE_RESCAN_STATUS),
|
||||
)
|
||||
.order("desc")
|
||||
.first();
|
||||
}
|
||||
|
||||
export async function assertCanRequestRescan(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
target: RescanTarget,
|
||||
) {
|
||||
const existingInProgress = await getInProgressRequestForTarget(ctx, target);
|
||||
if (existingInProgress) {
|
||||
throw new ConvexError("A rescan request is already in progress for this release");
|
||||
}
|
||||
|
||||
const existingRequests = await listRequestsForTarget(ctx, target);
|
||||
if (existingRequests.length >= MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE) {
|
||||
throw new ConvexError(
|
||||
`Rescan request limit reached for this release (${MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildRescanState(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
target: RescanTarget,
|
||||
) {
|
||||
const requests = await listRequestsForTarget(ctx, target);
|
||||
const inProgressRequest =
|
||||
requests.find((request) => request.status === ACTIVE_RESCAN_STATUS) ?? null;
|
||||
const requestCount = Math.min(requests.length, MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE);
|
||||
return {
|
||||
maxRequests: MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE,
|
||||
requestCount,
|
||||
remainingRequests: Math.max(0, MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE - requestCount),
|
||||
canRequest:
|
||||
requestCount < MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE && inProgressRequest === null,
|
||||
inProgressRequest: serializeRescanRequest(inProgressRequest),
|
||||
latestRequest: serializeRescanRequest(requests[0] ?? null),
|
||||
};
|
||||
}
|
||||
|
||||
async function listInProgressRequestsForTarget(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
target: RescanTarget,
|
||||
) {
|
||||
if (target.kind === "skill") {
|
||||
return await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_skill_version_status", (q) =>
|
||||
q
|
||||
.eq("targetKind", "skill")
|
||||
.eq("skillVersionId", target.artifactId)
|
||||
.eq("status", ACTIVE_RESCAN_STATUS),
|
||||
)
|
||||
.order("desc")
|
||||
.take(MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE);
|
||||
}
|
||||
|
||||
return await ctx.db
|
||||
.query("rescanRequests")
|
||||
.withIndex("by_package_release_status", (q) =>
|
||||
q
|
||||
.eq("targetKind", "plugin")
|
||||
.eq("packageReleaseId", target.artifactId)
|
||||
.eq("status", ACTIVE_RESCAN_STATUS),
|
||||
)
|
||||
.order("desc")
|
||||
.take(MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE);
|
||||
}
|
||||
|
||||
export async function finalizeInProgressRescanRequestsForTarget(
|
||||
ctx: Pick<MutationCtx, "db">,
|
||||
target: RescanTarget,
|
||||
scanState: RescanScanState,
|
||||
) {
|
||||
const requests = await listInProgressRequestsForTarget(ctx, target);
|
||||
const now = Date.now();
|
||||
for (const request of requests) {
|
||||
const status = terminalRequestStatusForScanState(scanState, request.createdAt);
|
||||
if (!status) continue;
|
||||
await ctx.db.patch(request._id, {
|
||||
status,
|
||||
updatedAt: now,
|
||||
completedAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function errorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message.slice(0, 500) : "Unknown rescan dispatch error";
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { ConvexError } from "convex/values";
|
||||
import type { Doc, Id } from "../../_generated/dataModel";
|
||||
import type { MutationCtx, QueryCtx } from "../../_generated/server";
|
||||
import type { OwnedResourceActor } from "../../lib/publishers";
|
||||
|
||||
export async function getLatestSkillRescanTarget(
|
||||
ctx: Pick<QueryCtx | MutationCtx, "db">,
|
||||
skillId: Id<"skills">,
|
||||
) {
|
||||
const skill = await ctx.db.get(skillId);
|
||||
if (!skill || skill.softDeletedAt) throw new ConvexError("Skill not found");
|
||||
if (!skill.latestVersionId) throw new ConvexError("Skill has no published version");
|
||||
const version = await ctx.db.get(skill.latestVersionId);
|
||||
if (!version || version.softDeletedAt) throw new ConvexError("Latest skill version not found");
|
||||
return { skill, version };
|
||||
}
|
||||
|
||||
export async function insertSkillRescanRequest(
|
||||
ctx: Pick<MutationCtx, "db">,
|
||||
actor: OwnedResourceActor,
|
||||
target: {
|
||||
skill: Doc<"skills">;
|
||||
version: Doc<"skillVersions">;
|
||||
},
|
||||
) {
|
||||
const now = Date.now();
|
||||
return await ctx.db.insert("rescanRequests", {
|
||||
targetKind: "skill",
|
||||
skillId: target.skill._id,
|
||||
skillVersionId: target.version._id,
|
||||
targetVersion: target.version.version,
|
||||
requestedByUserId: actor._id,
|
||||
ownerUserId: target.skill.ownerUserId,
|
||||
ownerPublisherId: target.skill.ownerPublisherId,
|
||||
status: "in_progress",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
@@ -956,11 +956,36 @@ describe("packages public queries", () => {
|
||||
expect(result.page.map((entry) => entry.name)).toEqual(["official-demo"]);
|
||||
});
|
||||
|
||||
it("uses the official index for official-only listings without a family filter", async () => {
|
||||
const { ctx, indexNames, paginate } = makeDigestCtx({
|
||||
it("keeps scanning official-only listings without a family filter", async () => {
|
||||
const { ctx } = makeDigestCtx({
|
||||
pages: [
|
||||
{
|
||||
page: [makeDigest("official-late", { isOfficial: true })],
|
||||
page: [makeDigest("noise-1", { isOfficial: false })],
|
||||
isDone: false,
|
||||
continueCursor: "cursor:1",
|
||||
},
|
||||
{
|
||||
page: [makeDigest("noise-2", { isOfficial: false })],
|
||||
isDone: false,
|
||||
continueCursor: "cursor:2",
|
||||
},
|
||||
{
|
||||
page: [makeDigest("noise-3", { isOfficial: false })],
|
||||
isDone: false,
|
||||
continueCursor: "cursor:3",
|
||||
},
|
||||
{
|
||||
page: [makeDigest("noise-4", { isOfficial: false })],
|
||||
isDone: false,
|
||||
continueCursor: "cursor:4",
|
||||
},
|
||||
{
|
||||
page: [makeDigest("noise-5", { isOfficial: false })],
|
||||
isDone: false,
|
||||
continueCursor: "cursor:5",
|
||||
},
|
||||
{
|
||||
page: [makeDigest("official-late", { isOfficial: true, updatedAt: 10 })],
|
||||
isDone: true,
|
||||
continueCursor: "",
|
||||
},
|
||||
@@ -973,8 +998,6 @@ describe("packages public queries", () => {
|
||||
});
|
||||
|
||||
expect(result.page.map((entry) => entry.name)).toEqual(["official-late"]);
|
||||
expect(indexNames).toEqual(["by_active_official_updated"]);
|
||||
expect(paginate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("filters private packages and capability flags in public search", async () => {
|
||||
@@ -1247,60 +1270,6 @@ describe("packages public queries", () => {
|
||||
expect(ctx.db.query).toHaveBeenCalledWith("packageSearchDigest");
|
||||
});
|
||||
|
||||
it("keeps direct package-name matches scoped to the requested family", async () => {
|
||||
const exactPkg = makePackageDoc({
|
||||
_id: "packages:code",
|
||||
name: "demo-plugin",
|
||||
normalizedName: "demo-plugin",
|
||||
family: "code-plugin",
|
||||
});
|
||||
const exactDigest = makeDigest("demo-plugin", {
|
||||
packageId: "packages:code",
|
||||
family: "code-plugin",
|
||||
});
|
||||
const { ctx } = makeDigestCtx({
|
||||
pages: [],
|
||||
exactPackages: [exactPkg],
|
||||
exactDigests: [exactDigest],
|
||||
});
|
||||
|
||||
const result = await searchPublicHandler(ctx, {
|
||||
query: "demo-plugin",
|
||||
family: "bundle-plugin",
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("stops fallback scanning after enough package search matches", async () => {
|
||||
const { ctx, paginate } = makeDigestCtx({
|
||||
pages: [
|
||||
{
|
||||
page: [
|
||||
makeDigest("demo-alpha", { updatedAt: 20 }),
|
||||
makeDigest("demo-beta", { updatedAt: 10 }),
|
||||
],
|
||||
isDone: false,
|
||||
continueCursor: "cursor:1",
|
||||
},
|
||||
{
|
||||
page: [makeDigest("demo-gamma")],
|
||||
isDone: true,
|
||||
continueCursor: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await searchPublicHandler(ctx, {
|
||||
query: "demo",
|
||||
limit: 2,
|
||||
});
|
||||
|
||||
expect(result.map((entry) => entry.package.name)).toEqual(["demo-alpha", "demo-beta"]);
|
||||
expect(paginate).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps spaced queries on the scan path without throwing", async () => {
|
||||
const { ctx } = makeDigestCtx({
|
||||
pages: [
|
||||
@@ -1352,7 +1321,7 @@ describe("packages public queries", () => {
|
||||
expect(ctx.db.query).not.toHaveBeenCalledWith("publisherMembers");
|
||||
});
|
||||
|
||||
it("keeps public list pages to one paginated query per invocation", async () => {
|
||||
it("caps public list scans below the Convex read limit budget", async () => {
|
||||
const { ctx, paginate } = makeDigestCtx({
|
||||
pages: Array.from({ length: 120 }, (_, index) => ({
|
||||
page: [makeDigest(`noise-${index}`, { executesCode: false })],
|
||||
@@ -1367,10 +1336,7 @@ describe("packages public queries", () => {
|
||||
});
|
||||
|
||||
expect(result.page).toEqual([]);
|
||||
expect(result.isDone).toBe(false);
|
||||
expect(result.continueCursor).toBeTruthy();
|
||||
expect(paginate).toHaveBeenCalledTimes(1);
|
||||
expect(paginate).toHaveBeenCalledWith({ cursor: null, numItems: 100 });
|
||||
expect(paginate).toHaveBeenCalledTimes(100);
|
||||
});
|
||||
|
||||
it("caps public search scans below the Convex read limit budget", async () => {
|
||||
@@ -1389,7 +1355,7 @@ describe("packages public queries", () => {
|
||||
});
|
||||
|
||||
expect(result).toEqual([]);
|
||||
expect(paginate).toHaveBeenCalledTimes(5);
|
||||
expect(paginate).toHaveBeenCalledTimes(150);
|
||||
});
|
||||
|
||||
it("uses the official index for no-family official search filters", async () => {
|
||||
@@ -2594,15 +2560,6 @@ describe("packages public queries", () => {
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (table === "rescanRequests") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({
|
||||
take: vi.fn().mockResolvedValue([]),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected table ${table}`);
|
||||
}),
|
||||
},
|
||||
@@ -2868,18 +2825,7 @@ describe("package scan backfill", () => {
|
||||
if (id === "packages:demo") return pkg;
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "rescanRequests") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({
|
||||
take: vi.fn(async () => []),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
throw new Error(`Unexpected query table: ${table}`);
|
||||
}),
|
||||
query: vi.fn(),
|
||||
insert: vi.fn(),
|
||||
patch,
|
||||
replace: vi.fn(),
|
||||
|
||||
@@ -11,19 +11,11 @@ import { ConvexError, v } from "convex/values";
|
||||
import { internal } from "./_generated/api";
|
||||
import type { Doc, Id } from "./_generated/dataModel";
|
||||
import type { ActionCtx, MutationCtx, QueryCtx } from "./_generated/server";
|
||||
import {
|
||||
action,
|
||||
internalAction,
|
||||
internalMutation,
|
||||
internalQuery,
|
||||
mutation,
|
||||
query,
|
||||
} from "./functions";
|
||||
import { action, internalAction, internalMutation, internalQuery, query } from "./functions";
|
||||
import {
|
||||
assertAdmin,
|
||||
assertModerator,
|
||||
getOptionalActiveAuthUserId,
|
||||
requireUser,
|
||||
requireUserFromAction,
|
||||
} from "./lib/access";
|
||||
import { requireGitHubAccountAge } from "./lib/githubAccount";
|
||||
@@ -41,11 +33,7 @@ import {
|
||||
} from "./lib/packageRegistry";
|
||||
import { isPackageBlockedFromPublic, resolvePackageReleaseScanStatus } from "./lib/packageSecurity";
|
||||
import { toPublicPublisher } from "./lib/public";
|
||||
import {
|
||||
assertCanManageOwnedResource,
|
||||
getOwnerPublisher,
|
||||
getPublisherMembership,
|
||||
} from "./lib/publishers";
|
||||
import { getOwnerPublisher, getPublisherMembership } from "./lib/publishers";
|
||||
import {
|
||||
findOversizedPublishFile,
|
||||
getPublishFileSizeError,
|
||||
@@ -55,35 +43,13 @@ import {
|
||||
import { tokenize } from "./lib/searchText";
|
||||
import { hashSkillFiles } from "./lib/skills";
|
||||
import { runStaticPublishScan } from "./lib/staticPublishScan";
|
||||
import { getLatestPackageRescanTarget, insertPackageRescanRequest } from "./model/packages/rescans";
|
||||
import {
|
||||
assertCanRequestRescan,
|
||||
buildRescanState,
|
||||
errorMessage,
|
||||
finalizeInProgressRescanRequestsForTarget,
|
||||
} from "./model/rescans/policy";
|
||||
|
||||
const MAX_PUBLIC_LIST_PAGE_SIZE = 200;
|
||||
const MAX_PACKAGE_SCAN_DOCUMENTS = 30_000;
|
||||
const MAX_PUBLIC_LIST_SCAN_PAGES = 200;
|
||||
const MAX_SEARCH_PAGE_SIZE = 200;
|
||||
const MAX_SEARCH_SCAN_DOCUMENTS = 1_000;
|
||||
const MAX_SEARCH_SCAN_PAGES = 20;
|
||||
const MAX_SEARCH_SCAN_PAGES = 200;
|
||||
const MAX_DIRECT_PACKAGE_SEARCH_CANDIDATES = 20;
|
||||
const INITIAL_PACKAGE_VT_SCAN_DELAY_MS = 30_000;
|
||||
const vtEngineStatsValidator = v.object({
|
||||
malicious: v.optional(v.number()),
|
||||
suspicious: v.optional(v.number()),
|
||||
undetected: v.optional(v.number()),
|
||||
harmless: v.optional(v.number()),
|
||||
});
|
||||
const vtAnalysisValidator = v.object({
|
||||
status: v.string(),
|
||||
verdict: v.optional(v.string()),
|
||||
analysis: v.optional(v.string()),
|
||||
source: v.optional(v.string()),
|
||||
scanner: v.optional(v.string()),
|
||||
engineStats: v.optional(vtEngineStatsValidator),
|
||||
checkedAt: v.number(),
|
||||
});
|
||||
const internalRefs = internal as unknown as {
|
||||
llmEval: {
|
||||
evaluatePackageReleaseWithLlm: unknown;
|
||||
@@ -109,9 +75,6 @@ const internalRefs = internal as unknown as {
|
||||
getByIdInternal: unknown;
|
||||
revokeInternal: unknown;
|
||||
};
|
||||
rescanRequests: {
|
||||
markStatusInternal: unknown;
|
||||
};
|
||||
skills: {
|
||||
getSkillBySlugInternal: unknown;
|
||||
};
|
||||
@@ -282,7 +245,6 @@ type DashboardPackageListItem = {
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
pendingReview?: true;
|
||||
rescanState: Awaited<ReturnType<typeof buildRescanState>> | null;
|
||||
latestRelease: {
|
||||
version: string;
|
||||
createdAt: number;
|
||||
@@ -391,24 +353,6 @@ function digestMatchesFilters(
|
||||
return true;
|
||||
}
|
||||
|
||||
function digestMatchesSearchFilters(
|
||||
digest: PackageDigestLike,
|
||||
args: {
|
||||
family?: PackageFamily;
|
||||
channel?: PackageChannel;
|
||||
isOfficial?: boolean;
|
||||
executesCode?: boolean;
|
||||
capabilityTag?: string;
|
||||
},
|
||||
) {
|
||||
if (args.family && digest.family !== args.family) return false;
|
||||
if (args.channel && digest.channel !== args.channel) return false;
|
||||
if (typeof args.isOfficial === "boolean" && digest.isOfficial !== args.isOfficial) {
|
||||
return false;
|
||||
}
|
||||
return digestMatchesFilters(digest, args);
|
||||
}
|
||||
|
||||
function toPublicPackageListItem(digest: PackageDigestLike): PublicPackageListItem {
|
||||
return {
|
||||
name: digest.name,
|
||||
@@ -453,13 +397,6 @@ async function toDashboardPackageListItem(
|
||||
createdAt: pkg.createdAt,
|
||||
updatedAt: pkg.updatedAt,
|
||||
pendingReview: pkg.scanStatus === "pending" ? true : undefined,
|
||||
rescanState:
|
||||
latestRelease && !latestRelease.softDeletedAt
|
||||
? await buildRescanState(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: latestRelease._id,
|
||||
})
|
||||
: null,
|
||||
latestRelease:
|
||||
latestRelease && !latestRelease.softDeletedAt
|
||||
? {
|
||||
@@ -980,12 +917,12 @@ async function requireTrustedPublisherEditor(
|
||||
pkg: Doc<"packages">,
|
||||
actorUserId: Id<"users">,
|
||||
) {
|
||||
await assertCanManageOwnedResource(ctx, {
|
||||
actor: { _id: actorUserId },
|
||||
ownerUserId: pkg.ownerUserId,
|
||||
ownerPublisherId: pkg.ownerPublisherId,
|
||||
allowPlatformAdmin: false,
|
||||
});
|
||||
if (pkg.ownerUserId === actorUserId) return;
|
||||
if (!pkg.ownerPublisherId) throw new ConvexError("Forbidden");
|
||||
const membership = await getPublisherMembership(ctx, pkg.ownerPublisherId, actorUserId);
|
||||
if (!membership || membership.role === "publisher") {
|
||||
throw new ConvexError("Forbidden");
|
||||
}
|
||||
}
|
||||
|
||||
export const getByName = query({
|
||||
@@ -1208,84 +1145,90 @@ async function listPackagePageImpl(
|
||||
const targetCount = args.paginationOpts.numItems;
|
||||
const collected: PublicPackageListItem[] = [];
|
||||
const decodedCursor = decodePublicPageCursor(args.paginationOpts.cursor);
|
||||
if (decodedCursor.done && decodedCursor.offset === 0) {
|
||||
return { page: collected, isDone: true, continueCursor: "" };
|
||||
}
|
||||
const pageCursor = decodedCursor.cursor;
|
||||
const offset = decodedCursor.offset;
|
||||
const effectivePageSize = Math.min(
|
||||
MAX_PUBLIC_LIST_PAGE_SIZE,
|
||||
Math.max(
|
||||
targetCount,
|
||||
decodedCursor.pageSize ?? 0,
|
||||
offset > 0 ? offset + targetCount : targetCount,
|
||||
),
|
||||
);
|
||||
let cursor = decodedCursor.cursor;
|
||||
let offset = decodedCursor.offset;
|
||||
let pageSize = decodedCursor.pageSize;
|
||||
let done = decodedCursor.done;
|
||||
let loops = 0;
|
||||
let remainingScanBudget = MAX_PACKAGE_SCAN_DOCUMENTS;
|
||||
const family = args.family;
|
||||
const channel = args.channel;
|
||||
const isOfficial = args.isOfficial;
|
||||
|
||||
const builder = args.capabilityTag
|
||||
? buildPackageCapabilityDigestQuery(ctx, {
|
||||
capabilityTag: args.capabilityTag,
|
||||
family,
|
||||
channel,
|
||||
isOfficial,
|
||||
executesCode: args.executesCode,
|
||||
})
|
||||
: buildPackageDigestQuery(ctx, {
|
||||
family,
|
||||
channel,
|
||||
isOfficial,
|
||||
executesCode: args.executesCode,
|
||||
});
|
||||
const page: {
|
||||
page: PackageDigestLike[];
|
||||
isDone: boolean;
|
||||
continueCursor: string;
|
||||
} = await builder.order("desc").paginate({ cursor: pageCursor, numItems: effectivePageSize });
|
||||
for (let index = offset; index < page.page.length; index += 1) {
|
||||
const digest = page.page[index] as PackageDigestLike;
|
||||
if (!(await canViewPackage(digest))) continue;
|
||||
if (channel && digest.channel !== channel) continue;
|
||||
if (typeof isOfficial === "boolean" && digest.isOfficial !== isOfficial) {
|
||||
continue;
|
||||
}
|
||||
if (!digestMatchesFilters(digest, args)) continue;
|
||||
collected.push(toPublicPackageListItem(digest));
|
||||
if (collected.length >= targetCount) {
|
||||
const nextOffset = index + 1;
|
||||
const nextState =
|
||||
nextOffset < page.page.length
|
||||
? {
|
||||
cursor: pageCursor,
|
||||
offset: nextOffset,
|
||||
pageSize: effectivePageSize,
|
||||
done: page.isDone,
|
||||
}
|
||||
: {
|
||||
cursor: page.continueCursor,
|
||||
offset: 0,
|
||||
pageSize: effectivePageSize,
|
||||
done: page.isDone,
|
||||
};
|
||||
return {
|
||||
page: collected,
|
||||
isDone: nextState.done && nextState.offset === 0,
|
||||
continueCursor: encodePublicPageCursor(nextState),
|
||||
};
|
||||
while (
|
||||
(offset > 0 || !done) &&
|
||||
collected.length < targetCount &&
|
||||
loops < MAX_PUBLIC_LIST_SCAN_PAGES &&
|
||||
remainingScanBudget > 0
|
||||
) {
|
||||
loops += 1;
|
||||
const effectivePageSize = Math.min(
|
||||
remainingScanBudget,
|
||||
offset > 0 && pageSize
|
||||
? Math.max(pageSize, offset + 1)
|
||||
: Math.max(targetCount * 3, targetCount),
|
||||
);
|
||||
if (effectivePageSize <= 0) break;
|
||||
remainingScanBudget -= effectivePageSize;
|
||||
const pageCursor = cursor;
|
||||
const builder = args.capabilityTag
|
||||
? buildPackageCapabilityDigestQuery(ctx, {
|
||||
capabilityTag: args.capabilityTag,
|
||||
family,
|
||||
channel,
|
||||
isOfficial,
|
||||
executesCode: args.executesCode,
|
||||
})
|
||||
: buildPackageDigestQuery(ctx, {
|
||||
family,
|
||||
channel,
|
||||
isOfficial,
|
||||
executesCode: args.executesCode,
|
||||
});
|
||||
const page: {
|
||||
page: PackageDigestLike[];
|
||||
isDone: boolean;
|
||||
continueCursor: string;
|
||||
} = await builder.order("desc").paginate({ cursor: pageCursor, numItems: effectivePageSize });
|
||||
for (let index = offset; index < page.page.length; index += 1) {
|
||||
const digest = page.page[index] as PackageDigestLike;
|
||||
if (!(await canViewPackage(digest))) continue;
|
||||
if (channel && digest.channel !== channel) continue;
|
||||
if (typeof isOfficial === "boolean" && digest.isOfficial !== isOfficial) {
|
||||
continue;
|
||||
}
|
||||
if (!digestMatchesFilters(digest, args)) continue;
|
||||
collected.push(toPublicPackageListItem(digest));
|
||||
if (collected.length >= targetCount) {
|
||||
const nextOffset = index + 1;
|
||||
if (nextOffset < page.page.length) {
|
||||
cursor = pageCursor;
|
||||
offset = nextOffset;
|
||||
pageSize = effectivePageSize;
|
||||
done = page.isDone;
|
||||
} else {
|
||||
cursor = page.continueCursor;
|
||||
offset = 0;
|
||||
pageSize = effectivePageSize;
|
||||
done = page.isDone;
|
||||
}
|
||||
return {
|
||||
page: collected,
|
||||
isDone: done && offset === 0,
|
||||
continueCursor: encodePublicPageCursor({ cursor, offset, pageSize, done }),
|
||||
};
|
||||
}
|
||||
}
|
||||
done = page.isDone;
|
||||
cursor = page.continueCursor;
|
||||
offset = 0;
|
||||
pageSize = effectivePageSize;
|
||||
}
|
||||
|
||||
return {
|
||||
page: collected,
|
||||
isDone: page.isDone,
|
||||
continueCursor: encodePublicPageCursor({
|
||||
cursor: page.continueCursor,
|
||||
offset: 0,
|
||||
pageSize: effectivePageSize,
|
||||
done: page.isDone,
|
||||
}),
|
||||
isDone: done,
|
||||
continueCursor: encodePublicPageCursor({ cursor, offset, pageSize, done }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1370,7 +1313,11 @@ async function searchPackagesImpl(
|
||||
: await resolveDirectPackageSearchDigests(ctx, queryText);
|
||||
for (const digest of directDigests) {
|
||||
if (!(await canViewPackage(digest))) continue;
|
||||
if (!digestMatchesSearchFilters(digest, args)) continue;
|
||||
if (args.channel && digest.channel !== args.channel) continue;
|
||||
if (typeof args.isOfficial === "boolean" && digest.isOfficial !== args.isOfficial) {
|
||||
continue;
|
||||
}
|
||||
if (!digestMatchesFilters(digest, args)) continue;
|
||||
const score = packageSearchScore(digest, queryText);
|
||||
if (score <= 0 || seen.has(digest.packageId)) continue;
|
||||
seen.add(digest.packageId);
|
||||
@@ -1385,14 +1332,9 @@ async function searchPackagesImpl(
|
||||
let cursor: string | null = null;
|
||||
let done = false;
|
||||
let loops = 0;
|
||||
let remainingScanBudget = MAX_SEARCH_SCAN_DOCUMENTS;
|
||||
let remainingScanBudget = MAX_PACKAGE_SCAN_DOCUMENTS;
|
||||
|
||||
while (
|
||||
matches.length < targetCount &&
|
||||
!done &&
|
||||
loops < MAX_SEARCH_SCAN_PAGES &&
|
||||
remainingScanBudget > 0
|
||||
) {
|
||||
while (!done && loops < MAX_SEARCH_SCAN_PAGES && remainingScanBudget > 0) {
|
||||
loops += 1;
|
||||
const effectivePageSize = Math.min(pageSize, remainingScanBudget);
|
||||
if (effectivePageSize <= 0) break;
|
||||
@@ -1404,7 +1346,11 @@ async function searchPackagesImpl(
|
||||
} = await builder.order("desc").paginate({ cursor, numItems: effectivePageSize });
|
||||
for (const digest of page.page) {
|
||||
if (!(await canViewPackage(digest))) continue;
|
||||
if (!digestMatchesSearchFilters(digest, args)) continue;
|
||||
if (args.channel && digest.channel !== args.channel) continue;
|
||||
if (typeof args.isOfficial === "boolean" && digest.isOfficial !== args.isOfficial) {
|
||||
continue;
|
||||
}
|
||||
if (!digestMatchesFilters(digest, args)) continue;
|
||||
const score = packageSearchScore(digest, queryText);
|
||||
if (score <= 0 || seen.has(digest.packageId)) continue;
|
||||
seen.add(digest.packageId);
|
||||
@@ -1412,7 +1358,6 @@ async function searchPackagesImpl(
|
||||
score,
|
||||
package: toPublicPackageListItem(digest),
|
||||
});
|
||||
if (matches.length >= targetCount) break;
|
||||
}
|
||||
done = page.isDone;
|
||||
cursor = page.continueCursor;
|
||||
@@ -2201,9 +2146,9 @@ export const insertReleaseInternal = internalMutation({
|
||||
const nextIsOfficial = nextChannel === "official";
|
||||
const nextOwnerPublisherId = stringifyOptionalId(args.ownerPublisherId ?? null);
|
||||
const nextOwnerUserId = stringifyId(args.ownerUserId);
|
||||
const nextNameLabel = typeof args.name === "string" ? args.name : "<unknown>";
|
||||
const nextRuntimeIdLabel = typeof args.runtimeId === "string" ? args.runtimeId : "<unknown>";
|
||||
const nextVersionLabel = typeof args.version === "string" ? args.version : "<unknown>";
|
||||
const nextName = args.name;
|
||||
const nextRuntimeId = args.runtimeId ?? null;
|
||||
const nextVersion = args.version;
|
||||
if (existing) {
|
||||
const existingIsLegacyPersonalPackage =
|
||||
!existing.ownerPublisherId &&
|
||||
@@ -2226,7 +2171,7 @@ export const insertReleaseInternal = internalMutation({
|
||||
}
|
||||
if (existing && existing.family !== args.family) {
|
||||
throw new ConvexError(
|
||||
`Package "${nextNameLabel}" already exists as a ${existing.family}; family changes are not allowed`,
|
||||
`Package "${nextName}" already exists as a ${existing.family}; family changes are not allowed`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
@@ -2237,7 +2182,7 @@ export const insertReleaseInternal = internalMutation({
|
||||
existing.runtimeId !== args.runtimeId
|
||||
) {
|
||||
throw new ConvexError(
|
||||
`Package "${nextNameLabel}" already exists with plugin id "${existing.runtimeId}"; runtime id changes are not allowed`,
|
||||
`Package "${nextName}" already exists with plugin id "${existing.runtimeId}"; runtime id changes are not allowed`,
|
||||
);
|
||||
}
|
||||
if (args.family === "code-plugin" && args.runtimeId) {
|
||||
@@ -2246,9 +2191,7 @@ export const insertReleaseInternal = internalMutation({
|
||||
.withIndex("by_runtime_id", (q) => q.eq("runtimeId", args.runtimeId))
|
||||
.unique();
|
||||
if (runtimeCollision && runtimeCollision._id !== existing?._id) {
|
||||
throw new ConvexError(
|
||||
`Plugin id "${nextRuntimeIdLabel}" is already claimed by another package`,
|
||||
);
|
||||
throw new ConvexError(`Plugin id "${nextRuntimeId}" is already claimed by another package`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2285,7 +2228,7 @@ export const insertReleaseInternal = internalMutation({
|
||||
q.eq("packageId", existing._id).eq("version", args.version),
|
||||
)
|
||||
.unique();
|
||||
if (releaseExists) throw new ConvexError(`Version ${nextVersionLabel} already exists`);
|
||||
if (releaseExists) throw new ConvexError(`Version ${nextVersion} already exists`);
|
||||
}
|
||||
const priorReleases = existing
|
||||
? await ctx.db
|
||||
@@ -2414,7 +2357,15 @@ export const updateReleaseScanResultsInternal = internalMutation({
|
||||
args: {
|
||||
releaseId: v.id("packageReleases"),
|
||||
sha256hash: v.optional(v.string()),
|
||||
vtAnalysis: v.optional(vtAnalysisValidator),
|
||||
vtAnalysis: v.optional(
|
||||
v.object({
|
||||
status: v.string(),
|
||||
verdict: v.optional(v.string()),
|
||||
analysis: v.optional(v.string()),
|
||||
source: v.optional(v.string()),
|
||||
checkedAt: v.number(),
|
||||
}),
|
||||
),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const release = await ctx.db.get(args.releaseId);
|
||||
@@ -2440,16 +2391,10 @@ export const updateReleaseScanResultsInternal = internalMutation({
|
||||
await ctx.db.patch(args.releaseId, patch);
|
||||
}
|
||||
if (args.vtAnalysis !== undefined) {
|
||||
const updatedRelease = {
|
||||
await syncLatestPackageVerification(ctx, {
|
||||
...activeRelease,
|
||||
...patch,
|
||||
} as Doc<"packageReleases">;
|
||||
await syncLatestPackageVerification(ctx, updatedRelease);
|
||||
await finalizeInProgressRescanRequestsForTarget(
|
||||
ctx,
|
||||
{ kind: "plugin", artifactId: args.releaseId },
|
||||
updatedRelease,
|
||||
);
|
||||
} as Doc<"packageReleases">);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -2481,13 +2426,7 @@ export const updateReleaseLlmAnalysisInternal = internalMutation({
|
||||
handler: async (ctx, args) => {
|
||||
const release = await ctx.db.get(args.releaseId);
|
||||
if (!isReleaseActive(release)) return;
|
||||
const updatedRelease = { ...release, llmAnalysis: args.llmAnalysis };
|
||||
await ctx.db.patch(args.releaseId, { llmAnalysis: args.llmAnalysis });
|
||||
await finalizeInProgressRescanRequestsForTarget(
|
||||
ctx,
|
||||
{ kind: "plugin", artifactId: args.releaseId },
|
||||
updatedRelease,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2535,16 +2474,10 @@ export const updateReleaseStaticScanInternal = internalMutation({
|
||||
|
||||
await ctx.db.patch(args.releaseId, patch);
|
||||
|
||||
const updatedRelease = {
|
||||
await syncLatestPackageVerification(ctx, {
|
||||
...activeRelease,
|
||||
...patch,
|
||||
} as Doc<"packageReleases">;
|
||||
await syncLatestPackageVerification(ctx, updatedRelease);
|
||||
await finalizeInProgressRescanRequestsForTarget(
|
||||
ctx,
|
||||
{ kind: "plugin", artifactId: args.releaseId },
|
||||
updatedRelease,
|
||||
);
|
||||
} as Doc<"packageReleases">);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2671,183 +2604,3 @@ export const backfillPackageReleaseScans = action({
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
async function markPackageRescanRequest(
|
||||
ctx: { runMutation: (ref: never, args: never) => Promise<unknown> },
|
||||
requestId: Id<"rescanRequests">,
|
||||
status: "completed" | "failed",
|
||||
error?: string,
|
||||
) {
|
||||
await ctx.runMutation(
|
||||
internalRefs.rescanRequests.markStatusInternal as never,
|
||||
{
|
||||
requestId,
|
||||
status,
|
||||
error,
|
||||
} as never,
|
||||
);
|
||||
}
|
||||
|
||||
export const getRescanState = query({
|
||||
args: {
|
||||
packageId: v.id("packages"),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { user } = await requireUser(ctx);
|
||||
const target = await getLatestPackageRescanTarget(ctx, args.packageId);
|
||||
await assertCanManageOwnedResource(ctx, {
|
||||
actor: user,
|
||||
ownerUserId: target.pkg.ownerUserId,
|
||||
ownerPublisherId: target.pkg.ownerPublisherId,
|
||||
allowPlatformAdmin: true,
|
||||
});
|
||||
return {
|
||||
targetKind: "plugin" as const,
|
||||
targetVersion: target.release.version,
|
||||
packageReleaseId: target.release._id,
|
||||
...(await buildRescanState(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: target.release._id,
|
||||
})),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const getOwnerRescanStateByName = query({
|
||||
args: {
|
||||
name: v.string(),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const viewerUserId = await getOptionalViewerUserId(ctx);
|
||||
if (!viewerUserId) return null;
|
||||
|
||||
const pkg = await getPackageByNormalizedName(ctx, normalizePackageName(args.name));
|
||||
if (!pkg || pkg.softDeletedAt || pkg.family === "skill" || !pkg.latestReleaseId) return null;
|
||||
|
||||
const release = await ctx.db.get(pkg.latestReleaseId);
|
||||
if (!release || release.softDeletedAt) return null;
|
||||
|
||||
const actor = await ctx.db.get(viewerUserId);
|
||||
if (!actor || actor.deletedAt || actor.deactivatedAt) return null;
|
||||
if (actor.role !== "admin") {
|
||||
const canAccess = await viewerCanAccessPackageOwner(ctx, pkg, viewerUserId);
|
||||
if (!canAccess) return null;
|
||||
}
|
||||
|
||||
return {
|
||||
targetKind: "plugin" as const,
|
||||
targetVersion: release.version,
|
||||
packageReleaseId: release._id,
|
||||
...(await buildRescanState(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: release._id,
|
||||
})),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const requestRescan = mutation({
|
||||
args: {
|
||||
packageId: v.id("packages"),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const { user } = await requireUser(ctx);
|
||||
const target = await getLatestPackageRescanTarget(ctx, args.packageId);
|
||||
await assertCanManageOwnedResource(ctx, {
|
||||
actor: user,
|
||||
ownerUserId: target.pkg.ownerUserId,
|
||||
ownerPublisherId: target.pkg.ownerPublisherId,
|
||||
allowPlatformAdmin: true,
|
||||
});
|
||||
await assertCanRequestRescan(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: target.release._id,
|
||||
});
|
||||
|
||||
const requestId = await insertPackageRescanRequest(ctx, user, target);
|
||||
await ctx.scheduler.runAfter(0, internal.packages.dispatchPackageRescanInternal, {
|
||||
requestId,
|
||||
releaseId: target.release._id,
|
||||
});
|
||||
|
||||
return {
|
||||
requestId,
|
||||
...(await buildRescanState(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: target.release._id,
|
||||
})),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const requestRescanForApiTokenInternal = internalMutation({
|
||||
args: {
|
||||
actorUserId: v.id("users"),
|
||||
name: v.string(),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const actor = await ctx.db.get(args.actorUserId);
|
||||
if (!actor || actor.deletedAt || actor.deactivatedAt) throw new ConvexError("Unauthorized");
|
||||
|
||||
const pkg = await getPackageByNormalizedName(ctx, normalizePackageName(args.name));
|
||||
if (!pkg || pkg.softDeletedAt || pkg.family === "skill") {
|
||||
throw new ConvexError("Plugin not found");
|
||||
}
|
||||
|
||||
const target = await getLatestPackageRescanTarget(ctx, pkg._id);
|
||||
await assertCanManageOwnedResource(ctx, {
|
||||
actor,
|
||||
ownerUserId: target.pkg.ownerUserId,
|
||||
ownerPublisherId: target.pkg.ownerPublisherId,
|
||||
allowPlatformAdmin: true,
|
||||
});
|
||||
await assertCanRequestRescan(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: target.release._id,
|
||||
});
|
||||
|
||||
const requestId = await insertPackageRescanRequest(ctx, actor, target);
|
||||
await ctx.scheduler.runAfter(0, internal.packages.dispatchPackageRescanInternal, {
|
||||
requestId,
|
||||
releaseId: target.release._id,
|
||||
});
|
||||
|
||||
const state = await buildRescanState(ctx, {
|
||||
kind: "plugin",
|
||||
artifactId: target.release._id,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
targetKind: "package" as const,
|
||||
name: target.pkg.normalizedName,
|
||||
version: target.release.version,
|
||||
status: state.inProgressRequest?.status ?? state.latestRequest?.status ?? "in_progress",
|
||||
remainingRequests: state.remainingRequests,
|
||||
maxRequests: state.maxRequests,
|
||||
pendingRequestId: requestId,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const dispatchPackageRescanInternal = internalAction({
|
||||
args: {
|
||||
requestId: v.id("rescanRequests"),
|
||||
releaseId: v.id("packageReleases"),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
try {
|
||||
await runActionRef(ctx, internalRefs.packages.scanPackageReleaseStaticallyInternal, {
|
||||
releaseId: args.releaseId,
|
||||
});
|
||||
await runActionRef(ctx, internalRefs.vt.scanPackageReleaseWithVirusTotal, {
|
||||
releaseId: args.releaseId,
|
||||
});
|
||||
await runActionRef(ctx, internalRefs.llmEval.evaluatePackageReleaseWithLlm, {
|
||||
releaseId: args.releaseId,
|
||||
});
|
||||
} catch (error) {
|
||||
await markPackageRescanRequest(ctx, args.requestId, "failed", errorMessage(error));
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { getAuthUserId } from "@convex-dev/auth/server";
|
||||
import { ConvexError, v } from "convex/values";
|
||||
import type { Doc, Id } from "./_generated/dataModel";
|
||||
import type { MutationCtx } from "./_generated/server";
|
||||
import { internalMutation, internalQuery, mutation, query } from "./functions";
|
||||
import { assertAdmin, getOptionalActiveAuthUserId, requireUser } from "./lib/access";
|
||||
import { assertAdmin, requireUser } from "./lib/access";
|
||||
import { toPublicPublisher } from "./lib/public";
|
||||
import {
|
||||
ensurePersonalPublisherForUser,
|
||||
@@ -403,7 +404,7 @@ export const resolvePublishTargetForUserInternal = internalMutation({
|
||||
export const listMine = query({
|
||||
args: {},
|
||||
handler: async (ctx) => {
|
||||
const userId = await getOptionalActiveAuthUserId(ctx);
|
||||
const userId = await getAuthUserId(ctx);
|
||||
if (!userId) return [];
|
||||
const user = await ctx.db.get(userId);
|
||||
if (!user || user.deletedAt || user.deactivatedAt) return [];
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { v } from "convex/values";
|
||||
import { internalMutation } from "./functions";
|
||||
|
||||
export const markStatusInternal = internalMutation({
|
||||
args: {
|
||||
requestId: v.id("rescanRequests"),
|
||||
status: v.union(v.literal("completed"), v.literal("failed")),
|
||||
error: v.optional(v.string()),
|
||||
},
|
||||
handler: async (ctx, args) => {
|
||||
const now = Date.now();
|
||||
await ctx.db.patch(args.requestId, {
|
||||
status: args.status,
|
||||
error: args.error,
|
||||
updatedAt: now,
|
||||
completedAt: now,
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -1,515 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
dispatchPackageRescanInternal,
|
||||
requestRescan as requestPackageRescan,
|
||||
} from "./packages";
|
||||
import {
|
||||
dispatchSkillRescanInternal,
|
||||
getRescanState as getSkillRescanState,
|
||||
requestRescan as requestSkillRescan,
|
||||
} from "./skills";
|
||||
import { requireUser } from "./lib/access";
|
||||
import {
|
||||
finalizeInProgressRescanRequestsForTarget,
|
||||
MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE,
|
||||
} from "./model/rescans/policy";
|
||||
|
||||
vi.mock("./lib/access", () => ({
|
||||
requireUser: vi.fn(),
|
||||
}));
|
||||
|
||||
type WrappedHandler<TArgs, TResult = unknown> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<TResult>;
|
||||
};
|
||||
|
||||
const requestSkillRescanHandler = (
|
||||
requestSkillRescan as unknown as WrappedHandler<{ skillId: string }>
|
||||
)._handler;
|
||||
const requestPackageRescanHandler = (
|
||||
requestPackageRescan as unknown as WrappedHandler<{ packageId: string }>
|
||||
)._handler;
|
||||
const getSkillRescanStateHandler = (
|
||||
getSkillRescanState as unknown as WrappedHandler<{ skillId: string }>
|
||||
)._handler;
|
||||
const dispatchSkillRescanHandler = (
|
||||
dispatchSkillRescanInternal as unknown as WrappedHandler<{
|
||||
requestId: string;
|
||||
skillId: string;
|
||||
versionId: string;
|
||||
}>
|
||||
)._handler;
|
||||
const dispatchPackageRescanHandler = (
|
||||
dispatchPackageRescanInternal as unknown as WrappedHandler<{
|
||||
requestId: string;
|
||||
releaseId: string;
|
||||
}>
|
||||
)._handler;
|
||||
|
||||
type RescanRequest = {
|
||||
_id: string;
|
||||
targetKind: "skill" | "plugin";
|
||||
skillId?: string;
|
||||
skillVersionId?: string;
|
||||
packageId?: string;
|
||||
packageReleaseId?: string;
|
||||
targetVersion: string;
|
||||
requestedByUserId: string;
|
||||
ownerUserId: string;
|
||||
ownerPublisherId?: string;
|
||||
status: "in_progress" | "completed" | "failed";
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
completedAt?: number;
|
||||
};
|
||||
|
||||
function chainEq(constraints: Record<string, unknown>) {
|
||||
return {
|
||||
eq(field: string, value: unknown) {
|
||||
constraints[field] = value;
|
||||
return chainEq(constraints);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function matches(doc: Record<string, unknown>, constraints: Record<string, unknown>) {
|
||||
return Object.entries(constraints).every(([key, value]) => doc[key] === value);
|
||||
}
|
||||
|
||||
function createDb(options?: {
|
||||
requests?: RescanRequest[];
|
||||
userRole?: "admin" | "moderator" | "user";
|
||||
ownerPublisherId?: string;
|
||||
membershipRole?: "owner" | "admin" | "publisher";
|
||||
skillLatestVersionId?: string;
|
||||
packageLatestReleaseId?: string;
|
||||
skillSoftDeletedAt?: number;
|
||||
skillVersionSoftDeletedAt?: number;
|
||||
packageSoftDeletedAt?: number;
|
||||
packageReleaseSoftDeletedAt?: number;
|
||||
}) {
|
||||
const requests = [...(options?.requests ?? [])];
|
||||
const skill = {
|
||||
_id: "skills:1",
|
||||
slug: "flagged-skill",
|
||||
ownerUserId: "users:owner",
|
||||
ownerPublisherId: options?.ownerPublisherId,
|
||||
latestVersionId: options?.skillLatestVersionId ?? "skillVersions:latest",
|
||||
softDeletedAt: options?.skillSoftDeletedAt,
|
||||
};
|
||||
const version = {
|
||||
_id: "skillVersions:latest",
|
||||
skillId: "skills:1",
|
||||
version: "1.2.3",
|
||||
softDeletedAt: options?.skillVersionSoftDeletedAt,
|
||||
};
|
||||
const pkg = {
|
||||
_id: "packages:1",
|
||||
name: "flagged-plugin",
|
||||
family: "code-plugin",
|
||||
ownerUserId: "users:owner",
|
||||
ownerPublisherId: options?.ownerPublisherId,
|
||||
latestReleaseId: options?.packageLatestReleaseId ?? "packageReleases:latest",
|
||||
softDeletedAt: options?.packageSoftDeletedAt,
|
||||
};
|
||||
const release = {
|
||||
_id: "packageReleases:latest",
|
||||
packageId: "packages:1",
|
||||
version: "2.0.0",
|
||||
softDeletedAt: options?.packageReleaseSoftDeletedAt,
|
||||
};
|
||||
const actor = {
|
||||
_id: "users:actor",
|
||||
role: options?.userRole ?? "user",
|
||||
deletedAt: undefined,
|
||||
deactivatedAt: undefined,
|
||||
};
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "skills:1") return skill;
|
||||
if (id === "skillVersions:latest") return version;
|
||||
if (id === "packages:1") return pkg;
|
||||
if (id === "packageReleases:latest") return release;
|
||||
if (id === "users:actor") return actor;
|
||||
return null;
|
||||
}),
|
||||
insert: vi.fn(async (table: string, doc: Omit<RescanRequest, "_id">) => {
|
||||
if (table !== "rescanRequests") throw new Error(`unexpected insert ${table}`);
|
||||
const inserted = {
|
||||
_id: `rescanRequests:${requests.length + 1}`,
|
||||
...doc,
|
||||
} as RescanRequest;
|
||||
requests.push(inserted);
|
||||
return inserted._id;
|
||||
}),
|
||||
patch: vi.fn(async (id: string, patch: Partial<RescanRequest>) => {
|
||||
const request = requests.find((candidate) => candidate._id === id);
|
||||
if (request) Object.assign(request, patch);
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "publisherMembers") {
|
||||
return {
|
||||
withIndex: (name: string, build: (q: ReturnType<typeof chainEq>) => unknown) => {
|
||||
if (name !== "by_publisher_user") throw new Error(`unexpected index ${name}`);
|
||||
const constraints: Record<string, unknown> = {};
|
||||
build(chainEq(constraints));
|
||||
return {
|
||||
unique: async () =>
|
||||
options?.membershipRole
|
||||
? {
|
||||
publisherId: constraints.publisherId,
|
||||
userId: constraints.userId,
|
||||
role: options.membershipRole,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table !== "rescanRequests") throw new Error(`unexpected table ${table}`);
|
||||
return {
|
||||
withIndex: (_name: string, build: (q: ReturnType<typeof chainEq>) => unknown) => {
|
||||
const constraints: Record<string, unknown> = {};
|
||||
build(chainEq(constraints));
|
||||
const matched = requests
|
||||
.filter((request) => matches(request as unknown as Record<string, unknown>, constraints))
|
||||
.sort((a, b) => b.createdAt - a.createdAt);
|
||||
return {
|
||||
order: () => ({
|
||||
take: async (limit: number) => matched.slice(0, limit),
|
||||
first: async () => matched[0] ?? null,
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
}),
|
||||
normalizeId: vi.fn((table: string, id: string) => (id.startsWith(`${table}:`) ? id : null)),
|
||||
};
|
||||
|
||||
return { db, requests };
|
||||
}
|
||||
|
||||
function createRequest(overrides?: Partial<RescanRequest>): RescanRequest {
|
||||
return {
|
||||
_id: "rescanRequests:existing",
|
||||
targetKind: "skill",
|
||||
skillId: "skills:1",
|
||||
skillVersionId: "skillVersions:latest",
|
||||
targetVersion: "1.2.3",
|
||||
requestedByUserId: "users:owner",
|
||||
ownerUserId: "users:owner",
|
||||
status: "completed",
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(requireUser).mockReset();
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: "users:owner",
|
||||
user: { _id: "users:owner", role: "user" },
|
||||
} as never);
|
||||
});
|
||||
|
||||
describe("rescan requests", () => {
|
||||
it("returns owner-visible state for the latest skill version", async () => {
|
||||
const { db } = createDb({
|
||||
requests: [
|
||||
createRequest({ _id: "rescanRequests:1", status: "completed", createdAt: 1 }),
|
||||
createRequest({ _id: "rescanRequests:2", status: "failed", createdAt: 2 }),
|
||||
],
|
||||
});
|
||||
|
||||
const result = await getSkillRescanStateHandler({ db } as never, {
|
||||
skillId: "skills:1",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
targetKind: "skill",
|
||||
targetVersion: "1.2.3",
|
||||
maxRequests: MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE,
|
||||
requestCount: 2,
|
||||
remainingRequests: 1,
|
||||
canRequest: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a skill rescan request and schedules dispatch", async () => {
|
||||
const { db, requests } = createDb();
|
||||
const scheduler = { runAfter: vi.fn(async () => undefined) };
|
||||
|
||||
const result = await requestSkillRescanHandler({ db, scheduler } as never, {
|
||||
skillId: "skills:1",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
requestId: "rescanRequests:1",
|
||||
remainingRequests: 2,
|
||||
});
|
||||
expect(requests[0]).toMatchObject({
|
||||
targetKind: "skill",
|
||||
skillId: "skills:1",
|
||||
skillVersionId: "skillVersions:latest",
|
||||
status: "in_progress",
|
||||
targetVersion: "1.2.3",
|
||||
});
|
||||
expect(scheduler.runAfter).toHaveBeenCalledWith(
|
||||
0,
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
requestId: "rescanRequests:1",
|
||||
skillId: "skills:1",
|
||||
versionId: "skillVersions:latest",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a plugin rescan request against the latest release", async () => {
|
||||
const { db, requests } = createDb();
|
||||
const scheduler = { runAfter: vi.fn(async () => undefined) };
|
||||
|
||||
await requestPackageRescanHandler({ db, scheduler } as never, {
|
||||
packageId: "packages:1",
|
||||
});
|
||||
|
||||
expect(requests[0]).toMatchObject({
|
||||
targetKind: "plugin",
|
||||
packageId: "packages:1",
|
||||
packageReleaseId: "packageReleases:latest",
|
||||
status: "in_progress",
|
||||
targetVersion: "2.0.0",
|
||||
});
|
||||
expect(scheduler.runAfter).toHaveBeenCalledWith(
|
||||
0,
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
requestId: "rescanRequests:1",
|
||||
releaseId: "packageReleases:latest",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects duplicate in-progress requests for the same release", async () => {
|
||||
const { db } = createDb({
|
||||
requests: [createRequest({ status: "in_progress" })],
|
||||
});
|
||||
|
||||
await expect(
|
||||
requestSkillRescanHandler({ db, scheduler: { runAfter: vi.fn() } } as never, {
|
||||
skillId: "skills:1",
|
||||
}),
|
||||
).rejects.toThrow("already in progress");
|
||||
});
|
||||
|
||||
it("enforces the per-release rescan cap", async () => {
|
||||
const { db } = createDb({
|
||||
requests: Array.from({ length: MAX_OWNER_RESCAN_REQUESTS_PER_RELEASE }, (_, index) =>
|
||||
createRequest({
|
||||
_id: `rescanRequests:${index}`,
|
||||
status: "completed",
|
||||
createdAt: index,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
await expect(
|
||||
requestSkillRescanHandler({ db, scheduler: { runAfter: vi.fn() } } as never, {
|
||||
skillId: "skills:1",
|
||||
}),
|
||||
).rejects.toThrow("Rescan request limit reached");
|
||||
});
|
||||
|
||||
it("rejects non-owners", async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: "users:actor",
|
||||
user: { _id: "users:actor", role: "user" },
|
||||
} as never);
|
||||
const { db } = createDb();
|
||||
|
||||
await expect(
|
||||
requestSkillRescanHandler({ db, scheduler: { runAfter: vi.fn() } } as never, {
|
||||
skillId: "skills:1",
|
||||
}),
|
||||
).rejects.toThrow("Forbidden");
|
||||
});
|
||||
|
||||
it("lets org admins request owner rescans", async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: "users:actor",
|
||||
user: { _id: "users:actor", role: "user" },
|
||||
} as never);
|
||||
const { db } = createDb({
|
||||
ownerPublisherId: "publishers:org",
|
||||
membershipRole: "admin",
|
||||
});
|
||||
|
||||
await expect(
|
||||
requestSkillRescanHandler({ db, scheduler: { runAfter: vi.fn() } } as never, {
|
||||
skillId: "skills:1",
|
||||
}),
|
||||
).resolves.toMatchObject({ requestId: "rescanRequests:1" });
|
||||
});
|
||||
|
||||
it("rejects publisher-only org members", async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: "users:actor",
|
||||
user: { _id: "users:actor", role: "user" },
|
||||
} as never);
|
||||
const { db } = createDb({
|
||||
ownerPublisherId: "publishers:org",
|
||||
membershipRole: "publisher",
|
||||
});
|
||||
|
||||
await expect(
|
||||
requestSkillRescanHandler({ db, scheduler: { runAfter: vi.fn() } } as never, {
|
||||
skillId: "skills:1",
|
||||
}),
|
||||
).rejects.toThrow("Forbidden");
|
||||
});
|
||||
|
||||
it("lets admins request owner rescans", async () => {
|
||||
vi.mocked(requireUser).mockResolvedValue({
|
||||
userId: "users:admin",
|
||||
user: { _id: "users:admin", role: "admin" },
|
||||
} as never);
|
||||
const { db } = createDb();
|
||||
|
||||
await expect(
|
||||
requestSkillRescanHandler({ db, scheduler: { runAfter: vi.fn() } } as never, {
|
||||
skillId: "skills:1",
|
||||
}),
|
||||
).resolves.toMatchObject({ requestId: "rescanRequests:1" });
|
||||
});
|
||||
|
||||
it("rejects missing or soft-deleted skill targets", async () => {
|
||||
const softDeletedSkill = createDb({ skillSoftDeletedAt: 123 });
|
||||
await expect(
|
||||
requestSkillRescanHandler(
|
||||
{ db: softDeletedSkill.db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{ skillId: "skills:1" },
|
||||
),
|
||||
).rejects.toThrow("Skill not found");
|
||||
|
||||
const softDeletedVersion = createDb({ skillVersionSoftDeletedAt: 123 });
|
||||
await expect(
|
||||
requestSkillRescanHandler(
|
||||
{ db: softDeletedVersion.db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{ skillId: "skills:1" },
|
||||
),
|
||||
).rejects.toThrow("Latest skill version not found");
|
||||
});
|
||||
|
||||
it("rejects missing or soft-deleted plugin targets", async () => {
|
||||
const softDeletedPackage = createDb({ packageSoftDeletedAt: 123 });
|
||||
await expect(
|
||||
requestPackageRescanHandler(
|
||||
{ db: softDeletedPackage.db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{ packageId: "packages:1" },
|
||||
),
|
||||
).rejects.toThrow("Plugin not found");
|
||||
|
||||
const softDeletedRelease = createDb({ packageReleaseSoftDeletedAt: 123 });
|
||||
await expect(
|
||||
requestPackageRescanHandler(
|
||||
{ db: softDeletedRelease.db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{ packageId: "packages:1" },
|
||||
),
|
||||
).rejects.toThrow("Latest plugin release not found");
|
||||
});
|
||||
|
||||
it("dispatches skill rescans through each existing scanner without completing early", async () => {
|
||||
const runAction = vi.fn(async () => undefined);
|
||||
const runMutation = vi.fn(async () => undefined);
|
||||
|
||||
await dispatchSkillRescanHandler({ runAction, runMutation } as never, {
|
||||
requestId: "rescanRequests:1",
|
||||
skillId: "skills:1",
|
||||
versionId: "skillVersions:latest",
|
||||
});
|
||||
|
||||
expect(runAction).toHaveBeenCalledTimes(3);
|
||||
expect(runAction).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ skillId: "skills:1", versionId: "skillVersions:latest" }),
|
||||
);
|
||||
expect(runAction).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ versionId: "skillVersions:latest" }),
|
||||
);
|
||||
expect(runAction).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ versionId: "skillVersions:latest" }),
|
||||
);
|
||||
expect(runMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("dispatches plugin rescans through each existing scanner without completing early", async () => {
|
||||
const runAction = vi.fn(async () => undefined);
|
||||
const runMutation = vi.fn(async () => undefined);
|
||||
|
||||
await dispatchPackageRescanHandler({ runAction, runMutation } as never, {
|
||||
requestId: "rescanRequests:1",
|
||||
releaseId: "packageReleases:latest",
|
||||
});
|
||||
|
||||
expect(runAction).toHaveBeenCalledTimes(3);
|
||||
expect(runAction).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ releaseId: "packageReleases:latest" }),
|
||||
);
|
||||
expect(runAction).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ releaseId: "packageReleases:latest" }),
|
||||
);
|
||||
expect(runAction).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ releaseId: "packageReleases:latest" }),
|
||||
);
|
||||
expect(runMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("completes in-progress rescans when all scanner results are fresh", async () => {
|
||||
const { db, requests } = createDb({
|
||||
requests: [createRequest({ status: "in_progress", createdAt: 100 })],
|
||||
});
|
||||
|
||||
await finalizeInProgressRescanRequestsForTarget(
|
||||
{ db } as never,
|
||||
{ kind: "skill", artifactId: "skillVersions:latest" as never },
|
||||
{
|
||||
staticScan: { status: "clean", checkedAt: 101 },
|
||||
vtAnalysis: { status: "clean", checkedAt: 102 },
|
||||
llmAnalysis: { status: "benign", checkedAt: 103 },
|
||||
},
|
||||
);
|
||||
|
||||
expect(requests[0]).toMatchObject({ status: "completed" });
|
||||
expect(requests[0].completedAt).toEqual(expect.any(Number));
|
||||
});
|
||||
|
||||
it("keeps in-progress rescans open while VT only has old results", async () => {
|
||||
const { db, requests } = createDb({
|
||||
requests: [createRequest({ status: "in_progress", createdAt: 100 })],
|
||||
});
|
||||
|
||||
await finalizeInProgressRescanRequestsForTarget(
|
||||
{ db } as never,
|
||||
{ kind: "skill", artifactId: "skillVersions:latest" as never },
|
||||
{
|
||||
staticScan: { status: "clean", checkedAt: 101 },
|
||||
vtAnalysis: { status: "clean", checkedAt: 99 },
|
||||
llmAnalysis: { status: "benign", checkedAt: 103 },
|
||||
},
|
||||
);
|
||||
|
||||
expect(requests[0]).toMatchObject({ status: "in_progress" });
|
||||
});
|
||||
});
|
||||
@@ -12,23 +12,6 @@ const manualModerationOverride = v.object({
|
||||
updatedAt: v.number(),
|
||||
});
|
||||
|
||||
const vtEngineStatsValidator = v.object({
|
||||
malicious: v.optional(v.number()),
|
||||
suspicious: v.optional(v.number()),
|
||||
undetected: v.optional(v.number()),
|
||||
harmless: v.optional(v.number()),
|
||||
});
|
||||
|
||||
const vtAnalysisValidator = v.object({
|
||||
status: v.string(),
|
||||
verdict: v.optional(v.string()),
|
||||
analysis: v.optional(v.string()),
|
||||
source: v.optional(v.string()),
|
||||
scanner: v.optional(v.string()),
|
||||
engineStats: v.optional(vtEngineStatsValidator),
|
||||
checkedAt: v.number(),
|
||||
});
|
||||
|
||||
const users = defineTable({
|
||||
name: v.optional(v.string()),
|
||||
image: v.optional(v.string()),
|
||||
@@ -112,22 +95,10 @@ const badgesValidator = v.optional(
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* Nested stat fields on the `skills` document.
|
||||
*
|
||||
* The four migrated fields below are kept for backward compatibility only.
|
||||
* Always use the top-level fields (`statsDownloads`, `statsStars`,
|
||||
* `statsInstallsCurrent`, `statsInstallsAllTime`) as the source of truth,
|
||||
* and use `readCanonicalStat()` / `applySkillStatDeltas()` to read/write them.
|
||||
*/
|
||||
const statsValidator = v.object({
|
||||
/** @deprecated Use top-level `statsDownloads` instead. */
|
||||
downloads: v.number(),
|
||||
/** @deprecated Use top-level `statsInstallsCurrent` instead. */
|
||||
installsCurrent: v.optional(v.number()),
|
||||
/** @deprecated Use top-level `statsInstallsAllTime` instead. */
|
||||
installsAllTime: v.optional(v.number()),
|
||||
/** @deprecated Use top-level `statsStars` instead. */
|
||||
stars: v.number(),
|
||||
versions: v.number(),
|
||||
comments: v.number(),
|
||||
@@ -446,7 +417,15 @@ const skillVersions = defineTable({
|
||||
createdAt: v.number(),
|
||||
softDeletedAt: v.optional(v.number()),
|
||||
sha256hash: v.optional(v.string()),
|
||||
vtAnalysis: v.optional(vtAnalysisValidator),
|
||||
vtAnalysis: v.optional(
|
||||
v.object({
|
||||
status: v.string(),
|
||||
verdict: v.optional(v.string()),
|
||||
analysis: v.optional(v.string()),
|
||||
source: v.optional(v.string()),
|
||||
checkedAt: v.number(),
|
||||
}),
|
||||
),
|
||||
llmAnalysis: v.optional(
|
||||
v.object({
|
||||
status: v.string(),
|
||||
@@ -713,7 +692,15 @@ const packageReleases = defineTable({
|
||||
capabilities: packageCapabilitiesValidator,
|
||||
verification: packageVerificationValidator,
|
||||
sha256hash: v.optional(v.string()),
|
||||
vtAnalysis: v.optional(vtAnalysisValidator),
|
||||
vtAnalysis: v.optional(
|
||||
v.object({
|
||||
status: v.string(),
|
||||
verdict: v.optional(v.string()),
|
||||
analysis: v.optional(v.string()),
|
||||
source: v.optional(v.string()),
|
||||
checkedAt: v.number(),
|
||||
}),
|
||||
),
|
||||
llmAnalysis: v.optional(
|
||||
v.object({
|
||||
status: v.string(),
|
||||
@@ -1200,33 +1187,6 @@ const vtScanLogs = defineTable({
|
||||
createdAt: v.number(),
|
||||
}).index("by_type_date", ["type", "createdAt"]);
|
||||
|
||||
const rescanRequests = defineTable({
|
||||
targetKind: v.union(v.literal("skill"), v.literal("plugin")),
|
||||
skillId: v.optional(v.id("skills")),
|
||||
skillVersionId: v.optional(v.id("skillVersions")),
|
||||
packageId: v.optional(v.id("packages")),
|
||||
packageReleaseId: v.optional(v.id("packageReleases")),
|
||||
targetVersion: v.string(),
|
||||
requestedByUserId: v.id("users"),
|
||||
ownerUserId: v.id("users"),
|
||||
ownerPublisherId: v.optional(v.id("publishers")),
|
||||
status: v.union(v.literal("in_progress"), v.literal("completed"), v.literal("failed")),
|
||||
error: v.optional(v.string()),
|
||||
createdAt: v.number(),
|
||||
updatedAt: v.number(),
|
||||
completedAt: v.optional(v.number()),
|
||||
})
|
||||
.index("by_skill_version", ["targetKind", "skillVersionId", "createdAt"])
|
||||
.index("by_skill_version_status", ["targetKind", "skillVersionId", "status", "createdAt"])
|
||||
.index("by_package_release", ["targetKind", "packageReleaseId", "createdAt"])
|
||||
.index("by_package_release_status", [
|
||||
"targetKind",
|
||||
"packageReleaseId",
|
||||
"status",
|
||||
"createdAt",
|
||||
])
|
||||
.index("by_requester", ["requestedByUserId", "createdAt"]);
|
||||
|
||||
const apiTokens = defineTable({
|
||||
userId: v.id("users"),
|
||||
label: v.string(),
|
||||
@@ -1388,7 +1348,6 @@ export default defineSchema({
|
||||
soulStars,
|
||||
auditLogs,
|
||||
vtScanLogs,
|
||||
rescanRequests,
|
||||
apiTokens,
|
||||
rateLimits,
|
||||
downloadDedupes,
|
||||
|
||||
@@ -17,16 +17,14 @@ vi.mock("./lib/badges", () => ({
|
||||
Boolean(skill.badges?.highlighted),
|
||||
}));
|
||||
|
||||
type WrappedHandler<Result = { skill: { slug: string; _id: string } }> = {
|
||||
_handler: (ctx: unknown, args: unknown) => Promise<Array<Result>>;
|
||||
type WrappedHandler = {
|
||||
_handler: (
|
||||
ctx: unknown,
|
||||
args: unknown,
|
||||
) => Promise<Array<{ skill: { slug: string; _id: string } }>>;
|
||||
};
|
||||
|
||||
const searchSkillsHandler = (
|
||||
searchSkills as unknown as WrappedHandler<{
|
||||
skill: { slug: string; _id: string };
|
||||
score: number;
|
||||
}>
|
||||
)._handler;
|
||||
const searchSkillsHandler = (searchSkills as unknown as WrappedHandler)._handler;
|
||||
const lexicalFallbackSkillsHandler = (lexicalFallbackSkills as unknown as WrappedHandler)._handler;
|
||||
const hydrateResultsHandler = (
|
||||
hydrateResults as unknown as {
|
||||
@@ -67,39 +65,6 @@ describe("search helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to lexical skill search when embedding generation fails", async () => {
|
||||
generateEmbeddingMock.mockRejectedValueOnce(new Error("API unavailable"));
|
||||
const fallback = [
|
||||
{
|
||||
skill: makePublicSkill({ id: "skills:orf", slug: "orf", displayName: "ORF" }),
|
||||
version: null,
|
||||
ownerHandle: "steipete",
|
||||
owner: null,
|
||||
},
|
||||
];
|
||||
const vectorSearch = vi.fn().mockRejectedValue(new Error("should not be called"));
|
||||
const runQuery = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(null) // getExactSkillSlugMatch
|
||||
.mockResolvedValueOnce(fallback); // lexicalFallbackSkills
|
||||
|
||||
const result = await searchSkillsHandler(
|
||||
{
|
||||
vectorSearch,
|
||||
runQuery,
|
||||
},
|
||||
{ query: "orf", limit: 10 },
|
||||
);
|
||||
|
||||
expect(vectorSearch).not.toHaveBeenCalled();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].skill.slug).toBe("orf");
|
||||
expect(runQuery).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ query: "orf", queryTokens: ["orf"] }),
|
||||
);
|
||||
});
|
||||
|
||||
it("applies highlightedOnly filtering in lexical fallback", async () => {
|
||||
const highlighted = {
|
||||
...makeSkillDoc({
|
||||
@@ -248,7 +213,7 @@ describe("search helpers", () => {
|
||||
skill: makePublicSkill({
|
||||
id: `skills:${index}`,
|
||||
slug: `downloader-${index}`,
|
||||
displayName: `Skill Downloader ${index}`,
|
||||
displayName: `Downloader ${index}`,
|
||||
downloads: 100 - index,
|
||||
}),
|
||||
version: null,
|
||||
@@ -275,12 +240,14 @@ describe("search helpers", () => {
|
||||
|
||||
const result = await searchSkillsHandler(
|
||||
{
|
||||
vectorSearch: vi.fn().mockResolvedValue(
|
||||
vectorEntries.map((entry, index) => ({
|
||||
_id: entry.embeddingId,
|
||||
_score: 0.9 - index * 0.01,
|
||||
})),
|
||||
),
|
||||
vectorSearch: vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
vectorEntries.map((entry, index) => ({
|
||||
_id: entry.embeddingId,
|
||||
_score: 0.9 - index * 0.01,
|
||||
})),
|
||||
),
|
||||
runQuery,
|
||||
},
|
||||
{ query: "skill-downloader", limit: 10 },
|
||||
@@ -300,7 +267,7 @@ describe("search helpers", () => {
|
||||
skill: makePublicSkill({
|
||||
id: "skills:1",
|
||||
slug: "downloader-1",
|
||||
displayName: "Skill Downloader 1",
|
||||
displayName: "Downloader 1",
|
||||
downloads: 50,
|
||||
}),
|
||||
version: null,
|
||||
@@ -349,7 +316,7 @@ describe("search helpers", () => {
|
||||
...makePublicSkill({
|
||||
id: "skills:1",
|
||||
slug: "downloader-1",
|
||||
displayName: "Skill Downloader 1",
|
||||
displayName: "Downloader 1",
|
||||
downloads: 50,
|
||||
}),
|
||||
badges: { highlighted: { byUserId: "users:mod", at: 1 } },
|
||||
@@ -455,7 +422,7 @@ describe("search helpers", () => {
|
||||
skill: makePublicSkill({
|
||||
id: "skills:other",
|
||||
slug: "downloader-2",
|
||||
displayName: "Skill Downloader 2",
|
||||
displayName: "Downloader 2",
|
||||
downloads: 50,
|
||||
}),
|
||||
version: null,
|
||||
@@ -663,50 +630,6 @@ describe("search helpers", () => {
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("finds recently created skills missed by the updatedAt fallback scan (#1185)", async () => {
|
||||
const newSkill = makeSkillDoc({
|
||||
id: "skills:new",
|
||||
slug: "ai-clipping",
|
||||
displayName: "AI Clipping",
|
||||
});
|
||||
const ctx = makeLexicalCtx({
|
||||
exactSlugSkill: null,
|
||||
recentSkills: [],
|
||||
recentByCreated: [newSkill],
|
||||
});
|
||||
|
||||
const result = await lexicalFallbackSkillsHandler(ctx, {
|
||||
query: "clipping",
|
||||
queryTokens: ["clipping"],
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].skill.slug).toBe("ai-clipping");
|
||||
});
|
||||
|
||||
it("deduplicates skills found by both fallback scan windows", async () => {
|
||||
const skill = makeSkillDoc({
|
||||
id: "skills:dup",
|
||||
slug: "orf-dup",
|
||||
displayName: "ORF Dup",
|
||||
});
|
||||
const ctx = makeLexicalCtx({
|
||||
exactSlugSkill: null,
|
||||
recentSkills: [skill],
|
||||
recentByCreated: [skill],
|
||||
});
|
||||
|
||||
const result = await lexicalFallbackSkillsHandler(ctx, {
|
||||
query: "orf",
|
||||
queryTokens: ["orf"],
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].skill.slug).toBe("orf-dup");
|
||||
});
|
||||
|
||||
it("advances candidate limit until max", () => {
|
||||
expect(__test.getNextCandidateLimit(50, 1000)).toBe(100);
|
||||
expect(__test.getNextCandidateLimit(800, 1000)).toBe(1000);
|
||||
@@ -720,25 +643,6 @@ describe("search helpers", () => {
|
||||
expect(exactScore).toBeGreaterThan(looseScore);
|
||||
});
|
||||
|
||||
it("boosts exact full slug over a longer slug containing all query tokens", () => {
|
||||
const queryTokens = tokenize("self-improving-agent");
|
||||
const exactScore = __test.scoreSkillResult(
|
||||
queryTokens,
|
||||
0.5,
|
||||
"Self Improving Agent",
|
||||
"self-improving-agent",
|
||||
10,
|
||||
);
|
||||
const containingScore = __test.scoreSkillResult(
|
||||
queryTokens,
|
||||
0.6,
|
||||
"Self Improving Agent",
|
||||
"xiucheng-self-improving-agent",
|
||||
100,
|
||||
);
|
||||
expect(exactScore).toBeGreaterThan(containingScore);
|
||||
});
|
||||
|
||||
it("adds a popularity prior for equally relevant matches", () => {
|
||||
const queryTokens = tokenize("notion");
|
||||
const lowDownloads = __test.scoreSkillResult(
|
||||
@@ -882,14 +786,14 @@ describe("search helpers", () => {
|
||||
it("only hydrates new embedding IDs on subsequent iterations (incremental)", async () => {
|
||||
generateEmbeddingMock.mockResolvedValueOnce([0, 1, 2]);
|
||||
|
||||
// limit=50 -> candidateLimit starts at 200, maxCandidate=256.
|
||||
// First iteration must return exactly candidateLimit (200) to trigger expansion.
|
||||
const firstBatch = Array.from({ length: 200 }, (_, i) => ({
|
||||
// limit=10 → candidateLimit starts at 50, maxCandidate=200.
|
||||
// First iteration must return exactly candidateLimit (50) to trigger expansion.
|
||||
const firstBatch = Array.from({ length: 50 }, (_, i) => ({
|
||||
_id: `skillEmbeddings:e${i}`,
|
||||
_score: 0.5 - i * 0.001,
|
||||
}));
|
||||
// Second iteration returns 210 results (200 old + 10 new).
|
||||
// 210 < next candidateLimit (256), so the loop breaks.
|
||||
// Second iteration returns 60 results (50 old + 10 new).
|
||||
// 60 < next candidateLimit (100), so the loop breaks.
|
||||
const secondBatch = [
|
||||
...firstBatch,
|
||||
...Array.from({ length: 10 }, (_, i) => ({
|
||||
@@ -929,12 +833,12 @@ describe("search helpers", () => {
|
||||
|
||||
await searchSkillsHandler(
|
||||
{ vectorSearch: vectorSearchMock, runQuery },
|
||||
{ query: "test", limit: 50 },
|
||||
{ query: "test", limit: 10 },
|
||||
);
|
||||
|
||||
// Should have been called twice, but second call should only have new IDs
|
||||
expect(hydrateCalls).toHaveLength(2);
|
||||
expect(hydrateCalls[0]).toHaveLength(200);
|
||||
expect(hydrateCalls[0]).toHaveLength(50);
|
||||
expect(hydrateCalls[1]).toHaveLength(10);
|
||||
// Verify no overlap between the two hydrate calls
|
||||
const firstSet = new Set(hydrateCalls[0]);
|
||||
@@ -962,96 +866,6 @@ describe("search helpers", () => {
|
||||
expect(merged).toHaveLength(2);
|
||||
expect(merged.map((entry) => entry.skill._id)).toEqual(["skills:1", "skills:2"]);
|
||||
});
|
||||
|
||||
it("preserves vector scores across candidate expansion iterations", async () => {
|
||||
// Regression test for scoreById overwrite bug.
|
||||
//
|
||||
// Setup:
|
||||
// limit=50 -> candidateLimit starts at 200, maxCandidate=256
|
||||
// Iteration 1: vectorSearch returns exactly 200 results (= candidateLimit)
|
||||
// → results.length < candidateLimit is false → loop continues
|
||||
// Iteration 2: vectorSearch returns 2 results (< 256) → loop exits
|
||||
//
|
||||
// skillA appears ONLY in iteration 1 (score 0.95).
|
||||
// skillB appears ONLY in iteration 2 (score 0.5).
|
||||
//
|
||||
// With the BUG: scoreById = new Map(iter2_results) → skillA missing → vectorScore=0
|
||||
// With the FIX: scoreById.set() merges → skillA retains 0.95
|
||||
generateEmbeddingMock.mockResolvedValueOnce([0, 1, 2]);
|
||||
|
||||
const skillA = makePublicSkill({
|
||||
id: "skills:a",
|
||||
slug: "baidu-yijian-vision",
|
||||
displayName: "Baidu Yijian Vision",
|
||||
downloads: 100,
|
||||
});
|
||||
const skillB = makePublicSkill({
|
||||
id: "skills:b",
|
||||
slug: "baidu-yijian-test",
|
||||
displayName: "Baidu Yijian Test",
|
||||
downloads: 50,
|
||||
});
|
||||
|
||||
// Iteration 1: exactly 200 entries so the loop does NOT exit early.
|
||||
// skillA is entry 0; entries 1-199 are fillers filtered out by hydrateResults.
|
||||
const iter1Results = Array.from({ length: 200 }, (_, i) => ({
|
||||
_id: i === 0 ? "skillEmbeddings:a" : `skillEmbeddings:filler${i}`,
|
||||
_score: i === 0 ? 0.95 : 0.1,
|
||||
}));
|
||||
|
||||
// Iteration 2: 2 entries, both new IDs (skillA is absent from this batch).
|
||||
// results.length (2) < candidateLimit (256) → loop exits.
|
||||
const iter2Results = [
|
||||
{ _id: "skillEmbeddings:b", _score: 0.5 },
|
||||
{ _id: "skillEmbeddings:filler50", _score: 0.08 },
|
||||
];
|
||||
|
||||
const runQuery = vi
|
||||
.fn()
|
||||
// hydrateResults iteration 1: 50 new IDs → only skillA survives hydration
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
embeddingId: "skillEmbeddings:a",
|
||||
skill: skillA,
|
||||
version: null,
|
||||
ownerHandle: "owner",
|
||||
owner: null,
|
||||
},
|
||||
])
|
||||
// hydrateResults iteration 2: 2 new IDs → only skillB survives hydration
|
||||
.mockResolvedValueOnce([
|
||||
{
|
||||
embeddingId: "skillEmbeddings:b",
|
||||
skill: skillB,
|
||||
version: null,
|
||||
ownerHandle: "owner",
|
||||
owner: null,
|
||||
},
|
||||
])
|
||||
// lexicalFallbackSkills (exactMatches < limit after loop exits)
|
||||
.mockResolvedValueOnce([]);
|
||||
|
||||
const result = await searchSkillsHandler(
|
||||
{
|
||||
vectorSearch: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(iter1Results) // iteration 1: 50 results, loop continues
|
||||
.mockResolvedValueOnce(iter2Results), // iteration 2: 2 results, loop exits
|
||||
runQuery,
|
||||
},
|
||||
{ query: "baidu yijian", limit: 50 },
|
||||
);
|
||||
|
||||
const resultA = result.find(
|
||||
(r: { skill: { slug: string } }) => r.skill.slug === "baidu-yijian-vision",
|
||||
);
|
||||
expect(resultA).toBeDefined();
|
||||
// With scoreById correctly merged: skillA retains vectorScore=0.95.
|
||||
// With the bug (overwrite): skillA.embeddingId absent from iter2 map → vectorScore=0.
|
||||
// Lexical boost for "baidu-yijian-vision" slug matching "baidu yijian" ≈ 0.8 (prefix).
|
||||
// Fix: score ≈ 0.95 + 0.8 + popularity > 1.5; Bug: score ≈ 0 + 0.8 + popularity < 0.9.
|
||||
expect(resultA!.score).toBeGreaterThan(1.0);
|
||||
});
|
||||
});
|
||||
|
||||
function makePublicSkill(params: {
|
||||
@@ -1108,20 +922,16 @@ function makeSkillDoc(params: {
|
||||
function makeLexicalCtx(params: {
|
||||
exactSlugSkill: ReturnType<typeof makeSkillDoc> | null;
|
||||
recentSkills: Array<ReturnType<typeof makeSkillDoc>>;
|
||||
recentByCreated?: Array<ReturnType<typeof makeSkillDoc>>;
|
||||
}) {
|
||||
// Convert skill docs to digest-shaped rows (add skillId + owner fields).
|
||||
const toDigestRows = (skills: Array<ReturnType<typeof makeSkillDoc>>) =>
|
||||
skills.map((skill) => ({
|
||||
...skill,
|
||||
skillId: skill._id,
|
||||
ownerHandle: "owner",
|
||||
ownerName: "Owner",
|
||||
ownerDisplayName: "Owner",
|
||||
ownerImage: undefined,
|
||||
}));
|
||||
const digestByUpdated = toDigestRows(params.recentSkills);
|
||||
const digestByCreated = toDigestRows(params.recentByCreated ?? []);
|
||||
const digestRows = params.recentSkills.map((skill) => ({
|
||||
...skill,
|
||||
skillId: skill._id,
|
||||
ownerHandle: "owner",
|
||||
ownerName: "Owner",
|
||||
ownerDisplayName: "Owner",
|
||||
ownerImage: undefined,
|
||||
}));
|
||||
return {
|
||||
db: {
|
||||
query: vi.fn((table: string) => {
|
||||
@@ -1143,14 +953,7 @@ function makeLexicalCtx(params: {
|
||||
if (index === "by_active_updated") {
|
||||
return {
|
||||
order: () => ({
|
||||
take: vi.fn().mockResolvedValue(digestByUpdated),
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (index === "by_active_created") {
|
||||
return {
|
||||
order: () => ({
|
||||
take: vi.fn().mockResolvedValue(digestByCreated),
|
||||
take: vi.fn().mockResolvedValue(digestRows),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@ import { isSkillHighlighted } from "./lib/badges";
|
||||
import { generateEmbedding } from "./lib/embeddings";
|
||||
import type { HydratableSkill, PublicPublisher } from "./lib/public";
|
||||
import { toPublicPublisher, toPublicSkill, toPublicSoul } from "./lib/public";
|
||||
import { SKILL_CAPABILITY_TAGS } from "./lib/skillCapabilityTags";
|
||||
import { getOwnerPublisher } from "./lib/publishers";
|
||||
import { matchesExactTokens, tokenize } from "./lib/searchText";
|
||||
import { SKILL_CAPABILITY_TAGS } from "./lib/skillCapabilityTags";
|
||||
import { isSkillSuspicious } from "./lib/skillSafety";
|
||||
import { digestToHydratableSkill, digestToOwnerInfo } from "./lib/skillSearchDigest";
|
||||
|
||||
@@ -46,13 +46,12 @@ type SkillSearchEntry = {
|
||||
|
||||
type SearchResult = SkillSearchEntry & { score: number };
|
||||
|
||||
const EXACT_SLUG_BOOST = 2.5;
|
||||
const SLUG_TOKEN_BOOST = 1.4;
|
||||
const SLUG_EXACT_BOOST = 1.4;
|
||||
const SLUG_PREFIX_BOOST = 0.8;
|
||||
const NAME_EXACT_BOOST = 1.1;
|
||||
const NAME_PREFIX_BOOST = 0.6;
|
||||
const POPULARITY_WEIGHT = 0.08;
|
||||
const FALLBACK_SCAN_LIMIT = 2000;
|
||||
const FALLBACK_SCAN_LIMIT = 500;
|
||||
const SKILL_CAPABILITY_TAG_SET = new Set<string>(SKILL_CAPABILITY_TAGS);
|
||||
|
||||
function getNextCandidateLimit(current: number, max: number) {
|
||||
@@ -76,11 +75,8 @@ function getLexicalBoost(queryTokens: string[], displayName: string, slug: strin
|
||||
const nameTokens = tokenize(displayName);
|
||||
|
||||
let boost = 0;
|
||||
const normalizedQuery = queryTokens.join("-");
|
||||
if (normalizedQuery === slug) {
|
||||
boost += EXACT_SLUG_BOOST;
|
||||
} else if (matchesAllTokens(queryTokens, slugTokens, (candidate, query) => candidate === query)) {
|
||||
boost += SLUG_TOKEN_BOOST;
|
||||
if (matchesAllTokens(queryTokens, slugTokens, (candidate, query) => candidate === query)) {
|
||||
boost += SLUG_EXACT_BOOST;
|
||||
} else if (
|
||||
matchesAllTokens(queryTokens, slugTokens, (candidate, query) => candidate.startsWith(query))
|
||||
) {
|
||||
@@ -160,75 +156,70 @@ export const searchSkills: ReturnType<typeof action> = action({
|
||||
matchesCapabilityTag(rawExactSlugMatch.skill, args.capabilityTag)
|
||||
? rawExactSlugMatch
|
||||
: null;
|
||||
let vector: number[] | null;
|
||||
let vector: number[];
|
||||
try {
|
||||
vector = await generateEmbedding(query);
|
||||
} catch (error) {
|
||||
console.warn("Search embedding generation failed, falling back to lexical search", error);
|
||||
vector = null;
|
||||
console.warn("Search embedding generation failed", error);
|
||||
return [];
|
||||
}
|
||||
const limit = args.limit ?? 10;
|
||||
// Convex vectorSearch max limit is 256; clamp candidate sizes accordingly.
|
||||
// Keep the initial pool large enough to catch moderate-vector matches
|
||||
// that win after lexical and popularity scoring, even for small limits.
|
||||
const maxCandidate = Math.min(Math.max(limit * 10, 200), 256);
|
||||
let candidateLimit = Math.min(Math.max(limit * 3, 200), 256);
|
||||
let candidateLimit = Math.min(Math.max(limit * 3, 50), 256);
|
||||
let hydrated: SkillSearchEntry[] = [];
|
||||
const seenEmbeddingIds = new Set<Id<"skillEmbeddings">>();
|
||||
let scoreById = new Map<Id<"skillEmbeddings">, number>();
|
||||
let exactMatches: SkillSearchEntry[] = [];
|
||||
|
||||
if (vector) {
|
||||
while (candidateLimit <= maxCandidate) {
|
||||
const results = await ctx.vectorSearch("skillEmbeddings", "by_embedding", {
|
||||
vector,
|
||||
limit: candidateLimit,
|
||||
filter: (q) =>
|
||||
q.or(q.eq("visibility", "latest"), q.eq("visibility", "latest-approved")),
|
||||
});
|
||||
while (candidateLimit <= maxCandidate) {
|
||||
const results = await ctx.vectorSearch("skillEmbeddings", "by_embedding", {
|
||||
vector,
|
||||
limit: candidateLimit,
|
||||
filter: (q) => q.or(q.eq("visibility", "latest"), q.eq("visibility", "latest-approved")),
|
||||
});
|
||||
|
||||
// Only hydrate embedding IDs we haven't seen yet (incremental).
|
||||
// Track all attempted IDs, not just successful hydrations, to avoid
|
||||
// re-hydrating filtered-out entries (soft-deleted, suspicious) each loop.
|
||||
const newEmbeddingIds = results.map((r) => r._id).filter((id) => !seenEmbeddingIds.has(id));
|
||||
for (const id of newEmbeddingIds) seenEmbeddingIds.add(id);
|
||||
// Only hydrate embedding IDs we haven't seen yet (incremental).
|
||||
// Track all attempted IDs, not just successful hydrations, to avoid
|
||||
// re-hydrating filtered-out entries (soft-deleted, suspicious) each loop.
|
||||
const newEmbeddingIds = results.map((r) => r._id).filter((id) => !seenEmbeddingIds.has(id));
|
||||
for (const id of newEmbeddingIds) seenEmbeddingIds.add(id);
|
||||
|
||||
if (newEmbeddingIds.length > 0) {
|
||||
const newEntries = (await ctx.runQuery(internal.search.hydrateResults, {
|
||||
embeddingIds: newEmbeddingIds,
|
||||
nonSuspiciousOnly: args.nonSuspiciousOnly,
|
||||
})) as SkillSearchEntry[];
|
||||
hydrated = [...hydrated, ...newEntries];
|
||||
}
|
||||
|
||||
for (const result of results) {
|
||||
scoreById.set(result._id, result._score);
|
||||
}
|
||||
|
||||
// Skills already have badges from their docs (via toPublicSkill).
|
||||
// No need for a separate badge table lookup.
|
||||
const filtered = hydrated.filter(
|
||||
(entry) =>
|
||||
(!args.highlightedOnly || isSkillHighlighted(entry.skill)) &&
|
||||
matchesCapabilityTag(entry.skill, args.capabilityTag),
|
||||
);
|
||||
|
||||
exactMatches = filtered.filter((entry) =>
|
||||
matchesExactTokens(queryTokens, [
|
||||
entry.skill.displayName,
|
||||
entry.skill.slug,
|
||||
entry.skill.summary,
|
||||
]),
|
||||
);
|
||||
|
||||
if (exactMatches.length >= limit || results.length < candidateLimit) {
|
||||
break;
|
||||
}
|
||||
|
||||
const nextLimit = getNextCandidateLimit(candidateLimit, maxCandidate);
|
||||
if (!nextLimit) break;
|
||||
candidateLimit = nextLimit;
|
||||
if (newEmbeddingIds.length > 0) {
|
||||
const newEntries = (await ctx.runQuery(internal.search.hydrateResults, {
|
||||
embeddingIds: newEmbeddingIds,
|
||||
nonSuspiciousOnly: args.nonSuspiciousOnly,
|
||||
})) as SkillSearchEntry[];
|
||||
hydrated = [...hydrated, ...newEntries];
|
||||
}
|
||||
|
||||
scoreById = new Map<Id<"skillEmbeddings">, number>(
|
||||
results.map((result) => [result._id, result._score]),
|
||||
);
|
||||
|
||||
// Skills already have badges from their docs (via toPublicSkill).
|
||||
// No need for a separate badge table lookup.
|
||||
const filtered = hydrated.filter(
|
||||
(entry) =>
|
||||
(!args.highlightedOnly || isSkillHighlighted(entry.skill)) &&
|
||||
matchesCapabilityTag(entry.skill, args.capabilityTag),
|
||||
);
|
||||
|
||||
exactMatches = filtered.filter((entry) =>
|
||||
matchesExactTokens(queryTokens, [
|
||||
entry.skill.displayName,
|
||||
entry.skill.slug,
|
||||
entry.skill.summary,
|
||||
]),
|
||||
);
|
||||
|
||||
if (exactMatches.length >= limit || results.length < candidateLimit) {
|
||||
break;
|
||||
}
|
||||
|
||||
const nextLimit = getNextCandidateLimit(candidateLimit, maxCandidate);
|
||||
if (!nextLimit) break;
|
||||
candidateLimit = nextLimit;
|
||||
}
|
||||
|
||||
const primaryMatches = exactSlugMatch
|
||||
@@ -389,36 +380,23 @@ export const lexicalFallbackSkills = internalQuery({
|
||||
}
|
||||
|
||||
// Scan recent active digests (~800 bytes each) instead of full skill docs (~3-5KB).
|
||||
// Use updatedAt and createdAt windows so newly published skills are visible even
|
||||
// when they are not in the most recently updated slice.
|
||||
const [recentByUpdated, recentByCreated] = await Promise.all([
|
||||
ctx.db
|
||||
.query("skillSearchDigest")
|
||||
.withIndex("by_active_updated", (q) => q.eq("softDeletedAt", undefined))
|
||||
.order("desc")
|
||||
.take(FALLBACK_SCAN_LIMIT),
|
||||
ctx.db
|
||||
.query("skillSearchDigest")
|
||||
.withIndex("by_active_created", (q) => q.eq("softDeletedAt", undefined))
|
||||
.order("desc")
|
||||
.take(FALLBACK_SCAN_LIMIT),
|
||||
]);
|
||||
const recentDigests = await ctx.db
|
||||
.query("skillSearchDigest")
|
||||
.withIndex("by_active_updated", (q) => q.eq("softDeletedAt", undefined))
|
||||
.order("desc")
|
||||
.take(FALLBACK_SCAN_LIMIT);
|
||||
|
||||
const addDigestCandidates = (digests: typeof recentByUpdated) => {
|
||||
for (const digest of digests) {
|
||||
if (seenSkillIds.has(digest.skillId)) continue;
|
||||
const skill = digestToHydratableSkill(digest);
|
||||
if (args.nonSuspiciousOnly && isSkillSuspicious(skill)) continue;
|
||||
if (!matchesCapabilityTag(skill, args.capabilityTag)) continue;
|
||||
seenSkillIds.add(digest.skillId);
|
||||
candidates.push(skill);
|
||||
// Pre-resolve owner from digest to avoid users table reads.
|
||||
const ownerInfo = digestToOwnerInfo(digest);
|
||||
if (ownerInfo) preResolvedOwners.set(digest.skillId, ownerInfo);
|
||||
}
|
||||
};
|
||||
addDigestCandidates(recentByUpdated);
|
||||
addDigestCandidates(recentByCreated);
|
||||
for (const digest of recentDigests) {
|
||||
if (seenSkillIds.has(digest.skillId)) continue;
|
||||
const skill = digestToHydratableSkill(digest);
|
||||
if (args.nonSuspiciousOnly && isSkillSuspicious(skill)) continue;
|
||||
if (!matchesCapabilityTag(skill, args.capabilityTag)) continue;
|
||||
seenSkillIds.add(digest.skillId);
|
||||
candidates.push(skill);
|
||||
// Pre-resolve owner from digest to avoid users table reads.
|
||||
const ownerInfo = digestToOwnerInfo(digest);
|
||||
if (ownerInfo) preResolvedOwners.set(digest.skillId, ownerInfo);
|
||||
}
|
||||
|
||||
const matched = candidates.filter((skill) =>
|
||||
matchesExactTokens(args.queryTokens, [skill.displayName, skill.slug, skill.summary]),
|
||||
@@ -481,9 +459,8 @@ export const searchSouls: ReturnType<typeof action> = action({
|
||||
}
|
||||
const limit = args.limit ?? 10;
|
||||
// Convex vectorSearch max limit is 256; clamp candidate sizes accordingly.
|
||||
// Match searchSkills so soul search does not miss boosted exact matches.
|
||||
const maxCandidate = Math.min(Math.max(limit * 10, 200), 256);
|
||||
let candidateLimit = Math.min(Math.max(limit * 3, 200), 256);
|
||||
let candidateLimit = Math.min(Math.max(limit * 3, 50), 256);
|
||||
let hydrated: HydratedSoulEntry[] = [];
|
||||
let scoreById = new Map<Id<"soulEmbeddings">, number>();
|
||||
let exactMatches: HydratedSoulEntry[] = [];
|
||||
@@ -499,9 +476,9 @@ export const searchSouls: ReturnType<typeof action> = action({
|
||||
embeddingIds: results.map((result) => result._id),
|
||||
})) as HydratedSoulEntry[];
|
||||
|
||||
for (const result of results) {
|
||||
scoreById.set(result._id, result._score);
|
||||
}
|
||||
scoreById = new Map<Id<"soulEmbeddings">, number>(
|
||||
results.map((result) => [result._id, result._score]),
|
||||
);
|
||||
|
||||
exactMatches = hydrated.filter((entry) =>
|
||||
matchesExactTokens(queryTokens, [
|
||||
|
||||
@@ -1,719 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@convex-dev/auth/server", () => ({
|
||||
getAuthUserId: vi.fn(),
|
||||
authTables: {},
|
||||
}));
|
||||
|
||||
import { insertVersion } from "./skills";
|
||||
|
||||
type WrappedHandler<TArgs> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<unknown>;
|
||||
};
|
||||
|
||||
const insertVersionHandler = (insertVersion as unknown as WrappedHandler<Record<string, unknown>>)
|
||||
._handler;
|
||||
|
||||
const OWNER_USER_ID = "users:owner";
|
||||
const OWNER_PUBLISHER_ID = "publishers:owner";
|
||||
const SKILL_ID = "skills:1";
|
||||
const PREV_LATEST_VERSION_ID = "skillVersions:prev";
|
||||
const PREV_EMBEDDING_ID = "skillEmbeddings:prev";
|
||||
const NEW_VERSION_ID = "skillVersions:new";
|
||||
const NEW_EMBEDDING_ID = "skillEmbeddings:new";
|
||||
|
||||
type SkillDoc = {
|
||||
_id: string;
|
||||
slug: string;
|
||||
displayName: string;
|
||||
summary: string;
|
||||
ownerUserId: string;
|
||||
ownerPublisherId: string;
|
||||
latestVersionId: string | undefined;
|
||||
latestVersionSummary:
|
||||
| {
|
||||
version: string;
|
||||
createdAt: number;
|
||||
changelog: string;
|
||||
changelogSource?: "auto" | "user";
|
||||
clawdis?: unknown;
|
||||
}
|
||||
| undefined;
|
||||
tags: Record<string, string>;
|
||||
capabilityTags: string[] | undefined;
|
||||
stats: {
|
||||
downloads: number;
|
||||
installsCurrent: number;
|
||||
installsAllTime: number;
|
||||
stars: number;
|
||||
versions: number;
|
||||
comments: number;
|
||||
};
|
||||
badges: Record<string, unknown>;
|
||||
moderationStatus: string;
|
||||
moderationReason: string;
|
||||
moderationFlags: string[] | undefined;
|
||||
isSuspicious: boolean;
|
||||
softDeletedAt: number | undefined;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
manualOverride?: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
function buildExistingSkill(overrides: Partial<SkillDoc> = {}): SkillDoc {
|
||||
return {
|
||||
_id: SKILL_ID,
|
||||
slug: "my-skill",
|
||||
displayName: "My Skill v2",
|
||||
summary: "Summary of v2.0.0",
|
||||
ownerUserId: OWNER_USER_ID,
|
||||
ownerPublisherId: OWNER_PUBLISHER_ID,
|
||||
latestVersionId: PREV_LATEST_VERSION_ID,
|
||||
latestVersionSummary: {
|
||||
version: "2.0.0",
|
||||
createdAt: 1,
|
||||
changelog: "Major release",
|
||||
changelogSource: "user",
|
||||
clawdis: {},
|
||||
},
|
||||
tags: { latest: PREV_LATEST_VERSION_ID },
|
||||
capabilityTags: ["cap-v2"],
|
||||
stats: {
|
||||
downloads: 0,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 0,
|
||||
stars: 0,
|
||||
versions: 1,
|
||||
comments: 0,
|
||||
},
|
||||
badges: {
|
||||
redactionApproved: undefined,
|
||||
highlighted: undefined,
|
||||
official: undefined,
|
||||
deprecated: undefined,
|
||||
},
|
||||
moderationStatus: "active",
|
||||
moderationReason: "pending.scan",
|
||||
moderationFlags: undefined,
|
||||
isSuspicious: false,
|
||||
softDeletedAt: undefined,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
manualOverride: undefined,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPublishArgs(overrides?: Partial<Record<string, unknown>>) {
|
||||
return {
|
||||
userId: OWNER_USER_ID,
|
||||
slug: "my-skill",
|
||||
displayName: "My Skill v1 backport",
|
||||
version: "1.0.1",
|
||||
changelog: "Backport fix",
|
||||
changelogSource: "user",
|
||||
tags: [] as string[],
|
||||
capabilityTags: ["cap-v1-backport"],
|
||||
summary: "Summary of v1.0.1 backport",
|
||||
fingerprint: "f".repeat(64),
|
||||
files: [
|
||||
{
|
||||
path: "SKILL.md",
|
||||
size: 128,
|
||||
storageId: "_storage:1",
|
||||
sha256: "a".repeat(64),
|
||||
contentType: "text/markdown",
|
||||
},
|
||||
],
|
||||
parsed: {
|
||||
frontmatter: { description: "backport summary from frontmatter" },
|
||||
metadata: {},
|
||||
clawdis: {},
|
||||
},
|
||||
staticScan: {
|
||||
status: "clean",
|
||||
reasonCodes: [],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.2.0",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
embedding: [0.1, 0.2],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type Captured = {
|
||||
skillPatches: Array<Record<string, unknown>>;
|
||||
embeddingInserts: Array<Record<string, unknown>>;
|
||||
embeddingPatches: Array<{ id: string; value: Record<string, unknown> }>;
|
||||
versionInserted: Record<string, unknown> | null;
|
||||
allPatches: Array<{ id: string; value: Record<string, unknown> }>;
|
||||
};
|
||||
|
||||
function buildDb(skill: SkillDoc, captured: Captured) {
|
||||
// Trigger-driven code (syncSkillSearchDigestForSkill -> getOwnerPublisher)
|
||||
// will ask for publishers via `db.get(ownerPublisherId)`. Return null so
|
||||
// getOwnerPublisher falls back to resolving the publisher from the owner user.
|
||||
const publisherTableQuery = () => ({
|
||||
withIndex: () => ({
|
||||
unique: async () => null,
|
||||
take: async () => [],
|
||||
}),
|
||||
});
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (arg0: string, arg1?: string) => {
|
||||
// triggers.wrapDB calls innerDb.get(tableName, id) for tables with
|
||||
// registered triggers; other call sites use db.get(id).
|
||||
const id = arg1 !== undefined ? arg1 : arg0;
|
||||
if (id === OWNER_USER_ID) {
|
||||
return {
|
||||
_id: OWNER_USER_ID,
|
||||
_creationTime: Date.now() - 60 * 24 * 60 * 60 * 1000,
|
||||
createdAt: Date.now() - 60 * 24 * 60 * 60 * 1000,
|
||||
updatedAt: Date.now() - 60 * 24 * 60 * 60 * 1000,
|
||||
handle: "alice",
|
||||
name: "Alice",
|
||||
email: "alice@example.com",
|
||||
displayName: "Alice",
|
||||
deletedAt: undefined,
|
||||
deactivatedAt: undefined,
|
||||
trustedPublisher: true,
|
||||
role: "user",
|
||||
personalPublisherId: OWNER_PUBLISHER_ID,
|
||||
};
|
||||
}
|
||||
if (id === OWNER_PUBLISHER_ID) {
|
||||
// Returning null lets getOwnerPublisher fall back to user-based
|
||||
// resolution, which then hits the synthesize fallback.
|
||||
return null;
|
||||
}
|
||||
if (id === SKILL_ID) return skill;
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "publishers" || table === "publisherMembers") {
|
||||
// ensurePersonalPublisherForUser / getOwnerPublisher may poll these
|
||||
// tables during triggers. Returning an empty index matches the state
|
||||
// of a fresh test environment without real publisher rows.
|
||||
return publisherTableQuery();
|
||||
}
|
||||
if (table === "skills") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name === "by_slug") {
|
||||
return { unique: async () => skill };
|
||||
}
|
||||
if (name === "by_owner") {
|
||||
return { order: () => ({ take: async () => [skill] }) };
|
||||
}
|
||||
throw new Error(`unexpected skills index ${name}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "skillSlugAliases") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== "by_slug") {
|
||||
throw new Error(`unexpected skillSlugAliases index ${name}`);
|
||||
}
|
||||
return { unique: async () => null };
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "skillVersions") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== "by_skill_version") {
|
||||
throw new Error(`unexpected skillVersions index ${name}`);
|
||||
}
|
||||
return { unique: async () => null };
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "skillVersionFingerprints") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== "by_fingerprint") {
|
||||
throw new Error(`unexpected skillVersionFingerprints index ${name}`);
|
||||
}
|
||||
return { take: async () => [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "skillBadges") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== "by_skill") {
|
||||
throw new Error(`unexpected skillBadges index ${name}`);
|
||||
}
|
||||
return { take: async () => [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "skillEmbeddings") {
|
||||
return {
|
||||
withIndex: (
|
||||
name: string,
|
||||
build:
|
||||
| ((q: { eq: (field: string, value: string) => unknown }) => unknown)
|
||||
| undefined,
|
||||
) => {
|
||||
if (name !== "by_version") {
|
||||
throw new Error(`unexpected skillEmbeddings index ${name}`);
|
||||
}
|
||||
let requestedVersionId: string | null = null;
|
||||
const q = {
|
||||
eq: (field: string, value: string) => {
|
||||
if (field !== "versionId") throw new Error(`unexpected field ${field}`);
|
||||
requestedVersionId = value;
|
||||
return q;
|
||||
},
|
||||
};
|
||||
build?.(q);
|
||||
return {
|
||||
unique: async () => {
|
||||
if (requestedVersionId === PREV_LATEST_VERSION_ID) {
|
||||
return {
|
||||
_id: PREV_EMBEDDING_ID,
|
||||
versionId: PREV_LATEST_VERSION_ID,
|
||||
isLatest: true,
|
||||
isApproved: false,
|
||||
visibility: "public",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "globalStats") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== "by_key") {
|
||||
throw new Error(`unexpected globalStats index ${name}`);
|
||||
}
|
||||
return {
|
||||
unique: async () => ({
|
||||
_id: "globalStats:1",
|
||||
activeSkillsCount: 100,
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
if (table === "skillSearchDigest") {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
unique: async () => null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (table === "reservedSlugs") {
|
||||
return {
|
||||
withIndex: (name: string) => {
|
||||
if (name !== "by_slug_active_deletedAt") {
|
||||
throw new Error(`unexpected reservedSlugs index ${name}`);
|
||||
}
|
||||
return { order: () => ({ take: async () => [] }) };
|
||||
},
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
patch: vi.fn(async (arg0: unknown, arg1: unknown, arg2?: unknown) => {
|
||||
// convex-helpers `triggers` calls innerDb.patch(tableName, id, value)
|
||||
// for tables with registered triggers (e.g. "skills"); otherwise it
|
||||
// falls back to innerDb.patch(id, value).
|
||||
const [id, value] =
|
||||
arg2 !== undefined ? [arg1 as string, arg2] : [arg0 as string, arg1];
|
||||
|
||||
captured.allPatches.push({
|
||||
id: id,
|
||||
value: value as Record<string, unknown>,
|
||||
});
|
||||
|
||||
if (id === SKILL_ID) {
|
||||
captured.skillPatches.push(value as Record<string, unknown>);
|
||||
Object.assign(skill, value as Record<string, unknown>);
|
||||
return;
|
||||
}
|
||||
if (id === PREV_EMBEDDING_ID) {
|
||||
captured.embeddingPatches.push({ id, value: value as Record<string, unknown> });
|
||||
return;
|
||||
}
|
||||
if (typeof id === "string" && id.startsWith("users:")) return;
|
||||
if (typeof id === "string" && id.startsWith("publishers:")) return;
|
||||
}),
|
||||
insert: vi.fn(async (table: string, value: Record<string, unknown>) => {
|
||||
if (table === "skillVersions") {
|
||||
captured.versionInserted = value;
|
||||
return NEW_VERSION_ID;
|
||||
}
|
||||
if (table === "skillEmbeddings") {
|
||||
captured.embeddingInserts.push(value);
|
||||
return NEW_EMBEDDING_ID;
|
||||
}
|
||||
if (table === "embeddingSkillMap") {
|
||||
return "embeddingSkillMap:1";
|
||||
}
|
||||
if (table === "skillVersionFingerprints") {
|
||||
return "skillVersionFingerprints:1";
|
||||
}
|
||||
// Trigger side-effect / digest tables: accept silently so the async
|
||||
// digest plumbing invoked by the skills trigger doesn't fail the test.
|
||||
if (table === "skillSearchDigest") {
|
||||
return `${table}:mock`;
|
||||
}
|
||||
// Intentionally throw for publishers / publisherMembers so
|
||||
// ensurePersonalPublisherForUser's `isMissingPublisherTableError` branch
|
||||
// takes the synthesize fallback, avoiding the publishers trigger chain.
|
||||
throw new Error(`unexpected insert table ${table}`);
|
||||
}),
|
||||
normalizeId: vi.fn((tableName: string, id: string) =>
|
||||
id.startsWith(`${tableName}:`) ? id : null,
|
||||
),
|
||||
};
|
||||
return db;
|
||||
}
|
||||
|
||||
function buildCtx(skill: SkillDoc) {
|
||||
const captured: Captured = {
|
||||
skillPatches: [],
|
||||
embeddingInserts: [],
|
||||
embeddingPatches: [],
|
||||
versionInserted: null,
|
||||
allPatches: [],
|
||||
};
|
||||
const db = buildDb(skill, captured);
|
||||
const ctx = {
|
||||
db,
|
||||
scheduler: { runAfter: vi.fn() },
|
||||
};
|
||||
return { ctx, captured, db };
|
||||
}
|
||||
|
||||
describe("skills.insertVersion latest-tag protection", () => {
|
||||
it("promotes latest when publishing a strictly higher version", async () => {
|
||||
const skill = buildExistingSkill();
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
const result = await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "2.1.0",
|
||||
displayName: "My Skill v2.1",
|
||||
summary: "Summary of v2.1.0",
|
||||
capabilityTags: ["cap-v2.1"],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
skillId: SKILL_ID,
|
||||
versionId: NEW_VERSION_ID,
|
||||
embeddingId: NEW_EMBEDDING_ID,
|
||||
});
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1);
|
||||
expect(finalPatch).toBeDefined();
|
||||
expect(finalPatch).toMatchObject({
|
||||
latestVersionId: NEW_VERSION_ID,
|
||||
displayName: "My Skill v2.1",
|
||||
capabilityTags: ["cap-v2.1"],
|
||||
tags: expect.objectContaining({ latest: NEW_VERSION_ID }),
|
||||
});
|
||||
expect((finalPatch as Record<string, unknown>).latestVersionSummary).toMatchObject({
|
||||
version: "2.1.0",
|
||||
});
|
||||
|
||||
// New embedding is the latest; the previous latest embedding is demoted.
|
||||
expect(captured.embeddingInserts[0]).toMatchObject({
|
||||
versionId: NEW_VERSION_ID,
|
||||
isLatest: true,
|
||||
});
|
||||
expect(captured.embeddingPatches).toHaveLength(1);
|
||||
expect(captured.embeddingPatches[0]).toMatchObject({
|
||||
id: PREV_EMBEDDING_ID,
|
||||
value: expect.objectContaining({ isLatest: false }),
|
||||
});
|
||||
});
|
||||
|
||||
it("does not clobber latest when publishing an older (backport) version", async () => {
|
||||
const skill = buildExistingSkill();
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
const result = await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "1.0.1",
|
||||
displayName: "My Skill v1 backport",
|
||||
summary: "Summary of v1.0.1 backport",
|
||||
capabilityTags: ["cap-v1-backport"],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
skillId: SKILL_ID,
|
||||
versionId: NEW_VERSION_ID,
|
||||
embeddingId: NEW_EMBEDDING_ID,
|
||||
});
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch).toBeDefined();
|
||||
|
||||
// Latest pointer is preserved.
|
||||
expect(finalPatch.latestVersionId).toBe(PREV_LATEST_VERSION_ID);
|
||||
expect(finalPatch.latestVersionSummary).toMatchObject({ version: "2.0.0" });
|
||||
|
||||
// Skill card fields must keep tracking the existing latest, not the backport.
|
||||
expect(finalPatch.displayName).toBe("My Skill v2");
|
||||
expect(finalPatch.summary).toBe("Summary of v2.0.0");
|
||||
expect(finalPatch.capabilityTags).toEqual(["cap-v2"]);
|
||||
|
||||
// `tags.latest` still points to the previous version.
|
||||
expect(finalPatch.tags).toEqual(
|
||||
expect.objectContaining({ latest: PREV_LATEST_VERSION_ID }),
|
||||
);
|
||||
|
||||
// versions counter still increments on every publish, regardless of version order.
|
||||
expect(finalPatch.stats).toMatchObject({ versions: 2 });
|
||||
});
|
||||
|
||||
it("keeps the previous latest embedding untouched on backport publishes", async () => {
|
||||
const skill = buildExistingSkill();
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({ version: "1.0.1" }) as never,
|
||||
);
|
||||
|
||||
// New version embedding is NOT marked latest.
|
||||
expect(captured.embeddingInserts).toHaveLength(1);
|
||||
expect(captured.embeddingInserts[0]).toMatchObject({
|
||||
versionId: NEW_VERSION_ID,
|
||||
isLatest: false,
|
||||
});
|
||||
|
||||
// Previous latest embedding must not be demoted.
|
||||
expect(captured.embeddingPatches).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("routes a custom tag to the backport version but leaves latest alone", async () => {
|
||||
const skill = buildExistingSkill();
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "1.0.1",
|
||||
tags: ["lts"],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.tags).toEqual(
|
||||
expect.objectContaining({
|
||||
latest: PREV_LATEST_VERSION_ID,
|
||||
lts: NEW_VERSION_ID,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores an explicit `latest` in args.tags for a backport publish", async () => {
|
||||
// Security regression: a caller must not be able to defeat the semver
|
||||
// guard by smuggling `latest` through the custom-tag loop.
|
||||
const skill = buildExistingSkill();
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "1.0.1",
|
||||
tags: ["latest", "lts"],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.latestVersionId).toBe(PREV_LATEST_VERSION_ID);
|
||||
expect(finalPatch.latestVersionSummary).toMatchObject({ version: "2.0.0" });
|
||||
expect(finalPatch.tags).toEqual(
|
||||
expect.objectContaining({
|
||||
latest: PREV_LATEST_VERSION_ID,
|
||||
lts: NEW_VERSION_ID,
|
||||
}),
|
||||
);
|
||||
// New embedding must still be marked non-latest.
|
||||
expect(captured.embeddingInserts[0]).toMatchObject({ isLatest: false });
|
||||
expect(captured.embeddingPatches).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("ignores case-variant `LaTeSt` in args.tags for a backport publish", async () => {
|
||||
// Defense in depth against case-only bypass attempts.
|
||||
const skill = buildExistingSkill();
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "1.0.1",
|
||||
tags: ["LaTeSt"],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.latestVersionId).toBe(PREV_LATEST_VERSION_ID);
|
||||
expect(finalPatch.tags).toEqual(
|
||||
expect.objectContaining({ latest: PREV_LATEST_VERSION_ID }),
|
||||
);
|
||||
// The case-variant tag must not leak into the stored tag map either.
|
||||
const tags = finalPatch.tags as Record<string, string>;
|
||||
expect(tags.LaTeSt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("treats the very first publish as latest even when the version is low", async () => {
|
||||
const skill = buildExistingSkill({
|
||||
latestVersionId: undefined,
|
||||
latestVersionSummary: undefined,
|
||||
tags: {},
|
||||
stats: {
|
||||
downloads: 0,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 0,
|
||||
stars: 0,
|
||||
versions: 0,
|
||||
comments: 0,
|
||||
},
|
||||
});
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "0.0.1",
|
||||
displayName: "My Skill v0",
|
||||
summary: "Summary of v0.0.1",
|
||||
capabilityTags: ["cap-v0"],
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.latestVersionId).toBe(NEW_VERSION_ID);
|
||||
expect(finalPatch.latestVersionSummary).toMatchObject({ version: "0.0.1" });
|
||||
expect(finalPatch.tags).toEqual(expect.objectContaining({ latest: NEW_VERSION_ID }));
|
||||
expect(finalPatch.displayName).toBe("My Skill v0");
|
||||
expect(finalPatch.capabilityTags).toEqual(["cap-v0"]);
|
||||
expect(captured.embeddingInserts[0]).toMatchObject({ isLatest: true });
|
||||
});
|
||||
|
||||
it("does not derive moderation flags from a backport's displayName", async () => {
|
||||
// Regression for reviewer catch: on backport publishes the skill card
|
||||
// keeps the old displayName, so the moderation evaluation must run
|
||||
// against the old displayName too. Otherwise we persist flags that were
|
||||
// triggered by text the user can never see on the card.
|
||||
const skill = buildExistingSkill({ displayName: "Harmless Card Title" });
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "1.0.1",
|
||||
// "phishing" would match FLAG_RULES ("suspicious.keyword") if it
|
||||
// actually reached deriveModerationFlags.
|
||||
displayName: "backport phishing helper",
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
// Card displayName is unchanged (backport cannot leak its title).
|
||||
expect(finalPatch.displayName).toBe("Harmless Card Title");
|
||||
// And the flags derived from that evaluation must not contain the
|
||||
// keyword match sourced from the backport-only title.
|
||||
const flags = (finalPatch.moderationFlags ?? []) as string[];
|
||||
expect(flags).not.toContain("suspicious.keyword");
|
||||
});
|
||||
|
||||
it("still derives moderation flags from displayName when the publish IS the new latest", async () => {
|
||||
// Counter-case for the guard above: when the publish actually promotes
|
||||
// to latest, the new displayName is what lives on the card, so flags
|
||||
// derived from it must be recorded.
|
||||
const skill = buildExistingSkill({ displayName: "Harmless Card Title" });
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "3.0.0",
|
||||
displayName: "shiny phishing helper",
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.displayName).toBe("shiny phishing helper");
|
||||
const flags = (finalPatch.moderationFlags ?? []) as string[];
|
||||
expect(flags).toContain("suspicious.keyword");
|
||||
});
|
||||
|
||||
it("does not throw when the persisted latestVersionSummary.version is not valid semver", async () => {
|
||||
// Regression for reviewer catch: the schema only enforces v.string() on
|
||||
// latestVersionSummary.version, so legacy / imported skills may persist
|
||||
// non-semver values. Without the semver.valid() guard, semver.gt would
|
||||
// throw `TypeError: Invalid Version` and crash the publish mutation.
|
||||
const skill = buildExistingSkill({
|
||||
latestVersionSummary: {
|
||||
version: "not-a-semver",
|
||||
createdAt: 1000,
|
||||
changelog: "legacy",
|
||||
},
|
||||
});
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
// Must not throw `TypeError: Invalid Version` from semver.gt().
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "1.0.0",
|
||||
displayName: "Recovered v1",
|
||||
}) as never,
|
||||
);
|
||||
|
||||
// The new publish should self-heal the skill back into a valid semver
|
||||
// latest pointer, since the persisted one is unusable for comparison.
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.latestVersionId).toBe(NEW_VERSION_ID);
|
||||
expect(finalPatch.latestVersionSummary).toMatchObject({ version: "1.0.0" });
|
||||
expect(finalPatch.tags).toEqual(
|
||||
expect.objectContaining({ latest: NEW_VERSION_ID }),
|
||||
);
|
||||
expect(captured.embeddingInserts[0]).toMatchObject({ isLatest: true });
|
||||
});
|
||||
|
||||
it("does not throw when the persisted latestVersionSummary.version is an empty string", async () => {
|
||||
// Empty string is falsy but still fails semver.valid(); make sure both
|
||||
// guard clauses (`!prevLatestVersion` and `!semver.valid(...)`) keep us
|
||||
// safe rather than only one of them.
|
||||
const skill = buildExistingSkill({
|
||||
latestVersionSummary: {
|
||||
version: "",
|
||||
createdAt: 1000,
|
||||
changelog: "legacy",
|
||||
},
|
||||
});
|
||||
const { ctx, captured } = buildCtx(skill);
|
||||
|
||||
await insertVersionHandler(
|
||||
ctx as never,
|
||||
buildPublishArgs({
|
||||
version: "0.1.0",
|
||||
displayName: "Recovered v0.1",
|
||||
}) as never,
|
||||
);
|
||||
|
||||
const finalPatch = captured.skillPatches.at(-1) as Record<string, unknown>;
|
||||
expect(finalPatch.latestVersionId).toBe(NEW_VERSION_ID);
|
||||
expect(finalPatch.latestVersionSummary).toMatchObject({ version: "0.1.0" });
|
||||
});
|
||||
});
|
||||
@@ -11,62 +11,44 @@ type WrappedHandler<TArgs, TResult = unknown> = {
|
||||
_handler: (ctx: unknown, args: TArgs) => Promise<TResult>;
|
||||
};
|
||||
|
||||
function makeSkill(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
_id: "skills:skill",
|
||||
_creationTime: 1,
|
||||
slug: "demo-skill",
|
||||
displayName: "Demo Skill",
|
||||
summary: "Demo skill",
|
||||
ownerUserId: "users:owner",
|
||||
ownerPublisherId: undefined,
|
||||
canonicalSkillId: undefined,
|
||||
forkOf: undefined,
|
||||
latestVersionId: undefined,
|
||||
latestVersionSummary: undefined,
|
||||
tags: {},
|
||||
capabilityTags: [],
|
||||
badges: undefined,
|
||||
statsDownloads: 7,
|
||||
statsStars: 3,
|
||||
statsInstallsCurrent: 0,
|
||||
statsInstallsAllTime: 0,
|
||||
stats: {
|
||||
downloads: 0,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 0,
|
||||
stars: 0,
|
||||
versions: 1,
|
||||
comments: 0,
|
||||
},
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
softDeletedAt: undefined,
|
||||
moderationStatus: "active",
|
||||
moderationFlags: [],
|
||||
moderationReason: undefined,
|
||||
moderationVerdict: "clean",
|
||||
isSuspicious: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const listHandler = (
|
||||
list as unknown as WrappedHandler<
|
||||
{ ownerPublisherId?: string; ownerUserId?: string; limit?: number },
|
||||
Array<{ slug: string; stats: { downloads: number; stars: number } }>
|
||||
Array<{ slug: string }>
|
||||
>
|
||||
)._handler;
|
||||
|
||||
describe("skills.list", () => {
|
||||
it("includes legacy personal skills when listing a personal publisher", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:owner" as never);
|
||||
const legacySkill = makeSkill({
|
||||
const legacySkill = {
|
||||
_id: "skills:legacy",
|
||||
_creationTime: 1,
|
||||
slug: "legacy-skill",
|
||||
displayName: "Legacy Skill",
|
||||
summary: "Pre-backfill skill",
|
||||
});
|
||||
ownerUserId: "users:owner",
|
||||
ownerPublisherId: undefined,
|
||||
canonicalSkillId: undefined,
|
||||
forkOf: undefined,
|
||||
latestVersionId: undefined,
|
||||
tags: {},
|
||||
badges: undefined,
|
||||
stats: {
|
||||
downloads: 0,
|
||||
installsCurrent: 0,
|
||||
installsAllTime: 0,
|
||||
stars: 0,
|
||||
versions: 1,
|
||||
comments: 0,
|
||||
},
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
softDeletedAt: undefined,
|
||||
moderationStatus: "active",
|
||||
moderationFlags: [],
|
||||
moderationReason: undefined,
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
@@ -139,118 +121,4 @@ describe("skills.list", () => {
|
||||
|
||||
expect(result).toEqual([expect.objectContaining({ slug: "legacy-skill" })]);
|
||||
});
|
||||
|
||||
it("includes non-public flagged skills for the owning user dashboard", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:owner" as never);
|
||||
const blockedSkill = makeSkill({
|
||||
slug: "blocked-skill",
|
||||
moderationStatus: "hidden",
|
||||
moderationFlags: ["blocked.malware"],
|
||||
moderationReason: "scanner.vt.malicious",
|
||||
moderationVerdict: "malicious",
|
||||
isSuspicious: true,
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "users:owner") {
|
||||
return {
|
||||
_id: "users:owner",
|
||||
_creationTime: 1,
|
||||
handle: "owner",
|
||||
displayName: "Owner",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "skills") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({
|
||||
take: vi.fn().mockResolvedValue([blockedSkill]),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (table === "skillBadges") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
take: vi.fn().mockResolvedValue([]),
|
||||
})),
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const result = await listHandler(
|
||||
ctx as never,
|
||||
{ ownerUserId: "users:owner", limit: 10 } as never,
|
||||
);
|
||||
|
||||
expect(result).toEqual([
|
||||
expect.objectContaining({
|
||||
slug: "blocked-skill",
|
||||
moderationStatus: "hidden",
|
||||
moderationVerdict: "malicious",
|
||||
stats: expect.objectContaining({ downloads: 7, stars: 3 }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not expose non-public flagged skills to non-owner list callers", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue(null);
|
||||
const blockedSkill = makeSkill({
|
||||
slug: "blocked-skill",
|
||||
moderationStatus: "hidden",
|
||||
moderationFlags: ["blocked.malware"],
|
||||
moderationReason: "scanner.vt.malicious",
|
||||
moderationVerdict: "malicious",
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
db: {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "users:owner") {
|
||||
return {
|
||||
_id: "users:owner",
|
||||
_creationTime: 1,
|
||||
handle: "owner",
|
||||
displayName: "Owner",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "skills") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({
|
||||
take: vi.fn().mockResolvedValue([blockedSkill]),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (table === "skillBadges") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
take: vi.fn().mockResolvedValue([]),
|
||||
})),
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const result = await listHandler(
|
||||
ctx as never,
|
||||
{ ownerUserId: "users:owner", limit: 10 } as never,
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,16 +57,6 @@ function makeCtx(params: { skill: Record<string, unknown>; version?: Record<stri
|
||||
};
|
||||
}
|
||||
|
||||
if (table === "rescanRequests") {
|
||||
return {
|
||||
withIndex: vi.fn(() => ({
|
||||
order: vi.fn(() => ({
|
||||
take: vi.fn(async () => []),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected query table: ${table}`);
|
||||
});
|
||||
const get = vi.fn(async (id: string) => {
|
||||
@@ -436,66 +426,4 @@ describe("skills manual overrides", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("clears legacy suspicious state when LLM corroborates clean VT Code Insight-only suspicious", async () => {
|
||||
const now = 1_700_000_400_000;
|
||||
vi.spyOn(Date, "now").mockReturnValue(now);
|
||||
|
||||
const skill = {
|
||||
_id: "skills:1",
|
||||
ownerUserId: "users:owner",
|
||||
latestVersionId: "skillVersions:9",
|
||||
softDeletedAt: undefined,
|
||||
moderationStatus: "hidden",
|
||||
moderationReason: "scanner.vt.suspicious",
|
||||
moderationVerdict: "suspicious",
|
||||
moderationFlags: ["flagged.suspicious"],
|
||||
};
|
||||
const version = {
|
||||
_id: "skillVersions:9",
|
||||
skillId: "skills:1",
|
||||
staticScan: {
|
||||
status: "clean",
|
||||
reasonCodes: [],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: now - 200,
|
||||
},
|
||||
vtAnalysis: {
|
||||
status: "suspicious",
|
||||
scanner: "code_insight",
|
||||
engineStats: {
|
||||
malicious: 0,
|
||||
suspicious: 0,
|
||||
harmless: 12,
|
||||
undetected: 54,
|
||||
},
|
||||
checkedAt: now - 100,
|
||||
},
|
||||
llmAnalysis: undefined,
|
||||
};
|
||||
|
||||
const { ctx, patch } = makeCtx({ skill, version });
|
||||
|
||||
await updateVersionLlmAnalysisInternalHandler(ctx, {
|
||||
versionId: "skillVersions:9",
|
||||
llmAnalysis: {
|
||||
status: "clean",
|
||||
checkedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
expect(patch).toHaveBeenCalledWith(
|
||||
"skills:1",
|
||||
expect.objectContaining({
|
||||
moderationStatus: "active",
|
||||
moderationReason: "scanner.aggregate.clean",
|
||||
moderationFlags: undefined,
|
||||
moderationVerdict: "clean",
|
||||
moderationReasonCodes: undefined,
|
||||
isSuspicious: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
getActiveSkillBatchForStaticScanBackfillInternal,
|
||||
getPendingScanSkillsInternal,
|
||||
} from "./skills";
|
||||
import { MODERATION_ENGINE_VERSION } from "./lib/moderationReasonCodes";
|
||||
|
||||
type PendingScanResult = Array<{
|
||||
skillId: string;
|
||||
@@ -192,7 +191,7 @@ describe("skills.getPendingScanSkillsInternal", () => {
|
||||
const versionId = skill.latestVersionId as string;
|
||||
return [
|
||||
versionId,
|
||||
{ _id: versionId, sha256hash: `${versionId.slice(-8)}${"f".repeat(56)}` },
|
||||
{ _id: versionId, sha256hash: `${String(versionId).slice(-8)}${"f".repeat(56)}` },
|
||||
];
|
||||
}),
|
||||
);
|
||||
@@ -280,7 +279,7 @@ describe("skills.getActiveSkillBatchForStaticScanBackfillInternal", () => {
|
||||
"skillVersions:current-static",
|
||||
{
|
||||
_id: "skillVersions:current-static",
|
||||
staticScan: { engineVersion: MODERATION_ENGINE_VERSION },
|
||||
staticScan: { engineVersion: "v2.4.0" },
|
||||
},
|
||||
],
|
||||
[
|
||||
|
||||
@@ -7,7 +7,6 @@ vi.mock("@convex-dev/auth/server", () => ({
|
||||
|
||||
import {
|
||||
approveSkillByHashInternal,
|
||||
backfillLatestSkillModerationInternal,
|
||||
clearOwnerSuspiciousFlagsInternal,
|
||||
escalateSkillByIdInternal,
|
||||
escalateByVtInternal,
|
||||
@@ -29,9 +28,6 @@ const escalateSkillByIdHandler = (
|
||||
const escalateByVtHandler = (
|
||||
escalateByVtInternal as unknown as WrappedHandler<Record<string, unknown>>
|
||||
)._handler;
|
||||
const backfillLatestSkillModerationHandler = (
|
||||
backfillLatestSkillModerationInternal as unknown as WrappedHandler<Record<string, unknown>>
|
||||
)._handler;
|
||||
const clearOwnerSuspiciousFlagsHandler = (
|
||||
clearOwnerSuspiciousFlagsInternal as unknown as WrappedHandler<Record<string, unknown>>
|
||||
)._handler;
|
||||
@@ -657,7 +653,7 @@ describe("skills anti-spam guards", () => {
|
||||
const runAfter = vi.fn();
|
||||
const db = {
|
||||
get: vi.fn(async (tableOrId: string, maybeId?: string) => {
|
||||
const key = maybeId ?? tableOrId;
|
||||
const key = String(maybeId ?? tableOrId);
|
||||
if (storedSkills.has(key)) return storedSkills.get(key);
|
||||
if (key === "users:owner") {
|
||||
return {
|
||||
@@ -763,7 +759,7 @@ describe("skills anti-spam guards", () => {
|
||||
patch,
|
||||
insert,
|
||||
normalizeId: vi.fn((tableName: string, id: string) =>
|
||||
id.startsWith(`${tableName}:`) ? id : null,
|
||||
String(id).startsWith(`${tableName}:`) ? id : null,
|
||||
),
|
||||
};
|
||||
|
||||
@@ -844,7 +840,7 @@ describe("skills anti-spam guards", () => {
|
||||
});
|
||||
const db = {
|
||||
get: vi.fn(async (tableOrId: string, maybeId?: string) => {
|
||||
const key = maybeId ?? tableOrId;
|
||||
const key = String(maybeId ?? tableOrId);
|
||||
if (storedSkills.has(key)) return storedSkills.get(key);
|
||||
if (key === "users:owner") {
|
||||
return {
|
||||
@@ -952,7 +948,7 @@ describe("skills anti-spam guards", () => {
|
||||
patch,
|
||||
insert,
|
||||
normalizeId: vi.fn((tableName: string, id: string) =>
|
||||
id.startsWith(`${tableName}:`) ? id : null,
|
||||
String(id).startsWith(`${tableName}:`) ? id : null,
|
||||
),
|
||||
};
|
||||
|
||||
@@ -1151,63 +1147,6 @@ describe("skills anti-spam guards", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores non-latest versions when approving by hash", async () => {
|
||||
const patch = vi.fn(async () => {});
|
||||
const version = {
|
||||
_id: "skillVersions:old",
|
||||
skillId: "skills:1",
|
||||
staticScan: {
|
||||
status: "suspicious",
|
||||
reasonCodes: ["suspicious.dynamic_code_execution"],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
vtAnalysis: { status: "suspicious" },
|
||||
llmAnalysis: { status: "clean" },
|
||||
};
|
||||
const skill = {
|
||||
_id: "skills:1",
|
||||
slug: "rollback-helper",
|
||||
ownerUserId: "users:owner",
|
||||
latestVersionId: "skillVersions:latest",
|
||||
moderationFlags: undefined,
|
||||
moderationReason: "scanner.vt.clean",
|
||||
};
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "skills:1") return skill;
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "skillVersions") {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
unique: async () => version,
|
||||
}),
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
patch,
|
||||
insert: vi.fn(),
|
||||
normalizeId: vi.fn(),
|
||||
};
|
||||
|
||||
await approveSkillByHashHandler(
|
||||
{ db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{
|
||||
sha256hash: "h".repeat(64),
|
||||
scanner: "vt",
|
||||
status: "clean",
|
||||
} as never,
|
||||
);
|
||||
|
||||
expect(patch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("vt suspicious escalation does not keep suspicious flags for admin owners", async () => {
|
||||
const patch = vi.fn(async () => {});
|
||||
const version = { _id: "skillVersions:1", skillId: "skills:1" };
|
||||
@@ -1266,147 +1205,6 @@ describe("skills anti-spam guards", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("vt suspicious escalation clears legacy quarantine for uncorroborated Code Insight", async () => {
|
||||
const patch = vi.fn(async () => {});
|
||||
const version = {
|
||||
_id: "skillVersions:1",
|
||||
skillId: "skills:1",
|
||||
staticScan: {
|
||||
status: "clean",
|
||||
reasonCodes: [],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
vtAnalysis: {
|
||||
status: "suspicious",
|
||||
scanner: "code_insight",
|
||||
engineStats: {
|
||||
malicious: 0,
|
||||
suspicious: 0,
|
||||
harmless: 12,
|
||||
undetected: 54,
|
||||
},
|
||||
},
|
||||
llmAnalysis: { status: "clean" },
|
||||
};
|
||||
const skill = {
|
||||
_id: "skills:1",
|
||||
slug: "doc-only",
|
||||
ownerUserId: "users:owner",
|
||||
latestVersionId: "skillVersions:1",
|
||||
moderationStatus: "hidden",
|
||||
moderationFlags: ["flagged.suspicious"],
|
||||
moderationReason: "scanner.vt.suspicious",
|
||||
};
|
||||
const owner = {
|
||||
_id: "users:owner",
|
||||
role: "user",
|
||||
deletedAt: undefined,
|
||||
};
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "skills:1") return skill;
|
||||
if (id === "users:owner") return owner;
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table);
|
||||
if (globalStatsQuery) return globalStatsQuery;
|
||||
const digestQuery = buildDigestQuery(table);
|
||||
if (digestQuery) return digestQuery;
|
||||
if (table === "skillVersions") {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
unique: async () => version,
|
||||
}),
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
patch,
|
||||
insert: vi.fn(),
|
||||
normalizeId: vi.fn(),
|
||||
};
|
||||
|
||||
await escalateByVtHandler(
|
||||
{ db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{
|
||||
sha256hash: "h".repeat(64),
|
||||
status: "suspicious",
|
||||
} as never,
|
||||
);
|
||||
|
||||
expect(patch).toHaveBeenCalledWith(
|
||||
"skills:1",
|
||||
expect.objectContaining({
|
||||
moderationStatus: "active",
|
||||
moderationFlags: undefined,
|
||||
moderationReason: "scanner.vt.clean",
|
||||
moderationVerdict: "clean",
|
||||
moderationReasonCodes: undefined,
|
||||
isSuspicious: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores vt escalation for non-latest versions", async () => {
|
||||
const patch = vi.fn(async () => {});
|
||||
const version = {
|
||||
_id: "skillVersions:old",
|
||||
skillId: "skills:1",
|
||||
staticScan: {
|
||||
status: "suspicious",
|
||||
reasonCodes: ["suspicious.dynamic_code_execution"],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
llmAnalysis: { status: "clean" },
|
||||
};
|
||||
const skill = {
|
||||
_id: "skills:1",
|
||||
slug: "rollback-helper",
|
||||
ownerUserId: "users:owner",
|
||||
latestVersionId: "skillVersions:latest",
|
||||
moderationFlags: undefined,
|
||||
moderationReason: "scanner.vt.clean",
|
||||
};
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "skills:1") return skill;
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
if (table === "skillVersions") {
|
||||
return {
|
||||
withIndex: () => ({
|
||||
unique: async () => version,
|
||||
}),
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
patch,
|
||||
insert: vi.fn(),
|
||||
normalizeId: vi.fn(),
|
||||
};
|
||||
|
||||
await escalateByVtHandler(
|
||||
{ db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{
|
||||
sha256hash: "h".repeat(64),
|
||||
status: "suspicious",
|
||||
} as never,
|
||||
);
|
||||
|
||||
expect(patch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rebuilds structured moderation state for legacy skillId escalation", async () => {
|
||||
const patch = vi.fn(async () => {});
|
||||
const version = {
|
||||
@@ -1559,104 +1357,4 @@ describe("skills anti-spam guards", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("re-syncs stale skill moderation from latestVersionId during backfill", async () => {
|
||||
const paginate = vi.fn().mockResolvedValue({
|
||||
page: [
|
||||
{
|
||||
_id: "skills:1",
|
||||
slug: "rollback-helper",
|
||||
ownerUserId: "users:owner",
|
||||
latestVersionId: "skillVersions:latest",
|
||||
moderationSourceVersionId: "skillVersions:old",
|
||||
moderationStatus: "hidden",
|
||||
moderationReason: "scanner.vt.suspicious",
|
||||
moderationFlags: ["flagged.suspicious"],
|
||||
manualOverride: undefined,
|
||||
softDeletedAt: undefined,
|
||||
},
|
||||
{
|
||||
_id: "skills:manual",
|
||||
slug: "manually-reviewed",
|
||||
ownerUserId: "users:owner",
|
||||
latestVersionId: "skillVersions:latest",
|
||||
moderationSourceVersionId: "skillVersions:old",
|
||||
moderationStatus: "active",
|
||||
moderationReason: "user.moderation",
|
||||
moderationFlags: undefined,
|
||||
manualOverride: undefined,
|
||||
softDeletedAt: undefined,
|
||||
},
|
||||
],
|
||||
continueCursor: null,
|
||||
isDone: true,
|
||||
});
|
||||
const patch = vi.fn(async () => {});
|
||||
const latestVersion = {
|
||||
_id: "skillVersions:latest",
|
||||
staticScan: {
|
||||
status: "clean",
|
||||
reasonCodes: [],
|
||||
findings: [],
|
||||
summary: "",
|
||||
engineVersion: "v2.1.1",
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
vtAnalysis: { status: "clean" },
|
||||
llmAnalysis: { status: "clean" },
|
||||
};
|
||||
const owner = {
|
||||
_id: "users:owner",
|
||||
role: "user",
|
||||
_creationTime: Date.now() - 60 * 24 * 60 * 60 * 1000,
|
||||
createdAt: Date.now() - 60 * 24 * 60 * 60 * 1000,
|
||||
deletedAt: undefined,
|
||||
};
|
||||
|
||||
const db = {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "skillVersions:latest") return latestVersion;
|
||||
if (id === "users:owner") return owner;
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn((table: string) => {
|
||||
const globalStatsQuery = buildGlobalStatsQuery(table);
|
||||
if (globalStatsQuery) return globalStatsQuery;
|
||||
if (table === "skills") {
|
||||
return {
|
||||
paginate,
|
||||
};
|
||||
}
|
||||
throw new Error(`unexpected table ${table}`);
|
||||
}),
|
||||
patch,
|
||||
insert: vi.fn(),
|
||||
normalizeId: vi.fn(),
|
||||
};
|
||||
|
||||
const result = await backfillLatestSkillModerationHandler(
|
||||
{ db, scheduler: { runAfter: vi.fn() } } as never,
|
||||
{ batchSize: 10 } as never,
|
||||
);
|
||||
|
||||
expect(result).toEqual({ patched: 1, isDone: true, scanned: 2 });
|
||||
expect(patch).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"skills:1",
|
||||
expect.objectContaining({
|
||||
moderationStatus: "active",
|
||||
moderationReason: "scanner.vt.clean",
|
||||
moderationFlags: undefined,
|
||||
moderationVerdict: "clean",
|
||||
moderationSourceVersionId: "skillVersions:latest",
|
||||
}),
|
||||
);
|
||||
expect(patch).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"globalStats:1",
|
||||
expect.objectContaining({
|
||||
activeSkillsCount: 101,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { v } from "convex/values";
|
||||
import { mutation, query } from "./functions";
|
||||
import { getOptionalActiveAuthUserId, requireUser } from "./lib/access";
|
||||
import { requireUser } from "./lib/access";
|
||||
import { toPublicSoul } from "./lib/public";
|
||||
|
||||
export const isStarred = query({
|
||||
args: { soulId: v.id("souls") },
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await getOptionalActiveAuthUserId(ctx);
|
||||
if (!userId) return false;
|
||||
const { userId } = await requireUser(ctx);
|
||||
const existing = await ctx.db
|
||||
.query("soulStars")
|
||||
.withIndex("by_soul_user", (q) => q.eq("soulId", args.soulId).eq("userId", userId))
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
/* @vitest-environment node */
|
||||
|
||||
import { getAuthUserId } from "@convex-dev/auth/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { isStarred } from "./stars";
|
||||
import { isStarred as isSoulStarred } from "./soulStars";
|
||||
|
||||
vi.mock("@convex-dev/auth/server", () => ({
|
||||
getAuthUserId: vi.fn(),
|
||||
}));
|
||||
|
||||
function unwrapHandler(wrapped: unknown) {
|
||||
const handler = (wrapped as { _handler?: unknown })._handler;
|
||||
if (typeof handler !== "function") {
|
||||
throw new Error("Expected Convex test wrapper to expose _handler");
|
||||
}
|
||||
return handler;
|
||||
}
|
||||
|
||||
const isStarredHandler = unwrapHandler(isStarred) as (
|
||||
ctx: unknown,
|
||||
args: { skillId: string },
|
||||
) => Promise<boolean>;
|
||||
const isSoulStarredHandler = unwrapHandler(isSoulStarred) as (
|
||||
ctx: unknown,
|
||||
args: { soulId: string },
|
||||
) => Promise<boolean>;
|
||||
|
||||
function makeCtx(options: { user?: Record<string, unknown> | null; existingStar?: unknown }) {
|
||||
return {
|
||||
db: {
|
||||
get: vi.fn(async (id: string) => {
|
||||
if (id === "users:viewer") return options.user ?? { _id: "users:viewer" };
|
||||
return null;
|
||||
}),
|
||||
query: vi.fn(() => ({
|
||||
withIndex: vi.fn(() => ({
|
||||
unique: vi.fn().mockResolvedValue(options.existingStar ?? null),
|
||||
})),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getAuthUserId).mockReset();
|
||||
});
|
||||
|
||||
describe("stars queries", () => {
|
||||
it("returns false instead of throwing when skill star auth is stale", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:viewer" as never);
|
||||
|
||||
await expect(
|
||||
isStarredHandler(makeCtx({ user: null }), { skillId: "skills:demo" }),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("returns false instead of throwing when soul star auth is stale", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:viewer" as never);
|
||||
|
||||
await expect(
|
||||
isSoulStarredHandler(makeCtx({ user: null }), { soulId: "souls:demo" }),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("still reports existing stars for active users", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:viewer" as never);
|
||||
|
||||
await expect(
|
||||
isStarredHandler(makeCtx({ existingStar: { _id: "stars:demo" } }), {
|
||||
skillId: "skills:demo",
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("still reports existing soul stars for active users", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:viewer" as never);
|
||||
|
||||
await expect(
|
||||
isSoulStarredHandler(makeCtx({ existingStar: { _id: "soulStars:demo" } }), {
|
||||
soulId: "souls:demo",
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,13 @@
|
||||
import { v } from "convex/values";
|
||||
import { internalMutation, mutation, query } from "./functions";
|
||||
import { getOptionalActiveAuthUserId, requireUser } from "./lib/access";
|
||||
import { requireUser } from "./lib/access";
|
||||
import { toPublicSkill } from "./lib/public";
|
||||
import { insertStatEvent } from "./skillStatEvents";
|
||||
|
||||
export const isStarred = query({
|
||||
args: { skillId: v.id("skills") },
|
||||
handler: async (ctx, args) => {
|
||||
const userId = await getOptionalActiveAuthUserId(ctx);
|
||||
if (!userId) return false;
|
||||
const { userId } = await requireUser(ctx);
|
||||
const existing = await ctx.db
|
||||
.query("stars")
|
||||
.withIndex("by_skill_user", (q) => q.eq("skillId", args.skillId).eq("userId", userId))
|
||||
|
||||
@@ -3,20 +3,15 @@ import { internal } from "./_generated/api";
|
||||
import type { Doc, Id } from "./_generated/dataModel";
|
||||
import type { ActionCtx, MutationCtx, QueryCtx } from "./_generated/server";
|
||||
import { internalAction, internalMutation, internalQuery, mutation, query } from "./functions";
|
||||
import {
|
||||
assertAdmin,
|
||||
assertModerator,
|
||||
getOptionalActiveAuthUserId,
|
||||
requireUser,
|
||||
} from "./lib/access";
|
||||
import { assertAdmin, assertModerator, getOptionalActiveAuthUserId, requireUser } from "./lib/access";
|
||||
import { syncGitHubProfile } from "./lib/githubAccount";
|
||||
import { toPublicUser } from "./lib/public";
|
||||
import {
|
||||
ensurePersonalPublisherForUser,
|
||||
getActiveUserByHandleOrPersonalPublisher,
|
||||
getPublisherByHandle,
|
||||
getUserByHandleOrPersonalPublisher,
|
||||
} from "./lib/publishers";
|
||||
import { toPublicUser } from "./lib/public";
|
||||
import {
|
||||
getLatestActiveReservedHandle,
|
||||
isHandleReservedForAnotherUser,
|
||||
@@ -301,9 +296,7 @@ export async function ensureHandler(ctx: MutationCtx) {
|
||||
updates.updatedAt = Date.now();
|
||||
await ctx.db.patch(userId, updates);
|
||||
}
|
||||
const ensuredUser = hasUpdates
|
||||
? ({ ...user, ...updates } as Doc<"users">)
|
||||
: ((await ctx.db.get(userId)) ?? user);
|
||||
const ensuredUser = hasUpdates ? ({ ...user, ...updates } as Doc<"users">) : ((await ctx.db.get(userId)) ?? user);
|
||||
await ensurePersonalPublisherForUser(ctx, ensuredUser);
|
||||
return await ctx.db.get(userId);
|
||||
}
|
||||
@@ -452,9 +445,7 @@ async function queryUsersForPublicList(
|
||||
: clampInt(args.limit * 6, args.limit, MAX_USER_SEARCH_SCAN);
|
||||
const scannedUsers = await ctx.db
|
||||
.query("users")
|
||||
.withIndex("by_active_handle", (q) =>
|
||||
q.eq("deletedAt", undefined).eq("deactivatedAt", undefined),
|
||||
)
|
||||
.withIndex("by_active_handle", (q) => q.eq("deletedAt", undefined).eq("deactivatedAt", undefined))
|
||||
.order("desc")
|
||||
.take(scanLimit);
|
||||
const activeUsers = scannedUsers.filter((user) => Boolean(user.handle));
|
||||
@@ -908,8 +899,7 @@ async function ensurePublisherHandleWithActor(
|
||||
|
||||
if (existing) {
|
||||
const nextDisplayName =
|
||||
args.displayName?.trim() &&
|
||||
(!existing.displayName || existing.displayName === existing.handle)
|
||||
args.displayName?.trim() && (!existing.displayName || existing.displayName === existing.handle)
|
||||
? displayName
|
||||
: existing.displayName;
|
||||
await ctx.db.patch(existing._id, {
|
||||
|
||||
@@ -92,7 +92,6 @@ describe("version file access actions", () => {
|
||||
it("allows owners to read hidden skill versions", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:owner" as never);
|
||||
const ctx = makeActionCtx({
|
||||
actor: { _id: "users:owner", role: "user" },
|
||||
version: makeSkillVersion(),
|
||||
skill: {
|
||||
_id: "skills:1",
|
||||
@@ -134,7 +133,6 @@ describe("version file access actions", () => {
|
||||
it("allows owners to read hidden skill files", async () => {
|
||||
vi.mocked(getAuthUserId).mockResolvedValue("users:owner" as never);
|
||||
const ctx = makeActionCtx({
|
||||
actor: { _id: "users:owner", role: "user" },
|
||||
version: makeSkillVersion(),
|
||||
skill: {
|
||||
_id: "skills:1",
|
||||
|
||||
@@ -92,26 +92,6 @@ describe("vt activation fallback", () => {
|
||||
});
|
||||
|
||||
describe("vt AV engine fallback verdicts", () => {
|
||||
it("strips unsupported VT stat keys before caching", () => {
|
||||
expect(
|
||||
__test.normalizeVtEngineStats({
|
||||
"confirmed-timeout": 0,
|
||||
failure: 2,
|
||||
harmless: 0,
|
||||
malicious: 0,
|
||||
suspicious: 0,
|
||||
timeout: 0,
|
||||
"type-unsupported": 10,
|
||||
undetected: 64,
|
||||
} as never),
|
||||
).toEqual({
|
||||
harmless: 0,
|
||||
malicious: 0,
|
||||
suspicious: 0,
|
||||
undetected: 64,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps engine verdicts in severity order", () => {
|
||||
expect(
|
||||
__test.statusFromAvStats({
|
||||
|
||||
@@ -166,16 +166,6 @@ type PackageReleaseScanDoc = Pick<
|
||||
>;
|
||||
type PackageScanDoc = Pick<Doc<"packages">, "family" | "isOfficial">;
|
||||
|
||||
function normalizeVtEngineStats(stats?: VTAnalysisStats | null) {
|
||||
if (!stats) return undefined;
|
||||
return {
|
||||
malicious: stats.malicious,
|
||||
suspicious: stats.suspicious,
|
||||
undetected: stats.undetected,
|
||||
harmless: stats.harmless,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPackageUndetectedFallbackAnalysis(
|
||||
release: PackageReleaseScanDoc,
|
||||
pkg: PackageScanDoc,
|
||||
@@ -213,14 +203,11 @@ function buildPackageScanAnalysisFromVtResult(
|
||||
);
|
||||
if (aiResult) {
|
||||
const verdict = normalizeVerdict(aiResult.verdict);
|
||||
const stats = vtResult.data.attributes.last_analysis_stats;
|
||||
return {
|
||||
status: verdictToStatus(verdict),
|
||||
verdict: aiResult.verdict,
|
||||
analysis: aiResult.analysis,
|
||||
source: aiResult.source,
|
||||
scanner: "code_insight",
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -524,7 +511,6 @@ export const scanWithVirusTotal = internalAction({
|
||||
);
|
||||
|
||||
if (aiResult) {
|
||||
const stats = existingFile.data.attributes.last_analysis_stats;
|
||||
// File exists and has AI analysis - use the verdict
|
||||
const verdict = normalizeVerdict(aiResult.verdict);
|
||||
const status = verdictToStatus(verdict);
|
||||
@@ -540,8 +526,6 @@ export const scanWithVirusTotal = internalAction({
|
||||
verdict: aiResult.verdict,
|
||||
analysis: aiResult.analysis,
|
||||
source: aiResult.source,
|
||||
scanner: "code_insight",
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
@@ -782,11 +766,6 @@ export const pollPackageReleaseScanResults = internalAction({
|
||||
attempt: attempt + 1,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
await runMutationRef(ctx, internalRefs.packages.updateReleaseScanResultsInternal, {
|
||||
releaseId: args.releaseId,
|
||||
vtAnalysis: { status: "stale", checkedAt: Date.now() },
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -811,11 +790,6 @@ export const pollPackageReleaseScanResults = internalAction({
|
||||
attempt: attempt + 1,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
await runMutationRef(ctx, internalRefs.packages.updateReleaseScanResultsInternal, {
|
||||
releaseId: args.releaseId,
|
||||
vtAnalysis: { status: "stale", checkedAt: Date.now() },
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[vt:package] Error polling ${release.sha256hash}:`, error);
|
||||
@@ -829,11 +803,6 @@ export const pollPackageReleaseScanResults = internalAction({
|
||||
attempt: attempt + 1,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
await runMutationRef(ctx, internalRefs.packages.updateReleaseScanResultsInternal, {
|
||||
releaseId: args.releaseId,
|
||||
vtAnalysis: { status: "error", checkedAt: Date.now() },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -945,7 +914,6 @@ export const pollPendingScans = internalAction({
|
||||
vtAnalysis: {
|
||||
status,
|
||||
source,
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
@@ -984,7 +952,6 @@ export const pollPendingScans = internalAction({
|
||||
// We have a verdict - update the skill
|
||||
const verdict = normalizeVerdict(aiResult.verdict);
|
||||
const status = verdictToStatus(verdict);
|
||||
const stats = vtResult.data.attributes.last_analysis_stats;
|
||||
|
||||
console.log(
|
||||
`[vt:pollPendingScans] Hash ${sha256hash} verdict: ${verdict} -> status: ${status}`,
|
||||
@@ -998,8 +965,6 @@ export const pollPendingScans = internalAction({
|
||||
verdict: aiResult.verdict,
|
||||
analysis: aiResult.analysis,
|
||||
source: aiResult.source,
|
||||
scanner: "code_insight",
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
@@ -1081,7 +1046,6 @@ async function requestRescan(apiKey: string, sha256hash: string): Promise<boolea
|
||||
}
|
||||
|
||||
export const __test = {
|
||||
normalizeVtEngineStats,
|
||||
statusFromAvStats,
|
||||
shouldActivateWhenVtUnavailable,
|
||||
};
|
||||
@@ -1285,7 +1249,6 @@ export const rescanActiveSkills = internalAction({
|
||||
vtAnalysis: {
|
||||
status,
|
||||
source,
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
@@ -1315,7 +1278,6 @@ export const rescanActiveSkills = internalAction({
|
||||
|
||||
const verdict = normalizeVerdict(aiResult.verdict);
|
||||
const status = verdictToStatus(verdict);
|
||||
const stats = vtResult.data.attributes.last_analysis_stats;
|
||||
|
||||
await ctx.runMutation(internal.skills.updateVersionScanResultsInternal, {
|
||||
versionId,
|
||||
@@ -1324,8 +1286,6 @@ export const rescanActiveSkills = internalAction({
|
||||
verdict: aiResult.verdict,
|
||||
analysis: aiResult.analysis,
|
||||
source: aiResult.source,
|
||||
scanner: "code_insight",
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
@@ -1616,7 +1576,6 @@ export const backfillActiveSkillsVTCache = internalAction({
|
||||
// Update the version with VT analysis
|
||||
const verdict = normalizeVerdict(aiResult.verdict);
|
||||
const status = verdictToStatus(verdict);
|
||||
const stats = vtResult.data.attributes.last_analysis_stats;
|
||||
|
||||
await ctx.runMutation(internal.skills.updateVersionScanResultsInternal, {
|
||||
versionId,
|
||||
@@ -1626,8 +1585,6 @@ export const backfillActiveSkillsVTCache = internalAction({
|
||||
verdict: aiResult.verdict,
|
||||
analysis: aiResult.analysis,
|
||||
source: aiResult.source,
|
||||
scanner: "code_insight",
|
||||
engineStats: normalizeVtEngineStats(stats),
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -11,19 +11,6 @@ Base: `https://clawhub.ai`
|
||||
|
||||
OpenAPI: `/api/v1/openapi.json`
|
||||
|
||||
## Public catalog reuse
|
||||
|
||||
You can build a third-party catalog, directory, or search surface on top of ClawHub's public read APIs. Public skill metadata and skill files are published under ClawHub's skill license rules, while the API itself is rate-limited and should be consumed responsibly.
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Use public read endpoints such as `GET /api/v1/skills`, `GET /api/v1/search`, and `GET /api/v1/skills/{slug}` for catalog listings.
|
||||
- Cache responses and respect `429`, `Retry-After`, and rate-limit headers instead of polling aggressively.
|
||||
- Link back to the canonical ClawHub skill URL when displaying listings so users can inspect the source registry record.
|
||||
- Use canonical page URLs in the form `https://clawhub.ai/<owner>/<slug>`.
|
||||
- Do not imply that ClawHub endorses, verifies, or operates the third-party site.
|
||||
- Do not mirror hidden, private, or moderation-blocked content by bypassing public API filters or auth boundaries.
|
||||
|
||||
## Auth
|
||||
|
||||
- Public read: no token required.
|
||||
|
||||
@@ -141,7 +141,6 @@ Stores your API token + cached registry URL.
|
||||
- Requires semver: `--version 1.2.3`.
|
||||
- Publishing a skill means it is released under `MIT-0` on ClawHub.
|
||||
- Published skills are free to use, modify, and redistribute without attribution.
|
||||
- ClawHub does not support paid skills or per-skill pricing.
|
||||
- Legacy alias: `publish <path>`.
|
||||
|
||||
### `delete <slug>`
|
||||
@@ -213,36 +212,6 @@ Stores your API token + cached registry URL.
|
||||
- `--fuzzy` resolves the handle via fuzzy user search (admin only).
|
||||
- `--yes` skips confirmation.
|
||||
|
||||
### `package explore [query...]`
|
||||
|
||||
- Browses or searches the unified package catalog via `GET /api/v1/packages` and `GET /api/v1/packages/search`.
|
||||
- Use this for plugins and other package-family entries; top-level `search` remains the skill search surface.
|
||||
- Flags:
|
||||
- `--family skill|code-plugin|bundle-plugin`
|
||||
- `--official`
|
||||
- `--executes-code`
|
||||
- `--limit <n>` (1-100, default: 25)
|
||||
- `--json`
|
||||
|
||||
Examples:
|
||||
|
||||
```bash
|
||||
clawhub package explore --family code-plugin
|
||||
clawhub package explore episodic-claw --family code-plugin
|
||||
```
|
||||
|
||||
### `package inspect <name>`
|
||||
|
||||
- Fetches package metadata without installing.
|
||||
- Use this for plugin metadata, compatibility, verification, source, and version/file inspection.
|
||||
- `--version <version>`: inspect a specific version (default: latest).
|
||||
- `--tag <tag>`: inspect a tagged version (e.g. `latest`).
|
||||
- `--versions`: list version history (first page).
|
||||
- `--limit <n>`: max versions to list (1-100).
|
||||
- `--files`: list files for the selected version.
|
||||
- `--file <path>`: fetch raw file content (text files only; 200KB limit).
|
||||
- `--json`: machine-readable output.
|
||||
|
||||
### `package publish <source>`
|
||||
|
||||
- Publishes a code plugin or bundle plugin via `POST /api/v1/packages`.
|
||||
@@ -261,53 +230,6 @@ clawhub package explore episodic-claw --family code-plugin
|
||||
- Existing flags (`--family`, `--name`, `--version`, `--source-repo`, `--source-commit`, `--source-ref`, `--source-path`) still work as overrides.
|
||||
- Private GitHub repos require `GITHUB_TOKEN`.
|
||||
|
||||
#### Recommended local flow
|
||||
|
||||
Use `--dry-run` first so you can confirm the resolved package metadata and
|
||||
source attribution before creating a live release:
|
||||
|
||||
```bash
|
||||
clawhub package publish ./my-plugin --family code-plugin --dry-run
|
||||
clawhub package publish ./my-plugin --family code-plugin
|
||||
```
|
||||
|
||||
#### Minimal `package.json` for `--family code-plugin`
|
||||
|
||||
External code plugins need a small amount of OpenClaw metadata in
|
||||
`package.json`. This minimal manifest is enough for a successful publish:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "@myorg/openclaw-my-plugin",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.3.24-beta.2"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.3.24-beta.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Required fields:
|
||||
|
||||
- `openclaw.compat.pluginApi`
|
||||
- `openclaw.build.openclawVersion`
|
||||
|
||||
Notes:
|
||||
|
||||
- `package.json.version` is your package release version, but it is not used as
|
||||
a fallback for OpenClaw compatibility/build validation.
|
||||
- `openclaw.compat.minGatewayVersion` and
|
||||
`openclaw.build.pluginSdkVersion` are optional extras if you want to publish
|
||||
more detailed compatibility metadata.
|
||||
- If you are using an older `clawhub` CLI release, upgrade before publishing so
|
||||
the local preflight checks run before upload.
|
||||
|
||||
#### GitHub Actions
|
||||
|
||||
ClawHub also ships an official reusable workflow at
|
||||
|
||||
@@ -52,7 +52,7 @@ Use the GitHub Actions workflow:
|
||||
gh workflow run clawhub-cli-npm-release.yml \
|
||||
--repo openclaw/clawhub \
|
||||
--ref main \
|
||||
-f tag=v0.11.0 \
|
||||
-f tag=v0.10.0 \
|
||||
-f preflight_only=true
|
||||
```
|
||||
|
||||
@@ -84,7 +84,7 @@ Ensure Convex env is set (auth + embeddings):
|
||||
- `OPENAI_API_KEY`
|
||||
- `SITE_URL` (your web app URL)
|
||||
- Optional webhook env (see `docs/webhook.md`)
|
||||
- Optional: `GITHUB_TOKEN` (recommended; raises GitHub API limits used by publish gates)
|
||||
- Optional: `GITHUB_TOKEN` (recommended; raises GitHub account lookup limit used by publish gate)
|
||||
|
||||
## 2) Deploy web app (Vercel)
|
||||
|
||||
|
||||
@@ -13,10 +13,6 @@ All v1 paths are under `/api/v1/...` and implemented by Convex HTTP routes (`con
|
||||
Legacy `/api/...` and `/api/cli/...` remain for compatibility (see `DEPRECATIONS.md`).
|
||||
OpenAPI: `/api/v1/openapi.json`.
|
||||
|
||||
## Public catalog reuse
|
||||
|
||||
Third-party directories may use the public read endpoints to list or search ClawHub skills. Please cache results, honor `429`/`Retry-After`, link users back to the canonical ClawHub listing (`https://clawhub.ai/<owner>/<slug>`), and avoid implying ClawHub endorsement of the third-party site. Do not attempt to mirror hidden, private, or moderation-blocked content outside the public API surface.
|
||||
|
||||
## Rate limits
|
||||
|
||||
Enforcement model:
|
||||
|
||||
@@ -106,54 +106,7 @@ bun clawhub skill publish . \
|
||||
--changelog "Initial release"
|
||||
```
|
||||
|
||||
## 5) Publish a code plugin
|
||||
|
||||
Create a plugin folder with a `package.json` that includes the required OpenClaw
|
||||
publish metadata:
|
||||
|
||||
```bash
|
||||
mkdir -p /tmp/clawhub-plugin-demo && cd /tmp/clawhub-plugin-demo
|
||||
cat > package.json <<'EOF'
|
||||
{
|
||||
"name": "@demo/openclaw-plugin-demo",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.3.24-beta.2"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.3.24-beta.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
```
|
||||
|
||||
Preview the resolved publish payload first:
|
||||
|
||||
```bash
|
||||
bun clawhub package publish . --family code-plugin --dry-run
|
||||
```
|
||||
|
||||
Then publish:
|
||||
|
||||
```bash
|
||||
bun clawhub package publish . --family code-plugin
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `openclaw.compat.pluginApi` and `openclaw.build.openclawVersion` are required
|
||||
for `code-plugin` publishes.
|
||||
- `package.json.version` does not replace either required OpenClaw field.
|
||||
- Add `openclaw.compat.minGatewayVersion` and
|
||||
`openclaw.build.pluginSdkVersion` when you want to expose fuller
|
||||
compatibility/build metadata, but they are not required for a successful
|
||||
publish.
|
||||
|
||||
## 6) Sync local skills (auto-publish new/changed)
|
||||
## 5) Sync local skills (auto-publish new/changed)
|
||||
|
||||
`sync` scans for local skill folders and publishes the ones that aren’t “synced” yet.
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 394 KiB |