@canonry/canonry 7.57.1 → 7.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +28 -0
  2. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +6 -0
  3. package/assets/assets/{AgentSetupPage-C-kQupMX.js → AgentSetupPage-DZBjF9HP.js} +3 -3
  4. package/assets/assets/{AuditHistoryPanel-DvZk-ikR.js → AuditHistoryPanel-DAY6GbzH.js} +1 -1
  5. package/assets/assets/{BacklinksPage-TLB85t4y.js → BacklinksPage-Ci9s8osY.js} +1 -1
  6. package/assets/assets/{HistoryPage-C4nHeKDs.js → HistoryPage-BM7PM3Ow.js} +1 -1
  7. package/assets/assets/MeasurementPropertyPage-DgMIc9zm.js +4 -0
  8. package/assets/assets/ProjectPage-OOpNW437.js +9 -0
  9. package/assets/assets/RunsPage-B6dUljTT.js +1 -0
  10. package/assets/assets/{SettingsPage-BjLpSN4f.js → SettingsPage-DjhPnQNP.js} +1 -1
  11. package/assets/assets/SiteHealthSection-CQipxjCq.js +2 -0
  12. package/assets/assets/ToneBadge-Bk7cBexZ.js +60 -0
  13. package/assets/assets/{TrafficPage-BtjRPsdl.js → TrafficPage-TceTtJmu.js} +2 -2
  14. package/assets/assets/{TrafficSourceDetailPage-Bw-9JMOF.js → TrafficSourceDetailPage-BVAVo-JO.js} +1 -1
  15. package/assets/assets/{account-context-bLel7cL8.js → account-context-ChEngAKj.js} +1 -1
  16. package/assets/assets/{card-DFlbarlV.js → card-qOcJFZhl.js} +1 -1
  17. package/assets/assets/{extract-error-message-BYvs9oIt.js → extract-error-message-bWEYiDDO.js} +1 -1
  18. package/assets/assets/{format-helpers-DPVlVrlp.js → format-helpers-CvOZG1pt.js} +1 -1
  19. package/assets/assets/{index-BMD46UDb.css → index-D67dZGOY.css} +1 -1
  20. package/assets/assets/index-cRQCvw6S.js +56 -0
  21. package/assets/assets/query-client-nsJhXK9R.js +1 -0
  22. package/assets/assets/react-query-BKjNH2ek.js +1 -0
  23. package/assets/assets/{react-sigma_core.esm.min-BaR2koVY.js → react-sigma_core.esm.min-RpFcdsyW.js} +1 -1
  24. package/assets/assets/{service-DiBkOka7.js → service-DwTt-v6l.js} +1 -1
  25. package/assets/index.html +8 -8
  26. package/dist/{ads-6PCFYPZ6.js → ads-BMBXQB67.js} +3 -3
  27. package/dist/{agent-UA3J23KG.js → agent-S6CU36RL.js} +7 -7
  28. package/dist/{agent-ask-D4RWVHZX.js → agent-ask-XG7WQBX6.js} +3 -3
  29. package/dist/{agent-conversations-BSKUJF7H.js → agent-conversations-C4QBZAPC.js} +3 -3
  30. package/dist/{agent-memory-ENPPLOV7.js → agent-memory-I7UJ7MKH.js} +3 -3
  31. package/dist/{agent-providers-5NV7YEVG.js → agent-providers-YHRIYJDT.js} +3 -3
  32. package/dist/{agent-transcript-TXDTQ7Q2.js → agent-transcript-2WICUOEW.js} +3 -3
  33. package/dist/{analytics-6ITOJIGW.js → analytics-Y5AGSYWD.js} +3 -3
  34. package/dist/{apply-EPQXYQRO.js → apply-DLVLMU3O.js} +3 -3
  35. package/dist/{backfill-WHQ5PRQY.js → backfill-JAHDHVXJ.js} +9 -9
  36. package/dist/{backlinks-ECIDQQ4I.js → backlinks-TEZTPNZ5.js} +3 -3
  37. package/dist/{bing-LHTVVJK7.js → bing-IIA5HLND.js} +3 -3
  38. package/dist/{bootstrap-KHYUCFLP.js → bootstrap-AKGA3BJI.js} +10 -10
  39. package/dist/{cdp-YZWEKVRO.js → cdp-WWOFWFYU.js} +7 -7
  40. package/dist/{chunk-2R32P77U.js → chunk-27SGL3DF.js} +1 -1
  41. package/dist/{chunk-72GHLLA5.js → chunk-2DZYA62C.js} +18 -6
  42. package/dist/{chunk-S2UDQAT7.js → chunk-3U7LL3JM.js} +1 -1
  43. package/dist/{chunk-BURMKOEF.js → chunk-4P7NK7XM.js} +2 -2
  44. package/dist/{chunk-MVUYDJ7G.js → chunk-4TM4NXQR.js} +2 -2
  45. package/dist/{chunk-GT7HWKBO.js → chunk-4UGM5YV4.js} +3 -3
  46. package/dist/{chunk-ZUAXF73A.js → chunk-52NCZIAC.js} +1 -1
  47. package/dist/{chunk-TIYL4KVS.js → chunk-6IBLGQVZ.js} +1 -1
  48. package/dist/{chunk-N6P3NLEI.js → chunk-7CKJTD3Q.js} +1129 -905
  49. package/dist/{chunk-6MK426LA.js → chunk-BP5OKJIC.js} +2 -2
  50. package/dist/{chunk-SOKD3TRA.js → chunk-F6W7FCS2.js} +196 -2
  51. package/dist/{chunk-HPC3CBPI.js → chunk-G34BVUMF.js} +1 -1
  52. package/dist/{chunk-XXYBDAS2.js → chunk-IFVTHGXG.js} +2 -2
  53. package/dist/{chunk-LCC5ZJPV.js → chunk-JGRUCEL4.js} +2 -2
  54. package/dist/{chunk-OJ5IDPYY.js → chunk-KWXARGCT.js} +27 -5
  55. package/dist/{chunk-VF36TGF4.js → chunk-L7TKNHEX.js} +1 -1
  56. package/dist/{chunk-522MYBLV.js → chunk-N2HCXIQ3.js} +1 -1
  57. package/dist/{chunk-4MJYGB56.js → chunk-NCIPNVD6.js} +8 -0
  58. package/dist/{chunk-HFMRK3V3.js → chunk-NMLVLFF7.js} +5 -5
  59. package/dist/{chunk-AMN7DC25.js → chunk-NS7KRCND.js} +1140 -573
  60. package/dist/{chunk-FC2JA3FN.js → chunk-NWQQYLZV.js} +2858 -2250
  61. package/dist/{chunk-W7EX6AYN.js → chunk-PEZO3YEC.js} +4 -4
  62. package/dist/{chunk-TXBL3N46.js → chunk-Q4J3XSWE.js} +1 -1
  63. package/dist/{chunk-RNDQREJC.js → chunk-QFO7JHX2.js} +9 -4
  64. package/dist/{chunk-KRIZF753.js → chunk-QSPLYPVA.js} +1 -1
  65. package/dist/{chunk-SLN2KNEE.js → chunk-RXMGU7AF.js} +8 -8
  66. package/dist/{chunk-5AJWITKP.js → chunk-SCS7R2ND.js} +2269 -2011
  67. package/dist/{chunk-3HRHHFQM.js → chunk-TH3NNUJW.js} +17 -1
  68. package/dist/{chunk-YFUQHJRZ.js → chunk-TVANRUBO.js} +108 -83
  69. package/dist/{chunk-JWBFDZIP.js → chunk-U65LWABS.js} +7 -3
  70. package/dist/{chunk-5L2ZTXBH.js → chunk-WLIGKWVB.js} +3 -3
  71. package/dist/{chunk-TIKT62IV.js → chunk-Y7NX6EIK.js} +1803 -1456
  72. package/dist/{chunk-ULFDCKIC.js → chunk-YDSY5YJE.js} +4 -4
  73. package/dist/{chunk-F7WRZW3A.js → chunk-YJPQBJZO.js} +250 -3
  74. package/dist/{chunk-E3YBETL6.js → chunk-ZYL3LCDZ.js} +1 -1
  75. package/dist/{citations-HXVWVRDO.js → citations-4LVBHTDX.js} +3 -3
  76. package/dist/{cli-catalog-EDAH3242.js → cli-catalog-PJYR3JHX.js} +3 -3
  77. package/dist/{cli-commands-5O54JBVV.js → cli-commands-2HYNKJDJ.js} +7 -7
  78. package/dist/cli.js +13 -13
  79. package/dist/{competitor-XYPBUM4Q.js → competitor-T7UXAW4F.js} +3 -3
  80. package/dist/{content-SDTRO2XT.js → content-DFYYGGPI.js} +3 -3
  81. package/dist/{dashboard-TERSQLOV.js → dashboard-2P3TEH6S.js} +6 -6
  82. package/dist/{demo-UT5Y2RFF.js → demo-UBMNDBRF.js} +1 -1
  83. package/dist/{demo-server-5D6QLZOA.js → demo-server-F4M74FVL.js} +11 -11
  84. package/dist/{discover-I6AQJPUK.js → discover-QTC5OBQG.js} +3 -3
  85. package/dist/{discover-eval-GLGBZC7B.js → discover-eval-QQZGUPR6.js} +3 -3
  86. package/dist/{doctor-Q47J7GZI.js → doctor-VHFDL5MH.js} +3 -3
  87. package/dist/{evidence-AMLTPRHA.js → evidence-4PRFOC2I.js} +3 -3
  88. package/dist/{export-cmd-NTCX43DE.js → export-cmd-BQE7BPKZ.js} +3 -3
  89. package/dist/{ga-END6LQJW.js → ga-ULY5XDBK.js} +3 -3
  90. package/dist/{gbp-CVJXSTTB.js → gbp-4WHNZAFY.js} +3 -3
  91. package/dist/{google-4OCFGWGV.js → google-O4IVWLSG.js} +4 -4
  92. package/dist/{google-marketing-NW27PADK.js → google-marketing-DCQDTDDG.js} +1 -1
  93. package/dist/{health-cmd-2KMNASB3.js → health-cmd-I2JTACS7.js} +3 -3
  94. package/dist/{history-6LBFXVKF.js → history-LUPHO3P3.js} +3 -3
  95. package/dist/index.d.ts +1197 -4
  96. package/dist/index.js +25 -25
  97. package/dist/{init-ONIDATRC.js → init-YKMNKERW.js} +11 -11
  98. package/dist/{insights-YH7NP5LX.js → insights-GC2W45U4.js} +3 -3
  99. package/dist/intelligence-service-4PHEK5F4.js +15 -0
  100. package/dist/{keys-CJ5DTL4Y.js → keys-DXQBSOBI.js} +3 -3
  101. package/dist/{keyword-7FMLF3B7.js → keyword-2DCR2QCJ.js} +3 -3
  102. package/dist/{logs-362Y2Z55.js → logs-H45QFIEB.js} +3 -3
  103. package/dist/{mcp-RTJ3HZLY.js → mcp-NXXP6M3C.js} +2 -2
  104. package/dist/mcp.js +10 -10
  105. package/dist/{measurement-plan-ICT6U62D.js → measurement-plan-IG4JUKKW.js} +5 -5
  106. package/dist/{notify-HT7QBF3B.js → notify-BLLWXMBB.js} +3 -3
  107. package/dist/{organic-evidence-CAGEQ5OR.js → organic-evidence-73K7W7SB.js} +3 -3
  108. package/dist/{overview-Y6RVRPC7.js → overview-4TAULPUG.js} +4 -4
  109. package/dist/{project-7OBPDHLH.js → project-ANX4JTWS.js} +3 -3
  110. package/dist/{query-23GN3BC6.js → query-U3MFTLGR.js} +3 -3
  111. package/dist/{research-N7EVBN47.js → research-3YZ6QI67.js} +3 -3
  112. package/dist/{results-export-BHEYAZXQ.js → results-export-72OVLKSC.js} +3 -3
  113. package/dist/{run-KVPMLHGQ.js → run-SI6IL4FC.js} +4 -4
  114. package/dist/{schedule-EZ2TLM22.js → schedule-FYEHU2VH.js} +3 -3
  115. package/dist/{search-UHUPUGT3.js → search-MXDT3DQE.js} +3 -3
  116. package/dist/{serve-VG52MHRC.js → serve-C4FOCQEX.js} +26 -26
  117. package/dist/{session-IQKGJYKH.js → session-VTFLD3C5.js} +13 -13
  118. package/dist/{settings-QCFPNHSC.js → settings-ZGS26QOP.js} +3 -3
  119. package/dist/{skills-FXPAKCVV.js → skills-ZMMCKKSA.js} +2 -2
  120. package/dist/{snapshot-NY5PNDWR.js → snapshot-5AGGUQKE.js} +3 -3
  121. package/dist/{src-V6W5XBAI.js → src-AIM5FPLZ.js} +15 -2
  122. package/dist/{status-MYXAVPIB.js → status-HVQI4E5X.js} +4 -4
  123. package/dist/{technical-aeo-4C2EQ6C5.js → technical-aeo-S4OFCURE.js} +3 -3
  124. package/dist/{telemetry-SMY4NDD2.js → telemetry-SPSC5MUN.js} +4 -4
  125. package/dist/{tools-KKSEFA25.js → tools-LRHO7QOT.js} +11 -11
  126. package/dist/{traffic-QTHEOB5M.js → traffic-5AXVN37M.js} +5 -5
  127. package/dist/{users-FDZPHCWI.js → users-WFKSUCGV.js} +3 -3
  128. package/dist/{visibility-stats-6B3S3AIY.js → visibility-stats-5S26GC27.js} +3 -3
  129. package/dist/{wordpress-5IIA4H3G.js → wordpress-IUPZC7II.js} +3 -3
  130. package/package.json +2 -1
  131. package/assets/assets/MeasurementPropertyPage-8E17rN5d.js +0 -4
  132. package/assets/assets/ProjectPage-B4SbAE_N.js +0 -7
  133. package/assets/assets/RunsPage-Enho1Wqz.js +0 -1
  134. package/assets/assets/SiteHealthSection-BUOBO4VH.js +0 -2
  135. package/assets/assets/ToneBadge-BLQKJIMR.js +0 -60
  136. package/assets/assets/index-DWP0Oz6d.js +0 -56
  137. package/assets/assets/query-client-DLuEpFRm.js +0 -1
  138. package/assets/assets/react-query-BVY1CIRz.js +0 -1
  139. package/dist/intelligence-service-KRIDKJH2.js +0 -15
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answerServiceAdapters,
3
3
  answerServiceDescriptors
4
- } from "./chunk-ZUAXF73A.js";
4
+ } from "./chunk-52NCZIAC.js";
5
5
  import {
6
6
  AeroLlmUsageFeatures,
7
7
  aeroTurnStatus,
@@ -27,14 +27,14 @@ import {
27
27
  resolveConfiguredAgentProvider,
28
28
  resolveSessionProviderAndModel,
29
29
  setAeroSystemPrompt
30
- } from "./chunk-72GHLLA5.js";
30
+ } from "./chunk-2DZYA62C.js";
31
31
  import {
32
32
  AeroToolProfiles,
33
33
  AeroToolScopes,
34
34
  buildAeroStateTools,
35
35
  isAeroToolProfile,
36
36
  truncateToolResult
37
- } from "./chunk-RNDQREJC.js";
37
+ } from "./chunk-QFO7JHX2.js";
38
38
  import {
39
39
  getGoogleAuthConfig,
40
40
  getGoogleConnection,
@@ -53,7 +53,7 @@ import {
53
53
  removeCloudflareTrafficConnection,
54
54
  removeCloudflareTrafficConnectionBySourceId,
55
55
  upsertCloudflareTrafficConnection
56
- } from "./chunk-TIYL4KVS.js";
56
+ } from "./chunk-6IBLGQVZ.js";
57
57
  import {
58
58
  claudeAdapter,
59
59
  embedQueries,
@@ -64,7 +64,7 @@ import {
64
64
  openaiAdapter,
65
65
  openrouterAdapter,
66
66
  perplexityAdapter
67
- } from "./chunk-6MK426LA.js";
67
+ } from "./chunk-BP5OKJIC.js";
68
68
  import {
69
69
  classifyUsageSurface,
70
70
  createApiUsageTelemetry,
@@ -76,7 +76,7 @@ import {
76
76
  startOutcomeTimer,
77
77
  trackFeatureCompleted,
78
78
  trackInstallState
79
- } from "./chunk-ULFDCKIC.js";
79
+ } from "./chunk-YDSY5YJE.js";
80
80
  import {
81
81
  isLoopbackBindHost
82
82
  } from "./chunk-TSENU4GG.js";
@@ -84,7 +84,7 @@ import {
84
84
  isApiProviderRegistrable,
85
85
  isCdpProviderRegistrable,
86
86
  registeredProviderNames
87
- } from "./chunk-S2UDQAT7.js";
87
+ } from "./chunk-3U7LL3JM.js";
88
88
  import {
89
89
  checkLatestVersionForServer,
90
90
  getOrCreateAnonymousId,
@@ -95,17 +95,17 @@ import {
95
95
  recordDashboardEvent,
96
96
  setTelemetryPreference,
97
97
  trackEvent
98
- } from "./chunk-XXYBDAS2.js";
98
+ } from "./chunk-IFVTHGXG.js";
99
99
  import {
100
100
  createCanonryMcpServer
101
- } from "./chunk-OJ5IDPYY.js";
101
+ } from "./chunk-KWXARGCT.js";
102
102
  import {
103
103
  CANONRY_MCP_TIERS,
104
104
  CANONRY_MCP_TOOLKIT_NAMES
105
- } from "./chunk-4MJYGB56.js";
105
+ } from "./chunk-NCIPNVD6.js";
106
106
  import {
107
107
  ApiClient
108
- } from "./chunk-SOKD3TRA.js";
108
+ } from "./chunk-F6W7FCS2.js";
109
109
  import {
110
110
  AGENT_PROVIDERS,
111
111
  adapterSupportsBatch,
@@ -136,21 +136,21 @@ import {
136
136
  saveConfigPatch,
137
137
  sentimentInstallReadiness,
138
138
  updateSharedProviderExecutionGate
139
- } from "./chunk-YFUQHJRZ.js";
139
+ } from "./chunk-TVANRUBO.js";
140
140
  import {
141
141
  getBundledSkillSnapshots
142
- } from "./chunk-HPC3CBPI.js";
142
+ } from "./chunk-G34BVUMF.js";
143
143
  import {
144
144
  computeFactorAverages,
145
145
  deleteSiteCrawlGraphLayout,
146
146
  persistSiteCrawlGraphLayout,
147
147
  prepareSiteCrawlGraphLayout,
148
148
  recordedSharePct
149
- } from "./chunk-MVUYDJ7G.js";
149
+ } from "./chunk-4TM4NXQR.js";
150
150
  import {
151
151
  CanonryMcpToolNames,
152
152
  canonryMcpTools
153
- } from "./chunk-F7WRZW3A.js";
153
+ } from "./chunk-YJPQBJZO.js";
154
154
  import {
155
155
  PACKAGE_VERSION
156
156
  } from "./chunk-AOJU5LKX.js";
@@ -162,11 +162,11 @@ import {
162
162
  addLogListener,
163
163
  createFastifyLogger,
164
164
  createLogger
165
- } from "./chunk-HFMRK3V3.js";
165
+ } from "./chunk-NMLVLFF7.js";
166
166
  import {
167
167
  computeCitedCompetitorDomains,
168
168
  determineCitationState
169
- } from "./chunk-VF36TGF4.js";
169
+ } from "./chunk-L7TKNHEX.js";
170
170
  import {
171
171
  BingApiError,
172
172
  CC_CACHE_DIR,
@@ -284,11 +284,12 @@ import {
284
284
  webhookResponseReason,
285
285
  webhookTargetRefusalReason,
286
286
  writeAuditLog
287
- } from "./chunk-FC2JA3FN.js";
287
+ } from "./chunk-NWQQYLZV.js";
288
288
  import {
289
289
  OperationalLogStore,
290
290
  SentimentIdempotencyConflict,
291
291
  SentimentRepository,
292
+ SeoRepository,
292
293
  adsAdGroups,
293
294
  adsAds,
294
295
  adsCampaigns,
@@ -355,6 +356,8 @@ import {
355
356
  schedules,
356
357
  sentimentCompletionReceipts,
357
358
  sentimentSettings,
359
+ seoJobs,
360
+ seoTasks,
358
361
  siteAuditPages,
359
362
  siteAuditSnapshots,
360
363
  siteCrawlAttempts,
@@ -367,7 +370,7 @@ import {
367
370
  siteLivenessState,
368
371
  trafficSources,
369
372
  usageCounters
370
- } from "./chunk-5AJWITKP.js";
373
+ } from "./chunk-SCS7R2ND.js";
371
374
  import {
372
375
  AGENT_MEMORY_VALUE_MAX_BYTES,
373
376
  AI_ENGINE_DOMAINS,
@@ -442,6 +445,11 @@ import {
442
445
  STORED_ONLY_HEADER,
443
446
  SchedulableRunKinds,
444
447
  SentimentOutcomes,
448
+ SeoAdapterOutcomes,
449
+ SeoCapabilities,
450
+ SeoProviders,
451
+ SeoRunStatuses,
452
+ SeoTargetKinds,
445
453
  SiteHealthLinkClassificationSources,
446
454
  SnapshotProviderModes,
447
455
  TrafficSourceStatuses,
@@ -505,6 +513,7 @@ import {
505
513
  effectiveDomains,
506
514
  embedClientConfigForRequest,
507
515
  embedProjectTabsError,
516
+ emptySeoResults,
508
517
  escapeRegExp,
509
518
  extractProviderHttpStatus,
510
519
  extractRecommendedCompetitors,
@@ -552,6 +561,7 @@ import {
552
561
  mostActionableProviderErrorCode,
553
562
  nextScheduleUpdatedAt,
554
563
  normalizeAgentSlug,
564
+ normalizeHostname,
555
565
  normalizeIdTokens,
556
566
  normalizeMeasurementExecutionQueryText,
557
567
  normalizeProjectDomain,
@@ -584,6 +594,7 @@ import {
584
594
  sentimentClassifierOutputSchema,
585
595
  sentimentEvaluatorProvider,
586
596
  sentimentSelectionSchema,
597
+ seoProfileInputSchema,
587
598
  serializeForInlineScript,
588
599
  serializeRunError,
589
600
  shiftIsoCalendarDate,
@@ -604,7 +615,7 @@ import {
604
615
  winnabilityClassLabel,
605
616
  withRetry,
606
617
  withSkippedProviders
607
- } from "./chunk-TIKT62IV.js";
618
+ } from "./chunk-Y7NX6EIK.js";
608
619
 
609
620
  // src/google-marketing-runtime.ts
610
621
  import crypto2 from "crypto";
@@ -3294,11 +3305,556 @@ import path5 from "path";
3294
3305
  import { isIP as isIP2 } from "net";
3295
3306
  import { fileURLToPath } from "url";
3296
3307
  import { setImmediate as yieldToEventLoop4 } from "timers/promises";
3297
- import { and as and26, eq as eq32, isNotNull as isNotNull5, isNull as isNull7, lte as lte3, max, ne as ne4, or as or4, sql as sql13 } from "drizzle-orm";
3308
+ import { and as and26, eq as eq33, isNotNull as isNotNull5, isNull as isNull7, lte as lte3, max, ne as ne4, or as or4, sql as sql13 } from "drizzle-orm";
3298
3309
 
3299
- // ../integration-typesafe/src/classifier.ts
3310
+ // src/seo-runtime.ts
3311
+ import { eq, inArray } from "drizzle-orm";
3312
+
3313
+ // ../integration-dataforseo/src/adapter.ts
3300
3314
  import { createHash } from "crypto";
3301
3315
 
3316
+ // ../integration-dataforseo/src/client.ts
3317
+ import { z } from "zod";
3318
+ var taskSchema = z.object({
3319
+ id: z.string().nullish(),
3320
+ status_code: z.number().int(),
3321
+ cost: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER / 1e6).nullish(),
3322
+ result: z.array(z.unknown()).nullish()
3323
+ });
3324
+ var dataForSeoEnvelopeSchema = z.object({
3325
+ status_code: z.number().int(),
3326
+ cost: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER / 1e6).nullish(),
3327
+ tasks: z.array(taskSchema).nullish()
3328
+ });
3329
+ var DataForSeoTransportError = class extends Error {
3330
+ constructor(status, unaccepted, throttle, retryAfter = null) {
3331
+ super(throttle ? "SEO provider rate limit exceeded." : "SEO provider request could not be completed.");
3332
+ this.status = status;
3333
+ this.unaccepted = unaccepted;
3334
+ this.throttle = throttle;
3335
+ this.retryAfter = retryAfter;
3336
+ }
3337
+ status;
3338
+ unaccepted;
3339
+ throttle;
3340
+ retryAfter;
3341
+ };
3342
+ async function fetchOnce2(credentials, endpoint, task, signal) {
3343
+ const response = await fetch(`https://api.dataforseo.com/v3/dataforseo_labs/google/${endpoint}/live`, {
3344
+ method: "POST",
3345
+ headers: {
3346
+ Authorization: `Basic ${Buffer.from(`${credentials.login}:${credentials.password}`).toString("base64")}`,
3347
+ "Content-Type": "application/json"
3348
+ },
3349
+ body: JSON.stringify([task]),
3350
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(6e4)]) : AbortSignal.timeout(6e4)
3351
+ });
3352
+ if (!response.ok) {
3353
+ const throttle = response.status === 429;
3354
+ const unaccepted = throttle || [400, 401, 402, 403, 404].includes(response.status);
3355
+ throw new DataForSeoTransportError(response.status, unaccepted, throttle, response.headers.get("Retry-After"));
3356
+ }
3357
+ const envelope = dataForSeoEnvelopeSchema.parse(await response.json());
3358
+ const tasks = envelope.tasks ?? [];
3359
+ const rateCodes = /* @__PURE__ */ new Set([40202, 40209]);
3360
+ const allTasksRejected = tasks.length > 0 && tasks.every((item) => rateCodes.has(item.status_code) && item.cost === 0);
3361
+ const requestRejected = tasks.length === 0 && rateCodes.has(envelope.status_code) && envelope.cost === 0;
3362
+ if (allTasksRejected || requestRejected) {
3363
+ throw new DataForSeoTransportError(429, true, true, response.headers.get("Retry-After"));
3364
+ }
3365
+ return envelope;
3366
+ }
3367
+ async function dataForSeoFetch(credentials, endpoint, task, signal) {
3368
+ let refusal = null;
3369
+ return withRetry(() => {
3370
+ if (signal?.aborted) throw refusal ?? new Error("SEO request was cancelled.");
3371
+ return fetchOnce2(credentials, endpoint, task, signal);
3372
+ }, {
3373
+ maxRetries: 2,
3374
+ baseDelayMs: 2e3,
3375
+ maxDelayMs: 3e4,
3376
+ isRetryable: (error) => !signal?.aborted && error instanceof DataForSeoTransportError && error.unaccepted && error.throttle && isRetryableHttpError(error),
3377
+ computeDelayMs: (_attempt, error, defaultMs) => retryAfterDelayMs(error) ?? defaultMs,
3378
+ onRetry: ({ err }) => {
3379
+ if (err instanceof DataForSeoTransportError) refusal = err;
3380
+ },
3381
+ sleep: (ms) => new Promise((resolve, reject) => {
3382
+ if (signal?.aborted) {
3383
+ reject(refusal ?? new Error("SEO request was cancelled."));
3384
+ return;
3385
+ }
3386
+ const cancelled = () => {
3387
+ clearTimeout(timer);
3388
+ reject(refusal ?? new Error("SEO request was cancelled."));
3389
+ };
3390
+ const timer = setTimeout(() => {
3391
+ signal?.removeEventListener("abort", cancelled);
3392
+ resolve();
3393
+ }, ms);
3394
+ signal?.addEventListener("abort", cancelled, { once: true });
3395
+ })
3396
+ });
3397
+ }
3398
+
3399
+ // ../integration-dataforseo/src/normalize.ts
3400
+ import { z as z2 } from "zod";
3401
+ var count = z2.number().int().nonnegative().nullish();
3402
+ var amount = z2.number().nonnegative().nullish();
3403
+ var keywordInfoSchema = z2.object({
3404
+ last_updated_time: z2.string().nullish(),
3405
+ search_volume: count,
3406
+ cpc: amount,
3407
+ competition: z2.number().min(0).max(1).nullish(),
3408
+ monthly_searches: z2.array(z2.object({ year: z2.number().int(), month: z2.number().int().min(1).max(12), search_volume: count })).nullish()
3409
+ });
3410
+ var keywordDataSchema = z2.object({
3411
+ keyword: z2.string(),
3412
+ keyword_info: keywordInfoSchema.nullish(),
3413
+ keyword_properties: z2.object({ keyword_difficulty: z2.number().min(0).max(100).nullish(), core_keyword: z2.string().nullish() }).nullish(),
3414
+ search_intent_info: z2.object({ main_intent: z2.string().nullish() }).nullish(),
3415
+ serp_info: z2.object({ serp_item_types: z2.array(z2.string()).nullish(), last_updated_time: z2.string().nullish() }).nullish()
3416
+ });
3417
+ var domainItemSchema = z2.object({
3418
+ location_code: z2.number().int(),
3419
+ language_code: z2.string(),
3420
+ metrics: z2.object({ organic: z2.object({
3421
+ count,
3422
+ etv: amount,
3423
+ estimated_paid_traffic_cost: amount,
3424
+ pos_1: count,
3425
+ pos_2_3: count,
3426
+ pos_4_10: count,
3427
+ pos_11_20: count
3428
+ }).nullish() })
3429
+ });
3430
+ var rankedItemSchema = z2.object({
3431
+ keyword_data: keywordDataSchema,
3432
+ ranked_serp_element: z2.object({
3433
+ last_updated_time: z2.string().nullish(),
3434
+ serp_item: z2.object({
3435
+ type: z2.literal("organic"),
3436
+ domain: z2.string().nullish(),
3437
+ url: z2.string().nullish(),
3438
+ rank_group: z2.number().int().positive().nullish(),
3439
+ rank_absolute: z2.number().int().positive().nullish(),
3440
+ etv: amount
3441
+ })
3442
+ })
3443
+ });
3444
+ var resultSchema = z2.object({
3445
+ location_code: z2.number().int(),
3446
+ language_code: z2.string(),
3447
+ target: z2.string().optional(),
3448
+ items: z2.array(z2.unknown()).nullable()
3449
+ });
3450
+ function provenance(request, collectedAt, sourceUpdatedAt) {
3451
+ return {
3452
+ provider: SeoProviders.dataforseo,
3453
+ dataset: `dataforseo-labs/google/${request.capability}`,
3454
+ engine: "google",
3455
+ locationCode: request.locationCode,
3456
+ languageCode: request.languageCode,
3457
+ device: "unspecified",
3458
+ collectedAt,
3459
+ sourceUpdatedAt
3460
+ };
3461
+ }
3462
+ function keywordMetrics(item, request, collectedAt) {
3463
+ return {
3464
+ keyword: item.keyword,
3465
+ searchVolume: item.keyword_info?.search_volume ?? null,
3466
+ cpcUsd: item.keyword_info?.cpc ?? null,
3467
+ adCompetition: item.keyword_info?.competition ?? null,
3468
+ keywordDifficulty: item.keyword_properties?.keyword_difficulty ?? null,
3469
+ searchIntent: item.search_intent_info?.main_intent ?? null,
3470
+ coreKeyword: item.keyword_properties?.core_keyword ?? null,
3471
+ monthlySearches: (item.keyword_info?.monthly_searches ?? []).map((month) => ({
3472
+ year: month.year,
3473
+ month: month.month,
3474
+ searchVolume: month.search_volume ?? null
3475
+ })),
3476
+ provenance: provenance(request, collectedAt, item.keyword_info?.last_updated_time ?? null)
3477
+ };
3478
+ }
3479
+ function normalizeDataForSeoResults(rawResults, request, collectedAt) {
3480
+ const output = emptySeoResults();
3481
+ for (const raw of rawResults) {
3482
+ const result = resultSchema.parse(raw);
3483
+ if (result.location_code !== request.locationCode || result.language_code !== request.languageCode) {
3484
+ throw new Error("SEO provider returned a different market.");
3485
+ }
3486
+ const providerTarget = request.target?.kind === SeoTargetKinds.host ? registrableDomain(request.target.value) : request.target?.value.toLowerCase();
3487
+ if (request.target && result.target?.toLowerCase() !== providerTarget) {
3488
+ throw new Error("SEO provider returned a different target.");
3489
+ }
3490
+ const items = result.items ?? [];
3491
+ switch (request.capability) {
3492
+ case SeoCapabilities["keyword-metrics"]: {
3493
+ const requested = new Map(request.keywords.map((keyword) => [keyword.toLowerCase(), keyword]));
3494
+ for (const rawItem of items) {
3495
+ const item = keywordDataSchema.parse(rawItem);
3496
+ const original = requested.get(item.keyword.toLowerCase());
3497
+ if (!original) throw new Error("SEO provider returned an unrequested keyword.");
3498
+ output.keywordMetrics.push({ ...keywordMetrics(item, request, collectedAt), keyword: original });
3499
+ }
3500
+ break;
3501
+ }
3502
+ case SeoCapabilities["domain-intelligence"]: {
3503
+ if (!request.target) throw new Error("SEO target is required.");
3504
+ for (const rawItem of items) {
3505
+ const item = domainItemSchema.parse(rawItem);
3506
+ if (item.location_code !== request.locationCode || item.language_code !== request.languageCode) {
3507
+ throw new Error("SEO provider returned a different market.");
3508
+ }
3509
+ const organic = item.metrics.organic;
3510
+ output.domainIntelligence.push({
3511
+ target: request.target,
3512
+ organicKeywords: organic?.count ?? null,
3513
+ estimatedOrganicTraffic: organic?.etv ?? null,
3514
+ estimatedOrganicTrafficValueUsd: organic?.estimated_paid_traffic_cost ?? null,
3515
+ top1: organic?.pos_1 ?? null,
3516
+ top2To3: organic?.pos_2_3 ?? null,
3517
+ top4To10: organic?.pos_4_10 ?? null,
3518
+ top11To20: organic?.pos_11_20 ?? null,
3519
+ // This endpoint has no per-result dataset timestamp. Fetch time is not substituted.
3520
+ provenance: provenance(request, collectedAt, null)
3521
+ });
3522
+ }
3523
+ break;
3524
+ }
3525
+ case SeoCapabilities["ranked-keywords"]: {
3526
+ if (!request.target) throw new Error("SEO target is required.");
3527
+ for (const rawItem of items) {
3528
+ const item = rankedItemSchema.parse(rawItem);
3529
+ const metric = keywordMetrics(item.keyword_data, request, collectedAt);
3530
+ const serp = item.ranked_serp_element;
3531
+ if (request.target.kind === SeoTargetKinds.host && serp.serp_item.domain?.toLowerCase() !== request.target.value.toLowerCase()) {
3532
+ throw new Error("SEO provider returned evidence outside the exact host scope.");
3533
+ }
3534
+ output.rankedKeywords.push({
3535
+ target: request.target,
3536
+ keyword: metric.keyword,
3537
+ url: serp.serp_item.url ?? null,
3538
+ rankOrganic: serp.serp_item.rank_group ?? null,
3539
+ rankAbsolute: serp.serp_item.rank_absolute ?? null,
3540
+ searchVolume: metric.searchVolume,
3541
+ cpcUsd: metric.cpcUsd,
3542
+ keywordDifficulty: metric.keywordDifficulty,
3543
+ estimatedTraffic: serp.serp_item.etv ?? null,
3544
+ serpFeatures: item.keyword_data.serp_info?.serp_item_types ?? [],
3545
+ provenance: provenance(request, collectedAt, serp.last_updated_time ?? null)
3546
+ });
3547
+ }
3548
+ break;
3549
+ }
3550
+ }
3551
+ }
3552
+ return output;
3553
+ }
3554
+
3555
+ // ../integration-dataforseo/src/adapter.ts
3556
+ var ENDPOINTS = {
3557
+ [SeoCapabilities["keyword-metrics"]]: "keyword_overview",
3558
+ [SeoCapabilities["domain-intelligence"]]: "domain_rank_overview",
3559
+ [SeoCapabilities["ranked-keywords"]]: "ranked_keywords"
3560
+ };
3561
+ var REQUEST_REFUSALS = /* @__PURE__ */ new Set([4e4, 40006, 40100, 40104, 40200, 40203, 40205, 40206, 40207, 40210, 40501, 40502, 40503, 40506]);
3562
+ function taskPayload(request) {
3563
+ const parsed = seoProfileInputSchema.pick({ keywords: true, locationCode: true, languageCode: true, limit: true }).safeParse({
3564
+ keywords: request.keywords,
3565
+ locationCode: request.locationCode,
3566
+ languageCode: request.languageCode,
3567
+ limit: request.limit
3568
+ });
3569
+ if (!parsed.success) throw validationError("Check the SEO keywords, provider location, language, and row limit.");
3570
+ if (request.tag.length > 255) throw validationError("SEO task identifier is too long.");
3571
+ const common = { location_code: request.locationCode, language_code: request.languageCode, tag: request.tag };
3572
+ if (request.capability === SeoCapabilities["keyword-metrics"]) {
3573
+ if (request.keywords.length === 0 || new Set(request.keywords.map((keyword) => keyword.toLowerCase())).size !== request.keywords.length) {
3574
+ throw validationError("SEO keyword metrics require distinct keywords, ignoring case.");
3575
+ }
3576
+ return { ...common, keywords: request.keywords, include_clickstream_data: false, include_serp_info: true };
3577
+ }
3578
+ const target = request.target;
3579
+ const host = target ? normalizeHostname(target.value) : null;
3580
+ if (!target || !host || !registrableDomain(host)) {
3581
+ throw validationError("SEO requires a bare public domain or hostname.");
3582
+ }
3583
+ const domain = registrableDomain(host);
3584
+ if (target.kind === SeoTargetKinds.domain && (host !== domain || !target.includeSubdomains)) {
3585
+ throw validationError("Use the root domain with subdomains included, or choose exact host scope.");
3586
+ }
3587
+ if (target.kind === SeoTargetKinds.host && target.includeSubdomains) {
3588
+ throw validationError("Exact host scope cannot include subdomains.");
3589
+ }
3590
+ switch (request.capability) {
3591
+ case SeoCapabilities["domain-intelligence"]:
3592
+ if (target.kind !== SeoTargetKinds.domain) throw validationError("Domain intelligence requires a whole-domain scope.");
3593
+ return { ...common, target: host, limit: 1, ignore_synonyms: false };
3594
+ case SeoCapabilities["ranked-keywords"]:
3595
+ return {
3596
+ // Root-domain lookup plus an exact domain filter avoids DataForSEO treating
3597
+ // a leading www hostname as a single-page URL.
3598
+ ...common,
3599
+ target: target.kind === SeoTargetKinds.host ? domain : host,
3600
+ limit: request.limit,
3601
+ offset: 0,
3602
+ item_types: ["organic"],
3603
+ include_clickstream_data: false,
3604
+ ignore_synonyms: false,
3605
+ historical_serp_mode: "live",
3606
+ order_by: ["ranked_serp_element.serp_item.etv,desc"],
3607
+ ...target.kind === SeoTargetKinds.host ? { filters: ["ranked_serp_element.serp_item.domain", "=", host] } : {}
3608
+ };
3609
+ }
3610
+ }
3611
+ function estimate(request) {
3612
+ taskPayload(request);
3613
+ const rows = request.capability === SeoCapabilities["keyword-metrics"] ? request.keywords.length : request.capability === SeoCapabilities["domain-intelligence"] ? 1 : request.limit;
3614
+ return { maxCostMicros: 12e3 + 120 * rows, catalogRevision: "dataforseo-google-labs-2026-10-22" };
3615
+ }
3616
+ function appendResults(target, source) {
3617
+ target.keywordMetrics.push(...source.keywordMetrics);
3618
+ target.domainIntelligence.push(...source.domainIntelligence);
3619
+ target.rankedKeywords.push(...source.rankedKeywords);
3620
+ }
3621
+ function createDataForSeoAdapter(credentials) {
3622
+ const auth = { login: credentials.login.trim(), password: credentials.password };
3623
+ const accountKey = createHash("sha256").update(`dataforseo:${credentials.login.trim().toLowerCase()}`).digest("hex");
3624
+ return {
3625
+ provider: SeoProviders.dataforseo,
3626
+ accountKey,
3627
+ capabilities: seoProfileInputSchema.shape.capabilities.element.options,
3628
+ estimate,
3629
+ async execute(request, options) {
3630
+ const payload = taskPayload(request);
3631
+ const results = emptySeoResults();
3632
+ if (options?.signal?.aborted) return { outcome: SeoAdapterOutcomes.failed, tasks: [{ remoteTaskId: null, statusCode: null, costMicros: 0 }], results, fetchedAt: (/* @__PURE__ */ new Date()).toISOString(), error: "SEO request was cancelled before submission." };
3633
+ try {
3634
+ const envelope = await dataForSeoFetch(auth, ENDPOINTS[request.capability], payload, options?.signal);
3635
+ const fetchedAt2 = (/* @__PURE__ */ new Date()).toISOString();
3636
+ const tasks = envelope.tasks ?? [];
3637
+ if (tasks.length === 0) {
3638
+ const refused = envelope.cost === 0 && REQUEST_REFUSALS.has(envelope.status_code);
3639
+ return {
3640
+ outcome: refused ? SeoAdapterOutcomes.failed : SeoAdapterOutcomes.unknown,
3641
+ results,
3642
+ fetchedAt: fetchedAt2,
3643
+ tasks: [{ remoteTaskId: null, statusCode: envelope.status_code, costMicros: refused ? 0 : null }],
3644
+ error: refused ? "SEO provider rejected the request." : "SEO provider returned no task receipt; reconciliation is required."
3645
+ };
3646
+ }
3647
+ const receipts = tasks.map((task) => ({
3648
+ remoteTaskId: task.id ?? null,
3649
+ statusCode: task.status_code,
3650
+ costMicros: task.cost == null ? null : dollarsToMicros(task.cost)
3651
+ }));
3652
+ let successes = 0;
3653
+ for (const task of tasks) {
3654
+ if (task.status_code !== 2e4) continue;
3655
+ try {
3656
+ appendResults(results, normalizeDataForSeoResults(task.result ?? [], request, fetchedAt2));
3657
+ successes++;
3658
+ } catch {
3659
+ }
3660
+ }
3661
+ const outcome = successes === tasks.length ? SeoAdapterOutcomes.completed : successes > 0 ? SeoAdapterOutcomes.partial : SeoAdapterOutcomes.failed;
3662
+ return {
3663
+ outcome,
3664
+ tasks: receipts,
3665
+ results,
3666
+ fetchedAt: fetchedAt2,
3667
+ error: outcome === SeoAdapterOutcomes.completed ? null : "Some SEO provider results could not be collected."
3668
+ };
3669
+ } catch (error) {
3670
+ const unaccepted = error instanceof DataForSeoTransportError && error.unaccepted;
3671
+ return {
3672
+ outcome: unaccepted ? SeoAdapterOutcomes.failed : SeoAdapterOutcomes.unknown,
3673
+ tasks: [{ remoteTaskId: null, statusCode: error instanceof DataForSeoTransportError ? error.status : null, costMicros: unaccepted ? 0 : null }],
3674
+ results,
3675
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
3676
+ error: unaccepted ? "SEO provider rejected the request." : "SEO provider acceptance is unknown; reconciliation is required."
3677
+ };
3678
+ }
3679
+ }
3680
+ };
3681
+ }
3682
+
3683
+ // src/seo-runtime.ts
3684
+ var SeoRuntime = class {
3685
+ constructor(db, config, fingerprint) {
3686
+ this.db = db;
3687
+ this.config = config;
3688
+ this.fingerprint = fingerprint;
3689
+ this.repository = new SeoRepository(db);
3690
+ }
3691
+ db;
3692
+ config;
3693
+ fingerprint;
3694
+ started = false;
3695
+ timer = null;
3696
+ running = null;
3697
+ activeRequest = null;
3698
+ pending = /* @__PURE__ */ new Map();
3699
+ cached = null;
3700
+ configUnavailable = false;
3701
+ repository;
3702
+ getRuntime = () => {
3703
+ try {
3704
+ const fingerprint = this.fingerprint?.();
3705
+ if (!this.configUnavailable && fingerprint !== void 0 && this.cached?.fingerprint === fingerprint) return this.cached.runtime;
3706
+ const config = this.config();
3707
+ if (fingerprint !== void 0 && this.fingerprint?.() !== fingerprint) throw new Error("SEO configuration changed during reload.");
3708
+ const runtime = config?.enabled ? {
3709
+ policy: config.policy,
3710
+ connections: Object.entries(config.connections).filter(([, value]) => value.enabled).map(([id, value]) => {
3711
+ switch (value.provider) {
3712
+ case SeoProviders.dataforseo:
3713
+ return { id, label: value.label, adapter: createDataForSeoAdapter(value) };
3714
+ }
3715
+ })
3716
+ } : null;
3717
+ this.configUnavailable = false;
3718
+ this.cached = fingerprint === void 0 ? null : { fingerprint, runtime };
3719
+ return runtime;
3720
+ } catch {
3721
+ this.configUnavailable = true;
3722
+ return null;
3723
+ }
3724
+ };
3725
+ start() {
3726
+ if (this.started) return;
3727
+ this.started = true;
3728
+ for (const [id, entry] of this.pending) {
3729
+ clearInterval(entry.heartbeat);
3730
+ entry.heartbeat = this.heartbeat(id, entry.owner);
3731
+ }
3732
+ this.timer = setInterval(() => this.wake(), 5e3);
3733
+ this.timer.unref();
3734
+ this.wake();
3735
+ }
3736
+ wake() {
3737
+ if (!this.started || this.running) return;
3738
+ this.running = Promise.resolve().then(async () => {
3739
+ if (!this.flushSettlements()) return;
3740
+ this.repository.recover();
3741
+ await this.drain();
3742
+ }).catch(() => {
3743
+ createLogger("SeoRuntime").error("seo.dispatch.failed", { message: "SEO dispatch paused; durable receipts remain available." });
3744
+ }).finally(() => {
3745
+ this.running = null;
3746
+ });
3747
+ }
3748
+ async stop() {
3749
+ this.started = false;
3750
+ if (this.timer) clearInterval(this.timer);
3751
+ this.activeRequest?.abort();
3752
+ await this.running;
3753
+ this.flushSettlements();
3754
+ for (const entry of this.pending.values()) clearInterval(entry.heartbeat);
3755
+ if (this.pending.size) createLogger("SeoRuntime").error("seo.shutdown.unpersisted", { message: "SEO provider receipts could not be saved before shutdown. Reservations remain held for operator reconciliation." });
3756
+ }
3757
+ heartbeat(taskId, owner) {
3758
+ const timer = setInterval(() => {
3759
+ try {
3760
+ this.repository.renew(taskId, owner);
3761
+ } catch {
3762
+ createLogger("SeoRuntime").error("seo.lease.failed", { message: "SEO task lease could not be renewed." });
3763
+ }
3764
+ }, 3e4);
3765
+ timer.unref();
3766
+ return timer;
3767
+ }
3768
+ flushSettlements() {
3769
+ for (const [id, entry] of this.pending) {
3770
+ try {
3771
+ if (!entry.settled) {
3772
+ if (!this.repository.settle(id, entry.result, entry.owner)) {
3773
+ createLogger("SeoRuntime").error("seo.receipt.superseded", { message: "SEO receipt could not replace an already reconciled or differently owned task." });
3774
+ clearInterval(entry.heartbeat);
3775
+ this.pending.delete(id);
3776
+ continue;
3777
+ }
3778
+ entry.settled = true;
3779
+ }
3780
+ if (entry.result.outcome === SeoAdapterOutcomes.unknown || entry.result.tasks.some((receipt) => receipt.costMicros === null) || this.db.select().from(seoTasks).where(eq(seoTasks.id, id)).get()?.status === SeoRunStatuses["reconciliation-required"]) this.repository.cancel(entry.jobId);
3781
+ clearInterval(entry.heartbeat);
3782
+ this.pending.delete(id);
3783
+ } catch {
3784
+ createLogger("SeoRuntime").error("seo.receipt.persistence-failed", { message: "SEO receipt persistence will be retried. Further dispatch is paused." });
3785
+ return false;
3786
+ }
3787
+ }
3788
+ return true;
3789
+ }
3790
+ async execute(adapter, request) {
3791
+ const controller = new AbortController();
3792
+ this.activeRequest = controller;
3793
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(9e4)]);
3794
+ const unknown = () => ({ outcome: SeoAdapterOutcomes.unknown, tasks: [], results: emptySeoResults(), error: null, fetchedAt: (/* @__PURE__ */ new Date()).toISOString() });
3795
+ let timeout;
3796
+ let onAbort = () => {
3797
+ };
3798
+ const aborted = new Promise((resolve) => {
3799
+ onAbort = () => {
3800
+ timeout = setTimeout(() => resolve(unknown()), 500);
3801
+ };
3802
+ signal.addEventListener("abort", onAbort, { once: true });
3803
+ });
3804
+ try {
3805
+ return await Promise.race([adapter.execute(request, { signal }), aborted]);
3806
+ } catch {
3807
+ return unknown();
3808
+ } finally {
3809
+ signal.removeEventListener("abort", onAbort);
3810
+ if (timeout) clearTimeout(timeout);
3811
+ this.activeRequest = null;
3812
+ }
3813
+ }
3814
+ async drain() {
3815
+ while (this.started) {
3816
+ const jobs = this.db.select().from(seoJobs).where(inArray(seoJobs.status, [SeoRunStatuses.queued, SeoRunStatuses.running])).all();
3817
+ let progressed = false;
3818
+ for (const job of jobs) {
3819
+ if (!this.started) return;
3820
+ const runtime = this.getRuntime();
3821
+ if (!runtime && this.configUnavailable) return;
3822
+ const connection = runtime?.connections.find((connection2) => connection2.id === job.connectionId && connection2.adapter.accountKey === job.accountKey);
3823
+ if (!runtime || !connection || !job.projectId || !job.runId || job.cancelRequested) {
3824
+ this.repository.cancel(job.id);
3825
+ continue;
3826
+ }
3827
+ const heldTasks = this.db.select().from(seoTasks).where(eq(seoTasks.jobId, job.id)).all();
3828
+ let pricesSafe = false;
3829
+ try {
3830
+ pricesSafe = heldTasks.filter((task2) => task2.status === SeoRunStatuses.queued).every((task2) => {
3831
+ const estimate2 = connection.adapter.estimate(task2.request);
3832
+ return estimate2.maxCostMicros <= task2.reservedMicros && estimate2.catalogRevision === task2.catalogRevision;
3833
+ });
3834
+ } catch {
3835
+ pricesSafe = false;
3836
+ }
3837
+ if (!pricesSafe) {
3838
+ this.repository.cancel(job.id);
3839
+ continue;
3840
+ }
3841
+ const task = this.repository.claim(job.id, { ...runtime.policy, accountKey: connection.adapter.accountKey });
3842
+ if (!task) continue;
3843
+ progressed = true;
3844
+ const owner = task.leaseOwner;
3845
+ const heartbeat = this.heartbeat(task.id, owner);
3846
+ const result = await this.execute(connection.adapter, task.request);
3847
+ this.pending.set(task.id, { jobId: job.id, owner, result, settled: false, heartbeat });
3848
+ if (!this.flushSettlements()) return;
3849
+ }
3850
+ if (!progressed) return;
3851
+ }
3852
+ }
3853
+ };
3854
+
3855
+ // ../integration-typesafe/src/classifier.ts
3856
+ import { createHash as createHash2 } from "crypto";
3857
+
3302
3858
  // ../integration-typesafe/src/client.ts
