@canonry/canonry 7.123.1 → 7.123.2

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 (144) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +3 -1
  2. package/assets/assets/{AccessControls-qKt0MIwz.js → AccessControls-Dta-SizF.js} +1 -1
  3. package/assets/assets/{AgentSetupPage-CS6TAG_q.js → AgentSetupPage-BCZb2JPd.js} +1 -1
  4. package/assets/assets/{AuditHistoryPanel-C9muxa5U.js → AuditHistoryPanel-CKfjkLV9.js} +1 -1
  5. package/assets/assets/{BacklinksPage-YSi04rze.js → BacklinksPage-DqonUKGQ.js} +1 -1
  6. package/assets/assets/{ChartPrimitives-DA5ldw5q.js → ChartPrimitives-QqkNW1z_.js} +1 -1
  7. package/assets/assets/{HistoryPage-tTCABHZr.js → HistoryPage-5GKX_eTg.js} +1 -1
  8. package/assets/assets/{MeasurementPropertyPage-B-eHRFSF.js → MeasurementPropertyPage-DX2Y334y.js} +1 -1
  9. package/assets/assets/{ProjectPage-DK7y3uMN.js → ProjectPage-CVjtoNwY.js} +3 -3
  10. package/assets/assets/{RunsPage-B6HxjqFp.js → RunsPage-DvNIMEBR.js} +1 -1
  11. package/assets/assets/{ServerTrafficSection-BCPF6Rxk.js → ServerTrafficSection-CTXgnGFO.js} +3 -3
  12. package/assets/assets/{SettingsPage-Dlsqc0Xk.js → SettingsPage-DNRMlgyi.js} +1 -1
  13. package/assets/assets/{ToneBadge-BekCDc9B.js → ToneBadge-BT5eyW7T.js} +1 -1
  14. package/assets/assets/{TrafficPage-CcZ2VKWS.js → TrafficPage-By1Ha68i.js} +1 -1
  15. package/assets/assets/{TrafficSourceDetailPage-BUWRBlEj.js → TrafficSourceDetailPage-Dd1suSAW.js} +1 -1
  16. package/assets/assets/{account-context-CTgTl_U3.js → account-context-DXPWWIHe.js} +1 -1
  17. package/assets/assets/{agent-trust-copy-C3Su6oTh.js → agent-trust-copy-Co71D_rr.js} +1 -1
  18. package/assets/assets/{card-fF4DLMtN.js → card-FKB7Bzi_.js} +1 -1
  19. package/assets/assets/{index-CZK8ELxf.js → index--sAfSMDD.js} +4 -4
  20. package/assets/assets/{preload-helper-D6vLhNAZ.js → preload-helper-DPpAnfor.js} +1 -1
  21. package/assets/assets/{query-client-bLCsQvmN.js → query-client-CfqIBFn5.js} +1 -1
  22. package/assets/assets/{react-query-DPn84_Mu.js → react-query-DPm_HpW7.js} +1 -1
  23. package/assets/assets/{react-sigma_core.esm.min-Dkaqqban.js → react-sigma_core.esm.min-6VFVUIDW.js} +1 -1
  24. package/assets/assets/{server-traffic-CCdnHKbu.js → server-traffic-nohNgNs2.js} +1 -1
  25. package/assets/assets/{service-CUnyHRGl.js → service-DvysKXv7.js} +1 -1
  26. package/assets/index.html +9 -9
  27. package/dist/activity-IHLM2J7H.js +13 -0
  28. package/dist/{ads-OXZFLKFO.js → ads-DDVAI7ZZ.js} +4 -4
  29. package/dist/{agent-VMLMGUVU.js → agent-OEFMVVYC.js} +8 -8
  30. package/dist/{agent-ask-IGL7KSBW.js → agent-ask-4HETA3Z7.js} +4 -4
  31. package/dist/{agent-conversations-ZQQJTVLM.js → agent-conversations-CCMZJIWB.js} +4 -4
  32. package/dist/{agent-journeys-Z3ZILTRB.js → agent-journeys-VXHMJ3SE.js} +4 -4
  33. package/dist/{agent-memory-MEFTNQWG.js → agent-memory-MOTZGQY6.js} +4 -4
  34. package/dist/{agent-providers-ZZ6RN4TB.js → agent-providers-QIPWDCAJ.js} +4 -4
  35. package/dist/{agent-transcript-QK3OTZ7B.js → agent-transcript-YIMZZF7M.js} +4 -4
  36. package/dist/{analytics-VAJT24GQ.js → analytics-46CHCOBG.js} +4 -4
  37. package/dist/{apply-IWCME5ZF.js → apply-6YQMLMGS.js} +4 -4
  38. package/dist/{backfill-WGEXXMFQ.js → backfill-YL2FNUFE.js} +11 -11
  39. package/dist/{backlinks-QVFDZZCI.js → backlinks-5GE5HVBE.js} +4 -4
  40. package/dist/{bing-JUCW5FTY.js → bing-YUVHQVCO.js} +4 -4
  41. package/dist/{bootstrap-R2O2TPAR.js → bootstrap-MT3QPFXR.js} +11 -11
  42. package/dist/{cdp-VTQYZVW5.js → cdp-JMYRL3XN.js} +8 -8
  43. package/dist/{chunk-NI5THOYW.js → chunk-2FZM66FH.js} +6 -6
  44. package/dist/{chunk-AUMR4UXI.js → chunk-2YRIEAVO.js} +4 -4
  45. package/dist/{chunk-SLHX5HBD.js → chunk-3MYRQB3W.js} +4 -4
  46. package/dist/{chunk-QXUNANMR.js → chunk-3SKGFNCD.js} +2 -2
  47. package/dist/{chunk-TSCCU54X.js → chunk-54X76NGL.js} +5 -5
  48. package/dist/{chunk-DMFFERXC.js → chunk-B7YR57FO.js} +1 -1
  49. package/dist/{chunk-2DT55UKG.js → chunk-CBORUOY3.js} +3 -3
  50. package/dist/{chunk-73AQQAPC.js → chunk-CBYBYL7A.js} +11 -1
  51. package/dist/{chunk-Z6ZH7N6U.js → chunk-FB7ZRPBD.js} +3 -3
  52. package/dist/{chunk-OCL6NZGL.js → chunk-IA7U7XXS.js} +2 -2
  53. package/dist/{chunk-LGD3K4G5.js → chunk-JMBAYBFO.js} +4 -4
  54. package/dist/{chunk-BSUAO3RJ.js → chunk-JPRWAASQ.js} +1 -1
  55. package/dist/{chunk-BNL3BKXK.js → chunk-K77OPDGD.js} +1 -1
  56. package/dist/{chunk-CCBFBQFR.js → chunk-LBVLZWLF.js} +3 -3
  57. package/dist/{chunk-F3PBATIZ.js → chunk-LJKOYEYH.js} +1 -1
  58. package/dist/{chunk-7OYOUVZS.js → chunk-LN7L45WN.js} +371 -371
  59. package/dist/{chunk-F3UXTYXA.js → chunk-MFZIEBHI.js} +4 -4
  60. package/dist/{chunk-NDVKLJXW.js → chunk-MKCI6M2G.js} +5 -5
  61. package/dist/{chunk-WRWTDHSO.js → chunk-MMCYPRRQ.js} +22 -22
  62. package/dist/{chunk-7D735WS6.js → chunk-N2BYOBOL.js} +1 -1
  63. package/dist/{chunk-DLJAUCAU.js → chunk-NGD7TX3R.js} +5 -5
  64. package/dist/{chunk-6URM26ZP.js → chunk-NLW6XEUI.js} +2 -2
  65. package/dist/{chunk-BVJUYSOB.js → chunk-QNO2KO66.js} +2 -2
  66. package/dist/{chunk-NNJ6PD64.js → chunk-RII4R3ZZ.js} +4 -4
  67. package/dist/{chunk-2RG6CSZB.js → chunk-RXDYCDE6.js} +1 -1
  68. package/dist/{chunk-HSYZCNXY.js → chunk-SGLMEEQ5.js} +2 -2
  69. package/dist/{chunk-YWLJQ2FY.js → chunk-UEIMKBG6.js} +1 -1
  70. package/dist/{chunk-YXM6FPGD.js → chunk-UF5MG47X.js} +1 -1
  71. package/dist/{chunk-ZP6PZZAW.js → chunk-UH3M7XSQ.js} +2 -2
  72. package/dist/{chunk-CQSLBPR2.js → chunk-UUKO5OCN.js} +8 -8
  73. package/dist/{chunk-7KQESJWH.js → chunk-V7OJEOEQ.js} +264 -178
  74. package/dist/{chunk-LQGTGSA5.js → chunk-VSPGQLEH.js} +3 -3
  75. package/dist/{chunk-NZOLX55S.js → chunk-W7KF43JV.js} +1 -1
  76. package/dist/{chunk-XXSDKDKU.js → chunk-WAAESDBG.js} +4 -4
  77. package/dist/{chunk-TTK6ZZHK.js → chunk-WHJA4QYX.js} +2 -2
  78. package/dist/{chunk-RHH2K4BZ.js → chunk-WQYYCJGN.js} +4 -4
  79. package/dist/{chunk-LWGO6ETW.js → chunk-XAF22QBW.js} +2 -2
  80. package/dist/{chunk-2J6LXZPK.js → chunk-YA54KGF3.js} +1 -1
  81. package/dist/{citations-HQQQM73E.js → citations-XDBO5C6Y.js} +5 -5
  82. package/dist/{cli-catalog-STHVOXXT.js → cli-catalog-I4EVHBN3.js} +4 -4
  83. package/dist/cli-commands-RQQ2IA24.js +18 -0
  84. package/dist/cli.js +14 -14
  85. package/dist/{competitor-VP52MSQM.js → competitor-4AIJ4XJF.js} +4 -4
  86. package/dist/{content-IHFS2BRF.js → content-T3RJQQZB.js} +4 -4
  87. package/dist/{dashboard-2DBFBHAU.js → dashboard-TCT2OZFG.js} +7 -7
  88. package/dist/{demo-UFZBEKZC.js → demo-JQNKAWZI.js} +3 -3
  89. package/dist/{demo-server-3YTYVGJU.js → demo-server-7SFA77LN.js} +13 -13
  90. package/dist/{discover-X2RATQCF.js → discover-XW7THOUJ.js} +5 -5
  91. package/dist/{discover-eval-FEQ3HAM2.js → discover-eval-B2VMAP7A.js} +4 -4
  92. package/dist/{doctor-2CM5FVMJ.js → doctor-GWFLDP6E.js} +4 -4
  93. package/dist/{evidence-5IAVY6JN.js → evidence-3E56FTV3.js} +4 -4
  94. package/dist/{export-cmd-LGXY4GIT.js → export-cmd-EM7KBF7D.js} +4 -4
  95. package/dist/{ga-KVFZSSFH.js → ga-H67UEL5Z.js} +7 -4
  96. package/dist/{gbp-PLSX7QBV.js → gbp-ZIPJARZX.js} +4 -4
  97. package/dist/{google-R7HNCZNY.js → google-L3GPQYBY.js} +5 -5
  98. package/dist/{google-marketing-ZEU6ZNTS.js → google-marketing-STFWTVH2.js} +2 -2
  99. package/dist/{health-cmd-UNYQIHHZ.js → health-cmd-WGTE6GDP.js} +5 -5
  100. package/dist/{history-IR234HUF.js → history-X4REKZI7.js} +4 -4
  101. package/dist/index.d.ts +15 -15
  102. package/dist/index.js +26 -26
  103. package/dist/{init-IZ3ANN2I.js → init-KSAQEVOI.js} +13 -13
  104. package/dist/{insights-OQ4TYD7O.js → insights-DKIQVLF7.js} +4 -4
  105. package/dist/intelligence-service-XOQWGWUQ.js +15 -0
  106. package/dist/{journeys-G72GTTDS.js → journeys-IBX6DVER.js} +4 -4
  107. package/dist/{keys-A2NSFAJR.js → keys-HC56635P.js} +4 -4
  108. package/dist/{keyword-4ECZAEFL.js → keyword-XCFZ6XYF.js} +4 -4
  109. package/dist/{logs-OMBVVMGA.js → logs-DOBMYWEL.js} +4 -4
  110. package/dist/{mcp-OALO7GAG.js → mcp-7URS3Y35.js} +5 -5
  111. package/dist/mcp.js +10 -10
  112. package/dist/{measurement-plan-3KJSVBMM.js → measurement-plan-A5XD6GTX.js} +6 -6
  113. package/dist/{notify-AYBCSPXF.js → notify-WB4D7YSN.js} +4 -4
  114. package/dist/{organic-evidence-XMS6WPCR.js → organic-evidence-WNHMO6EJ.js} +4 -4
  115. package/dist/{overview-K4RBEW7T.js → overview-V6VDXKGL.js} +7 -7
  116. package/dist/{project-KGIYKLEE.js → project-FK454CW2.js} +4 -4
  117. package/dist/{project-setup-OBS4PSB4.js → project-setup-DU3QZQIH.js} +4 -4
  118. package/dist/{query-TJAMHSAJ.js → query-XN753RNY.js} +4 -4
  119. package/dist/{research-REDM6KKM.js → research-SQRXT62J.js} +4 -4
  120. package/dist/{results-export-E7P2G3FV.js → results-export-V2SWKZ4S.js} +4 -4
  121. package/dist/{run-43C6BWTO.js → run-V6JJFAQX.js} +6 -6
  122. package/dist/{schedule-B4TSMTC4.js → schedule-THBN6G7B.js} +4 -4
  123. package/dist/{search-VE7DGSD7.js → search-DGNFW3LV.js} +4 -4
  124. package/dist/{serve-365C4I42.js → serve-MCHKKOOS.js} +27 -27
  125. package/dist/{session-ZB2BI6VG.js → session-7DJVNGNI.js} +14 -14
  126. package/dist/{settings-W3SCNC25.js → settings-J2IGFFTN.js} +4 -4
  127. package/dist/{sitemaps-YPD7U2ZP.js → sitemaps-OZBTUP7H.js} +4 -4
  128. package/dist/{skills-K6BM2BQV.js → skills-HDFOPJA4.js} +3 -3
  129. package/dist/{snapshot-GK6G72YF.js → snapshot-GZDMZHRT.js} +4 -4
  130. package/dist/{src-RUWMU4ZS.js → src-Y2JHYSZX.js} +2 -2
  131. package/dist/{status-I23DTMWM.js → status-3DBBZVSJ.js} +6 -6
  132. package/dist/{support-PEI7R4MY.js → support-MAV3J2JF.js} +2 -2
  133. package/dist/{technical-aeo-W5ZF2TPH.js → technical-aeo-OYXGISRF.js} +4 -4
  134. package/dist/{telemetry-YV6IHYS7.js → telemetry-CZEUM2S6.js} +5 -5
  135. package/dist/{tools-57J55S4A.js → tools-DPR6GTYF.js} +12 -12
  136. package/dist/{traffic-SQ4O6QW6.js → traffic-NORJ3VPC.js} +6 -6
  137. package/dist/{trends-MCDIYFQB.js → trends-DWJIK23M.js} +4 -4
  138. package/dist/{users-R66ASOSH.js → users-IUPRSMBK.js} +4 -4
  139. package/dist/{visibility-stats-7XTGKFPE.js → visibility-stats-A7CXPJAL.js} +5 -5
  140. package/dist/{wordpress-ZMNF2C2H.js → wordpress-SEFAVNRT.js} +4 -4
  141. package/package.json +1 -1
  142. package/dist/activity-NEHRLN66.js +0 -13
  143. package/dist/cli-commands-KWRHN6M5.js +0 -18
  144. package/dist/intelligence-service-A6B7TKOX.js +0 -15
