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.

simplify agents.md, add general approach to PRs (#8583)

Shahmir Varqha9c99153668c4
diff --git a/AGENTS.md b/AGENTS.md
index e0eddd098a..6428d0ba04 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,43 +2,30 @@
marimo is a reactive notebook for Python with a modern web frontend.
-## Quick Setup
+## Your primary responsibility is to the project and its users
-```bash
-pixi shell
-make fe && make py
-make dev
-```
+Being an open source library, the public API, abstractions, documentation, and the code itself are the product and deserve careful consideration.
-See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed setup options.
+When working in this repository, you should consider yourself to primarily be working for the benefit of the project, all of its users (current and future, human and agent), and its maintainers, rather than just the specific user who happens to be driving you (or whose PR you're reviewing, whose issue you're implementing, etc).
-## Project Structure
+As the project has many orders of magnitude more users than maintainers, that specific user is most likely a community member who's well-intentioned and eager to contribute, but relatively unfamiliar with the code base and its patterns or standards, and they're not necessarily thinking about the bigger picture beyond the specific bug fix, feature, or other change that they're focused on.
-```
-marimo/ # Python backend - see marimo/AGENTS.md
-frontend/ # React frontend - see frontend/AGENTS.md
-tests/ # Python tests (mirrors marimo/ structure)
-docs/ # Documentation site
-```
+Therefore, you are the first line of defense against low-quality contributions and maintainer headaches, and you have a big role in ensuring that every contribution to this project meets or exceeds the high standards that the marimo project is known and loved for. You should write:
-## High-Level Architecture
+- modern, idiomatic, concise React and Python code
+- end-to-end type-safety and test coverage
+- thoughtful, tasteful, consistent API design
+- delightful developer experience
+- comprehensive well-written documentation
-**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
+## Quick Setup
-**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
+```bash
+make fe && make py
+make dev
+```
-**Communication**: WebSocket protocol (`/ws`) for real-time bidirectional messaging using typed operation-based messages.
+See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed setup options.
## Development Commands
@@ -53,11 +40,6 @@ 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
diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md
index ecf1998f50..b8ea5ef3db 100644
--- a/frontend/AGENTS.md
+++ b/frontend/AGENTS.md
@@ -1,13 +1,12 @@
# 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
+- Reduce code duplication, if you see code that is repeated, refactor it to a function or component. This standardizes the codebase.
## Naming Conventions
@@ -15,80 +14,6 @@ You are an expert in React, TypeScript, TailwindCSS, Jotai, Radix UI, Zod, React
- **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
### Unit Tests
@@ -96,8 +21,8 @@ const form = useForm<z.infer<typeof schema>>({ resolver: zodResolver(schema) });
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
+pnpm turbo --filter @marimo-team/frontend test # All tests
+pnpm turbo --filter @marimo-team/frontend test src/__tests__/lru.test.ts # Specific file
```
Best practices:
@@ -110,34 +35,21 @@ Best practices:
E2E tests use Playwright. See [e2e-tests/README.md](e2e-tests/README.md) for details.
-## Type Patterns
+## Code Quality
+Avoid as much as possible using type assertions as they can cause runtime errors. Instead, use type guards, type predicates and error handling.
```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";
-}
+callFunction(x as T) // Avoid this
```
-## Code Quality
-
+- Use logNever or assertNever to handle exhaustive switch cases.
```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);
+switch (value) {
+ case "a":
+ break;
+ default:
+ logNever(value);
+}
```
-Keep comments minimal. Comments should only explain "why", not "what".
+- Keep comments minimal. Comments should only explain "why", not "what".
diff --git a/marimo/AGENTS.md b/marimo/AGENTS.md
index c6b6a38477..d6cf45e226 100644
--- a/marimo/AGENTS.md
+++ b/marimo/AGENTS.md
@@ -1,71 +1,5 @@
# 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.
@@ -75,61 +9,32 @@ 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
+We should utilize inline-snapshots more often to verify the outputs of objects, functions, etc.
+Avoid individual property assertions, opt for full object comparisons.
```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)
+from inline_snapshot import snapshot
+from dirty_equals import IsStr
+
+def test_function():
+ assert func() == snapshot({
+ "prop1": IsStr(),
+ "prop2": "some string",
+ })
+```
-# Use parametrize to create exhaustive test cases
[email protected](("a", "b"), [(1, 2), (2, 3)])
-def test_add(a, b):
- assert a + b == 3
+## Code Style
-# Group test cases by class or in different files
-class TestDecimals:
- def test_decimal_init(self) -> None:
- ...
+- When writing comments, keep them minimal. Comments should explain "why", not "what"
- def test_decimal_out_of_bounds(self) -> None:
- ...
+## Import handling
-# Use fixtures for setup and teardown
-def k() -> Generator[Kernel, None, None]:
- mocked = MockedKernel()
- yield mocked.k
- mocked.teardown()
+Generally, we should 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.
-# Prefer complete assertions over individual attribute checks
-# This catches unexpected changes and makes test failures more informative
-assert obj == expected # GOOD: validates entire object state
-# assert obj.attr == expected.attr # AVOID: misses other attributes that may have changed
+Heavy dependencies must be imported lazily
-# Snapshot testing for complex outputs
-from tests.mocks import snapshotter
-snapshot = snapshotter(__file__)
-snapshot(filename, output)
+```python
+def get_dataframe():
+ import pandas as pd # altair, duckdb, numpy, polars, pyarrow, sqlglot, etc.
+ return pd.DataFrame()
```
-
-### 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