Complete guide to defining domain models using TypeSpec with code generation.
βDomain models are the single source of truth. TypeScript types are generated artifacts.β
TypeSpec-First Architecture ensures:
1. Define TypeSpec models tsp/**/*.tsp
β
βΌ
2. Generate pnpm generate
(= tsp compile tsp/ --emit @typespec-tools/emitter-typescript,
then prettier --write over the generated directory)
β
βΌ
3. Import generated types import type { Settings }
from '@/domain/generated/output.js'
β
βΌ
4. Build pnpm build
β
βΌ
5. Test pnpm test
Every directory has an index.tsp barrel that imports its own files;
main.tsp imports only the five top-level barrels. Adding a file means adding
one import line to the nearest index.tsp β never to main.tsp.
tsp/
βββ main.tsp # Entry point β imports the five barrels below
βββ common/ # Shared types
β βββ index.tsp
β βββ base.tsp # BaseEntity, SoftDeletableEntity, AuditableEntity
β βββ scalars.tsp # UUID scalar
β βββ ask.tsp # Askable interface pattern
β βββ enums/ # Shared enumerations
β βββ index.tsp
β βββ lifecycle.tsp # SdlcLifecycle enum
β βββ states.tsp # status enums
β βββ agent-config.tsp # AgentType enum
β βββ ...
βββ domain/ # Domain layer models
β βββ index.tsp
β βββ entities/ # One file per entity
β β βββ index.tsp
β β βββ feature.tsp
β β βββ epic.tsp
β β βββ ...
β βββ value-objects/ # Embedded value objects
βββ agents/ # Agent system models
β βββ index.tsp
β βββ agent-run.tsp
β βββ feature-agent.tsp
β βββ ...
βββ deployment/ # Deployment configuration
β βββ index.tsp
β βββ deploy-skill.tsp
β βββ ...
βββ ui/ # Presentation-layer value objects
tspconfig.yaml wires three emitters β @typespec/openapi3,
@typespec/json-schema and @typespec-tools/emitter-typescript β and sets
output-dir to apis/, overriding the TypeScript emitterβs output directory to
packages/core/src/domain/generated.
# After running: pnpm generate (or pnpm tsp:compile)
apis/
βββ openapi/
β βββ openapi.yaml # OpenAPI 3.x spec (API documentation)
βββ json-schema/ # JSON Schema files (one per model)
βββ Feature.json
βββ Task.json
βββ Settings.json
βββ ...
packages/core/src/domain/generated/
βββ output.ts # TypeScript types (DO NOT EDIT)
Use pnpm generate rather than pnpm tsp:compile when you intend to commit
the result: generate runs the TypeScript emitter and then prettier --write
over the generated directory, which is exactly what CI re-runs when it checks
that the committed output is current. tsp:compile alone skips the formatting
pass and will leave the tree looking stale.
// tsp/domain/entities/settings.tsp
import "../common/base.tsp";
import "../common/enums/log-level.tsp";
/**
* Global application settings (singleton).
* Stored at ~/.shep/data as single SQLite record.
*/
model Settings extends BaseEntity {
/** Singleton ID (always 'singleton') */
id: "singleton";
/** Model configuration for different agents */
models: ModelConfiguration;
/** User profile information (optional) */
user: UserProfile;
/** Environment configuration */
environment: EnvironmentConfig;
/** System configuration */
system: SystemConfig;
}
/**
* AI model configuration for different agents.
*/
model ModelConfiguration {
/** Model for analyze agent (e.g., 'claude-opus-4') */
analyze: string;
/** Model for requirements agent */
requirements: string;
/** Model for plan agent */
plan: string;
/** Model for implementation agent */
implement: string;
}
/**
* User profile information.
*/
model UserProfile {
/** User's full name */
name?: string;
/** User's email address */
email?: string;
/** GitHub username */
githubUsername?: string;
}
/**
* Environment configuration.
*/
model EnvironmentConfig {
/** Default text editor (vim, nano, code, etc.) */
defaultEditor: string;
/** Preferred shell (bash, zsh, fish, etc.) */
shellPreference: string;
}
/**
* System configuration.
*/
model SystemConfig {
/** Enable automatic updates */
autoUpdate: boolean;
/** Logging level */
logLevel: LogLevel;
}
// tsp/common/enums/log-level.tsp
/**
* Logging level for system output.
*/
enum LogLevel {
/** Debug level logging (most verbose) */
debug,
/** Informational messages */
info,
/** Warning messages */
warn,
/** Error messages only */
error,
}
// tsp/common/base.tsp
/**
* Base entity with ID and timestamps.
* All entities should extend this model.
*/
model BaseEntity {
/** Unique identifier */
id: string;
/** Creation timestamp */
@encode(DateTimeKnownEncoding.rfc3339)
createdAt: utcDateTime;
/** Last update timestamp */
@encode(DateTimeKnownEncoding.rfc3339)
updatedAt: utcDateTime;
}
/**
* Entity with soft delete support.
*/
model SoftDeletableEntity extends BaseEntity {
/** Soft delete flag */
isDeleted: boolean = false;
/** Deletion timestamp (null if not deleted) */
@encode(DateTimeKnownEncoding.rfc3339)
deletedAt?: utcDateTime;
}
main.tsp imports only the five top-level barrels, so a new file is registered
in the index.tsp of the directory it lives in β not in main.tsp.
// tsp/domain/entities/index.tsp
import "./feature.tsp";
import "./epic.tsp";
import "./settings.tsp"; // NEW
// tsp/main.tsp β unchanged when you add an entity
import "./common/index.tsp";
import "./domain/index.tsp";
import "./agents/index.tsp";
import "./deployment/index.tsp";
import "./ui/index.tsp";
@service(#{ title: "Shep AI Domain Models" })
namespace ShepAI.Domain;
# Generate TypeScript + OpenAPI + JSON Schema, then format the output
pnpm generate
# Verify generated output
grep "export interface Settings" packages/core/src/domain/generated/output.ts
// packages/core/src/application/use-cases/settings/initialize-settings.use-case.ts
import type { Settings } from '@/domain/generated/output.js';
import type { ISettingsRepository } from '@/application/ports/output/repositories/settings.repository.interface.js';
export class InitializeSettingsUseCase {
constructor(private readonly settingsRepository: ISettingsRepository) {}
async execute(): Promise<Settings> {
// Check if settings already exist
const existing = await this.settingsRepository.load();
if (existing !== null) {
return existing;
}
// Create default settings (using generated type)
const defaults: Settings = {
id: 'singleton',
createdAt: new Date(),
updatedAt: new Date(),
models: {
analyze: 'claude-opus-4',
requirements: 'claude-sonnet-4',
plan: 'claude-sonnet-4',
implement: 'claude-sonnet-4',
},
user: {},
environment: {
defaultEditor: 'vim',
shellPreference: 'bash',
},
system: {
autoUpdate: true,
logLevel: 'info',
},
};
// Initialize in repository
await this.settingsRepository.initialize(defaults);
return defaults;
}
}
β
Good: tsp/domain/entities/feature.tsp (one model)
β
Good: tsp/domain/entities/task.tsp (one model)
β Bad: tsp/domain/entities.tsp (all models in one file)
/**
* Feature entity tracking work through SDLC lifecycle.
* Represents a unit of work from requirements to deployment.
*/
model Feature extends BaseEntity {
/** Human-readable feature name */
name: string;
/** Detailed feature description */
description: string;
/** Current SDLC lifecycle phase */
lifecycle: SdlcLifecycle;
/** Repository path this feature belongs to */
repoPath: string;
}
// Good: Enum for fixed set of values
enum SdlcLifecycle {
Requirements,
Plan,
Implementation,
Test,
Deploy,
Maintenance,
}
// Bad: String with no validation
model Feature {
lifecycle: string; // Could be anything!
}
model UserProfile {
// Optional fields with ?
name?: string;
email?: string;
// Required field (no ?)
createdAt: utcDateTime;
}
// Good: Extend BaseEntity for consistency
model Settings extends BaseEntity {
// Inherits: id, createdAt, updatedAt
models: ModelConfiguration;
}
// Bad: Duplicate fields
model Settings {
id: string;
createdAt: utcDateTime; // Duplicate!
updatedAt: utcDateTime; // Duplicate!
models: ModelConfiguration;
}
model BaseEntity {
/** Creation timestamp (RFC 3339 format) */
@encode(DateTimeKnownEncoding.rfc3339)
createdAt: utcDateTime;
}
// Generated TypeScript:
// createdAt: string; (ISO 8601 string)
model LegacyFeature {
name: string;
/** @deprecated Use 'description' instead */
@deprecated("Use 'description' instead")
summary: string;
description: string;
}
model Settings {
/** Default text editor
* @example "vim"
* @example "code"
*/
defaultEditor: string;
}
// tsp/domain/entities/settings.tsp
model Settings extends BaseEntity {
// ... existing fields ...
/** NEW: Telemetry opt-out flag */
telemetryEnabled: boolean = true; // Default value
}
Workflow:
.tsp filepnpm tsp:compile β Regenerate TypeScript.tsp and generated files// tsp/domain/entities/settings.tsp
model Settings extends BaseEntity {
// ... existing fields ...
// REMOVED: oldField: string; β Delete this line
}
Workflow:
.tsp filepnpm tsp:compile β TypeScript compile errors appear// Before
model Settings {
editorPreference: string;
}
// After
model Settings {
defaultEditor: string;
}
Workflow:
@deprecatedpnpm tsp:compilepnpm tsp:compile again| Script | Command |
|---|---|
generate |
pnpm tsp:codegen β the one you want before committing |
tsp:codegen |
tsp compile tsp/ --emit @typespec-tools/emitter-typescript && prettier --write packages/core/src/domain/generated/ |
tsp:compile |
tsp compile tsp/ β runs every emitter in tspconfig.yaml, no formatting pass |
lint:tsp |
tsp compile tsp/ --no-emit β validate only, emit nothing |
tsp:format |
tsp format "tsp/**/*.tsp" (format:tsp is the same command) |
tsp:watch |
tsp compile tsp/ --watch |
validate |
lint:fix β format β typecheck β tsp:compile |
# Regenerate + format (what CI verifies)
pnpm generate
# Validate without emitting anything
pnpm lint:tsp
# Watch mode (recompile on changes)
pnpm tsp:watch
# Format TypeSpec sources
pnpm tsp:format
# Full local check before pushing
pnpm validate
Cause: Model name conflicts with existing type.
Solution: Rename the model or use namespace:
namespace Settings {
model Configuration {
// ...
}
}
Cause: Missing or out-of-date TypeSpec dependencies.
Solution: reinstall first β the toolchain is already declared in
devDependencies (@typespec/compiler, @typespec/json-schema,
@typespec/openapi3, @typespec/protobuf,
@typespec/prettier-plugin-typespec and @typespec-tools/emitter-typescript).
pnpm install
Only add a package if you are genuinely introducing a new library (for example
@typespec/http, which this project does not currently use).
Cause: Cached compilation output.
Solution:
# Clear generated output
rm -rf apis/ packages/core/src/domain/generated/
# Recompile
pnpm tsp:compile
Cause: Breaking change in domain model (expected behavior).
Solution:
TypeSpec compilation runs in CI pipeline:
The Lint & Format job runs pnpm tsp:compile to prove the TypeSpec still
compiles. The Type Check job is the one that catches stale generated output:
# .github/workflows/ci.yml β typecheck job
- run: pnpm run generate
- name: Verify generated code is committed
run: |
if ! git diff --exit-code -- packages/core/src/domain/generated apis; then
echo "::error::Generated output is stale. Run 'pnpm run generate' and commit the result."
exit 1
fi
- run: pnpm run typecheck
The pre-commit hook runs pnpm generate and stages
apis/json-schema/ and packages/core/src/domain/generated/ for you, so in
practice this only fires when the hook was bypassed.
IMPORTANT: Always commit generated files (packages/core/src/domain/generated/output.ts) to version control. This ensures:
Update when:
Related files:
tsp/ - TypeSpec source filestspconfig.yaml - TypeSpec configurationpackage.json - TypeSpec dependencies and scripts