Last updated: 2026-03-05
Governance-first clinical documentation audit modelling platform for NDIS-aligned environments, built with Next.js, Prisma, and PostgreSQL.
- Production app: https://chartgen-gubii.netlify.app
- Main deploy alias: https://main--chartgen-gubii.netlify.app
- Netlify admin: https://app.netlify.com/projects/chartgen-gubii
- GitHub repo: https://github.com/gUBII/chartgen
- Creator GitHub: https://github.com/gUBII/
v3.9.0(staged feature ledger available at/whats-newandsrc/docs/RELEASE_HISTORY.md)- Timeline window:
October 2025 -> March 2026(staged release ledger for historical commits). - Includes UI kit primitives + shell standardization, admin dashboard CRUD, and restoration module wiring for Meal, Sleep, BGL, Bowel, Hygiene, Community, and Repositioning.
- Includes post-v3.9 operations upgrades: 365-day preview + larger batch support, XLSX export on Restoration/MAR pages, injector pointer/buttons, Discard Batch reset flow, global nuke controls, and MAR template management.
Chartgen currently implements:
- Restoration preview generation (
POST /api/engine/preview) returning meal candidates plus MAR/Sleep/BGL/Bowel/Hygiene/Community/Reposition logs - MAR preview generation (
POST /api/engine/mar-preview) - Unified preview/commit behavior across 8 chart families
- Candidate editing (
PATCHon both preview routes) - Batch approval (
approveAll) with governance controls - Transactional commit into official ledger (
POST /api/engine/commit) - Provenance hash verification and audit-event chaining
- Signed cookie session auth with role-aware access (
fullandguest) - Protected Ops API for online DB health checks and UAT execution
- UAT JSON artifact persistence for stress/cleanup runs
- Admin dashboard for direct chart/staff/participant data operations (
/admin) - 365-day preview window support with larger commit throughput
- XLSX export actions on both Restoration and MAR workflows
- Injector pointer prefill + DB-backed injector button templates
- Discard Batch and env-gated global-nuke cleanup controls
- MAR templates API + seeding support for fast medication setup
This policy applies specifically during periods of rapid iteration, especially when working with AI agents or performing focused, isolated tasks. It aims to maximize velocity while maintaining core quality.
- Conventions First: Always adhere to existing project conventions (formatting, naming, structure) from surrounding code and configuration.
- Verify & Justify Libraries/Frameworks: Never assume external libraries/frameworks. Verify existing usage or explicitly justify new additions.
- Idiomatic Changes: Ensure changes integrate naturally and idiomatically with the local context.
- Minimal High-Value Comments: Add comments sparingly, focusing on why something is done, especially for complex logic. Avoid stating what is done.
- Proactive Testing (Unit/Integration): When adding features or fixing bugs, include unit/integration tests to verify quality.
- Ecosystem Tool Preference: Utilize ecosystem tools (e.g., linters, formatters) before manual code changes.
- Iterative Verification: Employ output logs or debug statements during development to ensure correctness.
- Strict Error Handling: Implement robust error handling, especially for API interactions, to prevent cascading failures.
- No Direct Modification of
gemini.md: All task results and status updates must be written tohandoff/gemini_handshake.md. - Prioritize Explicit Instructions: Address direct, UUID-tagged instructions in the handshake log before speculative work.
- Product ownership: Chartgen is independently authored by Farhan Rashid (gUBII)
- Deployment environments: GoodwillCare and COHS instances run in Nexis365-hosted infrastructure
- Platform boundary: Nexis365 provides hosting/platform capabilities; product governance remains independent
For approveAll in both meal and MAR routes:
actorStaffIdis required- actor must have role
SUPERVISORorCLINICAL_LEAD - actor cannot approve a batch they generated (
SELF_APPROVAL_FORBIDDEN)
POST /api/engine/commit supports two payload modes:
Legacy (batch-based):
batchId+actorStaffId→ commits pre-approved meal/MAR candidates- requires elevated role (
SUPERVISORorCLINICAL_LEAD)
Phase E (grouped):
- Supports 8 log types:
marLogs,mealLogs,sleepLogs,bglLogs,bowelLogs,hygieneLogs,communityLogs,repositionLogs - each array processed in transaction; all succeed or all fail
- strict source/type validation (422 rejection of invalid sources/types)
- verifies candidate provenance hashes before any ledger write
- blocks duplicate commit of the same batch
- writes
AuditEvent(LEDGER_WRITTEN) with previous-hash linkage
MARStatus now includes:
ADMINISTEREDREFUSEDHELDLATENOT_ADMINISTERED
Migration applied:
prisma/migrations/20260226120823_add_held_to_mar_status/migration.sql
- Generate candidates into a
RestorationBatch(PENDING). - Review/edit candidate rows.
- Approve candidates via
approveAllwith governance checks. - Commit approved candidates to
MealLog/MARLog(source = RESTORED_APPROVED). - Record append-only
AuditEventfor traceability.
flowchart TD
subgraph Client ["Client Layer (Next.js)"]
UI["Web Browser"]
AuthCtx["AuthContext / gwc_session"]
end
subgraph API ["API Layer (App Router)"]
Engine["/api/engine/* (Preview/Commit)"]
Audit["/api/audit/* (KPI/Gap Reports)"]
Ops["/api/ops/* (DB-Health/UAT)"]
QA["/api/qa/* (Anomaly Detection)"]
AdminAPI["/api/admin/* (CRUD)"]
end
subgraph Service ["Domain Services"]
RestoEng["Restoration Engine"]
Realism["Temporal Realism"]
Detector["Anomaly Detectors"]
end
subgraph Persistence ["Data Layer"]
Prisma["Prisma Client"]
Neon["PostgreSQL (Neon)"]
end
UI --> AuthCtx
AuthCtx --> API
API --> Service
Service --> Prisma
Prisma --> Neon
sequenceDiagram
participant UI as Restoration UI
participant API as /api/engine/preview
participant Review as Review/Edit UI
participant Commit as /api/engine/commit
participant DB as PostgreSQL (Neon)
participant Audit as AuditEvent Ledger
UI->>API: POST generation payload
API->>DB: create RestorationBatch + candidates (PENDING)
UI->>Review: PATCH edits / approveAll
Review->>DB: update candidates (APPROVED)
UI->>Commit: POST grouped payload (8 log arrays)
Commit->>DB: transaction insertMany (ledger tables)
Commit->>Audit: append LEDGER_WRITTEN + hash linkage
flowchart TD
Login["/login"] --> AuthPost["POST /api/auth/login"]
AuthPost --> Cookie["Set-Cookie: gwc_session"]
Cookie --> Middleware{"Middleware Gate"}
Middleware -- Restricted --> Check["Check Session + Role"]
Check -- "role=full" --> Full["Allow: /admin, /uat, /audit-*"]
Check -- "role=guest" --> Guest["Allow: /restoration (read), /mar (read)"]
Check -- "no-role" --> Redirect["Redirect to /login"]
flowchart LR
Source["Synthetic/Live Logs"] --> DB[("PostgreSQL")]
DB --> Detector["GET /api/qa/detect-anomalies"]
Detector --> Ghost["Ghost Shift Engine"]
Detector --> Bowel["Constipation Gap Engine"]
Detector --> Restraint["Restraint Engine"]
Ghost --> Report["Anomalous Breach Report"]
Bowel --> Report
Restraint --> Report
GET /- landing pageGET /whats-new- full version timeline fromv1.0tov3.9GET /login- access-control login pageGET /deployment-notes- deployment and hosting boundary notesGET /audit-readiness- audit-modelling and readiness framingGET /restoration- meal chart control center with grouped commit support and defect highlighting (full-access)GET /mar- medication chart (MAR) control centerGET /chartgen-core- technical route (not user-navigable)GET /audit-engine- KPI trends and AI gap-report generation (full-access only)GET /audit-explorer- audit data browser with filtering and pagination (full-access only)GET /uat- online UAT control center (health check + stress + cleanup runners)GET /admin- administration dashboard for chart records (full-access only)
POST /api/engine/preview- generate restoration bundle (meal candidates + MAR rows + multi-chart module logs)PATCH /api/engine/preview- edit meal candidate orapproveAllPOST /api/engine/mar-preview- generate MAR candidatesPATCH /api/engine/mar-preview- edit MAR candidate orapproveAllPOST /api/engine/commit- commit approved candidates to ledgerGET /api/ops/db-health- protected pooled/direct DB connectivity probePOST /api/ops/uat- protected online stress and cleanup execution endpoint
cd /Users/moofasa/chartgen
npm installSet .env:
DATABASE_URL="postgresql://admin:password123@localhost:5432/chartgen_audit?schema=public"
DIRECT_URL="postgresql://admin:password123@localhost:5432/chartgen_audit?schema=public"
SITE_PASSWORD="set-a-strong-password-for-full-access"
SESSION_SECRET="replace-with-long-random-secret"npx prisma migrate dev
npx prisma generate
npx prisma db seednpm run devOpen:
http://localhost:3000/restorationhttp://localhost:3000/marhttp://localhost:3000/uat
From prisma/seed.cjs:
- Supervisor Staff ID:
32213 - Participant ID:
112334
This usually indicates the full session did not resolve. Try these checks:
-
Check session validity:
curl -X GET https://chartgen-gubii.netlify.app/api/auth/check \ -H "Cookie: gwc_session=<your-token-here>"Expected:
{ "authenticated": true, "role": "full" }or{ "authenticated": true, "role": "guest" } -
Ensure full-access login:
- Use
role: "full"in login payload, notrole: "guest" - Verify
SITE_PASSWORDenvironment variable is set and correct
- Use
-
Cookie handling in browser/curl:
- Browser: Cookies are set automatically; check DevTools → Application → Cookies
- cURL: Pass cookie as
gwc_session=<token-only>(do NOT includegwc_session=prefix twice)curl -H "Cookie: gwc_session=<token>" https://chartgen-gubii.netlify.app/restoration
-
Session TTL:
- Check if token has expired:
SESSION_TTL_SEC(default 7 days) - Re-login if session is older than TTL
- Check if token has expired:
npm run build
npm run lint
npm run lint:report
npm run lint:strict
npm run db:health
npm run db:health:trend -- --url https://chartgen-gubii.netlify.app --samples 3 --interval 1 --cookie "gwc_session=<full-session-token>"
npm run agent:check:result -- /Users/moofasa/chartgen/handoff/claude_handshake.log <UUID>
npm run agent:check:result -- /Users/moofasa/chartgen/handoff/gemini_handshake.md <UUID>
npx prisma validate
npx prisma migrate status
npm run db:stress -- --concurrency 20 --duration-sec 45 --mode simple
npm run db:cleanup:uat -- --participant-key 112334Use this checklist for independent verifier lane before merge/deploy:
- Route access boundaries are correct (
fullroutes blocked for guest). - Build compiles against current Prisma schema (
GapReportand QA tables present in client). - Lint report has no new errors relative to baseline.
- Grouped commit accepts all 8 arrays and writes transactionally.
- Defect-highlighted rows remain visible in restoration preview.
/api/qa/detect-anomaliesreturns expected breach types for seeded synthetic records.
- Admin Dashboard (AD-01/02):
-
/adminroute loads with list view. - Create/edit forms persist to DB for each chart family.
-
- App Shell (SH-01/02/03/04):
-
SiteHeaderandPrimaryNavcorrectly gate all 9 restricted routes. - Nav links highlight active route.
-
- UI Kit (UI-01/02/03/04):
- primitives render with consistent styling and a11y markers.
-
DataTableandTabshandle keyboard navigation correctly.
- Decomposition (LP-01, RS-01):
- Landing page modularized without UI regressions.
- Restoration dashboard decomposed into hooks/components with state integrity.
npm run lint- Existing local policy (
--max-warnings=15), useful for day-to-day work.
- Existing local policy (
npm run lint:report- Non-blocking lint report; always exits
0.
- Non-blocking lint report; always exits
npm run lint:strict- Strict gate for CI/release checks (
--max-warnings=0).
- Strict gate for CI/release checks (
/uatnow executes online operations via protected APIs (full-login required):GET /api/ops/db-healthPOST /api/ops/uatwithaction: "stress"POST /api/ops/uatwithaction: "cleanup"(DRY_RUN+ confirmation-gatedAPPLY)
- Trend monitor command (JSON summary + non-zero on degraded samples):
npm run db:health:trend -- --url https://chartgen-gubii.netlify.app --samples 5 --interval 10 --cookie "gwc_session=<full-session-token>"- Output keys:
samples,warning_count,degraded_count,pooled_max_ms,direct_max_ms,final_status
- Each online run writes a JSON artifact with timestamp and commit reference.
- Default artifact directory:
- local:
reports/uat - Netlify runtime:
/tmp/chartgen-uat-reports
- local:
- PostgreSQL database instance (Supabase, AWS RDS, Railway, Neon, etc.)
- GitHub repository pushed to main branch
- Netlify account connected to GitHub
Set these in Netlify Dashboard (Settings > Build & Deploy > Environment):
DATABASE_URL=postgresql://user:password@endpoint-pooler.region.aws.neon.tech/dbname?sslmode=require
DIRECT_URL=postgresql://user:password@endpoint.region.aws.neon.tech/dbname?sslmode=require
SESSION_SECRET=<long-random-string-for-HMAC-signing>
SESSION_TTL_SEC=604800
SESSION_SECRET: HMAC signing key for session tokens (required). Use a long random string (32+ chars).SESSION_TTL_SEC: Session time-to-live in seconds (optional, default: 604800 = 7 days). Invalid or non-positive values fallback to default.- Cookie parity: Sessions read
gwc_sessionfirst, then fallback to legacysessioncookie for backward compatibility.
netlify.toml runs npx prisma generate && npm run build for production and preview contexts.
Database migrations are intentionally run outside the build step so production deploys do not fail when DB credentials are missing or invalid at build time.
Critical for Netlify: The prisma/schema.prisma includes rhel-openssl-3.0.x in binaryTargets:
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "rhel-openssl-3.0.x"]
}This is required because Netlify's Edge functions runtime uses RHEL-based Linux with OpenSSL 3.0.x. Without this, Prisma client initialization fails with engine mismatch errors on production.
- Create/confirm Neon project + database in region closest to Netlify runtime.
- Reset the database user password in Neon.
- Build fresh Neon connection strings:
DATABASE_URL=postgresql://<user>:<url-encoded-password>@<endpoint>-pooler.<region>.aws.neon.tech/<db>?sslmode=require
DIRECT_URL=postgresql://<user>:<url-encoded-password>@<endpoint>.region.aws.neon.tech/<db>?sslmode=require- Validate credentials from this repo (use
DIRECT_URLfor Prisma CLI):
DATABASE_URL="postgresql://...-pooler..." DIRECT_URL="postgresql://...direct..." npx prisma migrate status- Apply migrations:
DATABASE_URL="postgresql://...-pooler..." DIRECT_URL="postgresql://...direct..." npx prisma migrate deploy- Optional: seed baseline data:
DATABASE_URL="postgresql://...-pooler..." DIRECT_URL="postgresql://...direct..." npx prisma db seedVia Netlify UI:
- Go to netlify.com
- Click "New site from Git" > Connect GitHub > Select
gUBII/chartgen - Build command should be
npx prisma generate && npm run build - Publish directory:
.next - Click Deploy
- After deploy, go Settings > Build & Deploy > Environment
- Add both
DATABASE_URLandDIRECT_URLenvironment variables - Trigger production redeploy via Deploys tab
- Run migrations from a terminal using both URLs
Via Netlify CLI:
npm install -g netlify-cli
netlify login
netlify env:set DATABASE_URL "postgresql://user:password@endpoint-pooler.region.aws.neon.tech/dbname?sslmode=require" --context production
netlify env:set DIRECT_URL "postgresql://user:password@endpoint.region.aws.neon.tech/dbname?sslmode=require" --context production
DATABASE_URL="postgresql://...-pooler..." DIRECT_URL="postgresql://...direct..." npx prisma migrate deploy
netlify deploy --prod --triggerAfter successful production deploy:
npx netlify statusshows the correct linked project and production URL- Visit deployed site (e.g.,
https://chartgen-gubii.netlify.app) - Test
/marendpoint: Generate and download PDF - Test
/restorationendpoint: Verify database writes - Monitor Netlify function logs for errors
If deployment fails:
- Re-run
netlify deploy --prodwith corrected DATABASE_URL - Check PostgreSQL connectivity and permissions
- Verify migrations ran successfully via
DATABASE_URL="postgresql://...-pooler..." DIRECT_URL="postgresql://...direct..." npx prisma migrate status
To seed test staff and participants in production (e.g., for UAT on Netlify):
-
Create
.env.production.localwith production database credentials:cat > .env.production.local << 'EOF' DATABASE_URL="postgresql://user:password@endpoint-pooler.region.aws.neon.tech/dbname?sslmode=require" DIRECT_URL="postgresql://user:password@endpoint.region.aws.neon.tech/dbname?sslmode=require" EOF
-
Run seed scripts against production DB:
set -a; source .env.production.local; set +a node scripts/seed-uat-staff.mjs node scripts/seed-uat-participant.mjs
-
IMPORTANT: Never commit
.env.production.localto version control. Add to.gitignoreif not already present.
Staff roles created: SUPPORT_WORKER, SUPERVISOR, CLINICAL_LEAD Participants created: Two test participants ready for preview generation
This enables UAT teams to generate preview batches without the "STAFF_REQUIRED" error.
# Preview
curl -X POST http://localhost:3000/api/engine/preview \
-H "Content-Type: application/json" \
-d '{"participantId":"112334","generatedByStaffId":"32213","startDate":"2026-02-20","endDate":"2026-02-22"}'
# Approve all
curl -X PATCH http://localhost:3000/api/engine/preview \
-H "Content-Type: application/json" \
-d '{"approveAll":true,"batchId":"<meal-batch-id>","actorStaffId":"32213"}'
# Commit
curl -X POST http://localhost:3000/api/engine/commit \
-H "Content-Type: application/json" \
-d '{"batchId":"<meal-batch-id>","actorStaffId":"32213"}'# MAR preview
curl -X POST http://localhost:3000/api/engine/mar-preview \
-H "Content-Type: application/json" \
-d '{"participantId":"112334","generatedByStaffId":"32213","startDate":"2026-02-20","endDate":"2026-02-22","medications":[{"name":"Aspirin","dosage":"100mg","route":"PO","hour":8,"minute":0}]}'
# Approve all
curl -X PATCH http://localhost:3000/api/engine/mar-preview \
-H "Content-Type: application/json" \
-d '{"approveAll":true,"batchId":"<mar-batch-id>","actorStaffId":"32213"}'
# Commit (MAR-only batches are supported)
curl -X POST http://localhost:3000/api/engine/commit \
-H "Content-Type: application/json" \
-d '{"batchId":"<mar-batch-id>","actorStaffId":"32213"}'npm run test:governanceruns executable governance integration checks against a running API server.npm testremains a placeholder and is not wired to a framework suite yet.- Current verification is build + Prisma validation +
npm run test:governance+ runtime API smoke testing. - Note:
src/app/api/engine/__tests__/directory exists but contains no test files.
See: src/docs/QUALITY_AND_TESTING.md.
src/docs/README.md- docs indexsrc/docs/ARCHITECTURE_REFERENCE.md- architecture and route behaviorsrc/docs/RESTORATION_ENGINE_NOTES.md- realism model detailssrc/docs/OPERATIONS_RUNBOOK.md- operations and troubleshootingsrc/docs/QUALITY_AND_TESTING.md- testing reality and quality gatessrc/docs/TECHNOLOGY_CONTEXT.md- design principles and constraintssrc/docs/PHASE1_AUDIT.md- historical audit record with closure statussrc/docs/UAT_AND_AUTH_ROADMAP.md- UAT execution plan plus login/auth rollout roadmapLATEST_LINKS_AND_INSTRUCTIONS.txt- root location for operational commandssrc/docs/LATEST_LINKS_AND_INSTRUCTIONS.md- documentation location for operational commands