@canonry/canonry 7.56.0 → 7.57.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 (130) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +1 -1
  2. package/assets/agent-workspace/skills/canonry/references/google-business-profile.md +1 -1
  3. package/assets/assets/{AgentSetupPage-BkKw_in_.js → AgentSetupPage-C-kQupMX.js} +1 -1
  4. package/assets/assets/{AuditHistoryPanel-UtRnS-sh.js → AuditHistoryPanel-DvZk-ikR.js} +1 -1
  5. package/assets/assets/{BacklinksPage-DCSmuAOQ.js → BacklinksPage-TLB85t4y.js} +1 -1
  6. package/assets/assets/{HistoryPage-DzpqCNJM.js → HistoryPage-C4nHeKDs.js} +1 -1
  7. package/assets/assets/{MeasurementPropertyPage-Dh0BJw_f.js → MeasurementPropertyPage-8E17rN5d.js} +1 -1
  8. package/assets/assets/{ProjectPage-D-9IeFap.js → ProjectPage-B4SbAE_N.js} +1 -1
  9. package/assets/assets/{RunsPage-DtllYN3I.js → RunsPage-Enho1Wqz.js} +1 -1
  10. package/assets/assets/{SettingsPage-_p15s-OC.js → SettingsPage-BjLpSN4f.js} +1 -1
  11. package/assets/assets/{SiteHealthSection-BEpXTW3G.js → SiteHealthSection-BUOBO4VH.js} +2 -2
  12. package/assets/assets/ToneBadge-BLQKJIMR.js +60 -0
  13. package/assets/assets/{TrafficPage-wru6cQPP.js → TrafficPage-BtjRPsdl.js} +1 -1
  14. package/assets/assets/{TrafficSourceDetailPage-_XKbd-aS.js → TrafficSourceDetailPage-Bw-9JMOF.js} +1 -1
  15. package/assets/assets/{account-context-BekDho6K.js → account-context-bLel7cL8.js} +1 -1
  16. package/assets/assets/{card-By9JlCCv.js → card-DFlbarlV.js} +1 -1
  17. package/assets/assets/{extract-error-message-SMPhaAkr.js → extract-error-message-BYvs9oIt.js} +1 -1
  18. package/assets/assets/{format-helpers-CVjOUs0j.js → format-helpers-DPVlVrlp.js} +1 -1
  19. package/assets/assets/{index-el2M4tYf.js → index-DWP0Oz6d.js} +4 -4
  20. package/assets/assets/{query-client-8RITTP1A.js → query-client-DLuEpFRm.js} +1 -1
  21. package/assets/assets/{react-query-BXwc1UHc.js → react-query-BVY1CIRz.js} +1 -1
  22. package/assets/assets/{react-sigma_core.esm.min-CM12VcoB.js → react-sigma_core.esm.min-BaR2koVY.js} +1 -1
  23. package/assets/assets/{service-B0wkGxvy.js → service-DiBkOka7.js} +1 -1
  24. package/assets/index.html +7 -7
  25. package/dist/{ads-SPXNKDEW.js → ads-6PCFYPZ6.js} +3 -3
  26. package/dist/{agent-THPYOGXD.js → agent-UA3J23KG.js} +7 -7
  27. package/dist/{agent-ask-VHRA5RVU.js → agent-ask-D4RWVHZX.js} +3 -3
  28. package/dist/{agent-conversations-5HXXVMZV.js → agent-conversations-BSKUJF7H.js} +3 -3
  29. package/dist/{agent-memory-SKBUFHGV.js → agent-memory-ENPPLOV7.js} +3 -3
  30. package/dist/{agent-providers-TOIA75C6.js → agent-providers-5NV7YEVG.js} +3 -3
  31. package/dist/{agent-transcript-DFE2PDTS.js → agent-transcript-TXDTQ7Q2.js} +3 -3
  32. package/dist/{analytics-JJHPK2TK.js → analytics-6ITOJIGW.js} +3 -3
  33. package/dist/{apply-AC36NXPF.js → apply-EPQXYQRO.js} +3 -3
  34. package/dist/{backfill-HMP43HMJ.js → backfill-4LAL4IIT.js} +9 -9
  35. package/dist/{backlinks-EKSQJXMS.js → backlinks-ECIDQQ4I.js} +3 -3
  36. package/dist/{bing-XZQ6CQM4.js → bing-LHTVVJK7.js} +3 -3
  37. package/dist/{bootstrap-GJUT3AVH.js → bootstrap-KHYUCFLP.js} +10 -10
  38. package/dist/{cdp-QROXKBXS.js → cdp-YZWEKVRO.js} +7 -7
  39. package/dist/{chunk-AOBMI5UM.js → chunk-2R32P77U.js} +1 -1
  40. package/dist/{chunk-NZ6KZLTM.js → chunk-3HRHHFQM.js} +6 -1
  41. package/dist/{chunk-XUW5SU24.js → chunk-3OTH3ABK.js} +4 -4
  42. package/dist/{chunk-ADCVXKSD.js → chunk-522MYBLV.js} +1 -1
  43. package/dist/{chunk-37YB52NM.js → chunk-5AJWITKP.js} +45 -1
  44. package/dist/{chunk-SJLCALSV.js → chunk-5L2ZTXBH.js} +3 -3
  45. package/dist/{chunk-RELKG6XH.js → chunk-6MK426LA.js} +2 -2
  46. package/dist/{chunk-BALZYIFH.js → chunk-BJN7FNIB.js} +4 -4
  47. package/dist/{chunk-2Z7FALTN.js → chunk-BURMKOEF.js} +2 -2
  48. package/dist/{chunk-TPCXTUL5.js → chunk-E3YBETL6.js} +1 -1
  49. package/dist/{chunk-ZNAAZHNT.js → chunk-F7WRZW3A.js} +47 -3
  50. package/dist/{chunk-DOP5QNPM.js → chunk-FHYOQI26.js} +2989 -1907
  51. package/dist/{chunk-DDM6PVXJ.js → chunk-GT7HWKBO.js} +3 -3
  52. package/dist/{chunk-VZURJP3T.js → chunk-HPC3CBPI.js} +1 -1
  53. package/dist/{chunk-3BHGEP3O.js → chunk-J4YFSAAY.js} +8 -8
  54. package/dist/{chunk-RWYKUCPF.js → chunk-JQS2H65K.js} +375 -325
  55. package/dist/{chunk-C5LD76KR.js → chunk-JWBFDZIP.js} +3 -3
  56. package/dist/{chunk-WRYVESRH.js → chunk-KRIZF753.js} +1 -1
  57. package/dist/{chunk-NSE55FZE.js → chunk-LCC5ZJPV.js} +2 -2
  58. package/dist/{chunk-F5DLOQ3B.js → chunk-MVUYDJ7G.js} +2 -2
  59. package/dist/{chunk-3HZZ2XZD.js → chunk-NUHCDBKR.js} +5 -5
  60. package/dist/{chunk-T7A46CVU.js → chunk-OAA7RHMG.js} +5 -5
  61. package/dist/{chunk-CFGQOIXW.js → chunk-OJ5IDPYY.js} +3 -3
  62. package/dist/{chunk-Q5ZRUA57.js → chunk-S2UDQAT7.js} +1 -1
  63. package/dist/{chunk-S4H7KMIH.js → chunk-SHUTA74W.js} +618 -282
  64. package/dist/{chunk-V4V7WOHY.js → chunk-SOKD3TRA.js} +46 -2
  65. package/dist/{chunk-QAGZQ2DY.js → chunk-TIKT62IV.js} +1749 -1634
  66. package/dist/{chunk-SVLNIJS2.js → chunk-TIYL4KVS.js} +1 -1
  67. package/dist/{chunk-P2OVWQKT.js → chunk-TXBL3N46.js} +1 -1
  68. package/dist/{chunk-W5FAL4LJ.js → chunk-ULFDCKIC.js} +4 -4
  69. package/dist/{chunk-ZOVL5NAP.js → chunk-VF36TGF4.js} +1 -1
  70. package/dist/{chunk-4QRF7TNW.js → chunk-XXYBDAS2.js} +2 -2
  71. package/dist/{chunk-PUTJ6LPE.js → chunk-YFUQHJRZ.js} +1 -1
  72. package/dist/{chunk-RCCZ6VGK.js → chunk-ZUAXF73A.js} +1 -1
  73. package/dist/{citations-5ARZ6M42.js → citations-HXVWVRDO.js} +3 -3
  74. package/dist/{cli-catalog-XD7VY3ES.js → cli-catalog-EDAH3242.js} +3 -3
  75. package/dist/{cli-commands-KGTXEDAZ.js → cli-commands-NUXQWIKA.js} +7 -7
  76. package/dist/cli.js +13 -13
  77. package/dist/{competitor-XWTEIVZL.js → competitor-XYPBUM4Q.js} +3 -3
  78. package/dist/{content-4EVGV32G.js → content-SDTRO2XT.js} +3 -3
  79. package/dist/{dashboard-YEYFINMF.js → dashboard-55IRUB73.js} +6 -6
  80. package/dist/{demo-RK5OKZIY.js → demo-KEFXTKRQ.js} +1 -1
  81. package/dist/{demo-server-JL4JLKMG.js → demo-server-BDQDPUWN.js} +11 -11
  82. package/dist/{discover-VQYJ4UOL.js → discover-I6AQJPUK.js} +3 -3
  83. package/dist/{discover-eval-FMEMPSM3.js → discover-eval-GLGBZC7B.js} +3 -3
  84. package/dist/{doctor-VYES5HCM.js → doctor-Q47J7GZI.js} +3 -3
  85. package/dist/{evidence-BG45EBS3.js → evidence-AMLTPRHA.js} +3 -3
  86. package/dist/{export-cmd-PQZCMR7C.js → export-cmd-NTCX43DE.js} +3 -3
  87. package/dist/{ga-ZQL2LHQA.js → ga-END6LQJW.js} +3 -3
  88. package/dist/{gbp-KNWDBHFM.js → gbp-CVJXSTTB.js} +33 -4
  89. package/dist/{google-GOKE6J5E.js → google-4OCFGWGV.js} +4 -4
  90. package/dist/{google-marketing-7DYEKRHS.js → google-marketing-NW27PADK.js} +1 -1
  91. package/dist/{health-cmd-4OZ7EYWI.js → health-cmd-2KMNASB3.js} +3 -3
  92. package/dist/{history-U2W77DIY.js → history-6LBFXVKF.js} +3 -3
  93. package/dist/index.d.ts +319 -13
  94. package/dist/index.js +24 -24
  95. package/dist/{init-WTLTEYSB.js → init-542CZBNS.js} +11 -11
  96. package/dist/{insights-LWMDBEYC.js → insights-YH7NP5LX.js} +3 -3
  97. package/dist/intelligence-service-6IVSAF2X.js +15 -0
  98. package/dist/{keys-RSKVNMJI.js → keys-CJ5DTL4Y.js} +3 -3
  99. package/dist/{keyword-IM4GUM5U.js → keyword-7FMLF3B7.js} +3 -3
  100. package/dist/{logs-B35V2RPE.js → logs-362Y2Z55.js} +3 -3
  101. package/dist/{mcp-UFMKQFGP.js → mcp-RTJ3HZLY.js} +2 -2
  102. package/dist/mcp.js +9 -9
  103. package/dist/{measurement-plan-BOHLLJD5.js → measurement-plan-ICT6U62D.js} +5 -5
  104. package/dist/{notify-RQIQP5ZF.js → notify-HT7QBF3B.js} +3 -3
  105. package/dist/{organic-evidence-C3OZR7UY.js → organic-evidence-CAGEQ5OR.js} +3 -3
  106. package/dist/{overview-OVIPKMAY.js → overview-Y6RVRPC7.js} +4 -4
  107. package/dist/{project-QBUTYR6J.js → project-7OBPDHLH.js} +3 -3
  108. package/dist/{query-KCGET5FS.js → query-23GN3BC6.js} +3 -3
  109. package/dist/{research-HTURJWRL.js → research-N7EVBN47.js} +3 -3
  110. package/dist/{results-export-GJNXEXV4.js → results-export-BHEYAZXQ.js} +3 -3
  111. package/dist/{run-ZNTT7W5M.js → run-KVPMLHGQ.js} +4 -4
  112. package/dist/{schedule-S2ODDXFB.js → schedule-EZ2TLM22.js} +3 -3
  113. package/dist/{search-UW56VG5B.js → search-UHUPUGT3.js} +3 -3
  114. package/dist/{serve-BIWTUO6A.js → serve-R2OR4ZF2.js} +25 -25
  115. package/dist/{session-T4Q6NH3K.js → session-CSYHALIE.js} +12 -12
  116. package/dist/{settings-TGSORPVW.js → settings-QCFPNHSC.js} +3 -3
  117. package/dist/{skills-SBZZLY4T.js → skills-FXPAKCVV.js} +2 -2
  118. package/dist/{snapshot-OMS33CN4.js → snapshot-NY5PNDWR.js} +3 -3
  119. package/dist/{src-LKNW35M6.js → src-V6W5XBAI.js} +4 -2
  120. package/dist/{status-7D7NUW7M.js → status-MYXAVPIB.js} +4 -4
  121. package/dist/{technical-aeo-UFDHAV7G.js → technical-aeo-4C2EQ6C5.js} +3 -3
  122. package/dist/{telemetry-ZPVJITHJ.js → telemetry-SMY4NDD2.js} +4 -4
  123. package/dist/{tools-PDV6BJ5Y.js → tools-HIRCGFM2.js} +11 -11
  124. package/dist/{traffic-T6YAKUY5.js → traffic-QTHEOB5M.js} +5 -5
  125. package/dist/{users-6N2YMWAP.js → users-FDZPHCWI.js} +3 -3
  126. package/dist/{visibility-stats-GODBRQVG.js → visibility-stats-6B3S3AIY.js} +3 -3
  127. package/dist/{wordpress-ISFI67TH.js → wordpress-5IIA4H3G.js} +3 -3
  128. package/package.json +1 -1
  129. package/assets/assets/ToneBadge-nxe12_3b.js +0 -60
  130. package/dist/intelligence-service-PY6QR36M.js +0 -15
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answerServiceAdapters,
3
3
  answerServiceDescriptors
4
- } from "./chunk-RCCZ6VGK.js";
4
+ } from "./chunk-ZUAXF73A.js";
5
5
  import {
6
6
  AeroLlmUsageFeatures,
7
7
  aeroTurnStatus,
@@ -27,14 +27,14 @@ import {
27
27
  resolveConfiguredAgentProvider,
28
28
  resolveSessionProviderAndModel,
29
29
  setAeroSystemPrompt
30
- } from "./chunk-3HZZ2XZD.js";
30
+ } from "./chunk-NUHCDBKR.js";
31
31
  import {
32
32
  AeroToolProfiles,
33
33
  AeroToolScopes,
34
34
  buildAeroStateTools,
35
35
  isAeroToolProfile,
36
36
  truncateToolResult
37
- } from "./chunk-XUW5SU24.js";
37
+ } from "./chunk-3OTH3ABK.js";
38
38
  import {
39
39
  getGoogleAuthConfig,
40
40
  getGoogleConnection,
@@ -53,7 +53,7 @@ import {
53
53
  removeCloudflareTrafficConnection,
54
54
  removeCloudflareTrafficConnectionBySourceId,
55
55
  upsertCloudflareTrafficConnection
56
- } from "./chunk-SVLNIJS2.js";
56
+ } from "./chunk-TIYL4KVS.js";
57
57
  import {
58
58
  claudeAdapter,
59
59
  embedQueries,
@@ -64,7 +64,7 @@ import {
64
64
  openaiAdapter,
65
65
  openrouterAdapter,
66
66
  perplexityAdapter
67
- } from "./chunk-RELKG6XH.js";
67
+ } from "./chunk-6MK426LA.js";
68
68
  import {
69
69
  classifyUsageSurface,
70
70
  createApiUsageTelemetry,
@@ -76,7 +76,7 @@ import {
76
76
  startOutcomeTimer,
77
77
  trackFeatureCompleted,
78
78
  trackInstallState
79
- } from "./chunk-W5FAL4LJ.js";
79
+ } from "./chunk-ULFDCKIC.js";
80
80
  import {
81
81
  isLoopbackBindHost
82
82
  } from "./chunk-TSENU4GG.js";
