Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions .agents/skills/verify-suni/scripts/verify-suni.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ MAILPIT="http://localhost:8025"

die() { echo "verify-suni: $*" >&2; exit 1; }
ab() { agent-browser --session "$SESSION" "$@"; }
web_url() { pnpm --silent --dir "$ROOT" exec portless get suni; }
api_url() { pnpm --silent --dir "$ROOT" exec portless get api.suni; }
web_url() { app_url suni; }
api_url() { app_url api.suni; }
root_pid() { [[ -f "$STATE/pid" ]] && cat "$STATE/pid"; }
alive() { local p; p="$(root_pid)" && kill -0 "$p" 2>/dev/null; }
# Turbo and bun start their own process groups, so ownership is the process tree under our pnpm.
Expand All @@ -24,10 +24,30 @@ owns() { [[ -n "$1" ]] && alive && tree "$(root_pid)" | grep -qx "$1"; }
run_id() { cat "$STATE/run_id" 2>/dev/null || die "no run started; run: $0 up"; }
evidence_dir() { echo "$BASE/evidence/$(run_id)"; }

route_pid() {
local host="${1#https://}"
# "<url> <pid>" for every portless route whose process runs `portless <app>`.
# Matched by command, not URL: from a worktree, `portless get` adds a prefix the dev servers may not use.
app_routes() {
local url pid
pnpm --silent --dir "$ROOT" exec portless list 2>/dev/null |
awk -v h="$host" '$1 == "https://" h { gsub(/[()]/, "", $NF); print $NF }'
awk '$2 == "->" { gsub(/[()]/, "", $NF); print $1, $NF }' |
while read -r url pid; do
ps -ww -o command= -p "$pid" 2>/dev/null | grep -q "portless[^ ]* $1 " && echo "$url $pid"
done
}
# The URL our run serves <app> on; before launch, the URL portless would assign.
app_url() {
local url pid
while read -r url pid; do
owns "$pid" && { echo "$url"; return; }
done < <(app_routes "$1")
pnpm --silent --dir "$ROOT" exec portless get "$1"
}
# A pid serving <app> that this run did not start, on any URL.
foreign_pid() {
local url pid
while read -r url pid; do
owns "$pid" || { echo "$pid"; return; }
done < <(app_routes "$1")
}

ready() {
Expand All @@ -41,8 +61,8 @@ cmd_up() {
return
fi
local foreign
foreign="$(route_pid "$(web_url)")"
[[ -z "$foreign" ]] || die "$(web_url) is served by pid $foreign, which this run did not start. Stop it or verify against it by hand; never double-drive it."
foreign="$(foreign_pid suni)"
[[ -z "$foreign" ]] || die "the Suni web app is served by pid $foreign, which this run did not start. Stop it or verify against it by hand; never double-drive it."

command -v agent-browser >/dev/null || die "agent-browser missing: npm i -g agent-browser && agent-browser install"
mkdir -p "$STATE"
Expand Down Expand Up @@ -87,8 +107,8 @@ cmd_doctor() {
local fail=0
check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fail=1; fi; }
check "dev server started by this run is alive (pid $(root_pid || echo none))" alive
check "web route $(web_url) is served by our process tree" 'owns "$(route_pid "$(web_url)")"'
check "api route $(api_url) is served by our process tree" 'owns "$(route_pid "$(api_url)")"'
check "web route $(web_url) is served by our process tree" '[[ -z "$(foreign_pid suni)" ]] && [[ -n "$(app_routes suni)" ]]'
check "api route $(api_url) is served by our process tree" '[[ -z "$(foreign_pid api.suni)" ]] && [[ -n "$(app_routes api.suni)" ]]'
check "web answers and api /api/auth/ok answers" ready
check "postgres and mailpit containers are healthy" \
'[[ "$(docker inspect -f "{{.State.Health.Status}}" suni-dev-postgres-1 suni-dev-mailpit-1 2>/dev/null | sort -u)" == "healthy" ]]'
Expand Down
14 changes: 14 additions & 0 deletions .coderabbit.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ const SOURCE_FILES = "{apps,packages}/**/*.{ts,tsx}";

const REACT_FILES = "{apps/web,packages/ui}/src/**/*.tsx";

const API_ROUTERS = "packages/api/src/routers/**/*.ts";

const WEB_COMPONENTS = "apps/web/src/**/*.tsx";

export default defineConfig({
reviews: {
high_level_summary: false,
Expand Down Expand Up @@ -33,6 +37,16 @@ export default defineConfig({
instructions:
"Hold changed code to the rules in docs/agents/react-accessibility.md.",
},
{
path: API_ROUTERS,
instructions:
"A mutation on a child entity (branch, contact) must check, in the same `UPDATE ... WHERE`, that neither it nor its parents are archived. State changes are one atomic `UPDATE ... WHERE ... RETURNING`, not a read followed by a write. Fields only admins may see are removed in the query, not hidden in the UI.",
},
{
path: WEB_COMPONENTS,
instructions:
"UI copy and accessibility text (`aria-label`, `sr-only`, `title`) must be in Spanish. A flex container that holds a wide table needs `min-w-0`. When a dialog's trigger can disappear on close, set `finalFocus`.",
},
],
},
knowledge_base: {
Expand Down
17 changes: 16 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm run check

type-aware-lint:
name: Type-aware lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm run check:type-aware

check-types:
name: Check types
runs-on: ubuntu-latest
Expand Down Expand Up @@ -102,7 +117,7 @@ jobs:
check:
name: Check
if: always()
needs: [lint-format, check-types, build, knip, migrations]
needs: [lint-format, type-aware-lint, check-types, build, knip, migrations]
runs-on: ubuntu-latest
steps:
# Single required check for branch protection: fails unless every job succeeded.
Expand Down
25 changes: 21 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
Suni manufactures cleaning and sanitation products for homes and businesses. This repo is Suni's internal operations system: inventory, orders, production, and related operations. The public company landing page will be added here later.

- Users are staff from four areas: administration, production (plant), warehouse, and sales.
- Access will be role-based, so each area sees only its own part of the system. The per-area role system is not built yet. Today Better Auth's admin plugin gives each user the `user` or `admin` role: `protectedProcedure` checks for a session and `adminProcedure` also requires `admin`. Until per-area roles exist, ask how a new route or procedure should be scoped instead of adding ad hoc role checks.
- The domain modules are not built yet; today the code is the scaffold, auth, and admin user management.
- Access will be role-based, so each area sees only its own part of the system. The per-area role system is not built yet. Today Better Auth's admin plugin gives each user the `user` or `admin` role: `protectedProcedure` checks for a session, `scopedProcedure` adds `context.userId` and `context.admin` for handlers that branch on the role, and `adminProcedure` also requires `admin`. Non-admin sellers reach only their own customers and branches and the contacts under them. Until per-area roles exist, ask how a new route or procedure should be scoped instead of adding ad hoc role checks.
- Built so far: auth, admin user management, and the sales modules for customers, their branches, and their contacts.

This is a TypeScript monorepo with a React/Vite web app, a Hono/oRPC server, and shared UI, API, auth, and database packages.

Expand Down Expand Up @@ -51,14 +51,31 @@ A change is not done until it reaches every surface it touches. Before calling w

- Drizzle table and enums.
- Zod validation in `@suni/db/validation/*`, shared by the API and the form.
- oRPC procedure and its access scoping (`protectedProcedure` or `adminProcedure`, per the role note above).
- Hook with query invalidation.
- oRPC procedure and its access scoping (`protectedProcedure`, `scopedProcedure`, or `adminProcedure`, per the role note above).
- Hook in `apps/web/src/hooks/`. Every successful mutation refreshes all oRPC queries (see `apps/web/src/utils/orpc.ts`), so hooks never list query keys.
- Route with loading, empty and error states.
- Reverse actions: archive needs unarchive, and a way in needs a way out and a way to see it.
- Nav items and actions hidden from users who cannot use them.
- Migration or `.env.schema` change needed? The user generates migrations, never you.
- Docs, only if existing guidance became inaccurate.

## Rules and what enforces them

When the operator corrects a repeated mistake, fix it and add a row here. If the rule was already here with no enforcer, that is a repeat: enforce it in the same change. Drop a row once its mistake can no longer be written.

| Rule | Enforced by |
| --- | --- |
| Hooks never list query keys to invalidate. | The `MutationCache` in `apps/web/src/utils/orpc.ts` |
| Customer and branch reads hide seller identity from non-admins. | `suni/require-seller-scope` |
| No unnecessary conditions or type assertions. | `pnpm run check:type-aware` (pre-push and CI) |
| No manual memoization. | React Compiler plus a `no-restricted-imports` ban |
| Web types come from `AppRouterInputs`/`AppRouterOutputs`, not hand-derived. | `suni/prefer-router-types` |
| Validation strings are bounded; text is never nullable. | `suni/require-string-bound`, `suni/no-nullable-text` |
| Zod schemas live in `@suni/db/validation/*`, not in components. | `no-restricted-imports` of `zod/**` in components |
| Forms use TanStack Form; the web never imports server packages. | `no-restricted-imports` |
| A mutation on a child entity checks, in the same `UPDATE ... WHERE`, that neither it nor its parents are archived. | Review only |
| UI copy and accessibility text (`aria-label`, `sr-only`, `title`) are in Spanish. | Review only |

## Context files

- [apps/web/AGENTS.md](apps/web/AGENTS.md) (web routes, client setup, and local commands)
Expand Down
4 changes: 1 addition & 3 deletions apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { ZodToJsonSchemaConverter } from "@orpc/zod/zod4";
import { appRouter } from "@suni/api/routers/index";
import { initLogger } from "evlog";
import { createAuthMiddleware } from "evlog/better-auth";
import type { BetterAuthInstance } from "evlog/better-auth";
import { createFsDrain } from "evlog/fs";
import { evlog } from "evlog/hono";
import type { EvlogVariables } from "evlog/hono";
Expand All @@ -22,8 +21,7 @@ initLogger({
env: { service: "suni-server" },
});

// SAFETY: auth is created by Better Auth and implements the evlog BetterAuthInstance contract.
const identifyUser = createAuthMiddleware(auth as BetterAuthInstance, {
const identifyUser = createAuthMiddleware(auth, {
exclude: ["/api/auth/**"],
maskEmail: true,
});
Expand Down
5 changes: 4 additions & 1 deletion apps/web/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ See [package.json](package.json) for available scripts. From the repo root, run
## Conventions

- Import shared UI from `@suni/ui/components/*`; keep app-specific components in `src/components/`, grouped by feature (for example `src/components/users/`).
- Put oRPC queries and mutations in `src/hooks/` and have mutations await query invalidation. Load a single record for a route in its `loader`.
- Put oRPC queries and mutations in `src/hooks/`. Do not invalidate queries in a hook: the `QueryClient` in `src/utils/orpc.ts` refreshes every oRPC query after any successful mutation. Load a single record for a route in its `loader`.
- Name hooks verb plus resource (`useListCustomers`, `useCreateCustomer`). Type data with `AppRouterInputs` and `AppRouterOutputs`, never by redeclaring shapes.
- Build forms with TanStack Form (`@tanstack/react-form`) and the Zod schemas from `@suni/db/validation/*`. Do not use react-hook-form.
- Use `Link` for buttons that only navigate.
- Every page that fetches data renders loading, empty, and error states.
- Hide navigation and actions the current user cannot use, matching the procedure each one calls (`useIsAdmin` for admin-only ones).
- Keep a component's props type, constants, and labels in the same file as the component.
- The React Compiler is on. Do not use `useMemo`, `useCallback` or `memo`; lint rejects them.
- A flex container that holds a wide table needs `min-w-0`, or the table stretches the page.
- When a dialog's trigger can disappear on close (it is archived, removed or filtered out), set `finalFocus` so focus lands somewhere sensible.

## Generated files

Expand Down
4 changes: 4 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@
"zod": "catalog:"
},
"devDependencies": {
"@babel/core": "7.29.7",
"@rolldown/plugin-babel": "0.2.4",
"@tanstack/router-plugin": "^1.168.35",
"@types/babel__core": "7.20.5",
"@types/node": "^26.4.1",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@vitejs/plugin-react": "^6.1.1",
"babel-plugin-react-compiler": "1.0.0",
"typescript": "catalog:",
"vite": "^8.2.2"
}
Expand Down
7 changes: 2 additions & 5 deletions apps/web/src/components/customers/branches/grid.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { skipToken } from "@tanstack/react-query";
import { Building2 } from "lucide-react";
import type { ReactNode } from "react";
import { useMemo, useState } from "react";
import { useState } from "react";

import { NewEntityButton } from "@/components/customers/new-entity-button";
import { EntityGrid } from "@/components/customers/shared/entity-grid";
Expand Down Expand Up @@ -52,10 +52,7 @@ export function BranchesList({
customerId ? skipToken : { status: "all" }
);

const rowsByStatus = useMemo(
() => byStatus(matchingName(query.data ?? [], filters.name)),
[query.data, filters.name]
);
const rowsByStatus = byStatus(matchingName(query.data ?? [], filters.name));

const visibleBranches = rowsByStatus[filters.status];

Expand Down
9 changes: 3 additions & 6 deletions apps/web/src/components/customers/contacts/contact-grid.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Users } from "lucide-react";
import type { ReactNode } from "react";
import { useMemo, useState } from "react";
import { useState } from "react";

import { NewEntityButton } from "@/components/customers/new-entity-button";
import { EntityGrid } from "@/components/customers/shared/entity-grid";
Expand Down Expand Up @@ -45,10 +45,7 @@ export function ContactsList({
branchId,
});

const rowsByStatus = useMemo(
() => byStatus(matchingName(query.data ?? [], filters.name)),
[query.data, filters.name]
);
const rowsByStatus = byStatus(matchingName(query.data ?? [], filters.name));

const visibleContacts = rowsByStatus[filters.status];

Expand Down Expand Up @@ -90,7 +87,7 @@ export function ContactsList({
{visibleContacts.map((contact) => (
<ContactCard
contact={contact}
customer={customerId ? undefined : (contact.customer ?? undefined)}
customer={customerId ? undefined : contact.customer}
key={contact.id}
/>
))}
Expand Down
8 changes: 4 additions & 4 deletions apps/web/src/components/customers/customer-filters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { SegmentedControl } from "@/components/customers/shared/segmented-contro

const routeApi = getRouteApi("/_auth/customers/");

type Search = ReturnType<typeof routeApi.useSearch>;
type TypeFilter = "all" | (typeof CUSTOMER_TYPES)[number];

const TYPE_OPTIONS: { value: Search["type"]; label: string }[] = [
const TYPE_OPTIONS: { value: TypeFilter; label: string }[] = [
{ value: "all", label: "Todos" },
...CUSTOMER_TYPES.map((value) => ({ value, label: value })),
];
Expand All @@ -23,10 +23,10 @@ export default function CustomerFilters({ customers }: CustomerFiltersProps) {
const { name, type } = routeApi.useSearch();
const navigate = routeApi.useNavigate();

const setFilters = (filters: Partial<Search>) =>
const setFilters = (filters: { name?: string; type?: TypeFilter }) =>
navigate({ search: (prev) => ({ ...prev, ...filters }), replace: true });

const countOf = (value: Search["type"]) =>
const countOf = (value: TypeFilter) =>
value === "all"
? customers.length
: customers.filter((customer) => customer.type === value).length;
Expand Down
22 changes: 7 additions & 15 deletions apps/web/src/components/customers/new-entity-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import { ReactSelect } from "@suni/ui/components/react-select";
import { skipToken } from "@tanstack/react-query";
import { Plus } from "lucide-react";
import { useMemo, useState } from "react";
import { useState } from "react";

import { BranchFormDialog } from "@/components/customers/branches/branch-form-dialog";
import { ContactFormDialog } from "@/components/customers/contacts/contact-form-dialog";
Expand All @@ -28,13 +28,9 @@ function CustomerPicker({ value, onValueChange }: PickerProps) {
status: "active",
});

const options = useMemo(
() =>
customers
.toSorted(byName)
.map((customer) => ({ value: customer.id, label: customer.name })),
[customers]
);
const options = customers
.toSorted(byName)
.map((customer) => ({ value: customer.id, label: customer.name }));

return (
<ReactSelect
Expand Down Expand Up @@ -62,13 +58,9 @@ function BranchPicker({
customerId ? { customerId } : skipToken
);

const options = useMemo(
() =>
branches
.toSorted(byName)
.map((branch) => ({ value: branch.id, label: branch.name })),
[branches]
);
const options = branches
.toSorted(byName)
.map((branch) => ({ value: branch.id, label: branch.name }));

return (
<ReactSelect
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/components/sign-in-form.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { userSchema } from "@suni/db/validation/users";
import { Button } from "@suni/ui/components/button";
import { Input } from "@suni/ui/components/input";
import { Label } from "@suni/ui/components/label";
import { useForm } from "@tanstack/react-form";
import { useState } from "react";
import { toast } from "sonner";
import { z } from "zod";

import { authClient } from "@/lib/auth-client";

Expand Down Expand Up @@ -51,7 +51,7 @@ function EmailSignInForm({ onSent }: { onSent: () => void }) {
toast.error("No pudimos enviar el enlace. Intenta de nuevo.");
}
},
validators: { onSubmit: z.object({ email: z.email("Correo inválido") }) },
validators: { onSubmit: userSchema.pick({ email: true }) },
});

return (
Expand Down
Loading
Loading