Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: style guide, ast-grep (#4721)

teo0bbf95471397
diff --git a/.coderabbit.yaml b/.coderabbit.yaml
index 8c792a66b7..bd7bd4907f 100644
--- a/.coderabbit.yaml
+++ b/.coderabbit.yaml
@@ -166,9 +166,12 @@ reviews:
enabled: true
timeout_ms: 90000
- # AST analysis
+ # AST analysis. rule_dirs points at the same custom rules that CI runs
+ # (sgconfig.yml at the repo root), so bot comments match CI failures.
ast-grep:
essential_rules: true
+ rule_dirs:
+ - "rules/ast-grep"
# Disabled: not used in this repo
ruff:
@@ -242,6 +245,7 @@ knowledge_base:
filePatterns:
- "**/CLAUDE.md"
- "**/AGENTS.md"
+ - "STYLE_GUIDE.md"
- "**/.cursor/rules/*.mdc"
- "**/.cursor/commands/*.md"
diff --git a/.github/workflows/code_check_conventions.yml b/.github/workflows/code_check_conventions.yml
new file mode 100644
index 0000000000..d675505278
--- /dev/null
+++ b/.github/workflows/code_check_conventions.yml
@@ -0,0 +1,90 @@
+# DO NOT EDIT — regenerate with `cargo x workflows` (from rust/cloud-storage).
+# Source: rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs
+name: conventions code check
+'on':
+ pull_request:
+ types:
+ - opened
+ - synchronize
+ - reopened
+ - ready_for_review
+ branches:
+ - main
+permissions:
+ contents: read
+jobs:
+ path-check:
+ runs-on: namespace-profile-linux-small
+ outputs:
+ should_run: ${{ steps.filter.outputs.should_run }}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ clean: 'false'
+ persist-credentials: 'false'
+ - id: filter
+ name: Filter changed paths
+ uses: dorny/paths-filter@d1c1ffe0248fe513906c8e24db8ea791d46f8590
+ with:
+ filters: |
+ should_run:
+ - 'rust/**'
+ - 'js/app/**'
+ - 'js/lexical-core/**'
+ - 'rules/**'
+ - 'sgconfig.yml'
+ - '.github/workflows/code_check_conventions.yml'
+ ast-grep:
+ needs:
+ - path-check
+ if: needs.path-check.outputs.should_run == 'true' && github.event.pull_request.draft == false
+ name: ast-grep Conventions
+ runs-on: namespace-profile-linux-small;overrides.cache-tag=web-ci
+ steps:
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ clean: 'false'
+ persist-credentials: 'false'
+ - name: Mount Namespace cache volume
+ uses: namespacelabs/nscloud-cache-action@15799a6b54e5765f85b2aac25b3f0df43ed571c0
+ with:
+ cache: bun
+ path: /nix
+ continue-on-error: true
+ - name: Setup Nix
+ uses: './.github/actions/setup-nix'
+ - name: Setup Nix dev shell
+ uses: './.github/actions/setup-cachix'
+ with:
+ cachix-auth-token: ${{ secrets.CACHIX_AUTH_TOKEN }}
+ dev-shell: 'true'
+ - name: Run ast-grep
+ run: bunx --yes @ast-grep/[email protected] scan
+ status-check:
+ needs:
+ - path-check
+ - ast-grep
+ if: always()
+ name: Conventions Status Check
+ runs-on: namespace-profile-linux-small
+ steps:
+ - name: Check job results
+ run: |
+ echo "path-check: ${{ needs.path-check.result }}"
+ echo "ast-grep: ${{ needs.ast-grep.result }}"
+
+ # Fail if any job failed, or ast-grep was cancelled (skipped and
+ # success are both OK; cancelled means it started and didn't finish)
+ if [[ "${{ needs.path-check.result }}" == "failure" ]] || \
+ [[ "${{ needs.ast-grep.result }}" == "failure" ]] || \
+ [[ "${{ needs.ast-grep.result }}" == "cancelled" ]]; then
+ echo "❌ One or more jobs failed"
+ exit 1
+ fi
+
+ echo "✅ All jobs passed or were skipped"
+concurrency:
+ group: code-check-conventions-${{ github.ref }}
+ cancel-in-progress: true
diff --git a/STYLE_GUIDE.md b/STYLE_GUIDE.md
new file mode 100644
index 0000000000..3a1af532d1
--- /dev/null
+++ b/STYLE_GUIDE.md
@@ -0,0 +1,213 @@
+# Code Review Style Guide
+
+**Check locally.** `just check` is the single gate: format + lint + code rules, scoped
+to your changes vs `origin/main`, every finding printed as `file:line [rule-id]` with
+the command that fixes it. `just check full` adds tsc + clippy.
+
+**Format.** One rule per line: `<id> [scope] rule (evidence · enforcement · docs)`.
+The id prefix is the domain:
+
+- `CS-##` — cloud storage (`rust/cloud-storage`)
+- `FE-##` — frontend (`js/app`, `js/lexical-core`)
+
+IDs are stable — cite them in review comments ("see CS-30", "FE-12"), never renumber or
+reuse them; deletions leave gaps and new rules append with the next free number. Scope
+tags make the list greppable.
+
+CS scopes: `[db]` database & migrations · `[types]` type design · `[cfg]` config, env,
+secrets · `[err]` errors & observability · `[arch]` architecture & boundaries · `[api]`
+API & handler design · `[sec]` security & permissions · `[rust]` Rust idioms · `[perf]`
+performance · `[test]` testing
+
+FE scopes: `[data]` data fetching & queries · `[solid]` Solid reactivity & state ·
+`[async]` async & error handling · `[arch]` architecture & module hygiene · `[ts]`
+TypeScript · `[ui]` UI / UX conventions
+
+---
+
+## Cloud storage (`rust/cloud-storage`)
+
+- **CS-01** `[db]` Generate ids as UUIDv7 in application code — never `gen_random_uuid()`
+ (UUIDv4); v7 ids sort by creation time. (#4296)
+- **CS-02** `[db]` Make seed/backfill inserts and anything that can race idempotent with
+ an `ON CONFLICT` handler. (#4296, #4498)
+- **CS-03** `[db]` Prefer natural/composite keys over surrogate ids when the table is
+ queried/sorted by those columns anyway, and key REST routes on the natural id.
+ (#4296, #4498)
+- **CS-04** `[db]` Name user columns `user_id` — not `owner_user_id` or other variants;
+ follow existing tables. (#4498)
+- **CS-05** `[db]` New tables need a deliberate cascade/cleanup story, not whatever the
+ default happens to be. (#4296)
+- **CS-06** `[db]` Don't add redundant indexes — a column already covered as the leading
+ part of the primary key does not need its own index. (#3961)
+- **CS-07** `[db]` Don't store columns that are implicit in context (e.g. a scoping id
+ already fixed per durable object / per tenant). (#3961)
+- **CS-08** `[db]` Use `sqlx::query!` / `query_as!` (compile-time checked) by default;
+ the non-macro form is only for queries that genuinely cannot be statically known.
+ (#4156 · enforced: clippy `disallowed-methods` · also: CLAUDE.md)
+- **CS-09** `[db]` The `.sqlx` cache lives at the workspace root — run `just prepare_db`
+ from `rust/cloud-storage`; never commit a `.sqlx` directory inside an individual
+ crate. (#4577 · also: CLAUDE.md)
+- **CS-10** `[types]` Newtype your identifiers and tokens — wrap raw `String`
+ ids/tokens/model-ids in a validated newtype that checks shape at construction.
+ (#4020, #4077, #4276)
+- **CS-11** `[types]` A closed set of string values is an enum, not a `String` — impl
+ `Display`/`FromStr` as needed. (#4296, #4410)
+- **CS-12** `[types]` Optional means `Option<T>` — don't rely on sentinel values or
+ convention to express absence. (#4296)
+- **CS-13** `[types]` Model tri-state data (not-loaded / missing / present) as one flat
+ enum, not nested `Option`s or ad-hoc flags. (#4527)
+- **CS-14** `[cfg]` All env access goes through `macro_env_var` / `macro_config` — never
+ `std::env::var`, never hand-rolled wrappers; use `MaybeEnvVar` for optional vars. The
+ same goes for AWS config instantiation (`macro_aws_config`) and tracing subscriber
+ setup (`macro_entrypoint`): use the shared crates.
+ (#4306, #4334, #4380 · enforced: clippy `disallowed-methods` · also: CLAUDE.md)
+- **CS-15** `[cfg]` Fail fast: validate config at service instantiation, not deep inside
+ request handling — a missing env var should kill startup, not a request. (#4077, #4156)
+- **CS-16** `[cfg]` Don't add `.context()` to env-var macro errors — the macro error
+ already statically names the missing variable. (#4156)
+- **CS-17** `[cfg]` Doppler secret key names must exactly match the env var name
+ referenced in code. (#4525)
+- **CS-18** `[cfg]` All new environment variables are plain env vars, not
+ `LocalOrRemote`/doppler-wrapped; non-secret config goes in Doppler as raw values, not
+ AWS Secrets Manager secrets. (#4305, #4525)
+- **CS-19** `[err]` Give third-party errors their own variant — don't collapse e.g. a
+ `jsonwebtoken` failure into a generic internal error. (#4020)
+- **CS-20** `[err]` Depending on a rate-limited external provider requires a fallback
+ (fallback model, retry story, or documented degradation). (#4296)
+- **CS-21** `[err]` Wire usage metering on every invocation path — MCP-triggered tool
+ calls count too, not just the primary path. (#4296)
+- **CS-22** `[err]` Tracing: `#[instrument(err)]` only on `Result` functions; log errors
+ as structured fields (`tracing::error!(error=?e, "msg")`); prefer `.inspect_err` over
+ `if let Err(e)` for logging. (also: CLAUDE.md)
+- **CS-23** `[arch]` Do not grow `macro_db_client` — new domain logic gets a new crate;
+ the catch-all crates must shrink, not accumulate. (#4380)
+- **CS-24** `[arch]` Keep source files under ~1000 lines — split before a reviewer has
+ to ask. (#4364)
+- **CS-25** `[arch]` `mod.rs` declares submodules; it doesn't host logic — move real
+ code into its own module file. (#4175 · enforced: ast-grep
+ `rust-mod-rs-declarations-only`, hint)
+- **CS-26** `[arch]` Reuse before reimplementing — if the logic plausibly exists
+ (service clients, permission checks, oauth utils, the `agent` crate), find it and
+ reuse/extract it instead of writing a second copy. (#3692, #4020, #4380, #4485)
+- **CS-27** `[arch]` Shared domain tables are only touched by their owning crate — e.g.
+ `entity_access` mutations go through `entity_access`/`entity_access_db_utils`, never
+ raw SQL elsewhere. (#3769)
+- **CS-28** `[arch]` Don't extract single-use code into shared crates prematurely, and
+ watch dependency direction: general-purpose crates must not import from specific ones.
+ (#4410)
+- **CS-29** `[arch]` Group proliferating root files (e.g. Dockerfiles) into a dedicated
+ folder. (#4380)
+- **CS-30** `[api]` Axum handlers take shared services via `State`, not `Extension`.
+ (#4556 · enforced: ast-grep `rust-no-axum-extension-param`, warning · also: CLAUDE.md)
+- **CS-31** `[api]` Attach cross-cutting services to the owning domain service, not ad
+ hoc at the router/handler layer — e.g. `EntityAccessManagementService` hangs off the
+ email/document service itself, the way the documents crate does. (#4572)
+- **CS-32** `[api]` New API/soup models mirror the shape of their existing counterpart:
+ omit fields derivable from a nested field, keep lazily-loaded collections lazy,
+ include only fields relevant to the new context. (#4165)
+- **CS-33** `[api]` Trait methods every implementor must consciously declare get no
+ default impl (e.g. schema version) — defaults are for genuine defaults, not escape
+ hatches. (#4276)
+- **CS-34** `[api]` Design generic abstractions to map `T -> U`, not just `T -> T`, when
+ mapping is the point of the abstraction. (#4396)
+- **CS-35** `[api]` Keep sibling endpoints on a resource using the same DTO shape;
+ migrate them together rather than changing one in isolation. (#4386)
+- **CS-36** `[sec]` Permission grants are stateless HTTP endpoints, not channel
+ messages — in-memory channel flows don't survive reconnects. (#4201, #4296)
+- **CS-37** `[sec]` Mint narrowly-scoped tokens instead of forwarding the user's full
+ JWT downstream — least privilege by construction. (#4296)
+- **CS-38** `[sec]` Tool responses must be valid members of the message chain — include
+ `tool_call_id` and required chain metadata. (#4296)
+- **CS-39** `[sec]` Pin third-party GitHub Actions to a commit SHA, not a movable tag.
+ (#4276)
+- **CS-40** `[rust]` Repeated literals become named consts. (#4020)
+- **CS-41** `[rust]` Don't use `#[allow(...)]` — use `#[expect(..., reason = "...")]`
+ on the narrowest item it applies to; `allow` silently rots when the lint stops firing,
+ `expect` warns. (#4396, #4647)
+- **CS-42** `[rust]` Don't re-state trait bounds already implied by a supertrait. (#4276)
+- **CS-43** `[rust]` Use the smallest sufficient integer type — a version counter that
+ can't plausibly pass 255 is a `u8`. (#4396)
+- **CS-44** `[rust]` Large inline strings belong in files — use `include_str!`. (#4156)
+- **CS-45** `[rust]` CLI binaries use `clap`, not hand-rolled arg parsing. (#3678)
+- **CS-46** `[rust]` Use `rootcause` for error handling in new code — it's preferred
+ over `anyhow` these days. In code that's still on anyhow, prefer `bail!` for early
+ error returns. (also: CLAUDE.md)
+- **CS-47** `[perf]` Keep latency-critical services thin: push bytes directly instead of
+ round-tripping through presigned URLs or extra services; dispatch non-blocking
+ background work with `wait_until`. (#3781)
+- **CS-48** `[perf]` Don't do per-message work on hot websocket paths — accumulate and
+ flush on a timer/alarm. (#3961)
+- **CS-49** `[test]` Tests live in a sibling `test.rs`, not inline `#[cfg(test)]` blocks
+ in the implementation file. (#4647 · also: CLAUDE.md)
+- **CS-50** `[test]` Update tests and run `just prepare_db` with any db-crate change.
+ (also: CLAUDE.md)
+
+## Frontend (`js/app`, `js/lexical-core`)
+
+- **FE-01** `[data]` Never call a service client outside the `queries` package — UI code
+ calling an endpoint directly is usually re-fetching data an existing query already
+ caches. (#3750, #3961 · also: AGENTS.md)
+- **FE-02** `[data]` Every query module has a `keys.ts` structured like the existing
+ ones. (#3710)
+- **FE-03** `[data]` Conditional fetching uses a debounced signal passed to TanStack
+ Query's `enabled`, not a custom resource. (#3961)
+- **FE-04** `[data]` Pre-populating data means exposing a cache-seeding method on the
+ query, not an ad hoc manual cache. (#4020)
+- **FE-05** `[data]` Data-dependent UI that must not suspend uses `queryReadyGate`.
+ (#4077)
+- **FE-06** `[data]` Extend `QUERY_FILTERS_BASE` instead of re-deriving filter
+ exclusions per query, and prefer explicit include lists — exclude lists silently break
+ when a new entity type is added. (#3947, #4260)
+- **FE-07** `[data]` Don't hardcode backend-owned config in the frontend (e.g. system
+ bot config) — fetch it dynamically or generate types from the backend source of
+ truth. (#3692)
+- **FE-08** `[solid]` No ad-hoc global state modules — shared state for a subtree lives
+ in a Context scoped to a clear ownership boundary. (#3750 · also: AGENTS.md)
+- **FE-09** `[solid]` Derive, don't sync — an effect that only copies one signal into
+ another similarly-shaped signal should be a derived signal at the appropriate level.
+ (#3898)
+- **FE-10** `[solid]` `createEffect` is for external/imperative systems only (DOM APIs,
+ third-party libs, navigation events) — never for deriving state; use `on()` to make
+ dependencies explicit when an effect is warranted. (#3750, #3898 · also: AGENTS.md)
+- **FE-11** `[solid]` Check `solid-primitives` before writing a custom reactive utility.
+ (also: AGENTS.md)
+- **FE-12** `[async]` `async`/`await` with `try`/`catch`, not `.then()`/`.catch()`
+ chains. (#3716, #3781 · enforced: oxlint `promise/prefer-await-to-then` —
+ `bun run lint:oxlint` from `js/`)
+- **FE-13** `[async]` Extract multi-step async coordination into named helper functions,
+ and make intentionally-unawaited promises explicit — no bare floating promises.
+ (#3781)
+- **FE-14** `[async]` Keep neverthrow `Result`/`ResultAsync` intact end-to-end — use the
+ existing helpers (`ResultAsync`, `throwOnError` in `queryOptions`, `catchToResult`)
+ instead of ad hoc `Promise <-> Result` conversions. (#3781, #4373)
+- **FE-15** `[async]` Guard once, at the top — missing/invalid state gets an early
+ return at the start of the function or hook, not a repeated check in every branch or
+ a silent fall-through. (#3750, #4057)
+- **FE-16** `[arch]` Keep modules single-purpose: feature-specific logic out of generic
+ util files, generic/collaboration logic decoupled from feature specifics, styling out
+ of core business logic. (#3750, #3781, #3947)
+- **FE-17** `[arch]` Reuse existing shared utilities and primitives before hand-rolling
+ (`removeNodeAndRestoreSelection`, Kobalte components) — re-implementations
+ reintroduce bugs that were already fixed. (#4281, #4321 · also: AGENTS.md)
+- **FE-18** `[arch]` Within a package, use relative imports — don't route through the
+ package's own barrel file; it adds indirection and invites circular dependencies.
+ (#3692)
+- **FE-19** `[ts]` Trust `match` narrowing — an exhaustive `ts-pattern` match already
+ narrows the type inside each closure; a manual `Extract<>` alias is redundant. (#4201)
+- **FE-20** `[ts]` Exhaustive branching uses `match` from `ts-pattern`. (also: AGENTS.md)
+- **FE-21** `[ts]` No `any` — proper types or `unknown` + type guards. (also: AGENTS.md)
+- **FE-22** `[ui]` Pending or permission-gated actions render as a dimmed version of the
+ real UI with inline accept/reject controls — not a generic placeholder icon. (#4201)
+- **FE-23** `[ui]` Disclosure carets rotate 180° to point down when expanded, matching
+ Discussion, SplitFileMenu, CollapsibleMessage, etc. (#4582)
+- **FE-24** `[ui]` Truncated/collapsed controls get a tooltip (matching the app's
+ tooltip pattern) so the lost label stays discoverable. (#4492)
+- **FE-25** `[ui]` Semantic color tokens, not raw Tailwind palette classes — the default
+ palette is disabled via `--color-*: initial` in `js/app/packages/app/index.css`, so
+ classes like `text-red-500` silently render nothing. (enforced: ast-grep
+ `tsx-no-raw-tailwind-palette`, CI error · also: AGENTS.md)
+- **FE-26** `[ui]` Prefer composition over configurability; keep reusable components
+ small and free of queries/complex state. (also: AGENTS.md)
+- **FE-27** `[ui]` Don't add `cursor-pointer` to clickable elements. (enforced: ast-grep
+ `tsx-no-cursor-pointer`, warning · also: AGENTS.md)
diff --git a/js/app/.oxlintrc.json b/js/app/.oxlintrc.json
new file mode 100644
index 0000000000..4e19075404
--- /dev/null
+++ b/js/app/.oxlintrc.json
@@ -0,0 +1,25 @@
+{
+ // oxlint runs ALONGSIDE Biome, scoped to rules Biome cannot express.
+ // Enforces FE-12 (and eventually FE-13) from STYLE_GUIDE.md.
+ //
+ // Run: bun run lint:oxlint (from js/), or `bunx oxlint` from js/app.
+ //
+ // typescript/no-floating-promises additionally needs type information:
+ // install `bun add -d oxlint oxlint-tsgolint` and run `oxlint --type-aware`
+ // (requires access to the repo's private git dependencies to update the
+ // lockfile, so it is not wired up yet).
+ "plugins": ["promise"],
+ "categories": {
+ "correctness": "off"
+ },
+ "rules": {
+ "promise/prefer-await-to-then": "warn"
+ },
+ "ignorePatterns": [
+ "**/node_modules/**",
+ "**/dist/**",
+ "**/generated/**",
+ "**/*.gen.ts",
+ "**/patches/**"
+ ]
+}
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index 488fa92eed..30f1291d6b 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -755,7 +755,7 @@ const SidebarSettingsWidget = (props: SidebarSettingsWidgetProps) => {
/>
</Dropdown.Item>
<Dropdown.Item
- class="flex items-center gap-2 px-2.5 py-2 text-sm cursor-default outline-none text-red-500"
+ class="flex items-center gap-2 px-2.5 py-2 text-sm cursor-default outline-none text-failure"
onSelect={() => logout()}
>
<span class="size-5 flex items-center justify-center">
diff --git a/js/app/packages/app/component/auth/Shared.tsx b/js/app/packages/app/component/auth/Shared.tsx
index 3922ff2cdd..c5949590f6 100644
--- a/js/app/packages/app/component/auth/Shared.tsx
+++ b/js/app/packages/app/component/auth/Shared.tsx
@@ -64,7 +64,7 @@ export function Input(props: {
export function ErrorMsg(props: { msg?: string }) {
return (
<Show when={props.msg}>
- <div class="grid items-center justify-center p-4 border-b border-edge-muted text-sm text-red-500">
+ <div class="grid items-center justify-center p-4 border-b border-edge-muted text-sm text-failure">
{props.msg}
</div>
</Show>
diff --git a/js/app/packages/channel/Media/MediaViewerDialog.tsx b/js/app/packages/channel/Media/MediaViewerDialog.tsx
index 44b66f4c6b..35fba61dc1 100644
--- a/js/app/packages/channel/Media/MediaViewerDialog.tsx
+++ b/js/app/packages/channel/Media/MediaViewerDialog.tsx
@@ -119,7 +119,7 @@ function VideoViewerContent(props: {
<div class="flex size-full items-center justify-center">
<video
- class="max-h-[80vh] max-w-[90vw] rounded-2xl bg-black"
+ class="max-h-[80vh] max-w-[90vw] rounded-2xl bg-[black]"
controls
autoplay
playsinline
diff --git a/js/app/packages/core/component/AI/component/debug/HttpStream.tsx b/js/app/packages/core/component/AI/component/debug/HttpStream.tsx
index 524c9a1e6d..6ddeeaf5ee 100644
--- a/js/app/packages/core/component/AI/component/debug/HttpStream.tsx
+++ b/js/app/packages/core/component/AI/component/debug/HttpStream.tsx
@@ -141,8 +141,8 @@ export default function HttpStreamDebug() {
class={cn(
'text-sm px-2 py-1 rounded',
connectionState() === WebsocketConnectionState.Open
- ? 'bg-green-100 text-green-800'
- : 'bg-red-100 text-red-800'
+ ? 'bg-success-bg text-success-ink'
+ : 'bg-failure-bg text-failure-ink'
)}
>
{connectionState() === WebsocketConnectionState.Open
@@ -202,7 +202,7 @@ export default function HttpStreamDebug() {
{/* Error */}
<Show when={error()}>
- <div class="text-sm p-2 bg-red-100 text-red-800 rounded">
+ <div class="text-sm p-2 bg-failure-bg text-failure-ink rounded">
{error()}
</div>
</Show>
@@ -214,7 +214,7 @@ export default function HttpStreamDebug() {
<div class="flex items-center justify-between">
<span class="text-sm font-medium">Response</span>
<Show when={isStreaming()}>
- <span class="text-sm text-blue-600 animate-pulse">
+ <span class="text-sm text-accent animate-pulse">
Streaming...
</span>
</Show>
@@ -223,7 +223,7 @@ export default function HttpStreamDebug() {
<Show
when={responseText()}
fallback={
- <div class="p-4 text-center text-sm text-gray-500">
+ <div class="p-4 text-center text-sm text-ink-muted">
No response yet. Send a message to start streaming.
</div>
}
@@ -242,7 +242,7 @@ export default function HttpStreamDebug() {
Chunks ({chunks().length})
</span>
<Show when={isStreaming()}>
- <span class="text-sm text-blue-600 animate-pulse">
+ <span class="text-sm text-accent animate-pulse">
Receiving...
</span>
</Show>
@@ -251,7 +251,7 @@ export default function HttpStreamDebug() {
<Show
when={chunks().length > 0}
fallback={
- <div class="p-4 text-center text-sm text-gray-500">
+ <div class="p-4 text-center text-sm text-ink-muted">
No chunks yet. Send a message to start streaming.
</div>
}
@@ -259,7 +259,7 @@ export default function HttpStreamDebug() {
<For each={chunks()}>
{(chunk) => (
<div class="p-3 border-b border-edge last:border-b-0">
- <div class="text-xs text-gray-500 mb-1">
+ <div class="text-xs text-ink-muted mb-1">
{chunk.timestamp.toLocaleTimeString()}
</div>
<pre class="text-xs font-mono whitespace-pre-wrap break-all">
diff --git a/js/app/packages/notifications/components/Playground.tsx b/js/app/packages/notifications/components/Playground.tsx
index 0f23fa871b..68bcd5e87d 100644
--- a/js/app/packages/notifications/components/Playground.tsx
+++ b/js/app/packages/notifications/components/Playground.tsx
@@ -77,14 +77,14 @@ function TypeButton(props: {
<div class="flex flex-col gap-1 flex-1 min-w-0">
<span
class={`text-xs font-mono uppercase font-medium ${
- props.isSelected ? 'text-black' : 'text-accent'
+ props.isSelected ? 'text-[black]' : 'text-accent'
}`}
>
{label}
</span>
<span
class={`text-xs font-mono truncate ${
- props.isSelected ? 'text-black/70' : 'text-ink-muted'
+ props.isSelected ? 'text-[black]/70' : 'text-ink-muted'
}`}
>
{props.type}
@@ -92,7 +92,7 @@ function TypeButton(props: {
</div>
<span
class={`text-sm font-medium shrink-0 ${
- props.isSelected ? 'text-black' : 'text-ink-muted'
+ props.isSelected ? 'text-[black]' : 'text-ink-muted'
}`}
>
{props.count}
@@ -641,12 +641,12 @@ function PlaygroundContent() {
>
<div class="flex items-center justify-between">
<span
- class={`text-sm font-medium ${customMode() ? 'text-black' : 'text-accent'}`}
+ class={`text-sm font-medium ${customMode() ? 'text-[black]' : 'text-accent'}`}
>
Custom Message Test
</span>
<span
- class={`text-xs ${customMode() ? 'text-black/70' : 'text-ink-muted'}`}
+ class={`text-xs ${customMode() ? 'text-[black]/70' : 'text-ink-muted'}`}
>
Builder
</span>
@@ -766,7 +766,7 @@ export const BrowserNotificationPreview: Component<NotificationProps> = (
{/* Content */}
<div class="flex-1 min-w-0">
- <div class="text-white font-medium text-sm mb-1 truncate">
+ <div class="text-[white] font-medium text-sm mb-1 truncate">
{props.title}
</div>
<div class="text-[oklch(0.707_0.022_261.325)] text-sm line-clamp-2">
diff --git a/js/app/packages/theme/components/ColorPickerPopover.tsx b/js/app/packages/theme/components/ColorPickerPopover.tsx
index d09b05d000..4c8dbc7dac 100644
--- a/js/app/packages/theme/components/ColorPickerPopover.tsx
+++ b/js/app/packages/theme/components/ColorPickerPopover.tsx
@@ -18,7 +18,7 @@ import { ColorSwatch } from './ColorSwatch';
const CHROMA_MAX = 0.37;
const RING =
- 'pointer-events-none absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_1px_3px_oklch(0_0_0/0.4)]';
+ 'pointer-events-none absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-[white] shadow-[0_1px_3px_oklch(0_0_0/0.4)]';
/** 2D field: chroma on X (0 → max), lightness on Y (top = light). Drag sets both. */
function ColorField(props: {
@@ -104,7 +104,7 @@ function HueSlider(props: { h: () => number; onH: (n: number) => void }) {
{/* Kobalte positions the thumb on the main (vertical) axis via `bottom` +
its own transform; we only center it horizontally and paint it. */}
<Slider.Thumb
- class="absolute left-1/2 -ml-[7px] size-3.5 rounded-full border-2 border-white shadow-[0_1px_3px_oklch(0_0_0/0.4)] outline-none"
+ class="absolute left-1/2 -ml-[7px] size-3.5 rounded-full border-2 border-[white] shadow-[0_1px_3px_oklch(0_0_0/0.4)] outline-none"
style={{ 'background-color': `oklch(0.7 0.2 ${props.h()}deg)` }}
>
<Slider.Input />
diff --git a/js/app/packages/ui/components/Checkbox.tsx b/js/app/packages/ui/components/Checkbox.tsx
index d2084882a9..a0b83f74fa 100644
--- a/js/app/packages/ui/components/Checkbox.tsx
+++ b/js/app/packages/ui/components/Checkbox.tsx
@@ -30,7 +30,7 @@ const CONTROL_CLASS = cn(
'data-checked:bg-accent data-checked:border-accent',
'data-indeterminate:bg-accent data-indeterminate:border-accent',
'data-disabled:opacity-50 data-disabled:cursor-not-allowed',
- 'data-invalid:border-red-500'
+ 'data-invalid:border-failure'
);
function CheckboxIndicator(props: IndicatorProps) {
diff --git a/js/package.json b/js/package.json
index 4071ff4656..cfa350e154 100644
--- a/js/package.json
+++ b/js/package.json
@@ -62,6 +62,7 @@
"lint:ci": "cd app && bunx --bun @biomejs/biome ci --changed --no-errors-on-unmatched --error-on-warnings",
"check": "cd app && tsc --noEmit --skipLibCheck --project packages/app/tsconfig.json",
"lint": "cd app && bunx --bun @biomejs/biome lint --skip=suspicious/noImportCycles",
+ "lint:oxlint": "cd app && bunx --yes [email protected]",
"format": "cd app && bunx --bun @biomejs/biome format --write"
},
"trustedDependencies": [
diff --git a/just/check.just b/just/check.just
new file mode 100644
index 0000000000..5ec219125a
--- /dev/null
+++ b/just/check.just
@@ -0,0 +1,72 @@
+# Single local quality gate: format + lint + code rules, scoped to files you
+# changed vs origin/main (merge-base, plus uncommitted and untracked work) so
+# the output is exactly what is wrong with YOUR changes — legacy findings in
+# untouched files never appear. Findings print as file:line with the rule id;
+# ast-grep rule ids map to STYLE_GUIDE.md (its `severity: error` rules fail
+# the run, warnings/hints only print; oxlint is warn-only for now).
+#
+# just check fast: rustfmt + biome + oxlint + ast-grep (~seconds)
+# just check full also runs tsc + clippy (~minutes)
+#
+# Override the diff base with CHECK_BASE=<ref> (useful in shallow clones,
+# where no origin/main merge-base exists and the scope silently narrows to
+# uncommitted work only).
+check *ARGS:
+ #!/usr/bin/env bash
+ set -uo pipefail
+ cd {{ justfile_directory() }}
+
+ base="${CHECK_BASE:-$(git merge-base HEAD origin/main 2>/dev/null || true)}"
+ if [ -z "$base" ]; then
+ echo "note: no merge-base with origin/main (shallow clone?); checking uncommitted changes only."
+ echo " Set CHECK_BASE=<ref> to widen."
+ fi
+ changed=$({ [ -n "$base" ] && git diff --name-only "$base"; \
+ git diff --name-only HEAD; \
+ git ls-files --others --exclude-standard; } | sort -u \
+ | while IFS= read -r f; do [ -f "$f" ] && printf '%s\n' "$f"; done)
+ if [ -z "$changed" ]; then echo "no changed files — nothing to check"; exit 0; fi
+
+ rs_cs=$(grep -E '^rust/cloud-storage/.*\.rs$' <<<"$changed" || true)
+ rs_sync=$(grep -E '^rust/sync-service/.*\.rs$' <<<"$changed" || true)
+ js=$(grep -E '^js/app/.*\.(ts|tsx)$' <<<"$changed" || true)
+ sg=$(grep -E '^(rust|js)/.*\.(rs|ts|tsx)$' <<<"$changed" || true)
+
+ fail=0
+ if [ -n "$rs_cs" ]; then
+ echo "── cargo fmt (rust/cloud-storage)"
+ (cd rust/cloud-storage && cargo fmt --check) \
+ || { echo " fix: cd rust/cloud-storage && cargo fmt"; fail=1; }
+ fi
+ if [ -n "$rs_sync" ]; then
+ echo "── cargo fmt (rust/sync-service)"
+ (cd rust/sync-service && cargo fmt --check) \
+ || { echo " fix: cd rust/sync-service && cargo fmt"; fail=1; }
+ fi
+ if [ -n "$js" ]; then
+ echo "── biome (js/app format + lint, same flags as CI)"
+ (cd js/app && bunx --bun @biomejs/biome ci --colors=off --no-errors-on-unmatched \
+ --error-on-warnings $(sed 's|^js/app/||' <<<"$js")) \
+ || { echo " fix: cd js && bun run fix, then re-check"; fail=1; }
+ echo "── oxlint (warn-only; STYLE_GUIDE.md FE-12)"
+ (cd js/app && bunx --yes [email protected] $(sed 's|^js/app/||' <<<"$js")) || fail=1
+ fi
+ if [ -n "$sg" ]; then
+ echo "── ast-grep code rules (rule ids map to STYLE_GUIDE.md)"
+ bunx --yes @ast-grep/[email protected] scan --report-style=short $sg || fail=1
+ fi
+ if [ "{{ ARGS }}" = "full" ]; then
+ if [ -n "$js" ]; then
+ echo "── tsc (js/app)"
+ (cd js && bun run check) || fail=1
+ fi
+ if [ -n "$rs_cs" ]; then
+ echo "── clippy (rust/cloud-storage)"
+ (cd rust/cloud-storage && RUSTFLAGS="-Dwarnings -Dclippy::disallowed_methods" \
+ RUSTDOCFLAGS=-Dwarnings SQLX_OFFLINE=true cargo clippy --workspace --all-features) || fail=1
+ fi
+ fi
+
+ echo
+ if [ "$fail" -ne 0 ]; then echo "FAIL"; exit 1; fi
+ echo "OK"
diff --git a/justfile b/justfile
index 2f5032bd05..cb0d952d81 100644
--- a/justfile
+++ b/justfile
@@ -134,6 +134,7 @@ stop-databases:
# Import LocalStack recipes
import 'local_stack.just'
import 'just/xtask.just'
+import 'just/check.just'
# Sets up local database
setup_local_dbs:
diff --git a/rules/ast-grep/rust-mod-rs-declarations-only.yml b/rules/ast-grep/rust-mod-rs-declarations-only.yml
new file mode 100644
index 0000000000..831766fcb1
--- /dev/null
+++ b/rules/ast-grep/rust-mod-rs-declarations-only.yml
@@ -0,0 +1,22 @@
+id: rust-mod-rs-declarations-only
+language: rust
+severity: hint
+message: mod.rs should only declare submodules and re-exports; move logic into its own module file.
+note: |-
+ Rule CS-25 in STYLE_GUIDE.md, mined from PR #4175.
+ Define functions, types, and impls in a named module file and re-export
+ from mod.rs if needed. lib.rs is deliberately exempt: a small crate
+ living entirely in lib.rs is fine.
+ Aspirational: ~246 existing mod.rs files violate this; apply it to new
+ modules and to mod.rs files you are already refactoring.
+files:
+ - rust/**/mod.rs
+rule:
+ any:
+ - kind: function_item
+ - kind: struct_item
+ - kind: enum_item
+ - kind: trait_item
+ - kind: impl_item
+ inside:
+ kind: source_file
diff --git a/rules/ast-grep/rust-no-axum-extension-param.yml b/rules/ast-grep/rust-no-axum-extension-param.yml
new file mode 100644
index 0000000000..1c55d20cb6
--- /dev/null
+++ b/rules/ast-grep/rust-no-axum-extension-param.yml
@@ -0,0 +1,17 @@
+id: rust-no-axum-extension-param
+language: rust
+severity: warning
+message: Axum handlers should take shared services via State, not Extension.
+note: |-
+ Rule CS-30 in STYLE_GUIDE.md. Recent reviews enforce
+ State for shared services (PR #4556); attach cross-cutting services to the
+ owning domain service rather than wiring them at the router layer (CS-31,
+ PR #4572). ~200 legacy uses exist — don't add new ones.
+files:
+ - rust/**
+rule:
+ kind: parameter
+ has:
+ field: type
+ kind: generic_type
+ regex: ^(axum::(extract::)?)?Extension<
diff --git a/rules/ast-grep/tsx-no-cursor-pointer.yml b/rules/ast-grep/tsx-no-cursor-pointer.yml
new file mode 100644
index 0000000000..1a64fcb544
--- /dev/null
+++ b/rules/ast-grep/tsx-no-cursor-pointer.yml
@@ -0,0 +1,12 @@
+id: tsx-no-cursor-pointer
+language: tsx
+severity: warning
+message: Don't add cursor-pointer to clickable elements.
+note: |-
+ Rule FE-27 in STYLE_GUIDE.md (also js/app/AGENTS.md, Styling). The
+ app deliberately does not use pointer cursors on clickable elements.
+files:
+ - js/app/**
+rule:
+ kind: string_fragment
+ regex: (^|[^-\w])cursor-pointer([^-\w]|$)
diff --git a/rules/ast-grep/tsx-no-raw-tailwind-palette.yml b/rules/ast-grep/tsx-no-raw-tailwind-palette.yml
new file mode 100644
index 0000000000..368d550144
--- /dev/null
+++ b/rules/ast-grep/tsx-no-raw-tailwind-palette.yml
@@ -0,0 +1,15 @@
+id: tsx-no-raw-tailwind-palette
+language: tsx
+severity: error
+message: Raw Tailwind palette classes are disabled in @theme and render NOTHING. Use semantic color tokens.
+note: |-
+ Rule FE-25 in STYLE_GUIDE.md. The default palette is reset via
+ `--color-*: initial` in js/app/packages/app/index.css, so classes like
+ `text-red-500` silently produce no CSS. Use semantic tokens instead:
+ failure/failure-bg/failure-ink, success-*, alert-*, accent, ink-muted, etc.
+files:
+ - js/app/**
+ - js/lexical-core/**
+rule:
+ kind: string_fragment
+ regex: (^|[^-\w])(bg|text|border|ring|fill|stroke|from|to|via|outline|decoration|divide|caret|accent|shadow)-((red|blue|green|gray|grey|zinc|slate|neutral|stone|amber|yellow|lime|emerald|teal|cyan|sky|indigo|violet|purple|fuchsia|pink|rose)-[0-9]{2,3}|black|white)([^-\w]|$)
diff --git a/rust/cloud-storage/CLAUDE.md b/rust/cloud-storage/CLAUDE.md
index 40ac5090ce..bbacf6d8f1 100644
--- a/rust/cloud-storage/CLAUDE.md
+++ b/rust/cloud-storage/CLAUDE.md
@@ -228,7 +228,7 @@ mentioning other documents).
2. **Incremental Testing**: Run tests frequently to catch issues early
3. **Fixture Management**: Update test fixtures when changing table structures
4. **SQLX Workflow**: Schema changes require migration → prepare → test cycle
-5. **Axum Patterns**: Use Extension instead of State for handlers in this codebase
+5. **Axum Patterns**: Handlers take shared services via `State`, not `Extension` (see STYLE_GUIDE.md CS-30; this case study predates that convention)
### Index Strategy
@@ -251,8 +251,8 @@ The migration included comprehensive indexes:
### Rust Error Handling
-- Prefer `anyhow::bail!("error message")` over `Err(anyhow::anyhow!("error message"))`
-- Use `bail!` for early returns with errors - it's more concise and idiomatic
+- New code uses `rootcause` for error handling — it's preferred over `anyhow` (see STYLE_GUIDE.md CS-46)
+- In code still on anyhow: prefer `anyhow::bail!("error message")` over `Err(anyhow::anyhow!("error message"))` for early returns - it's more concise and idiomatic
### Documentation Requirements
diff --git a/rust/cloud-storage/tools/xtask/crates/xtask_local/Cargo.toml b/rust/cloud-storage/tools/xtask/crates/xtask_local/Cargo.toml
index d57830f923..2f057cc161 100644
--- a/rust/cloud-storage/tools/xtask/crates/xtask_local/Cargo.toml
+++ b/rust/cloud-storage/tools/xtask/crates/xtask_local/Cargo.toml
@@ -33,9 +33,9 @@ rdkafka = { workspace = true, optional = true }
# Docker Engine API client for the discrete container/image ops.
bollard = "0.21"
console = "0.15"
+indicatif = "0.18"
docker-compose-types = { version = "0.24", features = ["indexmap"] }
indexmap = { workspace = true }
-indicatif = "0.18"
serde_yaml = { workspace = true }
# Parse user-provided `--env-file` overlays. EnumIter derives the port list.
dotenvy = { workspace = true }
diff --git a/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs b/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs
new file mode 100644
index 0000000000..3cf7341989
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs
@@ -0,0 +1,120 @@
+//! `conventions code check` — repo convention lints, generated into
+//! `code_check_conventions.yml`.
+//!
+//! Runs `ast-grep scan` over the custom structural rules in `rules/ast-grep`
+//! (config: `sgconfig.yml` at the repo root). The scan fails only on
+//! `severity: error` findings; `warning`/`hint` rules surface through
+//! CodeRabbit's ast-grep integration on changed code instead. The rules encode
+//! conventions from `STYLE_GUIDE.md` at the repo root.
+
+use gh_workflow::{
+ Concurrency, Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run,
+ Step, Use, Workflow,
+};
+
+use crate::workflows::{runners, steps, vars};
+
+/// ast-grep is fetched with bunx, so this shares the `web-ci` bun cache volume
+/// the way the infra checks do.
+fn conventions_runner() -> String {
+ runners::Runner::Small.with_cache_tag(vars::WEB_CI_CACHE_TAG)
+}
+
+/// Build the workflow.
+pub fn code_check_conventions() -> Workflow {
+ Workflow::new("conventions code check")
+ // Read-only: the workflow only checks out code and runs a scan.
+ .permissions(Permissions {
+ contents: Some(Level::Read),
+ ..Default::default()
+ })
+ .on(Event::default().pull_request(
+ PullRequest::default()
+ .add_branch("main")
+ .add_type(PullRequestType::Opened)
+ .add_type(PullRequestType::Synchronize)
+ .add_type(PullRequestType::Reopened)
+ .add_type(PullRequestType::ReadyForReview),
+ ))
+ .concurrency(
+ Concurrency::new(Expression::new("code-check-conventions-${{ github.ref }}"))
+ .cancel_in_progress(true),
+ )
+ .add_job("path-check", path_check())
+ .add_job("ast-grep", ast_grep())
+ .add_job("status-check", status_check())
+}
+
+fn path_check() -> Job {
+ Job::default()
+ .runs_on(runners::Runner::Small.to_string())
+ .add_output("should_run", "${{ steps.filter.outputs.should_run }}")
+ .add_step(steps::checkout(false, false))
+ .add_step(paths_filter())
+}
+
+fn ast_grep() -> Job {
+ steps::gated_job()
+ .name("ast-grep Conventions")
+ .runs_on(conventions_runner())
+ .add_step(steps::checkout(false, false))
+ .add_step(steps::mount_web_cache_volume(false))
+ .add_step(steps::setup_nix())
+ .add_step(steps::setup_dev_shell())
+ .add_step(run_ast_grep())
+}
+
+/// Always-run collector used as the required status check. Its name must stay
+/// stable because branch protection references it.
+fn status_check() -> Job {
+ Job::default()
+ .name("Conventions Status Check")
+ .cond(Expression::new("always()"))
+ .needs(vec!["path-check".to_string(), "ast-grep".to_string()])
+ .runs_on(runners::Runner::Small.to_string())
+ .add_step(check_job_results())
+}
+
+fn paths_filter() -> Step<Use> {
+ Step::new("Filter changed paths")
+ .uses(
+ "dorny",
+ "paths-filter",
+ "d1c1ffe0248fe513906c8e24db8ea791d46f8590",
+ ) // v3.0.3
+ .id("filter")
+ .add_with((
+ "filters",
+ indoc::indoc! {r#"
+ should_run:
+ - 'rust/**'
+ - 'js/app/**'
+ - 'js/lexical-core/**'
+ - 'rules/**'
+ - 'sgconfig.yml'
+ - '.github/workflows/code_check_conventions.yml'
+ "#},
+ ))
+}
+
+fn run_ast_grep() -> Step<Run> {
+ Step::new("Run ast-grep").run("bunx --yes @ast-grep/[email protected] scan")
+}
+
+fn check_job_results() -> Step<Run> {
+ Step::new("Check job results").run(indoc::indoc! {r#"
+ echo "path-check: ${{ needs.path-check.result }}"
+ echo "ast-grep: ${{ needs.ast-grep.result }}"
+
+ # Fail if any job failed, or ast-grep was cancelled (skipped and
+ # success are both OK; cancelled means it started and didn't finish)
+ if [[ "${{ needs.path-check.result }}" == "failure" ]] || \
+ [[ "${{ needs.ast-grep.result }}" == "failure" ]] || \
+ [[ "${{ needs.ast-grep.result }}" == "cancelled" ]]; then
+ echo "❌ One or more jobs failed"
+ exit 1
+ fi
+
+ echo "✅ All jobs passed or were skipped"
+ "#})
+}
diff --git a/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/mod.rs b/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/mod.rs
index 87629de3d3..0e3edf7755 100644
--- a/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/mod.rs
+++ b/rust/cloud-storage/tools/xtask/crates/xtask_workflows/src/workflows/mod.rs
@@ -21,6 +21,7 @@ mod check_generated;
mod check_node_modules_nix;
mod cleanup_preview;
mod code_check_cloud_storage;
+mod code_check_conventions;
mod code_check_infra;
mod deploy_ai_editing_worker;
mod deploy_preview;
@@ -149,6 +150,11 @@ const WORKFLOWS: &[WorkflowFile] = &[
file_name: "code_check_cloud_storage.yml",
render_yaml: || render_gh_workflow(code_check_cloud_storage::code_check_cloud_storage)(),
},
+ WorkflowFile {
+ slug: "code_check_conventions",
+ file_name: "code_check_conventions.yml",
+ render_yaml: || render_gh_workflow(code_check_conventions::code_check_conventions)(),
+ },
WorkflowFile {
slug: "deploy_ai_editing_worker",
file_name: "deploy_ai_editing_worker.yml",
diff --git a/sgconfig.yml b/sgconfig.yml
new file mode 100644
index 0000000000..dbe0a16bf5
--- /dev/null
+++ b/sgconfig.yml
@@ -0,0 +1,13 @@
+# ast-grep configuration — custom structural rules for repo conventions.
+#
+# These rules are consumed identically by:
+# - CI (ast-grep scan)
+# - local runs (bunx @ast-grep/cli scan)
+# - CodeRabbit (reviews.tools.ast-grep.rule_dirs in .coderabbit.yaml)
+#
+# Rules encode conventions from STYLE_GUIDE.md (repo root). severity: error
+# rules are CI-blocking (zero existing violations); severity: warning rules
+# surface on changed code via CodeRabbit without failing CI while existing
+# violations are burned down.
+ruleDirs:
+ - rules/ast-grep