# AI Agent Guide for core-db

Ground truth for AI coding agents in this repository. This is `@talkpilot/core-db` — the only package that should talk to Mongo. `.cursor/rules/development.mdc` exists but may lag (TalkPilot + Municipal only); do not expand those rules in an unrelated ticket.

## What this is
Shared Mongo layer: typed getters, schemas, factories, indexes. Consumed by TalkPilot, municipal, WebsiteTalk, and clinic services. Publishing a version here is how other repos pick up schema/getter changes.

## Coding philosophy
- Strict TypeScript. No `any`; use `unknown` and narrow.
- No narrating comments.
- Split types, getters, and schemas into separate files.

## Project structure
- `src/talkpilot/` — calls, flows, sessions, clients, phone numbers, subscriptions, …
- `src/municipal/` — cities, streets, tickets, departmentsSubjects, …
- `src/websitalk/` — scans, scanResources, websiteUrls.
- `src/configuration/` — prompts, models.
- `src/test-utils/` — Fishery factories and test DB helpers.
- `src/utils/` — validation, pagination, shared types.
- `dist/` is what consumers import — generated, tests excluded from the build.

## Copy this
New getter: `src/<domain>/<entity>/<entity>.types.ts` + `<entity>.getter.ts` (or `*.getters.ts`) + optional `<entity>.schema.ts` + barrel `index.ts` + `__tests__/<entity>.spec.ts`.
Export it from `src/index.ts`.
Examples: `src/talkpilot/calls/calls.getters.ts`, `src/talkpilot/phone_numbers/phone_numbers.getter.ts`.

Naming: `find*` for many, `get*ById` (or equivalent single-doc) for one. Always use that domain’s `getDb()` / collection helper — never another domain’s client. Exception already on disk: `src/talkpilot/calls/calls.statistics.getters.ts` imports municipal `tickets.statistics.getters` — do not “clean that up.”

## Where data lives
This repo **owns** `mongodb`. Four isolated clients — connect each independently:

- `mongodbClient` — TalkPilot
- `municipalDataMongodbClient` — municipal
- `websitalkMongodbClient` — WebsiteTalk
- `configurationMongodbClient` — configuration

Do not cross-import getters across domains, except the talkpilot call-stats → municipal tickets exception above.

## Do / don't
- Do not put HTTP, Express, or business orchestration here.
- Validate `MONGO_URI` (and siblings) on demand in `connect()`, using `src/utils/validation`.
- After a getter/schema change: bump package version, build, publish; then bump the consumer. Downstream pins skew — do not assume they are on latest.
- `prepare` runs `build` on install.

## Siblings
Every Node service should call getters from here. If a service is about to `getDb().collection` or `import from 'mongodb'`, the getter belongs in this PR first.

## Tests
Jest + `mongodb-memory-server` (`src/__tests__/setup.ts`). Factories in `src/test-utils/factories/`. Colocate `__tests__/` under the domain.
