@canonry/canonry 7.108.3 → 7.111.0

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 (150) hide show
  1. package/README.md +2 -1
  2. package/assets/agent-workspace/skills/aero/SKILL.md +12 -3
  3. package/assets/agent-workspace/skills/aero/references/agent-operations.md +7 -2
  4. package/assets/agent-workspace/skills/aero/references/getting-started.md +326 -0
  5. package/assets/agent-workspace/skills/aero/references/orchestration.md +2 -2
  6. package/assets/agent-workspace/skills/aero/soul.md +1 -1
  7. package/assets/agent-workspace/skills/canonry/SKILL.md +9 -3
  8. package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +1 -1
  9. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +13 -5
  10. package/assets/agent-workspace/skills/canonry/references/getting-started.md +328 -0
  11. package/assets/assets/{AccessControls-B6bkOAge.js → AccessControls-CJMIWtDc.js} +2 -2
  12. package/assets/assets/{AgentSetupPage-H8VoauIK.js → AgentSetupPage-DR8w0A9t.js} +1 -1
  13. package/assets/assets/{AuditHistoryPanel-Cmm537Mw.js → AuditHistoryPanel-BLF2-WSw.js} +1 -1
  14. package/assets/assets/{BacklinksPage-Dg6IJr83.js → BacklinksPage-BCuEkphC.js} +1 -1
  15. package/assets/assets/{ChartPrimitives-C1meaNiX.js → ChartPrimitives-Dxr7b1zf.js} +1 -1
  16. package/assets/assets/{HistoryPage-DMmZ0fSd.js → HistoryPage-C3UcNB4C.js} +1 -1
  17. package/assets/assets/{MeasurementPropertyPage-x4S_SV30.js → MeasurementPropertyPage-BKDciQn4.js} +1 -1
  18. package/assets/assets/ProjectPage-BwkFGMs_.js +15 -0
  19. package/assets/assets/{RunsPage-DG43ZJib.js → RunsPage-BqteFByy.js} +1 -1
  20. package/assets/assets/{ServerTrafficSection-B-QGjFGD.js → ServerTrafficSection-CqHfSvux.js} +1 -1
  21. package/assets/assets/{SettingsPage-CJlAiPn3.js → SettingsPage-BORbl6fR.js} +1 -1
  22. package/assets/assets/ToneBadge-Cu25HdVj.js +60 -0
  23. package/assets/assets/{TrafficPage-Dlp26Fvy.js → TrafficPage-xqJU4CR4.js} +1 -1
  24. package/assets/assets/{TrafficSourceDetailPage-D-x32dzk.js → TrafficSourceDetailPage-CVHyU3Za.js} +1 -1
  25. package/assets/assets/{account-context-C66suepK.js → account-context-DR0diETl.js} +1 -1
  26. package/assets/assets/{agent-trust-copy-BKQRIoVJ.js → agent-trust-copy-DX06JhNj.js} +1 -1
  27. package/assets/assets/{card-iPmHn3JZ.js → card-BG4pD6H7.js} +1 -1
  28. package/assets/assets/{index-C05Wdzzv.js → index-CggAFvBE.js} +15 -15
  29. package/assets/assets/{query-client-D_jULVYr.js → query-client-DiID-orC.js} +1 -1
  30. package/assets/assets/{react-query-ih29UP0I.js → react-query-gPYNMl8L.js} +1 -1
  31. package/assets/assets/{react-sigma_core.esm.min-sHrGO6oc.js → react-sigma_core.esm.min-CaAAyMHy.js} +1 -1
  32. package/assets/assets/{server-traffic-BScF0-_t.js → server-traffic-DGkceMij.js} +1 -1
  33. package/assets/assets/{service-DYJdF5mP.js → service-DqtXV3A5.js} +1 -1
  34. package/assets/index.html +8 -8
  35. package/dist/{ads-ZU44TW6I.js → ads-MA5UHDSK.js} +3 -3
  36. package/dist/{agent-R5WTIW7T.js → agent-QBDESRUX.js} +10 -10
  37. package/dist/{agent-ask-YDKBWYQG.js → agent-ask-DVUWIY4T.js} +3 -3
  38. package/dist/{agent-conversations-QJOBINIB.js → agent-conversations-Q7SE57ZA.js} +3 -3
  39. package/dist/{agent-journeys-4GGOACCO.js → agent-journeys-OWNSW6GR.js} +3 -3
  40. package/dist/{agent-memory-3YG553SD.js → agent-memory-YIVRBUPS.js} +3 -3
  41. package/dist/{agent-providers-TVVMJQN7.js → agent-providers-UDILAU6B.js} +3 -3
  42. package/dist/{agent-transcript-RZC6273N.js → agent-transcript-KU7ELEEC.js} +3 -3
  43. package/dist/{analytics-U4TVQGMD.js → analytics-WFMI7N5Y.js} +3 -3
  44. package/dist/{apply-GVBOUXIO.js → apply-2WHADGXD.js} +3 -3
  45. package/dist/{backfill-5FQEVO4U.js → backfill-ZNGMPK7N.js} +10 -10
  46. package/dist/{backlinks-YGCLFL6X.js → backlinks-LH77XWHZ.js} +3 -3
  47. package/dist/{bing-LT62N7BY.js → bing-5OCPBLYU.js} +3 -3
  48. package/dist/{bootstrap-XSFNQARX.js → bootstrap-SCTHOCSM.js} +10 -10
  49. package/dist/{cdp-5MY2I2N3.js → cdp-6OEBXRAY.js} +7 -7
  50. package/dist/{chunk-ZVCDFSFW.js → chunk-3SCJOPT5.js} +3 -3
  51. package/dist/{chunk-JKXLOSXJ.js → chunk-44JAOWMT.js} +3 -3
  52. package/dist/{chunk-QGGHCVKX.js → chunk-46HRC23F.js} +1 -1
  53. package/dist/{chunk-E3B4JEYL.js → chunk-4EWCBHGV.js} +2 -2
  54. package/dist/{chunk-OQ4BIGR5.js → chunk-523WBUKU.js} +38 -7
  55. package/dist/{chunk-NXX3E7JX.js → chunk-5IX4ZOSU.js} +1 -1
  56. package/dist/{chunk-ZBNFFCA5.js → chunk-A2VDUQB2.js} +4 -4
  57. package/dist/{chunk-PQL22SU6.js → chunk-BNHQ55UD.js} +3 -3
  58. package/dist/{chunk-XZ25DG73.js → chunk-BZMIVLRX.js} +5 -5
  59. package/dist/{chunk-YW6J3STO.js → chunk-CIDXBCEW.js} +1 -1
  60. package/dist/{chunk-2QJP2EKJ.js → chunk-CJRL5BT3.js} +1 -1
  61. package/dist/{chunk-HASKRW5X.js → chunk-DR4QNC2H.js} +2 -2
  62. package/dist/{chunk-BPGQZNU6.js → chunk-EQ6RZE7U.js} +9 -12
  63. package/dist/{chunk-XHFLXURT.js → chunk-EUARY2OX.js} +71 -2
  64. package/dist/{chunk-R25V7AQG.js → chunk-GHNEC23U.js} +1 -1
  65. package/dist/{chunk-VSYYI634.js → chunk-H5LL4HMB.js} +1 -1
  66. package/dist/{chunk-BUJD4PDG.js → chunk-IBTMJA76.js} +7 -7
  67. package/dist/{chunk-F5KJWMYH.js → chunk-IU26JPKH.js} +1444 -1209
  68. package/dist/{chunk-7XJZM7F5.js → chunk-KMES74KU.js} +1 -1
  69. package/dist/{chunk-DJA35P57.js → chunk-LGPITEEE.js} +1 -1
  70. package/dist/{chunk-NWKFGMF3.js → chunk-LGPJMBH2.js} +2 -2
  71. package/dist/{chunk-VQIEAP5U.js → chunk-LPW2TRLI.js} +7 -7
  72. package/dist/{chunk-C5PWXO5G.js → chunk-MQU5QBUQ.js} +26 -1
  73. package/dist/{chunk-TV6CKQ2M.js → chunk-N5U474SX.js} +4 -4
  74. package/dist/{chunk-LDYUNH5Q.js → chunk-ORX3X7P5.js} +590 -355
  75. package/dist/{chunk-QRYPKPBN.js → chunk-PPOHDQ3T.js} +2 -2
  76. package/dist/{chunk-A2XEI5JG.js → chunk-QKEBSO3T.js} +2 -2
  77. package/dist/{chunk-E4WDOYDS.js → chunk-S7TL4SCS.js} +4 -4
  78. package/dist/{chunk-FCKYBJCJ.js → chunk-TSQG2PNH.js} +368 -368
  79. package/dist/{chunk-SAAYXL6V.js → chunk-U4YVA2A2.js} +2 -2
  80. package/dist/{chunk-QHNM2UTO.js → chunk-UKQPA7NT.js} +4 -4
  81. package/dist/chunk-UX3HJV2V.js +12 -0
  82. package/dist/{chunk-VHESSGBR.js → chunk-VXOZUCH4.js} +5 -5
  83. package/dist/{chunk-DHPVTGOX.js → chunk-WK6SPZG4.js} +1 -1
  84. package/dist/{chunk-UMPRDHNQ.js → chunk-XAS6ARPI.js} +1 -1
  85. package/dist/{chunk-SDF6U4XX.js → chunk-YOQQUG7C.js} +1 -1
  86. package/dist/{chunk-3T5N2K7K.js → chunk-YQ5NFMQB.js} +1 -1
  87. package/dist/{chunk-VYIM2IUO.js → chunk-ZKYOGC7O.js} +1 -1
  88. package/dist/{citations-YW5QU7GI.js → citations-27ENEGJM.js} +4 -4
  89. package/dist/{cli-catalog-VSPAEL7Y.js → cli-catalog-PAZQB7WG.js} +3 -3
  90. package/dist/{cli-commands-GJD73IE6.js → cli-commands-L6G5AQG2.js} +7 -7
  91. package/dist/cli.js +13 -13
  92. package/dist/{competitor-KUG7ZH4D.js → competitor-EK5UX6W6.js} +3 -3
  93. package/dist/{content-SE7WEAKG.js → content-3MBCVYMR.js} +3 -3
  94. package/dist/{dashboard-43VOXHID.js → dashboard-5LZMYX52.js} +6 -6
  95. package/dist/{demo-TWI6ROFX.js → demo-2NB2BVZO.js} +1 -1
  96. package/dist/{demo-server-AQKTQ6AW.js → demo-server-MUJ566YQ.js} +13 -12
  97. package/dist/{discover-X65CLZYY.js → discover-VMPF4CLS.js} +4 -4
  98. package/dist/{discover-eval-R4XVP5LH.js → discover-eval-EK5ZAJKW.js} +3 -3
  99. package/dist/{doctor-VUBA5CN3.js → doctor-2KY5SS4O.js} +3 -3
  100. package/dist/{evidence-UIFGERY4.js → evidence-OXYY666S.js} +3 -3
  101. package/dist/{export-cmd-6RTU5OZG.js → export-cmd-5Q6TNXN6.js} +3 -3
  102. package/dist/{ga-AZG7BHWQ.js → ga-CG3KAWEE.js} +3 -3
  103. package/dist/{gbp-FBC5KMEQ.js → gbp-F555XC4I.js} +16 -5
  104. package/dist/{google-6TQ4YWAS.js → google-44XHCXOZ.js} +4 -4
  105. package/dist/{google-marketing-7MPF6LFW.js → google-marketing-MSJVMCMQ.js} +1 -1
  106. package/dist/{health-cmd-Y5ZQ4TLG.js → health-cmd-KXCY4527.js} +4 -4
  107. package/dist/{history-YGGU2RYB.js → history-Y6PMRNUA.js} +3 -3
  108. package/dist/index.d.ts +93 -9
  109. package/dist/index.js +27 -26
  110. package/dist/{init-Z64A6CBW.js → init-CCVUPSZZ.js} +12 -12
  111. package/dist/{insights-7XFNQHTX.js → insights-FGR5AU5D.js} +3 -3
  112. package/dist/intelligence-service-NOZAMR73.js +16 -0
  113. package/dist/{journeys-PDWXN3IM.js → journeys-2V4KIVDF.js} +3 -3
  114. package/dist/{keys-BKNJETWE.js → keys-2EOH2M22.js} +3 -3
  115. package/dist/{keyword-Z37NIEW4.js → keyword-XFHVSN3B.js} +3 -3
  116. package/dist/{logs-ENWHNCTC.js → logs-WJU66NI5.js} +3 -3
  117. package/dist/{mcp-MV2VUJ4E.js → mcp-23HANPN3.js} +4 -4
  118. package/dist/mcp.js +11 -10
  119. package/dist/{measurement-plan-AWNVH5MW.js → measurement-plan-VQIG5UCP.js} +5 -5
  120. package/dist/{notify-ZAFR4B47.js → notify-E33IOGRC.js} +12 -22
  121. package/dist/{organic-evidence-ZK5IAVLI.js → organic-evidence-3YJ3WTF5.js} +3 -3
  122. package/dist/{overview-ZFZYSJPU.js → overview-66VPXGSA.js} +5 -5
  123. package/dist/{project-HPZQGUR7.js → project-SHXJFR3K.js} +3 -3
  124. package/dist/{project-setup-CEVH6KLJ.js → project-setup-SMTRU7UG.js} +3 -3
  125. package/dist/{query-TOOIX2PP.js → query-UNCXNQLZ.js} +3 -3
  126. package/dist/{research-HYJ76XNV.js → research-C5JIOYGU.js} +3 -3
  127. package/dist/{results-export-2MMDPWIU.js → results-export-WZZDWAQB.js} +3 -3
  128. package/dist/{run-NNYEDFEF.js → run-NRBLHGT3.js} +5 -5
  129. package/dist/{schedule-S5W3XMP3.js → schedule-BOBKSQAN.js} +3 -3
  130. package/dist/{search-CPOTR6WQ.js → search-26B4UX3P.js} +3 -3
  131. package/dist/{serve-5Y342F64.js → serve-3TN2RDHE.js} +28 -27
  132. package/dist/{session-WWV5MXI4.js → session-PTB4UBY3.js} +15 -14
  133. package/dist/{settings-4UFTKOY4.js → settings-25JAM5MJ.js} +3 -3
  134. package/dist/{sitemaps-FAZT7L64.js → sitemaps-YXJIIT52.js} +3 -3
  135. package/dist/{skills-K5RXHUIL.js → skills-HAYPXHWH.js} +2 -2
  136. package/dist/{snapshot-JM2B2WXU.js → snapshot-V6D4W4MF.js} +3 -3
  137. package/dist/{src-UU4CGSEN.js → src-ENRBRVV2.js} +4 -2
  138. package/dist/{status-DYJPL4WJ.js → status-35RGWHEQ.js} +5 -5
  139. package/dist/{technical-aeo-XSLLHFE5.js → technical-aeo-YG7Q3554.js} +3 -3
  140. package/dist/{telemetry-26GTSZNT.js → telemetry-LUT6F4HJ.js} +4 -4
  141. package/dist/{tools-QR2RY6LW.js → tools-NPGGINFO.js} +12 -11
  142. package/dist/{traffic-OF52YJKX.js → traffic-CKYSAD4T.js} +5 -5
  143. package/dist/{trends-SECIYTNL.js → trends-NQZD7X67.js} +3 -3
  144. package/dist/{users-ZM7IR4US.js → users-6FPNRCXJ.js} +3 -3
  145. package/dist/{visibility-stats-V5P4CZO4.js → visibility-stats-S2FXH3NH.js} +4 -4
  146. package/dist/{wordpress-Z32JMXJK.js → wordpress-BN62WUII.js} +3 -3
  147. package/package.json +2 -2
  148. package/assets/assets/ProjectPage-DnDw0Cvk.js +0 -15
  149. package/assets/assets/ToneBadge-BkNG9buI.js +0 -60
  150. package/dist/intelligence-service-3U6RMPRG.js +0 -16
@@ -24,18 +24,18 @@ import {
24
24
  resolveConfiguredAgentProvider,
25
25
  resolveSessionProviderAndModel,
26
26
  setAeroSystemPrompt
27
- } from "./chunk-VQIEAP5U.js";
27
+ } from "./chunk-LPW2TRLI.js";
28
28
  import {
29
29
  answerServiceAdapters,
30
30
  answerServiceDescriptors
31
- } from "./chunk-R25V7AQG.js";
31
+ } from "./chunk-GHNEC23U.js";
32
32
  import {
33
33
  AeroToolProfiles,
34
34
  AeroToolScopes,
35
35
  buildAeroStateTools,
36
36
  isAeroToolProfile,
37
37
  truncateToolResult
38
- } from "./chunk-QHNM2UTO.js";
38
+ } from "./chunk-UKQPA7NT.js";
39
39
  import {
40
40
  getGoogleAuthConfig,
41
41
  getGoogleConnection,
@@ -54,7 +54,7 @@ import {
54
54
  removeCloudflareTrafficConnection,
55
55
  removeCloudflareTrafficConnectionBySourceId,
56
56
  upsertCloudflareTrafficConnection
57
- } from "./chunk-VSYYI634.js";
57
+ } from "./chunk-H5LL4HMB.js";
58
58
  import {
59
59
  claudeAdapter,
60
60
  embedQueries,
@@ -66,7 +66,7 @@ import {
66
66
  openrouterAdapter,
67
67
  perplexityAdapter,
68
68
  startTrafficReclassification
69
- } from "./chunk-VHESSGBR.js";
69
+ } from "./chunk-VXOZUCH4.js";
70
70
  import {
71
71
  classifyUsageSurface,
72
72
  createApiUsageTelemetry,
@@ -78,7 +78,7 @@ import {
78
78
  startOutcomeTimer,
79
79
  trackFeatureCompleted,
80
80
  trackInstallState
81
- } from "./chunk-E4WDOYDS.js";
81
+ } from "./chunk-S7TL4SCS.js";
82
82
  import {
83
83
  isLoopbackBindHost
84
84
  } from "./chunk-TSENU4GG.js";
