- **End-User Friendly**: Make entries easy to understand for end users. For new features, explain what they actually do in plain language without heavy technical jargon. For bug fixes, describe what the bug was in a friendly, relatable way rather than focusing on internal code mechanics, file paths, or private symbols.
- **Formatting**: `- **<scope>**: <Description>` (e.g. `- **asset**: Fix an issue where moving a video to trash while it was still transcoding could cause it to lose its trashed status`).
Add any additional context, caveats, or follow-up work.
```
## Submission Rules
- **Strict Requirement**: A submission is considered complete **only** when there is a single final code state in which **all** of the following pass **simultaneously**:
- **Backend Testing Mandate**: Every backend feature, service method, workflow, and activity MUST be accompanied by comprehensive tests. Logic-heavy code without corresponding test coverage is considered incomplete.
- Fixes must be iterated until **no check causes any other check to fail**.
- **Type Safety**: The use of explicit `any` is strictly forbidden and will result in lint errors. You should use `unknown` instead when the type is not known. If you absolutely must use `any` due to a limitation (e.g. interacting with an untyped 3rd party library), you must add an eslint-disable comment (e.g., `// eslint-disable-next-line @typescript-eslint/no-explicit-any`) and include a comment directly above it clearly explaining _why_ we cannot be type-safe here.
- Do **not** submit intermediate states where some checks pass and others fail, even temporarily.
- **Cleanup Requirement**: Remove all verification related files (scripts, screenshots, `verification/` folder) before submit.
5.**Operations First**: If an Operation exists for an action (see [Operations](#operations)), API routes must call it via `runOperation` instead of re-implementing its permission checks and audit logging. UI-only routes (ordering, recents, settings, multi-id variants, etc.) keep calling services directly.
We follow Bun's monorepo conventions for dependency management:
1.**Self-Contained Packages**: Every workspace package MUST declare its own runtime `dependencies` in its local `package.json`. Do not rely on dependencies being available via the root.
2.**Shared DevDependencies**: Common development tools (e.g., `typescript`, `eslint`, `vitest`, `prisma`) MUST be declared in the root `package.json` to ensure version consistency across the workspace.
3.**Local DevDependencies**: Tools specific to a single package (e.g., `@vitejs/plugin-react` for `webui`) should be declared in that package's local `package.json`.
4.**Workspace Imports**: Use `workspace:*` for internal package dependencies.
5.**Clean Root**: The root `package.json` must not contain runtime `dependencies`. It is reserved for shared `devDependencies` and workspace-wide `scripts`.
6.**Adding Packages**: Never edit `package.json` manually to add new dependencies. Always use `bun add` (e.g., `bun add <package> --filter <workspace>`) from the root without specifying an explicit version, letting Bun resolve the correct version.
We use a root-level `tsconfig.json` to manage path mappings for the entire workspace. This ensures that imports across packages resolve correctly during typechecking and in the IDE.
1.**Path Mappings**: All workspace packages MUST have an entry in the `paths` object in the root `tsconfig.json`.
```json
"paths": {
"@shumai/core": ["packages/core/src/index.ts"],
"@shumai/core/src/*": ["packages/core/src/*"]
}
```
2. **Package tsconfig**: Each package should have its own `tsconfig.json` that extends the root configuration and defines its specific `include`/`exclude` rules.
3. **Cross-Package Resolution**: When adding a new package, you MUST update the root `tsconfig.json` path mappings to ensure it can be imported by other packages.
- **Route Chaining**: Always define API routes using method chaining on a Hono instance. This ensures that the type definitions for inputs and outputs are correctly inferred and preserved in the exported type.
- **Export Pattern**: Export the chained route instance as the default export.
```typescript
const app = new Hono()
const route = app
.get('/', ...)
.post('/', ...)
export default route
```
- **Type Safety**: Use `zValidator` for request validation (query, json, form) to ensure full end-to-end type safety with the Hono RPC client.
An **Operation** is a capability agents can use, defined once and exposed automatically on every surface: Shumai's built-in agent tools, the MCP server, and `shumai-cli`. Its implementation holds the policy (permission checks, audit logging) and orchestration; the work itself is done by core services.
- **Definition** (`packages/operations/src/**`, package `@shumai/operations`): name (snake_case, used as the tool name), title, description written for an LLM, Zod `input`/`output` schemas with `.describe()` on every field, `surfaces`, `annotations` (`readOnly`, `destructive`, `idempotent`), and optional `cli` metadata. This package must stay free of server dependencies (no `@shumai/core`/`@shumai/db`) so clients like the CLI can import it.
```typescript
export const createFolder = defineOperation({
name: 'create_folder',
title: 'Create Folder',
description: 'Create a new folder in a specified parent folder.',
- `authz` returns every permission the input requires; all are checked before any side effect.
- `execute` calls core services only. **Importing the `prisma` client in Operations is forbidden** (enforced by lint), which is stricter than DBOS activities. Add a service method if one is missing.
- `audit` returns entries; team/project are resolved from the affected asset, never trusted from the caller.
- Outputs are DTOs (validated against the output schema), never Prisma objects.
- **Register** the definition in `packages/operations/src/registry.ts` and the implementation in `packages/core/src/operations/registry.ts`. A definition without an implementation fails typecheck.
- **Run** Operations only through `runOperation(op, { userId, via, agentId? }, input)`. `via` (`api`, `agent`, `mcp`, `cli`) is recorded in audit logs.
- **Tests**: real-database tests per Operation covering success, permission denial (no side effects), and audit entries.
- **CLI spec**: object input fields must be listed in `cli.flatten` (one flag per sub-field, e.g. `{ videoConfig: 'video' }` → `--video-start`) or in `cli.omit` (optional fields the CLI doesn't expose).
- **Surface presentation**: by default each surface shows the Operation output as JSON. To add surface-only parameters or render output differently, add an extension for that surface:
- agent: `AgentToolExtension` in `packages/agent/src/operation-extensions/` (e.g. image blocks, saving downloads into the sandbox). `parameterOverrides` and `intercept` support agent-only modes, such as `download_asset` by storage key; `hiddenParameters` and `adjustParameters` reshape the tool for a session, such as `create_file` taking a sandbox path and the project's Creation Context schema;
`read_asset` is backed by a registry of readers in `packages/core/src/asset-read/readers/`, one per asset family (`model3d`, `image`, `video`, `document`). The shared pipeline (`assetReadService`) handles access checks, version stacks, annotations, render tasks, and waiting; a reader only contains type-specific logic.
To add a reader:
1. Add its kind to `READER_KINDS` and its options to `readerOptionSchemas` in `packages/operations/src/asset/read-asset.ts` (one optional `<name>Config` field on `read_asset`).
2. Implement `AssetReader` (`matches`, synchronous `validate`, `plan`, and `collect` if `plan` can return `render`), and add it to `readers` in `packages/core/src/asset-read/registry.ts`. Order matters: the first matching reader wins. A declared kind without a reader fails typecheck.
3. `plan` returns either `ready` with the result, or `render` with a workflow task spec and optional `context`. The pipeline stores the request on the task payload (`assetRead`), so `collect` and `get_asset_render` work across restarts and instances.
4. Use `badRequest(...)` for invalid input. Return storage keys in `ReadResult`; the pipeline turns them into short-lived links. Keys only go to server-side presenters (agent, MCP), which must not pass them on to clients.
- **Prefer System Colors**: Always prefer using semantic system color design tokens (e.g., `bg-background`, `text-foreground`, `text-sidebar-primary`, `text-muted-foreground`, etc.) over hardcoded color utilities (e.g., `bg-blue-50`, `text-emerald-600`, `bg-emerald-500`). This ensures seamless compatibility with light and dark themes.
To optimize initial bundle size, all routes must be code-split into `[route].tsx` (lightweight route definition and loaders) and `[route].lazy.tsx` (UI component and heavy imports).
We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite.
- **Mandatory Reproduction**: When fixing a backend bug, you MUST first write a test case that reproduces the bug (demonstrates the failure) before applying the fix. This ensures the bug is truly understood and prevents future regressions.
- For comprehensive testing against a real database instance, we use `Testcontainers` alongside a `PrismaTestingHelper` which wraps each test within an automatic PostgreSQL transaction rollback boundary.
- All service tests must use `setupTestDbHooks()` from `@shumai/db` to initialize the database boundaries for each test suite inside the `describe` block. This automatically registers `beforeEach` and `afterEach` hooks to manage transaction state.
- Import `prisma` from `@shumai/db` directly to interact with the database in tests. The testing helper automatically proxies it.
const team = await teamService.ensureDefaultTeam()
expect(team).toBeDefined()
expect(team.name).toBe('Default Team')
})
})
```
The `bunfig.toml` is configured to run `setup-tests.ts` automatically as a preload step. This initializes the `Testcontainers` PostgreSQL instance and applies migrations before the tests begin running.
- **Fixtures**: Use the `owner`, `project`, and `file` fixtures for setup — they seed data through API calls/DB (no slow UI setup). You can add more fixtures if necessary.
- **Documentation**: Every test case MUST be documented in [`apps/web/e2e/README.md`](apps/web/e2e/README.md). Add or update the corresponding entry in the README whenever you add, rename, or remove a spec.
- **Defining Types**: In `packages/db/prisma/schema.prisma`, annotate the JSON column with a triple-slash comment specifying the type name from `packages/db/src/prisma-json-types.ts`:
export type WorkflowTaskPayload = Record<string, unknown> | TaskSpec | AiTaskPayload
}
}
```
- **Usage**: When accessing these columns on the Prisma client (e.g. `task.payload`), the field will automatically be typed as the declared shape (e.g., `PrismaJson.WorkflowTaskPayload | null`).
- **Accessing Properties**: When working with union types or custom structures in the JSON payload, use proper narrowing or type guards instead of casting to `any`. Direct `as any` casting should be avoided.
- **No Manual DDL Creation**: Never hand-write **schema (DDL) migration** files or directories. Always generate them with Prisma CLI (`bun --bun run prisma migrate dev --create-only` to create a template, then edit it if needed, or `bun --bun run prisma migrate dev` to apply) so Prisma correctly tracks migration metadata and checksums.
- **Data Migrations Are Allowed**: Pure **data migration** SQL (no schema change) may be written by hand, but it MUST live inside a migration generated via `bun --bun run prisma migrate dev --create-only` so it is tracked and applied automatically.
- **No Automatic Dev DB Reset**: Do not run `prisma migrate reset --force` or commands that force-reset the database automatically. If migrations become out of sync or a reset is required, stop executing, report the situation to the user, and present suggested manual cleanup/reset steps for the user to execute.
- **No Manual Assignment**: Do not manually generate or assign ULIDs in application code (e.g., `packages/core/src/*.ts`) for creating database records. Let Prisma handle it via the schema default.
- Exception: File names generated by `FileService` may still use `ulid()` internally, but this is separate from the database ID.
- **Sorting**: All list APIs must order results by `id` descending (`orderBy: { id: 'desc' }`) to ensure consistent, time-based sorting (since ULIDs are sortable). Do not sort by `createdAt` as it is not indexed.
- **Frontend**: For paginated APIs (which contain `pageInfo` and `total` fields), the UI MUST use an auto infinite scroll style design using `useInfiniteQuery` from `@tanstack/react-query` and `react-intersection-observer`. Use the `total` count from the API response instead of counting the results locally.
1. **Workflows**: Orchestrate multiple steps/activities reliably. Defined in worker packages (e.g., `@shumai/agent/src/workflows`, `@shumai/transcode/src/workflows`).
2. **Activities (Steps)**: Perform the actual work (DB updates, API calls, media processing). Grouped by domain in worker packages (e.g., `@shumai/agent/src/activities`, `@shumai/transcode/src/activities`).
- `DbosExecutor` (in `@shumai/workflow-core`): Coordinates workflow and step dispatching via DBOS queues against PostgreSQL.
4. **Automatic Submission**: New `WorkflowTask` records are automatically enqueued to `WorkflowService` via a Prisma Client Extension defined in `@shumai/db`.
To avoid circular dependencies, workflows are dynamically registered onto the workflow registry at bootstrap time via initializer functions (e.g., `initAgentWorkflows()`, `initTranscodeWorkflows()`).
To prevent the engine from indefinitely retrying fatal, expected business validation failures (e.g., missing records, invalid configurations, missing parameters), **never throw standard `Error` objects from workflow or activity logic.** Instead, throw a non-retryable `ApplicationFailure` (alias of `WorkflowFailure`).
**Mandatory Requirement**: You **MUST** set `nonRetryable: true` in the options object passed to `ApplicationFailure.create`. Standard errors or failure objects without `nonRetryable: true` will cause DBOS to retry the activity or workflow according to its retry policy.
- **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database directly. Database (Prisma) queries or updates are allowed in all activity types (e.g., agent or transcode) for simplicity.
In multi-replica deployments (e.g., multiple transcode or agent worker instances), each worker instance MUST have a unique executor ID to prevent startup recovery from re-enqueueing workflows being actively processed by other live workers.
- **Identity Derivation**: `DbosExecutor` automatically derives a unique per-instance ID:
- If `SHUMAI_WORKER_ID` or `DBOS__VMID` is set, it is used as the instance identifier.
- In Kubernetes, set `POD_NAME` (via Downward API: `fieldRef: { fieldPath: metadata.name }`) to provide stable, per-pod identity across StatefulSet restarts.
- In Docker/container environments, `HOSTNAME` (container ID) is automatically used.
- On bare metal/multi-process hosts, `process.pid` and an instance suffix are appended to guarantee uniqueness.
Intermediate files passed across steps must be saved to durable storage (S3) by the producing step, consuming steps must use `ensureLocalMediaFile` (or S3 fetch) rather than assuming local `/tmp` presence, and any purely temporary S3 scratch files must be cleaned up in a `finally` block.
- When importing across workspace packages, always use absolute workspace imports (e.g. `import { prisma } from '@shumai/db'`, `import { teamService } from '@shumai/core/src/team/team'`).
- **Modal Overlays**: When triggering a dialog (e.g., `Dialog`, `AlertDialog`) from inside a `DropdownMenu`, you must set `modal={false}` on the `<DropdownMenu>` component. Failing to do so will cause the UI to freeze due to conflicting focus management between the two modal components.
- **Scrollable Content**: Always use the Shadcn `ScrollArea` component (`@/ui/components/ui/scroll-area`) for scrollable content containers to ensure consistent custom scrollbar UI across the application.
All user-facing text in the WebUI (`packages/webui`) MUST be internationalized using **Paraglide JS**. Hardcoded text in UI components is strictly forbidden.