@hasna/contacts 0.6.4 → 0.6.5

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 (57) hide show
  1. package/dist/cli/index.js +1611 -3860
  2. package/dist/db/companies.d.ts.map +1 -1
  3. package/dist/db/contacts.d.ts +0 -4
  4. package/dist/db/contacts.d.ts.map +1 -1
  5. package/dist/db/database.d.ts.map +1 -1
  6. package/dist/db/tags.d.ts.map +1 -1
  7. package/dist/index.d.ts +1 -33
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +91 -1556
  10. package/dist/mcp/index.js +81 -1943
  11. package/dist/server/index.js +12 -348
  12. package/dist/server/serve.d.ts.map +1 -1
  13. package/dist/types/index.d.ts +0 -6
  14. package/dist/types/index.d.ts.map +1 -1
  15. package/package.json +2 -1
  16. package/dist/db/coordination.d.ts +0 -30
  17. package/dist/db/coordination.d.ts.map +0 -1
  18. package/dist/db/documents.d.ts +0 -38
  19. package/dist/db/documents.d.ts.map +0 -1
  20. package/dist/db/field-history.d.ts +0 -17
  21. package/dist/db/field-history.d.ts.map +0 -1
  22. package/dist/db/freshness.d.ts +0 -24
  23. package/dist/db/freshness.d.ts.map +0 -1
  24. package/dist/db/graph.d.ts +0 -21
  25. package/dist/db/graph.d.ts.map +0 -1
  26. package/dist/db/health.d.ts +0 -40
  27. package/dist/db/health.d.ts.map +0 -1
  28. package/dist/db/identity.d.ts +0 -32
  29. package/dist/db/identity.d.ts.map +0 -1
  30. package/dist/db/job-history.d.ts +0 -29
  31. package/dist/db/job-history.d.ts.map +0 -1
  32. package/dist/db/learnings.d.ts +0 -43
  33. package/dist/db/learnings.d.ts.map +0 -1
  34. package/dist/db/org-chart.d.ts +0 -37
  35. package/dist/db/org-chart.d.ts.map +0 -1
  36. package/dist/db/signals.d.ts +0 -18
  37. package/dist/db/signals.d.ts.map +0 -1
  38. package/dist/lib/context.d.ts +0 -5
  39. package/dist/lib/context.d.ts.map +0 -1
  40. package/dist/lib/document-scanner.d.ts +0 -8
  41. package/dist/lib/document-scanner.d.ts.map +0 -1
  42. package/dist/lib/embeddings.d.ts +0 -9
  43. package/dist/lib/embeddings.d.ts.map +0 -1
  44. package/dist/lib/freshness.d.ts +0 -19
  45. package/dist/lib/freshness.d.ts.map +0 -1
  46. package/dist/lib/images.d.ts +0 -30
  47. package/dist/lib/images.d.ts.map +0 -1
  48. package/dist/lib/learning-maintenance.d.ts +0 -8
  49. package/dist/lib/learning-maintenance.d.ts.map +0 -1
  50. package/dist/lib/meeting-capture.d.ts +0 -15
  51. package/dist/lib/meeting-capture.d.ts.map +0 -1
  52. package/dist/lib/signals.d.ts +0 -9
  53. package/dist/lib/signals.d.ts.map +0 -1
  54. package/dist/lib/signature-parser.d.ts +0 -36
  55. package/dist/lib/signature-parser.d.ts.map +0 -1
  56. package/dist/lib/vault.d.ts +0 -24
  57. package/dist/lib/vault.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,16 +1,19 @@
1
1
  // @bun
2
2
  var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
3
7
  var __export = (target, all) => {
4
8
  for (var name in all)
5
9
  __defProp(target, name, {
6
10
  get: all[name],
7
11
  enumerable: true,
8
12
  configurable: true,
9
- set: (newValue) => all[name] = () => newValue
13
+ set: __exportSetter.bind(all, name)
10
14
  });
11
15
  };
12
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
- var __require = import.meta.require;
14
17
 
15
18
  // src/db/database.ts
16
19
  import { Database } from "bun:sqlite";
@@ -408,177 +411,6 @@ var init_database = __esm(() => {
408
411
  deal_id TEXT REFERENCES deals(id) ON DELETE SET NULL,
409
412
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
410
413
  );
411
- `,
412
- `
413
- -- CON-00069: temporal field history
414
- CREATE TABLE IF NOT EXISTS contact_field_history (
415
- id TEXT PRIMARY KEY,
416
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
417
- field_name TEXT NOT NULL,
418
- old_value TEXT,
419
- new_value TEXT,
420
- valid_from TEXT NOT NULL DEFAULT (datetime('now')),
421
- source TEXT,
422
- confidence TEXT NOT NULL DEFAULT 'imported' CHECK(confidence IN ('verified','inferred','imported','stale')),
423
- created_by TEXT,
424
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
425
- );
426
-
427
- -- CON-00070: job history
428
- CREATE TABLE IF NOT EXISTS job_history (
429
- id TEXT PRIMARY KEY,
430
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
431
- company_id TEXT REFERENCES companies(id) ON DELETE SET NULL,
432
- company_name TEXT NOT NULL,
433
- title TEXT,
434
- start_date TEXT,
435
- end_date TEXT,
436
- is_current INTEGER NOT NULL DEFAULT 0,
437
- inferred INTEGER NOT NULL DEFAULT 0,
438
- source TEXT,
439
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
440
- );
441
-
442
- -- CON-00071: learnings
443
- CREATE TABLE IF NOT EXISTS contact_learnings (
444
- id TEXT PRIMARY KEY,
445
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
446
- content TEXT NOT NULL,
447
- type TEXT NOT NULL DEFAULT 'fact' CHECK(type IN ('preference','fact','inference','warning','signal')),
448
- confidence INTEGER NOT NULL DEFAULT 70 CHECK(confidence BETWEEN 0 AND 100),
449
- importance INTEGER NOT NULL DEFAULT 5 CHECK(importance BETWEEN 1 AND 10),
450
- learned_by TEXT,
451
- session_id TEXT,
452
- visibility TEXT NOT NULL DEFAULT 'shared' CHECK(visibility IN ('private','shared','human')),
453
- tags TEXT NOT NULL DEFAULT '[]',
454
- confirmed_count INTEGER NOT NULL DEFAULT 0,
455
- contradicts_id TEXT REFERENCES contact_learnings(id) ON DELETE SET NULL,
456
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
457
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
458
- );
459
-
460
- -- CON-00072: coordination
461
- CREATE TABLE IF NOT EXISTS contact_locks (
462
- id TEXT PRIMARY KEY,
463
- contact_id TEXT NOT NULL UNIQUE REFERENCES contacts(id) ON DELETE CASCADE,
464
- agent_name TEXT NOT NULL,
465
- reason TEXT,
466
- acquired_at TEXT NOT NULL DEFAULT (datetime('now')),
467
- expires_at TEXT NOT NULL,
468
- session_id TEXT
469
- );
470
- CREATE TABLE IF NOT EXISTS contact_agent_activity (
471
- id TEXT PRIMARY KEY,
472
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
473
- agent_name TEXT NOT NULL,
474
- action TEXT NOT NULL,
475
- details TEXT,
476
- session_id TEXT,
477
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
478
- );
479
-
480
- -- CON-00073: relationship graph extra columns
481
- ALTER TABLE contact_relationships ADD COLUMN strength_score INTEGER NOT NULL DEFAULT 50;
482
- ALTER TABLE contact_relationships ADD COLUMN interaction_count INTEGER NOT NULL DEFAULT 0;
483
- ALTER TABLE contact_relationships ADD COLUMN last_interaction TEXT;
484
- ALTER TABLE contact_relationships ADD COLUMN relationship_status TEXT NOT NULL DEFAULT 'stable' CHECK(relationship_status IN ('warming','stable','cooling','ghost'));
485
-
486
- -- CON-00074: identity resolution
487
- CREATE TABLE IF NOT EXISTS contact_identities (
488
- id TEXT PRIMARY KEY,
489
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
490
- system TEXT NOT NULL,
491
- external_id TEXT NOT NULL,
492
- external_url TEXT,
493
- confidence TEXT NOT NULL DEFAULT 'inferred' CHECK(confidence IN ('verified','inferred')),
494
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
495
- UNIQUE(system, external_id)
496
- );
497
- ALTER TABLE contacts ADD COLUMN canonical_id TEXT;
498
-
499
- -- CON-00076: relationship signals
500
- ALTER TABLE contacts ADD COLUMN relationship_health INTEGER NOT NULL DEFAULT 50;
501
- ALTER TABLE contacts ADD COLUMN avg_response_hours REAL;
502
- ALTER TABLE contacts ADD COLUMN preferred_channel TEXT;
503
- ALTER TABLE contacts ADD COLUMN engagement_status TEXT NOT NULL DEFAULT 'new' CHECK(engagement_status IN ('warming','stable','cooling','ghost','new'));
504
- ALTER TABLE contacts ADD COLUMN interaction_count_30d INTEGER NOT NULL DEFAULT 0;
505
- ALTER TABLE contacts ADD COLUMN interaction_count_90d INTEGER NOT NULL DEFAULT 0;
506
-
507
- -- CON-00079: freshness scoring
508
- CREATE TABLE IF NOT EXISTS contact_field_confidence (
509
- id TEXT PRIMARY KEY,
510
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
511
- field_name TEXT NOT NULL,
512
- confidence TEXT NOT NULL DEFAULT 'imported' CHECK(confidence IN ('verified','inferred','imported','stale')),
513
- source TEXT,
514
- last_verified_at TEXT NOT NULL DEFAULT (datetime('now')),
515
- UNIQUE(contact_id, field_name)
516
- );
517
-
518
- -- CON-00080: org chart
519
- CREATE TABLE IF NOT EXISTS org_chart_edges (
520
- id TEXT PRIMARY KEY,
521
- company_id TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
522
- contact_a_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
523
- contact_b_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
524
- edge_type TEXT NOT NULL CHECK(edge_type IN ('reports_to','manages','collaborates_with','peer')),
525
- inferred INTEGER NOT NULL DEFAULT 0,
526
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
527
- UNIQUE(company_id, contact_a_id, contact_b_id, edge_type)
528
- );
529
- CREATE TABLE IF NOT EXISTS deal_contact_roles (
530
- id TEXT PRIMARY KEY,
531
- deal_id TEXT NOT NULL REFERENCES deals(id) ON DELETE CASCADE,
532
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
533
- account_role TEXT NOT NULL CHECK(account_role IN ('economic_buyer','technical_evaluator','champion','blocker','influencer','user','sponsor','other')),
534
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
535
- UNIQUE(deal_id, contact_id)
536
- );
537
-
538
- -- CON-00075: embeddings
539
- CREATE TABLE IF NOT EXISTS contact_embeddings (
540
- contact_id TEXT PRIMARY KEY REFERENCES contacts(id) ON DELETE CASCADE,
541
- embedding TEXT NOT NULL,
542
- model TEXT NOT NULL DEFAULT 'tfidf',
543
- embedded_text TEXT,
544
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
545
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
546
- );
547
- `,
548
- `
549
- ALTER TABLE contacts ADD COLUMN sensitivity TEXT NOT NULL DEFAULT 'normal' CHECK(sensitivity IN ('normal','confidential','restricted'));
550
-
551
- CREATE TABLE IF NOT EXISTS contact_documents (
552
- id TEXT PRIMARY KEY,
553
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
554
- doc_type TEXT NOT NULL,
555
- label TEXT,
556
- encrypted_value TEXT NOT NULL,
557
- iv TEXT NOT NULL,
558
- encrypted_file_path TEXT,
559
- metadata TEXT NOT NULL DEFAULT '{}',
560
- expires_at TEXT,
561
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
562
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
563
- );
564
-
565
- CREATE TABLE IF NOT EXISTS contact_health (
566
- id TEXT PRIMARY KEY,
567
- contact_id TEXT NOT NULL UNIQUE REFERENCES contacts(id) ON DELETE CASCADE,
568
- blood_type TEXT,
569
- allergies TEXT NOT NULL DEFAULT '[]',
570
- medical_conditions TEXT NOT NULL DEFAULT '[]',
571
- medications TEXT NOT NULL DEFAULT '[]',
572
- emergency_contacts TEXT NOT NULL DEFAULT '[]',
573
- health_insurance_provider TEXT,
574
- health_insurance_id TEXT,
575
- primary_physician TEXT,
576
- primary_physician_phone TEXT,
577
- organ_donor INTEGER NOT NULL DEFAULT 0,
578
- notes TEXT,
579
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
580
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
581
- );
582
414
  `
583
415
  ];
584
416
  });
@@ -665,7 +497,6 @@ __export(exports_contacts, {
665
497
  getContactProjectIds: () => getContactProjectIds,
666
498
  getContactByEmail: () => getContactByEmail,
667
499
  getContact: () => getContact,
668
- findOrCreateContact: () => findOrCreateContact,
669
500
  deleteContact: () => deleteContact,
670
501
  createContact: () => createContact,
671
502
  autoLinkContactToCompany: () => autoLinkContactToCompany,
@@ -683,7 +514,6 @@ function rowToContact(row) {
683
514
  follow_up_at: row.follow_up_at ?? null,
684
515
  archived: !!row.archived,
685
516
  project_id: row.project_id ?? null,
686
- sensitivity: row.sensitivity ?? "normal",
687
517
  do_not_contact: !!row.do_not_contact,
688
518
  priority: row.priority ?? 3,
689
519
  timezone: row.timezone ?? null
@@ -771,8 +601,8 @@ function createContact(input, db) {
771
601
  const firstName = input.first_name ?? "";
772
602
  const lastName = input.last_name ?? "";
773
603
  const displayName = input.display_name ?? (firstName || lastName ? `${firstName} ${lastName}`.trim() : "Unnamed Contact");
774
- d.run(`INSERT INTO contacts (id, first_name, last_name, display_name, nickname, avatar_url, notes, birthday, company_id, job_title, source, custom_fields, last_contacted_at, website, preferred_contact_method, status, follow_up_at, project_id, sensitivity, do_not_contact, priority, timezone, created_at, updated_at)
775
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
604
+ d.run(`INSERT INTO contacts (id, first_name, last_name, display_name, nickname, avatar_url, notes, birthday, company_id, job_title, source, custom_fields, last_contacted_at, website, preferred_contact_method, status, follow_up_at, project_id, do_not_contact, priority, timezone, created_at, updated_at)
605
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
776
606
  id,
777
607
  firstName,
778
608
  lastName,
@@ -791,7 +621,6 @@ function createContact(input, db) {
791
621
  input.status ?? "active",
792
622
  input.follow_up_at ?? null,
793
623
  input.project_id ?? null,
794
- input.sensitivity ?? "normal",
795
624
  input.do_not_contact ? 1 : 0,
796
625
  input.priority ?? 3,
797
626
  input.timezone ?? null,
@@ -840,7 +669,6 @@ function listContacts(opts = {}, db) {
840
669
  order_by = "display_name",
841
670
  order_dir = "asc",
842
671
  include_dnc = false,
843
- include_restricted = false,
844
672
  priority_min,
845
673
  updated_since
846
674
  } = opts;
@@ -851,9 +679,6 @@ function listContacts(opts = {}, db) {
851
679
  if (!include_dnc) {
852
680
  conditions.push("c.do_not_contact = 0");
853
681
  }
854
- if (!include_restricted) {
855
- conditions.push("c.sensitivity != 'restricted'");
856
- }
857
682
  if (company_id) {
858
683
  conditions.push("c.company_id = ?");
859
684
  params.push(company_id);
@@ -982,10 +807,6 @@ function updateContact(id, input, db) {
982
807
  setClauses.push("project_id = ?");
983
808
  params.push(input.project_id);
984
809
  }
985
- if (input.sensitivity !== undefined) {
986
- setClauses.push("sensitivity = ?");
987
- params.push(input.sensitivity);
988
- }
989
810
  if (input.do_not_contact !== undefined) {
990
811
  setClauses.push("do_not_contact = ?");
991
812
  params.push(input.do_not_contact ? 1 : 0);
@@ -1033,26 +854,26 @@ function searchContacts(query, db) {
1033
854
  const ftsRows = d.query(`
1034
855
  SELECT c.* FROM contacts c
1035
856
  JOIN contacts_fts fts ON fts.id = c.id
1036
- WHERE contacts_fts MATCH ? AND c.archived = 0 AND c.sensitivity != 'restricted'
857
+ WHERE contacts_fts MATCH ? AND c.archived = 0
1037
858
  ORDER BY rank
1038
859
  LIMIT 50
1039
860
  `).all(`"${query.replace(/"/g, '""')}"*`);