@@ -84,7 +84,7 @@ import {
84
84
  isApiProviderRegistrable,
85
85
  isCdpProviderRegistrable,
86
86
  registeredProviderNames
87
- } from "./chunk-Q5ZRUA57.js";
87
+ } from "./chunk-S2UDQAT7.js";
88
88
  import {
89
89
  checkLatestVersionForServer,
90
90
  getOrCreateAnonymousId,
@@ -95,17 +95,17 @@ import {
95
95
  recordDashboardEvent,
96
96
  setTelemetryPreference,
97
97
  trackEvent
98
- } from "./chunk-4QRF7TNW.js";
98
+ } from "./chunk-XXYBDAS2.js";
99
99
  import {
100
100
  createCanonryMcpServer
101
- } from "./chunk-CFGQOIXW.js";
101
+ } from "./chunk-OJ5IDPYY.js";
102
102
  import {
103
103
  CANONRY_MCP_TIERS,
104
104
  CANONRY_MCP_TOOLKIT_NAMES
105
105
  } from "./chunk-4MJYGB56.js";
106
106
  import {
107
107
  ApiClient
108
- } from "./chunk-V4V7WOHY.js";
108
+ } from "./chunk-SOKD3TRA.js";
109
109
  import {
110
110
  AGENT_PROVIDERS,
111
111
  adapterSupportsBatch,
@@ -136,21 +136,21 @@ import {
136
136
  saveConfigPatch,
137
137
  sentimentInstallReadiness,
138
138
  updateSharedProviderExecutionGate
139
- } from "./chunk-PUTJ6LPE.js";
139
+ } from "./chunk-YFUQHJRZ.js";
140
140
  import {
141
141
  getBundledSkillSnapshots
142
- } from "./chunk-VZURJP3T.js";
142
+ } from "./chunk-HPC3CBPI.js";
143
143
  import {
144
144
  computeFactorAverages,
145
145
  deleteSiteCrawlGraphLayout,
146
146
  persistSiteCrawlGraphLayout,
147
147
  prepareSiteCrawlGraphLayout,
148
148
  recordedSharePct
149
- } from "./chunk-F5DLOQ3B.js";
149
+ } from "./chunk-MVUYDJ7G.js";
150
150
  import {
151
151
  CanonryMcpToolNames,
152
152
  canonryMcpTools
153
- } from "./chunk-ZNAAZHNT.js";
153
+ } from "./chunk-F7WRZW3A.js";
154
154
  import {
155
155
  PACKAGE_VERSION
156
156
  } from "./chunk-AOJU5LKX.js";
