# IMS — Claude Code Instructions ## Project HSE Incident Management System for Setia Corporation (3PL warehouse). Replaces WhatsApp/Excel safety reporting. Client: Ms. Agnes, Mr. Terence, Mr. Yap, Mr. Jensen. ## Stack - **Frontend + API routes:** Next.js 16 (App Router) - **Database:** self-hosted PostgreSQL on the production server (`127.0.0.1:5433`, db `ims`) with RLS and pgvector. Access through Drizzle ORM + `pg`. Supabase is no longer used (migrated 2026-09-30). - **Auth:** own email + password. `bcryptjs` hashes, `jose` JWT in the `ims_session` cookie (8h), checked in `middleware.ts`. No Supabase GoTrue. - **Storage:** evidence files on the server filesystem (`EVIDENCE_DIR`, `/var/lib/ims-evidence`), served through `/api/evidence/...` with HMAC-signed URLs (`EVIDENCE_URL_SECRET`). Backed up nightly. - **Hosting:** own server `175.136.239.121` (SSH port 9321), nginx → systemd service `ims` on port 3003 at https://ims.setia.com.my - **AI:** DeepSeek via the OpenAI-compatible client (`lib/claude/client.ts`; key set in Settings or `DEEPSEEK_API_KEY`) for quality check, triage, RCA, risk flags and bulk import. Embeddings (similar incidents) use Google `text-embedding-004` (`GOOGLE_AI_API_KEY`). Server-side only, never client-side. - **Email:** Brevo (`BREVO_API_KEY`, `BREVO_FROM_EMAIL`, `BREVO_FROM_NAME`). Resend is no longer used. - **WhatsApp:** Meta WhatsApp Business Cloud API - **PDF:** pdf-lib (JKKP form fill, incident report) - **QR:** qrcode npm package ## Current Phase **All phases (0–6) complete as of 2026-07-12.** Supabase to local PostgreSQL migration completed and live 2026-09-30. **UI refresh in progress:** follow `design-system/design.md` §8 build order (tokens → ui primitives → TableCard → shells → migrate Incidents list → remaining screens). Legacy Supabase code (`lib/supabase/*`, `@supabase/*` deps, `supabase/` folder) was removed 2026-11-06; `db/schema.sql` + `db/rls.sql` are the schema source of truth. **Roles (since 2026-11-06):** `ssa` (Site Safety Assistant, replaces reporter + supervisor + capa_owner), `hse`, `management`, `admin`. SSA pages live under `app/(protected)/ssa/`. See `[[phases]]` memory for full phase breakdown and deliverables. ## Deployment (Production) Host `ims.setia.com.my` (175.136.239.121), SSH port 9321, user `setia`. The server holds **build output only, no source**. - **NEVER run `next build`, `pnpm build` or `npm ci` on the server.** A build without source deletes the working `.next` (took production down on 2026-09-30). - App files: `/srv/apps/ims/app` (`/var/www/ims` is a symlink to it). Service: systemd `ims` (`node server.js`, port 3003). Restart: `sudo systemctl restart ims`. - Env files live in `/srv/apps/ims/shared/` (`.env`, `.env.production`); `app/.env*` are links to them. Never overwrite, delete or ship `.env*`. - Evidence files: `/var/lib/ims-evidence` (do not touch). A deploy never runs DB migrations; ask before changing the DB. - Cron: two daily jobs call `http://127.0.0.1:3003/api/cron/...` with `CRON_SECRET` from `shared/.env` (`docs/vps-cron.md`). Deploy steps: 1. Build locally: `npm run build` (`output: 'standalone'`). 2. Stage and upload without any `.env*` or macOS `._*` files (use `COPYFILE_DISABLE=1 tar --exclude='.env*' --exclude='._*'`). Only `server.js`, `package.json`, `node_modules`, `.next` (standalone `.next` plus `.next/static`) and `public` are needed, since the standalone output otherwise drags in the whole project. 3. On the server confirm `/srv/apps/ims/app/.next/BUILD_ID` exists, then `sudo systemctl restart ims`. Never restart if `BUILD_ID` is missing. 4. Verify https://ims.setia.com.my/login returns 200 and `systemctl is-active ims` is `active`. Keep a rollback copy first: `tar -czf /srv/apps/ims/next-backup-.tgz .next`. ## Dev Conventions - Never commit `.env` or API keys. All secrets in env vars only. - RLS enforced at DB level for every table (`db/rls.sql`) — never rely on UI-only hiding. Query through `withUser` (RLS as the signed-in user) or `asAdmin` from `lib/db/with-user.ts`; do the write and its `audit_log` entry in one transaction. - AI calls: server-side API routes only (`/app/api/...`). - Incident reference format: `SITE-YYYYMM-####` - Every DB mutation writes to `audit_log` (table, record_id, action, changed_by, changed_at, old/new value). - Evidence files: never hard-delete; retain minimum 5 years (DOSH JKKP 8 requirement). - AI suggestions logged to `audit_log` — capture what the AI suggested + what the human chose. - Schema changes: edit `db/schema.sql` / `db/rls.sql` and apply by hand to the server database with the owner's go-ahead. ## File Structure ``` IMS/ ├── docs/ # PRD, tech spec, roadmap, specs — source of truth ├── design-system/ # design.md (UI source of truth) + .dc.html references ├── app/ # Next.js App Router pages + API routes ├── components/ │ ├── ui/ # Button, StatusTag, TableCard, … (design.md §4) │ └── layout/ # AppShell, MobileShell ├── lib/ │ ├── db/ # Drizzle schema, withUser/asAdmin, audit helper │ ├── auth/ # bcryptjs passwords, jose sessions, roles │ ├── storage/ # evidence files on disk + signed URLs │ ├── claude/ # AI client (DeepSeek) + Google embeddings │ └── notifications/ # Brevo email + WhatsApp senders, in-app ├── db/ # schema.sql, rls.sql, migration/ops scripts └── public/ ``` ## Deep Context (memory files — load instead of re-reading raw docs) - `[[project_overview]]` — objectives, roles, success metrics - `[[architecture]]` — module diagram, stack rationale, deployment - `[[db_schema]]` — all 10 tables, fields, RLS, pgvector - `[[phases]]` — 4 phases + deliverables, current phase - `[[compliance]]` — NADOPOD 2004, JKKP 6/7/8 rules ## Design system (IMS Admin refresh) Source of truth: `design-system/design.md`. Visual references: `design-system/IMS Admin.dc.html` (screens) and `design-system/IMS Admin Spec.dc.html` (patterns). Tokens live in `app/globals.css` (`@theme static`) and mirror design.md §2. The Modernist files under `design-system/_ds/` are retired; do not use them as a style reference. - Neutral commerce-admin style: Geist (`--font-geist`, `--font-geist-mono`), ink `#1f1f1f` on `#f1f1f1` ground, white cards radius 12 with the `shadow-card` ring, one teal accent `#0f766e`. Rules are 1px (`border-rule`), never 2px. - Use tokens, never hard-coded hex, font names or px values the tokens carry: `bg-ground`, `bg-surface`, `bg-surface-2`, `text-ink`, `text-muted`, `text-faint`, `border-rule`, `border-ring`, `bg-accent`, `bg-accent-tint`, `text-danger`, and the `st-*` status pairs. `gray-*`/`blue-*`/`red-*` remaps stay only until legacy pages are migrated. - Radius comes from the scale: `rounded-md` (8) buttons, chips, inputs, pills; `rounded-xl` (12) cards and mobile controls; `rounded-[5px]` checkbox. Headings and labels are flush left. - Status and priority colours only via `StatusTag` / `PriorityTag` (design.md §4.2): dark text on a light tint, text label always present, no icon required. Add new statuses in `components/ui/status-tag.tsx`, not per page. - Every list is a `TableCard` (design.md §4.9): saved views, toolbar, sortable header, row hover quick actions, selected tint, footer pager, floating bulk bar, empty state, mobile stacked variant. Do not hand-build tables. - Build UI with `components/ui/*`: `Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `Field`/`Input`/`Select`/`Textarea`, `FilterChip`, `Segmented`, `Avatar`, `Card`, `Drawer`, `TableCard`; pages sit in `AppShell` (desktop) or `MobileShell` (SSA). - Icons: Lucide (`lucide-react`), 16px stroke 2 in UI, 12px stroke 2.5 inside chips and checks, 22px stroke 1.8 in the mobile tab bar. - Interaction: hover/active values per component in design.md §4; `:focus-visible` 2px accent ring is global; transitions 120ms on bg/shadow only; mobile hit targets ≥ 44px. - Incident evidence photos stay full colour. - New pattern needed? Check design.md first. If it isn't there, design it in the design tool, then add it to design.md in the same PR as the component. - Gotcha: never write `*/` inside a CSS comment in `globals.css`; it ends the comment and silently swallows the `@theme` block. - Run `npm run check:design` before committing UI changes; it must print `design gates: clean`. The gate flags 2px borders, `Archivo`, hard-coded hex, `bg-white`, `shadow-xl/2xl`, centered button labels and off-palette hues; rounded corners are allowed. Extend `scripts/check-design-gates.mjs` when design.md adds a rule. ## graphify When graphify-out/graph.json exists: - Run `graphify query ""` before browsing source. - Use `graphify path "" ""` for relationships. - Use `graphify explain ""` for focused concepts. - After code changes: `graphify update .`