@@ -86,7 +86,7 @@ import {
86
86
  isApiProviderRegistrable,
87
87
  isCdpProviderRegistrable,
88
88
  registeredProviderNames
89
- } from "./chunk-SDF6U4XX.js";
89
+ } from "./chunk-YOQQUG7C.js";
90
90
  import {
91
91
  checkLatestVersionForServer,
92
92
  getOrCreateAnonymousId,
@@ -98,17 +98,17 @@ import {
98
98
  recordDashboardEvent,
99
99
  setTelemetryPreference,
100
100
  trackEvent
101
- } from "./chunk-HASKRW5X.js";
101
+ } from "./chunk-DR4QNC2H.js";
102
102
  import {
103
103
  createCanonryMcpServer
104
- } from "./chunk-OQ4BIGR5.js";
104
+ } from "./chunk-523WBUKU.js";
105
105
  import {
106
106
  CANONRY_MCP_TIERS,
107
107
  CANONRY_MCP_TOOLKIT_NAMES
108
- } from "./chunk-YW6J3STO.js";
108
+ } from "./chunk-CIDXBCEW.js";
109
109
  import {
110
110
  ApiClient
111
- } from "./chunk-A2XEI5JG.js";
111
+ } from "./chunk-QKEBSO3T.js";
112
112
  import {
113
113
  AGENT_PROVIDERS,
114
114
  PROVIDER_MODELS,
@@ -143,21 +143,21 @@ import {
143
143
  saveConfigPatch,
144
144
  sentimentInstallReadiness,
145
145
  updateSharedProviderExecutionGate
146
- } from "./chunk-VYIM2IUO.js";
146
+ } from "./chunk-ZKYOGC7O.js";
147
147
  import {
148
148
  getBundledSkillSnapshots
149
- } from "./chunk-2QJP2EKJ.js";
149
+ } from "./chunk-CJRL5BT3.js";
150
150
  import {
151
151
  computeFactorAverages,
152
152
  deleteSiteCrawlGraphLayout,
153
153
  persistSiteCrawlGraphLayout,
154
154
  prepareSiteCrawlGraphLayout,
155
155
  recordedSharePct
156
- } from "./chunk-QRYPKPBN.js";
156
+ } from "./chunk-PPOHDQ3T.js";
157
157
  import {
158
158
  CanonryMcpToolNames,
159
159
  canonryMcpTools
160
- } from "./chunk-BPGQZNU6.js";
160
+ } from "./chunk-EQ6RZE7U.js";
161
161
  import {
162
162
  PACKAGE_VERSION
163
163
  } from "./chunk-AOJU5LKX.js";
@@ -166,16 +166,16 @@ import {
166
166
  } from "./chunk-HGMYEDAQ.js";
