Skip to main content

Entities Module

The Entities Module (@ever-works/agent/entities) defines all TypeORM entity classes, enums, types, and supporting interfaces used across the Ever Works platform. These entities map directly to database tables and form the core domain model.

Module Structure

packages/agent/src/entities/
├── index.ts # Barrel exports for all entities and types
├── _types.ts # TimestampColumn custom decorator
├── types.ts # Shared enums, types, and re-exports
├── notification.types.ts # Notification-specific enums and DTOs
├── user.entity.ts # User entity
├── work.entity.ts # Work entity (core domain)
├── work-member.entity.ts # Work member with role-based access
├── work-advanced-prompts.entity.ts # Custom AI prompt overrides
├── work-custom-domain.entity.ts # Custom domain mapping
├── work-generation-history.entity.ts # Generation run tracking
├── work-schedule.entity.ts # Scheduled update configuration
├── api-key.entity.ts # API key management
├── refresh-token.entity.ts # JWT refresh token rotation
├── oauth-token.entity.ts # OAuth provider tokens
├── subscription-plan.entity.ts # Subscription plan definitions
├── user-subscription.entity.ts # User-plan associations
├── usage-ledger-entry.entity.ts # Usage-based billing ledger
├── notification.entity.ts # User notifications
└── cache.entity.ts # Cache storage entries

Entity Relationship Diagram

Core Entities

User

The User entity (users table) represents an authenticated platform user.

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
emailvarcharUnique email address
passwordvarchar (nullable)Hashed password (null for OAuth-only users)
usernamevarcharDisplay name / GitHub username
emailVerifiedbooleanWhether email is confirmed
emailVerificationTokenvarchar (nullable)Pending verification token
passwordResetTokenvarchar (nullable)Pending password reset token
passwordResetExpiresAttimestamp (nullable)Reset token expiry
lastLoginAttimestamp (nullable)Last successful login
defaultPlanvarcharDefault subscription plan code
createdAttimestampAccount creation date
updatedAttimestampLast update date

Relations: works (OneToMany), generationHistory (OneToMany), subscriptions (OneToMany), schedules (OneToMany), memberships (OneToMany).

Helper method: asCommitter() returns a { name, email } object for git commit authoring.

Work

The Work entity (works table) is the central domain object representing a generated work/listing site.

Core fields:

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
namevarcharDisplay name
slugvarcharURL-safe identifier, used for repo names
userIduuid (FK)Creator's user ID
ownervarchar (nullable)GitHub org/user override for repos
descriptionvarcharWork description
gitProvidervarcharGit provider (github)
deployProvidervarchar (nullable)Deploy provider (vercel)
websitevarchar (nullable)Published website URL
companyNamevarchar (nullable)Associated company
organizationbooleanWhether repos use org scope

Generation fields: generateStatus (JSON), generationStartedAt, generationProgressedAt, generationFinishedAt.

Domain type fields (for smart image routing): domainType (software / ecommerce / services / general), domainTypeConfidence, domainTypeManuallySet.

Deployment fields: deployProjectId, deploymentState, deploymentStartedAt.

Repository fields: lastPullRequest (JSON with main/data PR info), repoVisibility (JSON), itemsCount.

Community PR fields: communityPrEnabled, communityPrAutoClose, communityPrState (JSON).

Website template fields: websiteTemplateAutoUpdate, websiteTemplateUseBeta, websiteTemplateLastCommit, websiteTemplateLastError, websiteTemplateLastUpdatedAt, websiteTemplateLastCheckedAt.

Helper methods:

MethodReturn TypeDescription
getDataRepo()stringReturns {slug}-data
getWebsiteRepo()stringReturns {slug}-website
getMainRepo()stringReturns slug
getRepoOwner()stringReturns owner or user.username
isCreator(userId)booleanChecks if user is the work creator
getMember(userId)WorkMember | undefinedFinds member entry
hasAccess(userId)booleanCreator or member check
getUserRole(userId)WorkMemberRole | nullReturns role (owner for creator)

WorkMember

Represents a user's membership in a work with role-based access control.

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
workIduuid (FK)Work reference
userIduuid (FK)User reference
roleenummanager, editor, or viewer
invitedByUserIduuid (nullable)Who sent the invite
createdAttimestampMembership creation date

Role hierarchy (highest to lowest): owner > manager > editor > viewer.

