@talkpilot/core-db 1.2.1 → 1.2.2

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.
Files changed (74) hide show
  1. package/.cursor/rules/development.mdc +65 -65
  2. package/DEVELOPMENT.md +98 -98
  3. package/README.md +139 -160
  4. package/README_OLD.md +160 -0
  5. package/dist/talkpilot/calls/calls.dashboard.d.ts +3 -0
  6. package/dist/talkpilot/calls/calls.dashboard.d.ts.map +1 -0
  7. package/dist/talkpilot/calls/calls.dashboard.js +191 -0
  8. package/dist/talkpilot/calls/calls.dashboard.js.map +1 -0
  9. package/dist/talkpilot/calls/calls.getters.d.ts +3 -2
  10. package/dist/talkpilot/calls/calls.getters.d.ts.map +1 -1
  11. package/dist/talkpilot/calls/calls.getters.js +1 -2
  12. package/dist/talkpilot/calls/calls.getters.js.map +1 -1
  13. package/dist/talkpilot/calls/calls.types.d.ts +3 -7
  14. package/dist/talkpilot/calls/calls.types.d.ts.map +1 -1
  15. package/dist/talkpilot/calls/dashboard/calls.dashboard.d.ts +36 -0
  16. package/dist/talkpilot/calls/dashboard/calls.dashboard.d.ts.map +1 -0
  17. package/dist/talkpilot/calls/dashboard/calls.dashboard.js +208 -0
  18. package/dist/talkpilot/calls/dashboard/calls.dashboard.js.map +1 -0
  19. package/dist/talkpilot/calls/dashboard/calls.dashboard.types.d.ts +66 -0
  20. package/dist/talkpilot/calls/dashboard/calls.dashboard.types.d.ts.map +1 -0
  21. package/dist/talkpilot/calls/dashboard/calls.dashboard.types.js +3 -0
  22. package/dist/talkpilot/calls/dashboard/calls.dashboard.types.js.map +1 -0
  23. package/dist/talkpilot/calls/index.d.ts +1 -0
  24. package/dist/talkpilot/calls/index.d.ts.map +1 -1
  25. package/dist/talkpilot/calls/index.js +1 -0
  26. package/dist/talkpilot/calls/index.js.map +1 -1
  27. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts +2 -1
  28. package/dist/talkpilot/clientsConfig/clientsConfig.getters.d.ts.map +1 -1
  29. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js +14 -0
  30. package/dist/talkpilot/clientsConfig/clientsConfig.getters.js.map +1 -1
  31. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts +4 -1
  32. package/dist/talkpilot/clientsConfig/clientsConfig.types.d.ts.map +1 -1
  33. package/dist/talkpilot/clientsConfig/clientsConfig.types.js +6 -0
  34. package/dist/talkpilot/clientsConfig/clientsConfig.types.js.map +1 -1
  35. package/dist/talkpilot/flows/flows.schema.js +1 -1
  36. package/dist/talkpilot/phone_numbers/index.d.ts +2 -2
  37. package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts +1 -1
  38. package/dist/talkpilot/phone_numbers/phone_numbers.getter.d.ts.map +1 -1
  39. package/dist/talkpilot/phone_numbers/phone_numbers.getter.js +5 -3
  40. package/dist/talkpilot/phone_numbers/phone_numbers.getter.js.map +1 -1
  41. package/dist/talkpilot/phone_numbers/phone_numbers.schema.js +12 -12
  42. package/dist/talkpilot/phone_numbers/phone_numbers.types.d.ts +4 -4
  43. package/dist/talkpilot/results/results.getter.d.ts.map +1 -1
  44. package/dist/talkpilot/results/results.getter.js.map +1 -1
  45. package/dist/talkpilot/retry_analyze/retryAnalyze.getters.d.ts.map +1 -1
  46. package/dist/talkpilot/retry_analyze/retryAnalyze.getters.js.map +1 -1
  47. package/dist/utils/shared.types.d.ts +5 -0
  48. package/dist/utils/shared.types.d.ts.map +1 -0
  49. package/dist/utils/shared.types.js +3 -0
  50. package/dist/utils/shared.types.js.map +1 -0
  51. package/jest.config.js +19 -19
  52. package/package.json +46 -45
  53. package/src/talkpilot/calls/__tests__/calls.dashboard.spec.ts +46 -0
  54. package/src/talkpilot/calls/__tests__/calls.spec.ts +48 -30
  55. package/src/talkpilot/calls/calls.getters.ts +6 -6
  56. package/src/talkpilot/calls/calls.types.ts +10 -12
  57. package/src/talkpilot/calls/dashboard/calls.dashboard.ts +243 -0
  58. package/src/talkpilot/calls/dashboard/calls.dashboard.types.ts +70 -0
  59. package/src/talkpilot/calls/index.ts +1 -0
  60. package/src/talkpilot/clientsConfig/__tests__/clientsConfig.getters.spec.ts +53 -0
  61. package/src/talkpilot/clientsConfig/__tests__/clientsConfig.spec.ts +19 -9
  62. package/src/talkpilot/clientsConfig/clientsConfig.getters.ts +34 -1
  63. package/src/talkpilot/clientsConfig/clientsConfig.types.ts +9 -1
  64. package/src/talkpilot/flows/__tests__/flows.schema.spec.ts +6 -2
  65. package/src/talkpilot/flows/flows.schema.ts +1 -1
  66. package/src/talkpilot/phone_numbers/__tests__/phone_numbers.spec.ts +40 -35
  67. package/src/talkpilot/phone_numbers/index.ts +2 -2
  68. package/src/talkpilot/phone_numbers/phone_numbers.getter.ts +10 -6
  69. package/src/talkpilot/phone_numbers/phone_numbers.schema.ts +12 -12
  70. package/src/talkpilot/phone_numbers/phone_numbers.types.ts +4 -4
  71. package/src/talkpilot/results/results.getter.ts +6 -2
  72. package/src/talkpilot/retry_analyze/retryAnalyze.getters.ts +13 -4
  73. package/src/utils/shared.types.ts +4 -0
  74. package/tsconfig.json +23 -23
