chore: scaffold Next.js 15 + Supabase clients + vitest

This commit is contained in:
2026-07-09 21:33:59 +08:00
commit f83686fcca
29 changed files with 11655 additions and 0 deletions
@@ -0,0 +1,182 @@
# Product Requirements Document (PRD)
## Centralized AI-Powered HSE Incident Management & Reporting System
**Prepared for:** Setia Corporation — 3PL Warehouse Operations
**Based on:** Draft Proposal (Nurul Ain Athirah, June 2026) + Incident Reporting Flowchart, reviewed and extended
**Purpose:** This document defines *what* the system must do. Hand it to Claude Code together with `02_Technical_Specification_for_Claude_Code.md` and `03_Development_Roadmap_and_Claude_Code_Brief.md` to build it.
---
## 1. Objectives
Replace the current WhatsApp / Excel / paper-based HSE reporting process with a single digital system that:
1. Captures every incident, near miss, hazard, and asset event in one database — with photo, video, and document evidence attached at every stage, not just at first report.
2. Runs a structured, auditable workflow from report → response → investigation → CAPA → verification → closure.
3. Tracks CAPA (Corrective and Preventive Actions) to completion with owner, due date, evidence, and automatic overdue escalation.
4. Gives management a live dashboard instead of a monthly manual compilation.
5. Keeps Setia Corporation compliant with Malaysian DOSH reporting law (NADOPOD 2004) without manual form-filling.
6. Uses AI (Claude) to reduce the admin burden on HSE staff — drafting summaries, suggesting root causes and CAPA, flagging incomplete reports, and detecting risk patterns across sites.
---
## 2. Users & Roles
| Role | Who | Access | Key responsibility |
|---|---|---|---|
| Reporter | Any employee, supervisor, witness, security guard | Submit reports via QR/app; view status of own reports only | Report incidents/hazards immediately |
| Operation Supervisor | Warehouse/shift supervisor | Full access to incidents in their site/zone | Secure area, first response, initial classification |
| HSE Officer | Safety Assistant / HSE team | Full access across all sites | Investigation, RCA, CAPA assignment, verification, closure, DOSH filing |
| CAPA Owner | Department head (Ops, Maintenance, HR, etc.) | Access to CAPA items assigned to their department only | Complete corrective actions, upload proof |
| Management / Admin | Ms. Agnes, Mr. Terence, Mr. Yap, Mr. Jensen, etc. | Read-only dashboard across all sites; admin can manage users/config | Review trends, approve budget for corrective actions, audit readiness |
| System Admin | IT/appointed super-user | Full config access | User management, site/zone setup, form configuration |
Every action in the system must be attributable to a logged-in user — no anonymous edits (see §9 Compliance).
---
## 3. Incident Types Covered
The current flowchart only branches on **Injury** and **MHE (asset)**. The system must cover all of the following, each with its own lightweight intake form:
- Injury / medical treatment case (LTI and non-LTI)
- Near miss (no injury/damage, but could have) — **kept fast and low-friction on purpose**, since near-miss volume is the single best leading indicator of future serious incidents
- Unsafe condition / hazard observation (proactive, not tied to an event)
- Property / asset / MHE damage (forklift, racking, dock equipment)
- Environmental incident (spill, leak, chemical release, waste)
- Security incident (theft, unauthorized access, if relevant to your sites)
- Fire / emergency incident
---
## 4. Incident Lifecycle & Workflow Rules
This corrects and extends the two flowcharts supplied. The visual summary was shown earlier in this conversation; the rules below are the ones that must be encoded in the system's logic.
### Phase 1 — Report
- Reporter scans a site/zone-specific QR code (or opens the app), selects incident type, fills a short form, and attaches at least one photo (video/documents optional at this stage).
- System auto-generates a unique incident reference number (format: `SITE-YYYYMM-####`) and timestamps the report.
- System auto-detects the reporting site/zone from the QR code (no manual typing → fewer errors).
- Automatic notification fires immediately to the relevant Supervisor and HSE Officer (see §7).
### Phase 2 — Triage & Initial Response
- Supervisor/HSE confirms or reclassifies incident type and assigns a **severity level (15)**, which the current flowchart does not have — this is what drives SLA timers in step below. AI can suggest a severity level from the description (see §8), but a human always confirms it.
- Workflow branches based on type:
- **Injury involved →** medical treatment or first aid → medical status (LTI / non-LTI).
- **Asset/MHE involved →** emergency shutdown & LOTO if needed → operator-error check → minor/major classification → HR/discipline path if applicable.
- **Environmental →** containment steps, spill-kit deployment logged, environmental authority check.
- **Near miss / hazard observation →** skip straight to root-cause + CAPA, no medical/asset branch needed.
- **Regulatory check (new, mandatory):** at this point the system checks the severity/injury data against the DOSH NADOPOD 2004 rules (see §9) and tells the HSE Officer exactly which obligation applies — immediate notification, JKKP 6/7 within 7 days, or record-only in JKKP 8. This removes reliance on the HSE officer remembering the rule.
### Phase 3 — Investigation & CAPA
- HSE conducts investigation: witness statements, alcohol/urine test (if applicable), evidence collection, structured root cause analysis (5-Why and/or fishbone — selectable template, not free text only).
- Every CAPA item created must have: description, responsible department/owner, due date, priority, and linkage to the root cause it addresses.
- System auto-escalates (notifies owner, then owner's manager, then HSE) if a CAPA passes its due date without a status update.
### Phase 4 — Verification & Closure
- CAPA owner uploads **completion evidence** (photo/document proof the fix is in place) before marking a CAPA "done."
- HSE verifies effectiveness. If not effective, the CAPA **reopens** rather than the incident being closed with an open gap — this loop is missing from both flowcharts provided and is added here deliberately.
- Once all CAPAs are verified, HSE closes the incident; record locks (no further edits, only addenda) and flows into the dashboard and the JKKP 8 annual register automatically.
---
## 5. Evidence Management (Photos, Videos, Documents)
This must be a first-class feature across the entire lifecycle, not just at initial report:
| Stage | Evidence expected |
|---|---|
| Report | Scene photo/video, hazard photo |
| Response | LOTO tag photo, first-aid record, medical referral letter |
| Investigation | Witness statement scans, CCTV export, equipment inspection report, alcohol/urine test result |
| CAPA | **Before/after photos**, purchase receipts, training attendance sheets, updated SOP document |
| Verification | Final confirmation photo/video that the corrective action is in place and working |
Requirements:
- Accept JPG/PNG/HEIC, MP4/MOV, PDF/DOCX/XLSX. Max file size per upload configurable (recommend 200MB for video, compress on upload).
- Every file stores: uploader, timestamp, incident ID, stage, and an immutable file hash (for audit integrity — important if DOSH ever questions a record).
- Files retained **minimum 5 years** to match DOSH JKKP 8 register retention law — do not auto-delete.
- Thumbnail/preview generation so HSE doesn't have to download every file to review it.
---
## 6. CAPA Monitoring (dedicated module)
Because this was explicitly requested as a standout feature:
- Central CAPA register, filterable by site, department, status (open/in progress/overdue/verified/closed), and due date.
- Kanban-style board view (To Do / In Progress / Verification / Closed) in addition to table view — much faster for a department head to scan than a spreadsheet.
- Auto-escalation ladder: 3 days before due → reminder; on due date → notify owner; 3 days overdue → notify owner's manager; 7 days overdue → notify HSE + flagged red on dashboard.
- CAPA effectiveness re-check scheduled automatically (e.g., 30/60/90 days after closure) to confirm the fix actually held — this is beyond what the current proposal covers and beyond most SME-level systems, but is standard in mature EHS practice.
---
## 7. Notifications
- **Email** for formal records (investigation assignment, CAPA assignment, closure).
- **WhatsApp Business API** for time-critical alerts (new serious incident, CAPA overdue) — recommended in addition to email because your teams already operate on WhatsApp; email-only notification (as in the original proposal) will likely be checked less often by warehouse floor staff.
- In-app notification badge for all users.
---
## 8. AI-Assisted Capabilities (this is what makes it an "AI" system, not just a digital form)
| Capability | What it does | Business value |
|---|---|---|
| Report quality check | Flags incomplete reports (e.g., injury reported but no photo, or description too vague) before submission | Fixes the "delayed/incomplete information" problem named in the original proposal |
| Auto severity/category suggestion | Suggests severity level and incident category from the free-text description | Speeds up triage, reduces inconsistent classification between HSE staff |
| Similar-incident retrieval | Surfaces past incidents with similar description/location/equipment | Reveals recurring hazards fast — supports the "limited safety trend visibility" gap named in the proposal |
| Root cause & CAPA drafting assistant | Suggests likely root causes and draft corrective actions based on the investigation notes, for HSE to accept/edit | Cuts investigation write-up time, improves CAPA quality consistency |
| Auto-fill regulatory forms | Generates JKKP 6/7 draft PDFs and the JKKP 8 annual register from stored data | Removes the single biggest admin burden named in the proposal |
| Risk heatmap / prediction | Combines near-miss + incident + audit data by site/zone/shift to flag rising-risk areas before a serious incident occurs | Matches what leading commercial EHS platforms (VelocityEHS, Intelex) market as "predictive safety" in 2026 — but tuned to your own warehouses instead of generic industry data |
All AI outputs are **suggestions the human reviews and approves** — never auto-submitted to DOSH or auto-closed without a human sign-off. This matters both legally and for HSE staff trust in the tool.
---
## 9. Compliance Requirements — Malaysia Specific (correction to the source flowchart)
The uploaded flowchart labels the legal threshold box "OSHA Regulations." **For Malaysia this should be the Occupational Safety and Health Act 1994 (amended 2022) and its subsidiary regulation, NADOPOD 2004** (Notification of Accident, Dangerous Occurrence, Occupational Poisoning and Occupational Disease Regulations), enforced by DOSH/JKKP. The system's compliance logic should follow the actual rule, which is more specific than the flowchart's single ">4 days" box:
| Situation | Obligation |
|---|---|
| Fatality, or serious bodily injury as defined in NADOPOD's First Schedule (e.g., fracture, amputation, loss of sight) | Notify nearest DOSH office **immediately** by fastest means, then submit **JKKP 6** within 7 days |
| Dangerous occurrence (Second Schedule — e.g., boiler explosion, structural collapse), regardless of injury | Notify DOSH **immediately**, then **JKKP 6** within 7 days |
| Other injury causing incapacity for **more than 4 consecutive days** | Submit **JKKP 6** within 7 days (immediate call not legally required, but recommended for serious cases) |
| Occupational poisoning/disease (Third Schedule) | **JKKP 7** within 7 days |
| Any of the above | Also logged in the **JKKP 8** annual register, kept on-site 5 years, submitted to DOSH before 31 January each year |
Build the severity/injury intake fields so the system can determine which box applies automatically, and generate a checklist/reminder for the HSE Officer rather than relying on memory.
---
## 10. Dashboard & Analytics Requirements
- Total incidents, near misses, severity rate, open vs. closed — as in the original proposal — **plus**:
- Leading vs. lagging indicator split (near-miss/hazard reports = leading; injury/LTI = lagging) — this is the single biggest gap vs. commercial platforms and the cheapest to add.
- Site/zone/shift heatmap — critical for a multi-warehouse 3PL operation to compare performance and spot which dock, zone, or shift is generating the most risk.
- CAPA on-time completion rate (%).
- Top incident category and top root cause, trended over time.
- DOSH-reportable incident count and filing status (filed / pending / overdue) — audit-readiness at a glance.
- Exportable to PDF/Excel for board reporting.
---
## 11. Non-Functional Requirements
- **Mobile-first**, works on low-end Android phones common on warehouse floors; must work with poor/no signal (offline capture, syncs when back online).
- **Multi-language** UI: Bahasa Malaysia, English, Mandarin at minimum (Tamil if your workforce needs it) — the original proposal's Google Form is English-only, which will suppress reporting from non-English-fluent floor staff.
- **Multi-site** from day one — site and zone are first-class fields on every record, not an afterthought.
- **Role-based access control** enforced at the data level, not just hidden UI elements.
- **Full audit trail**: every create/edit/status-change/file-upload logged with user + timestamp, immutable.
- **Data retention**: minimum 5 years per DOSH requirement; evidence files never hard-deleted.
---
## 12. Success Metrics for the Project
- 100% of incidents captured digitally within 30 days of launch (zero WhatsApp-only reports).
- CAPA on-time closure rate above 85% within 3 months.
- Time from incident report to HSE Officer notification under 2 minutes (vs. current dependency on someone forwarding a WhatsApp message).
- Monthly HSE report preparation time reduced from days to minutes (auto-generated from dashboard).
- Zero missed DOSH statutory reporting deadlines.
@@ -0,0 +1,127 @@
# Technical Specification
## HSE Incident Management System — Build Spec for Claude Code
This document tells Claude Code *how* to build what `01_PRD_HSE_Incident_Management_System.md` describes. Give Claude Code both files together. If you're new to coding: you don't need to understand every line below — just hand this file to Claude Code and let it explain each decision to you as it builds.
---
## 1. Recommended Tech Stack
Chosen for one reason above all: **you're a beginner, so fewer moving parts = fewer things that can break and fewer things you need to host/manage yourself.**
| Layer | Choice | Why |
|---|---|---|
| Frontend + backend | **Next.js** (React) | One framework handles both the web pages and the server logic — no separate backend project to manage |
| Database + Auth + File Storage | **Supabase** (hosted Postgres) | Gives you a database, user login system, and file storage (for photos/videos) in one dashboard, with a generous free tier. You don't manage servers. |
| Hosting | **Vercel** (frontend) + Supabase cloud | Both have simple free/low-cost tiers, deploy with a few clicks, no server administration |
| AI features | **Claude API** (Anthropic) | For triage suggestions, RCA/CAPA drafting, and the JKKP form auto-fill logic described in the PRD §8 |
| Notifications | **Resend** or SendGrid (email) + **WhatsApp Business Cloud API** (Meta) | Matches PRD §7 |
| QR codes | `qrcode` npm package (generates codes for each site/zone, no external cost) | |
| PDF generation (JKKP forms) | `pdf-lib` (fills the official JKKP 6/7 PDF templates with stored data) | |
**Alternative stack** (if you later hand this to a professional dev team instead of building it yourself): Python/FastAPI backend + PostgreSQL + AWS S3 for storage + React frontend. Same schema and logic below applies either way — this spec is written to be stack-agnostic where it matters.
**Budget note:** Video evidence storage is the main cost driver as usage grows. Start on Supabase's free/starter storage tier; if video volume grows heavy in Phase 3+, migrate large-file storage to **Cloudflare R2** (cheaper for large files, still simple to set up) while keeping structured data in Supabase.
---
## 2. System Architecture (module view)
```
┌─────────────────────────────────────────────────────────┐
│ Reporter mobile/web app → QR scan → incident form │
└───────────────────────────┬─────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Next.js application │
│ - Incident intake & workflow engine │
│ - CAPA module │
│ - Dashboard & analytics │
│ - Admin (users, sites, roles) │
└───────┬───────────────┬───────────────┬───────────────────┘
▼ ▼ ▼
┌───────────────┐ ┌──────────────┐ ┌─────────────────────┐
│ Supabase DB │ │ Supabase │ │ Claude API │
│ (Postgres) │ │ Storage │ │ - triage suggestion │
│ + Auth (RLS) │ │ (photos/ │ │ - RCA/CAPA drafting │
│ │ │ videos/docs)│ │ - JKKP form drafting │
└───────────────┘ └──────────────┘ └─────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Notifications: Email (Resend) + WhatsApp Cloud API │
└─────────────────────────────────────────────────────────┘
```
---
## 3. Database Schema
Core tables (Postgres). Claude Code should generate this as Supabase migrations. Field lists are the minimum required — add more as needed during build, don't remove any listed here.
**sites** — id, name, address, region, active
**zones** — id, site_id (FK), name (e.g. "Dock A", "Cold Storage"), qr_code_token (unique)
**users** — id, name, email, phone, role (enum: reporter/supervisor/hse/capa_owner/management/admin), department, site_id, active
**incidents** — id, reference_no (unique, auto-generated), incident_type (enum: injury/near_miss/hazard/asset_damage/environmental/security/fire), site_id, zone_id, reported_by, reported_at, description, severity (1-5, nullable until triaged), status (enum: reported/triaged/investigating/capa_pending/verification/closed), injury_involved (bool), asset_involved (bool), medical_status (enum: none/first_aid/medical_treatment/lti, nullable), lost_days (int, nullable), closed_at (nullable)
**evidence_files** — id, incident_id (FK), stage (enum: report/response/investigation/capa/verification), file_url, file_type, file_hash, uploaded_by, uploaded_at
**investigations** — id, incident_id (FK), investigator_id, method (enum: five_why/fishbone/other), findings_text, root_cause_summary, alcohol_test_result (nullable), witness_statement_refs, completed_at
**capa_actions** — id, incident_id (FK), root_cause_ref, description, owner_user_id, department, due_date, priority (enum: low/med/high), status (enum: open/in_progress/overdue/pending_verification/verified/reopened/closed), completed_at, verified_by, verified_at, effectiveness_recheck_date
**dosh_reports** — id, incident_id (FK), form_type (enum: jkkp6/jkkp7/jkkp8), status (enum: not_required/pending/submitted), submitted_at, submitted_by, file_url (generated PDF)
**notifications_log** — id, incident_id or capa_id, channel (email/whatsapp/in_app), recipient, sent_at, status
**audit_log** — id, table_name, record_id, action, changed_by, changed_at, old_value, new_value
**Row-level security (RLS):** Enforce role-based access at the database level using Supabase RLS policies — e.g., a `capa_owner` can only see/update `capa_actions` rows where `owner_user_id` or `department` matches their own; a `reporter` can only see incidents where `reported_by` = themselves. This is safer than hiding buttons in the UI alone (per PRD §11).
---
## 4. Screens / Pages to Build
Organize as Claude Code build tasks in roughly this order (also see the phased roadmap doc):
1. **Login / role-based home redirect**
2. **Report incident** (mobile-first form, QR pre-fills site/zone, photo/video upload, offline-capable)
3. **My reports** (reporter's own submission status tracker)
4. **Incident inbox** (supervisor/HSE view — list + filters by site/status/severity)
5. **Incident detail** (full timeline: report → response → investigation → CAPA → verification, with evidence gallery per stage)
6. **Triage panel** (severity + classification, shows AI suggestion + regulatory checklist from PRD §9)
7. **Investigation workspace** (RCA template picker: 5-Why / fishbone, findings entry, AI-drafted root cause/CAPA suggestions to accept or edit)
8. **CAPA board** (Kanban + table view, filters, overdue highlighting)
9. **CAPA detail** (owner uploads completion evidence, HSE verifies)
10. **Dashboard** (KPIs, heatmap by site/zone, leading/lagging split, DOSH filing status — per PRD §10)
11. **DOSH register** (JKKP 6/7 draft generator, JKKP 8 annual register export)
12. **Admin** (manage users, sites/zones + QR generation, form field config)
---
## 5. AI Integration Details (Claude API)
Map directly to PRD §8. Each is a server-side call from Next.js to the Claude API, never client-side (keep your API key secret):
- **Report quality check**: on form submit, send description + evidence count to Claude; return a short list of missing items (e.g., "no photo attached for an injury report").
- **Severity/category suggestion**: send description + incident type; return suggested severity (1-5) + confidence + category, for the triaging user to confirm.
- **Similar-incident retrieval**: use vector embeddings (Supabase supports `pgvector`) on incident descriptions; on new report, query top-5 similar past incidents by embedding distance + same site/zone.
- **RCA/CAPA drafting assistant**: send investigation findings text; return suggested root cause categories and 2-3 draft CAPA descriptions for HSE to edit/accept.
- **JKKP form drafting**: send structured incident + investigation data in a prompt that asks Claude to produce the JKKP 6/7 field values as JSON; feed that JSON into `pdf-lib` to fill the actual form template.
All AI calls are logged (which incident, which suggestion, what the human ultimately chose) — this creates a useful dataset over time and keeps a clear line between "AI suggested" and "human decided," which matters if a record is ever audited.
---
## 6. Security & Auth
- Supabase Auth with email/password or phone OTP (phone OTP likely better adoption for warehouse floor staff without corporate email).
- Role stored in `users.role`, enforced via RLS (see §3) — never trust role checks only in the frontend.
- File uploads scanned/validated for type and size before storage.
- All admin actions (user role changes, site config) logged to `audit_log`.
---
## 7. Deployment Recommendation
1. Supabase project (free tier to start) → run schema migrations from §3.
2. Next.js app → deploy to Vercel, connect to Supabase via environment variables (never commit API keys to code).
3. Custom domain (e.g. `hse.setiacorp.com`) once MVP is validated.
4. Set up Resend/WhatsApp Cloud API credentials as environment variables.
5. Claude API key as environment variable, called only from server-side API routes.
This matches the phased build order in `03_Development_Roadmap_and_Claude_Code_Brief.md` — start with local development, deploy to a free-tier staging environment after Phase 1 (MVP) so real users can start testing early.
@@ -0,0 +1,99 @@
# Development Roadmap & Claude Code Brief
## How to actually build this, phase by phase
You're a coding beginner, so the goal here is: don't try to build everything at once. Build a small working version, get your HSE team using it, then add the smarter features. Each phase below is something you can hand to Claude Code as a separate session, with a ready-to-use starting prompt.
---
## Before you start
1. Create free accounts: Supabase, Vercel, Anthropic (Claude API), Resend (or SendGrid).
2. Create a project folder and put all three documents (`01_PRD...`, `02_Technical_Specification...`, this file) inside a `/docs` folder in that project. Claude Code will read them for context.
3. Open Claude Code in that folder and paste the starting prompt for Phase 0 below.
---
## Phase 0 — Foundation (Week 12)
**Goal:** Empty but working skeleton — login, roles, database, one site set up.
**Deliverables:**
- Next.js project connected to Supabase
- Database schema from `02_Technical_Specification...md` §3 created as migrations
- Login + role-based routing (reporter/supervisor/HSE/CAPA owner/management/admin)
- One test site + zone + QR code generated
**Starting prompt for Claude Code:**
> "Read the files in /docs. Set up a Next.js + Supabase project implementing the database schema in section 3 of the technical spec. Add Supabase Auth with the roles listed in the PRD section 2. Build a simple login page and a role-based redirect (each role lands on a different placeholder home page for now). Don't build the incident form yet — just the foundation."
---
## Phase 1 — MVP: core reporting (Week 36)
**Goal:** A real, usable incident reporting tool — this alone already replaces WhatsApp/Excel reporting.
**Deliverables:**
- QR-triggered incident report form (mobile-first), photo/video upload
- Auto reference number generation
- Email notification to supervisor + HSE on new report
- Incident inbox (list + filter) for supervisor/HSE
- Incident detail page showing evidence + basic status
- Basic dashboard: total incidents, open vs closed, by site
**Starting prompt for Claude Code:**
> "Read /docs. Build the incident report form and incident inbox described in PRD sections 3-4 and technical spec section 4, items 1-5. Use Supabase Storage for photo/video uploads. Send an email via Resend to the site's supervisor and HSE officer when a new incident is submitted. Keep the AI features out of scope for this phase — pure data capture and notification only."
**Milestone check:** Get 2-3 real HSE staff to use this for two weeks before moving on. Real feedback here is worth more than building further blind.
---
## Phase 2 — Investigation, CAPA & compliance (Week 710)
**Goal:** Close the loop — this is what makes it a *management* system, not just a form.
**Deliverables:**
- Triage panel with severity (1-5) and the DOSH regulatory checklist (PRD §9)
- Investigation workspace with RCA templates (5-Why, fishbone)
- CAPA board (Kanban + table), owner assignment, due dates, overdue escalation
- Verification step with completion evidence + reopen-if-ineffective logic
- JKKP 6/7 draft PDF generation
**Starting prompt for Claude Code:**
> "Read /docs. Build the triage, investigation, and CAPA modules described in PRD sections 4 and 6, and technical spec section 4, items 6-9. Implement the DOSH notification logic from PRD section 9 as a checklist shown during triage. Add the CAPA overdue escalation rules from PRD section 6. Don't build AI drafting yet — HSE and CAPA owners fill everything manually for now."
---
## Phase 3 — AI features (Week 1114)
**Goal:** This is the part that makes it better than most commercial EHS tools your competitors would pay for.
**Deliverables:**
- Report quality check (flags incomplete submissions before they're sent)
- AI severity/category suggestion at triage
- Similar-incident retrieval
- RCA/CAPA drafting assistant
- Full dashboard with leading/lagging split and site/zone heatmap
**Starting prompt for Claude Code:**
> "Read /docs. Add the AI-assisted features from PRD section 8 and technical spec section 5, using the Claude API. Start with the report quality check and severity suggestion, since those are the simplest. Log every AI suggestion and the human's final decision to the audit_log table, as described in technical spec section 5."
---
## Phase 4 — Scale & polish (ongoing, Week 15+)
- Roll out to additional warehouse sites
- WhatsApp Business API notifications (in addition to email)
- Multi-language UI (Bahasa Malaysia / Mandarin, per PRD §11)
- Offline capture for low-signal warehouse zones
- CAPA effectiveness re-check automation (30/60/90-day follow-up)
- Optional: link incidents to your WMS zone/shift data, so you can cross-reference whether incidents cluster around specific shifts, pick zones, or peak-season periods — something a generic commercial EHS platform cannot do out of the box because it doesn't know your WMS.
---
## Working with Claude Code as a beginner — a few tips
- **One phase per session.** Don't paste all four phases into one giant request — Claude Code works best with a clear, scoped task, and you'll understand what's happening if you review it in chunks.
- **Ask it to explain, not just build.** Add "explain what you're doing in simple terms as you go" to your prompts if you want the learning benefit, not just the output.
- **Review before merging.** Ask Claude Code to summarize each change before you accept it — especially anything touching the database schema or user roles/permissions.
- **Keep the docs updated.** If you change a requirement mid-build (e.g., decide to add a new incident type), update the PRD first, then tell Claude Code to re-read it — keeping the docs as the source of truth avoids drift between what's documented and what's built.
- **Test with real HSE staff early**, especially after Phase 1. A reporting tool that's technically correct but that warehouse floor staff find annoying to use will fail the same way WhatsApp-only reporting has gaps today — usability is a compliance issue here, not just a nice-to-have.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,62 @@
# IMS Project Initialization Design
**Date:** 2026-07-09
**Scope:** CLAUDE.md + memory notes + Obsidian wiki — no code scaffold
---
## Context
HSE Incident Management System for Setia Corporation (3PL warehouse). Replaces WhatsApp/Excel-based safety reporting. Full requirements in `docs/01_PRD...`, tech spec in `docs/02_Technical_Specification...`, roadmap in `docs/03_Development_Roadmap...`.
Three docs total ~7,000 words. Reading them every Claude session wastes tokens. Goal: distill into structured memory files + lean CLAUDE.md so future sessions load targeted context instead of raw docs.
---
## Approach: Lean CLAUDE.md + Rich Memory (Approach A)
**Why:** CLAUDE.md stays operational (<80 lines), memory files scoped by topic, Obsidian graph shows relationships between topics. Best token efficiency across multi-session builds.
---
## Files Created
### 1. `/Users/yapweeihan/Desktop/Projects/IMS/CLAUDE.md`
Claude-facing instructions only:
- Stack + versions (Next.js, Supabase, Vercel, Claude API, Resend, WhatsApp Business)
- Current phase (Phase 0 — not started)
- Dev conventions (RLS always enforced, API keys server-side only, never commit .env)
- graphify rules (query before browsing)
- Pointer to memory files for deep context
### 2. `~/.claude/projects/-Users-yapweeihan-Desktop-Projects-IMS/memory/`
Five per-topic files:
- `project_overview.md` — client, objectives, user roles, success metrics
- `architecture.md` — stack choices + rationale, module diagram
- `db_schema.md` — all 10 tables, key fields, RLS rules, pgvector note
- `phases.md` — 4 phases with deliverables; current phase marker updated each session
- `compliance.md` — Malaysia NADOPOD 2004 rules, JKKP 6/7/8 triggers, 5-year retention
### 3. `~/Desktop/ClaudeVault/`
Obsidian vault additions:
- `IMS-memory/` symlink → memory dir (live-updating)
- `IMS/wiki.md` — condensed human+Claude-readable summary of all 3 docs with `[[wikilinks]]` to memory files
---
## Conventions
- Memory `phases.md` gets updated at the start of each build phase (Phase 0 → 1 → 2...) so Claude always knows where we are.
- CLAUDE.md never grows beyond 100 lines; deep context lives in memory.
- Obsidian graph view shows `[[project_overview]]``[[architecture]]``[[db_schema]]``[[phases]]``[[compliance]]` topology.
- All memory files use frontmatter (`type`, `name`, `description`) consistent with the global memory system.
---
## Verification
1. `cat /Users/yapweeihan/Desktop/Projects/IMS/CLAUDE.md` — under 100 lines, readable in one scroll.
2. `ls ~/.claude/projects/-Users-yapweeihan-Desktop-Projects-IMS/memory/` — 5 .md files + MEMORY.md index.
3. Obsidian vault `ClaudeVault` shows `IMS-memory/` folder and `IMS/wiki.md`.
4. Obsidian Graph View shows `[[wikilinks]]` between IMS memory notes.
5. Future Claude session: reading MEMORY.md index + one targeted memory file is enough to answer "what phase are we in?" and "what is the db schema?" without reading the raw docs.