KKEPT
On this page

Developer Guide

This page is for engineers running or extending KEPT. It documents what the repository actually contains.

Stack

LayerChoice
FrameworkNext.js 15 (App Router), React 19
LanguageTypeScript (strict)
StylingTailwind CSS 3.4 with design tokens
DatabasePostgres (Neon) via Drizzle ORM
AuthNeon Auth with a mock adapter for development
AIOpenAI and LongCat behind an AiProvider interface, plus a mock provider
ValidationZod, React Hook Form
TestsVitest (unit and integration), Playwright (E2E)

Architecture

Four layers, each depending only on the one above it:

code
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:

  1. Domain code has zero framework dependencies.

  2. The repository pattern is interface plus adapter. Mock mode runs the whole application with no external services.

  3. UI never queries repositories directly; pages call application services.

  4. Every mutation emits an event. activity_events is the audit history and the timeline.

  5. org_id is derived on the server. Browser-supplied tenant identifiers are never trusted.

  6. Row Level Security stays enabled on every tenant table.

  7. AI never owns canonical state. Suggestions require human confirmation.

Running locally

bash
pnpm install
pnpm dev

With the default environment the app runs entirely in APP_DATA_MODE=mock with seeded demo data and no external services.

Scripts

CommandPurpose
pnpm devStart the development server.
pnpm buildProduction build.
pnpm startStart the production server.
pnpm lintESLint.
pnpm typecheckTypeScript type checking.
pnpm testVitest unit tests.
pnpm test:integrationIntegration tests (requires DATABASE_URL).
pnpm test:e2ePlaywright E2E tests.
pnpm db:generateGenerate a Drizzle migration from the schema.
pnpm db:migrateApply the schema and the security baseline.
pnpm db:seed:demoSeed the demo organisation (idempotent).
pnpm db:seedSeed the legacy sample organisation.
pnpm db:studioOpen Drizzle Studio.

Environment variables

All variables are validated by a Zod schema at startup. An invalid value throws Invalid environment: ....

Core mode switches

VariableValuesDefaultPurpose
APP_DATA_MODEmock, postgresmockSelects the in-memory or Postgres repository set.
AUTH_PROVIDERmock, neonmockSelects the authentication adapter.
AI_PROVIDERmock, longcat, openai, routermockSelects the AI adapter. router uses the routing table with fallback.

Database

VariablePurpose
DATABASE_URLPooled Postgres connection string.
DATABASE_URL_UNPOOLEDDirect 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

VariablePurpose
NEON_AUTH_BASE_URLNeon Auth base URL.
NEON_AUTH_JWKS_URLJWKS endpoint for JWT verification.
NEXT_PUBLIC_NEON_AUTH_BASE_URLClient-visible Neon Auth base URL.
NEXT_PUBLIC_AUTH_PROVIDERClient-visible auth provider flag. The sign-in page uses it to render the persona switcher in mock mode.

AI providers

VariablePurpose
OPENAI_API_KEYOpenAI key. Used for client-facing work: replies, claim safety, commitment extraction.
DEFAULT_OPENAI_MODELOpenAI model. .env.example sets gpt-4o-mini.
LONGCAT_API_KEYLongCat key. Used for internal reasoning: tasks, brief, weekly plan, QA.
LONGCAT_BASE_URLLongCat base URL. Default https://api.longcat.chat/openai/v1.
LONGCAT_MODELLongCat model. Default LongCat-2.0.

Integrations and storage

VariablePurpose
GITHUB_APP_IDGitHub App identifier.
GITHUB_PRIVATE_KEYGitHub App private key.
GITHUB_WEBHOOK_SECRETHMAC-SHA256 secret used to verify webhooks.
NEON_STORAGE_URLObject storage endpoint for attachments and import archives.
NEXT_PUBLIC_SITE_URLCanonical site URL for metadata. Falls back to VERCEL_PROJECT_PRODUCTION_URL.

Running against Postgres

Local development can target any Postgres 15 or newer.

bash
# .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 dev

pnpm db:migrate applies two files in order:

  1. drizzle/0000_full_schema_baseline.sql — generated from src/infrastructure/db/schema/index.ts.

  2. 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:

EnumValues
person_roleowner, ceo, admin, manager, team_lead, developer, qa, bd
task_statusplanned, active, blocked, completed, cancelled
task_prioritylow, normal, high, urgent
task_sourcemanual, client_message, weekly_plan, ai_suggestion, import
update_choiceprogress, blocked, no_activity, completed
blocker_statusactive, resolved
commitment_statusopen, met, missed, withdrawn
qa_statuspending, in_progress, changes_requested, passed, cancelled
import_statuspending, processing, ready_for_review, approved, rejected, failed
weekly_plan_statusdraft, 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 for owner, ceo, admin, manager, team_lead.

  • seesAllOrgProjects(person) — true for owner, ceo, admin, manager.

  • canAccessProject(person, orgId) — same organisation plus project: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.json schedules /api/execution/escalation-evaluate daily 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

bash
pnpm test                # Unit tests
pnpm test:integration    # Integration tests, requires DATABASE_URL
pnpm test:e2e            # Playwright E2E tests

The 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.