@@ -162,11 +162,11 @@ import {
162
162
  addLogListener,
163
163
  createFastifyLogger,
164
164
  createLogger
165
- } from "./chunk-T7A46CVU.js";
165
+ } from "./chunk-OAA7RHMG.js";
166
166
  import {
167
167
  computeCitedCompetitorDomains,
168
168
  determineCitationState
169
- } from "./chunk-ZOVL5NAP.js";
169
+ } from "./chunk-VF36TGF4.js";
170
170
  import {
171
171
  BingApiError,
172
172
  CC_CACHE_DIR,
@@ -284,7 +284,7 @@ import {
284
284
  webhookResponseReason,
285
285
  webhookTargetRefusalReason,
286
286
  writeAuditLog
287
- } from "./chunk-DOP5QNPM.js";
287
+ } from "./chunk-FHYOQI26.js";
288
288
  import {
289
289
  OperationalLogStore,
290
290
  SentimentIdempotencyConflict,
@@ -349,6 +349,7 @@ import {
349
349
  recordSentimentCompletion,
350
350
  researchRunQueries,
351
351
  researchRuns,
352
+ reviewWebhookDeliveries,
352
353
  runFills,
353
354
  runs,
354
355
  schedules,
@@ -366,7 +367,7 @@ import {
366
367
  siteLivenessState,
367
368
  trafficSources,
368
369
  usageCounters
369
- } from "./chunk-37YB52NM.js";
370
+ } from "./chunk-5AJWITKP.js";
370
371
  import {
371
372
  AGENT_MEMORY_VALUE_MAX_BYTES,
372
373
  AI_ENGINE_DOMAINS,
@@ -428,6 +429,7 @@ import {
428
429
  RUN_FILL_PROVIDER_BREAKER,
429
430
  ResearchQueryStatuses,
430
431
  ResearchRunStatuses,
432
+ ReviewDeliveryStates,
431
433
  RunKinds,
432
434
  RunStatuses,
433
435
  RunTriggers,
@@ -516,6 +518,7 @@ import {
516
518
  googleAdsAccessibleCustomersResponseSchema,
517
519
  googleAdsCampaignMetricsQuerySchema,
518
520
  googleAdsRawSnapshotDtoSchema,
521
+ googleBusinessReviewUrl,
519
522
  gtmAccountsResponseSchema,
520
523
  gtmContainerListResponseSchema,
521
524
  gtmGoogleAdsConversionIdMappingDtoSchema,
@@ -601,7 +604,7 @@ import {
601
604
  winnabilityClassLabel,
602
605
  withRetry,
603
606
  withSkippedProviders
604
- } from "./chunk-QAGZQ2DY.js";
607
+ } from "./chunk-TIKT62IV.js";
605
608
 
606
609
  // src/google-marketing-runtime.ts
607
610
  import crypto2 from "crypto";
@@ -3291,7 +3294,7 @@ import path5 from "path";
3291
3294
  import { isIP as isIP2 } from "net";
3292
3295
  import { fileURLToPath } from "url";
3293
3296
  import { setImmediate as yieldToEventLoop4 } from "timers/promises";
3294
- import { and as and25, eq as eq31, isNotNull as isNotNull5, isNull as isNull5, lte as lte2, max, ne as ne4, or as or3, sql as sql13 } from "drizzle-orm";
3297
+ import { and as and26, eq as eq32, isNotNull as isNotNull5, isNull as isNull7, lte as lte3, max, ne as ne4, or as or4, sql as sql13 } from "drizzle-orm";
3295
3298
 
3296
3299
  // ../integration-typesafe/src/classifier.ts
3297
3300
  import { createHash } from "crypto";
@@ -5097,7 +5100,7 @@ function nonBlank(value) {
5097
5100
  return trimmed ? trimmed : void 0;
5098
5101
  }
5099
5102
  function resolveBuildCommit(env = process.env) {
5100
- const embedded = true ? "121fabd2ae5a36b928f00082840026e46b003c0a" : void 0;
5103
+ const embedded = true ? "bf7eb78a9aebff429d424e6f332c70205845d2ae" : void 0;
5101
5104
  return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
5102
5105
  }
5103
5106
  function resolveInstanceIdentity(env = process.env) {
@@ -8286,9 +8289,9 @@ async function executeGbpSync(db, runId, projectId, opts) {
8286
8289
  if (ageDays >= placesRefreshDays) {
8287
8290
  try {
8288
8291
  const place = await getPlaceDetails(loc.placeId, placesApiKey, { tier: placesTier });
8289
- const hash = hashPlaceDetails(place);
8290
- if (!latestPlace || latestPlace.contentHash !== hash) {
8291
- placeToWrite = { contentHash: hash, attributes: place, tier: placesTier, placeId: loc.placeId };
8292
+ const hash2 = hashPlaceDetails(place);
8293
+ if (!latestPlace || latestPlace.contentHash !== hash2) {
8294
+ placeToWrite = { contentHash: hash2, attributes: place, tier: placesTier, placeId: loc.placeId };
8292
8295
  } else {
8293
8296
  placeToTouch = latestPlace.id;
8294
8297
  }
@@ -13073,9 +13076,293 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
13073
13076
  return () => clearInterval(timer);
13074
13077
  }
13075
13078
 
13079
+ // src/review-webhook-delivery.ts
13080
+ import { createHash as createHash6 } from "crypto";
13081
+ import { and as and18, asc as asc4, eq as eq20, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
13082
+ var log19 = createLogger("ReviewDelivery");
13083
+ var hash = (value) => createHash6("sha256").update(JSON.stringify(value)).digest("hex");
13084
+ var REVIEW_DELIVERY_MAX_ATTEMPTS = 10;
13085
+ var REVIEW_CHAT_SENDS_PER_PASS = 3;
13086
+ var REVIEW_DELIVERY_INTERVAL_MS = 6e4;
13087
+ var RETRY_BASE_MS = 6e4;
13088
+ var RETRY_MAX_MS = 6 * 60 * 6e4;
13089
+ function retryDelayMs(attempts, retryAfterSeconds) {
13090
+ const backoff = Math.min(RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1), RETRY_MAX_MS);
13091
+ return Math.max(backoff, (retryAfterSeconds ?? 0) * 1e3);
13092
+ }
13093
+ function permanentlyRefused(status) {
13094
+ return status >= 400 && status < 500 && status !== 408 && status !== 425 && status !== 429;
13095
+ }
13096
+ function reviewEventId(projectId, review) {
13097
+ return "evt_" + hash([
13098
+ projectId,
13099
+ review.reviewName,
13100
+ review.origin,
13101
+ review.starRating,
13102
+ review.comment,
13103
+ review.alertStateAt
13104
+ ]);
13105
+ }
13106
+ function reviewEventRefusal(db, projectId, payload, notification, targetDigest, now) {
13107
+ if (!notification?.enabled || !notification.config.events.includes("review.negative")) return "destination_disabled";
13108
+ if (targetDigest !== void 0 && hash(notification.config.url) !== targetDigest) return "destination_changed";
13109
+ const project = db.select().from(projects).where(eq20(projects.id, projectId)).get();
13110
+ if (!project || project.name !== payload.project.name || project.canonicalDomain !== payload.project.canonicalDomain) return "project_changed";
13111
+ const review = payload.reviews[0];
13112
+ const location = db.select().from(gbpLocations).where(and18(
13113
+ eq20(gbpLocations.projectId, projectId),
13114
+ eq20(gbpLocations.locationName, review.location.name),
13115
+ eq20(gbpLocations.selected, true)
13116
+ )).get();
13117
+ if (!location || review.origin === "gbp" && !review.reviewName.startsWith(`${location.accountName}/${location.locationName}/reviews/`)) return "location_removed_or_deselected";
13118
+ const current = db.select().from(gbpReviews).where(and18(
13119
+ eq20(gbpReviews.projectId, projectId),
13120
+ eq20(gbpReviews.origin, review.origin),
13121
+ eq20(gbpReviews.reviewName, review.reviewName),
13122
+ eq20(gbpReviews.locationName, review.location.name)
13123
+ )).get();
13124
+ if (!current) return "review_removed";
13125
+ if (!isWithinAlertWindow(review.updateTime, now) || !isWithinAlertWindow(current.updateTime, now)) return "review_expired";
13126
+ const threshold = resolveNegativeReviewMaxStars(readNegativeReviewMaxStars(db, projectId));
13127
+ if (!isNegativeReviewRating(current.starRating, threshold) || !isNegativeReviewRating(review.starRating, threshold)) return "review_no_longer_negative";
13128
+ if (["baseline", "skipped", "suppressed", "stale", "none"].includes(current.alertState)) return "review_suppressed";
13129
+ if (review.origin === "places") {
13130
+ const v4HasWorked = db.select({ id: gbpReviewRatings.id }).from(gbpReviewRatings).where(and18(
13131
+ eq20(gbpReviewRatings.projectId, projectId),
13132
+ eq20(gbpReviewRatings.locationName, review.location.name),
13133
+ eq20(gbpReviewRatings.origin, "gbp")
13134
+ )).get() !== void 0;
13135
+ if (businessProfileReviewsCover(location.reviewsAccess, v4HasWorked)) return "review_origin_superseded";
13136
+ }
13137
+ return null;
13138
+ }
13139
+ function cancelReviewDelivery(db, id, reason) {
13140
+ db.transaction((tx) => {
13141
+ const canceled = tx.update(reviewWebhookDeliveries).set({ state: ReviewDeliveryStates.Canceled, retryAt: null }).where(and18(
13142
+ eq20(reviewWebhookDeliveries.id, id),
13143
+ eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending)
13144
+ )).returning({ projectId: reviewWebhookDeliveries.projectId, eventId: reviewWebhookDeliveries.eventId, notificationId: reviewWebhookDeliveries.notificationId, targetDigest: reviewWebhookDeliveries.targetDigest }).get();
13145
+ if (canceled) writeAuditLog(tx, {
13146
+ projectId: canceled.projectId,
13147
+ actor: "scheduler",
13148
+ action: "notification.review-canceled",
13149
+ entityType: "review-webhook-delivery",
13150
+ entityId: id,
13151
+ diff: { eventId: canceled.eventId, notificationId: canceled.notificationId, targetDigest: canceled.targetDigest, reason }
13152
+ });
13153
+ });
13154
+ }
13155
+ function deferReviewDelivery(db, saved, now) {
13156
+ if (saved.state !== ReviewDeliveryStates.Pending && saved.state !== ReviewDeliveryStates.Attempting) return;
13157
+ const waited = now - Date.parse(saved.createdAt);
13158
+ const delay = Math.min(Math.max(RETRY_BASE_MS, Number.isFinite(waited) ? waited / 4 : RETRY_BASE_MS), RETRY_MAX_MS);
13159
+ db.update(reviewWebhookDeliveries).set({ retryAt: new Date(now + delay).toISOString() }).where(and18(
13160
+ eq20(reviewWebhookDeliveries.id, saved.id),
13161
+ eq20(reviewWebhookDeliveries.state, saved.state),
13162
+ eq20(reviewWebhookDeliveries.attempts, saved.attempts)
13163
+ )).run();
13164
+ }
13165
+ function auditUndelivered(db, saved, outcome) {
13166
+ writeAuditLog(db, {
13167
+ projectId: saved.projectId,
13168
+ actor: "scheduler",
13169
+ action: "notification.review-undelivered",
13170
+ entityType: "review-webhook-delivery",
13171
+ entityId: saved.id,
13172
+ diff: { eventId: saved.eventId, notificationId: saved.notificationId, targetDigest: saved.targetDigest, ...outcome }
13173
+ });
13174
+ }
13175
+ function dueReviewDeliveryProjects(db, now) {
13176
+ const at = new Date(now).toISOString();
13177
+ const staleAttempt = new Date(now - 6e4).toISOString();
13178
+ return db.selectDistinct({ projectId: reviewWebhookDeliveries.projectId }).from(reviewWebhookDeliveries).where(or(
13179
+ and18(eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending), or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at))),
13180
+ and18(eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
13181
+ )).all().map((row) => row.projectId);
13182
+ }
13183
+ function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS) {
13184
+ let running = false;
13185
+ const timer = setInterval(() => {
13186
+ if (running) return;
13187
+ running = true;
13188
+ void drain().catch((err) => {
13189
+ log19.warn("review-delivery.drain-failed", { error: describeError(err) });
13190
+ }).finally(() => {
13191
+ running = false;
13192
+ });
13193
+ }, intervalMs);
13194
+ timer.unref?.();
13195
+ return () => clearInterval(timer);
13196
+ }
13197
+ async function drainReviewDeliveries(options) {
13198
+ const now = (options.now ?? Date.now)();
13199
+ const at = new Date(now).toISOString();
13200
+ const staleAttempt = new Date(now - 6e4).toISOString();
13201
+ const ready = options.db.select().from(reviewWebhookDeliveries).where(and18(
13202
+ eq20(reviewWebhookDeliveries.projectId, options.projectId),
13203
+ or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at)),
13204
+ or(
13205
+ eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
13206
+ and18(eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
13207
+ )
13208
+ )).orderBy(asc4(reviewWebhookDeliveries.retryAt), asc4(reviewWebhookDeliveries.attemptedAt), asc4(reviewWebhookDeliveries.createdAt), asc4(reviewWebhookDeliveries.id)).limit(100).all();
13209
+ let delivered = 0;
13210
+ const chatSendsLeft = options.chatSendsLeft ?? /* @__PURE__ */ new Map();
13211
+ for (const debt of ready) {
13212
+ await deliverReviewEvent({
13213
+ ...options,
13214
+ notificationId: debt.notificationId,
13215
+ payload: debt.payload,
13216
+ chatSendsLeft,
13217
+ onDelivered: () => {
13218
+ delivered += 1;
13219
+ options.onDelivered?.();
13220
+ }
13221
+ });
13222
+ }
13223
+ return delivered;
13224
+ }
13225
+ async function deliverReviewEvent(options) {
13226
+ const { db, projectId, notificationId, payload } = options;
13227
+ if (!payload.eventId || !/^evt_[a-f0-9]{64}$/u.test(payload.eventId) || payload.reviews.length !== 1)
13228
+ return false;
13229
+ const notification = db.select().from(notifications).where(
13230
+ and18(
13231
+ eq20(notifications.id, notificationId),
13232
+ eq20(notifications.projectId, projectId)
13233
+ )
13234
+ ).get();
13235
+ const id = hash([projectId, notificationId, payload.eventId]);
13236
+ const now = options.now ?? Date.now;
13237
+ const at = new Date(now()).toISOString();
13238
+ let saved = db.select().from(reviewWebhookDeliveries).where(eq20(reviewWebhookDeliveries.id, id)).get();
13239
+ const event = saved?.payload ?? payload;
13240
+ const refusal = reviewEventRefusal(db, projectId, event, notification, saved?.targetDigest, new Date(now()));
13241
+ if (refusal) {
13242
+ cancelReviewDelivery(db, id, refusal);
13243
+ if (saved?.state === ReviewDeliveryStates.Attempting) deferReviewDelivery(db, saved, now());
13244
+ return false;
13245
+ }
13246
+ if (!notification) return false;
13247
+ const targetDigest = hash(notification.config.url);
13248
+ db.insert(reviewWebhookDeliveries).values({
13249
+ id,
13250
+ projectId,
13251
+ notificationId,
13252
+ eventId: payload.eventId,
13253
+ targetDigest,
13254
+ payload,
13255
+ createdAt: at
13256
+ }).onConflictDoNothing().run();
13257
+ saved = db.select().from(reviewWebhookDeliveries).where(eq20(reviewWebhookDeliveries.id, id)).get();
13258
+ if (!saved || saved.targetDigest !== targetDigest) return false;
13259
+ if (saved.state === ReviewDeliveryStates.Sent) return true;
13260
+ if (saved.state === ReviewDeliveryStates.Uncertain || saved.state === ReviewDeliveryStates.Canceled) return false;
13261
+ const review = saved.payload.reviews[0];
13262
+ const destination = resolveDestination(notification.config.url);
13263
+ if (destination.render && !googleBusinessReviewUrl(review.reviewUri) && !googleBusinessReviewUrl(review.location.mapsUri)) {
13264
+ deferReviewDelivery(db, saved, now());
13265
+ return false;
13266
+ }
13267
+ if (saved.state === ReviewDeliveryStates.Attempting) {
13268
+ if (!saved.attemptedAt || !Number.isFinite(Date.parse(saved.attemptedAt)) || now() - Date.parse(saved.attemptedAt) < 6e4)
13269
+ return false;
13270
+ const state2 = destination.signed ? ReviewDeliveryStates.Pending : ReviewDeliveryStates.Uncertain;
13271
+ const moved = db.update(reviewWebhookDeliveries).set({ state: state2 }).where(
13272
+ and18(
13273
+ eq20(reviewWebhookDeliveries.id, id),
13274
+ eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
13275
+ eq20(reviewWebhookDeliveries.attempts, saved.attempts),
13276
+ eq20(reviewWebhookDeliveries.attemptedAt, saved.attemptedAt)
13277
+ )
13278
+ ).returning({ id: reviewWebhookDeliveries.id }).get();
13279
+ if (moved && state2 === ReviewDeliveryStates.Uncertain) {
13280
+ auditUndelivered(db, saved, { state: state2, reason: "interrupted_attempt", attempts: saved.attempts });
13281
+ }
13282
+ saved = db.select().from(reviewWebhookDeliveries).where(eq20(reviewWebhookDeliveries.id, id)).get();
13283
+ if (!saved || saved.state !== ReviewDeliveryStates.Pending) return false;
13284
+ }
13285
+ if (saved.retryAt && Date.parse(saved.retryAt) > now()) return false;
13286
+ if (destination.render && options.chatSendsLeft) {
13287
+ const left = options.chatSendsLeft.get(targetDigest) ?? REVIEW_CHAT_SENDS_PER_PASS;
13288
+ if (left <= 0) return false;
13289
+ options.chatSendsLeft.set(targetDigest, left - 1);
13290
+ }
13291
+ if (destination.signed && !notification.webhookSecret) {
13292
+ deferReviewDelivery(db, saved, now());
13293
+ return false;
13294
+ }
13295
+ const target = await (options.resolve ?? resolveWebhookTarget)(
13296
+ notification.config.url,
13297
+ { allowLoopback: options.allowLoopback ?? false }
13298
+ );
13299
+ if (!target.ok) {
13300
+ deferReviewDelivery(db, saved, now());
13301
+ return false;
13302
+ }
13303
+ const latest = db.select().from(notifications).where(
13304
+ and18(
13305
+ eq20(notifications.id, notificationId),
13306
+ eq20(notifications.projectId, projectId)
13307
+ )
13308
+ ).get();
13309
+ const latestRefusal = reviewEventRefusal(db, projectId, saved.payload, latest, targetDigest, new Date(now()));
13310
+ if (latestRefusal) {
13311
+ cancelReviewDelivery(db, id, latestRefusal);
13312
+ return false;
13313
+ }
13314
+ const claimed = db.update(reviewWebhookDeliveries).set({
13315
+ state: ReviewDeliveryStates.Attempting,
13316
+ attempts: saved.attempts + 1,
13317
+ attemptedAt: new Date(now()).toISOString()
13318
+ }).where(
13319
+ and18(
13320
+ eq20(reviewWebhookDeliveries.id, id),
13321
+ eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
13322
+ eq20(reviewWebhookDeliveries.attempts, saved.attempts)
13323
+ )
13324
+ ).returning({ id: reviewWebhookDeliveries.id }).get();
13325
+ if (!claimed) return false;
13326
+ const rendered = destination.render?.(toAlertView(saved.payload));
13327
+ const body = destination.destination === "discord" && rendered && typeof rendered === "object" ? { ...rendered, allowed_mentions: { parse: [] } } : rendered ?? saved.payload;
13328
+ let result;
13329
+ try {
13330
+ result = await (options.deliver ?? deliverWebhook)(
13331
+ target.target,
13332
+ body,
13333
+ destination.signed ? notification.webhookSecret : null
13334
+ );
13335
+ } catch (err) {
13336
+ result = { status: 0, error: describeError(err), requestSent: true };
13337
+ }
13338
+ const attempts = saved.attempts + 1;
13339
+ const sent = result.status >= 200 && result.status < 300;
13340
+ const uncertain = !sent && result.status === 0 && result.requestSent !== false && !destination.signed;
13341
+ const refused = !sent && permanentlyRefused(result.status);
13342
+ const exhausted = !sent && !uncertain && !refused && attempts >= REVIEW_DELIVERY_MAX_ATTEMPTS;
13343
+ const state = sent ? ReviewDeliveryStates.Sent : uncertain ? ReviewDeliveryStates.Uncertain : refused || exhausted ? ReviewDeliveryStates.Failed : ReviewDeliveryStates.Pending;
13344
+ db.update(reviewWebhookDeliveries).set({
13345
+ state,
13346
+ deliveredAt: sent ? new Date(now()).toISOString() : null,
13347
+ retryAt: state === ReviewDeliveryStates.Pending ? new Date(now() + retryDelayMs(attempts, result.retryAfterSeconds)).toISOString() : null
13348
+ }).where(
13349
+ and18(
13350
+ eq20(reviewWebhookDeliveries.id, id),
13351
+ eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
13352
+ eq20(reviewWebhookDeliveries.attempts, attempts)
13353
+ )
13354
+ ).run();
13355
+ if (state === ReviewDeliveryStates.Uncertain || state === ReviewDeliveryStates.Failed) {
13356
+ const reason = uncertain ? "no_response" : refused ? "refused" : "retries_exhausted";
13357
+ auditUndelivered(db, saved, { state, reason, status: result.status, attempts });
13358
+ }
13359
+ if (sent) options.onDelivered?.();
13360
+ return sent;
13361
+ }
13362
+
13076
13363
  // src/provider-batch-poller.ts
13077
- import { and as and18, eq as eq20, inArray as inArray10, isNotNull as isNotNull3, isNull as isNull3, notExists as notExists2, sql as sql9 } from "drizzle-orm";
13078
- var log19 = createLogger("ProviderBatchPoller");
13364
+ import { and as and19, eq as eq21, inArray as inArray10, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql9 } from "drizzle-orm";
13365
+ var log20 = createLogger("ProviderBatchPoller");
13079
13366
  var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
13080
13367
  var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
13081
13368
  var PROVIDER_BATCH_CANCEL_GRACE_MS = 60 * 6e4;
@@ -13099,7 +13386,7 @@ var ProviderBatchPoller = class {
13099
13386
  try {
13100
13387
  if (await this.advance(row)) settledRuns.set(row.runId, row.projectId);
13101
13388
  } catch (err) {
13102
- log19.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
13389
+ log20.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
13103
13390
  this.reschedule(row.id, null);
13104
13391
  }
13105
13392
  }
@@ -13108,7 +13395,7 @@ var ProviderBatchPoller = class {
13108
13395
  try {
13109
13396
  this.deps.runner.finalizeBatchRun(runId, projectId);
13110
13397
  } catch (err) {
13111
- log19.warn("batch.finalize-failed", { runId, error: describeError(err) });
13398
+ log20.warn("batch.finalize-failed", { runId, error: describeError(err) });
13112
13399
  }
13113
13400
  }
13114
13401
  }
@@ -13117,7 +13404,7 @@ var ProviderBatchPoller = class {
13117
13404
  * outstanding (ingested or cancelled), so its run may now finalize.
13118
13405
  */
13119
13406
  async advance(row) {
13120
- const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq20(runs.id, row.runId)).get()?.status;
13407
+ const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq21(runs.id, row.runId)).get()?.status;
13121
13408
  if (runStatus !== RunStatuses.running) {
13122
13409
  await this.deps.runner.abandonProviderBatches([row.id], "Cancelled because its run is no longer running.");
13123
13410
  this.schedule.delete(row.id);
@@ -13134,15 +13421,15 @@ var ProviderBatchPoller = class {
13134
13421
  status = poll.status;
13135
13422
  if (poll.status === "ended") {
13136
13423
  const endedAt = poll.endedAt ?? new Date(this.now()).toISOString();
13137
- const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and18(eq20(providerBatches.id, row.id), eq20(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13424
+ const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and19(eq21(providerBatches.id, row.id), eq21(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13138
13425
  this.schedule.delete(row.id);
13139
13426
  return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
13140
13427
  }
13141
13428
  } catch (err) {
13142
- log19.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
13429
+ log20.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
13143
13430
  }
13144
13431
  } else {
13145
- log19.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
13432
+ log20.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
13146
13433
  }
13147
13434
  this.reschedule(row.id, status);
13148
13435
  return this.enforceDeadline(row, registered);
@@ -13158,18 +13445,18 @@ var ProviderBatchPoller = class {
13158
13445
  const at = new Date(now).toISOString();
13159
13446
  if (row.cancelRequestedAt === null) {
13160
13447
  if (now < Date.parse(row.deadlineAt)) return false;
13161
- const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and18(
13162
- eq20(providerBatches.id, row.id),
13163
- eq20(providerBatches.status, ProviderBatchStatuses.submitted),
13164
- isNull3(providerBatches.cancelRequestedAt)
13448
+ const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and19(
13449
+ eq21(providerBatches.id, row.id),
13450
+ eq21(providerBatches.status, ProviderBatchStatuses.submitted),
13451
+ isNull4(providerBatches.cancelRequestedAt)
13165
13452
  )).run().changes === 1;
13166
13453
  if (!claimed) return false;
13167
- log19.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
13454
+ log20.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
13168
13455
  if (registered?.adapter.batch && row.providerBatchId) {
13169
13456
  try {
13170
13457
  await registered.adapter.batch.cancel(row.providerBatchId, registered.config);
13171
13458
  } catch (err) {
13172
- log19.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
13459
+ log20.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
13173
13460
  }
13174
13461
  }
13175
13462
  return false;
@@ -13179,9 +13466,9 @@ var ProviderBatchPoller = class {
13179
13466
  status: ProviderBatchStatuses.cancelled,
13180
13467
  error: `The provider batch did not end within an hour of being cancelled at its deadline; its ${row.requestCount} answer(s) were not recorded.`,
13181
13468
  updatedAt: at
13182
- }).where(and18(eq20(providerBatches.id, row.id), eq20(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13469
+ }).where(and19(eq21(providerBatches.id, row.id), eq21(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13183
13470
  this.schedule.delete(row.id);
13184
- if (gaveUp) log19.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
13471
+ if (gaveUp) log20.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
13185
13472
  return gaveUp;
13186
13473
  }
13187
13474
  async ingest(row) {
@@ -13190,7 +13477,7 @@ var ProviderBatchPoller = class {
13190
13477
  return result.kind !== "skipped";
13191
13478
  } catch (err) {
13192
13479
  const error = describeError(err);
13193
- log19.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
13480
+ log20.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
13194
13481
  const now = this.now();
13195
13482
  const unreadable = row.resultsExpireAt !== null && now >= Date.parse(row.resultsExpireAt);
13196
13483
  if (unreadable || now >= Date.parse(row.deadlineAt) + PROVIDER_BATCH_CANCEL_GRACE_MS) {
@@ -13219,10 +13506,10 @@ var ProviderBatchPoller = class {
13219
13506
  /** Runs the sweep handed off whose batches have all settled. */
13220
13507
  finalizableRuns() {
13221
13508
  const holding = [ProviderBatchStatuses.submitting, ...OUTSTANDING_PROVIDER_BATCH_STATUSES];
13222
- return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and18(
13223
- eq20(runs.status, RunStatuses.running),
13509
+ return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and19(
13510
+ eq21(runs.status, RunStatuses.running),
13224
13511
  isNotNull3(runs.pendingProviderErrors),
13225
- notExists2(this.deps.db.select({ one: sql9`1` }).from(providerBatches).where(and18(eq20(providerBatches.runId, runs.id), inArray10(providerBatches.status, holding))))
13512
+ notExists2(this.deps.db.select({ one: sql9`1` }).from(providerBatches).where(and19(eq21(providerBatches.runId, runs.id), inArray10(providerBatches.status, holding))))
13226
13513
  )).all();
13227
13514
  }
13228
13515
  };
@@ -13232,7 +13519,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
13232
13519
  const timer = setInterval(() => {
13233
13520
  if (running) return;
13234
13521
  running = true;
13235
- void poller.tick().catch((err) => log19.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
13522
+ void poller.tick().catch((err) => log20.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
13236
13523
  running = false;
13237
13524
  });
13238
13525
  }, intervalMs);
@@ -13241,7 +13528,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
13241
13528
  }
13242
13529
 
13243
13530
  // src/data-refresh.ts
13244
- var log20 = createLogger("DataRefresh");
13531
+ var log21 = createLogger("DataRefresh");
13245
13532
  function gaRefreshDays(now = /* @__PURE__ */ new Date()) {
13246
13533
  const [reportMonth] = reportMonthsForDoctor(void 0, now);
13247
13534
  const reach = inclusiveDayCount(`${reportMonth}-01`, now.toISOString().slice(0, 10)) ?? 0;
@@ -13282,15 +13569,15 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
13282
13569
  if (result.status === "rejected") {
13283
13570
  const reason = result.reason;
13284
13571
  const message = describeError(reason);
13285
- log20.warn("integration.refresh-failed", { projectName, integration, error: message });
13572
+ log21.warn("integration.refresh-failed", { projectName, integration, error: message });
13286
13573
  return;
13287
13574
  }
13288
13575
  switch (completion) {
13289
13576
  case "synchronous":
13290
- log20.info("integration.refreshed", { projectName, integration });
13577
+ log21.info("integration.refreshed", { projectName, integration });
13291
13578
  return;
13292
13579
  case "queued":
13293
- log20.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
13580
+ log21.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
13294
13581
  return;
13295
13582
  default: {
13296
13583
  const _exhaustive = completion;
@@ -13301,9 +13588,9 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
13301
13588
  }
13302
13589
 
13303
13590
  // src/notifier.ts
13304
- import { eq as eq21, desc as desc8, and as and19, inArray as inArray11, or } from "drizzle-orm";
13591
+ import { eq as eq22, desc as desc8, and as and20, inArray as inArray11, or as or2, isNull as isNull5 } from "drizzle-orm";
13305
13592
  import crypto21 from "crypto";
13306
- var log21 = createLogger("Notifier");
13593
+ var log22 = createLogger("Notifier");
13307
13594
  var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
13308
13595
  function trackWebhookDelivery(input) {
13309
13596
  const sample = sampleDelivery(input.failure ? "failed" : "succeeded");
@@ -13421,26 +13708,26 @@ var Notifier = class {
13421
13708
  }
13422
13709
  /** Called after a run completes (success, partial, or failed). */
13423
13710
  async onRunCompleted(runId, projectId, opts) {
13424
- log21.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
13425
- const notifs = this.db.select().from(notifications).where(eq21(notifications.projectId, projectId)).all().filter((n) => n.enabled);
13711
+ log22.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
13712
+ const notifs = this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled);
13426
13713
  if (notifs.length === 0) {
13427
- log21.info("notifications.none-enabled", { projectId });
13714
+ log22.info("notifications.none-enabled", { projectId });
13428
13715
  return;
13429
13716
  }
13430
- log21.info("notifications.found", { projectId, count: notifs.length });
13431
- const run = this.db.select().from(runs).where(eq21(runs.id, runId)).get();
13717
+ log22.info("notifications.found", { projectId, count: notifs.length });
13718
+ const run = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
13432
13719
  if (!run) {
13433
- log21.error("run.not-found", { runId, msg: "skipping notification dispatch" });
13720
+ log22.error("run.not-found", { runId, msg: "skipping notification dispatch" });
13434
13721
  return;
13435
13722
  }
13436
- const project = this.db.select().from(projects).where(eq21(projects.id, projectId)).get();
13723
+ const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
13437
13724
  if (!project) {
13438
- log21.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
13725
+ log22.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
13439
13726
  return;
13440
13727
  }
13441
13728
  const transitions = this.computeTransitions(runId, projectId);
13442
13729
  const events = [];
13443
- log21.info("run.status", { runId: run.id, status: run.status, projectId });
13730
+ log22.info("run.status", { runId: run.id, status: run.status, projectId });
13444
13731
  if ((run.status === "completed" || run.status === "partial") && opts?.origin !== "fill") {
13445
13732
  events.push("run.completed");
13446
13733
  }
@@ -13456,7 +13743,7 @@ var Notifier = class {
13456
13743
  if (!config.url) continue;
13457
13744
  const subscribedEvents = config.events;
13458
13745
  const matchingEvents = events.filter((e) => subscribedEvents.includes(e));
13459
- log21.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
13746
+ log22.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
13460
13747
  if (matchingEvents.length === 0) continue;
13461
13748
  for (const event of matchingEvents) {
13462
13749
  const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : transitions;
@@ -13512,9 +13799,9 @@ var Notifier = class {
13512
13799
  * than inferred from the absence of a webhook.
13513
13800
  */
13514
13801
  async onHealthChecked(projectId, report) {
13515
- const project = this.db.select().from(projects).where(eq21(projects.id, projectId)).get();
13802
+ const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
13516
13803
  if (!project) {
13517
- log21.error("project.not-found", { projectId, msg: "skipping health notification" });
13804
+ log22.error("project.not-found", { projectId, msg: "skipping health notification" });
13518
13805
  return null;
13519
13806
  }
13520
13807
  const rank = healthRank;
@@ -13545,7 +13832,7 @@ var Notifier = class {
13545
13832
  const status = noSignal ? "warn" : worst ? worst.status : "ok";
13546
13833
  const code = noSignal ? HEALTH_NO_SIGNAL_CODE : worst?.code ?? "health.ok";
13547
13834
  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.`;
13548
- const previous = this.db.select().from(doctorHealthState).where(eq21(doctorHealthState.projectId, projectId)).get();
13835
+ const previous = this.db.select().from(doctorHealthState).where(eq22(doctorHealthState.projectId, projectId)).get();
13549
13836
  const previousStatus = previous?.status ?? null;
13550
13837
  const failingSignature = failing.map((c) => `${c.status}:${c.code}`).join(",");
13551
13838
  const failingNow = failing.map((c) => ({ id: c.id, code: c.code, rank: rank(c.status) }));
@@ -13615,7 +13902,7 @@ var Notifier = class {
13615
13902
  const urgentById = new Map(urgentItems.map((item) => [item.id, item]));
13616
13903
  const generalEvent = event;
13617
13904
  const urgentRecord = previous?.urgentNotified ?? null;
13618
- const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq21(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
13905
+ const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
13619
13906
  const listedEvents = (notif) => notif.config.events;
13620
13907
  const hasUrl = (notif) => Boolean(notif.config.url);
13621
13908
  const urgentSubscribers = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -13663,7 +13950,7 @@ var Notifier = class {
13663
13950
  if (previous === void 0) {
13664
13951
  this.db.insert(doctorHealthState).values({ ...observation, notifiedAt: null }).run();
13665
13952
  } else {
13666
- this.db.update(doctorHealthState).set(observation).where(eq21(doctorHealthState.projectId, projectId)).run();
13953
+ this.db.update(doctorHealthState).set(observation).where(eq22(doctorHealthState.projectId, projectId)).run();
13667
13954
  }
13668
13955
  for (const group of urgentGroups) {
13669
13956
  const { urgentEvent, urgentTold, urgentNew, urgentCleared, urgentNotifs, urgentSettled } = group;
@@ -13707,10 +13994,10 @@ var Notifier = class {
13707
13994
  }
13708
13995
  if (accepted > 0) {
13709
13996
  recordUrgentReceipts(urgentReceipts, group.subscribers, formatUrgentBreaches(urgentSettled) || null);
13710
- this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq21(doctorHealthState.projectId, projectId)).run();
13997
+ this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq22(doctorHealthState.projectId, projectId)).run();
13711
13998
  }
13712
13999
  if (urgentNotifs.length > 0) {
13713
- log21.info("health.urgent-notified", {
14000
+ log22.info("health.urgent-notified", {
13714
14001
  projectId,
13715
14002
  event: urgentEvent,
13716
14003
  codes: urgentEvent === "health.urgent" ? breachCodes(urgentNew) : breachCodes(urgentCleared),
@@ -13721,9 +14008,9 @@ var Notifier = class {
13721
14008
  }
13722
14009
  if (!event) {
13723
14010
  if (clearedThisPass.length > 0 || easedThisPass.length > 0) {
13724
- log21.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
14011
+ log22.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
13725
14012
  } else {
13726
- log21.info("health.unchanged", { projectId, status, code });
14013
+ log22.info("health.unchanged", { projectId, status, code });
13727
14014
  }
13728
14015
  return null;
13729
14016
  }
@@ -13751,9 +14038,9 @@ var Notifier = class {
13751
14038
  if (await this.sendWebhook(config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) delivered += 1;
13752
14039
  }
13753
14040
  if (delivered > 0) {
13754
- this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq21(doctorHealthState.projectId, projectId)).run();
14041
+ this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq22(doctorHealthState.projectId, projectId)).run();
13755
14042
  }
13756
- log21.info("health.notified", {
14043
+ log22.info("health.notified", {
13757
14044
  projectId,
13758
14045
  event,
13759
14046
  status,
@@ -13781,12 +14068,12 @@ var Notifier = class {
13781
14068
  async onSiteLivenessChecked(projectId, result) {
13782
14069
  const { check, checkedAt } = result;
13783
14070
  if (check.status !== "ok" && check.status !== "fail") return null;
13784
- const project = this.db.select().from(projects).where(eq21(projects.id, projectId)).get();
14071
+ const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
13785
14072
  if (!project) {
13786
- log21.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
14073
+ log22.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
13787
14074
  return null;
13788
14075
  }
13789
- const previous = this.db.select().from(siteLivenessState).where(eq21(siteLivenessState.projectId, projectId)).get();
14076
+ const previous = this.db.select().from(siteLivenessState).where(eq22(siteLivenessState.projectId, projectId)).get();
13790
14077
  const sincePrevious = previous ? Date.parse(checkedAt) - Date.parse(previous.checkedAt) : Number.NaN;
13791
14078
  const countsAsRepeat = Number.isFinite(sincePrevious) && sincePrevious >= SITE_LIVENESS_MIN_PASS_GAP_MS && sincePrevious <= SITE_LIVENESS_MAX_PASS_GAP_MS;
13792
14079
  const failures = check.status === "fail" ? countsAsRepeat ? (previous?.consecutiveFailures ?? 0) + 1 : 1 : 0;
@@ -13796,7 +14083,7 @@ var Notifier = class {
13796
14083
  if (check.status === "ok" && outagePaged) event = "health.recovered";
13797
14084
  const confirmed = check.status === "fail" && failures >= SITE_LIVENESS_FAILURES_TO_PAGE;
13798
14085
  const urgentRecord = previous?.urgentNotifiedAt ?? null;
13799
- const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq21(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
14086
+ const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
13800
14087
  const listedEvents = (notif) => notif.config.events;
13801
14088
  const hasUrl = (notif) => Boolean(notif.config.url);
13802
14089
  const scoped = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -13829,7 +14116,7 @@ var Notifier = class {
13829
14116
  if (previous === void 0) {
13830
14117
  this.db.insert(siteLivenessState).values(observation).run();
13831
14118
  } else {
13832
- this.db.update(siteLivenessState).set(observation).where(eq21(siteLivenessState.projectId, projectId)).run();
14119
+ this.db.update(siteLivenessState).set(observation).where(eq22(siteLivenessState.projectId, projectId)).run();
13833
14120
  }
13834
14121
  if (!event && urgentGroups.every((group) => group.urgentEvent === null)) return null;
13835
14122
  const payloadFor = (name) => {
@@ -13865,9 +14152,9 @@ var Notifier = class {
13865
14152
  }
13866
14153
  }
13867
14154
  if (event === "health.degraded" && delivered > 0) {
13868
- this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq21(siteLivenessState.projectId, projectId)).run();
14155
+ this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq22(siteLivenessState.projectId, projectId)).run();
13869
14156
  }
13870
- log21.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
14157
+ log22.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
13871
14158
  }
13872
14159
  for (const group of urgentGroups) {
13873
14160
  const { urgentEvent, urgentNotifs, generalIds } = group;
@@ -13879,10 +14166,10 @@ var Notifier = class {
13879
14166
  }
13880
14167
  if (accepted > 0) {
13881
14168
  recordUrgentReceipts(urgentReceipts, group.subscribers, group.settled);
13882
- this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq21(siteLivenessState.projectId, projectId)).run();
14169
+ this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq22(siteLivenessState.projectId, projectId)).run();
13883
14170
  }
13884
14171
  if (urgentNotifs.length > 0 || generalIds.size > 0) {
13885
- log21.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
14172
+ log22.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
13886
14173
  }
13887
14174
  }
13888
14175
  return event;
@@ -13905,7 +14192,7 @@ var Notifier = class {
13905
14192
  */
13906
14193
  isNewInsightNews(projectId, insight) {
13907
14194
  const key = insightNotifyKey(projectId, insight);
13908
- const previous = this.db.select().from(insightNotifyState).where(eq21(insightNotifyState.key, key)).get();
14195
+ const previous = this.db.select().from(insightNotifyState).where(eq22(insightNotifyState.key, key)).get();
13909
14196
  if (!previous) return true;
13910
14197
  if (severityRank(insight.severity) > severityRank(previous.severity)) return true;
13911
14198
  const magnitude = insightMagnitude(insight);
@@ -13927,9 +14214,9 @@ var Notifier = class {
13927
14214
  magnitude: insightMagnitude(insight),
13928
14215
  notifiedAt: (/* @__PURE__ */ new Date()).toISOString()
13929
14216
  };
13930
- const existing = this.db.select().from(insightNotifyState).where(eq21(insightNotifyState.key, key)).get();
14217
+ const existing = this.db.select().from(insightNotifyState).where(eq22(insightNotifyState.key, key)).get();
13931
14218
  if (existing) {
13932
- this.db.update(insightNotifyState).set(row).where(eq21(insightNotifyState.key, key)).run();
14219
+ this.db.update(insightNotifyState).set(row).where(eq22(insightNotifyState.key, key)).run();
13933
14220
  } else {
13934
14221
  this.db.insert(insightNotifyState).values(row).run();
13935
14222
  }
@@ -13943,11 +14230,11 @@ var Notifier = class {
13943
14230
  if (criticalInsights.length > 0) insightEvents.push("insight.critical");
13944
14231
  if (highInsights.length > 0) insightEvents.push("insight.high");
13945
14232
  if (insightEvents.length === 0) return;
13946
- const notifs = this.db.select().from(notifications).where(eq21(notifications.projectId, projectId)).all().filter((n) => n.enabled);
14233
+ const notifs = this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled);
13947
14234
  if (notifs.length === 0) return;
13948
- const run = this.db.select().from(runs).where(eq21(runs.id, runId)).get();
14235
+ const run = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
13949
14236
  if (!run) return;
13950
- const project = this.db.select().from(projects).where(eq21(projects.id, projectId)).get();
14237
+ const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
13951
14238
  if (!project) return;
13952
14239
  for (const notif of notifs) {
13953
14240
  const config = notif.config;
@@ -14008,12 +14295,31 @@ var Notifier = class {
14008
14295
  this.reviewDispatchInFlight.delete(projectId);
14009
14296
  }
14010
14297
  }
14298
+ /**
14299
+ * Send the review deliveries that are due, for every project that has some.
14300
+ * The engine runs this on a timer, so a failed send waits for its retry time
14301
+ * rather than the next GBP sync. A project mid-dispatch is skipped: that
14302
+ * dispatch drains its own deliveries.
14303
+ */
14304
+ async drainDueReviewDeliveries() {
14305
+ let delivered = 0;
14306
+ for (const projectId of dueReviewDeliveryProjects(this.db, Date.now())) {
14307
+ if (this.reviewDispatchInFlight.has(projectId)) continue;
14308
+ this.reviewDispatchInFlight.add(projectId);
14309
+ try {
14310
+ delivered += await drainReviewDeliveries({ db: this.db, projectId, allowLoopback: this.allowLoopbackWebhooks });
14311
+ } finally {
14312
+ this.reviewDispatchInFlight.delete(projectId);
14313
+ }
14314
+ }
14315
+ return delivered;
14316
+ }
14011
14317
  async dispatchQueuedReviewAlerts(projectId) {
14012
- const pendingReviews = this.db.select().from(gbpReviews).where(and19(eq21(gbpReviews.projectId, projectId), eq21(gbpReviews.alertState, "pending"))).all();
14013
- const pendingRatings = this.db.select().from(gbpReviewRatings).where(and19(eq21(gbpReviewRatings.projectId, projectId), eq21(gbpReviewRatings.alertState, "pending"))).all();
14014
- if (pendingReviews.length === 0 && pendingRatings.length === 0) return { reviews: 0, ratingDrops: 0, delivered: 0 };
14015
- const project = this.db.select().from(projects).where(eq21(projects.id, projectId)).get();
14318
+ const pendingReviews = this.db.select().from(gbpReviews).where(and20(eq22(gbpReviews.projectId, projectId), eq22(gbpReviews.alertState, "pending"))).all();
14319
+ const pendingRatings = this.db.select().from(gbpReviewRatings).where(and20(eq22(gbpReviewRatings.projectId, projectId), eq22(gbpReviewRatings.alertState, "pending"))).all();
14320
+ const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
14016
14321
  if (!project) return { reviews: 0, ratingDrops: 0, delivered: 0 };
14322
+ const chatSendsLeft = /* @__PURE__ */ new Map();
14017
14323
  const now = /* @__PURE__ */ new Date();
14018
14324
  const nowIso = now.toISOString();
14019
14325
  const negativeMaxStars = resolveNegativeReviewMaxStars(readNegativeReviewMaxStars(this.db, projectId));
@@ -14023,10 +14329,10 @@ var Notifier = class {
14023
14329
  displayName: gbpLocations.displayName,
14024
14330
  mapsUri: gbpLocations.mapsUri,
14025
14331
  reviewsAccess: gbpLocations.reviewsAccess
14026
- }).from(gbpLocations).where(eq21(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
14332
+ }).from(gbpLocations).where(eq22(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
14027
14333
  );
14028
14334
  const v4HasWorked = new Set(
14029
- this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and19(eq21(gbpReviewRatings.projectId, projectId), eq21(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
14335
+ this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and20(eq22(gbpReviewRatings.projectId, projectId), eq22(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
14030
14336
  );
14031
14337
  const coveredByBusinessProfile = (locationName) => businessProfileReviewsCover(locations.get(locationName)?.reviewsAccess ?? null, v4HasWorked.has(locationName));
14032
14338
  const locationRef = (locationName) => {
@@ -14055,7 +14361,7 @@ var Notifier = class {
14055
14361
  else if (row.rating === null || row.previousRating === null) setRatingState([row.id], "none");
14056
14362
  else ratingsToSend.push(row);
14057
14363
  }
14058
- const enabled = this.db.select().from(notifications).where(eq21(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
14364
+ const enabled = this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
14059
14365
  const subscribedTo = (event) => enabled.filter((n) => (n.config.events ?? []).includes(event));
14060
14366
  const projectRef = { name: project.name, canonicalDomain: project.canonicalDomain };
14061
14367
  const dashboardUrl = `${this.serverUrl}/projects/${project.name}`;
@@ -14073,29 +14379,55 @@ var Notifier = class {
14073
14379
  setReviewState(ids, "skipped");
14074
14380
  } else {
14075
14381
  reviewsToSend.sort((a, b) => a.updateTime.localeCompare(b.updateTime));
14076
- const payload = {
14077
- source: "canonry",
14078
- event: "review.negative",
14079
- project: projectRef,
14080
- reviews: reviewsToSend.map((r) => ({
14081
- location: locationRef(r.locationName),
14082
- origin: r.origin,
14083
- reviewName: r.reviewName,
14084
- starRating: r.starRating,
14085
- comment: r.comment,
14086
- reviewerName: r.reviewerName,
14087
- createTime: r.createTime,
14088
- updateTime: r.updateTime,
14089
- replied: r.origin === "places" ? null : r.replyComment !== null,
14090
- reviewUri: r.reviewUri
14091
- })),
14092
- dashboardUrl
14093
- };
14094
- const accepted = await sendAll("review.negative", payload);
14095
- if (accepted > 0) setReviewState(ids, "sent");
14096
- delivered += accepted;
14382
+ for (const review of reviewsToSend) {
14383
+ const payload = {
14384
+ source: "canonry",
14385
+ event: "review.negative",
14386
+ eventId: reviewEventId(projectId, review),
14387
+ project: projectRef,
14388
+ reviews: [{
14389
+ location: locationRef(review.locationName),
14390
+ origin: review.origin,
14391
+ reviewName: review.reviewName,
14392
+ starRating: review.starRating,
14393
+ comment: review.comment,
14394
+ reviewerName: review.reviewerName,
14395
+ createTime: review.createTime,
14396
+ updateTime: review.updateTime,
14397
+ replied: review.origin === "places" ? null : review.replyComment !== null,
14398
+ reviewUri: review.reviewUri
14399
+ }],
14400
+ dashboardUrl
14401
+ };
14402
+ let all = true;
14403
+ for (const notification of subscribedTo("review.negative")) {
14404
+ const sent = await deliverReviewEvent({
14405
+ db: this.db,
14406
+ projectId,
14407
+ notificationId: notification.id,
14408
+ payload,
14409
+ allowLoopback: this.allowLoopbackWebhooks,
14410
+ chatSendsLeft,
14411
+ onDelivered: () => {
14412
+ delivered += 1;
14413
+ }
14414
+ });
14415
+ if (!sent) all = false;
14416
+ }
14417
+ if (all) {
14418
+ this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and20(
14419
+ eq22(gbpReviews.id, review.id),
14420
+ eq22(gbpReviews.alertState, "pending"),
14421
+ eq22(gbpReviews.updateTime, review.updateTime),
14422
+ review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq22(gbpReviews.alertStateAt, review.alertStateAt),
14423
+ review.comment === null ? isNull5(gbpReviews.comment) : eq22(gbpReviews.comment, review.comment),
14424
+ review.starRating === null ? isNull5(gbpReviews.starRating) : eq22(gbpReviews.starRating, review.starRating)
14425
+ )).run();
14426
+ }
14427
+ }
14097
14428
  }
14098
14429
  }
14430
+ delivered += await drainReviewDeliveries({ db: this.db, projectId, allowLoopback: this.allowLoopbackWebhooks, chatSendsLeft });
14099
14431
  if (ratingsToSend.length > 0) {
14100
14432
  const ids = ratingsToSend.map((r) => r.id);
14101
14433
  if (subscribedTo("review.rating-dropped").length === 0) {
@@ -14121,7 +14453,7 @@ var Notifier = class {
14121
14453
  delivered += accepted;
14122
14454
  }
14123
14455
  }
14124
- log21.info("reviews.dispatched", {
14456
+ log22.info("reviews.dispatched", {
14125
14457
  projectId,
14126
14458
  reviews: reviewsToSend.length,
14127
14459
  ratingDrops: ratingsToSend.length,
@@ -14130,21 +14462,21 @@ var Notifier = class {
14130
14462
  return { reviews: reviewsToSend.length, ratingDrops: ratingsToSend.length, delivered };
14131
14463
  }
14132
14464
  computeTransitions(runId, projectId) {
14133
- const thisRun = this.db.select().from(runs).where(eq21(runs.id, runId)).get();
14465
+ const thisRun = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
14134
14466
  if (!thisRun) return [];
14135
14467
  const completeness = measurementRunCompleteness(this.db, runId);
14136
14468
  if (completeness.planned && !completeness.complete) {
14137
- log21.info("transitions.skipped-incomplete", {
14469
+ log22.info("transitions.skipped-incomplete", {
14138
14470
  runId,
14139
14471
  executed: completeness.executed,
14140
14472
  expected: completeness.expected
14141
14473
  });
14142
14474
  return [];
14143
14475
  }
14144
- const groupSiblings = this.db.select().from(runs).where(and19(
14145
- eq21(runs.projectId, projectId),
14146
- eq21(runs.kind, thisRun.kind),
14147
- eq21(runs.createdAt, thisRun.createdAt),
14476
+ const groupSiblings = this.db.select().from(runs).where(and20(
14477
+ eq22(runs.projectId, projectId),
14478
+ eq22(runs.kind, thisRun.kind),
14479
+ eq22(runs.createdAt, thisRun.createdAt),
14148
14480
  notProbeRun()
14149
14481
  )).all();
14150
14482
  const stillPending = groupSiblings.some((r) => r.status === "queued" || r.status === "running");
@@ -14161,17 +14493,17 @@ var Notifier = class {
14161
14493
  return candidate.id > best.id ? candidate : best;
14162
14494
  });
14163
14495
  if (winner.id !== runId) return [];
14164
- const projectLocations = this.db.select({ locations: projects.locations }).from(projects).where(eq21(projects.id, projectId)).get();
14496
+ const projectLocations = this.db.select({ locations: projects.locations }).from(projects).where(eq22(projects.id, projectId)).get();
14165
14497
  const locationCount = Math.max(
14166
14498
  1,
14167
14499
  (projectLocations?.locations ?? []).length
14168
14500
  );
14169
14501
  const RECENT_FETCH_LIMIT = Math.max(8, locationCount * 4);
14170
14502
  const recentRuns = this.db.select().from(runs).where(
14171
- and19(
14172
- eq21(runs.projectId, projectId),
14173
- eq21(runs.kind, thisRun.kind),
14174
- or(eq21(runs.status, "completed"), eq21(runs.status, "partial")),
14503
+ and20(
14504
+ eq22(runs.projectId, projectId),
14505
+ eq22(runs.kind, thisRun.kind),
14506
+ or2(eq22(runs.status, "completed"), eq22(runs.status, "partial")),
14175
14507
  notProbeRun()
14176
14508
  )
14177
14509
  ).orderBy(desc8(runs.createdAt), desc8(runs.id)).limit(RECENT_FETCH_LIMIT).all();
@@ -14189,7 +14521,7 @@ var Notifier = class {
14189
14521
  provider: querySnapshots.provider,
14190
14522
  location: querySnapshots.location,
14191
14523
  citationState: querySnapshots.citationState
14192
- }).from(querySnapshots).leftJoin(queries, eq21(querySnapshots.queryId, queries.id)).where(inArray11(querySnapshots.runId, currentRunIds)).all();
14524
+ }).from(querySnapshots).leftJoin(queries, eq22(querySnapshots.queryId, queries.id)).where(inArray11(querySnapshots.runId, currentRunIds)).all();
14193
14525
  const previousSnapshots = this.db.select({
14194
14526
  queryId: querySnapshots.queryId,
14195
14527
  provider: querySnapshots.provider,
@@ -14227,7 +14559,7 @@ var Notifier = class {
14227
14559
  const targetLabel = redactNotificationUrl(url).urlDisplay;
14228
14560
  const targetCheck = await resolveWebhookTarget(url, { allowLoopback: this.allowLoopbackWebhooks });
14229
14561
  if (!targetCheck.ok) {
14230
- log21.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
14562
+ log22.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
14231
14563
  this.logDelivery(projectId, notificationId, payload.event, "failed", `SSRF: ${targetCheck.message}`);
14232
14564
  const reasonCode = webhookTargetRefusalReason(targetCheck);
14233
14565
  trackWebhookDelivery({
@@ -14240,7 +14572,7 @@ var Notifier = class {
14240
14572
  });
14241
14573
  return false;
14242
14574
  }
14243
- log21.info("webhook.send", { event: payload.event, url: targetLabel });
14575
+ log22.info("webhook.send", { event: payload.event, url: targetLabel });
14244
14576
  const maxRetries = 3;
14245
14577
  const delays = [1e3, 4e3, 16e3];
14246
14578
  let lastStatusClass = "network";
@@ -14249,13 +14581,13 @@ var Notifier = class {
14249
14581
  try {
14250
14582
  const response = await deliverWebhook(targetCheck.target, body, signingSecret);
14251
14583
  if (response.status >= 200 && response.status < 300) {
14252
- log21.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
14584
+ log22.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
14253
14585
  this.logDelivery(projectId, notificationId, payload.event, "sent", null);
14254
14586
  trackWebhookDelivery({ url, event: payload.event, attempts: attempt + 1, durationBucket: elapsed(), statusClass: "2xx" });
14255
14587
  return true;
14256
14588
  }
14257
14589
  const errorDetail = response.error ?? `HTTP ${response.status}`;
14258
- log21.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
14590
+ log22.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
14259
14591
  lastStatusClass = response.status === 0 && response.timedOut ? "timeout" : statusClassOf(response.status);
14260
14592
  lastFailure = { reasonCode: webhookResponseReason(response) ?? "UNKNOWN" };
14261
14593
  if (attempt === maxRetries - 1) {
@@ -14267,7 +14599,7 @@ var Notifier = class {
14267
14599
  lastFailure = outcomeFailure(err);
14268
14600
  if (attempt === maxRetries - 1) {
14269
14601
  this.logDelivery(projectId, notificationId, payload.event, "failed", errorDetail);
14270
- log21.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
14602
+ log22.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
14271
14603
  }
14272
14604
  }
14273
14605
  if (attempt < maxRetries - 1) {
@@ -14299,8 +14631,8 @@ var Notifier = class {
14299
14631
  };
14300
14632
 
14301
14633
  // src/run-coordinator.ts
14302
- import { eq as eq22 } from "drizzle-orm";
14303
- var log22 = createLogger("RunCoordinator");
14634
+ import { eq as eq23 } from "drizzle-orm";
14635
+ var log23 = createLogger("RunCoordinator");
14304
14636
  function reportInsightsGenerated(runTrigger, outcome) {
14305
14637
  trackFeatureCompleted({
14306
14638
  feature: "insights",
@@ -14333,22 +14665,22 @@ var RunCoordinator = class {
14333
14665
  */
14334
14666
  onAnswersRecorded;
14335
14667
  async onRunCompleted(runId, projectId, opts) {
14336
- const runRow = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
14668
+ const runRow = this.db.select().from(runs).where(eq23(runs.id, runId)).get();
14337
14669
  const kind = runRow?.kind ?? RunKinds["answer-visibility"];
14338
14670
  if (runRow?.trigger === RunTriggers.probe) {
14339
- log22.info("probe.skip-side-effects", { runId, projectId, kind });
14671
+ log23.info("probe.skip-side-effects", { runId, projectId, kind });
14340
14672
  return;
14341
14673
  }
14342
14674
  if (kind === RunKinds["answer-visibility"] && (runRow?.status === RunStatuses.completed || runRow?.status === RunStatuses.partial) && this.onAnswersRecorded) {
14343
14675
  try {
14344
14676
  await this.onAnswersRecorded(runId, projectId);
14345
14677
  } catch (err) {
14346
- log22.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
14678
+ log23.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
14347
14679
  }
14348
14680
  }
14349
14681
  const completeness = measurementRunCompleteness(this.db, runId);
14350
14682
  if (completeness.planned && !completeness.complete) {
14351
- log22.info("measurement.incomplete-skip-derived", {
14683
+ log23.info("measurement.incomplete-skip-derived", {
14352
14684
  runId,
14353
14685
  projectId,
14354
14686
  executed: completeness.executed,
@@ -14357,7 +14689,7 @@ var RunCoordinator = class {
14357
14689
  try {
14358
14690
  await this.notifier.onRunCompleted(runId, projectId);
14359
14691
  } catch (err) {
14360
- log22.error("notifier.failed", { runId, error: describeError(err) });
14692
+ log23.error("notifier.failed", { runId, error: describeError(err) });
14361
14693
  }
14362
14694
  return;
14363
14695
  }
@@ -14365,7 +14697,7 @@ var RunCoordinator = class {
14365
14697
  try {
14366
14698
  await this.onSentimentCompleted(runId, projectId);
14367
14699
  } catch {
14368
- log22.error("sentiment.wakeup-failed", { runId, projectId });
14700
+ log23.error("sentiment.wakeup-failed", { runId, projectId });
14369
14701
  }
14370
14702
  }
14371
14703
  let insightCount = 0;
@@ -14385,12 +14717,12 @@ var RunCoordinator = class {
14385
14717
  try {
14386
14718
  await this.onInsightsGenerated(runId, projectId, result);
14387
14719
  } catch (err) {
14388
- log22.error("insight-webhook.failed", { runId, error: describeError(err) });
14720
+ log23.error("insight-webhook.failed", { runId, error: describeError(err) });
14389
14721
  }
14390
14722
  }
14391
14723
  }
14392
14724
  } catch (err) {
14393
- log22.error("intelligence.failed", { runId, error: describeError(err) });
14725
+ log23.error("intelligence.failed", { runId, error: describeError(err) });
14394
14726
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
14395
14727
  }
14396
14728
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
@@ -14408,24 +14740,24 @@ var RunCoordinator = class {
14408
14740
  try {
14409
14741
  await this.onInsightsGenerated(runId, projectId, analysisResultFromInsights(gbpInsights));
14410
14742
  } catch (err) {
14411
- log22.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
14743
+ log23.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
14412
14744
  }
14413
14745
  }
14414
14746
  } catch (err) {
14415
- log22.error("gbp-intelligence.failed", { runId, error: describeError(err) });
14747
+ log23.error("gbp-intelligence.failed", { runId, error: describeError(err) });
14416
14748
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
14417
14749
  }
14418
14750
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
14419
14751
  try {
14420
14752
  await this.notifier.dispatchReviewAlerts(projectId);
14421
14753
  } catch (err) {
14422
- log22.error("review-webhook.failed", { runId, error: describeError(err) });
14754
+ log23.error("review-webhook.failed", { runId, error: describeError(err) });
14423
14755
  }
14424
14756
  }
14425
14757
  try {
14426
14758
  await (opts ? this.notifier.onRunCompleted(runId, projectId, opts) : this.notifier.onRunCompleted(runId, projectId));
14427
14759
  } catch (err) {
14428
- log22.error("notifier.failed", { runId, error: describeError(err) });
14760
+ log23.error("notifier.failed", { runId, error: describeError(err) });
14429
14761
  }
14430
14762
  if (this.onAeroEvent) {
14431
14763
  try {
@@ -14438,7 +14770,7 @@ var RunCoordinator = class {
14438
14770
  };
14439
14771
  await this.onAeroEvent(ctx);
14440
14772
  } catch (err) {
14441
- log22.error("aero.failed", { runId, error: describeError(err) });
14773
+ log23.error("aero.failed", { runId, error: describeError(err) });
14442
14774
  }
14443
14775
  }
14444
14776
  }
@@ -14453,7 +14785,7 @@ var RunCoordinator = class {
14453
14785
  * so the Aero queue is never starved of a follow-up.
14454
14786
  */
14455
14787
  buildDiscoveryAeroContext(runId, projectId, status, error) {
14456
- const session = this.db.select().from(discoverySessions).where(eq22(discoverySessions.runId, runId)).get();
14788
+ const session = this.db.select().from(discoverySessions).where(eq23(discoverySessions.runId, runId)).get();
14457
14789
  const competitorMap = session ? session.competitorMap : [];
14458
14790
  return {
14459
14791
  kind: RunKinds["aeo-discover-probe"],
@@ -14496,13 +14828,13 @@ function analysisResultFromInsights(insights2) {
14496
14828
 
14497
14829
  // src/agent/session-registry.ts
14498
14830
  import crypto23 from "crypto";
14499
- import { eq as eq25 } from "drizzle-orm";
14831
+ import { eq as eq26 } from "drizzle-orm";
14500
14832
 
14501
14833
  // src/agent/remote-mcp.ts
14502
14834
  import { Type } from "@earendil-works/pi-ai";
14503
14835
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
14504
14836
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
14505
- var log23 = createLogger("RemoteMcp");
14837
+ var log24 = createLogger("RemoteMcp");
14506
14838
  var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([]);
14507
14839
  async function connectStreamableHttp(server) {
14508
14840
  const transport = new StreamableHTTPClientTransport(new URL(server.url), {
@@ -14570,7 +14902,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
14570
14902
  try {
14571
14903
  client = await connect(server);
14572
14904
  } catch (err) {
14573
- log23.error("external-mcp.connect-failed", {
14905
+ log24.error("external-mcp.connect-failed", {
14574
14906
  label,
14575
14907
  error: describeError(err)
14576
14908
  });
@@ -14580,7 +14912,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
14580
14912
  try {
14581
14913
  listed = await client.listTools();
14582
14914
  } catch (err) {
14583
- log23.error("external-mcp.list-failed", {
14915
+ log24.error("external-mcp.list-failed", {
14584
14916
  label,
14585
14917
  error: describeError(err)
14586
14918
  });
@@ -14591,7 +14923,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
14591
14923
  if (!isReadOnly(tool)) continue;
14592
14924
  tools.push(adaptRemoteTool(client, tool));
14593
14925
  }
14594
- log23.info("external-mcp.loaded", {
14926
+ log24.info("external-mcp.loaded", {
14595
14927
  label,
14596
14928
  discovered: listed.tools.length,
14597
14929
  adopted: tools.length
@@ -14602,7 +14934,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
14602
14934
 
14603
14935
  // src/agent/memory-store.ts
14604
14936
  import crypto22 from "crypto";
14605
- import { and as and20, desc as desc9, eq as eq23, like, sql as sql10, or as or2 } from "drizzle-orm";
14937
+ import { and as and21, desc as desc9, eq as eq24, like, sql as sql10, or as or3 } from "drizzle-orm";
14606
14938
  var COMPACTION_KEY_PREFIX = "compaction:";
14607
14939
  var COMPACTION_NOTES_PER_SESSION = 3;
14608
14940
  function rowToDto(row) {
@@ -14616,7 +14948,7 @@ function rowToDto(row) {
14616
14948
  };
14617
14949
  }
14618
14950
  function listMemoryEntries(db, projectId, opts = {}) {
14619
- const query = db.select().from(agentMemory).where(eq23(agentMemory.projectId, projectId)).orderBy(desc9(agentMemory.updatedAt));
14951
+ const query = db.select().from(agentMemory).where(eq24(agentMemory.projectId, projectId)).orderBy(desc9(agentMemory.updatedAt));
14620
14952
  const rows = opts.limit === void 0 ? query.all() : query.limit(opts.limit).all();
14621
14953
  return rows.map(rowToDto);
14622
14954
  }
@@ -14647,21 +14979,21 @@ function upsertMemoryEntry(db, args) {
14647
14979
  updatedAt: now
14648
14980
  }
14649
14981
  }).run();
14650
- const row = db.select().from(agentMemory).where(and20(eq23(agentMemory.projectId, args.projectId), eq23(agentMemory.key, args.key))).get();
14982
+ const row = db.select().from(agentMemory).where(and21(eq24(agentMemory.projectId, args.projectId), eq24(agentMemory.key, args.key))).get();
14651
14983
  if (!row) throw new Error("memory upsert produced no row");
14652
14984
  return rowToDto(row);
14653
14985
  }
14654
14986
  function deleteMemoryEntry(db, projectId, key) {
14655
- const result = db.delete(agentMemory).where(and20(eq23(agentMemory.projectId, projectId), eq23(agentMemory.key, key))).run();
14987
+ const result = db.delete(agentMemory).where(and21(eq24(agentMemory.projectId, projectId), eq24(agentMemory.key, key))).run();
14656
14988
  const changes = result.changes ?? 0;
14657
14989
  return changes > 0;
14658
14990
  }
14659
14991
  function loadRecentForHydrate(db, projectId, limit, sessionId) {
14660
14992
  if (sessionId === void 0) return listMemoryEntries(db, projectId, { limit });
14661
14993
  const sessionPrefix = `compaction:${sessionId ?? ""}:`;
14662
- return db.select().from(agentMemory).where(and20(
14663
- eq23(agentMemory.projectId, projectId),
14664
- or2(sql10`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql10`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
14994
+ return db.select().from(agentMemory).where(and21(
14995
+ eq24(agentMemory.projectId, projectId),
14996
+ or3(sql10`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql10`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
14665
14997
  )).orderBy(desc9(agentMemory.updatedAt)).limit(limit).all().map(rowToDto);
14666
14998
  }
14667
14999
  function writeCompactionNote(db, args) {
@@ -14686,8 +15018,8 @@ function writeCompactionNote(db, args) {
14686
15018
  }).run();
14687
15019
  const sessionPrefix = `${COMPACTION_KEY_PREFIX}${args.sessionId}:`;
14688
15020
  const existing = tx.select({ id: agentMemory.id, updatedAt: agentMemory.updatedAt }).from(agentMemory).where(
14689
- and20(
14690
- eq23(agentMemory.projectId, args.projectId),
15021
+ and21(
15022
+ eq24(agentMemory.projectId, args.projectId),
14691
15023
  like(agentMemory.key, `${sessionPrefix}%`)
14692
15024
  )
14693
15025
  ).orderBy(desc9(agentMemory.updatedAt)).all();
@@ -14695,7 +15027,7 @@ function writeCompactionNote(db, args) {
14695
15027
  if (stale.length > 0) {
14696
15028
  tx.delete(agentMemory).where(sql10`${agentMemory.id} IN (${sql10.join(stale.map((s) => sql10`${s}`), sql10`, `)})`).run();
14697
15029
  }
14698
- const row = tx.select().from(agentMemory).where(and20(eq23(agentMemory.projectId, args.projectId), eq23(agentMemory.key, key))).get();
15030
+ const row = tx.select().from(agentMemory).where(and21(eq24(agentMemory.projectId, args.projectId), eq24(agentMemory.key, key))).get();
14699
15031
  if (row) inserted = rowToDto(row);
14700
15032
  });
14701
15033
  if (!inserted) throw new Error("compaction note write produced no row");
@@ -14769,7 +15101,7 @@ function trackAeroTurn(agent, turn) {
14769
15101
  }
14770
15102
 
14771
15103
  // src/agent/project-shape.ts
14772
- import { and as and21, count as count3, eq as eq24 } from "drizzle-orm";
15104
+ import { and as and22, count as count3, eq as eq25 } from "drizzle-orm";
14773
15105
  var ADVANCED_TOOLS = [
14774
15106
  "canonry_measurement_portfolio_summary",
14775
15107
  "canonry_measurement_overview",
@@ -14796,10 +15128,10 @@ var ADVANCED_ROUTES = [
14796
15128
  ];
14797
15129
  function aeroProjectShape(db, projectId) {
14798
15130
  try {
14799
- const pointer = db.select().from(measurementPlans).where(eq24(measurementPlans.projectId, projectId)).get();
14800
- const version = pointer ? db.select().from(measurementPlanVersions).where(and21(
14801
- eq24(measurementPlanVersions.projectId, projectId),
14802
- eq24(measurementPlanVersions.id, pointer.activeVersionId)
15131
+ const pointer = db.select().from(measurementPlans).where(eq25(measurementPlans.projectId, projectId)).get();
15132
+ const version = pointer ? db.select().from(measurementPlanVersions).where(and22(
15133
+ eq25(measurementPlanVersions.projectId, projectId),
15134
+ eq25(measurementPlanVersions.id, pointer.activeVersionId)
14803
15135
  )).get() : void 0;
14804
15136
  if (version) {
14805
15137
  const plan = JSON.parse(version.canonicalJson);
@@ -14826,7 +15158,7 @@ canonry_visibility_report describes the whole project, not one Property. canonry
14826
15158
  pinned: ADVANCED_TOOLS
14827
15159
  };
14828
15160
  }
14829
- const tracked = db.select({ total: count3() }).from(queries).where(eq24(queries.projectId, projectId)).get()?.total ?? 0;
15161
+ const tracked = db.select({ total: count3() }).from(queries).where(eq25(queries.projectId, projectId)).get()?.total ?? 0;
14830
15162
  return {
14831
15163
  prompt: `
14832
15164
 
@@ -14966,7 +15298,7 @@ async function compactMessages(args) {
14966
15298
  }
14967
15299
 
14968
15300
  // src/agent/session-registry.ts
14969
- var log24 = createLogger("SessionRegistry");
15301
+ var log25 = createLogger("SessionRegistry");
14970
15302
  var MAX_HYDRATE_NOTES = 20;
14971
15303
  var MAX_HYDRATE_BYTES = 32 * 1024;
14972
15304
  function escapeMemoryFragment(value) {
@@ -15025,7 +15357,7 @@ var SessionRegistry = class {
15025
15357
  if (!this.externalToolsPromise) {
15026
15358
  this.externalToolsPromise = loadExternalMcpTools(this.opts.config.externalMcpServers).catch(
15027
15359
  (err) => {
15028
- log24.error("external-mcp.load-failed", {
15360
+ log25.error("external-mcp.load-failed", {
15029
15361
  error: describeError(err)
15030
15362
  });
15031
15363
  return [];
@@ -15082,7 +15414,7 @@ var SessionRegistry = class {
15082
15414
  modelProvider: effectiveProvider,
15083
15415
  modelId: effectiveModelId,
15084
15416
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
15085
- }).where(eq25(agentSessions.projectId, projectId)).run();
15417
+ }).where(eq26(agentSessions.projectId, projectId)).run();
15086
15418
  }
15087
15419
  const agent2 = createAeroSession({
15088
15420
  projectName,
@@ -15301,13 +15633,13 @@ ${lines.join("\n")}
15301
15633
  agent.state.messages = result.messages;
15302
15634
  setAeroSystemPrompt(agent, this.buildHydratedSystemPrompt(projectId, row.systemPrompt));
15303
15635
  this.save(projectName);
15304
- log24.info("compaction.completed", {
15636
+ log25.info("compaction.completed", {
15305
15637
  projectName,
15306
15638
  removedCount: result.removedCount,
15307
15639
  summaryBytes: Buffer.byteLength(result.summary, "utf8")
15308
15640
  });
15309
15641
  } catch (err) {
15310
- log24.error("compaction.failed", {
15642
+ log25.error("compaction.failed", {
15311
15643
  projectName,
15312
15644
  error: describeError(err)
15313
15645
  });
@@ -15401,7 +15733,7 @@ ${lines.join("\n")}
15401
15733
  modelProvider: nextProvider,
15402
15734
  modelId: nextModelId,
15403
15735
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
15404
- }).where(eq25(agentSessions.projectId, projectId)).run();
15736
+ }).where(eq26(agentSessions.projectId, projectId)).run();
15405
15737
  }
15406
15738
  /** Snapshot pending work without consuming it before an atomic conversation switch. */
15407
15739
  prepareConversationChange(projectName) {
@@ -15485,7 +15817,7 @@ ${lines.join("\n")}
15485
15817
  }
15486
15818
  trackAeroTurn(agent, { trigger: OutcomeTriggers.agent });
15487
15819
  } catch (err) {
15488
- log24.error("drain.failed", {
15820
+ log25.error("drain.failed", {
15489
15821
  projectName,
15490
15822
  error: describeError(err)
15491
15823
  });
@@ -15582,11 +15914,11 @@ ${lines.join("\n")}
15582
15914
  return id;
15583
15915
  }
15584
15916
  tryResolveProjectId(projectName) {
15585
- const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq25(projects.name, projectName)).get();
15917
+ const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq26(projects.name, projectName)).get();
15586
15918
  return row?.id;
15587
15919
  }
15588
15920
  loadRow(projectId) {
15589
- const row = this.opts.db.select().from(agentSessions).where(eq25(agentSessions.projectId, projectId)).get();
15921
+ const row = this.opts.db.select().from(agentSessions).where(eq26(agentSessions.projectId, projectId)).get();
15590
15922
  return row ?? null;
15591
15923
  }
15592
15924
  insertRow(params) {
@@ -15606,7 +15938,7 @@ ${lines.join("\n")}
15606
15938
  }
15607
15939
  updateRow(projectId, patch) {
15608
15940
  const now = (/* @__PURE__ */ new Date()).toISOString();
15609
- this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq25(agentSessions.projectId, projectId)).run();
15941
+ this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq26(agentSessions.projectId, projectId)).run();
15610
15942
  }
15611
15943
  /**
15612
15944
  * Store a refreshed prompt snapshot without touching `updatedAt`, which the
@@ -15615,13 +15947,13 @@ ${lines.join("\n")}
15615
15947
  * recently used right after an upgrade.
15616
15948
  */
15617
15949
  persistPromptSnapshot(projectId, systemPrompt) {
15618
- this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq25(agentSessions.projectId, projectId)).run();
15950
+ this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq26(agentSessions.projectId, projectId)).run();
15619
15951
  }
15620
15952
  };
15621
15953
 
15622
15954
  // src/agent/viewer-sessions.ts
15623
15955
  import crypto24 from "crypto";
15624
- import { and as and22, eq as eq26, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
15956
+ import { and as and23, eq as eq27, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
15625
15957
  var AERO_VIEWER_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([
15626
15958
  CanonryMcpToolNames.canonry_ads_account,
15627
15959
  CanonryMcpToolNames.canonry_ads_geo_search,
@@ -15798,12 +16130,12 @@ var ViewerAeroSessions = class {
15798
16130
  */
15799
16131
  removeKey(id) {
15800
16132
  try {
15801
- this.opts.db.delete(apiKeys).where(eq26(apiKeys.id, id)).run();
16133
+ this.opts.db.delete(apiKeys).where(eq27(apiKeys.id, id)).run();
15802
16134
  } catch {
15803
16135
  try {
15804
16136
  this.opts.db.transaction((tx) => {
15805
- tx.delete(dashboardSessions).where(eq26(dashboardSessions.apiKeyId, id)).run();
15806
- tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq26(apiKeys.id, id)).run();
16137
+ tx.delete(dashboardSessions).where(eq27(dashboardSessions.apiKeyId, id)).run();
16138
+ tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq27(apiKeys.id, id)).run();
15807
16139
  });
15808
16140
  } catch {
15809
16141
  }
@@ -15816,7 +16148,7 @@ var ViewerAeroSessions = class {
15816
16148
  */
15817
16149
  revokeOrphanedKeys() {
15818
16150
  try {
15819
- this.opts.db.delete(apiKeys).where(and22(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
16151
+ this.opts.db.delete(apiKeys).where(and23(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
15820
16152
  } catch {
15821
16153
  }
15822
16154
  }
@@ -15833,7 +16165,7 @@ var ViewerAeroSessions = class {
15833
16165
  // src/mcp-http.ts
15834
16166
  import crypto25 from "crypto";
15835
16167
  import { isIP } from "net";
15836
- import { eq as eq27 } from "drizzle-orm";
16168
+ import { eq as eq28 } from "drizzle-orm";
15837
16169
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
15838
16170
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
15839
16171
  var SESSION_IDLE_MS = 10 * 60 * 1e3;
@@ -15855,8 +16187,8 @@ function mintSessionKey(db, scopes, userId) {
15855
16187
  function revokeSessionKey(db, id) {
15856
16188
  try {
15857
16189
  db.transaction((tx) => {
15858
- tx.delete(dashboardSessions).where(eq27(dashboardSessions.apiKeyId, id)).run();
15859
- tx.update(apiKeys).set({ revokedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq27(apiKeys.id, id)).run();
16190
+ tx.delete(dashboardSessions).where(eq28(dashboardSessions.apiKeyId, id)).run();
16191
+ tx.update(apiKeys).set({ revokedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq28(apiKeys.id, id)).run();
15860
16192
  });
15861
16193
  } catch {
15862
16194
  }
@@ -16078,7 +16410,7 @@ function registerMcpHttpRoutes(scope, opts) {
16078
16410
  }
16079
16411
 
16080
16412
  // src/agent/agent-routes.ts
16081
- import { eq as eq28 } from "drizzle-orm";
16413
+ import { eq as eq29 } from "drizzle-orm";
16082
16414
  function viewerAeroCaller(request, opts) {
16083
16415
  if (!opts.viewerSessions) return null;
16084
16416
  const principal = request.principal;
@@ -16118,7 +16450,7 @@ function turnAttribution(request) {
16118
16450
  };
16119
16451
  }
16120
16452
  function resolveProject(db, name) {
16121
- const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq28(projects.name, name)).get();
16453
+ const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq29(projects.name, name)).get();
16122
16454
  if (!row) throw notFound("project", name);
16123
16455
  return row;
16124
16456
  }
@@ -16237,7 +16569,7 @@ function registerAgentRoutes(app, opts) {
16237
16569
  }
16238
16570
  requireInstanceAdministrator(request);
16239
16571
  const project = resolveProject(opts.db, request.params.name);
16240
- const row = opts.db.select().from(agentSessions).where(eq28(agentSessions.projectId, project.id)).get();
16572
+ const row = opts.db.select().from(agentSessions).where(eq29(agentSessions.projectId, project.id)).get();
16241
16573
  const nextTurn = opts.sessionRegistry.nextTurnModel(project.name);
16242
16574
  if (!row) {
16243
16575
  return { conversationId: null, messages: [], modelProvider: null, modelId: null, nextTurn, updatedAt: null };
@@ -16279,7 +16611,7 @@ function registerAgentRoutes(app, opts) {
16279
16611
  const project = resolveProject(opts.db, request.params.name);
16280
16612
  if (opts.sessionRegistry.isBusy(project.name)) throw agentBusy(project.name);
16281
16613
  opts.sessionRegistry.reset(project.name);
16282
- opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq28(agentSessions.projectId, project.id)).run();
16614
+ opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq29(agentSessions.projectId, project.id)).run();
16283
16615
  return { status: "reset" };
16284
16616
  }
16285
16617
  );
@@ -16303,7 +16635,7 @@ function registerAgentRoutes(app, opts) {
16303
16635
  return streamViewerTurn(opts, project, viewerId, body, reply, turnAttribution(request));
16304
16636
  }
16305
16637
  if (body.conversationId !== void 0) {
16306
- const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq28(agentSessions.projectId, project.id)).get();
16638
+ const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq29(agentSessions.projectId, project.id)).get();
16307
16639
  if ((current?.id ?? null) !== body.conversationId) throw validationError("The active conversation changed. Reload the conversation before sending.");
16308
16640
  }
16309
16641
  const promptText = body.prompt;
@@ -16714,7 +17046,7 @@ function stripHtml(html) {
16714
17046
  }
16715
17047
 
16716
17048
  // src/snapshot-service.ts
16717
- var log25 = createLogger("Snapshot");
17049
+ var log26 = createLogger("Snapshot");
16718
17050
  var ANALYSIS_PROVIDER_PRIORITY = ["openai", "claude", "gemini", "perplexity", "muse", "local"];
16719
17051
  var SNAPSHOT_QUERY_COUNT = 6;
16720
17052
  var SnapshotService = class {
@@ -16816,7 +17148,7 @@ var SnapshotService = class {
16816
17148
  return mapAuditReport(report);
16817
17149
  } catch (err) {
16818
17150
  const message = describeError(err);
16819
- log25.warn("audit.failed", { homepageUrl, error: message });
17151
+ log26.warn("audit.failed", { homepageUrl, error: message });
16820
17152
  return {
16821
17153
  url: homepageUrl,
16822
17154
  finalUrl: homepageUrl,
@@ -16845,7 +17177,7 @@ var SnapshotService = class {
16845
17177
  queries: parsedQueries
16846
17178
  };
16847
17179
  } catch (err) {
16848
- log25.warn("profile.generation-failed", {
17180
+ log26.warn("profile.generation-failed", {
16849
17181
  domain: ctx.domain,
16850
17182
  provider: ctx.analysisProvider.adapter.name,
16851
17183
  error: describeError(err)
@@ -16993,7 +17325,7 @@ var SnapshotService = class {
16993
17325
  recommendedActions: uniqueStrings2(parsed.recommendedActions ?? []).slice(0, 4)
16994
17326
  };
16995
17327
  } catch (err) {
16996
- log25.warn("response.analysis-failed", {
17328
+ log26.warn("response.analysis-failed", {
16997
17329
  provider: ctx.analysisProvider.adapter.name,
16998
17330
  error: describeError(err)
16999
17331
  });
@@ -17263,7 +17595,7 @@ function clipText(value, length) {
17263
17595
  }
17264
17596
 
17265
17597
  // src/research-runner.ts
17266
- import { and as and23, eq as eq29, inArray as inArray12, sql as sql11 } from "drizzle-orm";
17598
+ import { and as and24, eq as eq30, inArray as inArray12, sql as sql11 } from "drizzle-orm";
17267
17599
  var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
17268
17600
  function finalResearchRunStatus(completed, failed, waiting) {
17269
17601
  if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
@@ -17271,13 +17603,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
17271
17603
  return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
17272
17604
  }
17273
17605
  async function executeResearchRun(db, registry, runId, projectId, options = {}) {
17274
- const run = db.select().from(researchRuns).where(and23(eq29(researchRuns.id, runId), eq29(researchRuns.projectId, projectId))).get();
17606
+ const run = db.select().from(researchRuns).where(and24(eq30(researchRuns.id, runId), eq30(researchRuns.projectId, projectId))).get();
17275
17607
  if (!run || run.status !== ResearchRunStatuses.queued) return;
17276
- const project = db.select().from(projects).where(eq29(projects.id, projectId)).get();
17608
+ const project = db.select().from(projects).where(eq30(projects.id, projectId)).get();
17277
17609
  if (!project) return;
17278
17610
  const provider = registry.get(run.provider);
17279
17611
  const now = (/* @__PURE__ */ new Date()).toISOString();
17280
- const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and23(eq29(researchRuns.id, runId), eq29(researchRuns.status, ResearchRunStatuses.queued))).run();
17612
+ const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and24(eq30(researchRuns.id, runId), eq30(researchRuns.status, ResearchRunStatuses.queued))).run();
17281
17613
  if (claim.changes !== 1) return;
17282
17614
  const elapsed = startOutcomeTimer();
17283
17615
  const requested = currentOutcomeOrigin();
@@ -17311,8 +17643,8 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
17311
17643
  }
17312
17644
  reserved = run.totalQueries;
17313
17645
  reservation = { scope, period };
17314
- const rows = db.select().from(researchRunQueries).where(eq29(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
17315
- const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq29(competitors.projectId, projectId)).orderBy(competitors.domain).all();
17646
+ const rows = db.select().from(researchRunQueries).where(eq30(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
17647
+ const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq30(competitors.projectId, projectId)).orderBy(competitors.domain).all();
17316
17648
  const competitorDomains = competitorRows.map((row) => row.domain);
17317
17649
  const competitorAliases = new Map(competitorRows.map((row) => [row.domain, competitorIdentityAliases(row)]).filter(([, aliases]) => aliases.length > 0));
17318
17650
  const domains = effectiveDomains(project);
@@ -17322,7 +17654,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
17322
17654
  await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
17323
17655
  try {
17324
17656
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
17325
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and23(eq29(researchRunQueries.id, row.id), eq29(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
17657
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and24(eq30(researchRunQueries.id, row.id), eq30(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
17326
17658
  const raw = await gate.run(async () => {
17327
17659
  dispatched++;
17328
17660
  return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
@@ -17353,7 +17685,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
17353
17685
  rawResponse: raw.rawResponse,
17354
17686
  answerEvidence: raw.evidence ?? null,
17355
17687
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
17356
- }).where(and23(eq29(researchRunQueries.id, row.id), eq29(researchRunQueries.status, ResearchQueryStatuses.running))).run();
17688
+ }).where(and24(eq30(researchRunQueries.id, row.id), eq30(researchRunQueries.status, ResearchQueryStatuses.running))).run();
17357
17689
  if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
17358
17690
  } catch (error) {
17359
17691
  if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
@@ -17404,11 +17736,11 @@ function researchOutcomeStatus(status) {
17404
17736
  }
17405
17737
  }
17406
17738
  function incrementResearchProgress(db, runId, column) {
17407
- db.update(researchRuns).set({ [column]: sql11`${researchRuns[column]} + 1` }).where(eq29(researchRuns.id, runId)).run();
17739
+ db.update(researchRuns).set({ [column]: sql11`${researchRuns[column]} + 1` }).where(eq30(researchRuns.id, runId)).run();
17408
17740
  }
17409
17741
  function markResearchQueryFailed(db, runId, queryId, error) {
17410
17742
  const message = describeError(error);
17411
- const unfinished = and23(eq29(researchRunQueries.id, queryId), inArray12(researchRunQueries.status, unfinishedResearchQueryStatuses));
17743
+ const unfinished = and24(eq30(researchRunQueries.id, queryId), inArray12(researchRunQueries.status, unfinishedResearchQueryStatuses));
17412
17744
  if (error instanceof IncompleteAnswerError && error.resumable) {
17413
17745
  db.update(researchRunQueries).set({
17414
17746
  status: ResearchQueryStatuses["waiting-upstream"],
@@ -17424,10 +17756,10 @@ function markResearchQueryFailed(db, runId, queryId, error) {
17424
17756
  if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
17425
17757
  }
17426
17758
  function markUnfinishedResearchQueriesFailed(db, runId, error) {
17427
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and23(eq29(researchRunQueries.researchRunId, runId), inArray12(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
17759
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and24(eq30(researchRunQueries.researchRunId, runId), inArray12(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
17428
17760
  }
17429
17761
  function finalizeResearchRun(db, runId, fatalError) {
17430
- const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq29(researchRunQueries.researchRunId, runId)).all();
17762
+ const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq30(researchRunQueries.researchRunId, runId)).all();
17431
17763
  const completed = rows.filter((row) => row.status === ResearchQueryStatuses.completed).length;
17432
17764
  const failed = rows.filter((row) => row.status === ResearchQueryStatuses.failed).length;
17433
17765
  const waiting = rows.filter((row) => row.status === ResearchQueryStatuses["waiting-upstream"]).length;
@@ -17439,12 +17771,12 @@ function finalizeResearchRun(db, runId, fatalError) {
17439
17771
  error: fatalError ?? (failed === rows.length ? "Every research query failed." : null),
17440
17772
  // A run waiting on upstream jobs has not finished.
17441
17773
  finishedAt: waiting > 0 ? null : (/* @__PURE__ */ new Date()).toISOString()
17442
- }).where(eq29(researchRuns.id, runId)).run();
17774
+ }).where(eq30(researchRuns.id, runId)).run();
17443
17775
  return { status, total: rows.length, completed, failed };
17444
17776
  }
17445
17777
 
17446
17778
  // src/google-marketing-sync.ts
17447
- import { and as and24, eq as eq30, isNull as isNull4, sql as sql12 } from "drizzle-orm";
17779
+ import { and as and25, eq as eq31, isNull as isNull6, sql as sql12 } from "drizzle-orm";
17448
17780
  var RUNTIME_FAILURE_REASONS = {
17449
17781
  INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
17450
17782
  NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
@@ -17481,10 +17813,10 @@ function assertSnapshotContext(metadata, expected) {
17481
17813
  }
17482
17814
  }
17483
17815
  function requireSyncRun(db, runId, projectId, kind) {
17484
- const run = db.select().from(runs).where(and24(
17485
- eq30(runs.id, runId),
17486
- eq30(runs.projectId, projectId),
17487
- eq30(runs.kind, kind)
17816
+ const run = db.select().from(runs).where(and25(
17817
+ eq31(runs.id, runId),
17818
+ eq31(runs.projectId, projectId),
17819
+ eq31(runs.kind, kind)
17488
17820
  )).get();
17489
17821
  if (!run) throw withOutcomeReason(new Error(`Run ${runId} is not a ${kind} run for this project.`), OutcomeReasonCodes.NOT_FOUND);
17490
17822
  if (run.status !== RunStatuses.queued) {
@@ -17500,19 +17832,19 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
17500
17832
  status: RunStatuses.failed,
17501
17833
  error: serializeRunError({ message: safeErrorMessage(error) }),
17502
17834
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
17503
- }).where(and24(
17504
- eq30(runs.id, runId),
17505
- eq30(runs.projectId, projectId),
17506
- eq30(runs.kind, kind),
17507
- eq30(runs.status, expectedStatus)
17835
+ }).where(and25(
17836
+ eq31(runs.id, runId),
17837
+ eq31(runs.projectId, projectId),
17838
+ eq31(runs.kind, kind),
17839
+ eq31(runs.status, expectedStatus)
17508
17840
  )).run();
17509
17841
  }
17510
17842
  function claimSyncRun(db, runId, projectId, kind, startedAt) {
17511
- const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and24(
17512
- eq30(runs.id, runId),
17513
- eq30(runs.projectId, projectId),
17514
- eq30(runs.kind, kind),
17515
- eq30(runs.status, RunStatuses.queued)
17843
+ const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and25(
17844
+ eq31(runs.id, runId),
17845
+ eq31(runs.projectId, projectId),
17846
+ eq31(runs.kind, kind),
17847
+ eq31(runs.status, RunStatuses.queued)
17516
17848
  )).run();
17517
17849
  return claim.changes === 1;
17518
17850
  }
@@ -17522,9 +17854,9 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
17522
17854
  let evidenceCollected = false;
17523
17855
  try {
17524
17856
  requireSyncRun(db, runId, projectId, RunKinds["google-ads-sync"]);
17525
- const project = db.select().from(projects).where(eq30(projects.id, projectId)).get();
17857
+ const project = db.select().from(projects).where(eq31(projects.id, projectId)).get();
17526
17858
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
17527
- const connection = db.select().from(googleAdsConnections).where(eq30(googleAdsConnections.projectId, projectId)).get();
17859
+ const connection = db.select().from(googleAdsConnections).where(eq31(googleAdsConnections.projectId, projectId)).get();
17528
17860
  if (!connection?.selectedCustomerId) {
17529
17861
  throw withOutcomeReason(new Error("Google Ads needs a selected customer before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
17530
17862
  }
@@ -17576,11 +17908,11 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
17576
17908
  status: RunStatuses.completed,
17577
17909
  finishedAt,
17578
17910
  error: null
17579
- }).where(and24(
17580
- eq30(runs.id, runId),
17581
- eq30(runs.projectId, projectId),
17582
- eq30(runs.kind, RunKinds["google-ads-sync"]),
17583
- eq30(runs.status, RunStatuses.running)
17911
+ }).where(and25(
17912
+ eq31(runs.id, runId),
17913
+ eq31(runs.projectId, projectId),
17914
+ eq31(runs.kind, RunKinds["google-ads-sync"]),
17915
+ eq31(runs.status, RunStatuses.running)
17584
17916
  )).run();
17585
17917
  if (terminalClaim.changes !== 1) {
17586
17918
  throw withOutcomeReason(
@@ -17600,12 +17932,12 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
17600
17932
  lastMetricsSnapshotAt: result.metrics?.metadata.capturedAt ?? connection.lastMetricsSnapshotAt,
17601
17933
  lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
17602
17934
  updatedAt: finishedAt
17603
- }).where(and24(
17604
- eq30(googleAdsConnections.id, connection.id),
17605
- eq30(googleAdsConnections.projectId, projectId),
17606
- eq30(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
17607
- connection.selectedLoginCustomerId === null ? isNull4(googleAdsConnections.selectedLoginCustomerId) : eq30(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
17608
- eq30(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
17935
+ }).where(and25(
17936
+ eq31(googleAdsConnections.id, connection.id),
17937
+ eq31(googleAdsConnections.projectId, projectId),
17938
+ eq31(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
17939
+ connection.selectedLoginCustomerId === null ? isNull6(googleAdsConnections.selectedLoginCustomerId) : eq31(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
17940
+ eq31(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
17609
17941
  )).run();
17610
17942
  if (connectionClaim.changes !== 1) {
17611
17943
  throw withOutcomeReason(
@@ -17645,9 +17977,9 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
17645
17977
  let evidenceCollected = false;
17646
17978
  try {
17647
17979
  requireSyncRun(db, runId, projectId, RunKinds["gtm-sync"]);
17648
- const project = db.select().from(projects).where(eq30(projects.id, projectId)).get();
17980
+ const project = db.select().from(projects).where(eq31(projects.id, projectId)).get();
17649
17981
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
17650
- const connection = db.select().from(gtmConnections).where(eq30(gtmConnections.projectId, projectId)).get();
17982
+ const connection = db.select().from(gtmConnections).where(eq31(gtmConnections.projectId, projectId)).get();
17651
17983
  if (!connection?.selectedAccountId || !connection.selectedContainerId) {
17652
17984
  throw withOutcomeReason(new Error("GTM needs a selected account and container before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
17653
17985
  }
@@ -17685,11 +18017,11 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
17685
18017
  status: RunStatuses.completed,
17686
18018
  finishedAt,
17687
18019
  error: null
17688
- }).where(and24(
17689
- eq30(runs.id, runId),
17690
- eq30(runs.projectId, projectId),
17691
- eq30(runs.kind, RunKinds["gtm-sync"]),
17692
- eq30(runs.status, RunStatuses.running)
18020
+ }).where(and25(
18021
+ eq31(runs.id, runId),
18022
+ eq31(runs.projectId, projectId),
18023
+ eq31(runs.kind, RunKinds["gtm-sync"]),
18024
+ eq31(runs.status, RunStatuses.running)
17693
18025
  )).run();
17694
18026
  if (terminalClaim.changes !== 1) {
17695
18027
  throw withOutcomeReason(
@@ -17710,13 +18042,13 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
17710
18042
  lastSnapshotAt: snapshot.metadata.capturedAt,
17711
18043
  lastSnapshotId: snapshot.metadata.id,
17712
18044
  updatedAt: finishedAt
17713
- }).where(and24(
17714
- eq30(gtmConnections.id, connection.id),
17715
- eq30(gtmConnections.projectId, projectId),
17716
- eq30(gtmConnections.selectedAccountId, connection.selectedAccountId),
17717
- eq30(gtmConnections.selectedContainerId, connection.selectedContainerId),
17718
- connection.selectedWorkspaceId === null ? isNull4(gtmConnections.selectedWorkspaceId) : eq30(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
17719
- eq30(gtmConnections.selectionGeneration, connection.selectionGeneration)
18045
+ }).where(and25(
18046
+ eq31(gtmConnections.id, connection.id),
18047
+ eq31(gtmConnections.projectId, projectId),
18048
+ eq31(gtmConnections.selectedAccountId, connection.selectedAccountId),
18049
+ eq31(gtmConnections.selectedContainerId, connection.selectedContainerId),
18050
+ connection.selectedWorkspaceId === null ? isNull6(gtmConnections.selectedWorkspaceId) : eq31(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
18051
+ eq31(gtmConnections.selectionGeneration, connection.selectionGeneration)
17720
18052
  )).run();
17721
18053
  if (connectionClaim.changes !== 1) {
17722
18054
  throw withOutcomeReason(
@@ -17754,7 +18086,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
17754
18086
  // src/server.ts
17755
18087
  var _require = createRequire(import.meta.url);
17756
18088
  var { version: PKG_VERSION } = _require("../package.json");
17757
- var log26 = createLogger("Server");
18089
+ var log27 = createLogger("Server");
17758
18090
  var runtimeStartupByServer = /* @__PURE__ */ new WeakMap();
17759
18091
  function waitForServerRuntimeStartup(app) {
17760
18092
  const startup = runtimeStartupByServer.get(app);
@@ -17994,7 +18326,7 @@ function applyLegacyCredentials(rows, config) {
17994
18326
  }
17995
18327
  if (migratedGoogle > 0) {
17996
18328
  saveConfigPatch({ google: config.google });
17997
- log26.info("credentials.migrated", { type: "google", count: migratedGoogle });
18329
+ log27.info("credentials.migrated", { type: "google", count: migratedGoogle });
17998
18330
  }
17999
18331
  let migratedGa4 = 0;
18000
18332
  for (const row of rows.ga4) {
@@ -18012,7 +18344,7 @@ function applyLegacyCredentials(rows, config) {
18012
18344
  }
18013
18345
  if (migratedGa4 > 0) {
18014
18346
  saveConfigPatch({ ga4: config.ga4 });
18015
- log26.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
18347
+ log27.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
18016
18348
  }
18017
18349
  }
18018
18350
  function isLoopbackPeerAddress(address) {
@@ -18279,16 +18611,16 @@ async function createServer(opts) {
18279
18611
  applyLegacyCredentials(legacyRows, opts.config);
18280
18612
  dropLegacyCredentialColumns(opts.db);
18281
18613
  } catch (err) {
18282
- log26.warn("credentials.migration.failed", {
18614
+ log27.warn("credentials.migration.failed", {
18283
18615
  error: describeError(err)
18284
18616
  });
18285
18617
  }
18286
- log26.info("providers.configured", {
18618
+ log27.info("providers.configured", {
18287
18619
  providers: registeredProviderNames({ providers, cdp: opts.config.cdp })
18288
18620
  });
18289
18621
  registry.replace(configuredProviderEntries(opts.config, API_ADAPTERS, cdpChatgptAdapter));
18290
18622
  for (const name of providersWithUnsupportedBatch(providers, (provider) => adapterMap[provider])) {
18291
- log26.warn("provider.batch.unsupported", {
18623
+ log27.warn("provider.batch.unsupported", {
18292
18624
  provider: name,
18293
18625
  message: `providers.${name}.batch.enabled is true, but the ${name} adapter has no batch API; its sweeps run sync.`
18294
18626
  });
@@ -18340,7 +18672,7 @@ async function createServer(opts) {
18340
18672
  async (ctx) => {
18341
18673
  if (!sessionRegistry) return;
18342
18674
  if (!agentProactive) return;
18343
- const project = opts.db.select({ name: projects.name }).from(projects).where(eq31(projects.id, ctx.projectId)).get();
18675
+ const project = opts.db.select({ name: projects.name }).from(projects).where(eq32(projects.id, ctx.projectId)).get();
18344
18676
  if (!project) return;
18345
18677
  let content;
18346
18678
  if (ctx.kind === RunKinds["aeo-discover-probe"]) {
@@ -18766,6 +19098,7 @@ async function createServer(opts) {
18766
19098
  ))
18767
19099
  };
18768
19100
  let stopSiteLiveness = null;
19101
+ let stopReviewDeliveries = null;
18769
19102
  let stopProviderBatchPoller = null;
18770
19103
  let stopInstallState = null;
18771
19104
  const scheduler = new Scheduler(opts.db, {
@@ -18805,7 +19138,7 @@ async function createServer(opts) {
18805
19138
  void (async () => {
18806
19139
  try {
18807
19140
  const report = await schedulerClient.runDoctor({ project: projectName, checkIds: scheduledHealthCheckIds() });
18808
- const project = opts.db.select().from(projects).where(eq31(projects.name, projectName)).get();
19141
+ const project = opts.db.select().from(projects).where(eq32(projects.name, projectName)).get();
18809
19142
  if (!project) {
18810
19143
  app.log.warn({ projectName }, "doctor schedule fired for an unknown project");
18811
19144
  return;
@@ -19077,7 +19410,7 @@ async function createServer(opts) {
19077
19410
  })();
19078
19411
  if (opts.config.apiKey) {
19079
19412
  const keyHash = hashApiKey(opts.config.apiKey);
19080
- const existing = opts.db.select().from(apiKeys).where(eq31(apiKeys.keyHash, keyHash)).get();
19413
+ const existing = opts.db.select().from(apiKeys).where(eq32(apiKeys.keyHash, keyHash)).get();
19081
19414
  if (!existing) {
19082
19415
  const prefix = opts.config.apiKey.slice(0, 12);
19083
19416
  opts.db.insert(apiKeys).values({
@@ -19095,15 +19428,15 @@ async function createServer(opts) {
19095
19428
  opts.config.publicUrl?.startsWith("https://") || opts.config.apiUrl?.startsWith("https://")
19096
19429
  );
19097
19430
  const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
19098
- opts.db.delete(dashboardSessions).where(or3(
19099
- eq31(dashboardSessions.apiKeyHash, ""),
19100
- and25(
19431
+ opts.db.delete(dashboardSessions).where(or4(
19432
+ eq32(dashboardSessions.apiKeyHash, ""),
19433
+ and26(
19101
19434
  isNotNull5(dashboardSessions.passwordFingerprint),
19102
19435
  ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
19103
19436
  )
19104
19437
  )).run();
19105
19438
  if (!opts.config.dashboardPasswordHash) {
19106
- const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and25(eq31(auditLog.entityType, "dashboard-password"), eq31(auditLog.action, action))).get()?.at ?? null;
19439
+ const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and26(eq32(auditLog.entityType, "dashboard-password"), eq32(auditLog.action, action))).get()?.at ?? null;
19107
19440
  const createdAt = lastPasswordEventAt("dashboard-password.created");
19108
19441
  const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
19109
19442
  if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
@@ -19117,7 +19450,7 @@ async function createServer(opts) {
19117
19450
  }
19118
19451
  const createSession = (key, passwordBased = false, db = opts.db) => {
19119
19452
  const now = /* @__PURE__ */ new Date();
19120
- db.delete(dashboardSessions).where(lte2(dashboardSessions.expiresAt, now.toISOString())).run();
19453
+ db.delete(dashboardSessions).where(lte3(dashboardSessions.expiresAt, now.toISOString())).run();
19121
19454
  const sessionId = crypto26.randomBytes(32).toString("hex");
19122
19455
  db.insert(dashboardSessions).values({
19123
19456
  tokenHash: hashSessionToken(sessionId),
@@ -19137,23 +19470,23 @@ async function createServer(opts) {
19137
19470
  currentApiKeyHash: apiKeys.keyHash,
19138
19471
  passwordFingerprint: dashboardSessions.passwordFingerprint,
19139
19472
  expiresAt: dashboardSessions.expiresAt
19140
- }).from(dashboardSessions).innerJoin(apiKeys, eq31(apiKeys.id, dashboardSessions.apiKeyId)).where(and25(eq31(dashboardSessions.tokenHash, tokenHash), isNull5(apiKeys.revokedAt))).get();
19473
+ }).from(dashboardSessions).innerJoin(apiKeys, eq32(apiKeys.id, dashboardSessions.apiKeyId)).where(and26(eq32(dashboardSessions.tokenHash, tokenHash), isNull7(apiKeys.revokedAt))).get();
19141
19474
  if (!session) return null;
19142
19475
  const expiresAt = Date.parse(session.expiresAt);
19143
19476
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
19144
- opts.db.delete(dashboardSessions).where(eq31(dashboardSessions.tokenHash, tokenHash)).run();
19477
+ opts.db.delete(dashboardSessions).where(eq32(dashboardSessions.tokenHash, tokenHash)).run();
19145
19478
  return null;
19146
19479
  }
19147
19480
  return session.apiKeyId;
19148
19481
  };
19149
19482
  const clearSession = (sessionId) => {
19150
19483
  if (sessionId) {
19151
- opts.db.delete(dashboardSessions).where(eq31(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
19484
+ opts.db.delete(dashboardSessions).where(eq32(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
19152
19485
  }
19153
19486
  };
19154
19487
  const getDefaultApiKey = () => {
19155
19488
  if (!opts.config.apiKey) return void 0;
19156
- return opts.db.select().from(apiKeys).where(eq31(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
19489
+ return opts.db.select().from(apiKeys).where(eq32(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
19157
19490
  };
19158
19491
  const setSessionCookie = (reply, sessionId) => {
19159
19492
  reply.header(
@@ -19312,12 +19645,12 @@ async function createServer(opts) {
19312
19645
  return reply.send({ authenticated: true });
19313
19646
  }
19314
19647
  if (apiKey) {
19315
- const key = opts.db.select().from(apiKeys).where(eq31(apiKeys.keyHash, hashApiKey(apiKey))).get();
19648
+ const key = opts.db.select().from(apiKeys).where(eq32(apiKeys.keyHash, hashApiKey(apiKey))).get();
19316
19649
  if (!key || key.revokedAt) {
19317
19650
  const err2 = authInvalid();
19318
19651
  return reply.status(err2.statusCode).send(err2.toJSON());
19319
19652
  }
19320
- opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq31(apiKeys.id, key.id)).run();
19653
+ opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq32(apiKeys.id, key.id)).run();
19321
19654
  setSessionCookie(reply, createSession(key));
19322
19655
  return reply.send({ authenticated: true });
19323
19656
  }
@@ -19383,7 +19716,7 @@ async function createServer(opts) {
19383
19716
  const sentimentPoller = createSentimentPoller(
19384
19717
  () => sentimentWorker.tick(),
19385
19718
  () => {
19386
- log26.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
19719
+ log27.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
19387
19720
  }
19388
19721
  );
19389
19722
  const pollSentiment = sentimentPoller.poll;
@@ -19395,7 +19728,7 @@ async function createServer(opts) {
19395
19728
  const recomputeDebts = /* @__PURE__ */ new Map();
19396
19729
  let recomputeSequence = 0;
19397
19730
  const markAnswerFieldRecompute = (projectId, full) => {
19398
- opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql13`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq31(projects.id, projectId)).run();
19731
+ opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql13`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq32(projects.id, projectId)).run();
19399
19732
  };
19400
19733
  const requestAnswerFieldRecompute = (projectId, projectName, scope, reason) => {
19401
19734
  const sequence = ++recomputeSequence;
@@ -19413,10 +19746,10 @@ async function createServer(opts) {
19413
19746
  if (pass.full && debt.latestFull <= sequence) debt.latestFull = 0;
19414
19747
  try {
19415
19748
  if (debt.latest === sequence && debt.latestFull === 0) {
19416
- opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq31(projects.id, projectId)).run();
19749
+ opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq32(projects.id, projectId)).run();
19417
19750
  if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
19418
19751
  } else if (debt.latestFull === 0) {
19419
- opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and25(eq31(projects.id, projectId), eq31(projects.answerFieldsRecompute, "full"))).run();
19752
+ opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and26(eq32(projects.id, projectId), eq32(projects.answerFieldsRecompute, "full"))).run();
19420
19753
  }
19421
19754
  } catch (err) {
19422
19755
  app.log.error({ err, projectId }, "could not clear the owed answer field recompute");
@@ -19453,7 +19786,7 @@ async function createServer(opts) {
19453
19786
  await yieldToEventLoop4();
19454
19787
  const reason = (competitorAutoAliasReasons.get(projectId) ?? []).join(",");
19455
19788
  competitorAutoAliasReasons.delete(projectId);
19456
- const project = opts.db.select().from(projects).where(eq31(projects.id, projectId)).get();
19789
+ const project = opts.db.select().from(projects).where(eq32(projects.id, projectId)).get();
19457
19790
  if (!project || project.competitorAutoAliases === "off") return;
19458
19791
  if (project.competitorAutoAliases === "apply") {
19459
19792
  await competitorAutoAliases.request(projectId, reason).catch(() => void 0);
@@ -19649,8 +19982,8 @@ async function createServer(opts) {
19649
19982
  getAgentPin: () => describeAgentPin(opts.config),
19650
19983
  getGoogleMarketingDoctorInput: (ctx) => {
19651
19984
  if (!ctx.project) return null;
19652
- const googleAds = opts.db.select().from(googleAdsConnections).where(eq31(googleAdsConnections.projectId, ctx.project.id)).get();
19653
- const gtm = opts.db.select().from(gtmConnections).where(eq31(gtmConnections.projectId, ctx.project.id)).get();
19985
+ const googleAds = opts.db.select().from(googleAdsConnections).where(eq32(googleAdsConnections.projectId, ctx.project.id)).get();
19986
+ const gtm = opts.db.select().from(gtmConnections).where(eq32(gtmConnections.projectId, ctx.project.id)).get();
19654
19987
  const googleAdsCredential = getGoogleAdsConnection(opts.config, ctx.project.id);
19655
19988
  const gtmCredential = getGtmConnection(opts.config, ctx.project.id);
19656
19989
  const googleAdsConnected = Boolean(googleAdsCredential?.accessToken);
@@ -19896,7 +20229,7 @@ async function createServer(opts) {
19896
20229
  ...inspectOpts,
19897
20230
  config: opts.config
19898
20231
  }).then(() => {
19899
- const finished = opts.db.select({ status: runs.status }).from(runs).where(eq31(runs.id, runId)).get();
20232
+ const finished = opts.db.select({ status: runs.status }).from(runs).where(eq32(runs.id, runId)).get();
19900
20233
  if (finished?.status === RunStatuses.completed || finished?.status === RunStatuses.partial) {
19901
20234
  return maybeRefreshGscCoverage(
19902
20235
  opts.db,
@@ -20365,6 +20698,7 @@ async function createServer(opts) {
20365
20698
  },
20366
20699
  notify: (projectId, result) => notifier.onSiteLivenessChecked(projectId, result)
20367
20700
  });
20701
+ stopReviewDeliveries = startReviewDeliveryLoop(() => notifier.drainDueReviewDeliveries());
20368
20702
  stopProviderBatchPoller = startProviderBatchPoller({ db: opts.db, registry, runner: jobRunner });
20369
20703
  if (!embed.enabled) {
20370
20704
  stopInstallState = startInstallStateTelemetry({
@@ -20374,7 +20708,7 @@ async function createServer(opts) {
20374
20708
  isBacklinksInstalled: () => isDuckdbInstalled()
20375
20709
  });
20376
20710
  }
20377
- for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq31(researchRuns.status, ResearchRunStatuses.queued)).all()) {
20711
+ for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq32(researchRuns.status, ResearchRunStatuses.queued)).all()) {
20378
20712
  dispatchResearchRun(run.id, run.projectId, OutcomeTriggers.startup);
20379
20713
  }
20380
20714
  runtimeStartupSettled = true;
@@ -20389,6 +20723,8 @@ async function createServer(opts) {
20389
20723
  stopLogCapture();
20390
20724
  stopSiteLiveness?.();
20391
20725
  stopSiteLiveness = null;
20726
+ stopReviewDeliveries?.();
20727
+ stopReviewDeliveries = null;
20392
20728
  stopProviderBatchPoller?.();
20393
20729
  stopProviderBatchPoller = null;
20394
20730
  stopInstallState?.();