@canonry/canonry 7.122.0 → 7.123.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/assets/agent-workspace/skills/aero/SKILL.md +6 -4
  2. package/assets/agent-workspace/skills/aero/references/orchestration.md +2 -2
  3. package/assets/agent-workspace/skills/aero/references/reporting.md +1 -1
  4. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +4 -3
  5. package/assets/assets/{AccessControls-CUyRn6C4.js → AccessControls-qKt0MIwz.js} +2 -2
  6. package/assets/assets/{AgentSetupPage-DZpC1KEN.js → AgentSetupPage-CS6TAG_q.js} +4 -4
  7. package/assets/assets/{AuditHistoryPanel--uz8Pwrq.js → AuditHistoryPanel-C9muxa5U.js} +1 -1
  8. package/assets/assets/{BacklinksPage-CO95Zmi-.js → BacklinksPage-YSi04rze.js} +1 -1
  9. package/assets/assets/{ChartPrimitives-Cs6yrwNk.js → ChartPrimitives-DA5ldw5q.js} +1 -1
  10. package/assets/assets/{HistoryPage-jJE-3Cp-.js → HistoryPage-tTCABHZr.js} +1 -1
  11. package/assets/assets/MeasurementPropertyPage-B-eHRFSF.js +4 -0
  12. package/assets/assets/ProjectPage-DK7y3uMN.js +15 -0
  13. package/assets/assets/{RunsPage-BSc3AZzW.js → RunsPage-B6HxjqFp.js} +1 -1
  14. package/assets/assets/{ServerTrafficSection-DVCQnnCe.js → ServerTrafficSection-BCPF6Rxk.js} +3 -3
  15. package/assets/assets/{SettingsPage-Cx3ChDuH.js → SettingsPage-Dlsqc0Xk.js} +1 -1
  16. package/assets/assets/{ToneBadge-D_99MaKo.js → ToneBadge-BekCDc9B.js} +2 -2
  17. package/assets/assets/{TrafficPage-4lFwcOoT.js → TrafficPage-CcZ2VKWS.js} +1 -1
  18. package/assets/assets/{TrafficSourceDetailPage-BEjZCkMr.js → TrafficSourceDetailPage-BUWRBlEj.js} +1 -1
  19. package/assets/assets/{account-context-DHwkScAb.js → account-context-CTgTl_U3.js} +1 -1
  20. package/assets/assets/{agent-trust-copy-B2DSn_wB.js → agent-trust-copy-C3Su6oTh.js} +1 -1
  21. package/assets/assets/{card-DsNIE4Gq.js → card-fF4DLMtN.js} +1 -1
  22. package/assets/assets/index-CZK8ELxf.js +43 -0
  23. package/assets/assets/index-ODrMZLgB.css +1 -0
  24. package/assets/assets/{preload-helper-BHfj17NS.js → preload-helper-D6vLhNAZ.js} +1 -1
  25. package/assets/assets/{query-client-DmL4VdXj.js → query-client-bLCsQvmN.js} +1 -1
  26. package/assets/assets/react-query-DPn84_Mu.js +1 -0
  27. package/assets/assets/{react-sigma_core.esm.min-CE7yMg4d.js → react-sigma_core.esm.min-Dkaqqban.js} +1 -1
  28. package/assets/assets/{server-traffic-CiJh_mR4.js → server-traffic-CCdnHKbu.js} +1 -1
  29. package/assets/assets/{service-Ck0xuYS9.js → service-CUnyHRGl.js} +1 -1
  30. package/assets/index.html +10 -10
  31. package/dist/activity-NEHRLN66.js +13 -0
  32. package/dist/{ads-RVWK3WOT.js → ads-OXZFLKFO.js} +4 -4
  33. package/dist/{agent-OSSTIYD5.js → agent-VMLMGUVU.js} +8 -8
  34. package/dist/{agent-ask-2SPA6RIE.js → agent-ask-IGL7KSBW.js} +4 -4
  35. package/dist/{agent-conversations-36UMFQY6.js → agent-conversations-ZQQJTVLM.js} +4 -4
  36. package/dist/{agent-journeys-TW2CF6JI.js → agent-journeys-Z3ZILTRB.js} +4 -4
  37. package/dist/{agent-memory-GD2X65LE.js → agent-memory-MEFTNQWG.js} +4 -4
  38. package/dist/{agent-providers-A4E2TUJ7.js → agent-providers-ZZ6RN4TB.js} +4 -4
  39. package/dist/{agent-transcript-JLHXL72N.js → agent-transcript-QK3OTZ7B.js} +4 -4
  40. package/dist/{analytics-BZ7FJTK4.js → analytics-VAJT24GQ.js} +4 -4
  41. package/dist/{apply-BJDXDQXK.js → apply-IWCME5ZF.js} +4 -4
  42. package/dist/{backfill-F2OC7F22.js → backfill-WGEXXMFQ.js} +11 -11
  43. package/dist/{backlinks-IGSJG4TC.js → backlinks-QVFDZZCI.js} +4 -4
  44. package/dist/{bing-HHWCD5QU.js → bing-JUCW5FTY.js} +4 -4
  45. package/dist/{bootstrap-5LOT7HNU.js → bootstrap-R2O2TPAR.js} +11 -11
  46. package/dist/{cdp-5XNSVSBE.js → cdp-VTQYZVW5.js} +8 -8
  47. package/dist/chunk-2DT55UKG.js +34 -0
  48. package/dist/{chunk-HGXAKSRX.js → chunk-2J6LXZPK.js} +1 -1
  49. package/dist/{chunk-3LJH6WL6.js → chunk-2RG6CSZB.js} +1 -1
  50. package/dist/{chunk-WKYQ7255.js → chunk-6URM26ZP.js} +2 -2
  51. package/dist/{chunk-UYRC244Y.js → chunk-73AQQAPC.js} +403 -294
  52. package/dist/{chunk-NGTWSJSP.js → chunk-7D735WS6.js} +1 -1
  53. package/dist/{chunk-VXBYTMSM.js → chunk-7KQESJWH.js} +118 -37
  54. package/dist/{chunk-T3HVXCOW.js → chunk-7OYOUVZS.js} +382 -370
  55. package/dist/{chunk-SPNDMTXM.js → chunk-AUMR4UXI.js} +18 -5
  56. package/dist/{chunk-3CT756HO.js → chunk-BNL3BKXK.js} +1 -1
  57. package/dist/{chunk-F5UUN6UB.js → chunk-BSUAO3RJ.js} +1 -1
  58. package/dist/{chunk-RVRQJ2SA.js → chunk-BVJUYSOB.js} +2 -2
  59. package/dist/{chunk-X2WJ563G.js → chunk-CCBFBQFR.js} +3 -3
  60. package/dist/{chunk-QE3PIF67.js → chunk-CQSLBPR2.js} +8 -8
  61. package/dist/{chunk-REDBG2JO.js → chunk-DLJAUCAU.js} +5 -5
  62. package/dist/{chunk-ZA44DK2O.js → chunk-DMFFERXC.js} +1 -1
  63. package/dist/{chunk-XDCXC6DL.js → chunk-F3PBATIZ.js} +1 -1
  64. package/dist/{chunk-EGH7MBFI.js → chunk-F3UXTYXA.js} +4 -4
  65. package/dist/{chunk-S6GBOBNO.js → chunk-HSYZCNXY.js} +2 -2
  66. package/dist/{chunk-TH6JFDUI.js → chunk-LGD3K4G5.js} +4 -4
  67. package/dist/{chunk-LNBJ3ZEK.js → chunk-LQGTGSA5.js} +16 -3
  68. package/dist/{chunk-BB2KXNOG.js → chunk-LWGO6ETW.js} +2 -2
  69. package/dist/{chunk-NJTIZSBH.js → chunk-NDVKLJXW.js} +5 -5
  70. package/dist/{chunk-G56TRFKC.js → chunk-NI5THOYW.js} +6 -6
  71. package/dist/{chunk-HVE7FL2B.js → chunk-NNJ6PD64.js} +4 -4
  72. package/dist/{chunk-LJ3MSVVW.js → chunk-NZOLX55S.js} +1 -1
  73. package/dist/{chunk-LZSY5GNZ.js → chunk-OCL6NZGL.js} +2 -2
  74. package/dist/{chunk-QFPQIPX3.js → chunk-QXUNANMR.js} +2 -2
  75. package/dist/{chunk-NZQWQK4N.js → chunk-RHH2K4BZ.js} +8 -4
  76. package/dist/{chunk-YETOLZWJ.js → chunk-SLHX5HBD.js} +4 -4
  77. package/dist/{chunk-D4G3FP7N.js → chunk-TSCCU54X.js} +5 -5
  78. package/dist/{chunk-M2OSHVTB.js → chunk-TTK6ZZHK.js} +2 -2
  79. package/dist/{chunk-AYXUCVYX.js → chunk-WRWTDHSO.js} +625 -567
  80. package/dist/{chunk-E6WLCHXT.js → chunk-XXSDKDKU.js} +4 -4
  81. package/dist/{chunk-CCFEMZI5.js → chunk-YWLJQ2FY.js} +1 -1
  82. package/dist/{chunk-IQGRGJFP.js → chunk-YXM6FPGD.js} +1 -1
  83. package/dist/{chunk-RHWKLRLF.js → chunk-Z6ZH7N6U.js} +3 -3
  84. package/dist/{chunk-TAFIB6LC.js → chunk-ZP6PZZAW.js} +3 -2
  85. package/dist/{citations-BJKMX32Y.js → citations-HQQQM73E.js} +5 -5
  86. package/dist/{cli-catalog-VK4DK55E.js → cli-catalog-STHVOXXT.js} +4 -4
  87. package/dist/cli-commands-KWRHN6M5.js +18 -0
  88. package/dist/cli.js +14 -14
  89. package/dist/{competitor-ONXSUUEJ.js → competitor-VP52MSQM.js} +4 -4
  90. package/dist/{content-U276NS4F.js → content-IHFS2BRF.js} +4 -4
  91. package/dist/{dashboard-SVYP4JIF.js → dashboard-2DBFBHAU.js} +7 -7
  92. package/dist/{demo-CJEZXMD7.js → demo-UFZBEKZC.js} +3 -3
  93. package/dist/{demo-server-ASS76Y3T.js → demo-server-3YTYVGJU.js} +15 -13
  94. package/dist/{discover-O6MXXTQP.js → discover-X2RATQCF.js} +5 -5
  95. package/dist/{discover-eval-RWCDKTW2.js → discover-eval-FEQ3HAM2.js} +4 -4
  96. package/dist/{doctor-LDHRSYBN.js → doctor-2CM5FVMJ.js} +4 -4
  97. package/dist/{evidence-HCQ3XGR3.js → evidence-5IAVY6JN.js} +4 -4
  98. package/dist/{export-cmd-FCD27XDA.js → export-cmd-LGXY4GIT.js} +4 -4
  99. package/dist/{ga-DNE32K5T.js → ga-KVFZSSFH.js} +4 -4
  100. package/dist/{gbp-BD6N5ZNR.js → gbp-PLSX7QBV.js} +4 -4
  101. package/dist/{google-JGLRBRDJ.js → google-R7HNCZNY.js} +5 -5
  102. package/dist/{google-marketing-VGDUCHDK.js → google-marketing-ZEU6ZNTS.js} +2 -2
  103. package/dist/{health-cmd-SSUFVJXH.js → health-cmd-UNYQIHHZ.js} +5 -5
  104. package/dist/{history-FPNPI3FR.js → history-IR234HUF.js} +4 -4
  105. package/dist/index.d.ts +8 -8
  106. package/dist/index.js +26 -26
  107. package/dist/{init-LE67AJR6.js → init-IZ3ANN2I.js} +13 -13
  108. package/dist/{insights-JXWPCIKX.js → insights-OQ4TYD7O.js} +4 -4
  109. package/dist/intelligence-service-A6B7TKOX.js +15 -0
  110. package/dist/{journeys-ULUM5VHN.js → journeys-G72GTTDS.js} +4 -4
  111. package/dist/{keys-K7LFSZEV.js → keys-A2NSFAJR.js} +4 -4
  112. package/dist/{keyword-FEVMF4GU.js → keyword-4ECZAEFL.js} +4 -4
  113. package/dist/{logs-IFSEC6EG.js → logs-OMBVVMGA.js} +4 -4
  114. package/dist/{mcp-GEHAKVJQ.js → mcp-OALO7GAG.js} +5 -5
  115. package/dist/mcp.js +10 -10
  116. package/dist/{measurement-plan-P3VN75M2.js → measurement-plan-3KJSVBMM.js} +6 -6
  117. package/dist/{notify-J4FVK5NC.js → notify-AYBCSPXF.js} +4 -4
  118. package/dist/{organic-evidence-X53DBTMQ.js → organic-evidence-XMS6WPCR.js} +4 -4
  119. package/dist/{overview-F3LYI5W4.js → overview-K4RBEW7T.js} +52 -29
  120. package/dist/{project-RXT5IJKZ.js → project-KGIYKLEE.js} +4 -4
  121. package/dist/{project-setup-ATO24GGB.js → project-setup-OBS4PSB4.js} +4 -4
  122. package/dist/{query-LGPJDI56.js → query-TJAMHSAJ.js} +4 -4
  123. package/dist/{research-BHOCLEHN.js → research-REDM6KKM.js} +4 -4
  124. package/dist/{results-export-PFKBOBPA.js → results-export-E7P2G3FV.js} +4 -4
  125. package/dist/{run-ASLSXRUQ.js → run-43C6BWTO.js} +6 -6
  126. package/dist/{schedule-SQOLIVNL.js → schedule-B4TSMTC4.js} +4 -4
  127. package/dist/{search-3ZHHJHIN.js → search-VE7DGSD7.js} +4 -4
  128. package/dist/{serve-VOZCS346.js → serve-365C4I42.js} +27 -27
  129. package/dist/{session-KZJB4SN3.js → session-ZB2BI6VG.js} +14 -14
  130. package/dist/{settings-JOPGFAZS.js → settings-W3SCNC25.js} +4 -4
  131. package/dist/{sitemaps-AAEYPCF3.js → sitemaps-YPD7U2ZP.js} +4 -4
  132. package/dist/{skills-IWK7KYBF.js → skills-K6BM2BQV.js} +3 -3
  133. package/dist/{snapshot-N45FCZO3.js → snapshot-GK6G72YF.js} +4 -4
  134. package/dist/{src-D5YFNRUG.js → src-RUWMU4ZS.js} +2 -2
  135. package/dist/{status-O4GQAJV5.js → status-I23DTMWM.js} +6 -6
  136. package/dist/{support-RNNKG6QY.js → support-PEI7R4MY.js} +2 -2
  137. package/dist/{technical-aeo-IMGI4ST7.js → technical-aeo-W5ZF2TPH.js} +4 -4
  138. package/dist/{telemetry-ELCKZQGI.js → telemetry-YV6IHYS7.js} +5 -5
  139. package/dist/{tools-7NYNPJTI.js → tools-57J55S4A.js} +12 -12
  140. package/dist/{traffic-NJ476WXB.js → traffic-SQ4O6QW6.js} +6 -6
  141. package/dist/{trends-ULBZCMKS.js → trends-MCDIYFQB.js} +4 -4
  142. package/dist/{users-TFQRXDHF.js → users-R66ASOSH.js} +4 -4
  143. package/dist/{visibility-stats-Q3F5ORLR.js → visibility-stats-7XTGKFPE.js} +5 -5
  144. package/dist/{wordpress-JPDUJ7ZW.js → wordpress-ZMNF2C2H.js} +4 -4
  145. package/package.json +1 -1
  146. package/assets/assets/MeasurementPropertyPage-DVFgfLBE.js +0 -4
  147. package/assets/assets/ProjectPage-BUMmtHvg.js +0 -15
  148. package/assets/assets/index-BBPDLDlS.js +0 -43
  149. package/assets/assets/index-Dr7ccjP_.css +0 -1
  150. package/assets/assets/react-query-ss3hNF7i.js +0 -1
  151. package/dist/cli-commands-7AIQBJRW.js +0 -18
  152. package/dist/intelligence-service-XCADQRDI.js +0 -15
@@ -24,21 +24,21 @@ import {
24
24
  resolveConfiguredAgentProvider,
25
25
  resolveSessionProviderAndModel,
26
26
  setAeroSystemPrompt
27
- } from "./chunk-G56TRFKC.js";
28
- import {
29
- answerServiceAdapters,
30
- answerServiceDescriptors
31
- } from "./chunk-NGTWSJSP.js";
32
- import {
33
- isManagedCanonryInstall
34
- } from "./chunk-XAJS5FH3.js";
27
+ } from "./chunk-NI5THOYW.js";
35
28
  import {
36
29
  AeroToolProfiles,
37
30
  AeroToolScopes,
38
31
  buildAeroStateTools,
39
32
  isAeroToolProfile,
40
33
  truncateToolResult
41
- } from "./chunk-NJTIZSBH.js";
34
+ } from "./chunk-NDVKLJXW.js";
35
+ import {
36
+ answerServiceAdapters,
37
+ answerServiceDescriptors
38
+ } from "./chunk-7D735WS6.js";
39
+ import {
40
+ isManagedCanonryInstall
41
+ } from "./chunk-XAJS5FH3.js";
42
42
  import {
43
43
  getGoogleAuthConfig,
44
44
  getGoogleConnection,
@@ -57,7 +57,7 @@ import {
57
57
  removeCloudflareTrafficConnection,
58
58
  removeCloudflareTrafficConnectionBySourceId,
59
59
  upsertCloudflareTrafficConnection
60
- } from "./chunk-3CT756HO.js";
60
+ } from "./chunk-BNL3BKXK.js";
61
61
  import {
62
62
  claudeAdapter,
63
63
  embedQueries,
@@ -69,7 +69,7 @@ import {
69
69
  openrouterAdapter,
70
70
  perplexityAdapter,
71
71
  startTrafficReclassification
72
- } from "./chunk-D4G3FP7N.js";
72
+ } from "./chunk-TSCCU54X.js";
73
73
  import {
74
74
  classifyUsageSurface,
75
75
  createApiUsageTelemetry,
@@ -81,7 +81,7 @@ import {
81
81
  startOutcomeTimer,
82
82
  trackFeatureCompleted,
83
83
  trackInstallState
84
- } from "./chunk-E6WLCHXT.js";
84
+ } from "./chunk-XXSDKDKU.js";
85
85
  import {
86
86
  isLoopbackBindHost
87
87
  } from "./chunk-TSENU4GG.js";
@@ -89,7 +89,7 @@ import {
89
89
  isApiProviderRegistrable,
90
90
  isCdpProviderRegistrable,
91
91
  registeredProviderNames
92
- } from "./chunk-F5UUN6UB.js";
92
+ } from "./chunk-BSUAO3RJ.js";
93
93
  import {
94
94
  checkLatestVersionForServer,
95
95
  getOrCreateAnonymousId,
@@ -101,17 +101,17 @@ import {
101
101
  recordDashboardEvent,
102
102
  setTelemetryPreference,
103
103
  trackEvent
104
- } from "./chunk-LZSY5GNZ.js";
104
+ } from "./chunk-OCL6NZGL.js";
105
105
  import {
106
106
  createCanonryMcpServer
107
- } from "./chunk-EGH7MBFI.js";
107
+ } from "./chunk-F3UXTYXA.js";
108
108
  import {
109
109
  CANONRY_MCP_TIERS,
110
110
  CANONRY_MCP_TOOLKIT_NAMES
111
111
  } from "./chunk-XXKC266R.js";
112
112
  import {
113
113
  ApiClient
114
- } from "./chunk-LNBJ3ZEK.js";
114
+ } from "./chunk-LQGTGSA5.js";
115
115
  import {
116
116
  AGENT_PROVIDERS,
117
117
  PROVIDER_MODELS,
@@ -146,40 +146,41 @@ import {
146
146
  saveConfigPatch,
147
147
  sentimentInstallReadiness,
148
148
  updateSharedProviderExecutionGate
149
- } from "./chunk-WKYQ7255.js";
149
+ } from "./chunk-6URM26ZP.js";
150
150
  import {
151
151
  getBundledSkillSnapshots
152
- } from "./chunk-RVRQJ2SA.js";
152
+ } from "./chunk-BVJUYSOB.js";
153
153
  import {
154
154
  computeFactorAverages,
155
155
  deleteSiteCrawlGraphLayout,
156
156
  persistSiteCrawlGraphLayout,
157
157
  prepareSiteCrawlGraphLayout,
158
158
  recordedSharePct
159
- } from "./chunk-M2OSHVTB.js";
159
+ } from "./chunk-TTK6ZZHK.js";
160
160
  import {
161
161
  CanonryMcpToolNames,
162
162
  canonryMcpTools
163
- } from "./chunk-SPNDMTXM.js";
163
+ } from "./chunk-AUMR4UXI.js";
164
164
  import {
165
165
  PACKAGE_VERSION
166
166
  } from "./chunk-AOJU5LKX.js";
167
167
  import {
168
168
  CliError
169
- } from "./chunk-ZA44DK2O.js";
169
+ } from "./chunk-DMFFERXC.js";
170
170
  import {
171
171
  IntelligenceService
172
- } from "./chunk-REDBG2JO.js";
172
+ } from "./chunk-DLJAUCAU.js";
173
173
  import {
174
174
  computeCitedCompetitorDomains,
175
175
  determineCitationState
176
- } from "./chunk-3LJH6WL6.js";
176
+ } from "./chunk-2RG6CSZB.js";
177
177
  import {
178
178
  addLogListener,
179
179
  createFastifyLogger,
180
180
  createLogger
181
- } from "./chunk-BB2KXNOG.js";
181
+ } from "./chunk-LWGO6ETW.js";
182
182
  import {
183
+ BING_THROTTLE_COOLDOWN_MS,
183
184
  BingApiError,
184
185
  CC_CACHE_DIR,
185
186
  ChatGptAccounts,
@@ -211,6 +212,7 @@ import {
211
212
  bingDateToDay,
212
213
  bingKeywordMarket,
213
214
  bingPositionOrNull,
215
+ bingThrottleCooldownRemainingMs,
214
216
  blockedAddressReason,
215
217
  buildLocationProfileFields,
216
218
  captureSimpleMeasurementDefinition,
@@ -332,7 +334,7 @@ import {
332
334
  webhookTargetRefusalReason,
333
335
  webhookUserAgent,
334
336
  writeAuditLog
335
- } from "./chunk-VXBYTMSM.js";
337
+ } from "./chunk-7KQESJWH.js";
336
338
  import {
337
339
  OperationalLogStore,
338
340
  SentimentIdempotencyConflict,
@@ -434,7 +436,7 @@ import {
434
436
  unrecognizedAgentEventsHourly,
435
437
  unrecognizedAgentNotifyState,
436
438
  usageCounters
437
- } from "./chunk-LJ3MSVVW.js";
439
+ } from "./chunk-NZOLX55S.js";
438
440
  import {
439
441
  AGENT_MEMORY_VALUE_MAX_BYTES,
440
442
  AI_ENGINE_DOMAINS,
@@ -717,7 +719,7 @@ import {
717
719
  winnabilityClassLabel,
718
720
  withRetry,
719
721
  withSkippedProviders
720
- } from "./chunk-UYRC244Y.js";
722
+ } from "./chunk-73AQQAPC.js";
721
723
 
722
724
  // src/google-marketing-runtime.ts
723
725
  import crypto2 from "crypto";
@@ -3407,7 +3409,7 @@ import path6 from "path";
3407
3409
  import { isIP as isIP2 } from "net";
3408
3410
  import { fileURLToPath } from "url";
3409
3411
  import { setImmediate as yieldToEventLoop4 } from "timers/promises";
3410
- import { and as and33, eq as eq39, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql16 } from "drizzle-orm";
3412
+ import { and as and33, eq as eq40, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql16 } from "drizzle-orm";
3411
3413
 
3412
3414
  // src/seo-runtime.ts
3413
3415
  import { eq, inArray } from "drizzle-orm";
@@ -6469,7 +6471,7 @@ function nonBlank(value) {
6469
6471
  return trimmed ? trimmed : void 0;
6470
6472
  }
6471
6473
  function resolveBuildCommit(env = process.env) {
6472
- const embedded = true ? "8225094f5eeb8e00d8cc2be4a64ebf040325462c" : void 0;
6474
+ const embedded = true ? "91d25b44bae8ffb4644c4890c5270d3fefa0ecb6" : void 0;
6473
6475
  return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
6474
6476
  }
6475
6477
  function resolveInstanceIdentity(env = process.env) {
@@ -11273,6 +11275,7 @@ function bingRunFailure(err) {
11273
11275
  return runFailure(err, err instanceof BingApiError && err.isThrottle ? OutcomeReasonCodes.RATE_LIMITED : void 0);
11274
11276
  }
11275
11277
  var BING_INSPECT_SPACING_MS = 2e3;
11278
+ var BING_INSPECT_RUN_MAX_URLS = 20;
11276
11279
  async function executeBingInspectSitemap(db, runId, projectId, opts) {
11277
11280
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.bing, "inspect");
11278
11281
  let abortCause;
@@ -11347,20 +11350,17 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11347
11350
  if (err instanceof BingApiError && err.isThrottle) throw err;
11348
11351
  blockedUrls = /* @__PURE__ */ new Set();
11349
11352
  }
11350
- const skipped = Math.max(0, sitemapUrls.length - INSPECT_SWEEP_MAX_URLS);
11351
11353
  const dueUrls = [...sitemapUrls].sort((a, b) => (lastInspected.get(a) ?? "").localeCompare(lastInspected.get(b) ?? ""));
11352
- const targetUrls = dueUrls.slice(0, INSPECT_SWEEP_MAX_URLS);
11353
- if (skipped > 0) {
11354
- log10.warn("sitemap.over-budget", {
11355
- runId,
11356
- projectId,
11357
- sitemapUrls: sitemapUrls.length,
11358
- inspecting: targetUrls.length,
11359
- skipped,
11360
- dailyQuota: INSPECT_DAILY_QUOTA,
11361
- note: `Sitemap has ${sitemapUrls.length} pages; inspecting the ${targetUrls.length} least recently inspected. ${skipped} pages will not have a verdict from this run.`
11362
- });
11363
- }
11354
+ const targetUrls = dueUrls.slice(0, BING_INSPECT_RUN_MAX_URLS);
11355
+ const rotated = sitemapUrls.length - targetUrls.length;
11356
+ log10.info("inspect.batch", {
11357
+ runId,
11358
+ projectId,
11359
+ sitemapUrls: sitemapUrls.length,
11360
+ inspecting: targetUrls.length,
11361
+ neverInspected: discovered.length,
11362
+ rotated
11363
+ });
11364
11364
  const siteUrl = conn.siteUrl;
11365
11365
  let lastInspectError;
11366
11366
  let lastInspectFailurePhase;
@@ -11499,8 +11499,8 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11499
11499
  syncRunId: runId
11500
11500
  }
11501
11501
  }).run();
