On this page
Developer Guide
This page is for engineers running or extending KEPT. It documents what the repository actually contains.
Stack
| Layer | Choice |
|---|---|
| Framework | Next.js 15 (App Router), React 19 |
| Language | TypeScript (strict) |
| Styling | Tailwind CSS 3.4 with design tokens |
| Database | Postgres (Neon) via Drizzle ORM |
| Auth | Neon Auth with a mock adapter for development |
| AI | OpenAI and LongCat behind an AiProvider interface, plus a mock provider |
| Validation | Zod, React Hook Form |
| Tests | Vitest (unit and integration), Playwright (E2E) |
Architecture
Four layers, each depending only on the one above it:
src/domain/ Pure business types and rules. No framework imports.
src/application/ Use cases: day close, task updates, weekly planning, AI context.
src/infrastructure/ Repositories, auth, AI adapters, database schema.
src/app/ Next.js pages and API routes. Thin; they delegate to application.Key principles from the codebase:
Domain code has zero framework dependencies.
The repository pattern is interface plus adapter. Mock mode runs the whole application with no external services.
UI never queries repositories directly; pages call application services.
Every mutation emits an event.
activity_eventsis the audit history and the timeline.org_idis derived on the server. Browser-supplied tenant identifiers are never trusted.Row Level Security stays enabled on every tenant table.
AI never owns canonical state. Suggestions require human confirmation.
Running locally
pnpm install
pnpm devWith the default environment the app runs entirely in APP_DATA_MODE=mock with seeded demo data and no external services.
Scripts
| Command | Purpose |
|---|---|
pnpm dev | Start the development server. |
pnpm build | Production build. |
pnpm start | Start the production server. |
pnpm lint | ESLint. |
pnpm typecheck | TypeScript type checking. |
pnpm test | Vitest unit tests. |
pnpm test:integration | Integration tests (requires DATABASE_URL). |
pnpm test:e2e | Playwright E2E tests. |
pnpm db:generate | Generate a Drizzle migration from the schema. |
pnpm db:migrate | Apply the schema and the security baseline. |
pnpm db:seed:demo | Seed the demo organisation (idempotent). |
pnpm db:seed | Seed the legacy sample organisation. |
pnpm db:studio | Open Drizzle Studio. |
Environment variables
All variables are validated by a Zod schema at startup. An invalid value throws Invalid environment: ....
Core mode switches
| Variable | Values | Default | Purpose |
|---|---|---|---|
APP_DATA_MODE | mock, postgres | mock | Selects the in-memory or Postgres repository set. |
AUTH_PROVIDER | mock, neon | mock | Selects the authentication adapter. |
AI_PROVIDER | mock, longcat, openai, router | mock | Selects the AI adapter. router uses the routing table with fallback. |
Database
| Variable | Purpose |
|---|---|
DATABASE_URL | Pooled Postgres connection string. |
DATABASE_URL_UNPOOLED | Direct connection, used for migrations. |
.env.example also lists DATABASE_URL_APP. It is not declared in the Zod schema, so it is not validated.
Authentication
| Variable | Purpose |
|---|---|
NEON_AUTH_BASE_URL | Neon Auth base URL. |
NEON_AUTH_JWKS_URL | JWKS endpoint for JWT verification. |
NEXT_PUBLIC_NEON_AUTH_BASE_URL | Client-visible Neon Auth base URL. |
NEXT_PUBLIC_AUTH_PROVIDER | Client-visible auth provider flag. The sign-in page uses it to render the persona switcher in mock mode. |
AI providers
| Variable | Purpose |
|---|---|
OPENAI_API_KEY | OpenAI key. Used for client-facing work: replies, claim safety, commitment extraction. |
DEFAULT_OPENAI_MODEL | OpenAI model. .env.example sets gpt-4o-mini. |
LONGCAT_API_KEY | LongCat key. Used for internal reasoning: tasks, brief, weekly plan, QA. |
LONGCAT_BASE_URL | LongCat base URL. Default https://api.longcat.chat/openai/v1. |
LONGCAT_MODEL | LongCat model. Default LongCat-2.0. |
Integrations and storage
| Variable | Purpose |
|---|---|
GITHUB_APP_ID | GitHub App identifier. |
GITHUB_PRIVATE_KEY | GitHub App private key. |
GITHUB_WEBHOOK_SECRET | HMAC-SHA256 secret used to verify webhooks. |
NEON_STORAGE_URL | Object storage endpoint for attachments and import archives. |
NEXT_PUBLIC_SITE_URL | Canonical site URL for metadata. Falls back to VERCEL_PROJECT_PRODUCTION_URL. |
Running against Postgres
Local development can target any Postgres 15 or newer.
# .env.local
APP_DATA_MODE=postgres
AUTH_PROVIDER=mock
AI_PROVIDER=mock
DATABASE_URL=postgresql://user:password@host/db?sslmode=require
pnpm db:migrate
pnpm db:seed:demo
pnpm devpnpm db:migrate applies two files in order:
drizzle/0000_full_schema_baseline.sql— generated fromsrc/infrastructure/db/schema/index.ts.drizzle/0001_local_security.sql— creates the application roles,auth_get_current_org_id(),get_auth_user(), the RLS policies, and the grants.
In Postgres mode with AUTH_PROVIDER=mock, sign in using the persona buttons on /login. The persona resolves through get_auth_user().
Row Level Security
All tenant tables have RLS enabled with FORCE ROW LEVEL SECURITY. Policies use auth_get_current_org_id(), which reads the transaction-local app.current_org_id session variable set by the application. The kept_app role cannot bypass RLS; only the owner role can.
Data model
Thirty tables and nineteen enums. The core entities are Organization, Person, Client, Project, Task, TaskUpdate, Blocker, Commitment, ClientMessage, ActivityEvent, WeeklyPlan, ProjectAssignment, ImportedKnowledge, QATask, Team, BreakSession, WorkSession, and Notification.
Key enums:
| Enum | Values |
|---|---|
person_role | owner, ceo, admin, manager, team_lead, developer, qa, bd |
task_status | planned, active, blocked, completed, cancelled |
task_priority | low, normal, high, urgent |
task_source | manual, client_message, weekly_plan, ai_suggestion, import |
update_choice | progress, blocked, no_activity, completed |
blocker_status | active, resolved |
commitment_status | open, met, missed, withdrawn |
qa_status | pending, in_progress, changes_requested, passed, cancelled |
import_status | pending, processing, ready_for_review, approved, rejected, failed |
weekly_plan_status | draft, published |
Roles and permissions
src/application/authorization.ts holds a 29-permission matrix across the eight roles. Helpers:
can(person, permission)— capability check.isManager(person)— true forowner,ceo,admin,manager,team_lead.seesAllOrgProjects(person)— true forowner,ceo,admin,manager.canAccessProject(person, orgId)— same organisation plusproject:view.
Scope-level access lives in two more files:
src/application/project-visibility.ts— which projects a person can see.src/application/execution-access-policy.ts—ExecutionAccessPolicy, covering organisation, team, person, project, task, and QA scopes.
API surface
All routes are under src/app/api. Every request is authenticated by the middleware and scoped to the session's organisation.
Auth
/api/auth/signin, /api/auth/signup, /api/auth/signout, /api/auth/status, /api/auth/mock-signin, /api/auth/forgot-password.
Core work
/api/tasks, /api/tasks/bulk, /api/tasks/[taskId], /api/task-updates, /api/tasks/[taskId]/timeline, /api/tasks/[taskId]/acknowledge, /api/tasks/[taskId]/seen, /api/tasks/[taskId]/escalate, /api/tasks/[taskId]/attachments, /api/task-suggestions.
Day and session
/api/day-start, /api/day-close, /api/check-out, /api/break, /api/break/summary, /api/work-session, /api/work-session/resolve.
Projects and knowledge
/api/projects, /api/projects/[projectId], /api/projects/[projectId]/assignments, /api/projects/[projectId]/facts, /api/imports, /api/imports/[importId].
Clients, messages, commitments
/api/clients, /api/messages, /api/draft-reply, /api/draft-reply/validate, /api/commitments.
Organisation
/api/organizations, /api/people, /api/people/[personId], /api/people/[personId]/work-check, /api/teams, /api/teams/[teamId], /api/teams/[teamId]/members, /api/invites, /api/invites/accept, /api/invites/[inviteId]/revoke.
Execution and reporting
/api/execution/overview, /api/execution/escalations, /api/execution/escalation-evaluate, /api/execution/escalation-brief.
AI
/api/ai/day-close-suggest, /api/ai/health, /api/ai/qa-checklist, /api/ai/suggest-tasks, /api/ai/weekly-plan-suggest, /api/ai/projects/[projectId]/brief, /api/ai/projects/[projectId]/suggest-tasks.
Integrations and health
/api/webhooks/github, /api/health, /api/health/detailed, /api/notifications, /api/search, /api/qa-tasks.
Note
vercel.jsonschedules/api/execution/escalation-evaluatedaily at 09:00. The escalation engine itself is deterministic and does not use a model.
Business rules worth knowing
Day close. Eligible tasks are those assigned to the person with requiresDailyUpdate set and plannedWeek null or earlier than the current week start. The active subset excludes completed, cancelled, and planned tasks. Every task in the active subset must have a task_updates row for today.
Weeks. Week start is hardcoded to Sunday, and plannedWeek stores the ISO date of that week start.
Stale. A task is stale after 24 hours without an update, or after 24 hours since assignment if it was never opened.
Escalation. src/application/execution-escalation-service.ts applies an ordered rule list producing REMINDER, ATTENTION, URGENT, or CRITICAL. Working hours are 09:00–18:00 and weekends are excluded.
Publishing. Publishing a weekly plan flips planned tasks to active for that week.
Imports. src/lib/safe-import/create-project.ts creates a project, facts, knowledge entries, and one owner assignment. It never creates tasks, blockers, or commitments.
Ownership. Assigning a project grants visibility. Task creation adds the assignee as a contributor, never as an owner.
Testing
pnpm test # Unit tests
pnpm test:integration # Integration tests, requires DATABASE_URL
pnpm test:e2e # Playwright E2E testsThe mock data mode lets the full suite run without external services. Integration tests cover cross-organisation isolation and transaction safety; E2E tests cover the admin and developer workflows.
Existing internal documentation
The repository also carries internal engineering notes that are separate from this user guide:
docs/architecture.md— layer responsibilities and provider boundaries.docs/domain-model.md— the domain entities and their rules.docs/runbook.md— operational procedures.docs/v1-decisions.md— the decisions behind v1.docs/design/README.md— the UI redesign plan and token migration notes.