Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

add agents.md, remove cursorrules, update PR template (#7780)

Shahmir Varqha4afbc18fad6e
diff --git a/.cursor/rules/python.mdc b/.cursor/rules/python.mdc
deleted file mode 100644
index 023cfa3467..0000000000
--- a/.cursor/rules/python.mdc
+++ /dev/null
@@ -1,75 +0,0 @@
----
-description:
-globs:
-alwaysApply: true
----
----
-description: Rules for writing Python (backend of marimo)
-globs: marimo/*.py scripts/*.py test/*.py pyodide/*.py
----
-
-You are an expert in Python and websockets protocol with Python.
-
-Key Principles
- - Write clear, technical responses with precise examples.
- - Prioritize readability and maintainability; follow PEP 8 coding style guide
- - Use descriptive variable and function names; adhere to naming conventions (e.g., lowercase with underscores for functions and variables).
- - Use type hints consistently throughout the codebase
- - Keep comments to a minimum; be concise when writing them
-
-Error Handling and Validation
- - Use try-except blocks to handle cases where the code can fail
- - Follow established error handling patterns with specific or custom exceptions
-
-Logging
- - As a general rule, we should have logs for every unexpected action of the application, using the appropriate log level.
- - A log level or log severity is a piece of information telling how important a given log message is:
- - debug: should be used for information that may be needed for diagnosing issues and troubleshooting or when running application in the test environment for the purpose of making sure everything is running correctly
- - info should be used as standard log level, indicating that something happened
- - warn: should be used when something unexpected happened but the code can continue the work
- - error: should be used when the application hits an issue preventing one or more functionalities from properly functioning
-
-Logging Format
- - Always use marimo's logger:
-
- ```python
- from marimo import _loggers
-
- LOGGER = _loggers.marimo_logger()
-
- LOGGER.info("Debugging applications with params %s %s", "key1", "key2")
- ```
-
- will produce:
-
- ```sh
- [D 250406 21:43:21 runtime:2055] Debugging applications with params key1 key2
- ```
-
-Security
- - Don’t log sensitive information. Make sure you never log:
- - authorization tokens
- - passwords
-
-Testing
- - Changes or new functionality in the codebase should come with unit tests using pytest.
- - Tests exist in the tests folder.
- - We use pytest-asyncio globally, so you don't need to add `@pytest.mark.asyncio`
- - Utilize snapshot testing where appropriate:
-
- ```
- from tests.mocks import snapshotter
-
- snapshot = snapshotter(__file__)
-
- snapshot(filename, output)
- ```
-
-Unit tests
- - A good unit test should:
- - focus on a single use-case at a time
- - have a minimal set of assertions per test
- - demonstrate every use case. The rule of thumb is: if it can happen, it should be covered
- - To run a test using hatch, you can run the following command:
- `hatch run +py=3.12 test:test tests/path/to/test.py`
- `hatch run +py=3.12 test-optional:test tests/path/to/test.py` (when the test includes an optional dependency)
diff --git a/.cursor/rules/react-typescript.mdc b/.cursor/rules/react-typescript.mdc
deleted file mode 100644
index dbfedaab17..0000000000
--- a/.cursor/rules/react-typescript.mdc
+++ /dev/null
@@ -1,47 +0,0 @@
----
-description:
-globs:
-alwaysApply: true
----
----
-description: Rules for writing React with Typescript (frontend of marimo)
-globs: frontend/*.ts?(x) openapi/*.ts?(x) lsp/*.ts?(x)
----
-
-You are an expert in React, TypeScript, TailwindCSS, Radix, Zod, React Hook Form and UX design.
-
-Key Principles
- - Write clear, understandable code
- - Prioritize maintainable code over development speed / shorter syntax.
-
-Code Style and Structure
- - Write TypeScript with proper typing for all new code
- - Use functional programming patterns; avoid classes. Prefer composition over inheritance.
- - Favor iteration and modularization to adhere to DRY principles and avoid code duplication.
- - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
- - Don't use `useState` or `useEffect` to store local state. It's false convenience. Take the extra 3 minutes and change it to a `logic` early on in the development.
- - Structure files logically: main logic, component, types, utils
- - Keep comments to a minimum; be concise when writing them
-
-Naming Conventions
- - Use lowercase with dashes for directories (e.g., components/auth-wizard).
- - Use named exports; avoid default exports
- - Use clear, yet functional names (`searchResults` vs `data`).
- - Logics are camelCase (`dashboardLogic`)
- - React components are PascalCase (`DashboardMenu`).
-
-UI and Styling
- - Use Tailwind CSS as primary styling solution
- - There are many UI components taken from radix and customized in '@/components/ui'. Develop reusable UI components in that folder instead of directly importing from radix.
-
-Build System
- - Use Vite
-
-Forms
- - Use React Hook Form with Zod
-
-Testing Requirements
- - Use Vitest for testing
- - Test components for all edge cases. The rule of thumb is: if it can happen, it should be covered
- - To run a test using pnpm, run the following command:
- `cd frontend && pnpm test src/path/to/file.test.ts`
\ No newline at end of file
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index bf977f260e..485b6571d5 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -3,8 +3,9 @@
<!--
Provide a concise summary of what this pull request is addressing.
-If this PR fixes any issues, list them here by number (e.g., Fixes #123).
+If this PR closes any issues, list them here by number (e.g., Closes #123).
-->
+Closes #
## 🔍 Description of Changes
@@ -16,5 +17,6 @@ Detail the specific changes made in this pull request. Explain the problem addre
- [ ] I have read the [contributor guidelines](https://github.com/marimo-team/marimo/blob/main/CONTRIBUTING.md).
- [ ] For large changes, or changes that affect the public API: this change was discussed or approved through an issue, on [Discord](https://marimo.io/discord?ref=pr), or the community [discussions](https://github.com/marimo-team/marimo/discussions) (Please provide a link if applicable).
-- [ ] I have added tests for the changes made.
-- [ ] I have run the code and verified that it works as expected.
+- [ ] Tests have been added for the changes made.
+- [ ] Documentation has been updated where applicable, including docstrings for API changes.
+- [ ] Pull request title is a good summary of the changes - it will be used in the [release notes](https://github.com/marimo-team/marimo/releases).
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000000..e0eddd098a
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,64 @@
+# marimo Development Guidelines
+
+marimo is a reactive notebook for Python with a modern web frontend.
+
+## Quick Setup
+
+```bash
+pixi shell
+make fe && make py
+make dev
+```
+
+See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed setup options.
+
+## Project Structure
+
+```
+marimo/ # Python backend - see marimo/AGENTS.md
+frontend/ # React frontend - see frontend/AGENTS.md
+tests/ # Python tests (mirrors marimo/ structure)
+docs/ # Documentation site
+```
+
+## High-Level Architecture
+
+**Backend (`/marimo/`)**: Reactive notebook runtime built on Starlette/Uvicorn
+- `_ast/`: AST handling, cell parsing, dependency analysis
+- `_runtime/`: Reactive execution engine, dataflow graph
+- `_server/`: HTTP/WebSocket server, API endpoints, session management
+- `_plugins/`: UI components (buttons, sliders, tables)
+- `_sql/`: SQL cell support with multiple engine backends
+- `_output/`: Output formatting and MIME types
+
+**Frontend (`/frontend/src/`)**: Interactive UI built with React/TypeScript/Vite
+- `core/`: Application state, cell management, runtime communication
+- `codemirror/`: Code editor with Python/SQL support, completions
+- `plugins/`: React implementations of UI components
+- `components/`: Reusable UI components
+- `hooks/`: Custom React hooks
+
+**Communication**: WebSocket protocol (`/ws`) for real-time bidirectional messaging using typed operation-based messages.
+
+## Development Commands
+
+```bash
+# Python
+make py-check # Typecheck and lint Python
+uvx hatch run +py=3.12 test:test tests/path/to/test.py
+uvx hatch run +py=3.12 test-optional:test tests/path/to/test.py # with optional deps
+
+# Frontend
+make fe-check # Typecheck and lint frontend
+cd frontend && pnpm test src/path/to/file.test.ts
+```
+
+## Key Development Tips
+
+- UI plugins require changes in both Python (`_plugins/`) and React (`plugins/`)
+- The frontend communicates with the backend via WebSocket on `/ws`
+
+## Pull Requests
+
+- Run `make check` before committing
+- See [CONTRIBUTING.md](CONTRIBUTING.md) for PR guidelines and CLA
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000000..43c994c2d3
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md
new file mode 100644
index 0000000000..d8331dae05
--- /dev/null
+++ b/frontend/AGENTS.md
@@ -0,0 +1,136 @@
+# Frontend Guidelines
+
+You are an expert in React, TypeScript, TailwindCSS, Jotai, Radix UI, Zod, React Hook Form, and modern UX design.
+
+## Key Principles
+
+- Write clear, maintainable code over clever/short syntax
+- Use TypeScript with proper typing for all code
+- Use functional programming patterns; avoid classes
+- Favor composition over inheritance
+
+## Naming Conventions
+
+- **Directories**: lowercase with dashes (`components/auth-wizard/`)
+- **Components**: PascalCase (`DashboardMenu.tsx`)
+- **Variables**: descriptive with auxiliary verbs (`isLoading`, `hasError`, `canSubmit`)
+
+## Path Aliases
+
+```typescript
+import { Button } from "@/components/ui/button";
+import { cn } from "@/utils/cn";
+```
+
+## Lazy Loading
+
+Use lazy loading for components that require heavy dependencies.
+
+```typescript
+import { lazy } from "react";
+const LazyComponent = lazy(() => import("@/components/LazyComponent"));
+```
+
+## State Management with Jotai
+
+While React hooks are preferred, Jotai is useful when you need to persist state outside of the React component tree or store in local storage.
+
+Use `createReducerAndAtoms` for complex state, `atomFamily` for per-item atoms:
+
+```typescript
+import { atom, useAtomValue } from "jotai";
+import { atomFamily } from "jotai/utils";
+import { createReducerAndAtoms } from "@/utils/createReducer";
+
+// Complex state with reducer pattern
+const { useActions, valueAtom: notebookAtom } = createReducerAndAtoms(initialState, {
+ createNewCell: (state, action: CreateNewCellAction) => ({ ...state, /* changes */ }),
+});
+
+// Derived atoms
+export const cellIdsAtom = atom((get) => get(notebookAtom).cellIds);
+
+// Per-item atoms (clean up with .remove() to prevent memory leaks)
+export const cellDataAtom = atomFamily((cellId: CellId) =>
+ atom((get) => get(notebookAtom).cellData[cellId])
+);
+
+// Imperative access outside React
+import { store } from "@/core/state/jotai";
+export const getNotebook = () => store.get(notebookAtom);
+
+// Local storage
+const sessionAtom = atomWithStorage<SessionState>("marimo:session", initialState, jotaiJsonStorage);
+```
+
+## UI and Styling
+
+Use Tailwind with the `cn` utility. Custom UI components wrap Radix primitives in `@/components/ui/`:
+
+```typescript
+import { cn } from "@/utils/cn";
+
+<div className={cn(
+ "inline-flex items-center justify-center rounded-md",
+ isActive && "bg-primary text-primary-foreground"
+)} />
+```
+
+## Forms
+
+Use React Hook Form with Zod validation:
+
+```typescript
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+const schema = z.object({ name: z.string().min(1), email: z.string().email() });
+const form = useForm<z.infer<typeof schema>>({ resolver: zodResolver(schema) });
+```
+
+## Testing
+
+Tests live alongside source files or in `__tests__` directories.
+
+```bash
+pnpm --filter @marimo-team/frontend test # All tests
+pnpm --filter @marimo-team/frontend test src/__tests__/lru.test.ts # Specific file
+```
+
+Best practices
+- test edge cases
+- use descriptive names
+- group with `describe`
+
+## Type Patterns
+
+```typescript
+// Pick/Omit for derived types
+type CellBasics = Pick<CellRuntimeState, "status" | "output">;
+interface ButtonProps extends Omit<VariantProps<typeof buttonVariants>, "disabled"> {}
+
+// Record for object types
+type Variables = Record<CellId, CellData>;
+
+// Type guards
+function isErrorMime(mimetype?: string): boolean {
+ return mimetype === "application/vnd.marimo+error";
+}
+```
+
+## Code Quality
+
+```typescript
+import { logNever } from "@/utils/logNever";
+import { Logger } from "@/utils/Logger";
+
+// Exhaustive switch handling
+logNever(value);
+
+// Logging
+Logger.warn(`Cell ${cellId} not found`);
+Logger.error(`Error in reducer:`, error);
+```
+
+Keep comments minimal. Comments should only explain "why", not "what".
diff --git a/marimo/AGENTS.md b/marimo/AGENTS.md
new file mode 100644
index 0000000000..cd4adce250
--- /dev/null
+++ b/marimo/AGENTS.md
@@ -0,0 +1,133 @@
+# Python Backend Guidelines
+
+You are an expert in Python, websockets protocol, and Starlette/ASGI web frameworks.
+
+## Key Principles
+
+- Prioritize readability and maintainability; follow PEP 8 (79 char line limit)
+- Use type hints consistently throughout the codebase
+- Use descriptive variable and function names (lowercase with underscores)
+- Use `Final` for constants: `_name: Final[str] = "marimo-tabs"`
+- Private modules use `_` prefix (e.g., `_plugins`, `_server`, `_utils`)
+
+## Type Hints
+
+- Use modern typing syntax (`list[str]` not `List[str]`, `str | None` not `Optional[str]`)
+
+## Error Handling
+
+- Raise specific exceptions, never bare `raise Exception`
+- Use `HTTPException` with appropriate status codes for API errors:
+
+```python
+from marimo._utils.http import HTTPStatus
+raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail="AI is not configured.")
+```
+
+## Logging
+
+```python
+from marimo import _loggers
+LOGGER = _loggers.marimo_logger()
+
+LOGGER.debug("Diagnostic info: %s", value) # troubleshooting
+LOGGER.info("Standard operation: %s", value) # normal events
+LOGGER.warning("Unexpected but handled: %s", value) # recoverable issues
+LOGGER.error("Functionality broken: %s", value) # critical errors
+```
+
+Use `%s` formatting (not f-strings) for lazy evaluation. Never log sensitive data.
+
+## Dataclasses vs msgspec
+
+Use **msgspec.Struct** for API models (everything in `_server/models/`), commands, and fast JSON serialization:
+
+```python
+import msgspec
+
+class SaveNotebookRequest(msgspec.Struct, rename="camel"):
+ cell_ids: list[CellId_t]
+ codes: list[str]
+ filename: str
+ persist: bool = True
+```
+
+Use **dataclasses** for internal structures, test fixtures, and complex initialization.
+
+## Import handling
+
+Heavy dependencies must be imported lazily (banned at module level by ruff):
+
+```python
+def get_dataframe():
+ import pandas as pd # altair, duckdb, numpy, polars, pyarrow, sqlglot, etc.
+ return pd.DataFrame()
+```
+
+Besides heavy dependencies, always import at the top of the file. If there are circular imports, it means the file structure is not optimal. Refactor code to remove circular dependencies.
+
+## Testing
+
+Tests live in `tests/` folder, mirroring `marimo/` structure.
+
+```bash
+uvx hatch run +py=3.12 test:test tests/path/to/test.py
+uvx hatch run +py=3.12 test-optional:test tests/path/to/test.py # with optional deps
+```
+
+### Best Practices
+
+```python
+# Focus on single use-case per test
+def test_number_init() -> None:
+ number = ui.number(1, 10)
+ assert number.start == 1 and number.stop == 10
+
+# Test error cases with context managers
+def test_number_out_of_bounds() -> None:
+ with pytest.raises(ValueError) as e:
+ ui.number(1, 10, value=11)
+ assert "must be less than or equal" in str(e.value)
+
+# Use parametrize to create exhaustive test cases
[email protected](("a", "b"), [(1, 2), (2, 3)])
+def test_add(a, b):
+ assert a + b == 3
+
+# Group test cases by class or in different files
+class TestDecimals:
+ def test_decimal_init(self) -> None:
+ ...
+
+ def test_decimal_out_of_bounds(self) -> None:
+ ...
+
+# Use fixtures for setup and teardown
+def k() -> Generator[Kernel, None, None]:
+ mocked = MockedKernel()
+ yield mocked.k
+ mocked.teardown()
+
+# Validate entire object state, not individual attributes
+assert obj == expected # instead of assert obj.attr == expected.attr
+
+# Snapshot testing for complex outputs
+from tests.mocks import snapshotter
+snapshot = snapshotter(__file__)
+snapshot(filename, output)
+```
+
+### Debugging Issues
+
+1. Create a test case that reproduces the issue.
+2. Run the test case and inspect the issue.
+2. Add debug prints if root cause unclear.
+
+## Code Style
+
+- Google-style docstrings
+- Explicit encoding in `open()`
+- Typecheck and lint with `make py-check`
+- Use `log_never` to ensure exhaustive handling
+- Comments explain "why", not "what" - keep minimal