1040
861
  const emailRows = d.query(`
1041
862
  SELECT DISTINCT c.* FROM contacts c
1042
863
  JOIN emails e ON e.contact_id = c.id
1043
- WHERE e.address LIKE ? AND c.archived = 0 AND c.sensitivity != 'restricted'
864
+ WHERE e.address LIKE ? AND c.archived = 0
1044
865
  LIMIT 20
1045
866
  `).all(`%${query}%`);
1046
867
  const phoneRows = d.query(`
1047
868
  SELECT DISTINCT c.* FROM contacts c
1048
869
  JOIN phones p ON p.contact_id = c.id
1049
- WHERE p.number LIKE ? AND c.archived = 0 AND c.sensitivity != 'restricted'
870
+ WHERE p.number LIKE ? AND c.archived = 0
1050
871
  LIMIT 20
1051
872
  `).all(`%${query}%`);
1052
873
  const companyRows = d.query(`
1053
874
  SELECT DISTINCT c.* FROM contacts c
1054
875
  JOIN companies co ON co.id = c.company_id
1055
- WHERE co.name LIKE ? AND c.archived = 0 AND c.sensitivity != 'restricted'
876
+ WHERE co.name LIKE ? AND c.archived = 0
1056
877
  LIMIT 20
1057
878
  `).all(`%${query}%`);
1058
879
  const seen = new Set;
@@ -1205,25 +1026,6 @@ function listColdContacts(days, db) {
1205
1026
  LIMIT 100`).all(`-${days}`);
1206
1027
  return rows.map((row) => loadContactDetails(d, rowToContact(row)));
1207
1028
  }
1208
- async function findOrCreateContact(input, db) {
1209
- const d = db || getDatabase();
1210
- const emailAddresses = (input.emails ?? []).map((e) => e.address);
1211
- for (const addr of emailAddresses) {
1212
- const emailRow = d.query(`SELECT contact_id FROM emails WHERE LOWER(address) = LOWER(?) AND contact_id IS NOT NULL LIMIT 1`).get(addr);
1213
- if (emailRow) {
1214
- return { contact: getContact(emailRow.contact_id, d), created: false };
1215
- }
1216
- }
1217
- const nameQuery = input.display_name ?? (input.first_name || input.last_name ? `${input.first_name ?? ""} ${input.last_name ?? ""}`.trim() : null);
1218
- if (nameQuery) {
1219
- const results = searchContacts(nameQuery, d);
1220
- if (results.length > 0 && results[0]) {
1221
- return { contact: results[0], created: false };
1222
- }
1223
- }
1224
- const contact = createContact(input, d);
1225
- return { contact, created: true };
1226
- }
1227
1029
  function autoLinkContactToCompany(contactId, db) {
1228
1030
  const d = db || getDatabase();
1229
1031
  const row = d.query(`SELECT * FROM contacts WHERE id = ?`).get(contactId);
@@ -1274,96 +1076,6 @@ var init_contacts = __esm(() => {
1274
1076
  init_activity();
1275
1077
  });
1276
1078
 
1277
- // src/db/events.ts
1278
- var exports_events = {};
1279
- __export(exports_events, {
1280
- logEvent: () => logEvent,
1281
- listEvents: () => listEvents,
1282
- getEvent: () => getEvent,
1283
- deleteEvent: () => deleteEvent
1284
- });
1285
- function rowToEvent(row) {
1286
- let contact_ids = [];
1287
- try {
1288
- contact_ids = JSON.parse(row.contact_ids);
1289
- } catch {
1290
- contact_ids = [];
1291
- }
1292
- return {
1293
- id: row.id,
1294
- title: row.title,
1295
- type: row.type,
1296
- event_date: row.event_date,
1297
- duration_min: row.duration_min,
1298
- contact_ids,
1299
- company_id: row.company_id,
1300
- notes: row.notes,
1301
- outcome: row.outcome,
1302
- deal_id: row.deal_id,
1303
- created_at: row.created_at
1304
- };
1305
- }
1306
- function logEvent(input, db) {
1307
- const d = db || getDatabase();
1308
- const id = uuid();
1309
- const timestamp = now();
1310
- d.run(`INSERT INTO events (id, title, type, event_date, duration_min, contact_ids, company_id, notes, outcome, deal_id, created_at)
1311
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
1312
- id,
1313
- input.title,
1314
- input.type ?? "meeting",
1315
- input.event_date,
1316
- input.duration_min ?? null,
1317
- JSON.stringify(input.contact_ids ?? []),
1318
- input.company_id ?? null,
1319
- input.notes ?? null,
1320
- input.outcome ?? null,
1321
- input.deal_id ?? null,
1322
- timestamp
1323
- ]);
1324
- return rowToEvent(d.query(`SELECT * FROM events WHERE id = ?`).get(id));
1325
- }
1326
- function getEvent(id, db) {
1327
- const d = db || getDatabase();
1328
- const row = d.query(`SELECT * FROM events WHERE id = ?`).get(id);
1329
- return row ? rowToEvent(row) : null;
1330
- }
1331
- function listEvents(opts = {}, db) {
1332
- const d = db || getDatabase();
1333
- const conditions = [];
1334
- const params = [];
1335
- if (opts.contact_id) {
1336
- conditions.push("contact_ids LIKE ?");
1337
- params.push(`%${opts.contact_id}%`);
1338
- }
1339
- if (opts.company_id) {
1340
- conditions.push("company_id = ?");
1341
- params.push(opts.company_id);
1342
- }
1343
- if (opts.type) {
1344
- conditions.push("type = ?");
1345
- params.push(opts.type);
1346
- }
1347
- if (opts.date_from) {
1348
- conditions.push("event_date >= ?");
1349
- params.push(opts.date_from);
1350
- }
1351
- if (opts.date_to) {
1352
- conditions.push("event_date <= ?");
1353
- params.push(opts.date_to);
1354
- }
1355
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1356
- const rows = d.query(`SELECT * FROM events ${where} ORDER BY event_date DESC`).all(...params);
1357
- return rows.map(rowToEvent);
1358
- }
1359
- function deleteEvent(id, db) {
1360
- const d = db || getDatabase();
1361
- d.run(`DELETE FROM events WHERE id = ?`, [id]);
1362
- }
1363
- var init_events = __esm(() => {
1364
- init_database();
1365
- });
1366
-
1367
1079
  // src/index.ts
1368
1080
  init_database();
1369
1081
  init_contacts();