167
167
  import {
168
168
  IntelligenceService
169
- } from "./chunk-XZ25DG73.js";
169
+ } from "./chunk-BZMIVLRX.js";
170
170
  import {
171
171
  computeCitedCompetitorDomains,
172
172
  determineCitationState
173
- } from "./chunk-UMPRDHNQ.js";
173
+ } from "./chunk-XAS6ARPI.js";
174
174
  import {
175
175
  addLogListener,
176
176
  createFastifyLogger,
177
177
  createLogger
178
- } from "./chunk-NWKFGMF3.js";
178
+ } from "./chunk-LGPJMBH2.js";
179
179
  import {
180
180
  BingApiError,
181
181
  CC_CACHE_DIR,
@@ -292,9 +292,11 @@ import {
292
292
  pruneCachedRelease,
293
293
  queryBacklinks,
294
294
  queueRunIfProjectIdle,
295
+ readAdvancedSignalTransitions,
295
296
  readAnswerIdentity,
296
297
  readInstalledVersion,
297
298
  readMarketCompetitorNames,
299
+ readQueryClasses,
298
300
  redactNotificationUrl,
299
301
  refreshAccessToken,
300
302
  refreshSnapshotMentionIdentity,
@@ -315,6 +317,7 @@ import {
315
317
  sentimentClassifierInput,
316
318
  sentimentHash,
317
319
  serializeUserSessionCookie,
320
+ snapshotMentionObserver,
318
321
  startScheduledSeoRefreshes,
319
322
  stripIpv6Brackets,
320
323
  syncRunClaimKey,
@@ -322,8 +325,9 @@ import {
322
325
  webhookOutcomeTarget,
323
326
  webhookResponseReason,
324
327
  webhookTargetRefusalReason,
328
+ webhookUserAgent,
325
329
  writeAuditLog
326
- } from "./chunk-F5KJWMYH.js";
330
+ } from "./chunk-IU26JPKH.js";
327
331
  import {
328
332
  OperationalLogStore,
329
333
  SentimentIdempotencyConflict,
@@ -403,7 +407,9 @@ import {
403
407
  runFills,
404
408
  runs,
405
409
  schedules,
410
+ sentimentAlertRuns,
406
411
  sentimentCompletionReceipts,
412
+ sentimentJobs,
407
413
  sentimentSettings,
408
414
  seoJobs,
409
415
  seoTasks,
@@ -423,7 +429,7 @@ import {
423
429
  unrecognizedAgentEventsHourly,
424
430
  unrecognizedAgentNotifyState,
425
431
  usageCounters
426
- } from "./chunk-C5PWXO5G.js";
432
+ } from "./chunk-MQU5QBUQ.js";
427
433
  import {
428
434
  AGENT_MEMORY_VALUE_MAX_BYTES,
429
435
  AI_ENGINE_DOMAINS,
@@ -471,6 +477,7 @@ import {
471
477
  MEASUREMENT_PLAN_V2_SCHEMA_VERSION,
472
478
  McpTransportStatuses,
473
479
  MemorySources,
480
+ MentionStates,
474
481
  ONBOARDING_FLOW_VERSION,
475
482
  OPERATION_ACCESS_HEADER,
476
483
  OUTSTANDING_PROVIDER_BATCH_STATUSES,
@@ -704,7 +711,7 @@ import {
704
711
  winnabilityClassLabel,
705
712
  withRetry,
706
713
  withSkippedProviders
707
- } from "./chunk-XHFLXURT.js";
714
+ } from "./chunk-EUARY2OX.js";
708
715
 
709
716
  // src/google-marketing-runtime.ts
710
717
  import crypto2 from "crypto";
@@ -3394,7 +3401,7 @@ import path6 from "path";
3394
3401
  import { isIP as isIP2 } from "net";
3395
3402
  import { fileURLToPath } from "url";
3396
3403
  import { setImmediate as yieldToEventLoop4 } from "timers/promises";
3397
- import { and as and32, eq as eq38, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql15 } from "drizzle-orm";
3404
+ import { and as and33, eq as eq39, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql16 } from "drizzle-orm";
3398
3405
 
3399
3406
  // src/seo-runtime.ts
3400
3407
  import { eq, inArray } from "drizzle-orm";
@@ -6458,7 +6465,7 @@ function nonBlank(value) {
6458
6465
  return trimmed ? trimmed : void 0;
6459
6466
  }
6460
6467
  function resolveBuildCommit(env = process.env) {
6461
- const embedded = true ? "42321b563bf8f0b576ed77b3494681ed1728b5a6" : void 0;
6468
+ const embedded = true ? "b8543616b388df22f1c38a72badac38815b9f071" : void 0;
6462
6469
  return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
6463
6470
  }
6464
6471
  function resolveInstanceIdentity(env = process.env) {
@@ -9798,7 +9805,9 @@ async function executeGbpSync(db, runId, projectId, opts) {
9798
9805
  }
9799
9806
  const reviewNow = /* @__PURE__ */ new Date();
9800
9807
  const insertNow = reviewNow.toISOString();
9801
- db.transaction((tx) => {
9808
+ const written = db.transaction((tx) => {
9809
+ const stillSelected = tx.select({ id: gbpLocations.id }).from(gbpLocations).where(and8(eq10(gbpLocations.id, loc.id), eq10(gbpLocations.selected, true))).get();
9810
+ if (!stillSelected) return false;
9802
9811
  tx.delete(gbpDailyMetrics).where(and8(eq10(gbpDailyMetrics.projectId, projectId), eq10(gbpDailyMetrics.locationName, loc.locationName))).run();
9803
9812
  for (const row of metricRows) {
9804
9813
  tx.insert(gbpDailyMetrics).values({
@@ -9929,7 +9938,12 @@ async function executeGbpSync(db, runId, projectId, opts) {
9929
9938
  reviewsAccessReason: reviewFetch.access.reason,
9930
9939
  reviewsCheckedAt: insertNow
9931
9940
  }).where(eq10(gbpLocations.id, loc.id)).run();
9941
+ return true;
9932
9942
  });
9943
+ if (!written) {
9944
+ log6.info("location.deselected-during-sync", { runId, location: loc.locationName });
9945
+ return;
9946
+ }
9933
9947
  okCount++;
9934
9948
  rowsWritten += metricRows.length + keywordRows.length + placeActionRows.length + monthlyKeywordResults.reduce((total, month) => total + month.rows.length, 0);
9935
9949
  const access = reviewFetch.access;
@@ -15422,6 +15436,22 @@ async function deliverReviewEvent(options) {
15422
15436
 
15423
15437
  // src/unrecognized-agent-alerts.ts
15424
15438
  import { and as and21, desc as desc8, eq as eq25, gte as gte3, sql as sql10 } from "drizzle-orm";
15439
+
15440
+ // src/alert-loop.ts
15441
+ function startAlertLoop(dispatch, intervalMs, onError) {
15442
+ let running = false;
15443
+ const timer = setInterval(() => {
15444
+ if (running) return;
15445
+ running = true;
15446
+ void dispatch().catch(onError).finally(() => {
15447
+ running = false;
15448
+ });
15449
+ }, intervalMs);
15450
+ timer.unref();
15451
+ return () => clearInterval(timer);
15452
+ }
15453
+
15454
+ // src/unrecognized-agent-alerts.ts
15425
15455
  var log22 = createLogger("UnrecognizedAgentAlerts");
15426
15456
  var UNRECOGNIZED_AGENT_ALERT_WINDOW_MS = 7 * 864e5;
15427
15457
  var UNRECOGNIZED_AGENT_ALERT_MIN_HITS = 3;
@@ -15481,23 +15511,71 @@ function recordUnrecognizedAgentDecisions(db, projectId, names, state, now) {
15481
15511
  }
15482
15512
  }
15483
15513
  function startUnrecognizedAgentAlertLoop(dispatch, intervalMs = UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS) {
15484
- let running = false;
15485
- const timer = setInterval(() => {
15486
- if (running) return;
15487
- running = true;
15488
- void dispatch().catch((err) => {
15489
- log22.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
15490
- }).finally(() => {
15491
- running = false;
15492
- });
15493
- }, intervalMs);
15494
- timer.unref?.();
15495
- return () => clearInterval(timer);
15514
+ return startAlertLoop(dispatch, intervalMs, (err) => {
15515
+ log22.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
15516
+ });
15517
+ }
15518
+
15519
+ // src/sentiment-alerts.ts
15520
+ import { and as and22, asc as asc5, eq as eq26, gte as gte4, inArray as inArray11, sql as sql11 } from "drizzle-orm";
15521
+ var log23 = createLogger("SentimentAlerts");
15522
+ var SENTIMENT_ALERT_WINDOW_MS = 7 * 864e5;
15523
+ var SENTIMENT_ALERT_INTERVAL_MS = 5 * 6e4;
15524
+ var SentimentAlertStates = {
15525
+ sent: "sent",
15526
+ skipped: "skipped",
15527
+ quiet: "quiet",
15528
+ baseline: "baseline"
15529
+ };
15530
+ var AUTOMATIC = "automatic";
15531
+ function settledSentimentRuns(db, now) {
15532
+ const since = new Date(now - SENTIMENT_ALERT_WINDOW_MS).toISOString();
15533
+ const jobRunId = sql11`json_extract(${sentimentJobs.selection}, '$.runId')`;
15534
+ const lastReceipt = sql11`(SELECT MAX(${sentimentCompletionReceipts.sequence}) FROM ${sentimentCompletionReceipts}
15535
+ WHERE ${sentimentCompletionReceipts.projectId} = ${runs.projectId} AND ${sentimentCompletionReceipts.runId} = ${runs.id})`;
15536
+ const rows = db.select({
15537
+ projectId: sentimentJobs.projectId,
15538
+ runId: runs.id,
15539
+ open: sql11`SUM(${sentimentJobs.pendingItems} + ${sentimentJobs.runningItems})`,
15540
+ lastReceipt,
15541
+ reconciled: sentimentSettings.reconciledSequence
15542
+ }).from(sentimentJobs).innerJoin(runs, and22(eq26(runs.projectId, sentimentJobs.projectId), sql11`${runs.id} = ${jobRunId}`)).leftJoin(sentimentSettings, eq26(sentimentSettings.projectId, sentimentJobs.projectId)).where(and22(eq26(sentimentJobs.action, AUTOMATIC), gte4(sentimentJobs.createdAt, since), notProbeRun())).groupBy(sentimentJobs.projectId, runs.id).orderBy(asc5(runs.createdAt), asc5(runs.id)).all();
15543
+ const settled = /* @__PURE__ */ new Map();
15544
+ const waiting = /* @__PURE__ */ new Set();
15545
+ for (const row of rows) {
15546
+ if (waiting.has(row.projectId)) continue;
15547
+ const admitted = row.lastReceipt === null || row.lastReceipt <= (row.reconciled ?? 0);
15548
+ if (Number(row.open) > 0 || !admitted) {
15549
+ waiting.add(row.projectId);
15550
+ continue;
15551
+ }
15552
+ const list = settled.get(row.projectId);
15553
+ if (list) list.push(row.runId);
15554
+ else settled.set(row.projectId, [row.runId]);
15555
+ }
15556
+ return settled;
15557
+ }
15558
+ function undecidedSentimentRuns(db, projectId, runIds) {
15559
+ if (runIds.length === 0) return { undecided: [], firstPass: false };
15560
+ const decided = new Set(db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(and22(eq26(sentimentAlertRuns.projectId, projectId), inArray11(sentimentAlertRuns.runId, [...runIds]))).all().map((row) => row.runId));
15561
+ const firstPass = db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(eq26(sentimentAlertRuns.projectId, projectId)).limit(1).get() === void 0;
15562
+ return { undecided: runIds.filter((runId) => !decided.has(runId)), firstPass };
15563
+ }
15564
+ function recordSentimentAlertRuns(db, projectId, runIds, state, now) {
15565
+ const recordedAt = new Date(now).toISOString();
15566
+ for (const runId of runIds) {
15567
+ db.insert(sentimentAlertRuns).values({ projectId, runId, state, recordedAt }).onConflictDoNothing().run();
15568
+ }
15569
+ }
15570
+ function startSentimentAlertLoop(dispatch, intervalMs = SENTIMENT_ALERT_INTERVAL_MS) {
15571
+ return startAlertLoop(dispatch, intervalMs, (err) => {
15572
+ log23.warn("sentiment-alerts.dispatch-failed", { error: describeError(err) });
15573
+ });
15496
15574
  }
15497
15575
 
15498
15576
  // src/provider-batch-poller.ts
15499
- import { and as and22, eq as eq26, inArray as inArray11, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql11 } from "drizzle-orm";
15500
- var log23 = createLogger("ProviderBatchPoller");
15577
+ import { and as and23, eq as eq27, inArray as inArray12, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql12 } from "drizzle-orm";
15578
+ var log24 = createLogger("ProviderBatchPoller");
15501
15579
  var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
15502
15580
  var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
15503
15581
  var PROVIDER_BATCH_CANCEL_GRACE_MS = 60 * 6e4;
@@ -15513,7 +15591,7 @@ var ProviderBatchPoller = class {
15513
15591
  /** One pass: advance every outstanding batch that is due, then finalize what that settled. */
15514
15592
  async tick() {
15515
15593
  const { db } = this.deps;
15516
- const rows = db.select().from(providerBatches).where(inArray11(providerBatches.status, [...OUTSTANDING_PROVIDER_BATCH_STATUSES])).all();
15594
+ const rows = db.select().from(providerBatches).where(inArray12(providerBatches.status, [...OUTSTANDING_PROVIDER_BATCH_STATUSES])).all();
15517
15595
  const live = new Set(rows.map((row) => row.id));
15518
15596
  for (const id of this.schedule.keys()) if (!live.has(id)) this.schedule.delete(id);
15519
15597
  const settledRuns = /* @__PURE__ */ new Map();
@@ -15521,7 +15599,7 @@ var ProviderBatchPoller = class {
15521
15599
  try {
15522
15600
  if (await this.advance(row)) settledRuns.set(row.runId, row.projectId);
15523
15601
  } catch (err) {
15524
- log23.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15602
+ log24.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15525
15603
  this.reschedule(row.id, null);
15526
15604
  }
15527
15605
  }
@@ -15530,7 +15608,7 @@ var ProviderBatchPoller = class {
15530
15608
  try {
15531
15609
  this.deps.runner.finalizeBatchRun(runId, projectId);
15532
15610
  } catch (err) {
15533
- log23.warn("batch.finalize-failed", { runId, error: describeError(err) });
15611
+ log24.warn("batch.finalize-failed", { runId, error: describeError(err) });
15534
15612
  }
15535
15613
  }
15536
15614
  }
@@ -15539,7 +15617,7 @@ var ProviderBatchPoller = class {
15539
15617
  * outstanding (ingested or cancelled), so its run may now finalize.
15540
15618
  */
15541
15619
  async advance(row) {
15542
- const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq26(runs.id, row.runId)).get()?.status;
15620
+ const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq27(runs.id, row.runId)).get()?.status;
15543
15621
  if (runStatus !== RunStatuses.running) {
15544
15622
  await this.deps.runner.abandonProviderBatches([row.id], "Cancelled because its run is no longer running.");
15545
15623
  this.schedule.delete(row.id);
@@ -15556,15 +15634,15 @@ var ProviderBatchPoller = class {
15556
15634
  status = poll.status;
15557
15635
  if (poll.status === "ended") {
15558
15636
  const endedAt = poll.endedAt ?? new Date(this.now()).toISOString();
15559
- const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and22(eq26(providerBatches.id, row.id), eq26(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15637
+ const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and23(eq27(providerBatches.id, row.id), eq27(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15560
15638
  this.schedule.delete(row.id);
15561
15639
  return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
15562
15640
  }
15563
15641
  } catch (err) {
15564
- log23.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15642
+ log24.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15565
15643
  }
15566
15644
  } else {
15567
- log23.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
15645
+ log24.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
15568
15646
  }
15569
15647
  this.reschedule(row.id, status);
15570
15648
  return this.enforceDeadline(row, registered);
@@ -15580,18 +15658,18 @@ var ProviderBatchPoller = class {
15580
15658
  const at = new Date(now).toISOString();
15581
15659
  if (row.cancelRequestedAt === null) {
15582
15660
  if (now < Date.parse(row.deadlineAt)) return false;
15583
- const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and22(
15584
- eq26(providerBatches.id, row.id),
15585
- eq26(providerBatches.status, ProviderBatchStatuses.submitted),
15661
+ const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and23(
15662
+ eq27(providerBatches.id, row.id),
15663
+ eq27(providerBatches.status, ProviderBatchStatuses.submitted),
15586
15664
  isNull4(providerBatches.cancelRequestedAt)
15587
15665
  )).run().changes === 1;
15588
15666
  if (!claimed) return false;
15589
- log23.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
15667
+ log24.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
15590
15668
  if (registered?.adapter.batch && row.providerBatchId) {
15591
15669
  try {
15592
15670
  await registered.adapter.batch.cancel(row.providerBatchId, registered.config);
15593
15671
  } catch (err) {
15594
- log23.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
15672
+ log24.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
15595
15673
  }
15596
15674
  }
15597
15675
  return false;
@@ -15601,9 +15679,9 @@ var ProviderBatchPoller = class {
15601
15679
  status: ProviderBatchStatuses.cancelled,
15602
15680
  error: `The provider batch did not end within an hour of being cancelled at its deadline; its ${row.requestCount} answer(s) were not recorded.`,
15603
15681
  updatedAt: at
15604
- }).where(and22(eq26(providerBatches.id, row.id), eq26(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15682
+ }).where(and23(eq27(providerBatches.id, row.id), eq27(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15605
15683
  this.schedule.delete(row.id);
15606
- if (gaveUp) log23.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
15684
+ if (gaveUp) log24.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
15607
15685
  return gaveUp;
15608
15686
  }
15609
15687
  async ingest(row) {
@@ -15612,7 +15690,7 @@ var ProviderBatchPoller = class {
15612
15690
  return result.kind !== "skipped";
15613
15691
  } catch (err) {
15614
15692
  const error = describeError(err);
15615
- log23.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
15693
+ log24.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
15616
15694
  const now = this.now();
15617
15695
  const unreadable = row.resultsExpireAt !== null && now >= Date.parse(row.resultsExpireAt);
15618
15696
  if (unreadable || now >= Date.parse(row.deadlineAt) + PROVIDER_BATCH_CANCEL_GRACE_MS) {
@@ -15641,10 +15719,10 @@ var ProviderBatchPoller = class {
15641
15719
  /** Runs the sweep handed off whose batches have all settled. */
15642
15720
  finalizableRuns() {
15643
15721
  const holding = [ProviderBatchStatuses.submitting, ...OUTSTANDING_PROVIDER_BATCH_STATUSES];
15644
- return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and22(
15645
- eq26(runs.status, RunStatuses.running),
15722
+ return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and23(
15723
+ eq27(runs.status, RunStatuses.running),
15646
15724
  isNotNull3(runs.pendingProviderErrors),
15647
- notExists2(this.deps.db.select({ one: sql11`1` }).from(providerBatches).where(and22(eq26(providerBatches.runId, runs.id), inArray11(providerBatches.status, holding))))
15725
+ notExists2(this.deps.db.select({ one: sql12`1` }).from(providerBatches).where(and23(eq27(providerBatches.runId, runs.id), inArray12(providerBatches.status, holding))))
15648
15726
  )).all();
15649
15727
  }
15650
15728
  };
@@ -15654,7 +15732,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
15654
15732
  const timer = setInterval(() => {
15655
15733
  if (running) return;
15656
15734
  running = true;
15657
- void poller.tick().catch((err) => log23.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
15735
+ void poller.tick().catch((err) => log24.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
15658
15736
  running = false;
15659
15737
  });
15660
15738
  }, intervalMs);
@@ -15663,7 +15741,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
15663
15741
  }
15664
15742
 
15665
15743
  // src/data-refresh.ts
15666
- var log24 = createLogger("DataRefresh");
15744
+ var log25 = createLogger("DataRefresh");
15667
15745
  function gaRefreshDays(now = /* @__PURE__ */ new Date()) {
15668
15746
  const [reportMonth] = reportMonthsForDoctor(void 0, now);
15669
15747
  const reach = inclusiveDayCount(`${reportMonth}-01`, now.toISOString().slice(0, 10)) ?? 0;
@@ -15705,15 +15783,15 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
15705
15783
  if (result.status === "rejected") {
15706
15784
  const reason = result.reason;
15707
15785
  const message = describeError(reason);
15708
- log24.warn("integration.refresh-failed", { projectName, integration, error: message });
15786
+ log25.warn("integration.refresh-failed", { projectName, integration, error: message });
15709
15787
  return;
15710
15788
  }
15711
15789
  switch (completion) {
15712
15790
  case "synchronous":
15713
- log24.info("integration.refreshed", { projectName, integration });
15791
+ log25.info("integration.refreshed", { projectName, integration });
15714
15792
  return;
15715
15793
  case "queued":
15716
- log24.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
15794
+ log25.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
15717
15795
  return;
15718
15796
  default: {
15719
15797
  const _exhaustive = completion;
@@ -15724,12 +15802,12 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
15724
15802
  }
15725
15803
 
15726
15804
  // src/notifier.ts
15727
- import { eq as eq28, desc as desc10, and as and24, inArray as inArray12, or as or2, isNull as isNull5 } from "drizzle-orm";
15805
+ import { eq as eq29, desc as desc10, and as and25, inArray as inArray13, or as or2, isNull as isNull5 } from "drizzle-orm";
15728
15806
  import crypto25 from "crypto";
15729
15807
 
15730
15808
  // src/site-health-alerts.ts
15731
15809
  import crypto24 from "crypto";
15732
- import { and as and23, asc as asc5, desc as desc9, eq as eq27, gt as gt3 } from "drizzle-orm";
15810
+ import { and as and24, asc as asc6, desc as desc9, eq as eq28, gt as gt3 } from "drizzle-orm";
15733
15811
  var ISSUE_TITLES = {
15734
15812
  "missing-h1": "Missing H1",
15735
15813
  "multiple-h1": "Multiple H1 tags",
@@ -15742,18 +15820,18 @@ function siteHealthProblemKey(code, url) {
15742
15820
  return `${code}|${crypto24.createHash("sha256").update(url).digest("hex").slice(0, 16)}`;
15743
15821
  }
15744
15822
  function readSiteHealthScan(db, projectId, runId) {
15745
- const snapshot = db.select().from(siteCrawlSnapshots).where(and23(eq27(siteCrawlSnapshots.projectId, projectId), eq27(siteCrawlSnapshots.runId, runId))).orderBy(desc9(siteCrawlSnapshots.updatedAt)).limit(1).get();
15823
+ const snapshot = db.select().from(siteCrawlSnapshots).where(and24(eq28(siteCrawlSnapshots.projectId, projectId), eq28(siteCrawlSnapshots.runId, runId))).orderBy(desc9(siteCrawlSnapshots.updatedAt)).limit(1).get();
15746
15824
  if (!snapshot?.detailsAvailable || !snapshot.attemptId) return null;
15747
- const scope = and23(
15748
- eq27(siteCrawlPages.projectId, projectId),
15749
- eq27(siteCrawlPages.runId, runId),
15750
- eq27(siteCrawlPages.attemptId, snapshot.attemptId)
15825
+ const scope = and24(
15826
+ eq28(siteCrawlPages.projectId, projectId),
15827
+ eq28(siteCrawlPages.runId, runId),
15828
+ eq28(siteCrawlPages.attemptId, snapshot.attemptId)
15751
15829
  );
15752
15830
  const pagesByCode = /* @__PURE__ */ new Map();
15753
15831
  const keys = /* @__PURE__ */ new Set();
15754
15832
  let after;
15755
15833
  for (; ; ) {
15756
- const pages = db.select({ nodeKey: siteCrawlPages.nodeKey, url: siteCrawlPages.url, auditFields: siteCrawlPages.auditFields }).from(siteCrawlPages).where(after === void 0 ? scope : and23(scope, gt3(siteCrawlPages.nodeKey, after))).orderBy(asc5(siteCrawlPages.nodeKey)).limit(PAGE_BATCH).all();
15834
+ const pages = db.select({ nodeKey: siteCrawlPages.nodeKey, url: siteCrawlPages.url, auditFields: siteCrawlPages.auditFields }).from(siteCrawlPages).where(after === void 0 ? scope : and24(scope, gt3(siteCrawlPages.nodeKey, after))).orderBy(asc6(siteCrawlPages.nodeKey)).limit(PAGE_BATCH).all();
15757
15835
  for (const page of pages) {
15758
15836
  const defects = page.auditFields.criticalDefects;
15759
15837
  for (const defect of Array.isArray(defects) ? defects : []) {
@@ -15795,7 +15873,7 @@ function settledSiteHealthKeys(scan, reported) {
15795
15873
  return [...scan.complete ? scan.keys : /* @__PURE__ */ new Set([...reported, ...scan.keys])].sort(compareText);
15796
15874
  }
15797
15875
  function readSiteHealthNotifyState(db, projectId) {
15798
- return db.select().from(siteHealthNotifyState).where(eq27(siteHealthNotifyState.projectId, projectId)).get() ?? null;
15876
+ return db.select().from(siteHealthNotifyState).where(eq28(siteHealthNotifyState.projectId, projectId)).get() ?? null;
15799
15877
  }
15800
15878
  function writeSiteHealthNotifyState(db, input) {
15801
15879
  const values = { reportedKeys: input.reportedKeys, runId: input.runId, updatedAt: input.updatedAt, notifiedAt: input.notifiedAt };
@@ -15803,7 +15881,7 @@ function writeSiteHealthNotifyState(db, input) {
15803
15881
  }
15804
15882
 
15805
15883
  // src/notifier.ts
15806
- var log25 = createLogger("Notifier");
15884
+ var log26 = createLogger("Notifier");
15807
15885
  var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
15808
15886
  function trackWebhookDelivery(input) {
15809
15887
  const sample = sampleDelivery(input.failure ? "failed" : "succeeded");
@@ -15916,52 +15994,67 @@ var Notifier = class {
15916
15994
  reviewDispatchInFlight = /* @__PURE__ */ new Set();
15917
15995
  /** Set while a {@link dispatchUnrecognizedAgentAlerts} pass runs, so passes never overlap. */
15918
15996
  unrecognizedAgentDispatchInFlight = false;
15997
+ /** The sentiment install's readiness; without it no sentiment alert is read. */
15998
+ sentimentInstall;
15999
+ /** Set while a {@link dispatchSentimentAlerts} pass runs, so passes never overlap. */
16000
+ sentimentDispatchInFlight = false;
16001
+ /**
16002
+ * Answers of sweeps no webhook accepted yet, by run id, so a refused alert
16003
+ * is retried without reading every assessment of two sweeps again. Kept
16004
+ * only while the sweep is undecided and still in the alert window.
16005
+ */
16006
+ undeliveredSentimentAlerts = /* @__PURE__ */ new Map();
15919
16007
  constructor(db, serverUrl, opts = {}) {
15920
16008
  this.db = db;
15921
16009
  this.serverUrl = serverUrl;
15922
16010
  this.allowLoopbackWebhooks = opts.allowLoopbackWebhooks === true;
16011
+ this.sentimentInstall = opts.sentimentInstall ?? null;
15923
16012
  }
15924
16013
  /** Called after a run completes (success, partial, or failed). */
15925
16014
  async onRunCompleted(runId, projectId, opts) {
15926
- log25.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
15927
- const notifs = this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16015
+ log26.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
16016
+ const notifs = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled);
15928
16017
  if (notifs.length === 0) {
15929
- log25.info("notifications.none-enabled", { projectId });
16018
+ log26.info("notifications.none-enabled", { projectId });
15930
16019
  return;
15931
16020
  }
15932
- log25.info("notifications.found", { projectId, count: notifs.length });
15933
- const run = this.db.select().from(runs).where(eq28(runs.id, runId)).get();
16021
+ log26.info("notifications.found", { projectId, count: notifs.length });
16022
+ const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
15934
16023
  if (!run) {
15935
- log25.error("run.not-found", { runId, msg: "skipping notification dispatch" });
16024
+ log26.error("run.not-found", { runId, msg: "skipping notification dispatch" });
15936
16025
  return;
15937
16026
  }
15938
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16027
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
15939
16028
  if (!project) {
15940
- log25.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
16029
+ log26.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
15941
16030
  return;
15942
16031
  }
15943
- const transitions = this.computeTransitions(runId, projectId);
16032
+ const transitions = this.computeTransitions(runId, project);
15944
16033
  const events = [];
15945
- log25.info("run.status", { runId: run.id, status: run.status, projectId });
16034
+ log26.info("run.status", { runId: run.id, status: run.status, projectId });
15946
16035
  if ((run.status === "completed" || run.status === "partial") && opts?.origin !== "fill") {
15947
16036
  events.push("run.completed");
15948
16037
  }
15949
16038
  if (run.status === "failed") {
15950
16039
  events.push("run.failed");
15951
16040
  }
15952
- const lostTransitions = transitions.filter((t) => t.to === CitationStates["not-cited"] && t.from === CitationStates.cited);
15953
- const gainedTransitions = transitions.filter((t) => t.to === CitationStates.cited && t.from === CitationStates["not-cited"]);
16041
+ const lostTransitions = transitions.citation.filter((t) => t.to === CitationStates["not-cited"] && t.from === CitationStates.cited);
16042
+ const gainedTransitions = transitions.citation.filter((t) => t.to === CitationStates.cited && t.from === CitationStates["not-cited"]);
16043
+ const lostMentions = transitions.mention.filter((t) => t.to === MentionStates["not-mentioned"]);
16044
+ const gainedMentions = transitions.mention.filter((t) => t.to === MentionStates.mentioned);
15954
16045
  if (lostTransitions.length > 0) events.push("citation.lost");
15955
16046
  if (gainedTransitions.length > 0) events.push("citation.gained");
16047
+ if (lostMentions.length > 0) events.push("mention.lost");
16048
+ if (gainedMentions.length > 0) events.push("mention.gained");
15956
16049
  for (const notif of notifs) {
15957
16050
  const config = notif.config;
15958
16051
  if (!config.url) continue;
15959
16052
  const subscribedEvents = config.events;
15960
16053
  const matchingEvents = events.filter((e) => subscribedEvents.includes(e));
15961
- log25.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
16054
+ log26.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
15962
16055
  if (matchingEvents.length === 0) continue;
15963
16056
  for (const event of matchingEvents) {
15964
- const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : transitions;
16057
+ const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : event === "mention.lost" ? lostMentions : event === "mention.gained" ? gainedMentions : transitions.citation;
15965
16058
  const payload = {
15966
16059
  source: "canonry",
15967
16060
  event,
@@ -16014,9 +16107,9 @@ var Notifier = class {
16014
16107
  * than inferred from the absence of a webhook.
16015
16108
  */
16016
16109
  async onHealthChecked(projectId, report) {
16017
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16110
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16018
16111
  if (!project) {
16019
- log25.error("project.not-found", { projectId, msg: "skipping health notification" });
16112
+ log26.error("project.not-found", { projectId, msg: "skipping health notification" });
16020
16113
  return null;
16021
16114
  }
16022
16115
  const rank = healthRank;
@@ -16047,7 +16140,7 @@ var Notifier = class {
16047
16140
  const status = noSignal ? "warn" : worst ? worst.status : "ok";
16048
16141
  const code = noSignal ? HEALTH_NO_SIGNAL_CODE : worst?.code ?? "health.ok";
16049
16142
  const summary = noSignal ? `No health check produced a result (${healthChecks.length} skipped) \u2014 health is unknown, not confirmed.` : worst?.summary ?? `All ${graded.length} health check(s) passing.`;
16050
- const previous = this.db.select().from(doctorHealthState).where(eq28(doctorHealthState.projectId, projectId)).get();
16143
+ const previous = this.db.select().from(doctorHealthState).where(eq29(doctorHealthState.projectId, projectId)).get();
16051
16144
  const previousStatus = previous?.status ?? null;
16052
16145
  const failingSignature = failing.map((c) => `${c.status}:${c.code}`).join(",");
16053
16146
  const failingNow = failing.map((c) => ({ id: c.id, code: c.code, rank: rank(c.status) }));
@@ -16117,7 +16210,7 @@ var Notifier = class {
16117
16210
  const urgentById = new Map(urgentItems.map((item) => [item.id, item]));
16118
16211
  const generalEvent = event;
16119
16212
  const urgentRecord = previous?.urgentNotified ?? null;
16120
- const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16213
+ const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16121
16214
  const listedEvents = (notif) => notif.config.events;
16122
16215
  const hasUrl = (notif) => Boolean(notif.config.url);
16123
16216
  const urgentSubscribers = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -16165,7 +16258,7 @@ var Notifier = class {
16165
16258
  if (previous === void 0) {
16166
16259
  this.db.insert(doctorHealthState).values({ ...observation, notifiedAt: null }).run();
16167
16260
  } else {
16168
- this.db.update(doctorHealthState).set(observation).where(eq28(doctorHealthState.projectId, projectId)).run();
16261
+ this.db.update(doctorHealthState).set(observation).where(eq29(doctorHealthState.projectId, projectId)).run();
16169
16262
  }
16170
16263
  for (const group of urgentGroups) {
16171
16264
  const { urgentEvent, urgentTold, urgentNew, urgentCleared, urgentNotifs, urgentSettled } = group;
@@ -16209,10 +16302,10 @@ var Notifier = class {
16209
16302
  }
16210
16303
  if (accepted > 0) {
16211
16304
  recordUrgentReceipts(urgentReceipts, group.subscribers, formatUrgentBreaches(urgentSettled) || null);
16212
- this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq28(doctorHealthState.projectId, projectId)).run();
16305
+ this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq29(doctorHealthState.projectId, projectId)).run();
16213
16306
  }
16214
16307
  if (urgentNotifs.length > 0) {
16215
- log25.info("health.urgent-notified", {
16308
+ log26.info("health.urgent-notified", {
16216
16309
  projectId,
16217
16310
  event: urgentEvent,
16218
16311
  codes: urgentEvent === "health.urgent" ? breachCodes(urgentNew) : breachCodes(urgentCleared),
@@ -16223,9 +16316,9 @@ var Notifier = class {
16223
16316
  }
16224
16317
  if (!event) {
16225
16318
  if (clearedThisPass.length > 0 || easedThisPass.length > 0) {
16226
- log25.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
16319
+ log26.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
16227
16320
  } else {
16228
- log25.info("health.unchanged", { projectId, status, code });
16321
+ log26.info("health.unchanged", { projectId, status, code });
16229
16322
  }
16230
16323
  return null;
16231
16324
  }
@@ -16253,9 +16346,9 @@ var Notifier = class {
16253
16346
  if (await this.sendWebhook(config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) delivered += 1;
16254
16347
  }
16255
16348
  if (delivered > 0) {
16256
- this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq28(doctorHealthState.projectId, projectId)).run();
16349
+ this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq29(doctorHealthState.projectId, projectId)).run();
16257
16350
  }
16258
- log25.info("health.notified", {
16351
+ log26.info("health.notified", {
16259
16352
  projectId,
16260
16353
  event,
16261
16354
  status,
@@ -16283,12 +16376,12 @@ var Notifier = class {
16283
16376
  async onSiteLivenessChecked(projectId, result) {
16284
16377
  const { check, checkedAt } = result;
16285
16378
  if (check.status !== "ok" && check.status !== "fail") return null;
16286
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16379
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16287
16380
  if (!project) {
16288
- log25.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
16381
+ log26.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
16289
16382
  return null;
16290
16383
  }
16291
- const previous = this.db.select().from(siteLivenessState).where(eq28(siteLivenessState.projectId, projectId)).get();
16384
+ const previous = this.db.select().from(siteLivenessState).where(eq29(siteLivenessState.projectId, projectId)).get();
16292
16385
  const sincePrevious = previous ? Date.parse(checkedAt) - Date.parse(previous.checkedAt) : Number.NaN;
16293
16386
  const countsAsRepeat = Number.isFinite(sincePrevious) && sincePrevious >= SITE_LIVENESS_MIN_PASS_GAP_MS && sincePrevious <= SITE_LIVENESS_MAX_PASS_GAP_MS;
16294
16387
  const failures = check.status === "fail" ? countsAsRepeat ? (previous?.consecutiveFailures ?? 0) + 1 : 1 : 0;
@@ -16298,7 +16391,7 @@ var Notifier = class {
16298
16391
  if (check.status === "ok" && outagePaged) event = "health.recovered";
16299
16392
  const confirmed = check.status === "fail" && failures >= SITE_LIVENESS_FAILURES_TO_PAGE;
16300
16393
  const urgentRecord = previous?.urgentNotifiedAt ?? null;
16301
- const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16394
+ const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16302
16395
  const listedEvents = (notif) => notif.config.events;
16303
16396
  const hasUrl = (notif) => Boolean(notif.config.url);
16304
16397
  const scoped = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -16331,7 +16424,7 @@ var Notifier = class {
16331
16424
  if (previous === void 0) {
16332
16425
  this.db.insert(siteLivenessState).values(observation).run();
16333
16426
  } else {
16334
- this.db.update(siteLivenessState).set(observation).where(eq28(siteLivenessState.projectId, projectId)).run();
16427
+ this.db.update(siteLivenessState).set(observation).where(eq29(siteLivenessState.projectId, projectId)).run();
16335
16428
  }
16336
16429
  if (!event && urgentGroups.every((group) => group.urgentEvent === null)) return null;
16337
16430
  const payloadFor = (name) => {
@@ -16367,9 +16460,9 @@ var Notifier = class {
16367
16460
  }
16368
16461
  }
16369
16462
  if (event === "health.degraded" && delivered > 0) {
16370
- this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq28(siteLivenessState.projectId, projectId)).run();
16463
+ this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq29(siteLivenessState.projectId, projectId)).run();
16371
16464
  }
16372
- log25.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
16465
+ log26.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
16373
16466
  }
16374
16467
  for (const group of urgentGroups) {
16375
16468
  const { urgentEvent, urgentNotifs, generalIds } = group;
@@ -16381,10 +16474,10 @@ var Notifier = class {
16381
16474
  }
16382
16475
  if (accepted > 0) {
16383
16476
  recordUrgentReceipts(urgentReceipts, group.subscribers, group.settled);
16384
- this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq28(siteLivenessState.projectId, projectId)).run();
16477
+ this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq29(siteLivenessState.projectId, projectId)).run();
16385
16478
  }
16386
16479
  if (urgentNotifs.length > 0 || generalIds.size > 0) {
16387
- log25.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
16480
+ log26.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
16388
16481
  }
16389
16482
  }
16390
16483
  return event;
@@ -16407,7 +16500,7 @@ var Notifier = class {
16407
16500
  */
16408
16501
  isNewInsightNews(projectId, insight) {
16409
16502
  const key = insightNotifyKey(projectId, insight);
16410
- const previous = this.db.select().from(insightNotifyState).where(eq28(insightNotifyState.key, key)).get();
16503
+ const previous = this.db.select().from(insightNotifyState).where(eq29(insightNotifyState.key, key)).get();
16411
16504
  if (!previous) return true;
16412
16505
  if (severityRank(insight.severity) > severityRank(previous.severity)) return true;
16413
16506
  const magnitude = insightMagnitude(insight);
@@ -16429,9 +16522,9 @@ var Notifier = class {
16429
16522
  magnitude: insightMagnitude(insight),
16430
16523
  notifiedAt: (/* @__PURE__ */ new Date()).toISOString()
16431
16524
  };
16432
- const existing = this.db.select().from(insightNotifyState).where(eq28(insightNotifyState.key, key)).get();
16525
+ const existing = this.db.select().from(insightNotifyState).where(eq29(insightNotifyState.key, key)).get();
16433
16526
  if (existing) {
16434
- this.db.update(insightNotifyState).set(row).where(eq28(insightNotifyState.key, key)).run();
16527
+ this.db.update(insightNotifyState).set(row).where(eq29(insightNotifyState.key, key)).run();
16435
16528
  } else {
16436
16529
  this.db.insert(insightNotifyState).values(row).run();
16437
16530
  }
@@ -16445,11 +16538,11 @@ var Notifier = class {
16445
16538
  if (criticalInsights.length > 0) insightEvents.push("insight.critical");
16446
16539
  if (highInsights.length > 0) insightEvents.push("insight.high");
16447
16540
  if (insightEvents.length === 0) return;
16448
- const notifs = this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16541
+ const notifs = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16449
16542
  if (notifs.length === 0) return;
16450
- const run = this.db.select().from(runs).where(eq28(runs.id, runId)).get();
16543
+ const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16451
16544
  if (!run) return;
16452
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16545
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16453
16546
  if (!project) return;
16454
16547
  for (const notif of notifs) {
16455
16548
  const config = notif.config;
@@ -16530,9 +16623,9 @@ var Notifier = class {
16530
16623
  return delivered;
16531
16624
  }
16532
16625
  async dispatchQueuedReviewAlerts(projectId) {
16533
- const pendingReviews = this.db.select().from(gbpReviews).where(and24(eq28(gbpReviews.projectId, projectId), eq28(gbpReviews.alertState, "pending"))).all();
16534
- const pendingRatings = this.db.select().from(gbpReviewRatings).where(and24(eq28(gbpReviewRatings.projectId, projectId), eq28(gbpReviewRatings.alertState, "pending"))).all();
16535
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16626
+ const pendingReviews = this.db.select().from(gbpReviews).where(and25(eq29(gbpReviews.projectId, projectId), eq29(gbpReviews.alertState, "pending"))).all();
16627
+ const pendingRatings = this.db.select().from(gbpReviewRatings).where(and25(eq29(gbpReviewRatings.projectId, projectId), eq29(gbpReviewRatings.alertState, "pending"))).all();
16628
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16536
16629
  if (!project) return { reviews: 0, ratingDrops: 0, delivered: 0 };
16537
16630
  const chatSendsLeft = /* @__PURE__ */ new Map();
16538
16631
  const now = /* @__PURE__ */ new Date();
@@ -16544,10 +16637,10 @@ var Notifier = class {
16544
16637
  displayName: gbpLocations.displayName,
16545
16638
  mapsUri: gbpLocations.mapsUri,
16546
16639
  reviewsAccess: gbpLocations.reviewsAccess
16547
- }).from(gbpLocations).where(eq28(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
16640
+ }).from(gbpLocations).where(eq29(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
16548
16641
  );
16549
16642
  const v4HasWorked = new Set(
16550
- this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and24(eq28(gbpReviewRatings.projectId, projectId), eq28(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
16643
+ this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and25(eq29(gbpReviewRatings.projectId, projectId), eq29(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
16551
16644
  );
16552
16645
  const coveredByBusinessProfile = (locationName) => businessProfileReviewsCover(locations.get(locationName)?.reviewsAccess ?? null, v4HasWorked.has(locationName));
16553
16646
  const locationRef = (locationName) => {
@@ -16556,11 +16649,11 @@ var Notifier = class {
16556
16649
  };
16557
16650
  const setReviewState = (ids, alertState) => {
16558
16651
  if (ids.length === 0) return;
16559
- this.db.update(gbpReviews).set({ alertState, alertStateAt: nowIso }).where(inArray12(gbpReviews.id, ids)).run();
16652
+ this.db.update(gbpReviews).set({ alertState, alertStateAt: nowIso }).where(inArray13(gbpReviews.id, ids)).run();
16560
16653
  };
16561
16654
  const setRatingState = (ids, alertState) => {
16562
16655
  if (ids.length === 0) return;
16563
- this.db.update(gbpReviewRatings).set({ alertState, alertStateAt: nowIso }).where(inArray12(gbpReviewRatings.id, ids)).run();
16656
+ this.db.update(gbpReviewRatings).set({ alertState, alertStateAt: nowIso }).where(inArray13(gbpReviewRatings.id, ids)).run();
16564
16657
  };
16565
16658
  const reviewsToSend = [];
16566
16659
  for (const row of pendingReviews) {
@@ -16576,7 +16669,7 @@ var Notifier = class {
16576
16669
  else if (row.rating === null || row.previousRating === null) setRatingState([row.id], "none");
16577
16670
  else ratingsToSend.push(row);
16578
16671
  }
16579
- const enabled = this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
16672
+ const enabled = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
16580
16673
  const subscribedTo = (event) => enabled.filter((n) => (n.config.events ?? []).includes(event));
16581
16674
  const projectRef = { name: project.name, canonicalDomain: project.canonicalDomain };
16582
16675
  const dashboardUrl = `${this.serverUrl}/projects/${project.name}`;
@@ -16630,13 +16723,13 @@ var Notifier = class {
16630
16723
  if (!sent) all = false;
16631
16724
  }
16632
16725
  if (all) {
16633
- this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and24(
16634
- eq28(gbpReviews.id, review.id),
16635
- eq28(gbpReviews.alertState, "pending"),
16636
- eq28(gbpReviews.updateTime, review.updateTime),
16637
- review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq28(gbpReviews.alertStateAt, review.alertStateAt),
16638
- review.comment === null ? isNull5(gbpReviews.comment) : eq28(gbpReviews.comment, review.comment),
16639
- review.starRating === null ? isNull5(gbpReviews.starRating) : eq28(gbpReviews.starRating, review.starRating)
16726
+ this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and25(
16727
+ eq29(gbpReviews.id, review.id),
16728
+ eq29(gbpReviews.alertState, "pending"),
16729
+ eq29(gbpReviews.updateTime, review.updateTime),
16730
+ review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq29(gbpReviews.alertStateAt, review.alertStateAt),
16731
+ review.comment === null ? isNull5(gbpReviews.comment) : eq29(gbpReviews.comment, review.comment),
16732
+ review.starRating === null ? isNull5(gbpReviews.starRating) : eq29(gbpReviews.starRating, review.starRating)
16640
16733
  )).run();
16641
16734
  }
16642
16735
  }
@@ -16668,7 +16761,7 @@ var Notifier = class {
16668
16761
  delivered += accepted;
16669
16762
  }
16670
16763
  }
16671
- log25.info("reviews.dispatched", {
16764
+ log26.info("reviews.dispatched", {
16672
16765
  projectId,
16673
16766
  reviews: reviewsToSend.length,
16674
16767
  ratingDrops: ratingsToSend.length,
@@ -16676,30 +16769,32 @@ var Notifier = class {
16676
16769
  });
16677
16770
  return { reviews: reviewsToSend.length, ratingDrops: ratingsToSend.length, delivered };
16678
16771
  }
16679
- computeTransitions(runId, projectId) {
16680
- const thisRun = this.db.select().from(runs).where(eq28(runs.id, runId)).get();
16681
- if (!thisRun) return [];
16772
+ computeTransitions(runId, project) {
16773
+ const none = { citation: [], mention: [] };
16774
+ const projectId = project.id;
16775
+ const thisRun = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16776
+ if (!thisRun) return none;
16682
16777
  const completeness = measurementRunCompleteness(this.db, runId);
16683
16778
  if (completeness.planned && !completeness.complete) {
16684
- log25.info("transitions.skipped-incomplete", {
16779
+ log26.info("transitions.skipped-incomplete", {
16685
16780
  runId,
16686
16781
  executed: completeness.executed,
16687
16782
  expected: completeness.expected
16688
16783
  });
16689
- return [];
16784
+ return none;
16690
16785
  }
16691
- const groupSiblings = this.db.select().from(runs).where(and24(
16692
- eq28(runs.projectId, projectId),
16693
- eq28(runs.kind, thisRun.kind),
16694
- eq28(runs.createdAt, thisRun.createdAt),
16786
+ const groupSiblings = this.db.select().from(runs).where(and25(
16787
+ eq29(runs.projectId, projectId),
16788
+ eq29(runs.kind, thisRun.kind),
16789
+ eq29(runs.createdAt, thisRun.createdAt),
16695
16790
  notProbeRun()
16696
16791
  )).all();
16697
16792
  const stillPending = groupSiblings.some((r) => r.status === "queued" || r.status === "running");
16698
- if (stillPending) return [];
16793
+ if (stillPending) return none;
16699
16794
  const completedPartialSiblings = groupSiblings.filter(
16700
16795
  (r) => r.status === "completed" || r.status === "partial"
16701
16796
  );
16702
- if (completedPartialSiblings.length === 0) return [];
16797
+ if (completedPartialSiblings.length === 0) return none;
16703
16798
  const winner = completedPartialSiblings.reduce((best, candidate) => {
16704
16799
  const candFinish = candidate.finishedAt ?? "";
16705
16800
  const bestFinish = best.finishedAt ?? "";
@@ -16707,27 +16802,27 @@ var Notifier = class {
16707
16802
  if (candFinish < bestFinish) return best;
16708
16803
  return candidate.id > best.id ? candidate : best;
16709
16804
  });
16710
- if (winner.id !== runId) return [];
16711
- const projectLocations = this.db.select({ locations: projects.locations }).from(projects).where(eq28(projects.id, projectId)).get();
16712
- const locationCount = Math.max(
16713
- 1,
16714
- (projectLocations?.locations ?? []).length
16715
- );
16805
+ if (winner.id !== runId) return none;
16806
+ if (thisRun.measurementPlanVersionId !== null) {
16807
+ const advanced = this.advancedTransitions(runId, projectId);
16808
+ if (advanced !== null) return advanced;
16809
+ }
16810
+ const locationCount = Math.max(1, project.locations.length);
16716
16811
  const RECENT_FETCH_LIMIT = Math.max(8, locationCount * 4);
16717
16812
  const recentRuns = this.db.select().from(runs).where(
16718
- and24(
16719
- eq28(runs.projectId, projectId),
16720
- eq28(runs.kind, thisRun.kind),
16721
- or2(eq28(runs.status, "completed"), eq28(runs.status, "partial")),
16813
+ and25(
16814
+ eq29(runs.projectId, projectId),
16815
+ eq29(runs.kind, thisRun.kind),
16816
+ or2(eq29(runs.status, "completed"), eq29(runs.status, "partial")),
16722
16817
  notProbeRun()
16723
16818
  )
16724
16819
  ).orderBy(desc10(runs.createdAt), desc10(runs.id)).limit(RECENT_FETCH_LIMIT).all();
16725
16820
  const groups = groupRunsByCreatedAt(recentRuns);
16726
16821
  const currentGroupIdx = groups.findIndex((g) => g[0]?.createdAt === thisRun.createdAt);
16727
- if (currentGroupIdx < 0) return [];
16822
+ if (currentGroupIdx < 0) return none;
16728
16823
  const currentGroup = groups[currentGroupIdx] ?? [];
16729
16824
  const previousGroup = groups[currentGroupIdx + 1] ?? [];
16730
- if (currentGroup.length === 0 || previousGroup.length === 0) return [];
16825
+ if (currentGroup.length === 0 || previousGroup.length === 0) return none;
16731
16826
  const currentRunIds = currentGroup.map((r) => r.id);
16732
16827
  const previousRunIds = previousGroup.map((r) => r.id);
16733
16828
  const currentSnapshots = this.db.select({
@@ -16736,40 +16831,96 @@ var Notifier = class {
16736
16831
  provider: querySnapshots.provider,
16737
16832
  location: querySnapshots.location,
16738
16833
  citationState: querySnapshots.citationState,
16739
- retrievalStatus: querySnapshots.retrievalStatus
16740
- }).from(querySnapshots).leftJoin(queries, eq28(querySnapshots.queryId, queries.id)).where(inArray12(querySnapshots.runId, currentRunIds)).all();
16834
+ retrievalStatus: querySnapshots.retrievalStatus,
16835
+ answerText: querySnapshots.answerText,
16836
+ answerMentioned: querySnapshots.answerMentioned,
16837
+ mentionIdentity: querySnapshots.mentionIdentity
16838
+ }).from(querySnapshots).leftJoin(queries, eq29(querySnapshots.queryId, queries.id)).where(inArray13(querySnapshots.runId, currentRunIds)).all();
16741
16839
  const previousSnapshots = this.db.select({
16742
16840
  queryId: querySnapshots.queryId,
16743
16841
  provider: querySnapshots.provider,
16744
16842
  location: querySnapshots.location,
16745
16843
  citationState: querySnapshots.citationState,
16746
- retrievalStatus: querySnapshots.retrievalStatus
16747
- }).from(querySnapshots).where(inArray12(querySnapshots.runId, previousRunIds)).all();
16748
- const prevMap = /* @__PURE__ */ new Map();
16844
+ retrievalStatus: querySnapshots.retrievalStatus,
16845
+ answerText: querySnapshots.answerText,
16846
+ answerMentioned: querySnapshots.answerMentioned,
16847
+ mentionIdentity: querySnapshots.mentionIdentity
16848
+ }).from(querySnapshots).where(inArray13(querySnapshots.runId, previousRunIds)).all();
16849
+ const citationState = (s) => {
16850
+ const state = readCitationState(s);
16851
+ return isCitationStateMeasured(state) ? state : null;
16852
+ };
16853
+ const observeMention = snapshotMentionObserver(project);
16854
+ const mentionState = (s) => {
16855
+ const mentioned = observeMention(s);
16856
+ return mentioned === null ? null : mentioned ? MentionStates.mentioned : MentionStates["not-mentioned"];
16857
+ };
16858
+ const prevCitation = /* @__PURE__ */ new Map();
16859
+ const prevMention = /* @__PURE__ */ new Map();
16749
16860
  for (const s of previousSnapshots) {
16750
16861
  if (s.queryId == null) continue;
16751
- const state = readCitationState(s);
16752
- if (!isCitationStateMeasured(state)) continue;
16753
- prevMap.set(`${s.queryId}:${s.provider}:${s.location ?? ""}`, state);
16754
- }
16755
- const transitions = [];
16862
+ const key = `${s.queryId}:${s.provider}:${s.location ?? ""}`;
16863
+ const cited = citationState(s);
16864
+ if (cited !== null) prevCitation.set(key, cited);
16865
+ const mentioned = mentionState(s);
16866
+ if (mentioned !== null) prevMention.set(key, mentioned);
16867
+ }
16868
+ const citation = [];
16869
+ const mention = [];
16870
+ const changedQueries = /* @__PURE__ */ new Map();
16756
16871
  for (const s of currentSnapshots) {
16757
16872
  if (s.queryId == null) continue;
16758
- const state = readCitationState(s);
16759
- if (!isCitationStateMeasured(state)) continue;
16760
16873
  const key = `${s.queryId}:${s.provider}:${s.location ?? ""}`;
16761
- const prevState = prevMap.get(key);
16762
- if (prevState && prevState !== state) {
16763
- transitions.push({
16764
- query: s.query ?? s.queryId,
16765
- from: prevState,
16766
- to: state,
16767
- provider: s.provider,
16768
- location: s.location
16769
- });
16770
- }
16874
+ const query = s.query ?? s.queryId;
16875
+ const tracked = { id: s.queryId, query };
16876
+ const change = (from, to) => {
16877
+ if (from === void 0 || from === to) return null;
16878
+ const transition = { query, from, to, provider: s.provider, location: s.location, queryClass: null };
16879
+ changedQueries.set(transition, tracked);
16880
+ return transition;
16881
+ };
16882
+ const cited = citationState(s);
16883
+ const citationChange = cited === null ? null : change(prevCitation.get(key), cited);
16884
+ if (citationChange) citation.push(citationChange);
16885
+ const mentioned = mentionState(s);
16886
+ const mentionChange = mentioned === null ? null : change(prevMention.get(key), mentioned);
16887
+ if (mentionChange) mention.push(mentionChange);
16771
16888
  }
16772
- return transitions;
16889
+ if (changedQueries.size > 0) {
16890
+ const classes = readQueryClasses(this.db, project, [...changedQueries.values()]);
16891
+ for (const [transition, tracked] of changedQueries) transition.queryClass = classes.get(tracked.id) ?? null;
16892
+ }
16893
+ return { citation, mention };
16894
+ }
16895
+ /**
16896
+ * The per-Property changes of a custom-portfolio sweep, or null when the
16897
+ * project has no schema v2 plan to read them from, in which case its
16898
+ * changes are the project-level ones.
16899
+ */
16900
+ advancedTransitions(runId, projectId) {
16901
+ let read;
16902
+ try {
16903
+ read = readAdvancedSignalTransitions(this.db, projectId, runId);
16904
+ } catch (error) {
16905
+ log26.error("transitions.advanced-unreadable", { runId, error: describeError(error) });
16906
+ return { citation: [], mention: [] };
16907
+ }
16908
+ if (read === null) return null;
16909
+ if (read.state === "unavailable") {
16910
+ log26.info("transitions.advanced-not-comparable", { runId, reason: read.reason });
16911
+ return { citation: [], mention: [] };
16912
+ }
16913
+ const wire = (t) => ({
16914
+ query: t.query,
16915
+ from: t.from,
16916
+ to: t.to,
16917
+ provider: t.provider,
16918
+ location: t.location,
16919
+ queryClass: t.queryClass,
16920
+ property: t.property,
16921
+ markets: t.markets
16922
+ });
16923
+ return { citation: read.citation.map(wire), mention: read.mention.map(wire) };
16773
16924
  }
16774
16925
  /** True only when the destination accepted the payload. Callers that record "already said" must not count an attempt. */
16775
16926
  /**
@@ -16793,12 +16944,12 @@ var Notifier = class {
16793
16944
  recordUnrecognizedAgentDecisions(this.db, projectId, baseline, UnrecognizedAgentNotifyStates.baseline, now);
16794
16945
  if (due.length === 0) continue;
16795
16946
  const names = due.map((agent) => agent.name);
16796
- const subscribed = this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("traffic.agent.discovered"));
16947
+ const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("traffic.agent.discovered"));
16797
16948
  if (subscribed.length === 0) {
16798
16949
  recordUnrecognizedAgentDecisions(this.db, projectId, names, UnrecognizedAgentNotifyStates.skipped, now);
16799
16950
  continue;
16800
16951
  }
16801
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16952
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16802
16953
  if (!project) continue;
16803
16954
  const payload = {
16804
16955
  source: "canonry",
@@ -16821,6 +16972,84 @@ var Notifier = class {
16821
16972
  }
16822
16973
  return sentNames;
16823
16974
  }
16975
+ /**
16976
+ * Send `sentiment.unfavorable` for sweeps whose automatic sentiment work has
16977
+ * settled: one message per sweep listing the answers sentiment newly rates
16978
+ * unfavorable (`SentimentService.newlyUnfavorable`). A sweep is decided
16979
+ * once: `sent` when a webhook accepted it, `skipped` when nothing
16980
+ * subscribed, so subscribing later starts from new sweeps, `quiet` when no
16981
+ * answer turned, and `baseline` for what had settled before the project's
16982
+ * first pass. When every delivery fails the sweep stays undecided and the
16983
+ * next pass retries it while its sentiment jobs are inside the window; so
16984
+ * does a sweep read while sentiment is off, which says nothing about it.
16985
+ * Returns how many sweeps were sent.
16986
+ */
16987
+ async dispatchSentimentAlerts(now = Date.now()) {
16988
+ if (this.sentimentInstall === null || this.sentimentDispatchInFlight) return 0;
16989
+ this.sentimentDispatchInFlight = true;
16990
+ let sentRuns = 0;
16991
+ try {
16992
+ const service = new SentimentService(this.db, { install: this.sentimentInstall, previewSecret: crypto25.randomUUID() });
16993
+ const settledRuns = settledSentimentRuns(this.db, now);
16994
+ const inWindow = new Set([...settledRuns.values()].flat());
16995
+ for (const runId of this.undeliveredSentimentAlerts.keys()) if (!inWindow.has(runId)) this.undeliveredSentimentAlerts.delete(runId);
16996
+ for (const [projectId, settled] of settledRuns) {
16997
+ const { undecided, firstPass } = undecidedSentimentRuns(this.db, projectId, settled);
16998
+ if (undecided.length === 0) continue;
16999
+ if (firstPass) {
17000
+ recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.baseline, now);
17001
+ continue;
17002
+ }
17003
+ const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("sentiment.unfavorable"));
17004
+ if (subscribed.length === 0) {
17005
+ recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.skipped, now);
17006
+ continue;
17007
+ }
17008
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
17009
+ if (!project) continue;
17010
+ for (const runId of undecided) {
17011
+ let answers = this.undeliveredSentimentAlerts.get(runId) ?? null;
17012
+ if (answers === null) {
17013
+ try {
17014
+ answers = service.newlyUnfavorable(projectId, runId);
17015
+ } catch (error) {
17016
+ log26.error("sentiment-alerts.unreadable", { projectId, runId, error: describeError(error) });
17017
+ continue;
17018
+ }
17019
+ }
17020
+ if (answers === null) continue;
17021
+ if (answers.length === 0) {
17022
+ recordSentimentAlertRuns(this.db, projectId, [runId], SentimentAlertStates.quiet, now);
17023
+ continue;
17024
+ }
17025
+ const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
17026
+ if (!run) continue;
17027
+ const payload = {
17028
+ source: "canonry",
17029
+ event: "sentiment.unfavorable",
17030
+ project: { name: project.name, canonicalDomain: project.canonicalDomain },
17031
+ run: { id: run.id, status: run.status, finishedAt: run.finishedAt },
17032
+ answers,
17033
+ dashboardUrl: `${this.serverUrl}/projects/${project.name}`
17034
+ };
17035
+ let accepted = false;
17036
+ for (const notif of subscribed) {
17037
+ if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
17038
+ }
17039
+ if (accepted) {
17040
+ recordSentimentAlertRuns(this.db, projectId, [runId], SentimentAlertStates.sent, now);
17041
+ this.undeliveredSentimentAlerts.delete(runId);
17042
+ sentRuns++;
17043
+ } else {
17044
+ this.undeliveredSentimentAlerts.set(runId, answers);
17045
+ }
17046
+ }
17047
+ }
17048
+ } finally {
17049
+ this.sentimentDispatchInFlight = false;
17050
+ }
17051
+ return sentRuns;
17052
+ }
16824
17053
  /**
16825
17054
  * After a site audit, send `site-health.issue.new` to the webhooks that list
16826
17055
  * it when the scan found a critical page problem on a page where it was not
@@ -16837,12 +17066,12 @@ var Notifier = class {
16837
17066
  * observable in tests.
16838
17067
  */
16839
17068
  async onSiteAuditCompleted(runId, projectId) {
16840
- const run = this.db.select().from(runs).where(eq28(runs.id, runId)).get();
17069
+ const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16841
17070
  if (!run || run.kind !== RunKinds["site-audit"]) return null;
16842
17071
  if (run.status !== RunStatuses.completed && run.status !== RunStatuses.partial) return null;
16843
- const subscribed = this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("site-health.issue.new"));
17072
+ const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("site-health.issue.new"));
16844
17073
  if (subscribed.length === 0) return null;
16845
- const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
17074
+ const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16846
17075
  if (!project) return null;
16847
17076
  const scan = readSiteHealthScan(this.db, projectId, runId);
16848
17077
  if (!scan) return null;
@@ -16876,7 +17105,7 @@ var Notifier = class {
16876
17105
  if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
16877
17106
  }
16878
17107
  if (!accepted) {
16879
- log25.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
17108
+ log26.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
16880
17109
  return null;
16881
17110
  }
16882
17111
  writeSiteHealthNotifyState(this.db, {
@@ -16896,7 +17125,7 @@ var Notifier = class {
16896
17125
  const targetLabel = redactNotificationUrl(url).urlDisplay;
16897
17126
  const targetCheck = await resolveWebhookTarget(url, { allowLoopback: this.allowLoopbackWebhooks });
16898
17127
  if (!targetCheck.ok) {
16899
- log25.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
17128
+ log26.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
16900
17129
  this.logDelivery(projectId, notificationId, payload.event, "failed", `SSRF: ${targetCheck.message}`);
16901
17130
  const reasonCode = webhookTargetRefusalReason(targetCheck);
16902
17131
  trackWebhookDelivery({
@@ -16909,22 +17138,22 @@ var Notifier = class {
16909
17138
  });
16910
17139
  return false;
16911
17140
  }
16912
- log25.info("webhook.send", { event: payload.event, url: targetLabel });
17141
+ log26.info("webhook.send", { event: payload.event, url: targetLabel });
16913
17142
  const maxRetries = 3;
16914
17143
  const delays = [1e3, 4e3, 16e3];
16915
17144
  let lastStatusClass = "network";
16916
17145
  let lastFailure = { reasonCode: "UNKNOWN" };
16917
17146
  for (let attempt = 0; attempt < maxRetries; attempt++) {
16918
17147
  try {
16919
- const response = await deliverWebhook(targetCheck.target, body, signingSecret);
17148
+ const response = await deliverWebhook(targetCheck.target, body, signingSecret, { userAgent: webhookUserAgent(PACKAGE_VERSION) });
16920
17149
  if (response.status >= 200 && response.status < 300) {
16921
- log25.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
17150
+ log26.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
16922
17151
  this.logDelivery(projectId, notificationId, payload.event, "sent", null);
16923
17152
  trackWebhookDelivery({ url, event: payload.event, attempts: attempt + 1, durationBucket: elapsed(), statusClass: "2xx" });
16924
17153
  return true;
16925
17154
  }
16926
17155
  const errorDetail = response.error ?? `HTTP ${response.status}`;
16927
- log25.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
17156
+ log26.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
16928
17157
  lastStatusClass = response.status === 0 && response.timedOut ? "timeout" : statusClassOf(response.status);
16929
17158
  lastFailure = { reasonCode: webhookResponseReason(response) ?? "UNKNOWN" };
16930
17159
  if (attempt === maxRetries - 1) {
@@ -16936,7 +17165,7 @@ var Notifier = class {
16936
17165
  lastFailure = outcomeFailure(err);
16937
17166
  if (attempt === maxRetries - 1) {
16938
17167
  this.logDelivery(projectId, notificationId, payload.event, "failed", errorDetail);
16939
- log25.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
17168
+ log26.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
16940
17169
  }
16941
17170
  }
16942
17171
  if (attempt < maxRetries - 1) {
@@ -16968,8 +17197,8 @@ var Notifier = class {
16968
17197
  };
16969
17198
 
16970
17199
  // src/run-coordinator.ts
16971
- import { eq as eq29 } from "drizzle-orm";
16972
- var log26 = createLogger("RunCoordinator");
17200
+ import { eq as eq30 } from "drizzle-orm";
17201
+ var log27 = createLogger("RunCoordinator");
16973
17202
  function reportInsightsGenerated(runTrigger, outcome) {
16974
17203
  trackFeatureCompleted({
16975
17204
  feature: "insights",
@@ -17002,22 +17231,22 @@ var RunCoordinator = class {
17002
17231
  */
17003
17232
  onAnswersRecorded;
17004
17233
  async onRunCompleted(runId, projectId, opts) {
17005
- const runRow = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
17234
+ const runRow = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
17006
17235
  const kind = runRow?.kind ?? RunKinds["answer-visibility"];
17007
17236
  if (runRow?.trigger === RunTriggers.probe) {
17008
- log26.info("probe.skip-side-effects", { runId, projectId, kind });
17237
+ log27.info("probe.skip-side-effects", { runId, projectId, kind });
17009
17238
  return;
17010
17239
  }
17011
17240
  if (kind === RunKinds["answer-visibility"] && (runRow?.status === RunStatuses.completed || runRow?.status === RunStatuses.partial) && this.onAnswersRecorded) {
17012
17241
  try {
17013
17242
  await this.onAnswersRecorded(runId, projectId);
17014
17243
  } catch (err) {
17015
- log26.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
17244
+ log27.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
17016
17245
  }
17017
17246
  }
17018
17247
  const completeness = measurementRunCompleteness(this.db, runId);
17019
17248
  if (completeness.planned && !completeness.complete) {
17020
- log26.info("measurement.incomplete-skip-derived", {
17249
+ log27.info("measurement.incomplete-skip-derived", {
17021
17250
  runId,
17022
17251
  projectId,
17023
17252
  executed: completeness.executed,
@@ -17026,7 +17255,7 @@ var RunCoordinator = class {
17026
17255
  try {
17027
17256
  await this.notifier.onRunCompleted(runId, projectId);
17028
17257
  } catch (err) {
17029
- log26.error("notifier.failed", { runId, error: describeError(err) });
17258
+ log27.error("notifier.failed", { runId, error: describeError(err) });
17030
17259
  }
17031
17260
  return;
17032
17261
  }
@@ -17034,7 +17263,7 @@ var RunCoordinator = class {
17034
17263
  try {
17035
17264
  await this.onSentimentCompleted(runId, projectId);
17036
17265
  } catch {
17037
- log26.error("sentiment.wakeup-failed", { runId, projectId });
17266
+ log27.error("sentiment.wakeup-failed", { runId, projectId });
17038
17267
  }
17039
17268
  }
17040
17269
  let insightCount = 0;
@@ -17054,12 +17283,12 @@ var RunCoordinator = class {
17054
17283
  try {
17055
17284
  await this.onInsightsGenerated(runId, projectId, result);
17056
17285
  } catch (err) {
17057
- log26.error("insight-webhook.failed", { runId, error: describeError(err) });
17286
+ log27.error("insight-webhook.failed", { runId, error: describeError(err) });
17058
17287
  }
17059
17288
  }
17060
17289
  }
17061
17290
  } catch (err) {
17062
- log26.error("intelligence.failed", { runId, error: describeError(err) });
17291
+ log27.error("intelligence.failed", { runId, error: describeError(err) });
17063
17292
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
17064
17293
  }
17065
17294
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
@@ -17077,30 +17306,30 @@ var RunCoordinator = class {
17077
17306
  try {
17078
17307
  await this.onInsightsGenerated(runId, projectId, analysisResultFromInsights(gbpInsights));
17079
17308
  } catch (err) {
17080
- log26.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
17309
+ log27.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
17081
17310
  }
17082
17311
  }
17083
17312
  } catch (err) {
17084
- log26.error("gbp-intelligence.failed", { runId, error: describeError(err) });
17313
+ log27.error("gbp-intelligence.failed", { runId, error: describeError(err) });
17085
17314
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
17086
17315
  }
17087
17316
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
17088
17317
  try {
17089
17318
  await this.notifier.dispatchReviewAlerts(projectId);
17090
17319
  } catch (err) {
17091
- log26.error("review-webhook.failed", { runId, error: describeError(err) });
17320
+ log27.error("review-webhook.failed", { runId, error: describeError(err) });
17092
17321
  }
17093
17322
  }
17094
17323
  try {
17095
17324
  await (opts ? this.notifier.onRunCompleted(runId, projectId, opts) : this.notifier.onRunCompleted(runId, projectId));
17096
17325
  } catch (err) {
17097
- log26.error("notifier.failed", { runId, error: describeError(err) });
17326
+ log27.error("notifier.failed", { runId, error: describeError(err) });
17098
17327
  }
17099
17328
  if (kind === RunKinds["site-audit"]) {
17100
17329
  try {
17101
17330
  await this.notifier.onSiteAuditCompleted(runId, projectId);
17102
17331
  } catch (err) {
17103
- log26.error("site-health-webhook.failed", { runId, error: describeError(err) });
17332
+ log27.error("site-health-webhook.failed", { runId, error: describeError(err) });
17104
17333
  }
17105
17334
  }
17106
17335
  if (this.onAeroEvent) {
@@ -17114,7 +17343,7 @@ var RunCoordinator = class {
17114
17343
  };
17115
17344
  await this.onAeroEvent(ctx);
17116
17345
  } catch (err) {
17117
- log26.error("aero.failed", { runId, error: describeError(err) });
17346
+ log27.error("aero.failed", { runId, error: describeError(err) });
17118
17347
  }
17119
17348
  }
17120
17349
  }
@@ -17129,7 +17358,7 @@ var RunCoordinator = class {
17129
17358
  * so the Aero queue is never starved of a follow-up.
17130
17359
  */
17131
17360
  buildDiscoveryAeroContext(runId, projectId, status, error) {
17132
- const session = this.db.select().from(discoverySessions).where(eq29(discoverySessions.runId, runId)).get();
17361
+ const session = this.db.select().from(discoverySessions).where(eq30(discoverySessions.runId, runId)).get();
17133
17362
  const competitorMap = session ? session.competitorMap : [];
17134
17363
  return {
17135
17364
  kind: RunKinds["aeo-discover-probe"],
@@ -17173,12 +17402,12 @@ function analysisResultFromInsights(insights2) {
17173
17402
 
17174
17403
  // src/agent/session-registry.ts
17175
17404
  import crypto27 from "crypto";
17176
- import { and as and27, eq as eq32, gt as gt4, lte as lte3 } from "drizzle-orm";
17405
+ import { and as and28, eq as eq33, gt as gt4, lte as lte3 } from "drizzle-orm";
17177
17406
 
17178
17407
  // src/agent/remote-mcp.ts
17179
17408
  import { Type } from "@earendil-works/pi-ai";
17180
17409
  import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
17181
- var log27 = createLogger("RemoteMcp");
17410
+ var log28 = createLogger("RemoteMcp");
17182
17411
  var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([]);
17183
17412
  async function connectStreamableHttp(server) {
17184
17413
  const transport = new StreamableHTTPClientTransport(new URL(server.url), {
@@ -17246,7 +17475,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17246
17475
  try {
17247
17476
  client = await connect(server);
17248
17477
  } catch (err) {
17249
- log27.error("external-mcp.connect-failed", {
17478
+ log28.error("external-mcp.connect-failed", {
17250
17479
  label,
17251
17480
  error: describeError(err)
17252
17481
  });
@@ -17256,7 +17485,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17256
17485
  try {
17257
17486
  listed = await client.listTools();
17258
17487
  } catch (err) {
17259
- log27.error("external-mcp.list-failed", {
17488
+ log28.error("external-mcp.list-failed", {
17260
17489
  label,
17261
17490
  error: describeError(err)
17262
17491
  });
@@ -17267,7 +17496,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17267
17496
  if (!isReadOnly(tool)) continue;
17268
17497
  tools.push(adaptRemoteTool(client, tool));
17269
17498
  }
17270
- log27.info("external-mcp.loaded", {
17499
+ log28.info("external-mcp.loaded", {
17271
17500
  label,
17272
17501
  discovered: listed.tools.length,
17273
17502
  adopted: tools.length
@@ -17278,7 +17507,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17278
17507
 
17279
17508
  // src/agent/memory-store.ts
17280
17509
  import crypto26 from "crypto";
17281
- import { and as and25, desc as desc11, eq as eq30, like, sql as sql12, or as or3 } from "drizzle-orm";
17510
+ import { and as and26, desc as desc11, eq as eq31, like, sql as sql13, or as or3 } from "drizzle-orm";
17282
17511
  var COMPACTION_KEY_PREFIX = "compaction:";
17283
17512
  var COMPACTION_NOTES_PER_SESSION = 3;
17284
17513
  function rowToDto(row) {
@@ -17292,7 +17521,7 @@ function rowToDto(row) {
17292
17521
  };
17293
17522
  }
17294
17523
  function listMemoryEntries(db, projectId, opts = {}) {
17295
- const query = db.select().from(agentMemory).where(eq30(agentMemory.projectId, projectId)).orderBy(desc11(agentMemory.updatedAt));
17524
+ const query = db.select().from(agentMemory).where(eq31(agentMemory.projectId, projectId)).orderBy(desc11(agentMemory.updatedAt));
17296
17525
  const rows = opts.limit === void 0 ? query.all() : query.limit(opts.limit).all();
17297
17526
  return rows.map(rowToDto);
17298
17527
  }
@@ -17323,21 +17552,21 @@ function upsertMemoryEntry(db, args) {
17323
17552
  updatedAt: now
17324
17553
  }
17325
17554
  }).run();
17326
- const row = db.select().from(agentMemory).where(and25(eq30(agentMemory.projectId, args.projectId), eq30(agentMemory.key, args.key))).get();
17555
+ const row = db.select().from(agentMemory).where(and26(eq31(agentMemory.projectId, args.projectId), eq31(agentMemory.key, args.key))).get();
17327
17556
  if (!row) throw new Error("memory upsert produced no row");
17328
17557
  return rowToDto(row);
17329
17558
  }
17330
17559
  function deleteMemoryEntry(db, projectId, key) {
17331
- const result = db.delete(agentMemory).where(and25(eq30(agentMemory.projectId, projectId), eq30(agentMemory.key, key))).run();
17560
+ const result = db.delete(agentMemory).where(and26(eq31(agentMemory.projectId, projectId), eq31(agentMemory.key, key))).run();
17332
17561
  const changes = result.changes ?? 0;
17333
17562
  return changes > 0;
17334
17563
  }
17335
17564
  function loadRecentForHydrate(db, projectId, limit, sessionId) {
17336
17565
  if (sessionId === void 0) return listMemoryEntries(db, projectId, { limit });
17337
17566
  const sessionPrefix = `compaction:${sessionId ?? ""}:`;
17338
- return db.select().from(agentMemory).where(and25(
17339
- eq30(agentMemory.projectId, projectId),
17340
- or3(sql12`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql12`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
17567
+ return db.select().from(agentMemory).where(and26(
17568
+ eq31(agentMemory.projectId, projectId),
17569
+ or3(sql13`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql13`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
17341
17570
  )).orderBy(desc11(agentMemory.updatedAt)).limit(limit).all().map(rowToDto);
17342
17571
  }
17343
17572
  function writeCompactionNote(db, args) {
@@ -17362,16 +17591,16 @@ function writeCompactionNote(db, args) {
17362
17591
  }).run();
17363
17592
  const sessionPrefix = `${COMPACTION_KEY_PREFIX}${args.sessionId}:`;
17364
17593
  const existing = tx.select({ id: agentMemory.id, updatedAt: agentMemory.updatedAt }).from(agentMemory).where(
17365
- and25(
17366
- eq30(agentMemory.projectId, args.projectId),
17594
+ and26(
17595
+ eq31(agentMemory.projectId, args.projectId),
17367
17596
  like(agentMemory.key, `${sessionPrefix}%`)
17368
17597
  )
17369
17598
  ).orderBy(desc11(agentMemory.updatedAt)).all();
17370
17599
  const stale = existing.slice(COMPACTION_NOTES_PER_SESSION).map((r) => r.id);
17371
17600
  if (stale.length > 0) {
17372
- tx.delete(agentMemory).where(sql12`${agentMemory.id} IN (${sql12.join(stale.map((s) => sql12`${s}`), sql12`, `)})`).run();
17601
+ tx.delete(agentMemory).where(sql13`${agentMemory.id} IN (${sql13.join(stale.map((s) => sql13`${s}`), sql13`, `)})`).run();
17373
17602
  }
17374
- const row = tx.select().from(agentMemory).where(and25(eq30(agentMemory.projectId, args.projectId), eq30(agentMemory.key, key))).get();
17603
+ const row = tx.select().from(agentMemory).where(and26(eq31(agentMemory.projectId, args.projectId), eq31(agentMemory.key, key))).get();
17375
17604
  if (row) inserted = rowToDto(row);
17376
17605
  });
17377
17606
  if (!inserted) throw new Error("compaction note write produced no row");
@@ -17379,7 +17608,7 @@ function writeCompactionNote(db, args) {
17379
17608
  }
17380
17609
 
17381
17610
  // src/agent/turn-telemetry.ts
17382
- var log28 = createLogger("AeroTurn");
17611
+ var log29 = createLogger("AeroTurn");
17383
17612
  var PROVIDER_ERROR_REASONS = {
17384
17613
  PROVIDER_AUTH: "INVALID_CREDENTIALS",
17385
17614
  PROVIDER_BILLING: "BILLING",
@@ -17435,7 +17664,7 @@ function trackAeroTurn(agent, turn) {
17435
17664
  phase: turn.phase ?? (turn.error === void 0 && agent.state.errorMessage ? OutcomePhases["provider-request"] : OutcomePhases.unknown)
17436
17665
  });
17437
17666
  const outcome = turnOutcome(turn.error === void 0 ? status.reason : "error", turn.error, agent.state.errorMessage);
17438
- log28.info("completed", {
17667
+ log29.info("completed", {
17439
17668
  operationId,
17440
17669
  projectId: turn.projectId,
17441
17670
  provider: modelProvider,
@@ -17463,7 +17692,7 @@ function trackAeroTurn(agent, turn) {
17463
17692
  }
17464
17693
 
17465
17694
  // src/agent/project-shape.ts
17466
- import { and as and26, count as count5, eq as eq31 } from "drizzle-orm";
17695
+ import { and as and27, count as count5, eq as eq32 } from "drizzle-orm";
17467
17696
  var ADVANCED_TOOLS = [
17468
17697
  "canonry_measurement_portfolio_summary",
17469
17698
  "canonry_measurement_overview",
@@ -17490,10 +17719,10 @@ var ADVANCED_ROUTES = [
17490
17719
  ];
17491
17720
  function aeroProjectShape(db, projectId) {
17492
17721
  try {
17493
- const pointer = db.select().from(measurementPlans).where(eq31(measurementPlans.projectId, projectId)).get();
17494
- const version = pointer ? db.select().from(measurementPlanVersions).where(and26(
17495
- eq31(measurementPlanVersions.projectId, projectId),
17496
- eq31(measurementPlanVersions.id, pointer.activeVersionId)
17722
+ const pointer = db.select().from(measurementPlans).where(eq32(measurementPlans.projectId, projectId)).get();
17723
+ const version = pointer ? db.select().from(measurementPlanVersions).where(and27(
17724
+ eq32(measurementPlanVersions.projectId, projectId),
17725
+ eq32(measurementPlanVersions.id, pointer.activeVersionId)
17497
17726
  )).get() : void 0;
17498
17727
  if (version) {
17499
17728
  const plan = JSON.parse(version.canonicalJson);
@@ -17520,7 +17749,7 @@ canonry_visibility_report describes the whole project, not one Property. canonry
17520
17749
  pinned: ADVANCED_TOOLS
17521
17750
  };
17522
17751
  }
17523
- const tracked = db.select({ total: count5() }).from(queries).where(eq31(queries.projectId, projectId)).get()?.total ?? 0;
17752
+ const tracked = db.select({ total: count5() }).from(queries).where(eq32(queries.projectId, projectId)).get()?.total ?? 0;
17524
17753
  return {
17525
17754
  prompt: `
17526
17755
 
@@ -17660,7 +17889,7 @@ async function compactMessages(args) {
17660
17889
  }
17661
17890
 
17662
17891
  // src/agent/session-registry.ts
17663
- var log29 = createLogger("SessionRegistry");
17892
+ var log30 = createLogger("SessionRegistry");
17664
17893
  var MAX_HYDRATE_NOTES = 20;
17665
17894
  var PROVIDER_ACCOUNT_COOLDOWN_MS = 24 * 60 * 60 * 1e3;
17666
17895
  var MAX_HYDRATE_BYTES = 32 * 1024;
@@ -17722,7 +17951,7 @@ var SessionRegistry = class {
17722
17951
  if (!this.externalToolsPromise) {
17723
17952
  this.externalToolsPromise = loadExternalMcpTools(this.opts.config.externalMcpServers).catch(
17724
17953
  (err) => {
17725
- log29.error("external-mcp.load-failed", {
17954
+ log30.error("external-mcp.load-failed", {
17726
17955
  error: describeError(err)
17727
17956
  });
17728
17957
  return [];
@@ -17798,7 +18027,7 @@ var SessionRegistry = class {
17798
18027
  modelProvider: effectiveProvider,
17799
18028
  modelId: effectiveModelId,
17800
18029
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
17801
- }).where(eq32(agentSessions.projectId, projectId)).run();
18030
+ }).where(eq33(agentSessions.projectId, projectId)).run();
17802
18031
  }
17803
18032
  const agent2 = createAeroSession({
17804
18033
  projectName,
@@ -18017,13 +18246,13 @@ ${lines.join("\n")}
18017
18246
  agent.state.messages = result.messages;
18018
18247
  setAeroSystemPrompt(agent, this.buildHydratedSystemPrompt(projectId, row.systemPrompt));
18019
18248
  this.save(projectName);
18020
- log29.info("compaction.completed", {
18249
+ log30.info("compaction.completed", {
18021
18250
  projectName,
18022
18251
  removedCount: result.removedCount,
18023
18252
  summaryBytes: Buffer.byteLength(result.summary, "utf8")
18024
18253
  });
18025
18254
  } catch (err) {
18026
- log29.error("compaction.failed", {
18255
+ log30.error("compaction.failed", {
18027
18256
  projectName,
18028
18257
  error: describeError(err)
18029
18258
  });
@@ -18117,7 +18346,7 @@ ${lines.join("\n")}
18117
18346
  modelProvider: nextProvider,
18118
18347
  modelId: nextModelId,
18119
18348
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
18120
- }).where(eq32(agentSessions.projectId, projectId)).run();
18349
+ }).where(eq33(agentSessions.projectId, projectId)).run();
18121
18350
  }
18122
18351
  /** Snapshot pending work without consuming it before an atomic conversation switch. */
18123
18352
  prepareConversationChange(projectName) {
@@ -18205,7 +18434,7 @@ ${lines.join("\n")}
18205
18434
  }
18206
18435
  trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, projectId });
18207
18436
  } catch (err) {
18208
- log29.error("drain.failed", {
18437
+ log30.error("drain.failed", {
18209
18438
  projectName,
18210
18439
  error: describeError(err)
18211
18440
  });
@@ -18327,9 +18556,9 @@ ${lines.join("\n")}
18327
18556
  persisted = true;
18328
18557
  } catch (error) {
18329
18558
  this.providerCooldownFallbacks.set(accountKey, cooldown);
18330
- log29.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
18559
+ log30.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
18331
18560
  }
18332
- log29.warn("provider.background-paused", {
18561
+ log30.warn("provider.background-paused", {
18333
18562
  projectName,
18334
18563
  provider: agent.state.model.provider,
18335
18564
  reason,
@@ -18340,14 +18569,14 @@ ${lines.join("\n")}
18340
18569
  } else if (aeroTurnStatus(agent)?.reason === "completed" && durableKnown && (fallbackFailureId || durableFailureId) && this.providerCooldownFallbacks.get(accountKey)?.failureId === fallbackFailureId) {
18341
18570
  try {
18342
18571
  if (durableFailureId) {
18343
- this.opts.db.delete(agentProviderCooldowns).where(and27(
18344
- eq32(agentProviderCooldowns.accountKey, accountKey),
18345
- eq32(agentProviderCooldowns.failureId, durableFailureId)
18572
+ this.opts.db.delete(agentProviderCooldowns).where(and28(
18573
+ eq33(agentProviderCooldowns.accountKey, accountKey),
18574
+ eq33(agentProviderCooldowns.failureId, durableFailureId)
18346
18575
  )).run();
18347
18576
  }
18348
18577
  this.providerCooldownFallbacks.delete(accountKey);
18349
18578
  } catch (error) {
18350
- log29.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
18579
+ log30.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
18351
18580
  }
18352
18581
  }
18353
18582
  }
@@ -18376,13 +18605,13 @@ ${lines.join("\n")}
18376
18605
  }
18377
18606
  const fallback = this.providerCooldownFallbacks.get(accountKey);
18378
18607
  try {
18379
- const durable = this.opts.db.select().from(agentProviderCooldowns).where(and27(
18380
- eq32(agentProviderCooldowns.accountKey, accountKey),
18608
+ const durable = this.opts.db.select().from(agentProviderCooldowns).where(and28(
18609
+ eq33(agentProviderCooldowns.accountKey, accountKey),
18381
18610
  gt4(agentProviderCooldowns.retryAt, Date.now())
18382
18611
  )).get();
18383
18612
  return { fallback, durable };
18384
18613
  } catch (error) {
18385
- log29.warn("provider.background-pause.read-failed", { error: describeError(error) });
18614
+ log30.warn("provider.background-pause.read-failed", { error: describeError(error) });
18386
18615
  return { fallback, durable: null };
18387
18616
  }
18388
18617
  }
@@ -18396,11 +18625,11 @@ ${lines.join("\n")}
18396
18625
  return id;
18397
18626
  }
18398
18627
  tryResolveProjectId(projectName) {
18399
- const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq32(projects.name, projectName)).get();
18628
+ const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq33(projects.name, projectName)).get();
18400
18629
  return row?.id;
18401
18630
  }
18402
18631
  loadRow(projectId) {
18403
- const row = this.opts.db.select().from(agentSessions).where(eq32(agentSessions.projectId, projectId)).get();
18632
+ const row = this.opts.db.select().from(agentSessions).where(eq33(agentSessions.projectId, projectId)).get();
18404
18633
  return row ?? null;
18405
18634
  }
18406
18635
  insertRow(params) {
@@ -18420,7 +18649,7 @@ ${lines.join("\n")}
18420
18649
  }
18421
18650
  updateRow(projectId, patch) {
18422
18651
  const now = (/* @__PURE__ */ new Date()).toISOString();
18423
- this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq32(agentSessions.projectId, projectId)).run();
18652
+ this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq33(agentSessions.projectId, projectId)).run();
18424
18653
  }
18425
18654
  /**
18426
18655
  * Store a refreshed prompt snapshot without touching `updatedAt`, which the
@@ -18429,13 +18658,13 @@ ${lines.join("\n")}
18429
18658
  * recently used right after an upgrade.
18430
18659
  */
18431
18660
  persistPromptSnapshot(projectId, systemPrompt) {
18432
- this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq32(agentSessions.projectId, projectId)).run();
18661
+ this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq33(agentSessions.projectId, projectId)).run();
18433
18662
  }
18434
18663
  };
18435
18664
 
18436
18665
  // src/agent/viewer-sessions.ts
18437
18666
  import crypto28 from "crypto";
18438
- import { and as and28, eq as eq33, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
18667
+ import { and as and29, eq as eq34, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
18439
18668
 
18440
18669
  // src/agent/chatgpt-plan.ts
18441
18670
  import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
@@ -18806,12 +19035,12 @@ var ViewerAeroSessions = class {
18806
19035
  */
18807
19036
  removeKey(id) {
18808
19037
  try {
18809
- this.opts.db.delete(apiKeys).where(eq33(apiKeys.id, id)).run();
19038
+ this.opts.db.delete(apiKeys).where(eq34(apiKeys.id, id)).run();
18810
19039
  } catch {
18811
19040
  try {
18812
19041
  this.opts.db.transaction((tx) => {
18813
- tx.delete(dashboardSessions).where(eq33(dashboardSessions.apiKeyId, id)).run();
18814
- tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq33(apiKeys.id, id)).run();
19042
+ tx.delete(dashboardSessions).where(eq34(dashboardSessions.apiKeyId, id)).run();
19043
+ tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq34(apiKeys.id, id)).run();
18815
19044
  });
18816
19045
  } catch {
18817
19046
  }
@@ -18824,7 +19053,7 @@ var ViewerAeroSessions = class {
18824
19053
  */
18825
19054
  revokeOrphanedKeys() {
18826
19055
  try {
18827
- this.opts.db.delete(apiKeys).where(and28(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
19056
+ this.opts.db.delete(apiKeys).where(and29(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
18828
19057
  } catch {
18829
19058
  }
18830
19059
  }
@@ -18841,7 +19070,7 @@ var ViewerAeroSessions = class {
18841
19070
  // src/mcp-http.ts
18842
19071
  import crypto29 from "crypto";
18843
19072
  import { isIP } from "net";
18844
- import { and as and29, eq as eq34, isNull as isNull6 } from "drizzle-orm";
19073
+ import { and as and30, eq as eq35, isNull as isNull6 } from "drizzle-orm";
18845
19074
  import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node";
18846
19075
  import { McpServer, createMcpHandler, isInitializeRequest, isLegacyRequest } from "@modelcontextprotocol/server";
18847
19076
  var SESSION_IDLE_MS = 10 * 60 * 1e3;
@@ -18947,12 +19176,12 @@ function registerMcpHttpRoutes(scope, opts) {
18947
19176
  try {
18948
19177
  withoutLockWait(() => {
18949
19178
  opts.db.transaction((tx) => {
18950
- tx.delete(dashboardSessions).where(eq34(dashboardSessions.apiKeyId, id)).run();
18951
- tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and29(eq34(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
19179
+ tx.delete(dashboardSessions).where(eq35(dashboardSessions.apiKeyId, id)).run();
19180
+ tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and30(eq35(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
18952
19181
  });
18953
19182
  if (remove) {
18954
19183
  try {
18955
- opts.db.delete(apiKeys).where(eq34(apiKeys.id, id)).run();
19184
+ opts.db.delete(apiKeys).where(eq35(apiKeys.id, id)).run();
18956
19185
  } catch (error) {
18957
19186
  scope.log.warn({ err: error, keyId: id }, "Retained revoked MCP request key after deletion failed");
18958
19187
  }
@@ -19003,14 +19232,14 @@ function registerMcpHttpRoutes(scope, opts) {
19003
19232
  withoutLockWait(() => {
19004
19233
  const cutoff = now() - SESSION_IDLE_MS;
19005
19234
  for (const session of legacyServers) {
19006
- const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq34(apiKeys.id, session.sessionKeyId)).get() : void 0;
19235
+ const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq35(apiKeys.id, session.sessionKeyId)).get() : void 0;
19007
19236
  if (session.lastSeenAt < cutoff || session.expiresAt !== void 0 && session.expiresAt <= now() || session.sessionKeyId && (!key || key.revokedAt)) {
19008
19237
  void session.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP session"));
19009
19238
  }
19010
19239
  }
19011
19240
  for (const exchange of modernExchanges) {
19012
19241
  if (!exchange.sessionKey) continue;
19013
- const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq34(apiKeys.id, exchange.sessionKey.id)).get();
19242
+ const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq35(apiKeys.id, exchange.sessionKey.id)).get();
19014
19243
  if (!key || key.revokedAt || exchange.sessionKey.expiresAt <= now()) {
19015
19244
  void exchange.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP request"));
19016
19245
  }
@@ -19296,7 +19525,7 @@ function resolveChatGptSettings(config, env = process.env) {
19296
19525
  }
19297
19526
 
19298
19527
  // src/agent/agent-routes.ts
19299
- import { eq as eq35 } from "drizzle-orm";
19528
+ import { eq as eq36 } from "drizzle-orm";
19300
19529
  function viewerAeroCaller(request, opts) {
19301
19530
  if (!opts.viewerSessions) return null;
19302
19531
  const principal = request.principal;
@@ -19339,7 +19568,7 @@ function turnAttribution(request) {
19339
19568
  };
19340
19569
  }
19341
19570
  function resolveProject(db, name) {
19342
- const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq35(projects.name, name)).get();
19571
+ const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq36(projects.name, name)).get();
19343
19572
  if (!row) throw notFound("project", name);
19344
19573
  return row;
19345
19574
  }
@@ -19462,7 +19691,7 @@ function registerAgentRoutes(app, opts) {
19462
19691
  }
19463
19692
  requireInstanceAdministrator(request);
19464
19693
  const project = resolveProject(opts.db, request.params.name);
19465
- const row = opts.db.select().from(agentSessions).where(eq35(agentSessions.projectId, project.id)).get();
19694
+ const row = opts.db.select().from(agentSessions).where(eq36(agentSessions.projectId, project.id)).get();
19466
19695
  const nextTurn = opts.sessionRegistry.nextTurnModel(project.name);
19467
19696
  if (!row) {
19468
19697
  return { conversationId: null, messages: [], modelProvider: null, modelId: null, nextTurn, updatedAt: null };
@@ -19504,7 +19733,7 @@ function registerAgentRoutes(app, opts) {
19504
19733
  const project = resolveProject(opts.db, request.params.name);
19505
19734
  if (opts.sessionRegistry.isBusy(project.name)) throw agentBusy(project.name);
19506
19735
  opts.sessionRegistry.reset(project.name);
19507
- opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq35(agentSessions.projectId, project.id)).run();
19736
+ opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq36(agentSessions.projectId, project.id)).run();
19508
19737
  return { status: "reset" };
19509
19738
  }
19510
19739
  );
@@ -19528,7 +19757,7 @@ function registerAgentRoutes(app, opts) {
19528
19757
  return streamViewerTurn(opts, project, viewerId, body, reply, turnAttribution(request));
19529
19758
  }
19530
19759
  if (body.conversationId !== void 0) {
19531
- const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq35(agentSessions.projectId, project.id)).get();
19760
+ const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq36(agentSessions.projectId, project.id)).get();
19532
19761
  if ((current?.id ?? null) !== body.conversationId) throw validationError("The active conversation changed. Reload the conversation before sending.");
19533
19762
  }
19534
19763
  const promptText = body.prompt;
@@ -19940,7 +20169,7 @@ function stripHtml(html) {
19940
20169
  }
19941
20170
 
19942
20171
  // src/snapshot-service.ts
19943
- var log30 = createLogger("Snapshot");
20172
+ var log31 = createLogger("Snapshot");
19944
20173
  var ANALYSIS_PROVIDER_PRIORITY = ["openai", "claude", "gemini", "perplexity", "muse", "local"];
19945
20174
  var SNAPSHOT_QUERY_COUNT = 6;
19946
20175
  var SnapshotService = class {
@@ -20042,7 +20271,7 @@ var SnapshotService = class {
20042
20271
  return mapAuditReport(report);
20043
20272
  } catch (err) {
20044
20273
  const message = describeError(err);
20045
- log30.warn("audit.failed", { homepageUrl, error: message });
20274
+ log31.warn("audit.failed", { homepageUrl, error: message });
20046
20275
  return {
20047
20276
  url: homepageUrl,
20048
20277
  finalUrl: homepageUrl,
@@ -20071,7 +20300,7 @@ var SnapshotService = class {
20071
20300
  queries: parsedQueries
20072
20301
  };
20073
20302
  } catch (err) {
20074
- log30.warn("profile.generation-failed", {
20303
+ log31.warn("profile.generation-failed", {
20075
20304
  domain: ctx.domain,
20076
20305
  provider: ctx.analysisProvider.adapter.name,
20077
20306
  error: describeError(err)
@@ -20221,7 +20450,7 @@ var SnapshotService = class {
20221
20450
  recommendedActions: uniqueStrings2(parsed.recommendedActions ?? []).slice(0, 4)
20222
20451
  };
20223
20452
  } catch (err) {
20224
- log30.warn("response.analysis-failed", {
20453
+ log31.warn("response.analysis-failed", {
20225
20454
  provider: ctx.analysisProvider.adapter.name,
20226
20455
  error: describeError(err)
20227
20456
  });
@@ -20491,7 +20720,7 @@ function clipText(value, length) {
20491
20720
  }
20492
20721
 
20493
20722
  // src/research-runner.ts
20494
- import { and as and30, eq as eq36, inArray as inArray13, sql as sql13 } from "drizzle-orm";
20723
+ import { and as and31, eq as eq37, inArray as inArray14, sql as sql14 } from "drizzle-orm";
20495
20724
  var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
20496
20725
  function finalResearchRunStatus(completed, failed, waiting) {
20497
20726
  if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
@@ -20499,13 +20728,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
20499
20728
  return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
20500
20729
  }
20501
20730
  async function executeResearchRun(db, registry, runId, projectId, options = {}) {
20502
- const run = db.select().from(researchRuns).where(and30(eq36(researchRuns.id, runId), eq36(researchRuns.projectId, projectId))).get();
20731
+ const run = db.select().from(researchRuns).where(and31(eq37(researchRuns.id, runId), eq37(researchRuns.projectId, projectId))).get();
20503
20732
  if (!run || run.status !== ResearchRunStatuses.queued) return;
20504
- const project = db.select().from(projects).where(eq36(projects.id, projectId)).get();
20733
+ const project = db.select().from(projects).where(eq37(projects.id, projectId)).get();
20505
20734
  if (!project) return;
20506
20735
  const provider = registry.get(run.provider);
20507
20736
  const now = (/* @__PURE__ */ new Date()).toISOString();
20508
- const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and30(eq36(researchRuns.id, runId), eq36(researchRuns.status, ResearchRunStatuses.queued))).run();
20737
+ const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and31(eq37(researchRuns.id, runId), eq37(researchRuns.status, ResearchRunStatuses.queued))).run();
20509
20738
  if (claim.changes !== 1) return;
20510
20739
  const elapsed = startOutcomeTimer();
20511
20740
  const requested = currentOutcomeOrigin();
@@ -20539,8 +20768,8 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20539
20768
  }
20540
20769
  reserved = run.totalQueries;
20541
20770
  reservation = { scope, period };
20542
- const rows = db.select().from(researchRunQueries).where(eq36(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
20543
- const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq36(competitors.projectId, projectId)).orderBy(competitors.domain).all();
20771
+ const rows = db.select().from(researchRunQueries).where(eq37(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
20772
+ const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq37(competitors.projectId, projectId)).orderBy(competitors.domain).all();
20544
20773
  const competitorDomains = competitorRows.map((row) => row.domain);
20545
20774
  const competitorAliases = new Map(competitorRows.map((row) => [row.domain, competitorIdentityAliases(row)]).filter(([, aliases]) => aliases.length > 0));
20546
20775
  const domains = effectiveDomains(project);
@@ -20550,7 +20779,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20550
20779
  await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
20551
20780
  try {
20552
20781
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
20553
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and30(eq36(researchRunQueries.id, row.id), eq36(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
20782
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and31(eq37(researchRunQueries.id, row.id), eq37(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
20554
20783
  const raw = await gate.run(async () => {
20555
20784
  dispatched++;
20556
20785
  return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
@@ -20581,7 +20810,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20581
20810
  rawResponse: raw.rawResponse,
20582
20811
  answerEvidence: raw.evidence ?? null,
20583
20812
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
20584
- }).where(and30(eq36(researchRunQueries.id, row.id), eq36(researchRunQueries.status, ResearchQueryStatuses.running))).run();
20813
+ }).where(and31(eq37(researchRunQueries.id, row.id), eq37(researchRunQueries.status, ResearchQueryStatuses.running))).run();
20585
20814
  if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
20586
20815
  } catch (error) {
20587
20816
  if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
@@ -20632,11 +20861,11 @@ function researchOutcomeStatus(status) {
20632
20861
  }
20633
20862
  }
20634
20863
  function incrementResearchProgress(db, runId, column) {
20635
- db.update(researchRuns).set({ [column]: sql13`${researchRuns[column]} + 1` }).where(eq36(researchRuns.id, runId)).run();
20864
+ db.update(researchRuns).set({ [column]: sql14`${researchRuns[column]} + 1` }).where(eq37(researchRuns.id, runId)).run();
20636
20865
  }
20637
20866
  function markResearchQueryFailed(db, runId, queryId, error) {
20638
20867
  const message = describeError(error);
20639
- const unfinished = and30(eq36(researchRunQueries.id, queryId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses));
20868
+ const unfinished = and31(eq37(researchRunQueries.id, queryId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses));
20640
20869
  if (error instanceof IncompleteAnswerError && error.resumable) {
20641
20870
  db.update(researchRunQueries).set({
20642
20871
  status: ResearchQueryStatuses["waiting-upstream"],
@@ -20652,10 +20881,10 @@ function markResearchQueryFailed(db, runId, queryId, error) {
20652
20881
  if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
20653
20882
  }
20654
20883
  function markUnfinishedResearchQueriesFailed(db, runId, error) {
20655
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and30(eq36(researchRunQueries.researchRunId, runId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
20884
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and31(eq37(researchRunQueries.researchRunId, runId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
20656
20885
  }
20657
20886
  function finalizeResearchRun(db, runId, fatalError) {
20658
- const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq36(researchRunQueries.researchRunId, runId)).all();
20887
+ const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq37(researchRunQueries.researchRunId, runId)).all();
20659
20888
  const completed = rows.filter((row) => row.status === ResearchQueryStatuses.completed).length;
20660
20889
  const failed = rows.filter((row) => row.status === ResearchQueryStatuses.failed).length;
20661
20890
  const waiting = rows.filter((row) => row.status === ResearchQueryStatuses["waiting-upstream"]).length;
@@ -20667,12 +20896,12 @@ function finalizeResearchRun(db, runId, fatalError) {
20667
20896
  error: fatalError ?? (failed === rows.length ? "Every research query failed." : null),
20668
20897
  // A run waiting on upstream jobs has not finished.
20669
20898
  finishedAt: waiting > 0 ? null : (/* @__PURE__ */ new Date()).toISOString()
20670
- }).where(eq36(researchRuns.id, runId)).run();
20899
+ }).where(eq37(researchRuns.id, runId)).run();
20671
20900
  return { status, total: rows.length, completed, failed };
20672
20901
  }
20673
20902
 
20674
20903
  // src/google-marketing-sync.ts
20675
- import { and as and31, eq as eq37, isNull as isNull7, sql as sql14 } from "drizzle-orm";
20904
+ import { and as and32, eq as eq38, isNull as isNull7, sql as sql15 } from "drizzle-orm";
20676
20905
  var RUNTIME_FAILURE_REASONS = {
20677
20906
  INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
20678
20907
  NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
@@ -20709,10 +20938,10 @@ function assertSnapshotContext(metadata, expected) {
20709
20938
  }
20710
20939
  }
20711
20940
  function requireSyncRun(db, runId, projectId, kind) {
20712
- const run = db.select().from(runs).where(and31(
20713
- eq37(runs.id, runId),
20714
- eq37(runs.projectId, projectId),
20715
- eq37(runs.kind, kind)
20941
+ const run = db.select().from(runs).where(and32(
20942
+ eq38(runs.id, runId),
20943
+ eq38(runs.projectId, projectId),
20944
+ eq38(runs.kind, kind)
20716
20945
  )).get();
20717
20946
  if (!run) throw withOutcomeReason(new Error(`Run ${runId} is not a ${kind} run for this project.`), OutcomeReasonCodes.NOT_FOUND);
20718
20947
  if (run.status !== RunStatuses.queued) {
@@ -20728,19 +20957,19 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
20728
20957
  status: RunStatuses.failed,
20729
20958
  error: serializeRunError({ message: safeErrorMessage(error) }),
20730
20959
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
20731
- }).where(and31(
20732
- eq37(runs.id, runId),
20733
- eq37(runs.projectId, projectId),
20734
- eq37(runs.kind, kind),
20735
- eq37(runs.status, expectedStatus)
20960
+ }).where(and32(
20961
+ eq38(runs.id, runId),
20962
+ eq38(runs.projectId, projectId),
20963
+ eq38(runs.kind, kind),
20964
+ eq38(runs.status, expectedStatus)
20736
20965
  )).run();
20737
20966
  }
20738
20967
  function claimSyncRun(db, runId, projectId, kind, startedAt) {
20739
- const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and31(
20740
- eq37(runs.id, runId),
20741
- eq37(runs.projectId, projectId),
20742
- eq37(runs.kind, kind),
20743
- eq37(runs.status, RunStatuses.queued)
20968
+ const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and32(
20969
+ eq38(runs.id, runId),
20970
+ eq38(runs.projectId, projectId),
20971
+ eq38(runs.kind, kind),
20972
+ eq38(runs.status, RunStatuses.queued)
20744
20973
  )).run();
20745
20974
  return claim.changes === 1;
20746
20975
  }
@@ -20750,9 +20979,9 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
20750
20979
  let evidenceCollected = false;
20751
20980
  try {
20752
20981
  requireSyncRun(db, runId, projectId, RunKinds["google-ads-sync"]);
20753
- const project = db.select().from(projects).where(eq37(projects.id, projectId)).get();
20982
+ const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
20754
20983
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
20755
- const connection = db.select().from(googleAdsConnections).where(eq37(googleAdsConnections.projectId, projectId)).get();
20984
+ const connection = db.select().from(googleAdsConnections).where(eq38(googleAdsConnections.projectId, projectId)).get();
20756
20985
  if (!connection?.selectedCustomerId) {
20757
20986
  throw withOutcomeReason(new Error("Google Ads needs a selected customer before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
20758
20987
  }
@@ -20804,11 +21033,11 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
20804
21033
  status: RunStatuses.completed,
20805
21034
  finishedAt,
20806
21035
  error: null
20807
- }).where(and31(
20808
- eq37(runs.id, runId),
20809
- eq37(runs.projectId, projectId),
20810
- eq37(runs.kind, RunKinds["google-ads-sync"]),
20811
- eq37(runs.status, RunStatuses.running)
21036
+ }).where(and32(
21037
+ eq38(runs.id, runId),
21038
+ eq38(runs.projectId, projectId),
21039
+ eq38(runs.kind, RunKinds["google-ads-sync"]),
21040
+ eq38(runs.status, RunStatuses.running)
20812
21041
  )).run();
20813
21042
  if (terminalClaim.changes !== 1) {
20814
21043
  throw withOutcomeReason(
@@ -20828,12 +21057,12 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
20828
21057
  lastMetricsSnapshotAt: result.metrics?.metadata.capturedAt ?? connection.lastMetricsSnapshotAt,
20829
21058
  lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
20830
21059
  updatedAt: finishedAt
20831
- }).where(and31(
20832
- eq37(googleAdsConnections.id, connection.id),
20833
- eq37(googleAdsConnections.projectId, projectId),
20834
- eq37(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
20835
- connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) : eq37(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
20836
- eq37(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
21060
+ }).where(and32(
21061
+ eq38(googleAdsConnections.id, connection.id),
21062
+ eq38(googleAdsConnections.projectId, projectId),
21063
+ eq38(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
21064
+ connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) : eq38(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
21065
+ eq38(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
20837
21066
  )).run();
20838
21067
  if (connectionClaim.changes !== 1) {
20839
21068
  throw withOutcomeReason(
@@ -20873,9 +21102,9 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20873
21102
  let evidenceCollected = false;
20874
21103
  try {
20875
21104
  requireSyncRun(db, runId, projectId, RunKinds["gtm-sync"]);
20876
- const project = db.select().from(projects).where(eq37(projects.id, projectId)).get();
21105
+ const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
20877
21106
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
20878
- const connection = db.select().from(gtmConnections).where(eq37(gtmConnections.projectId, projectId)).get();
21107
+ const connection = db.select().from(gtmConnections).where(eq38(gtmConnections.projectId, projectId)).get();
20879
21108
  if (!connection?.selectedAccountId || !connection.selectedContainerId) {
20880
21109
  throw withOutcomeReason(new Error("GTM needs a selected account and container before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
20881
21110
  }
@@ -20913,11 +21142,11 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20913
21142
  status: RunStatuses.completed,
20914
21143
  finishedAt,
20915
21144
  error: null
20916
- }).where(and31(
20917
- eq37(runs.id, runId),
20918
- eq37(runs.projectId, projectId),
20919
- eq37(runs.kind, RunKinds["gtm-sync"]),
20920
- eq37(runs.status, RunStatuses.running)
21145
+ }).where(and32(
21146
+ eq38(runs.id, runId),
21147
+ eq38(runs.projectId, projectId),
21148
+ eq38(runs.kind, RunKinds["gtm-sync"]),
21149
+ eq38(runs.status, RunStatuses.running)
20921
21150
  )).run();
20922
21151
  if (terminalClaim.changes !== 1) {
20923
21152
  throw withOutcomeReason(
@@ -20932,19 +21161,19 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20932
21161
  selectedWorkspaceName: selectedWorkspace?.name ?? null,
20933
21162
  ...workspaceReplaced ? {
20934
21163
  selectedWorkspaceId: workspaceId,
20935
- selectionGeneration: sql14`${gtmConnections.selectionGeneration} + 1`
21164
+ selectionGeneration: sql15`${gtmConnections.selectionGeneration} + 1`
20936
21165
  } : {},
20937
21166
  lastValidatedAt: snapshot.metadata.capturedAt,
20938
21167
  lastSnapshotAt: snapshot.metadata.capturedAt,
20939
21168
  lastSnapshotId: snapshot.metadata.id,
20940
21169
  updatedAt: finishedAt
20941
- }).where(and31(
20942
- eq37(gtmConnections.id, connection.id),
20943
- eq37(gtmConnections.projectId, projectId),
20944
- eq37(gtmConnections.selectedAccountId, connection.selectedAccountId),
20945
- eq37(gtmConnections.selectedContainerId, connection.selectedContainerId),
20946
- connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) : eq37(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
20947
- eq37(gtmConnections.selectionGeneration, connection.selectionGeneration)
21170
+ }).where(and32(
21171
+ eq38(gtmConnections.id, connection.id),
21172
+ eq38(gtmConnections.projectId, projectId),
21173
+ eq38(gtmConnections.selectedAccountId, connection.selectedAccountId),
21174
+ eq38(gtmConnections.selectedContainerId, connection.selectedContainerId),
21175
+ connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) : eq38(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
21176
+ eq38(gtmConnections.selectionGeneration, connection.selectionGeneration)
20948
21177
  )).run();
20949
21178
  if (connectionClaim.changes !== 1) {
20950
21179
  throw withOutcomeReason(
@@ -20982,7 +21211,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20982
21211
  // src/server.ts
20983
21212
  var _require = createRequire(import.meta.url);
20984
21213
  var { version: PKG_VERSION } = _require("../package.json");
20985
- var log31 = createLogger("Server");
21214
+ var log32 = createLogger("Server");
20986
21215
  var runtimeStartupByServer = /* @__PURE__ */ new WeakMap();
20987
21216
  function waitForServerRuntimeStartup(app) {
20988
21217
  const startup = runtimeStartupByServer.get(app);
@@ -21234,7 +21463,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
21234
21463
  }
21235
21464
  if (migratedGoogle > 0) {
21236
21465
  persistConfigPatch({ google: config.google });
21237
- log31.info("credentials.migrated", { type: "google", count: migratedGoogle });
21466
+ log32.info("credentials.migrated", { type: "google", count: migratedGoogle });
21238
21467
  }
21239
21468
  let migratedGa4 = 0;
21240
21469
  for (const row of rows.ga4) {
@@ -21252,7 +21481,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
21252
21481
  }
21253
21482
  if (migratedGa4 > 0) {
21254
21483
  persistConfigPatch({ ga4: config.ga4 });
21255
- log31.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
21484
+ log32.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
21256
21485
  }
21257
21486
  }
21258
21487
  function isLoopbackPeerAddress(address) {
@@ -21535,17 +21764,17 @@ async function createServer(opts) {
21535
21764
  applyLegacyCredentials(legacyRows, opts.config, persistConfigPatch);
21536
21765
  dropLegacyCredentialColumns(opts.db);
21537
21766
  } catch (err) {
21538
- log31.warn("credentials.migration.failed", {
21767
+ log32.warn("credentials.migration.failed", {
21539
21768
  error: describeError(err)
21540
21769
  });
21541
21770
  }
21542
21771
  }
21543
- log31.info("providers.configured", {
21772
+ log32.info("providers.configured", {
21544
21773
  providers: registeredProviderNames({ providers, cdp: opts.config.cdp })
21545
21774
  });
21546
21775
  registry.replace(configuredProviderEntries(opts.config, API_ADAPTERS, cdpChatgptAdapter));
21547
21776
  for (const name of providersWithUnsupportedBatch(providers, (provider) => adapterMap[provider])) {
21548
- log31.warn("provider.batch.unsupported", {
21777
+ log32.warn("provider.batch.unsupported", {
21549
21778
  provider: name,
21550
21779
  message: `providers.${name}.batch.enabled is true, but the ${name} adapter has no batch API; its sweeps run sync.`
21551
21780
  });
@@ -21565,7 +21794,11 @@ async function createServer(opts) {
21565
21794
  return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
21566
21795
  });
21567
21796
  const allowLoopbackWebhooks = process.env.CANONRY_ALLOW_LOOPBACK_WEBHOOKS !== "0";
21568
- const notifier = new Notifier(opts.db, serverUrl, { allowLoopbackWebhooks });
21797
+ const sentimentInstall = () => {
21798
+ const configuration = loadSentimentInstallConfig();
21799
+ return { ...sentimentInstallReadiness(configuration), model: configuration.model, provider: configuration.provider };
21800
+ };
21801
+ const notifier = new Notifier(opts.db, serverUrl, { allowLoopbackWebhooks, sentimentInstall });
21569
21802
  const intelligenceService = new IntelligenceService(opts.db);
21570
21803
  const aeroClient = new ApiClient(opts.config.apiUrl, opts.config.apiKey, {
21571
21804
  skipProbe: true,
@@ -21592,7 +21825,7 @@ async function createServer(opts) {
21592
21825
  settings: () => resolveChatGptSettings(opts.config)
21593
21826
  });
21594
21827
  if (opts.config.chatgpt && (opts.config.chatgpt.signIn || opts.config.chatgpt.planUsage) && !resolveChatGptSettings(opts.config)) {
21595
- log31.warn("chatgpt.disabled", {
21828
+ log32.warn("chatgpt.disabled", {
21596
21829
  reason: "Sign in with ChatGPT needs chatgpt.clientId and an HTTPS publicUrl; it stays off until both are set."
21597
21830
  });
21598
21831
  }
@@ -21612,7 +21845,7 @@ async function createServer(opts) {
21612
21845
  async (ctx) => {
21613
21846
  if (!sessionRegistry) return;
21614
21847
  if (!agentProactive) return;
21615
- const project = opts.db.select({ name: projects.name }).from(projects).where(eq38(projects.id, ctx.projectId)).get();
21848
+ const project = opts.db.select({ name: projects.name }).from(projects).where(eq39(projects.id, ctx.projectId)).get();
21616
21849
  if (!project) return;
21617
21850
  let content;
21618
21851
  if (ctx.kind === RunKinds["aeo-discover-probe"]) {
@@ -22042,6 +22275,7 @@ async function createServer(opts) {
22042
22275
  let stopSiteLiveness = null;
22043
22276
  let stopReviewDeliveries = null;
22044
22277
  let stopUnrecognizedAgentAlerts = null;
22278
+ let stopSentimentAlerts = null;
22045
22279
  let stopTrafficReclassification = null;
22046
22280
  let stopProviderBatchPoller = null;
22047
22281
  let stopInstallState = null;
@@ -22086,7 +22320,7 @@ async function createServer(opts) {
22086
22320
  void (async () => {
22087
22321
  try {
22088
22322
  const report = await schedulerClient.runDoctor({ project: projectName, checkIds: scheduledHealthCheckIds() });
22089
- const project = opts.db.select().from(projects).where(eq38(projects.name, projectName)).get();
22323
+ const project = opts.db.select().from(projects).where(eq39(projects.name, projectName)).get();
22090
22324
  if (!project) {
22091
22325
  app.log.warn({ projectName }, "doctor schedule fired for an unknown project");
22092
22326
  return;
@@ -22378,7 +22612,7 @@ async function createServer(opts) {
22378
22612
  })();
22379
22613
  if (opts.config.apiKey) {
22380
22614
  const keyHash = hashApiKey(opts.config.apiKey);
22381
- const existing = opts.db.select().from(apiKeys).where(eq38(apiKeys.keyHash, keyHash)).get();
22615
+ const existing = opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, keyHash)).get();
22382
22616
  if (!existing) {
22383
22617
  const prefix = opts.config.apiKey.slice(0, 12);
22384
22618
  opts.db.insert(apiKeys).values({
@@ -22397,14 +22631,14 @@ async function createServer(opts) {
22397
22631
  );
22398
22632
  const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
22399
22633
  opts.db.delete(dashboardSessions).where(or4(
22400
- eq38(dashboardSessions.apiKeyHash, ""),
22401
- and32(
22634
+ eq39(dashboardSessions.apiKeyHash, ""),
22635
+ and33(
22402
22636
  isNotNull5(dashboardSessions.passwordFingerprint),
22403
22637
  ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
22404
22638
  )
22405
22639
  )).run();
22406
22640
  if (!opts.config.dashboardPasswordHash) {
22407
- const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and32(eq38(auditLog.entityType, "dashboard-password"), eq38(auditLog.action, action))).get()?.at ?? null;
22641
+ const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and33(eq39(auditLog.entityType, "dashboard-password"), eq39(auditLog.action, action))).get()?.at ?? null;
22408
22642
  const createdAt = lastPasswordEventAt("dashboard-password.created");
22409
22643
  const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
22410
22644
  if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
@@ -22438,23 +22672,23 @@ async function createServer(opts) {
22438
22672
  currentApiKeyHash: apiKeys.keyHash,
22439
22673
  passwordFingerprint: dashboardSessions.passwordFingerprint,
22440
22674
  expiresAt: dashboardSessions.expiresAt
22441
- }).from(dashboardSessions).innerJoin(apiKeys, eq38(apiKeys.id, dashboardSessions.apiKeyId)).where(and32(eq38(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
22675
+ }).from(dashboardSessions).innerJoin(apiKeys, eq39(apiKeys.id, dashboardSessions.apiKeyId)).where(and33(eq39(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
22442
22676
  if (!session) return null;
22443
22677
  const expiresAt = Date.parse(session.expiresAt);
22444
22678
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
22445
- opts.db.delete(dashboardSessions).where(eq38(dashboardSessions.tokenHash, tokenHash)).run();
22679
+ opts.db.delete(dashboardSessions).where(eq39(dashboardSessions.tokenHash, tokenHash)).run();
22446
22680
  return null;
22447
22681
  }
22448
22682
  return session.apiKeyId;
22449
22683
  };
22450
22684
  const clearSession = (sessionId) => {
22451
22685
  if (sessionId) {
22452
- opts.db.delete(dashboardSessions).where(eq38(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
22686
+ opts.db.delete(dashboardSessions).where(eq39(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
22453
22687
  }
22454
22688
  };
22455
22689
  const getDefaultApiKey = () => {
22456
22690
  if (!opts.config.apiKey) return void 0;
22457
- return opts.db.select().from(apiKeys).where(eq38(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
22691
+ return opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
22458
22692
  };
22459
22693
  const setSessionCookie = (reply, sessionId) => {
22460
22694
  reply.header(
@@ -22615,12 +22849,12 @@ async function createServer(opts) {
22615
22849
  return reply.send({ authenticated: true });
22616
22850
  }
22617
22851
  if (apiKey) {
22618
- const key = opts.db.select().from(apiKeys).where(eq38(apiKeys.keyHash, hashApiKey(apiKey))).get();
22852
+ const key = opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, hashApiKey(apiKey))).get();
22619
22853
  if (!key || key.revokedAt) {
22620
22854
  const err2 = authInvalid();
22621
22855
  return reply.status(err2.statusCode).send(err2.toJSON());
22622
22856
  }
22623
- opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq38(apiKeys.id, key.id)).run();
22857
+ opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq39(apiKeys.id, key.id)).run();
22624
22858
  setSessionCookie(reply, createSession(key));
22625
22859
  return reply.send({ authenticated: true });
22626
22860
  }
@@ -22686,7 +22920,7 @@ async function createServer(opts) {
22686
22920
  const sentimentPoller = createSentimentPoller(
22687
22921
  () => sentimentWorker.tick(),
22688
22922
  () => {
22689
- log31.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
22923
+ log32.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
22690
22924
  }
22691
22925
  );
22692
22926
  const pollSentiment = sentimentPoller.poll;
@@ -22698,7 +22932,7 @@ async function createServer(opts) {
22698
22932
  const recomputeDebts = /* @__PURE__ */ new Map();
22699
22933
  let recomputeSequence = 0;
22700
22934
  const markAnswerFieldRecompute = (projectId, full) => {
22701
- opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql15`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq38(projects.id, projectId)).run();
22935
+ opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql16`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq39(projects.id, projectId)).run();
22702
22936
  };
22703
22937
  const requestAnswerFieldRecompute = (projectId, projectName, scope, reason) => {
22704
22938
  const sequence = ++recomputeSequence;
@@ -22716,10 +22950,10 @@ async function createServer(opts) {
22716
22950
  if (pass.full && debt.latestFull <= sequence) debt.latestFull = 0;
22717
22951
  try {
22718
22952
  if (debt.latest === sequence && debt.latestFull === 0) {
22719
- opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq38(projects.id, projectId)).run();
22953
+ opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq39(projects.id, projectId)).run();
22720
22954
  if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
22721
22955
  } else if (debt.latestFull === 0) {
22722
- opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and32(eq38(projects.id, projectId), eq38(projects.answerFieldsRecompute, "full"))).run();
22956
+ opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and33(eq39(projects.id, projectId), eq39(projects.answerFieldsRecompute, "full"))).run();
22723
22957
  }
22724
22958
  } catch (err) {
22725
22959
  app.log.error({ err, projectId }, "could not clear the owed answer field recompute");
@@ -22756,7 +22990,7 @@ async function createServer(opts) {
22756
22990
  await yieldToEventLoop4();
22757
22991
  const reason = (competitorAutoAliasReasons.get(projectId) ?? []).join(",");
22758
22992
  competitorAutoAliasReasons.delete(projectId);
22759
- const project = opts.db.select().from(projects).where(eq38(projects.id, projectId)).get();
22993
+ const project = opts.db.select().from(projects).where(eq39(projects.id, projectId)).get();
22760
22994
  if (!project || project.competitorAutoAliases === "off") return;
22761
22995
  if (project.competitorAutoAliases === "apply") {
22762
22996
  await competitorAutoAliases.request(projectId, reason).catch(() => void 0);
@@ -22881,10 +23115,7 @@ async function createServer(opts) {
22881
23115
  db: opts.db,
22882
23116
  claimScheduledSync,
22883
23117
  sentiment: {
22884
- install: () => {
22885
- const configuration = loadSentimentInstallConfig();
22886
- return { ...sentimentInstallReadiness(configuration), model: configuration.model, provider: configuration.provider };
22887
- },
23118
+ install: sentimentInstall,
22888
23119
  previewSecret: opts.config.apiKey,
22889
23120
  estimate: (input) => {
22890
23121
  const built = buildJevSentimentRequest(input);
@@ -22950,6 +23181,7 @@ async function createServer(opts) {
22950
23181
  // Powers the `canonry.version.current` doctor check. Non-blocking.
22951
23182
  getUpdateStatus: () => getServerUpdateStatus(),
22952
23183
  allowLoopbackWebhooks,
23184
+ appVersion: PACKAGE_VERSION,
22953
23185
  // Wall-clock budget for one incremental Vercel drain. This is the only lever
22954
23186
  // that decides whether a source catches up or falls further behind, and it
22955
23187
  // was previously reachable only from tests, so a source losing ground could
@@ -22983,8 +23215,8 @@ async function createServer(opts) {
22983
23215
  getAgentPin: () => describeAgentPin(opts.config),
22984
23216
  getGoogleMarketingDoctorInput: (ctx) => {
22985
23217
  if (!ctx.project) return null;
22986
- const googleAds = opts.db.select().from(googleAdsConnections).where(eq38(googleAdsConnections.projectId, ctx.project.id)).get();
22987
- const gtm = opts.db.select().from(gtmConnections).where(eq38(gtmConnections.projectId, ctx.project.id)).get();
23218
+ const googleAds = opts.db.select().from(googleAdsConnections).where(eq39(googleAdsConnections.projectId, ctx.project.id)).get();
23219
+ const gtm = opts.db.select().from(gtmConnections).where(eq39(gtmConnections.projectId, ctx.project.id)).get();
22988
23220
  const googleAdsCredential = getGoogleAdsConnection(opts.config, ctx.project.id);
22989
23221
  const gtmCredential = getGtmConnection(opts.config, ctx.project.id);
22990
23222
  const googleAdsConnected = Boolean(googleAdsCredential?.accessToken);
@@ -23234,7 +23466,7 @@ async function createServer(opts) {
23234
23466
  ...inspectOpts,
23235
23467
  config: opts.config
23236
23468
  }).then(() => {
23237
- const finished = opts.db.select({ status: runs.status }).from(runs).where(eq38(runs.id, runId)).get();
23469
+ const finished = opts.db.select({ status: runs.status }).from(runs).where(eq39(runs.id, runId)).get();
23238
23470
  if (finished?.status === RunStatuses.completed || finished?.status === RunStatuses.partial) {
23239
23471
  return maybeRefreshGscCoverage(
23240
23472
  opts.db,
@@ -23712,6 +23944,7 @@ async function createServer(opts) {
23712
23944
  });
23713
23945
  stopReviewDeliveries = startReviewDeliveryLoop(() => notifier.drainDueReviewDeliveries());
23714
23946
  stopUnrecognizedAgentAlerts = startUnrecognizedAgentAlertLoop(() => notifier.dispatchUnrecognizedAgentAlerts());
23947
+ stopSentimentAlerts = startSentimentAlertLoop(() => notifier.dispatchSentimentAlerts());
23715
23948
  stopTrafficReclassification = startTrafficReclassification({ db: opts.db });
23716
23949
  stopProviderBatchPoller = startProviderBatchPoller({ db: opts.db, registry, runner: jobRunner });
23717
23950
  if (!embed.enabled) {
@@ -23722,7 +23955,7 @@ async function createServer(opts) {
23722
23955
  isBacklinksInstalled: () => isDuckdbInstalled()
23723
23956
  });
23724
23957
  }
23725
- for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq38(researchRuns.status, ResearchRunStatuses.queued)).all()) {
23958
+ for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq39(researchRuns.status, ResearchRunStatuses.queued)).all()) {
23726
23959
  dispatchResearchRun(run.id, run.projectId, OutcomeTriggers.startup);
23727
23960
  }
23728
23961
  runtimeStartupSettled = true;
@@ -23741,6 +23974,8 @@ async function createServer(opts) {
23741
23974
  stopReviewDeliveries = null;
23742
23975
  stopUnrecognizedAgentAlerts?.();
23743
23976
  stopUnrecognizedAgentAlerts = null;
23977
+ stopSentimentAlerts?.();
23978
+ stopSentimentAlerts = null;
23744
23979
  stopTrafficReclassification?.();
23745
23980
  stopTrafficReclassification = null;
23746
23981
  stopProviderBatchPoller?.();