11502
- const status = errors > 0 || outcome.aborted || skipped > 0 ? RunStatuses.partial : RunStatuses.completed;
11503
- const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped after provider failures; ${total - inspected} of ${total} pages were not inspected (${total - inspected - errors} not attempted).` : skipped > 0 ? `${total - inspected} of ${total} pages were not inspected in this run (${skipped} deferred by the per-run budget; ${errors} failed).` : `${errors} of ${targetUrls.length} pages could not be inspected.`;
11502
+ const status = errors > 0 || outcome.aborted ? RunStatuses.partial : RunStatuses.completed;
11503
+ const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped after provider failures; ${targetUrls.length - inspected} of ${targetUrls.length} pages in this run's batch were not inspected (${targetUrls.length - inspected - errors} not attempted).` : `${errors} of ${targetUrls.length} pages could not be inspected.`;
11504
11504
  db.update(runs).set({ status, error: degradedReason, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq13(runs.id, runId)).run();
11505
11505
  log10.info("inspect.completed", {
11506
11506
  runId,
@@ -12010,10 +12010,58 @@ async function executeBingSync(db, runId, projectId, opts) {
12010
12010
  }
12011
12011
  }
12012
12012
 
12013
+ // src/bing-job-lane.ts
12014
+ import { eq as eq15 } from "drizzle-orm";
12015
+ var log12 = createLogger("BingJobLane");
12016
+ var BING_LANE_MAX_COOLDOWN_WAIT_MS = BING_THROTTLE_COOLDOWN_MS + 6e4;
12017
+ var lanes = /* @__PURE__ */ new Map();
12018
+ function acquire(key, kind) {
12019
+ const lane = lanes.get(key);
12020
+ if (!lane) {
12021
+ lanes.set(key, { waiting: [] });
12022
+ return Promise.resolve();
12023
+ }
12024
+ log12.info("lane.wait", { kind, ahead: lane.waiting.length + 1 });
12025
+ return new Promise((start) => lane.waiting.push({ kind, start }));
12026
+ }
12027
+ function release(key) {
12028
+ const lane = lanes.get(key);
12029
+ if (!lane) return;
12030
+ const syncIndex = lane.waiting.findIndex((waiter) => waiter.kind === "sync");
12031
+ const next = syncIndex >= 0 ? lane.waiting.splice(syncIndex, 1)[0] : lane.waiting.shift();
12032
+ if (next) next.start();
12033
+ else lanes.delete(key);
12034
+ }
12035
+ var realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12036
+ async function runInBingLane(apiKey, kind, work, deps = {}) {
12037
+ const key = credentialGateKey("bing", apiKey);
12038
+ await acquire(key, kind);
12039
+ try {
12040
+ const cooling = bingThrottleCooldownRemainingMs(apiKey);
12041
+ if (cooling > 0) {
12042
+ const waitMs = Math.min(cooling, BING_LANE_MAX_COOLDOWN_WAIT_MS);
12043
+ log12.info("lane.cooldown-wait", { kind, waitMs });
12044
+ await (deps.sleep ?? realSleep)(waitMs);
12045
+ }
12046
+ return await work();
12047
+ } finally {
12048
+ release(key);
12049
+ }
12050
+ }
12051
+ function bingApiKeyForProject(db, config, projectId) {
12052
+ const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq15(projects.id, projectId)).get();
12053
+ if (!project) return null;
12054
+ return config.bing?.connections?.find((conn) => conn.domain === project.canonicalDomain)?.apiKey ?? null;
12055
+ }
12056
+ async function runBingJob(db, config, projectId, kind, work, deps = {}) {
12057
+ const apiKey = bingApiKeyForProject(db, config, projectId);
12058
+ return apiKey ? await runInBingLane(apiKey, kind, work, deps) : await work();
12059
+ }
12060
+
12013
12061
  // src/coverage-refresh.ts
12014
12062
  import crypto18 from "crypto";
12015
- import { and as and11, desc as desc6, eq as eq15, inArray as inArray7 } from "drizzle-orm";
12016
- var log12 = createLogger("CoverageRefresh");
12063
+ import { and as and11, desc as desc6, eq as eq16, inArray as inArray7 } from "drizzle-orm";
12064
+ var log13 = createLogger("CoverageRefresh");
12017
12065
  var COVERAGE_REFRESH_MIN_INTERVAL_MS = 60 * 60 * 1e3;
12018
12066
  var COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS = 2 * 60 * 1e3;
12019
12067
  var ACTIVE_OR_DONE_STATUSES = [
@@ -12024,12 +12072,12 @@ var ACTIVE_OR_DONE_STATUSES = [
12024
12072
  ];
12025
12073
  var IN_FLIGHT_STATUSES = [RunStatuses.queued, RunStatuses.running];
12026
12074
  function runWasUserInitiated(db, runId) {
12027
- const row = db.select({ trigger: runs.trigger }).from(runs).where(eq15(runs.id, runId)).get();
12075
+ const row = db.select({ trigger: runs.trigger }).from(runs).where(eq16(runs.id, runId)).get();
12028
12076
  return row?.trigger === RunTriggers.manual;
12029
12077
  }
12030
12078
  var defaultDeps = { executeInspectSitemap };
12031
12079
  async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps, nowMs = Date.now(), opts = {}) {
12032
- const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq15(projects.id, projectId)).get();
12080
+ const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq16(projects.id, projectId)).get();
12033
12081
  if (!project) return null;
12034
12082
  const { clientId, clientSecret } = getGoogleAuthConfig(config);
12035
12083
  if (!clientId || !clientSecret) return null;
@@ -12037,27 +12085,27 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
12037
12085
  if (!conn?.refreshToken || !conn.propertyId) return null;
12038
12086
  const inFlight = db.select({ createdAt: runs.createdAt }).from(runs).where(
12039
12087
  and11(
12040
- eq15(runs.projectId, projectId),
12041
- eq15(runs.kind, RunKinds["inspect-sitemap"]),
12088
+ eq16(runs.projectId, projectId),
12089
+ eq16(runs.kind, RunKinds["inspect-sitemap"]),
12042
12090
  inArray7(runs.status, IN_FLIGHT_STATUSES)
12043
12091
  )
12044
12092
  ).orderBy(desc6(runs.createdAt)).limit(1).get();
12045
12093
  if (inFlight) {
12046
- log12.info("skip.in-flight", { projectId });
12094
+ log13.info("skip.in-flight", { projectId });
12047
12095
  return null;
12048
12096
  }
12049
12097
  const windowMs = opts.userInitiated ? COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS : COVERAGE_REFRESH_MIN_INTERVAL_MS;
12050
12098
  const recent = db.select({ createdAt: runs.createdAt }).from(runs).where(
12051
12099
  and11(
12052
- eq15(runs.projectId, projectId),
12053
- eq15(runs.kind, RunKinds["inspect-sitemap"]),
12100
+ eq16(runs.projectId, projectId),
12101
+ eq16(runs.kind, RunKinds["inspect-sitemap"]),
12054
12102
  inArray7(runs.status, ACTIVE_OR_DONE_STATUSES)
12055
12103
  )
12056
12104
  ).orderBy(desc6(runs.createdAt)).limit(1).get();
12057
12105
  if (recent) {
12058
12106
  const ageMs = nowMs - Date.parse(recent.createdAt);
12059
12107
  if (Number.isFinite(ageMs) && ageMs < windowMs) {
12060
- log12.info("skip.recent", { projectId, ageMs, windowMs, userInitiated: opts.userInitiated === true });
12108
+ log13.info("skip.recent", { projectId, ageMs, windowMs, userInitiated: opts.userInitiated === true });
12061
12109
  return null;
12062
12110
  }
12063
12111
  }
@@ -12070,11 +12118,11 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
12070
12118
  trigger: RunTriggers.scheduled,
12071
12119
  createdAt: new Date(nowMs).toISOString()
12072
12120
  }).run();