@@ -1618,7 +1330,6 @@ function listCompanyEmployees(companyId, db) {
1618
1330
  follow_up_at: r.follow_up_at ?? null,
1619
1331
  archived: !!r.archived,
1620
1332
  project_id: r.project_id ?? null,
1621
- sensitivity: r.sensitivity ?? "normal",
1622
1333
  do_not_contact: !!r.do_not_contact,
1623
1334
  priority: r.priority ?? 3,
1624
1335
  timezone: r.timezone ?? null
@@ -1749,7 +1460,6 @@ function listContactsByTag(tagId, db) {
1749
1460
  follow_up_at: r.follow_up_at ?? null,
1750
1461
  archived: !!r.archived,
1751
1462
  project_id: r.project_id ?? null,
1752
- sensitivity: r.sensitivity ?? "normal",
1753
1463
  do_not_contact: !!r.do_not_contact,
1754
1464
  priority: r.priority ?? 3,
1755
1465
  timezone: r.timezone ?? null
@@ -2543,10 +2253,86 @@ function getDealsByStage(db) {
2543
2253
  }
2544
2254
  return result;
2545
2255
  }
2546
-
2547
- // src/index.ts
2548
- init_events();
2549
-
2256
+ // src/db/events.ts
2257
+ init_database();
2258
+ function rowToEvent(row) {
2259
+ let contact_ids = [];
2260
+ try {
2261
+ contact_ids = JSON.parse(row.contact_ids);
2262
+ } catch {
2263
+ contact_ids = [];
2264
+ }
2265
+ return {
2266
+ id: row.id,
2267
+ title: row.title,
2268
+ type: row.type,
2269
+ event_date: row.event_date,
2270
+ duration_min: row.duration_min,
2271
+ contact_ids,
2272
+ company_id: row.company_id,
2273
+ notes: row.notes,
2274
+ outcome: row.outcome,
2275
+ deal_id: row.deal_id,
2276
+ created_at: row.created_at
2277
+ };
2278
+ }
2279
+ function logEvent(input, db) {
2280
+ const d = db || getDatabase();
2281
+ const id = uuid();
2282
+ const timestamp = now();
2283
+ d.run(`INSERT INTO events (id, title, type, event_date, duration_min, contact_ids, company_id, notes, outcome, deal_id, created_at)
2284
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
2285
+ id,
2286
+ input.title,
2287
+ input.type ?? "meeting",
2288
+ input.event_date,
2289
+ input.duration_min ?? null,
2290
+ JSON.stringify(input.contact_ids ?? []),
2291
+ input.company_id ?? null,
2292
+ input.notes ?? null,
2293
+ input.outcome ?? null,
2294
+ input.deal_id ?? null,
2295
+ timestamp
2296
+ ]);
2297
+ return rowToEvent(d.query(`SELECT * FROM events WHERE id = ?`).get(id));
2298
+ }
2299
+ function getEvent(id, db) {
2300
+ const d = db || getDatabase();
2301
+ const row = d.query(`SELECT * FROM events WHERE id = ?`).get(id);
2302
+ return row ? rowToEvent(row) : null;
2303
+ }
2304
+ function listEvents(opts = {}, db) {
2305
+ const d = db || getDatabase();
2306
+ const conditions = [];
2307
+ const params = [];
2308
+ if (opts.contact_id) {
2309
+ conditions.push("contact_ids LIKE ?");
2310
+ params.push(`%${opts.contact_id}%`);
2311
+ }
2312
+ if (opts.company_id) {
2313
+ conditions.push("company_id = ?");
2314
+ params.push(opts.company_id);
2315
+ }
2316
+ if (opts.type) {
2317
+ conditions.push("type = ?");
2318
+ params.push(opts.type);
2319
+ }
2320
+ if (opts.date_from) {
2321
+ conditions.push("event_date >= ?");
2322
+ params.push(opts.date_from);
2323
+ }
2324
+ if (opts.date_to) {
2325
+ conditions.push("event_date <= ?");
2326
+ params.push(opts.date_to);
2327
+ }
2328
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2329
+ const rows = d.query(`SELECT * FROM events ${where} ORDER BY event_date DESC`).all(...params);
2330
+ return rows.map(rowToEvent);
2331
+ }
2332
+ function deleteEvent(id, db) {
2333
+ const d = db || getDatabase();
2334
+ d.run(`DELETE FROM events WHERE id = ?`, [id]);
2335
+ }
2550
2336
  // src/db/notes.ts
2551
2337
  init_types();
2552
2338
  init_database();
@@ -3745,1180 +3531,6 @@ async function pullGoogleContactsAsInputs(opts = {}) {
3745
3531
 
3746
3532
  // src/index.ts
3747
3533
  init_types();
3748
-
3749
- // src/db/field-history.ts
3750
- init_database();
3751
- function recordFieldChange(contactId, fieldName, oldValue, newValue, source, createdBy, db) {
3752
- const _db2 = db || getDatabase();
3753
- _db2.query(`INSERT INTO contact_field_history(id,contact_id,field_name,old_value,new_value,valid_from,source,created_by,created_at) VALUES(?,?,?,?,?,?,?,?,?)`).run(uuid(), contactId, fieldName, oldValue != null ? String(oldValue) : null, newValue != null ? String(newValue) : null, now(), source || null, createdBy || null, now());
3754
- }
3755
- function getFieldHistory(contactId, fieldName, db) {
3756
- const _db2 = db || getDatabase();
3757
- if (fieldName) {
3758
- return _db2.query(`SELECT * FROM contact_field_history WHERE contact_id=? AND field_name=? ORDER BY valid_from DESC`).all(contactId, fieldName);
3759
- }
3760
- return _db2.query(`SELECT * FROM contact_field_history WHERE contact_id=? ORDER BY valid_from DESC`).all(contactId);
3761
- }
3762
- function getContactAt(contactId, timestamp, db) {
3763
- const _db2 = db || getDatabase();
3764
- const rows = _db2.query(`SELECT field_name, new_value FROM contact_field_history WHERE contact_id=? AND valid_from<=? ORDER BY valid_from ASC`).all(contactId, timestamp);
3765
- const result = {};
3766
- for (const r of rows) {
3767
- if (r.new_value != null)
3768
- result[r.field_name] = r.new_value;
3769
- }
3770
- return result;
3771
- }
3772
- // src/db/job-history.ts
3773
- init_database();
3774
- function rowToJob(r) {
3775
- return { ...r, is_current: !!r["is_current"], inferred: !!r["inferred"] };
3776
- }
3777
- function addJobEntry(contactId, input, db) {
3778
- const _db2 = db || getDatabase();
3779
- if (input.is_current) {
3780
- _db2.query(`UPDATE job_history SET is_current=0, end_date=COALESCE(end_date,?) WHERE contact_id=? AND is_current=1`).run(new Date().toISOString().slice(0, 10), contactId);
3781
- }
3782
- const id = uuid();
3783
- _db2.query(`INSERT INTO job_history(id,contact_id,company_id,company_name,title,start_date,end_date,is_current,inferred,source,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)`).run(id, contactId, input.company_id || null, input.company_name, input.title || null, input.start_date || null, input.end_date || null, input.is_current ? 1 : 0, input.inferred ? 1 : 0, input.source || null, now());
3784
- return rowToJob(_db2.query(`SELECT * FROM job_history WHERE id=?`).get(id));
3785
- }
3786
- function getJobHistory(contactId, db) {
3787
- const _db2 = db || getDatabase();
3788
- return _db2.query(`SELECT * FROM job_history WHERE contact_id=? ORDER BY is_current DESC, start_date DESC`).all(contactId).map(rowToJob);
3789
- }
3790
- function getCurrentRole(contactId, db) {
3791
- const _db2 = db || getDatabase();
3792
- const r = _db2.query(`SELECT * FROM job_history WHERE contact_id=? AND is_current=1`).get(contactId);
3793
- return r ? rowToJob(r) : null;
3794
- }
3795
- function getPreviousEmployers(contactId, db) {
3796
- const _db2 = db || getDatabase();
3797
- return _db2.query(`SELECT * FROM job_history WHERE contact_id=? AND is_current=0 ORDER BY start_date DESC`).all(contactId).map(rowToJob);
3798
- }
3799
- // src/db/learnings.ts
3800
- init_database();
3801
- function rowToLearning(r) {
3802
- return { ...r, tags: JSON.parse(r["tags"] || "[]") };
3803
- }
3804
- function saveLearning(contactId, input, db) {
3805
- const _db2 = db || getDatabase();
3806
- const id = uuid();
3807
- _db2.query(`INSERT INTO contact_learnings(id,contact_id,content,type,confidence,importance,learned_by,session_id,visibility,tags,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`).run(id, contactId, input.content, input.type || "fact", input.confidence ?? 70, input.importance ?? 5, input.learned_by || null, input.session_id || null, input.visibility || "shared", JSON.stringify(input.tags || []), now(), now());
3808
- return rowToLearning(_db2.query(`SELECT * FROM contact_learnings WHERE id=?`).get(id));
3809
- }
3810
- function getLearnings(contactId, opts = {}, db) {
3811
- const _db2 = db || getDatabase();
3812
- let sql = `SELECT * FROM contact_learnings WHERE contact_id=?`;
3813
- const params = [contactId];
3814
- if (opts.type) {
3815
- sql += ` AND type=?`;
3816
- params.push(opts.type);
3817
- }
3818
- if (opts.min_importance) {
3819
- sql += ` AND importance>=?`;
3820
- params.push(opts.min_importance);
3821
- }
3822
- if (opts.visibility) {
3823
- sql += ` AND visibility=?`;
3824
- params.push(opts.visibility);
3825
- }
3826
- sql += ` ORDER BY importance DESC, confidence DESC`;
3827
- return _db2.query(sql).all(...params).map(rowToLearning);
3828
- }
3829
- function searchLearnings(query, opts = {}, db) {
3830
- const _db2 = db || getDatabase();
3831
- let sql = `SELECT * FROM contact_learnings WHERE content LIKE ?`;
3832
- const params = [`%${query}%`];
3833
- if (opts.type) {
3834
- sql += ` AND type=?`;
3835
- params.push(opts.type);
3836
- }
3837
- if (opts.contact_id) {
3838
- sql += ` AND contact_id=?`;
3839
- params.push(opts.contact_id);
3840
- }
3841
- sql += ` ORDER BY importance DESC, confidence DESC LIMIT 50`;
3842
- return _db2.query(sql).all(...params).map(rowToLearning);
3843
- }
3844
- function confirmLearning(learningId, _agentName, db) {
3845
- const _db2 = db || getDatabase();
3846
- _db2.query(`UPDATE contact_learnings SET confirmed_count=confirmed_count+1, confidence=MIN(100,confidence+10), updated_at=? WHERE id=?`).run(now(), learningId);
3847
- }
3848
- function decayLearnings(db) {
3849
- const _db2 = db || getDatabase();
3850
- const cutoff = new Date(Date.now() - 30 * 86400000).toISOString();
3851
- const result = _db2.query(`UPDATE contact_learnings SET confidence=MAX(10,confidence-5), updated_at=? WHERE confirmed_count=0 AND created_at<? AND confidence>10`).run(now(), cutoff);
3852
- return result.changes || 0;
3853
- }
3854
- function deleteLearning(learningId, db) {
3855
- const _db2 = db || getDatabase();
3856
- _db2.query(`DELETE FROM contact_learnings WHERE id=?`).run(learningId);
3857
- }
3858
- // src/db/coordination.ts
3859
- init_database();
3860
- function acquireLock(contactId, agentName, ttlSeconds = 300, reason, sessionId, db) {
3861
- const _db2 = db || getDatabase();
3862
- cleanExpiredLocks(_db2);
3863
- const existing = _db2.query(`SELECT * FROM contact_locks WHERE contact_id=?`).get(contactId);
3864
- if (existing)
3865
- return { acquired: false, held_by: existing.agent_name, lock: existing };
3866
- const id = uuid();
3867
- const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString();
3868
- _db2.query(`INSERT INTO contact_locks(id,contact_id,agent_name,reason,acquired_at,expires_at,session_id) VALUES(?,?,?,?,?,?,?)`).run(id, contactId, agentName, reason || null, now(), expiresAt, sessionId || null);
3869
- return {
3870
- acquired: true,
3871
- lock: _db2.query(`SELECT * FROM contact_locks WHERE id=?`).get(id)
3872
- };
3873
- }
3874
- function releaseLock(contactId, agentName, db) {
3875
- const _db2 = db || getDatabase();
3876
- const result = _db2.query(`DELETE FROM contact_locks WHERE contact_id=? AND agent_name=?`).run(contactId, agentName);
3877
- return (result.changes || 0) > 0;
3878
- }
3879
- function checkLock(contactId, db) {
3880
- const _db2 = db || getDatabase();
3881
- cleanExpiredLocks(_db2);
3882
- return _db2.query(`SELECT * FROM contact_locks WHERE contact_id=?`).get(contactId);
3883
- }
3884
- function cleanExpiredLocks(db) {
3885
- const _db2 = db || getDatabase();
3886
- _db2.query(`DELETE FROM contact_locks WHERE expires_at<?`).run(now());
3887
- }
3888
- function logAgentActivity(contactId, agentName, action, details, sessionId, db) {
3889
- const _db2 = db || getDatabase();
3890
- _db2.query(`INSERT INTO contact_agent_activity(id,contact_id,agent_name,action,details,session_id,created_at) VALUES(?,?,?,?,?,?,?)`).run(uuid(), contactId, agentName, action, details || null, sessionId || null, now());
3891
- }
3892
- function getAgentActivity(contactId, limit = 20, db) {
3893
- const _db2 = db || getDatabase();
3894
- return _db2.query(`SELECT * FROM contact_agent_activity WHERE contact_id=? ORDER BY created_at DESC LIMIT ?`).all(contactId, limit);
3895
- }
3896
- // src/db/graph.ts
3897
- init_database();
3898
- function computeRelationshipStrength(contactId, db) {
3899
- const _db2 = db || getDatabase();
3900
- const contact = _db2.query(`SELECT last_contacted_at, interaction_count_30d, interaction_count_90d FROM contacts WHERE id=?`).get(contactId);
3901
- if (!contact)
3902
- return 0;
3903
- let score = 50;
3904
- if (contact.last_contacted_at) {
3905
- const days = Math.floor((Date.now() - new Date(contact.last_contacted_at).getTime()) / 86400000);
3906
- score += days < 7 ? 30 : days < 30 ? 20 : days < 90 ? 5 : -20;
3907
- } else {
3908
- score -= 20;
3909
- }
3910
- score += Math.min(20, (contact.interaction_count_30d || 0) * 4);
3911
- return Math.max(0, Math.min(100, score));
3912
- }
3913
- function findWarmPath(fromContactId, toContactId, db) {
3914
- const _db2 = db || getDatabase();
3915
- const visited = new Set([fromContactId]);
3916
- const queue = [{ id: fromContactId, path: [] }];
3917
- while (queue.length) {
3918
- const item = queue.shift();
3919
- const { id, path } = item;
3920
- if (id === toContactId)
3921
- return path;
3922
- if (path.length >= 4)
3923
- continue;
3924
- const neighbors = _db2.query(`SELECT cr.*, c.display_name FROM contact_relationships cr JOIN contacts c ON (CASE WHEN cr.contact_a_id=? THEN cr.contact_b_id ELSE cr.contact_a_id END)=c.id WHERE (cr.contact_a_id=? OR cr.contact_b_id=?) LIMIT 20`).all(id, id, id);
3925
- for (const n of neighbors) {
3926
- const nextId = n.contact_a_id === id ? n.contact_b_id : n.contact_a_id;
3927
- if (visited.has(nextId))
3928
- continue;
3929
- visited.add(nextId);
3930
- queue.push({
3931
- id: nextId,
3932
- path: [
3933
- ...path,
3934
- { contact_id: nextId, display_name: n.display_name, strength: n.strength_score || 50 }
3935
- ]
3936
- });
3937
- }
3938
- }
3939
- return [];
3940
- }
3941
- function findConnectionsAtCompany(companyId, db) {
3942
- const _db2 = db || getDatabase();
3943
- return _db2.query(`SELECT c.id as contact_id, c.display_name, c.job_title, c.relationship_health as strength FROM contacts c WHERE c.company_id=? AND c.archived=0 ORDER BY c.relationship_health DESC`).all(companyId);
3944
- }
3945
- function detectCoolingRelationships(db) {
3946
- const _db2 = db || getDatabase();
3947
- const cutoff = new Date(Date.now() - 45 * 86400000).toISOString();
3948
- return _db2.query(`SELECT id as contact_id, display_name, CAST((julianday('now') - julianday(last_contacted_at)) AS INTEGER) as days_since FROM contacts WHERE last_contacted_at IS NOT NULL AND last_contacted_at < ? AND engagement_status != 'ghost' AND archived=0 ORDER BY last_contacted_at ASC LIMIT 50`).all(cutoff);
3949
- }
3950
- // src/db/identity.ts
3951
- init_database();
3952
- function addIdentity(contactId, system, externalId, externalUrl, confidence = "inferred", db) {
3953
- const _db2 = db || getDatabase();
3954
- const id = uuid();
3955
- _db2.query(`INSERT OR REPLACE INTO contact_identities(id,contact_id,system,external_id,external_url,confidence,created_at) VALUES(?,?,?,?,?,?,?)`).run(id, contactId, system, externalId, externalUrl || null, confidence, now());
3956
- return _db2.query(`SELECT * FROM contact_identities WHERE id=?`).get(id);
3957
- }
3958
- function resolveIdentity(system, externalId, db) {
3959
- const _db2 = db || getDatabase();
3960
- const row = _db2.query(`SELECT c.id, c.display_name FROM contacts c JOIN contact_identities ci ON c.id=ci.contact_id WHERE ci.system=? AND ci.external_id=?`).get(system, externalId);
3961
- return row || null;
3962
- }
3963
- function resolveByPartial(partial, db) {
3964
- const _db2 = db || getDatabase();
3965
- const matches = new Map;
3966
- const addMatch = (id, name, title, score, reason) => {
3967
- const existing = matches.get(id);
3968
- if (existing) {
3969
- existing.confidence_score = Math.min(100, existing.confidence_score + score);
3970
- existing.match_reasons.push(reason);
3971
- } else {
3972
- matches.set(id, {
3973
- contact: { id, display_name: name, job_title: title },
3974
- confidence_score: score,
3975
- match_reasons: [reason]
3976
- });
3977
- }
3978
- };
3979
- if (partial.email) {
3980
- const rows = _db2.query(`SELECT c.id, c.display_name, c.job_title FROM contacts c JOIN emails e ON c.id=e.contact_id WHERE LOWER(e.address)=LOWER(?)`).all(partial.email);
3981
- rows.forEach((r) => addMatch(r.id, r.display_name, r.job_title, 90, `email match: ${partial.email}`));
3982
- }
3983
- if (partial.linkedin_url) {
3984
- const rows = _db2.query(`SELECT c.id, c.display_name, c.job_title FROM contacts c JOIN social_profiles sp ON c.id=sp.contact_id WHERE sp.platform='linkedin' AND sp.url LIKE ?`).all(`%${partial.linkedin_url.split("/").pop()}%`);
3985
- rows.forEach((r) => addMatch(r.id, r.display_name, r.job_title, 85, `linkedin match`));
3986
- }
3987
- if (partial.name) {
3988
- const rows = _db2.query(`SELECT id, display_name, job_title FROM contacts WHERE display_name LIKE ? AND archived=0 LIMIT 10`).all(`%${partial.name}%`);
3989
- rows.forEach((r) => addMatch(r.id, r.display_name, r.job_title, 40, `name match: ${partial.name}`));
3990
- }
3991
- return Array.from(matches.values()).sort((a, b) => b.confidence_score - a.confidence_score);
3992
- }
3993
- function getIdentities(contactId, db) {
3994
- const _db2 = db || getDatabase();
3995
- return _db2.query(`SELECT * FROM contact_identities WHERE contact_id=? ORDER BY created_at DESC`).all(contactId);
3996
- }
3997
- // src/db/org-chart.ts
3998
- init_database();
3999
- function addOrgChartEdge(companyId, contactAId, contactBId, edgeType, inferred = false, db) {
4000
- const _db2 = db || getDatabase();
4001
- const id = uuid();
4002
- _db2.query(`INSERT OR IGNORE INTO org_chart_edges(id,company_id,contact_a_id,contact_b_id,edge_type,inferred,created_at) VALUES(?,?,?,?,?,?,?)`).run(id, companyId, contactAId, contactBId, edgeType, inferred ? 1 : 0, now());
4003
- return _db2.query(`SELECT * FROM org_chart_edges WHERE company_id=? AND contact_a_id=? AND contact_b_id=? AND edge_type=?`).get(companyId, contactAId, contactBId, edgeType);
4004
- }
4005
- function listOrgChart(companyId, db) {
4006
- const _db2 = db || getDatabase();
4007
- return _db2.query(`SELECT oe.*, ca.display_name as contact_a_name, cb.display_name as contact_b_name FROM org_chart_edges oe JOIN contacts ca ON oe.contact_a_id=ca.id JOIN contacts cb ON oe.contact_b_id=cb.id WHERE oe.company_id=?`).all(companyId);
4008
- }
4009
- function setDealContactRole(dealId, contactId, accountRole, db) {
4010
- const _db2 = db || getDatabase();
4011
- const id = uuid();
4012
- _db2.query(`INSERT OR REPLACE INTO deal_contact_roles(id,deal_id,contact_id,account_role,created_at) VALUES(?,?,?,?,?)`).run(id, dealId, contactId, accountRole, now());
4013
- return _db2.query(`SELECT * FROM deal_contact_roles WHERE deal_id=? AND contact_id=?`).get(dealId, contactId);
4014
- }
4015
- function getDealTeam(dealId, db) {
4016
- const _db2 = db || getDatabase();
4017
- return _db2.query(`SELECT dr.*, c.display_name, c.job_title FROM deal_contact_roles dr JOIN contacts c ON dr.contact_id=c.id WHERE dr.deal_id=?`).all(dealId);
4018
- }
4019
- function getCoverageGaps(companyId, db) {
4020
- const _db2 = db || getDatabase();
4021
- const total = _db2.query(`SELECT COUNT(*) c FROM contacts WHERE company_id=? AND archived=0`).get(companyId).c;
4022
- const hasManager = _db2.query(`SELECT COUNT(*) c FROM org_chart_edges WHERE company_id=? AND edge_type='manages'`).get(companyId).c > 0;
4023
- const hasEco = _db2.query(`SELECT COUNT(*) c FROM deal_contact_roles dr JOIN deals d ON dr.deal_id=d.id WHERE d.company_id=? AND dr.account_role='economic_buyer'`).get(companyId).c > 0;
4024
- const hasTech = _db2.query(`SELECT COUNT(*) c FROM deal_contact_roles dr JOIN deals d ON dr.deal_id=d.id WHERE d.company_id=? AND dr.account_role='technical_evaluator'`).get(companyId).c > 0;
4025
- const missing = [
4026
- !hasManager && "org chart relationships",
4027
- !hasEco && "economic buyer",
4028
- !hasTech && "technical evaluator"
4029
- ].filter(Boolean);
4030
- return {
4031
- total_contacts: total,
4032
- has_manager: hasManager,
4033
- has_technical: hasTech,
4034
- has_economic_buyer: hasEco,
4035
- suggestion: missing.length ? `Missing: ${missing.join(", ")}` : "Good coverage"
4036
- };
4037
- }
4038
- // src/db/signals.ts
4039
- init_database();
4040
- function getRelationshipSignals(contactId, db) {
4041
- const _db2 = db || getDatabase();
4042
- const row = _db2.query(`SELECT id as contact_id, display_name, last_contacted_at, interaction_count_30d, engagement_status, relationship_health FROM contacts WHERE id=?`).get(contactId);
4043
- if (!row)
4044
- return [];
4045
- const daysSince = row.last_contacted_at ? Math.floor((Date.now() - new Date(row.last_contacted_at).getTime()) / 86400000) : null;
4046
- const signals = [];
4047
- const cnt = row.interaction_count_30d || 0;
4048
- const health = row.relationship_health ?? 50;
4049
- if (daysSince === null || daysSince > 180) {
4050
- signals.push({ ...row, signal_type: "ghost", days_since_contact: daysSince, reason: "No contact in 180+ days or never contacted" });
4051
- } else if (daysSince > 60 && cnt === 0) {
4052
- signals.push({ ...row, signal_type: "cooling", days_since_contact: daysSince, reason: `No contact in ${daysSince} days, no recent interactions` });
4053
- } else if (cnt > 3 && health > 70) {
4054
- signals.push({ ...row, signal_type: "warming", days_since_contact: daysSince, reason: `${cnt} interactions in last 30 days, health score ${health}` });
4055
- } else {
4056
- signals.push({ ...row, signal_type: "healthy", days_since_contact: daysSince, reason: `Last contact ${daysSince}d ago, ${cnt} interactions in 30d` });
4057
- }
4058
- return signals;
4059
- }
4060
- function getGhostContacts(db) {
4061
- const _db2 = db || getDatabase();
4062
- const rows = _db2.query(`SELECT id as contact_id, display_name, last_contacted_at, interaction_count_30d, engagement_status, relationship_health FROM contacts WHERE (last_contacted_at IS NULL OR julianday('now') - julianday(last_contacted_at) > 180) AND archived=0 ORDER BY last_contacted_at ASC LIMIT 50`).all();
4063
- return rows.map((r) => ({
4064
- ...r,
4065
- signal_type: "ghost",
4066
- days_since_contact: r.last_contacted_at ? Math.floor((Date.now() - new Date(r.last_contacted_at).getTime()) / 86400000) : null,
4067
- reason: "No contact in 180+ days or never contacted"
4068
- }));
4069
- }
4070
- function getWarmingContacts(db) {
4071
- const _db2 = db || getDatabase();
4072
- const rows = _db2.query(`SELECT id as contact_id, display_name, last_contacted_at, interaction_count_30d, engagement_status, relationship_health FROM contacts WHERE interaction_count_30d > 2 AND relationship_health > 60 AND archived=0 ORDER BY relationship_health DESC LIMIT 50`).all();
4073
- return rows.map((r) => ({
4074
- ...r,
4075
- signal_type: "warming",
4076
- days_since_contact: r.last_contacted_at ? Math.floor((Date.now() - new Date(r.last_contacted_at).getTime()) / 86400000) : null,
4077
- reason: `${r.interaction_count_30d} interactions in last 30 days`
4078
- }));
4079
- }
4080
- function recomputeAllSignals(db) {
4081
- const _db2 = db || getDatabase();
4082
- _db2.query(`
4083
- UPDATE contacts SET
4084
- engagement_status = CASE
4085
- WHEN interaction_count_30d > 3 THEN 'warm'
4086
- WHEN last_contacted_at IS NULL OR julianday('now') - julianday(last_contacted_at) > 180 THEN 'ghost'
4087
- WHEN julianday('now') - julianday(last_contacted_at) > 60 THEN 'cooling'
4088
- ELSE 'active'
4089
- END,
4090
- updated_at = datetime('now')
4091
- WHERE archived = 0
4092
- `).run();
4093
- const result = _db2.query(`SELECT changes() as n`).get();
4094
- return { updated: result?.n ?? 0 };
4095
- }
4096
- // src/db/freshness.ts
4097
- init_database();
4098
- var SCORED_FIELDS = ["display_name", "job_title", "company_id", "emails", "phones", "last_contacted_at"];
4099
- function getFreshnessScore(contactId, db) {
4100
- const _db2 = db || getDatabase();
4101
- const contact = _db2.query(`SELECT * FROM contacts WHERE id=?`).get(contactId);
4102
- if (!contact)
4103
- throw new Error(`Contact not found: ${contactId}`);
4104
- let historyRows = [];
4105
- try {
4106
- historyRows = _db2.query(`SELECT field_name, new_value, source, created_at FROM contact_field_history WHERE contact_id=? ORDER BY created_at DESC`).all(contactId);
4107
- } catch {}
4108
- let verifiedRows = [];
4109
- try {
4110
- verifiedRows = _db2.query(`SELECT field_name, verified_at, source FROM field_verifications WHERE contact_id=?`).all(contactId);
4111
- } catch {}
4112
- const verifiedMap = new Map(verifiedRows.map((r) => [r.field_name, r]));
4113
- const historyMap = new Map;
4114
- for (const r of historyRows) {
4115
- if (!historyMap.has(r.field_name))
4116
- historyMap.set(r.field_name, r);
4117
- }
4118
- const fields = SCORED_FIELDS.map((field) => {
4119
- let value = null;
4120
- if (field === "emails") {
4121
- const emailRow = _db2.query(`SELECT address FROM emails WHERE contact_id=? LIMIT 1`).get(contactId);
4122
- value = emailRow?.address ?? null;
4123
- } else if (field === "phones") {
4124
- const phoneRow = _db2.query(`SELECT number FROM phones WHERE contact_id=? LIMIT 1`).get(contactId);
4125
- value = phoneRow?.number ?? null;
4126
- } else {
4127
- value = contact[field] != null ? String(contact[field]) : null;
4128
- }
4129
- const verified = verifiedMap.get(field);
4130
- const history = historyMap.get(field);
4131
- let confidence = "unknown";
4132
- let days_old = null;
4133
- let last_verified_at = null;
4134
- let source = null;
4135
- if (verified) {
4136
- confidence = "verified";
4137
- last_verified_at = verified.verified_at;
4138
- source = verified.source;
4139
- days_old = Math.floor((Date.now() - new Date(verified.verified_at).getTime()) / 86400000);
4140
- } else if (history) {
4141
- confidence = history.source === "import" ? "imported" : "inferred";
4142
- last_verified_at = history.created_at;
4143
- source = history.source;
4144
- days_old = Math.floor((Date.now() - new Date(history.created_at).getTime()) / 86400000);
4145
- if (days_old > 365)
4146
- confidence = "stale";
4147
- } else if (value) {
4148
- confidence = "inferred";
4149
- }
4150
- return { field_name: field, value, last_verified_at, source, confidence, days_old };
4151
- });
4152
- const fieldScore = fields.reduce((acc, f) => {
4153
- if (!f.value)
4154
- return acc;
4155
- if (f.confidence === "verified")
4156
- return acc + 20;
4157
- if (f.confidence === "imported" || f.confidence === "inferred")
4158
- return acc + 10;
4159
- return acc + 5;
4160
- }, 0);
4161
- const overall_score = Math.min(100, fieldScore);
4162
- return {
4163
- contact_id: contactId,
4164
- overall_score,
4165
- fields,
4166
- stale_fields: fields.filter((f) => f.confidence === "stale" || !f.value && f.field_name !== "phones").map((f) => f.field_name),
4167
- verified_fields: fields.filter((f) => f.confidence === "verified").map((f) => f.field_name)
4168
- };
4169
- }
4170
- function getStaleContacts(threshold = 40, db) {
4171
- const _db2 = db || getDatabase();
4172
- const rows = _db2.query(`SELECT * FROM (
4173
- SELECT c.id as contact_id, c.display_name,
4174
- (CASE WHEN c.job_title IS NOT NULL THEN 15 ELSE 0 END +
4175
- CASE WHEN c.company_id IS NOT NULL THEN 15 ELSE 0 END +
4176
- CASE WHEN c.last_contacted_at IS NOT NULL THEN 20 ELSE 0 END +
4177
- CASE WHEN EXISTS(SELECT 1 FROM emails WHERE contact_id=c.id) THEN 20 ELSE 0 END +
4178
- CASE WHEN EXISTS(SELECT 1 FROM phones WHERE contact_id=c.id) THEN 15 ELSE 0 END +
4179
- CASE WHEN c.notes IS NOT NULL THEN 10 ELSE 0 END +
4180
- CASE WHEN EXISTS(SELECT 1 FROM contact_tags WHERE contact_id=c.id) THEN 5 ELSE 0 END
4181
- ) as score
4182
- FROM contacts c WHERE c.archived=0
4183
- ) WHERE score < ? ORDER BY score ASC LIMIT 100`).all(threshold);
4184
- return rows;
4185
- }
4186
- function markFieldVerified(contactId, fieldName, source, db) {
4187
- const _db2 = db || getDatabase();
4188
- try {
4189
- _db2.query(`INSERT OR REPLACE INTO field_verifications(contact_id,field_name,verified_at,source) VALUES(?,?,?,?)`).run(contactId, fieldName, now(), source || null);
4190
- } catch {
4191
- _db2.query(`INSERT INTO activity_log(id,contact_id,action,details,created_at) VALUES(?,?,?,?,?)`).run(crypto.randomUUID(), contactId, "field.verified", JSON.stringify({ field_name: fieldName, source }), now());
4192
- }
4193
- }
4194
- // src/lib/context.ts
4195
- init_database();
4196
- init_contacts();
4197
- function getContactCard(contactId, db) {
4198
- const _db2 = db || getDatabase();
4199
- const c = getContact(contactId, _db2);
4200
- const emails = c.emails;
4201
- const phones = c.phones;
4202
- const company = c.company;
4203
- return {
4204
- id: c.id,
4205
- display_name: c.display_name,
4206
- job_title: c.job_title,
4207
- company: company?.name,
4208
- primary_email: emails?.find((e) => e.is_primary)?.address || emails?.[0]?.address,
4209
- primary_phone: phones?.find((p) => p.is_primary)?.number || phones?.[0]?.number
4210
- };
4211
- }
4212
- function getContactBrief(contactId, taskContext, db) {
4213
- const _db2 = db || getDatabase();
4214
- const c = getContact(contactId, _db2);
4215
- const notes = listNotes(contactId, _db2).slice(0, 3);
4216
- const learnings = getLearnings(contactId, { min_importance: 7 }, _db2).slice(0, 5);
4217
- const ctx = (taskContext ?? "").toLowerCase();
4218
- const lastContactedAt = c.last_contacted_at;
4219
- const daysSince = lastContactedAt ? Math.floor((Date.now() - new Date(lastContactedAt).getTime()) / 86400000) : null;
4220
- const company = c.company;
4221
- const brief = {
4222
- id: c.id,
4223
- display_name: c.display_name,
4224
- job_title: c.job_title,
4225
- company: company?.name,
4226
- status: c.status,
4227
- last_contacted: daysSince !== null ? `${daysSince}d ago` : "never",
4228
- relationship_health: c.relationship_health,
4229
- engagement_status: c.engagement_status,
4230
- preferred_contact: c.preferred_contact_method || c.preferred_channel
4231
- };
4232
- if (ctx.includes("meeting") || ctx.includes("call") || ctx.includes("prep")) {
4233
- brief.recent_notes = notes.map((n) => ({ date: n.created_at?.slice(0, 10), content: n.body }));
4234
- brief.key_learnings = learnings.map((l) => l.content);
4235
- }
4236
- if (ctx.includes("outreach") || ctx.includes("email")) {
4237
- brief.preferred_channel = c.preferred_channel;
4238
- brief.follow_up_at = c.follow_up_at;
4239
- }
4240
- if (ctx.includes("deal")) {
4241
- const dealCompany = c.company;
4242
- brief.company_details = dealCompany ? { name: dealCompany.name, domain: dealCompany.domain } : null;
4243
- }
4244
- if (learnings.length)
4245
- brief.top_learnings = learnings.map((l) => l.content);
4246
- return brief;
4247
- }
4248
- async function assembleContext(contactIds, format = "meeting_prep", db) {
4249
- const _db2 = db || getDatabase();
4250
- const briefs = contactIds.map((id) => {
4251
- try {
4252
- return getContactBrief(id, format, _db2);
4253
- } catch {
4254
- return { id, error: "not found" };
4255
- }
4256
- });
4257
- return { format, contact_count: contactIds.length, assembled_at: new Date().toISOString(), contacts: briefs };
4258
- }
4259
- // src/lib/embeddings.ts
4260
- init_database();
4261
- function tokenize(text) {
4262
- return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((t) => t.length > 2);
4263
- }
4264
- function buildTfIdf(tokens) {
4265
- const freq = new Map;
4266
- for (const t of tokens)
4267
- freq.set(t, (freq.get(t) || 0) + 1);
4268
- const max = Math.max(...freq.values(), 1);
4269
- const result = new Map;
4270
- freq.forEach((v, k) => result.set(k, v / max));
4271
- return result;
4272
- }
4273
- function cosineSimilarity(a, b) {
4274
- let dot = 0, normA = 0, normB = 0;
4275
- a.forEach((v, k) => {
4276
- if (b.has(k))
4277
- dot += v * b.get(k);
4278
- normA += v * v;
4279
- });
4280
- b.forEach((v) => normB += v * v);
4281
- return normA && normB ? dot / (Math.sqrt(normA) * Math.sqrt(normB)) : 0;
4282
- }
4283
- function buildContactEmbeddingText(contact) {
4284
- const tags = contact.tags ?? [];
4285
- const socialProfiles = contact.social_profiles ?? [];
4286
- const company = contact.company;
4287
- const parts = [
4288
- contact.display_name,
4289
- contact.job_title,
4290
- contact.notes,
4291
- company?.name,
4292
- company?.industry,
4293
- ...tags.map((t) => t.name),
4294
- ...socialProfiles.map((s) => s.platform)
4295
- ].filter(Boolean);
4296
- return parts.join(" ");
4297
- }
4298
- async function embedContact(contactId, db) {
4299
- const { getContact: getContact2 } = await Promise.resolve().then(() => (init_contacts(), exports_contacts));
4300
- const _db2 = db || getDatabase();
4301
- const contact = getContact2(contactId, _db2);
4302
- const text = buildContactEmbeddingText(contact);
4303
- const tokens = tokenize(text);
4304
- const tfidf = buildTfIdf(tokens);
4305
- const embedding = JSON.stringify(Array.from(tfidf.entries()).sort((a, b) => b[1] - a[1]).slice(0, 100));
4306
- _db2.query(`INSERT OR REPLACE INTO contact_embeddings(contact_id, embedding, model, embedded_text, created_at, updated_at) VALUES(?,?,'tfidf',?,?,?)`).run(contactId, embedding, text.slice(0, 500), now(), now());
4307
- }
4308
- async function embedAllContacts(db) {
4309
- const _db2 = db || getDatabase();
4310
- const contacts = _db2.query(`SELECT id FROM contacts WHERE archived=0`).all();
4311
- for (const c of contacts) {
4312
- try {
4313
- await embedContact(c.id, _db2);
4314
- } catch {}
4315
- }
4316
- return contacts.length;
4317
- }
4318
- function semanticSearch(query, limit = 10, db) {
4319
- const _db2 = db || getDatabase();
4320
- const queryTokens = buildTfIdf(tokenize(query));
4321
- let embeddings = [];
4322
- try {
4323
- embeddings = _db2.query(`SELECT contact_id, embedding FROM contact_embeddings`).all();
4324
- } catch {
4325
- return [];
4326
- }
4327
- const results = embeddings.map((e) => {
4328
- try {
4329
- const emb = new Map(JSON.parse(e.embedding));
4330
- return { contact_id: e.contact_id, score: cosineSimilarity(queryTokens, emb) };
4331
- } catch {
4332
- return { contact_id: e.contact_id, score: 0 };
4333
- }
4334
- }).filter((r) => r.score > 0).sort((a, b) => b.score - a.score).slice(0, limit);
4335
- return results;
4336
- }
4337
- // src/lib/signature-parser.ts
4338
- function parseEmailSignature(text) {
4339
- const result = {};
4340
- const phoneMatch = text.match(/(\+?[\d\s\-\(\)]{7,20})/);
4341
- if (phoneMatch)
4342
- result.phone = phoneMatch[1]?.trim();
4343
- const emailMatch = text.match(/[\w.+-]+@[\w-]+\.[a-z]{2,}/i);
4344
- if (emailMatch)
4345
- result.email = emailMatch[0];
4346
- const linkedinMatch = text.match(/(?:linkedin\.com\/in\/)([\w-]+)/i);
4347
- if (linkedinMatch)
4348
- result.linkedin = `https://linkedin.com/in/${linkedinMatch[1]}`;
4349
- const websiteMatch = text.match(/https?:\/\/(?!linkedin)(?!twitter)[\w.-]+\.[a-z]{2,}/i);
4350
- if (websiteMatch)
4351
- result.website = websiteMatch[0];
4352
- const lines = text.split(`
4353
- `).map((l) => l.trim()).filter((l) => l.length > 2 && l.length < 80);
4354
- if (lines[0])
4355
- result.name = lines[0];
4356
- for (const line of lines.slice(1)) {
4357
- if (line.match(/\b(CEO|CTO|VP|Director|Manager|Engineer|Partner|Associate|Consultant|Analyst|President|Founder)\b/i)) {
4358
- result.title = line;
4359
- } else if (!result.company && line.match(/^[A-Z][A-Za-z\s,\.]+$/) && !line.includes("@")) {
4360
- result.company = line;
4361
- }
4362
- }
4363
- return result;
4364
- }
4365
- function extractContactsFromEmailThread(participants) {
4366
- return participants.map((p) => {
4367
- const sig = p.signature ? parseEmailSignature(p.signature) : {};
4368
- const name = p.name || sig.name || p.email.split("@")[0] || "Unknown";
4369
- const contact = {
4370
- display_name: name,
4371
- emails: [{ address: p.email, type: "work", is_primary: true }],
4372
- source: "import"
4373
- };
4374
- if (sig.title)
4375
- contact.job_title = sig.title;
4376
- if (sig.phone)
4377
- contact.phones = [{ number: sig.phone, type: "work", is_primary: true }];
4378
- if (sig.linkedin)
4379
- contact.social_profiles = [{ platform: "linkedin", url: sig.linkedin, is_primary: true }];
4380
- if (sig.website)
4381
- contact.website = sig.website;
4382
- return contact;
4383
- });
4384
- }
4385
- // src/lib/meeting-capture.ts
4386
- init_database();
4387
- async function ingestMeetingParticipants(event, db) {
4388
- const { findOrCreateContact: findOrCreateContact2 } = await Promise.resolve().then(() => (init_contacts(), exports_contacts));
4389
- const { logEvent: logEvent2 } = await Promise.resolve().then(() => (init_events(), exports_events));
4390
- const _db2 = db || getDatabase();
4391
- let created = 0;
4392
- let updated = 0;
4393
- const ids = [];
4394
- for (const a of event.attendees) {
4395
- try {
4396
- const nameParts = a.name.split(" ");
4397
- const result = await findOrCreateContact2({
4398
- display_name: a.name,
4399
- first_name: nameParts[0],
4400
- last_name: nameParts.slice(1).join(" ") || undefined,
4401
- emails: [{ address: a.email, type: "work", is_primary: true }],
4402
- source: "import"
4403
- }, _db2);
4404
- ids.push(result.contact.id);
4405
- if (result.created)
4406
- created++;
4407
- else
4408
- updated++;
4409
- } catch {}
4410
- }
4411
- if (ids.length) {
4412
- try {
4413
- logEvent2({
4414
- title: event.title,
4415
- type: "meeting",
4416
- event_date: event.event_date,
4417
- contact_ids: ids,
4418
- notes: event.context
4419
- }, _db2);
4420
- } catch {}
4421
- }
4422
- return { created, updated, contact_ids: ids };
4423
- }
4424
-
4425
- // src/index.ts
4426
- init_contacts();
4427
-
4428
- // src/lib/images.ts
4429
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, copyFileSync, unlinkSync, readdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
4430
- import { join as join3, extname, basename } from "path";
4431
- var IMAGES_DIR = join3(process.env["HOME"] || "~", ".contacts", "images");
4432
- function ensureImagesDir() {
4433
- if (!existsSync3(IMAGES_DIR))
4434
- mkdirSync2(IMAGES_DIR, { recursive: true });
4435
- }
4436
- function getImagesDir() {
4437
- ensureImagesDir();
4438
- return IMAGES_DIR;
4439
- }
4440
- function saveImage(entityId, source, options) {
4441
- ensureImagesDir();
4442
- deleteImage(entityId);
4443
- const base64Match = source.match(/^data:image\/(\w+);base64,(.+)$/s);
4444
- if (base64Match) {
4445
- const ext2 = base64Match[1] === "jpeg" ? "jpg" : base64Match[1];
4446
- const data = Buffer.from(base64Match[2], "base64");
4447
- const filename2 = `${entityId}.${ext2}`;
4448
- writeFileSync(join3(IMAGES_DIR, filename2), data);
4449
- return filename2;
4450
- }
4451
- if (!existsSync3(source) && /^[A-Za-z0-9+/=\n\r]+$/.test(source.trim()) && source.length > 100) {
4452
- const ext2 = options?.format || "jpg";
4453
- const data = Buffer.from(source.trim(), "base64");
4454
- const filename2 = `${entityId}.${ext2}`;
4455
- writeFileSync(join3(IMAGES_DIR, filename2), data);
4456
- return filename2;
4457
- }
4458
- if (!existsSync3(source)) {
4459
- throw new Error(`Image file not found: ${source}`);
4460
- }
4461
- const ext = extname(source).slice(1).toLowerCase() || "jpg";
4462
- const validExts = ["jpg", "jpeg", "png", "gif", "webp", "svg", "avif", "ico"];
4463
- if (!validExts.includes(ext)) {
4464
- throw new Error(`Unsupported image format: ${ext}. Supported: ${validExts.join(", ")}`);
4465
- }
4466
- const filename = `${entityId}.${ext === "jpeg" ? "jpg" : ext}`;
4467
- copyFileSync(source, join3(IMAGES_DIR, filename));
4468
- return filename;
4469
- }
4470
- function getImagePath(entityId) {
4471
- ensureImagesDir();
4472
- const files = readdirSync(IMAGES_DIR);
4473
- const match = files.find((f) => f.startsWith(`${entityId}.`));
4474
- return match ? join3(IMAGES_DIR, match) : null;
4475
- }
4476
- function getImageAsBase64(entityId) {
4477
- const path = getImagePath(entityId);
4478
- if (!path)
4479
- return null;
4480
- const ext = extname(path).slice(1);
4481
- const mime = ext === "jpg" ? "image/jpeg" : ext === "svg" ? "image/svg+xml" : `image/${ext}`;
4482
- const data = readFileSync2(path);
4483
- return `data:${mime};base64,${data.toString("base64")}`;
4484
- }
4485
- function deleteImage(entityId) {
4486
- ensureImagesDir();
4487
- const files = readdirSync(IMAGES_DIR);
4488
- let deleted = false;
4489
- for (const f of files) {
4490
- if (f.startsWith(`${entityId}.`)) {
4491
- unlinkSync(join3(IMAGES_DIR, f));
4492
- deleted = true;
4493
- }
4494
- }
4495
- return deleted;
4496
- }
4497
- function listImages() {
4498
- ensureImagesDir();
4499
- const files = readdirSync(IMAGES_DIR).filter((f) => !f.startsWith("."));
4500
- return files.map((f) => ({
4501
- entity_id: basename(f, extname(f)),
4502
- filename: f,
4503
- path: join3(IMAGES_DIR, f)
4504
- }));
4505
- }
4506
- // src/lib/vault.ts
4507
- import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync3, unlinkSync as unlinkSync2 } from "fs";
4508
- import { join as join4 } from "path";
4509
- import { createCipheriv, createDecipheriv, randomBytes, pbkdf2Sync, createHash } from "crypto";
4510
- var VAULT_DIR = join4(process.env["HOME"] || "~", ".contacts");
4511
- var VAULT_CONFIG = join4(VAULT_DIR, "vault.json");
4512
- var VAULT_SESSION = join4(VAULT_DIR, ".vault-session");
4513
- var DOCUMENTS_DIR = join4(VAULT_DIR, "documents");
4514
- var SESSION_TTL_MS = 30 * 60 * 1000;
4515
- var _derivedKey = null;
4516
- function deriveKey(passphrase, salt) {
4517
- return pbkdf2Sync(passphrase, salt, 1e5, 32, "sha512");
4518
- }
4519
- function saveSession(key) {
4520
- const session = {
4521
- key: key.toString("hex"),
4522
- expires_at: new Date(Date.now() + SESSION_TTL_MS).toISOString()
4523
- };
4524
- writeFileSync2(VAULT_SESSION, JSON.stringify(session), { mode: 384 });
4525
- }
4526
- function loadSession() {
4527
- if (!existsSync4(VAULT_SESSION))
4528
- return null;
4529
- try {
4530
- const session = JSON.parse(readFileSync3(VAULT_SESSION, "utf-8"));
4531
- if (new Date(session.expires_at).getTime() < Date.now()) {
4532
- try {
4533
- unlinkSync2(VAULT_SESSION);
4534
- } catch {}
4535
- return null;
4536
- }
4537
- return Buffer.from(session.key, "hex");
4538
- } catch {
4539
- return null;
4540
- }
4541
- }
4542
- function clearSession() {
4543
- try {
4544
- if (existsSync4(VAULT_SESSION))
4545
- unlinkSync2(VAULT_SESSION);
4546
- } catch {}
4547
- }
4548
- function initVault(passphrase) {
4549
- if (!existsSync4(VAULT_DIR))
4550
- mkdirSync3(VAULT_DIR, { recursive: true });
4551
- if (!existsSync4(DOCUMENTS_DIR))
4552
- mkdirSync3(DOCUMENTS_DIR, { recursive: true });
4553
- const salt = randomBytes(32);
4554
- const key = deriveKey(passphrase, salt);
4555
- const keyHash = createHash("sha256").update(key).digest("hex");
4556
- const config = { salt: salt.toString("hex"), key_hash: keyHash, created_at: new Date().toISOString() };
4557
- writeFileSync2(VAULT_CONFIG, JSON.stringify(config, null, 2));
4558
- _derivedKey = key;
4559
- saveSession(key);
4560
- }
4561
- function isVaultInitialized() {
4562
- return existsSync4(VAULT_CONFIG);
4563
- }
4564
- function unlockVault(passphrase) {
4565
- if (!existsSync4(VAULT_CONFIG))
4566
- throw new Error("Vault not initialized. Run 'contacts vault init' first.");
4567
- const config = JSON.parse(readFileSync3(VAULT_CONFIG, "utf-8"));
4568
- const salt = Buffer.from(config.salt, "hex");
4569
- const key = deriveKey(passphrase, salt);
4570
- const keyHash = createHash("sha256").update(key).digest("hex");
4571
- if (keyHash !== config.key_hash)
4572
- return false;
4573
- _derivedKey = key;
4574
- saveSession(key);
4575
- return true;
4576
- }
4577
- function lockVault() {
4578
- _derivedKey = null;
4579
- clearSession();
4580
- }
4581
- function isVaultUnlocked() {
4582
- if (_derivedKey)
4583
- return true;
4584
- const sessionKey = loadSession();
4585
- if (sessionKey) {
4586
- _derivedKey = sessionKey;
4587
- return true;
4588
- }
4589
- return false;
4590
- }
4591
- function requireVault() {
4592
- if (_derivedKey)
4593
- return _derivedKey;
4594
- const sessionKey = loadSession();
4595
- if (sessionKey) {
4596
- _derivedKey = sessionKey;
4597
- return _derivedKey;
4598
- }
4599
- throw new Error("Vault is locked. Unlock with 'contacts vault unlock --passphrase <pass>' or vault_unlock MCP tool first.");
4600
- }
4601
- function encrypt(plaintext) {
4602
- const key = requireVault();
4603
- const iv = randomBytes(16);
4604
- const cipher = createCipheriv("aes-256-gcm", key, iv);
4605
- let encrypted = cipher.update(plaintext, "utf8", "hex");
4606
- encrypted += cipher.final("hex");
4607
- const authTag = cipher.getAuthTag().toString("hex");
4608
- return { ciphertext: encrypted + ":" + authTag, iv: iv.toString("hex") };
4609
- }
4610
- function decrypt(ciphertext, iv) {
4611
- const key = requireVault();
4612
- const [encData, authTag] = ciphertext.split(":");
4613
- if (!encData || !authTag)
4614
- throw new Error("Invalid ciphertext format");
4615
- const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "hex"));
4616
- decipher.setAuthTag(Buffer.from(authTag, "hex"));
4617
- let decrypted = decipher.update(encData, "hex", "utf8");
4618
- decrypted += decipher.final("utf8");
4619
- return decrypted;
4620
- }
4621
- function storeFile(sourcePath, entityId) {
4622
- if (!existsSync4(DOCUMENTS_DIR))
4623
- mkdirSync3(DOCUMENTS_DIR, { recursive: true });
4624
- const ext = sourcePath.split(".").pop() || "bin";
4625
- const destPath = join4(DOCUMENTS_DIR, `${entityId}.${ext}`);
4626
- const data = readFileSync3(sourcePath);
4627
- writeFileSync2(destPath, data);
4628
- return destPath;
4629
- }
4630
- function getDocumentFilePath(entityId) {
4631
- if (!existsSync4(DOCUMENTS_DIR))
4632
- return null;
4633
- const { readdirSync: readdirSync2 } = __require("fs");
4634
- const files = readdirSync2(DOCUMENTS_DIR);
4635
- const match = files.find((f) => f.startsWith(`${entityId}.`) && !f.endsWith(".enc"));
4636
- return match ? join4(DOCUMENTS_DIR, match) : null;
4637
- }
4638
- function decryptFile(encPath) {
4639
- const key = requireVault();
4640
- const data = readFileSync3(encPath);
4641
- const iv = data.subarray(0, 16);
4642
- const authTag = data.subarray(16, 32);
4643
- const encrypted = data.subarray(32);
4644
- const decipher = createDecipheriv("aes-256-gcm", key, iv);
4645
- decipher.setAuthTag(authTag);
4646
- return Buffer.concat([decipher.update(encrypted), decipher.final()]);
4647
- }
4648
- function getDocumentsDir() {
4649
- if (!existsSync4(DOCUMENTS_DIR))
4650
- mkdirSync3(DOCUMENTS_DIR, { recursive: true });
4651
- return DOCUMENTS_DIR;
4652
- }
4653
- // src/db/documents.ts
4654
- init_database();
4655
- import { existsSync as existsSync5, unlinkSync as unlinkSync3 } from "fs";
4656
- var DOCUMENT_TYPES = [
4657
- "passport",
4658
- "national_id",
4659
- "tax_id",
4660
- "ssn",
4661
- "drivers_license",
4662
- "bank_account",
4663
- "visa",
4664
- "insurance",
4665
- "contract",
4666
- "certificate",
4667
- "medical_record",
4668
- "prescription",
4669
- "allergy_list",
4670
- "vaccination",
4671
- "blood_type",
4672
- "health_insurance",
4673
- "medical_condition",
4674
- "emergency_contact_medical",
4675
- "other"
4676
- ];
4677
- function addDocument(input, db) {
4678
- requireVault();
4679
- const _db2 = db || getDatabase();
4680
- const id = uuid();
4681
- const { ciphertext, iv } = encrypt(input.value);
4682
- let filePath = null;
4683
- if (input.file_path) {
4684
- filePath = storeFile(input.file_path, id);
4685
- }
4686
- _db2.query(`INSERT INTO contact_documents (id, contact_id, doc_type, label, encrypted_value, iv, encrypted_file_path, metadata, expires_at, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(id, input.contact_id, input.doc_type, input.label ?? null, ciphertext, iv, filePath, JSON.stringify(input.metadata || {}), input.expires_at ?? null, now(), now());
4687
- return getDocument(id, _db2);
4688
- }
4689
- function getDocument(id, db) {
4690
- requireVault();
4691
- const _db2 = db || getDatabase();
4692
- const row = _db2.query(`SELECT * FROM contact_documents WHERE id = ?`).get(id);
4693
- if (!row)
4694
- throw new Error(`Document not found: ${id}`);
4695
- return rowToDoc(row);
4696
- }
4697
- function listDocuments(contactId, db) {
4698
- const _db2 = db || getDatabase();
4699
- const rows = _db2.query(`SELECT id, doc_type, label, encrypted_file_path, expires_at, created_at FROM contact_documents WHERE contact_id = ? ORDER BY created_at DESC`).all(contactId);
4700
- return rows.map((r) => ({
4701
- id: r.id,
4702
- doc_type: r.doc_type,
4703
- label: r.label,
4704
- has_file: !!r.encrypted_file_path,
4705
- expires_at: r.expires_at,
4706
- created_at: r.created_at
4707
- }));
4708
- }
4709
- function deleteDocument(id, db) {
4710
- const _db2 = db || getDatabase();
4711
- const row = _db2.query(`SELECT encrypted_file_path FROM contact_documents WHERE id = ?`).get(id);
4712
- if (row?.encrypted_file_path && existsSync5(row.encrypted_file_path)) {
4713
- try {
4714
- unlinkSync3(row.encrypted_file_path);
4715
- } catch {}
4716
- }
4717
- _db2.query(`DELETE FROM contact_documents WHERE id = ?`).run(id);
4718
- }
4719
- function rowToDoc(row) {
4720
- return {
4721
- id: row.id,
4722
- contact_id: row.contact_id,
4723
- doc_type: row.doc_type,
4724
- label: row.label,
4725
- value: decrypt(row.encrypted_value, row.iv),
4726
- has_file: !!row.encrypted_file_path,
4727
- file_path: row.encrypted_file_path,
4728
- metadata: JSON.parse(row.metadata || "{}"),
4729
- expires_at: row.expires_at,
4730
- created_at: row.created_at,
4731
- updated_at: row.updated_at
4732
- };
4733
- }
4734
- // src/db/health.ts
4735
- init_database();
4736
- function setHealthData(contactId, input, db) {
4737
- requireVault();
4738
- const _db2 = db || getDatabase();
4739
- const existing = _db2.query(`SELECT id FROM contact_health WHERE contact_id = ?`).get(contactId);
4740
- if (existing) {
4741
- const sets = [];
4742
- const params = [];
4743
- if (input.blood_type !== undefined) {
4744
- sets.push("blood_type = ?");
4745
- params.push(input.blood_type);
4746
- }
4747
- if (input.allergies !== undefined) {
4748
- sets.push("allergies = ?");
4749
- params.push(JSON.stringify(input.allergies));
4750
- }
4751
- if (input.medical_conditions !== undefined) {
4752
- sets.push("medical_conditions = ?");
4753
- params.push(JSON.stringify(input.medical_conditions));
4754
- }
4755
- if (input.medications !== undefined) {
4756
- sets.push("medications = ?");
4757
- params.push(JSON.stringify(input.medications));
4758
- }
4759
- if (input.emergency_contacts !== undefined) {
4760
- sets.push("emergency_contacts = ?");
4761
- params.push(JSON.stringify(input.emergency_contacts));
4762
- }
4763
- if (input.health_insurance_provider !== undefined) {
4764
- sets.push("health_insurance_provider = ?");
4765
- params.push(input.health_insurance_provider);
4766
- }
4767
- if (input.health_insurance_id !== undefined) {
4768
- sets.push("health_insurance_id = ?");
4769
- params.push(input.health_insurance_id);
4770
- }
4771
- if (input.primary_physician !== undefined) {
4772
- sets.push("primary_physician = ?");
4773
- params.push(input.primary_physician);
4774
- }
4775
- if (input.primary_physician_phone !== undefined) {
4776
- sets.push("primary_physician_phone = ?");
4777
- params.push(input.primary_physician_phone);
4778
- }
4779
- if (input.organ_donor !== undefined) {
4780
- sets.push("organ_donor = ?");
4781
- params.push(input.organ_donor ? 1 : 0);
4782
- }
4783
- if (input.notes !== undefined) {
4784
- sets.push("notes = ?");
4785
- params.push(input.notes);
4786
- }
4787
- if (sets.length) {
4788
- sets.push("updated_at = ?");
4789
- params.push(now());
4790
- params.push(contactId);
4791
- _db2.query(`UPDATE contact_health SET ${sets.join(", ")} WHERE contact_id = ?`).run(...params);
4792
- }
4793
- } else {
4794
- const id = uuid();
4795
- _db2.query(`INSERT INTO contact_health (id, contact_id, blood_type, allergies, medical_conditions, medications, emergency_contacts, health_insurance_provider, health_insurance_id, primary_physician, primary_physician_phone, organ_donor, notes, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(id, contactId, input.blood_type ?? null, JSON.stringify(input.allergies || []), JSON.stringify(input.medical_conditions || []), JSON.stringify(input.medications || []), JSON.stringify(input.emergency_contacts || []), input.health_insurance_provider ?? null, input.health_insurance_id ?? null, input.primary_physician ?? null, input.primary_physician_phone ?? null, input.organ_donor ? 1 : 0, input.notes ?? null, now(), now());
4796
- }
4797
- return getHealthData(contactId, _db2);
4798
- }
4799
- function getHealthData(contactId, db) {
4800
- requireVault();
4801
- const _db2 = db || getDatabase();
4802
- const row = _db2.query(`SELECT * FROM contact_health WHERE contact_id = ?`).get(contactId);
4803
- if (!row)
4804
- return null;
4805
- return {
4806
- id: row.id,
4807
- contact_id: row.contact_id,
4808
- blood_type: row.blood_type,
4809
- allergies: JSON.parse(row.allergies || "[]"),
4810
- medical_conditions: JSON.parse(row.medical_conditions || "[]"),
4811
- medications: JSON.parse(row.medications || "[]"),
4812
- emergency_contacts: JSON.parse(row.emergency_contacts || "[]"),
4813
- health_insurance_provider: row.health_insurance_provider,
4814
- health_insurance_id: row.health_insurance_id,
4815
- primary_physician: row.primary_physician,
4816
- primary_physician_phone: row.primary_physician_phone,
4817
- organ_donor: !!row.organ_donor,
4818
- notes: row.notes,
4819
- created_at: row.created_at,
4820
- updated_at: row.updated_at
4821
- };
4822
- }
4823
- function deleteHealthData(contactId, db) {
4824
- const _db2 = db || getDatabase();
4825
- _db2.query(`DELETE FROM contact_health WHERE contact_id = ?`).run(contactId);
4826
- }
4827
- // src/lib/document-scanner.ts
4828
- import { readFileSync as readFileSync4, existsSync as existsSync6 } from "fs";
4829
- import { extname as extname2 } from "path";
4830
- async function scanDocument(imageSource, docType) {
4831
- const apiKey = process.env["OPENAI_API_KEY"];
4832
- if (!apiKey) {
4833
- throw new Error("OPENAI_API_KEY not set. Set it in ~/.secrets or environment to use document scanning.");
4834
- }
4835
- let imageData;
4836
- if (imageSource.startsWith("data:image/")) {
4837
- imageData = imageSource;
4838
- } else if (existsSync6(imageSource)) {
4839
- const buffer = readFileSync4(imageSource);
4840
- const ext = extname2(imageSource).slice(1).toLowerCase();
4841
- const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "png" ? "image/png" : ext === "webp" ? "image/webp" : ext === "gif" ? "image/gif" : "image/jpeg";
4842
- imageData = `data:${mime};base64,${buffer.toString("base64")}`;
4843
- } else if (/^[A-Za-z0-9+/=\n\r]+$/.test(imageSource.trim()) && imageSource.length > 100) {
4844
- imageData = `data:image/jpeg;base64,${imageSource.trim()}`;
4845
- } else {
4846
- throw new Error(`Image source not found or invalid: ${imageSource.slice(0, 50)}...`);
4847
- }
4848
- const typeHint = docType ? ` This is a ${docType} document.` : "";
4849
- const prompt = `Extract all text and structured data from this document image.${typeHint} Return a JSON object with these fields:
4850
- - document_type: detected type (passport, national_id, drivers_license, tax_document, medical_record, prescription, insurance_card, bank_statement, visa, certificate, contract, other)
4851
- - full_name: full name as shown
4852
- - date_of_birth: in YYYY-MM-DD format if visible
4853
- - document_number: main ID/document number
4854
- - issuing_country: country code or name
4855
- - issue_date: in YYYY-MM-DD format if visible
4856
- - expiry_date: in YYYY-MM-DD format if visible
4857
- - address: full address if visible
4858
- - nationality: if visible
4859
- - gender: if visible
4860
- - mrz_code: Machine Readable Zone text if this is a passport/ID with MRZ
4861
- - phone: any phone numbers visible
4862
- - email: any email addresses visible
4863
- - additional_fields: object with any other visible structured data
4864
- - raw_text: all visible text transcribed
4865
-
4866
- Only include fields that are actually visible in the document. Return valid JSON only.`;
4867
- const response = await fetch("https://api.openai.com/v1/chat/completions", {
4868
- method: "POST",
4869
- headers: {
4870
- Authorization: `Bearer ${apiKey}`,
4871
- "Content-Type": "application/json"
4872
- },
4873
- body: JSON.stringify({
4874
- model: "gpt-4o",
4875
- messages: [
4876
- {
4877
- role: "user",
4878
- content: [
4879
- { type: "text", text: prompt },
4880
- { type: "image_url", image_url: { url: imageData, detail: "high" } }
4881
- ]
4882
- }
4883
- ],
4884
- max_tokens: 2000,
4885
- temperature: 0
4886
- })
4887
- });
4888
- if (!response.ok) {
4889
- const err = await response.text();
4890
- throw new Error(`OpenAI API error: ${response.status} \u2014 ${err}`);
4891
- }
4892
- const data = await response.json();
4893
- const content = data.choices?.[0]?.message?.content || "";
4894
- const jsonMatch = content.match(/```json\s*([\s\S]*?)```/) || content.match(/\{[\s\S]*\}/);
4895
- if (!jsonMatch) {
4896
- return { fields: {}, raw_text: content, document_type: docType || "unknown", confidence: 0.3 };
4897
- }
4898
- try {
4899
- const parsed = JSON.parse(jsonMatch[1] || jsonMatch[0]);
4900
- const { document_type, raw_text, additional_fields, ...mainFields } = parsed;
4901
- const fields = {};
4902
- for (const [k, v] of Object.entries(mainFields)) {
4903
- if (v && typeof v === "string")
4904
- fields[k] = v;
4905
- }
4906
- if (additional_fields && typeof additional_fields === "object") {
4907
- for (const [k, v] of Object.entries(additional_fields)) {
4908
- if (v && typeof v === "string")
4909
- fields[k] = v;
4910
- }
4911
- }
4912
- return {
4913
- fields,
4914
- raw_text: raw_text || content,
4915
- document_type: document_type || docType || "unknown",
4916
- confidence: Object.keys(fields).length > 3 ? 0.9 : Object.keys(fields).length > 0 ? 0.7 : 0.3
4917
- };
4918
- } catch {
4919
- return { fields: {}, raw_text: content, document_type: docType || "unknown", confidence: 0.3 };
4920
- }
4921
- }
4922
3534
  export {
4923
3535
  updateVendorCommunication,
4924
3536
  updateTag,
@@ -4929,48 +3541,29 @@ export {
4929
3541
  updateContact,
4930
3542
  updateCompany,
4931
3543
  updateApplication,
4932
- unlockVault,
4933
3544
  unarchiveContact,
4934
3545
  unarchiveCompany,
4935
- storeFile,
4936
- setHealthData,
4937
- setDealContactRole,
4938
- semanticSearch,
4939
- searchLearnings,
4940
3546
  searchGoogleContacts,
4941
3547
  searchContacts,
4942
3548
  searchCompanies,
4943
- scanDocument,
4944
- saveLearning,
4945
- saveImage,
4946
3549
  runConnector,
4947
- resolveIdentity,
4948
- resolveByPartial,
4949
3550
  resetDatabase,
4950
- requireVault,
4951
3551
  removeTagFromContact,
4952
3552
  removeTagFromCompany,
4953
3553
  removeOrgMember,
4954
3554
  removeContactFromGroup,
4955
3555
  removeCompanyFromGroup,
4956
- releaseLock,
4957
- recordFieldChange,
4958
- recomputeAllSignals,
4959
3556
  readConnectorTokens,
4960
3557
  pushContactToGoogle,
4961
3558
  pullGoogleContactsAsInputs,
4962
3559
  parseName,
4963
3560
  parseLinkedIn,
4964
- parseEmailSignature,
4965
3561
  parseAddressHeader,
4966
3562
  mergeContacts,
4967
3563
  markFollowUpDone,
4968
- markFieldVerified,
4969
3564
  logVendorCommunication,
4970
3565
  logEvent,
4971
- logAgentActivity,
4972
3566
  logActivity,
4973
- lockVault,
4974
3567
  listVendorCommunications,
4975
3568
  listTags,
4976
3569
  listRelationships,
@@ -4981,18 +3574,15 @@ export {
4981
3574
  listOverdueTasks,
4982
3575
  listOrgMembersForContact,
4983
3576
  listOrgMembers,
4984
- listOrgChart,
4985
3577
  listNotesForContactAtCompany,
4986
3578
  listNotes,
4987
3579
  listMissingInvoices,
4988
- listImages,
4989
3580
  listGroupsForContact,
4990
3581
  listGroupsForCompany,
4991
3582
  listGroups,
4992
3583
  listGoogleContacts,
4993
3584
  listFollowUpDue,
4994
3585
  listEvents,
4995
- listDocuments,
4996
3586
  listDeals,
4997
3587
  listContactsInGroup,
4998
3588
  listContactsByTag,
@@ -5006,91 +3596,48 @@ export {
5006
3596
  listColdContacts,
5007
3597
  listApplications,
5008
3598
  listActivity,
5009
- isVaultUnlocked,
5010
- isVaultInitialized,
5011
- initVault,
5012
- ingestMeetingParticipants,
5013
3599
  importToApple,
5014
3600
  importFromCsv,
5015
3601
  importContacts,
5016
3602
  googlePersonToContactInput,
5017
- getWarmingContacts,
5018
3603
  getUpcomingItems,
5019
3604
  getTagByName,
5020
3605
  getTag,
5021
- getStaleContacts,
5022
- getRelationshipSignals,
5023
3606
  getRelationship,
5024
- getPreviousEmployers,
5025
3607
  getOrgMember,
5026
3608
  getNote,
5027
3609
  getNetworkStats,
5028
- getLearnings,
5029
- getJobHistory,
5030
- getImagesDir,
5031
- getImagePath,
5032
- getImageAsBase64,
5033
- getIdentities,
5034
- getHealthData,
5035
3610
  getGroup,
5036
- getGhostContacts,
5037
- getFreshnessScore,
5038
- getFieldHistory,
5039
3611
  getEvent,
5040
3612
  getEntityTeam,
5041
- getDocumentsDir,
5042
- getDocumentFilePath,
5043
- getDocument,
5044
3613
  getDealsByStage,
5045
- getDealTeam,
5046
3614
  getDeal,
5047
3615
  getDatabase,
5048
- getCurrentRole,
5049
- getCoverageGaps,
5050
3616
  getContactTimeline,
5051
3617
  getContactTask,
5052
- getContactCard,
5053
3618
  getContactByEmail,
5054
- getContactBrief,
5055
- getContactAt,
5056
3619
  getContact,
5057
3620
  getConnectorTokenPath,
5058
3621
  getCompany,
5059
3622
  getApplication,
5060
- getAgentActivity,
5061
3623
  getActivity,
5062
3624
  generateBrief,
5063
- findWarmPath,
5064
- findOrCreateContact,
5065
- findConnectionsAtCompany,
5066
3625
  extractContactsFromGmail,
5067
- extractContactsFromEmailThread,
5068
3626
  exportFromApple,
5069
3627
  exportContacts,
5070
- encrypt,
5071
- embedContact,
5072
- embedAllContacts,
5073
3628
  domainToCompany,
5074
- detectCoolingRelationships,
5075
3629
  deleteVendorCommunication,
5076
3630
  deleteTag,
5077
3631
  deleteRelationship,
5078
3632
  deleteNote,
5079
- deleteLearning,
5080
- deleteImage,
5081
- deleteHealthData,
5082
3633
  deleteGroup,
5083
3634
  deleteEvent,
5084
- deleteDocument,
5085
3635
  deleteDeal,
5086
3636
  deleteContactTask,
5087
3637
  deleteContact,
5088
3638
  deleteCompanyRelationship,
5089
3639
  deleteCompany,
5090
3640
  deleteApplication,
5091
- decryptFile,
5092
- decrypt,
5093
- decayLearnings,
5094
3641
  createTag,
5095
3642
  createRelationship,
5096
3643
  createGroup,
@@ -5101,33 +3648,21 @@ export {
5101
3648
  createCompany,
5102
3649
  createApplication,
5103
3650
  contactToGoogleArgs,
5104
- confirmLearning,
5105
- computeRelationshipStrength,
5106
- cleanExpiredLocks,
5107
- checkLock,
5108
3651
  checkEscalations,
5109
- buildContactEmbeddingText,
5110
3652
  autoLinkContactToCompany,
5111
3653
  auditContact,
5112
- assembleContext,
5113
3654
  archiveContact,
5114
3655
  archiveCompany,
5115
3656
  addTagToContact,
5116
3657
  addTagToCompany,
5117
3658
  addPhoneToContact,
5118
3659
  addOrgMember,
5119
- addOrgChartEdge,
5120
3660
  addNote,
5121
- addJobEntry,
5122
- addIdentity,
5123
3661
  addEmailToContact,
5124
- addDocument,
5125
3662
  addContactToGroup,
5126
3663
  addCompanyToGroup,
5127
- acquireLock,
5128
3664
  TagNotFoundError,
5129
3665
  DuplicateTagNameError,
5130
- DOCUMENT_TYPES,
5131
3666
  ContactNotFoundError,
5132
3667
  ConnectorNotInstalledError,
5133
3668
  ConnectorAuthError,