3303
3859
  var TYPESAFE_URL = "https://api.typesafe.ai/v1/systemone";
3304
3860
  var JEV_MODEL = SENTIMENT_MODEL;
@@ -3314,7 +3870,7 @@ function usageFrom(value) {
3314
3870
  function failure(code, message, retryable = false, retryAfterMs = null, usage = usageFrom(null), returnedModel = null) {
3315
3871
  return { ok: false, returnedModel, error: { code, message, retryable, retryAfterMs }, usage };
3316
3872
  }
3317
- async function fetchOnce2(request, options) {
3873
+ async function fetchOnce3(request, options) {
3318
3874
  if (options.signal?.aborted) return failure("canceled", "Classification was canceled before dispatch.");
3319
3875
  if (request.model !== JEV_MODEL) return failure("model-mismatch", "The direct TypeSafe evaluator requires its pinned model.");
3320
3876
  if (!options.apiKey.trim()) return failure("credential-missing", "TypeSafe credentials are unavailable.");
@@ -3372,7 +3928,7 @@ async function fetchOnce2(request, options) {
3372
3928
  }
3373
3929
  }
3374
3930
  function requestJev(request, options) {
3375
- return withRetry(() => fetchOnce2(request, options), {
3931
+ return withRetry(() => fetchOnce3(request, options), {
3376
3932
  maxRetries: 0,
3377
3933
  isRetryable: isRetryableHttpError,
3378
3934
  computeDelayMs: (_attempt, error, defaultMs) => retryAfterDelayMs(error) ?? defaultMs
@@ -3417,7 +3973,7 @@ function buildJevSentimentRequest(input) {
3417
3973
  if (input.subject.mentionNotApplicable || !identityMatcher.keys.size) return reject(SentimentOutcomes["subject-not-applicable"], "The subject has no usable frozen identity.");
3418
3974
  if (!/^en(?:[-_][a-z0-9]+)*$/i.test(input.language)) return reject(SentimentOutcomes["unsupported-language"], "Only English answers are supported by this evaluator.");
3419
3975
  if (tokenBound(Buffer.byteLength(input.sourceText, "utf8")) > STATE_AND_QUESTION_TOKEN_LIMIT || input.sentences.length > EVIDENCE_SENTENCE_LIMIT) return reject(SentimentOutcomes["input-too-large"], "The full answer exceeds the calibrated input bound or 254-sentence evidence limit; it was not truncated.");
3420
- if (createHash("sha256").update(input.sourceText).digest("hex") !== input.sourceTextHash) return reject(SentimentOutcomes["invalid-conclusion-evidence"], "The frozen source text hash does not match the answer.");
3976
+ if (createHash2("sha256").update(input.sourceText).digest("hex") !== input.sourceTextHash) return reject(SentimentOutcomes["invalid-conclusion-evidence"], "The frozen source text hash does not match the answer.");
3421
3977
  const ids = /* @__PURE__ */ new Set();
3422
3978
  let previousEnd = 0;
3423
3979
  for (const span of input.sentences) {
@@ -3447,9 +4003,9 @@ function buildJevSentimentRequest(input) {
3447
4003
  complaint: choice(wording.complaint, evidence)
3448
4004
  };
3449
4005
  const request = { model: input.definition.requestedModel, state: { rules: SOURCE_RULE, subject: input.subject, execution: input.context, language: input.language, answerSentences: sentences }, questions };
3450
- const estimate = estimateJevRequest(request);
3451
- if (estimate.inputTokens > REQUEST_TOKEN_LIMIT || estimate.stateAndLongestQuestionTokens > STATE_AND_QUESTION_TOKEN_LIMIT) return { ok: false, outcome: SentimentOutcomes["input-too-large"], reason: "The full request exceeds the calibrated TypeSafe context bound; it was not truncated.", estimate };
3452
- return { ok: true, request, estimate };
4006
+ const estimate2 = estimateJevRequest(request);
4007
+ if (estimate2.inputTokens > REQUEST_TOKEN_LIMIT || estimate2.stateAndLongestQuestionTokens > STATE_AND_QUESTION_TOKEN_LIMIT) return { ok: false, outcome: SentimentOutcomes["input-too-large"], reason: "The full request exceeds the calibrated TypeSafe context bound; it was not truncated.", estimate: estimate2 };
4008
+ return { ok: true, request, estimate: estimate2 };
3453
4009
  }
3454
4010
  function parseChoice(value, question) {
3455
4011
  const answer = asRecord(value);
@@ -3499,7 +4055,7 @@ function createJevSentimentClassifier(dispatch) {
3499
4055
  }
3500
4056
 
3501
4057
  // ../integration-typesafe/src/evaluation.ts
3502
- import { createHash as createHash2 } from "crypto";
4058
+ import { createHash as createHash3 } from "crypto";
3503
4059
  var STANCES = [SentimentOutcomes.favorable, SentimentOutcomes.mixed, SentimentOutcomes.unfavorable];
3504
4060
  var SENTIMENT_CHALLENGE_GATES = {
3505
4061
  "same-name": { outcome: SentimentOutcomes["wrong-subject"], target: 0.9 },
@@ -3571,8 +4127,8 @@ function createConfiguredSentimentClassifier(configuration, registry, reload) {
3571
4127
  }
3572
4128
 
3573
4129
  // src/sentiment-worker.ts
3574
- import { createHash as createHash3, randomUUID } from "crypto";
3575
- import { and, asc, eq, gt } from "drizzle-orm";
4130
+ import { createHash as createHash4, randomUUID } from "crypto";
4131
+ import { and, asc, eq as eq2, gt } from "drizzle-orm";
3576
4132
  var RATE_LIMIT_FLOOR_MS = 3e4;
3577
4133
  var RATE_LIMIT_CEILING_MS = 15 * 6e4;
3578
4134
  var AUTHORIZATION_PROBE_INTERVAL_MS = 60 * 6e4;
@@ -3607,7 +4163,7 @@ var applyMentionIdentity = (tx, work) => {
3607
4163
  refreshSnapshotMentionIdentity(tx, [work.snapshotId]);
3608
4164
  };
3609
4165
  function credentialFingerprint(apiKey) {
3610
- return createHash3("sha256").update("canonry-sentiment-credential\0").update(apiKey ?? "").digest("hex");
4166
+ return createHash4("sha256").update("canonry-sentiment-credential\0").update(apiKey ?? "").digest("hex");
3611
4167
  }
3612
4168
  var SentimentWorker = class {
3613
4169
  constructor(db, options) {
@@ -3637,9 +4193,9 @@ var SentimentWorker = class {
3637
4193
  this.repository.resumeInstall(this.now());
3638
4194
  let admitted = 0;
3639
4195
  const service = this.service();
3640
- for (const settings of this.db.select().from(sentimentSettings).where(eq(sentimentSettings.enabled, true)).all()) {
4196
+ for (const settings of this.db.select().from(sentimentSettings).where(eq2(sentimentSettings.enabled, true)).all()) {
3641
4197
  const start = Math.max(settings.completionBoundary, settings.reconciledSequence);
3642
- const receipts = this.db.select().from(sentimentCompletionReceipts).where(and(eq(sentimentCompletionReceipts.projectId, settings.projectId), gt(sentimentCompletionReceipts.sequence, start))).orderBy(asc(sentimentCompletionReceipts.sequence)).all();
4198
+ const receipts = this.db.select().from(sentimentCompletionReceipts).where(and(eq2(sentimentCompletionReceipts.projectId, settings.projectId), gt(sentimentCompletionReceipts.sequence, start))).orderBy(asc(sentimentCompletionReceipts.sequence)).all();
3643
4199
  if (!receipts.length) continue;
3644
4200
  const definition = service.definition(settings.evaluationDefinitionId);
3645
4201
  if (!hasCurrentSentimentTemplate(definition) || sentimentEvaluatorProvider(definition) !== configuration.provider || definition.requestedModel !== configuration.model) continue;
@@ -3755,8 +4311,8 @@ var SentimentWorker = class {
3755
4311
  report({ status: OutcomeStatuses.cancelled, reasonCode: OutcomeReasonCodes.CANCELLED_BY_USER });
3756
4312
  return;
3757
4313
  }
3758
- const estimate = prepared?.ok ? prepared.estimatedInputTokens : Math.ceil(canonicalSentimentJson(input).length / 3);
3759
- if (estimate > config.maxInputTokensPerMinute) {
4314
+ const estimate2 = prepared?.ok ? prepared.estimatedInputTokens : Math.ceil(canonicalSentimentJson(input).length / 3);
4315
+ if (estimate2 > config.maxInputTokensPerMinute) {
3760
4316
  this.repository.failWork({ workItemId: work.id, owner, now: this.now(), errorCode: "INPUT_EXCEEDS_INSTALL_TOKEN_BUDGET" });
3761
4317
  report({ status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.QUOTA_EXCEEDED });
3762
4318
  return;
@@ -3766,10 +4322,10 @@ var SentimentWorker = class {
3766
4322
  report({ status: OutcomeStatuses.failed, reasonCode: CLASSIFIER_FAILURE_REASONS[work.errorCode ?? ""] ?? OutcomeReasonCodes.UNKNOWN });
3767
4323
  return;
3768
4324
  }
3769
- const attempt = this.repository.startAttempt({ workItemId: work.id, owner, requestedModel: input.definition.requestedModel, now: this.now(), estimatedInputTokens: estimate, maxRequestsPerMinute: config.maxRequestsPerMinute, maxAttempts: config.maxAttempts, maxInputTokensPerMinute: config.maxInputTokensPerMinute });
4325
+ const attempt = this.repository.startAttempt({ workItemId: work.id, owner, requestedModel: input.definition.requestedModel, now: this.now(), estimatedInputTokens: estimate2, maxRequestsPerMinute: config.maxRequestsPerMinute, maxAttempts: config.maxAttempts, maxInputTokensPerMinute: config.maxInputTokensPerMinute });
3770
4326
  if (!attempt) {
3771
4327
  const used = this.repository.recentDispatch(this.now());
3772
- if (used.requests >= config.maxRequestsPerMinute || used.tokens + estimate > config.maxInputTokensPerMinute) {
4328
+ if (used.requests >= config.maxRequestsPerMinute || used.tokens + estimate2 > config.maxInputTokensPerMinute) {
3773
4329
  this.repository.releaseWork({ workItemId: work.id, owner, now: this.now() });
3774
4330
  return "released";
3775
4331
  }
@@ -5100,7 +5656,7 @@ function nonBlank(value) {
5100
5656
  return trimmed ? trimmed : void 0;
5101
5657
  }
5102
5658
  function resolveBuildCommit(env = process.env) {
5103
- const embedded = true ? "13194e0e9f292077ded0501f56c5a8c1d0b34977" : void 0;
5659
+ const embedded = true ? "d05c2c6d41782d560e716d3db55e1bfd8233de82" : void 0;
5104
5660
  return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
5105
5661
  }
5106
5662
  function resolveInstanceIdentity(env = process.env) {
@@ -5116,7 +5672,7 @@ import fs3 from "fs";
5116
5672
  import path3 from "path";
5117
5673
  import os2 from "os";
5118
5674
  import { setImmediate as yieldToEventLoop } from "timers/promises";
5119
- import { and as and3, asc as asc2, count, desc, eq as eq3, inArray, isNotNull, isNull, lt, ne, sql as sql2 } from "drizzle-orm";
5675
+ import { and as and3, asc as asc2, count as count2, desc, eq as eq4, inArray as inArray2, isNotNull, isNull, lt, ne, sql as sql2 } from "drizzle-orm";
5120
5676
 
5121
5677
  // src/run-telemetry.ts
5122
5678
  import crypto4 from "crypto";
@@ -5302,7 +5858,7 @@ function failureStreakSampling(status, priorStreak, runId) {
5302
5858
 
5303
5859
  // src/usage-quota.ts
5304
5860
  import crypto5 from "crypto";
5305
- import { and as and2, eq as eq2, lte, sql } from "drizzle-orm";
5861
+ import { and as and2, eq as eq3, lte, sql } from "drizzle-orm";
5306
5862
  function getCurrentUsageDay() {
5307
5863
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
5308
5864
  }
@@ -5311,9 +5867,9 @@ function reserveDailyQueryQuota(db, input) {
5311
5867
  if (input.count > input.limit) return { reserved: false, used: 0 };
5312
5868
  return db.transaction((tx) => {
5313
5869
  const reserveExisting = () => tx.update(usageCounters).set({ count: sql`${usageCounters.count} + ${input.count}`, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and2(
5314
- eq2(usageCounters.scope, input.scope),
5315
- eq2(usageCounters.period, input.period),
5316
- eq2(usageCounters.metric, "queries"),
5870
+ eq3(usageCounters.scope, input.scope),
5871
+ eq3(usageCounters.period, input.period),
5872
+ eq3(usageCounters.metric, "queries"),
5317
5873
  lte(usageCounters.count, input.limit - input.count)
5318
5874
  )).run();
5319
5875
  if (reserveExisting().changes === 1) return { reserved: true, used: 0 };
@@ -5327,13 +5883,13 @@ function reserveDailyQueryQuota(db, input) {
5327
5883
  }).onConflictDoNothing().run();
5328
5884
  if (inserted.changes === 1) return { reserved: true, used: 0 };
5329
5885
  if (reserveExisting().changes === 1) return { reserved: true, used: 0 };
5330
- const row = tx.select({ count: usageCounters.count }).from(usageCounters).where(and2(eq2(usageCounters.scope, input.scope), eq2(usageCounters.period, input.period), eq2(usageCounters.metric, "queries"))).get();
5886
+ const row = tx.select({ count: usageCounters.count }).from(usageCounters).where(and2(eq3(usageCounters.scope, input.scope), eq3(usageCounters.period, input.period), eq3(usageCounters.metric, "queries"))).get();
5331
5887
  return { reserved: false, used: row?.count ?? 0 };
5332
5888
  });
5333
5889
  }
5334
5890
  function releaseDailyQueryQuota(db, input) {
5335
5891
  if (input.count <= 0) return;
5336
- db.update(usageCounters).set({ count: sql`MAX(0, ${usageCounters.count} - ${input.count})`, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and2(eq2(usageCounters.scope, input.scope), eq2(usageCounters.period, input.period), eq2(usageCounters.metric, "queries"))).run();
5892
+ db.update(usageCounters).set({ count: sql`MAX(0, ${usageCounters.count} - ${input.count})`, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and2(eq3(usageCounters.scope, input.scope), eq3(usageCounters.period, input.period), eq3(usageCounters.metric, "queries"))).run();
5337
5893
  }
5338
5894
 
5339
5895
  // src/cited-url-capture.ts
@@ -5489,7 +6045,7 @@ function unansweredOutcome(type) {
5489
6045
  }
5490
6046
  }
5491
6047
  function tallyBatchLedger(db, batchId) {
5492
- const handled = db.select({ outcome: providerBatchRequests.outcome }).from(providerBatchRequests).where(eq3(providerBatchRequests.batchId, batchId)).all().flatMap((row) => row.outcome === null ? [] : [row.outcome]);
6048
+ const handled = db.select({ outcome: providerBatchRequests.outcome }).from(providerBatchRequests).where(eq4(providerBatchRequests.batchId, batchId)).all().flatMap((row) => row.outcome === null ? [] : [row.outcome]);
5493
6049
  return {
5494
6050
  ingestedCount: handled.length,
5495
6051
  recordedCount: handled.filter((outcome) => outcome === ProviderBatchRequestOutcomes.recorded).length,
@@ -5655,16 +6211,16 @@ var JobRunner = class {
5655
6211
  );
5656
6212
  }
5657
6213
  hasProviderBatches(runId) {
5658
- return this.db.select({ id: providerBatches.id }).from(providerBatches).where(eq3(providerBatches.runId, runId)).limit(1).get() !== void 0;
6214
+ return this.db.select({ id: providerBatches.id }).from(providerBatches).where(eq4(providerBatches.runId, runId)).limit(1).get() !== void 0;
5659
6215
  }
5660
6216
  recoverStaleRuns() {
5661
- const staleFills = this.db.update(runFills).set({ status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: "Server restarted while the fill was in progress" }).where(inArray(runFills.status, ["queued", "running"])).run();
6217
+ const staleFills = this.db.update(runFills).set({ status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: "Server restarted while the fill was in progress" }).where(inArray2(runFills.status, ["queued", "running"])).run();
5662
6218
  if (staleFills.changes > 0) log2.warn("fill.recovered-stale", { count: staleFills.changes });
5663
6219
  const unknownBatches = this.db.update(providerBatches).set({
5664
6220
  status: ProviderBatchStatuses.unknown,
5665
6221
  error: "Server restarted while the batch was being submitted; it may or may not exist at the provider, so it was not resubmitted.",
5666
6222
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5667
- }).where(eq3(providerBatches.status, ProviderBatchStatuses.submitting)).run();
6223
+ }).where(eq4(providerBatches.status, ProviderBatchStatuses.submitting)).run();
5668
6224
  if (unknownBatches.changes > 0) log2.warn("batch.recovered-submitting", { count: unknownBatches.changes });
5669
6225
  const stale = this.db.select({
5670
6226
  id: runs.id,
@@ -5673,19 +6229,20 @@ var JobRunner = class {
5673
6229
  status: runs.status,
5674
6230
  trigger: runs.trigger,
5675
6231
  startedAt: runs.startedAt
5676
- }).from(runs).where(inArray(runs.status, ["running", "queued"])).all();
6232
+ }).from(runs).where(inArray2(runs.status, ["running", "queued"])).all();
5677
6233
  if (stale.length === 0) return;
5678
6234
  const now = (/* @__PURE__ */ new Date()).toISOString();
5679
6235
  for (const run of stale) {
6236
+ if (run.kind === RunKinds["seo-sync"]) continue;
5680
6237
  if (run.status === RunStatuses.running && this.recoverBatchRun(run.id)) continue;
5681
6238
  const recovered = this.db.transaction((tx) => {
5682
- const claim = tx.update(runs).set({ status: "failed", finishedAt: now, error: "Server restarted while run was in progress" }).where(and3(eq3(runs.id, run.id), eq3(runs.status, run.status))).run();
6239
+ const claim = tx.update(runs).set({ status: "failed", finishedAt: now, error: "Server restarted while run was in progress" }).where(and3(eq4(runs.id, run.id), eq4(runs.status, run.status))).run();
5683
6240
  if (claim.changes === 0) return false;
5684
6241
  if (run.kind === RunKinds["site-audit"]) {
5685
6242
  tx.update(siteCrawlAttempts).set({ state: "failed", finishedAt: now, updatedAt: now, error: "Server restarted while run was in progress" }).where(and3(
5686
- eq3(siteCrawlAttempts.projectId, run.projectId),
5687
- eq3(siteCrawlAttempts.runId, run.id),
5688
- inArray(siteCrawlAttempts.state, ["queued", "running"])
6243
+ eq4(siteCrawlAttempts.projectId, run.projectId),
6244
+ eq4(siteCrawlAttempts.runId, run.id),
6245
+ inArray2(siteCrawlAttempts.state, ["queued", "running"])
5689
6246
  )).run();
5690
6247
  }
5691
6248
  return true;
@@ -5707,17 +6264,17 @@ var JobRunner = class {
5707
6264
  * (it is not yet, this early in boot).
5708
6265
  */
5709
6266
  recoverBatchRun(runId) {
5710
- const batches = this.db.select({ id: providerBatches.id, status: providerBatches.status }).from(providerBatches).where(eq3(providerBatches.runId, runId)).all();
6267
+ const batches = this.db.select({ id: providerBatches.id, status: providerBatches.status }).from(providerBatches).where(eq4(providerBatches.runId, runId)).all();
5711
6268
  if (batches.length === 0) return false;
5712
6269
  const owning = batches.filter((batch) => batch.status !== ProviderBatchStatuses.failed).map((batch) => batch.id);
5713
- const owned = new Set(owning.length === 0 ? [] : this.db.select({ executionId: providerBatchRequests.executionId, provider: providerBatches.provider }).from(providerBatchRequests).innerJoin(providerBatches, eq3(providerBatchRequests.batchId, providerBatches.id)).where(inArray(providerBatchRequests.batchId, owning)).all().map((row) => measurementSlotKey(row.executionId, row.provider)));
5714
- const run = this.db.select({ pendingProviderErrors: runs.pendingProviderErrors }).from(runs).where(eq3(runs.id, runId)).get();
6270
+ const owned = new Set(owning.length === 0 ? [] : this.db.select({ executionId: providerBatchRequests.executionId, provider: providerBatches.provider }).from(providerBatchRequests).innerJoin(providerBatches, eq4(providerBatchRequests.batchId, providerBatches.id)).where(inArray2(providerBatchRequests.batchId, owning)).all().map((row) => measurementSlotKey(row.executionId, row.provider)));
6271
+ const run = this.db.select({ pendingProviderErrors: runs.pendingProviderErrors }).from(runs).where(eq4(runs.id, runId)).get();
5715
6272
  const pending = { ...run?.pendingProviderErrors ?? {} };
5716
6273
  for (const slot of measurementRunSlotState(this.db, runId).missing) {
5717
6274
  if (owned.has(measurementSlotKey(slot.executionId, slot.provider))) continue;
5718
6275
  pending[slot.provider] ??= "Server restarted while run was in progress";
5719
6276
  }
5720
- this.db.update(runs).set({ pendingProviderErrors: pending }).where(and3(eq3(runs.id, runId), eq3(runs.status, RunStatuses.running))).run();
6277
+ this.db.update(runs).set({ pendingProviderErrors: pending }).where(and3(eq4(runs.id, runId), eq4(runs.status, RunStatuses.running))).run();
5721
6278
  log2.warn("run.recovered-batch-pending", {
5722
6279
  runId,
5723
6280
  outstanding: batches.filter((batch) => RUN_HOLDING_BATCH_STATUSES.includes(batch.status)).length,
@@ -5738,7 +6295,7 @@ var JobRunner = class {
5738
6295
  trackRecoveredSiteAudit(run) {
5739
6296
  try {
5740
6297
  const startedAt = run.startedAt ? Date.parse(run.startedAt) : Number.NaN;
5741
- const project = this.db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq3(projects.id, run.projectId)).get();
6298
+ const project = this.db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq4(projects.id, run.projectId)).get();
5742
6299
  trackEvent(
5743
6300
  "site_audit.completed",
5744
6301
  buildSiteAuditCompletedProps({
@@ -5795,17 +6352,17 @@ var JobRunner = class {
5795
6352
  throw new Error(`Run ${runId} is not executable from status '${existingRun.status}'`);
5796
6353
  }
5797
6354
  if (existingRun.status === "queued") {
5798
- this.db.update(runs).set({ status: "running", startedAt: now }).where(and3(eq3(runs.id, runId), eq3(runs.status, "queued"))).run();
6355
+ this.db.update(runs).set({ status: "running", startedAt: now }).where(and3(eq4(runs.id, runId), eq4(runs.status, "queued"))).run();
5799
6356
  }
5800
6357
  this.throwIfRunCancelled(runId);
5801
- const project = this.db.select().from(projects).where(eq3(projects.id, projectId)).get();
6358
+ const project = this.db.select().from(projects).where(eq4(projects.id, projectId)).get();
5802
6359
  if (!project) {
5803
6360
  throw new Error(`Project ${projectId} not found`);
5804
6361
  }
5805
6362
  canonicalDomain = project.canonicalDomain;
5806
- const sourceIdentity = this.db.select({ identity: runs.measurementExecutionIdentity }).from(runs).where(eq3(runs.id, runId)).get()?.identity;
6363
+ const sourceIdentity = this.db.select({ identity: runs.measurementExecutionIdentity }).from(runs).where(eq4(runs.id, runId)).get()?.identity;
5807
6364
  if (sourceIdentity && !sourceIdentity.language) {
5808
- this.db.update(runs).set({ measurementExecutionIdentity: { ...sourceIdentity, language: project.language } }).where(eq3(runs.id, runId)).run();
6365
+ this.db.update(runs).set({ measurementExecutionIdentity: { ...sourceIdentity, language: project.language } }).where(eq4(runs.id, runId)).run();
5809
6366
  }
5810
6367
  if (locationOverride === null) {
5811
6368
  runLocation = void 0;
@@ -5818,7 +6375,7 @@ var JobRunner = class {
5818
6375
  }
5819
6376
  }
5820
6377
  const scopedQueryNames = existingRun.queries;
5821
- projectQueries = scopedQueryNames ? this.db.select().from(queries).where(and3(eq3(queries.projectId, projectId), inArray(queries.query, scopedQueryNames))).all() : this.db.select().from(queries).where(eq3(queries.projectId, projectId)).all();
6378
+ projectQueries = scopedQueryNames ? this.db.select().from(queries).where(and3(eq4(queries.projectId, projectId), inArray2(queries.query, scopedQueryNames))).all() : this.db.select().from(queries).where(eq4(queries.projectId, projectId)).all();
5822
6379
  planExecution = resolvePlanExecution(existingRun, projectQueries);
5823
6380
  if (planExecution) {
5824
6381
  const plan = planExecution;
@@ -5847,7 +6404,7 @@ var JobRunner = class {
5847
6404
  providers: calledProviders.map((p) => p.adapter.name),
5848
6405
  ...Object.keys(skipped).length > 0 ? { skippedProviders: Object.keys(skipped) } : {}
5849
6406
  });
5850
- const projectCompetitors = this.db.select().from(competitors).where(eq3(competitors.projectId, projectId)).orderBy(competitors.domain).all();
6407
+ const projectCompetitors = this.db.select().from(competitors).where(eq4(competitors.projectId, projectId)).orderBy(competitors.domain).all();
5851
6408
  const competitorDomains = projectCompetitors.map((c) => c.domain);
5852
6409
  recording = runRecordingContext(this.db, {
5853
6410
  runId,
@@ -6235,7 +6792,7 @@ var JobRunner = class {
6235
6792
  status: "failed",
6236
6793
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
6237
6794
  error: errorMessage
6238
- }).where(and3(eq3(runs.id, runId), inArray(runs.status, ["queued", "running"]))).run();
6795
+ }).where(and3(eq4(runs.id, runId), inArray2(runs.status, ["queued", "running"]))).run();
6239
6796
  this.flushProviderUsage(providerDispatchCounts, providerReservations);
6240
6797
  const abandoned = this.markBatchesCancelled(batchRowIds, `Cancelled because the run failed: ${errorMessage}`);
6241
6798
  const abortReason2 = classifyRunAbortReason(errorMessage);
@@ -6321,13 +6878,13 @@ var JobRunner = class {
6321
6878
  status: outcome.status,
6322
6879
  finishedAt,
6323
6880
  ...outcome.error !== null ? { error: outcome.error } : {}
6324
- }).where(and3(eq3(runs.id, runId), eq3(runs.status, RunStatuses.running))).run().changes === 1;
6881
+ }).where(and3(eq4(runs.id, runId), eq4(runs.status, RunStatuses.running))).run().changes === 1;
6325
6882
  if (changed) recordSentimentCompletion(tx, { projectId: input.projectId, runId, completionKey: "initial", completedAt: finishedAt });
6326
6883
  return changed;
6327
6884
  });
6328
6885
  if (input.quota) this.flushProviderUsage(input.quota.dispatched, input.quota.reservations);
6329
6886
  if (!won) {
6330
- const current = this.db.select({ status: runs.status }).from(runs).where(eq3(runs.id, runId)).get();
6887
+ const current = this.db.select({ status: runs.status }).from(runs).where(eq4(runs.id, runId)).get();
6331
6888
  log2.info("run.finalize-skipped", { runId, status: current?.status ?? null });
6332
6889
  return false;
6333
6890
  }
@@ -6404,7 +6961,7 @@ var JobRunner = class {
6404
6961
  */
6405
6962
  handOffBatchRun(input) {
6406
6963
  const { runId, projectId } = input;
6407
- const handedOff = this.db.update(runs).set({ pendingProviderErrors: Object.fromEntries(input.providerErrors) }).where(and3(eq3(runs.id, runId), eq3(runs.status, RunStatuses.running))).run().changes === 1;
6964
+ const handedOff = this.db.update(runs).set({ pendingProviderErrors: Object.fromEntries(input.providerErrors) }).where(and3(eq4(runs.id, runId), eq4(runs.status, RunStatuses.running))).run().changes === 1;
6408
6965
  this.flushProviderUsage(input.quota.dispatched, input.quota.reservations);
6409
6966
  if (!handedOff) {
6410
6967
  if (this.isRunCancelled(runId)) throw new RunCancelledError(runId);
@@ -6438,12 +6995,12 @@ var JobRunner = class {
6438
6995
  status: runs.status,
6439
6996
  pendingProviderErrors: runs.pendingProviderErrors,
6440
6997
  skippedProviders: runs.skippedProviders
6441
- }).from(runs).where(and3(eq3(runs.id, runId), eq3(runs.projectId, projectId))).get();
6998
+ }).from(runs).where(and3(eq4(runs.id, runId), eq4(runs.projectId, projectId))).get();
6442
6999
  if (!run || run.status !== RunStatuses.running || run.pendingProviderErrors === null) return null;
6443
- const holding = txDb.select({ id: providerBatches.id }).from(providerBatches).where(and3(eq3(providerBatches.runId, runId), inArray(providerBatches.status, RUN_HOLDING_BATCH_STATUSES))).limit(1).get();
7000
+ const holding = txDb.select({ id: providerBatches.id }).from(providerBatches).where(and3(eq4(providerBatches.runId, runId), inArray2(providerBatches.status, RUN_HOLDING_BATCH_STATUSES))).limit(1).get();
6444
7001
  if (holding) return null;
6445
7002
  const state = measurementRunSlotState(txDb, runId);
6446
- const inserted = txDb.select({ value: count() }).from(querySnapshots).where(eq3(querySnapshots.runId, runId)).get()?.value ?? 0;
7003
+ const inserted = txDb.select({ value: count2() }).from(querySnapshots).where(eq4(querySnapshots.runId, runId)).get()?.value ?? 0;
6447
7004
  const providerErrors = this.batchRunProviderErrors(txDb, runId, run.pendingProviderErrors, state.missing);
6448
7005
  const skippedProviders = run.skippedProviders ?? {};
6449
7006
  const shortfall = state.missing.length + (state.readable ? 0 : 1);
@@ -6453,7 +7010,7 @@ var JobRunner = class {
6453
7010
  finishedAt,
6454
7011
  pendingProviderErrors: null,
6455
7012
  ...outcome.error !== null ? { error: outcome.error } : {}
6456
- }).where(and3(eq3(runs.id, runId), eq3(runs.status, RunStatuses.running), isNotNull(runs.pendingProviderErrors))).run().changes === 1;
7013
+ }).where(and3(eq4(runs.id, runId), eq4(runs.status, RunStatuses.running), isNotNull(runs.pendingProviderErrors))).run().changes === 1;
6457
7014
  if (!won) return null;
6458
7015
  recordSentimentCompletion(tx, { projectId, runId, completionKey: "initial", completedAt: finishedAt });
6459
7016
  return { kind: run.kind, inserted, providerErrors, skippedProviders, status: outcome.status };
@@ -6489,7 +7046,7 @@ var JobRunner = class {
6489
7046
  const add = (provider, message) => {
6490
7047
  if (!errors.has(provider)) errors.set(provider, message);
6491
7048
  };
6492
- const batches = db.select().from(providerBatches).where(eq3(providerBatches.runId, runId)).orderBy(asc2(providerBatches.createdAt), asc2(providerBatches.id)).all();
7049
+ const batches = db.select().from(providerBatches).where(eq4(providerBatches.runId, runId)).orderBy(asc2(providerBatches.createdAt), asc2(providerBatches.id)).all();
6493
7050
  for (const batch of batches) {
6494
7051
  switch (batch.status) {
6495
7052
  case ProviderBatchStatuses.unknown:
@@ -6497,7 +7054,7 @@ var JobRunner = class {
6497
7054
  if (batch.error) add(batch.provider, batch.error);
6498
7055
  break;
6499
7056
  case ProviderBatchStatuses.ingested: {
6500
- const unrecorded = db.select({ outcome: providerBatchRequests.outcome, error: providerBatchRequests.error }).from(providerBatchRequests).where(and3(eq3(providerBatchRequests.batchId, batch.id), inArray(providerBatchRequests.outcome, [...UNRECORDED_OUTCOMES]))).orderBy(asc2(providerBatchRequests.executionId)).all();
7057
+ const unrecorded = db.select({ outcome: providerBatchRequests.outcome, error: providerBatchRequests.error }).from(providerBatchRequests).where(and3(eq4(providerBatchRequests.batchId, batch.id), inArray2(providerBatchRequests.outcome, [...UNRECORDED_OUTCOMES]))).orderBy(asc2(providerBatchRequests.executionId)).all();
6501
7058
  const first = unrecorded[0];
6502
7059
  if (first) {
6503
7060
  add(batch.provider, `Batch answers not recorded: ${unrecorded.length} of ${batch.requestCount}. First: ${first.error ?? first.outcome}`);
@@ -6530,8 +7087,8 @@ var JobRunner = class {
6530
7087
  startedAt: runs.startedAt,
6531
7088
  createdAt: runs.createdAt,
6532
7089
  manifest: runs.measurementManifest
6533
- }).from(runs).where(eq3(runs.id, runId)).get();
6534
- const project = this.db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq3(projects.id, projectId)).get();
7090
+ }).from(runs).where(eq4(runs.id, runId)).get();
7091
+ const project = this.db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq4(projects.id, projectId)).get();
6535
7092
  const providers = /* @__PURE__ */ new Set();
6536
7093
  const nodes = /* @__PURE__ */ new Set();
6537
7094
  try {
@@ -6675,8 +7232,8 @@ var JobRunner = class {
6675
7232
  const sweepLive = ctx.reservations.has(providerName);
6676
7233
  this.db.transaction((tx) => {
6677
7234
  const txDb = tx;
6678
- txDb.update(providerBatches).set({ status: ProviderBatchStatuses.failed, error: message, updatedAt: at }).where(and3(eq3(providerBatches.id, rowId), eq3(providerBatches.status, ProviderBatchStatuses.submitting))).run();
6679
- txDb.update(providerBatches).set({ quotaReleased: lines.length, updatedAt: at }).where(eq3(providerBatches.id, rowId)).run();
7235
+ txDb.update(providerBatches).set({ status: ProviderBatchStatuses.failed, error: message, updatedAt: at }).where(and3(eq4(providerBatches.id, rowId), eq4(providerBatches.status, ProviderBatchStatuses.submitting))).run();
7236
+ txDb.update(providerBatches).set({ quotaReleased: lines.length, updatedAt: at }).where(eq4(providerBatches.id, rowId)).run();
6680
7237
  if (!sweepLive) releaseDailyQueryQuota(txDb, { scope: reservation.scope, period: reservation.period, count: lines.length });
6681
7238
  });
6682
7239
  log2.warn("batch.submit-refused", { runId: ctx.runId, provider: providerName, batchId: rowId, requests: lines.length, error: message });
@@ -6688,7 +7245,7 @@ var JobRunner = class {
6688
7245
  status: ProviderBatchStatuses.unknown,
6689
7246
  error: `The provider batch of ${lines.length} answer(s) may or may not have been created, so it was not resubmitted and its answers were not recorded: ${message}`,
6690
7247
  updatedAt: at
6691
- }).where(and3(eq3(providerBatches.id, rowId), eq3(providerBatches.status, ProviderBatchStatuses.submitting))).run();
7248
+ }).where(and3(eq4(providerBatches.id, rowId), eq4(providerBatches.status, ProviderBatchStatuses.submitting))).run();
6692
7249
  log2.error("batch.submit-unknown", { runId: ctx.runId, provider: providerName, batchId: rowId, requests: lines.length, error: message });
6693
7250
  return [];
6694
7251
  }
@@ -6699,9 +7256,9 @@ var JobRunner = class {
6699
7256
  submittedAt: submitted.toISOString(),
6700
7257
  deadlineAt: new Date(submitted.getTime() + deadlineMs).toISOString(),
6701
7258
  updatedAt: submitted.toISOString()
6702
- }).where(and3(eq3(providerBatches.id, rowId), eq3(providerBatches.status, ProviderBatchStatuses.submitting))).run().changes === 1;
7259
+ }).where(and3(eq4(providerBatches.id, rowId), eq4(providerBatches.status, ProviderBatchStatuses.submitting))).run().changes === 1;
6703
7260
  if (!accepted) {
6704
- this.db.update(providerBatches).set({ providerBatchId: result.providerBatchId, updatedAt: submitted.toISOString() }).where(eq3(providerBatches.id, rowId)).run();
7261
+ this.db.update(providerBatches).set({ providerBatchId: result.providerBatchId, updatedAt: submitted.toISOString() }).where(eq4(providerBatches.id, rowId)).run();
6705
7262
  await this.cancelAtProvider([{ id: rowId, provider: providerName, providerBatchId: result.providerBatchId }]);
6706
7263
  return [];
6707
7264
  }
@@ -6725,15 +7282,15 @@ var JobRunner = class {
6725
7282
  markBatchesCancelled(batchIds, reason) {
6726
7283
  if (batchIds.length === 0) return [];
6727
7284
  const now = (/* @__PURE__ */ new Date()).toISOString();
6728
- const rows = this.db.select().from(providerBatches).where(and3(inArray(providerBatches.id, [...batchIds]), inArray(providerBatches.status, RUN_HOLDING_BATCH_STATUSES))).all();
7285
+ const rows = this.db.select().from(providerBatches).where(and3(inArray2(providerBatches.id, [...batchIds]), inArray2(providerBatches.status, RUN_HOLDING_BATCH_STATUSES))).all();
6729
7286
  const marked = [];
6730
7287
  for (const row of rows) {
6731
7288
  const changed = this.db.transaction((tx) => {
6732
7289
  const txDb = tx;
6733
- const moved = txDb.update(providerBatches).set({ status: ProviderBatchStatuses.cancelled, error: reason, cancelRequestedAt: row.cancelRequestedAt ?? now, updatedAt: now }).where(and3(eq3(providerBatches.id, row.id), eq3(providerBatches.status, row.status))).run().changes === 1;
7290
+ const moved = txDb.update(providerBatches).set({ status: ProviderBatchStatuses.cancelled, error: reason, cancelRequestedAt: row.cancelRequestedAt ?? now, updatedAt: now }).where(and3(eq4(providerBatches.id, row.id), eq4(providerBatches.status, row.status))).run().changes === 1;
6734
7291
  if (moved && row.status === ProviderBatchStatuses.ended) {
6735
7292
  const tally = tallyBatchLedger(txDb, row.id);
6736
- txDb.update(providerBatches).set({ ingestedCount: tally.ingestedCount, recordedCount: tally.recordedCount }).where(eq3(providerBatches.id, row.id)).run();
7293
+ txDb.update(providerBatches).set({ ingestedCount: tally.ingestedCount, recordedCount: tally.recordedCount }).where(eq4(providerBatches.id, row.id)).run();
6737
7294
  }
6738
7295
  return moved;
6739
7296
  });
@@ -6766,13 +7323,13 @@ var JobRunner = class {
6766
7323
  */
6767
7324
  async cancelRunBatches(runId, projectId) {
6768
7325
  const sweepReports = this.isExecuting(runId);
6769
- const ids = this.db.select({ id: providerBatches.id }).from(providerBatches).where(and3(eq3(providerBatches.runId, runId), eq3(providerBatches.projectId, projectId))).all().map((row) => row.id);
7326
+ const ids = this.db.select({ id: providerBatches.id }).from(providerBatches).where(and3(eq4(providerBatches.runId, runId), eq4(providerBatches.projectId, projectId))).all().map((row) => row.id);
6770
7327
  const marked = this.markBatchesCancelled(ids, "Cancelled with its run.");
6771
7328
  if (!sweepReports) {
6772
7329
  const claimed = this.db.update(runs).set({ pendingProviderErrors: null }).where(and3(
6773
- eq3(runs.id, runId),
6774
- eq3(runs.projectId, projectId),
6775
- eq3(runs.status, RunStatuses.cancelled),
7330
+ eq4(runs.id, runId),
7331
+ eq4(runs.projectId, projectId),
7332
+ eq4(runs.status, RunStatuses.cancelled),
6776
7333
  isNotNull(runs.pendingProviderErrors)
6777
7334
  )).run().changes === 1;
6778
7335
  if (claimed) {
@@ -6795,9 +7352,9 @@ var JobRunner = class {
6795
7352
  * identity as it is now, as a fill's are.
6796
7353
  */
6797
7354
  async ingestProviderBatch(batchId) {
6798
- const batch = this.db.select().from(providerBatches).where(eq3(providerBatches.id, batchId)).get();
7355
+ const batch = this.db.select().from(providerBatches).where(eq4(providerBatches.id, batchId)).get();
6799
7356
  if (batch?.status !== ProviderBatchStatuses.ended) return { kind: "skipped" };
6800
- const runStatus = this.db.select({ status: runs.status }).from(runs).where(eq3(runs.id, batch.runId)).get()?.status;
7357
+ const runStatus = this.db.select({ status: runs.status }).from(runs).where(eq4(runs.id, batch.runId)).get()?.status;
6801
7358
  if (runStatus !== RunStatuses.running) {
6802
7359
  this.markBatchesCancelled([batch.id], "Cancelled because its run is no longer running.");
6803
7360
  return { kind: "cancelled" };
@@ -6807,7 +7364,7 @@ var JobRunner = class {
6807
7364
  if (!registered || !capability || !registered.adapter.parseTrackedQueryResponse || !batch.providerBatchId) {
6808
7365
  throw new Error(`No ${batch.provider} batch API is configured to read batch ${batch.id}`);
6809
7366
  }
6810
- const requests = new Map(this.db.select().from(providerBatchRequests).where(eq3(providerBatchRequests.batchId, batch.id)).all().map((row) => [row.id, row]));
7367
+ const requests = new Map(this.db.select().from(providerBatchRequests).where(eq4(providerBatchRequests.batchId, batch.id)).all().map((row) => [row.id, row]));
6811
7368
  const ctx = { ...this.buildRunRecordingContext(batch.runId, batch.projectId), onInserted: () => {
6812
7369
  } };
6813
7370
  const pending = [];
@@ -6842,7 +7399,7 @@ var JobRunner = class {
6842
7399
  continue;
6843
7400
  }
6844
7401
  if (request.outcome !== null || queued.has(request.id)) continue;
6845
- if (this.db.select({ status: providerBatches.status }).from(providerBatches).where(eq3(providerBatches.id, batch.id)).get()?.status !== ProviderBatchStatuses.ended) return { kind: "cancelled" };
7402
+ if (this.db.select({ status: providerBatches.status }).from(providerBatches).where(eq4(providerBatches.id, batch.id)).get()?.status !== ProviderBatchStatuses.ended) return { kind: "cancelled" };
6846
7403
  const prepared = await this.prepareBatchLine(ctx, registered, batch, request, line);
6847
7404
  const payloadBytes = Buffer.byteLength(prepared.slot?.snapshot.rawResponse ?? "") + Buffer.byteLength(prepared.slot?.snapshot.answerText ?? "") + Buffer.byteLength(prepared.error ?? "");
6848
7405
  if (pending.length > 0 && pendingBytes + payloadBytes > BATCH_INGEST_PAYLOAD_BYTES) {
@@ -6911,14 +7468,14 @@ var JobRunner = class {
6911
7468
  /** Snapshots and their replay ledger commit together, with no callbacks or awaits. */
6912
7469
  persistBatchLines(batch, lines) {
6913
7470
  return this.db.transaction((tx) => {
6914
- if (tx.select({ status: providerBatches.status }).from(providerBatches).where(eq3(providerBatches.id, batch.id)).get()?.status !== ProviderBatchStatuses.ended) return null;
6915
- if (tx.select({ status: runs.status }).from(runs).where(eq3(runs.id, batch.runId)).get()?.status !== RunStatuses.running) throw new RunCancelledError(batch.runId);
7471
+ if (tx.select({ status: providerBatches.status }).from(providerBatches).where(eq4(providerBatches.id, batch.id)).get()?.status !== ProviderBatchStatuses.ended) return null;
7472
+ if (tx.select({ status: runs.status }).from(runs).where(eq4(runs.id, batch.runId)).get()?.status !== RunStatuses.running) throw new RunCancelledError(batch.runId);
6916
7473
  const current = new Map(tx.select({
6917
7474
  id: providerBatchRequests.id,
6918
7475
  outcome: providerBatchRequests.outcome,
6919
7476
  queryId: providerBatchRequests.queryId,
6920
7477
  executionId: providerBatchRequests.executionId
6921
- }).from(providerBatchRequests).where(inArray(providerBatchRequests.id, lines.map((line) => line.requestId))).all().map((row) => [row.id, row]));
7478
+ }).from(providerBatchRequests).where(inArray2(providerBatchRequests.id, lines.map((line) => line.requestId))).all().map((row) => [row.id, row]));
6922
7479
  const settled = [];
6923
7480
  for (const line of lines) {
6924
7481
  const request = current.get(line.requestId);
@@ -6931,14 +7488,14 @@ var JobRunner = class {
6931
7488
  inserted = tx.insert(querySnapshots).values(snapshot).onConflictDoNothing().run().changes > 0;
6932
7489
  if (!inserted) {
6933
7490
  const existing = tx.select({ providerBatchId: querySnapshots.providerBatchId }).from(querySnapshots).where(and3(
6934
- eq3(querySnapshots.runId, batch.runId),
6935
- eq3(querySnapshots.measurementExecutionId, request.executionId),
6936
- eq3(querySnapshots.provider, batch.provider)
7491
+ eq4(querySnapshots.runId, batch.runId),
7492
+ eq4(querySnapshots.measurementExecutionId, request.executionId),
7493
+ eq4(querySnapshots.provider, batch.provider)
6937
7494
  )).get();
6938
7495
  outcome = existing?.providerBatchId === batch.id ? ProviderBatchRequestOutcomes.recorded : ProviderBatchRequestOutcomes.duplicate;
6939
7496
  }
6940
7497
  }
6941
- tx.update(providerBatchRequests).set({ outcome, error: line.error }).where(and3(eq3(providerBatchRequests.id, request.id), isNull(providerBatchRequests.outcome))).run();
7498
+ tx.update(providerBatchRequests).set({ outcome, error: line.error }).where(and3(eq4(providerBatchRequests.id, request.id), isNull(providerBatchRequests.outcome))).run();
6942
7499
  settled.push({ line, outcome, inserted });
6943
7500
  }
6944
7501
  return settled;
@@ -6949,9 +7506,9 @@ var JobRunner = class {
6949
7506
  const at = (/* @__PURE__ */ new Date()).toISOString();
6950
7507
  const result = this.db.transaction((tx) => {
6951
7508
  const txDb = tx;
6952
- const current = txDb.select().from(providerBatches).where(eq3(providerBatches.id, batch.id)).get();
7509
+ const current = txDb.select().from(providerBatches).where(eq4(providerBatches.id, batch.id)).get();
6953
7510
  if (current?.status !== ProviderBatchStatuses.ended) return { kind: "skipped" };
6954
- txDb.update(providerBatchRequests).set({ outcome: ProviderBatchRequestOutcomes.errored, error: "The provider returned no result for this request." }).where(and3(eq3(providerBatchRequests.batchId, batch.id), isNull(providerBatchRequests.outcome))).run();
7511
+ txDb.update(providerBatchRequests).set({ outcome: ProviderBatchRequestOutcomes.errored, error: "The provider returned no result for this request." }).where(and3(eq4(providerBatchRequests.batchId, batch.id), isNull(providerBatchRequests.outcome))).run();
6955
7512
  const tally = tallyBatchLedger(txDb, batch.id);
6956
7513
  const released = releaseUnbilledBatchQuota(txDb, current, tally.unbilled);
6957
7514
  txDb.update(providerBatches).set({
@@ -6961,7 +7518,7 @@ var JobRunner = class {
6961
7518
  quotaReleased: current.quotaReleased + released,
6962
7519
  ingestedAt: at,
6963
7520
  updatedAt: at
6964
- }).where(and3(eq3(providerBatches.id, batch.id), eq3(providerBatches.status, ProviderBatchStatuses.ended))).run();
7521
+ }).where(and3(eq4(providerBatches.id, batch.id), eq4(providerBatches.status, ProviderBatchStatuses.ended))).run();
6965
7522
  const { recordedCount: recorded, notRecorded } = tally;
6966
7523
  return { kind: "ingested", recorded, notRecorded, released };
6967
7524
  });
@@ -6990,12 +7547,12 @@ var JobRunner = class {
6990
7547
  const at = (/* @__PURE__ */ new Date()).toISOString();
6991
7548
  const abandoned = this.db.transaction((tx) => {
6992
7549
  const txDb = tx;
6993
- const claimed = txDb.update(providerBatches).set({ status: ProviderBatchStatuses.cancelled, error, updatedAt: at }).where(and3(eq3(providerBatches.id, batchId), eq3(providerBatches.status, ProviderBatchStatuses.ended))).run().changes === 1;
6994
- const batch2 = claimed ? txDb.select().from(providerBatches).where(eq3(providerBatches.id, batchId)).get() : void 0;
7550
+ const claimed = txDb.update(providerBatches).set({ status: ProviderBatchStatuses.cancelled, error, updatedAt: at }).where(and3(eq4(providerBatches.id, batchId), eq4(providerBatches.status, ProviderBatchStatuses.ended))).run().changes === 1;
7551
+ const batch2 = claimed ? txDb.select().from(providerBatches).where(eq4(providerBatches.id, batchId)).get() : void 0;
6995
7552
  if (!batch2) return null;
6996
7553
  const tally2 = tallyBatchLedger(txDb, batch2.id);
6997
7554
  const released2 = releaseUnbilledBatchQuota(txDb, batch2, tally2.unbilled);
6998
- txDb.update(providerBatches).set({ ingestedCount: tally2.ingestedCount, recordedCount: tally2.recordedCount, quotaReleased: batch2.quotaReleased + released2 }).where(eq3(providerBatches.id, batch2.id)).run();
7555
+ txDb.update(providerBatches).set({ ingestedCount: tally2.ingestedCount, recordedCount: tally2.recordedCount, quotaReleased: batch2.quotaReleased + released2 }).where(eq4(providerBatches.id, batch2.id)).run();
6999
7556
  return { batch: batch2, tally: tally2, released: released2 };
7000
7557
  });
7001
7558
  if (!abandoned) return false;
@@ -7021,7 +7578,7 @@ var JobRunner = class {
7021
7578
  * it stays the same sweep, with the same place in every history.
7022
7579
  */
7023
7580
  async executeRunFill(fillId) {
7024
- const claim = this.db.update(runFills).set({ status: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and3(eq3(runFills.id, fillId), eq3(runFills.status, "queued"))).run();
7581
+ const claim = this.db.update(runFills).set({ status: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and3(eq4(runFills.id, fillId), eq4(runFills.status, "queued"))).run();
7025
7582
  if (claim.changes !== 1) {
7026
7583
  log2.warn("fill.not-claimed", { fillId });
7027
7584
  return;
@@ -7031,11 +7588,11 @@ var JobRunner = class {
7031
7588
  } catch (err) {
7032
7589
  const error = describeError(err);
7033
7590
  log2.error("fill.aborted", { fillId, error });
7034
- this.db.update(runFills).set({ status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error }).where(and3(eq3(runFills.id, fillId), eq3(runFills.status, "running"))).run();
7591
+ this.db.update(runFills).set({ status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error }).where(and3(eq4(runFills.id, fillId), eq4(runFills.status, "running"))).run();
7035
7592
  }
7036
7593
  }
7037
7594
  async runClaimedFill(fillId) {
7038
- const fill = this.db.select().from(runFills).where(eq3(runFills.id, fillId)).get();
7595
+ const fill = this.db.select().from(runFills).where(eq4(runFills.id, fillId)).get();
7039
7596
  if (!fill) return;
7040
7597
  const { runId, projectId } = fill;
7041
7598
  const requested = new Set(parseJsonColumn(fill.providers, []).map((provider) => provider.trim().toLocaleLowerCase("en")));
@@ -7050,13 +7607,13 @@ var JobRunner = class {
7050
7607
  const run = this.getRunState(runId);
7051
7608
  if (!run) throw new Error(`Run ${runId} not found`);
7052
7609
  if (run.status !== "partial") throw new Error(`Run ${runId} is ${run.status}; only a partial run can be filled`);
7053
- const runCreatedAt = this.db.select({ createdAt: runs.createdAt }).from(runs).where(eq3(runs.id, runId)).get().createdAt;
7610
+ const runCreatedAt = this.db.select({ createdAt: runs.createdAt }).from(runs).where(eq4(runs.id, runId)).get().createdAt;
7054
7611
  recording = this.buildRunRecordingContext(runId, projectId);
7055
- const projectQueries = this.db.select().from(queries).where(eq3(queries.projectId, projectId)).all();
7612
+ const projectQueries = this.db.select().from(queries).where(eq4(queries.projectId, projectId)).all();
7056
7613
  const plan = resolvePlanExecution(run, projectQueries);
7057
7614
  if (!plan) throw new Error(`Run ${runId} did not measure a published plan`);
7058
7615
  const recorded = new Set(
7059
- this.db.select({ executionId: querySnapshots.measurementExecutionId, provider: querySnapshots.provider }).from(querySnapshots).where(eq3(querySnapshots.runId, runId)).all().flatMap((row) => row.executionId ? [measurementSlotKey(row.executionId, row.provider)] : [])
7616
+ this.db.select({ executionId: querySnapshots.measurementExecutionId, provider: querySnapshots.provider }).from(querySnapshots).where(eq4(querySnapshots.runId, runId)).all().flatMap((row) => row.executionId ? [measurementSlotKey(row.executionId, row.provider)] : [])
7060
7617
  );
7061
7618
  const unitsByProvider = /* @__PURE__ */ new Map();
7062
7619
  for (const [provider, units] of plan.unitsByProvider) {
@@ -7075,15 +7632,15 @@ var JobRunner = class {
7075
7632
  const dispatchable = [];
7076
7633
  for (const registered of activeProviders) {
7077
7634
  const name = registered.adapter.name;
7078
- const count4 = unitsByProvider.get(name)?.length ?? 0;
7635
+ const count5 = unitsByProvider.get(name)?.length ?? 0;
7079
7636
  const scope = `${projectId}:${adapterConnectionName(registered.adapter)}`;
7080
7637
  const limit = registered.config.quotaPolicy.maxRequestsPerDay;
7081
- const quota = reserveDailyQueryQuota(this.db, { scope, period: todayPeriod, count: count4, limit });
7638
+ const quota = reserveDailyQueryQuota(this.db, { scope, period: todayPeriod, count: count5, limit });
7082
7639
  if (!quota.reserved) {
7083
- providerErrors.set(name, `Daily quota exceeded for ${name}: ${quota.used} queries used today, limit is ${limit}. This fill needs ${count4} more.`);
7640
+ providerErrors.set(name, `Daily quota exceeded for ${name}: ${quota.used} queries used today, limit is ${limit}. This fill needs ${count5} more.`);
7084
7641
  continue;
7085
7642
  }
7086
- providerReservations.set(name, { scope, period: todayPeriod, reserved: count4 });
7643
+ providerReservations.set(name, { scope, period: todayPeriod, reserved: count5 });
7087
7644
  dispatchable.push(registered);
7088
7645
  }
7089
7646
  const executionGates = /* @__PURE__ */ new Map();
@@ -7108,16 +7665,16 @@ var JobRunner = class {
7108
7665
  };
7109
7666
  let removed = false;
7110
7667
  const attemptRemoved = () => {
7111
- if (!removed && this.db.select({ status: runFills.status }).from(runFills).where(eq3(runFills.id, fillId)).get()?.status !== "running") {
7668
+ if (!removed && this.db.select({ status: runFills.status }).from(runFills).where(eq4(runFills.id, fillId)).get()?.status !== "running") {
7112
7669
  removed = true;
7113
7670
  log2.warn("fill.attempt-removed", { fillId, runId });
7114
7671
  }
7115
7672
  return removed;
7116
7673
  };
7117
7674
  const slotRecorded = (provider, executionId) => this.db.select({ id: querySnapshots.id }).from(querySnapshots).where(and3(
7118
- eq3(querySnapshots.runId, runId),
7119
- eq3(querySnapshots.measurementExecutionId, executionId),
7120
- eq3(querySnapshots.provider, provider)
7675
+ eq4(querySnapshots.runId, runId),
7676
+ eq4(querySnapshots.measurementExecutionId, executionId),
7677
+ eq4(querySnapshots.provider, provider)
7121
7678
  )).get() !== void 0;
7122
7679
  const ctx = {
7123
7680
  ...recording,
@@ -7181,13 +7738,13 @@ var JobRunner = class {
7181
7738
  const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
7182
7739
  return this.db.transaction((tx) => {
7183
7740
  const txDb = tx;
7184
- const parent = txDb.select({ projectId: runs.projectId, createdAt: runs.createdAt, error: runs.error }).from(runs).where(eq3(runs.id, input.runId)).get();
7741
+ const parent = txDb.select({ projectId: runs.projectId, createdAt: runs.createdAt, error: runs.error }).from(runs).where(eq4(runs.id, input.runId)).get();
7185
7742
  const superseded = input.superseded || parent !== void 0 && newerFullSweep(txDb, { id: input.runId, projectId: parent.projectId, createdAt: parent.createdAt }) !== void 0;
7186
7743
  const state = measurementRunSlotState(txDb, input.runId);
7187
7744
  const complete = state.planned && state.readable && state.missing.length === 0 && !state.hasUnboundSnapshot;
7188
7745
  let justCompleted = false;
7189
7746
  if (complete) {
7190
- justCompleted = txDb.update(runs).set({ status: "completed", error: null }).where(and3(eq3(runs.id, input.runId), eq3(runs.status, "partial"))).run().changes === 1;
7747
+ justCompleted = txDb.update(runs).set({ status: "completed", error: null }).where(and3(eq4(runs.id, input.runId), eq4(runs.status, "partial"))).run().changes === 1;
7191
7748
  if (justCompleted && parent) recordSentimentCompletion(tx, { projectId: parent.projectId, runId: input.runId, completionKey: input.fillId, completedAt: finishedAt, fillOrigin: input.fillId });
7192
7749
  } else if (state.readable && !input.fatal) {
7193
7750
  const previous = parseRunError(parent?.error)?.providers ?? {};
@@ -7195,14 +7752,14 @@ var JobRunner = class {
7195
7752
  const remaining = /* @__PURE__ */ new Map();
7196
7753
  for (const slot of state.missing) remaining.set(slot.provider, (remaining.get(slot.provider) ?? 0) + 1);
7197
7754
  const providers = {};
7198
- for (const [provider, count4] of remaining) {
7199
- providers[provider] = fresh[provider] ?? previous[provider] ?? { message: `Expected measurements not run yet: ${count4}.` };
7755
+ for (const [provider, count5] of remaining) {
7756
+ providers[provider] = fresh[provider] ?? previous[provider] ?? { message: `Expected measurements not run yet: ${count5}.` };
7200
7757
  }
7201
- txDb.update(runs).set({ error: serializeRunError({ providers }) }).where(and3(eq3(runs.id, input.runId), eq3(runs.status, "partial"))).run();
7758
+ txDb.update(runs).set({ error: serializeRunError({ providers }) }).where(and3(eq4(runs.id, input.runId), eq4(runs.status, "partial"))).run();
7202
7759
  }
7203
7760
  const status = complete ? "completed" : input.filled > 0 ? "partial" : "failed";
7204
7761
  const reason = input.fatal ?? (superseded ? "Stopped because a newer sweep started; no answers were added behind it." : null) ?? (input.providerErrors.size > 0 ? formatRunErrorOneLine(buildRunErrorFromMessages(input.providerErrors)) : null);
7205
- txDb.update(runFills).set({ status, filled: input.filled, error: complete ? null : reason, finishedAt }).where(eq3(runFills.id, input.fillId)).run();
7762
+ txDb.update(runFills).set({ status, filled: input.filled, error: complete ? null : reason, finishedAt }).where(eq4(runFills.id, input.fillId)).run();
7206
7763
  return { justCompleted, superseded };
7207
7764
  });
7208
7765
  }
@@ -7415,11 +7972,11 @@ var JobRunner = class {
7415
7972
  * project's identity or competitor list changed in between.
7416
7973
  */
7417
7974
  buildRunRecordingContext(runId, projectId) {
7418
- const run = this.db.select({ measurementPlanVersionId: runs.measurementPlanVersionId }).from(runs).where(and3(eq3(runs.id, runId), eq3(runs.projectId, projectId))).get();
7975
+ const run = this.db.select({ measurementPlanVersionId: runs.measurementPlanVersionId }).from(runs).where(and3(eq4(runs.id, runId), eq4(runs.projectId, projectId))).get();
7419
7976
  if (!run) throw new Error(`Run ${runId} not found`);
7420
- const project = this.db.select().from(projects).where(eq3(projects.id, projectId)).get();
7977
+ const project = this.db.select().from(projects).where(eq4(projects.id, projectId)).get();
7421
7978
  if (!project) throw new Error(`Project ${projectId} not found`);
7422
- const projectCompetitors = this.db.select().from(competitors).where(eq3(competitors.projectId, projectId)).orderBy(competitors.domain).all();
7979
+ const projectCompetitors = this.db.select().from(competitors).where(eq4(competitors.projectId, projectId)).orderBy(competitors.domain).all();
7423
7980
  return runRecordingContext(this.db, {
7424
7981
  runId,
7425
7982
  measurementPlanVersionId: run.measurementPlanVersionId,
@@ -7453,7 +8010,7 @@ var JobRunner = class {
7453
8010
  log2.error("run.answer-fields-rescore-failed", { runId: recording.runId, projectId, error: describeError(err) });
7454
8011
  }
7455
8012
  }
7456
- incrementUsage(scope, metric, count4) {
8013
+ incrementUsage(scope, metric, count5) {
7457
8014
  const now = (/* @__PURE__ */ new Date()).toISOString();
7458
8015
  const period = now.slice(0, 10);
7459
8016
  this.db.insert(usageCounters).values({
@@ -7461,11 +8018,11 @@ var JobRunner = class {
7461
8018
  scope,
7462
8019
  period,
7463
8020
  metric,
7464
- count: count4,
8021
+ count: count5,
7465
8022
  updatedAt: now
7466
8023
  }).onConflictDoUpdate({
7467
8024
  target: [usageCounters.scope, usageCounters.period, usageCounters.metric],
7468
- set: { count: sql2`${usageCounters.count} + ${count4}`, updatedAt: now }
8025
+ set: { count: sql2`${usageCounters.count} + ${count5}`, updatedAt: now }
7469
8026
  }).run();
7470
8027
  }
7471
8028
  flushProviderUsage(providerDispatchCounts, providerReservations) {
@@ -7478,7 +8035,7 @@ var JobRunner = class {
7478
8035
  /** The answers a run stored, for `run.completed`. Telemetry only: a failed read reports none. */
7479
8036
  runAnswerUsage(runId) {
7480
8037
  try {
7481
- return this.db.select({ provider: querySnapshots.provider, usage: querySnapshots.usage, dispatchMode: querySnapshots.dispatchMode }).from(querySnapshots).where(eq3(querySnapshots.runId, runId)).all();
8038
+ return this.db.select({ provider: querySnapshots.provider, usage: querySnapshots.usage, dispatchMode: querySnapshots.dispatchMode }).from(querySnapshots).where(eq4(querySnapshots.runId, runId)).all();
7482
8039
  } catch (err) {
7483
8040
  log2.warn("telemetry.run-usage-read-failed", { runId, error: describeError(err) });
7484
8041
  return [];
@@ -7499,14 +8056,14 @@ var JobRunner = class {
7499
8056
  */
7500
8057
  priorFailureStreak(projectId, currentRunId) {
7501
8058
  try {
7502
- const current = this.db.select({ kind: runs.kind, createdAt: runs.createdAt }).from(runs).where(eq3(runs.id, currentRunId)).get();
8059
+ const current = this.db.select({ kind: runs.kind, createdAt: runs.createdAt }).from(runs).where(eq4(runs.id, currentRunId)).get();
7503
8060
  if (!current) return 0;
7504
8061
  const recent = this.db.select({ status: runs.status, error: runs.error }).from(runs).where(and3(
7505
- eq3(runs.projectId, projectId),
7506
- eq3(runs.kind, current.kind),
8062
+ eq4(runs.projectId, projectId),
8063
+ eq4(runs.kind, current.kind),
7507
8064
  lt(runs.createdAt, current.createdAt),
7508
8065
  ne(runs.trigger, RunTriggers.probe),
7509
- inArray(runs.status, ["completed", "partial", "failed"])
8066
+ inArray2(runs.status, ["completed", "partial", "failed"])
7510
8067
  )).orderBy(desc(runs.createdAt)).limit(FAILURE_STREAK_LOOKBACK).all();
7511
8068
  let streak = 0;
7512
8069
  for (const row of recent) {
@@ -7520,10 +8077,10 @@ var JobRunner = class {
7520
8077
  }
7521
8078
  }
7522
8079
  hasPriorActivation(projectId, currentRunId) {
7523
- return this.db.select({ id: querySnapshots.id }).from(querySnapshots).innerJoin(runs, eq3(querySnapshots.runId, runs.id)).where(and3(
7524
- eq3(runs.projectId, projectId),
7525
- eq3(runs.kind, "answer-visibility"),
7526
- inArray(runs.status, ["completed", "partial"]),
8080
+ return this.db.select({ id: querySnapshots.id }).from(querySnapshots).innerJoin(runs, eq4(querySnapshots.runId, runs.id)).where(and3(
8081
+ eq4(runs.projectId, projectId),
8082
+ eq4(runs.kind, "answer-visibility"),
8083
+ inArray2(runs.status, ["completed", "partial"]),
7527
8084
  ne(runs.trigger, "probe"),
7528
8085
  ne(runs.id, currentRunId)
7529
8086
  )).limit(1).get() !== void 0;
@@ -7541,10 +8098,10 @@ var JobRunner = class {
7541
8098
  providerDispatchModes: runs.providerDispatchModes,
7542
8099
  pendingProviderErrors: runs.pendingProviderErrors,
7543
8100
  skippedProviders: runs.skippedProviders
7544
- }).from(runs).where(eq3(runs.id, runId)).get();
8101
+ }).from(runs).where(eq4(runs.id, runId)).get();
7545
8102
  }
7546
8103
  isRunCancelled(runId) {
7547
- return this.db.select({ status: runs.status }).from(runs).where(eq3(runs.id, runId)).get()?.status === "cancelled";
8104
+ return this.db.select({ status: runs.status }).from(runs).where(eq4(runs.id, runId)).get()?.status === "cancelled";
7548
8105
  }
7549
8106
  throwIfRunCancelled(runId) {
7550
8107
  if (this.isRunCancelled(runId)) {
@@ -7557,7 +8114,7 @@ var JobRunner = class {
7557
8114
  this.db.update(runs).set({
7558
8115
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
7559
8116
  error: currentRun.error ?? "Cancelled by user"
7560
- }).where(eq3(runs.id, runId)).run();
8117
+ }).where(eq4(runs.id, runId)).run();
7561
8118
  }
7562
8119
  trackEvent(
7563
8120
  "run.completed",
@@ -7609,11 +8166,11 @@ function maybeShowActivationNotice(io = {}) {
7609
8166
 
7610
8167
  // src/gsc-sync.ts
7611
8168
  import crypto8 from "crypto";
7612
- import { eq as eq6, and as and5, sql as sql3 } from "drizzle-orm";
8169
+ import { eq as eq7, and as and5, sql as sql3 } from "drizzle-orm";
7613
8170
 
7614
8171
  // src/gsc-coverage-snapshot.ts
7615
8172
  import crypto7 from "crypto";
7616
- import { and as and4, desc as desc2, eq as eq4, gte } from "drizzle-orm";
8173
+ import { and as and4, desc as desc2, eq as eq5, gte } from "drizzle-orm";
7617
8174
  var COVERAGE_IMPRESSION_WINDOW_DAYS = 30;
7618
8175
  function pageKey(raw) {
7619
8176
  if (!raw) return null;
@@ -7631,21 +8188,21 @@ function isoDaysAgo(days) {
7631
8188
  function writeCoverageSnapshot(db, projectId, runId, opts = {}) {
7632
8189
  const windowDays = opts.windowDays ?? COVERAGE_IMPRESSION_WINDOW_DAYS;
7633
8190
  const since = isoDaysAgo(windowDays);
7634
- const pageRows = db.select({ page: gscSearchData.page, impressions: gscSearchData.impressions }).from(gscSearchData).where(and4(eq4(gscSearchData.projectId, projectId), gte(gscSearchData.date, since))).all();
7635
- const allInspections = db.select().from(gscUrlInspections).where(eq4(gscUrlInspections.projectId, projectId)).all();
7636
- const latestCrawl = db.select({ runId: siteCrawlSnapshots.runId, attemptId: siteCrawlSnapshots.attemptId }).from(siteCrawlSnapshots).innerJoin(runs, eq4(siteCrawlSnapshots.runId, runs.id)).where(and4(
7637
- eq4(siteCrawlSnapshots.projectId, projectId),
7638
- eq4(siteCrawlSnapshots.complete, true),
7639
- eq4(runs.status, "completed")
8191
+ const pageRows = db.select({ page: gscSearchData.page, impressions: gscSearchData.impressions }).from(gscSearchData).where(and4(eq5(gscSearchData.projectId, projectId), gte(gscSearchData.date, since))).all();
8192
+ const allInspections = db.select().from(gscUrlInspections).where(eq5(gscUrlInspections.projectId, projectId)).all();
8193
+ const latestCrawl = db.select({ runId: siteCrawlSnapshots.runId, attemptId: siteCrawlSnapshots.attemptId }).from(siteCrawlSnapshots).innerJoin(runs, eq5(siteCrawlSnapshots.runId, runs.id)).where(and4(
8194
+ eq5(siteCrawlSnapshots.projectId, projectId),
8195
+ eq5(siteCrawlSnapshots.complete, true),
8196
+ eq5(runs.status, "completed")
7640
8197
  )).orderBy(desc2(siteCrawlSnapshots.createdAt)).limit(1).get();
7641
- const hasCrawlHistory = Boolean(db.select({ id: siteCrawlSnapshots.id }).from(siteCrawlSnapshots).where(eq4(siteCrawlSnapshots.projectId, projectId)).limit(1).get());
7642
- const latestAudit = db.select({ runId: siteAuditSnapshots.runId }).from(siteAuditSnapshots).where(eq4(siteAuditSnapshots.projectId, projectId)).orderBy(desc2(siteAuditSnapshots.createdAt)).limit(1).get();
8198
+ const hasCrawlHistory = Boolean(db.select({ id: siteCrawlSnapshots.id }).from(siteCrawlSnapshots).where(eq5(siteCrawlSnapshots.projectId, projectId)).limit(1).get());
8199
+ const latestAudit = db.select({ runId: siteAuditSnapshots.runId }).from(siteAuditSnapshots).where(eq5(siteAuditSnapshots.projectId, projectId)).orderBy(desc2(siteAuditSnapshots.createdAt)).limit(1).get();
7643
8200
  const sitemapUrls = latestCrawl?.attemptId ? db.select({ url: siteCrawlPages.url }).from(siteCrawlPages).where(and4(
7644
- eq4(siteCrawlPages.projectId, projectId),
7645
- eq4(siteCrawlPages.runId, latestCrawl.runId),
7646
- eq4(siteCrawlPages.attemptId, latestCrawl.attemptId),
7647
- eq4(siteCrawlPages.inventoryEligible, true)
7648
- )).all() : !hasCrawlHistory && latestAudit ? db.select({ url: siteAuditPages.url }).from(siteAuditPages).where(eq4(siteAuditPages.runId, latestAudit.runId)).all() : [];
8201
+ eq5(siteCrawlPages.projectId, projectId),
8202
+ eq5(siteCrawlPages.runId, latestCrawl.runId),
8203
+ eq5(siteCrawlPages.attemptId, latestCrawl.attemptId),
8204
+ eq5(siteCrawlPages.inventoryEligible, true)
8205
+ )).all() : !hasCrawlHistory && latestAudit ? db.select({ url: siteAuditPages.url }).from(siteAuditPages).where(eq5(siteAuditPages.runId, latestAudit.runId)).all() : [];
7649
8206
  const impressionsByKey = /* @__PURE__ */ new Map();
7650
8207
  for (const row of pageRows) {
7651
8208
  const key = pageKey(row.page);
@@ -7672,7 +8229,7 @@ function writeCoverageSnapshot(db, projectId, runId, opts = {}) {
7672
8229
  });
7673
8230
  const now = opts.now ?? /* @__PURE__ */ new Date();
7674
8231
  const snapshotDate = now.toISOString().split("T")[0];
7675
- db.delete(gscCoverageSnapshots).where(and4(eq4(gscCoverageSnapshots.projectId, projectId), eq4(gscCoverageSnapshots.date, snapshotDate))).run();
8232
+ db.delete(gscCoverageSnapshots).where(and4(eq5(gscCoverageSnapshots.projectId, projectId), eq5(gscCoverageSnapshots.date, snapshotDate))).run();
7676
8233
  db.insert(gscCoverageSnapshots).values({
7677
8234
  id: crypto7.randomUUID(),
7678
8235
  projectId,
@@ -7696,9 +8253,9 @@ function writeCoverageSnapshot(db, projectId, runId, opts = {}) {
7696
8253
  }
7697
8254
 
7698
8255
  // src/sync-outcome.ts
7699
- import { eq as eq5 } from "drizzle-orm";
8256
+ import { eq as eq6 } from "drizzle-orm";
7700
8257
  function storedRunTrigger(db, runId) {
7701
- const row = db.select({ trigger: runs.trigger }).from(runs).where(eq5(runs.id, runId)).get();
8258
+ const row = db.select({ trigger: runs.trigger }).from(runs).where(eq6(runs.id, runId)).get();
7702
8259
  return typeof row?.trigger === "string" ? row.trigger : void 0;
7703
8260
  }
7704
8261
  function runOrigin(storedTrigger, requested) {
@@ -7751,13 +8308,13 @@ var log3 = createLogger("GscSync");
7751
8308
  async function executeGscSync(db, runId, projectId, opts) {
7752
8309
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.search_console, "sync");
7753
8310
  const now = (/* @__PURE__ */ new Date()).toISOString();
7754
- db.update(runs).set({ status: "running", startedAt: now }).where(eq6(runs.id, runId)).run();
8311
+ db.update(runs).set({ status: "running", startedAt: now }).where(eq7(runs.id, runId)).run();
7755
8312
  try {
7756
8313
  const { clientId: googleClientId, clientSecret: googleClientSecret } = getGoogleAuthConfig(opts.config);
7757
8314
  if (!googleClientId || !googleClientSecret) {
7758
8315
  throw withOutcomeReason(new Error("Google OAuth is not configured in the local Canonry config"), OutcomeReasonCodes.NOT_CONNECTED);
7759
8316
  }
7760
- const project = db.select().from(projects).where(eq6(projects.id, projectId)).get();
8317
+ const project = db.select().from(projects).where(eq7(projects.id, projectId)).get();
7761
8318
  if (!project) {
7762
8319
  throw withOutcomeReason(new Error(`Project not found: ${projectId}`), OutcomeReasonCodes.NOT_FOUND);
7763
8320
  }
@@ -7796,7 +8353,7 @@ async function executeGscSync(db, runId, projectId, opts) {
7796
8353
  log3.info("fetch.complete", { runId, projectId, rowCount: rows.length });
7797
8354
  db.delete(gscSearchData).where(
7798
8355
  and5(
7799
- eq6(gscSearchData.projectId, projectId),
8356
+ eq7(gscSearchData.projectId, projectId),
7800
8357
  sql3`${gscSearchData.date} >= ${startDate}`,
7801
8358
  sql3`${gscSearchData.date} <= ${endDate}`
7802
8359
  )
@@ -7831,7 +8388,7 @@ async function executeGscSync(db, runId, projectId, opts) {
7831
8388
  });
7832
8389
  db.delete(gscDailyTotals).where(
7833
8390
  and5(
7834
- eq6(gscDailyTotals.projectId, projectId),
8391
+ eq7(gscDailyTotals.projectId, projectId),
7835
8392
  sql3`${gscDailyTotals.date} >= ${startDate}`,
7836
8393
  sql3`${gscDailyTotals.date} <= ${endDate}`
7837
8394
  )
@@ -7851,7 +8408,7 @@ async function executeGscSync(db, runId, projectId, opts) {
7851
8408
  }
7852
8409
  const observedThrough = totalRows.map((row) => row.keys[0] ?? "").filter((date) => date !== "").reduce((max2, date) => max2 === null || date > max2 ? date : max2, null);
7853
8410
  if (observedThrough !== null || endDate) {
7854
- const existing = db.select().from(gscDataWatermarks).where(eq6(gscDataWatermarks.projectId, projectId)).get();
8411
+ const existing = db.select().from(gscDataWatermarks).where(eq7(gscDataWatermarks.projectId, projectId)).get();
7855
8412
  const nextThrough = [existing?.dataThroughDate ?? null, observedThrough].filter((d) => d !== null).reduce((max2, d) => max2 === null || d > max2 ? d : max2, null);
7856
8413
  if (nextThrough !== null) {
7857
8414
  db.insert(gscDataWatermarks).values({
@@ -7879,7 +8436,7 @@ async function executeGscSync(db, runId, projectId, opts) {
7879
8436
  });
7880
8437
  db.delete(gscQueryDailyTotals).where(
7881
8438
  and5(
7882
- eq6(gscQueryDailyTotals.projectId, projectId),
8439
+ eq7(gscQueryDailyTotals.projectId, projectId),
7883
8440
  sql3`${gscQueryDailyTotals.date} >= ${startDate}`,
7884
8441
  sql3`${gscQueryDailyTotals.date} <= ${endDate}`
7885
8442
  )
@@ -7903,13 +8460,13 @@ async function executeGscSync(db, runId, projectId, opts) {
7903
8460
  }
7904
8461
  log3.info("query-totals.complete", { runId, projectId, rowCount: queryTotalRows.length });
7905
8462
  const coverage = writeCoverageSnapshot(db, projectId, runId);
7906
- db.update(runs).set({ status: "completed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq6(runs.id, runId)).run();
8463
+ db.update(runs).set({ status: "completed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq7(runs.id, runId)).run();
7907
8464
  log3.info("sync.completed", { runId, projectId, searchDataRows: rows.length, indexed: coverage.indexed, notIndexed: coverage.notIndexed, unknown: coverage.unknown, verifiedByInspection: coverage.verifiedByInspection });
7908
8465
  const counts = { rows: rows.length, urls: new Set(rows.map((row) => row.keys[1] ?? "")).size };
7909
8466
  reportOutcome(rows.length === 0 ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA, counts } : { status: OutcomeStatuses.succeeded, counts });
7910
8467
  } catch (err) {
7911
8468
  const errorMsg = describeError(err);
7912
- db.update(runs).set({ status: "failed", error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq6(runs.id, runId)).run();
8469
+ db.update(runs).set({ status: "failed", error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq7(runs.id, runId)).run();
7913
8470
  log3.error("sync.failed", { runId, projectId, error: errorMsg });
7914
8471
  reportOutcome({ status: OutcomeStatuses.failed, ...googleRunFailure(err) });
7915
8472
  throw err;
@@ -7918,11 +8475,11 @@ async function executeGscSync(db, runId, projectId, opts) {
7918
8475
 
7919
8476
  // src/gbp-sync.ts
7920
8477
  import crypto10 from "crypto";
7921
- import { eq as eq8, and as and7, desc as desc4, inArray as inArray3, lt as lt2 } from "drizzle-orm";
8478
+ import { eq as eq9, and as and7, desc as desc4, inArray as inArray4, lt as lt2 } from "drizzle-orm";
7922
8479
 
7923
8480
  // src/gbp-reviews.ts
7924
8481
  import crypto9 from "crypto";
7925
- import { and as and6, desc as desc3, eq as eq7, inArray as inArray2, sql as sql4 } from "drizzle-orm";
8482
+ import { and as and6, desc as desc3, eq as eq8, inArray as inArray3, sql as sql4 } from "drizzle-orm";
7926
8483
  var log4 = createLogger("GbpReviews");
7927
8484
  var MS_PER_DAY = 864e5;
7928
8485
  var REVIEW_ALERT_MAX_AGE_DAYS = 30;
@@ -7944,25 +8501,25 @@ function ratingAlertState(origin, previous, current) {
7944
8501
  }
7945
8502
  function hasBaseline(db, projectId, locationName, origin) {
7946
8503
  return db.select({ id: gbpReviewRatings.id }).from(gbpReviewRatings).where(and6(
7947
- eq7(gbpReviewRatings.projectId, projectId),
7948
- eq7(gbpReviewRatings.locationName, locationName),
7949
- eq7(gbpReviewRatings.origin, origin)
8504
+ eq8(gbpReviewRatings.projectId, projectId),
8505
+ eq8(gbpReviewRatings.locationName, locationName),
8506
+ eq8(gbpReviewRatings.origin, origin)
7950
8507
  )).limit(1).get() !== void 0;
7951
8508
  }
7952
8509
  function placesReviewsDue(db, projectId, locationName, now) {
7953
8510
  const latest = db.select({ observedAt: gbpReviewRatings.observedAt }).from(gbpReviewRatings).where(and6(
7954
- eq7(gbpReviewRatings.projectId, projectId),
7955
- eq7(gbpReviewRatings.locationName, locationName),
7956
- eq7(gbpReviewRatings.origin, "places")
8511
+ eq8(gbpReviewRatings.projectId, projectId),
8512
+ eq8(gbpReviewRatings.locationName, locationName),
8513
+ eq8(gbpReviewRatings.origin, "places")
7957
8514
  )).orderBy(desc3(gbpReviewRatings.observedAt)).limit(1).get();
7958
8515
  if (!latest) return true;
7959
8516
  return now.getTime() - Date.parse(latest.observedAt) >= PLACES_REVIEW_MIN_INTERVAL_HOURS * 36e5;
7960
8517
  }
7961
8518
  function newestStoredUpdateTime(db, projectId, locationName, origin) {
7962
8519
  const row = db.select({ newest: sql4`max(${gbpReviews.updateTime})` }).from(gbpReviews).where(and6(
7963
- eq7(gbpReviews.projectId, projectId),
7964
- eq7(gbpReviews.locationName, locationName),
7965
- eq7(gbpReviews.origin, origin)
8520
+ eq8(gbpReviews.projectId, projectId),
8521
+ eq8(gbpReviews.locationName, locationName),
8522
+ eq8(gbpReviews.origin, origin)
7966
8523
  )).get();
7967
8524
  return row?.newest ?? null;
7968
8525
  }
@@ -8032,9 +8589,9 @@ function persistReviewObservation(tx, projectId, runId, obs, ctx) {
8032
8589
  const { now, negativeMaxStars } = ctx;
8033
8590
  const nowIso = now.toISOString();
8034
8591
  const latestRating = tx.select().from(gbpReviewRatings).where(and6(
8035
- eq7(gbpReviewRatings.projectId, projectId),
8036
- eq7(gbpReviewRatings.locationName, obs.locationName),
8037
- eq7(gbpReviewRatings.origin, obs.origin)
8592
+ eq8(gbpReviewRatings.projectId, projectId),
8593
+ eq8(gbpReviewRatings.locationName, obs.locationName),
8594
+ eq8(gbpReviewRatings.origin, obs.origin)
8038
8595
  )).orderBy(desc3(gbpReviewRatings.observedAt)).limit(1).get();
8039
8596
  const baseline = latestRating === void 0;
8040
8597
  let queuedRatingDrop = false;
@@ -8055,7 +8612,7 @@ function persistReviewObservation(tx, projectId, runId, obs, ctx) {
8055
8612
  alertStateAt: nowIso
8056
8613
  }).run();
8057
8614
  } else if (sameRating(latestRating.rating, obs.rating) && latestRating.reviewCount === obs.reviewCount) {
8058
- tx.update(gbpReviewRatings).set({ observedAt: nowIso, syncRunId: runId }).where(eq7(gbpReviewRatings.id, latestRating.id)).run();
8615
+ tx.update(gbpReviewRatings).set({ observedAt: nowIso, syncRunId: runId }).where(eq8(gbpReviewRatings.id, latestRating.id)).run();
8059
8616
  } else {
8060
8617
  const alertState = ratingAlertState(obs.origin, latestRating.rating, obs.rating);
8061
8618
  queuedRatingDrop = alertState === "pending";
@@ -8083,9 +8640,9 @@ function persistReviewObservation(tx, projectId, runId, obs, ctx) {
8083
8640
  const existing = /* @__PURE__ */ new Map();
8084
8641
  for (let i = 0; i < names.length; i += LOOKUP_CHUNK) {
8085
8642
  const rows = tx.select().from(gbpReviews).where(and6(
8086
- eq7(gbpReviews.projectId, projectId),
8087
- eq7(gbpReviews.origin, obs.origin),
8088
- inArray2(gbpReviews.reviewName, names.slice(i, i + LOOKUP_CHUNK))
8643
+ eq8(gbpReviews.projectId, projectId),
8644
+ eq8(gbpReviews.origin, obs.origin),
8645
+ inArray3(gbpReviews.reviewName, names.slice(i, i + LOOKUP_CHUNK))
8089
8646
  )).all();
8090
8647
  for (const row of rows) existing.set(row.reviewName, row);
8091
8648
  }
@@ -8123,9 +8680,9 @@ function persistReviewObservation(tx, projectId, runId, obs, ctx) {
8123
8680
  } else if (stored.starRating !== review.starRating || stored.comment !== review.comment) {
8124
8681
  const alertState = reviewAlertState(review, { baseline, now, negativeMaxStars });
8125
8682
  if (alertState === "pending") queuedReviews++;
8126
- tx.update(gbpReviews).set({ ...content, alertState, alertStateAt: nowIso }).where(eq7(gbpReviews.id, stored.id)).run();
8683
+ tx.update(gbpReviews).set({ ...content, alertState, alertStateAt: nowIso }).where(eq8(gbpReviews.id, stored.id)).run();
8127
8684
  } else {
8128
- tx.update(gbpReviews).set(content).where(eq7(gbpReviews.id, stored.id)).run();
8685
+ tx.update(gbpReviews).set(content).where(eq8(gbpReviews.id, stored.id)).run();
8129
8686
  }
8130
8687
  }
8131
8688
  return { baseline, inserted, queuedReviews, queuedRatingDrop };
@@ -8182,13 +8739,13 @@ async function executeGbpSync(db, runId, projectId, opts) {
8182
8739
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.gbp, "sync");
8183
8740
  const reportReviews = startRunOutcome(db, runId, FeatureNames.gbp, "reviews");
8184
8741
  const now = (/* @__PURE__ */ new Date()).toISOString();
8185
- db.update(runs).set({ status: "running", startedAt: now }).where(eq8(runs.id, runId)).run();
8742
+ db.update(runs).set({ status: "running", startedAt: now }).where(eq9(runs.id, runId)).run();
8186
8743
  try {
8187
8744
  const { clientId, clientSecret } = getGoogleAuthConfig(opts.config);
8188
8745
  if (!clientId || !clientSecret) {
8189
8746
  throw withOutcomeReason(new Error("Google OAuth is not configured in the local Canonry config"), OutcomeReasonCodes.NOT_CONNECTED);
8190
8747
  }
8191
- const project = db.select().from(projects).where(eq8(projects.id, projectId)).get();
8748
+ const project = db.select().from(projects).where(eq9(projects.id, projectId)).get();
8192
8749
  if (!project) throw withOutcomeReason(new Error(`Project not found: ${projectId}`), OutcomeReasonCodes.NOT_FOUND);
8193
8750
  const conn = getGoogleConnection(opts.config, project.canonicalDomain, "gbp");
8194
8751
  if (!conn || !conn.refreshToken) {
@@ -8209,7 +8766,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8209
8766
  });
8210
8767
  saveConfigPatch(opts.config);
8211
8768
  }
8212
- let locationRows = db.select().from(gbpLocations).where(and7(eq8(gbpLocations.projectId, projectId), eq8(gbpLocations.selected, true))).all();
8769
+ let locationRows = db.select().from(gbpLocations).where(and7(eq9(gbpLocations.projectId, projectId), eq9(gbpLocations.selected, true))).all();
8213
8770
  if (opts.locationNames?.length) {
8214
8771
  const wanted = new Set(opts.locationNames);
8215
8772
  locationRows = locationRows.filter((l) => wanted.has(l.locationName));
@@ -8276,15 +8833,15 @@ async function executeGbpSync(db, runId, projectId, opts) {
8276
8833
  fetchLocationReviews(db, projectId, loc, reviewContext)
8277
8834
  ]);
8278
8835
  const lodgingHash = lodging ? hashLodging(lodging) : null;
8279
- const latestLodging = lodging ? db.select().from(gbpLodgingSnapshots).where(and7(eq8(gbpLodgingSnapshots.projectId, projectId), eq8(gbpLodgingSnapshots.locationName, loc.locationName))).orderBy(desc4(gbpLodgingSnapshots.syncedAt)).limit(1).get() : void 0;
8836
+ const latestLodging = lodging ? db.select().from(gbpLodgingSnapshots).where(and7(eq9(gbpLodgingSnapshots.projectId, projectId), eq9(gbpLodgingSnapshots.locationName, loc.locationName))).orderBy(desc4(gbpLodgingSnapshots.syncedAt)).limit(1).get() : void 0;
8280
8837
  const lodgingChanged = lodging !== null && latestLodging?.contentHash !== lodgingHash;
8281
8838
  const attributesHash = hashAttributes(attributes);
8282
- const latestAttributes = db.select().from(gbpAttributesSnapshots).where(and7(eq8(gbpAttributesSnapshots.projectId, projectId), eq8(gbpAttributesSnapshots.locationName, loc.locationName))).orderBy(desc4(gbpAttributesSnapshots.syncedAt)).limit(1).get();
8839
+ const latestAttributes = db.select().from(gbpAttributesSnapshots).where(and7(eq9(gbpAttributesSnapshots.projectId, projectId), eq9(gbpAttributesSnapshots.locationName, loc.locationName))).orderBy(desc4(gbpAttributesSnapshots.syncedAt)).limit(1).get();
8283
8840
  const attributesChanged = latestAttributes?.contentHash !== attributesHash;
8284
8841
  let placeToWrite = null;
8285
8842
  let placeToTouch = null;
8286
8843
  if (placesTier !== "off" && placesApiKey && lodging !== null && loc.placeId) {
8287
- const latestPlace = db.select().from(gbpPlaceDetails).where(and7(eq8(gbpPlaceDetails.projectId, projectId), eq8(gbpPlaceDetails.locationName, loc.locationName))).orderBy(desc4(gbpPlaceDetails.syncedAt)).limit(1).get();
8844
+ const latestPlace = db.select().from(gbpPlaceDetails).where(and7(eq9(gbpPlaceDetails.projectId, projectId), eq9(gbpPlaceDetails.locationName, loc.locationName))).orderBy(desc4(gbpPlaceDetails.syncedAt)).limit(1).get();
8288
8845
  const ageDays = latestPlace ? (Date.now() - new Date(latestPlace.syncedAt).getTime()) / MS_PER_DAY2 : Infinity;
8289
8846
  if (ageDays >= placesRefreshDays) {
8290
8847
  try {
@@ -8303,7 +8860,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8303
8860
  const reviewNow = /* @__PURE__ */ new Date();
8304
8861
  const insertNow = reviewNow.toISOString();
8305
8862
  db.transaction((tx) => {
8306
- tx.delete(gbpDailyMetrics).where(and7(eq8(gbpDailyMetrics.projectId, projectId), eq8(gbpDailyMetrics.locationName, loc.locationName))).run();
8863
+ tx.delete(gbpDailyMetrics).where(and7(eq9(gbpDailyMetrics.projectId, projectId), eq9(gbpDailyMetrics.locationName, loc.locationName))).run();
8307
8864
  for (const row of metricRows) {
8308
8865
  tx.insert(gbpDailyMetrics).values({
8309
8866
  id: crypto10.randomUUID(),
@@ -8315,7 +8872,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8315
8872
  syncRunId: runId
8316
8873
  }).run();
8317
8874
  }
8318
- tx.delete(gbpKeywordImpressions).where(and7(eq8(gbpKeywordImpressions.projectId, projectId), eq8(gbpKeywordImpressions.locationName, loc.locationName))).run();
8875
+ tx.delete(gbpKeywordImpressions).where(and7(eq9(gbpKeywordImpressions.projectId, projectId), eq9(gbpKeywordImpressions.locationName, loc.locationName))).run();
8319
8876
  for (const row of keywordRows) {
8320
8877
  tx.insert(gbpKeywordImpressions).values({
8321
8878
  id: crypto10.randomUUID(),
@@ -8332,9 +8889,9 @@ async function executeGbpSync(db, runId, projectId, opts) {
8332
8889
  const fetchedMonths = monthlyKeywordResults.map((r) => r.month);
8333
8890
  if (fetchedMonths.length > 0) {
8334
8891
  tx.delete(gbpKeywordMonthly).where(and7(
8335
- eq8(gbpKeywordMonthly.projectId, projectId),
8336
- eq8(gbpKeywordMonthly.locationName, loc.locationName),
8337
- inArray3(gbpKeywordMonthly.month, fetchedMonths)
8892
+ eq9(gbpKeywordMonthly.projectId, projectId),
8893
+ eq9(gbpKeywordMonthly.locationName, loc.locationName),
8894
+ inArray4(gbpKeywordMonthly.month, fetchedMonths)
8338
8895
  )).run();
8339
8896
  for (const { month, rows } of monthlyKeywordResults) {
8340
8897
  for (const row of rows) {
@@ -8352,12 +8909,12 @@ async function executeGbpSync(db, runId, projectId, opts) {
8352
8909
  }
8353
8910
  }
8354
8911
  tx.delete(gbpKeywordMonthly).where(and7(
8355
- eq8(gbpKeywordMonthly.projectId, projectId),
8356
- eq8(gbpKeywordMonthly.locationName, loc.locationName),
8912
+ eq9(gbpKeywordMonthly.projectId, projectId),
8913
+ eq9(gbpKeywordMonthly.locationName, loc.locationName),
8357
8914
  lt2(gbpKeywordMonthly.month, keywordRetentionCutoff)
8358
8915
  )).run();
8359
8916
  }
8360
- tx.delete(gbpPlaceActions).where(and7(eq8(gbpPlaceActions.projectId, projectId), eq8(gbpPlaceActions.locationName, loc.locationName))).run();
8917
+ tx.delete(gbpPlaceActions).where(and7(eq9(gbpPlaceActions.projectId, projectId), eq9(gbpPlaceActions.locationName, loc.locationName))).run();
8361
8918
  for (const row of placeActionRows) {
8362
8919
  tx.insert(gbpPlaceActions).values({
8363
8920
  id: crypto10.randomUUID(),
@@ -8383,7 +8940,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8383
8940
  syncRunId: runId
8384
8941
  }).run();
8385
8942
  } else if (lodging !== null && latestLodging) {
8386
- tx.update(gbpLodgingSnapshots).set({ syncedAt: insertNow, syncRunId: runId }).where(eq8(gbpLodgingSnapshots.id, latestLodging.id)).run();
8943
+ tx.update(gbpLodgingSnapshots).set({ syncedAt: insertNow, syncRunId: runId }).where(eq9(gbpLodgingSnapshots.id, latestLodging.id)).run();
8387
8944
  }
8388
8945
  if (attributesChanged) {
8389
8946
  tx.insert(gbpAttributesSnapshots).values({
@@ -8397,7 +8954,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8397
8954
  syncRunId: runId
8398
8955
  }).run();
8399
8956
  } else if (latestAttributes) {
8400
- tx.update(gbpAttributesSnapshots).set({ syncedAt: insertNow, syncRunId: runId }).where(eq8(gbpAttributesSnapshots.id, latestAttributes.id)).run();
8957
+ tx.update(gbpAttributesSnapshots).set({ syncedAt: insertNow, syncRunId: runId }).where(eq9(gbpAttributesSnapshots.id, latestAttributes.id)).run();
8401
8958
  }
8402
8959
  if (placeToWrite) {
8403
8960
  tx.insert(gbpPlaceDetails).values({
@@ -8412,7 +8969,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8412
8969
  syncRunId: runId
8413
8970
  }).run();
8414
8971
  } else if (placeToTouch) {
8415
- tx.update(gbpPlaceDetails).set({ syncedAt: insertNow, syncRunId: runId }).where(eq8(gbpPlaceDetails.id, placeToTouch)).run();
8972
+ tx.update(gbpPlaceDetails).set({ syncedAt: insertNow, syncRunId: runId }).where(eq9(gbpPlaceDetails.id, placeToTouch)).run();
8416
8973
  }
8417
8974
  for (const observation of reviewFetch.observations) {
8418
8975
  const persisted = persistReviewObservation(tx, projectId, runId, observation, { now: reviewNow, negativeMaxStars });
@@ -8432,7 +8989,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8432
8989
  reviewsAccess: reviewFetch.access.status,
8433
8990
  reviewsAccessReason: reviewFetch.access.reason,
8434
8991
  reviewsCheckedAt: insertNow
8435
- }).where(eq8(gbpLocations.id, loc.id)).run();
8992
+ }).where(eq9(gbpLocations.id, loc.id)).run();
8436
8993
  });
8437
8994
  okCount++;
8438
8995
  rowsWritten += metricRows.length + keywordRows.length + placeActionRows.length + monthlyKeywordResults.reduce((total, month) => total + month.rows.length, 0);
@@ -8450,19 +9007,19 @@ async function executeGbpSync(db, runId, projectId, opts) {
8450
9007
  }
8451
9008
  const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
8452
9009
  if (errors.size === 0) {
8453
- db.update(runs).set({ status: "completed", finishedAt }).where(eq8(runs.id, runId)).run();
9010
+ db.update(runs).set({ status: "completed", finishedAt }).where(eq9(runs.id, runId)).run();
8454
9011
  } else if (okCount > 0) {
8455
9012
  db.update(runs).set({
8456
9013
  status: "partial",
8457
9014
  error: serializeRunError(buildRunErrorFromMessages(errors)),
8458
9015
  finishedAt
8459
- }).where(eq8(runs.id, runId)).run();
9016
+ }).where(eq9(runs.id, runId)).run();
8460
9017
  } else {
8461
9018
  db.update(runs).set({
8462
9019
  status: "failed",
8463
9020
  error: serializeRunError(buildRunErrorFromMessages(errors)),
8464
9021
  finishedAt
8465
- }).where(eq8(runs.id, runId)).run();
9022
+ }).where(eq9(runs.id, runId)).run();
8466
9023
  }
8467
9024
  log5.info("sync.done", { runId, projectId, ok: okCount, failed: errors.size });
8468
9025
  const counts = { rows: rowsWritten, items: okCount, failures: errors.size };
@@ -8471,7 +9028,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
8471
9028
  if (reviews) reportReviews(reviews);
8472
9029
  } catch (err) {
8473
9030
  const errorMsg = describeError(err);
8474
- db.update(runs).set({ status: "failed", error: serializeRunError({ message: errorMsg }), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq8(runs.id, runId)).run();
9031
+ db.update(runs).set({ status: "failed", error: serializeRunError({ message: errorMsg }), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq9(runs.id, runId)).run();
8475
9032
  log5.error("sync.failed", { runId, projectId, error: errorMsg });
8476
9033
  reportOutcome({ status: OutcomeStatuses.failed, ...gbpRunFailure(err) });
8477
9034
  throw err;
@@ -8513,7 +9070,7 @@ async function refreshSelectedLocationProfiles(db, projectId, accessToken, locat
8513
9070
  ...profile,
8514
9071
  updatedAt
8515
9072
  };
8516
- db.update(gbpLocations).set(update).where(and7(eq8(gbpLocations.projectId, projectId), eq8(gbpLocations.id, row.id))).run();
9073
+ db.update(gbpLocations).set(update).where(and7(eq9(gbpLocations.projectId, projectId), eq9(gbpLocations.id, row.id))).run();
8517
9074
  refreshedRows.set(row.id, { ...row, ...update });
8518
9075
  }
8519
9076
  }
@@ -8522,7 +9079,7 @@ async function refreshSelectedLocationProfiles(db, projectId, accessToken, locat
8522
9079
 
8523
9080
  // src/ads-sync.ts
8524
9081
  import crypto11 from "crypto";
8525
- import { and as and8, eq as eq9, inArray as inArray4, notInArray } from "drizzle-orm";
9082
+ import { and as and8, eq as eq10, inArray as inArray5, notInArray } from "drizzle-orm";
8526
9083
 
8527
9084
  // ../integration-openai-ads/src/constants.ts
8528
9085
  var OPENAI_ADS_API_BASE = "https://api.ads.openai.com/v1";
@@ -9175,11 +9732,11 @@ function toDailyUpserts(level, entityId, read) {
9175
9732
  async function executeAdsSync(db, runId, projectId, opts) {
9176
9733
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.openai_ads, "sync");
9177
9734
  const now = (/* @__PURE__ */ new Date()).toISOString();
9178
- db.update(runs).set({ status: "running", startedAt: now }).where(eq9(runs.id, runId)).run();
9735
+ db.update(runs).set({ status: "running", startedAt: now }).where(eq10(runs.id, runId)).run();
9179
9736
  try {
9180
- const project = db.select().from(projects).where(eq9(projects.id, projectId)).get();
9737
+ const project = db.select().from(projects).where(eq10(projects.id, projectId)).get();
9181
9738
  if (!project) throw withOutcomeReason(new Error(`Project not found: ${projectId}`), OutcomeReasonCodes.NOT_FOUND);
9182
- const connRow = db.select().from(adsConnections).where(eq9(adsConnections.projectId, projectId)).get();
9739
+ const connRow = db.select().from(adsConnections).where(eq10(adsConnections.projectId, projectId)).get();
9183
9740
  if (!connRow) {
9184
9741
  throw withOutcomeReason(new Error('No ads connection found for this project. Run "canonry ads connect" first.'), OutcomeReasonCodes.NOT_CONNECTED);
9185
9742
  }
@@ -9246,9 +9803,9 @@ async function executeAdsSync(db, runId, projectId, opts) {
9246
9803
  const upstreamIds = campaigns.map((c) => c.id);
9247
9804
  const refreshedIds = syncedCampaigns.map((c) => c.id);
9248
9805
  db.transaction((tx) => {
9249
- tx.delete(adsCampaigns).where(upstreamIds.length === 0 ? eq9(adsCampaigns.projectId, projectId) : and8(eq9(adsCampaigns.projectId, projectId), notInArray(adsCampaigns.id, upstreamIds))).run();
9806
+ tx.delete(adsCampaigns).where(upstreamIds.length === 0 ? eq10(adsCampaigns.projectId, projectId) : and8(eq10(adsCampaigns.projectId, projectId), notInArray(adsCampaigns.id, upstreamIds))).run();
9250
9807
  if (refreshedIds.length > 0) {
9251
- tx.delete(adsCampaigns).where(and8(eq9(adsCampaigns.projectId, projectId), inArray4(adsCampaigns.id, refreshedIds))).run();
9808
+ tx.delete(adsCampaigns).where(and8(eq10(adsCampaigns.projectId, projectId), inArray5(adsCampaigns.id, refreshedIds))).run();
9252
9809
  }
9253
9810
  for (const campaign of syncedCampaigns) {
9254
9811
  tx.insert(adsCampaigns).values({
@@ -9347,23 +9904,23 @@ async function executeAdsSync(db, runId, projectId, opts) {
9347
9904
  conversionTrackingConfigured,
9348
9905
  ...entitySnapshotRefreshed ? { lastSyncedAt: insertNow } : {},
9349
9906
  updatedAt: insertNow
9350
- }).where(eq9(adsConnections.projectId, projectId)).run();
9907
+ }).where(eq10(adsConnections.projectId, projectId)).run();
9351
9908
  });
9352
9909
  const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
9353
9910
  if (errors.size === 0) {
9354
- db.update(runs).set({ status: "completed", finishedAt }).where(eq9(runs.id, runId)).run();
9911
+ db.update(runs).set({ status: "completed", finishedAt }).where(eq10(runs.id, runId)).run();
9355
9912
  } else if (syncedCampaigns.length > 0) {
9356
9913
  db.update(runs).set({
9357
9914
  status: "partial",
9358
9915
  error: serializeRunError(buildRunErrorFromMessages(errors)),
9359
9916
  finishedAt
9360
- }).where(eq9(runs.id, runId)).run();
9917
+ }).where(eq10(runs.id, runId)).run();
9361
9918
  } else {
9362
9919
  db.update(runs).set({
9363
9920
  status: "failed",
9364
9921
  error: serializeRunError(buildRunErrorFromMessages(errors)),
9365
9922
  finishedAt
9366
- }).where(eq9(runs.id, runId)).run();
9923
+ }).where(eq10(runs.id, runId)).run();
9367
9924
  }
9368
9925
  log6.info("sync.done", { runId, projectId, campaigns: syncedCampaigns.length, insightRows: insightUpserts.length, failed: errors.size });
9369
9926
  const counts = { campaigns: syncedCampaigns.length, rows: insightUpserts.length, failures: errors.size };
@@ -9374,7 +9931,7 @@ async function executeAdsSync(db, runId, projectId, opts) {
9374
9931
  }
9375
9932
  } catch (err) {
9376
9933
  const errorMsg = describeError(err);
9377
- db.update(runs).set({ status: "failed", error: serializeRunError({ message: errorMsg }), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq9(runs.id, runId)).run();
9934
+ db.update(runs).set({ status: "failed", error: serializeRunError({ message: errorMsg }), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq10(runs.id, runId)).run();
9378
9935
  log6.error("sync.failed", { runId, projectId, error: errorMsg });
9379
9936
  reportOutcome({ status: OutcomeStatuses.failed, ...runFailure(err) });
9380
9937
  throw err;
@@ -9383,7 +9940,7 @@ async function executeAdsSync(db, runId, projectId, opts) {
9383
9940
 
9384
9941
  // src/gsc-inspect-sitemap.ts
9385
9942
  import crypto13 from "crypto";
9386
- import { eq as eq10 } from "drizzle-orm";
9943
+ import { eq as eq11 } from "drizzle-orm";
9387
9944
 
9388
9945
  // src/sitemap-parser.ts
9389
9946
  var log7 = createLogger("SitemapParser");
@@ -9607,13 +10164,13 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
9607
10164
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.search_console, "inspect");
9608
10165
  let abortCause;
9609
10166
  const now = (/* @__PURE__ */ new Date()).toISOString();
9610
- db.update(runs).set({ status: "running", startedAt: now }).where(eq10(runs.id, runId)).run();
10167
+ db.update(runs).set({ status: "running", startedAt: now }).where(eq11(runs.id, runId)).run();
9611
10168
  try {
9612
10169
  const { clientId: googleClientId, clientSecret: googleClientSecret } = getGoogleAuthConfig(opts.config);
9613
10170
  if (!googleClientId || !googleClientSecret) {
9614
10171
  throw withOutcomeReason(new Error("Google OAuth is not configured in the local Canonry config"), OutcomeReasonCodes.NOT_CONNECTED);
9615
10172
  }
9616
- const project = db.select().from(projects).where(eq10(projects.id, projectId)).get();
10173
+ const project = db.select().from(projects).where(eq11(projects.id, projectId)).get();
9617
10174
  if (!project) {
9618
10175
  throw withOutcomeReason(new Error(`Project not found: ${projectId}`), OutcomeReasonCodes.NOT_FOUND);
9619
10176
  }
@@ -9721,7 +10278,7 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
9721
10278
  const snapNotIndexed = coverage.notIndexed;
9722
10279
  const attempted = targetUrls.length;
9723
10280
  const status = skipped > 0 || errors > 0 && inspected > 0 ? "partial" : errors === attempted ? "failed" : "completed";
9724
- db.update(runs).set({ status, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq10(runs.id, runId)).run();
10281
+ db.update(runs).set({ status, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(runs.id, runId)).run();
9725
10282
  log8.info("inspect.completed", { runId, projectId, inspected, errors, total: urls.length, indexed: snapIndexed, notIndexed: snapNotIndexed });
9726
10283
  const counts = { urls: inspected, failures: errors, skipped };
9727
10284
  if (status === RunStatuses.completed) {
@@ -9732,7 +10289,7 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
9732
10289
  }
9733
10290
  } catch (err) {
9734
10291
  const errorMsg = describeError(err);
9735
- db.update(runs).set({ status: "failed", error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq10(runs.id, runId)).run();
10292
+ db.update(runs).set({ status: "failed", error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(runs.id, runId)).run();
9736
10293
  log8.error("inspect.failed", { runId, projectId, error: errorMsg });
9737
10294
  const failure2 = googleRunFailure(abortCause ?? err);
9738
10295
  reportOutcome({
@@ -9745,7 +10302,7 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
9745
10302
 
9746
10303
  // src/bing-inspect-sitemap.ts
9747
10304
  import crypto14 from "crypto";
9748
- import { eq as eq11, desc as desc5 } from "drizzle-orm";
10305
+ import { eq as eq12, desc as desc5 } from "drizzle-orm";
9749
10306
  var log9 = createLogger("BingInspectSitemap");
9750
10307
  function bingRunFailure(err) {
9751
10308
  return runFailure(err, err instanceof BingApiError && err.isThrottle ? OutcomeReasonCodes.RATE_LIMITED : void 0);
@@ -9769,9 +10326,9 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
9769
10326
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.bing, "sync");
9770
10327
  let abortCause;
9771
10328
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
9772
- db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq11(runs.id, runId)).run();
10329
+ db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq12(runs.id, runId)).run();
9773
10330
  try {
9774
- const project = db.select().from(projects).where(eq11(projects.id, projectId)).get();
10331
+ const project = db.select().from(projects).where(eq12(projects.id, projectId)).get();
9775
10332
  if (!project) {
9776
10333
  throw withOutcomeReason(new Error(`Project not found: ${projectId}`), OutcomeReasonCodes.NOT_FOUND);
9777
10334
  }
@@ -9795,7 +10352,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
9795
10352
  if (sitemapUrls.length === 0) {
9796
10353
  throw withOutcomeReason(new Error("No URLs found in sitemap"), OutcomeReasonCodes.NO_DATA);
9797
10354
  }
9798
- const trackedRows = db.select({ url: bingUrlInspections.url }).from(bingUrlInspections).where(eq11(bingUrlInspections.projectId, projectId)).all();
10355
+ const trackedRows = db.select({ url: bingUrlInspections.url }).from(bingUrlInspections).where(eq12(bingUrlInspections.projectId, projectId)).all();
9799
10356
  const trackedUrls = new Set(trackedRows.map((r) => r.url));
9800
10357
  const discovered = sitemapUrls.filter((u) => !trackedUrls.has(u));
9801
10358
  log9.info("sitemap.diff", {
@@ -9923,7 +10480,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
9923
10480
  `Bing inspection failed for every URL attempted (${errors} of ${targetUrls.length}); coverage was left unchanged rather than re-dated from stored inspections. Last error: ${detail}`
9924
10481
  );
9925
10482
  }
9926
- const allInspections = db.select().from(bingUrlInspections).where(eq11(bingUrlInspections.projectId, projectId)).orderBy(desc5(bingUrlInspections.inspectedAt)).all();
10483
+ const allInspections = db.select().from(bingUrlInspections).where(eq12(bingUrlInspections.projectId, projectId)).orderBy(desc5(bingUrlInspections.inspectedAt)).all();
9927
10484
  const latestByUrl = /* @__PURE__ */ new Map();
9928
10485
  const definitiveByUrl = /* @__PURE__ */ new Map();
9929
10486
  for (const row of allInspections) {
@@ -9967,7 +10524,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
9967
10524
  }).run();
9968
10525
  const status = errors > 0 && errors >= targetUrls.length ? RunStatuses.failed : errors > 0 || outcome.aborted ? RunStatuses.partial : RunStatuses.completed;
9969
10526
  const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped early after sustained failures; ${targetUrls.length - inspected} of ${targetUrls.length} pages were not inspected.` : `${errors} of ${targetUrls.length} pages could not be inspected.`;
9970
- db.update(runs).set({ status, error: degradedReason, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(runs.id, runId)).run();
10527
+ db.update(runs).set({ status, error: degradedReason, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq12(runs.id, runId)).run();
9971
10528
  log9.info("inspect.completed", {
9972
10529
  runId,
9973
10530
  projectId,
@@ -9991,7 +10548,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
9991
10548
  }
9992
10549
  } catch (err) {
9993
10550
  const errorMsg = describeError(err);
9994
- db.update(runs).set({ status: RunStatuses.failed, error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(runs.id, runId)).run();
10551
+ db.update(runs).set({ status: RunStatuses.failed, error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq12(runs.id, runId)).run();
9995
10552
  log9.error("inspect.failed", { runId, projectId, error: errorMsg });
9996
10553
  const failure2 = bingRunFailure(abortCause ?? err);
9997
10554
  reportOutcome({
@@ -10004,7 +10561,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
10004
10561
 
10005
10562
  // src/coverage-refresh.ts
10006
10563
  import crypto15 from "crypto";
10007
- import { and as and9, desc as desc6, eq as eq12, inArray as inArray5 } from "drizzle-orm";
10564
+ import { and as and9, desc as desc6, eq as eq13, inArray as inArray6 } from "drizzle-orm";
10008
10565
  var log10 = createLogger("CoverageRefresh");
10009
10566
  var COVERAGE_REFRESH_MIN_INTERVAL_MS = 60 * 60 * 1e3;
10010
10567
  var COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS = 2 * 60 * 1e3;
@@ -10016,12 +10573,12 @@ var ACTIVE_OR_DONE_STATUSES = [
10016
10573
  ];
10017
10574
  var IN_FLIGHT_STATUSES = [RunStatuses.queued, RunStatuses.running];
10018
10575
  function runWasUserInitiated(db, runId) {
10019
- const row = db.select({ trigger: runs.trigger }).from(runs).where(eq12(runs.id, runId)).get();
10576
+ const row = db.select({ trigger: runs.trigger }).from(runs).where(eq13(runs.id, runId)).get();
10020
10577
  return row?.trigger === RunTriggers.manual;
10021
10578
  }
10022
10579
  var defaultDeps = { executeInspectSitemap };
10023
10580
  async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps, nowMs = Date.now(), opts = {}) {
10024
- const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq12(projects.id, projectId)).get();
10581
+ const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq13(projects.id, projectId)).get();
10025
10582
  if (!project) return null;
10026
10583
  const { clientId, clientSecret } = getGoogleAuthConfig(config);
10027
10584
  if (!clientId || !clientSecret) return null;
@@ -10029,9 +10586,9 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
10029
10586
  if (!conn?.refreshToken || !conn.propertyId) return null;
10030
10587
  const inFlight = db.select({ createdAt: runs.createdAt }).from(runs).where(
10031
10588
  and9(
10032
- eq12(runs.projectId, projectId),
10033
- eq12(runs.kind, RunKinds["inspect-sitemap"]),
10034
- inArray5(runs.status, IN_FLIGHT_STATUSES)
10589
+ eq13(runs.projectId, projectId),
10590
+ eq13(runs.kind, RunKinds["inspect-sitemap"]),
10591
+ inArray6(runs.status, IN_FLIGHT_STATUSES)
10035
10592
  )
10036
10593
  ).orderBy(desc6(runs.createdAt)).limit(1).get();
10037
10594
  if (inFlight) {
@@ -10041,9 +10598,9 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
10041
10598
  const windowMs = opts.userInitiated ? COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS : COVERAGE_REFRESH_MIN_INTERVAL_MS;
10042
10599
  const recent = db.select({ createdAt: runs.createdAt }).from(runs).where(
10043
10600
  and9(
10044
- eq12(runs.projectId, projectId),
10045
- eq12(runs.kind, RunKinds["inspect-sitemap"]),
10046
- inArray5(runs.status, ACTIVE_OR_DONE_STATUSES)
10601
+ eq13(runs.projectId, projectId),
10602
+ eq13(runs.kind, RunKinds["inspect-sitemap"]),
10603
+ inArray6(runs.status, ACTIVE_OR_DONE_STATUSES)
10047
10604
  )
10048
10605
  ).orderBy(desc6(runs.createdAt)).limit(1).get();
10049
10606
  if (recent) {
@@ -10078,7 +10635,7 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
10078
10635
  // src/commoncrawl-sync.ts
10079
10636
  import crypto16 from "crypto";
10080
10637
  import path4 from "path";
10081
- import { and as and10, eq as eq13, sql as sql5 } from "drizzle-orm";
10638
+ import { and as and10, eq as eq14, sql as sql5 } from "drizzle-orm";
10082
10639
  var log11 = createLogger("CommonCrawlSync");
10083
10640
  var INSERT_CHUNK_SIZE = 1e4;
10084
10641
  function defaultDeps2() {
@@ -10113,7 +10670,7 @@ async function executeReleaseSync(db, syncId, opts) {
10113
10670
  phaseDetail: "downloading vertices + edges",
10114
10671
  updatedAt: downloadStartedAt,
10115
10672
  error: null
10116
- }).where(eq13(ccReleaseSyncs.id, syncId)).run();
10673
+ }).where(eq14(ccReleaseSyncs.id, syncId)).run();
10117
10674
  const paths = ccReleasePaths(release);
10118
10675
  const releaseCacheDir = path4.join(deps.cacheDir, release);
10119
10676
  const vertexPath = path4.join(releaseCacheDir, paths.vertexFilename);
@@ -10136,7 +10693,7 @@ async function executeReleaseSync(db, syncId, opts) {
10136
10693
  vertexSha256: vertex.sha256,
10137
10694
  edgesSha256: edges.sha256,
10138
10695
  updatedAt: downloadFinishedAt
10139
- }).where(eq13(ccReleaseSyncs.id, syncId)).run();
10696
+ }).where(eq14(ccReleaseSyncs.id, syncId)).run();
10140
10697
  const allProjects = db.select().from(projects).all();
10141
10698
  const targets = Array.from(new Set(allProjects.map((p) => p.canonicalDomain)));
10142
10699
  let rows = [];
@@ -10152,8 +10709,8 @@ async function executeReleaseSync(db, syncId, opts) {
10152
10709
  }
10153
10710
  const queriedAt = deps.now().toISOString();
10154
10711
  db.transaction((tx) => {
10155
- tx.delete(backlinkDomains).where(eq13(backlinkDomains.releaseSyncId, syncId)).run();
10156
- tx.delete(backlinkSummaries).where(eq13(backlinkSummaries.releaseSyncId, syncId)).run();
10712
+ tx.delete(backlinkDomains).where(eq14(backlinkDomains.releaseSyncId, syncId)).run();
10713
+ tx.delete(backlinkSummaries).where(eq14(backlinkSummaries.releaseSyncId, syncId)).run();
10157
10714
  const expanded = [];
10158
10715
  for (const r of rows) {
10159
10716
  const projectIds = projectsByDomain.get(r.targetDomain);
@@ -10213,7 +10770,7 @@ async function executeReleaseSync(db, syncId, opts) {
10213
10770
  domainsDiscovered: rows.length,
10214
10771
  updatedAt: finishedAt,
10215
10772
  error: null
10216
- }).where(eq13(ccReleaseSyncs.id, syncId)).run();
10773
+ }).where(eq14(ccReleaseSyncs.id, syncId)).run();
10217
10774
  log11.info("sync.completed", {
10218
10775
  syncId,
10219
10776
  release,
@@ -10249,7 +10806,7 @@ async function executeReleaseSync(db, syncId, opts) {
10249
10806
  error: errorMsg,
10250
10807
  phaseDetail: null,
10251
10808
  updatedAt: finishedAt
10252
- }).where(eq13(ccReleaseSyncs.id, syncId)).run();
10809
+ }).where(eq14(ccReleaseSyncs.id, syncId)).run();
10253
10810
  log11.error("sync.failed", { syncId, release, error: errorMsg });
10254
10811
  trackFeatureCompleted({
10255
10812
  ...outcome,
@@ -10282,7 +10839,7 @@ async function syncLatestReleaseOnSchedule(projectName, deps) {
10282
10839
  if (probed === null) report({ status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_FOUND });
10283
10840
  return;
10284
10841
  }
10285
- const alreadySynced = deps.db.select().from(ccReleaseSyncs).where(and10(eq13(ccReleaseSyncs.release, probed.release), eq13(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready))).limit(1).get();
10842
+ const alreadySynced = deps.db.select().from(ccReleaseSyncs).where(and10(eq14(ccReleaseSyncs.release, probed.release), eq14(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready))).limit(1).get();
10286
10843
  if (alreadySynced) {
10287
10844
  deps.log.info({ projectName, release: probed.release }, "Scheduled backlinks sync: already up to date, skipping");
10288
10845
  report({ status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NOT_DUE });
@@ -10315,7 +10872,7 @@ function groupByProject(rows, projectsByDomain) {
10315
10872
  // src/backlink-extract.ts
10316
10873
  import crypto17 from "crypto";
10317
10874
  import fs4 from "fs";
10318
- import { and as and11, desc as desc7, eq as eq14 } from "drizzle-orm";
10875
+ import { and as and11, desc as desc7, eq as eq15 } from "drizzle-orm";
10319
10876
  var log12 = createLogger("BacklinkExtract");
10320
10877
  function defaultDeps3() {
10321
10878
  return {
@@ -10329,14 +10886,14 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
10329
10886
  const startedAt = deps.now().toISOString();
10330
10887
  const reportOutcome = startRunOutcome(db, runId, "backlinks", "extract");
10331
10888
  let refusal;
10332
- db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq14(runs.id, runId)).run();
10889
+ db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq15(runs.id, runId)).run();
10333
10890
  try {
10334
- const project = db.select().from(projects).where(eq14(projects.id, projectId)).get();
10891
+ const project = db.select().from(projects).where(eq15(projects.id, projectId)).get();
10335
10892
  if (!project) {
10336
10893
  refusal = OutcomeReasonCodes.NOT_FOUND;
10337
10894
  throw new Error(`Project not found: ${projectId}`);
10338
10895
  }
10339
- const sync = opts.release ? db.select().from(ccReleaseSyncs).where(eq14(ccReleaseSyncs.release, opts.release)).get() : db.select().from(ccReleaseSyncs).where(eq14(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready)).orderBy(desc7(ccReleaseSyncs.createdAt)).limit(1).get();
10896
+ const sync = opts.release ? db.select().from(ccReleaseSyncs).where(eq15(ccReleaseSyncs.release, opts.release)).get() : db.select().from(ccReleaseSyncs).where(eq15(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready)).orderBy(desc7(ccReleaseSyncs.createdAt)).limit(1).get();
10340
10897
  refusal = OutcomeReasonCodes.NO_DATA;
10341
10898
  if (!sync) {
10342
10899
  throw new Error("No ready release sync available \u2014 run `canonry backlinks sync` first");
@@ -10367,9 +10924,9 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
10367
10924
  db.transaction((tx) => {
10368
10925
  tx.delete(backlinkDomains).where(
10369
10926
  and11(
10370
- eq14(backlinkDomains.projectId, projectId),
10371
- eq14(backlinkDomains.source, BacklinkSources.commoncrawl),
10372
- eq14(backlinkDomains.release, release)
10927
+ eq15(backlinkDomains.projectId, projectId),
10928
+ eq15(backlinkDomains.source, BacklinkSources.commoncrawl),
10929
+ eq15(backlinkDomains.release, release)
10373
10930
  )
10374
10931
  ).run();
10375
10932
  if (rows.length > 0) {
@@ -10412,7 +10969,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
10412
10969
  }).run();
10413
10970
  });
10414
10971
  const finishedAt = deps.now().toISOString();
10415
- db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq14(runs.id, runId)).run();
10972
+ db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq15(runs.id, runId)).run();
10416
10973
  log12.info("extract.completed", { runId, projectId, release, rows: rows.length });
10417
10974
  const summary = computeSummary(rows);
10418
10975
  reportOutcome({ status: OutcomeStatuses.succeeded, counts: { domains: summary.totalLinkingDomains, links: summary.totalHosts } });
@@ -10423,7 +10980,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
10423
10980
  status: RunStatuses.failed,
10424
10981
  error: errorMsg,
10425
10982
  finishedAt
10426
- }).where(eq14(runs.id, runId)).run();
10983
+ }).where(eq15(runs.id, runId)).run();
10427
10984
  log12.error("extract.failed", { runId, projectId, error: errorMsg });
10428
10985
  reportOutcome({ status: OutcomeStatuses.failed, ...outcomeFailure(err, refusal) });
10429
10986
  throw err;
@@ -10435,7 +10992,7 @@ function computeSummary(rows) {
10435
10992
 
10436
10993
  // src/discovery-run.ts
10437
10994
  import crypto18 from "crypto";
10438
- import { and as and12, eq as eq15 } from "drizzle-orm";
10995
+ import { and as and12, eq as eq16 } from "drizzle-orm";
10439
10996
  var log13 = createLogger("DiscoveryRun");
10440
10997
  var DEFAULT_SEED_COUNT = 30;
10441
10998
  var EMBED_RETRY_MAX_RETRIES = 3;
@@ -10478,11 +11035,11 @@ async function executeDiscoveryRun(opts) {
10478
11035
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
10479
11036
  const reportOutcome = startRunOutcome(opts.db, opts.runId, "discovery", "run");
10480
11037
  let notConfigured = false;
10481
- opts.db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq15(runs.id, opts.runId)).run();
11038
+ opts.db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq16(runs.id, opts.runId)).run();
10482
11039
  try {
10483
- const projectRow = opts.db.select().from(projects).where(eq15(projects.id, opts.projectId)).get();
11040
+ const projectRow = opts.db.select().from(projects).where(eq16(projects.id, opts.projectId)).get();
10484
11041
  if (!projectRow) throw new Error(`Project ${opts.projectId} not found`);
10485
- const projectCompetitors = opts.db.select({ domain: competitors.domain }).from(competitors).where(eq15(competitors.projectId, opts.projectId)).orderBy(competitors.domain).all().map((r) => r.domain.toLowerCase());
11042
+ const projectCompetitors = opts.db.select({ domain: competitors.domain }).from(competitors).where(eq16(competitors.projectId, opts.projectId)).orderBy(competitors.domain).all().map((r) => r.domain.toLowerCase());
10486
11043
  const canonicalDomains = effectiveDomains({
10487
11044
  canonicalDomain: projectRow.canonicalDomain,
10488
11045
  ownedDomains: projectRow.ownedDomains
@@ -10524,7 +11081,7 @@ async function executeDiscoveryRun(opts) {
10524
11081
  seedProvider: result.seedProvider,
10525
11082
  result
10526
11083
  });
10527
- opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq15(runs.id, opts.runId)).run();
11084
+ opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq16(runs.id, opts.runId)).run();
10528
11085
  log13.info("discovery.completed", {
10529
11086
  runId: opts.runId,
10530
11087
  sessionId: opts.sessionId,
@@ -10548,7 +11105,7 @@ async function executeDiscoveryRun(opts) {
10548
11105
  status: RunStatuses.failed,
10549
11106
  finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
10550
11107
  error: errorMsg
10551
- }).where(eq15(runs.id, opts.runId)).run();
11108
+ }).where(eq16(runs.id, opts.runId)).run();
10552
11109
  const failure2 = classifyProviderOutcomeError(err);
10553
11110
  reportOutcome({
10554
11111
  status: OutcomeStatuses.failed,
@@ -10818,9 +11375,9 @@ function writeDiscoveryInsight(db, input) {
10818
11375
  });
10819
11376
  db.transaction((tx) => {
10820
11377
  tx.update(insights).set({ dismissed: true }).where(and12(
10821
- eq15(insights.projectId, input.projectId),
10822
- eq15(insights.type, "discovery.basket-divergence"),
10823
- eq15(insights.dismissed, false)
11378
+ eq16(insights.projectId, input.projectId),
11379
+ eq16(insights.type, "discovery.basket-divergence"),
11380
+ eq16(insights.dismissed, false)
10824
11381
  )).run();
10825
11382
  tx.insert(insights).values({
10826
11383
  id: crypto18.randomUUID(),
@@ -10860,7 +11417,7 @@ function buildDiscoveryInsightTitle(input) {
10860
11417
 
10861
11418
  // src/execute-site-audit.ts
10862
11419
  import crypto19 from "crypto";
10863
- import { and as and14, eq as eq17, ne as ne2, sql as sql6 } from "drizzle-orm";
11420
+ import { and as and14, eq as eq18, ne as ne2, sql as sql6 } from "drizzle-orm";
10864
11421
  import { runSiteCrawl } from "@canonry/aeo-audit";
10865
11422
 
10866
11423
  // src/site-audit-root.ts
@@ -11048,7 +11605,7 @@ async function requestPinnedSiteAuditRoot(target, options) {
11048
11605
  }
11049
11606
 
11050
11607
  // src/site-crawl-template-links.ts
11051
- import { and as and13, asc as asc3, eq as eq16, gt as gt2, inArray as inArray6 } from "drizzle-orm";
11608
+ import { and as and13, asc as asc3, eq as eq17, gt as gt2, inArray as inArray7 } from "drizzle-orm";
11052
11609
  var TEMPLATE_LINK_READ_BATCH = 2e3;
11053
11610
  var TEMPLATE_LINK_WRITE_BATCH = 500;
11054
11611
  function placementOccurrencesOf(row) {
@@ -11071,9 +11628,9 @@ function* streamAttemptEdges(db, scope) {
11071
11628
  placementContentOccurrences: siteCrawlEdges.placementContentOccurrences,
11072
11629
  placementUnknownOccurrences: siteCrawlEdges.placementUnknownOccurrences
11073
11630
  }).from(siteCrawlEdges).where(and13(
11074
- eq16(siteCrawlEdges.projectId, scope.projectId),
11075
- eq16(siteCrawlEdges.runId, scope.runId),
11076
- eq16(siteCrawlEdges.attemptId, scope.attemptId),
11631
+ eq17(siteCrawlEdges.projectId, scope.projectId),
11632
+ eq17(siteCrawlEdges.runId, scope.runId),
11633
+ eq17(siteCrawlEdges.attemptId, scope.attemptId),
11077
11634
  gt2(siteCrawlEdges.edgeKey, after)
11078
11635
  )).orderBy(asc3(siteCrawlEdges.edgeKey)).limit(TEMPLATE_LINK_READ_BATCH).all();
11079
11636
  if (rows.length === 0) return;
@@ -11099,9 +11656,9 @@ function writeGroupKey(isTemplate, templateRatio) {
11099
11656
  }
11100
11657
  function classifySiteCrawlTemplateLinks(db, scope, pagesFetched, placementRulesetVersion) {
11101
11658
  const scopeFilter = and13(
11102
- eq16(siteCrawlEdges.projectId, scope.projectId),
11103
- eq16(siteCrawlEdges.runId, scope.runId),
11104
- eq16(siteCrawlEdges.attemptId, scope.attemptId)
11659
+ eq17(siteCrawlEdges.projectId, scope.projectId),
11660
+ eq17(siteCrawlEdges.runId, scope.runId),
11661
+ eq17(siteCrawlEdges.attemptId, scope.attemptId)
11105
11662
  );
11106
11663
  const placementAvailable = templateLinkPlacementAvailable(placementRulesetVersion);
11107
11664
  const ubiquityAvailable = templateLinkUbiquityAvailable(pagesFetched);
@@ -11136,7 +11693,7 @@ function classifySiteCrawlTemplateLinks(db, scope, pagesFetched, placementRulese
11136
11693
  const now = (/* @__PURE__ */ new Date()).toISOString();
11137
11694
  for (const group of edgeKeysByValue.values()) {
11138
11695
  for (const chunk of chunked(group.edgeKeys)) {
11139
- db.update(siteCrawlEdges).set({ isTemplate: group.isTemplate, templateRatio: group.templateRatio, updatedAt: now }).where(and13(scopeFilter, inArray6(siteCrawlEdges.edgeKey, chunk))).run();
11696
+ db.update(siteCrawlEdges).set({ isTemplate: group.isTemplate, templateRatio: group.templateRatio, updatedAt: now }).where(and13(scopeFilter, inArray7(siteCrawlEdges.edgeKey, chunk))).run();
11140
11697
  }
11141
11698
  }
11142
11699
  return {
@@ -11147,7 +11704,7 @@ function classifySiteCrawlTemplateLinks(db, scope, pagesFetched, placementRulese
11147
11704
  }
11148
11705
 
11149
11706
  // src/site-audit-issues.ts
11150
- import { createHash as createHash4 } from "crypto";
11707
+ import { createHash as createHash5 } from "crypto";
11151
11708
  var GROUP_IDENTITY_VERSION = "duplicate-metadata-v1";
11152
11709
  function buildSiteCrawlIssueEvidence(siteIssues, pages) {
11153
11710
  if (siteIssues === void 0) return null;
@@ -11164,7 +11721,7 @@ function buildSiteCrawlIssueEvidence(siteIssues, pages) {
11164
11721
  const field = issue.code === "site.duplicate-title" ? "pageTitle" : issue.code === "site.duplicate-meta-description" ? "metaDescription" : null;
11165
11722
  const values = field ? affectedUrls.map((url) => metadataByUrl.get(url)?.[field]?.trim()) : [];
11166
11723
  const value = values[0];
11167
- const key = value && values.every((candidate) => candidate === value) ? `site-issue:${createHash4("sha256").update(JSON.stringify([GROUP_IDENTITY_VERSION, issue.code, value])).digest("hex")}` : null;
11724
+ const key = value && values.every((candidate) => candidate === value) ? `site-issue:${createHash5("sha256").update(JSON.stringify([GROUP_IDENTITY_VERSION, issue.code, value])).digest("hex")}` : null;
11168
11725
  return { key, code: issue.code, message: issue.message, affectedUrls };
11169
11726
  });
11170
11727
  groups.sort((left, right) => left.code.localeCompare(right.code) || (left.key ?? "").localeCompare(right.key ?? "") || JSON.stringify(left.affectedUrls).localeCompare(JSON.stringify(right.affectedUrls)));
@@ -11316,7 +11873,7 @@ function trackSiteAuditOutcome(db, input) {
11316
11873
  );
11317
11874
  const pagesAudited = input.crawl?.pagesAudited ?? 0;
11318
11875
  if (pagesAudited === 0 || input.trigger === RunTriggers.probe) return;
11319
- const prior = db.select({ id: siteAuditSnapshots.id }).from(siteAuditSnapshots).where(and14(eq17(siteAuditSnapshots.projectId, input.projectId), ne2(siteAuditSnapshots.runId, input.runId))).limit(1).get();
11876
+ const prior = db.select({ id: siteAuditSnapshots.id }).from(siteAuditSnapshots).where(and14(eq18(siteAuditSnapshots.projectId, input.projectId), ne2(siteAuditSnapshots.runId, input.runId))).limit(1).get();
11320
11877
  if (prior) return;
11321
11878
  trackEvent("activation.completed", {
11322
11879
  flowVersion: ONBOARDING_FLOW_VERSION,
@@ -11330,12 +11887,12 @@ function trackSiteAuditOutcome(db, input) {
11330
11887
  }
11331
11888
  async function executeSiteAudit(db, runId, projectId, opts = {}) {
11332
11889
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
11333
- const claim = db.update(runs).set({ status: "running", startedAt }).where(and14(eq17(runs.id, runId), eq17(runs.projectId, projectId), eq17(runs.status, "queued"))).run();
11890
+ const claim = db.update(runs).set({ status: "running", startedAt }).where(and14(eq18(runs.id, runId), eq18(runs.projectId, projectId), eq18(runs.status, "queued"))).run();
11334
11891
  if (claim.changes === 0) return;
11335
11892
  const startTime = Date.now();
11336
- const trigger = db.select({ trigger: runs.trigger }).from(runs).where(eq17(runs.id, runId)).get()?.trigger ?? null;
11893
+ const trigger = db.select({ trigger: runs.trigger }).from(runs).where(eq18(runs.id, runId)).get()?.trigger ?? null;
11337
11894
  let canonicalDomain = null;
11338
- const attemptNumber = (db.select({ value: sql6`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(eq17(siteCrawlAttempts.runId, runId)).get()?.value ?? 0) + 1;
11895
+ const attemptNumber = (db.select({ value: sql6`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(eq18(siteCrawlAttempts.runId, runId)).get()?.value ?? 0) + 1;
11339
11896
  const attemptId = crypto19.randomUUID();
11340
11897
  db.insert(siteCrawlAttempts).values({
11341
11898
  id: attemptId,
@@ -11370,22 +11927,22 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11370
11927
  const nodeKey = nodeKeyByUrl.get(url);
11371
11928
  if (!nodeKey) continue;
11372
11929
  const scope = [
11373
- eq17(siteCrawlEdges.projectId, projectId),
11374
- eq17(siteCrawlEdges.runId, runId),
11375
- eq17(siteCrawlEdges.attemptId, attemptId)
11930
+ eq18(siteCrawlEdges.projectId, projectId),
11931
+ eq18(siteCrawlEdges.runId, runId),
11932
+ eq18(siteCrawlEdges.attemptId, attemptId)
11376
11933
  ];
11377
11934
  tx.update(siteCrawlEdges).set({ sourceNodeKey: nodeKey, updatedAt: now }).where(and14(
11378
11935
  ...scope,
11379
- eq17(siteCrawlEdges.sourceUrl, url)
11936
+ eq18(siteCrawlEdges.sourceUrl, url)
11380
11937
  )).run();
11381
11938
  tx.update(siteCrawlEdges).set({ targetNodeKey: nodeKey, updatedAt: now }).where(and14(
11382
11939
  ...scope,
11383
- eq17(siteCrawlEdges.targetUrl, url)
11940
+ eq18(siteCrawlEdges.targetUrl, url)
11384
11941
  )).run();
11385
11942
  const pageScope = [
11386
- eq17(siteCrawlPages.projectId, projectId),
11387
- eq17(siteCrawlPages.runId, runId),
11388
- eq17(siteCrawlPages.attemptId, attemptId)
11943
+ eq18(siteCrawlPages.projectId, projectId),
11944
+ eq18(siteCrawlPages.runId, runId),
11945
+ eq18(siteCrawlPages.attemptId, attemptId)
11389
11946
  ];
11390
11947
  const canonicalTargets = tx.select({
11391
11948
  id: siteCrawlPages.id,
@@ -11393,13 +11950,13 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11393
11950
  fetchState: siteCrawlPages.fetchState,
11394
11951
  indexabilityState: siteCrawlPages.indexabilityState,
11395
11952
  indexabilityReasons: siteCrawlPages.indexabilityReasons
11396
- }).from(siteCrawlPages).where(and14(...pageScope, eq17(siteCrawlPages.canonicalUrl, url))).all();
11953
+ }).from(siteCrawlPages).where(and14(...pageScope, eq18(siteCrawlPages.canonicalUrl, url))).all();
11397
11954
  for (const target of canonicalTargets) {
11398
11955
  tx.update(siteCrawlPages).set({
11399
11956
  canonicalNodeKey: nodeKey,
11400
11957
  healthState: deriveSiteHealthState({ ...target, canonicalNodeKey: nodeKey }),
11401
11958
  updatedAt: now
11402
- }).where(eq17(siteCrawlPages.id, target.id)).run();
11959
+ }).where(eq18(siteCrawlPages.id, target.id)).run();
11403
11960
  }
11404
11961
  }
11405
11962
  };
@@ -11556,19 +12113,19 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11556
12113
  linkScoreNormalized: metrics.linkScore,
11557
12114
  updatedAt: now
11558
12115
  }).where(and14(
11559
- eq17(siteCrawlPages.projectId, projectId),
11560
- eq17(siteCrawlPages.runId, runId),
11561
- eq17(siteCrawlPages.attemptId, attemptId),
11562
- eq17(siteCrawlPages.nodeKey, key)
12116
+ eq18(siteCrawlPages.projectId, projectId),
12117
+ eq18(siteCrawlPages.runId, runId),
12118
+ eq18(siteCrawlPages.attemptId, attemptId),
12119
+ eq18(siteCrawlPages.nodeKey, key)
11563
12120
  )).run();
11564
12121
  };
11565
12122
  const persistEvent = async (event) => {
11566
12123
  const now = (/* @__PURE__ */ new Date()).toISOString();
11567
12124
  db.transaction((tx) => {
11568
12125
  const receipt = tx.select({ checksum: siteCrawlEventReceipts.checksum }).from(siteCrawlEventReceipts).where(and14(
11569
- eq17(siteCrawlEventReceipts.attemptId, attemptId),
11570
- eq17(siteCrawlEventReceipts.sequence, event.sequence),
11571
- eq17(siteCrawlEventReceipts.batchId, event.batchId)
12126
+ eq18(siteCrawlEventReceipts.attemptId, attemptId),
12127
+ eq18(siteCrawlEventReceipts.sequence, event.sequence),
12128
+ eq18(siteCrawlEventReceipts.batchId, event.batchId)
11572
12129
  )).get();
11573
12130
  if (receipt) {
11574
12131
  if (receipt.checksum !== event.checksum) {
@@ -11601,18 +12158,18 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11601
12158
  pagesErrored: event.type === "summary" ? observedErrorCount(observedPages.values()) : sql6`${siteCrawlAttempts.pagesErrored}`,
11602
12159
  edgesDiscovered: progress.edgesObserved,
11603
12160
  updatedAt: now
11604
- }).where(eq17(siteCrawlAttempts.id, attemptId)).run();
12161
+ }).where(eq18(siteCrawlAttempts.id, attemptId)).run();
11605
12162
  } else {
11606
12163
  tx.update(siteCrawlAttempts).set({
11607
12164
  lastEventSequence: event.sequence,
11608
12165
  lastEventChecksum: event.checksum,
11609
12166
  updatedAt: now
11610
- }).where(eq17(siteCrawlAttempts.id, attemptId)).run();
12167
+ }).where(eq18(siteCrawlAttempts.id, attemptId)).run();
11611
12168
  }
11612
12169
  });
11613
12170
  };
11614
12171
  try {
11615
- const project = db.select().from(projects).where(eq17(projects.id, projectId)).get();
12172
+ const project = db.select().from(projects).where(eq18(projects.id, projectId)).get();
11616
12173
  if (!project) throw new Error(`Project not found: ${projectId}`);
11617
12174
  canonicalDomain = project.canonicalDomain;
11618
12175
  const homepageUrl = toHomepageUrl(project.canonicalDomain);
@@ -11712,7 +12269,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11712
12269
  }
11713
12270
  }
11714
12271
  const published = db.transaction((tx) => {
11715
- const claim2 = tx.update(runs).set({ status: terminalStatus, finishedAt }).where(and14(eq17(runs.id, runId), eq17(runs.status, "running"))).run();
12272
+ const claim2 = tx.update(runs).set({ status: terminalStatus, finishedAt }).where(and14(eq18(runs.id, runId), eq18(runs.status, "running"))).run();
11716
12273
  if (claim2.changes === 0) return false;
11717
12274
  if (hasAuditedPages) {
11718
12275
  tx.insert(siteAuditSnapshots).values({
@@ -11822,7 +12379,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11822
12379
  edgesDiscovered: crawlSummary.edgesObserved,
11823
12380
  finishedAt,
11824
12381
  updatedAt: finishedAt
11825
- }).where(eq17(siteCrawlAttempts.id, attemptId)).run();
12382
+ }).where(eq18(siteCrawlAttempts.id, attemptId)).run();
11826
12383
  return true;
11827
12384
  });
11828
12385
  if (!published) {
@@ -11835,7 +12392,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11835
12392
  error: describeError(cleanupError)
11836
12393
  });
11837
12394
  }
11838
- const current = db.select({ status: runs.status }).from(runs).where(eq17(runs.id, runId)).get();
12395
+ const current = db.select({ status: runs.status }).from(runs).where(eq18(runs.id, runId)).get();
11839
12396
  if (current?.status === "cancelled") throw new SiteAuditCancelledError(`Site audit cancelled before publication: ${runId}`);
11840
12397
  throw new Error(`Site audit run was no longer running before publication: ${runId}`);
11841
12398
  }
@@ -11870,12 +12427,12 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
11870
12427
  error: message,
11871
12428
  finishedAt,
11872
12429
  updatedAt: finishedAt
11873
- }).where(eq17(siteCrawlAttempts.id, attemptId)).run();
12430
+ }).where(eq18(siteCrawlAttempts.id, attemptId)).run();
11874
12431
  tx.update(runs).set({
11875
12432
  status: cancelled ? "cancelled" : "failed",
11876
12433
  error: message,
11877
12434
  finishedAt
11878
- }).where(and14(eq17(runs.id, runId), eq17(runs.status, "running"))).run();
12435
+ }).where(and14(eq18(runs.id, runId), eq18(runs.status, "running"))).run();
11879
12436
  });
11880
12437
  log14.error("failed", { runId, projectId, cancelled, error: message });
11881
12438
  trackSiteAuditOutcome(db, {
@@ -12073,7 +12630,7 @@ function derivedRouteAdapter(adapter, route) {
12073
12630
  }
12074
12631
 
12075
12632
  // src/install-state-telemetry.ts
12076
- import { and as and15, count as count2, eq as eq18, gte as gte2, inArray as inArray7, isNotNull as isNotNull2, isNull as isNull2, ne as ne3, sql as sql7 } from "drizzle-orm";
12633
+ import { and as and15, count as count3, eq as eq19, gte as gte2, inArray as inArray8, isNotNull as isNotNull2, isNull as isNull2, ne as ne3, sql as sql7 } from "drizzle-orm";
12077
12634
  var log16 = createLogger("InstallStateTelemetry");
12078
12635
  var INSTALL_STATE_FIRST_DELAY_MS = 5 * 6e4;
12079
12636
  var INSTALL_STATE_INTERVAL_MS = 24 * 60 * 6e4;
@@ -12096,31 +12653,31 @@ function buildInstallState(sources, now, startedAt) {
12096
12653
  const since = new Date(now - INSTALL_STATE_INTERVAL_MS).toISOString();
12097
12654
  const projectIds = db.select({ id: projects.id }).from(projects);
12098
12655
  const total = (query) => whole(query.get()?.value);
12099
- const googleByType = new Map(db.select({ type: googleConnections.connectionType, value: count2() }).from(googleConnections).groupBy(googleConnections.connectionType).all().map((row) => [row.type, whole(row.value)]));
12100
- const gaServiceAccounts = total(db.select({ value: count2() }).from(gaConnections));
12101
- const trafficByType = db.select({ type: trafficSources.sourceType, value: count2() }).from(trafficSources).where(and15(isNull2(trafficSources.archivedAt), ne3(trafficSources.status, TrafficSourceStatuses.archived))).groupBy(trafficSources.sourceType).all();
12102
- const webhookSources = db.select({ config: notifications.config }).from(notifications).where(eq18(notifications.enabled, true)).all().map((row) => row.config.source);
12656
+ const googleByType = new Map(db.select({ type: googleConnections.connectionType, value: count3() }).from(googleConnections).groupBy(googleConnections.connectionType).all().map((row) => [row.type, whole(row.value)]));
12657
+ const gaServiceAccounts = total(db.select({ value: count3() }).from(gaConnections));
12658
+ const trafficByType = db.select({ type: trafficSources.sourceType, value: count3() }).from(trafficSources).where(and15(isNull2(trafficSources.archivedAt), ne3(trafficSources.status, TrafficSourceStatuses.archived))).groupBy(trafficSources.sourceType).all();
12659
+ const webhookSources = db.select({ config: notifications.config }).from(notifications).where(eq19(notifications.enabled, true)).all().map((row) => row.config.source);
12103
12660
  const agentWebhooks = webhookSources.filter((source) => source === AGENT_WEBHOOK_SOURCE).length;
12104
12661
  const webhooks = webhookSources.length - agentWebhooks;
12105
- const bing = total(db.select({ value: count2() }).from(bingConnections));
12106
- const openAiAds = total(db.select({ value: count2() }).from(adsConnections));
12107
- const googleAdsConnected = total(db.select({ value: count2() }).from(googleAdsConnections));
12108
- const backlinkSources = total(db.select({ value: count2() }).from(
12662
+ const bing = total(db.select({ value: count3() }).from(bingConnections));
12663
+ const openAiAds = total(db.select({ value: count3() }).from(adsConnections));
12664
+ const googleAdsConnected = total(db.select({ value: count3() }).from(googleAdsConnections));
12665
+ const backlinkSources = total(db.select({ value: count3() }).from(
12109
12666
  db.selectDistinct({ projectId: backlinkSummaries.projectId, source: backlinkSummaries.source }).from(backlinkSummaries).as("backlink_sources")
12110
12667
  ));
12111
12668
  const counts = {
12112
- projects: total(db.select({ value: count2() }).from(projects)),
12113
- queries: total(db.select({ value: count2() }).from(queries)),
12114
- competitors: total(db.select({ value: count2() }).from(competitors)),
12669
+ projects: total(db.select({ value: count3() }).from(projects)),
12670
+ queries: total(db.select({ value: count3() }).from(queries)),
12671
+ competitors: total(db.select({ value: count3() }).from(competitors)),
12115
12672
  locations: total(db.select({ value: sql7`coalesce(sum(json_array_length(${projects.locations})), 0)` }).from(projects)),
12116
- schedules: total(db.select({ value: count2() }).from(schedules).where(eq18(schedules.enabled, true))),
12673
+ schedules: total(db.select({ value: count3() }).from(schedules).where(eq19(schedules.enabled, true))),
12117
12674
  webhooks,
12118
12675
  agentWebhooks,
12119
12676
  trafficSources: trafficByType.reduce((sum, row) => sum + whole(row.value), 0),
12120
12677
  googleConnections: [...googleByType.values()].reduce((sum, value) => sum + value, 0) + gaServiceAccounts,
12121
12678
  bingConnections: bing,
12122
12679
  backlinkSources,
12123
- adsAccounts: openAiAds + total(db.select({ value: count2() }).from(googleAdsConnections).where(isNotNull2(googleAdsConnections.selectedCustomerId)))
12680
+ adsAccounts: openAiAds + total(db.select({ value: count3() }).from(googleAdsConnections).where(isNotNull2(googleAdsConnections.selectedCustomerId)))
12124
12681
  };
12125
12682
  const connected = /* @__PURE__ */ new Set();
12126
12683
  if ((googleByType.get("gsc") ?? 0) > 0) connected.add(IntegrationNames.gsc);
@@ -12128,7 +12685,7 @@ function buildInstallState(sources, now, startedAt) {
12128
12685
  if ((googleByType.get("gbp") ?? 0) > 0) connected.add(IntegrationNames.gbp);
12129
12686
  if (bing > 0) connected.add(IntegrationNames.bing);
12130
12687
  if (googleAdsConnected > 0) connected.add(IntegrationNames.google_ads);
12131
- if (total(db.select({ value: count2() }).from(gtmConnections)) > 0) connected.add(IntegrationNames.gtm);
12688
+ if (total(db.select({ value: count3() }).from(gtmConnections)) > 0) connected.add(IntegrationNames.gtm);
12132
12689
  if (openAiAds > 0) connected.add(IntegrationNames.openai_ads);
12133
12690
  for (const row of trafficByType) {
12134
12691
  const integration = TRAFFIC_INTEGRATIONS[row.type];
@@ -12149,7 +12706,7 @@ function buildInstallState(sources, now, startedAt) {
12149
12706
  const usagePath = (field) => sql7`json_extract(${querySnapshots.usage}, ${`$.${field}`})`;
12150
12707
  const answers = db.select({
12151
12708
  provider: querySnapshots.provider,
12152
- answers: count2(),
12709
+ answers: count3(),
12153
12710
  measured: sql7`sum(case when ${usagePath("inputTokens")} is not null then 1 else 0 end)`,
12154
12711
  unpriced: sql7`sum(case when ${usagePath("inputTokens")} is not null and ${usagePath("estimatedCostMicros")} is null then 1 else 0 end)`,
12155
12712
  inputTokens: sql7`coalesce(sum(${usagePath("inputTokens")}), 0)`,
@@ -12157,14 +12714,14 @@ function buildInstallState(sources, now, startedAt) {
12157
12714
  costMicros: sql7`coalesce(sum(${usagePath("estimatedCostMicros")}), 0)`
12158
12715
  }).from(querySnapshots).where(gte2(querySnapshots.createdAt, since)).groupBy(sql7`+${querySnapshots.provider}`).all();
12159
12716
  for (const row of answers) addCalls(row.provider, whole(row.answers));
12160
- for (const row of db.select({ provider: researchRuns.provider, answered: sql7`coalesce(sum(${researchRuns.completedQueries}), 0)` }).from(researchRuns).where(and15(inArray7(researchRuns.projectId, projectIds), gte2(researchRuns.createdAt, since))).groupBy(researchRuns.provider).all()) {
12717
+ for (const row of db.select({ provider: researchRuns.provider, answered: sql7`coalesce(sum(${researchRuns.completedQueries}), 0)` }).from(researchRuns).where(and15(inArray8(researchRuns.projectId, projectIds), gte2(researchRuns.createdAt, since))).groupBy(researchRuns.provider).all()) {
12161
12718
  addCalls(row.provider, whole(row.answered));
12162
12719
  }
12163
12720
  for (const session of db.select({
12164
12721
  seedProviders: discoverySessions.seedProviders,
12165
12722
  seedCountRaw: discoverySessions.seedCountRaw,
12166
12723
  probeCount: discoverySessions.probeCount
12167
- }).from(discoverySessions).where(and15(inArray7(discoverySessions.projectId, projectIds), gte2(discoverySessions.createdAt, since))).all()) {
12724
+ }).from(discoverySessions).where(and15(inArray8(discoverySessions.projectId, projectIds), gte2(discoverySessions.createdAt, since))).all()) {
12168
12725
  if (session.seedCountRaw !== null) {
12169
12726
  for (const provider of session.seedProviders?.length ? session.seedProviders : [ProviderNames.gemini]) addCalls(provider, 1);
12170
12727
  }
@@ -12173,15 +12730,15 @@ function buildInstallState(sources, now, startedAt) {
12173
12730
  const answered = answers.reduce((sum, row) => sum + whole(row.answers), 0);
12174
12731
  const measured = answers.reduce((sum, row) => sum + whole(row.measured), 0);
12175
12732
  const usage24h = {
12176
- sweeps: total(db.select({ value: count2() }).from(runs).where(and15(
12177
- inArray7(runs.projectId, projectIds),
12178
- eq18(runs.kind, RunKinds["answer-visibility"]),
12733
+ sweeps: total(db.select({ value: count3() }).from(runs).where(and15(
12734
+ inArray8(runs.projectId, projectIds),
12735
+ eq19(runs.kind, RunKinds["answer-visibility"]),
12179
12736
  gte2(runs.createdAt, since),
12180
12737
  ne3(runs.trigger, RunTriggers.probe)
12181
12738
  ))),
12182
- audits: total(db.select({ value: count2() }).from(runs).where(and15(
12183
- inArray7(runs.projectId, projectIds),
12184
- eq18(runs.kind, RunKinds["site-audit"]),
12739
+ audits: total(db.select({ value: count3() }).from(runs).where(and15(
12740
+ inArray8(runs.projectId, projectIds),
12741
+ eq19(runs.kind, RunKinds["site-audit"]),
12185
12742
  gte2(runs.createdAt, since)
12186
12743
  ))),
12187
12744
  providerCalls: [...providerCalls.values()].reduce((sum, calls) => sum + calls, 0)
@@ -12194,18 +12751,18 @@ function buildInstallState(sources, now, startedAt) {
12194
12751
  }
12195
12752
  }
12196
12753
  const aero = db.select({
12197
- calls: count2(),
12754
+ calls: count3(),
12198
12755
  inputTokens: sql7`coalesce(sum(${llmUsageEvents.inputTokens}), 0)`,
12199
12756
  outputTokens: sql7`coalesce(sum(${llmUsageEvents.outputTokens}), 0)`,
12200
12757
  costMillicents: sql7`coalesce(sum(${llmUsageEvents.costMillicents}), 0)`
12201
- }).from(llmUsageEvents).where(and15(eq18(llmUsageEvents.feature, AeroLlmUsageFeatures.turn), gte2(llmUsageEvents.createdAt, since))).get();
12758
+ }).from(llmUsageEvents).where(and15(eq19(llmUsageEvents.feature, AeroLlmUsageFeatures.turn), gte2(llmUsageEvents.createdAt, since))).get();
12202
12759
  const aeroCalls = whole(aero?.calls);
12203
12760
  usage24h.aeroModelCalls = aeroCalls;
12204
12761
  usage24h.aeroInputTokens = whole(aero?.inputTokens);
12205
12762
  usage24h.aeroOutputTokens = whole(aero?.outputTokens);
12206
12763
  const aeroMillicents = whole(aero?.costMillicents);
12207
12764
  if (aeroCalls === 0 || aeroMillicents > 0) usage24h.aeroCostMicros = aeroMillicents * 10;
12208
- usage24h.webhookDeliveries = total(db.select({ value: count2() }).from(auditLog).where(and15(gte2(auditLog.createdAt, since), eq18(auditLog.action, WEBHOOK_DELIVERED_ACTION))));
12765
+ usage24h.webhookDeliveries = total(db.select({ value: count3() }).from(auditLog).where(and15(gte2(auditLog.createdAt, since), eq19(auditLog.action, WEBHOOK_DELIVERED_ACTION))));
12209
12766
  const providerCalls24h = Object.fromEntries(PROVIDER_NAMES.flatMap((name) => providerCalls.has(name) ? [[name, providerCalls.get(name)]] : []));
12210
12767
  return {
12211
12768
  providers: registeredProviderNames(config).filter((name) => KNOWN_PROVIDERS2.has(name)),
@@ -12335,7 +12892,7 @@ function configuredProviderEntries(config, apiAdapters, cdpAdapter) {
12335
12892
 
12336
12893
  // src/provider-reload-batch-guard.ts
12337
12894
  import { isDeepStrictEqual } from "util";
12338
- import { and as and16, inArray as inArray8 } from "drizzle-orm";
12895
+ import { and as and16, inArray as inArray9 } from "drizzle-orm";
12339
12896
  function pendingBatchIdentity(provider) {
12340
12897
  const { quotaPolicy: _quotaPolicy, ...identity } = resolveRegistration(provider.adapter, provider.config).config;
12341
12898
  return identity;
@@ -12350,8 +12907,8 @@ function assertProviderReloadKeepsPendingBatches(db, previous, next, executing =
12350
12907
  const active = executing.filter((snapshot) => changedRegistration(snapshot.registration));
12351
12908
  if (changed.length === 0 && active.length === 0) return;
12352
12909
  const pending = changed.length === 0 ? [] : db.select({ id: providerBatches.id, provider: providerBatches.provider, runId: providerBatches.runId }).from(providerBatches).where(and16(
12353
- inArray8(providerBatches.provider, changed),
12354
- inArray8(providerBatches.status, [ProviderBatchStatuses.submitting, ProviderBatchStatuses.submitted, ProviderBatchStatuses.ended])
12910
+ inArray9(providerBatches.provider, changed),
12911
+ inArray9(providerBatches.status, [ProviderBatchStatuses.submitting, ProviderBatchStatuses.submitted, ProviderBatchStatuses.ended])
12355
12912
  )).all();
12356
12913
  if (pending.length === 0 && active.length === 0) return;
12357
12914
  throw operationInProgress("Changes to provider credentials or execution settings must wait for outstanding batch work to settle.", {
@@ -12362,7 +12919,7 @@ function assertProviderReloadKeepsPendingBatches(db, previous, next, executing =
12362
12919
  }
12363
12920
 
12364
12921
  // src/provider-model-catalog.ts
12365
- import { createHash as createHash5 } from "crypto";
12922
+ import { createHash as createHash6 } from "crypto";
12366
12923
  var TTL_MS = 60 * 60 * 1e3;
12367
12924
  var RETRY_MS = 60 * 1e3;
12368
12925
  var TIMEOUT_MS2 = 3e3;
@@ -12376,7 +12933,7 @@ function createProviderModelCatalog(registry) {
12376
12933
  }
12377
12934
  const fallback = provider.adapter.modelRegistry.knownModels;
12378
12935
  if (!provider.adapter.listModels) return fallback;
12379
- const identity = createHash5("sha256").update(JSON.stringify(provider.config)).digest("hex");
12936
+ const identity = createHash6("sha256").update(JSON.stringify(provider.config)).digest("hex");
12380
12937
  let entry = cache.get(name);
12381
12938
  if (entry?.identity !== identity) {
12382
12939
  entry = { identity, expiresAt: 0 };
@@ -12415,7 +12972,7 @@ function createProviderModelCatalog(registry) {
12415
12972
  const provider = registry.get(name) ?? unregistered?.();
12416
12973
  if (!provider) return [];
12417
12974
  const entry = cache.get(name);
12418
- const identity = createHash5("sha256").update(JSON.stringify(provider.config)).digest("hex");
12975
+ const identity = createHash6("sha256").update(JSON.stringify(provider.config)).digest("hex");
12419
12976
  return (entry?.identity === identity ? entry.models : void 0) ?? provider.adapter.modelRegistry.knownModels;
12420
12977
  };
12421
12978
  return Object.assign((name) => read(name), {
@@ -12431,7 +12988,7 @@ function createProviderModelCatalog(registry) {
12431
12988
  // src/scheduler.ts
12432
12989
  import crypto20 from "crypto";
12433
12990
  import cron from "node-cron";
12434
- import { and as and17, eq as eq19, inArray as inArray9, notExists, sql as sql8 } from "drizzle-orm";
12991
+ import { and as and17, eq as eq20, inArray as inArray10, notExists, sql as sql8 } from "drizzle-orm";
12435
12992
  var log17 = createLogger("Scheduler");
12436
12993
  var SLOT_FIRED = { status: OutcomeStatuses.succeeded };
12437
12994
  var slotSkipped = (reasonCode) => ({ status: OutcomeStatuses.skipped, reasonCode });
@@ -12488,8 +13045,8 @@ var Scheduler = class {
12488
13045
  ensureHealthSchedules() {
12489
13046
  const projectsWithoutHealth = this.db.select({ id: projects.id }).from(projects).where(notExists(
12490
13047
  this.db.select({ one: sql8`1` }).from(schedules).where(and17(
12491
- eq19(schedules.projectId, projects.id),
12492
- eq19(schedules.kind, SchedulableRunKinds.doctor)
13048
+ eq20(schedules.projectId, projects.id),
13049
+ eq20(schedules.kind, SchedulableRunKinds.doctor)
12493
13050
  ))
12494
13051
  )).all();
12495
13052
  if (projectsWithoutHealth.length === 0) return;
@@ -12532,7 +13089,7 @@ var Scheduler = class {
12532
13089
  start() {
12533
13090
  this.ensureHealthSchedules();
12534
13091
  this.ensureQueryBaskets();
12535
- const allSchedules = this.db.select().from(schedules).where(eq19(schedules.enabled, true)).all();
13092
+ const allSchedules = this.db.select().from(schedules).where(eq20(schedules.enabled, true)).all();
12536
13093
  for (const schedule of allSchedules) {
12537
13094
  const missedRunAt = schedule.nextRunAt;
12538
13095
  const recurrence = scheduleRecurrence(schedule);
@@ -12566,7 +13123,7 @@ var Scheduler = class {
12566
13123
  this.stopTask(key, existing, "Stopped");
12567
13124
  this.tasks.delete(key);
12568
13125
  }
12569
- const schedule = this.db.select().from(schedules).where(and17(eq19(schedules.projectId, projectId), eq19(schedules.kind, kind))).get();
13126
+ const schedule = this.db.select().from(schedules).where(and17(eq20(schedules.projectId, projectId), eq20(schedules.kind, kind))).get();
12570
13127
  if (schedule && schedule.enabled) {
12571
13128
  this.registerCronTask(schedule);
12572
13129
  }
@@ -12594,12 +13151,12 @@ var Scheduler = class {
12594
13151
  /** Runtime timing writes must not restore a version already issued to a settings caller. */
12595
13152
  updateScheduleTiming(scheduleId, timing) {
12596
13153
  this.db.transaction((tx) => {
12597
- const current = tx.select({ updatedAt: schedules.updatedAt }).from(schedules).where(eq19(schedules.id, scheduleId)).get();
13154
+ const current = tx.select({ updatedAt: schedules.updatedAt }).from(schedules).where(eq20(schedules.id, scheduleId)).get();
12598
13155
  if (!current) return;
12599
13156
  tx.update(schedules).set({
12600
13157
  ...timing,
12601
13158
  updatedAt: nextScheduleUpdatedAt(current.updatedAt)
12602
- }).where(eq19(schedules.id, scheduleId)).run();
13159
+ }).where(eq20(schedules.id, scheduleId)).run();
12603
13160
  });
12604
13161
  }
12605
13162
  registerCronTask(schedule, options = {}) {
@@ -12660,7 +13217,7 @@ var Scheduler = class {
12660
13217
  };
12661
13218
  const tick = () => {
12662
13219
  if (stopped) return;
12663
- const current = this.db.select().from(schedules).where(eq19(schedules.id, scheduleId)).get();
13220
+ const current = this.db.select().from(schedules).where(eq20(schedules.id, scheduleId)).get();
12664
13221
  if (!current || !current.enabled || !scheduleRecurrence(current)) {
12665
13222
  this.remove(projectId, kind);
12666
13223
  return;
@@ -12678,7 +13235,7 @@ var Scheduler = class {
12678
13235
  this.triggerRun(scheduleId, projectId, kind);
12679
13236
  }
12680
13237
  }
12681
- arm(this.db.select({ nextRunAt: schedules.nextRunAt }).from(schedules).where(eq19(schedules.id, scheduleId)).get()?.nextRunAt);
13238
+ arm(this.db.select({ nextRunAt: schedules.nextRunAt }).from(schedules).where(eq20(schedules.id, scheduleId)).get()?.nextRunAt);
12682
13239
  };
12683
13240
  this.tasks.set(key, task);
12684
13241
  let registeredNextRunAt = schedule.nextRunAt;
@@ -12693,7 +13250,7 @@ var Scheduler = class {
12693
13250
  /** Atomically advance a due callback-only calendar occurrence before dispatch. */
12694
13251
  claimCalendarOccurrence(schedule, dueAt, now) {
12695
13252
  return this.db.transaction((tx) => {
12696
- const current = tx.select().from(schedules).where(eq19(schedules.id, schedule.id)).get();
13253
+ const current = tx.select().from(schedules).where(eq20(schedules.id, schedule.id)).get();
12697
13254
  if (!current || !current.enabled || current.updatedAt !== schedule.updatedAt || current.nextRunAt !== dueAt) return false;
12698
13255
  const recurrence = scheduleRecurrence(current);
12699
13256
  if (!recurrence) return false;
@@ -12703,10 +13260,10 @@ var Scheduler = class {
12703
13260
  nextRunAt,
12704
13261
  updatedAt: nextScheduleUpdatedAt(current.updatedAt)
12705
13262
  }).where(and17(
12706
- eq19(schedules.id, current.id),
12707
- eq19(schedules.enabled, true),
12708
- eq19(schedules.nextRunAt, dueAt),
12709
- eq19(schedules.updatedAt, schedule.updatedAt)
13263
+ eq20(schedules.id, current.id),
13264
+ eq20(schedules.enabled, true),
13265
+ eq20(schedules.nextRunAt, dueAt),
13266
+ eq20(schedules.updatedAt, schedule.updatedAt)
12710
13267
  )).run();
12711
13268
  return result.changes === 1;
12712
13269
  });
@@ -12728,7 +13285,7 @@ var Scheduler = class {
12728
13285
  fireSlot(scheduleId, projectId, kind, claimedOccurrence) {
12729
13286
  try {
12730
13287
  const now = (/* @__PURE__ */ new Date()).toISOString();
12731
- const currentSchedule = this.db.select().from(schedules).where(eq19(schedules.id, scheduleId)).get();
13288
+ const currentSchedule = this.db.select().from(schedules).where(eq20(schedules.id, scheduleId)).get();
12732
13289
  if (!currentSchedule || !currentSchedule.enabled) {
12733
13290
  log17.warn("schedule.stale", { scheduleId, projectId, kind, msg: "schedule no longer exists or is disabled" });
12734
13291
  this.remove(projectId, kind);
@@ -12744,7 +13301,7 @@ var Scheduler = class {
12744
13301
  timezone: currentSchedule.timezone,
12745
13302
  recurrence
12746
13303
  });
12747
- const project = this.db.select().from(projects).where(eq19(projects.id, projectId)).get();
13304
+ const project = this.db.select().from(projects).where(eq20(projects.id, projectId)).get();
12748
13305
  if (!project) {
12749
13306
  log17.error("project.not-found", { projectId, kind, msg: "skipping scheduled run" });
12750
13307
  this.remove(projectId, kind);
@@ -12796,9 +13353,9 @@ var Scheduler = class {
12796
13353
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
12797
13354
  }
12798
13355
  const activeAdsRun = this.db.select({ id: runs.id }).from(runs).where(and17(
12799
- eq19(runs.projectId, projectId),
12800
- eq19(runs.kind, RunKinds["ads-sync"]),
12801
- inArray9(runs.status, [RunStatuses.queued, RunStatuses.running])
13356
+ eq20(runs.projectId, projectId),
13357
+ eq20(runs.kind, RunKinds["ads-sync"]),
13358
+ inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
12802
13359
  )).get();
12803
13360
  if (activeAdsRun) {
12804
13361
  log17.info("ads-sync.skipped-active", { projectName: project.name, activeRunId: activeAdsRun.id });
@@ -12867,9 +13424,9 @@ var Scheduler = class {
12867
13424
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
12868
13425
  }
12869
13426
  const active = this.db.select({ id: runs.id }).from(runs).where(and17(
12870
- eq19(runs.projectId, projectId),
12871
- eq19(runs.kind, RunKinds["site-audit"]),
12872
- inArray9(runs.status, [RunStatuses.queued, RunStatuses.running])
13427
+ eq20(runs.projectId, projectId),
13428
+ eq20(runs.kind, RunKinds["site-audit"]),
13429
+ inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
12873
13430
  )).get();
12874
13431
  if (active) {
12875
13432
  log17.info("site-audit.skipped-active", { projectName: project.name, activeRunId: active.id });
@@ -13077,10 +13634,10 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
13077
13634
  }
13078
13635
 
13079
13636
  // src/review-webhook-delivery.ts
13080
- import { createHash as createHash6 } from "crypto";
13081
- import { and as and18, asc as asc4, eq as eq20, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
13637
+ import { createHash as createHash7 } from "crypto";
13638
+ import { and as and18, asc as asc4, eq as eq21, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
13082
13639
  var log19 = createLogger("ReviewDelivery");
13083
- var hash = (value) => createHash6("sha256").update(JSON.stringify(value)).digest("hex");
13640
+ var hash = (value) => createHash7("sha256").update(JSON.stringify(value)).digest("hex");
13084
13641
  var REVIEW_DELIVERY_MAX_ATTEMPTS = 10;
13085
13642
  var REVIEW_CHAT_SENDS_PER_PASS = 3;
13086
13643
  var REVIEW_DELIVERY_INTERVAL_MS = 6e4;
@@ -13106,20 +13663,20 @@ function reviewEventId(projectId, review) {
13106
13663
  function reviewEventRefusal(db, projectId, payload, notification, targetDigest, now) {
13107
13664
  if (!notification?.enabled || !notification.config.events.includes("review.negative")) return "destination_disabled";
13108
13665
  if (targetDigest !== void 0 && hash(notification.config.url) !== targetDigest) return "destination_changed";
13109
- const project = db.select().from(projects).where(eq20(projects.id, projectId)).get();
13666
+ const project = db.select().from(projects).where(eq21(projects.id, projectId)).get();
13110
13667
  if (!project || project.name !== payload.project.name || project.canonicalDomain !== payload.project.canonicalDomain) return "project_changed";
13111
13668
  const review = payload.reviews[0];
13112
13669
  const location = db.select().from(gbpLocations).where(and18(
13113
- eq20(gbpLocations.projectId, projectId),
13114
- eq20(gbpLocations.locationName, review.location.name),
13115
- eq20(gbpLocations.selected, true)
13670
+ eq21(gbpLocations.projectId, projectId),
13671
+ eq21(gbpLocations.locationName, review.location.name),
13672
+ eq21(gbpLocations.selected, true)
13116
13673
  )).get();
13117
13674
  if (!location || review.origin === "gbp" && !review.reviewName.startsWith(`${location.accountName}/${location.locationName}/reviews/`)) return "location_removed_or_deselected";
13118
13675
  const current = db.select().from(gbpReviews).where(and18(
13119
- eq20(gbpReviews.projectId, projectId),
13120
- eq20(gbpReviews.origin, review.origin),
13121
- eq20(gbpReviews.reviewName, review.reviewName),
13122
- eq20(gbpReviews.locationName, review.location.name)
13676
+ eq21(gbpReviews.projectId, projectId),
13677
+ eq21(gbpReviews.origin, review.origin),
13678
+ eq21(gbpReviews.reviewName, review.reviewName),
13679
+ eq21(gbpReviews.locationName, review.location.name)
13123
13680
  )).get();
13124
13681
  if (!current) return "review_removed";
13125
13682
  if (!isWithinAlertWindow(review.updateTime, now) || !isWithinAlertWindow(current.updateTime, now)) return "review_expired";
@@ -13128,9 +13685,9 @@ function reviewEventRefusal(db, projectId, payload, notification, targetDigest,
13128
13685
  if (["baseline", "skipped", "suppressed", "stale", "none"].includes(current.alertState)) return "review_suppressed";
13129
13686
  if (review.origin === "places") {
13130
13687
  const v4HasWorked = db.select({ id: gbpReviewRatings.id }).from(gbpReviewRatings).where(and18(
13131
- eq20(gbpReviewRatings.projectId, projectId),
13132
- eq20(gbpReviewRatings.locationName, review.location.name),
13133
- eq20(gbpReviewRatings.origin, "gbp")
13688
+ eq21(gbpReviewRatings.projectId, projectId),
13689
+ eq21(gbpReviewRatings.locationName, review.location.name),
13690
+ eq21(gbpReviewRatings.origin, "gbp")
13134
13691
  )).get() !== void 0;
13135
13692
  if (businessProfileReviewsCover(location.reviewsAccess, v4HasWorked)) return "review_origin_superseded";
13136
13693
  }
@@ -13139,8 +13696,8 @@ function reviewEventRefusal(db, projectId, payload, notification, targetDigest,
13139
13696
  function cancelReviewDelivery(db, id, reason) {
13140
13697
  db.transaction((tx) => {
13141
13698
  const canceled = tx.update(reviewWebhookDeliveries).set({ state: ReviewDeliveryStates.Canceled, retryAt: null }).where(and18(
13142
- eq20(reviewWebhookDeliveries.id, id),
13143
- eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending)
13699
+ eq21(reviewWebhookDeliveries.id, id),
13700
+ eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending)
13144
13701
  )).returning({ projectId: reviewWebhookDeliveries.projectId, eventId: reviewWebhookDeliveries.eventId, notificationId: reviewWebhookDeliveries.notificationId, targetDigest: reviewWebhookDeliveries.targetDigest }).get();
13145
13702
  if (canceled) writeAuditLog(tx, {
13146
13703
  projectId: canceled.projectId,
@@ -13157,9 +13714,9 @@ function deferReviewDelivery(db, saved, now) {
13157
13714
  const waited = now - Date.parse(saved.createdAt);
13158
13715
  const delay = Math.min(Math.max(RETRY_BASE_MS, Number.isFinite(waited) ? waited / 4 : RETRY_BASE_MS), RETRY_MAX_MS);
13159
13716
  db.update(reviewWebhookDeliveries).set({ retryAt: new Date(now + delay).toISOString() }).where(and18(
13160
- eq20(reviewWebhookDeliveries.id, saved.id),
13161
- eq20(reviewWebhookDeliveries.state, saved.state),
13162
- eq20(reviewWebhookDeliveries.attempts, saved.attempts)
13717
+ eq21(reviewWebhookDeliveries.id, saved.id),
13718
+ eq21(reviewWebhookDeliveries.state, saved.state),
13719
+ eq21(reviewWebhookDeliveries.attempts, saved.attempts)
13163
13720
  )).run();
13164
13721
  }
13165
13722
  function auditUndelivered(db, saved, outcome) {
@@ -13176,8 +13733,8 @@ function dueReviewDeliveryProjects(db, now) {
13176
13733
  const at = new Date(now).toISOString();
13177
13734
  const staleAttempt = new Date(now - 6e4).toISOString();
13178
13735
  return db.selectDistinct({ projectId: reviewWebhookDeliveries.projectId }).from(reviewWebhookDeliveries).where(or(
13179
- and18(eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending), or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at))),
13180
- and18(eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
13736
+ and18(eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending), or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at))),
13737
+ and18(eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
13181
13738
  )).all().map((row) => row.projectId);
13182
13739
  }
13183
13740
  function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS) {
@@ -13199,11 +13756,11 @@ async function drainReviewDeliveries(options) {
13199
13756
  const at = new Date(now).toISOString();
13200
13757
  const staleAttempt = new Date(now - 6e4).toISOString();
13201
13758
  const ready = options.db.select().from(reviewWebhookDeliveries).where(and18(
13202
- eq20(reviewWebhookDeliveries.projectId, options.projectId),
13759
+ eq21(reviewWebhookDeliveries.projectId, options.projectId),
13203
13760
  or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at)),
13204
13761
  or(
13205
- eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
13206
- and18(eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
13762
+ eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
13763
+ and18(eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
13207
13764
  )
13208
13765
  )).orderBy(asc4(reviewWebhookDeliveries.retryAt), asc4(reviewWebhookDeliveries.attemptedAt), asc4(reviewWebhookDeliveries.createdAt), asc4(reviewWebhookDeliveries.id)).limit(100).all();
13209
13766
  let delivered = 0;
@@ -13228,14 +13785,14 @@ async function deliverReviewEvent(options) {
13228
13785
  return false;
13229
13786
  const notification = db.select().from(notifications).where(
13230
13787
  and18(
13231
- eq20(notifications.id, notificationId),
13232
- eq20(notifications.projectId, projectId)
13788
+ eq21(notifications.id, notificationId),
13789
+ eq21(notifications.projectId, projectId)
13233
13790
  )
13234
13791
  ).get();
13235
13792
  const id = hash([projectId, notificationId, payload.eventId]);
13236
13793
  const now = options.now ?? Date.now;
13237
13794
  const at = new Date(now()).toISOString();
13238
- let saved = db.select().from(reviewWebhookDeliveries).where(eq20(reviewWebhookDeliveries.id, id)).get();
13795
+ let saved = db.select().from(reviewWebhookDeliveries).where(eq21(reviewWebhookDeliveries.id, id)).get();
13239
13796
  const event = saved?.payload ?? payload;
13240
13797
  const refusal = reviewEventRefusal(db, projectId, event, notification, saved?.targetDigest, new Date(now()));
13241
13798
  if (refusal) {
@@ -13254,7 +13811,7 @@ async function deliverReviewEvent(options) {
13254
13811
  payload,
13255
13812
  createdAt: at
13256
13813
  }).onConflictDoNothing().run();
13257
- saved = db.select().from(reviewWebhookDeliveries).where(eq20(reviewWebhookDeliveries.id, id)).get();
13814
+ saved = db.select().from(reviewWebhookDeliveries).where(eq21(reviewWebhookDeliveries.id, id)).get();
13258
13815
  if (!saved || saved.targetDigest !== targetDigest) return false;
13259
13816
  if (saved.state === ReviewDeliveryStates.Sent) return true;
13260
13817
  if (saved.state === ReviewDeliveryStates.Uncertain || saved.state === ReviewDeliveryStates.Canceled) return false;
@@ -13270,16 +13827,16 @@ async function deliverReviewEvent(options) {
13270
13827
  const state2 = destination.signed ? ReviewDeliveryStates.Pending : ReviewDeliveryStates.Uncertain;
13271
13828
  const moved = db.update(reviewWebhookDeliveries).set({ state: state2 }).where(
13272
13829
  and18(
13273
- eq20(reviewWebhookDeliveries.id, id),
13274
- eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
13275
- eq20(reviewWebhookDeliveries.attempts, saved.attempts),
13276
- eq20(reviewWebhookDeliveries.attemptedAt, saved.attemptedAt)
13830
+ eq21(reviewWebhookDeliveries.id, id),
13831
+ eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
13832
+ eq21(reviewWebhookDeliveries.attempts, saved.attempts),
13833
+ eq21(reviewWebhookDeliveries.attemptedAt, saved.attemptedAt)
13277
13834
  )
13278
13835
  ).returning({ id: reviewWebhookDeliveries.id }).get();
13279
13836
  if (moved && state2 === ReviewDeliveryStates.Uncertain) {
13280
13837
  auditUndelivered(db, saved, { state: state2, reason: "interrupted_attempt", attempts: saved.attempts });
13281
13838
  }
13282
- saved = db.select().from(reviewWebhookDeliveries).where(eq20(reviewWebhookDeliveries.id, id)).get();
13839
+ saved = db.select().from(reviewWebhookDeliveries).where(eq21(reviewWebhookDeliveries.id, id)).get();
13283
13840
  if (!saved || saved.state !== ReviewDeliveryStates.Pending) return false;
13284
13841
  }
13285
13842
  if (saved.retryAt && Date.parse(saved.retryAt) > now()) return false;
@@ -13302,8 +13859,8 @@ async function deliverReviewEvent(options) {
13302
13859
  }
13303
13860
  const latest = db.select().from(notifications).where(
13304
13861
  and18(
13305
- eq20(notifications.id, notificationId),
13306
- eq20(notifications.projectId, projectId)
13862
+ eq21(notifications.id, notificationId),
13863
+ eq21(notifications.projectId, projectId)
13307
13864
  )
13308
13865
  ).get();
13309
13866
  const latestRefusal = reviewEventRefusal(db, projectId, saved.payload, latest, targetDigest, new Date(now()));
@@ -13317,9 +13874,9 @@ async function deliverReviewEvent(options) {
13317
13874
  attemptedAt: new Date(now()).toISOString()
13318
13875
  }).where(
13319
13876
  and18(
13320
- eq20(reviewWebhookDeliveries.id, id),
13321
- eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
13322
- eq20(reviewWebhookDeliveries.attempts, saved.attempts)
13877
+ eq21(reviewWebhookDeliveries.id, id),
13878
+ eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
13879
+ eq21(reviewWebhookDeliveries.attempts, saved.attempts)
13323
13880
  )
13324
13881
  ).returning({ id: reviewWebhookDeliveries.id }).get();
13325
13882
  if (!claimed) return false;
@@ -13347,9 +13904,9 @@ async function deliverReviewEvent(options) {
13347
13904
  retryAt: state === ReviewDeliveryStates.Pending ? new Date(now() + retryDelayMs(attempts, result.retryAfterSeconds)).toISOString() : null
13348
13905
  }).where(
13349
13906
  and18(
13350
- eq20(reviewWebhookDeliveries.id, id),
13351
- eq20(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
13352
- eq20(reviewWebhookDeliveries.attempts, attempts)
13907
+ eq21(reviewWebhookDeliveries.id, id),
13908
+ eq21(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
13909
+ eq21(reviewWebhookDeliveries.attempts, attempts)
13353
13910
  )
13354
13911
  ).run();
13355
13912
  if (state === ReviewDeliveryStates.Uncertain || state === ReviewDeliveryStates.Failed) {
@@ -13361,7 +13918,7 @@ async function deliverReviewEvent(options) {
13361
13918
  }
13362
13919
 
13363
13920
  // src/provider-batch-poller.ts
13364
- import { and as and19, eq as eq21, inArray as inArray10, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql9 } from "drizzle-orm";
13921
+ import { and as and19, eq as eq22, inArray as inArray11, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql9 } from "drizzle-orm";
13365
13922
  var log20 = createLogger("ProviderBatchPoller");
13366
13923
  var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
13367
13924
  var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
@@ -13378,7 +13935,7 @@ var ProviderBatchPoller = class {
13378
13935
  /** One pass: advance every outstanding batch that is due, then finalize what that settled. */
13379
13936
  async tick() {
13380
13937
  const { db } = this.deps;
13381
- const rows = db.select().from(providerBatches).where(inArray10(providerBatches.status, [...OUTSTANDING_PROVIDER_BATCH_STATUSES])).all();
13938
+ const rows = db.select().from(providerBatches).where(inArray11(providerBatches.status, [...OUTSTANDING_PROVIDER_BATCH_STATUSES])).all();
13382
13939
  const live = new Set(rows.map((row) => row.id));
13383
13940
  for (const id of this.schedule.keys()) if (!live.has(id)) this.schedule.delete(id);
13384
13941
  const settledRuns = /* @__PURE__ */ new Map();
@@ -13404,7 +13961,7 @@ var ProviderBatchPoller = class {
13404
13961
  * outstanding (ingested or cancelled), so its run may now finalize.
13405
13962
  */
13406
13963
  async advance(row) {
13407
- const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq21(runs.id, row.runId)).get()?.status;
13964
+ const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq22(runs.id, row.runId)).get()?.status;
13408
13965
  if (runStatus !== RunStatuses.running) {
13409
13966
  await this.deps.runner.abandonProviderBatches([row.id], "Cancelled because its run is no longer running.");
13410
13967
  this.schedule.delete(row.id);
@@ -13421,7 +13978,7 @@ var ProviderBatchPoller = class {
13421
13978
  status = poll.status;
13422
13979
  if (poll.status === "ended") {
13423
13980
  const endedAt = poll.endedAt ?? new Date(this.now()).toISOString();
13424
- const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and19(eq21(providerBatches.id, row.id), eq21(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13981
+ const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and19(eq22(providerBatches.id, row.id), eq22(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13425
13982
  this.schedule.delete(row.id);
13426
13983
  return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
13427
13984
  }
@@ -13446,8 +14003,8 @@ var ProviderBatchPoller = class {
13446
14003
  if (row.cancelRequestedAt === null) {
13447
14004
  if (now < Date.parse(row.deadlineAt)) return false;
13448
14005
  const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and19(
13449
- eq21(providerBatches.id, row.id),
13450
- eq21(providerBatches.status, ProviderBatchStatuses.submitted),
14006
+ eq22(providerBatches.id, row.id),
14007
+ eq22(providerBatches.status, ProviderBatchStatuses.submitted),
13451
14008
  isNull4(providerBatches.cancelRequestedAt)
13452
14009
  )).run().changes === 1;
13453
14010
  if (!claimed) return false;
@@ -13466,7 +14023,7 @@ var ProviderBatchPoller = class {
13466
14023
  status: ProviderBatchStatuses.cancelled,
13467
14024
  error: `The provider batch did not end within an hour of being cancelled at its deadline; its ${row.requestCount} answer(s) were not recorded.`,
13468
14025
  updatedAt: at
13469
- }).where(and19(eq21(providerBatches.id, row.id), eq21(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
14026
+ }).where(and19(eq22(providerBatches.id, row.id), eq22(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
13470
14027
  this.schedule.delete(row.id);
13471
14028
  if (gaveUp) log20.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
13472
14029
  return gaveUp;
@@ -13507,9 +14064,9 @@ var ProviderBatchPoller = class {
13507
14064
  finalizableRuns() {
13508
14065
  const holding = [ProviderBatchStatuses.submitting, ...OUTSTANDING_PROVIDER_BATCH_STATUSES];
13509
14066
  return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and19(
13510
- eq21(runs.status, RunStatuses.running),
14067
+ eq22(runs.status, RunStatuses.running),
13511
14068
  isNotNull3(runs.pendingProviderErrors),
13512
- notExists2(this.deps.db.select({ one: sql9`1` }).from(providerBatches).where(and19(eq21(providerBatches.runId, runs.id), inArray10(providerBatches.status, holding))))
14069
+ notExists2(this.deps.db.select({ one: sql9`1` }).from(providerBatches).where(and19(eq22(providerBatches.runId, runs.id), inArray11(providerBatches.status, holding))))
13513
14070
  )).all();
13514
14071
  }
13515
14072
  };
@@ -13588,7 +14145,7 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
13588
14145
  }
13589
14146
 
13590
14147
  // src/notifier.ts
13591
- import { eq as eq22, desc as desc8, and as and20, inArray as inArray11, or as or2, isNull as isNull5 } from "drizzle-orm";
14148
+ import { eq as eq23, desc as desc8, and as and20, inArray as inArray12, or as or2, isNull as isNull5 } from "drizzle-orm";
13592
14149
  import crypto21 from "crypto";
13593
14150
  var log22 = createLogger("Notifier");
13594
14151
  var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
@@ -13709,18 +14266,18 @@ var Notifier = class {
13709
14266
  /** Called after a run completes (success, partial, or failed). */
13710
14267
  async onRunCompleted(runId, projectId, opts) {
13711
14268
  log22.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
13712
- const notifs = this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled);
14269
+ const notifs = this.db.select().from(notifications).where(eq23(notifications.projectId, projectId)).all().filter((n) => n.enabled);
13713
14270
  if (notifs.length === 0) {
13714
14271
  log22.info("notifications.none-enabled", { projectId });
13715
14272
  return;
13716
14273
  }
13717
14274
  log22.info("notifications.found", { projectId, count: notifs.length });
13718
- const run = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
14275
+ const run = this.db.select().from(runs).where(eq23(runs.id, runId)).get();
13719
14276
  if (!run) {
13720
14277
  log22.error("run.not-found", { runId, msg: "skipping notification dispatch" });
13721
14278
  return;
13722
14279
  }
13723
- const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
14280
+ const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
13724
14281
  if (!project) {
13725
14282
  log22.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
13726
14283
  return;
@@ -13799,7 +14356,7 @@ var Notifier = class {
13799
14356
  * than inferred from the absence of a webhook.
13800
14357
  */
13801
14358
  async onHealthChecked(projectId, report) {
13802
- const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
14359
+ const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
13803
14360
  if (!project) {
13804
14361
  log22.error("project.not-found", { projectId, msg: "skipping health notification" });
13805
14362
  return null;
@@ -13832,7 +14389,7 @@ var Notifier = class {
13832
14389
  const status = noSignal ? "warn" : worst ? worst.status : "ok";
13833
14390
  const code = noSignal ? HEALTH_NO_SIGNAL_CODE : worst?.code ?? "health.ok";
13834
14391
  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.`;
13835
- const previous = this.db.select().from(doctorHealthState).where(eq22(doctorHealthState.projectId, projectId)).get();
14392
+ const previous = this.db.select().from(doctorHealthState).where(eq23(doctorHealthState.projectId, projectId)).get();
13836
14393
  const previousStatus = previous?.status ?? null;
13837
14394
  const failingSignature = failing.map((c) => `${c.status}:${c.code}`).join(",");
13838
14395
  const failingNow = failing.map((c) => ({ id: c.id, code: c.code, rank: rank(c.status) }));
@@ -13902,7 +14459,7 @@ var Notifier = class {
13902
14459
  const urgentById = new Map(urgentItems.map((item) => [item.id, item]));
13903
14460
  const generalEvent = event;
13904
14461
  const urgentRecord = previous?.urgentNotified ?? null;
13905
- const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
14462
+ const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq23(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
13906
14463
  const listedEvents = (notif) => notif.config.events;
13907
14464
  const hasUrl = (notif) => Boolean(notif.config.url);
13908
14465
  const urgentSubscribers = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -13950,7 +14507,7 @@ var Notifier = class {
13950
14507
  if (previous === void 0) {
13951
14508
  this.db.insert(doctorHealthState).values({ ...observation, notifiedAt: null }).run();
13952
14509
  } else {
13953
- this.db.update(doctorHealthState).set(observation).where(eq22(doctorHealthState.projectId, projectId)).run();
14510
+ this.db.update(doctorHealthState).set(observation).where(eq23(doctorHealthState.projectId, projectId)).run();
13954
14511
  }
13955
14512
  for (const group of urgentGroups) {
13956
14513
  const { urgentEvent, urgentTold, urgentNew, urgentCleared, urgentNotifs, urgentSettled } = group;
@@ -13994,7 +14551,7 @@ var Notifier = class {
13994
14551
  }
13995
14552
  if (accepted > 0) {
13996
14553
  recordUrgentReceipts(urgentReceipts, group.subscribers, formatUrgentBreaches(urgentSettled) || null);
13997
- this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq22(doctorHealthState.projectId, projectId)).run();
14554
+ this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq23(doctorHealthState.projectId, projectId)).run();
13998
14555
  }
13999
14556
  if (urgentNotifs.length > 0) {
14000
14557
  log22.info("health.urgent-notified", {
@@ -14038,7 +14595,7 @@ var Notifier = class {
14038
14595
  if (await this.sendWebhook(config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) delivered += 1;
14039
14596
  }
14040
14597
  if (delivered > 0) {
14041
- this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq22(doctorHealthState.projectId, projectId)).run();
14598
+ this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq23(doctorHealthState.projectId, projectId)).run();
14042
14599
  }
14043
14600
  log22.info("health.notified", {
14044
14601
  projectId,
@@ -14068,12 +14625,12 @@ var Notifier = class {
14068
14625
  async onSiteLivenessChecked(projectId, result) {
14069
14626
  const { check, checkedAt } = result;
14070
14627
  if (check.status !== "ok" && check.status !== "fail") return null;
14071
- const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
14628
+ const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
14072
14629
  if (!project) {
14073
14630
  log22.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
14074
14631
  return null;
14075
14632
  }
14076
- const previous = this.db.select().from(siteLivenessState).where(eq22(siteLivenessState.projectId, projectId)).get();
14633
+ const previous = this.db.select().from(siteLivenessState).where(eq23(siteLivenessState.projectId, projectId)).get();
14077
14634
  const sincePrevious = previous ? Date.parse(checkedAt) - Date.parse(previous.checkedAt) : Number.NaN;
14078
14635
  const countsAsRepeat = Number.isFinite(sincePrevious) && sincePrevious >= SITE_LIVENESS_MIN_PASS_GAP_MS && sincePrevious <= SITE_LIVENESS_MAX_PASS_GAP_MS;
14079
14636
  const failures = check.status === "fail" ? countsAsRepeat ? (previous?.consecutiveFailures ?? 0) + 1 : 1 : 0;
@@ -14083,7 +14640,7 @@ var Notifier = class {
14083
14640
  if (check.status === "ok" && outagePaged) event = "health.recovered";
14084
14641
  const confirmed = check.status === "fail" && failures >= SITE_LIVENESS_FAILURES_TO_PAGE;
14085
14642
  const urgentRecord = previous?.urgentNotifiedAt ?? null;
14086
- const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
14643
+ const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq23(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
14087
14644
  const listedEvents = (notif) => notif.config.events;
14088
14645
  const hasUrl = (notif) => Boolean(notif.config.url);
14089
14646
  const scoped = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
@@ -14116,7 +14673,7 @@ var Notifier = class {
14116
14673
  if (previous === void 0) {
14117
14674
  this.db.insert(siteLivenessState).values(observation).run();
14118
14675
  } else {
14119
- this.db.update(siteLivenessState).set(observation).where(eq22(siteLivenessState.projectId, projectId)).run();
14676
+ this.db.update(siteLivenessState).set(observation).where(eq23(siteLivenessState.projectId, projectId)).run();
14120
14677
  }
14121
14678
  if (!event && urgentGroups.every((group) => group.urgentEvent === null)) return null;
14122
14679
  const payloadFor = (name) => {
@@ -14152,7 +14709,7 @@ var Notifier = class {
14152
14709
  }
14153
14710
  }
14154
14711
  if (event === "health.degraded" && delivered > 0) {
14155
- this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq22(siteLivenessState.projectId, projectId)).run();
14712
+ this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq23(siteLivenessState.projectId, projectId)).run();
14156
14713
  }
14157
14714
  log22.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
14158
14715
  }
@@ -14166,7 +14723,7 @@ var Notifier = class {
14166
14723
  }
14167
14724
  if (accepted > 0) {
14168
14725
  recordUrgentReceipts(urgentReceipts, group.subscribers, group.settled);
14169
- this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq22(siteLivenessState.projectId, projectId)).run();
14726
+ this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq23(siteLivenessState.projectId, projectId)).run();
14170
14727
  }
14171
14728
  if (urgentNotifs.length > 0 || generalIds.size > 0) {
14172
14729
  log22.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
@@ -14192,7 +14749,7 @@ var Notifier = class {
14192
14749
  */
14193
14750
  isNewInsightNews(projectId, insight) {
14194
14751
  const key = insightNotifyKey(projectId, insight);
14195
- const previous = this.db.select().from(insightNotifyState).where(eq22(insightNotifyState.key, key)).get();
14752
+ const previous = this.db.select().from(insightNotifyState).where(eq23(insightNotifyState.key, key)).get();
14196
14753
  if (!previous) return true;
14197
14754
  if (severityRank(insight.severity) > severityRank(previous.severity)) return true;
14198
14755
  const magnitude = insightMagnitude(insight);
@@ -14214,9 +14771,9 @@ var Notifier = class {
14214
14771
  magnitude: insightMagnitude(insight),
14215
14772
  notifiedAt: (/* @__PURE__ */ new Date()).toISOString()
14216
14773
  };
14217
- const existing = this.db.select().from(insightNotifyState).where(eq22(insightNotifyState.key, key)).get();
14774
+ const existing = this.db.select().from(insightNotifyState).where(eq23(insightNotifyState.key, key)).get();
14218
14775
  if (existing) {
14219
- this.db.update(insightNotifyState).set(row).where(eq22(insightNotifyState.key, key)).run();
14776
+ this.db.update(insightNotifyState).set(row).where(eq23(insightNotifyState.key, key)).run();
14220
14777
  } else {
14221
14778
  this.db.insert(insightNotifyState).values(row).run();
14222
14779
  }
@@ -14230,11 +14787,11 @@ var Notifier = class {
14230
14787
  if (criticalInsights.length > 0) insightEvents.push("insight.critical");
14231
14788
  if (highInsights.length > 0) insightEvents.push("insight.high");
14232
14789
  if (insightEvents.length === 0) return;
14233
- const notifs = this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled);
14790
+ const notifs = this.db.select().from(notifications).where(eq23(notifications.projectId, projectId)).all().filter((n) => n.enabled);
14234
14791
  if (notifs.length === 0) return;
14235
- const run = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
14792
+ const run = this.db.select().from(runs).where(eq23(runs.id, runId)).get();
14236
14793
  if (!run) return;
14237
- const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
14794
+ const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
14238
14795
  if (!project) return;
14239
14796
  for (const notif of notifs) {
14240
14797
  const config = notif.config;
@@ -14315,9 +14872,9 @@ var Notifier = class {
14315
14872
  return delivered;
14316
14873
  }
14317
14874
  async dispatchQueuedReviewAlerts(projectId) {
14318
- const pendingReviews = this.db.select().from(gbpReviews).where(and20(eq22(gbpReviews.projectId, projectId), eq22(gbpReviews.alertState, "pending"))).all();
14319
- const pendingRatings = this.db.select().from(gbpReviewRatings).where(and20(eq22(gbpReviewRatings.projectId, projectId), eq22(gbpReviewRatings.alertState, "pending"))).all();
14320
- const project = this.db.select().from(projects).where(eq22(projects.id, projectId)).get();
14875
+ const pendingReviews = this.db.select().from(gbpReviews).where(and20(eq23(gbpReviews.projectId, projectId), eq23(gbpReviews.alertState, "pending"))).all();
14876
+ const pendingRatings = this.db.select().from(gbpReviewRatings).where(and20(eq23(gbpReviewRatings.projectId, projectId), eq23(gbpReviewRatings.alertState, "pending"))).all();
14877
+ const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
14321
14878
  if (!project) return { reviews: 0, ratingDrops: 0, delivered: 0 };
14322
14879
  const chatSendsLeft = /* @__PURE__ */ new Map();
14323
14880
  const now = /* @__PURE__ */ new Date();
@@ -14329,10 +14886,10 @@ var Notifier = class {
14329
14886
  displayName: gbpLocations.displayName,
14330
14887
  mapsUri: gbpLocations.mapsUri,
14331
14888
  reviewsAccess: gbpLocations.reviewsAccess
14332
- }).from(gbpLocations).where(eq22(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
14889
+ }).from(gbpLocations).where(eq23(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
14333
14890
  );
14334
14891
  const v4HasWorked = new Set(
14335
- this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and20(eq22(gbpReviewRatings.projectId, projectId), eq22(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
14892
+ this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and20(eq23(gbpReviewRatings.projectId, projectId), eq23(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
14336
14893
  );
14337
14894
  const coveredByBusinessProfile = (locationName) => businessProfileReviewsCover(locations.get(locationName)?.reviewsAccess ?? null, v4HasWorked.has(locationName));
14338
14895
  const locationRef = (locationName) => {
@@ -14341,11 +14898,11 @@ var Notifier = class {
14341
14898
  };
14342
14899
  const setReviewState = (ids, alertState) => {
14343
14900
  if (ids.length === 0) return;
14344
- this.db.update(gbpReviews).set({ alertState, alertStateAt: nowIso }).where(inArray11(gbpReviews.id, ids)).run();
14901
+ this.db.update(gbpReviews).set({ alertState, alertStateAt: nowIso }).where(inArray12(gbpReviews.id, ids)).run();
14345
14902
  };
14346
14903
  const setRatingState = (ids, alertState) => {
14347
14904
  if (ids.length === 0) return;
14348
- this.db.update(gbpReviewRatings).set({ alertState, alertStateAt: nowIso }).where(inArray11(gbpReviewRatings.id, ids)).run();
14905
+ this.db.update(gbpReviewRatings).set({ alertState, alertStateAt: nowIso }).where(inArray12(gbpReviewRatings.id, ids)).run();
14349
14906
  };
14350
14907
  const reviewsToSend = [];
14351
14908
  for (const row of pendingReviews) {
@@ -14361,7 +14918,7 @@ var Notifier = class {
14361
14918
  else if (row.rating === null || row.previousRating === null) setRatingState([row.id], "none");
14362
14919
  else ratingsToSend.push(row);
14363
14920
  }
14364
- const enabled = this.db.select().from(notifications).where(eq22(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
14921
+ const enabled = this.db.select().from(notifications).where(eq23(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
14365
14922
  const subscribedTo = (event) => enabled.filter((n) => (n.config.events ?? []).includes(event));
14366
14923
  const projectRef = { name: project.name, canonicalDomain: project.canonicalDomain };
14367
14924
  const dashboardUrl = `${this.serverUrl}/projects/${project.name}`;
@@ -14416,12 +14973,12 @@ var Notifier = class {
14416
14973
  }
14417
14974
  if (all) {
14418
14975
  this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and20(
14419
- eq22(gbpReviews.id, review.id),
14420
- eq22(gbpReviews.alertState, "pending"),
14421
- eq22(gbpReviews.updateTime, review.updateTime),
14422
- review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq22(gbpReviews.alertStateAt, review.alertStateAt),
14423
- review.comment === null ? isNull5(gbpReviews.comment) : eq22(gbpReviews.comment, review.comment),
14424
- review.starRating === null ? isNull5(gbpReviews.starRating) : eq22(gbpReviews.starRating, review.starRating)
14976
+ eq23(gbpReviews.id, review.id),
14977
+ eq23(gbpReviews.alertState, "pending"),
14978
+ eq23(gbpReviews.updateTime, review.updateTime),
14979
+ review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq23(gbpReviews.alertStateAt, review.alertStateAt),
14980
+ review.comment === null ? isNull5(gbpReviews.comment) : eq23(gbpReviews.comment, review.comment),
14981
+ review.starRating === null ? isNull5(gbpReviews.starRating) : eq23(gbpReviews.starRating, review.starRating)
14425
14982
  )).run();
14426
14983
  }
14427
14984
  }
@@ -14462,7 +15019,7 @@ var Notifier = class {
14462
15019
  return { reviews: reviewsToSend.length, ratingDrops: ratingsToSend.length, delivered };
14463
15020
  }
14464
15021
  computeTransitions(runId, projectId) {
14465
- const thisRun = this.db.select().from(runs).where(eq22(runs.id, runId)).get();
15022
+ const thisRun = this.db.select().from(runs).where(eq23(runs.id, runId)).get();
14466
15023
  if (!thisRun) return [];
14467
15024
  const completeness = measurementRunCompleteness(this.db, runId);
14468
15025
  if (completeness.planned && !completeness.complete) {
@@ -14474,9 +15031,9 @@ var Notifier = class {
14474
15031
  return [];
14475
15032
  }
14476
15033
  const groupSiblings = this.db.select().from(runs).where(and20(
14477
- eq22(runs.projectId, projectId),
14478
- eq22(runs.kind, thisRun.kind),
14479
- eq22(runs.createdAt, thisRun.createdAt),
15034
+ eq23(runs.projectId, projectId),
15035
+ eq23(runs.kind, thisRun.kind),
15036
+ eq23(runs.createdAt, thisRun.createdAt),
14480
15037
  notProbeRun()
14481
15038
  )).all();
14482
15039
  const stillPending = groupSiblings.some((r) => r.status === "queued" || r.status === "running");
@@ -14493,7 +15050,7 @@ var Notifier = class {
14493
15050
  return candidate.id > best.id ? candidate : best;
14494
15051
  });
14495
15052
  if (winner.id !== runId) return [];
14496
- const projectLocations = this.db.select({ locations: projects.locations }).from(projects).where(eq22(projects.id, projectId)).get();
15053
+ const projectLocations = this.db.select({ locations: projects.locations }).from(projects).where(eq23(projects.id, projectId)).get();
14497
15054
  const locationCount = Math.max(
14498
15055
  1,
14499
15056
  (projectLocations?.locations ?? []).length
@@ -14501,9 +15058,9 @@ var Notifier = class {
14501
15058
  const RECENT_FETCH_LIMIT = Math.max(8, locationCount * 4);
14502
15059
  const recentRuns = this.db.select().from(runs).where(
14503
15060
  and20(
14504
- eq22(runs.projectId, projectId),
14505
- eq22(runs.kind, thisRun.kind),
14506
- or2(eq22(runs.status, "completed"), eq22(runs.status, "partial")),
15061
+ eq23(runs.projectId, projectId),
15062
+ eq23(runs.kind, thisRun.kind),
15063
+ or2(eq23(runs.status, "completed"), eq23(runs.status, "partial")),
14507
15064
  notProbeRun()
14508
15065
  )
14509
15066
  ).orderBy(desc8(runs.createdAt), desc8(runs.id)).limit(RECENT_FETCH_LIMIT).all();
@@ -14521,13 +15078,13 @@ var Notifier = class {
14521
15078
  provider: querySnapshots.provider,
14522
15079
  location: querySnapshots.location,
14523
15080
  citationState: querySnapshots.citationState
14524
- }).from(querySnapshots).leftJoin(queries, eq22(querySnapshots.queryId, queries.id)).where(inArray11(querySnapshots.runId, currentRunIds)).all();
15081
+ }).from(querySnapshots).leftJoin(queries, eq23(querySnapshots.queryId, queries.id)).where(inArray12(querySnapshots.runId, currentRunIds)).all();
14525
15082
  const previousSnapshots = this.db.select({
14526
15083
  queryId: querySnapshots.queryId,
14527
15084
  provider: querySnapshots.provider,
14528
15085
  location: querySnapshots.location,
14529
15086
  citationState: querySnapshots.citationState
14530
- }).from(querySnapshots).where(inArray11(querySnapshots.runId, previousRunIds)).all();
15087
+ }).from(querySnapshots).where(inArray12(querySnapshots.runId, previousRunIds)).all();
14531
15088
  const prevMap = /* @__PURE__ */ new Map();
14532
15089
  for (const s of previousSnapshots) {
14533
15090
  if (s.queryId == null) continue;
@@ -14631,7 +15188,7 @@ var Notifier = class {
14631
15188
  };
14632
15189
 
14633
15190
  // src/run-coordinator.ts
14634
- import { eq as eq23 } from "drizzle-orm";
15191
+ import { eq as eq24 } from "drizzle-orm";
14635
15192
  var log23 = createLogger("RunCoordinator");
14636
15193
  function reportInsightsGenerated(runTrigger, outcome) {
14637
15194
  trackFeatureCompleted({
@@ -14665,7 +15222,7 @@ var RunCoordinator = class {
14665
15222
  */
14666
15223
  onAnswersRecorded;
14667
15224
  async onRunCompleted(runId, projectId, opts) {
14668
- const runRow = this.db.select().from(runs).where(eq23(runs.id, runId)).get();
15225
+ const runRow = this.db.select().from(runs).where(eq24(runs.id, runId)).get();
14669
15226
  const kind = runRow?.kind ?? RunKinds["answer-visibility"];
14670
15227
  if (runRow?.trigger === RunTriggers.probe) {
14671
15228
  log23.info("probe.skip-side-effects", { runId, projectId, kind });
@@ -14785,7 +15342,7 @@ var RunCoordinator = class {
14785
15342
  * so the Aero queue is never starved of a follow-up.
14786
15343
  */
14787
15344
  buildDiscoveryAeroContext(runId, projectId, status, error) {
14788
- const session = this.db.select().from(discoverySessions).where(eq23(discoverySessions.runId, runId)).get();
15345
+ const session = this.db.select().from(discoverySessions).where(eq24(discoverySessions.runId, runId)).get();
14789
15346
  const competitorMap = session ? session.competitorMap : [];
14790
15347
  return {
14791
15348
  kind: RunKinds["aeo-discover-probe"],
@@ -14828,7 +15385,7 @@ function analysisResultFromInsights(insights2) {
14828
15385
 
14829
15386
  // src/agent/session-registry.ts
14830
15387
  import crypto23 from "crypto";
14831
- import { eq as eq26 } from "drizzle-orm";
15388
+ import { eq as eq27 } from "drizzle-orm";
14832
15389
 
14833
15390
  // src/agent/remote-mcp.ts
14834
15391
  import { Type } from "@earendil-works/pi-ai";
@@ -14934,7 +15491,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
14934
15491
 
14935
15492
  // src/agent/memory-store.ts
14936
15493
  import crypto22 from "crypto";
14937
- import { and as and21, desc as desc9, eq as eq24, like, sql as sql10, or as or3 } from "drizzle-orm";
15494
+ import { and as and21, desc as desc9, eq as eq25, like, sql as sql10, or as or3 } from "drizzle-orm";
14938
15495
  var COMPACTION_KEY_PREFIX = "compaction:";
14939
15496
  var COMPACTION_NOTES_PER_SESSION = 3;
14940
15497
  function rowToDto(row) {
@@ -14948,7 +15505,7 @@ function rowToDto(row) {
14948
15505
  };
14949
15506
  }
14950
15507
  function listMemoryEntries(db, projectId, opts = {}) {
14951
- const query = db.select().from(agentMemory).where(eq24(agentMemory.projectId, projectId)).orderBy(desc9(agentMemory.updatedAt));
15508
+ const query = db.select().from(agentMemory).where(eq25(agentMemory.projectId, projectId)).orderBy(desc9(agentMemory.updatedAt));
14952
15509
  const rows = opts.limit === void 0 ? query.all() : query.limit(opts.limit).all();
14953
15510
  return rows.map(rowToDto);
14954
15511
  }
@@ -14979,12 +15536,12 @@ function upsertMemoryEntry(db, args) {
14979
15536
  updatedAt: now
14980
15537
  }
14981
15538
  }).run();
14982
- const row = db.select().from(agentMemory).where(and21(eq24(agentMemory.projectId, args.projectId), eq24(agentMemory.key, args.key))).get();
15539
+ const row = db.select().from(agentMemory).where(and21(eq25(agentMemory.projectId, args.projectId), eq25(agentMemory.key, args.key))).get();
14983
15540
  if (!row) throw new Error("memory upsert produced no row");
14984
15541
  return rowToDto(row);
14985
15542
  }
14986
15543
  function deleteMemoryEntry(db, projectId, key) {
14987
- const result = db.delete(agentMemory).where(and21(eq24(agentMemory.projectId, projectId), eq24(agentMemory.key, key))).run();
15544
+ const result = db.delete(agentMemory).where(and21(eq25(agentMemory.projectId, projectId), eq25(agentMemory.key, key))).run();
14988
15545
  const changes = result.changes ?? 0;
14989
15546
  return changes > 0;
14990
15547
  }
@@ -14992,7 +15549,7 @@ function loadRecentForHydrate(db, projectId, limit, sessionId) {
14992
15549
  if (sessionId === void 0) return listMemoryEntries(db, projectId, { limit });
14993
15550
  const sessionPrefix = `compaction:${sessionId ?? ""}:`;
14994
15551
  return db.select().from(agentMemory).where(and21(
14995
- eq24(agentMemory.projectId, projectId),
15552
+ eq25(agentMemory.projectId, projectId),
14996
15553
  or3(sql10`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql10`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
14997
15554
  )).orderBy(desc9(agentMemory.updatedAt)).limit(limit).all().map(rowToDto);
14998
15555
  }
@@ -15019,7 +15576,7 @@ function writeCompactionNote(db, args) {
15019
15576
  const sessionPrefix = `${COMPACTION_KEY_PREFIX}${args.sessionId}:`;
15020
15577
  const existing = tx.select({ id: agentMemory.id, updatedAt: agentMemory.updatedAt }).from(agentMemory).where(
15021
15578
  and21(
15022
- eq24(agentMemory.projectId, args.projectId),
15579
+ eq25(agentMemory.projectId, args.projectId),
15023
15580
  like(agentMemory.key, `${sessionPrefix}%`)
15024
15581
  )
15025
15582
  ).orderBy(desc9(agentMemory.updatedAt)).all();
@@ -15027,7 +15584,7 @@ function writeCompactionNote(db, args) {
15027
15584
  if (stale.length > 0) {
15028
15585
  tx.delete(agentMemory).where(sql10`${agentMemory.id} IN (${sql10.join(stale.map((s) => sql10`${s}`), sql10`, `)})`).run();
15029
15586
  }
15030
- const row = tx.select().from(agentMemory).where(and21(eq24(agentMemory.projectId, args.projectId), eq24(agentMemory.key, key))).get();
15587
+ const row = tx.select().from(agentMemory).where(and21(eq25(agentMemory.projectId, args.projectId), eq25(agentMemory.key, key))).get();
15031
15588
  if (row) inserted = rowToDto(row);
15032
15589
  });
15033
15590
  if (!inserted) throw new Error("compaction note write produced no row");
@@ -15101,7 +15658,7 @@ function trackAeroTurn(agent, turn) {
15101
15658
  }
15102
15659
 
15103
15660
  // src/agent/project-shape.ts
15104
- import { and as and22, count as count3, eq as eq25 } from "drizzle-orm";
15661
+ import { and as and22, count as count4, eq as eq26 } from "drizzle-orm";
15105
15662
  var ADVANCED_TOOLS = [
15106
15663
  "canonry_measurement_portfolio_summary",
15107
15664
  "canonry_measurement_overview",
@@ -15128,10 +15685,10 @@ var ADVANCED_ROUTES = [
15128
15685
  ];
15129
15686
  function aeroProjectShape(db, projectId) {
15130
15687
  try {
15131
- const pointer = db.select().from(measurementPlans).where(eq25(measurementPlans.projectId, projectId)).get();
15688
+ const pointer = db.select().from(measurementPlans).where(eq26(measurementPlans.projectId, projectId)).get();
15132
15689
  const version = pointer ? db.select().from(measurementPlanVersions).where(and22(
15133
- eq25(measurementPlanVersions.projectId, projectId),
15134
- eq25(measurementPlanVersions.id, pointer.activeVersionId)
15690
+ eq26(measurementPlanVersions.projectId, projectId),
15691
+ eq26(measurementPlanVersions.id, pointer.activeVersionId)
15135
15692
  )).get() : void 0;
15136
15693
  if (version) {
15137
15694
  const plan = JSON.parse(version.canonicalJson);
@@ -15158,7 +15715,7 @@ canonry_visibility_report describes the whole project, not one Property. canonry
15158
15715
  pinned: ADVANCED_TOOLS
15159
15716
  };
15160
15717
  }
15161
- const tracked = db.select({ total: count3() }).from(queries).where(eq25(queries.projectId, projectId)).get()?.total ?? 0;
15718
+ const tracked = db.select({ total: count4() }).from(queries).where(eq26(queries.projectId, projectId)).get()?.total ?? 0;
15162
15719
  return {
15163
15720
  prompt: `
15164
15721
 
@@ -15414,7 +15971,7 @@ var SessionRegistry = class {
15414
15971
  modelProvider: effectiveProvider,
15415
15972
  modelId: effectiveModelId,
15416
15973
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
15417
- }).where(eq26(agentSessions.projectId, projectId)).run();
15974
+ }).where(eq27(agentSessions.projectId, projectId)).run();
15418
15975
  }
15419
15976
  const agent2 = createAeroSession({
15420
15977
  projectName,
@@ -15733,7 +16290,7 @@ ${lines.join("\n")}
15733
16290
  modelProvider: nextProvider,
15734
16291
  modelId: nextModelId,
15735
16292
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
15736
- }).where(eq26(agentSessions.projectId, projectId)).run();
16293
+ }).where(eq27(agentSessions.projectId, projectId)).run();
15737
16294
  }
15738
16295
  /** Snapshot pending work without consuming it before an atomic conversation switch. */
15739
16296
  prepareConversationChange(projectName) {
@@ -15914,11 +16471,11 @@ ${lines.join("\n")}
15914
16471
  return id;
15915
16472
  }
15916
16473
  tryResolveProjectId(projectName) {
15917
- const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq26(projects.name, projectName)).get();
16474
+ const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq27(projects.name, projectName)).get();
15918
16475
  return row?.id;
15919
16476
  }
15920
16477
  loadRow(projectId) {
15921
- const row = this.opts.db.select().from(agentSessions).where(eq26(agentSessions.projectId, projectId)).get();
16478
+ const row = this.opts.db.select().from(agentSessions).where(eq27(agentSessions.projectId, projectId)).get();
15922
16479
  return row ?? null;
15923
16480
  }
15924
16481
  insertRow(params) {
@@ -15938,7 +16495,7 @@ ${lines.join("\n")}
15938
16495
  }
15939
16496
  updateRow(projectId, patch) {
15940
16497
  const now = (/* @__PURE__ */ new Date()).toISOString();
15941
- this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq26(agentSessions.projectId, projectId)).run();
16498
+ this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq27(agentSessions.projectId, projectId)).run();
15942
16499
  }
15943
16500
  /**
15944
16501
  * Store a refreshed prompt snapshot without touching `updatedAt`, which the
@@ -15947,13 +16504,13 @@ ${lines.join("\n")}
15947
16504
  * recently used right after an upgrade.
15948
16505
  */
15949
16506
  persistPromptSnapshot(projectId, systemPrompt) {
15950
- this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq26(agentSessions.projectId, projectId)).run();
16507
+ this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq27(agentSessions.projectId, projectId)).run();
15951
16508
  }
15952
16509
  };
15953
16510
 
15954
16511
  // src/agent/viewer-sessions.ts
15955
16512
  import crypto24 from "crypto";
15956
- import { and as and23, eq as eq27, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
16513
+ import { and as and23, eq as eq28, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
15957
16514
  var AERO_VIEWER_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([
15958
16515
  CanonryMcpToolNames.canonry_ads_account,
15959
16516
  CanonryMcpToolNames.canonry_ads_geo_search,
@@ -16066,8 +16623,8 @@ var ViewerAeroSessions = class {
16066
16623
  if (this.isBusy(project.name, userId)) throw agentBusy(project.name);
16067
16624
  const today = new Date(this.now()).toISOString().slice(0, 10);
16068
16625
  const used = this.turnsToday.get(key);
16069
- const count4 = used?.date === today ? used.count : 0;
16070
- if (count4 >= VIEWER_AERO_DAILY_TURN_LIMIT) throw viewerAeroDailyLimitExceeded(VIEWER_AERO_DAILY_TURN_LIMIT);
16626
+ const count5 = used?.date === today ? used.count : 0;
16627
+ if (count5 >= VIEWER_AERO_DAILY_TURN_LIMIT) throw viewerAeroDailyLimitExceeded(VIEWER_AERO_DAILY_TURN_LIMIT);
16071
16628
  const minted = mintViewerAeroKey(this.opts.db, userId, new Date(this.now()));
16072
16629
  this.acquisitions.add(key);
16073
16630
  let handedOff = false;
@@ -16082,7 +16639,7 @@ var ViewerAeroSessions = class {
16082
16639
  setAeroSystemPrompt(agent, loadAeroSystemPrompt(void 0, { extras: false }) + VIEWER_AERO_PROMPT + shape.prompt + aeroViewPrompt(preferences.context));
16083
16640
  configureAeroRuntime(agent, [...buildViewerAeroTools(client, project.name, this.opts.managedSweeps), buildAeroViewTool(view, evidence)], void 0, true, shape.pinned);
16084
16641
  this.sessions.set(key, { agent, lastUsedAt: this.now(), updatedAt: this.sessions.get(key)?.updatedAt ?? null });
16085
- this.turnsToday.set(key, { date: today, count: count4 + 1 });
16642
+ this.turnsToday.set(key, { date: today, count: count5 + 1 });
16086
16643
  handedOff = true;
16087
16644
  let released = false;
16088
16645
  return {
@@ -16130,12 +16687,12 @@ var ViewerAeroSessions = class {
16130
16687
  */
16131
16688
  removeKey(id) {
16132
16689
  try {
16133
- this.opts.db.delete(apiKeys).where(eq27(apiKeys.id, id)).run();
16690
+ this.opts.db.delete(apiKeys).where(eq28(apiKeys.id, id)).run();
16134
16691
  } catch {
16135
16692
  try {
16136
16693
  this.opts.db.transaction((tx) => {
16137
- tx.delete(dashboardSessions).where(eq27(dashboardSessions.apiKeyId, id)).run();
16138
- tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq27(apiKeys.id, id)).run();
16694
+ tx.delete(dashboardSessions).where(eq28(dashboardSessions.apiKeyId, id)).run();
16695
+ tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq28(apiKeys.id, id)).run();
16139
16696
  });
16140
16697
  } catch {
16141
16698
  }
@@ -16165,7 +16722,7 @@ var ViewerAeroSessions = class {
16165
16722
  // src/mcp-http.ts
16166
16723
  import crypto25 from "crypto";
16167
16724
  import { isIP } from "net";
16168
- import { eq as eq28 } from "drizzle-orm";
16725
+ import { eq as eq29 } from "drizzle-orm";
16169
16726
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
16170
16727
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
16171
16728
  var SESSION_IDLE_MS = 10 * 60 * 1e3;
@@ -16187,8 +16744,8 @@ function mintSessionKey(db, scopes, userId) {
16187
16744
  function revokeSessionKey(db, id) {
16188
16745
  try {
16189
16746
  db.transaction((tx) => {
16190
- tx.delete(dashboardSessions).where(eq28(dashboardSessions.apiKeyId, id)).run();
16191
- tx.update(apiKeys).set({ revokedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq28(apiKeys.id, id)).run();
16747
+ tx.delete(dashboardSessions).where(eq29(dashboardSessions.apiKeyId, id)).run();
16748
+ tx.update(apiKeys).set({ revokedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq29(apiKeys.id, id)).run();
16192
16749
  });
16193
16750
  } catch {
16194
16751
  }
@@ -16410,7 +16967,7 @@ function registerMcpHttpRoutes(scope, opts) {
16410
16967
  }
16411
16968
 
16412
16969
  // src/agent/agent-routes.ts
16413
- import { eq as eq29 } from "drizzle-orm";
16970
+ import { eq as eq30 } from "drizzle-orm";
16414
16971
  function viewerAeroCaller(request, opts) {
16415
16972
  if (!opts.viewerSessions) return null;
16416
16973
  const principal = request.principal;
@@ -16450,7 +17007,7 @@ function turnAttribution(request) {
16450
17007
  };
16451
17008
  }
16452
17009
  function resolveProject(db, name) {
16453
- const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq29(projects.name, name)).get();
17010
+ const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq30(projects.name, name)).get();
16454
17011
  if (!row) throw notFound("project", name);
16455
17012
  return row;
16456
17013
  }
@@ -16569,7 +17126,7 @@ function registerAgentRoutes(app, opts) {
16569
17126
  }
16570
17127
  requireInstanceAdministrator(request);
16571
17128
  const project = resolveProject(opts.db, request.params.name);
16572
- const row = opts.db.select().from(agentSessions).where(eq29(agentSessions.projectId, project.id)).get();
17129
+ const row = opts.db.select().from(agentSessions).where(eq30(agentSessions.projectId, project.id)).get();
16573
17130
  const nextTurn = opts.sessionRegistry.nextTurnModel(project.name);
16574
17131
  if (!row) {
16575
17132
  return { conversationId: null, messages: [], modelProvider: null, modelId: null, nextTurn, updatedAt: null };
@@ -16611,7 +17168,7 @@ function registerAgentRoutes(app, opts) {
16611
17168
  const project = resolveProject(opts.db, request.params.name);
16612
17169
  if (opts.sessionRegistry.isBusy(project.name)) throw agentBusy(project.name);
16613
17170
  opts.sessionRegistry.reset(project.name);
16614
- opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq29(agentSessions.projectId, project.id)).run();
17171
+ opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq30(agentSessions.projectId, project.id)).run();
16615
17172
  return { status: "reset" };
16616
17173
  }
16617
17174
  );
@@ -16635,7 +17192,7 @@ function registerAgentRoutes(app, opts) {
16635
17192
  return streamViewerTurn(opts, project, viewerId, body, reply, turnAttribution(request));
16636
17193
  }
16637
17194
  if (body.conversationId !== void 0) {
16638
- const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq29(agentSessions.projectId, project.id)).get();
17195
+ const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq30(agentSessions.projectId, project.id)).get();
16639
17196
  if ((current?.id ?? null) !== body.conversationId) throw validationError("The active conversation changed. Reload the conversation before sending.");
16640
17197
  }
16641
17198
  const promptText = body.prompt;
@@ -17451,7 +18008,7 @@ function buildSnapshotSummary(companyName, queries2, providers, queryResults, au
17451
18008
  competitorCounts.set(competitor, (competitorCounts.get(competitor) ?? 0) + 1);
17452
18009
  }
17453
18010
  }
17454
- const topCompetitors = [...competitorCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 10).map(([name, count4]) => ({ name, count: count4 }));
18011
+ const topCompetitors = [...competitorCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 10).map(([name, count5]) => ({ name, count: count5 }));
17455
18012
  const defaultMeaning = totalComparisons > 0 ? `${companyName} was mentioned in ${mentionCount}/${totalComparisons} successful provider-query response${totalComparisons === 1 ? "" : "s"} across ${queries2.length} category queries.` : `No successful provider responses were returned across ${queries2.length} category queries.`;
17456
18013
  const failureNote = failedComparisons > 0 ? [
17457
18014
  `${failedComparisons} provider response${failedComparisons === 1 ? "" : "s"} failed and ${failedComparisons === 1 ? "was" : "were"} excluded from visibility totals.`
@@ -17595,7 +18152,7 @@ function clipText(value, length) {
17595
18152
  }
17596
18153
 
17597
18154
  // src/research-runner.ts
17598
- import { and as and24, eq as eq30, inArray as inArray12, sql as sql11 } from "drizzle-orm";
18155
+ import { and as and24, eq as eq31, inArray as inArray13, sql as sql11 } from "drizzle-orm";
17599
18156
  var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
17600
18157
  function finalResearchRunStatus(completed, failed, waiting) {
17601
18158
  if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
@@ -17603,13 +18160,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
17603
18160
  return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
17604
18161
  }
17605
18162
  async function executeResearchRun(db, registry, runId, projectId, options = {}) {
17606
- const run = db.select().from(researchRuns).where(and24(eq30(researchRuns.id, runId), eq30(researchRuns.projectId, projectId))).get();
18163
+ const run = db.select().from(researchRuns).where(and24(eq31(researchRuns.id, runId), eq31(researchRuns.projectId, projectId))).get();
17607
18164
  if (!run || run.status !== ResearchRunStatuses.queued) return;
17608
- const project = db.select().from(projects).where(eq30(projects.id, projectId)).get();
18165
+ const project = db.select().from(projects).where(eq31(projects.id, projectId)).get();
17609
18166
  if (!project) return;
17610
18167
  const provider = registry.get(run.provider);
17611
18168
  const now = (/* @__PURE__ */ new Date()).toISOString();
17612
- const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and24(eq30(researchRuns.id, runId), eq30(researchRuns.status, ResearchRunStatuses.queued))).run();
18169
+ const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and24(eq31(researchRuns.id, runId), eq31(researchRuns.status, ResearchRunStatuses.queued))).run();
17613
18170
  if (claim.changes !== 1) return;
17614
18171
  const elapsed = startOutcomeTimer();
17615
18172
  const requested = currentOutcomeOrigin();
@@ -17643,8 +18200,8 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
17643
18200
  }
17644
18201
  reserved = run.totalQueries;
17645
18202
  reservation = { scope, period };
17646
- const rows = db.select().from(researchRunQueries).where(eq30(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
17647
- const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq30(competitors.projectId, projectId)).orderBy(competitors.domain).all();
18203
+ const rows = db.select().from(researchRunQueries).where(eq31(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
18204
+ const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq31(competitors.projectId, projectId)).orderBy(competitors.domain).all();
17648
18205
  const competitorDomains = competitorRows.map((row) => row.domain);
17649
18206
  const competitorAliases = new Map(competitorRows.map((row) => [row.domain, competitorIdentityAliases(row)]).filter(([, aliases]) => aliases.length > 0));
17650
18207
  const domains = effectiveDomains(project);
@@ -17654,7 +18211,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
17654
18211
  await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
17655
18212
  try {
17656
18213
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
17657
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and24(eq30(researchRunQueries.id, row.id), eq30(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
18214
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and24(eq31(researchRunQueries.id, row.id), eq31(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
17658
18215
  const raw = await gate.run(async () => {
17659
18216
  dispatched++;
17660
18217
  return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
@@ -17685,7 +18242,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
17685
18242
  rawResponse: raw.rawResponse,
17686
18243
  answerEvidence: raw.evidence ?? null,
17687
18244
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
17688
- }).where(and24(eq30(researchRunQueries.id, row.id), eq30(researchRunQueries.status, ResearchQueryStatuses.running))).run();
18245
+ }).where(and24(eq31(researchRunQueries.id, row.id), eq31(researchRunQueries.status, ResearchQueryStatuses.running))).run();
17689
18246
  if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
17690
18247
  } catch (error) {
17691
18248
  if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
@@ -17736,11 +18293,11 @@ function researchOutcomeStatus(status) {
17736
18293
  }
17737
18294
  }
17738
18295
  function incrementResearchProgress(db, runId, column) {
17739
- db.update(researchRuns).set({ [column]: sql11`${researchRuns[column]} + 1` }).where(eq30(researchRuns.id, runId)).run();
18296
+ db.update(researchRuns).set({ [column]: sql11`${researchRuns[column]} + 1` }).where(eq31(researchRuns.id, runId)).run();
17740
18297
  }
17741
18298
  function markResearchQueryFailed(db, runId, queryId, error) {
17742
18299
  const message = describeError(error);
17743
- const unfinished = and24(eq30(researchRunQueries.id, queryId), inArray12(researchRunQueries.status, unfinishedResearchQueryStatuses));
18300
+ const unfinished = and24(eq31(researchRunQueries.id, queryId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses));
17744
18301
  if (error instanceof IncompleteAnswerError && error.resumable) {
17745
18302
  db.update(researchRunQueries).set({
17746
18303
  status: ResearchQueryStatuses["waiting-upstream"],
@@ -17756,10 +18313,10 @@ function markResearchQueryFailed(db, runId, queryId, error) {
17756
18313
  if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
17757
18314
  }
17758
18315
  function markUnfinishedResearchQueriesFailed(db, runId, error) {
17759
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and24(eq30(researchRunQueries.researchRunId, runId), inArray12(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
18316
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and24(eq31(researchRunQueries.researchRunId, runId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
17760
18317
  }
17761
18318
  function finalizeResearchRun(db, runId, fatalError) {
17762
- const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq30(researchRunQueries.researchRunId, runId)).all();
18319
+ const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq31(researchRunQueries.researchRunId, runId)).all();
17763
18320
  const completed = rows.filter((row) => row.status === ResearchQueryStatuses.completed).length;
17764
18321
  const failed = rows.filter((row) => row.status === ResearchQueryStatuses.failed).length;
17765
18322
  const waiting = rows.filter((row) => row.status === ResearchQueryStatuses["waiting-upstream"]).length;
@@ -17771,12 +18328,12 @@ function finalizeResearchRun(db, runId, fatalError) {
17771
18328
  error: fatalError ?? (failed === rows.length ? "Every research query failed." : null),
17772
18329
  // A run waiting on upstream jobs has not finished.
17773
18330
  finishedAt: waiting > 0 ? null : (/* @__PURE__ */ new Date()).toISOString()
17774
- }).where(eq30(researchRuns.id, runId)).run();
18331
+ }).where(eq31(researchRuns.id, runId)).run();
17775
18332
  return { status, total: rows.length, completed, failed };
17776
18333
  }
17777
18334
 
17778
18335
  // src/google-marketing-sync.ts
17779
- import { and as and25, eq as eq31, isNull as isNull6, sql as sql12 } from "drizzle-orm";
18336
+ import { and as and25, eq as eq32, isNull as isNull6, sql as sql12 } from "drizzle-orm";
17780
18337
  var RUNTIME_FAILURE_REASONS = {
17781
18338
  INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
17782
18339
  NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
@@ -17814,9 +18371,9 @@ function assertSnapshotContext(metadata, expected) {
17814
18371
  }
17815
18372
  function requireSyncRun(db, runId, projectId, kind) {
17816
18373
  const run = db.select().from(runs).where(and25(
17817
- eq31(runs.id, runId),
17818
- eq31(runs.projectId, projectId),
17819
- eq31(runs.kind, kind)
18374
+ eq32(runs.id, runId),
18375
+ eq32(runs.projectId, projectId),
18376
+ eq32(runs.kind, kind)
17820
18377
  )).get();
17821
18378
  if (!run) throw withOutcomeReason(new Error(`Run ${runId} is not a ${kind} run for this project.`), OutcomeReasonCodes.NOT_FOUND);
17822
18379
  if (run.status !== RunStatuses.queued) {
@@ -17833,18 +18390,18 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
17833
18390
  error: serializeRunError({ message: safeErrorMessage(error) }),
17834
18391
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
17835
18392
  }).where(and25(
17836
- eq31(runs.id, runId),
17837
- eq31(runs.projectId, projectId),
17838
- eq31(runs.kind, kind),
17839
- eq31(runs.status, expectedStatus)
18393
+ eq32(runs.id, runId),
18394
+ eq32(runs.projectId, projectId),
18395
+ eq32(runs.kind, kind),
18396
+ eq32(runs.status, expectedStatus)
17840
18397
  )).run();
17841
18398
  }
17842
18399
  function claimSyncRun(db, runId, projectId, kind, startedAt) {
17843
18400
  const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and25(
17844
- eq31(runs.id, runId),
17845
- eq31(runs.projectId, projectId),
17846
- eq31(runs.kind, kind),
17847
- eq31(runs.status, RunStatuses.queued)
18401
+ eq32(runs.id, runId),
18402
+ eq32(runs.projectId, projectId),
18403
+ eq32(runs.kind, kind),
18404
+ eq32(runs.status, RunStatuses.queued)
17848
18405
  )).run();
17849
18406
  return claim.changes === 1;
17850
18407
  }
@@ -17854,9 +18411,9 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
17854
18411
  let evidenceCollected = false;
17855
18412
  try {
17856
18413
  requireSyncRun(db, runId, projectId, RunKinds["google-ads-sync"]);
17857
- const project = db.select().from(projects).where(eq31(projects.id, projectId)).get();
18414
+ const project = db.select().from(projects).where(eq32(projects.id, projectId)).get();
17858
18415
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
17859
- const connection = db.select().from(googleAdsConnections).where(eq31(googleAdsConnections.projectId, projectId)).get();
18416
+ const connection = db.select().from(googleAdsConnections).where(eq32(googleAdsConnections.projectId, projectId)).get();
17860
18417
  if (!connection?.selectedCustomerId) {
17861
18418
  throw withOutcomeReason(new Error("Google Ads needs a selected customer before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
17862
18419
  }
@@ -17909,10 +18466,10 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
17909
18466
  finishedAt,
17910
18467
  error: null
17911
18468
  }).where(and25(
17912
- eq31(runs.id, runId),
17913
- eq31(runs.projectId, projectId),
17914
- eq31(runs.kind, RunKinds["google-ads-sync"]),
17915
- eq31(runs.status, RunStatuses.running)
18469
+ eq32(runs.id, runId),
18470
+ eq32(runs.projectId, projectId),
18471
+ eq32(runs.kind, RunKinds["google-ads-sync"]),
18472
+ eq32(runs.status, RunStatuses.running)
17916
18473
  )).run();
17917
18474
  if (terminalClaim.changes !== 1) {
17918
18475
  throw withOutcomeReason(
@@ -17933,11 +18490,11 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
17933
18490
  lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
17934
18491
  updatedAt: finishedAt
17935
18492
  }).where(and25(
17936
- eq31(googleAdsConnections.id, connection.id),
17937
- eq31(googleAdsConnections.projectId, projectId),
17938
- eq31(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
17939
- connection.selectedLoginCustomerId === null ? isNull6(googleAdsConnections.selectedLoginCustomerId) : eq31(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
17940
- eq31(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
18493
+ eq32(googleAdsConnections.id, connection.id),
18494
+ eq32(googleAdsConnections.projectId, projectId),
18495
+ eq32(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
18496
+ connection.selectedLoginCustomerId === null ? isNull6(googleAdsConnections.selectedLoginCustomerId) : eq32(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
18497
+ eq32(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
17941
18498
  )).run();
17942
18499
  if (connectionClaim.changes !== 1) {
17943
18500
  throw withOutcomeReason(
@@ -17977,9 +18534,9 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
17977
18534
  let evidenceCollected = false;
17978
18535
  try {
17979
18536
  requireSyncRun(db, runId, projectId, RunKinds["gtm-sync"]);
17980
- const project = db.select().from(projects).where(eq31(projects.id, projectId)).get();
18537
+ const project = db.select().from(projects).where(eq32(projects.id, projectId)).get();
17981
18538
  if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
17982
- const connection = db.select().from(gtmConnections).where(eq31(gtmConnections.projectId, projectId)).get();
18539
+ const connection = db.select().from(gtmConnections).where(eq32(gtmConnections.projectId, projectId)).get();
17983
18540
  if (!connection?.selectedAccountId || !connection.selectedContainerId) {
17984
18541
  throw withOutcomeReason(new Error("GTM needs a selected account and container before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
17985
18542
  }
@@ -18018,10 +18575,10 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
18018
18575
  finishedAt,
18019
18576
  error: null
18020
18577
  }).where(and25(
18021
- eq31(runs.id, runId),
18022
- eq31(runs.projectId, projectId),
18023
- eq31(runs.kind, RunKinds["gtm-sync"]),
18024
- eq31(runs.status, RunStatuses.running)
18578
+ eq32(runs.id, runId),
18579
+ eq32(runs.projectId, projectId),
18580
+ eq32(runs.kind, RunKinds["gtm-sync"]),
18581
+ eq32(runs.status, RunStatuses.running)
18025
18582
  )).run();
18026
18583
  if (terminalClaim.changes !== 1) {
18027
18584
  throw withOutcomeReason(
@@ -18043,12 +18600,12 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
18043
18600
  lastSnapshotId: snapshot.metadata.id,
18044
18601
  updatedAt: finishedAt
18045
18602
  }).where(and25(
18046
- eq31(gtmConnections.id, connection.id),
18047
- eq31(gtmConnections.projectId, projectId),
18048
- eq31(gtmConnections.selectedAccountId, connection.selectedAccountId),
18049
- eq31(gtmConnections.selectedContainerId, connection.selectedContainerId),
18050
- connection.selectedWorkspaceId === null ? isNull6(gtmConnections.selectedWorkspaceId) : eq31(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
18051
- eq31(gtmConnections.selectionGeneration, connection.selectionGeneration)
18603
+ eq32(gtmConnections.id, connection.id),
18604
+ eq32(gtmConnections.projectId, projectId),
18605
+ eq32(gtmConnections.selectedAccountId, connection.selectedAccountId),
18606
+ eq32(gtmConnections.selectedContainerId, connection.selectedContainerId),
18607
+ connection.selectedWorkspaceId === null ? isNull6(gtmConnections.selectedWorkspaceId) : eq32(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
18608
+ eq32(gtmConnections.selectionGeneration, connection.selectionGeneration)
18052
18609
  )).run();
18053
18610
  if (connectionClaim.changes !== 1) {
18054
18611
  throw withOutcomeReason(
@@ -18634,6 +19191,10 @@ async function createServer(opts) {
18634
19191
  onFirstActivation: () => maybeShowActivationNotice()
18635
19192
  });
18636
19193
  jobRunner.recoverStaleRuns();
19194
+ const seoRuntime = new SeoRuntime(opts.db, () => loadConfig(runtimeConfigPath).seo, () => {
19195
+ const stat = fs5.statSync(runtimeConfigPath, { bigint: true });
19196
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
19197
+ });
18637
19198
  const allowLoopbackWebhooks = process.env.CANONRY_ALLOW_LOOPBACK_WEBHOOKS !== "0";
18638
19199
  const notifier = new Notifier(opts.db, serverUrl, { allowLoopbackWebhooks });
18639
19200
  const intelligenceService = new IntelligenceService(opts.db);
@@ -18672,7 +19233,7 @@ async function createServer(opts) {
18672
19233
  async (ctx) => {
18673
19234
  if (!sessionRegistry) return;
18674
19235
  if (!agentProactive) return;
18675
- const project = opts.db.select({ name: projects.name }).from(projects).where(eq32(projects.id, ctx.projectId)).get();
19236
+ const project = opts.db.select({ name: projects.name }).from(projects).where(eq33(projects.id, ctx.projectId)).get();
18676
19237
  if (!project) return;
18677
19238
  let content;
18678
19239
  if (ctx.kind === RunKinds["aeo-discover-probe"]) {
@@ -19138,7 +19699,7 @@ async function createServer(opts) {
19138
19699
  void (async () => {
19139
19700
  try {
19140
19701
  const report = await schedulerClient.runDoctor({ project: projectName, checkIds: scheduledHealthCheckIds() });
19141
- const project = opts.db.select().from(projects).where(eq32(projects.name, projectName)).get();
19702
+ const project = opts.db.select().from(projects).where(eq33(projects.name, projectName)).get();
19142
19703
  if (!project) {
19143
19704
  app.log.warn({ projectName }, "doctor schedule fired for an unknown project");
19144
19705
  return;
@@ -19410,7 +19971,7 @@ async function createServer(opts) {
19410
19971
  })();
19411
19972
  if (opts.config.apiKey) {
19412
19973
  const keyHash = hashApiKey(opts.config.apiKey);
19413
- const existing = opts.db.select().from(apiKeys).where(eq32(apiKeys.keyHash, keyHash)).get();
19974
+ const existing = opts.db.select().from(apiKeys).where(eq33(apiKeys.keyHash, keyHash)).get();
19414
19975
  if (!existing) {
19415
19976
  const prefix = opts.config.apiKey.slice(0, 12);
19416
19977
  opts.db.insert(apiKeys).values({
@@ -19429,14 +19990,14 @@ async function createServer(opts) {
19429
19990
  );
19430
19991
  const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
19431
19992
  opts.db.delete(dashboardSessions).where(or4(
19432
- eq32(dashboardSessions.apiKeyHash, ""),
19993
+ eq33(dashboardSessions.apiKeyHash, ""),
19433
19994
  and26(
19434
19995
  isNotNull5(dashboardSessions.passwordFingerprint),
19435
19996
  ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
19436
19997
  )
19437
19998
  )).run();
19438
19999
  if (!opts.config.dashboardPasswordHash) {
19439
- const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and26(eq32(auditLog.entityType, "dashboard-password"), eq32(auditLog.action, action))).get()?.at ?? null;
20000
+ const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and26(eq33(auditLog.entityType, "dashboard-password"), eq33(auditLog.action, action))).get()?.at ?? null;
19440
20001
  const createdAt = lastPasswordEventAt("dashboard-password.created");
19441
20002
  const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
19442
20003
  if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
@@ -19470,23 +20031,23 @@ async function createServer(opts) {
19470
20031
  currentApiKeyHash: apiKeys.keyHash,
19471
20032
  passwordFingerprint: dashboardSessions.passwordFingerprint,
19472
20033
  expiresAt: dashboardSessions.expiresAt
19473
- }).from(dashboardSessions).innerJoin(apiKeys, eq32(apiKeys.id, dashboardSessions.apiKeyId)).where(and26(eq32(dashboardSessions.tokenHash, tokenHash), isNull7(apiKeys.revokedAt))).get();
20034
+ }).from(dashboardSessions).innerJoin(apiKeys, eq33(apiKeys.id, dashboardSessions.apiKeyId)).where(and26(eq33(dashboardSessions.tokenHash, tokenHash), isNull7(apiKeys.revokedAt))).get();
19474
20035
  if (!session) return null;
19475
20036
  const expiresAt = Date.parse(session.expiresAt);
19476
20037
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
19477
- opts.db.delete(dashboardSessions).where(eq32(dashboardSessions.tokenHash, tokenHash)).run();
20038
+ opts.db.delete(dashboardSessions).where(eq33(dashboardSessions.tokenHash, tokenHash)).run();
19478
20039
  return null;
19479
20040
  }
19480
20041
  return session.apiKeyId;
19481
20042
  };
19482
20043
  const clearSession = (sessionId) => {
19483
20044
  if (sessionId) {
19484
- opts.db.delete(dashboardSessions).where(eq32(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
20045
+ opts.db.delete(dashboardSessions).where(eq33(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
19485
20046
  }
19486
20047
  };
19487
20048
  const getDefaultApiKey = () => {
19488
20049
  if (!opts.config.apiKey) return void 0;
19489
- return opts.db.select().from(apiKeys).where(eq32(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
20050
+ return opts.db.select().from(apiKeys).where(eq33(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
19490
20051
  };
19491
20052
  const setSessionCookie = (reply, sessionId) => {
19492
20053
  reply.header(
@@ -19645,12 +20206,12 @@ async function createServer(opts) {
19645
20206
  return reply.send({ authenticated: true });
19646
20207
  }
19647
20208
  if (apiKey) {
19648
- const key = opts.db.select().from(apiKeys).where(eq32(apiKeys.keyHash, hashApiKey(apiKey))).get();
20209
+ const key = opts.db.select().from(apiKeys).where(eq33(apiKeys.keyHash, hashApiKey(apiKey))).get();
19649
20210
  if (!key || key.revokedAt) {
19650
20211
  const err2 = authInvalid();
19651
20212
  return reply.status(err2.statusCode).send(err2.toJSON());
19652
20213
  }
19653
- opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq32(apiKeys.id, key.id)).run();
20214
+ opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq33(apiKeys.id, key.id)).run();
19654
20215
  setSessionCookie(reply, createSession(key));
19655
20216
  return reply.send({ authenticated: true });
19656
20217
  }
@@ -19728,7 +20289,7 @@ async function createServer(opts) {
19728
20289
  const recomputeDebts = /* @__PURE__ */ new Map();
19729
20290
  let recomputeSequence = 0;
19730
20291
  const markAnswerFieldRecompute = (projectId, full) => {
19731
- opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql13`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq32(projects.id, projectId)).run();
20292
+ opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql13`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq33(projects.id, projectId)).run();
19732
20293
  };
19733
20294
  const requestAnswerFieldRecompute = (projectId, projectName, scope, reason) => {
19734
20295
  const sequence = ++recomputeSequence;
@@ -19746,10 +20307,10 @@ async function createServer(opts) {
19746
20307
  if (pass.full && debt.latestFull <= sequence) debt.latestFull = 0;
19747
20308
  try {
19748
20309
  if (debt.latest === sequence && debt.latestFull === 0) {
19749
- opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq32(projects.id, projectId)).run();
20310
+ opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq33(projects.id, projectId)).run();
19750
20311
  if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
19751
20312
  } else if (debt.latestFull === 0) {
19752
- opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and26(eq32(projects.id, projectId), eq32(projects.answerFieldsRecompute, "full"))).run();
20313
+ opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and26(eq33(projects.id, projectId), eq33(projects.answerFieldsRecompute, "full"))).run();
19753
20314
  }
19754
20315
  } catch (err) {
19755
20316
  app.log.error({ err, projectId }, "could not clear the owed answer field recompute");
@@ -19786,7 +20347,7 @@ async function createServer(opts) {
19786
20347
  await yieldToEventLoop4();
19787
20348
  const reason = (competitorAutoAliasReasons.get(projectId) ?? []).join(",");
19788
20349
  competitorAutoAliasReasons.delete(projectId);
19789
- const project = opts.db.select().from(projects).where(eq32(projects.id, projectId)).get();
20350
+ const project = opts.db.select().from(projects).where(eq33(projects.id, projectId)).get();
19790
20351
  if (!project || project.competitorAutoAliases === "off") return;
19791
20352
  if (project.competitorAutoAliases === "apply") {
19792
20353
  await competitorAutoAliases.request(projectId, reason).catch(() => void 0);
@@ -19833,6 +20394,9 @@ async function createServer(opts) {
19833
20394
  sentimentTimer.unref();
19834
20395
  pollSentiment();
19835
20396
  });
20397
+ app.addHook("onClose", async () => {
20398
+ await seoRuntime.stop();
20399
+ });
19836
20400
  app.addHook("onClose", async () => {
19837
20401
  clearInterval(sentimentTimer);
19838
20402
  sentimentPoller.stop();
@@ -19982,8 +20546,8 @@ async function createServer(opts) {
19982
20546
  getAgentPin: () => describeAgentPin(opts.config),
19983
20547
  getGoogleMarketingDoctorInput: (ctx) => {
19984
20548
  if (!ctx.project) return null;
19985
- const googleAds = opts.db.select().from(googleAdsConnections).where(eq32(googleAdsConnections.projectId, ctx.project.id)).get();
19986
- const gtm = opts.db.select().from(gtmConnections).where(eq32(gtmConnections.projectId, ctx.project.id)).get();
20549
+ const googleAds = opts.db.select().from(googleAdsConnections).where(eq33(googleAdsConnections.projectId, ctx.project.id)).get();
20550
+ const gtm = opts.db.select().from(gtmConnections).where(eq33(gtmConnections.projectId, ctx.project.id)).get();
19987
20551
  const googleAdsCredential = getGoogleAdsConnection(opts.config, ctx.project.id);
19988
20552
  const gtmCredential = getGtmConnection(opts.config, ctx.project.id);
19989
20553
  const googleAdsConnected = Boolean(googleAdsCredential?.accessToken);
@@ -20159,6 +20723,8 @@ async function createServer(opts) {
20159
20723
  app.log.error({ runId: input.runId, err }, "Discovery run failed");
20160
20724
  });
20161
20725
  },
20726
+ getSeoRuntime: seoRuntime.getRuntime,
20727
+ onSeoRunRequested: () => seoRuntime.wake(),
20162
20728
  onResearchRunRequested: dispatchResearchRun,
20163
20729
  // Read issued search queries (fan-out) back out of a stored probe payload.
20164
20730
  // Discovery is Gemini-only today, so the Gemini extractor handles every
@@ -20229,7 +20795,7 @@ async function createServer(opts) {
20229
20795
  ...inspectOpts,
20230
20796
  config: opts.config
20231
20797
  }).then(() => {
20232
- const finished = opts.db.select({ status: runs.status }).from(runs).where(eq32(runs.id, runId)).get();
20798
+ const finished = opts.db.select({ status: runs.status }).from(runs).where(eq33(runs.id, runId)).get();
20233
20799
  if (finished?.status === RunStatuses.completed || finished?.status === RunStatuses.partial) {
20234
20800
  return maybeRefreshGscCoverage(
20235
20801
  opts.db,
@@ -20472,7 +21038,7 @@ async function createServer(opts) {
20472
21038
  }
20473
21039
  ];
20474
21040
  },
20475
- onGenerateQueries: async (providerName, count4, project) => {
21041
+ onGenerateQueries: async (providerName, count5, project) => {
20476
21042
  const provider = registry.get(providerName);
20477
21043
  if (!provider)
20478
21044
  throw new Error(`Provider "${providerName}" is not configured`);
@@ -20486,10 +21052,10 @@ async function createServer(opts) {
20486
21052
  language: project.language,
20487
21053
  existingQueries: project.existingQueries,
20488
21054
  siteText,
20489
- count: count4
21055
+ count: count5
20490
21056
  });
20491
21057
  const raw = await provider.adapter.generateText(prompt, provider.config);
20492
- return parseQueryResponse(raw, count4);
21058
+ return parseQueryResponse(raw, count5);
20493
21059
  },
20494
21060
  onSnapshotRequested: async (input) => {
20495
21061
  return snapshotService.createReport(input);
@@ -20685,6 +21251,7 @@ async function createServer(opts) {
20685
21251
  app.addHook("onListen", () => {
20686
21252
  if (runtimeStartupSettled) return;
20687
21253
  try {
21254
+ seoRuntime.start();
20688
21255
  scheduler.start();
20689
21256
  stopSiteLiveness = startSiteLivenessLoop({
20690
21257
  db: opts.db,
@@ -20708,7 +21275,7 @@ async function createServer(opts) {
20708
21275
  isBacklinksInstalled: () => isDuckdbInstalled()
20709
21276
  });
20710
21277
  }
20711
- for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq32(researchRuns.status, ResearchRunStatuses.queued)).all()) {
21278
+ for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq33(researchRuns.status, ResearchRunStatuses.queued)).all()) {
20712
21279
  dispatchResearchRun(run.id, run.projectId, OutcomeTriggers.startup);
20713
21280
  }
20714
21281
  runtimeStartupSettled = true;
@@ -20769,7 +21336,7 @@ function buildQueryGenerationPrompt(ctx) {
20769
21336
  );
20770
21337
  return lines.join("\n");
20771
21338
  }
20772
- function parseQueryResponse(raw, count4) {
21339
+ function parseQueryResponse(raw, count5) {
20773
21340
  const seen = /* @__PURE__ */ new Set();
20774
21341
  const results = [];
20775
21342
  for (const line of raw.split("\n")) {
@@ -20785,7 +21352,7 @@ function parseQueryResponse(raw, count4) {
20785
21352
  if (seen.has(key)) continue;
20786
21353
  seen.add(key);
20787
21354
  results.push(cleaned);
20788
- if (results.length >= count4) break;
21355
+ if (results.length >= count5) break;
20789
21356
  }
20790
21357
  return results;
20791
21358
  }