@@ -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,160 +1,139 @@
1
- # @talkpilot/core-db
2
-
3
- [NPM Version](https://www.npmjs.com/package/@talkpilot/core-db)
4
-
5
- A TypeScript-based core database management package designed to provide centralized database connections, ORM integrations, and client utilities for other projects. This package manages connections to both **TalkPilot** and **Municipal** MongoDB databases.
6
-
7
- ## Features
8
-
9
- - 🚀 **Multi-Domain Database Management**: Centralized handlers for both TalkPilot and Municipal Data domains.
10
- - 📦 **Reusable Getters**: Standardized functions for fetching data from various collections (calls, agents, leads, cities, etc.).
11
- - 🏗️ **Type-safe**: Built with TypeScript for full type safety across all your database interactions.
12
- - 🛠️ **Environment Aware**: Configurable via environment variables or explicit parameters.
13
-
14
- ## Installation
15
-
16
- This package is intended to be used as a dependency in other projects. If you're working locally, you can install it using a file path:
17
-
18
- ```bash
19
- # In your other project:
20
- npm install /path/to/core-db
21
- # or if published to a registry:
22
- npm install @talkpilot/core-db
23
- # or via GitHub
24
- npm install github:talkpilot/core-db
25
- ```
26
-
27
- ## Quick Start
28
-
29
- ### 1. Initialize Database Connections
30
-
31
- You must initialize the database clients before using any of the getters.
32
-
33
- ```typescript
34
- import { mongodbClient, municipalDataMongodbClient } from '@talkpilot/core-db';
35
-
36
- async function bootstrap() {
37
- // Initialize TalkPilot DB
38
- await mongodbClient.connect(process.env.TALKPILOT_MONGO_URI);
39
-
40
- // Initialize Municipal Data DB (optional)
41
- await municipalDataMongodbClient.connect(process.env.MUNICIPAL_MONGO_URI);
42
- }
43
-
44
- bootstrap().catch(console.error);
45
- ```
46
-
47
- ### 2. Using Getters
48
-
49
- Once initialized, you can import and use any of the exported database getters.
50
-
51
- ```typescript
52
- import { findAgents, findCities } from '@talkpilot/core-db';
53
-
54
- async function getSummary() {
55
- // Get all agents from TalkPilot DB
56
- const agents = await findAgents();
57
- console.log('Total Agents:', agents.length);
58
-
59
- // Get all cities from Municipal Data DB
60
- const cities = await findCities();
61
- console.log('Total Cities:', cities.length);
62
- }
63
- ```
64
-
65
- ## Available Domains
66
-
67
- The package exports two main sets of tools:
68
-
69
- ### TalkPilot Domain
70
-
71
- Includes access to:
72
-
73
- - `agents`, `calls`, `clients`, `flows`, `leads`, `phone_numbers`, `plans`, `results`, `sessions`, `subscriptions`, etc.
74
- - Exported as root level functions or via `mongodbClient`.
75
-
76
- ### Municipal Domain
77
-
78
- Includes access to:
79
-
80
- - `cities`, `streets`, `departmentsSubjects`, `tickets`.
81
- - Functions are prefixed where necessary or accessible via `getMunicipalDataDb`.
82
-
83
- ## Environment Variables
84
-
85
- The clients will automatically attempt to use the following environment variables if no URI is provided to the `connect()` method:
86
-
87
- - `MONGO_URI` or `MONGODB_URI`: Primary MongoDB connection string.
88
- - `MONGODB_DB_NAME`: Database name (defaults to 'municipal-data' for the municipal client if not specified).
89
-
90
- ## Development
91
-
92
- ### Setup
93
-
94
- 1. Clone the repository and install dependencies:
95
- ```bash
96
- git clone https://github.com/talkpilot/core-db.git
97
- cd core-db
98
- npm install
99
- ```
100
- 2. Build the project:
101
- ```bash
102
- npm run build
103
- ```
104
-
105
- This will generate the `dist/` directory with the compiled JavaScript and type definitions.
106
-
107
- ### Publishing New Versions
108
-
109
- To publish a new version of the package:
110
-
111
- 1. **Test your changes**:
112
- ```bash
113
- npm test
114
- ```
115
- 2. **Update the version**:
116
- ```bash
117
- # Bumps patch version (0.1.0 -> 0.1.1)
118
- npm version patch
119
- # Or for minor changes (0.1.0 -> 0.2.0)
120
- # npm version minor
121
- # Or for major changes (0.1.0 -> 1.0.0)
122
- # npm version major
123
- ```
124
- 3. **Publish to npm**:
125
- Ensure you have the shared team token in your `~/.npmrc` (see [Development Guide](./DEVELOPMENT.md#team-access--authentication)).
126
- 4. **Update in other repos**:
127
- ```bash
128
- npm update @talkpilot/core-db
129
- ```
130
-
131
- ## License
132
-
133
- MIT
134
-
135
- ---
136
-
137
- **Interested in contributing?** Check out our [Development Guide](./DEVELOPMENT.md) for standards and setup instructions.
138
-
139
- ## Release Notes
140
-
141
- ### 1.1.9
142
-
143
- - `getPhoneNumbersForFlows(clientId)` — lists each phone number linked to a flow for that client (newest first), with `flowId`, `phoneNumber`, and `isPrimary`.
144
- ### 1.1.5
145
-
146
- - `createPurchasedPhoneNumber` for API-bought numbers (Twilio/Telnyx metadata); optional `flowId` until linked to a flow. Types/schema updated accordingly.
147
-
148
- ### 1.0.16
149
-
150
- - Fixed critical issues present in version 1.0.15.
151
- - **Warning**: Version 1.0.15 is bugged and should not be used. Please use at least version 1.0.16.
152
-
153
- ### 1.0.20
154
-
155
- - Added to Moked106Config this param: withNeedAttentionCalls
156
- - withNeedAttentionCalls?: boolean
157
-
158
- ### 1.0.27
159
- - Added an optional `language` field to `ClientConfig` (e.g. Hebrew/English/Russian/French/Spanish) and updated tests.
160
-
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
+