@talkpilot/core-db 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,65 +1,65 @@
1
- ---
2
- description: Development standards and conventions for the core-db package
3
- globs: src/**/*.ts
4
- alwaysApply: true
5
- ---
6
-
7
- # Development Standards
8
-
9
- This package provides a centralized database layer for multiple domains (TalkPilot and Municipal). Follow these rules to maintain consistency and reliability.
10
-
11
- ## Project Structure
12
-
13
- - **`src/talkpilot/`**: All database logic, types, and getters related to the TalkPilot domain.
14
- - **`src/municipal/`**: All database logic, types, and getters related to the Municipal Data domain.
15
- - **`src/test-utils/`**: Shared testing infrastructure, including factories and database utilities.
16
-
17
- ## Database Connection Pattern
18
-
19
- Each domain is isolated. They have their own `db` instance and must be connected independently.
20
-
21
- ```typescript
22
- import { mongodbClient, municipalDataMongodbClient } from '@talkpilot/core-db';
23
-
24
- // TalkPilot
25
- await mongodbClient.connect(uri);
26
-
27
- // Municipal
28
- await municipalDataMongodbClient.connect(uri);
29
- ```
30
-
31
- ## Creating New Getters
32
-
33
- 1. **Location**: Place getters in the relevant domain folder (e.g., `src/talkpilot/agents/agents.getters.ts`).
34
- 2. **Naming**: Use `find...` for multiple results and `get...ById` for single results.
35
- 3. **Domain isolation**: Always use the `getDb()` function from the current domain's `index.ts`.
36
-
37
- ## Environment Validation
38
-
39
- Always validate configuration "on-demand" within the `connect` methods using the validation utilities.
40
-
41
- ```typescript
42
- import { validateConfig, validateMongoUri } from '../utils/validation';
43
-
44
- async connect(uri?: string) {
45
- const mongodbUri = uri || process.env.MONGO_URI;
46
- validateConfig('MONGO_URI', mongodbUri);
47
- validateMongoUri(mongodbUri!);
48
- // ... connection logic
49
- }
50
- ```
51
-
52
- ## Testing Standards
53
-
54
- 1. **In-Memory DB**: Use `mongodb-memory-server` for all tests. It is automatically initialized in `src/__tests__/setup.ts`.
55
- 2. **Factories**: Use the Fishery factories in `src/test-utils/factories/` to generate test data.
56
- 3. **Organization**: Place tests in a `__tests__` folder within the relevant domain.
57
-
58
- ```typescript
59
- import { createAgent } from '../../../test-utils/factories';
60
-
61
- it('should find agents', async () => {
62
- const agent = createAgent({ name: 'Test' });
63
- // ... test logic
64
- });
65
- ```
1
+ ---
2
+ description: Development standards and conventions for the core-db package
3
+ globs: src/**/*.ts
4
+ alwaysApply: true
5
+ ---
6
+
7
+ # Development Standards
8
+
9
+ This package provides a centralized database layer for multiple domains (TalkPilot and Municipal). Follow these rules to maintain consistency and reliability.
10
+
11
+ ## Project Structure
12
+
13
+ - **`src/talkpilot/`**: All database logic, types, and getters related to the TalkPilot domain.
14
+ - **`src/municipal/`**: All database logic, types, and getters related to the Municipal Data domain.
15
+ - **`src/test-utils/`**: Shared testing infrastructure, including factories and database utilities.
16
+
17
+ ## Database Connection Pattern
18
+
19
+ Each domain is isolated. They have their own `db` instance and must be connected independently.
20
+
21
+ ```typescript
22
+ import { mongodbClient, municipalDataMongodbClient } from '@talkpilot/core-db';
23
+
24
+ // TalkPilot
25
+ await mongodbClient.connect(uri);
26
+
27
+ // Municipal
28
+ await municipalDataMongodbClient.connect(uri);
29
+ ```
30
+
31
+ ## Creating New Getters
32
+
33
+ 1. **Location**: Place getters in the relevant domain folder (e.g., `src/talkpilot/agents/agents.getters.ts`).
34
+ 2. **Naming**: Use `find...` for multiple results and `get...ById` for single results.
35
+ 3. **Domain isolation**: Always use the `getDb()` function from the current domain's `index.ts`.
36
+
37
+ ## Environment Validation
38
+
39
+ Always validate configuration "on-demand" within the `connect` methods using the validation utilities.
40
+
41
+ ```typescript
42
+ import { validateConfig, validateMongoUri } from '../utils/validation';
43
+
44
+ async connect(uri?: string) {
45
+ const mongodbUri = uri || process.env.MONGO_URI;
46
+ validateConfig('MONGO_URI', mongodbUri);
47
+ validateMongoUri(mongodbUri!);
48
+ // ... connection logic
49
+ }
50
+ ```
51
+
52
+ ## Testing Standards
53
+
54
+ 1. **In-Memory DB**: Use `mongodb-memory-server` for all tests. It is automatically initialized in `src/__tests__/setup.ts`.
55
+ 2. **Factories**: Use the Fishery factories in `src/test-utils/factories/` to generate test data.
56
+ 3. **Organization**: Place tests in a `__tests__` folder within the relevant domain.
57
+
58
+ ```typescript
59
+ import { createAgent } from '../../../test-utils/factories';
60
+
61
+ it('should find agents', async () => {
62
+ const agent = createAgent({ name: 'Test' });
63
+ // ... test logic
64
+ });
65
+ ```
package/DEVELOPMENT.md CHANGED
@@ -1,98 +1,98 @@
1
- # Development Guide
2
-
3
- Welcome to the `core-db` development guide. This document explains how to set up, develop, and test this package.
4
-
5
- ## Getting Started
6
-
7
- ### Prerequisites
8
-
9
- - Node.js (v18 or later)
10
- - TypeScript
11
-
12
- ### Setup
13
-
14
- 1. Install dependencies:
15
- ```bash
16
- npm install
17
- ```
18
-
19
- 2. Build the project:
20
- ```bash
21
- npm run build
22
- ```
23
-
24
- ## Local Development
25
-
26
- If you want to use this package in another project locally without publishing it:
27
-
28
- 1. In the `core-db` folder:
29
- ```bash
30
- npm link
31
- ```
32
-
33
- 2. In your PROJECT folder:
34
- ```bash
35
- npm link @talkpilot/core-db
36
- ```
37
-
38
- ## Adding a New Getter
39
-
40
- 1. **Define Types**: Add your data types in the relevant domain's `types.ts` file.
41
- 2. **Implement Getter**: Add the function in the `getters.ts` file.
42
- 3. **Export**: Ensure the getter is exported from the domain's `index.ts` and finally from the main `src/index.ts`.
43
- 4. **Test**: Create a test in the domain's `__tests__` folder.
44
-
45
- ## Testing
46
-
47
- We use Jest with `mongodb-memory-server` for fast, isolated database tests.
48
-
49
- ### Running Tests
50
-
51
- ```bash
52
- npm test
53
- ```
54
-
55
- ### Using Factories
56
-
57
- Always use factories to generate test data to keep tests clean and maintainable.
58
-
59
- ```typescript
60
- import { createCallDoc } from '../calls.getters';
61
- import { createOutGoingCallDoc } from '../../../test-utils/factories';
62
-
63
- it('should save a call', async () => {
64
- const call = createOutGoingCallDoc({ callSid: 'CA123' });
65
- await createCallDoc(call);
66
- // ... assertions
67
- });
68
- ```
69
-
70
- ## Build Process
71
-
72
- The project is built using TypeScript (`tsc`). The output is generated in the `dist/` directory.
73
-
74
- - `main`: `dist/index.js`
75
- - `types`: `dist/index.d.ts`
76
-
77
- The `prepare` script in `package.json` ensures that the project is built automatically when installed via a Git URL.
78
-
79
- ## Team Access & Authentication
80
-
81
- To allow the whole team to publish and install without adding individual npm accounts, we use a shared **npm Granular Access Token**.
82
-
83
- ### One-time Local Setup
84
-
85
- Each developer needs to add the shared token to their local npm configuration. Do **NOT** add this to the project's `.npmrc` file, as it will be committed to Git.
86
-
87
- 1. Get the shared **npm Automation Token**.
88
- 2. Open (or create) your global npm configuration file:
89
- ```bash
90
- nano ~/.npmrc
91
- ```
92
- 3. Add the following line (replace `[TOKEN]` with the actual token):
93
- ```text
94
- //registry.npmjs.org/:_authToken=[TOKEN]
95
- ```
96
- 4. Save and exit.
97
-
98
- Now you can run `npm publish` and `npm install` for scoped `@talkpilot` packages without being prompted for credentials.
1
+ # Development Guide
2
+
3
+ Welcome to the `core-db` development guide. This document explains how to set up, develop, and test this package.
4
+
5
+ ## Getting Started
6
+
7
+ ### Prerequisites
8
+
9
+ - Node.js (v18 or later)
10
+ - TypeScript
11
+
12
+ ### Setup
13
+
14
+ 1. Install dependencies:
15
+ ```bash
16
+ npm install
17
+ ```
18
+
19
+ 2. Build the project:
20
+ ```bash
21
+ npm run build
22
+ ```
23
+
24
+ ## Local Development
25
+
26
+ If you want to use this package in another project locally without publishing it:
27
+
28
+ 1. In the `core-db` folder:
29
+ ```bash
30
+ npm link
31
+ ```
32
+
33
+ 2. In your PROJECT folder:
34
+ ```bash
35
+ npm link @talkpilot/core-db
36
+ ```
37
+
38
+ ## Adding a New Getter
39
+
40
+ 1. **Define Types**: Add your data types in the relevant domain's `types.ts` file.
41
+ 2. **Implement Getter**: Add the function in the `getters.ts` file.
42
+ 3. **Export**: Ensure the getter is exported from the domain's `index.ts` and finally from the main `src/index.ts`.
43
+ 4. **Test**: Create a test in the domain's `__tests__` folder.
44
+
45
+ ## Testing
46
+
47
+ We use Jest with `mongodb-memory-server` for fast, isolated database tests.
48
+
49
+ ### Running Tests
50
+
51
+ ```bash
52
+ npm test
53
+ ```
54
+
55
+ ### Using Factories
56
+
57
+ Always use factories to generate test data to keep tests clean and maintainable.
58
+
59
+ ```typescript
60
+ import { createCallDoc } from '../calls.getters';
61
+ import { createOutGoingCallDoc } from '../../../test-utils/factories';
62
+
63
+ it('should save a call', async () => {
64
+ const call = createOutGoingCallDoc({ callSid: 'CA123' });
65
+ await createCallDoc(call);
66
+ // ... assertions
67
+ });
68
+ ```
69
+
70
+ ## Build Process
71
+
72
+ The project is built using TypeScript (`tsc`). The output is generated in the `dist/` directory.
73
+
74
+ - `main`: `dist/index.js`
75
+ - `types`: `dist/index.d.ts`
76
+
77
+ The `prepare` script in `package.json` ensures that the project is built automatically when installed via a Git URL.
78
+
79
+ ## Team Access & Authentication
80
+
81
+ To allow the whole team to publish and install without adding individual npm accounts, we use a shared **npm Granular Access Token**.
82
+
83
+ ### One-time Local Setup
84
+
85
+ Each developer needs to add the shared token to their local npm configuration. Do **NOT** add this to the project's `.npmrc` file, as it will be committed to Git.
86
+
87
+ 1. Get the shared **npm Automation Token**.
88
+ 2. Open (or create) your global npm configuration file:
89
+ ```bash
90
+ nano ~/.npmrc
91
+ ```
92
+ 3. Add the following line (replace `[TOKEN]` with the actual token):
93
+ ```text
94
+ //registry.npmjs.org/:_authToken=[TOKEN]
95
+ ```
96
+ 4. Save and exit.
97
+
98
+ Now you can run `npm publish` and `npm install` for scoped `@talkpilot` packages without being prompted for credentials.
package/README.md CHANGED
@@ -1,139 +1,139 @@
1
- L1:# @talkpilot/core-db
2
-
3
- `@talkpilot/core-db` is the shared TypeScript database package that wires TalkPilot APIs, municipal CRM integrations, and internal tools to a single, type-safe MongoDB surface. Every repo (MIS, CIS, TalkPilot Server, etc.) imports this package to avoid re-implementing connections, collections, or validation helpers.
4
-
5
- ## Purpose
6
-
7
- - Provide a reliable, multi-domain MongoDB layer for TalkPilot and municipal data.
8
- - Export typed getters, vector search helpers, and document factories so services can focus on behavior instead of schema wiring.
9
- - Manage connection lifecycles, environment configuration, and test helpers from one place so every repo reuses the same plumbing.
10
-
11
- ## Main Concepts
12
-
13
- - **Multi-domain clients** – `src/connection.ts` exposes `mongodbClient` (TalkPilot) and `municipalDataMongodbClient`, each of which resolves `MONGO_URI`, DB overrides, and default names.
14
- - **Domain-specific getters** – `src/talkpilot/` and `src/municipal/` host typed getters (agents, calls, streets, tickets, etc.), vector-search helpers, and service-friendly adapters that keep caller code DRY.
15
- - **Product-specific clients (future)** – While the package currently exposes the shared TalkPilot + municipal clients, we expect each product (CIS, MIS, TalkPilot Server) to eventually get its own domain-specific client helpers or wrappers so the shared core can remain stable while new consumers add targeted extensions.
16
- - **Test helpers** – `src/test-utils/` plus `src/__tests__/` reuse `MongoMemoryServer` and shared factories so tests start with clean data regardless of the consuming repo.
17
- - **Utility layers** – `src/utils/` contains shared validation, pagination, and environment helpers that complement the getters.
18
- - **Environment awareness** – Defaults, fallbacks, and `process.env` lookups ensure local, CI, and Cloud Run clients all connect using the right URI/DB names.
19
-
20
- ## Key Components
21
-
22
- - `src/connection.ts` – Central connection logic that resolves URIs/DB names from env vars (`MONGO_URI`, `MONGODB_URI`, `TALKPILOT_DB_NAME`, `MUNICIPAL_DB_NAME`) and reuses a single `MongoClient`.
23
- - `src/talkpilot/` – Call history, agents, flows, sessions, leads, subscriptions, and support helpers exposed as getters plus helper enums/types for each collection.
24
- - `src/municipal/` – Municipal-specific collections (`cities`, `streets`, `departmentsSubjects`, `tickets`, etc.) plus vector search helpers and Ash Bina helpers used by MIS.
25
- - `src/utils/` – Shared helpers such as `resolveConnection`, pagination utilities, and schema validation helper functions.
26
- - `src/test-utils/` and `src/__tests__/` – Utilities that bootstrap `MongoMemoryServer`, expose factories, and make sure Jest environments can stub database calls predictably.
27
- - `dist/` – Compiled output consumed by downstream repos (CJS + ESM + type defs).
28
-
29
- ## Domain APIs
30
-
31
- - **TalkPilot domain** – Imports like `findAgents`, `getFlows`, `findCalls`, and `vectorSearchCalls` live in `src/talkpilot`. These functions are the canonical access pattern for call history, session metadata, and provider configs.
32
- - **Municipal domain** – Helpers such as `findStreets`, `getMunicipalCities`, `findDepartmentSubjects`, and `createTicket` live under `src/municipal` and feed MIS workflows (street hints, subject matching, Ash Bina tickets).
33
-
34
- ## Environment variables
35
-
36
- | Variable | Purpose | Required |
37
- |---------------------------|--------------------------------------------------------------------------------------|----------|
38
- | `MONGO_URI` | Primary MongoDB connection string for every domain (overridden by `MONGODB_URI`). | ✅ |
39
- | `MONGODB_URI` | Alternate connection string used when Mongo needs a second URI parameter. | ✅ |
40
- | `TALKPILOT_DB_NAME` | Optional override for the TalkPilot database name (defaults from URI path). | ❌ |
41
- | `MUNICIPAL_DB_NAME` | Optional override for the municipal database name (defaults to `municipal-data`). | ❌ |
42
- | `ENV` | Free-form label used in logs/validators (defaults to `unknown`). | ❌ |
43
-
44
- If you pass a `uri` directly to `mongodbClient.connect()` or `municipalDataMongodbClient.connect()`, the client will prefer that value over the env vars.
45
-
46
- ## Getting Started
47
-
48
- ### Prerequisites
49
-
50
- - Node.js 22.x+ (aligns with downstream services).
51
- - npm 11+ or Yarn.
52
- - MongoDB accessible from your environment or a `MongoMemoryServer` for tests.
53
-
54
- ### Setup
55
-
56
- 1. Clone the repo and install dependencies:
57
-
58
- ```bash
59
- git clone https://github.com/talkpilot/core-db.git
60
- cd core-db
61
- npm install
62
- ```
63
-
64
- 2. Build the package before using it locally:
65
-
66
- ```bash
67
- npm run build
68
- ```
69
-
70
- 3. Import `@talkpilot/core-db` from another project by pointing `package.json` at the local path during development or installing the published release.
71
-
72
- ## Sample `.env`
73
-
74
- ```
75
- MONGO_URI=mongodb://localhost:27017
76
- TALKPILOT_DB_NAME=talkpilot-dev
77
- MUNICIPAL_DB_NAME=municipal-dev
78
- ENV=development
79
- ```
80
-
81
- Adjust `MONGO_URI` to match the running Mongo instance and configure `talkpilot`/`municipal` DB names if you want to keep them separate.
82
-
83
- ## Local development
84
-
85
- 1. Run `npm install`.
86
- 2. Build the compiled output: `npm run build`.
87
- 3. Execute tests: `npm run test`.
88
- 4. Use `npm link` or `npm pack` to consume the freshly built package from other repos (`CIS`, `MIS`, `TalkPilot Server`).
89
-
90
- ## Development guide
91
-
92
- `DEVELOPMENT.md` contains the tactical steps for contributors. At a glance:
93
-
94
- - Node 18+/TypeScript is required (aligns with downstream services).
95
- - Run `npm install` → `npm run build` after cloning.
96
- - Use `npm link`/`npm link @talkpilot/core-db` to test the package locally before publishing.
97
- - When adding getters, define types, implement the function, export it through the domain `index.ts`, and add a corresponding test under the domain’s `__tests__` folder.
98
- - Always rely on the provided test factories (`src/test-utils/factories`) to seed data so tests remain consistent.
99
- - Jest with `mongodb-memory-server` is the only execution path we have to verify this core utility—unit tests are the safety net for every change.
100
-
101
- Refer to `DEVELOPMENT.md` for the full walkthrough, token instructions, and factory samples.
102
-
103
- ## 🧪 Testing
104
-
105
- - `npm run test` – Jest suite (factories, utils, integration mocks) powered by `mongodb-memory-server`.
106
- - Tests rely on `src/__tests__/setup.ts` to bootstrap the in-memory Mongo instances and wire shared factories/helpers before each run.
107
- - When adding getters, helpers, or domain logic, create focused coverage inside the consuming domain’s `__tests__/` folder and use the provided factories to keep fixtures consistent.
108
-
109
- `@talkpilot/core-db` does not run in a product UI or feature branch—unit tests are the *only* reliable execution path to ensure your changes work. Every change must ship with a unit test so downstream repos can upgrade without surprises; treat the test suite as the canonical safety net for this core utility package.
110
-
111
- ## 🧹 Lint & build verification
112
-
113
- - `npm run lint` – Run ESLint over `src/**/*.{ts,tsx}`.
114
- - `npm run format` – Format the source files with Prettier.
115
- - `npm run build` – Compile TypeScript and emit `dist/` (used by downstream consumers).
116
-
117
- ## ✅ Pre-push checklist
118
-
119
- 1. `npm run build`.
120
- 2. `npm run test`.
121
- 3. `npm run format`.
122
-
123
- ## Publishing & release notes
124
-
125
- - Releases are handled by `npm version <patch|minor|major>` followed by `npm publish`. The package is a **private `@talkpilot` dependency**, so every contributor must install the shared npm automation token into their global `~/.npmrc` before running publish or `npm install`.
126
- - The shared token is rotated periodically—if you see authentication failures, request the refreshed token, update your `~/.npmrc`, and retry. Never commit credentials to source control.
127
- - After publishing, downstream repos (`CIS`, `MIS`, `TalkPilot Server`, etc.) should run `npm update @talkpilot/core-db` so they receive the latest helpers/bug fixes.
128
- - Cloud Build & Cloud Run jobs that depend on this package pick up the new version the next time they rebuild their container; the services pull the compiled `dist/` output and type definitions when installing the dependency.
129
-
130
- ## 🛠 CI/CD & deployment
131
-
132
- - This package is consumed by Cloud Build-based services (TalkPilot Server, MIS, CIS) as a dependency when Docker images are built. Keep `dist/` in sync with your builds because the compiled artifact is what downstream services install.
133
- - Releases require the shared npm token documented in `DEVELOPMENT.md`; consult that guide for contribution, linking, and token rotation procedures.
134
-
135
- ## Resources
136
-
137
- - [DEVELOPMENT.md](./DEVELOPMENT.md) (setup, tooling, publishing, token management)
138
- - [src/test-utils](src/test-utils) and the `__tests__` folder for examples of `MongoMemoryServer` wiring.
139
-
1
+ L1:# @talkpilot/core-db
2
+
3
+ `@talkpilot/core-db` is the shared TypeScript database package that wires TalkPilot APIs, municipal CRM integrations, and internal tools to a single, type-safe MongoDB surface. Every repo (MIS, CIS, TalkPilot Server, etc.) imports this package to avoid re-implementing connections, collections, or validation helpers.
4
+
5
+ ## Purpose
6
+
7
+ - Provide a reliable, multi-domain MongoDB layer for TalkPilot and municipal data.
8
+ - Export typed getters, vector search helpers, and document factories so services can focus on behavior instead of schema wiring.
9
+ - Manage connection lifecycles, environment configuration, and test helpers from one place so every repo reuses the same plumbing.
10
+
11
+ ## Main Concepts
12
+
13
+ - **Multi-domain clients** – `src/connection.ts` exposes `mongodbClient` (TalkPilot) and `municipalDataMongodbClient`, each of which resolves `MONGO_URI`, DB overrides, and default names.
14
+ - **Domain-specific getters** – `src/talkpilot/` and `src/municipal/` host typed getters (agents, calls, streets, tickets, etc.), vector-search helpers, and service-friendly adapters that keep caller code DRY.
15
+ - **Product-specific clients (future)** – While the package currently exposes the shared TalkPilot + municipal clients, we expect each product (CIS, MIS, TalkPilot Server) to eventually get its own domain-specific client helpers or wrappers so the shared core can remain stable while new consumers add targeted extensions.
16
+ - **Test helpers** – `src/test-utils/` plus `src/__tests__/` reuse `MongoMemoryServer` and shared factories so tests start with clean data regardless of the consuming repo.
17
+ - **Utility layers** – `src/utils/` contains shared validation, pagination, and environment helpers that complement the getters.
18
+ - **Environment awareness** – Defaults, fallbacks, and `process.env` lookups ensure local, CI, and Cloud Run clients all connect using the right URI/DB names.
19
+
20
+ ## Key Components
21
+
22
+ - `src/connection.ts` – Central connection logic that resolves URIs/DB names from env vars (`MONGO_URI`, `MONGODB_URI`, `TALKPILOT_DB_NAME`, `MUNICIPAL_DB_NAME`) and reuses a single `MongoClient`.
23
+ - `src/talkpilot/` – Call history, agents, flows, sessions, leads, subscriptions, and support helpers exposed as getters plus helper enums/types for each collection.
24
+ - `src/municipal/` – Municipal-specific collections (`cities`, `streets`, `departmentsSubjects`, `tickets`, etc.) plus vector search helpers and Ash Bina helpers used by MIS.
25
+ - `src/utils/` – Shared helpers such as `resolveConnection`, pagination utilities, and schema validation helper functions.
26
+ - `src/test-utils/` and `src/__tests__/` – Utilities that bootstrap `MongoMemoryServer`, expose factories, and make sure Jest environments can stub database calls predictably.
27
+ - `dist/` – Compiled output consumed by downstream repos (CJS + ESM + type defs).
28
+
29
+ ## Domain APIs
30
+
31
+ - **TalkPilot domain** – Imports like `findAgents`, `getFlows`, `findCalls`, and `vectorSearchCalls` live in `src/talkpilot`. These functions are the canonical access pattern for call history, session metadata, and provider configs.
32
+ - **Municipal domain** – Helpers such as `findStreets`, `getMunicipalCities`, `findDepartmentSubjects`, and `createTicket` live under `src/municipal` and feed MIS workflows (street hints, subject matching, Ash Bina tickets).
33
+
34
+ ## Environment variables
35
+
36
+ | Variable | Purpose | Required |
37
+ |---------------------------|--------------------------------------------------------------------------------------|----------|
38
+ | `MONGO_URI` | Primary MongoDB connection string for every domain (overridden by `MONGODB_URI`). | ✅ |
39
+ | `MONGODB_URI` | Alternate connection string used when Mongo needs a second URI parameter. | ✅ |
40
+ | `TALKPILOT_DB_NAME` | Optional override for the TalkPilot database name (defaults from URI path). | ❌ |
41
+ | `MUNICIPAL_DB_NAME` | Optional override for the municipal database name (defaults to `municipal-data`). | ❌ |
42
+ | `ENV` | Free-form label used in logs/validators (defaults to `unknown`). | ❌ |
43
+
44
+ If you pass a `uri` directly to `mongodbClient.connect()` or `municipalDataMongodbClient.connect()`, the client will prefer that value over the env vars.
45
+
46
+ ## Getting Started
47
+
48
+ ### Prerequisites
49
+
50
+ - Node.js 22.x+ (aligns with downstream services).
51
+ - npm 11+ or Yarn.
52
+ - MongoDB accessible from your environment or a `MongoMemoryServer` for tests.
53
+
54
+ ### Setup
55
+
56
+ 1. Clone the repo and install dependencies:
57
+
58
+ ```bash
59
+ git clone https://github.com/talkpilot/core-db.git
60
+ cd core-db
61
+ npm install
62
+ ```
63
+
64
+ 2. Build the package before using it locally:
65
+
66
+ ```bash
67
+ npm run build
68
+ ```
69
+
70
+ 3. Import `@talkpilot/core-db` from another project by pointing `package.json` at the local path during development or installing the published release.
71
+
72
+ ## Sample `.env`
73
+
74
+ ```
75
+ MONGO_URI=mongodb://localhost:27017
76
+ TALKPILOT_DB_NAME=talkpilot-dev
77
+ MUNICIPAL_DB_NAME=municipal-dev
78
+ ENV=development
79
+ ```
80
+
81
+ Adjust `MONGO_URI` to match the running Mongo instance and configure `talkpilot`/`municipal` DB names if you want to keep them separate.
82
+
83
+ ## Local development
84
+
85
+ 1. Run `npm install`.
86
+ 2. Build the compiled output: `npm run build`.
87
+ 3. Execute tests: `npm run test`.
88
+ 4. Use `npm link` or `npm pack` to consume the freshly built package from other repos (`CIS`, `MIS`, `TalkPilot Server`).
89
+
90
+ ## Development guide
91
+
92
+ `DEVELOPMENT.md` contains the tactical steps for contributors. At a glance:
93
+
94
+ - Node 18+/TypeScript is required (aligns with downstream services).
95
+ - Run `npm install` → `npm run build` after cloning.
96
+ - Use `npm link`/`npm link @talkpilot/core-db` to test the package locally before publishing.
97
+ - When adding getters, define types, implement the function, export it through the domain `index.ts`, and add a corresponding test under the domain’s `__tests__` folder.
98
+ - Always rely on the provided test factories (`src/test-utils/factories`) to seed data so tests remain consistent.
99
+ - Jest with `mongodb-memory-server` is the only execution path we have to verify this core utility—unit tests are the safety net for every change.
100
+
101
+ Refer to `DEVELOPMENT.md` for the full walkthrough, token instructions, and factory samples.
102
+
103
+ ## 🧪 Testing
104
+
105
+ - `npm run test` – Jest suite (factories, utils, integration mocks) powered by `mongodb-memory-server`.
106
+ - Tests rely on `src/__tests__/setup.ts` to bootstrap the in-memory Mongo instances and wire shared factories/helpers before each run.
107
+ - When adding getters, helpers, or domain logic, create focused coverage inside the consuming domain’s `__tests__/` folder and use the provided factories to keep fixtures consistent.
108
+
109
+ `@talkpilot/core-db` does not run in a product UI or feature branch—unit tests are the *only* reliable execution path to ensure your changes work. Every change must ship with a unit test so downstream repos can upgrade without surprises; treat the test suite as the canonical safety net for this core utility package.
110
+
111
+ ## 🧹 Lint & build verification
112
+
113
+ - `npm run lint` – Run ESLint over `src/**/*.{ts,tsx}`.
114
+ - `npm run format` – Format the source files with Prettier.
115
+ - `npm run build` – Compile TypeScript and emit `dist/` (used by downstream consumers).
116
+
117
+ ## ✅ Pre-push checklist
118
+
119
+ 1. `npm run build`.
120
+ 2. `npm run test`.
121
+ 3. `npm run format`.
122
+
123
+ ## Publishing & release notes
124
+
125
+ - Releases are handled by `npm version <patch|minor|major>` followed by `npm publish`. The package is a **private `@talkpilot` dependency**, so every contributor must install the shared npm automation token into their global `~/.npmrc` before running publish or `npm install`.
126
+ - The shared token is rotated periodically—if you see authentication failures, request the refreshed token, update your `~/.npmrc`, and retry. Never commit credentials to source control.
127
+ - After publishing, downstream repos (`CIS`, `MIS`, `TalkPilot Server`, etc.) should run `npm update @talkpilot/core-db` so they receive the latest helpers/bug fixes.
128
+ - Cloud Build & Cloud Run jobs that depend on this package pick up the new version the next time they rebuild their container; the services pull the compiled `dist/` output and type definitions when installing the dependency.
129
+
130
+ ## 🛠 CI/CD & deployment
131
+
132
+ - This package is consumed by Cloud Build-based services (TalkPilot Server, MIS, CIS) as a dependency when Docker images are built. Keep `dist/` in sync with your builds because the compiled artifact is what downstream services install.
133
+ - Releases require the shared npm token documented in `DEVELOPMENT.md`; consult that guide for contribution, linking, and token rotation procedures.
134
+
135
+ ## Resources
136
+
137
+ - [DEVELOPMENT.md](./DEVELOPMENT.md) (setup, tooling, publishing, token management)
138
+ - [src/test-utils](src/test-utils) and the `__tests__` folder for examples of `MongoMemoryServer` wiring.
139
+