---
description: Development standards and conventions for the core-db package
globs: src/**/*.ts
alwaysApply: true
---

# Development Standards

This package provides a centralized database layer for multiple domains (TalkPilot and Municipal). Follow these rules to maintain consistency and reliability.

## Project Structure

- **`src/talkpilot/`**: All database logic, types, and getters related to the TalkPilot domain.
- **`src/municipal/`**: All database logic, types, and getters related to the Municipal Data domain.
- **`src/test-utils/`**: Shared testing infrastructure, including factories and database utilities.

## Database Connection Pattern

Each domain is isolated. They have their own `db` instance and must be connected independently.

```typescript
import { mongodbClient, municipalDataMongodbClient } from '@talkpilot/core-db';

// TalkPilot
await mongodbClient.connect(uri);

// Municipal
await municipalDataMongodbClient.connect(uri);
```

## Creating New Getters

1. **Location**: Place getters in the relevant domain folder (e.g., `src/talkpilot/agents/agents.getters.ts`).
2. **Naming**: Use `find...` for multiple results and `get...ById` for single results.
3. **Domain isolation**: Always use the `getDb()` function from the current domain's `index.ts`.

## Environment Validation

Always validate configuration "on-demand" within the `connect` methods using the validation utilities.

```typescript
import { validateConfig, validateMongoUri } from '../utils/validation';

async connect(uri?: string) {
  const mongodbUri = uri || process.env.MONGO_URI;
  validateConfig('MONGO_URI', mongodbUri);
  validateMongoUri(mongodbUri!);
  // ... connection logic
}
```

## Testing Standards

1. **In-Memory DB**: Use `mongodb-memory-server` for all tests. It is automatically initialized in `src/__tests__/setup.ts`.
2. **Factories**: Use the Fishery factories in `src/test-utils/factories/` to generate test data.
3. **Organization**: Place tests in a `__tests__` folder within the relevant domain.

```typescript
import { createAgent } from '../../../test-utils/factories';

it('should find agents', async () => {
  const agent = createAgent({ name: 'Test' });
  // ... test logic
});
```