Helper methods:

  • hasRoleOrHigher(requiredRole) -- Checks if member's role meets the minimum
  • canManageMembers() -- Returns true for manager and above
  • canEdit() -- Returns true for editor and above

WorkSchedule

Configures recurring work updates with scheduling, billing, and failure tracking.

ColumnTypeDescription
workIduuid (PK, FK)One-to-one with Work
cadenceenumdaily, weekly, biweekly, monthly
billingModeenumincluded or usage
statusenumactive, paused, failed
nextRunAttimestamp (nullable)Next scheduled execution
lastRunAttimestamp (nullable)Last execution time
consecutiveFailuresintFailure count for auto-pause logic
lastFailureReasonvarchar (nullable)Last error description
providerOverridesjson (nullable)Per-schedule plugin provider overrides

WorkGenerationHistory

Tracks each generation run with metrics and status.

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
workIduuid (FK)Work reference
userIduuid (FK)User who triggered it
methodvarcharGeneration method used
statusvarcharcompleted, failed, cancelled
startedAttimestampRun start time
completedAttimestamp (nullable)Run end time
metricsjson (nullable)GenerationMetrics (items, tokens, cost, duration)
triggeredByvarcharmanual, schedule, api
errorMessagevarchar (nullable)Error details on failure

GenerationMetrics type:

interface GenerationMetrics {
itemsGenerated?: number;
itemsUpdated?: number;
totalTokensUsed?: number;
estimatedCost?: number;
durationMs?: number;
stepsCompleted?: number;
totalSteps?: number;
}

Shared Types and Enums

types.ts

ExportKindValues / Description
GenerateStatusTypeenum (re-export)From @ever-works/contracts/api
WorkScheduleCadenceenum (re-export)daily, weekly, biweekly, monthly
WorkScheduleStatusenum (re-export)active, paused, failed
WorkScheduleBillingModeenum (re-export)included, usage
SubscriptionPlanCodeenumfree, standard, premium
WorkMemberRoleenumowner, manager, editor, viewer
DomainEnvironmentenumproduction, staging, development
GenerateStatustypeStatus object with step, progress, errors, warnings
CommunityPrStateinterfacePR processing state (processedPrNumbers, lastProcessedAt, etc.)
ClassToObject<T>utility typeConverts class to plain object type
ASSIGNABLE_MEMBER_ROLESconst array[manager, editor, viewer] (excludes owner)

notification.types.ts

ExportKindValues
NotificationTypeenuminfo, warning, error, success
NotificationCategoryenumai_credits, subscription, generation, system, security
CreateNotificationDtointerfaceFields for creating a notification
NotificationQueryOptionsinterfacePagination, filtering, category options

Supporting Entities

ApiKey

API key management with hashed storage and prefix-based lookup.

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
userIduuid (FK)Owner
namevarcharDisplay name
keyHashvarcharSHA-256 hash of the full key
keyPrefixvarcharFirst 8 characters for identification
expiresAttimestamp (nullable)Optional expiry
lastUsedAttimestamp (nullable)Usage tracking

RefreshToken

JWT refresh token with family-based rotation and revocation tracking.

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
userIduuid (FK)Token owner
tokenHashvarcharHashed token value
familyvarcharToken family for rotation detection
expiresAttimestampToken expiry
revokedAttimestamp (nullable)When revoked
replacedByTokenIduuid (nullable)Points to the replacement token

OAuthToken

Stores OAuth tokens from external providers (e.g., GitHub).

ColumnTypeDescription
iduuid (PK)Auto-generated UUID
userIduuid (FK)Token owner
providervarcharOAuth provider name
accessTokenvarcharEncrypted access token
refreshTokenvarchar (nullable)Encrypted refresh token
scopevarchar (nullable)Granted scopes
expiresAttimestamp (nullable)Token expiry
metadatajson (nullable)Additional provider data

Custom Decorator: TimestampColumn

The _types.ts file exports a TimestampColumn decorator that stores timestamps as bigint values in the database and transforms them to/from JavaScript Date objects:

import { TimestampColumn } from '@ever-works/agent/entities';

@Entity()
class MyEntity {
@TimestampColumn({ nullable: true })
processedAt?: Date;
}

This ensures consistent timestamp handling across all database backends (SQLite stores dates differently from PostgreSQL).