12073
- log12.info("refresh.start", { projectId, runId });
12121
+ log13.info("refresh.start", { projectId, runId });
12074
12122
  try {
12075
12123
  await deps.executeInspectSitemap(db, runId, projectId, { config });
12076
12124
  } catch (err) {
12077
- log12.error("refresh.failed", {
12125
+ log13.error("refresh.failed", {
12078
12126
  projectId,
12079
12127
  runId,
12080
12128
  error: describeError(err)
@@ -12086,8 +12134,8 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
12086
12134
  // src/commoncrawl-sync.ts
12087
12135
  import crypto19 from "crypto";
12088
12136
  import path5 from "path";
12089
- import { and as and12, eq as eq16, sql as sql6 } from "drizzle-orm";
12090
- var log13 = createLogger("CommonCrawlSync");
12137
+ import { and as and12, eq as eq17, sql as sql6 } from "drizzle-orm";
12138
+ var log14 = createLogger("CommonCrawlSync");
12091
12139
  var INSERT_CHUNK_SIZE = 1e4;
12092
12140
  function defaultDeps2() {
12093
12141
  return {
@@ -12100,7 +12148,7 @@ function defaultDeps2() {
12100
12148
  }
12101
12149
  async function executeReleaseSync(db, syncId, opts) {
12102
12150
  const deps = { ...defaultDeps2(), ...opts.deps };
12103
- const release = opts.release;
12151
+ const release2 = opts.release;
12104
12152
  const outcome = {
12105
12153
  feature: "backlinks",
12106
12154
  operation: "sync",
@@ -12109,9 +12157,9 @@ async function executeReleaseSync(db, syncId, opts) {
12109
12157
  const elapsed = startOutcomeTimer();
12110
12158
  let invalidRelease = false;
12111
12159
  try {
12112
- if (!isValidReleaseId(release)) {
12160
+ if (!isValidReleaseId(release2)) {
12113
12161
  invalidRelease = true;
12114
- throw new Error(`Invalid release id: ${release}`);
12162
+ throw new Error(`Invalid release id: ${release2}`);
12115
12163
  }
12116
12164
  if (db.select({ id: projects.id }).from(projects).limit(1).get()) deps.loadDuckdb();
12117
12165
  const downloadStartedAt = deps.now().toISOString();
@@ -12121,9 +12169,9 @@ async function executeReleaseSync(db, syncId, opts) {
12121
12169
  phaseDetail: "downloading vertices + edges",
12122
12170
  updatedAt: downloadStartedAt,
12123
12171
  error: null
12124
- }).where(eq16(ccReleaseSyncs.id, syncId)).run();
12125
- const paths = ccReleasePaths(release);
12126
- const releaseCacheDir = path5.join(deps.cacheDir, release);
12172
+ }).where(eq17(ccReleaseSyncs.id, syncId)).run();
12173
+ const paths = ccReleasePaths(release2);
12174
+ const releaseCacheDir = path5.join(deps.cacheDir, release2);
12127
12175
  const vertexPath = path5.join(releaseCacheDir, paths.vertexFilename);
12128
12176
  const edgesPath = path5.join(releaseCacheDir, paths.edgesFilename);
12129
12177
  const [vertex, edges] = await Promise.all([
@@ -12144,7 +12192,7 @@ async function executeReleaseSync(db, syncId, opts) {
12144
12192
  vertexSha256: vertex.sha256,
12145
12193
  edgesSha256: edges.sha256,
12146
12194
  updatedAt: downloadFinishedAt
12147
- }).where(eq16(ccReleaseSyncs.id, syncId)).run();
12195
+ }).where(eq17(ccReleaseSyncs.id, syncId)).run();
12148
12196
  const allProjects = db.select().from(projects).all();
12149
12197
  const targets = Array.from(new Set(allProjects.map((p) => p.canonicalDomain)));
12150
12198
  let rows = [];
@@ -12160,8 +12208,8 @@ async function executeReleaseSync(db, syncId, opts) {
12160
12208
  }
12161
12209
  const queriedAt = deps.now().toISOString();
12162
12210
  db.transaction((tx) => {
12163
- tx.delete(backlinkDomains).where(eq16(backlinkDomains.releaseSyncId, syncId)).run();
12164
- tx.delete(backlinkSummaries).where(eq16(backlinkSummaries.releaseSyncId, syncId)).run();
12211
+ tx.delete(backlinkDomains).where(eq17(backlinkDomains.releaseSyncId, syncId)).run();
12212
+ tx.delete(backlinkSummaries).where(eq17(backlinkSummaries.releaseSyncId, syncId)).run();
12165
12213
  const expanded = [];
12166
12214
  for (const r of rows) {
12167
12215
  const projectIds = projectsByDomain.get(r.targetDomain);
@@ -12171,7 +12219,7 @@ async function executeReleaseSync(db, syncId, opts) {
12171
12219
  id: crypto19.randomUUID(),
12172
12220
  projectId,
12173
12221
  releaseSyncId: syncId,
12174
- release,
12222
+ release: release2,
12175
12223
  targetDomain: r.targetDomain,
12176
12224
  linkingDomain: r.linkingDomain,
12177
12225
  numHosts: r.numHosts,
@@ -12192,7 +12240,7 @@ async function executeReleaseSync(db, syncId, opts) {
12192
12240
  projectId: p.id,
12193
12241
  releaseSyncId: syncId,
12194
12242
  source: BacklinkSources.commoncrawl,
12195
- release,
12243
+ release: release2,
12196
12244
  targetDomain: p.canonicalDomain,
12197
12245
  totalLinkingDomains: summary.totalLinkingDomains,
12198
12246
  totalHosts: summary.totalHosts,
@@ -12221,10 +12269,10 @@ async function executeReleaseSync(db, syncId, opts) {
12221
12269
  domainsDiscovered: rows.length,
12222
12270
  updatedAt: finishedAt,
12223
12271
  error: null
12224
- }).where(eq16(ccReleaseSyncs.id, syncId)).run();
12225
- log13.info("sync.completed", {
12272
+ }).where(eq17(ccReleaseSyncs.id, syncId)).run();
12273
+ log14.info("sync.completed", {
12226
12274
  syncId,
12227
- release,
12275
+ release: release2,
12228
12276
  projectsProcessed: allProjects.length,
12229
12277
  domainsDiscovered: rows.length
12230
12278
  });
@@ -12238,11 +12286,11 @@ async function executeReleaseSync(db, syncId, opts) {
12238
12286
  const autoExtractProjects = allProjects.filter((p) => p.autoExtractBacklinks);
12239
12287
  for (const p of autoExtractProjects) {
12240
12288
  try {
12241
- deps.enqueueAutoExtract({ projectId: p.id, release });
12289
+ deps.enqueueAutoExtract({ projectId: p.id, release: release2 });
12242
12290
  } catch (err) {
12243
- log13.error("auto-extract.enqueue-failed", {
12291
+ log14.error("auto-extract.enqueue-failed", {
12244
12292
  syncId,
12245
- release,
12293
+ release: release2,
12246
12294
  projectId: p.id,
12247
12295
  error: describeError(err)
12248
12296
  });
@@ -12257,8 +12305,8 @@ async function executeReleaseSync(db, syncId, opts) {
12257
12305
  error: errorMsg,
12258
12306
  phaseDetail: null,
12259
12307
  updatedAt: finishedAt
12260
- }).where(eq16(ccReleaseSyncs.id, syncId)).run();
12261
- log13.error("sync.failed", { syncId, release, error: errorMsg });
12308
+ }).where(eq17(ccReleaseSyncs.id, syncId)).run();
12309
+ log14.error("sync.failed", { syncId, release: release2, error: errorMsg });
12262
12310
  trackFeatureCompleted({
12263
12311
  ...outcome,
12264
12312
  status: OutcomeStatuses.failed,
@@ -12290,7 +12338,7 @@ async function syncLatestReleaseOnSchedule(projectName, deps) {
12290
12338
  if (probed === null) report({ status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_FOUND });
12291
12339
  return;
12292
12340
  }
12293
- const alreadySynced = deps.db.select().from(ccReleaseSyncs).where(and12(eq16(ccReleaseSyncs.release, probed.release), eq16(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready))).limit(1).get();
12341
+ const alreadySynced = deps.db.select().from(ccReleaseSyncs).where(and12(eq17(ccReleaseSyncs.release, probed.release), eq17(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready))).limit(1).get();
12294
12342
  if (alreadySynced) {
12295
12343
  deps.log.info({ projectName, release: probed.release }, "Scheduled backlinks sync: already up to date, skipping");
12296
12344
  report({ status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NOT_DUE });
@@ -12323,8 +12371,8 @@ function groupByProject(rows, projectsByDomain) {
12323
12371
  // src/backlink-extract.ts
12324
12372
  import crypto20 from "crypto";
12325
12373
  import fs5 from "fs";
12326
- import { and as and13, desc as desc7, eq as eq17 } from "drizzle-orm";
12327
- var log14 = createLogger("BacklinkExtract");
12374
+ import { and as and13, desc as desc7, eq as eq18 } from "drizzle-orm";
12375
+ var log15 = createLogger("BacklinkExtract");
12328
12376
  function defaultDeps3() {
12329
12377
  return {
12330
12378
  queryBacklinks,
@@ -12337,14 +12385,14 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12337
12385
  const startedAt = deps.now().toISOString();
12338
12386
  const reportOutcome = startRunOutcome(db, runId, "backlinks", "extract");
12339
12387
  let refusal;
12340
- db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq17(runs.id, runId)).run();
12388
+ db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq18(runs.id, runId)).run();
12341
12389
  try {
12342
- const project = db.select().from(projects).where(eq17(projects.id, projectId)).get();
12390
+ const project = db.select().from(projects).where(eq18(projects.id, projectId)).get();
12343
12391
  if (!project) {
12344
12392
  refusal = OutcomeReasonCodes.NOT_FOUND;
12345
12393
  throw new Error(`Project not found: ${projectId}`);
12346
12394
  }
12347
- const sync = opts.release ? db.select().from(ccReleaseSyncs).where(eq17(ccReleaseSyncs.release, opts.release)).get() : db.select().from(ccReleaseSyncs).where(eq17(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready)).orderBy(desc7(ccReleaseSyncs.createdAt)).limit(1).get();
12395
+ const sync = opts.release ? db.select().from(ccReleaseSyncs).where(eq18(ccReleaseSyncs.release, opts.release)).get() : db.select().from(ccReleaseSyncs).where(eq18(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready)).orderBy(desc7(ccReleaseSyncs.createdAt)).limit(1).get();
12348
12396
  refusal = OutcomeReasonCodes.NO_DATA;
12349
12397
  if (!sync) {
12350
12398
  throw new Error("No ready release sync available \u2014 run `canonry backlinks sync` first");
@@ -12370,14 +12418,14 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12370
12418
  });
12371
12419
  const queriedAt = deps.now().toISOString();
12372
12420
  const syncId = sync.id;
12373
- const release = sync.release;
12421
+ const release2 = sync.release;
12374
12422
  const targetDomain = project.canonicalDomain;
12375
12423
  db.transaction((tx) => {
12376
12424
  tx.delete(backlinkDomains).where(
12377
12425
  and13(
12378
- eq17(backlinkDomains.projectId, projectId),
12379
- eq17(backlinkDomains.source, BacklinkSources.commoncrawl),
12380
- eq17(backlinkDomains.release, release)
12426
+ eq18(backlinkDomains.projectId, projectId),
12427
+ eq18(backlinkDomains.source, BacklinkSources.commoncrawl),
12428
+ eq18(backlinkDomains.release, release2)
12381
12429
  )
12382
12430
  ).run();
12383
12431
  if (rows.length > 0) {
@@ -12386,7 +12434,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12386
12434
  projectId,
12387
12435
  releaseSyncId: syncId,
12388
12436
  source: BacklinkSources.commoncrawl,
12389
- release,
12437
+ release: release2,
12390
12438
  targetDomain,
12391
12439
  linkingDomain: r.linkingDomain,
12392
12440
  numHosts: r.numHosts,
@@ -12400,7 +12448,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12400
12448
  projectId,
12401
12449
  releaseSyncId: syncId,
12402
12450
  source: BacklinkSources.commoncrawl,
12403
- release,
12451
+ release: release2,
12404
12452
  targetDomain,
12405
12453
  totalLinkingDomains: summary2.totalLinkingDomains,
12406
12454
  totalHosts: summary2.totalHosts,
@@ -12420,8 +12468,8 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12420
12468
  }).run();
12421
12469
  });
12422
12470
  const finishedAt = deps.now().toISOString();
12423
- db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq17(runs.id, runId)).run();
12424
- log14.info("extract.completed", { runId, projectId, release, rows: rows.length });
12471
+ db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq18(runs.id, runId)).run();
12472
+ log15.info("extract.completed", { runId, projectId, release: release2, rows: rows.length });
12425
12473
  const summary = computeSummary(rows);
12426
12474
  reportOutcome({ status: OutcomeStatuses.succeeded, counts: { domains: summary.totalLinkingDomains, links: summary.totalHosts } });
12427
12475
  } catch (err) {
@@ -12431,8 +12479,8 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12431
12479
  status: RunStatuses.failed,
12432
12480
  error: errorMsg,
12433
12481
  finishedAt
12434
- }).where(eq17(runs.id, runId)).run();
12435
- log14.error("extract.failed", { runId, projectId, error: errorMsg });
12482
+ }).where(eq18(runs.id, runId)).run();
12483
+ log15.error("extract.failed", { runId, projectId, error: errorMsg });
12436
12484
  reportOutcome({ status: OutcomeStatuses.failed, ...outcomeFailure(err, refusal) });
12437
12485
  throw err;
12438
12486
  }
@@ -12443,8 +12491,8 @@ function computeSummary(rows) {
12443
12491
 
12444
12492
  // src/discovery-run.ts
12445
12493
  import crypto21 from "crypto";
12446
- import { and as and14, eq as eq18 } from "drizzle-orm";
12447
- var log15 = createLogger("DiscoveryRun");
12494
+ import { and as and14, eq as eq19 } from "drizzle-orm";
12495
+ var log16 = createLogger("DiscoveryRun");
12448
12496
  var DEFAULT_SEED_COUNT = 30;
12449
12497
  var EMBED_RETRY_MAX_RETRIES = 3;
12450
12498
  var EMBED_RETRY_MAX_DELAY_MS = 1e4;
@@ -12476,7 +12524,7 @@ async function embedWithRetry(fn) {
12476
12524
  isRetryable: isRetryableHttpError,
12477
12525
  maxDelayMs: EMBED_RETRY_MAX_DELAY_MS,
12478
12526
  onRetry: ({ attempt, delayMs }) => {
12479
- log15.warn("discovery.embed.retry", { attempt, delayMs });
12527
+ log16.warn("discovery.embed.retry", { attempt, delayMs });
12480
12528
  }
12481
12529
  }
12482
12530
  );
@@ -12486,11 +12534,11 @@ async function executeDiscoveryRun(opts) {
12486
12534
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
12487
12535
  const reportOutcome = startRunOutcome(opts.db, opts.runId, "discovery", "run");
12488
12536
  let notConfigured = false;
12489
- opts.db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq18(runs.id, opts.runId)).run();
12537
+ opts.db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq19(runs.id, opts.runId)).run();
12490
12538
  try {
12491
- const projectRow = opts.db.select().from(projects).where(eq18(projects.id, opts.projectId)).get();
12539
+ const projectRow = opts.db.select().from(projects).where(eq19(projects.id, opts.projectId)).get();
12492
12540
  if (!projectRow) throw new Error(`Project ${opts.projectId} not found`);
12493
- const projectCompetitors = opts.db.select({ domain: competitors.domain }).from(competitors).where(eq18(competitors.projectId, opts.projectId)).orderBy(competitors.domain).all().map((r) => r.domain.toLowerCase());
12541
+ const projectCompetitors = opts.db.select({ domain: competitors.domain }).from(competitors).where(eq19(competitors.projectId, opts.projectId)).orderBy(competitors.domain).all().map((r) => r.domain.toLowerCase());
12494
12542
  const canonicalDomains = effectiveDomains({
12495
12543
  canonicalDomain: projectRow.canonicalDomain,
12496
12544
  ownedDomains: projectRow.ownedDomains
@@ -12532,8 +12580,8 @@ async function executeDiscoveryRun(opts) {
12532
12580
  seedProvider: result.seedProvider,
12533
12581
  result
12534
12582
  });
12535
- opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq18(runs.id, opts.runId)).run();
12536
- log15.info("discovery.completed", {
12583
+ opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq19(runs.id, opts.runId)).run();
12584
+ log16.info("discovery.completed", {
12537
12585
  runId: opts.runId,
12538
12586
  sessionId: opts.sessionId,
12539
12587
  buckets: result.buckets,
@@ -12550,13 +12598,13 @@ async function executeDiscoveryRun(opts) {
12550
12598
  });
12551
12599
  } catch (err) {
12552
12600
  const errorMsg = describeError(err);
12553
- log15.error("discovery.failed", { runId: opts.runId, sessionId: opts.sessionId, error: errorMsg });
12601
+ log16.error("discovery.failed", { runId: opts.runId, sessionId: opts.sessionId, error: errorMsg });
12554
12602
  markSessionFailed(opts.db, opts.sessionId, errorMsg);
12555
12603
  opts.db.update(runs).set({
12556
12604
  status: RunStatuses.failed,
12557
12605
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
12558
12606
  error: errorMsg
12559
- }).where(eq18(runs.id, opts.runId)).run();
12607
+ }).where(eq19(runs.id, opts.runId)).run();
12560
12608
  const failure2 = classifyProviderOutcomeError(err);
12561
12609
  reportOutcome({
12562
12610
  status: OutcomeStatuses.failed,
@@ -12826,9 +12874,9 @@ function writeDiscoveryInsight(db, input) {
12826
12874
  });
12827
12875
  db.transaction((tx) => {
12828
12876
  tx.update(insights).set({ dismissed: true }).where(and14(
12829
- eq18(insights.projectId, input.projectId),
12830
- eq18(insights.type, "discovery.basket-divergence"),
12831
- eq18(insights.dismissed, false)
12877
+ eq19(insights.projectId, input.projectId),
12878
+ eq19(insights.type, "discovery.basket-divergence"),
12879
+ eq19(insights.dismissed, false)
12832
12880
  )).run();
12833
12881
  tx.insert(insights).values({
12834
12882
  id: crypto21.randomUUID(),
@@ -12868,7 +12916,7 @@ function buildDiscoveryInsightTitle(input) {
12868
12916
 
12869
12917
  // src/execute-site-audit.ts
12870
12918
  import crypto22 from "crypto";
12871
- import { and as and17, eq as eq21, ne as ne2, sql as sql7 } from "drizzle-orm";
12919
+ import { and as and17, eq as eq22, ne as ne2, sql as sql7 } from "drizzle-orm";
12872
12920
  import { runSiteCrawl } from "@canonry/agent-readiness";
12873
12921
 
12874
12922
  // src/site-audit-root.ts
@@ -13056,7 +13104,7 @@ async function requestPinnedSiteAuditRoot(target, options) {
13056
13104
  }
13057
13105
 
13058
13106
  // src/site-crawl-template-links.ts
13059
- import { and as and15, asc as asc3, eq as eq19, gt as gt2, inArray as inArray8 } from "drizzle-orm";
13107
+ import { and as and15, asc as asc3, eq as eq20, gt as gt2, inArray as inArray8 } from "drizzle-orm";
13060
13108
  var TEMPLATE_LINK_READ_BATCH = 2e3;
13061
13109
  var TEMPLATE_LINK_WRITE_BATCH = 500;
13062
13110
  function placementOccurrencesOf(row) {
@@ -13079,9 +13127,9 @@ function* streamAttemptEdges(db, scope) {
13079
13127
  placementContentOccurrences: siteCrawlEdges.placementContentOccurrences,
13080
13128
  placementUnknownOccurrences: siteCrawlEdges.placementUnknownOccurrences
13081
13129
  }).from(siteCrawlEdges).where(and15(
13082
- eq19(siteCrawlEdges.projectId, scope.projectId),
13083
- eq19(siteCrawlEdges.runId, scope.runId),
13084
- eq19(siteCrawlEdges.attemptId, scope.attemptId),
13130
+ eq20(siteCrawlEdges.projectId, scope.projectId),
13131
+ eq20(siteCrawlEdges.runId, scope.runId),
13132
+ eq20(siteCrawlEdges.attemptId, scope.attemptId),
13085
13133
  gt2(siteCrawlEdges.edgeKey, after)
13086
13134
  )).orderBy(asc3(siteCrawlEdges.edgeKey)).limit(TEMPLATE_LINK_READ_BATCH).all();
13087
13135
  if (rows.length === 0) return;
@@ -13107,9 +13155,9 @@ function writeGroupKey(isTemplate, templateRatio) {
13107
13155
  }
13108
13156
  function classifySiteCrawlTemplateLinks(db, scope, pagesFetched, placementRulesetVersion) {
13109
13157
  const scopeFilter = and15(
13110
- eq19(siteCrawlEdges.projectId, scope.projectId),
13111
- eq19(siteCrawlEdges.runId, scope.runId),
13112
- eq19(siteCrawlEdges.attemptId, scope.attemptId)
13158
+ eq20(siteCrawlEdges.projectId, scope.projectId),
13159
+ eq20(siteCrawlEdges.runId, scope.runId),
13160
+ eq20(siteCrawlEdges.attemptId, scope.attemptId)
13113
13161
  );
13114
13162
  const placementAvailable = templateLinkPlacementAvailable(placementRulesetVersion);
13115
13163
  const ubiquityAvailable = templateLinkUbiquityAvailable(pagesFetched);
@@ -13180,7 +13228,7 @@ function buildSiteCrawlIssueEvidence(siteIssues, pages) {
13180
13228
  }
13181
13229
 
13182
13230
  // src/site-audit-entity-registry.ts
13183
- import { and as and16, eq as eq20 } from "drizzle-orm";
13231
+ import { and as and16, eq as eq21 } from "drizzle-orm";
13184
13232
  function entityMatcher(matcher) {
13185
13233
  switch (matcher.kind) {
13186
13234
  case "prefix":
@@ -13208,9 +13256,9 @@ function planEntityRegistry(plan) {
13208
13256
  };
13209
13257
  }
13210
13258
  function activePlanEntityRegistry(db, projectId) {
13211
- const pointer = db.select({ versionId: measurementPlans.activeVersionId }).from(measurementPlans).where(eq20(measurementPlans.projectId, projectId)).get();
13259
+ const pointer = db.select({ versionId: measurementPlans.activeVersionId }).from(measurementPlans).where(eq21(measurementPlans.projectId, projectId)).get();
13212
13260
  if (!pointer) return null;
13213
- const version = db.select({ revision: measurementPlanVersions.revision, canonicalJson: measurementPlanVersions.canonicalJson }).from(measurementPlanVersions).where(and16(eq20(measurementPlanVersions.projectId, projectId), eq20(measurementPlanVersions.id, pointer.versionId))).get();
13261
+ const version = db.select({ revision: measurementPlanVersions.revision, canonicalJson: measurementPlanVersions.canonicalJson }).from(measurementPlanVersions).where(and16(eq21(measurementPlanVersions.projectId, projectId), eq21(measurementPlanVersions.id, pointer.versionId))).get();
13214
13262
  if (!version) return null;
13215
13263
  const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
13216
13264
  if (plan.schemaVersion !== MEASUREMENT_PLAN_V2_SCHEMA_VERSION) return null;
@@ -13219,7 +13267,7 @@ function activePlanEntityRegistry(db, projectId) {
13219
13267
  }
13220
13268
 
13221
13269
  // src/execute-site-audit.ts
13222
- var log16 = createLogger("SiteAudit");
13270
+ var log17 = createLogger("SiteAudit");
13223
13271
  var SiteAuditCancelledError = class extends Error {
13224
13272
  name = "SiteAuditCancelledError";
13225
13273
  };
@@ -13420,7 +13468,7 @@ function trackSiteAuditOutcome(db, input) {
13420
13468
  );
13421
13469
  const pagesAudited = input.crawl?.pagesAudited ?? 0;
13422
13470
  if (pagesAudited === 0 || input.trigger === RunTriggers.probe) return;
13423
- const prior = db.select({ id: siteAuditSnapshots.id }).from(siteAuditSnapshots).where(and17(eq21(siteAuditSnapshots.projectId, input.projectId), ne2(siteAuditSnapshots.runId, input.runId))).limit(1).get();
13471
+ const prior = db.select({ id: siteAuditSnapshots.id }).from(siteAuditSnapshots).where(and17(eq22(siteAuditSnapshots.projectId, input.projectId), ne2(siteAuditSnapshots.runId, input.runId))).limit(1).get();
13424
13472
  if (prior) return;
13425
13473
  trackEvent("activation.completed", {
13426
13474
  flowVersion: ONBOARDING_FLOW_VERSION,
@@ -13429,19 +13477,19 @@ function trackSiteAuditOutcome(db, input) {
13429
13477
  pagesAuditedBucket: bucketOnboardingCount(pagesAudited)
13430
13478
  });
13431
13479
  } catch (error) {
13432
- log16.warn("telemetry.failed", { runId: input.runId, projectId: input.projectId, error: describeError(error) });
13480
+ log17.warn("telemetry.failed", { runId: input.runId, projectId: input.projectId, error: describeError(error) });
13433
13481
  }
13434
13482
  }
13435
13483
  async function executeSiteAudit(db, runId, projectId, opts = {}) {
13436
13484
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
13437
- const claim = db.update(runs).set({ status: "running", startedAt }).where(and17(eq21(runs.id, runId), eq21(runs.projectId, projectId), eq21(runs.status, "queued"))).run();
13485
+ const claim = db.update(runs).set({ status: "running", startedAt }).where(and17(eq22(runs.id, runId), eq22(runs.projectId, projectId), eq22(runs.status, "queued"))).run();
13438
13486
  if (claim.changes === 0) return;
13439
13487
  const startTime = Date.now();
13440
13488
  const operationId = crypto22.randomUUID();
13441
13489
  let phase = OutcomePhases.setup;
13442
- const trigger = db.select({ trigger: runs.trigger }).from(runs).where(eq21(runs.id, runId)).get()?.trigger ?? null;
13490
+ const trigger = db.select({ trigger: runs.trigger }).from(runs).where(eq22(runs.id, runId)).get()?.trigger ?? null;
13443
13491
  let canonicalDomain = null;
13444
- const attemptNumber = (db.select({ value: sql7`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(eq21(siteCrawlAttempts.runId, runId)).get()?.value ?? 0) + 1;
13492
+ const attemptNumber = (db.select({ value: sql7`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(eq22(siteCrawlAttempts.runId, runId)).get()?.value ?? 0) + 1;
13445
13493
  const attemptId = crypto22.randomUUID();
13446
13494
  db.insert(siteCrawlAttempts).values({
13447
13495
  id: attemptId,
@@ -13477,22 +13525,22 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13477
13525
  const nodeKey = nodeKeyByUrl.get(url);
13478
13526
  if (!nodeKey) continue;
13479
13527
  const scope = [
13480
- eq21(siteCrawlEdges.projectId, projectId),
13481
- eq21(siteCrawlEdges.runId, runId),
13482
- eq21(siteCrawlEdges.attemptId, attemptId)
13528
+ eq22(siteCrawlEdges.projectId, projectId),
13529
+ eq22(siteCrawlEdges.runId, runId),
13530
+ eq22(siteCrawlEdges.attemptId, attemptId)
13483
13531
  ];
13484
13532
  tx.update(siteCrawlEdges).set({ sourceNodeKey: nodeKey, updatedAt: now }).where(and17(
13485
13533
  ...scope,
13486
- eq21(siteCrawlEdges.sourceUrl, url)
13534
+ eq22(siteCrawlEdges.sourceUrl, url)
13487
13535
  )).run();
13488
13536
  tx.update(siteCrawlEdges).set({ targetNodeKey: nodeKey, updatedAt: now }).where(and17(
13489
13537
  ...scope,
13490
- eq21(siteCrawlEdges.targetUrl, url)
13538
+ eq22(siteCrawlEdges.targetUrl, url)
13491
13539
  )).run();
13492
13540
  const pageScope = [
13493
- eq21(siteCrawlPages.projectId, projectId),
13494
- eq21(siteCrawlPages.runId, runId),
13495
- eq21(siteCrawlPages.attemptId, attemptId)
13541
+ eq22(siteCrawlPages.projectId, projectId),
13542
+ eq22(siteCrawlPages.runId, runId),
13543
+ eq22(siteCrawlPages.attemptId, attemptId)
13496
13544
  ];
13497
13545
  const canonicalTargets = tx.select({
13498
13546
  id: siteCrawlPages.id,
@@ -13500,13 +13548,13 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13500
13548
  fetchState: siteCrawlPages.fetchState,
13501
13549
  indexabilityState: siteCrawlPages.indexabilityState,
13502
13550
  indexabilityReasons: siteCrawlPages.indexabilityReasons
13503
- }).from(siteCrawlPages).where(and17(...pageScope, eq21(siteCrawlPages.canonicalUrl, url))).all();
13551
+ }).from(siteCrawlPages).where(and17(...pageScope, eq22(siteCrawlPages.canonicalUrl, url))).all();
13504
13552
  for (const target of canonicalTargets) {
13505
13553
  tx.update(siteCrawlPages).set({
13506
13554
  canonicalNodeKey: nodeKey,
13507
13555
  healthState: deriveSiteHealthState({ ...target, canonicalNodeKey: nodeKey }),
13508
13556
  updatedAt: now
13509
- }).where(eq21(siteCrawlPages.id, target.id)).run();
13557
+ }).where(eq22(siteCrawlPages.id, target.id)).run();
13510
13558
  }
13511
13559
  }
13512
13560
  };
@@ -13668,19 +13716,19 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13668
13716
  linkScoreNormalized: metrics.linkScore,
13669
13717
  updatedAt: now
13670
13718
  }).where(and17(
13671
- eq21(siteCrawlPages.projectId, projectId),
13672
- eq21(siteCrawlPages.runId, runId),
13673
- eq21(siteCrawlPages.attemptId, attemptId),
13674
- eq21(siteCrawlPages.nodeKey, key)
13719
+ eq22(siteCrawlPages.projectId, projectId),
13720
+ eq22(siteCrawlPages.runId, runId),
13721
+ eq22(siteCrawlPages.attemptId, attemptId),
13722
+ eq22(siteCrawlPages.nodeKey, key)
13675
13723
  )).run();
13676
13724
  };
13677
13725
  const persistEvent = async (event) => {
13678
13726
  const now = (/* @__PURE__ */ new Date()).toISOString();
13679
13727
  db.transaction((tx) => {
13680
13728
  const receipt = tx.select({ checksum: siteCrawlEventReceipts.checksum }).from(siteCrawlEventReceipts).where(and17(
13681
- eq21(siteCrawlEventReceipts.attemptId, attemptId),
13682
- eq21(siteCrawlEventReceipts.sequence, event.sequence),
13683
- eq21(siteCrawlEventReceipts.batchId, event.batchId)
13729
+ eq22(siteCrawlEventReceipts.attemptId, attemptId),
13730
+ eq22(siteCrawlEventReceipts.sequence, event.sequence),
13731
+ eq22(siteCrawlEventReceipts.batchId, event.batchId)
13684
13732
  )).get();
13685
13733
  if (receipt) {
13686
13734
  if (receipt.checksum !== event.checksum) {
@@ -13715,18 +13763,18 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13715
13763
  urlVersionsSkipped: event.type === "summary" ? event.summary.urlVersions?.skipped ?? 0 : sql7`${siteCrawlAttempts.urlVersionsSkipped}`,
13716
13764
  edgesDiscovered: progress.edgesObserved,
13717
13765
  updatedAt: now
13718
- }).where(eq21(siteCrawlAttempts.id, attemptId)).run();
13766
+ }).where(eq22(siteCrawlAttempts.id, attemptId)).run();
13719
13767
  } else {
13720
13768
  tx.update(siteCrawlAttempts).set({
13721
13769
  lastEventSequence: event.sequence,
13722
13770
  lastEventChecksum: event.checksum,
13723
13771
  updatedAt: now
13724
- }).where(eq21(siteCrawlAttempts.id, attemptId)).run();
13772
+ }).where(eq22(siteCrawlAttempts.id, attemptId)).run();
13725
13773
  }
13726
13774
  });
13727
13775
  };
13728
13776
  try {
13729
- const project = db.select().from(projects).where(eq21(projects.id, projectId)).get();
13777
+ const project = db.select().from(projects).where(eq22(projects.id, projectId)).get();
13730
13778
  if (!project) throw new Error(`Project not found: ${projectId}`);
13731
13779
  canonicalDomain = project.canonicalDomain;
13732
13780
  const homepageUrl = toHomepageUrl(project.canonicalDomain);
@@ -13749,7 +13797,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13749
13797
  return { host, rootUrl: resolved.effectiveUrl, error: null };
13750
13798
  } catch (error) {
13751
13799
  if (isCancelled(error, opts.signal)) throw error;
13752
- log16.warn("extra-site.unreachable", { runId, projectId, host, error: describeError(error) });
13800
+ log17.warn("extra-site.unreachable", { runId, projectId, host, error: describeError(error) });
13753
13801
  return { host, rootUrl: null, error: describeError(error) };
13754
13802
  }
13755
13803
  })
@@ -13759,9 +13807,9 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13759
13807
  try {
13760
13808
  entities = activePlanEntityRegistry(db, projectId);
13761
13809
  } catch (error) {
13762
- log16.warn("entity-registry.unavailable", { runId, projectId, error: describeError(error) });
13810
+ log17.warn("entity-registry.unavailable", { runId, projectId, error: describeError(error) });
13763
13811
  }
13764
- log16.info("start", {
13812
+ log17.info("start", {
13765
13813
  operationId,
13766
13814
  runId,
13767
13815
  projectId,
@@ -13806,7 +13854,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13806
13854
  crawlSummary.pagesFetched,
13807
13855
  placementRulesetVersion
13808
13856
  );
13809
- log16.info("template-links", {
13857
+ log17.info("template-links", {
13810
13858
  runId,
13811
13859
  projectId,
13812
13860
  detection: templateLinks.detection,
@@ -13845,7 +13893,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13845
13893
  try {
13846
13894
  persistSiteCrawlGraphLayout(db, { projectId, runId, attemptId }, graphLayout, finishedAt);
13847
13895
  } catch (error) {
13848
- log16.warn("graph-layout.persist-failed", {
13896
+ log17.warn("graph-layout.persist-failed", {
13849
13897
  runId,
13850
13898
  projectId,
13851
13899
  error: describeError(error)
@@ -13863,7 +13911,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13863
13911
  edges: []
13864
13912
  }, finishedAt);
13865
13913
  } catch (markerError) {
13866
- log16.warn("graph-layout.marker-persist-failed", {
13914
+ log17.warn("graph-layout.marker-persist-failed", {
13867
13915
  runId,
13868
13916
  projectId,
13869
13917
  error: describeError(markerError)
@@ -13871,7 +13919,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13871
13919
  }
13872
13920
  }
13873
13921
  const published = db.transaction((tx) => {
13874
- const claim2 = tx.update(runs).set({ status: terminalStatus, finishedAt }).where(and17(eq21(runs.id, runId), eq21(runs.status, "running"))).run();
13922
+ const claim2 = tx.update(runs).set({ status: terminalStatus, finishedAt }).where(and17(eq22(runs.id, runId), eq22(runs.status, "running"))).run();
13875
13923
  if (claim2.changes === 0) return false;
13876
13924
  if (aggregateScore !== null) {
13877
13925
  tx.insert(siteAuditSnapshots).values({
@@ -13986,24 +14034,24 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13986
14034
  edgesDiscovered: crawlSummary.edgesObserved,
13987
14035
  finishedAt,
13988
14036
  updatedAt: finishedAt
13989
- }).where(eq21(siteCrawlAttempts.id, attemptId)).run();
14037
+ }).where(eq22(siteCrawlAttempts.id, attemptId)).run();
13990
14038
  return true;
13991
14039
  });
13992
14040
  if (!published) {
13993
14041
  try {
13994
14042
  deleteSiteCrawlGraphLayout(db, { projectId, runId, attemptId });
13995
14043
  } catch (cleanupError) {
13996
- log16.warn("graph-layout.cleanup-failed", {
14044
+ log17.warn("graph-layout.cleanup-failed", {
13997
14045
  runId,
13998
14046
  projectId,
13999
14047
  error: describeError(cleanupError)
14000
14048
  });
14001
14049
  }
14002
- const current = db.select({ status: runs.status }).from(runs).where(eq21(runs.id, runId)).get();
14050
+ const current = db.select({ status: runs.status }).from(runs).where(eq22(runs.id, runId)).get();
14003
14051
  if (current?.status === "cancelled") throw new SiteAuditCancelledError(`Site audit cancelled before publication: ${runId}`);
14004
14052
  throw new Error(`Site audit run was no longer running before publication: ${runId}`);
14005
14053
  }
14006
- log16.info("completed", {
14054
+ log17.info("completed", {
14007
14055
  operationId,
14008
14056
  runId,
14009
14057
  projectId,
@@ -14050,14 +14098,14 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
14050
14098
  error: message,
14051
14099
  finishedAt,
14052
14100
  updatedAt: finishedAt
14053
- }).where(eq21(siteCrawlAttempts.id, attemptId)).run();
14101
+ }).where(eq22(siteCrawlAttempts.id, attemptId)).run();
14054
14102
  tx.update(runs).set({
14055
14103
  status: cancelled ? "cancelled" : "failed",
14056
14104
  error: message,
14057
14105
  finishedAt
14058
- }).where(and17(eq21(runs.id, runId), eq21(runs.status, "running"))).run();
14106
+ }).where(and17(eq22(runs.id, runId), eq22(runs.status, "running"))).run();
14059
14107
  });
14060
- log16.error("failed", { operationId, runId, projectId, phase, cancelled, error: message });
14108
+ log17.error("failed", { operationId, runId, projectId, phase, cancelled, error: message });
14061
14109
  trackSiteAuditOutcome(db, {
14062
14110
  operationId,
14063
14111
  phase,
@@ -14097,7 +14145,7 @@ function createAnswerFieldRecomputeQueue(opts) {
14097
14145
 
14098
14146
  // src/competitor-auto-alias-runner.ts
14099
14147
  import { setImmediate as yieldToEventLoop3 } from "timers/promises";
14100
- var log17 = createLogger("CompetitorAutoAliases");
14148
+ var log18 = createLogger("CompetitorAutoAliases");
14101
14149
  function createCompetitorAutoAliasRunner(opts) {
14102
14150
  const reasons = /* @__PURE__ */ new Map();
14103
14151
  const queue = createProjectPassQueue(async (projectId) => {
@@ -14108,7 +14156,7 @@ function createCompetitorAutoAliasRunner(opts) {
14108
14156
  if (!result) return null;
14109
14157
  const added = result.detection.competitors.reduce((sum, competitor) => sum + competitor.added.length, 0);
14110
14158
  const removed = result.detection.competitors.reduce((sum, competitor) => sum + competitor.removed.length, 0);
14111
- log17.info("detection.completed", {
14159
+ log18.info("detection.completed", {
14112
14160
  projectId,
14113
14161
  reason,
14114
14162
  runs: result.detection.scan.runs,
@@ -14121,7 +14169,7 @@ function createCompetitorAutoAliasRunner(opts) {
14121
14169
  try {
14122
14170
  opts.onNamesChanged(projectId, result.detection.project);
14123
14171
  } catch (err) {
14124
- log17.error("names-changed.failed", { projectId, error: describeError(err) });
14172
+ log18.error("names-changed.failed", { projectId, error: describeError(err) });
14125
14173
  }
14126
14174
  }
14127
14175
  return result;
@@ -14133,14 +14181,14 @@ function createCompetitorAutoAliasRunner(opts) {
14133
14181
  return {
14134
14182
  schedule(projectId, reason) {
14135
14183
  enqueue(projectId, reason).catch((err) => {
14136
- log17.error("detection.failed", { projectId, reason, error: describeError(err) });
14184
+ log18.error("detection.failed", { projectId, reason, error: describeError(err) });
14137
14185
  });
14138
14186
  },
14139
14187
  async request(projectId, reason) {
14140
14188
  try {
14141
14189
  return await enqueue(projectId, reason);
14142
14190
  } catch (err) {
14143
- log17.error("detection.failed", { projectId, reason, error: describeError(err) });
14191
+ log18.error("detection.failed", { projectId, reason, error: describeError(err) });
14144
14192
  throw err;
14145
14193
  }
14146
14194
  },
@@ -14149,8 +14197,8 @@ function createCompetitorAutoAliasRunner(opts) {
14149
14197
  }
14150
14198
 
14151
14199
  // src/install-state-telemetry.ts
14152
- import { and as and18, count as count4, eq as eq22, gte as gte2, inArray as inArray9, isNotNull as isNotNull2, isNull as isNull2, ne as ne3, sql as sql8 } from "drizzle-orm";
14153
- var log18 = createLogger("InstallStateTelemetry");
14200
+ import { and as and18, count as count4, eq as eq23, gte as gte2, inArray as inArray9, isNotNull as isNotNull2, isNull as isNull2, ne as ne3, sql as sql8 } from "drizzle-orm";
14201
+ var log19 = createLogger("InstallStateTelemetry");
14154
14202
  var INSTALL_STATE_FIRST_DELAY_MS = 5 * 6e4;
14155
14203
  var INSTALL_STATE_INTERVAL_MS = 24 * 60 * 6e4;
14156
14204
  var KNOWN_PROVIDERS2 = new Set(PROVIDER_NAMES);
@@ -14175,7 +14223,7 @@ function buildInstallState(sources, now, startedAt) {
14175
14223
  const googleByType = new Map(db.select({ type: googleConnections.connectionType, value: count4() }).from(googleConnections).groupBy(googleConnections.connectionType).all().map((row) => [row.type, whole(row.value)]));
14176
14224
  const gaServiceAccounts = total(db.select({ value: count4() }).from(gaConnections));
14177
14225
  const trafficByType = db.select({ type: trafficSources.sourceType, value: count4() }).from(trafficSources).where(and18(isNull2(trafficSources.archivedAt), ne3(trafficSources.status, TrafficSourceStatuses.archived))).groupBy(trafficSources.sourceType).all();
14178
- const webhookSources = db.select({ config: notifications.config }).from(notifications).where(eq22(notifications.enabled, true)).all().map((row) => row.config.source);
14226
+ const webhookSources = db.select({ config: notifications.config }).from(notifications).where(eq23(notifications.enabled, true)).all().map((row) => row.config.source);
14179
14227
  const agentWebhooks = webhookSources.filter((source) => source === AGENT_WEBHOOK_SOURCE).length;
14180
14228
  const webhooks = webhookSources.length - agentWebhooks;
14181
14229
  const bing = total(db.select({ value: count4() }).from(bingConnections));
@@ -14189,7 +14237,7 @@ function buildInstallState(sources, now, startedAt) {
14189
14237
  queries: total(db.select({ value: count4() }).from(queries)),
14190
14238
  competitors: total(db.select({ value: count4() }).from(competitors)),
14191
14239
  locations: total(db.select({ value: sql8`coalesce(sum(json_array_length(${projects.locations})), 0)` }).from(projects)),
14192
- schedules: total(db.select({ value: count4() }).from(schedules).where(eq22(schedules.enabled, true))),
14240
+ schedules: total(db.select({ value: count4() }).from(schedules).where(eq23(schedules.enabled, true))),
14193
14241
  webhooks,
14194
14242
  agentWebhooks,
14195
14243
  trafficSources: trafficByType.reduce((sum, row) => sum + whole(row.value), 0),
@@ -14251,13 +14299,13 @@ function buildInstallState(sources, now, startedAt) {
14251
14299
  const usage24h = {
14252
14300
  sweeps: total(db.select({ value: count4() }).from(runs).where(and18(
14253
14301
  inArray9(runs.projectId, projectIds),
14254
- eq22(runs.kind, RunKinds["answer-visibility"]),
14302
+ eq23(runs.kind, RunKinds["answer-visibility"]),
14255
14303
  gte2(runs.createdAt, since),
14256
14304
  ne3(runs.trigger, RunTriggers.probe)
14257
14305
  ))),
14258
14306
  audits: total(db.select({ value: count4() }).from(runs).where(and18(
14259
14307
  inArray9(runs.projectId, projectIds),
14260
- eq22(runs.kind, RunKinds["site-audit"]),
14308
+ eq23(runs.kind, RunKinds["site-audit"]),
14261
14309
  gte2(runs.createdAt, since)
14262
14310
  ))),
14263
14311
  providerCalls: [...providerCalls.values()].reduce((sum, calls) => sum + calls, 0)
@@ -14274,14 +14322,14 @@ function buildInstallState(sources, now, startedAt) {
14274
14322
  inputTokens: sql8`coalesce(sum(${llmUsageEvents.inputTokens}), 0)`,
14275
14323
  outputTokens: sql8`coalesce(sum(${llmUsageEvents.outputTokens}), 0)`,
14276
14324
  costMillicents: sql8`coalesce(sum(${llmUsageEvents.costMillicents}), 0)`
14277
- }).from(llmUsageEvents).where(and18(eq22(llmUsageEvents.feature, AeroLlmUsageFeatures.turn), gte2(llmUsageEvents.createdAt, since))).get();
14325
+ }).from(llmUsageEvents).where(and18(eq23(llmUsageEvents.feature, AeroLlmUsageFeatures.turn), gte2(llmUsageEvents.createdAt, since))).get();
14278
14326
  const aeroCalls = whole(aero?.calls);
14279
14327
  usage24h.aeroModelCalls = aeroCalls;
14280
14328
  usage24h.aeroInputTokens = whole(aero?.inputTokens);
14281
14329
  usage24h.aeroOutputTokens = whole(aero?.outputTokens);
14282
14330
  const aeroMillicents = whole(aero?.costMillicents);
14283
14331
  if (aeroCalls === 0 || aeroMillicents > 0) usage24h.aeroCostMicros = aeroMillicents * 10;
14284
- usage24h.webhookDeliveries = total(db.select({ value: count4() }).from(auditLog).where(and18(gte2(auditLog.createdAt, since), eq22(auditLog.action, WEBHOOK_DELIVERED_ACTION))));
14332
+ usage24h.webhookDeliveries = total(db.select({ value: count4() }).from(auditLog).where(and18(gte2(auditLog.createdAt, since), eq23(auditLog.action, WEBHOOK_DELIVERED_ACTION))));
14285
14333
  const providerCalls24h = Object.fromEntries(PROVIDER_NAMES.flatMap((name) => providerCalls.has(name) ? [[name, providerCalls.get(name)]] : []));
14286
14334
  return {
14287
14335
  providers: registeredProviderNames(config).filter((name) => KNOWN_PROVIDERS2.has(name)),
@@ -14315,7 +14363,7 @@ function startInstallStateTelemetry(sources) {
14315
14363
  try {
14316
14364
  if (isTelemetryEnabled()) trackInstallState(buildInstallState(sources, Date.now(), startedAt));
14317
14365
  } catch (err) {
14318
- log18.warn("telemetry.install-state-failed", { error: describeError(err) });
14366
+ log19.warn("telemetry.install-state-failed", { error: describeError(err) });
14319
14367
  }
14320
14368
  schedule(INSTALL_STATE_INTERVAL_MS);
14321
14369
  };
@@ -14437,8 +14485,8 @@ function createProviderModelCatalog(registry) {
14437
14485
  // src/scheduler.ts
14438
14486
  import crypto23 from "crypto";
14439
14487
  import cron from "node-cron";
14440
- import { and as and19, eq as eq23, inArray as inArray10, notExists, sql as sql9 } from "drizzle-orm";
14441
- var log19 = createLogger("Scheduler");
14488
+ import { and as and19, eq as eq24, inArray as inArray10, notExists, sql as sql9 } from "drizzle-orm";
14489
+ var log20 = createLogger("Scheduler");
14442
14490
  var SLOT_FIRED = { status: OutcomeStatuses.succeeded };
14443
14491
  var slotSkipped = (reasonCode) => ({ status: OutcomeStatuses.skipped, reasonCode });
14444
14492
  var slotFailed = (reasonCode) => ({ status: OutcomeStatuses.failed, reasonCode });
@@ -14517,8 +14565,8 @@ var Scheduler = class {
14517
14565
  ensureHealthSchedules() {
14518
14566
  const projectsWithoutHealth = this.db.select({ id: projects.id }).from(projects).where(notExists(
14519
14567
  this.db.select({ one: sql9`1` }).from(schedules).where(and19(
14520
- eq23(schedules.projectId, projects.id),
14521
- eq23(schedules.kind, SchedulableRunKinds.doctor)
14568
+ eq24(schedules.projectId, projects.id),
14569
+ eq24(schedules.kind, SchedulableRunKinds.doctor)
14522
14570
  ))
14523
14571
  )).all();
14524
14572
  if (projectsWithoutHealth.length === 0) return;
@@ -14528,7 +14576,7 @@ var Scheduler = class {
14528
14576
  if (ensureDefaultHealthSchedule(this.db, project.id, now)) seeded += 1;
14529
14577
  }
14530
14578
  if (seeded > 0) {
14531
- log19.info("health-schedule.seeded", { projectCount: seeded, cron: DEFAULT_HEALTH_CRON });
14579
+ log20.info("health-schedule.seeded", { projectCount: seeded, cron: DEFAULT_HEALTH_CRON });
14532
14580
  }
14533
14581
  }
14534
14582
  /**
@@ -14552,16 +14600,16 @@ var Scheduler = class {
14552
14600
  const current = ensureCurrentQueryBasketRevision(this.db, project.id);
14553
14601
  if (current !== null && current.revision !== previous) minted += 1;
14554
14602
  } catch (err) {
14555
- log19.warn("query-basket.mint-failed", { projectId: project.id, err: String(err) });
14603
+ log20.warn("query-basket.mint-failed", { projectId: project.id, err: String(err) });
14556
14604
  }
14557
14605
  }
14558
- if (minted > 0) log19.info("query-basket.ensured", { projectCount: minted });
14606
+ if (minted > 0) log20.info("query-basket.ensured", { projectCount: minted });
14559
14607
  }
14560
14608
  /** Load all enabled schedules from DB and register cron jobs. */
14561
14609
  start() {
14562
14610
  this.ensureHealthSchedules();
14563
14611
  this.ensureQueryBaskets();
14564
- const allSchedules = this.db.select().from(schedules).where(eq23(schedules.enabled, true)).all();
14612
+ const allSchedules = this.db.select().from(schedules).where(eq24(schedules.enabled, true)).all();
14565
14613
  for (const schedule of allSchedules) {
14566
14614
  const missedRunAt = schedule.nextRunAt;
14567
14615
  const recurrence = scheduleRecurrence(schedule);
@@ -14569,12 +14617,12 @@ var Scheduler = class {
14569
14617
  if (registered && missedRunAt && new Date(missedRunAt) < /* @__PURE__ */ new Date()) {
14570
14618
  const answerRecurrence = recurrence && schedule.kind === SchedulableRunKinds["answer-visibility"];
14571
14619
  if (!recurrence || answerRecurrence || this.claimCalendarOccurrence(schedule, missedRunAt, /* @__PURE__ */ new Date())) {
14572
- log19.info("run.catch-up", { projectId: schedule.projectId, kind: schedule.kind, missedRunAt });
14620
+ log20.info("run.catch-up", { projectId: schedule.projectId, kind: schedule.kind, missedRunAt });
14573
14621
  this.triggerRun(schedule.id, schedule.projectId, schedule.kind, answerRecurrence ? missedRunAt : void 0, OutcomeTriggers.startup);
14574
14622
  }
14575
14623
  }
14576
14624
  }
14577
- log19.info("started", { scheduleCount: allSchedules.length });
14625
+ log20.info("started", { scheduleCount: allSchedules.length });
14578
14626
  }
14579
14627
  /** Stop all cron tasks for graceful shutdown. */
14580
14628
  stop() {
@@ -14595,7 +14643,7 @@ var Scheduler = class {
14595
14643
  this.stopTask(key, existing, "Stopped");
14596
14644
  this.tasks.delete(key);
14597
14645
  }
14598
- const schedule = this.db.select().from(schedules).where(and19(eq23(schedules.projectId, projectId), eq23(schedules.kind, kind))).get();
14646
+ const schedule = this.db.select().from(schedules).where(and19(eq24(schedules.projectId, projectId), eq24(schedules.kind, kind))).get();
14599
14647
  if (schedule && schedule.enabled) {
14600
14648
  this.registerCronTask(schedule);
14601
14649
  }
@@ -14623,17 +14671,17 @@ var Scheduler = class {
14623
14671
  clearTimeout(pending);
14624
14672
  this.spreadTimers.delete(key);
14625
14673
  }
14626
- log19.info(`task.${verb.toLowerCase()}`, { key });
14674
+ log20.info(`task.${verb.toLowerCase()}`, { key });
14627
14675
  }
14628
14676
  /** Runtime timing writes must not restore a version already issued to a settings caller. */
14629
14677
  updateScheduleTiming(scheduleId, timing) {
14630
14678
  this.db.transaction((tx) => {
14631
- const current = tx.select({ updatedAt: schedules.updatedAt }).from(schedules).where(eq23(schedules.id, scheduleId)).get();
14679
+ const current = tx.select({ updatedAt: schedules.updatedAt }).from(schedules).where(eq24(schedules.id, scheduleId)).get();
14632
14680
  if (!current) return;
14633
14681
  tx.update(schedules).set({
14634
14682
  ...timing,
14635
14683
  updatedAt: nextScheduleUpdatedAt(current.updatedAt)
14636
- }).where(eq23(schedules.id, scheduleId)).run();
14684
+ }).where(eq24(schedules.id, scheduleId)).run();
14637
14685
  });
14638
14686
  }
14639
14687
  registerCronTask(schedule, options = {}) {
@@ -14643,13 +14691,13 @@ var Scheduler = class {
14643
14691
  return true;
14644
14692
  }
14645
14693
  if (schedule.recurrence) {
14646
- log19.error("calendar.invalid", { projectId: schedule.projectId, kind: schedule.kind });
14694
+ log20.error("calendar.invalid", { projectId: schedule.projectId, kind: schedule.kind });
14647
14695
  return false;
14648
14696
  }
14649
14697
  const { id: scheduleId, projectId, cronExpr, timezone } = schedule;
14650
14698
  const kind = schedule.kind;
14651
14699
  if (!cron.validate(cronExpr)) {
14652
- log19.error("cron.invalid", { projectId, kind, cronExpr });
14700
+ log20.error("cron.invalid", { projectId, kind, cronExpr });
14653
14701
  return false;
14654
14702
  }
14655
14703
  const key = taskKey(projectId, kind);
@@ -14679,7 +14727,7 @@ var Scheduler = class {
14679
14727
  });
14680
14728
  }
14681
14729
  const label = schedule.preset ?? cronExpr;
14682
- log19.info("cron.registered", { projectId, kind, schedule: label, timezone });
14730
+ log20.info("cron.registered", { projectId, kind, schedule: label, timezone });
14683
14731
  return true;
14684
14732
  }
14685
14733
  /** Calendar schedules are checked at most once a minute so long intervals
@@ -14709,7 +14757,7 @@ var Scheduler = class {
14709
14757
  };
14710
14758
  const tick = () => {
14711
14759
  if (stopped) return;
14712
- const current = this.db.select().from(schedules).where(eq23(schedules.id, scheduleId)).get();
14760
+ const current = this.db.select().from(schedules).where(eq24(schedules.id, scheduleId)).get();
14713
14761
  if (!current || !current.enabled || !scheduleRecurrence(current)) {
14714
14762
  this.remove(projectId, kind);
14715
14763
  return;
@@ -14727,7 +14775,7 @@ var Scheduler = class {
14727
14775
  this.triggerRun(scheduleId, projectId, kind);
14728
14776
  }
14729
14777
  }
14730
- arm(this.db.select({ nextRunAt: schedules.nextRunAt }).from(schedules).where(eq23(schedules.id, scheduleId)).get()?.nextRunAt);
14778
+ arm(this.db.select({ nextRunAt: schedules.nextRunAt }).from(schedules).where(eq24(schedules.id, scheduleId)).get()?.nextRunAt);
14731
14779
  };
14732
14780
  this.tasks.set(key, task);
14733
14781
  let registeredNextRunAt = schedule.nextRunAt;
@@ -14737,12 +14785,12 @@ var Scheduler = class {
14737
14785
  }
14738
14786
  if (options.preserveNextRunAt) arm(registeredNextRunAt);
14739
14787
  else timer = setTimeout(tick, 0);
14740
- log19.info("calendar.registered", { projectId, kind, recurrence, timezone });
14788
+ log20.info("calendar.registered", { projectId, kind, recurrence, timezone });
14741
14789
  }
14742
14790
  /** Atomically advance a due callback-only calendar occurrence before dispatch. */
14743
14791
  claimCalendarOccurrence(schedule, dueAt, now) {
14744
14792
  return this.db.transaction((tx) => {
14745
- const current = tx.select().from(schedules).where(eq23(schedules.id, schedule.id)).get();
14793
+ const current = tx.select().from(schedules).where(eq24(schedules.id, schedule.id)).get();
14746
14794
  if (!current || !current.enabled || current.updatedAt !== schedule.updatedAt || current.nextRunAt !== dueAt) return false;
14747
14795
  const recurrence = scheduleRecurrence(current);
14748
14796
  if (!recurrence) return false;
@@ -14752,10 +14800,10 @@ var Scheduler = class {
14752
14800
  nextRunAt,
14753
14801
  updatedAt: nextScheduleUpdatedAt(current.updatedAt)
14754
14802
  }).where(and19(
14755
- eq23(schedules.id, current.id),
14756
- eq23(schedules.enabled, true),
14757
- eq23(schedules.nextRunAt, dueAt),
14758
- eq23(schedules.updatedAt, schedule.updatedAt)
14803
+ eq24(schedules.id, current.id),
14804
+ eq24(schedules.enabled, true),
14805
+ eq24(schedules.nextRunAt, dueAt),
14806
+ eq24(schedules.updatedAt, schedule.updatedAt)
14759
14807
  )).run();
14760
14808
  return result.changes === 1;
14761
14809
  });
@@ -14777,15 +14825,15 @@ var Scheduler = class {
14777
14825
  fireSlot(scheduleId, projectId, kind, claimedOccurrence) {
14778
14826
  try {
14779
14827
  const now = (/* @__PURE__ */ new Date()).toISOString();
14780
- const currentSchedule = this.db.select().from(schedules).where(eq23(schedules.id, scheduleId)).get();
14828
+ const currentSchedule = this.db.select().from(schedules).where(eq24(schedules.id, scheduleId)).get();
14781
14829
  if (!currentSchedule || !currentSchedule.enabled) {
14782
- log19.warn("schedule.stale", { scheduleId, projectId, kind, msg: "schedule no longer exists or is disabled" });
14830
+ log20.warn("schedule.stale", { scheduleId, projectId, kind, msg: "schedule no longer exists or is disabled" });
14783
14831
  this.remove(projectId, kind);
14784
14832
  return slotSkipped(currentSchedule ? OutcomeReasonCodes.NOT_DUE : OutcomeReasonCodes.NOT_FOUND);
14785
14833
  }
14786
14834
  const recurrence = scheduleRecurrence(currentSchedule);
14787
14835
  if (claimedOccurrence && (!recurrence || currentSchedule.nextRunAt !== claimedOccurrence)) {
14788
- log19.info("calendar.stale-claim", { projectId, scheduleId, kind });
14836
+ log20.info("calendar.stale-claim", { projectId, scheduleId, kind });
14789
14837
  return slotSkipped(OutcomeReasonCodes.NOT_DUE);
14790
14838
  }
14791
14839
  const nextRunAt = nextRunFromSchedule({
@@ -14793,33 +14841,33 @@ var Scheduler = class {
14793
14841
  timezone: currentSchedule.timezone,
14794
14842
  recurrence
14795
14843
  });
14796
- const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
14844
+ const project = this.db.select().from(projects).where(eq24(projects.id, projectId)).get();
14797
14845
  if (!project) {
14798
- log19.error("project.not-found", { projectId, kind, msg: "skipping scheduled run" });
14846
+ log20.error("project.not-found", { projectId, kind, msg: "skipping scheduled run" });
14799
14847
  this.remove(projectId, kind);
14800
14848
  return slotSkipped(OutcomeReasonCodes.NOT_FOUND);
14801
14849
  }
14802
14850
  if (kind === SchedulableRunKinds["traffic-sync"]) {
14803
14851
  const sourceId = currentSchedule.sourceId;
14804
14852
  if (!sourceId) {
14805
- log19.warn("traffic-sync.missing-source", { scheduleId, projectId });
14853
+ log20.warn("traffic-sync.missing-source", { scheduleId, projectId });
14806
14854
  return slotFailed(OutcomeReasonCodes.VALIDATION);
14807
14855
  }
14808
14856
  if (!this.callbacks.onTrafficSyncRequested) {
14809
- log19.warn("traffic-sync.no-callback", { scheduleId, projectId, msg: "host did not register onTrafficSyncRequested" });
14857
+ log20.warn("traffic-sync.no-callback", { scheduleId, projectId, msg: "host did not register onTrafficSyncRequested" });
14810
14858
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14811
14859
  }
14812
14860
  this.updateScheduleTiming(currentSchedule.id, {
14813
14861
  lastRunAt: now,
14814
14862
  nextRunAt
14815
14863
  });
14816
- log19.info("traffic-sync.triggered", { projectName: project.name, sourceId });
14864
+ log20.info("traffic-sync.triggered", { projectName: project.name, sourceId });
14817
14865
  this.callbacks.onTrafficSyncRequested(project.name, sourceId);
14818
14866
  return SLOT_FIRED;
14819
14867
  }
14820
14868
  if (kind === SchedulableRunKinds["gbp-sync"]) {
14821
14869
  if (!this.callbacks.onGbpSyncRequested) {
14822
- log19.warn("gbp-sync.no-callback", { scheduleId, projectId, msg: "host did not register onGbpSyncRequested" });
14870
+ log20.warn("gbp-sync.no-callback", { scheduleId, projectId, msg: "host did not register onGbpSyncRequested" });
14823
14871
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14824
14872
  }
14825
14873
  const runId2 = crypto23.randomUUID();
@@ -14835,22 +14883,22 @@ var Scheduler = class {
14835
14883
  lastRunAt: now,
14836
14884
  nextRunAt
14837
14885
  });
14838
- log19.info("gbp-sync.triggered", { runId: runId2, projectName: project.name });
14886
+ log20.info("gbp-sync.triggered", { runId: runId2, projectName: project.name });
14839
14887
  this.callbacks.onGbpSyncRequested(runId2, projectId);
14840
14888
  return SLOT_FIRED;
14841
14889
  }
14842
14890
  if (kind === SchedulableRunKinds["ads-sync"]) {
14843
14891
  if (!this.callbacks.onAdsSyncRequested) {
14844
- log19.warn("ads-sync.no-callback", { scheduleId, projectId, msg: "host did not register onAdsSyncRequested" });
14892
+ log20.warn("ads-sync.no-callback", { scheduleId, projectId, msg: "host did not register onAdsSyncRequested" });
14845
14893
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14846
14894
  }
14847
14895
  const activeAdsRun = this.db.select({ id: runs.id }).from(runs).where(and19(
14848
- eq23(runs.projectId, projectId),
14849
- eq23(runs.kind, RunKinds["ads-sync"]),
14896
+ eq24(runs.projectId, projectId),
14897
+ eq24(runs.kind, RunKinds["ads-sync"]),
14850
14898
  inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
14851
14899
  )).get();
14852
14900
  if (activeAdsRun) {
14853
- log19.info("ads-sync.skipped-active", { projectName: project.name, activeRunId: activeAdsRun.id });
14901
+ log20.info("ads-sync.skipped-active", { projectName: project.name, activeRunId: activeAdsRun.id });
14854
14902
  this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
14855
14903
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14856
14904
  }
@@ -14867,22 +14915,22 @@ var Scheduler = class {
14867
14915
  lastRunAt: now,
14868
14916
  nextRunAt
14869
14917
  });
14870
- log19.info("ads-sync.triggered", { runId: runId2, projectName: project.name });
14918
+ log20.info("ads-sync.triggered", { runId: runId2, projectName: project.name });
14871
14919
  this.callbacks.onAdsSyncRequested(runId2, projectId);
14872
14920
  return SLOT_FIRED;
14873
14921
  }
14874
14922
  if (kind === SchedulableRunKinds["seo-sync"]) {
14875
14923
  if (!this.callbacks.onSeoSyncRequested) {
14876
- log19.warn("seo-sync.no-callback", { scheduleId, projectId, msg: "host did not register onSeoSyncRequested" });
14924
+ log20.warn("seo-sync.no-callback", { scheduleId, projectId, msg: "host did not register onSeoSyncRequested" });
14877
14925
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14878
14926
  }
14879
14927
  const activeSeoRun = this.db.select({ id: runs.id }).from(runs).where(and19(
14880
- eq23(runs.projectId, projectId),
14881
- eq23(runs.kind, RunKinds["seo-sync"]),
14928
+ eq24(runs.projectId, projectId),
14929
+ eq24(runs.kind, RunKinds["seo-sync"]),
14882
14930
  inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
14883
14931
  )).get();
14884
14932
  if (activeSeoRun) {
14885
- log19.info("seo-sync.skipped-active", { projectName: project.name, activeRunId: activeSeoRun.id });
14933
+ log20.info("seo-sync.skipped-active", { projectName: project.name, activeRunId: activeSeoRun.id });
14886
14934
  this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
14887
14935
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14888
14936
  }
@@ -14890,61 +14938,61 @@ var Scheduler = class {
14890
14938
  lastRunAt: now,
14891
14939
  nextRunAt
14892
14940
  });
14893
- log19.info("seo-sync.triggered", { projectName: project.name });
14941
+ log20.info("seo-sync.triggered", { projectName: project.name });
14894
14942
  this.callbacks.onSeoSyncRequested({ scheduleId, projectId, occurrence: now.slice(0, 16) });
14895
14943
  return SLOT_FIRED;
14896
14944
  }
14897
14945
  if (kind === SchedulableRunKinds["data-refresh"]) {
14898
14946
  if (!this.callbacks.onDataRefreshRequested) {
14899
- log19.warn("data-refresh.no-callback", { scheduleId, projectId, msg: "host did not register onDataRefreshRequested" });
14947
+ log20.warn("data-refresh.no-callback", { scheduleId, projectId, msg: "host did not register onDataRefreshRequested" });
14900
14948
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14901
14949
  }
14902
14950
  this.updateScheduleTiming(currentSchedule.id, {
14903
14951
  lastRunAt: now,
14904
14952
  nextRunAt
14905
14953
  });
14906
- log19.info("data-refresh.triggered", { projectName: project.name });
14954
+ log20.info("data-refresh.triggered", { projectName: project.name });
14907
14955
  this.callbacks.onDataRefreshRequested(project.name);
14908
14956
  return SLOT_FIRED;
14909
14957
  }
14910
14958
  if (kind === SchedulableRunKinds.doctor) {
14911
14959
  if (!this.callbacks.onDoctorRequested) {
14912
- log19.warn("doctor.no-callback", { scheduleId, projectId, msg: "host did not register onDoctorRequested" });
14960
+ log20.warn("doctor.no-callback", { scheduleId, projectId, msg: "host did not register onDoctorRequested" });
14913
14961
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14914
14962
  }
14915
14963
  this.updateScheduleTiming(currentSchedule.id, {
14916
14964
  lastRunAt: now,
14917
14965
  nextRunAt
14918
14966
  });
14919
- log19.info("doctor.triggered", { projectName: project.name });
14967
+ log20.info("doctor.triggered", { projectName: project.name });
14920
14968
  this.callbacks.onDoctorRequested(project.name);
14921
14969
  return SLOT_FIRED;
14922
14970
  }
14923
14971
  if (kind === SchedulableRunKinds["backlinks-sync"]) {
14924
14972
  if (!this.callbacks.onBacklinksSyncRequested) {
14925
- log19.warn("backlinks-sync.no-callback", { scheduleId, projectId, msg: "host did not register onBacklinksSyncRequested" });
14973
+ log20.warn("backlinks-sync.no-callback", { scheduleId, projectId, msg: "host did not register onBacklinksSyncRequested" });
14926
14974
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14927
14975
  }
14928
14976
  this.updateScheduleTiming(currentSchedule.id, {
14929
14977
  lastRunAt: now,
14930
14978
  nextRunAt
14931
14979
  });
14932
- log19.info("backlinks-sync.triggered", { projectName: project.name });
14980
+ log20.info("backlinks-sync.triggered", { projectName: project.name });
14933
14981
  this.callbacks.onBacklinksSyncRequested(project.name);
14934
14982
  return SLOT_FIRED;
14935
14983
  }
14936
14984
  if (kind === SchedulableRunKinds["site-audit"]) {
14937
14985
  if (!this.callbacks.onSiteAuditRequested) {
14938
- log19.warn("site-audit.no-callback", { scheduleId, projectId, msg: "host did not register onSiteAuditRequested" });
14986
+ log20.warn("site-audit.no-callback", { scheduleId, projectId, msg: "host did not register onSiteAuditRequested" });
14939
14987
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14940
14988
  }
14941
14989
  const active = this.db.select({ id: runs.id }).from(runs).where(and19(
14942
- eq23(runs.projectId, projectId),
14943
- eq23(runs.kind, RunKinds["site-audit"]),
14990
+ eq24(runs.projectId, projectId),
14991
+ eq24(runs.kind, RunKinds["site-audit"]),
14944
14992
  inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
14945
14993
  )).get();
14946
14994
  if (active) {
14947
- log19.info("site-audit.skipped-active", { projectName: project.name, activeRunId: active.id });
14995
+ log20.info("site-audit.skipped-active", { projectName: project.name, activeRunId: active.id });
14948
14996
  this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
14949
14997
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14950
14998
  }
@@ -14973,7 +15021,7 @@ var Scheduler = class {
14973
15021
  lastRunAt: now,
14974
15022
  nextRunAt
14975
15023
  });
14976
- log19.info("site-audit.triggered", { runId: runId2, projectName: project.name });
15024
+ log20.info("site-audit.triggered", { runId: runId2, projectName: project.name });
14977
15025
  this.callbacks.onSiteAuditRequested(runId2, projectId, {
14978
15026
  maxPages: effectiveRequest.maxPages,
14979
15027
  checkDeadLinks: effectiveRequest.checkDeadLinks,
@@ -14988,7 +15036,7 @@ var Scheduler = class {
14988
15036
  if (project.defaultLocation) {
14989
15037
  const loc = projectLocations.find((l) => l.label === project.defaultLocation);
14990
15038
  if (!loc) {
14991
- log19.warn("default-location.stale", { scheduleId, projectId, label: project.defaultLocation });
15039
+ log20.warn("default-location.stale", { scheduleId, projectId, label: project.defaultLocation });
14992
15040
  return slotFailed(OutcomeReasonCodes.VALIDATION);
14993
15041
  }
14994
15042
  resolvedLocation = loc;
@@ -14997,7 +15045,7 @@ var Scheduler = class {
14997
15045
  const scheduleProviders = currentSchedule.providers;
14998
15046
  const providers = scheduleProviders.length > 0 ? scheduleProviders : void 0;
14999
15047
  if (claimedOccurrence && recurrence && !nextRunAt) {
15000
- log19.error("calendar.invalid", { projectId, kind, scheduleId });
15048
+ log20.error("calendar.invalid", { projectId, kind, scheduleId });
15001
15049
  return slotFailed(OutcomeReasonCodes.VALIDATION);
15002
15050
  }
15003
15051
  const queueResult = queueRunIfProjectIdle(this.db, {
@@ -15025,11 +15073,11 @@ var Scheduler = class {
15025
15073
  });
15026
15074
  if (queueResult.conflict) {
15027
15075
  if (queueResult.scheduleClaimed === false) {
15028
- log19.info("calendar.skipped-claimed", { projectName: project.name, scheduleId: currentSchedule.id });
15076
+ log20.info("calendar.skipped-claimed", { projectName: project.name, scheduleId: currentSchedule.id });
15029
15077
  return slotSkipped(OutcomeReasonCodes.NOT_DUE);
15030
15078
  }
15031
15079
  const batchPending = hasOutstandingProviderBatch(this.db, queueResult.activeRunId);
15032
- log19.info("run.skipped-active", {
15080
+ log20.info("run.skipped-active", {
15033
15081
  projectName: project.name,
15034
15082
  activeRunId: queueResult.activeRunId,
15035
15083
  ...batchPending ? { reason: "batch-pending" } : {}
@@ -15038,7 +15086,7 @@ var Scheduler = class {
15038
15086
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
15039
15087
  }
15040
15088
  if (queueResult.refused) {
15041
- log19.warn("run.skipped-providers-failing", {
15089
+ log20.warn("run.skipped-providers-failing", {
15042
15090
  projectName: project.name,
15043
15091
  scheduleId: currentSchedule.id,
15044
15092
  ...queueResult.refused
@@ -15057,7 +15105,7 @@ var Scheduler = class {
15057
15105
  const runId = queueResult.runId;
15058
15106
  for (const [provider, reason] of Object.entries(queueResult.dispatch.ineligible)) {
15059
15107
  if (!reason) continue;
15060
- log19.warn("run.dispatch-sync-fallback", {
15108
+ log20.warn("run.dispatch-sync-fallback", {
15061
15109
  runId,
15062
15110
  projectName: project.name,
15063
15111
  provider,
@@ -15071,7 +15119,7 @@ var Scheduler = class {
15071
15119
  lastRunAt: now,
15072
15120
  nextRunAt
15073
15121
  });
15074
- log19.info("run.triggered", {
15122
+ log20.info("run.triggered", {
15075
15123
  runId,
15076
15124
  projectName: project.name,
15077
15125
  providers: providers ?? "all",
@@ -15080,14 +15128,14 @@ var Scheduler = class {
15080
15128
  this.callbacks.onRunCreated(runId, projectId, providers, resolvedLocation);
15081
15129
  return SLOT_FIRED;
15082
15130
  } catch (err) {
15083
- log19.error("trigger.error", { scheduleId, projectId, kind, error: describeError(err) });
15131
+ log20.error("trigger.error", { scheduleId, projectId, kind, error: describeError(err) });
15084
15132
  return { status: OutcomeStatuses.failed, ...outcomeFailure(err) };
15085
15133
  }
15086
15134
  }
15087
15135
  };
15088
15136
 
15089
15137
  // src/site-liveness-loop.ts
15090
- var log20 = createLogger("SiteLiveness");
15138
+ var log21 = createLogger("SiteLiveness");
15091
15139
  var SITE_LIVENESS_INTERVAL_MS = 10 * 6e4;
15092
15140
  async function runSiteLivenessPass(deps) {
15093
15141
  const now = deps.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
@@ -15104,10 +15152,10 @@ async function runSiteLivenessPass(deps) {
15104
15152
  const event = await deps.notify(project.id, { check, checkedAt: now() });
15105
15153
  if (event) {
15106
15154
  events += 1;
15107
- log20.info("site-liveness.notified", { projectName: project.name, event, code: check.code });
15155
+ log21.info("site-liveness.notified", { projectName: project.name, event, code: check.code });
15108
15156
  }
15109
15157
  } catch (err) {
15110
- log20.warn("site-liveness.project-failed", { projectName: project.name, err: String(err) });
15158
+ log21.warn("site-liveness.project-failed", { projectName: project.name, err: String(err) });
15111
15159
  if (failed === 0) firstFailure = err;
15112
15160
  failed += 1;
15113
15161
  }
@@ -15139,14 +15187,14 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
15139
15187
  };
15140
15188
  const timer = setInterval(() => {
15141
15189
  if (running) {
15142
- log20.warn("site-liveness.pass-still-running", { intervalMs });
15190
+ log21.warn("site-liveness.pass-still-running", { intervalMs });
15143
15191
  report({ status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.OPERATION_IN_PROGRESS });
15144
15192
  return;
15145
15193
  }
15146
15194
  running = true;
15147
15195
  const elapsed = startOutcomeTimer();
15148
15196
  void runSiteLivenessPass(deps).then((result) => report({ ...livenessOutcome(result), durationBucket: elapsed() })).catch((err) => {
15149
- log20.warn("site-liveness.pass-failed", { err: String(err) });
15197
+ log21.warn("site-liveness.pass-failed", { err: String(err) });
15150
15198
  report({ status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() });
15151
15199
  }).finally(() => {
15152
15200
  running = false;
@@ -15158,8 +15206,8 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
15158
15206
 
15159
15207
  // src/review-webhook-delivery.ts
15160
15208
  import { createHash as createHash7 } from "crypto";
15161
- import { and as and20, asc as asc4, eq as eq24, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
15162
- var log21 = createLogger("ReviewDelivery");
15209
+ import { and as and20, asc as asc4, eq as eq25, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
15210
+ var log22 = createLogger("ReviewDelivery");
15163
15211
  var hash = (value) => createHash7("sha256").update(JSON.stringify(value)).digest("hex");
15164
15212
  var REVIEW_DELIVERY_MAX_ATTEMPTS = 10;
15165
15213
  var REVIEW_CHAT_SENDS_PER_PASS = 3;
@@ -15186,20 +15234,20 @@ function reviewEventId(projectId, review) {
15186
15234
  function reviewEventRefusal(db, projectId, payload, notification, targetDigest, now) {
15187
15235
  if (!notification?.enabled || !notification.config.events.includes("review.negative")) return "destination_disabled";
15188
15236
  if (targetDigest !== void 0 && hash(notification.config.url) !== targetDigest) return "destination_changed";
15189
- const project = db.select().from(projects).where(eq24(projects.id, projectId)).get();
15237
+ const project = db.select().from(projects).where(eq25(projects.id, projectId)).get();
15190
15238
  if (!project || project.name !== payload.project.name || project.canonicalDomain !== payload.project.canonicalDomain) return "project_changed";
15191
15239
  const review = payload.reviews[0];
15192
15240
  const location = db.select().from(gbpLocations).where(and20(
15193
- eq24(gbpLocations.projectId, projectId),
15194
- eq24(gbpLocations.locationName, review.location.name),
15195
- eq24(gbpLocations.selected, true)
15241
+ eq25(gbpLocations.projectId, projectId),
15242
+ eq25(gbpLocations.locationName, review.location.name),
15243
+ eq25(gbpLocations.selected, true)
15196
15244
  )).get();
15197
15245
  if (!location || review.origin === "gbp" && !review.reviewName.startsWith(`${location.accountName}/${location.locationName}/reviews/`)) return "location_removed_or_deselected";
15198
15246
  const current = db.select().from(gbpReviews).where(and20(
15199
- eq24(gbpReviews.projectId, projectId),
15200
- eq24(gbpReviews.origin, review.origin),
15201
- eq24(gbpReviews.reviewName, review.reviewName),
15202
- eq24(gbpReviews.locationName, review.location.name)
15247
+ eq25(gbpReviews.projectId, projectId),
15248
+ eq25(gbpReviews.origin, review.origin),
15249
+ eq25(gbpReviews.reviewName, review.reviewName),
15250
+ eq25(gbpReviews.locationName, review.location.name)
15203
15251
  )).get();
15204
15252
  if (!current) return "review_removed";
15205
15253
  if (!isWithinAlertWindow(review.updateTime, now) || !isWithinAlertWindow(current.updateTime, now)) return "review_expired";
@@ -15208,9 +15256,9 @@ function reviewEventRefusal(db, projectId, payload, notification, targetDigest,
15208
15256
  if (["baseline", "skipped", "suppressed", "stale", "none"].includes(current.alertState)) return "review_suppressed";
15209
15257
  if (review.origin === "places") {
15210
15258
  const v4HasWorked = db.select({ id: gbpReviewRatings.id }).from(gbpReviewRatings).where(and20(
15211
- eq24(gbpReviewRatings.projectId, projectId),
15212
- eq24(gbpReviewRatings.locationName, review.location.name),
15213
- eq24(gbpReviewRatings.origin, "gbp")
15259
+ eq25(gbpReviewRatings.projectId, projectId),
15260
+ eq25(gbpReviewRatings.locationName, review.location.name),
15261
+ eq25(gbpReviewRatings.origin, "gbp")
15214
15262
  )).get() !== void 0;
15215
15263
  if (businessProfileReviewsCover(location.reviewsAccess, v4HasWorked)) return "review_origin_superseded";
15216
15264
  }
@@ -15219,8 +15267,8 @@ function reviewEventRefusal(db, projectId, payload, notification, targetDigest,
15219
15267
  function cancelReviewDelivery(db, id, reason) {
15220
15268
  db.transaction((tx) => {
15221
15269
  const canceled = tx.update(reviewWebhookDeliveries).set({ state: ReviewDeliveryStates.Canceled, retryAt: null }).where(and20(
15222
- eq24(reviewWebhookDeliveries.id, id),
15223
- eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending)
15270
+ eq25(reviewWebhookDeliveries.id, id),
15271
+ eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending)
15224
15272
  )).returning({ projectId: reviewWebhookDeliveries.projectId, eventId: reviewWebhookDeliveries.eventId, notificationId: reviewWebhookDeliveries.notificationId, targetDigest: reviewWebhookDeliveries.targetDigest }).get();
15225
15273
  if (canceled) writeAuditLog(tx, {
15226
15274
  projectId: canceled.projectId,
@@ -15237,9 +15285,9 @@ function deferReviewDelivery(db, saved, now) {
15237
15285
  const waited = now - Date.parse(saved.createdAt);
15238
15286
  const delay = Math.min(Math.max(RETRY_BASE_MS, Number.isFinite(waited) ? waited / 4 : RETRY_BASE_MS), RETRY_MAX_MS);
15239
15287
  db.update(reviewWebhookDeliveries).set({ retryAt: new Date(now + delay).toISOString() }).where(and20(
15240
- eq24(reviewWebhookDeliveries.id, saved.id),
15241
- eq24(reviewWebhookDeliveries.state, saved.state),
15242
- eq24(reviewWebhookDeliveries.attempts, saved.attempts)
15288
+ eq25(reviewWebhookDeliveries.id, saved.id),
15289
+ eq25(reviewWebhookDeliveries.state, saved.state),
15290
+ eq25(reviewWebhookDeliveries.attempts, saved.attempts)
15243
15291
  )).run();
15244
15292
  }
15245
15293
  function auditUndelivered(db, saved, outcome) {
@@ -15256,8 +15304,8 @@ function dueReviewDeliveryProjects(db, now) {
15256
15304
  const at = new Date(now).toISOString();
15257
15305
  const staleAttempt = new Date(now - 6e4).toISOString();
15258
15306
  return db.selectDistinct({ projectId: reviewWebhookDeliveries.projectId }).from(reviewWebhookDeliveries).where(or(
15259
- and20(eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending), or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at))),
15260
- and20(eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
15307
+ and20(eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending), or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at))),
15308
+ and20(eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
15261
15309
  )).all().map((row) => row.projectId);
15262
15310
  }
15263
15311
  function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS) {
@@ -15266,7 +15314,7 @@ function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS
15266
15314
  if (running) return;
15267
15315
  running = true;
15268
15316
  void drain().catch((err) => {
15269
- log21.warn("review-delivery.drain-failed", { error: describeError(err) });
15317
+ log22.warn("review-delivery.drain-failed", { error: describeError(err) });
15270
15318
  }).finally(() => {
15271
15319
  running = false;
15272
15320
  });
@@ -15279,11 +15327,11 @@ async function drainReviewDeliveries(options) {
15279
15327
  const at = new Date(now).toISOString();
15280
15328
  const staleAttempt = new Date(now - 6e4).toISOString();
15281
15329
  const ready = options.db.select().from(reviewWebhookDeliveries).where(and20(
15282
- eq24(reviewWebhookDeliveries.projectId, options.projectId),
15330
+ eq25(reviewWebhookDeliveries.projectId, options.projectId),
15283
15331
  or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at)),
15284
15332
  or(
15285
- eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
15286
- and20(eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
15333
+ eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
15334
+ and20(eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
15287
15335
  )
15288
15336
  )).orderBy(asc4(reviewWebhookDeliveries.retryAt), asc4(reviewWebhookDeliveries.attemptedAt), asc4(reviewWebhookDeliveries.createdAt), asc4(reviewWebhookDeliveries.id)).limit(100).all();
15289
15337
  let delivered = 0;
@@ -15308,14 +15356,14 @@ async function deliverReviewEvent(options) {
15308
15356
  return false;
15309
15357
  const notification = db.select().from(notifications).where(
15310
15358
  and20(
15311
- eq24(notifications.id, notificationId),
15312
- eq24(notifications.projectId, projectId)
15359
+ eq25(notifications.id, notificationId),
15360
+ eq25(notifications.projectId, projectId)
15313
15361
  )
15314
15362
  ).get();
15315
15363
  const id = hash([projectId, notificationId, payload.eventId]);
15316
15364
  const now = options.now ?? Date.now;
15317
15365
  const at = new Date(now()).toISOString();
15318
- let saved = db.select().from(reviewWebhookDeliveries).where(eq24(reviewWebhookDeliveries.id, id)).get();
15366
+ let saved = db.select().from(reviewWebhookDeliveries).where(eq25(reviewWebhookDeliveries.id, id)).get();
15319
15367
  const event = saved?.payload ?? payload;
15320
15368
  const refusal = reviewEventRefusal(db, projectId, event, notification, saved?.targetDigest, new Date(now()));
15321
15369
  if (refusal) {
@@ -15334,7 +15382,7 @@ async function deliverReviewEvent(options) {
15334
15382
  payload,
15335
15383
  createdAt: at
15336
15384
  }).onConflictDoNothing().run();
15337
- saved = db.select().from(reviewWebhookDeliveries).where(eq24(reviewWebhookDeliveries.id, id)).get();
15385
+ saved = db.select().from(reviewWebhookDeliveries).where(eq25(reviewWebhookDeliveries.id, id)).get();
15338
15386
  if (!saved || saved.targetDigest !== targetDigest) return false;
15339
15387
  if (saved.state === ReviewDeliveryStates.Sent) return true;
15340
15388
  if (saved.state === ReviewDeliveryStates.Uncertain || saved.state === ReviewDeliveryStates.Canceled) return false;
@@ -15350,16 +15398,16 @@ async function deliverReviewEvent(options) {
15350
15398
  const state2 = destination.signed ? ReviewDeliveryStates.Pending : ReviewDeliveryStates.Uncertain;
15351
15399
  const moved = db.update(reviewWebhookDeliveries).set({ state: state2 }).where(
15352
15400
  and20(
15353
- eq24(reviewWebhookDeliveries.id, id),
15354
- eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
15355
- eq24(reviewWebhookDeliveries.attempts, saved.attempts),
15356
- eq24(reviewWebhookDeliveries.attemptedAt, saved.attemptedAt)
15401
+ eq25(reviewWebhookDeliveries.id, id),
15402
+ eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
15403
+ eq25(reviewWebhookDeliveries.attempts, saved.attempts),
15404
+ eq25(reviewWebhookDeliveries.attemptedAt, saved.attemptedAt)
15357
15405
  )
15358
15406
  ).returning({ id: reviewWebhookDeliveries.id }).get();
15359
15407
  if (moved && state2 === ReviewDeliveryStates.Uncertain) {
15360
15408
  auditUndelivered(db, saved, { state: state2, reason: "interrupted_attempt", attempts: saved.attempts });
15361
15409
  }
15362
- saved = db.select().from(reviewWebhookDeliveries).where(eq24(reviewWebhookDeliveries.id, id)).get();
15410
+ saved = db.select().from(reviewWebhookDeliveries).where(eq25(reviewWebhookDeliveries.id, id)).get();
15363
15411
  if (!saved || saved.state !== ReviewDeliveryStates.Pending) return false;
15364
15412
  }
15365
15413
  if (saved.retryAt && Date.parse(saved.retryAt) > now()) return false;
@@ -15382,8 +15430,8 @@ async function deliverReviewEvent(options) {
15382
15430
  }
15383
15431
  const latest = db.select().from(notifications).where(
15384
15432
  and20(
15385
- eq24(notifications.id, notificationId),
15386
- eq24(notifications.projectId, projectId)
15433
+ eq25(notifications.id, notificationId),
15434
+ eq25(notifications.projectId, projectId)
15387
15435
  )
15388
15436
  ).get();
15389
15437
  const latestRefusal = reviewEventRefusal(db, projectId, saved.payload, latest, targetDigest, new Date(now()));
@@ -15397,9 +15445,9 @@ async function deliverReviewEvent(options) {
15397
15445
  attemptedAt: new Date(now()).toISOString()
15398
15446
  }).where(
15399
15447
  and20(
15400
- eq24(reviewWebhookDeliveries.id, id),
15401
- eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
15402
- eq24(reviewWebhookDeliveries.attempts, saved.attempts)
15448
+ eq25(reviewWebhookDeliveries.id, id),
15449
+ eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
15450
+ eq25(reviewWebhookDeliveries.attempts, saved.attempts)
15403
15451
  )
15404
15452
  ).returning({ id: reviewWebhookDeliveries.id }).get();
15405
15453
  if (!claimed) return false;
@@ -15427,9 +15475,9 @@ async function deliverReviewEvent(options) {
15427
15475
  retryAt: state === ReviewDeliveryStates.Pending ? new Date(now() + retryDelayMs(attempts, result.retryAfterSeconds)).toISOString() : null
15428
15476
  }).where(
15429
15477
  and20(
15430
- eq24(reviewWebhookDeliveries.id, id),
15431
- eq24(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
15432
- eq24(reviewWebhookDeliveries.attempts, attempts)
15478
+ eq25(reviewWebhookDeliveries.id, id),
15479
+ eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
15480
+ eq25(reviewWebhookDeliveries.attempts, attempts)
15433
15481
  )
15434
15482
  ).run();
15435
15483
  if (state === ReviewDeliveryStates.Uncertain || state === ReviewDeliveryStates.Failed) {
@@ -15441,7 +15489,7 @@ async function deliverReviewEvent(options) {
15441
15489
  }
15442
15490
 
15443
15491
  // src/unrecognized-agent-alerts.ts
15444
- import { and as and21, desc as desc8, eq as eq25, gte as gte3, sql as sql10 } from "drizzle-orm";
15492
+ import { and as and21, desc as desc8, eq as eq26, gte as gte3, sql as sql10 } from "drizzle-orm";
15445
15493
 
15446
15494
  // src/alert-loop.ts
15447
15495
  function startAlertLoop(dispatch, intervalMs, onError) {
@@ -15458,7 +15506,7 @@ function startAlertLoop(dispatch, intervalMs, onError) {
15458
15506
  }
15459
15507
 
15460
15508
  // src/unrecognized-agent-alerts.ts
15461
- var log22 = createLogger("UnrecognizedAgentAlerts");
15509
+ var log23 = createLogger("UnrecognizedAgentAlerts");
15462
15510
  var UNRECOGNIZED_AGENT_ALERT_WINDOW_MS = 7 * 864e5;
15463
15511
  var UNRECOGNIZED_AGENT_ALERT_MIN_HITS = 3;
15464
15512
  var UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS = 15 * 6e4;
@@ -15473,13 +15521,13 @@ function projectsWithRecentUnrecognizedAgents(db, now) {
15473
15521
  return db.selectDistinct({ projectId: unrecognizedAgentEventsHourly.projectId }).from(unrecognizedAgentEventsHourly).where(gte3(unrecognizedAgentEventsHourly.tsHour, since)).all().map((row) => row.projectId);
15474
15522
  }
15475
15523
  function undecidedUnrecognizedAgents(db, projectId, now) {
15476
- const decided = new Set(db.select({ agentName: unrecognizedAgentNotifyState.agentName }).from(unrecognizedAgentNotifyState).where(eq25(unrecognizedAgentNotifyState.projectId, projectId)).all().map((row) => row.agentName));
15524
+ const decided = new Set(db.select({ agentName: unrecognizedAgentNotifyState.agentName }).from(unrecognizedAgentNotifyState).where(eq26(unrecognizedAgentNotifyState.projectId, projectId)).all().map((row) => row.agentName));
15477
15525
  const totals = db.select({
15478
15526
  name: unrecognizedAgentEventsHourly.agentName,
15479
15527
  hits: sql10`SUM(${unrecognizedAgentEventsHourly.hits})`,
15480
15528
  firstSeenAt: sql10`MIN(${unrecognizedAgentEventsHourly.tsHour})`,
15481
15529
  lastSeenAt: sql10`MAX(${unrecognizedAgentEventsHourly.tsHour})`
15482
- }).from(unrecognizedAgentEventsHourly).where(eq25(unrecognizedAgentEventsHourly.projectId, projectId)).groupBy(unrecognizedAgentEventsHourly.agentName).all();
15530
+ }).from(unrecognizedAgentEventsHourly).where(eq26(unrecognizedAgentEventsHourly.projectId, projectId)).groupBy(unrecognizedAgentEventsHourly.agentName).all();
15483
15531
  const windowStart = new Date(now - UNRECOGNIZED_AGENT_ALERT_WINDOW_MS).toISOString();
15484
15532
  const recordingStart = totals.reduce((earliest, total) => earliest === null || total.firstSeenAt < earliest ? total.firstSeenAt : earliest, null);
15485
15533
  const baselineEnd = recordingStart === null ? null : new Date(Date.parse(recordingStart) + UNRECOGNIZED_AGENT_ALERT_WINDOW_MS).toISOString();
@@ -15497,7 +15545,7 @@ function undecidedUnrecognizedAgents(db, projectId, now) {
15497
15545
  continue;
15498
15546
  }
15499
15547
  if (Number(total.hits) < UNRECOGNIZED_AGENT_ALERT_MIN_HITS) continue;
15500
- const latest = db.select({ sampledUserAgent: unrecognizedAgentEventsHourly.sampledUserAgent, sampledPath: unrecognizedAgentEventsHourly.sampledPath }).from(unrecognizedAgentEventsHourly).where(and21(eq25(unrecognizedAgentEventsHourly.projectId, projectId), eq25(unrecognizedAgentEventsHourly.agentName, total.name))).orderBy(desc8(unrecognizedAgentEventsHourly.tsHour)).limit(1).get();
15548
+ const latest = db.select({ sampledUserAgent: unrecognizedAgentEventsHourly.sampledUserAgent, sampledPath: unrecognizedAgentEventsHourly.sampledPath }).from(unrecognizedAgentEventsHourly).where(and21(eq26(unrecognizedAgentEventsHourly.projectId, projectId), eq26(unrecognizedAgentEventsHourly.agentName, total.name))).orderBy(desc8(unrecognizedAgentEventsHourly.tsHour)).limit(1).get();
15501
15549
  due.push({
15502
15550
  name: total.name,
15503
15551
  hits: Number(total.hits),
@@ -15518,13 +15566,13 @@ function recordUnrecognizedAgentDecisions(db, projectId, names, state, now) {
15518
15566
  }
15519
15567
  function startUnrecognizedAgentAlertLoop(dispatch, intervalMs = UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS) {
15520
15568
  return startAlertLoop(dispatch, intervalMs, (err) => {
15521
- log22.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
15569
+ log23.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
15522
15570
  });
15523
15571
  }
15524
15572
 
15525
15573
  // src/sentiment-alerts.ts
15526
- import { and as and22, asc as asc5, eq as eq26, gte as gte4, inArray as inArray11, sql as sql11 } from "drizzle-orm";
15527
- var log23 = createLogger("SentimentAlerts");
15574
+ import { and as and22, asc as asc5, eq as eq27, gte as gte4, inArray as inArray11, sql as sql11 } from "drizzle-orm";
15575
+ var log24 = createLogger("SentimentAlerts");
15528
15576
  var SENTIMENT_ALERT_WINDOW_MS = 7 * 864e5;
15529
15577
  var SENTIMENT_ALERT_INTERVAL_MS = 5 * 6e4;
15530
15578
  var SentimentAlertStates = {
@@ -15545,7 +15593,7 @@ function settledSentimentRuns(db, now) {
15545
15593
  open: sql11`SUM(${sentimentJobs.pendingItems} + ${sentimentJobs.runningItems})`,
15546
15594
  lastReceipt,
15547
15595
  reconciled: sentimentSettings.reconciledSequence
15548
- }).from(sentimentJobs).innerJoin(runs, and22(eq26(runs.projectId, sentimentJobs.projectId), sql11`${runs.id} = ${jobRunId}`)).leftJoin(sentimentSettings, eq26(sentimentSettings.projectId, sentimentJobs.projectId)).where(and22(eq26(sentimentJobs.action, AUTOMATIC), gte4(sentimentJobs.createdAt, since), notProbeRun())).groupBy(sentimentJobs.projectId, runs.id).orderBy(asc5(runs.createdAt), asc5(runs.id)).all();
15596
+ }).from(sentimentJobs).innerJoin(runs, and22(eq27(runs.projectId, sentimentJobs.projectId), sql11`${runs.id} = ${jobRunId}`)).leftJoin(sentimentSettings, eq27(sentimentSettings.projectId, sentimentJobs.projectId)).where(and22(eq27(sentimentJobs.action, AUTOMATIC), gte4(sentimentJobs.createdAt, since), notProbeRun())).groupBy(sentimentJobs.projectId, runs.id).orderBy(asc5(runs.createdAt), asc5(runs.id)).all();
15549
15597
  const settled = /* @__PURE__ */ new Map();
15550
15598
  const waiting = /* @__PURE__ */ new Set();
15551
15599
  for (const row of rows) {
@@ -15563,8 +15611,8 @@ function settledSentimentRuns(db, now) {
15563
15611
  }
15564
15612
  function undecidedSentimentRuns(db, projectId, runIds) {
15565
15613
  if (runIds.length === 0) return { undecided: [], firstPass: false };
15566
- const decided = new Set(db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(and22(eq26(sentimentAlertRuns.projectId, projectId), inArray11(sentimentAlertRuns.runId, [...runIds]))).all().map((row) => row.runId));
15567
- const firstPass = db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(eq26(sentimentAlertRuns.projectId, projectId)).limit(1).get() === void 0;
15614
+ const decided = new Set(db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(and22(eq27(sentimentAlertRuns.projectId, projectId), inArray11(sentimentAlertRuns.runId, [...runIds]))).all().map((row) => row.runId));
15615
+ const firstPass = db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(eq27(sentimentAlertRuns.projectId, projectId)).limit(1).get() === void 0;
15568
15616
  return { undecided: runIds.filter((runId) => !decided.has(runId)), firstPass };
15569
15617
  }
15570
15618
  function recordSentimentAlertRuns(db, projectId, runIds, state, now) {
@@ -15575,13 +15623,13 @@ function recordSentimentAlertRuns(db, projectId, runIds, state, now) {
15575
15623
  }
15576
15624
  function startSentimentAlertLoop(dispatch, intervalMs = SENTIMENT_ALERT_INTERVAL_MS) {
15577
15625
  return startAlertLoop(dispatch, intervalMs, (err) => {
15578
- log23.warn("sentiment-alerts.dispatch-failed", { error: describeError(err) });
15626
+ log24.warn("sentiment-alerts.dispatch-failed", { error: describeError(err) });
15579
15627
  });
15580
15628
  }
15581
15629
 
15582
15630
  // src/provider-batch-poller.ts
15583
- import { and as and23, eq as eq27, inArray as inArray12, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql12 } from "drizzle-orm";
15584
- var log24 = createLogger("ProviderBatchPoller");
15631
+ import { and as and23, eq as eq28, inArray as inArray12, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql12 } from "drizzle-orm";
15632
+ var log25 = createLogger("ProviderBatchPoller");
15585
15633
  var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
15586
15634
  var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
15587
15635
  var PROVIDER_BATCH_CANCEL_GRACE_MS = 60 * 6e4;
@@ -15605,7 +15653,7 @@ var ProviderBatchPoller = class {
15605
15653
  try {
15606
15654
  if (await this.advance(row)) settledRuns.set(row.runId, row.projectId);
15607
15655
  } catch (err) {
15608
- log24.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15656
+ log25.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15609
15657
  this.reschedule(row.id, null);
15610
15658
  }
15611
15659
  }
@@ -15614,7 +15662,7 @@ var ProviderBatchPoller = class {
15614
15662
  try {
15615
15663
  this.deps.runner.finalizeBatchRun(runId, projectId);
15616
15664
  } catch (err) {
15617
- log24.warn("batch.finalize-failed", { runId, error: describeError(err) });
15665
+ log25.warn("batch.finalize-failed", { runId, error: describeError(err) });
15618
15666
  }
15619
15667
  }
15620
15668
  }
@@ -15623,7 +15671,7 @@ var ProviderBatchPoller = class {
15623
15671
  * outstanding (ingested or cancelled), so its run may now finalize.
15624
15672
  */
15625
15673
  async advance(row) {
15626
- const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq27(runs.id, row.runId)).get()?.status;
15674
+ const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq28(runs.id, row.runId)).get()?.status;
15627
15675
  if (runStatus !== RunStatuses.running) {
15628
15676
  await this.deps.runner.abandonProviderBatches([row.id], "Cancelled because its run is no longer running.");
15629
15677
  this.schedule.delete(row.id);
@@ -15640,15 +15688,15 @@ var ProviderBatchPoller = class {
15640
15688
  status = poll.status;
15641
15689
  if (poll.status === "ended") {
15642
15690
  const endedAt = poll.endedAt ?? new Date(this.now()).toISOString();
15643
- const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and23(eq27(providerBatches.id, row.id), eq27(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15691
+ const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and23(eq28(providerBatches.id, row.id), eq28(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15644
15692
  this.schedule.delete(row.id);
15645
15693
  return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
15646
15694
  }
15647
15695
  } catch (err) {
15648
- log24.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15696
+ log25.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15649
15697
  }
15650
15698
  } else {
15651
- log24.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
15699
+ log25.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
15652
15700
  }
15653
15701
  this.reschedule(row.id, status);
15654
15702
  return this.enforceDeadline(row, registered);
@@ -15665,17 +15713,17 @@ var ProviderBatchPoller = class {
15665
15713
  if (row.cancelRequestedAt === null) {
15666
15714
  if (now < Date.parse(row.deadlineAt)) return false;
15667
15715
  const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and23(
15668
- eq27(providerBatches.id, row.id),
15669
- eq27(providerBatches.status, ProviderBatchStatuses.submitted),
15716
+ eq28(providerBatches.id, row.id),
15717
+ eq28(providerBatches.status, ProviderBatchStatuses.submitted),
15670
15718
  isNull4(providerBatches.cancelRequestedAt)
15671
15719
  )).run().changes === 1;
15672
15720
  if (!claimed) return false;
15673
- log24.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
15721
+ log25.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
15674
15722
  if (registered?.adapter.batch && row.providerBatchId) {
15675
15723
  try {
15676
15724
  await registered.adapter.batch.cancel(row.providerBatchId, registered.config);
15677
15725
  } catch (err) {
15678
- log24.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
15726
+ log25.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
15679
15727
  }
15680
15728
  }
15681
15729
  return false;
@@ -15685,9 +15733,9 @@ var ProviderBatchPoller = class {
15685
15733
  status: ProviderBatchStatuses.cancelled,
15686
15734
  error: `The provider batch did not end within an hour of being cancelled at its deadline; its ${row.requestCount} answer(s) were not recorded.`,
15687
15735
  updatedAt: at
15688
- }).where(and23(eq27(providerBatches.id, row.id), eq27(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15736
+ }).where(and23(eq28(providerBatches.id, row.id), eq28(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15689
15737
  this.schedule.delete(row.id);
15690
- if (gaveUp) log24.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
15738
+ if (gaveUp) log25.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
15691
15739
  return gaveUp;
15692
15740
  }
15693
15741
  async ingest(row) {
@@ -15696,7 +15744,7 @@ var ProviderBatchPoller = class {
15696
15744
  return result.kind !== "skipped";
15697
15745
  } catch (err) {
15698
15746
  const error = describeError(err);
15699
- log24.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
15747
+ log25.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
15700
15748
  const now = this.now();
15701
15749
  const unreadable = row.resultsExpireAt !== null && now >= Date.parse(row.resultsExpireAt);
15702
15750
  if (unreadable || now >= Date.parse(row.deadlineAt) + PROVIDER_BATCH_CANCEL_GRACE_MS) {
@@ -15726,9 +15774,9 @@ var ProviderBatchPoller = class {
15726
15774
  finalizableRuns() {
15727
15775
  const holding = [ProviderBatchStatuses.submitting, ...OUTSTANDING_PROVIDER_BATCH_STATUSES];
15728
15776
  return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and23(
15729
- eq27(runs.status, RunStatuses.running),
15777
+ eq28(runs.status, RunStatuses.running),
15730
15778
  isNotNull3(runs.pendingProviderErrors),
15731
- notExists2(this.deps.db.select({ one: sql12`1` }).from(providerBatches).where(and23(eq27(providerBatches.runId, runs.id), inArray12(providerBatches.status, holding))))
15779
+ notExists2(this.deps.db.select({ one: sql12`1` }).from(providerBatches).where(and23(eq28(providerBatches.runId, runs.id), inArray12(providerBatches.status, holding))))
15732
15780
  )).all();
15733
15781
  }
15734
15782
  };
@@ -15738,7 +15786,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
15738
15786
  const timer = setInterval(() => {
15739
15787
  if (running) return;
15740
15788
  running = true;
15741
- void poller.tick().catch((err) => log24.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
15789
+ void poller.tick().catch((err) => log25.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
15742
15790
  running = false;
15743
15791
  });
15744
15792
  }, intervalMs);
@@ -15747,7 +15795,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
15747
15795
  }
15748
15796
 
15749
15797
  // src/data-refresh.ts
15750
- var log25 = createLogger("DataRefresh");
15798
+ var log26 = createLogger("DataRefresh");
15751
15799
  function gaRefreshDays(now = /* @__PURE__ */ new Date()) {
15752
15800
  const [reportMonth] = reportMonthsForDoctor(void 0, now);
15753
15801
  const reach = inclusiveDayCount(`${reportMonth}-01`, now.toISOString().slice(0, 10)) ?? 0;
@@ -15789,15 +15837,15 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
15789
15837
  if (result.status === "rejected") {
15790
15838
  const reason = result.reason;
15791
15839
  const message = describeError(reason);
15792
- log25.warn("integration.refresh-failed", { projectName, integration, error: message });
15840
+ log26.warn("integration.refresh-failed", { projectName, integration, error: message });
15793
15841
  return;
15794
15842
  }
15795
15843
  switch (completion) {
15796
15844
  case "synchronous":
15797
- log25.info("integration.refreshed", { projectName, integration });
15845
+ log26.info("integration.refreshed", { projectName, integration });
15798
15846
  return;
15799
15847
  case "queued":
15800
- log25.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
15848
+ log26.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
15801
15849
  return;
15802
15850
  default: {
15803
15851
  const _exhaustive = completion;
@@ -15808,12 +15856,12 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
15808
15856
  }
15809
15857
 
15810
15858
  // src/notifier.ts
15811
- import { eq as eq29, desc as desc10, and as and25, inArray as inArray13, or as or2, isNull as isNull5 } from "drizzle-orm";
15859
+ import { eq as eq30, desc as desc10, and as and25, inArray as inArray13, or as or2, isNull as isNull5 } from "drizzle-orm";
15812
15860
  import crypto25 from "crypto";
15813
15861
 
15814
15862
  // src/site-health-alerts.ts
15815
15863
  import crypto24 from "crypto";
15816
- import { and as and24, asc as asc6, desc as desc9, eq as eq28, gt as gt3 } from "drizzle-orm";
15864
+ import { and as and24, asc as asc6, desc as desc9, eq as eq29, gt as gt3 } from "drizzle-orm";
15817
15865
  var ISSUE_TITLES = {
15818
15866
  "missing-h1": "Missing H1",
15819
15867
  "multiple-h1": "Multiple H1 tags",
@@ -15826,12 +15874,12 @@ function siteHealthProblemKey(code, url) {
15826
15874
  return `${code}|${crypto24.createHash("sha256").update(url).digest("hex").slice(0, 16)}`;
15827
15875
  }
15828
15876
  function readSiteHealthScan(db, projectId, runId) {
15829
- const snapshot = db.select().from(siteCrawlSnapshots).where(and24(eq28(siteCrawlSnapshots.projectId, projectId), eq28(siteCrawlSnapshots.runId, runId))).orderBy(desc9(siteCrawlSnapshots.updatedAt)).limit(1).get();
15877
+ const snapshot = db.select().from(siteCrawlSnapshots).where(and24(eq29(siteCrawlSnapshots.projectId, projectId), eq29(siteCrawlSnapshots.runId, runId))).orderBy(desc9(siteCrawlSnapshots.updatedAt)).limit(1).get();
15830
15878
  if (!snapshot?.detailsAvailable || !snapshot.attemptId) return null;
15831
15879
  const scope = and24(
15832
- eq28(siteCrawlPages.projectId, projectId),
15833
- eq28(siteCrawlPages.runId, runId),
15834
- eq28(siteCrawlPages.attemptId, snapshot.attemptId)
15880
+ eq29(siteCrawlPages.projectId, projectId),
15881
+ eq29(siteCrawlPages.runId, runId),
15882
+ eq29(siteCrawlPages.attemptId, snapshot.attemptId)
15835
15883
  );
15836
15884
  const pagesByCode = /* @__PURE__ */ new Map();
15837
15885
  const keys = /* @__PURE__ */ new Set();
@@ -15879,7 +15927,7 @@ function settledSiteHealthKeys(scan, reported) {
15879
15927
  return [...scan.complete ? scan.keys : /* @__PURE__ */ new Set([...reported, ...scan.keys])].sort(compareText);
15880
15928
  }
15881
15929
  function readSiteHealthNotifyState(db, projectId) {
15882
- return db.select().from(siteHealthNotifyState).where(eq28(siteHealthNotifyState.projectId, projectId)).get() ?? null;
15930
+ return db.select().from(siteHealthNotifyState).where(eq29(siteHealthNotifyState.projectId, projectId)).get() ?? null;
15883
15931
  }
15884
15932
  function writeSiteHealthNotifyState(db, input) {
15885
15933
  const values = { reportedKeys: input.reportedKeys, runId: input.runId, updatedAt: input.updatedAt, notifiedAt: input.notifiedAt };
@@ -15887,7 +15935,7 @@ function writeSiteHealthNotifyState(db, input) {
15887
15935
  }
15888
15936
 
15889
15937
  // src/notifier.ts
15890
- var log26 = createLogger("Notifier");
15938
+ var log27 = createLogger("Notifier");
15891
15939
  var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
15892
15940
  function trackWebhookDelivery(input) {
15893
15941
  const sample = sampleDelivery(input.failure ? "failed" : "succeeded");
@@ -16018,26 +16066,26 @@ var Notifier = class {
16018
16066
  }
16019
16067
  /** Called after a run completes (success, partial, or failed). */
16020
16068
  async onRunCompleted(runId, projectId, opts) {
16021
- log26.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
16022
- const notifs = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16069
+ log27.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
16070
+ const notifs = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16023
16071
  if (notifs.length === 0) {
16024
- log26.info("notifications.none-enabled", { projectId });
16072
+ log27.info("notifications.none-enabled", { projectId });
16025
16073
  return;
16026
16074
  }
16027
- log26.info("notifications.found", { projectId, count: notifs.length });
16028
- const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16075
+ log27.info("notifications.found", { projectId, count: notifs.length });
16076
+ const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
16029
16077
  if (!run) {
16030
- log26.error("run.not-found", { runId, msg: "skipping notification dispatch" });
16078
+ log27.error("run.not-found", { runId, msg: "skipping notification dispatch" });
16031
16079
  return;
16032
16080
  }
16033
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16081
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
16034
16082
  if (!project) {
16035
- log26.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
16083
+ log27.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
16036
16084
  return;
16037
16085
  }
16038
16086
  const transitions = this.computeTransitions(runId, project);
16039
16087
  const events = [];
16040
- log26.info("run.status", { runId: run.id, status: run.status, projectId });
16088
+ log27.info("run.status", { runId: run.id, status: run.status, projectId });
16041
16089
  if ((run.status === "completed" || run.status === "partial") && opts?.origin !== "fill") {
16042
16090
  events.push("run.completed");
16043
16091
  }
@@ -16057,7 +16105,7 @@ var Notifier = class {
16057
16105
  if (!config.url) continue;
16058
16106
  const subscribedEvents = config.events;
16059
16107
  const matchingEvents = events.filter((e) => subscribedEvents.includes(e));
16060
- log26.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
16108
+ log27.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
16061
16109
  if (matchingEvents.length === 0) continue;
16062
16110
  for (const event of matchingEvents) {
16063
16111
  const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : event === "mention.lost" ? lostMentions : event === "mention.gained" ? gainedMentions : transitions.citation;
@@ -16113,9 +16161,9 @@ var Notifier = class {
16113
16161
  * than inferred from the absence of a webhook.
16114
16162
  */
16115
16163
  async onHealthChecked(projectId, report) {
16116
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16164
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
16117
16165
  if (!project) {
16118
- log26.error("project.not-found", { projectId, msg: "skipping health notification" });
16166
+ log27.error("project.not-found", { projectId, msg: "skipping health notification" });
16119
16167
  return null;
16120
16168
  }
16121
16169
  const rank = healthRank;
@@ -16146,7 +16194,7 @@ var Notifier = class {
16146
16194
  const status = noSignal ? "warn" : worst ? worst.status : "ok";
16147
16195
  const code = noSignal ? HEALTH_NO_SIGNAL_CODE : worst?.code ?? "health.ok";
16148
16196
  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.`;
16149
- const previous = this.db.select().from(doctorHealthState).where(eq29(doctorHealthState.projectId, projectId)).get();
16197
+ const previous = this.db.select().from(doctorHealthState).where(eq30(doctorHealthState.projectId, projectId)).get();
16150
16198
  const previousStatus = previous?.status ?? null;
16151
16199
  const failingSignature = failing.map((c) => `${c.status}:${c.code}`).join(",");
16152
16200
  const failingNow = failing.map((c) => ({ id: c.id, code: c.code, rank: rank(c.status) }));
@@ -16216,7 +16264,7 @@ var Notifier = class {
16216
16264
  const urgentById = new Map(urgentItems.map((item) => [item.id, item]));
16217
16265
  const generalEvent = event;
16218
16266
  const urgentRecord = previous?.urgentNotified ?? null;
16219
- const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16267
+ const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16220
16268
  const listedEvents = (notif) => notif.config.events;
16221
16269
  const hasUrl = (notif) => Boolean(notif.config.url);
16222
16270
  const urgentSubscribers = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -16264,7 +16312,7 @@ var Notifier = class {
16264
16312
  if (previous === void 0) {
16265
16313
  this.db.insert(doctorHealthState).values({ ...observation, notifiedAt: null }).run();
16266
16314
  } else {
16267
- this.db.update(doctorHealthState).set(observation).where(eq29(doctorHealthState.projectId, projectId)).run();
16315
+ this.db.update(doctorHealthState).set(observation).where(eq30(doctorHealthState.projectId, projectId)).run();
16268
16316
  }
16269
16317
  for (const group of urgentGroups) {
16270
16318
  const { urgentEvent, urgentTold, urgentNew, urgentCleared, urgentNotifs, urgentSettled } = group;
@@ -16308,10 +16356,10 @@ var Notifier = class {
16308
16356
  }
16309
16357
  if (accepted > 0) {
16310
16358
  recordUrgentReceipts(urgentReceipts, group.subscribers, formatUrgentBreaches(urgentSettled) || null);
16311
- this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq29(doctorHealthState.projectId, projectId)).run();
16359
+ this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq30(doctorHealthState.projectId, projectId)).run();
16312
16360
  }
16313
16361
  if (urgentNotifs.length > 0) {
16314
- log26.info("health.urgent-notified", {
16362
+ log27.info("health.urgent-notified", {
16315
16363
  projectId,
16316
16364
  event: urgentEvent,
16317
16365
  codes: urgentEvent === "health.urgent" ? breachCodes(urgentNew) : breachCodes(urgentCleared),
@@ -16322,9 +16370,9 @@ var Notifier = class {
16322
16370
  }
16323
16371
  if (!event) {
16324
16372
  if (clearedThisPass.length > 0 || easedThisPass.length > 0) {
16325
- log26.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
16373
+ log27.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
16326
16374
  } else {
16327
- log26.info("health.unchanged", { projectId, status, code });
16375
+ log27.info("health.unchanged", { projectId, status, code });
16328
16376
  }
16329
16377
  return null;
16330
16378
  }
@@ -16352,9 +16400,9 @@ var Notifier = class {
16352
16400
  if (await this.sendWebhook(config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) delivered += 1;
16353
16401
  }
16354
16402
  if (delivered > 0) {
16355
- this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq29(doctorHealthState.projectId, projectId)).run();
16403
+ this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq30(doctorHealthState.projectId, projectId)).run();
16356
16404
  }
16357
- log26.info("health.notified", {
16405
+ log27.info("health.notified", {
16358
16406
  projectId,
16359
16407
  event,
16360
16408
  status,
@@ -16382,12 +16430,12 @@ var Notifier = class {
16382
16430
  async onSiteLivenessChecked(projectId, result) {
16383
16431
  const { check, checkedAt } = result;
16384
16432
  if (check.status !== "ok" && check.status !== "fail") return null;
16385
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16433
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
16386
16434
  if (!project) {
16387
- log26.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
16435
+ log27.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
16388
16436
  return null;
16389
16437
  }
16390
- const previous = this.db.select().from(siteLivenessState).where(eq29(siteLivenessState.projectId, projectId)).get();
16438
+ const previous = this.db.select().from(siteLivenessState).where(eq30(siteLivenessState.projectId, projectId)).get();
16391
16439
  const sincePrevious = previous ? Date.parse(checkedAt) - Date.parse(previous.checkedAt) : Number.NaN;
16392
16440
  const countsAsRepeat = Number.isFinite(sincePrevious) && sincePrevious >= SITE_LIVENESS_MIN_PASS_GAP_MS && sincePrevious <= SITE_LIVENESS_MAX_PASS_GAP_MS;
16393
16441
  const failures = check.status === "fail" ? countsAsRepeat ? (previous?.consecutiveFailures ?? 0) + 1 : 1 : 0;
@@ -16397,7 +16445,7 @@ var Notifier = class {
16397
16445
  if (check.status === "ok" && outagePaged) event = "health.recovered";
16398
16446
  const confirmed = check.status === "fail" && failures >= SITE_LIVENESS_FAILURES_TO_PAGE;
16399
16447
  const urgentRecord = previous?.urgentNotifiedAt ?? null;
16400
- const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16448
+ const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
16401
16449
  const listedEvents = (notif) => notif.config.events;
16402
16450
  const hasUrl = (notif) => Boolean(notif.config.url);
16403
16451
  const scoped = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -16430,7 +16478,7 @@ var Notifier = class {
16430
16478
  if (previous === void 0) {
16431
16479
  this.db.insert(siteLivenessState).values(observation).run();
16432
16480
  } else {
16433
- this.db.update(siteLivenessState).set(observation).where(eq29(siteLivenessState.projectId, projectId)).run();
16481
+ this.db.update(siteLivenessState).set(observation).where(eq30(siteLivenessState.projectId, projectId)).run();
16434
16482
  }
16435
16483
  if (!event && urgentGroups.every((group) => group.urgentEvent === null)) return null;
16436
16484
  const payloadFor = (name) => {
@@ -16466,9 +16514,9 @@ var Notifier = class {
16466
16514
  }
16467
16515
  }
16468
16516
  if (event === "health.degraded" && delivered > 0) {
16469
- this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq29(siteLivenessState.projectId, projectId)).run();
16517
+ this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq30(siteLivenessState.projectId, projectId)).run();
16470
16518
  }
16471
- log26.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
16519
+ log27.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
16472
16520
  }
16473
16521
  for (const group of urgentGroups) {
16474
16522
  const { urgentEvent, urgentNotifs, generalIds } = group;
@@ -16480,10 +16528,10 @@ var Notifier = class {
16480
16528
  }
16481
16529
  if (accepted > 0) {
16482
16530
  recordUrgentReceipts(urgentReceipts, group.subscribers, group.settled);
16483
- this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq29(siteLivenessState.projectId, projectId)).run();
16531
+ this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq30(siteLivenessState.projectId, projectId)).run();
16484
16532
  }
16485
16533
  if (urgentNotifs.length > 0 || generalIds.size > 0) {
16486
- log26.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
16534
+ log27.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
16487
16535
  }
16488
16536
  }
16489
16537
  return event;
@@ -16506,7 +16554,7 @@ var Notifier = class {
16506
16554
  */
16507
16555
  isNewInsightNews(projectId, insight) {
16508
16556
  const key = insightNotifyKey(projectId, insight);
16509
- const previous = this.db.select().from(insightNotifyState).where(eq29(insightNotifyState.key, key)).get();
16557
+ const previous = this.db.select().from(insightNotifyState).where(eq30(insightNotifyState.key, key)).get();
16510
16558
  if (!previous) return true;
16511
16559
  if (severityRank(insight.severity) > severityRank(previous.severity)) return true;
16512
16560
  const magnitude = insightMagnitude(insight);
@@ -16528,9 +16576,9 @@ var Notifier = class {
16528
16576
  magnitude: insightMagnitude(insight),
16529
16577
  notifiedAt: (/* @__PURE__ */ new Date()).toISOString()
16530
16578
  };
16531
- const existing = this.db.select().from(insightNotifyState).where(eq29(insightNotifyState.key, key)).get();
16579
+ const existing = this.db.select().from(insightNotifyState).where(eq30(insightNotifyState.key, key)).get();
16532
16580
  if (existing) {
16533
- this.db.update(insightNotifyState).set(row).where(eq29(insightNotifyState.key, key)).run();
16581
+ this.db.update(insightNotifyState).set(row).where(eq30(insightNotifyState.key, key)).run();
16534
16582
  } else {
16535
16583
  this.db.insert(insightNotifyState).values(row).run();
16536
16584
  }
@@ -16544,11 +16592,11 @@ var Notifier = class {
16544
16592
  if (criticalInsights.length > 0) insightEvents.push("insight.critical");
16545
16593
  if (highInsights.length > 0) insightEvents.push("insight.high");
16546
16594
  if (insightEvents.length === 0) return;
16547
- const notifs = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16595
+ const notifs = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled);
16548
16596
  if (notifs.length === 0) return;
16549
- const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16597
+ const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
16550
16598
  if (!run) return;
16551
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16599
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
16552
16600
  if (!project) return;
16553
16601
  for (const notif of notifs) {
16554
16602
  const config = notif.config;
@@ -16629,9 +16677,9 @@ var Notifier = class {
16629
16677
  return delivered;
16630
16678
  }
16631
16679
  async dispatchQueuedReviewAlerts(projectId) {
16632
- const pendingReviews = this.db.select().from(gbpReviews).where(and25(eq29(gbpReviews.projectId, projectId), eq29(gbpReviews.alertState, "pending"))).all();
16633
- const pendingRatings = this.db.select().from(gbpReviewRatings).where(and25(eq29(gbpReviewRatings.projectId, projectId), eq29(gbpReviewRatings.alertState, "pending"))).all();
16634
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
16680
+ const pendingReviews = this.db.select().from(gbpReviews).where(and25(eq30(gbpReviews.projectId, projectId), eq30(gbpReviews.alertState, "pending"))).all();
16681
+ const pendingRatings = this.db.select().from(gbpReviewRatings).where(and25(eq30(gbpReviewRatings.projectId, projectId), eq30(gbpReviewRatings.alertState, "pending"))).all();
16682
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
16635
16683
  if (!project) return { reviews: 0, ratingDrops: 0, delivered: 0 };
16636
16684
  const chatSendsLeft = /* @__PURE__ */ new Map();
16637
16685
  const now = /* @__PURE__ */ new Date();
@@ -16643,10 +16691,10 @@ var Notifier = class {
16643
16691
  displayName: gbpLocations.displayName,
16644
16692
  mapsUri: gbpLocations.mapsUri,
16645
16693
  reviewsAccess: gbpLocations.reviewsAccess
16646
- }).from(gbpLocations).where(eq29(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
16694
+ }).from(gbpLocations).where(eq30(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
16647
16695
  );
16648
16696
  const v4HasWorked = new Set(
16649
- this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and25(eq29(gbpReviewRatings.projectId, projectId), eq29(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
16697
+ this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and25(eq30(gbpReviewRatings.projectId, projectId), eq30(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
16650
16698
  );
16651
16699
  const coveredByBusinessProfile = (locationName) => businessProfileReviewsCover(locations.get(locationName)?.reviewsAccess ?? null, v4HasWorked.has(locationName));
16652
16700
  const locationRef = (locationName) => {
@@ -16675,7 +16723,7 @@ var Notifier = class {
16675
16723
  else if (row.rating === null || row.previousRating === null) setRatingState([row.id], "none");
16676
16724
  else ratingsToSend.push(row);
16677
16725
  }
16678
- const enabled = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
16726
+ const enabled = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
16679
16727
  const subscribedTo = (event) => enabled.filter((n) => (n.config.events ?? []).includes(event));
16680
16728
  const projectRef = { name: project.name, canonicalDomain: project.canonicalDomain };
16681
16729
  const dashboardUrl = `${this.serverUrl}/projects/${project.name}`;
@@ -16730,12 +16778,12 @@ var Notifier = class {
16730
16778
  }
16731
16779
  if (all) {
16732
16780
  this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and25(
16733
- eq29(gbpReviews.id, review.id),
16734
- eq29(gbpReviews.alertState, "pending"),
16735
- eq29(gbpReviews.updateTime, review.updateTime),
16736
- review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq29(gbpReviews.alertStateAt, review.alertStateAt),
16737
- review.comment === null ? isNull5(gbpReviews.comment) : eq29(gbpReviews.comment, review.comment),
16738
- review.starRating === null ? isNull5(gbpReviews.starRating) : eq29(gbpReviews.starRating, review.starRating)
16781
+ eq30(gbpReviews.id, review.id),
16782
+ eq30(gbpReviews.alertState, "pending"),
16783
+ eq30(gbpReviews.updateTime, review.updateTime),
16784
+ review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq30(gbpReviews.alertStateAt, review.alertStateAt),
16785
+ review.comment === null ? isNull5(gbpReviews.comment) : eq30(gbpReviews.comment, review.comment),
16786
+ review.starRating === null ? isNull5(gbpReviews.starRating) : eq30(gbpReviews.starRating, review.starRating)
16739
16787
  )).run();
16740
16788
  }
16741
16789
  }
@@ -16767,7 +16815,7 @@ var Notifier = class {
16767
16815
  delivered += accepted;
16768
16816
  }
16769
16817
  }
16770
- log26.info("reviews.dispatched", {
16818
+ log27.info("reviews.dispatched", {
16771
16819
  projectId,
16772
16820
  reviews: reviewsToSend.length,
16773
16821
  ratingDrops: ratingsToSend.length,
@@ -16778,15 +16826,15 @@ var Notifier = class {
16778
16826
  computeTransitions(runId, project) {
16779
16827
  const none = { citation: [], mention: [] };
16780
16828
  const projectId = project.id;
16781
- const thisRun = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16829
+ const thisRun = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
16782
16830
  if (!thisRun) return none;
16783
16831
  if (isScopedRun(thisRun)) {
16784
- log26.info("transitions.skipped-spot-check", { runId });
16832
+ log27.info("transitions.skipped-spot-check", { runId });
16785
16833
  return none;
16786
16834
  }
16787
16835
  const completeness = measurementRunCompleteness(this.db, runId);
16788
16836
  if (completeness.planned && !completeness.complete) {
16789
- log26.info("transitions.skipped-incomplete", {
16837
+ log27.info("transitions.skipped-incomplete", {
16790
16838
  runId,
16791
16839
  executed: completeness.executed,
16792
16840
  expected: completeness.expected
@@ -16794,9 +16842,9 @@ var Notifier = class {
16794
16842
  return none;
16795
16843
  }
16796
16844
  const groupSiblings = this.db.select().from(runs).where(and25(
16797
- eq29(runs.projectId, projectId),
16798
- eq29(runs.kind, thisRun.kind),
16799
- eq29(runs.createdAt, thisRun.createdAt),
16845
+ eq30(runs.projectId, projectId),
16846
+ eq30(runs.kind, thisRun.kind),
16847
+ eq30(runs.createdAt, thisRun.createdAt),
16800
16848
  notProbeRun()
16801
16849
  )).all();
16802
16850
  const stillPending = groupSiblings.some((r) => r.status === "queued" || r.status === "running");
@@ -16821,9 +16869,9 @@ var Notifier = class {
16821
16869
  const RECENT_FETCH_LIMIT = Math.max(8, locationCount * 4);
16822
16870
  const recentRuns = this.db.select().from(runs).where(
16823
16871
  and25(
16824
- eq29(runs.projectId, projectId),
16825
- eq29(runs.kind, thisRun.kind),
16826
- or2(eq29(runs.status, "completed"), eq29(runs.status, "partial")),
16872
+ eq30(runs.projectId, projectId),
16873
+ eq30(runs.kind, thisRun.kind),
16874
+ or2(eq30(runs.status, "completed"), eq30(runs.status, "partial")),
16827
16875
  notProbeRun(),
16828
16876
  // The previous sweep, never a spot check between the two: diffed
16829
16877
  // against a 2-query check, every other query's change is lost.
@@ -16848,7 +16896,7 @@ var Notifier = class {
16848
16896
  answerText: querySnapshots.answerText,
16849
16897
  answerMentioned: querySnapshots.answerMentioned,
16850
16898
  mentionIdentity: querySnapshots.mentionIdentity
16851
- }).from(querySnapshots).leftJoin(queries, eq29(querySnapshots.queryId, queries.id)).where(inArray13(querySnapshots.runId, currentRunIds)).all();
16899
+ }).from(querySnapshots).leftJoin(queries, eq30(querySnapshots.queryId, queries.id)).where(inArray13(querySnapshots.runId, currentRunIds)).all();
16852
16900
  const previousSnapshots = this.db.select({
16853
16901
  queryId: querySnapshots.queryId,
16854
16902
  provider: querySnapshots.provider,
@@ -16915,12 +16963,12 @@ var Notifier = class {
16915
16963
  try {
16916
16964
  read = readAdvancedSignalTransitions(this.db, projectId, runId);
16917
16965
  } catch (error) {
16918
- log26.error("transitions.advanced-unreadable", { runId, error: describeError(error) });
16966
+ log27.error("transitions.advanced-unreadable", { runId, error: describeError(error) });
16919
16967
  return { citation: [], mention: [] };
16920
16968
  }
16921
16969
  if (read === null) return null;
16922
16970
  if (read.state === "unavailable") {
16923
- log26.info("transitions.advanced-not-comparable", { runId, reason: read.reason });
16971
+ log27.info("transitions.advanced-not-comparable", { runId, reason: read.reason });
16924
16972
  return { citation: [], mention: [] };
16925
16973
  }
16926
16974
  const wire = (t) => ({
@@ -16957,12 +17005,12 @@ var Notifier = class {
16957
17005
  recordUnrecognizedAgentDecisions(this.db, projectId, baseline, UnrecognizedAgentNotifyStates.baseline, now);
16958
17006
  if (due.length === 0) continue;
16959
17007
  const names = due.map((agent) => agent.name);
16960
- const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("traffic.agent.discovered"));
17008
+ const subscribed = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("traffic.agent.discovered"));
16961
17009
  if (subscribed.length === 0) {
16962
17010
  recordUnrecognizedAgentDecisions(this.db, projectId, names, UnrecognizedAgentNotifyStates.skipped, now);
16963
17011
  continue;
16964
17012
  }
16965
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
17013
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
16966
17014
  if (!project) continue;
16967
17015
  const payload = {
16968
17016
  source: "canonry",
@@ -17013,12 +17061,12 @@ var Notifier = class {
17013
17061
  recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.baseline, now);
17014
17062
  continue;
17015
17063
  }
17016
- const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("sentiment.unfavorable"));
17064
+ const subscribed = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("sentiment.unfavorable"));
17017
17065
  if (subscribed.length === 0) {
17018
17066
  recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.skipped, now);
17019
17067
  continue;
17020
17068
  }
17021
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
17069
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
17022
17070
  if (!project) continue;
17023
17071
  for (const runId of undecided) {
17024
17072
  let answers = this.undeliveredSentimentAlerts.get(runId) ?? null;
@@ -17026,7 +17074,7 @@ var Notifier = class {
17026
17074
  try {
17027
17075
  answers = service.newlyUnfavorable(projectId, runId);
17028
17076
  } catch (error) {
17029
- log26.error("sentiment-alerts.unreadable", { projectId, runId, error: describeError(error) });
17077
+ log27.error("sentiment-alerts.unreadable", { projectId, runId, error: describeError(error) });
17030
17078
  continue;
17031
17079
  }
17032
17080
  }
@@ -17035,7 +17083,7 @@ var Notifier = class {
17035
17083
  recordSentimentAlertRuns(this.db, projectId, [runId], SentimentAlertStates.quiet, now);
17036
17084
  continue;
17037
17085
  }
17038
- const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
17086
+ const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
17039
17087
  if (!run) continue;
17040
17088
  const payload = {
17041
17089
  source: "canonry",
@@ -17079,12 +17127,12 @@ var Notifier = class {
17079
17127
  * observable in tests.
17080
17128
  */
17081
17129
  async onSiteAuditCompleted(runId, projectId) {
17082
- const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
17130
+ const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
17083
17131
  if (!run || run.kind !== RunKinds["site-audit"]) return null;
17084
17132
  if (run.status !== RunStatuses.completed && run.status !== RunStatuses.partial) return null;
17085
- const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("site-health.issue.new"));
17133
+ const subscribed = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("site-health.issue.new"));
17086
17134
  if (subscribed.length === 0) return null;
17087
- const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
17135
+ const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
17088
17136
  if (!project) return null;
17089
17137
  const scan = readSiteHealthScan(this.db, projectId, runId);
17090
17138
  if (!scan) return null;
@@ -17118,7 +17166,7 @@ var Notifier = class {
17118
17166
  if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
17119
17167
  }
17120
17168
  if (!accepted) {
17121
- log26.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
17169
+ log27.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
17122
17170
  return null;
17123
17171
  }
17124
17172
  writeSiteHealthNotifyState(this.db, {
@@ -17138,7 +17186,7 @@ var Notifier = class {
17138
17186
  const targetLabel = redactNotificationUrl(url).urlDisplay;
17139
17187
  const targetCheck = await resolveWebhookTarget(url, { allowLoopback: this.allowLoopbackWebhooks });
17140
17188
  if (!targetCheck.ok) {
17141
- log26.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
17189
+ log27.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
17142
17190
  this.logDelivery(projectId, notificationId, payload.event, "failed", `SSRF: ${targetCheck.message}`);
17143
17191
  const reasonCode = webhookTargetRefusalReason(targetCheck);
17144
17192
  trackWebhookDelivery({
@@ -17151,7 +17199,7 @@ var Notifier = class {
17151
17199
  });
17152
17200
  return false;
17153
17201
  }
17154
- log26.info("webhook.send", { event: payload.event, url: targetLabel });
17202
+ log27.info("webhook.send", { event: payload.event, url: targetLabel });
17155
17203
  const maxRetries = 3;
17156
17204
  const delays = [1e3, 4e3, 16e3];
17157
17205
  let lastStatusClass = "network";
@@ -17160,13 +17208,13 @@ var Notifier = class {
17160
17208
  try {
17161
17209
  const response = await deliverWebhook(targetCheck.target, body, signingSecret, { userAgent: webhookUserAgent(PACKAGE_VERSION) });
17162
17210
  if (response.status >= 200 && response.status < 300) {
17163
- log26.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
17211
+ log27.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
17164
17212
  this.logDelivery(projectId, notificationId, payload.event, "sent", null);
17165
17213
  trackWebhookDelivery({ url, event: payload.event, attempts: attempt + 1, durationBucket: elapsed(), statusClass: "2xx" });
17166
17214
  return true;
17167
17215
  }
17168
17216
  const errorDetail = response.error ?? `HTTP ${response.status}`;
17169
- log26.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
17217
+ log27.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
17170
17218
  lastStatusClass = response.status === 0 && response.timedOut ? "timeout" : statusClassOf(response.status);
17171
17219
  lastFailure = { reasonCode: webhookResponseReason(response) ?? "UNKNOWN" };
17172
17220
  if (attempt === maxRetries - 1) {
@@ -17178,7 +17226,7 @@ var Notifier = class {
17178
17226
  lastFailure = outcomeFailure(err);
17179
17227
  if (attempt === maxRetries - 1) {
17180
17228
  this.logDelivery(projectId, notificationId, payload.event, "failed", errorDetail);
17181
- log26.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
17229
+ log27.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
17182
17230
  }
17183
17231
  }
17184
17232
  if (attempt < maxRetries - 1) {
@@ -17210,8 +17258,8 @@ var Notifier = class {
17210
17258
  };
17211
17259
 
17212
17260
  // src/run-coordinator.ts
17213
- import { eq as eq30 } from "drizzle-orm";
17214
- var log27 = createLogger("RunCoordinator");
17261
+ import { eq as eq31 } from "drizzle-orm";
17262
+ var log28 = createLogger("RunCoordinator");
17215
17263
  function reportInsightsGenerated(runTrigger, outcome) {
17216
17264
  trackFeatureCompleted({
17217
17265
  feature: "insights",
@@ -17244,31 +17292,31 @@ var RunCoordinator = class {
17244
17292
  */
17245
17293
  onAnswersRecorded;
17246
17294
  async onRunCompleted(runId, projectId, opts) {
17247
- const runRow = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
17295
+ const runRow = this.db.select().from(runs).where(eq31(runs.id, runId)).get();
17248
17296
  const kind = runRow?.kind ?? RunKinds["answer-visibility"];
17249
17297
  if (runRow?.trigger === RunTriggers.probe) {
17250
- log27.info("probe.skip-side-effects", { runId, projectId, kind });
17298
+ log28.info("probe.skip-side-effects", { runId, projectId, kind });
17251
17299
  return;
17252
17300
  }
17253
17301
  if (kind === RunKinds["answer-visibility"] && (runRow?.status === RunStatuses.completed || runRow?.status === RunStatuses.partial) && this.onAnswersRecorded) {
17254
17302
  try {
17255
17303
  await this.onAnswersRecorded(runId, projectId);
17256
17304
  } catch (err) {
17257
- log27.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
17305
+ log28.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
17258
17306
  }
17259
17307
  }
17260
17308
  if (kind === RunKinds["answer-visibility"] && runRow && isScopedRun(runRow)) {
17261
- log27.info("spot-check.skip-derived", { runId, projectId });
17309
+ log28.info("spot-check.skip-derived", { runId, projectId });
17262
17310
  try {
17263
17311
  await this.notifier.onRunCompleted(runId, projectId);
17264
17312
  } catch (err) {
17265
- log27.error("notifier.failed", { runId, error: describeError(err) });
17313
+ log28.error("notifier.failed", { runId, error: describeError(err) });
17266
17314
  }
17267
17315
  return;
17268
17316
  }
17269
17317
  const completeness = measurementRunCompleteness(this.db, runId);
17270
17318
  if (completeness.planned && !completeness.complete) {
17271
- log27.info("measurement.incomplete-skip-derived", {
17319
+ log28.info("measurement.incomplete-skip-derived", {
17272
17320
  runId,
17273
17321
  projectId,
17274
17322
  executed: completeness.executed,
@@ -17277,7 +17325,7 @@ var RunCoordinator = class {
17277
17325
  try {
17278
17326
  await this.notifier.onRunCompleted(runId, projectId);
17279
17327
  } catch (err) {
17280
- log27.error("notifier.failed", { runId, error: describeError(err) });
17328
+ log28.error("notifier.failed", { runId, error: describeError(err) });
17281
17329
  }
17282
17330
  return;
17283
17331
  }
@@ -17285,7 +17333,7 @@ var RunCoordinator = class {
17285
17333
  try {
17286
17334
  await this.onSentimentCompleted(runId, projectId);
17287
17335
  } catch {
17288
- log27.error("sentiment.wakeup-failed", { runId, projectId });
17336
+ log28.error("sentiment.wakeup-failed", { runId, projectId });
17289
17337
  }
17290
17338
  }
17291
17339
  let insightCount = 0;
@@ -17305,12 +17353,12 @@ var RunCoordinator = class {
17305
17353
  try {
17306
17354
  await this.onInsightsGenerated(runId, projectId, result);
17307
17355
  } catch (err) {
17308
- log27.error("insight-webhook.failed", { runId, error: describeError(err) });
17356
+ log28.error("insight-webhook.failed", { runId, error: describeError(err) });
17309
17357
  }
17310
17358
  }
17311
17359
  }
17312
17360
  } catch (err) {
17313
- log27.error("intelligence.failed", { runId, error: describeError(err) });
17361
+ log28.error("intelligence.failed", { runId, error: describeError(err) });
17314
17362
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
17315
17363
  }
17316
17364
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
@@ -17328,30 +17376,30 @@ var RunCoordinator = class {
17328
17376
  try {
17329
17377
  await this.onInsightsGenerated(runId, projectId, analysisResultFromInsights(gbpInsights));
17330
17378
  } catch (err) {
17331
- log27.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
17379
+ log28.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
17332
17380
  }
17333
17381
  }
17334
17382
  } catch (err) {
17335
- log27.error("gbp-intelligence.failed", { runId, error: describeError(err) });
17383
+ log28.error("gbp-intelligence.failed", { runId, error: describeError(err) });
17336
17384
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
17337
17385
  }
17338
17386
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
17339
17387
  try {
17340
17388
  await this.notifier.dispatchReviewAlerts(projectId);
17341
17389
  } catch (err) {
17342
- log27.error("review-webhook.failed", { runId, error: describeError(err) });
17390
+ log28.error("review-webhook.failed", { runId, error: describeError(err) });
17343
17391
  }
17344
17392
  }
17345
17393
  try {
17346
17394
  await (opts ? this.notifier.onRunCompleted(runId, projectId, opts) : this.notifier.onRunCompleted(runId, projectId));
17347
17395
  } catch (err) {
17348
- log27.error("notifier.failed", { runId, error: describeError(err) });
17396
+ log28.error("notifier.failed", { runId, error: describeError(err) });
17349
17397
  }
17350
17398
  if (kind === RunKinds["site-audit"]) {
17351
17399
  try {
17352
17400
  await this.notifier.onSiteAuditCompleted(runId, projectId);
17353
17401
  } catch (err) {
17354
- log27.error("site-health-webhook.failed", { runId, error: describeError(err) });
17402
+ log28.error("site-health-webhook.failed", { runId, error: describeError(err) });
17355
17403
  }
17356
17404
  }
17357
17405
  if (this.onAeroEvent) {
@@ -17365,7 +17413,7 @@ var RunCoordinator = class {
17365
17413
  };
17366
17414
  await this.onAeroEvent(ctx);
17367
17415
  } catch (err) {
17368
- log27.error("aero.failed", { runId, error: describeError(err) });
17416
+ log28.error("aero.failed", { runId, error: describeError(err) });
17369
17417
  }
17370
17418
  }
17371
17419
  }
@@ -17380,7 +17428,7 @@ var RunCoordinator = class {
17380
17428
  * so the Aero queue is never starved of a follow-up.
17381
17429
  */
17382
17430
  buildDiscoveryAeroContext(runId, projectId, status, error) {
17383
- const session = this.db.select().from(discoverySessions).where(eq30(discoverySessions.runId, runId)).get();
17431
+ const session = this.db.select().from(discoverySessions).where(eq31(discoverySessions.runId, runId)).get();
17384
17432
  const competitorMap = session ? session.competitorMap : [];
17385
17433
  return {
17386
17434
  kind: RunKinds["aeo-discover-probe"],
@@ -17424,12 +17472,12 @@ function analysisResultFromInsights(insights2) {
17424
17472
 
17425
17473
  // src/agent/session-registry.ts
17426
17474
  import crypto27 from "crypto";
17427
- import { and as and28, eq as eq33, gt as gt4, lte as lte3 } from "drizzle-orm";
17475
+ import { and as and28, eq as eq34, gt as gt4, lte as lte3 } from "drizzle-orm";
17428
17476
 
17429
17477
  // src/agent/remote-mcp.ts
17430
17478
  import { Type } from "@earendil-works/pi-ai";
17431
17479
  import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
17432
- var log28 = createLogger("RemoteMcp");
17480
+ var log29 = createLogger("RemoteMcp");
17433
17481
  var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([]);
17434
17482
  async function connectStreamableHttp(server) {
17435
17483
  const transport = new StreamableHTTPClientTransport(new URL(server.url), {
@@ -17497,7 +17545,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17497
17545
  try {
17498
17546
  client = await connect(server);
17499
17547
  } catch (err) {
17500
- log28.error("external-mcp.connect-failed", {
17548
+ log29.error("external-mcp.connect-failed", {
17501
17549
  label,
17502
17550
  error: describeError(err)
17503
17551
  });
@@ -17507,7 +17555,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17507
17555
  try {
17508
17556
  listed = await client.listTools();
17509
17557
  } catch (err) {
17510
- log28.error("external-mcp.list-failed", {
17558
+ log29.error("external-mcp.list-failed", {
17511
17559
  label,
17512
17560
  error: describeError(err)
17513
17561
  });
@@ -17518,7 +17566,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17518
17566
  if (!isReadOnly(tool)) continue;
17519
17567
  tools.push(adaptRemoteTool(client, tool));
17520
17568
  }
17521
- log28.info("external-mcp.loaded", {
17569
+ log29.info("external-mcp.loaded", {
17522
17570
  label,
17523
17571
  discovered: listed.tools.length,
17524
17572
  adopted: tools.length
@@ -17529,7 +17577,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17529
17577
 
17530
17578
  // src/agent/memory-store.ts
17531
17579
  import crypto26 from "crypto";
17532
- import { and as and26, desc as desc11, eq as eq31, like, sql as sql13, or as or3 } from "drizzle-orm";
17580
+ import { and as and26, desc as desc11, eq as eq32, like, sql as sql13, or as or3 } from "drizzle-orm";
17533
17581
  var COMPACTION_KEY_PREFIX = "compaction:";
17534
17582
  var COMPACTION_NOTES_PER_SESSION = 3;
17535
17583
  function rowToDto(row) {
@@ -17543,7 +17591,7 @@ function rowToDto(row) {
17543
17591
  };
17544
17592
  }
17545
17593
  function listMemoryEntries(db, projectId, opts = {}) {
17546
- const query = db.select().from(agentMemory).where(eq31(agentMemory.projectId, projectId)).orderBy(desc11(agentMemory.updatedAt));
17594
+ const query = db.select().from(agentMemory).where(eq32(agentMemory.projectId, projectId)).orderBy(desc11(agentMemory.updatedAt));
17547
17595
  const rows = opts.limit === void 0 ? query.all() : query.limit(opts.limit).all();
17548
17596
  return rows.map(rowToDto);
17549
17597
  }
@@ -17574,12 +17622,12 @@ function upsertMemoryEntry(db, args) {
17574
17622
  updatedAt: now
17575
17623
  }
17576
17624
  }).run();
17577
- const row = db.select().from(agentMemory).where(and26(eq31(agentMemory.projectId, args.projectId), eq31(agentMemory.key, args.key))).get();
17625
+ const row = db.select().from(agentMemory).where(and26(eq32(agentMemory.projectId, args.projectId), eq32(agentMemory.key, args.key))).get();
17578
17626
  if (!row) throw new Error("memory upsert produced no row");
17579
17627
  return rowToDto(row);
17580
17628
  }
17581
17629
  function deleteMemoryEntry(db, projectId, key) {
17582
- const result = db.delete(agentMemory).where(and26(eq31(agentMemory.projectId, projectId), eq31(agentMemory.key, key))).run();
17630
+ const result = db.delete(agentMemory).where(and26(eq32(agentMemory.projectId, projectId), eq32(agentMemory.key, key))).run();
17583
17631
  const changes = result.changes ?? 0;
17584
17632
  return changes > 0;
17585
17633
  }
@@ -17587,7 +17635,7 @@ function loadRecentForHydrate(db, projectId, limit, sessionId) {
17587
17635
  if (sessionId === void 0) return listMemoryEntries(db, projectId, { limit });
17588
17636
  const sessionPrefix = `compaction:${sessionId ?? ""}:`;
17589
17637
  return db.select().from(agentMemory).where(and26(
17590
- eq31(agentMemory.projectId, projectId),
17638
+ eq32(agentMemory.projectId, projectId),
17591
17639
  or3(sql13`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql13`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
17592
17640
  )).orderBy(desc11(agentMemory.updatedAt)).limit(limit).all().map(rowToDto);
17593
17641
  }
@@ -17614,7 +17662,7 @@ function writeCompactionNote(db, args) {
17614
17662
  const sessionPrefix = `${COMPACTION_KEY_PREFIX}${args.sessionId}:`;
17615
17663
  const existing = tx.select({ id: agentMemory.id, updatedAt: agentMemory.updatedAt }).from(agentMemory).where(
17616
17664
  and26(
17617
- eq31(agentMemory.projectId, args.projectId),
17665
+ eq32(agentMemory.projectId, args.projectId),
17618
17666
  like(agentMemory.key, `${sessionPrefix}%`)
17619
17667
  )
17620
17668
  ).orderBy(desc11(agentMemory.updatedAt)).all();
@@ -17622,7 +17670,7 @@ function writeCompactionNote(db, args) {
17622
17670
  if (stale.length > 0) {
17623
17671
  tx.delete(agentMemory).where(sql13`${agentMemory.id} IN (${sql13.join(stale.map((s) => sql13`${s}`), sql13`, `)})`).run();
17624
17672
  }
17625
- const row = tx.select().from(agentMemory).where(and26(eq31(agentMemory.projectId, args.projectId), eq31(agentMemory.key, key))).get();
17673
+ const row = tx.select().from(agentMemory).where(and26(eq32(agentMemory.projectId, args.projectId), eq32(agentMemory.key, key))).get();
17626
17674
  if (row) inserted = rowToDto(row);
17627
17675
  });
17628
17676
  if (!inserted) throw new Error("compaction note write produced no row");
@@ -17630,7 +17678,7 @@ function writeCompactionNote(db, args) {
17630
17678
  }
17631
17679
 
17632
17680
  // src/agent/turn-telemetry.ts
17633
- var log29 = createLogger("AeroTurn");
17681
+ var log30 = createLogger("AeroTurn");
17634
17682
  var PROVIDER_ERROR_REASONS = {
17635
17683
  PROVIDER_AUTH: "INVALID_CREDENTIALS",
17636
17684
  PROVIDER_BILLING: "BILLING",
@@ -17686,7 +17734,7 @@ function trackAeroTurn(agent, turn) {
17686
17734
  phase: turn.phase ?? (turn.error === void 0 && agent.state.errorMessage ? OutcomePhases["provider-request"] : OutcomePhases.unknown)
17687
17735
  });
17688
17736
  const outcome = turnOutcome(turn.error === void 0 ? status.reason : "error", turn.error, agent.state.errorMessage);
17689
- log29.info("completed", {
17737
+ log30.info("completed", {
17690
17738
  operationId,
17691
17739
  projectId: turn.projectId,
17692
17740
  provider: modelProvider,
@@ -17714,7 +17762,7 @@ function trackAeroTurn(agent, turn) {
17714
17762
  }
17715
17763
 
17716
17764
  // src/agent/project-shape.ts
17717
- import { and as and27, count as count5, eq as eq32 } from "drizzle-orm";
17765
+ import { and as and27, count as count5, eq as eq33 } from "drizzle-orm";
17718
17766
  var ADVANCED_TOOLS = [
17719
17767
  "canonry_measurement_portfolio_summary",
17720
17768
  "canonry_measurement_overview",
@@ -17741,10 +17789,10 @@ var ADVANCED_ROUTES = [
17741
17789
  ];
17742
17790
  function aeroProjectShape(db, projectId) {
17743
17791
  try {
17744
- const pointer = db.select().from(measurementPlans).where(eq32(measurementPlans.projectId, projectId)).get();
17792
+ const pointer = db.select().from(measurementPlans).where(eq33(measurementPlans.projectId, projectId)).get();
17745
17793
  const version = pointer ? db.select().from(measurementPlanVersions).where(and27(
17746
- eq32(measurementPlanVersions.projectId, projectId),
17747
- eq32(measurementPlanVersions.id, pointer.activeVersionId)
17794
+ eq33(measurementPlanVersions.projectId, projectId),
17795
+ eq33(measurementPlanVersions.id, pointer.activeVersionId)
17748
17796
  )).get() : void 0;
17749
17797
  if (version) {
17750
17798
  const plan = JSON.parse(version.canonicalJson);
@@ -17771,7 +17819,7 @@ canonry_visibility_report describes the whole project, not one Property. canonry
17771
17819
  pinned: ADVANCED_TOOLS
17772
17820
  };
17773
17821
  }
17774
- const tracked = db.select({ total: count5() }).from(queries).where(eq32(queries.projectId, projectId)).get()?.total ?? 0;
17822
+ const tracked = db.select({ total: count5() }).from(queries).where(eq33(queries.projectId, projectId)).get()?.total ?? 0;
17775
17823
  return {
17776
17824
  prompt: `
17777
17825
 
@@ -17911,7 +17959,7 @@ async function compactMessages(args) {
17911
17959
  }
17912
17960
 
17913
17961
  // src/agent/session-registry.ts
17914
- var log30 = createLogger("SessionRegistry");
17962
+ var log31 = createLogger("SessionRegistry");
17915
17963
  var MAX_HYDRATE_NOTES = 20;
17916
17964
  var PROVIDER_ACCOUNT_COOLDOWN_MS = 24 * 60 * 60 * 1e3;
17917
17965
  var MAX_HYDRATE_BYTES = 32 * 1024;
@@ -17973,7 +18021,7 @@ var SessionRegistry = class {
17973
18021
  if (!this.externalToolsPromise) {
17974
18022
  this.externalToolsPromise = loadExternalMcpTools(this.opts.config.externalMcpServers).catch(
17975
18023
  (err) => {
17976
- log30.error("external-mcp.load-failed", {
18024
+ log31.error("external-mcp.load-failed", {
17977
18025
  error: describeError(err)
17978
18026
  });
17979
18027
  return [];
@@ -18049,7 +18097,7 @@ var SessionRegistry = class {
18049
18097
  modelProvider: effectiveProvider,
18050
18098
  modelId: effectiveModelId,
18051
18099
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
18052
- }).where(eq33(agentSessions.projectId, projectId)).run();
18100
+ }).where(eq34(agentSessions.projectId, projectId)).run();
18053
18101
  }
18054
18102
  const agent2 = createAeroSession({
18055
18103
  projectName,
@@ -18268,13 +18316,13 @@ ${lines.join("\n")}
18268
18316
  agent.state.messages = result.messages;
18269
18317
  setAeroSystemPrompt(agent, this.buildHydratedSystemPrompt(projectId, row.systemPrompt));
18270
18318
  this.save(projectName);
18271
- log30.info("compaction.completed", {
18319
+ log31.info("compaction.completed", {
18272
18320
  projectName,
18273
18321
  removedCount: result.removedCount,
18274
18322
  summaryBytes: Buffer.byteLength(result.summary, "utf8")
18275
18323
  });
18276
18324
  } catch (err) {
18277
- log30.error("compaction.failed", {
18325
+ log31.error("compaction.failed", {
18278
18326
  projectName,
18279
18327
  error: describeError(err)
18280
18328
  });
@@ -18368,7 +18416,7 @@ ${lines.join("\n")}
18368
18416
  modelProvider: nextProvider,
18369
18417
  modelId: nextModelId,
18370
18418
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
18371
- }).where(eq33(agentSessions.projectId, projectId)).run();
18419
+ }).where(eq34(agentSessions.projectId, projectId)).run();
18372
18420
  }
18373
18421
  /** Snapshot pending work without consuming it before an atomic conversation switch. */
18374
18422
  prepareConversationChange(projectName) {
@@ -18456,7 +18504,7 @@ ${lines.join("\n")}
18456
18504
  }
18457
18505
  trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, projectId });
18458
18506
  } catch (err) {
18459
- log30.error("drain.failed", {
18507
+ log31.error("drain.failed", {
18460
18508
  projectName,
18461
18509
  error: describeError(err)
18462
18510
  });
@@ -18578,9 +18626,9 @@ ${lines.join("\n")}
18578
18626
  persisted = true;
18579
18627
  } catch (error) {
18580
18628
  this.providerCooldownFallbacks.set(accountKey, cooldown);
18581
- log30.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
18629
+ log31.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
18582
18630
  }
18583
- log30.warn("provider.background-paused", {
18631
+ log31.warn("provider.background-paused", {
18584
18632
  projectName,
18585
18633
  provider: agent.state.model.provider,
18586
18634
  reason,
@@ -18592,13 +18640,13 @@ ${lines.join("\n")}
18592
18640
  try {
18593
18641
  if (durableFailureId) {
18594
18642
  this.opts.db.delete(agentProviderCooldowns).where(and28(
18595
- eq33(agentProviderCooldowns.accountKey, accountKey),
18596
- eq33(agentProviderCooldowns.failureId, durableFailureId)
18643
+ eq34(agentProviderCooldowns.accountKey, accountKey),
18644
+ eq34(agentProviderCooldowns.failureId, durableFailureId)
18597
18645
  )).run();
18598
18646
  }
18599
18647
  this.providerCooldownFallbacks.delete(accountKey);
18600
18648
  } catch (error) {
18601
- log30.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
18649
+ log31.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
18602
18650
  }
18603
18651
  }
18604
18652
  }
@@ -18628,12 +18676,12 @@ ${lines.join("\n")}
18628
18676
  const fallback = this.providerCooldownFallbacks.get(accountKey);
18629
18677
  try {
18630
18678
  const durable = this.opts.db.select().from(agentProviderCooldowns).where(and28(
18631
- eq33(agentProviderCooldowns.accountKey, accountKey),
18679
+ eq34(agentProviderCooldowns.accountKey, accountKey),
18632
18680
  gt4(agentProviderCooldowns.retryAt, Date.now())
18633
18681
  )).get();
18634
18682
  return { fallback, durable };
18635
18683
  } catch (error) {
18636
- log30.warn("provider.background-pause.read-failed", { error: describeError(error) });
18684
+ log31.warn("provider.background-pause.read-failed", { error: describeError(error) });
18637
18685
  return { fallback, durable: null };
18638
18686
  }
18639
18687
  }
@@ -18647,11 +18695,11 @@ ${lines.join("\n")}
18647
18695
  return id;
18648
18696
  }
18649
18697
  tryResolveProjectId(projectName) {
18650
- const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq33(projects.name, projectName)).get();
18698
+ const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq34(projects.name, projectName)).get();
18651
18699
  return row?.id;
18652
18700
  }
18653
18701
  loadRow(projectId) {
18654
- const row = this.opts.db.select().from(agentSessions).where(eq33(agentSessions.projectId, projectId)).get();
18702
+ const row = this.opts.db.select().from(agentSessions).where(eq34(agentSessions.projectId, projectId)).get();
18655
18703
  return row ?? null;
18656
18704
  }
18657
18705
  insertRow(params) {
@@ -18671,7 +18719,7 @@ ${lines.join("\n")}
18671
18719
  }
18672
18720
  updateRow(projectId, patch) {
18673
18721
  const now = (/* @__PURE__ */ new Date()).toISOString();
18674
- this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq33(agentSessions.projectId, projectId)).run();
18722
+ this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq34(agentSessions.projectId, projectId)).run();
18675
18723
  }
18676
18724
  /**
18677
18725
  * Store a refreshed prompt snapshot without touching `updatedAt`, which the
@@ -18680,13 +18728,13 @@ ${lines.join("\n")}
18680
18728
  * recently used right after an upgrade.
18681
18729
  */
18682
18730
  persistPromptSnapshot(projectId, systemPrompt) {
18683
- this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq33(agentSessions.projectId, projectId)).run();
18731
+ this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq34(agentSessions.projectId, projectId)).run();
18684
18732
  }
18685
18733
  };
18686
18734
 
18687
18735
  // src/agent/viewer-sessions.ts
18688
18736
  import crypto28 from "crypto";
18689
- import { and as and29, eq as eq34, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
18737
+ import { and as and29, eq as eq35, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
18690
18738
 
18691
18739
  // src/agent/chatgpt-plan.ts
18692
18740
  import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
@@ -19057,12 +19105,12 @@ var ViewerAeroSessions = class {
19057
19105
  */
19058
19106
  removeKey(id) {
19059
19107
  try {
19060
- this.opts.db.delete(apiKeys).where(eq34(apiKeys.id, id)).run();
19108
+ this.opts.db.delete(apiKeys).where(eq35(apiKeys.id, id)).run();
19061
19109
  } catch {
19062
19110
  try {
19063
19111
  this.opts.db.transaction((tx) => {
19064
- tx.delete(dashboardSessions).where(eq34(dashboardSessions.apiKeyId, id)).run();
19065
- tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq34(apiKeys.id, id)).run();
19112
+ tx.delete(dashboardSessions).where(eq35(dashboardSessions.apiKeyId, id)).run();
19113
+ tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq35(apiKeys.id, id)).run();
19066
19114
  });
19067
19115
  } catch {
19068
19116
  }
@@ -19092,7 +19140,7 @@ var ViewerAeroSessions = class {
19092
19140
  // src/mcp-http.ts
19093
19141
  import crypto29 from "crypto";
19094
19142
  import { isIP } from "net";
19095
- import { and as and30, eq as eq35, isNull as isNull6 } from "drizzle-orm";
19143
+ import { and as and30, eq as eq36, isNull as isNull6 } from "drizzle-orm";
19096
19144
  import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node";
19097
19145
  import { McpServer, createMcpHandler, isInitializeRequest, isLegacyRequest } from "@modelcontextprotocol/server";
19098
19146
  var SESSION_IDLE_MS = 10 * 60 * 1e3;
@@ -19198,12 +19246,12 @@ function registerMcpHttpRoutes(scope, opts) {
19198
19246
  try {
19199
19247
  withoutLockWait(() => {
19200
19248
  opts.db.transaction((tx) => {
19201
- tx.delete(dashboardSessions).where(eq35(dashboardSessions.apiKeyId, id)).run();
19202
- tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and30(eq35(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
19249
+ tx.delete(dashboardSessions).where(eq36(dashboardSessions.apiKeyId, id)).run();
19250
+ tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and30(eq36(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
19203
19251
  });
19204
19252
  if (remove) {
19205
19253
  try {
19206
- opts.db.delete(apiKeys).where(eq35(apiKeys.id, id)).run();
19254
+ opts.db.delete(apiKeys).where(eq36(apiKeys.id, id)).run();
19207
19255
  } catch (error) {
19208
19256
  scope.log.warn({ err: error, keyId: id }, "Retained revoked MCP request key after deletion failed");
19209
19257
  }
@@ -19254,14 +19302,14 @@ function registerMcpHttpRoutes(scope, opts) {
19254
19302
  withoutLockWait(() => {
19255
19303
  const cutoff = now() - SESSION_IDLE_MS;
19256
19304
  for (const session of legacyServers) {
19257
- const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq35(apiKeys.id, session.sessionKeyId)).get() : void 0;
19305
+ const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq36(apiKeys.id, session.sessionKeyId)).get() : void 0;
19258
19306
  if (session.lastSeenAt < cutoff || session.expiresAt !== void 0 && session.expiresAt <= now() || session.sessionKeyId && (!key || key.revokedAt)) {
19259
19307
  void session.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP session"));
19260
19308
  }
19261
19309
  }
19262
19310
  for (const exchange of modernExchanges) {
19263
19311
  if (!exchange.sessionKey) continue;
19264
- const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq35(apiKeys.id, exchange.sessionKey.id)).get();
19312
+ const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq36(apiKeys.id, exchange.sessionKey.id)).get();
19265
19313
  if (!key || key.revokedAt || exchange.sessionKey.expiresAt <= now()) {
19266
19314
  void exchange.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP request"));
19267
19315
  }
@@ -19547,7 +19595,7 @@ function resolveChatGptSettings(config, env = process.env) {
19547
19595
  }
19548
19596
 
19549
19597
  // src/agent/agent-routes.ts
19550
- import { eq as eq36 } from "drizzle-orm";
19598
+ import { eq as eq37 } from "drizzle-orm";
19551
19599
  function viewerAeroCaller(request, opts) {
19552
19600
  if (!opts.viewerSessions) return null;
19553
19601
  const principal = request.principal;
@@ -19590,7 +19638,7 @@ function turnAttribution(request) {
19590
19638
  };
19591
19639
  }
19592
19640
  function resolveProject(db, name) {
19593
- const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq36(projects.name, name)).get();
19641
+ const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq37(projects.name, name)).get();
19594
19642
  if (!row) throw notFound("project", name);
19595
19643
  return row;
19596
19644
  }
@@ -19713,7 +19761,7 @@ function registerAgentRoutes(app, opts) {
19713
19761
  }
19714
19762
  requireInstanceAdministrator(request);
19715
19763
  const project = resolveProject(opts.db, request.params.name);
19716
- const row = opts.db.select().from(agentSessions).where(eq36(agentSessions.projectId, project.id)).get();
19764
+ const row = opts.db.select().from(agentSessions).where(eq37(agentSessions.projectId, project.id)).get();
19717
19765
  const nextTurn = opts.sessionRegistry.nextTurnModel(project.name);
19718
19766
  if (!row) {
19719
19767
  return { conversationId: null, messages: [], modelProvider: null, modelId: null, nextTurn, updatedAt: null };
@@ -19755,7 +19803,7 @@ function registerAgentRoutes(app, opts) {
19755
19803
  const project = resolveProject(opts.db, request.params.name);
19756
19804
  if (opts.sessionRegistry.isBusy(project.name)) throw agentBusy(project.name);
19757
19805
  opts.sessionRegistry.reset(project.name);
19758
- opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq36(agentSessions.projectId, project.id)).run();
19806
+ opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq37(agentSessions.projectId, project.id)).run();
19759
19807
  return { status: "reset" };
19760
19808
  }
19761
19809
  );
@@ -19779,7 +19827,7 @@ function registerAgentRoutes(app, opts) {
19779
19827
  return streamViewerTurn(opts, project, viewerId, body, reply, turnAttribution(request));
19780
19828
  }
19781
19829
  if (body.conversationId !== void 0) {
19782
- const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq36(agentSessions.projectId, project.id)).get();
19830
+ const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq37(agentSessions.projectId, project.id)).get();
19783
19831
  if ((current?.id ?? null) !== body.conversationId) throw validationError("The active conversation changed. Reload the conversation before sending.");
19784
19832
  }
19785
19833
  const promptText = body.prompt;
@@ -20191,7 +20239,7 @@ function stripHtml(html) {
20191
20239
  }
20192
20240
 
20193
20241
  // src/snapshot-service.ts
20194
- var log31 = createLogger("Snapshot");
20242
+ var log32 = createLogger("Snapshot");
20195
20243
  var ANALYSIS_PROVIDER_PRIORITY = ["openai", "claude", "gemini", "perplexity", "muse", "local"];
20196
20244
  var SNAPSHOT_QUERY_COUNT = 6;
20197
20245
  var SnapshotService = class {
@@ -20293,7 +20341,7 @@ var SnapshotService = class {
20293
20341
  return mapAuditReport(report);
20294
20342
  } catch (err) {
20295
20343
  const message = describeError(err);
20296
- log31.warn("audit.failed", { homepageUrl, error: message });
20344
+ log32.warn("audit.failed", { homepageUrl, error: message });
20297
20345
  return {
20298
20346
  url: homepageUrl,
20299
20347
  finalUrl: homepageUrl,
@@ -20322,7 +20370,7 @@ var SnapshotService = class {
20322
20370
  queries: parsedQueries
20323
20371
  };
20324
20372
  } catch (err) {
20325
- log31.warn("profile.generation-failed", {
20373
+ log32.warn("profile.generation-failed", {
20326
20374
  domain: ctx.domain,
20327
20375
  provider: ctx.analysisProvider.adapter.name,
20328
20376
  error: describeError(err)
@@ -20472,7 +20520,7 @@ var SnapshotService = class {
20472
20520
  recommendedActions: uniqueStrings2(parsed.recommendedActions ?? []).slice(0, 4)
20473
20521
  };
20474
20522
  } catch (err) {
20475
- log31.warn("response.analysis-failed", {
20523
+ log32.warn("response.analysis-failed", {
20476
20524
  provider: ctx.analysisProvider.adapter.name,
20477
20525
  error: describeError(err)
20478
20526
  });
@@ -20742,7 +20790,7 @@ function clipText(value, length) {
20742
20790
  }
20743
20791
 
20744
20792
  // src/research-runner.ts
20745
- import { and as and31, eq as eq37, inArray as inArray14, sql as sql14 } from "drizzle-orm";
20793
+ import { and as and31, eq as eq38, inArray as inArray14, sql as sql14 } from "drizzle-orm";
20746
20794
  var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
20747
20795
  function finalResearchRunStatus(completed, failed, waiting) {
20748
20796
  if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
@@ -20750,13 +20798,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
20750
20798
  return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
20751
20799
  }
20752
20800
  async function executeResearchRun(db, registry, runId, projectId, options = {}) {
20753
- const run = db.select().from(researchRuns).where(and31(eq37(researchRuns.id, runId), eq37(researchRuns.projectId, projectId))).get();
20801
+ const run = db.select().from(researchRuns).where(and31(eq38(researchRuns.id, runId), eq38(researchRuns.projectId, projectId))).get();
20754
20802
  if (!run || run.status !== ResearchRunStatuses.queued) return;
20755
- const project = db.select().from(projects).where(eq37(projects.id, projectId)).get();
20803
+ const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
20756
20804
  if (!project) return;
20757
20805
  const provider = registry.get(run.provider);
20758
20806
  const now = (/* @__PURE__ */ new Date()).toISOString();
20759
- const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and31(eq37(researchRuns.id, runId), eq37(researchRuns.status, ResearchRunStatuses.queued))).run();
20807
+ const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and31(eq38(researchRuns.id, runId), eq38(researchRuns.status, ResearchRunStatuses.queued))).run();
20760
20808
  if (claim.changes !== 1) return;
20761
20809
  const elapsed = startOutcomeTimer();
20762
20810
  const requested = currentOutcomeOrigin();
@@ -20790,8 +20838,8 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20790
20838
  }
20791
20839
  reserved = run.totalQueries;
20792
20840
  reservation = { scope, period };
20793
- const rows = db.select().from(researchRunQueries).where(eq37(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
20794
- const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq37(competitors.projectId, projectId)).orderBy(competitors.domain).all();
20841
+ const rows = db.select().from(researchRunQueries).where(eq38(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
20842
+ const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq38(competitors.projectId, projectId)).orderBy(competitors.domain).all();
20795
20843
  const competitorDomains = competitorRows.map((row) => row.domain);
20796
20844
  const competitorAliases = new Map(competitorRows.map((row) => [row.domain, competitorIdentityAliases(row)]).filter(([, aliases]) => aliases.length > 0));
20797
20845
  const domains = effectiveDomains(project);
@@ -20801,7 +20849,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20801
20849
  await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
20802
20850
  try {
20803
20851
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
20804
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and31(eq37(researchRunQueries.id, row.id), eq37(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
20852
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and31(eq38(researchRunQueries.id, row.id), eq38(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
20805
20853
  const raw = await gate.run(async () => {
20806
20854
  dispatched++;
20807
20855
  return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
@@ -20832,7 +20880,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20832
20880
  rawResponse: raw.rawResponse,
20833
20881
  answerEvidence: raw.evidence ?? null,
20834
20882
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
20835
- }).where(and31(eq37(researchRunQueries.id, row.id), eq37(researchRunQueries.status, ResearchQueryStatuses.running))).run();
20883
+ }).where(and31(eq38(researchRunQueries.id, row.id), eq38(researchRunQueries.status, ResearchQueryStatuses.running))).run();
20836
20884
  if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
20837
20885
  } catch (error) {
20838
20886
  if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
@@ -20883,11 +20931,11 @@ function researchOutcomeStatus(status) {
20883
20931
  }
20884
20932
  }
20885
20933
  function incrementResearchProgress(db, runId, column) {
20886
- db.update(researchRuns).set({ [column]: sql14`${researchRuns[column]} + 1` }).where(eq37(researchRuns.id, runId)).run();
20934
+ db.update(researchRuns).set({ [column]: sql14`${researchRuns[column]} + 1` }).where(eq38(researchRuns.id, runId)).run();
20887
20935
  }
20888
20936
  function markResearchQueryFailed(db, runId, queryId, error) {
20889
20937
  const message = describeError(error);
20890
- const unfinished = and31(eq37(researchRunQueries.id, queryId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses));
20938
+ const unfinished = and31(eq38(researchRunQueries.id, queryId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses));
20891
20939
  if (error instanceof IncompleteAnswerError && error.resumable) {
20892
20940
  db.update(researchRunQueries).set({
20893
20941
  status: ResearchQueryStatuses["waiting-upstream"],
@@ -20903,10 +20951,10 @@ function markResearchQueryFailed(db, runId, queryId, error) {
20903
20951
  if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
20904
20952
  }
20905
20953
  function markUnfinishedResearchQueriesFailed(db, runId, error) {
20906
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and31(eq37(researchRunQueries.researchRunId, runId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
20954
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and31(eq38(researchRunQueries.researchRunId, runId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
20907
20955
  }
20908
20956
  function finalizeResearchRun(db, runId, fatalError) {
20909
- const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq37(researchRunQueries.researchRunId, runId)).all();
20957
+ const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq38(researchRunQueries.researchRunId, runId)).all();
20910
20958
  const completed = rows.filter((row) => row.status === ResearchQueryStatuses.completed).length;
20911
20959
  const failed = rows.filter((row) => row.status === ResearchQueryStatuses.failed).length;
20912
20960
  const waiting = rows.filter((row) => row.status === ResearchQueryStatuses["waiting-upstream"]).length;
@@ -20918,12 +20966,12 @@ function finalizeResearchRun(db, runId, fatalError) {
20918
20966
  error: fatalError ?? (failed === rows.length ? "Every research query failed." : null),
20919
20967
  // A run waiting on upstream jobs has not finished.
20920
20968
  finishedAt: waiting > 0 ? null : (/* @__PURE__ */ new Date()).toISOString()
20921
- }).where(eq37(researchRuns.id, runId)).run();
20969
+ }).where(eq38(researchRuns.id, runId)).run();
20922
20970
  return { status, total: rows.length, completed, failed };
20923
20971
  }
20924
20972
 
20925
20973
  // src/google-marketing-sync.ts
20926
- import { and as and32, eq as eq38, isNull as isNull7, sql as sql15 } from "drizzle-orm";
20974
+ import { and as and32, eq as eq39, isNull as isNull7, sql as sql15 } from "drizzle-orm";
20927
20975
  var RUNTIME_FAILURE_REASONS = {
20928
20976
  INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
20929
20977
  NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
@@ -20961,9 +21009,9 @@ function assertSnapshotContext(metadata, expected) {
20961
21009
  }
20962
21010
  function requireSyncRun(db, runId, projectId, kind) {
20963
21011
  const run = db.select().from(runs).where(and32(
20964
- eq38(runs.id, runId),
20965
- eq38(runs.projectId, projectId),
20966
- eq38(runs.kind, kind)
21012
+ eq39(runs.id, runId),
21013
+ eq39(runs.projectId, projectId),
21014
+ eq39(runs.kind, kind)
20967
21015
  )).get();
20968
21016
  if (!run) throw withOutcomeReason(new Error(`Run ${runId} is not a ${kind} run for this project.`), OutcomeReasonCodes.NOT_FOUND);
20969
21017
  if (run.status !== RunStatuses.queued) {
@@ -20980,18 +21028,18 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
20980
21028
  error: serializeRunError({ message: safeErrorMessage(error) }),
20981
21029
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
20982
21030
  }).where(and32(
20983
- eq38(runs.id, runId),
20984
- eq38(runs.projectId, projectId),
20985
- eq38(runs.kind, kind),
20986
- eq38(runs.status, expectedStatus)
21031
+ eq39(runs.id, runId),
21032
+ eq39(runs.projectId, projectId),
21033
+ eq39(runs.kind, kind),
21034
+ eq39(runs.status, expectedStatus)
20987
21035
  )).run();
20988
21036
  }
20989
21037
  function claimSyncRun(db, runId, projectId, kind, startedAt) {
20990
21038
  const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and32(
20991
- eq38(runs.id, runId),
20992
- eq38(runs.projectId, projectId),
20993
- eq38(runs.kind, kind),
20994
- eq38(runs.status, RunStatuses.queued)
21039
+ eq39(runs.id, runId),
21040
+ eq39(runs.projectId, projectId),
21041
+ eq39(runs.kind, kind),
21042
+ eq39(runs.status, RunStatuses.queued)
20995
21043
  )).run();
20996
21044
  return claim.changes === 1;
20997
21045
  }
@@ -21001,9 +21049,9 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
21001
21049
  let evidenceCollected = false;
21002
21050
  try {
21003
21051
  requireSyncRun(db, runId, projectId, RunKinds["google-ads-sync"]);
21004
- const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
21052
+ const project = db.select().from(projects).where(eq39(projects.id, projectId)).get();
21005
21053
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
21006
- const connection = db.select().from(googleAdsConnections).where(eq38(googleAdsConnections.projectId, projectId)).get();
21054
+ const connection = db.select().from(googleAdsConnections).where(eq39(googleAdsConnections.projectId, projectId)).get();
21007
21055
  if (!connection?.selectedCustomerId) {
21008
21056
  throw withOutcomeReason(new Error("Google Ads needs a selected customer before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
21009
21057
  }
@@ -21056,10 +21104,10 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
21056
21104
  finishedAt,
21057
21105
  error: null
21058
21106
  }).where(and32(
21059
- eq38(runs.id, runId),
21060
- eq38(runs.projectId, projectId),
21061
- eq38(runs.kind, RunKinds["google-ads-sync"]),
21062
- eq38(runs.status, RunStatuses.running)
21107
+ eq39(runs.id, runId),
21108
+ eq39(runs.projectId, projectId),
21109
+ eq39(runs.kind, RunKinds["google-ads-sync"]),
21110
+ eq39(runs.status, RunStatuses.running)
21063
21111
  )).run();
21064
21112
  if (terminalClaim.changes !== 1) {
21065
21113
  throw withOutcomeReason(
@@ -21080,11 +21128,11 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
21080
21128
  lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
21081
21129
  updatedAt: finishedAt
21082
21130
  }).where(and32(
21083
- eq38(googleAdsConnections.id, connection.id),
21084
- eq38(googleAdsConnections.projectId, projectId),
21085
- eq38(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
21086
- connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) : eq38(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
21087
- eq38(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
21131
+ eq39(googleAdsConnections.id, connection.id),
21132
+ eq39(googleAdsConnections.projectId, projectId),
21133
+ eq39(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
21134
+ connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) : eq39(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
21135
+ eq39(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
21088
21136
  )).run();
21089
21137
  if (connectionClaim.changes !== 1) {
21090
21138
  throw withOutcomeReason(
@@ -21124,9 +21172,9 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
21124
21172
  let evidenceCollected = false;
21125
21173
  try {
21126
21174
  requireSyncRun(db, runId, projectId, RunKinds["gtm-sync"]);
21127
- const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
21175
+ const project = db.select().from(projects).where(eq39(projects.id, projectId)).get();
21128
21176
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
21129
- const connection = db.select().from(gtmConnections).where(eq38(gtmConnections.projectId, projectId)).get();
21177
+ const connection = db.select().from(gtmConnections).where(eq39(gtmConnections.projectId, projectId)).get();
21130
21178
  if (!connection?.selectedAccountId || !connection.selectedContainerId) {
21131
21179
  throw withOutcomeReason(new Error("GTM needs a selected account and container before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
21132
21180
  }
@@ -21165,10 +21213,10 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
21165
21213
  finishedAt,
21166
21214
  error: null
21167
21215
  }).where(and32(
21168
- eq38(runs.id, runId),
21169
- eq38(runs.projectId, projectId),
21170
- eq38(runs.kind, RunKinds["gtm-sync"]),
21171
- eq38(runs.status, RunStatuses.running)
21216
+ eq39(runs.id, runId),
21217
+ eq39(runs.projectId, projectId),
21218
+ eq39(runs.kind, RunKinds["gtm-sync"]),
21219
+ eq39(runs.status, RunStatuses.running)
21172
21220
  )).run();
21173
21221
  if (terminalClaim.changes !== 1) {
21174
21222
  throw withOutcomeReason(
@@ -21190,12 +21238,12 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
21190
21238
  lastSnapshotId: snapshot.metadata.id,
21191
21239
  updatedAt: finishedAt
21192
21240
  }).where(and32(
21193
- eq38(gtmConnections.id, connection.id),
21194
- eq38(gtmConnections.projectId, projectId),
21195
- eq38(gtmConnections.selectedAccountId, connection.selectedAccountId),
21196
- eq38(gtmConnections.selectedContainerId, connection.selectedContainerId),
21197
- connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) : eq38(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
21198
- eq38(gtmConnections.selectionGeneration, connection.selectionGeneration)
21241
+ eq39(gtmConnections.id, connection.id),
21242
+ eq39(gtmConnections.projectId, projectId),
21243
+ eq39(gtmConnections.selectedAccountId, connection.selectedAccountId),
21244
+ eq39(gtmConnections.selectedContainerId, connection.selectedContainerId),
21245
+ connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) : eq39(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
21246
+ eq39(gtmConnections.selectionGeneration, connection.selectionGeneration)
21199
21247
  )).run();
21200
21248
  if (connectionClaim.changes !== 1) {
21201
21249
  throw withOutcomeReason(
@@ -21233,7 +21281,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
21233
21281
  // src/server.ts
21234
21282
  var _require = createRequire(import.meta.url);
21235
21283
  var { version: PKG_VERSION } = _require("../package.json");
21236
- var log32 = createLogger("Server");
21284
+ var log33 = createLogger("Server");
21237
21285
  var runtimeStartupByServer = /* @__PURE__ */ new WeakMap();
21238
21286
  function waitForServerRuntimeStartup(app) {
21239
21287
  const startup = runtimeStartupByServer.get(app);
@@ -21485,7 +21533,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
21485
21533
  }
21486
21534
  if (migratedGoogle > 0) {
21487
21535
  persistConfigPatch({ google: config.google });
21488
- log32.info("credentials.migrated", { type: "google", count: migratedGoogle });
21536
+ log33.info("credentials.migrated", { type: "google", count: migratedGoogle });
21489
21537
  }
21490
21538
  let migratedGa4 = 0;
21491
21539
  for (const row of rows.ga4) {
@@ -21503,7 +21551,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
21503
21551
  }
21504
21552
  if (migratedGa4 > 0) {
21505
21553
  persistConfigPatch({ ga4: config.ga4 });
21506
- log32.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
21554
+ log33.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
21507
21555
  }
21508
21556
  }
21509
21557
  function isLoopbackPeerAddress(address) {
@@ -21786,17 +21834,17 @@ async function createServer(opts) {
21786
21834
  applyLegacyCredentials(legacyRows, opts.config, persistConfigPatch);
21787
21835
  dropLegacyCredentialColumns(opts.db);
21788
21836
  } catch (err) {
21789
- log32.warn("credentials.migration.failed", {
21837
+ log33.warn("credentials.migration.failed", {
21790
21838
  error: describeError(err)
21791
21839
  });
21792
21840
  }
21793
21841
  }
21794
- log32.info("providers.configured", {
21842
+ log33.info("providers.configured", {
21795
21843
  providers: registeredProviderNames({ providers, cdp: opts.config.cdp })
21796
21844
  });
21797
21845
  registry.replace(configuredProviderEntries(opts.config, API_ADAPTERS, cdpChatgptAdapter));
21798
21846
  for (const name of providersWithUnsupportedBatch(providers, (provider) => adapterMap[provider])) {
21799
- log32.warn("provider.batch.unsupported", {
21847
+ log33.warn("provider.batch.unsupported", {
21800
21848
  provider: name,
21801
21849
  message: `providers.${name}.batch.enabled is true, but the ${name} adapter has no batch API; its sweeps run sync.`
21802
21850
  });
@@ -21847,7 +21895,7 @@ async function createServer(opts) {
21847
21895
  settings: () => resolveChatGptSettings(opts.config)
21848
21896
  });
21849
21897
  if (opts.config.chatgpt && (opts.config.chatgpt.signIn || opts.config.chatgpt.planUsage) && !resolveChatGptSettings(opts.config)) {
21850
- log32.warn("chatgpt.disabled", {
21898
+ log33.warn("chatgpt.disabled", {
21851
21899
  reason: "Sign in with ChatGPT needs chatgpt.clientId and an HTTPS publicUrl; it stays off until both are set."
21852
21900
  });
21853
21901
  }
@@ -21867,7 +21915,7 @@ async function createServer(opts) {
21867
21915
  async (ctx) => {
21868
21916
  if (!sessionRegistry) return;
21869
21917
  if (!agentProactive) return;
21870
- const project = opts.db.select({ name: projects.name }).from(projects).where(eq39(projects.id, ctx.projectId)).get();
21918
+ const project = opts.db.select({ name: projects.name }).from(projects).where(eq40(projects.id, ctx.projectId)).get();
21871
21919
  if (!project) return;
21872
21920
  let content;
21873
21921
  if (ctx.kind === RunKinds["aeo-discover-probe"]) {
@@ -22342,7 +22390,7 @@ async function createServer(opts) {
22342
22390
  void (async () => {
22343
22391
  try {
22344
22392
  const report = await schedulerClient.runDoctor({ project: projectName, checkIds: scheduledHealthCheckIds() });
22345
- const project = opts.db.select().from(projects).where(eq39(projects.name, projectName)).get();
22393
+ const project = opts.db.select().from(projects).where(eq40(projects.name, projectName)).get();
22346
22394
  if (!project) {
22347
22395
  app.log.warn({ projectName }, "doctor schedule fired for an unknown project");
22348
22396
  return;
@@ -22364,7 +22412,7 @@ async function createServer(opts) {
22364
22412
  db: opts.db,
22365
22413
  // Probe directly (not the 5-min cache) so each tick sees fresh results.
22366
22414
  probe: () => probeLatestRelease(),
22367
- requestSync: (release) => schedulerClient.backlinksTriggerSync(release),
22415
+ requestSync: (release2) => schedulerClient.backlinksTriggerSync(release2),
22368
22416
  scheduledReleases: scheduledBacklinkReleases,
22369
22417
  log: app.log
22370
22418
  });
@@ -22619,7 +22667,7 @@ async function createServer(opts) {
22619
22667
  })();
22620
22668
  if (opts.config.apiKey) {
22621
22669
  const keyHash = hashApiKey(opts.config.apiKey);
22622
- const existing = opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, keyHash)).get();
22670
+ const existing = opts.db.select().from(apiKeys).where(eq40(apiKeys.keyHash, keyHash)).get();
22623
22671
  if (!existing) {
22624
22672
  const prefix = opts.config.apiKey.slice(0, 12);
22625
22673
  opts.db.insert(apiKeys).values({
@@ -22638,14 +22686,14 @@ async function createServer(opts) {
22638
22686
  );
22639
22687
  const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
22640
22688
  opts.db.delete(dashboardSessions).where(or4(
22641
- eq39(dashboardSessions.apiKeyHash, ""),
22689
+ eq40(dashboardSessions.apiKeyHash, ""),
22642
22690
  and33(
22643
22691
  isNotNull5(dashboardSessions.passwordFingerprint),
22644
22692
  ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
22645
22693
  )
22646
22694
  )).run();
22647
22695
  if (!opts.config.dashboardPasswordHash) {
22648
- const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and33(eq39(auditLog.entityType, "dashboard-password"), eq39(auditLog.action, action))).get()?.at ?? null;
22696
+ const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and33(eq40(auditLog.entityType, "dashboard-password"), eq40(auditLog.action, action))).get()?.at ?? null;
22649
22697
  const createdAt = lastPasswordEventAt("dashboard-password.created");
22650
22698
  const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
22651
22699
  if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
@@ -22679,23 +22727,23 @@ async function createServer(opts) {
22679
22727
  currentApiKeyHash: apiKeys.keyHash,
22680
22728
  passwordFingerprint: dashboardSessions.passwordFingerprint,
22681
22729
  expiresAt: dashboardSessions.expiresAt
22682
- }).from(dashboardSessions).innerJoin(apiKeys, eq39(apiKeys.id, dashboardSessions.apiKeyId)).where(and33(eq39(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
22730
+ }).from(dashboardSessions).innerJoin(apiKeys, eq40(apiKeys.id, dashboardSessions.apiKeyId)).where(and33(eq40(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
22683
22731
  if (!session) return null;
22684
22732
  const expiresAt = Date.parse(session.expiresAt);
22685
22733
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
22686
- opts.db.delete(dashboardSessions).where(eq39(dashboardSessions.tokenHash, tokenHash)).run();
22734
+ opts.db.delete(dashboardSessions).where(eq40(dashboardSessions.tokenHash, tokenHash)).run();
22687
22735
  return null;
22688
22736
  }
22689
22737
  return session.apiKeyId;
22690
22738
  };
22691
22739
  const clearSession = (sessionId) => {
22692
22740
  if (sessionId) {
22693
- opts.db.delete(dashboardSessions).where(eq39(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
22741
+ opts.db.delete(dashboardSessions).where(eq40(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
22694
22742
  }
22695
22743
  };
22696
22744
  const getDefaultApiKey = () => {
22697
22745
  if (!opts.config.apiKey) return void 0;
22698
- return opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
22746
+ return opts.db.select().from(apiKeys).where(eq40(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
22699
22747
  };
22700
22748
  const setSessionCookie = (reply, sessionId) => {
22701
22749
  reply.header(
@@ -22856,12 +22904,12 @@ async function createServer(opts) {
22856
22904
  return reply.send({ authenticated: true });
22857
22905
  }
22858
22906
  if (apiKey) {
22859
- const key = opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, hashApiKey(apiKey))).get();
22907
+ const key = opts.db.select().from(apiKeys).where(eq40(apiKeys.keyHash, hashApiKey(apiKey))).get();
22860
22908
  if (!key || key.revokedAt) {
22861
22909
  const err2 = authInvalid();
22862
22910
  return reply.status(err2.statusCode).send(err2.toJSON());
22863
22911
  }
22864
- opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq39(apiKeys.id, key.id)).run();
22912
+ opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq40(apiKeys.id, key.id)).run();
22865
22913
  setSessionCookie(reply, createSession(key));
22866
22914
  return reply.send({ authenticated: true });
22867
22915
  }
@@ -22927,7 +22975,7 @@ async function createServer(opts) {
22927
22975
  const sentimentPoller = createSentimentPoller(
22928
22976
  () => sentimentWorker.tick(),
22929
22977
  () => {
22930
- log32.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
22978
+ log33.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
22931
22979
  }
22932
22980
  );
22933
22981
  const pollSentiment = sentimentPoller.poll;
@@ -22939,7 +22987,7 @@ async function createServer(opts) {
22939
22987
  const recomputeDebts = /* @__PURE__ */ new Map();
22940
22988
  let recomputeSequence = 0;
22941
22989
  const markAnswerFieldRecompute = (projectId, full) => {
22942
- opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql16`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq39(projects.id, projectId)).run();
22990
+ opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql16`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq40(projects.id, projectId)).run();
22943
22991
  };
22944
22992
  const requestAnswerFieldRecompute = (projectId, projectName, scope, reason) => {
22945
22993
  const sequence = ++recomputeSequence;
@@ -22957,10 +23005,10 @@ async function createServer(opts) {
22957
23005
  if (pass.full && debt.latestFull <= sequence) debt.latestFull = 0;
22958
23006
  try {
22959
23007
  if (debt.latest === sequence && debt.latestFull === 0) {
22960
- opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq39(projects.id, projectId)).run();
23008
+ opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq40(projects.id, projectId)).run();
22961
23009
  if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
22962
23010
  } else if (debt.latestFull === 0) {
22963
- opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and33(eq39(projects.id, projectId), eq39(projects.answerFieldsRecompute, "full"))).run();
23011
+ opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and33(eq40(projects.id, projectId), eq40(projects.answerFieldsRecompute, "full"))).run();
22964
23012
  }
22965
23013
  } catch (err) {
22966
23014
  app.log.error({ err, projectId }, "could not clear the owed answer field recompute");
@@ -22997,7 +23045,7 @@ async function createServer(opts) {
22997
23045
  await yieldToEventLoop4();
22998
23046
  const reason = (competitorAutoAliasReasons.get(projectId) ?? []).join(",");
22999
23047
  competitorAutoAliasReasons.delete(projectId);
23000
- const project = opts.db.select().from(projects).where(eq39(projects.id, projectId)).get();
23048
+ const project = opts.db.select().from(projects).where(eq40(projects.id, projectId)).get();
23001
23049
  if (!project || project.competitorAutoAliases === "off") return;
23002
23050
  if (project.competitorAutoAliases === "apply") {
23003
23051
  await competitorAutoAliases.request(projectId, reason).catch(() => void 0);
@@ -23222,8 +23270,8 @@ async function createServer(opts) {
23222
23270
  getAgentPin: () => describeAgentPin(opts.config),
23223
23271
  getGoogleMarketingDoctorInput: (ctx) => {
23224
23272
  if (!ctx.project) return null;
23225
- const googleAds = opts.db.select().from(googleAdsConnections).where(eq39(googleAdsConnections.projectId, ctx.project.id)).get();
23226
- const gtm = opts.db.select().from(gtmConnections).where(eq39(gtmConnections.projectId, ctx.project.id)).get();
23273
+ const googleAds = opts.db.select().from(googleAdsConnections).where(eq40(googleAdsConnections.projectId, ctx.project.id)).get();
23274
+ const gtm = opts.db.select().from(gtmConnections).where(eq40(gtmConnections.projectId, ctx.project.id)).get();
23227
23275
  const googleAdsCredential = getGoogleAdsConnection(opts.config, ctx.project.id);
23228
23276
  const gtmCredential = getGtmConnection(opts.config, ctx.project.id);
23229
23277
  const googleAdsConnected = Boolean(googleAdsCredential?.accessToken);
@@ -23345,10 +23393,10 @@ async function createServer(opts) {
23345
23393
  alreadyPresent: result.alreadyPresent
23346
23394
  };
23347
23395
  },
23348
- onReleaseSyncRequested: (syncId, release) => {
23396
+ onReleaseSyncRequested: (syncId, release2) => {
23349
23397
  executeReleaseSync(opts.db, syncId, {
23350
- release,
23351
- trigger: scheduledBacklinkReleases.delete(release) ? OutcomeTriggers.scheduled : OutcomeTriggers.manual,
23398
+ release: release2,
23399
+ trigger: scheduledBacklinkReleases.delete(release2) ? OutcomeTriggers.scheduled : OutcomeTriggers.manual,
23352
23400
  deps: {
23353
23401
  enqueueAutoExtract: ({ projectId, release: r }) => {
23354
23402
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -23375,8 +23423,8 @@ async function createServer(opts) {
23375
23423
  app.log.error({ syncId, err }, "Common Crawl release sync failed");
23376
23424
  });
23377
23425
  },
23378
- onBacklinkExtractRequested: (runId, projectId, release) => {
23379
- executeBacklinkExtract(opts.db, runId, projectId, { release }).catch(
23426
+ onBacklinkExtractRequested: (runId, projectId, release2) => {
23427
+ executeBacklinkExtract(opts.db, runId, projectId, { release: release2 }).catch(
23380
23428
  (err) => {
23381
23429
  app.log.error({ runId, err }, "Backlink extract failed");
23382
23430
  }
@@ -23429,11 +23477,11 @@ async function createServer(opts) {
23429
23477
  onSiteAuditRequested: (runId, projectId, auditOpts) => {
23430
23478
  runSiteAudit(runId, projectId, auditOpts);
23431
23479
  },
23432
- onBacklinksPruneCache: (release) => {
23480
+ onBacklinksPruneCache: (release2) => {
23433
23481
  try {
23434
- pruneCachedRelease(release);
23482
+ pruneCachedRelease(release2);
23435
23483
  } catch (err) {
23436
- app.log.error({ release, err }, "Failed to prune cached release");
23484
+ app.log.error({ release: release2, err }, "Failed to prune cached release");
23437
23485
  }
23438
23486
  },
23439
23487
  listCachedReleases: () => {
@@ -23469,11 +23517,17 @@ async function createServer(opts) {
23469
23517
  bingSettingsSummary,
23470
23518
  bingConnectionStore,
23471
23519
  onBingInspectSitemapRequested: (runId, projectId, inspectOpts) => {
23472
- executeBingInspectSitemap(opts.db, runId, projectId, {
23473
- ...inspectOpts,
23474
- config: opts.config
23475
- }).then(() => {
23476
- const finished = opts.db.select({ status: runs.status }).from(runs).where(eq39(runs.id, runId)).get();
23520
+ runBingJob(
23521
+ opts.db,
23522
+ opts.config,
23523
+ projectId,
23524
+ "inspect",
23525
+ () => executeBingInspectSitemap(opts.db, runId, projectId, {
23526
+ ...inspectOpts,
23527
+ config: opts.config
23528
+ })
23529
+ ).then(() => {
23530
+ const finished = opts.db.select({ status: runs.status }).from(runs).where(eq40(runs.id, runId)).get();
23477
23531
  if (finished?.status === RunStatuses.completed || finished?.status === RunStatuses.partial) {
23478
23532
  return maybeRefreshGscCoverage(
23479
23533
  opts.db,
@@ -23490,11 +23544,15 @@ async function createServer(opts) {
23490
23544
  });
23491
23545
  },
23492
23546
  onBingSyncRequested: (runId, projectId) => {
23493
- executeBingSync(opts.db, runId, projectId, { config: opts.config }).catch(
23494
- (err) => {
23495
- app.log.error({ runId, err }, "Bing sync failed");
23496
- }
23497
- );
23547
+ runBingJob(
23548
+ opts.db,
23549
+ opts.config,
23550
+ projectId,
23551
+ "sync",
23552
+ () => executeBingSync(opts.db, runId, projectId, { config: opts.config })
23553
+ ).catch((err) => {
23554
+ app.log.error({ runId, err }, "Bing sync failed");
23555
+ });
23498
23556
  },
23499
23557
  wordpressConnectionStore,
23500
23558
  ga4CredentialStore,
@@ -23973,7 +24031,7 @@ async function createServer(opts) {
23973
24031
  isBacklinksInstalled: () => isDuckdbInstalled()
23974
24032
  });
23975
24033
  }
23976
- for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq39(researchRuns.status, ResearchRunStatuses.queued)).all()) {
24034
+ for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq40(researchRuns.status, ResearchRunStatuses.queued)).all()) {
23977
24035
  dispatchResearchRun(run.id, run.projectId, OutcomeTriggers.startup);
23978
24036
  }
23979
24037
  runtimeStartupSettled = true;