@@ -19,14 +19,14 @@ import {
19
19
  normalizeTrafficPathPattern,
20
20
  sessionizeJourneyRequests,
21
21
  verifyRequestSignature
22
- } from "./chunk-2J6LXZPK.js";
22
+ } from "./chunk-YA54KGF3.js";
23
23
  import {
24
24
  currentOutcomeAttribution,
25
25
  getRequestContext,
26
26
  registerRequestContext,
27
27
  requestAuditIdentity,
28
28
  sanitizeRequestContext
29
- } from "./chunk-YWLJQ2FY.js";
29
+ } from "./chunk-UEIMKBG6.js";
30
30
  import {
31
31
  RawEventSampleEventTypes,
32
32
  SentimentIdempotencyConflict,
@@ -190,7 +190,7 @@ import {
190
190
  userSessions,
191
191
  users,
192
192
  writeNegativeReviewMaxStars
193
- } from "./chunk-NZOLX55S.js";
193
+ } from "./chunk-W7KF43JV.js";
194
194
  import {
195
195
  ADS_ACTIVATE_SCOPE,
196
196
  ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
@@ -1395,7 +1395,7 @@ import {
1395
1395
  wordpressSchemaDeployResultDtoSchema,
1396
1396
  wordpressSchemaStatusResultDtoSchema,
1397
1397
  wordpressStatusDtoSchema
1398
- } from "./chunk-73AQQAPC.js";
1398
+ } from "./chunk-CBYBYL7A.js";
1399
1399
 
1400
1400
  // ../api-routes/src/user-session.ts
1401
1401
  import crypto2 from "crypto";
@@ -54316,6 +54316,8 @@ function resolveGa4SyncDays(days) {
54316
54316
  return { requestedDays, effectiveDays, clamped: effectiveDays !== requestedDays };
54317
54317
  }
54318
54318
  var GA4_REQUEST_TIMEOUT_MS = 3e4;
54319
+ var GA4_REPORT_TIMEOUT_MS = 6e4;
54320
+ var GA4_MAX_TIMEOUT_RETRIES = 1;
54319
54321
  var GA4_MAX_PAGES = 50;
54320
54322
  var GA4_MAX_CONCURRENT_REQUESTS = 4;
54321
54323
  var GA4_MAX_RETRIES = 3;
@@ -54538,16 +54540,17 @@ function parseRetryAfter(headerValue3) {
54538
54540
  }
54539
54541
  return void 0;
54540
54542
  }
54543
+ function isGa4Timeout(err) {
54544
+ return err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
54545
+ }
54541
54546
  function isRetryableGa4Error(err) {
54542
54547
  if (err instanceof GA4ApiError) {
54543
54548
  return err.status === 429 || err.status >= 500;
54544
54549
  }
54545
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
54546
- return true;
54547
- }
54548
- return false;
54550
+ return isGa4Timeout(err);
54549
54551
  }
