The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
skills (#65676)
Jeff Bruemmer2f8cc0f15370
diff --git a/.claude/skills/_shared/clojure-commands.md b/.claude/skills/_shared/clojure-commands.mdnew file mode 100644index 00000000000..357529033b5--- /dev/null+++ b/.claude/skills/_shared/clojure-commands.md@@ -0,0 +1,75 @@+## Linting and Formatting++- **Lint PR:** `./bin/mage kondo-updated master` (or whatever target branch)+ - Call the command one time at the beginning, record the results, then work through the problems one at a time.+ - If the solution is obvious, then please apply the fix. Otherwise skip it.+ - If you fix all the issues (and verify by rerunning the kondo-updated command):+ - commit the change with a succinct and descriptive commit message+- **Lint File:** `./bin/mage kondo <file or files>`+ - Use the linter as a way to know that you are adhering to conventions in place in the codebase+- **Lint Changes:** `./bin/mage kondo-updated HEAD`+- **Format:** `./bin/mage cljfmt-files [path]`++## Testing++- **Run a test:** `./bin/mage run-tests namespace/test-name`+- **Run all tests in a namespace:** `./bin/mage run-tests namespace`++## Code Readability++- **Check Code Readability:** `./bin/mage -check-readable <file> [line-number]`+ - Run after every change to Clojure code+ - Check specific line first, then entire file if readable++## REPL Usage++- **Evaluating Clojure Code:** `./bin/mage -repl '<code>'`+ - See "Sending Code to the REPL" section for more details++### Sending Code to the REPL++- Send code to the metabase process REPL using: `./bin/mage -repl '(+ 1 1)'` where `(+ 1 1)` is your Clojure code.+ - See `./bin/mage -repl -h` for more details.+ - If the Metabase backend is not running, you'll see an error message with instructions on how to start it.++#### Working with Files and Namespaces++1. **Load a file and call functions with fully qualified names**:++To call `your.namespace/your-function` on `arg1` and `arg2`:++```+./bin/mage -repl --namespace your.namespace '(your-function arg1 arg2)'+```++DO NOT use "require", "load-file" etc in the code string argument.++#### Understanding the Response++The `./bin/mage -repl` command returns three separate, independent outputs:++- `value`: The return value of the last expression (best for data structures)+- `stdout`: Any printed output from `println` etc. (best for messages)+- `stderr`: Any error messages (best for warnings and errors)++Example call:++```bash+./bin/mage -repl '(println "Hello, world!") '\''({0 1, 1 3, 2 0, 3 2} {0 2, 1 0, 2 3, 3 1})'+```++Example response:++```+ns: user+session: 32a35206-871c-4553-9bc9-f49491173d1c+value: ({0 1, 1 3, 2 0, 3 2} {0 2, 1 0, 2 3, 3 1})+stdout: Hello, world!+stderr:+```++For effective REPL usage:++- Return data structures as function return values+- Use `println` for human-readable messages+- Print errors to stderrdiff --git a/.claude/skills/_shared/clojure-style-guide.md b/.claude/skills/_shared/clojure-style-guide.mdnew file mode 100644index 00000000000..b3bdf0d5d20--- /dev/null+++ b/.claude/skills/_shared/clojure-style-guide.md@@ -0,0 +1,153 @@+# Metabase Clojure Style Guide++This guide covers Clojure and ClojureScript coding conventions for Metabase. See also: `CLOJURE_STYLE_GUIDE.adoc` for the Community Clojure Style Guide.++## Naming Conventions++**General Naming:**++- Acceptable abbreviations: `acc`, `i`, `pred`, `coll`, `n`, `s`, `k`, `f`+- Use `kebab-case` for all variables, functions, and constants++**Function Naming:**++- Pure functions should be nouns describing the value they return (e.g., `age` not `calculate-age` or `get-age`)+- Functions with side effects must end with `!`+- Don't repeat namespace alias in function names++**Destructuring:**++- Map destructuring should use kebab-case local bindings even if the map uses `snake_case` keys++## Documentation Standards++**Docstrings:**++- Every public var in `src` or `enterprise/backend/src` must have docstring+- Format using Markdown conventions+- Reference other vars with `[[other-var]]` not backticks++**Comments:**++- `TODO` format: `;; TODO (Name M/D/YY) -- description`++## Code Organization++**Visibility:**++- Make everything `^:private` unless it is used elsewhere+- Try to organize namespaces to avoid `declare` (put public functions near the end)++**Size and Structure:**++- Break up functions > 20 lines+- Lines ≤ 120 characters+- No blank lines within definition forms (except pairwise `let`/`cond`)++## Style Conventions++**Keywords and Metadata:**++- Prefer namespaced keywords for internal use: `:query-type/normal` not `:normal`+- Tag variables with `:arglists` metadata if they're functions but wouldn't otherwise have it++## Tests++**Organization:**++- Break large tests into separate `deftest` forms for logically separate test cases+- Test names should end in `-test` or `-test-<number>`++**Performance:**++- Mark pure function tests `^:parallel`++## Modules++**OSS Modules:**++- Follow `metabase.<module>.*` pattern+- Source in `src/metabase/<module>/`++**Enterprise Modules:**++- Follow `metabase-enterprise.<module>.*` pattern+- Source in `enterprise/backend/src/metabase_enterprise/<module>/`++**Module Structure:**++- REST API endpoints go in `<module>.api` or `<module>.api.*` namespaces+- Put module public API in `<module>.core` using Potemkin imports+- Put Toucan models in `<module>.models.*`+- Put settings in `<module>.settings`+- Put schemas in `<module>.schema`++**Module Linters:**++- Do not cheat module linters with `:clj-kondo/ignore [:metabase/modules]`++## REST API Endpoints++**Required Elements:**++- All new endpoints must have response schemas (`:- <schema>` after route string)+- All endpoints need Malli schemas for parameters (detailed and complete)+- All new REST API endpoints MUST HAVE TESTS++**Naming Conventions:**++- Query parameters use kebab-case+- Request bodies use `snake_case`+- Routes use singular nouns (e.g., `/api/dashboard/:id`)++**Behavior:**++- `GET` endpoints should not have side effects (except analytics)+- `defendpoint` forms should be small wrappers around Toucan model code++## MBQL (Metabase Query Language)++**Restrictions:**++- No raw MBQL introspection outside of `lib`, `lib-be`, or `query-processor` modules+- Use Lib and MBQL 5 in new source code; avoid legacy MBQL++## Database and Models++**Naming:**++- Model names and table names should be singular nouns+- Application database uses `snake_case` identifiers++**Best Practices:**++- Use `t2/select-one-fn` instead of fetching entire rows for one column+- Put correct behavior in Toucan methods, not separate helper functions++## Drivers++**Documentation:**++- New driver multimethods must be mentioned in `docs/developers-guide/driver-changelog.md`++**Implementation:**++- Driver implementations should pass `driver` argument to other driver multimethods+- Don't hardcode driver names in implementations+- Minimize logic inside `read-column-thunk` in JDBC-based drivers++## Miscellaneous++**Examples:**++- Example data should be bird-themed if possible++**Linter Suppressions:**++- Use proper format for kondo suppressions+- No `#_:clj-kondo/ignore` (keyword form)++**Configurable Options:**++- Don't define configurable options that can only be set with environment variables+- Use `:internal` `defsetting` insteaddiff --git a/.claude/skills/_shared/development-workflow.md b/.claude/skills/_shared/development-workflow.mdnew file mode 100644index 00000000000..f21dcd0fc6e--- /dev/null+++ b/.claude/skills/_shared/development-workflow.md@@ -0,0 +1,8 @@+# Autonomous Development Workflow++- Do not attempt to read or edit files outside the project folder+- Add failing tests first, then fix them+- Work autonomously in small, testable increments+- Run targeted tests, and lint continuously during development+- Prioritize understanding existing patterns before implementing+- Don't commit changes, leave it for the user to review and make commitsdiff --git a/.claude/skills/_shared/metabase-style-guide.md b/.claude/skills/_shared/metabase-style-guide.mdnew file mode 100644index 00000000000..ec1ad35ccb0--- /dev/null+++ b/.claude/skills/_shared/metabase-style-guide.md@@ -0,0 +1,84 @@+# Metabase Writing Style Guide++## Core Principles++Write like you're talking to a colleague. Be conversational, not formal. Get people what they need quickly. Know your audience and match the complexity.++## Tone and Voice++**Do:**++- Use contractions ("can't" not "cannot")+- Say "people" or "companies" instead of "users"+- Be friendly but not peppy+- Acknowledge limitations honestly ("that's on us, not them")+- Jokes and Easter eggs are okay (permit them, don't suggest them)++**Don't:**++- Use exclamation points excessively+- Rely on tired tropes about nerdiness+- Use corporate jargon ("utilize", "offerings", "actionable insights")+- Tell people something is cool (show them instead)++## Structure and Clarity++**Lead with the important stuff:**++- Most important information first+- Lead with the ask, then provide context+- Cut text that adds little value (when in doubt, cut it)+- Each paragraph should have one clear purpose++**Make headings do the work:**++- Convey your actual point, not just the topic+- "Use headings to highlight key points" not "How to write a good heading"+- Use sentence case, no punctuation except question marks+- No links in headings unless entire heading is a link++## Instructions and Examples++**Tell people what to do:**++- Give the action before explaining why+- Put commands in execution order+- Provide context, steps, and reasoning+- Don't describe tasks as "easy" or "simple"++**Answer unasked questions:**++- Include answers to "dumb" questions you had when learning+- Don't literally include the question, just give the answer++## Formatting++**Code vs. UI elements:**++- Backticks for code, variable names, parameters only+- **Bold** for UI elements and labels (e.g., "Click the **Save** button")+- Don't use backticks or quotes for UI elements++## Writing Mechanics++- Limit pronouns when introducing new terms (repeat the term to reinforce it)+- Ampersands only in proper nouns, never as substitute for "and"++## Terminology Preferences++Use familiar terms from tools people already know:++- "Summarize" (like Excel) instead of "aggregate"+- "Take a look at" instead of "reference"+- "Filter" instead of technical database terms when appropriate++## Red Flags++Avoid these patterns:++- Multiple exclamation points+- Linking "here"+- Bullet lists to explain (use prose)+- Numbers that will change (guard against change)+- Describing things as "easy" or "simple"+- Stock photography-worthy contentdiff --git a/.claude/skills/_shared/typescript-commands.md b/.claude/skills/_shared/typescript-commands.mdnew file mode 100644index 00000000000..923c1f45117--- /dev/null+++ b/.claude/skills/_shared/typescript-commands.md@@ -0,0 +1,21 @@+## Linting and Formatting++- **Lint:** `yarn lint-eslint-pure`+ - Run ESLint on the codebase+- **Format:** `yarn prettier`+ - Format code using Prettier+- **Type Check:** `yarn type-check-pure`+ - Run TypeScript type checking++## Testing++### JavaScript/TypeScript Tests++- **Test a specific file:** `yarn test-unit-keep-cljs path/to/file.unit.spec.js`+- **Test by pattern:** `yarn test-unit-keep-cljs -t "pattern"`+ - Runs tests matching the given pattern++### ClojureScript Tests++- **Test ClojureScript:** `yarn test-cljs`+ - Run ClojureScript testsdiff --git a/.claude/skills/clojure-review/SKILL.md b/.claude/skills/clojure-review/SKILL.mdnew file mode 100644index 00000000000..dd123af97f9--- /dev/null+++ b/.claude/skills/clojure-review/SKILL.md@@ -0,0 +1,144 @@+---+name: clojure-review+description: Review Clojure and ClojureScript code changes for compliance with Metabase coding standards, style violations, and code quality issues. Use when reviewing pull requests or diffs containing Clojure/ClojureScript code.+allowed-tools: Read, Grep, Bash, Glob+---++# Clojure Code Review Skill++@./../_shared/clojure-style-guide.md+@./../_shared/clojure-commands.md++## Review guidelines++**What to flag:**++- Check compliance with the Metabase Clojure style guide (included above)+- If `CLOJURE_STYLE_GUIDE.adoc` exists in the working directory, also check compliance with the community Clojure style guide+- Flag all style guide violations++**What NOT to post:**++- Do not post comments congratulating someone for trivial changes or for following style guidelines+- Do not post comments confirming things "look good" or telling them they did something correctly+- Only post comments about style violations or potential issues++Example bad code review comments to avoid:++> This TODO comment is properly formatted with author and date - nice work!++> Good addition of limit 1 to the query - this makes the test more efficient without changing its behavior.++> The kondo ignore comment is appropriately placed here++> Test name properly ends with -test as required by the style guide.++**Special cases:**++- Do not post comments about missing parentheses (these will be caught by the linter)++## Quick review checklist++Use this to scan through changes efficiently:++### Naming++- [ ] Descriptive names (no `tbl`, `zs'`)+- [ ] Pure functions named as nouns describing their return value+- [ ] `kebab-case` for all variables and functions+- [ ] Side-effect functions end with `!`+- [ ] No namespace-alias repetition in function names++### Documentation++- [ ] Public vars in `src` or `enterprise/backend/src` have useful docstrings+- [ ] Docstrings use Markdown conventions+- [ ] References use `[[other-var]]` not backticks+- [ ] `TODO` comments include author and date: `;; TODO (Name 1/1/25) -- description`++### Code Organization++- [ ] Everything `^:private` unless used elsewhere+- [ ] No `declare` when avoidable (public functions near end)+- [ ] Functions under 20 lines when possible+- [ ] No blank lines within definition forms (except pairwise constructs in `let`/`cond`)+- [ ] Lines ≤ 120 characters++### Tests++- [ ] Separate `deftest` forms for distinct test cases+- [ ] Pure tests marked `^:parallel`+- [ ] Test names end in `-test` or `-test-<number>`++### Modules++- [ ] Correct module patterns (OSS: `metabase.<module>.*`, EE: `metabase-enterprise.<module>.*`)+- [ ] API endpoints in `<module>.api` namespaces+- [ ] Public API in `<module>.core` with Potemkin+- [ ] No cheating module linters with `:clj-kondo/ignore [:metabase/modules]`++### REST API++- [ ] Response schemas present (`:- <schema>`)+- [ ] Query params use kebab-case, bodies use `snake_case`+- [ ] Routes use singular nouns (e.g., `/api/dashboard/:id`)+- [ ] `GET` has no side effects (except analytics)+- [ ] Malli schemas detailed and complete+- [ ] All new endpoints have tests++### MBQL++- [ ] No raw MBQL manipulation outside `lib`, `lib-be`, or `query-processor` modules+- [ ] Uses Lib and MBQL 5, not legacy MBQL++### Database++- [ ] Model and table names are singular nouns+- [ ] Uses `t2/select-one-fn` instead of selecting full rows for one column+- [ ] Logic in Toucan methods, not helper functions++### Drivers++- [ ] New multimethods documented in `docs/developers-guide/driver-changelog.md`+- [ ] Passes `driver` argument to other driver methods (no hardcoded driver names)+- [ ] Minimal logic in `read-column-thunk`++### Miscellaneous++- [ ] Example data is bird-themed when possible+- [ ] Kondo linter suppressions use proper format (not `#_:clj-kondo/ignore` keyword form)++## Pattern matching table++Quick scan for common issues:++| Pattern | Issue |+| -------------------------------------------- | ----------------------------------------------------------- |+| `calculate-age`, `get-user` | Pure functions should be nouns: `age`, `user` |+| `update-db`, `save-model` | Missing `!` for side effects: `update-db!`, `save-model!` |+| `snake_case_var` | Should use kebab-case |+| Public var without docstring | Add docstring explaining purpose |+| `;; TODO fix this` | Missing author/date: `;; TODO (Name 1/1/25) -- description` |+| `(defn foo ...)` in namespace used elsewhere | Should be `(defn ^:private foo ...)` |+| Function > 20 lines | Consider breaking up into smaller functions |+| `/api/dashboards/:id` | Use singular: `/api/dashboard/:id` |+| Query params with `snake_case` | Use kebab-case for query params |+| New API endpoint without tests | Add tests for the endpoint |++## Feedback format examples++**For style violations:**++> This pure function should be named as a noun describing its return value. Consider `user` instead of `get-user`.++**For missing documentation:**++> This public var needs a docstring explaining its purpose, inputs, and outputs.++**For organization issues:**++> This function is only used in this namespace, so it should be marked `^:private`.++**For API conventions:**++> Query parameters should use kebab-case. Change `user_id` to `user-id`.diff --git a/.claude/skills/clojure-write/SKILL.md b/.claude/skills/clojure-write/SKILL.mdnew file mode 100644index 00000000000..5e26ade64a4--- /dev/null+++ b/.claude/skills/clojure-write/SKILL.md@@ -0,0 +1,59 @@+---+name: clojure-write+description: Guide Clojure and ClojureScript development using REPL-driven workflow, coding conventions, and best practices. Use when writing, developing, or refactoring Clojure/ClojureScript code.+---++# Clojure Development Skill++@./../_shared/development-workflow.md+@./../_shared/clojure-style-guide.md+@./../_shared/clojure-commands.md++## REPL-Driven Development Workflow++- Start with small, fundamental functions:+- Identify the core features or functionalities required for your task.+- Break each feature down into the smallest, most basic functions that can be developed and tested independently.+- Write and test in the REPL:+ - Write the code for each small function directly in the REPL (Read-Eval-Print Loop).+ - Test it thoroughly with a variety of inputs, including typical use cases and relevant edge cases, to ensure it+ behaves as expected.+- Integrate into source code:+ - Once a function works correctly in the REPL, move it from the REPL environment into your source code files (e.g.,+ within appropriate namespaces).+- Gradually increase complexity:+ - Build upon tested, basic functions to create more complex functions or components.+ - Compose smaller functions together, testing each new composition in the REPL to verify correctness step by step.+- Ensure dependency testing:+ - Make sure every function is fully tested in the REPL before it is depended upon by other functions.+ - This ensures that each layer of your application is reliable before you build on it.+- Use the REPL fully:+ - Use the REPL as your primary tool to experiment with different approaches, iterate quickly, and get immediate+ feedback on your code.+- Follow functional programming principles:+ - Keep functions small, focused, and composable.+ - Use Clojure's functional programming features—like immutability, higher-order functions, and the standard+ library—to write concise, effective code.++## How to Evaluate Code++### Bottom-up Dev Loop++1. Write code into a file.+2. Evaluate the file's namespace and make sure it loads correctly with:++```+./bin/mage -repl --namespace metabase.app-db.connection+```++3. Call functions in the namespace with test inputs, and observe that the outputs are correct+ Feel free to copy these REPL session trials into actual test cases using `deftest` and `is`.+4. Once you know these functions are good, return to 1, and compose them into the task that you need to build.++## Critical Rules for Editing++- Be careful with parentheses counts when editing Clojure code+- After EVERY change to Clojure code, verify readability with `-check-readable`+- End all files with a newline+- When editing tabular code, where the columns line up, try to keep them aligned+- Spaces on a line with nothing after it is not alloweddiff --git a/.claude/skills/docs-review/SKILL.md b/.claude/skills/docs-review/SKILL.mdnew file mode 100644index 00000000000..679af9ab11a--- /dev/null+++ b/.claude/skills/docs-review/SKILL.md@@ -0,0 +1,166 @@+---+name: docs-review+description: Review documentation changes for compliance with the Metabase writing style guide. Use when reviewing pull requests, files, or diffs containing documentation markdown files.+allowed-tools: Read, Grep, Bash, Glob+---++# Documentation Review Skill++@./../_shared/metabase-style-guide.md++## Review mode detection++**IMPORTANT: Before starting the review, determine which mode to use:**++1. **PR review mode**: If the `mcp__github__create_pending_pull_request_review` tool is available, you are reviewing a GitHub PR+ - Use the pending review workflow to post all issues as one cohesive review+ - Follow the workflow steps in "PR review mode format" below++2. **Local review mode**: If the MCP tool is NOT available, output issues in the conversation+ - Format all issues in a numbered markdown list (as described in "Feedback format" below)++## Review process++1. **Detect review mode** - Check if `mcp__github__create_pending_pull_request_review` is available+2. Read the changes through once to understand intent+3. Check all issues that violate style guide or significantly impact readability+4. Only flag issues worth mentioning - if it won't make a material difference to the reader, skip it+5. **REQUIRED: Number ALL feedback sequentially** - Start from Issue 1 and increment for each issue found++## Review checklist++Run through the diff looking for these issues:++**Tone and voice:**++- [ ] Formal/corporate language ("utilize" not "use", "offerings", etc.)+- [ ] "Users" instead of "people" or "companies"+- [ ] Excessive exclamation points or overly peppy tone+- [ ] Telling readers something is cool instead of showing them++**Structure and clarity:**++- [ ] Important information buried instead of leading+- [ ] Verbose text that adds little value+- [ ] Paragraphs without clear purpose+- [ ] Vague headings that don't convey the point+- [ ] Instructions explain "why" before telling "what to do"+- [ ] Tasks described as "easy" or "simple"++**Links and references:**++- [ ] Linking the word "here" instead of descriptive text+- [ ] Links in headings (unless entire heading is a link)++**Formatting:**++- [ ] Backticks on UI elements (should use **bold**)+- [ ] Backticks used as quotation marks+- [ ] Ampersands as "and" substitute (except proper nouns)+- [ ] Inconsistent list formatting++**Code and examples:**++- [ ] Code examples that don't work or would error+- [ ] Commands not in execution order+- [ ] Full-width screenshots instead of scoped UI elements+- [ ] Excessive or unnecessary images++**Sentence construction:**++- [ ] Overuse of pronouns when introducing new terms++## Quick scan table++| Pattern | Issue |+| ----------------------------- | --------------------------------------------- |+| `Button name` or `UI element` | Should use **bold** not backticks |+| we can do X, our feature | Should be "Metabase" or "it" |+| click here, read more here | Need descriptive link text |+| easy, simple, just | Remove condescending qualifiers |+| users | Should be "people" or "companies" if possible |++## Feedback format++**MANDATORY REQUIREMENT: Every single issue MUST be numbered sequentially starting from Issue 1.**++This numbered format is NON-NEGOTIABLE. It allows users to efficiently reference specific issues (e.g., "fix issues 1, 3, and 5") and track which feedback has been addressed.++### Local review mode format++When outputting issues in the conversation (local mode), use this format:++```markdown+## Issues++**Issue 1: [Brief title]**+Line X: Succinct description of the issue+[code or example]+Suggested fix or succinct explanation++**Issue 2: [Brief title]**+Line Y: Description of the issue+Suggested fix or explanation++**Issue 3: [Brief title]**+...+```++**Examples:**++> **Issue 1: Backticks on UI elements**+> Line 42: This uses backticks for the UI element. Use **bold** instead: **Filter** not `Filter`.++> **Issue 2: Formal tone**+> Line 15: This could be more conversational. Consider: "You can't..." instead of "You cannot..."++> **Issue 3: Vague heading**+> Line 8: The heading could be more specific. Try stating the point directly: "Run migrations before upgrading" vs "Upgrade process"++### PR review mode format++When posting to GitHub (PR mode), use the **pending review workflow**:++**Workflow steps:**++1. **Start a review**: Use `mcp__github__create_pending_pull_request_review` to begin a pending review+ - This creates a draft review that won't be visible until submitted++2. **Get diff information**: Use `mcp__github__get_pull_request_diff` to understand the code changes and line numbers+ - This helps you determine the correct file paths and line numbers for comments++3. **Identify ALL issues**: Read through all changes and identify every issue worth mentioning+ - Collect all issues before posting any comments+ - Number them sequentially (Issue 1, Issue 2, Issue 3, etc.)++4. **Add review comments**: Use `mcp__github__add_pull_request_review_comment_to_pending_review` for each issue+ - **CRITICAL**: Post ALL comments in a SINGLE response using multiple tool calls in parallel+ - Each comment should reference a specific file path and line number from the diff+ - Start each comment body with `**Issue N: [Brief title]**`+ - Include the description and suggested fix++5. **Submit the review**: Use `mcp__github__submit_pending_pull_request_review` to publish all comments at once+ - Use event type `"COMMENT"` (NOT "REQUEST_CHANGES") to make it non-blocking+ - All comments will appear together as one cohesive review++**Comment format example:**+```+**Issue 1: Backticks on UI elements**++This uses backticks for the UI element. Use **bold** instead: **Filter** not `Filter`.+```++**IMPORTANT**:+- Each issue gets its own review comment attached to the pending review+- Number ALL comments sequentially (Issue 1, Issue 2, Issue 3, etc.)+- Always start the comment body with `**Issue N: [Brief title]**`+- **MUST add all comments in parallel in a single response** - Do NOT add them one after another in separate responses+- Do NOT output a summary message to the conversation - only post GitHub review comments+- The review will appear as a single review with multiple comments when submitted++## Final check++1. Remove any issues from your assessment that won't make a material difference to the reader if addressed. Only flag issues worth the author's time to fix.+2. **Verify all issues are numbered sequentially** starting from Issue 1 with no gaps in numbering.+3. Confirm the format exactly matches: `**Issue N: [Brief title]**` where N is the issue number.+4. **In PR mode**: Verify each issue was posted as a separate GitHub comment (not output to conversation).diff --git a/.claude/skills/docs-write/SKILL.md b/.claude/skills/docs-write/SKILL.mdnew file mode 100644index 00000000000..eb0d3728b3a--- /dev/null+++ b/.claude/skills/docs-write/SKILL.md@@ -0,0 +1,96 @@+---+name: docs-write+description: Write documentation following Metabase's conversational, clear, and user-focused style. Use when creating or editing documentation files (markdown, MDX, etc.).+allowed-tools: Read, Write, Grep, Bash, Glob+---++# Documentation Writing Skill++@./../_shared/metabase-style-guide.md++## When writing documentation++### Start here++1. **Who is this for?** Match complexity to audience. Don't oversimplify hard things or overcomplicate simple ones.+2. **What do they need?** Get them to the answer fast. Nobody wants to be in docs longer than necessary.+3. **What did you struggle with?** Those common questions you had when learning? Answer them (without literally including the question).++### Writing process++**Draft:**++- Write out the steps/explanation as you'd tell a colleague+- Lead with what to do, then explain why+- Use headings that state your point: "Set SAML before adding users" not "SAML configuration timing"++**Edit:**++- Read aloud. Does it sound like you talking? If it's too formal, simplify.+- Cut anything that doesn't directly help the reader+- Check each paragraph has one clear purpose+- Verify examples actually work (don't give examples that error)++**Polish:**++- Make links descriptive (never "here")+- Backticks only for code/variables, **bold** for UI elements+- American spelling, serial commas+- Keep images minimal and scoped tight++**Format:**++- Run prettier on the file after making edits: `yarn prettier --write <file-path>`+- This ensures consistent formatting across all documentation++### Common patterns++**Instructions:**++```markdown+Run:+\`\`\`+command-to-run+\`\`\`++Then:+\`\`\`+next-command+\`\`\`++This ensures you're getting the latest changes.+```++Not: "(remember to run X before Y...)" buried in a paragraph.++**Headings:**++- "Use environment variables for configuration" ✅+- "Environment variables" ❌ (too vague)+- "How to use environment variables for configuration" ❌ (too wordy)++**Links:**++- "Check out the [SAML documentation](link)" ✅+- "Read the docs [here](link)" ❌++### Watch out for++- Describing tasks as "easy" (you don't know the reader's context)+- Using "we" when talking about Metabase features (use "Metabase" or "it")+- Formal language: "utilize", "reference", "offerings"+- Too peppy: multiple exclamation points+- Burying the action in explanation+- Code examples that don't work+- Numbers that will become outdated++### Quick reference++| Write This | Not This |+| -------------------------- | ------------------ |+| people, companies | users |+| summarize | aggregate |+| take a look at | reference |+| can't, don't | cannot, do not |+| **Filter** button | \`Filter\` button |+| Check out [the docs](link) | Click [here](link) |diff --git a/.claude/skills/typescript-review/SKILL.md b/.claude/skills/typescript-review/SKILL.mdnew file mode 100644index 00000000000..2c1de31a524--- /dev/null+++ b/.claude/skills/typescript-review/SKILL.md@@ -0,0 +1,19 @@+---+name: typescript-review+description: Review TypeScript and JavaScript code changes for compliance with Metabase coding standards, style violations, and code quality issues. Use when reviewing pull requests or diffs containing TypeScript/JavaScript code.+allowed-tools: Read, Grep, Bash, Glob+---++# TypeScript/JavaScript Code Review Skill++@./../_shared/typescript-commands.md++## Code Review Guidelines++Review pull requests with a focus on:++- Compliance with project coding standards and conventions+- Code quality and best practices+- Clear and correct JSDoc comments+- Type safety and proper TypeScript usage+- React best practices (when applicable)\ No newline at end of filediff --git a/.claude/skills/typescript-write/SKILL.md b/.claude/skills/typescript-write/SKILL.mdnew file mode 100644index 00000000000..8204ff67333--- /dev/null+++ b/.claude/skills/typescript-write/SKILL.md@@ -0,0 +1,9 @@+---+name: typescript-write+description: Write TypeScript and JavaScript code following Metabase coding standards and best practices. Use when developing or refactoring TypeScript/JavaScript code.+---++# TypeScript/JavaScript Development Skill++@./../_shared/development-workflow.md+@./../_shared/typescript-commands.mddiff --git a/.github/workflows/claude-code-bug-fix.yml b/.github/workflows/claude-code-bug-fix.ymlindex 8317a298b91..6f6294c86ee 100644--- a/.github/workflows/claude-code-bug-fix.yml+++ b/.github/workflows/claude-code-bug-fix.yml@@ -159,15 +159,15 @@ jobs:1. **Analyze the issue description and comments** - Understand what the issue is describinga. Pay particular attention to reproduction steps and if there's an agreed upon fix.2. **Search the codebase** - Use Grep and Glob tools to find relevant files- 3. **Implement a fix** - Follow existing code patterns and conventions- 4. **Test the fix** - Run appropriate tests using the commands in CLAUDE.md:- - JavaScript/TypeScript: `yarn test-unit path/to/file.unit.spec.js`- - Clojure: `clojure -X:dev:test :only namespace/test-name`- - Lint: `yarn lint-eslint-pure` for JS/TS, `./bin/mage kondo <file>` for Clojure+ 3. **Implement a fix** - Use the appropriate write skill based on the file types:+ - Use clojure-write for Clojure/ClojureScript files+ - Use typescript-write for TypeScript/JavaScript files+ - Follow the coding standards and patterns in each skill+ 4. **Test the fix** - Run appropriate tests as specified in the skills5. **Verify the fix** - Ensure tests pass and code follows conventions## Important Guidelines- - Follow the development patterns in CLAUDE.md+ - Use the appropriate write skill for the language you're working in- Write failing tests first, then fix them- Work in small, testable increments- Don't commit changes - leave that for the workflowdiff --git a/.github/workflows/claude-code-review.yaml b/.github/workflows/claude-code-review.yamlindex 839fb8a490e..244e5b54848 100644--- a/.github/workflows/claude-code-review.yaml+++ b/.github/workflows/claude-code-review.yaml@@ -79,17 +79,14 @@ jobs:REPO: ${{ github.repository }}PR NUMBER: ${{ github.event.pull_request.number }}- Review this pull request with a focus on:+ Review this pull request for compliance with project coding standards and conventions.- - Compliance with project coding standards and conventions- - Code quality and best practices- - Clear and correct docstrings- - Clear and correct comments explaining what the code is doing+ **Use the appropriate review skill based on the file types changed:**+ - Use clojure-review for Clojure/ClojureScript files+ - Use typescript-review for TypeScript/JavaScript files+ - Follow the review guidelines and checklists in each skill- DO NOT post any comments confirming that something is correct or congratulating someone for following our- guidelines -- only post comments for style violations or concerns.-- Follow additional guidelines in the "Code Review Guidelines" section of CLAUDE.md .+ DO NOT post any comments confirming that something is correct - only post comments for style violations or concerns.Note: The PR branch is already checked out in the current working directory.diff --git a/.github/workflows/claude-docs-review.yml b/.github/workflows/claude-docs-review.ymlnew file mode 100644index 00000000000..01c1137545d--- /dev/null+++ b/.github/workflows/claude-docs-review.yml@@ -0,0 +1,78 @@+name: "Claude Docs Review"++on:+ pull_request:+ types:+ - opened+ - synchronize+ - reopened+ paths:+ - 'docs/**/*.md'+ - 'docs/**/*.mdx'+ workflow_dispatch:+ inputs:+ pr_number:+ description: 'PR number to review'+ required: true+ type: number++concurrency:+ group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-claude-docs-review+ cancel-in-progress: true++jobs:+ review:+ runs-on: ubuntu-latest+ permissions:+ contents: read+ pull-requests: write++ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 1+ # Make sure the value of GITHUB_TOKEN will not be persisted in repo's config+ persist-credentials: false++ - name: Delete old Claude docs review comments+ env:+ GH_TOKEN: ${{ github.token }}+ REPO: ${{ github.repository }}+ PR_NUMBER: ${{ github.event.pull_request.number || github.event.inputs.pr_number }}+ shell: bash+ run: |+ # Delete old reviews from the bot (reviews contain inline comments)+ old_review_ids=$(gh api "/repos/$REPO/pulls/$PR_NUMBER/reviews" --jq '.[] | select(.user.login=="metabase-bot[bot]") | .id')+ echo "Deleting reviews: $old_review_ids"+ for id in $old_review_ids; do+ # Note: This deletes the review and all associated comments+ gh api -X DELETE "/repos/$REPO/pulls/$PR_NUMBER/reviews/$id"+ echo "Deleted review $id"+ done++ - name: Generate GitHub App Token for Claude+ uses: actions/create-github-app-token@v1+ id: claude-app-token+ with:+ app-id: ${{ secrets.METABASE_BOT_APP_ID }}+ private-key: ${{ secrets.METABASE_BOT_APP_PRIVATE_KEY }}+ permission-contents: read # Required for reading repository files and PR diffs+ permission-pull-requests: write # Required for creating inline comments and PR comments++ - uses: anthropics/claude-code-action@v1+ timeout-minutes: 10+ with:+ anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}+ github_token: ${{ steps.claude-app-token.outputs.token }}+ prompt: |+ REPO: ${{ github.repository }}+ PR NUMBER: ${{ github.event.pull_request.number || github.event.inputs.pr_number }}++ Review the documentation changes in this pull request.++ Use the docs-review skill to review all changed documentation files for compliance with the Metabase writing style guide.++ DO NOT post any comments confirming that something is correct - only post comments for style violations or concerns.++ claude_args: |+ --allowedTools "mcp__github__create_pending_pull_request_review,mcp__github__get_pull_request_diff,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,Bash(gh pr view:*)"diff --git a/CLAUDE.md b/CLAUDE.mdindex b57dfeffe20..0f5095676f5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,722 +1,20 @@# Metabase Development Guide-## Autonomous Development Workflow+# Skills-- Do not attempt to read or edit files outside the project folder-- Add failing tests first, then fix them-- Work autonomously in small, testable increments-- Run targeted tests, and lint continuously during development-- Prioritize understanding existing patterns before implementing-- Don't commit changes, leave it for the user to review and make commits+For detailed guidance on writing and reviewing code and documentation, see the skills in [.claude/skills/](.claude/skills/):-## Quick Commands+## Clojure-### JavaScript/TypeScript+- **[clojure-write](.claude/skills/clojure-write/SKILL.md)** - Clojure/ClojureScript development with REPL-driven workflow and coding conventions+- **[clojure-review](.claude/skills/clojure-review/SKILL.md)** - Clojure/ClojureScript code review guidelines and style enforcement-- **Lint:** `yarn lint-eslint-pure`-- **Test:** `yarn test-unit-keep-cljs path/to/file.unit.spec.js` or `yarn test-unit-keep-cljs -t "pattern"`-- **Format:** `yarn prettier`-- **Type Check:** `yarn type-check-pure`+## TypeScript-### Clojure+- **[typescript-write](.claude/skills/typescript-write/SKILL.md)** - TypeScript/JavaScript development and best practices+- **[typescript-review](.claude/skills/typescript-review/SKILL.md)** - TypeScript/JavaScript code review guidelines-- **Lint PR:** `./bin/mage kondo-updated master` (or whatever target branch)- - Call the command one time at the beginning, record the results, then work through the problems one at a time.- - If the solution is obvious, then please apply the fix. Otherwise skip it.- - If you fix all the issues (and verify by rerunning the kondo-updated command):- - commit the change with a succinct and descriptive commit message-- **Lint File:** `./bin/mage kondo <file or files>` (or whatever target branch)- - Use the linter as a way to know that you are adhering to conventions in place in the codebase-- **Lint Changes:** `./bin/mage kondo-updated HEAD`-- **Format:** `./bin/mage cljfmt-files [path]`-- **Run a test:** `./bin-mage run-tests namespace/test-name`-- **Run all tests in a namespace:** `./bin-mage run-tests namespace`-- **Check Code Readability** `./bin/mage -check-readable` with optional line-number- - Run this after every change to Clojure code, only accept readable code-- **Evaluating Clojure Code** `./bin/mage -repl '<code>'`- - See `Sending code to the REPL` for more details+## Documentation-### ClojureScript--- **Test:** `yarn test-cljs`--## Clojure REPL-driven development--- Start with small, fundamental functions:-- Identify the core features or functionalities required for your task.-- Break each feature down into the smallest, most basic functions that can be developed and tested independently.-- Write and test in the REPL:- - Write the code for each small function directly in the REPL (Read-Eval-Print Loop).- - Test it thoroughly with a variety of inputs, including typical use cases and relevant edge cases, to ensure it- behaves as expected.-- Integrate into source code:- - Once a function works correctly in the REPL, move it from the REPL environment into your source code files (e.g.,- within appropriate namespaces).-- Gradually increase complexity:- - Build upon tested, basic functions to create more complex functions or components.- - Compose smaller functions together, testing each new composition in the REPL to verify correctness step by step.-- Ensure dependency testing:- - Make sure every function is fully tested in the REPL before it is depended upon by other functions.- - This ensures that each layer of your application is reliable before you build on it.-- Leverage the REPL fully:- - Use the REPL as your primary tool to experiment with different approaches, iterate quickly, and get immediate- feedback on your code.-- Follow functional programming principles:- - Keep functions small, focused, and composable.- - Leverage Clojure's functional programming features—like immutability, higher-order functions, and the standard- library—to write concise, effective code.--### How to evaluate code--#### Keeping Code Readable--The `./bin/mage -check-readable <file> <optional: line-number>` command checks if your Clojure code can be properly parsed.-This ensures your changes maintain valid syntax and structure.--- Edit Clojure files one step at a time.-- After EVERY change to a Clojure form, call `mage -check-readable src/metabase/thefile.clj <line-number>` with the line number.-- If it's readable then call `mage -check-readable dev/src/dev.clj` without the line number to check the entire file.-- If the change results in unreadable code, try again until it is readable.-- To overcome errors about parens, pay close attention to them. Count opening/closing parens you add/remove.--#### Bottom-up dev loop--1. Write code into a file.-2. Evaluate the file's namespace and make sure it loads correctly with:--```-mage -repl --namespace metabase.app-db.connection-```--3. Call functions in the namespace with test inputs, and observe that the outputs are correct 3.1- Feel free to copy these REPL session trials into actual test cases using `deftest` and `is`.-4. Once you know these functions are good, return to 1, and compose them into the task that you need to build.--#### Sending code to the REPL--- Send code to the metabase process REPL using: `./bin/mage -repl '(+ 1 1)'` where `(+ 1 1)` is your Clojure code.- - See `./bin/mage -repl -h` for more details.- - If the Metabase backend is not running, you'll see an error message with instructions on how to start it.--##### Working with files and namespaces--1. **Load a file and call functions with fully qualified names**:--To call `your.namespace/your-function` on `arg1` and `arg2`:--```-./bin/mage -repl --namespace your.namespace '(your-function arg1 arg2)'-```--DO NOT use "require", "load-file" etc in the code string argument.--##### Understanding the response--The `./bin/mage -repl` command returns three separate, independent outputs:--- `value`: The return value of the last expression (best for data structures)-- `stdout`: Any printed output from `println` etc. (best for messages)-- `stderr`: Any error messages (best for warnings and errors)--Example call:--```bash-./bin/mage -repl '(println "Hello, world!") '\''({0 1, 1 3, 2 0, 3 2} {0 2, 1 0, 2 3, 3 1})'-```--Example response:--```-ns: user-session: 32a35206-871c-4553-9bc9-f49491173d1c-value: ({0 1, 1 3, 2 0, 3 2} {0 2, 1 0, 2 3, 3 1})-stdout: Hello, world!-stderr:-```--For effective REPL usage:--- Return data structures as function return values-- Use `println` for human-readable messages-- Print errors to stderr--## Tips--- End all files with a newline.-- When editing tabular code, where the columns line up, try to keep them aligned.-- Spaces on a line with nothing after it is not allowed--## Critical REPL Usage Rules--- Be careful with parentheses counts when editing Clojure code-- After EVERY change to Clojure code, verify readability with `-check-readable`--# Code Review Guidelines--Review pull requests with a focus on:--- Compliance with project coding standards and conventions--- Code quality and best practices--- Clear and correct docstrings--- Clear and correct comments explaining what the code is doing--## More Instructions--- Carefully read the Community Clojure Style Guide from `CLOJURE_STYLE_GUIDE.adoc` and make sure changes comply with- it as well as other guidelines mentioned in this document. Flag _all_ violations of the Community Clojure Style- Guide.--- Do not post comments congratulating someone for trivial changes, or for following the style guidelines, or- confirming that things "look good", or telling them that they did something correctly; only post comments about- style violations or potential issues. Example bad code review comments to avoid:-- > This TODO comment is properly formatted with author and date - nice work!-- > Good addition of limit 1 to the query - this makes the test more efficient without changing its behavior.-- > The kondo ignore comment is appropriately placed here-- > The kondo ignore is properly used here. The comment on lines 42-45 explains why hardcoded driver names are needed,- > which is good context.-- > Test name properly ends with -test as required by the style guide.--- Do not post comments about missing parentheses.--# Code Conventions and Style Guide--## Clojure and ClojureScript--### General Conventions--- Prefer longer, more verbose names for functions and variables; avoid abbreviations unless they are well-known and- conventional in the Clojure world. `acc`, `i`, `pred`, `coll`, `n`, `s`, `k`, and `f` are examples of well-known- conventions; any Clojure developer has seen them before and can tell you what they mean. Avoid unconventional- abbreviations like `tbl` and unclear variable names like `zs'`. A good function or variable name should make its- purpose immediately clear. Error on the side of longer variable names if needed.-- ```clj- ;; too cryptic- (defn mayb+1 [n]- (when n- (inc n)))-- ;; just right- (defn maybe-inc [n]- (when n- (inc n)))- ```-- **Why?** Code is read many more times than it is written, and clearer variable names make using and tweaking your- code easier for others.-- Conventions used widely in our codebase (like `mp` for a Metadata Provider) are acceptable; one-offs like `zs'` are- not.--- Avoid misleading variable and function names. The names of a variable or function should clearly and unambiguously- describe its purpose and match what it does.-- ```clj- ;; bad- (defn nil-or-maplist? [v] ; coll would be a better variable name because it's more specific- (or (nil? v)- (and (sequential? v) ; v can actually be an array, vector, list, or lazy seq- (every? map? v))))-- ;; good- (defn nil-or-sequence-of-maps? [coll]- (or (nil? coll)- (and (sequential? coll)- (every? map? coll))))- ```-- **Why?** Poorly-named functions are prone to being used in cases where they're inappropriate or avoided in cases- when they would be suitable.--- Pure function names should be nouns describing the value they return.-- For example, a function to compute a user's age based on their birthdate should be called `age`, not `calculate-age`- or `get-age`.-- **Why?** A pure function is one which can be replaced with its value without affecting the result, so the name- should reflect that.--- Don't repeat the usual alias of the namespace a function belongs to in the name of a function itself.-- ```clj- (ns metabase.config)-- ;; bad- (defn config-is-dev? [] ...)-- ;; good- (defn is-dev? [] ...)- ```-- **Why?** It's obvious that `is-dev?` in the example above is referring to `dev`, because it's in the `config`- namespace. It's also needlessly noisy when using the function in another namespace:-- ```clj- ;; bad- (when (config/config-is-dev?)- ...)-- ;; good- (when (config/is-dev?)- ...)- ```-- In some cases, following this rule will require you to use a `(:refer-clojure :exclude [...])` form in your namespace- declaration. This is acceptable, and should be taken as a sign that you're following this rule correctly.--- If you shadow a `clojure.core` var, make sure you use `(:refer-clojure :exclude ...)` in the `ns` form.--- Make everything `^:private` unless it is used elsewhere.-- Don't make things public just for the sake of tests. Use the var form (e.g. `#'redshift/execute!`) instead in your- tests.-- **Why?** It's much easier to read and refactor code when you know its scope is limited to the current namespace.--- Tag variables with `:arglists` metadata if they are functions but wouldn't otherwise have it, such as when using- `def` to define partial functions or function compositions e.g.-- ```clj- (def ^{:arglists '([n])} plus-one (partial + 1))- ```-- **Why?** Good editors use this metadata show the expected arguments to a function as you're writing code.--- Try to organize namespaces in such a way that you don't need to use `declare`. This usually means putting the public- portion of a namespace near the end of a file.-- **Why?** Avoiding declare when unnecessary forces us to read and write code in a consistent manner, that is, from- top to bottom. When code is written in this consistent order we can safely assume referenced functions sit somewhere- above their reference in the namespace; this makes the code easier to navigate.--- Don't mark things `^:const` unless you have a really good reason for doing so. Add a comment explaining why you- marked it `^:const`.--- Every public var in `src` or `enterprise/backend/src` must have a _useful_ docstring. A useful docstring- should clearly explain the purpose of the function, its inputs and outputs, and anything else that is otherwise not- immediately clear. If there are other functions that have similar purposes, explain how the use-cases for this- function differ.-- Tests and other vars in the `test` or `enterprise/backend/test` do not _require_ docstrings, but general helper- functions used across many namespaces it should have docstrings.-- Schemas defined with `mr/def` e.g. `(mr/def ::my-schema)` do not require docstrings.--- Format docstrings according to Markdown conventions. (https://guide.clojure.style/#markdown-docstrings)--- Mentions of other vars in docstrings should use `[[some-other-var]]` (for vars in the same namespace) or- `[[metabase.namespace/some-other-var]]` (for vars in a different namespace) instead of backticks; references in- docstrings should be valid (i.e., point to something that exists).- (https://guide.clojure.style/#document-references)--- Judiciously use comments to explain sections of code that would not immediately be clear to someone else. Avoid- comments that do little more than repeat what the code already says.--- Make sure to update comments and docstrings when you change the code they describe.--- `TODO` comments should include the author and date, for example-- ```clj- ;; TODO (Cam 10/7/25) -- this is a properly formatted TODO comment- (...)- ```--- Break up larger functions (> 20 lines) in source code (`src` or `enterprise/backend/src`) whenever possible. Small- functions are much easier to test, understand, and tweak. Tests are allowed to be longer, especially when they- contain mock data, but they should probably never be more than 100 lines.--- Try to keep lines 120 characters wide or less; use this as a guideline when formatting docstrings or comments.--- **No Blank Lines Within Definition Forms** Do not place blank lines in the middle of a function or macro definition.- An exception can be made to indicate grouping of pairwise constructs as found in e.g. `let` and `cond`, in case- those don’t fit on the same line. `deftest` is **NOT** an exception to this rule.- (https://guide.clojure.style/#no-blank-lines-within-def-forms) Verify that the line in question is **actually- blank** (i.e., only contains whitespace for the **entire line**) before warning about this. **A line that contains- any non-whitespace character is not a blank line.** You will be shut down if you make this mistake too many times,- so be careful.--- Use `kebab-case` names for variables and defs, including constants.- (https://guide.clojure.style/#naming-functions-and-variables)-- ```clj- ;;; BAD- (def MY_CONSTANT 100)-- ;;; GOOD- (def my-constant 100)-- ;;; BAD- (defn myFunction [my_arg] ...)-- ;;; GOOD- (defn my-function [my-arg] ...)- ```--- Map destructuring should use kebab-case local bindings even if the map it was destructured from uses `snake_case`- keys or if it is returned as a value for a `snake_case` key.-- ```clj- ;; Good- (let [{database-id :database_id} some-object]- {:database_id database-id, :table_id 100})-- ;; Bad- (let [{database_id :database_id} some-object]- {:database_id database_id, :table_id 100})- ```--- Prefer namespaced keywords for keywords that are used internally (i.e., not returned by the REST API or persisted by- the app DB):-- ```clj- ;;; good- (defn query-type [x]- (if (some-pred? x)- :query-type/normal- :query-type/crazy))-- ;;; bad- (defn query-type [x]- (if (some-pred? x)- :normal- :crazy))- ```-- These are easy to search across the entire application and makes their origin clearer.--- Functions that have side-effects such as writing to the application database or mutating the global state of the- application should have names that end in exclamation points. Exclamation points should be considered "sticky", so- if a function uses another function with a name ending in an exclamation point, it too should have a name that ends- in an exclamation point. (https://guide.clojure.style/#naming-unsafe-functions)-- An exception is functions that write log messages or other output to the console; these don't need exclamation- points.--### Tests--- Large tests should be broken out into separate `deftest` forms when they consist of several logically separate test- cases.-- ```clj- (deftest ^:parallel my-test- (testing "Some logically discrete test case"- (is ...)))-- (deftest ^:parallel my-other-test- (testing "Another logically discrete test case"- (is ...)))-- (deftest ^:parallel my-third-different-test- (testing "A third logically discrete test case"- (is ...)))-- (deftest ^:parallel my-amazing-test- (testing "A fourth logically discrete test case"- (is ...)))- ```-- is preferable to-- ```clj- (deftest ^:parallel my-test- (testing "Some logically discrete test case"- (is ...))-- (testing "Another logically discrete test case"- (is ...))-- (testing "A third logically discrete test case"- (is ...))-- (testing "A fourth logically discrete test case"- (is ...)))- ```--- Mark pure function tests `^:parallel`.--- Test utility functions that are not thread-safe/safe in `^:parallel` tests should have names that end in an- exclamation mark.--- Test names in `deftest` forms should end in `-test` or `-test-<number>` e.g. `whatever-test` or `whatever-test-2` or- even `whatever-test-2b`. (https://guide.clojure.style/#test-naming)--### Modules--- The backend codebase is broken out into separate modules.--- The module configuration file lives in `.clj-kondo/config/modules/config.edn`. There is one entry for each module.- The entry has several keys, but the important ones are `:api` -- the list of namespaces this module provides for use- outside of the module -- and `:uses` -- the list of modules this module directly relies on.--- An OSS follows the pattern `metabase.<module>.*` (for the Clojure namespace) and `src/metabase/<module>/**`(for the- source files) with tests inside the corresponding `test/metabase/<module>/` directory, e.g. the `dashboards` module- is everything inside `src/metabase/dashboards/` and `test/metabase/dashboards/`; it might have a- `metabase.dashboards-rest.api` namespace that corresponds to the file `src/metabase/dashboards/api.clj`.--- An EE module follows the pattern `metabase-enterprise.<module>.*` (for the Clojure namespaces) and- `enterprise/backend/src/metabase_enterprise/<module>/**` (for the source files). The module name uses the- `enterprise/` prefix. For example, `enterprise/billing` is everything in the- `enterprise/backend/src/metabase_enterprise/billing/` directory (for source code) and- `enterprise/backend/test/metabase_enterprise/billing/` (for tests); it might have a namespace called- `metabase-enterprise.billing.api` which corresponds to the file- `enterprise/backend/src/metabase_enterprise/billing/api.clj`.--- REST API endpoints (defined by the `defendpoint` macro) should live in a `<module>.api` or `<module>.api.*`- namespace, e.g. `metabase.dashboards.api` or `metabase.dashboards.api.x`.--- When you add a new API endpoint namespace, you need to add a mapping for it in `metabase.api-routes.routes`.--- Put any functions used by other modules (the API meant for the rest of the backend code) in `<module>.core` .- `.core` should import stuff with Potemkin/ `metabase.util.namespace` and not be used inside the module itself. It’s- also nice to put a `:consistent-alias` entry for this namespace in the Kondo config.--- The `<module>.core` namespace should generally be empty other than importing things from other namespaces with- Potemkin (`potemkin/import-vars` and the like).--- Put Toucan models related to a feature in `<module>.models.*` and add mappings in `metabase.models.resolution`.--- Put scheduled Quartz tasks in `<module>.task.*`.--- Put event handlers (things that use the events subsystem in `metabase.events.core`) in `<module>.event.*`.--- Put `defsetting`s (Settings) in `<module>.settings`.--- Quartz tasks, event handlers, and Settings all need to be loaded on launch, so if you have any of the above add- them to a `<module>.init` namespace and require it in `metabase[-enterprise].core.init`.--- Don't try to cheat the module linters by using things like `#_{:clj-kondo/ignore [:metabase/modules]}`. Note that- this does not apply to using `:clj-kondo/ignore` to disable warnings for other linters besides `:metabase/modules`.--- Put Malli schemas in `<module>.schema`.--- Aim to keep the number of namespaces used outside of a module small. A module should only need at most a subset of- `<module>.api`, `<module>.settings`, `<module>.schema`, `<module>.init`, and `<module>.core`.--- Try to minimize the direct dependencies of a module as well as the indirect dependencies. Modules that are used by- lots of other modules (such as `util`) ideally will have no dependencies on other modules. Our goal is to make as- many modules as possible be "leaf nodes".--- Module names should be match the customer-facing name of the feature they concern, usually a plural noun, for- example, `dashboards` rather than `dashboard`.--### Settings--- Don't define configurable options that can only be set with environment variables; use an `:internal` `defsetting`- instead. We have lots of tooling around `defsetting`.--### REST API Endpoints--- All new REST API Endpoints (defined by `defendpoint`) should have a response schema (denoted by `:- <schema>` after- the route string).-- ```clj- ;;; BAD- (api.macros/defendpoint :get "/"- "Get a list of all transform tags."- ...)-- ;;; GOOD- (api.macros/defendpoint :get "/" :- [:sequential ::whatever-this-returns]- "Get a list of all transform tags."- ...)- ```--- Query parameters should also use kebab-case e.g. `GET /api/dashboards?include-archived=true` is good while `GET-/api/dashboards?include_archived=true` or `GET /api/dashboards?includeArchived=true` is bad.--- HTTP request bodies should use `snake_case`.--- REST API endpoints should have routes that use singular nouns, for example `GET /api/dashboard/:id` to get a- Dashboard rather than `GET /api/dashboards/:id`.--- `GET` endpoints should not have side effects outside of analytics like updating last-viewed-at timestamps or- recording usage metrics. A `GET` endpoint should not be creating new rows in the application database representing- user-facing objects, for example `GET /api/dashboard` should not attempt to populate empty Dashboards with content- by creating new rows in the application database.--- `defendpoint` forms should be small wrappers around Toucan model code. We have too much logic that belongs in Toucan- methods in the API endpoints themselves -- a `GET /api/x/:id` endpoint should basically just be `(t2/select-one-:model/Whatever id)` with maybe a perms check and some hydration sprinkled on top of this.--- All API endpoints should have Malli schemas for any parameters that aren't ignored. `_route-params` doesn't need a- schema, but `{:keys [x]}` should have one.--- Malli schemas for REST API endpoints should be detailed enough that someone can look at them and know how to use the- endpoint.-- Example: for an endpoint like this:-- ```clj- (api.macros/defendpoint :post "/check_transform"- "Check a proposed edit to a transform, and return the card, transform, etc. IDs for things that will break."- [_route-params- _query-params- {:keys [id source target] :as _body} :- ::transform-body]- ...)- ```-- This is a bad schema for the request body:-- ```clj- ;;; Bad, does not specify the shape of :source and :target in any real detail- (mr/def ::transform-body- [:map- [:id {:optional false} ms/PositiveInt]- [:name {:optional true} :string]- [:source {:optional true} [:maybe ms/Map]]- [:target {:optional true} [:maybe ms/Map]]])- ```-- While this is better:-- ```clj- ;;; Better, because it tells us the expected shape of :source and :target- (mr/def ::transform-body- [:map- [:id {:optional false} ms/PositiveInt]- [:name {:optional true} :string]- [:source {:optional true} [:maybe [:map [:x pos-int?] [:y pos-int?]]]]- [:target {:optional true} [:maybe [:map [:a pos-int?] [:b pos-int?]]]]])- ```--- All new REST API endpoints **MUST HAVE TESTS**.--### MBQL--- No raw MBQL introspection or manipulation should be done outside of Lib (the `lib` and `lib-be` modules) or the- Query Processor (the `query-processor` module) modules. MBQL maps include the `:model/Card` `dataset_query`, you can- usually recognize it when you see a map with a `:database` key and either `:type` or `:lib/type`. You should treat- this map as an opaque object outside of the aforementioned modules; pretend you didn't know it has a `:database` or- `:type` key.--- Use Lib and MBQL 5 in all new **source** code instead of legacy MBQL; avoid use of the `legacy-mbql` module, or the- `metabase.query-processor.store` namespace, in new code. Any code that checks whether a query `:type` is `:native`- or `:query` is a gigantic code smell. Exception: we will allow legacy MBQL in tests... for now.--- Use of `qp.store/with-metadata-provider` or `mt/with-metadata-provider` should be discouraged and phased out.--## Models and the Application Database--- Model names should be singular nouns, e.g. `:model/Dashboard` and not `:model/Dashboards`.--- Table names in the application database should be singular nouns, e.g. `transform` instead of `transforms`.--- The application database should use `snake_case` identifiers for table and column names.--## Using Toucan--- Never fetch an entire row from the application database only to immediately discard everything except for the value- of one column, this is super inefficient and also icky. Use `t2/select-one-fn` instead.-- ```clj- ;;; Bad- (:database_id (t2/select-one :model/Card :id 1))-- ;;; Good- (t2/select-one-fn :database_id :model/Card :id 1)-- ;;; Even better -- this does SELECT database_id instead of SELECT *- (t2/select-one-fn :database_id [:model/Card :database_id] :id 1)- ```--- One of the big ideas behind Toucan is there's never supposed to be a question of "what function to I use to create- an X correctly" or "what function do I use to update a Y correctly" -- the answer is always supposed to be- `t2/select`, `t2/update!`, etc. That's why they're backed by multimethods, so you can put the correct behavior in- the model's method and then it becomes impossible for you to forget to call the correct function. Avoid adding- functions like `select-dashboards` or `update-dashboard!` -- put this functionality in Toucan methods for the model- in question. This includes things like firing off events.--- Avoid the `mi/define-batched-hydration-method` and `mi/define-simple-hydration-method` helpers in new code; define- method implementations with `(methodical/defmethod t2/batched-hydrate ...)` directly instead.--### Drivers--- All new driver multimethods must be mentioned in `docs/developers-guide/driver-changelog.md`.--- All new driver multimethods should use Lib-style kebab-cased metadata and MBQL 5 queries.--- Driver multimethod implementations (`defmethod` forms) should explicitly pass any `driver` argument to any other- driver multimethods it invokes, rather than hardcoding the driver name.-- ```clj- ;;; Good- (defmethod driver/driver-method :postgres- [driver x]- (driver/some-other-method driver x))-- ;;; Bad- (defmethod driver/driver-method :postgres- [_driver x]- (driver/some-other-method :postgres x))- ```-- This is because other drivers may inherit from this driver and we need to propagate the driver name passed in to any- method implementations it inherits.--- Drivers should only use methods from the `driver` or `driver-api` modules.--- Be sure to minimize the amount of logic you're doing inside the `read-column-thunk` in JDBC-based drivers as much as- possible. Here's our Athena code for java.sql.Types/TIMESTAMP_WITH_TIMEZONE for example:-- ```clj- (defmethod sql-jdbc.execute/read-column-thunk [:athena Types/TIMESTAMP_WITH_TIMEZONE]- [_driver ^ResultSet rs _rs-meta ^Long i]- (fn []- ;; Using ZonedDateTime if available to conform tests first. OffsetDateTime if former is not available.- (when-some [^Timestamp timestamp (.getObject rs i Timestamp)]- (let [timestamp-instant (.toInstant timestamp)- results-timezone (driver-api/results-timezone-id)]- ...))))- ```-- Here's a tiny change that will avoid calling (driver-api/results-timezone-id) potentially 10 million times (for a- potential million-row result with 10 timestamp columns)-- ```clj- (defmethod sql-jdbc.execute/read-column-thunk [:athena Types/TIMESTAMP_WITH_TIMEZONE]- [_driver ^ResultSet rs _rs-meta ^Long i]- (let [results-timezone (driver-api/results-timezone-id)]- (fn []- ;; Using ZonedDateTime if available to conform tests first. OffsetDateTime if former is not available.- (when-some [^Timestamp timestamp (.getObject rs i Timestamp)]- (let [timestamp-instant (.toInstant timestamp)]- ...)))))- ```--- Avoid defining new datasets with `defdataset` as much as possible, since loading test data in cloud-based databases- is crazy slow.--### Misc--- Example data should be bird-themed if possible.--- Any comments that are written by or mention `Cam` should be given bonus points.--### Kondo--- Kondo linter warnings are suppressed with a comment proceeding the form to ignore warnings in e.g.-- ```clj- #_{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}- (do-x ...)- ```-- to ignore the `:metabase/disallow-hardcoded-driver-names-in-tests` Linter inside the `(do-x ...)` form. You do not- need to point these out to us, we know what they do.-- ```clj- ^{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}- (do-x ...)- ```-- is an acceptable alternative.--- Avoid ignoring **everything** with a `#_:clj-kondo/ignore` (a keyword instead of a map).+- **[docs-write](.claude/skills/docs-write/SKILL.md)** - Documentation writing with Metabase style guide+- **[docs-review](.claude/skills/docs-review/SKILL.md)** - Documentation review checklist