54550
54552
  async function withGa4Retry(fn, errLabel) {
54553
+ let timeoutRetries = 0;
54551
54554
  return withRetry(fn, {
54552
54555
  maxRetries: GA4_MAX_RETRIES,
54553
54556
  baseDelayMs: GA4_INITIAL_RETRY_DELAY_MS,
@@ -54555,7 +54558,12 @@ async function withGa4Retry(fn, errLabel) {
54555
54558
  // schedule operators have been seeing in production until we have a
54556
54559
  // reason to introduce variance.
54557
54560
  jitter: false,
54558
- isRetryable: isRetryableGa4Error,
54561
+ isRetryable: (err) => {
54562
+ if (!isRetryableGa4Error(err)) return false;
54563
+ if (!isGa4Timeout(err)) return true;
54564
+ timeoutRetries++;
54565
+ return timeoutRetries <= GA4_MAX_TIMEOUT_RETRIES;
54566
+ },
54559
54567
  // Honor `Retry-After` when the server supplies it; fall back to the
54560
54568
  // computed exponential delay otherwise.
54561
54569
  computeDelayMs: (_attempt, err, defaultMs) => {
@@ -54571,6 +54579,7 @@ async function withGa4Retry(fn, errLabel) {
54571
54579
  attempt: attempt + 1,
54572
54580
  maxAttempts: GA4_MAX_RETRIES + 1,
54573
54581
  status: ga4Err?.status,
54582
+ timedOut: isGa4Timeout(err),
54574
54583
  delayMs,
54575
54584
  usedRetryAfter: ga4Err?.retryAfterSeconds !== void 0
54576
54585
  });
@@ -54589,7 +54598,7 @@ async function runReport(accessToken, propertyId, request) {
54589
54598
  "Content-Type": "application/json"
54590
54599
  },
54591
54600
  body: JSON.stringify(request),
54592
- signal: AbortSignal.timeout(GA4_REQUEST_TIMEOUT_MS)
54601
+ signal: AbortSignal.timeout(GA4_REPORT_TIMEOUT_MS)
54593
54602
  });
54594
54603
  if (res.status === 401 || res.status === 403) {
54595
54604
  const body = await res.text().catch(() => "");
@@ -54643,7 +54652,7 @@ async function batchRunReports(accessToken, propertyId, requests) {
54643
54652
  "Content-Type": "application/json"
54644
54653
  },
54645
54654
  body: JSON.stringify({ requests }),
54646
- signal: AbortSignal.timeout(GA4_REQUEST_TIMEOUT_MS)
54655
+ signal: AbortSignal.timeout(GA4_REPORT_TIMEOUT_MS)
54647
54656
  });
54648
54657
  if (res.status === 401 || res.status === 403) {
54649
54658
  const body = await res.text().catch(() => "");
@@ -66660,6 +66669,23 @@ async function fetchGaSyncRanges(plan, fetchRange) {
66660
66669
  return results;
66661
66670
  }
66662
66671
 
66672
+ // ../api-routes/src/ga-sync-windows.ts
66673
+ function settleGaWindows(windows, results) {
66674
+ const read = [];
66675
+ const failed = [];
66676
+ results.forEach((result, index) => {
66677
+ if (result.status === "fulfilled") read.push(result.value);
66678
+ else failed.push({ window: windows[index], error: result.reason });
66679
+ });
66680
+ return { read, failed };
66681
+ }
66682
+ function keptGaWindows(windows, failures) {
66683
+ return windows.flatMap((window2) => {
66684
+ const failure = failures.find((entry) => entry.window === window2);
66685
+ return failure ? [{ window: window2, error: describeError(failure.error) }] : [];
66686
+ });
66687
+ }
66688
+
66663
66689
  // ../api-routes/src/ga-search-landing-pages.ts
66664
66690
  import crypto56 from "crypto";
66665
66691
  import { and as and85, asc as asc25, count as count7, desc as desc44, eq as eq99, gte as gte25, lte as lte24, sql as sql43 } from "drizzle-orm";
@@ -67483,18 +67509,40 @@ async function ga4Routes(app, opts) {
67483
67509
  let aiReferrals = [];
67484
67510
  let socialReferrals = [];
67485
67511
  const WINDOW_KEYS = GA_OVERVIEW_WINDOWS;
67486
- const [summary3, windowSummaries, windowMetrics] = await Promise.all([
67512
+ const windowsRequestedAt = /* @__PURE__ */ new Date();
67513
+ const [summary3, windowSummaryResults, windowMetricResults] = await Promise.all([
67487
67514
  fetchAggregateSummary(accessToken, propertyId, days),
67488
- Promise.all(WINDOW_KEYS.map((w) => fetchWindowSummary(accessToken, propertyId, w))),
67489
- Promise.all(WINDOW_KEYS.map((w) => fetchWindowMetrics(accessToken, propertyId, w)))
67515
+ Promise.allSettled(WINDOW_KEYS.map((w) => fetchWindowSummary(accessToken, propertyId, w))),
67516
+ Promise.allSettled(WINDOW_KEYS.map((w) => fetchWindowMetrics(accessToken, propertyId, w)))
67490
67517
  ]);
67518
+ const { read: windowSummaries, failed: failedSummaryWindows } = settleGaWindows(WINDOW_KEYS, windowSummaryResults);
67519
+ const { read: windowMetrics, failed: failedMetricWindows } = settleGaWindows(WINDOW_KEYS, windowMetricResults);
67520
+ const zoneReport = windowMetrics[0];
67521
+ if (!zoneReport) {
67522
+ const firstError = failedMetricWindows[0].error;
67523
+ throw firstError instanceof Error ? firstError : new Error(describeError(firstError));
67524
+ }
67525
+ const reportTimeZone2 = zoneReport.timeZone;
67526
+ const failedWindows = [...failedMetricWindows, ...failedSummaryWindows];
67527
+ for (const failure of failedWindows) {
67528
+ componentFailure ??= { error: failure.error };
67529
+ gaLog("warn", "window.kept", {
67530
+ projectId: project.id,
67531
+ runId,
67532
+ window: failure.window,
67533
+ report: failedMetricWindows.includes(failure) ? "totals" : "summary",
67534
+ error: describeError(failure.error)
67535
+ });
67536
+ }
67537
+ const keptWindows = keptGaWindows(WINDOW_KEYS, failedWindows);
67491
67538
  const requested = { startDate: summary3.periodStart, endDate: summary3.periodEnd };
67492
- const definition2 = JSON.stringify(["v1", windowMetrics[0].timeZone ?? "UTC"]);
67539
+ const definition2 = JSON.stringify(["v1", reportTimeZone2 ?? "UTC"]);
67493
67540
  const planInput = { projectId: project.id, propertyId, requested, definition: definition2 };
67494
67541
  const trafficPlan = planGaSyncCoverage(app.db, { ...planInput, component: "traffic" }, startedAt);
67495
67542
  const aiPlan = planGaSyncCoverage(app.db, { ...planInput, component: "ai" }, startedAt);
67496
67543
  const socialPlan = planGaSyncCoverage(app.db, { ...planInput, component: "social" }, startedAt);
67497
- const longestWindow = windowMetrics.at(-1);
67544
+ const longestWindowKey = WINDOW_KEYS.at(-1);
67545
+ const longestWindow = windowMetrics.find((metric2) => metric2.windowKey === longestWindowKey) ?? gaOverviewComparisonRanges(longestWindowKey, windowsRequestedAt, reportTimeZone2 ?? "UTC");
67498
67546
  const dailyPlan = planGaSyncCoverage(app.db, {
67499
67547
  ...planInput,
67500
67548
  component: "daily",
@@ -67512,7 +67560,7 @@ async function ga4Routes(app, opts) {
67512
67560
  requested: { startDate: shiftIsoCalendarDate(requested.endDate, -leadDays), endDate: requested.endDate }
67513
67561
  }, startedAt);
67514
67562
  const searchRequestedAt = /* @__PURE__ */ new Date();
67515
- const searchTimeZone = windowMetrics[0].timeZone ?? null;
67563
+ const searchTimeZone = reportTimeZone2 ?? null;
67516
67564
  const searchWindows = syncSearchLanding ? searchLandingWindowsToFetch(app.db, project.id, propertyId, searchTimeZone, searchRequestedAt.toISOString()) : [];
67517
67565
  const measurementFetch = Promise.allSettled([
67518
67566
  fetchGaSyncRanges(acquisitionPlan, (range) => fetchAcquisitionByChannel(accessToken, propertyId, acquisitionDays, { dateRange: range })),
@@ -67597,7 +67645,12 @@ async function ga4Routes(app, opts) {
67597
67645
  createdAt: now
67598
67646
  }).run();
67599
67647
  }
67600
- tx.delete(gaWindowMetrics).where(eq100(gaWindowMetrics.projectId, project.id)).run();
67648
+ if (windowMetrics.length > 0) {
67649
+ tx.delete(gaWindowMetrics).where(and86(
67650
+ eq100(gaWindowMetrics.projectId, project.id),
67651
+ inArray49(gaWindowMetrics.windowKey, windowMetrics.map((metric2) => metric2.windowKey))
67652
+ )).run();
67653
+ }
67601
67654
  for (const windowMetric of windowMetrics) {
67602
67655
  for (const [period2, totals] of [
67603
67656
  [GaOverviewPeriods.current, windowMetric.current],
@@ -67698,7 +67751,12 @@ async function ga4Routes(app, opts) {
67698
67751
  syncedAt: now,
67699
67752
  syncRunId: runId
67700
67753
  }).run();
67701
- tx.delete(gaTrafficWindowSummaries).where(eq100(gaTrafficWindowSummaries.projectId, project.id)).run();
67754
+ if (windowSummaries.length > 0) {
67755
+ tx.delete(gaTrafficWindowSummaries).where(and86(
67756
+ eq100(gaTrafficWindowSummaries.projectId, project.id),
67757
+ inArray49(gaTrafficWindowSummaries.windowKey, windowSummaries.map((ws) => ws.windowKey))
67758
+ )).run();
67759
+ }
67702
67760
  for (const ws of windowSummaries) {
67703
67761
  tx.insert(gaTrafficWindowSummaries).values({
67704
67762
  id: crypto57.randomUUID(),
@@ -67867,7 +67925,8 @@ async function ga4Routes(app, opts) {
67867
67925
  days,
67868
67926
  ...clamped ? { requestedDays, clamped } : {},
67869
67927
  totalUsers: summary3.totalUsers,
67870
- ...only ? { only } : {}
67928
+ ...only ? { only } : {},
67929
+ ...keptWindows.length > 0 ? { keptWindows: keptWindows.map((kept) => kept.window) } : {}
67871
67930
  });
67872
67931
  const counts2 = { rows: rows.length + dailyTotals.rows.length + aiReferrals.length + socialReferrals.length };
67873
67932
  if (componentFailure) {
@@ -67891,6 +67950,7 @@ async function ga4Routes(app, opts) {
67891
67950
  leads: leadResult,
67892
67951
  ...searchLandingResult ? { searchLandingPages: searchLandingResult } : {}
67893
67952
  },
67953
+ ...keptWindows.length > 0 ? { keptWindows } : {},
67894
67954
  ...syncedComponents ? { syncedComponents } : {}
67895
67955
  };
67896
67956
  } catch (e) {
@@ -77684,7 +77744,43 @@ var ga4ConnectionCheck = {
77684
77744
  var GA_AUTH_CHECKS = [ga4ConnectionCheck];
77685
77745
 
77686
77746
  // ../api-routes/src/doctor/checks/data-freshness.ts
77687
- import { and as and98, desc as desc51, eq as eq115, inArray as inArray53 } from "drizzle-orm";
77747
+ import { and as and99, desc as desc52, eq as eq116 } from "drizzle-orm";
77748
+
77749
+ // ../api-routes/src/doctor/checks/sync-run-state.ts
77750
+ import { and as and98, count as count9, desc as desc51, eq as eq115, gte as gte30, gt as gt9, inArray as inArray53, isNull as isNull18, notInArray as notInArray4, or as or21 } from "drizzle-orm";
77751
+ var SYNC_FAILURE_WINDOW = 3;
77752
+ var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
77753
+ var SUCCESS_STATUSES = [RunStatuses.completed, RunStatuses.partial];
77754
+ function latestErrorText(raw) {
77755
+ const parsed = parseRunError(raw);
77756
+ return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
77757
+ }
77758
+ function readSyncRunState(db, projectId, kind, options = {}) {
77759
+ const scope = and98(
77760
+ eq115(runs.projectId, projectId),
77761
+ eq115(runs.kind, kind),
77762
+ ...options.sourceId ? [eq115(runs.sourceId, options.sourceId)] : [],
77763
+ ...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
77764
+ );
77765
+ const graded = options.since ? and98(scope, gte30(runs.createdAt, options.since)) : scope;
77766
+ const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and98(graded, inArray53(runs.status, FINISHED_STATUSES))).orderBy(desc51(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
77767
+ const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and98(graded, inArray53(runs.status, SUCCESS_STATUSES))).orderBy(desc51(runs.createdAt)).limit(1).get();
77768
+ const failureCount = db.select({ count: count9() }).from(runs).where(and98(lastSuccess ? and98(graded, gt9(runs.createdAt, lastSuccess.createdAt)) : graded, eq115(runs.status, RunStatuses.failed))).get();
77769
+ const failuresSinceSuccess = Number(failureCount?.count ?? 0);
77770
+ const latest = recent[0];
77771
+ return {
77772
+ latestStatus: latest?.status ?? null,
77773
+ latestRunAt: latest?.createdAt ?? null,
77774
+ latestRunId: latest?.id ?? null,
77775
+ latestTrigger: latest?.trigger ?? null,
77776
+ latestError: latest?.status === RunStatuses.failed ? latestErrorText(latest.error) : null,
77777
+ lastSuccessAt: lastSuccess ? lastSuccess.finishedAt ?? lastSuccess.createdAt : null,
77778
+ consecutiveFailures: failuresSinceSuccess,
77779
+ repeatedFailure: recent.length >= SYNC_FAILURE_WINDOW && recent.every((run) => run.status === RunStatuses.failed)
77780
+ };
77781
+ }
77782
+
77783
+ // ../api-routes/src/doctor/checks/data-freshness.ts
77688
77784
  var GA_DATA_AGING_DAYS = 3;
77689
77785
  var GA_DATA_STALE_DAYS = 5;
77690
77786
  var GSC_DATA_AGING_DAYS = 5;
@@ -77693,6 +77789,7 @@ var BING_DATA_AGING_DAYS = 7;
77693
77789
  var SYNC_IDLE_DAYS = 3;
77694
77790
  var NOT_SYNCING_URGENT_DAYS = 8;
77695
77791
  var GSC_REPORTING_TIME_ZONE2 = "America/Los_Angeles";
77792
+ var SUMMARY_ERROR_LIMIT = 300;
77696
77793
  var DAY_MS6 = 24 * 60 * 60 * 1e3;
77697
77794
  var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
77698
77795
  function utcFromIsoDate(date) {
@@ -77713,8 +77810,8 @@ function daysSinceDate(date, now = /* @__PURE__ */ new Date(), timeZone) {
77713
77810
  function skipped(code, summary3) {
77714
77811
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
77715
77812
  }
77716
- function lastSyncAgeDays(ctx, kinds) {
77717
- const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and98(eq115(runs.projectId, ctx.project.id), inArray53(runs.kind, kinds), eq115(runs.status, "completed"))).orderBy(desc51(runs.createdAt)).limit(1).get();
77813
+ function lastSyncAgeDays(ctx, kind) {
77814
+ const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and99(eq116(runs.projectId, ctx.project.id), eq116(runs.kind, kind), eq116(runs.status, RunStatuses.completed))).orderBy(desc52(runs.createdAt)).limit(1).get();
77718
77815
  if (!row?.createdAt) return null;
77719
77816
  const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
77720
77817
  return Number.isFinite(age) ? age : null;
@@ -77723,7 +77820,7 @@ function grade(ctx, spec, newestDate) {
77723
77820
  const projectName = ctx.project.name;
77724
77821
  const code = (suffix) => `${spec.source}.data.${suffix}`;
77725
77822
  const sync = spec.syncCommand(projectName);
77726
- const syncAge = lastSyncAgeDays(ctx, spec.syncKinds);
77823
+ const syncAge = lastSyncAgeDays(ctx, spec.syncKind);
77727
77824
  const syncIdle = syncAge === null || syncAge >= SYNC_IDLE_DAYS;
77728
77825
  if (!newestDate) {
77729
77826
  return {
@@ -77754,6 +77851,26 @@ function grade(ctx, spec, newestDate) {
77754
77851
  details
77755
77852
  };
77756
77853
  }
77854
+ const syncState = readSyncRunState(ctx.db, ctx.project.id, spec.syncKind);
77855
+ if (syncState.latestStatus === RunStatuses.failed) {
77856
+ const errorText = syncState.latestError ?? "no error was recorded";
77857
+ const shownError = errorText.length > SUMMARY_ERROR_LIMIT ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT)}...` : errorText;
77858
+ const failures = syncState.consecutiveFailures;
77859
+ return {
77860
+ status: CheckStatuses.warn,
77861
+ code: code("sync-failing"),
77862
+ ...age >= spec.staleDays ? { urgent: true } : {},
77863
+ summary: `${failures <= 1 ? `The latest ${spec.label} sync` : `The last ${failures} ${spec.label} syncs`} failed, and stored data ends ${newestDate} (${age} days). Latest error: ${shownError}`,
77864
+ remediation: `Fix the cause the error names, then run \`${sync}\`.`,
77865
+ details: {
77866
+ ...details,
77867
+ consecutiveFailures: failures,
77868
+ latestRunAt: syncState.latestRunAt,
77869
+ latestError: syncState.latestError,
77870
+ lastSuccessAt: syncState.lastSuccessAt
77871
+ }
77872
+ };
77873
+ }
77757
77874
  if (syncIdle) {
77758
77875
  return {
77759
77876
  status: CheckStatuses.warn,
@@ -77783,7 +77900,7 @@ var GA_SPEC = {
77783
77900
  label: "GA4",
77784
77901
  agingDays: GA_DATA_AGING_DAYS,
77785
77902
  staleDays: GA_DATA_STALE_DAYS,
77786
- syncKinds: ["ga-sync"],
77903
+ syncKind: RunKinds["ga-sync"],
77787
77904
  syncCommand: (name) => `canonry ga sync ${name}`,
77788
77905
  quietExplanation: "GA4 omits days with no sessions, so a genuinely quiet period clears itself on the next visit.",
77789
77906
  brokenExplanation: "If the site did have visitors, check that the GA4 tag or its Tag Manager container is still on the live site."
@@ -77794,7 +77911,7 @@ var GSC_SPEC = {
77794
77911
  agingDays: GSC_DATA_AGING_DAYS,
77795
77912
  staleDays: GSC_DATA_STALE_DAYS,
77796
77913
  timeZone: GSC_REPORTING_TIME_ZONE2,
77797
- syncKinds: ["gsc-sync"],
77914
+ syncKind: RunKinds["gsc-sync"],
77798
77915
  syncCommand: (name) => `canonry google sync ${name}`,
77799
77916
  quietExplanation: "Search Console omits days with no impressions and reports two to three days behind, so a quiet period clears itself.",
77800
77917
  brokenExplanation: "If the site did have impressions, check that the property still lists this site and the connected account still has access."
@@ -77816,7 +77933,7 @@ var gaRecentDataCheck = {
77816
77933
  const connection = gaConnected(ctx);
77817
77934
  if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
77818
77935
  if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
77819
- const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq115(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc51(gaDailyTotals.date)).limit(1).get();
77936
+ const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq116(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc52(gaDailyTotals.date)).limit(1).get();
77820
77937
  return grade(ctx, GA_SPEC, newest?.date);
77821
77938
  }
77822
77939
  };
@@ -77831,16 +77948,16 @@ var gscRecentDataCheck = {
77831
77948
  if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
77832
77949
  return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
77833
77950
  }
77834
- const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq115(gscDataWatermarks.projectId, ctx.project.id)).get();
77951
+ const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq116(gscDataWatermarks.projectId, ctx.project.id)).get();
77835
77952
  if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
77836
- const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq115(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc51(gscDailyTotals.date)).limit(1).get();
77953
+ const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq116(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc52(gscDailyTotals.date)).limit(1).get();
77837
77954
  return grade(ctx, GSC_SPEC, newest?.date);
77838
77955
  }
77839
77956
  };
77840
77957
  var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
77841
77958
 
77842
77959
  // ../api-routes/src/doctor/checks/seo-refresh.ts
77843
- import { and as and99, asc as asc29, desc as desc52, eq as eq116, gt as gt9, inArray as inArray54, sql as sql49 } from "drizzle-orm";
77960
+ import { and as and100, asc as asc29, desc as desc53, eq as eq117, gt as gt10, inArray as inArray54, sql as sql49 } from "drizzle-orm";
77844
77961
  var GRACE_DAYS = 2;
77845
77962
  var DAY_MS7 = 24 * 60 * 60 * 1e3;
77846
77963
  var FIRING_SPAN_MS = 6e4;
@@ -77849,7 +77966,7 @@ function skipped2(code, summary3) {
77849
77966
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
77850
77967
  }
77851
77968
  function seoSyncRuns(projectId) {
77852
- return and99(eq116(runs.projectId, projectId), eq116(runs.kind, RunKinds["seo-sync"]));
77969
+ return and100(eq117(runs.projectId, projectId), eq117(runs.kind, RunKinds["seo-sync"]));
77853
77970
  }
77854
77971
  function scheduleTiming(schedule) {
77855
77972
  if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
@@ -77857,16 +77974,16 @@ function scheduleTiming(schedule) {
77857
77974
  return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
77858
77975
  }
77859
77976
  function latestFiring(ctx, projectId, enabledSince) {
77860
- const scheduled = and99(seoSyncRuns(projectId), eq116(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
77861
- const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc52(runs.createdAt)).limit(1).get();
77977
+ const scheduled = and100(seoSyncRuns(projectId), eq117(runs.trigger, RunTriggers.scheduled), gt10(runs.createdAt, enabledSince));
77978
+ const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc53(runs.createdAt)).limit(1).get();
77862
77979
  if (!newest) return [];
77863
77980
  const newestMs = Date.parse(newest.createdAt);
77864
77981
  const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
77865
- return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and99(scheduled, gt9(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
77982
+ return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and100(scheduled, gt10(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
77866
77983
  }
77867
77984
  function lastCompleted(ctx, projectId) {
77868
77985
  const at = sql49`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
77869
- return ctx.db.select({ id: runs.id, at }).from(runs).where(and99(seoSyncRuns(projectId), eq116(runs.status, RunStatuses.completed))).orderBy(desc52(at)).limit(1).get() ?? null;
77986
+ return ctx.db.select({ id: runs.id, at }).from(runs).where(and100(seoSyncRuns(projectId), eq117(runs.status, RunStatuses.completed))).orderBy(desc53(at)).limit(1).get() ?? null;
77870
77987
  }
77871
77988
  function isIncomplete(run) {
77872
77989
  return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
@@ -77880,7 +77997,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
77880
77997
  const incomplete = firing.filter(isIncomplete);
77881
77998
  const firedAt = firing[firing.length - 1]?.createdAt;
77882
77999
  if (incomplete.length === 0 || !firedAt) return incomplete;
77883
- const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq116(seoJobs.runId, runs.id)).where(and99(seoSyncRuns(projectId), eq116(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
78000
+ const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq117(seoJobs.runId, runs.id)).where(and100(seoSyncRuns(projectId), eq117(runs.status, RunStatuses.completed), gt10(runs.createdAt, firedAt))).all().map((row) => row.profileId));
77884
78001
  return incomplete.filter((run) => {
77885
78002
  const profile = profiles.get(run.id) ?? null;
77886
78003
  return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
@@ -77890,7 +78007,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
77890
78007
  function refreshReason(ctx, run) {
77891
78008
  const stored = parseRunError(run.error);
77892
78009
  if (stored) return formatRunErrorOneLine(stored);
77893
- const tasks = currentSeoTasks(ctx.db.select({ id: seoTasks.id, retryOf: seoTasks.retryOf, status: seoTasks.status, error: seoTasks.error, request: seoTasks.request }).from(seoTasks).innerJoin(seoJobs, eq116(seoTasks.jobId, seoJobs.id)).where(eq116(seoJobs.runId, run.id)).all());
78010
+ const tasks = currentSeoTasks(ctx.db.select({ id: seoTasks.id, retryOf: seoTasks.retryOf, status: seoTasks.status, error: seoTasks.error, request: seoTasks.request }).from(seoTasks).innerJoin(seoJobs, eq117(seoTasks.jobId, seoJobs.id)).where(eq117(seoJobs.runId, run.id)).all());
77894
78011
  const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
77895
78012
  const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
77896
78013
  const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
@@ -77910,7 +78027,7 @@ function refreshReason(ctx, run) {
77910
78027
  return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
77911
78028
  }
77912
78029
  function gradeSeoRefresh(ctx, project) {
77913
- const schedule = ctx.db.select().from(schedules).where(and99(eq116(schedules.projectId, project.id), eq116(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
78030
+ const schedule = ctx.db.select().from(schedules).where(and100(eq117(schedules.projectId, project.id), eq117(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
77914
78031
  if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
77915
78032
  if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
77916
78033
  const name = project.name;
@@ -77982,7 +78099,7 @@ function gradeSeoRefresh(ctx, project) {
77982
78099
  };
77983
78100
  }
77984
78101
  if (now >= Date.parse(deadlineAt)) {
77985
- const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and99(seoSyncRuns(project.id), inArray54(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
78102
+ const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and100(seoSyncRuns(project.id), inArray54(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
77986
78103
  const since = last ? `No SEO refresh has completed since ${day(last.at)}.` : "No SEO refresh has completed since the schedule was enabled.";
77987
78104
  const missed = last ? `The scheduled refresh due ${day(dueAt)} did not complete within ${GRACE_DAYS} days.` : `Its first refresh, due ${day(dueAt)}, did not complete within ${GRACE_DAYS} days.`;
77988
78105
  return {
@@ -78292,7 +78409,7 @@ var siteReachabilityCheck = {
78292
78409
  var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
78293
78410
 
78294
78411
  // ../api-routes/src/doctor/checks/api-hosts.ts
78295
- import { eq as eq118 } from "drizzle-orm";
78412
+ import { eq as eq119 } from "drizzle-orm";
78296
78413
 
78297
78414
  // ../api-routes/src/api-host-probe.ts
78298
78415
  import dns4 from "dns/promises";
@@ -78398,11 +78515,8 @@ async function probeApiHost(host, options = {}) {
78398
78515
  }
78399
78516
 
78400
78517
  // ../api-routes/src/doctor/checks/integration-sync.ts
78401
- import { and as and100, count as count9, desc as desc53, eq as eq117, gte as gte30, gt as gt10, inArray as inArray55, isNull as isNull18, notInArray as notInArray4, or as or21 } from "drizzle-orm";
78402
- var SYNC_FAILURE_WINDOW = 3;
78403
- var SUMMARY_ERROR_LIMIT = 300;
78404
- var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
78405
- var SUCCESS_STATUSES = [RunStatuses.completed, RunStatuses.partial];
78518
+ import { and as and101, eq as eq118 } from "drizzle-orm";
78519
+ var SUMMARY_ERROR_LIMIT2 = 300;
78406
78520
  var GBP_NOTHING_TO_SYNC_ERRORS = [serializeRunError({ message: GBP_NO_SELECTED_LOCATIONS_ERROR })];
78407
78521
  var CONNECTED = { state: "connected", since: null };
78408
78522
  function googleMarketingConnection(provider) {
@@ -78425,7 +78539,7 @@ function gscConnection(ctx, project) {
78425
78539
  function gbpConnection(ctx, project) {
78426
78540
  if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
78427
78541
  if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
78428
- const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and100(eq117(gbpLocations.projectId, project.id), eq117(gbpLocations.selected, true))).limit(1).get();
78542
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and101(eq118(gbpLocations.projectId, project.id), eq118(gbpLocations.selected, true))).limit(1).get();
78429
78543
  return selected ? CONNECTED : { state: "no-selected-locations" };
78430
78544
  }
78431
78545
  function gaConnection(ctx, project) {
@@ -78493,34 +78607,6 @@ var SPECS = [
78493
78607
  function skipped4(code, summary3) {
78494
78608
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
78495
78609
  }
78496
- function latestErrorText(raw) {
78497
- const parsed = parseRunError(raw);
78498
- return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
78499
- }
78500
- function readSyncRunState(db, projectId, kind, options = {}) {
78501
- const scope = and100(
78502
- eq117(runs.projectId, projectId),
78503
- eq117(runs.kind, kind),
78504
- ...options.sourceId ? [eq117(runs.sourceId, options.sourceId)] : [],
78505
- ...options.nothingToSyncErrors?.length ? [or21(isNull18(runs.error), notInArray4(runs.error, [...options.nothingToSyncErrors]))] : []
78506
- );
78507
- const graded = options.since ? and100(scope, gte30(runs.createdAt, options.since)) : scope;
78508
- const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and100(graded, inArray55(runs.status, FINISHED_STATUSES))).orderBy(desc53(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
78509
- const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and100(graded, inArray55(runs.status, SUCCESS_STATUSES))).orderBy(desc53(runs.createdAt)).limit(1).get();
78510
- const failureCount = db.select({ count: count9() }).from(runs).where(and100(lastSuccess ? and100(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq117(runs.status, RunStatuses.failed))).get();
78511
- const failuresSinceSuccess = Number(failureCount?.count ?? 0);
78512
- const latest = recent[0];
78513
- return {
78514
- latestStatus: latest?.status ?? null,
78515
- latestRunAt: latest?.createdAt ?? null,
78516
- latestRunId: latest?.id ?? null,
78517
- latestTrigger: latest?.trigger ?? null,
78518
- latestError: latest?.status === RunStatuses.failed ? latestErrorText(latest.error) : null,
78519
- lastSuccessAt: lastSuccess ? lastSuccess.finishedAt ?? lastSuccess.createdAt : null,
78520
- consecutiveFailures: failuresSinceSuccess,
78521
- repeatedFailure: recent.length >= SYNC_FAILURE_WINDOW && recent.every((run) => run.status === RunStatuses.failed)
78522
- };
78523
- }
78524
78610
  function gradeSyncFailures(ctx, spec) {
78525
78611
  const code = (suffix) => `${spec.prefix}.sync.${suffix}`;
78526
78612
  const project = ctx.project;
@@ -78554,7 +78640,7 @@ function gradeSyncFailures(ctx, spec) {
78554
78640
  };
78555
78641
  if (state.repeatedFailure) {
78556
78642
  const errorText = state.latestError ?? "no error was recorded";
78557
- const shownError = errorText.length > SUMMARY_ERROR_LIMIT ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT)}...` : errorText;
78643
+ const shownError = errorText.length > SUMMARY_ERROR_LIMIT2 ? `${truncateUtf16(errorText, SUMMARY_ERROR_LIMIT2)}...` : errorText;
78558
78644
  const lastSuccessText = state.lastSuccessAt ?? (connection.since ? `none since connecting at ${connection.since}` : "never");
78559
78645
  const notFound2 = spec.notFoundRemediation && /\bwas not found\b/i.test(errorText);
78560
78646
  return {
@@ -78604,7 +78690,7 @@ function connectionFor(prefix, ctx, project) {
78604
78690
  if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
78605
78691
  if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
78606
78692
  if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
78607
- return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq118(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
78693
+ return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq119(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
78608
78694
  }
78609
78695
  function syncCommand(prefix) {
78610
78696
  if (prefix === "gsc") return "google sync";
@@ -78649,7 +78735,7 @@ function definition(prefix) {
78649
78735
  var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
78650
78736
 
78651
78737
  // ../api-routes/src/doctor/checks/gbp-auth.ts
78652
- import { and as and101, eq as eq119 } from "drizzle-orm";
78738
+ import { and as and102, eq as eq120 } from "drizzle-orm";
78653
78739
  var RECENT_SYNC_WARN_DAYS = 4;
78654
78740
  var RECENT_SYNC_FAIL_DAYS = 30;
78655
78741
  function skippedNoProject3() {
@@ -78669,7 +78755,7 @@ function storeUnavailable() {
78669
78755
  };
78670
78756
  }
78671
78757
  function hasSelectedLocation(ctx, projectId) {
78672
- return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and101(eq119(gbpLocations.projectId, projectId), eq119(gbpLocations.selected, true))).limit(1).get();
78758
+ return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and102(eq120(gbpLocations.projectId, projectId), eq120(gbpLocations.selected, true))).limit(1).get();
78673
78759
  }
78674
78760
  async function resolveGbpToken(ctx) {
78675
78761
  if (!ctx.project) return { ok: false, output: skippedNoProject3() };
@@ -78929,7 +79015,7 @@ var recentSyncCheck = {
78929
79015
  title: "GBP recent sync",
78930
79016
  run: (ctx) => {
78931
79017
  if (!ctx.project) return skippedNoProject3();
78932
- const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and101(eq119(gbpLocations.projectId, ctx.project.id), eq119(gbpLocations.selected, true))).all();
79018
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and102(eq120(gbpLocations.projectId, ctx.project.id), eq120(gbpLocations.selected, true))).all();
78933
79019
  if (selected.length === 0) {
78934
79020
  return {
78935
79021
  status: CheckStatuses.skipped,
@@ -78989,7 +79075,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
78989
79075
  );
78990
79076
 
78991
79077
  // ../api-routes/src/doctor/checks/places.ts
78992
- import { eq as eq120 } from "drizzle-orm";
79078
+ import { eq as eq121 } from "drizzle-orm";
78993
79079
  var apiKeyCheck = {
78994
79080
  id: "gbp.places.api-key",
78995
79081
  category: CheckCategories.auth,
@@ -79034,7 +79120,7 @@ var apiKeyCheck = {
79034
79120
  details: { tier: cfg.tier }
79035
79121
  };
79036
79122
  }
79037
- const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq120(gbpLocations.projectId, ctx.project.id)).all();
79123
+ const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq121(gbpLocations.projectId, ctx.project.id)).all();
79038
79124
  const selected = rows.filter((r) => r.selected);
79039
79125
  const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
79040
79126
  const details = {
@@ -79067,7 +79153,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
79067
79153
  );
79068
79154
 
79069
79155
  // ../api-routes/src/doctor/checks/gbp-reviews.ts
79070
- import { and as and102, desc as desc54, eq as eq121, gte as gte31, inArray as inArray56, sql as sql50 } from "drizzle-orm";
79156
+ import { and as and103, desc as desc54, eq as eq122, gte as gte31, inArray as inArray55, sql as sql50 } from "drizzle-orm";
79071
79157
  var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
79072
79158
  var V4_ACCESS_REMEDIATION = "Business Profile reviews use the legacy My Business API (mybusiness.googleapis.com), which Google enables per Cloud project only on request; the API Library and `gcloud services enable` cannot turn it on. Open the enable link in the API access approval email as the approved account, or reply to the access-request thread asking Google to enable mybusiness.googleapis.com for your project number, then run `canonry gbp sync`.";
79073
79159
  var reviewsAccessCheck = {
@@ -79095,7 +79181,7 @@ var reviewsAccessCheck = {
79095
79181
  reviewsAccess: gbpLocations.reviewsAccess,
79096
79182
  reviewsAccessReason: gbpLocations.reviewsAccessReason,
79097
79183
  reviewsCheckedAt: gbpLocations.reviewsCheckedAt
79098
- }).from(gbpLocations).where(and102(eq121(gbpLocations.projectId, project.id), eq121(gbpLocations.selected, true))).all();
79184
+ }).from(gbpLocations).where(and103(eq122(gbpLocations.projectId, project.id), eq122(gbpLocations.selected, true))).all();
79099
79185
  if (locations.length === 0) {
79100
79186
  return {
79101
79187
  status: CheckStatuses.skipped,
@@ -79115,7 +79201,7 @@ var reviewsAccessCheck = {
79115
79201
  const places = ctx.getPlacesConfig?.();
79116
79202
  const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
79117
79203
  const v4Worked = new Set(
79118
- ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and102(eq121(gbpReviewRatings.projectId, project.id), eq121(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
79204
+ ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and103(eq122(gbpReviewRatings.projectId, project.id), eq122(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
79119
79205
  );
79120
79206
  const coverageOf = (loc) => {
79121
79207
  if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
@@ -79149,7 +79235,7 @@ var reviewsAccessCheck = {
79149
79235
  none > 0 ? `${none} have no review source` : null
79150
79236
  ].filter((part) => part !== null);
79151
79237
  const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
79152
- const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq121(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
79238
+ const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq122(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
79153
79239
  const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
79154
79240
  if (none > 0 && subscribed) {
79155
79241
  return {
@@ -79188,9 +79274,9 @@ var reviewDeliveryCheck = {
79188
79274
  attempts: reviewWebhookDeliveries.attempts,
79189
79275
  lastTouched,
79190
79276
  payload: reviewWebhookDeliveries.payload
79191
- }).from(reviewWebhookDeliveries).where(and102(
79192
- eq121(reviewWebhookDeliveries.projectId, ctx.project.id),
79193
- inArray56(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
79277
+ }).from(reviewWebhookDeliveries).where(and103(
79278
+ eq122(reviewWebhookDeliveries.projectId, ctx.project.id),
79279
+ inArray55(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
79194
79280
  gte31(lastTouched, since)
79195
79281
  )).orderBy(desc54(lastTouched)).all();
79196
79282
  if (rows.length === 0) {
@@ -79201,7 +79287,7 @@ var reviewDeliveryCheck = {
79201
79287
  remediation: null
79202
79288
  };
79203
79289
  }
79204
- const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq121(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
79290
+ const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq122(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
79205
79291
  const deliveries = rows.map((row) => {
79206
79292
  const review = row.payload.reviews[0];
79207
79293
  return {
@@ -79775,7 +79861,7 @@ var RUNTIME_STATE_CHECKS = [
79775
79861
  ];
79776
79862
 
79777
79863
  // ../api-routes/src/doctor/checks/traffic-source.ts
79778
- import { and as and103, desc as desc55, eq as eq122, gte as gte32, inArray as inArray57, isNotNull as isNotNull11, ne as ne18, sql as sql51 } from "drizzle-orm";
79864
+ import { and as and104, desc as desc55, eq as eq123, gte as gte32, inArray as inArray56, isNotNull as isNotNull11, ne as ne18, sql as sql51 } from "drizzle-orm";
79779
79865
  var RECENT_DATA_WARN_DAYS = 7;
79780
79866
  var RECENT_DATA_FAIL_DAYS = 30;
79781
79867
  function isCloudflareQueuePull(source) {
@@ -79809,8 +79895,8 @@ function skippedNoProject5() {
79809
79895
  function loadProbes(ctx) {
79810
79896
  if (!ctx.project) return [];
79811
79897
  const rows = ctx.db.select().from(trafficSources).where(
79812
- and103(
79813
- eq122(trafficSources.projectId, ctx.project.id),
79898
+ and104(
79899
+ eq123(trafficSources.projectId, ctx.project.id),
79814
79900
  ne18(trafficSources.status, TrafficSourceStatuses.archived)
79815
79901
  )
79816
79902
  ).all();
@@ -79973,27 +80059,27 @@ var recentDataCheck = {
79973
80059
  const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
79974
80060
  const recentCrawlers = Number(
79975
80061
  ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
79976
- and103(
79977
- eq122(crawlerEventsHourly.projectId, ctx.project.id),
79978
- inArray57(crawlerEventsHourly.sourceId, activeSourceIds),
80062
+ and104(
80063
+ eq123(crawlerEventsHourly.projectId, ctx.project.id),
80064
+ inArray56(crawlerEventsHourly.sourceId, activeSourceIds),
79979
80065
  gte32(crawlerEventsHourly.tsHour, warnCutoff)
79980
80066
  )
79981
80067
  ).get()?.total ?? 0
79982
80068
  );
79983
80069
  const recentReferrals = Number(
79984
80070
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
79985
- and103(
79986
- eq122(aiReferralEventsHourly.projectId, ctx.project.id),
79987
- inArray57(aiReferralEventsHourly.sourceId, activeSourceIds),
80071
+ and104(
80072
+ eq123(aiReferralEventsHourly.projectId, ctx.project.id),
80073
+ inArray56(aiReferralEventsHourly.sourceId, activeSourceIds),
79988
80074
  gte32(aiReferralEventsHourly.tsHour, warnCutoff)
79989
80075
  )
79990
80076
  ).get()?.total ?? 0
79991
80077
  );
79992
80078
  const recentUserFetches = Number(
79993
80079
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
79994
- and103(
79995
- eq122(aiUserFetchEventsHourly.projectId, ctx.project.id),
79996
- inArray57(aiUserFetchEventsHourly.sourceId, activeSourceIds),
80080
+ and104(
80081
+ eq123(aiUserFetchEventsHourly.projectId, ctx.project.id),
80082
+ inArray56(aiUserFetchEventsHourly.sourceId, activeSourceIds),
79997
80083
  gte32(aiUserFetchEventsHourly.tsHour, warnCutoff)
79998
80084
  )
79999
80085
  ).get()?.total ?? 0
@@ -80017,27 +80103,27 @@ var recentDataCheck = {
80017
80103
  }
80018
80104
  const olderCrawlers = Number(
80019
80105
  ctx.db.select({ total: sql51`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
80020
- and103(
80021
- eq122(crawlerEventsHourly.projectId, ctx.project.id),
80022
- inArray57(crawlerEventsHourly.sourceId, activeSourceIds),
80106
+ and104(
80107
+ eq123(crawlerEventsHourly.projectId, ctx.project.id),
80108
+ inArray56(crawlerEventsHourly.sourceId, activeSourceIds),
80023
80109
  gte32(crawlerEventsHourly.tsHour, failCutoff)
80024
80110
  )
80025
80111
  ).get()?.total ?? 0
80026
80112
  );
80027
80113
  const olderReferrals = Number(
80028
80114
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
80029
- and103(
80030
- eq122(aiReferralEventsHourly.projectId, ctx.project.id),
80031
- inArray57(aiReferralEventsHourly.sourceId, activeSourceIds),
80115
+ and104(
80116
+ eq123(aiReferralEventsHourly.projectId, ctx.project.id),
80117
+ inArray56(aiReferralEventsHourly.sourceId, activeSourceIds),
80032
80118
  gte32(aiReferralEventsHourly.tsHour, failCutoff)
80033
80119
  )
80034
80120
  ).get()?.total ?? 0
80035
80121
  );
80036
80122
  const olderUserFetches = Number(
80037
80123
  ctx.db.select({ total: sql51`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
80038
- and103(
80039
- eq122(aiUserFetchEventsHourly.projectId, ctx.project.id),
80040
- inArray57(aiUserFetchEventsHourly.sourceId, activeSourceIds),
80124
+ and104(
80125
+ eq123(aiUserFetchEventsHourly.projectId, ctx.project.id),
80126
+ inArray56(aiUserFetchEventsHourly.sourceId, activeSourceIds),
80041
80127
  gte32(aiUserFetchEventsHourly.tsHour, failCutoff)
80042
80128
  )
80043
80129
  ).get()?.total ?? 0
@@ -80363,10 +80449,10 @@ var syncLagCheck = {
80363
80449
  }
80364
80450
  };
80365
80451
  function lastQueueStopReason(ctx, sourceId) {
80366
- const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and103(
80367
- eq122(runs.projectId, ctx.project.id),
80368
- eq122(runs.kind, RunKinds["traffic-sync"]),
80369
- eq122(runs.sourceId, sourceId),
80452
+ const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and104(
80453
+ eq123(runs.projectId, ctx.project.id),
80454
+ eq123(runs.kind, RunKinds["traffic-sync"]),
80455
+ eq123(runs.sourceId, sourceId),
80370
80456
  isNotNull11(runs.syncSummary)
80371
80457
  )).orderBy(desc55(runs.createdAt)).limit(1).get();
80372
80458
  return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
@@ -81166,7 +81252,7 @@ async function doctorRoutes(app, opts) {
81166
81252
  }
81167
81253
 
81168
81254
  // ../api-routes/src/status.ts
81169
- import { and as and104, desc as desc56, eq as eq123, isNull as isNull19 } from "drizzle-orm";
81255
+ import { and as and105, desc as desc56, eq as eq124, isNull as isNull19 } from "drizzle-orm";
81170
81256
  function ageDays(iso2) {
81171
81257
  if (!iso2) return null;
81172
81258
  const ms = Date.now() - Date.parse(iso2);
@@ -81216,7 +81302,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
81216
81302
  };
81217
81303
  }
81218
81304
  function latestDate2(db, table, projectId) {
81219
- const row = db.select({ date: table.date }).from(table).where(eq123(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
81305
+ const row = db.select({ date: table.date }).from(table).where(eq124(table.projectId, projectId)).orderBy(desc56(table.date)).limit(1).get();
81220
81306
  return row?.date ?? null;
81221
81307
  }
81222
81308
  function projectRows(opts, project) {
@@ -81231,7 +81317,7 @@ function projectRows(opts, project) {
81231
81317
  const rows = [];
81232
81318
  const gsc = gscConnection(ctx, info);
81233
81319
  if (connected(gsc)) {
81234
- const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq123(gscDataWatermarks.projectId, project.id)).limit(1).get();
81320
+ const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq124(gscDataWatermarks.projectId, project.id)).limit(1).get();
81235
81321
  const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
81236
81322
  const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
81237
81323
  rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
@@ -81247,12 +81333,12 @@ function projectRows(opts, project) {
81247
81333
  rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
81248
81334
  rows.push(makeRow("bing-search", "Bing search data", RunKinds["bing-sync"], readSyncRunState(opts.db, project.id, RunKinds["bing-sync"]), SYNC_IDLE_DAYS, latestDate2(opts.db, bingTrafficDaily, project.id), null, ["bing.sync.recent-failures"], BING_DATA_AGING_DAYS));
81249
81335
  }
81250
- const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq123(adsConnections.projectId, project.id)).limit(1).get();
81336
+ const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq124(adsConnections.projectId, project.id)).limit(1).get();
81251
81337
  if (ads) rows.push(makeRow("ads", "OpenAI Ads", RunKinds["ads-sync"], readSyncRunState(opts.db, project.id, RunKinds["ads-sync"]), ADS_RECENT_SYNC_WARN_DAYS, null, null, ["ads.data.recent-sync"], ADS_RECENT_SYNC_WARN_DAYS, ads.lastSyncedAt));
81252
81338
  const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
81253
81339
  if (marketing?.googleAds) rows.push(makeRow("google-ads", "Google Ads", RunKinds["google-ads-sync"], readSyncRunState(opts.db, project.id, RunKinds["google-ads-sync"]), FRESH_SNAPSHOT_WARN_DAYS, null, null, ["google-ads.sync.recent-failures"], FRESH_SNAPSHOT_WARN_DAYS, marketing.googleAds.latestSnapshotAt));
81254
81340
  if (marketing?.gtm) rows.push(makeRow("gtm", "Google Tag Manager", RunKinds["gtm-sync"], readSyncRunState(opts.db, project.id, RunKinds["gtm-sync"]), FRESH_SNAPSHOT_WARN_DAYS, null, null, ["gtm.sync.recent-failures"], FRESH_SNAPSHOT_WARN_DAYS, marketing.gtm.latestSnapshotAt));
81255
- const sources = opts.db.select().from(trafficSources).where(and104(eq123(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
81341
+ const sources = opts.db.select().from(trafficSources).where(and105(eq124(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
81256
81342
  for (const source of sources) {
81257
81343
  const row = makeRow("traffic", source.displayName, RunKinds["traffic-sync"], readSyncRunState(opts.db, project.id, RunKinds["traffic-sync"], { sourceId: source.id }), null, null, source.id, ["traffic.source.sync-lag", "traffic.source.recent-data"]);
81258
81344
  const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
@@ -81264,7 +81350,7 @@ function projectRows(opts, project) {
81264
81350
  }
81265
81351
  function projectStatus(opts, project) {
81266
81352
  const integrations = projectRows(opts, project);
81267
- const healthRow = opts.db.select().from(doctorHealthState).where(eq123(doctorHealthState.projectId, project.id)).limit(1).get();
81353
+ const healthRow = opts.db.select().from(doctorHealthState).where(eq124(doctorHealthState.projectId, project.id)).limit(1).get();
81268
81354
  const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
81269
81355
  const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
81270
81356
  const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
@@ -81284,7 +81370,7 @@ async function statusRoutes(app, opts) {
81284
81370
  if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
81285
81371
  return instanceStatusDtoSchema.parse(result);
81286
81372
  }
81287
- const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq123(projects.id, scopedId)) : opts.db.select().from(projects)).all();
81373
+ const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq124(projects.id, scopedId)) : opts.db.select().from(projects)).all();
81288
81374
  const output = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), ...opts.getMcpHealth ? { mcp: opts.getMcpHealth() } : {}, summary: { projects: projectsRows.length, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: projectsRows.map((project) => projectStatus(opts, project)) };
81289
81375
  for (const project of output.projects) {
81290
81376
  const key = project.state === "never-synced" ? "neverSynced" : project.state;
@@ -81297,7 +81383,7 @@ async function statusRoutes(app, opts) {
81297
81383
 
81298
81384
  // ../api-routes/src/discovery/routes.ts
81299
81385
  import crypto64 from "crypto";
81300
- import { and as and105, desc as desc57, eq as eq124, gte as gte33, inArray as inArray58, isNull as isNull20, or as or22 } from "drizzle-orm";
81386
+ import { and as and106, desc as desc57, eq as eq125, gte as gte33, inArray as inArray57, isNull as isNull20, or as or22 } from "drizzle-orm";
81301
81387
  var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
81302
81388
  async function discoveryRoutes(app, opts) {
81303
81389
  app.post("/projects/:name/discover/run", async (request, reply) => {
@@ -81331,13 +81417,13 @@ async function discoveryRoutes(app, opts) {
81331
81417
  const now = (/* @__PURE__ */ new Date()).toISOString();
81332
81418
  const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
81333
81419
  const decision = app.db.transaction((tx) => {
81334
- const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and105(
81335
- eq124(discoverySessions.projectId, project.id),
81336
- eq124(discoverySessions.icpDescription, icpDescription),
81420
+ const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and106(
81421
+ eq125(discoverySessions.projectId, project.id),
81422
+ eq125(discoverySessions.icpDescription, icpDescription),
81337
81423
  // Buyer is part of session identity: it changes the seed prompt's
81338
81424
  // semantics, so a request with a different (or no) buyer must start
81339
81425
  // its own session, never adopt another buyer's probes.
81340
- parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq124(discoverySessions.buyerDescription, parsed.data.buyerDescription),
81426
+ parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq125(discoverySessions.buyerDescription, parsed.data.buyerDescription),
81341
81427
  // Locations are identity too: a different service-area subset seeds
81342
81428
  // and probes a different geo, so it must never reuse another geo's
81343
81429
  // session. resolveLocations is deterministic (project-config order),
@@ -81347,12 +81433,12 @@ async function discoveryRoutes(app, opts) {
81347
81433
  // locations a NULL row's subset is unknowable, so it conservatively
81348
81434
  // never reuses — a one-time, bounded (2h window) non-reuse after
81349
81435
  // upgrade, never a wrong reuse.
81350
- locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq124(discoverySessions.locations, locations)) : eq124(discoverySessions.locations, locations),
81436
+ locations.length === 0 ? or22(isNull20(discoverySessions.locations), eq125(discoverySessions.locations, locations)) : eq125(discoverySessions.locations, locations),
81351
81437
  // Seed provider set is identity: a different phrasing distribution
81352
81438
  // must never reuse another set's session. Null (= Gemini-only
81353
81439
  // default, including explicit ['gemini']) matches legacy rows.
81354
- seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq124(discoverySessions.seedProviders, seedProviders),
81355
- inArray58(discoverySessions.status, [
81440
+ seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq125(discoverySessions.seedProviders, seedProviders),
81441
+ inArray57(discoverySessions.status, [
81356
81442
  DiscoverySessionStatuses.queued,
81357
81443
  DiscoverySessionStatuses.seeding,
81358
81444
  DiscoverySessionStatuses.probing
@@ -81427,7 +81513,7 @@ async function discoveryRoutes(app, opts) {
81427
81513
  const project = resolveProject(app.db, request.params.name);
81428
81514
  const parsedLimit = parseInt(request.query.limit ?? "", 10);
81429
81515
  const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
81430
- const rows = app.db.select().from(discoverySessions).where(eq124(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
81516
+ const rows = app.db.select().from(discoverySessions).where(eq125(discoverySessions.projectId, project.id)).orderBy(desc57(discoverySessions.createdAt)).limit(limit).all();
81431
81517
  return reply.send(rows.map(serializeSession));
81432
81518
  }
81433
81519
  );
@@ -81435,11 +81521,11 @@ async function discoveryRoutes(app, opts) {
81435
81521
  "/projects/:name/discover/sessions/:id",
81436
81522
  async (request, reply) => {
81437
81523
  const project = resolveProject(app.db, request.params.name);
81438
- const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81524
+ const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
81439
81525
  if (!session || session.projectId !== project.id) {
81440
81526
  throw notFound("Discovery session", request.params.id);
81441
81527
  }
81442
- const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81528
+ const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
81443
81529
  const detail = {
81444
81530
  ...serializeSession(session),
81445
81531
  probes: probeRows.map(serializeProbe)
@@ -81453,7 +81539,7 @@ async function discoveryRoutes(app, opts) {
81453
81539
  requireAdminSession(request);
81454
81540
  requirePaidReadScope(request, [], "Discovery harvest requires wildcard (*) API key scope because it can call the embedding provider.");
81455
81541
  const project = resolveProject(app.db, request.params.name);
81456
- const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81542
+ const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
81457
81543
  if (!session || session.projectId !== project.id) {
81458
81544
  throw notFound("Discovery session", request.params.id);
81459
81545
  }
@@ -81461,7 +81547,7 @@ async function discoveryRoutes(app, opts) {
81461
81547
  const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
81462
81548
  const applyAnchor = request.query.anchor !== "false";
81463
81549
  const provider = session.seedProvider ?? "gemini";
81464
- const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81550
+ const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
81465
81551
  const extract = opts.harvestSearchQueries;
81466
81552
  const probesWithQueries = probeRows.map((row) => {
81467
81553
  if (!extract || !row.rawResponse) return { searchQueries: [] };
@@ -81472,7 +81558,7 @@ async function discoveryRoutes(app, opts) {
81472
81558
  return { searchQueries: [] };
81473
81559
  }
81474
81560
  });
81475
- const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq124(queries.projectId, project.id)).all().map((r) => r.query);
81561
+ const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq125(queries.projectId, project.id)).all().map((r) => r.query);
81476
81562
  const anchorTerms = buildHarvestAnchorTerms(
81477
81563
  [session.icpDescription ?? "", ...trackedQueries],
81478
81564
  effectiveDomains(project)
@@ -81519,11 +81605,11 @@ async function discoveryRoutes(app, opts) {
81519
81605
  "/projects/:name/discover/sessions/:id/promote",
81520
81606
  async (request, reply) => {
81521
81607
  const project = resolveProject(app.db, request.params.name);
81522
- const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81608
+ const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
81523
81609
  if (!session || session.projectId !== project.id) {
81524
81610
  throw notFound("Discovery session", request.params.id);
81525
81611
  }
81526
- const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81612
+ const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
81527
81613
  const cited = /* @__PURE__ */ new Set();
81528
81614
  const aspirational = /* @__PURE__ */ new Set();
81529
81615
  const wasted = /* @__PURE__ */ new Set();
@@ -81558,7 +81644,7 @@ async function discoveryRoutes(app, opts) {
81558
81644
  );
81559
81645
  app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
81560
81646
  const project = resolveProject(app.db, request.params.name);
81561
- const session = app.db.select().from(discoverySessions).where(eq124(discoverySessions.id, request.params.id)).get();
81647
+ const session = app.db.select().from(discoverySessions).where(eq125(discoverySessions.id, request.params.id)).get();
81562
81648
  if (!session || session.projectId !== project.id) {
81563
81649
  throw notFound("Discovery session", request.params.id);
81564
81650
  }
@@ -81581,7 +81667,7 @@ async function discoveryRoutes(app, opts) {
81581
81667
  const bucketSet = new Set(buckets);
81582
81668
  const includeCompetitors = parsed.data.includeCompetitors ?? true;
81583
81669
  const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
81584
- const probeRows = app.db.select().from(discoveryProbes).where(eq124(discoveryProbes.sessionId, session.id)).all();
81670
+ const probeRows = app.db.select().from(discoveryProbes).where(eq125(discoveryProbes.sessionId, session.id)).all();
81585
81671
  const candidateQueries = /* @__PURE__ */ new Set();
81586
81672
  for (const probe of probeRows) {
81587
81673
  if (!probe.bucket) continue;
@@ -81589,7 +81675,7 @@ async function discoveryRoutes(app, opts) {
81589
81675
  if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
81590
81676
  }
81591
81677
  const existingQueries = new Set(
81592
- app.db.select({ query: queries.query }).from(queries).where(eq124(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
81678
+ app.db.select({ query: queries.query }).from(queries).where(eq125(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
81593
81679
  );
81594
81680
  const promotedQueries = [];
81595
81681
  const skippedQueries = [];
@@ -81803,7 +81889,7 @@ function planCompetitorPromotion(input) {
81803
81889
 
81804
81890
  // ../api-routes/src/discovery/orchestrate.ts
81805
81891
  import crypto65 from "crypto";
81806
- import { eq as eq125 } from "drizzle-orm";
81892
+ import { eq as eq126 } from "drizzle-orm";
81807
81893
  var DEFAULT_MAX_PROBES = 100;
81808
81894
  var ABSOLUTE_MAX_PROBES = 500;
81809
81895
  function classifyProbeBucket(input) {
@@ -81889,7 +81975,7 @@ async function executeDiscovery(opts) {
81889
81975
  status: DiscoverySessionStatuses.seeding,
81890
81976
  dedupThreshold,
81891
81977
  startedAt
81892
- }).where(eq125(discoverySessions.id, opts.sessionId)).run();
81978
+ }).where(eq126(discoverySessions.id, opts.sessionId)).run();
81893
81979
  const seedResult = await opts.deps.seed({
81894
81980
  project: opts.project,
81895
81981
  icpDescription: opts.icpDescription,
@@ -81950,7 +82036,7 @@ async function executeDiscovery(opts) {
81950
82036
  dedupBandPairFraction: dedupStats.bandPairFraction,
81951
82037
  dedupPairsTotal: dedupStats.pairsTotal,
81952
82038
  warning
81953
- }).where(eq125(discoverySessions.id, opts.sessionId)).run();
82039
+ }).where(eq126(discoverySessions.id, opts.sessionId)).run();
81954
82040
  const probeLocation = opts.locations?.[0];
81955
82041
  const probeResults = await mapWithConcurrency(
81956
82042
  probedCanonicals,
@@ -82004,7 +82090,7 @@ async function executeDiscovery(opts) {
82004
82090
  wastedCount: buckets["wasted-surface"],
82005
82091
  competitorMap,
82006
82092
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
82007
- }).where(eq125(discoverySessions.id, opts.sessionId)).run();
82093
+ }).where(eq126(discoverySessions.id, opts.sessionId)).run();
82008
82094
  upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
82009
82095
  return {
82010
82096
  buckets,
@@ -82044,7 +82130,7 @@ function markSessionFailed(db, sessionId, error) {
82044
82130
  status: DiscoverySessionStatuses.failed,
82045
82131
  error,
82046
82132
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
82047
- }).where(eq125(discoverySessions.id, sessionId)).run();
82133
+ }).where(eq126(discoverySessions.id, sessionId)).run();
82048
82134
  }
82049
82135
  function dedupeStrings(input) {
82050
82136
  const seen2 = /* @__PURE__ */ new Set();
@@ -82061,7 +82147,7 @@ function dedupeStrings(input) {
82061
82147
  }
82062
82148
 
82063
82149
  // ../api-routes/src/trends.ts
82064
- import { and as and106, asc as asc30, eq as eq126 } from "drizzle-orm";
82150
+ import { and as and107, asc as asc30, eq as eq127 } from "drizzle-orm";
82065
82151
  function parseSurface(value) {
82066
82152
  const parsed = trendSurfaceSchema.safeParse(value);
82067
82153
  if (!parsed.success) {
@@ -82117,8 +82203,8 @@ async function trendsRoutes(app) {
82117
82203
  function readSurface(app, projectId, surface) {
82118
82204
  switch (surface) {
82119
82205
  case TrendSurfaces["index-coverage"]: {
82120
- const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq126(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
82121
- const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq126(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
82206
+ const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq127(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
82207
+ const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq127(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
82122
82208
  const coverage = (key, label, rows) => ({
82123
82209
  key,
82124
82210
  label,
@@ -82130,7 +82216,7 @@ function readSurface(app, projectId, surface) {
82130
82216
  return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
82131
82217
  }
82132
82218
  case TrendSurfaces["site-health"]: {
82133
- const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq126(siteAuditSnapshots.runId, runs.id)).where(and106(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
82219
+ const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq127(siteAuditSnapshots.runId, runs.id)).where(and107(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
82134
82220
  return [{
82135
82221
  key: "site-health",
82136
82222
  label: "Agent Readiness",
@@ -82142,7 +82228,7 @@ function readSurface(app, projectId, surface) {
82142
82228
  }
82143
82229
  case TrendSurfaces.backlinks: {
82144
82230
  const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
82145
- const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and106(eq126(backlinkSummaries.projectId, projectId), eq126(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
82231
+ const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and107(eq127(backlinkSummaries.projectId, projectId), eq127(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
82146
82232
  const filtered = totals.get(row.release);
82147
82233
  const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
82148
82234
  const windowEnd = releaseWindowEndMonth(row.release);
@@ -82172,7 +82258,7 @@ function readSurface(app, projectId, surface) {
82172
82258
  // ../api-routes/src/research.ts
82173
82259
  import crypto66 from "crypto";
82174
82260
  import { z as z7 } from "zod";
82175
- import { and as and107, count as count10, desc as desc58, eq as eq127, gte as gte34, lt as lt21, or as or23, sql as sql52 } from "drizzle-orm";
82261
+ import { and as and108, count as count10, desc as desc58, eq as eq128, gte as gte34, lt as lt21, or as or23, sql as sql52 } from "drizzle-orm";
82176
82262
  var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
82177
82263
  var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
82178
82264
  async function researchRoutes(app, opts) {
@@ -82191,7 +82277,7 @@ async function researchRoutes(app, opts) {
82191
82277
  const input = parsed.data;
82192
82278
  if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
82193
82279
  const requestHash2 = directResearchRequestHash(input);
82194
- const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and107(eq127(researchRuns.projectId, project.id), eq127(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
82280
+ const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and108(eq128(researchRuns.projectId, project.id), eq128(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
82195
82281
  if (existingReceipt) {
82196
82282
  assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
82197
82283
  const result2 = getDetail(app, project.id, existingReceipt.id);
@@ -82226,7 +82312,7 @@ async function researchRoutes(app, opts) {
82226
82312
  const initiatedBy = researchPrincipal(request);
82227
82313
  const decision = app.db.transaction((tx) => {
82228
82314
  if (input.idempotencyKey) {
82229
- const existing = tx.select().from(researchRuns).where(and107(eq127(researchRuns.projectId, project.id), eq127(researchRuns.idempotencyKey, input.idempotencyKey))).get();
82315
+ const existing = tx.select().from(researchRuns).where(and108(eq128(researchRuns.projectId, project.id), eq128(researchRuns.idempotencyKey, input.idempotencyKey))).get();
82230
82316
  if (existing) {
82231
82317
  assertSameDirectResearchRequest(existing, input, requestHash2);
82232
82318
  return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
@@ -82234,8 +82320,8 @@ async function researchRoutes(app, opts) {
82234
82320
  }
82235
82321
  if (initiatedBy?.limited) {
82236
82322
  const { start, end, date } = utcDayBounds(now);
82237
- const used = tx.select({ value: count10() }).from(researchRuns).where(and107(
82238
- eq127(researchRuns.projectId, project.id),
82323
+ const used = tx.select({ value: count10() }).from(researchRuns).where(and108(
82324
+ eq128(researchRuns.projectId, project.id),
82239
82325
  gte34(researchRuns.createdAt, start),
82240
82326
  lt21(researchRuns.createdAt, end),
82241
82327
  sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
@@ -82266,15 +82352,15 @@ async function researchRoutes(app, opts) {
82266
82352
  if (input.idempotencyKey.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
82267
82353
  const requestHash2 = researchBatchRequestHash(input);
82268
82354
  const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
82269
- const firstReceipt = app.db.select().from(researchRuns).where(and107(
82270
- eq127(researchRuns.projectId, project.id),
82271
- eq127(researchRuns.idempotencyKey, receiptKeys[0])
82355
+ const firstReceipt = app.db.select().from(researchRuns).where(and108(
82356
+ eq128(researchRuns.projectId, project.id),
82357
+ eq128(researchRuns.idempotencyKey, receiptKeys[0])
82272
82358
  )).get();
82273
82359
  if (firstReceipt) {
82274
82360
  if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
82275
- const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and107(
82276
- eq127(researchRuns.projectId, project.id),
82277
- eq127(researchRuns.idempotencyKey, key)
82361
+ const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and108(
82362
+ eq128(researchRuns.projectId, project.id),
82363
+ eq128(researchRuns.idempotencyKey, key)
82278
82364
  )).get());
82279
82365
  if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
82280
82366
  const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
@@ -82290,8 +82376,8 @@ async function researchRoutes(app, opts) {
82290
82376
  const decision = app.db.transaction((tx) => {
82291
82377
  if (initiatedBy?.limited) {
82292
82378
  const { start, end, date } = utcDayBounds(now);
82293
- const used = tx.select({ value: count10() }).from(researchRuns).where(and107(
82294
- eq127(researchRuns.projectId, project.id),
82379
+ const used = tx.select({ value: count10() }).from(researchRuns).where(and108(
82380
+ eq128(researchRuns.projectId, project.id),
82295
82381
  gte34(researchRuns.createdAt, start),
82296
82382
  lt21(researchRuns.createdAt, end),
82297
82383
  sql52`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
@@ -82345,9 +82431,9 @@ async function researchRoutes(app, opts) {
82345
82431
  const requested = Number.parseInt(request.query.limit ?? "", 10);
82346
82432
  const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
82347
82433
  const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
82348
- const rows = app.db.select().from(researchRuns).where(and107(
82349
- eq127(researchRuns.projectId, project.id),
82350
- cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and107(eq127(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
82434
+ const rows = app.db.select().from(researchRuns).where(and108(
82435
+ eq128(researchRuns.projectId, project.id),
82436
+ cursor ? or23(lt21(researchRuns.createdAt, cursor.createdAt), and108(eq128(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
82351
82437
  )).orderBy(desc58(researchRuns.createdAt), desc58(researchRuns.id)).limit(limit + 1).all();
82352
82438
  const runs2 = rows.slice(0, limit).map(serializeRun);
82353
82439
  const last = runs2.at(-1);
@@ -82497,9 +82583,9 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
82497
82583
  return stored;
82498
82584
  }
82499
82585
  function resolveResearchTemplate(app, projectId, selection, scope, location) {
82500
- const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and107(
82501
- eq127(measurementQueryTemplates.projectId, projectId),
82502
- eq127(measurementQueryTemplates.id, selection.templateId)
82586
+ const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and108(
82587
+ eq128(measurementQueryTemplates.projectId, projectId),
82588
+ eq128(measurementQueryTemplates.id, selection.templateId)
82503
82589
  )).get();
82504
82590
  if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
82505
82591
  const templateVersion = savedTemplate.updatedAt;
@@ -82508,7 +82594,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
82508
82594
  }
82509
82595
  const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
82510
82596
  if (bindingLocation) {
82511
- const project = app.db.select({ locations: projects.locations }).from(projects).where(eq127(projects.id, projectId)).get();
82597
+ const project = app.db.select({ locations: projects.locations }).from(projects).where(eq128(projects.id, projectId)).get();
82512
82598
  if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
82513
82599
  }
82514
82600
  const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
@@ -82521,9 +82607,9 @@ function classifyResearchQueries(project, plan, queries2) {
82521
82607
  return queries2.map((query2) => classifier?.classify(query2) ?? null);
82522
82608
  }
82523
82609
  function getDetail(app, projectId, id) {
82524
- const row = app.db.select().from(researchRuns).where(and107(eq127(researchRuns.id, id), eq127(researchRuns.projectId, projectId))).get();
82610
+ const row = app.db.select().from(researchRuns).where(and108(eq128(researchRuns.id, id), eq128(researchRuns.projectId, projectId))).get();
82525
82611
  if (!row) throw notFound("Research run", id);
82526
- const queries2 = app.db.select().from(researchRunQueries).where(eq127(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
82612
+ const queries2 = app.db.select().from(researchRunQueries).where(eq128(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
82527
82613
  return { ...serializeRun(row), queries: queries2 };
82528
82614
  }
82529
82615
  function serializeRun(row) {
@@ -82584,7 +82670,7 @@ function utcDayBounds(now) {
82584
82670
 
82585
82671
  // ../api-routes/src/simple-measurement-definitions.ts
82586
82672
  import crypto67 from "crypto";
82587
- import { and as and108, eq as eq128 } from "drizzle-orm";
82673
+ import { and as and109, eq as eq129 } from "drizzle-orm";
82588
82674
  function captureSimpleMeasurementDefinition(db, input) {
82589
82675
  return db.transaction((tx) => {
82590
82676
  const run = tx.select({
@@ -82592,7 +82678,7 @@ function captureSimpleMeasurementDefinition(db, input) {
82592
82678
  trigger: runs.trigger,
82593
82679
  status: runs.status,
82594
82680
  measurementPlanVersionId: runs.measurementPlanVersionId
82595
- }).from(runs).where(and108(eq128(runs.projectId, input.projectId), eq128(runs.id, input.runId))).get();
82681
+ }).from(runs).where(and109(eq129(runs.projectId, input.projectId), eq129(runs.id, input.runId))).get();
82596
82682
  if (!run) throw notFound("Run", input.runId);
82597
82683
  if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
82598
82684
  return null;
@@ -82613,7 +82699,7 @@ function captureSimpleMeasurementDefinition(db, input) {
82613
82699
  throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
82614
82700
  }
82615
82701
  }
82616
- const existing = tx.select().from(simpleMeasurementDefinitions).where(and108(eq128(simpleMeasurementDefinitions.projectId, input.projectId), eq128(simpleMeasurementDefinitions.runId, input.runId))).get();
82702
+ const existing = tx.select().from(simpleMeasurementDefinitions).where(and109(eq129(simpleMeasurementDefinitions.projectId, input.projectId), eq129(simpleMeasurementDefinitions.runId, input.runId))).get();
82617
82703
  if (existing) {
82618
82704
  const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
82619
82705
  const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
@@ -82639,15 +82725,15 @@ function captureSimpleMeasurementDefinition(db, input) {
82639
82725
  if (run.status !== RunStatuses.running) {
82640
82726
  throw validationError("Only a running run can capture a new measurement definition.");
82641
82727
  }
82642
- if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq128(querySnapshots.runId, input.runId)).limit(1).get()) {
82728
+ if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq129(querySnapshots.runId, input.runId)).limit(1).get()) {
82643
82729
  throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
82644
82730
  }
82645
- const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq128(queries.projectId, input.projectId)).all().map((query2) => query2.id));
82731
+ const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq129(queries.projectId, input.projectId)).all().map((query2) => query2.id));
82646
82732
  if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
82647
82733
  throw validationError("Every captured query must belong to the run project.");
82648
82734
  }
82649
82735
  if (definition2.competitors !== void 0) {
82650
- const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq128(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
82736
+ const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq129(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
82651
82737
  const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
82652
82738
  if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
82653
82739
  throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");