@canonry/canonry 7.106.0 → 7.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/assets/assets/{AccessControls-Cbocxgkh.js → AccessControls-B6bkOAge.js} +1 -1
  2. package/assets/assets/{AgentSetupPage-D8LsXJij.js → AgentSetupPage-DpAEnB3w.js} +4 -4
  3. package/assets/assets/AuditHistoryPanel-Cmm537Mw.js +1 -0
  4. package/assets/assets/{BacklinksPage-Ddf4OvEj.js → BacklinksPage-Dg6IJr83.js} +1 -1
  5. package/assets/assets/{ChartPrimitives-CKzua7sC.js → ChartPrimitives-C1meaNiX.js} +1 -1
  6. package/assets/assets/{HistoryPage-DohLtlfb.js → HistoryPage-DMmZ0fSd.js} +1 -1
  7. package/assets/assets/MeasurementPropertyPage-ChCEhCKX.js +4 -0
  8. package/assets/assets/ProjectPage-B42XeJQf.js +15 -0
  9. package/assets/assets/{RunsPage-Cq1TApLF.js → RunsPage-C6fUugLg.js} +1 -1
  10. package/assets/assets/{ServerTrafficSection-0YU8gKto.js → ServerTrafficSection-BkH0owR_.js} +1 -1
  11. package/assets/assets/{SettingsPage-Cwsr4lLw.js → SettingsPage-CSsTnTJz.js} +1 -1
  12. package/assets/assets/ToneBadge-BkNG9buI.js +60 -0
  13. package/assets/assets/{TrafficPage-CPMbzmqd.js → TrafficPage-BNH-yhiN.js} +1 -1
  14. package/assets/assets/{TrafficSourceDetailPage-RH27Yg7N.js → TrafficSourceDetailPage-Ce4hROUh.js} +1 -1
  15. package/assets/assets/{account-context-D9R5l1HJ.js → account-context-C66suepK.js} +1 -1
  16. package/assets/assets/agent-trust-copy-BKQRIoVJ.js +1 -0
  17. package/assets/assets/{card-J9bPWQbl.js → card-iPmHn3JZ.js} +1 -1
  18. package/assets/assets/index-9cWtJSDg.js +43 -0
  19. package/assets/assets/{query-client-DBo8qiYc.js → query-client-D_jULVYr.js} +1 -1
  20. package/assets/assets/react-query-ih29UP0I.js +1 -0
  21. package/assets/assets/{react-sigma_core.esm.min-6RHzHzDv.js → react-sigma_core.esm.min-C7Pkr6r0.js} +1 -1
  22. package/assets/assets/{server-traffic-k_xJuKFO.js → server-traffic-BScF0-_t.js} +1 -1
  23. package/assets/assets/{service-DGCFoxhm.js → service-DYJdF5mP.js} +1 -1
  24. package/assets/index.html +8 -8
  25. package/dist/{ads-PZ3XRR3G.js → ads-IJHKPMDL.js} +3 -3
  26. package/dist/{agent-XSNYX5UT.js → agent-X5SDBTII.js} +7 -7
  27. package/dist/{agent-ask-JLTMBXNF.js → agent-ask-UPROPFVK.js} +3 -3
  28. package/dist/{agent-conversations-ZE4T4FNS.js → agent-conversations-A7W74X6Q.js} +3 -3
  29. package/dist/{agent-journeys-BD3Z5DK6.js → agent-journeys-WOLFWP3G.js} +3 -3
  30. package/dist/{agent-memory-WX56VBOU.js → agent-memory-TH6ORG63.js} +3 -3
  31. package/dist/{agent-providers-CJTXJSZX.js → agent-providers-FKVRHV4J.js} +7 -3
  32. package/dist/{agent-transcript-AYTSM4SW.js → agent-transcript-UFEBYD4L.js} +3 -3
  33. package/dist/{analytics-OFNC3HM7.js → analytics-XNFXAKRP.js} +3 -3
  34. package/dist/{apply-WTICVOOL.js → apply-O46BRKQG.js} +3 -3
  35. package/dist/{backfill-WBJNVGP7.js → backfill-IUCWBDEI.js} +10 -10
  36. package/dist/{backlinks-N5AV2VX7.js → backlinks-PB2Y3APJ.js} +3 -3
  37. package/dist/{bing-ZTRTEF7T.js → bing-YOUZDEA2.js} +3 -3
  38. package/dist/{bootstrap-E277KW5U.js → bootstrap-E4EI2W54.js} +10 -10
  39. package/dist/{cdp-LOIU5NYH.js → cdp-72553DTZ.js} +7 -7
  40. package/dist/{chunk-V6M3NFTI.js → chunk-2S25YWMO.js} +1 -1
  41. package/dist/{chunk-A3AV433T.js → chunk-3XYCTAL7.js} +3 -3
  42. package/dist/{chunk-D2KDCPQJ.js → chunk-46QQ3MQC.js} +1 -1
  43. package/dist/{chunk-BO6EC224.js → chunk-4FEKXZYP.js} +5 -5
  44. package/dist/{chunk-LG4SNIWY.js → chunk-5KH7Y233.js} +5 -5
  45. package/dist/{chunk-RUKWZBJA.js → chunk-6OBPZ6WK.js} +1 -1
  46. package/dist/{chunk-GFXEV6DH.js → chunk-6Y3I2QFU.js} +2 -2
  47. package/dist/{chunk-6SQCUQ6U.js → chunk-7K3EFBNK.js} +27 -1
  48. package/dist/{chunk-5FHMAF6G.js → chunk-7XDDCPZV.js} +1 -1
  49. package/dist/{chunk-P2QM24P2.js → chunk-AVBTCCAY.js} +2 -2
  50. package/dist/{chunk-WQ6FUYQR.js → chunk-BPKV6YLN.js} +7 -7
  51. package/dist/{chunk-OXRXWDJK.js → chunk-CLWAZBJY.js} +1 -1
  52. package/dist/{chunk-2IXEJCHX.js → chunk-CORHE557.js} +4 -4
  53. package/dist/{chunk-QS2SI5TV.js → chunk-E2ACURKW.js} +2 -2
  54. package/dist/{chunk-HJNF2N7E.js → chunk-EFY5C7ZJ.js} +4 -4
  55. package/dist/{chunk-UDXC2FQ6.js → chunk-F5EGU7NA.js} +533 -317
  56. package/dist/{chunk-U5LKR2UV.js → chunk-FU324DV3.js} +2 -2
  57. package/dist/{chunk-66JQPB3X.js → chunk-HABH5YAF.js} +1 -1
  58. package/dist/{chunk-UTGTX62K.js → chunk-HAOLFBSD.js} +3 -3
  59. package/dist/{chunk-Z7RXT2DB.js → chunk-HOKR2Q26.js} +1 -1
  60. package/dist/{chunk-5YPNDBMQ.js → chunk-IZMQNTWQ.js} +3 -3
  61. package/dist/{chunk-FTUOVEFL.js → chunk-JH6E6IV4.js} +2 -2
  62. package/dist/{chunk-HIOVULSX.js → chunk-K6HCS36A.js} +15 -8
  63. package/dist/{chunk-TKHPOC3U.js → chunk-LU3TWJX7.js} +3 -3
  64. package/dist/{chunk-MKMFIVWH.js → chunk-MA5VHGWC.js} +41 -16
  65. package/dist/{chunk-VXMVIGUT.js → chunk-NE3IYK64.js} +366 -366
  66. package/dist/{chunk-OMIPA5T6.js → chunk-OEV6HQ3X.js} +47 -2
  67. package/dist/{chunk-NJIBWTHC.js → chunk-PKD22D4H.js} +1 -1
  68. package/dist/{chunk-7IXLQHAD.js → chunk-PYLSLW6L.js} +1 -1
  69. package/dist/{chunk-67AGNLTZ.js → chunk-QJGQOAUK.js} +1 -1
  70. package/dist/{chunk-TZKO46SO.js → chunk-QNSTLSVL.js} +2 -2
  71. package/dist/{chunk-CCJE5BG3.js → chunk-SHCFV7PL.js} +3 -3
  72. package/dist/{chunk-RCP3BHTJ.js → chunk-UJURPSOP.js} +4 -4
  73. package/dist/{chunk-CFA3LAJJ.js → chunk-V342HTLC.js} +3 -3
  74. package/dist/{chunk-7B5GNQ3G.js → chunk-WJUF7P7N.js} +1 -1
  75. package/dist/{chunk-V4JLKXUO.js → chunk-WTNB7B2K.js} +1 -1
  76. package/dist/{citations-JH3WBX7R.js → citations-A3N7E44V.js} +4 -4
  77. package/dist/{cli-catalog-5HHVSBEH.js → cli-catalog-2IKVWAJ7.js} +3 -3
  78. package/dist/{cli-commands-B73KKOO6.js → cli-commands-5AMQ5NAA.js} +7 -7
  79. package/dist/cli.js +13 -13
  80. package/dist/{competitor-GF7GPQYB.js → competitor-CZV7O3YY.js} +3 -3
  81. package/dist/{content-22RTG35W.js → content-7Y6QZH2G.js} +3 -3
  82. package/dist/{dashboard-PZFD3VQ5.js → dashboard-OOCOW7VZ.js} +6 -6
  83. package/dist/{demo-57K6FDUC.js → demo-72QLTRMQ.js} +1 -1
  84. package/dist/{demo-server-I3XLUSVF.js → demo-server-NFJOZ6ZF.js} +12 -12
  85. package/dist/{discover-ACR3RBZE.js → discover-LUCA6O5X.js} +4 -4
  86. package/dist/{discover-eval-3NVZS6R2.js → discover-eval-U2XY45WE.js} +3 -3
  87. package/dist/{doctor-WS54RVZG.js → doctor-4O3ZZJAG.js} +3 -3
  88. package/dist/{evidence-JHCKHZO3.js → evidence-COM64MWY.js} +3 -3
  89. package/dist/{export-cmd-UIAGRYIA.js → export-cmd-HEQ5TZER.js} +3 -3
  90. package/dist/{ga-6EPQEMVL.js → ga-F5KCSFBL.js} +3 -3
  91. package/dist/{gbp-JJFU6ICP.js → gbp-GNHJKLUF.js} +3 -3
  92. package/dist/{google-TLMZRH3K.js → google-SAW6YWIC.js} +4 -4
  93. package/dist/{google-marketing-YJ4NXFDN.js → google-marketing-SIZWYSL2.js} +1 -1
  94. package/dist/{health-cmd-O25TFAJ4.js → health-cmd-5IZFIQK2.js} +4 -4
  95. package/dist/{history-FR6Q3CBK.js → history-O3VAYWT6.js} +3 -3
  96. package/dist/index.d.ts +152 -68
  97. package/dist/index.js +25 -25
  98. package/dist/{init-DD4J4YSS.js → init-SEFJNN5H.js} +12 -12
  99. package/dist/{insights-IBY5B5OX.js → insights-UFSQCY2N.js} +3 -3
  100. package/dist/intelligence-service-OZIEPTCK.js +16 -0
  101. package/dist/{journeys-KOI5QQFC.js → journeys-XUPV4POH.js} +3 -3
  102. package/dist/{keys-4AHY5IFK.js → keys-MWIC2RAM.js} +3 -3
  103. package/dist/{keyword-EQ6PELW6.js → keyword-BI6JIKFU.js} +3 -3
  104. package/dist/{logs-CE4WXN6H.js → logs-DJAPNQRC.js} +3 -3
  105. package/dist/{mcp-IWWBC34X.js → mcp-K7KJOU2D.js} +4 -4
  106. package/dist/mcp.js +9 -9
  107. package/dist/{measurement-plan-VDPSR7HK.js → measurement-plan-IZ3ONXKO.js} +5 -5
  108. package/dist/{notify-AHUVAGR4.js → notify-23XROT44.js} +3 -3
  109. package/dist/{organic-evidence-MVYEV5X3.js → organic-evidence-MY3YS2FV.js} +3 -3
  110. package/dist/{overview-45CO73FF.js → overview-XF3HRTRP.js} +5 -5
  111. package/dist/{project-7ZWHWZA7.js → project-BTX7G7RS.js} +3 -3
  112. package/dist/{project-setup-2LKZJCVC.js → project-setup-OEF4VHVO.js} +3 -3
  113. package/dist/{query-2JFQQKEN.js → query-67PA6WZ2.js} +3 -3
  114. package/dist/{research-H2F2SEAT.js → research-AFDDYAZS.js} +3 -3
  115. package/dist/{results-export-O4QDL4I4.js → results-export-6BI6P2MI.js} +3 -3
  116. package/dist/{run-AFKDOBRN.js → run-24TJZZXB.js} +5 -5
  117. package/dist/{schedule-YXCZGI3A.js → schedule-J2LIJ52P.js} +3 -3
  118. package/dist/{search-VN7AJZXJ.js → search-6RAWS2IO.js} +3 -3
  119. package/dist/{serve-UHEKKSYV.js → serve-HVYLYGAG.js} +26 -26
  120. package/dist/{session-44KQBO5V.js → session-ZZG6G4D7.js} +13 -13
  121. package/dist/{settings-4MEEQPDN.js → settings-UV6TFSYN.js} +3 -3
  122. package/dist/{sitemaps-MXAXJHNL.js → sitemaps-YVX6NKUG.js} +3 -3
  123. package/dist/{skills-AJBTHIRA.js → skills-6GYQKVDM.js} +2 -2
  124. package/dist/{snapshot-WWC7XSR3.js → snapshot-N6RFEDB5.js} +3 -3
  125. package/dist/{src-LMTA4CFF.js → src-U2E6JQJF.js} +4 -2
  126. package/dist/{status-S6RC3TID.js → status-HZHN6UNX.js} +5 -5
  127. package/dist/{technical-aeo-MCY63IKX.js → technical-aeo-ZQD4Q7DP.js} +3 -3
  128. package/dist/{telemetry-MUVNMEEL.js → telemetry-GQA2LXOM.js} +4 -4
  129. package/dist/{tools-YRHUVB65.js → tools-XH6DGBGV.js} +11 -11
  130. package/dist/{traffic-2SLXGEFN.js → traffic-Y6T2OKJF.js} +5 -5
  131. package/dist/{trends-WKWU755Z.js → trends-DTHOUJUU.js} +3 -3
  132. package/dist/{users-5HHGV66M.js → users-JSG4WKPW.js} +3 -3
  133. package/dist/{visibility-stats-324HLULY.js → visibility-stats-4FW4DZSK.js} +4 -4
  134. package/dist/{wordpress-5VJS7NG5.js → wordpress-AHTU5C7M.js} +3 -3
  135. package/package.json +1 -1
  136. package/assets/assets/AuditHistoryPanel-DAoN-tMG.js +0 -1
  137. package/assets/assets/MeasurementPropertyPage-Bjno662S.js +0 -4
  138. package/assets/assets/ProjectPage-DHX8q69l.js +0 -15
  139. package/assets/assets/ToneBadge-B-o3PPLD.js +0 -60
  140. package/assets/assets/agent-trust-copy-CJRMqTZD.js +0 -1
  141. package/assets/assets/index-BDSlQWXJ.js +0 -43
  142. package/assets/assets/react-query-CS8RMm8t.js +0 -1
  143. package/dist/intelligence-service-4CAEDHVD.js +0 -16
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  AeroLlmUsageFeatures,
3
+ aeroTurnOperationId,
3
4
  aeroTurnStatus,
4
5
  aeroTurnUsage,
5
6
  aeroViewPrompt,
@@ -23,18 +24,18 @@ import {
23
24
  resolveConfiguredAgentProvider,
24
25
  resolveSessionProviderAndModel,
25
26
  setAeroSystemPrompt
26
- } from "./chunk-HIOVULSX.js";
27
+ } from "./chunk-K6HCS36A.js";
27
28
  import {
28
29
  answerServiceAdapters,
29
30
  answerServiceDescriptors
30
- } from "./chunk-7IXLQHAD.js";
31
+ } from "./chunk-PYLSLW6L.js";
31
32
  import {
32
33
  AeroToolProfiles,
33
34
  AeroToolScopes,
34
35
  buildAeroStateTools,
35
36
  isAeroToolProfile,
36
37
  truncateToolResult
37
- } from "./chunk-2IXEJCHX.js";
38
+ } from "./chunk-CORHE557.js";
38
39
  import {
39
40
  getGoogleAuthConfig,
40
41
  getGoogleConnection,
@@ -53,7 +54,7 @@ import {
53
54
  removeCloudflareTrafficConnection,
54
55
  removeCloudflareTrafficConnectionBySourceId,
55
56
  upsertCloudflareTrafficConnection
56
- } from "./chunk-67AGNLTZ.js";
57
+ } from "./chunk-QJGQOAUK.js";
57
58
  import {
58
59
  claudeAdapter,
59
60
  embedQueries,
@@ -65,7 +66,7 @@ import {
65
66
  openrouterAdapter,
66
67
  perplexityAdapter,
67
68
  startTrafficReclassification
68
- } from "./chunk-BO6EC224.js";
69
+ } from "./chunk-4FEKXZYP.js";
69
70
  import {
70
71
  classifyUsageSurface,
71
72
  createApiUsageTelemetry,
@@ -77,7 +78,7 @@ import {
77
78
  startOutcomeTimer,
78
79
  trackFeatureCompleted,
79
80
  trackInstallState
80
- } from "./chunk-HJNF2N7E.js";
81
+ } from "./chunk-EFY5C7ZJ.js";
81
82
  import {
82
83
  isLoopbackBindHost
83
84
  } from "./chunk-TSENU4GG.js";
@@ -85,7 +86,7 @@ import {
85
86
  isApiProviderRegistrable,
86
87
  isCdpProviderRegistrable,
87
88
  registeredProviderNames
88
- } from "./chunk-7B5GNQ3G.js";
89
+ } from "./chunk-WJUF7P7N.js";
89
90
  import {
90
91
  checkLatestVersionForServer,
91
92
  getOrCreateAnonymousId,
@@ -97,17 +98,17 @@ import {
97
98
  recordDashboardEvent,
98
99
  setTelemetryPreference,
99
100
  trackEvent
100
- } from "./chunk-QS2SI5TV.js";
101
+ } from "./chunk-E2ACURKW.js";
101
102
  import {
102
103
  createCanonryMcpServer
103
- } from "./chunk-CCJE5BG3.js";
104
+ } from "./chunk-SHCFV7PL.js";
104
105
  import {
105
106
  CANONRY_MCP_TIERS,
106
107
  CANONRY_MCP_TOOLKIT_NAMES
107
108
  } from "./chunk-YW6J3STO.js";
108
109
  import {
109
110
  ApiClient
110
- } from "./chunk-U5LKR2UV.js";
111
+ } from "./chunk-FU324DV3.js";
111
112
  import {
112
113
  AGENT_PROVIDERS,
113
114
  PROVIDER_MODELS,
@@ -142,21 +143,21 @@ import {
142
143
  saveConfigPatch,
143
144
  sentimentInstallReadiness,
144
145
  updateSharedProviderExecutionGate
145
- } from "./chunk-D2KDCPQJ.js";
146
+ } from "./chunk-46QQ3MQC.js";
146
147
  import {
147
148
  getBundledSkillSnapshots
148
- } from "./chunk-V4JLKXUO.js";
149
+ } from "./chunk-WTNB7B2K.js";
149
150
  import {
150
151
  computeFactorAverages,
151
152
  deleteSiteCrawlGraphLayout,
152
153
  persistSiteCrawlGraphLayout,
153
154
  prepareSiteCrawlGraphLayout,
154
155
  recordedSharePct
155
- } from "./chunk-P2QM24P2.js";
156
+ } from "./chunk-AVBTCCAY.js";
156
157
  import {
157
158
  CanonryMcpToolNames,
158
159
  canonryMcpTools
159
- } from "./chunk-A3AV433T.js";
160
+ } from "./chunk-3XYCTAL7.js";
160
161
  import {
161
162
  PACKAGE_VERSION
162
163
  } from "./chunk-AOJU5LKX.js";
@@ -165,16 +166,16 @@ import {
165
166
  } from "./chunk-HGMYEDAQ.js";
166
167
  import {
167
168
  IntelligenceService
168
- } from "./chunk-LG4SNIWY.js";
169
+ } from "./chunk-5KH7Y233.js";
169
170
  import {
170
171
  computeCitedCompetitorDomains,
171
172
  determineCitationState
172
- } from "./chunk-NJIBWTHC.js";
173
+ } from "./chunk-PKD22D4H.js";
173
174
  import {
174
175
  addLogListener,
175
176
  createFastifyLogger,
176
177
  createLogger
177
- } from "./chunk-TZKO46SO.js";
178
+ } from "./chunk-QNSTLSVL.js";
178
179
  import {
179
180
  BingApiError,
180
181
  CC_CACHE_DIR,
@@ -322,7 +323,7 @@ import {
322
323
  webhookResponseReason,
323
324
  webhookTargetRefusalReason,
324
325
  writeAuditLog
325
- } from "./chunk-MKMFIVWH.js";
326
+ } from "./chunk-MA5VHGWC.js";
326
327
  import {
327
328
  OperationalLogStore,
328
329
  SentimentIdempotencyConflict,
@@ -334,6 +335,7 @@ import {
334
335
  adsConnections,
335
336
  adsInsightsDaily,
336
337
  agentMemory,
338
+ agentProviderCooldowns,
337
339
  agentSessions,
338
340
  apiKeys,
339
341
  auditLog,
@@ -421,7 +423,7 @@ import {
421
423
  unrecognizedAgentEventsHourly,
422
424
  unrecognizedAgentNotifyState,
423
425
  usageCounters
424
- } from "./chunk-6SQCUQ6U.js";
426
+ } from "./chunk-7K3EFBNK.js";
425
427
  import {
426
428
  AGENT_MEMORY_VALUE_MAX_BYTES,
427
429
  AI_ENGINE_DOMAINS,
@@ -473,6 +475,8 @@ import {
473
475
  OPERATION_ACCESS_HEADER,
474
476
  OUTSTANDING_PROVIDER_BATCH_STATUSES,
475
477
  OperationAccesses,
478
+ OutcomeOperationKinds,
479
+ OutcomePhases,
476
480
  OutcomeReasonCodes,
477
481
  OutcomeStatuses,
478
482
  OutcomeSurfaces,
@@ -485,6 +489,7 @@ import {
485
489
  ProviderConnectionTestStatuses,
486
490
  ProviderConnectionsUnavailableReasons,
487
491
  ProviderDispatchModes,
492
+ ProviderErrorCodes,
488
493
  ProviderKinds,
489
494
  ProviderNames,
490
495
  ProviderReloadErrorReasons,
@@ -538,6 +543,7 @@ import {
538
543
  backoffDelayMs,
539
544
  bucketDuration,
540
545
  bucketOnboardingCount,
546
+ buildOutcomeDiagnostics,
541
547
  buildProviderRunError,
542
548
  buildRunErrorFromMessages,
543
549
  buildSimpleMeasurementDefinition,
@@ -616,7 +622,6 @@ import {
616
622
  isEligibleFor,
617
623
  isNegativeReviewRating,
618
624
  isOpenRouterRoute,
619
- isProviderAccountFailure,
620
625
  isReadOnlyKey,
621
626
  isRetryableHttpError,
622
627
  isSearchLocationIgnored,
@@ -699,7 +704,7 @@ import {
699
704
  winnabilityClassLabel,
700
705
  withRetry,
701
706
  withSkippedProviders
702
- } from "./chunk-OMIPA5T6.js";
707
+ } from "./chunk-OEV6HQ3X.js";
703
708
 
704
709
  // src/google-marketing-runtime.ts
705
710
  import crypto2 from "crypto";
@@ -3389,7 +3394,7 @@ import path6 from "path";
3389
3394
  import { isIP as isIP2 } from "net";
3390
3395
  import { fileURLToPath } from "url";
3391
3396
  import { setImmediate as yieldToEventLoop4 } from "timers/promises";
3392
- import { and as and31, eq as eq38, isNotNull as isNotNull5, isNull as isNull8, lte as lte3, max, ne as ne4, or as or4, sql as sql15 } from "drizzle-orm";
3397
+ import { and as and32, eq as eq38, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql15 } from "drizzle-orm";
3393
3398
 
3394
3399
  // src/seo-runtime.ts
3395
3400
  import { eq, inArray } from "drizzle-orm";
@@ -6453,7 +6458,7 @@ function nonBlank(value) {
6453
6458
  return trimmed ? trimmed : void 0;
6454
6459
  }
6455
6460
  function resolveBuildCommit(env = process.env) {
6456
- const embedded = true ? "49d7949e6f7e334419c4e857a03881602269f27b" : void 0;
6461
+ const embedded = true ? "83cab9f06c0f350c3a2477a1dc80ef730670f66e" : void 0;
6457
6462
  return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
6458
6463
  }
6459
6464
  function resolveInstanceIdentity(env = process.env) {
@@ -9114,6 +9119,8 @@ function writeCoverageSnapshot(db, projectId, runId, opts = {}) {
9114
9119
 
9115
9120
  // src/sync-outcome.ts
9116
9121
  import { eq as eq7 } from "drizzle-orm";
9122
+ import { randomUUID as randomUUID2 } from "crypto";
9123
+ var log3 = createLogger("RunOutcome");
9117
9124
  function storedRunTrigger(db, runId) {
9118
9125
  const row = db.select({ trigger: runs.trigger }).from(runs).where(eq7(runs.id, runId)).get();
9119
9126
  return typeof row?.trigger === "string" ? row.trigger : void 0;
@@ -9130,11 +9137,17 @@ function compactCounts(counts) {
9130
9137
  function startRunOutcome(db, runId, feature, operation) {
9131
9138
  const requested = currentOutcomeOrigin();
9132
9139
  const elapsed = startOutcomeTimer();
9140
+ const operationId = randomUUID2();
9141
+ log3.info("started", { operationId, runId, feature, operation });
9133
9142
  return (outcome) => {
9134
9143
  try {
9144
+ log3.info("completed", { operationId, runId, feature, operation, status: outcome.status });
9135
9145
  trackFeatureCompleted({
9136
9146
  feature,
9137
9147
  operation,
9148
+ operationId,
9149
+ operationKind: outcome.operationKind,
9150
+ diagnostics: outcome.diagnostics,
9138
9151
  ...runOrigin(storedRunTrigger(db, runId), requested),
9139
9152
  status: outcome.status,
9140
9153
  reasonCode: outcome.reasonCode,
@@ -9164,7 +9177,7 @@ function googleRunFailure(err) {
9164
9177
  }
9165
9178
 
9166
9179
  // src/gsc-sync.ts
9167
- var log3 = createLogger("GscSync");
9180
+ var log4 = createLogger("GscSync");
9168
9181
  var GSC_SITEMAP_INDEX_MAX_PER_SYNC = 20;
9169
9182
  function countOrNull(value) {
9170
9183
  if (value === void 0 || value === "") return null;
@@ -9264,12 +9277,12 @@ async function executeGscSync(db, runId, projectId, opts) {
9264
9277
  const endDate = formatIsoDateInTimeZone((/* @__PURE__ */ new Date()).toISOString(), GSC_REPORTING_TIME_ZONE);
9265
9278
  const days = opts.full ? 480 : opts.days ?? 30;
9266
9279
  const startDate = shiftIsoCalendarDate(endDate, -(days + lagOffset));
9267
- log3.info("fetch.start", { runId, projectId, propertyId: conn.propertyId, startDate, endDate });
9280
+ log4.info("fetch.start", { runId, projectId, propertyId: conn.propertyId, startDate, endDate });
9268
9281
  const rows = await fetchSearchAnalytics(accessToken, conn.propertyId, {
9269
9282
  startDate,
9270
9283
  endDate
9271
9284
  });
9272
- log3.info("fetch.complete", { runId, projectId, rowCount: rows.length });
9285
+ log4.info("fetch.complete", { runId, projectId, rowCount: rows.length });
9273
9286
  db.delete(gscSearchData).where(
9274
9287
  and6(
9275
9288
  eq8(gscSearchData.projectId, projectId),
@@ -9341,7 +9354,7 @@ async function executeGscSync(db, runId, projectId, opts) {
9341
9354
  }).run();
9342
9355
  }
9343
9356
  }
9344
- log3.info("daily-totals.complete", {
9357
+ log4.info("daily-totals.complete", {
9345
9358
  runId,
9346
9359
  projectId,
9347
9360
  rowCount: totalRows.length,
@@ -9377,22 +9390,22 @@ async function executeGscSync(db, runId, projectId, opts) {
9377
9390
  createdAt: queryTotalsNow
9378
9391
  }).run();
9379
9392
  }
9380
- log3.info("query-totals.complete", { runId, projectId, rowCount: queryTotalRows.length });
9393
+ log4.info("query-totals.complete", { runId, projectId, rowCount: queryTotalRows.length });
9381
9394
  try {
9382
9395
  const stored = await syncGscSitemaps(db, projectId, runId, accessToken, propertyId);
9383
- log3.info("sitemaps.complete", { runId, projectId, ...stored });
9396
+ log4.info("sitemaps.complete", { runId, projectId, ...stored });
9384
9397
  } catch (err) {
9385
- log3.warn("sitemaps.failed", { runId, projectId, error: describeError(err) });
9398
+ log4.warn("sitemaps.failed", { runId, projectId, error: describeError(err) });
9386
9399
  }
9387
9400
  const coverage = writeCoverageSnapshot(db, projectId, runId);
9388
9401
  db.update(runs).set({ status: "completed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq8(runs.id, runId)).run();
9389
- log3.info("sync.completed", { runId, projectId, searchDataRows: rows.length, indexed: coverage.indexed, notIndexed: coverage.notIndexed, unknown: coverage.unknown, verifiedByInspection: coverage.verifiedByInspection });
9402
+ log4.info("sync.completed", { runId, projectId, searchDataRows: rows.length, indexed: coverage.indexed, notIndexed: coverage.notIndexed, unknown: coverage.unknown, verifiedByInspection: coverage.verifiedByInspection });
9390
9403
  const counts = { rows: rows.length, urls: new Set(rows.map((row) => row.keys[1] ?? "")).size };
9391
9404
  reportOutcome(rows.length === 0 ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA, counts } : { status: OutcomeStatuses.succeeded, counts });
9392
9405
  } catch (err) {
9393
9406
  const errorMsg = describeError(err);
9394
9407
  db.update(runs).set({ status: "failed", error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq8(runs.id, runId)).run();
9395
- log3.error("sync.failed", { runId, projectId, error: errorMsg });
9408
+ log4.error("sync.failed", { runId, projectId, error: errorMsg });
9396
9409
  reportOutcome({ status: OutcomeStatuses.failed, ...googleRunFailure(err) });
9397
9410
  throw err;
9398
9411
  }
@@ -9405,7 +9418,7 @@ import { eq as eq10, and as and8, desc as desc4, inArray as inArray5, lt as lt2
9405
9418
  // src/gbp-reviews.ts
9406
9419
  import crypto11 from "crypto";
9407
9420
  import { and as and7, desc as desc3, eq as eq9, inArray as inArray4, sql as sql4 } from "drizzle-orm";
9408
- var log4 = createLogger("GbpReviews");
9421
+ var log5 = createLogger("GbpReviews");
9409
9422
  var MS_PER_DAY = 864e5;
9410
9423
  var REVIEW_ALERT_MAX_AGE_DAYS = 30;
9411
9424
  var REVIEW_PAGING_OVERLAP_DAYS = 7;
@@ -9473,12 +9486,12 @@ async function fetchLocationReviews(db, projectId, loc, ctx) {
9473
9486
  if (classified.projectWide) {
9474
9487
  if (!ctx.gate.projectWideReason) {
9475
9488
  ctx.gate.projectWideReason = classified.reason;
9476
- log4.info("reviews.unavailable", { runId: ctx.runId, reason: classified.reason });
9489
+ log5.info("reviews.unavailable", { runId: ctx.runId, reason: classified.reason });
9477
9490
  }
9478
9491
  } else if (classified.access === "error") {
9479
- log4.warn("reviews.failed", { runId: ctx.runId, location: loc.locationName, error: describeError(err) });
9492
+ log5.warn("reviews.failed", { runId: ctx.runId, location: loc.locationName, error: describeError(err) });
9480
9493
  } else {
9481
- log4.info("reviews.location-unavailable", { runId: ctx.runId, location: loc.locationName, reason: classified.reason });
9494
+ log5.info("reviews.location-unavailable", { runId: ctx.runId, location: loc.locationName, reason: classified.reason });
9482
9495
  }
9483
9496
  }
9484
9497
  }
@@ -9504,7 +9517,7 @@ async function fetchLocationReviews(db, projectId, loc, ctx) {
9504
9517
  }))
9505
9518
  });
9506
9519
  } catch (err) {
9507
- log4.warn("places-reviews.failed", { runId: ctx.runId, location: loc.locationName, error: describeError(err) });
9520
+ log5.warn("places-reviews.failed", { runId: ctx.runId, location: loc.locationName, error: describeError(err) });
9508
9521
  }
9509
9522
  }
9510
9523
  return { access, observations };
@@ -9619,7 +9632,7 @@ function sameRating(a, b) {
9619
9632
 
9620
9633
  // src/gbp-sync.ts
9621
9634
  var MS_PER_DAY2 = 864e5;
9622
- var log5 = createLogger("GbpSync");
9635
+ var log6 = createLogger("GbpSync");
9623
9636
  var LOCATION_CONCURRENCY = 4;
9624
9637
  var DEFAULT_DAYS_OF_METRICS = 30;
9625
9638
  var DEFAULT_MONTHS_OF_KEYWORDS = 12;
@@ -9710,7 +9723,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
9710
9723
  const trendMonths = Array.from({ length: KEYWORD_TREND_MONTHS }, (_, i) => monthMinus(i + 1));
9711
9724
  const keywordRetentionCutoff = monthKey(monthMinus(KEYWORD_HISTORY_RETENTION_MONTHS));
9712
9725
  const { apiKey: placesApiKey, tier: placesTier, refreshIntervalDays: placesRefreshDays } = getPlacesConfig(opts.config);
9713
- log5.info("sync.start", { runId, projectId, locations: locationRows.length, daysOfMetrics, monthsOfKeywords });
9726
+ log6.info("sync.start", { runId, projectId, locations: locationRows.length, daysOfMetrics, monthsOfKeywords });
9714
9727
  const negativeMaxStars = resolveNegativeReviewMaxStars(readNegativeReviewMaxStars(db, projectId));
9715
9728
  const reviewContext = {
9716
9729
  runId,
@@ -9779,7 +9792,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
9779
9792
  placeToTouch = latestPlace.id;
9780
9793
  }
9781
9794
  } catch (placesErr) {
9782
- log5.warn("places.failed", { runId, location: loc.locationName, error: describeError(placesErr) });
9795
+ log6.warn("places.failed", { runId, location: loc.locationName, error: describeError(placesErr) });
9783
9796
  }
9784
9797
  }
9785
9798
  }
@@ -9900,7 +9913,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
9900
9913
  for (const observation of reviewFetch.observations) {
9901
9914
  const persisted = persistReviewObservation(tx, projectId, runId, observation, { now: reviewNow, negativeMaxStars });
9902
9915
  if (persisted.queuedReviews > 0 || persisted.queuedRatingDrop) {
9903
- log5.info("reviews.queued", {
9916
+ log6.info("reviews.queued", {
9904
9917
  runId,
9905
9918
  location: loc.locationName,
9906
9919
  origin: observation.origin,
@@ -9927,7 +9940,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
9927
9940
  } catch (err) {
9928
9941
  lastLocationError = err;
9929
9942
  errors.set(loc.locationName, describeError(err));
9930
- log5.error("location.failed", { runId, location: loc.locationName, error: describeError(err) });
9943
+ log6.error("location.failed", { runId, location: loc.locationName, error: describeError(err) });
9931
9944
  }
9932
9945
  }));
9933
9946
  }
@@ -9947,7 +9960,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
9947
9960
  finishedAt
9948
9961
  }).where(eq10(runs.id, runId)).run();
9949
9962
  }
9950
- log5.info("sync.done", { runId, projectId, ok: okCount, failed: errors.size });
9963
+ log6.info("sync.done", { runId, projectId, ok: okCount, failed: errors.size });
9951
9964
  const counts = { rows: rowsWritten, items: okCount, failures: errors.size };
9952
9965
  reportOutcome(errors.size === 0 ? { status: OutcomeStatuses.succeeded, counts } : { status: okCount > 0 ? OutcomeStatuses.partial : OutcomeStatuses.failed, ...gbpRunFailure(lastLocationError), counts });
9953
9966
  const reviews = reviewsOutcome(reviewAccess, reviewsObserved, reviewsErrorReason ?? reviewsUnavailableReason);
@@ -9955,7 +9968,7 @@ async function executeGbpSync(db, runId, projectId, opts) {
9955
9968
  } catch (err) {
9956
9969
  const errorMsg = describeError(err);
9957
9970
  db.update(runs).set({ status: "failed", error: serializeRunError({ message: errorMsg }), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq10(runs.id, runId)).run();
9958
- log5.error("sync.failed", { runId, projectId, error: errorMsg });
9971
+ log6.error("sync.failed", { runId, projectId, error: errorMsg });
9959
9972
  reportOutcome({ status: OutcomeStatuses.failed, ...gbpRunFailure(err) });
9960
9973
  throw err;
9961
9974
  }
@@ -10571,7 +10584,7 @@ function removeOpenAiAdsConnection(config, projectName) {
10571
10584
  }
10572
10585
 
10573
10586
  // src/ads-sync.ts
10574
- var log6 = createLogger("AdsSync");
10587
+ var log7 = createLogger("AdsSync");
10575
10588
  var CAMPAIGN_INSIGHT_FIELDS = ["campaign.impressions", "campaign.clicks", "campaign.spend", "campaign.conversions", "metadata.readable_time"];
10576
10589
  var AD_GROUP_INSIGHT_FIELDS = ["ad_group.impressions", "ad_group.clicks", "ad_group.spend", "ad_group.conversions", "metadata.readable_time"];
10577
10590
  var CAMPAIGN_IN_PROGRESS_INSIGHT_FIELDS = CAMPAIGN_INSIGHT_FIELDS.filter((field) => field !== "campaign.conversions");
@@ -10629,7 +10642,7 @@ function toInsightUpserts(level, entityId, rows, opts) {
10629
10642
  const upserts = [];
10630
10643
  for (const row of rows) {
10631
10644
  if (!row.readable_time) {
10632
- log6.warn("insights.row-missing-date", { level, entityId, rowId: row.id });
10645
+ log7.warn("insights.row-missing-date", { level, entityId, rowId: row.id });
10633
10646
  continue;
10634
10647
  }
10635
10648
  upserts.push({
@@ -10674,7 +10687,7 @@ async function executeAdsSync(db, runId, projectId, opts) {
10674
10687
  );
10675
10688
  }
10676
10689
  const apiKey = cfgConn.apiKey;
10677
- log6.info("sync.start", { runId, projectId, adAccountId: connRow.adAccountId });
10690
+ log7.info("sync.start", { runId, projectId, adAccountId: connRow.adAccountId });
10678
10691
  const account = await getAdAccount(apiKey);
10679
10692
  const campaigns = await listCampaigns(apiKey);
10680
10693
  const insightAnchor = /* @__PURE__ */ new Date();
@@ -10719,7 +10732,7 @@ async function executeAdsSync(db, runId, projectId, opts) {
10719
10732
  } catch (err) {
10720
10733
  lastCampaignError = err;
10721
10734
  errors.set(campaign.name, describeError(err));
10722
- log6.error("campaign.failed", { runId, campaignId: campaign.id, error: describeError(err) });
10735
+ log7.error("campaign.failed", { runId, campaignId: campaign.id, error: describeError(err) });
10723
10736
  }
10724
10737
  }
10725
10738
  const conversionTrackingConfigured = campaigns.some(
@@ -10848,7 +10861,7 @@ async function executeAdsSync(db, runId, projectId, opts) {
10848
10861
  finishedAt
10849
10862
  }).where(eq11(runs.id, runId)).run();
10850
10863
  }
10851
- log6.info("sync.done", { runId, projectId, campaigns: syncedCampaigns.length, insightRows: insightUpserts.length, failed: errors.size });
10864
+ log7.info("sync.done", { runId, projectId, campaigns: syncedCampaigns.length, insightRows: insightUpserts.length, failed: errors.size });
10852
10865
  const counts = { campaigns: syncedCampaigns.length, rows: insightUpserts.length, failures: errors.size };
10853
10866
  if (errors.size > 0) {
10854
10867
  reportOutcome({ status: syncedCampaigns.length > 0 ? OutcomeStatuses.partial : OutcomeStatuses.failed, ...runFailure(lastCampaignError), counts });
@@ -10858,7 +10871,7 @@ async function executeAdsSync(db, runId, projectId, opts) {
10858
10871
  } catch (err) {
10859
10872
  const errorMsg = describeError(err);
10860
10873
  db.update(runs).set({ status: "failed", error: serializeRunError({ message: errorMsg }), finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(runs.id, runId)).run();
10861
- log6.error("sync.failed", { runId, projectId, error: errorMsg });
10874
+ log7.error("sync.failed", { runId, projectId, error: errorMsg });
10862
10875
  reportOutcome({ status: OutcomeStatuses.failed, ...runFailure(err) });
10863
10876
  throw err;
10864
10877
  }
@@ -10869,7 +10882,7 @@ import crypto15 from "crypto";
10869
10882
  import { eq as eq12 } from "drizzle-orm";
10870
10883
 
10871
10884
  // src/sitemap-parser.ts
10872
- var log7 = createLogger("SitemapParser");
10885
+ var log8 = createLogger("SitemapParser");
10873
10886
  var LOC_REGEX = /<loc>([^<]+)<\/loc>/gi;
10874
10887
  var SITEMAP_TAG_REGEX = /<sitemap>[\s\S]*?<\/sitemap>/gi;
10875
10888
  var sitemapFetch = createGuardedFetch({ allowLoopback: true });
@@ -10918,7 +10931,7 @@ async function parseSitemapRecursive(url, urls, visited, depth, isChild) {
10918
10931
  res = await fetchSitemap(url);
10919
10932
  } catch (err) {
10920
10933
  if (!isChild) throw err;
10921
- log7.warn("child-sitemap.fetch-failed", {
10934
+ log8.warn("child-sitemap.fetch-failed", {
10922
10935
  url,
10923
10936
  error: describeError(err)
10924
10937
  });
@@ -10931,7 +10944,7 @@ async function parseSitemapRecursive(url, urls, visited, depth, isChild) {
10931
10944
  classifyOutcomeError({ status: res.status }).reasonCode
10932
10945
  );
10933
10946
  }
10934
- log7.warn("child-sitemap.http-error", { url, status: res.status, statusText: res.statusText });
10947
+ log8.warn("child-sitemap.http-error", { url, status: res.status, statusText: res.statusText });
10935
10948
  return;
10936
10949
  }
10937
10950
  let xml;
@@ -10939,7 +10952,7 @@ async function parseSitemapRecursive(url, urls, visited, depth, isChild) {
10939
10952
  xml = await readSitemapBody(res);
10940
10953
  } catch (err) {
10941
10954
  if (!isChild) throw err;
10942
- log7.warn("child-sitemap.parse-failed", {
10955
+ log8.warn("child-sitemap.parse-failed", {
10943
10956
  url,
10944
10957
  error: describeError(err)
10945
10958
  });
@@ -11063,6 +11076,12 @@ async function inspectUrlsPaced(urls, cb, deps) {
11063
11076
  } catch (err) {
11064
11077
  errors++;
11065
11078
  cb.onError(url, err, index);
11079
+ if (deps.abortOnError?.(err)) {
11080
+ aborted = true;
11081
+ abortError = err;
11082
+ deps.log?.error("inspect.account-paused", { inspected, errors, remaining: Math.max(0, urls.length - nextIndex) });
11083
+ return;
11084
+ }
11066
11085
  if (isRetryable(err)) {
11067
11086
  consecutiveRetryableFailures++;
11068
11087
  if (consecutiveRetryableFailures >= INSPECT_FAILFAST_THRESHOLD) {
@@ -11085,7 +11104,7 @@ async function inspectUrlsPaced(urls, cb, deps) {
11085
11104
  }
11086
11105
 
11087
11106
  // src/gsc-inspect-sitemap.ts
11088
- var log8 = createLogger("InspectSitemap");
11107
+ var log9 = createLogger("InspectSitemap");
11089
11108
  async function executeInspectSitemap(db, runId, projectId, opts) {
11090
11109
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.search_console, "inspect");
11091
11110
  let abortCause;
@@ -11125,16 +11144,16 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
11125
11144
  persistConfigPatch(opts.config);
11126
11145
  }
11127
11146
  const sitemapUrl = opts.sitemapUrl || conn.sitemapUrl || `https://${project.canonicalDomain}/sitemap.xml`;
11128
- log8.info("sitemap.fetch", { runId, projectId, sitemapUrl });
11147
+ log9.info("sitemap.fetch", { runId, projectId, sitemapUrl });
11129
11148
  const urls = await fetchAndParseSitemap(sitemapUrl);
11130
- log8.info("sitemap.parsed", { runId, projectId, urlCount: urls.length, sitemapUrl });
11149
+ log9.info("sitemap.parsed", { runId, projectId, urlCount: urls.length, sitemapUrl });
11131
11150
  if (urls.length === 0) {
11132
11151
  throw withOutcomeReason(new Error("No URLs found in sitemap"), OutcomeReasonCodes.NO_DATA);
11133
11152
  }
11134
11153
  const skipped = Math.max(0, urls.length - INSPECT_SWEEP_MAX_URLS);
11135
11154
  const targetUrls = skipped > 0 ? urls.slice(0, INSPECT_SWEEP_MAX_URLS) : urls;
11136
11155
  if (skipped > 0) {
11137
- log8.warn("sitemap.over-budget", {
11156
+ log9.warn("sitemap.over-budget", {
11138
11157
  runId,
11139
11158
  projectId,
11140
11159
  sitemapUrls: urls.length,
@@ -11173,11 +11192,11 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
11173
11192
  inspectedAt,
11174
11193
  createdAt: inspectedAt
11175
11194
  }).run();
11176
- log8.info("inspect.url-done", { runId, projectId, url: pageUrl, progress: `${index + 1}/${urls.length}` });
11195
+ log9.info("inspect.url-done", { runId, projectId, url: pageUrl, progress: `${index + 1}/${urls.length}` });
11177
11196
  },
11178
11197
  onError: (pageUrl, err) => {
11179
11198
  lastInspectError = err;
11180
- log8.error("inspect.url-failed", { runId, projectId, url: pageUrl, error: describeError(err) });
11199
+ log9.error("inspect.url-failed", { runId, projectId, url: pageUrl, error: describeError(err) });
11181
11200
  }
11182
11201
  },
11183
11202
  {
@@ -11188,8 +11207,8 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
11188
11207
  // coverage refresh is exactly the overlap it fails on.
11189
11208
  rateGateKey: `gsc:${propertyId}`,
11190
11209
  log: {
11191
- info: (action, ctx) => log8.info(action, { runId, projectId, ...ctx }),
11192
- error: (action, ctx) => log8.error(action, { runId, projectId, ...ctx })
11210
+ info: (action, ctx) => log9.info(action, { runId, projectId, ...ctx }),
11211
+ error: (action, ctx) => log9.error(action, { runId, projectId, ...ctx })
11193
11212
  }
11194
11213
  }
11195
11214
  );
@@ -11206,7 +11225,7 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
11206
11225
  const attempted = targetUrls.length;
11207
11226
  const status = skipped > 0 || errors > 0 && inspected > 0 ? "partial" : errors === attempted ? "failed" : "completed";
11208
11227
  db.update(runs).set({ status, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq12(runs.id, runId)).run();
11209
- log8.info("inspect.completed", { runId, projectId, inspected, errors, total: urls.length, indexed: snapIndexed, notIndexed: snapNotIndexed });
11228
+ log9.info("inspect.completed", { runId, projectId, inspected, errors, total: urls.length, indexed: snapIndexed, notIndexed: snapNotIndexed });
11210
11229
  const counts = { urls: inspected, failures: errors, skipped };
11211
11230
  if (status === RunStatuses.completed) {
11212
11231
  reportOutcome({ status: OutcomeStatuses.succeeded, counts });
@@ -11217,7 +11236,7 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
11217
11236
  } catch (err) {
11218
11237
  const errorMsg = describeError(err);
11219
11238
  db.update(runs).set({ status: "failed", error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq12(runs.id, runId)).run();
11220
- log8.error("inspect.failed", { runId, projectId, error: errorMsg });
11239
+ log9.error("inspect.failed", { runId, projectId, error: errorMsg });
11221
11240
  const failure2 = googleRunFailure(abortCause ?? err);
11222
11241
  reportOutcome({
11223
11242
  status: failure2.reasonCode === OutcomeReasonCodes.NO_DATA ? OutcomeStatuses.skipped : OutcomeStatuses.failed,
@@ -11230,7 +11249,7 @@ async function executeInspectSitemap(db, runId, projectId, opts) {
11230
11249
  // src/bing-inspect-sitemap.ts
11231
11250
  import crypto16 from "crypto";
11232
11251
  import { eq as eq13, desc as desc5 } from "drizzle-orm";
11233
- var log9 = createLogger("BingInspectSitemap");
11252
+ var log10 = createLogger("BingInspectSitemap");
11234
11253
  function bingRunFailure(err) {
11235
11254
  return runFailure(err, err instanceof BingApiError && err.isThrottle ? OutcomeReasonCodes.RATE_LIMITED : void 0);
11236
11255
  }
@@ -11238,6 +11257,10 @@ var BING_INSPECT_SPACING_MS = 2e3;
11238
11257
  async function executeBingInspectSitemap(db, runId, projectId, opts) {
11239
11258
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.bing, "inspect");
11240
11259
  let abortCause;
11260
+ let total = 0;
11261
+ let inspected = 0;
11262
+ let errors = 0;
11263
+ let phase = OutcomePhases.setup;
11241
11264
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
11242
11265
  db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq13(runs.id, runId)).run();
11243
11266
  try {
@@ -11259,16 +11282,22 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11259
11282
  );
11260
11283
  }
11261
11284
  const sitemapUrl = opts.sitemapUrl ?? `https://${project.canonicalDomain}/sitemap.xml`;
11262
- log9.info("sitemap.fetch", { runId, projectId, sitemapUrl });
11285
+ log10.info("sitemap.fetch", { runId, projectId, sitemapUrl });
11286
+ phase = OutcomePhases.crawl;
11263
11287
  const sitemapUrls = await fetchAndParseSitemap(sitemapUrl);
11264
- log9.info("sitemap.parsed", { runId, projectId, urlCount: sitemapUrls.length, sitemapUrl });
11288
+ total = sitemapUrls.length;
11289
+ log10.info("sitemap.parsed", { runId, projectId, urlCount: sitemapUrls.length, sitemapUrl });
11265
11290
  if (sitemapUrls.length === 0) {
11266
11291
  throw withOutcomeReason(new Error("No URLs found in sitemap"), OutcomeReasonCodes.NO_DATA);
11267
11292
  }
11268
- const trackedRows = db.select({ url: bingUrlInspections.url }).from(bingUrlInspections).where(eq13(bingUrlInspections.projectId, projectId)).all();
11293
+ const trackedRows = db.select({ url: bingUrlInspections.url, inspectedAt: bingUrlInspections.inspectedAt }).from(bingUrlInspections).where(eq13(bingUrlInspections.projectId, projectId)).all();
11269
11294
  const trackedUrls = new Set(trackedRows.map((r) => r.url));
11295
+ const lastInspected = /* @__PURE__ */ new Map();
11296
+ for (const row of trackedRows) {
11297
+ if (row.inspectedAt > (lastInspected.get(row.url) ?? "")) lastInspected.set(row.url, row.inspectedAt);
11298
+ }
11270
11299
  const discovered = sitemapUrls.filter((u) => !trackedUrls.has(u));
11271
- log9.info("sitemap.diff", {
11300
+ log10.info("sitemap.diff", {
11272
11301
  runId,
11273
11302
  projectId,
11274
11303
  sitemapTotal: sitemapUrls.length,
@@ -11276,44 +11305,54 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11276
11305
  newlyDiscovered: discovered.length
11277
11306
  });
11278
11307
  let blockedUrls = /* @__PURE__ */ new Set();
11308
+ phase = OutcomePhases["provider-request"];
11279
11309
  try {
11310
+ await sharedRateGate(credentialGateKey("bing", conn.apiKey)).take(
11311
+ BING_INSPECT_SPACING_MS,
11312
+ opts.pacedDeps?.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
11313
+ );
11280
11314
  const issues = await getCrawlIssues(conn.apiKey, conn.siteUrl);
11281
11315
  for (const issue of issues) {
11282
11316
  if (issue.Url && isBlockingCrawlIssue(issue.IssueType ?? null)) {
11283
11317
  blockedUrls.add(issue.Url);
11284
11318
  }
11285
11319
  }
11286
- log9.info("crawl-issues.loaded", { runId, projectId, blockedCount: blockedUrls.size });
11320
+ log10.info("crawl-issues.loaded", { runId, projectId, blockedCount: blockedUrls.size });
11287
11321
  } catch (err) {
11288
- log9.warn("crawl-issues.lookup-failed", {
11322
+ log10.warn("crawl-issues.lookup-failed", {
11289
11323
  runId,
11290
11324
  projectId,
11291
11325
  error: describeError(err)
11292
11326
  });
11327
+ if (err instanceof BingApiError && err.isThrottle) throw err;
11293
11328
  blockedUrls = /* @__PURE__ */ new Set();
11294
11329
  }
11295
11330
  const skipped = Math.max(0, sitemapUrls.length - INSPECT_SWEEP_MAX_URLS);
11296
- const targetUrls = skipped > 0 ? sitemapUrls.slice(0, INSPECT_SWEEP_MAX_URLS) : sitemapUrls;
11331
+ const dueUrls = [...sitemapUrls].sort((a, b) => (lastInspected.get(a) ?? "").localeCompare(lastInspected.get(b) ?? ""));
11332
+ const targetUrls = dueUrls.slice(0, INSPECT_SWEEP_MAX_URLS);
11297
11333
  if (skipped > 0) {
11298
- log9.warn("sitemap.over-budget", {
11334
+ log10.warn("sitemap.over-budget", {
11299
11335
  runId,
11300
11336
  projectId,
11301
11337
  sitemapUrls: sitemapUrls.length,
11302
11338
  inspecting: targetUrls.length,
11303
11339
  skipped,
11304
11340
  dailyQuota: INSPECT_DAILY_QUOTA,
11305
- note: `Sitemap has ${sitemapUrls.length} pages; inspecting the first ${targetUrls.length}. ${skipped} pages will not have a verdict from this run.`
11341
+ note: `Sitemap has ${sitemapUrls.length} pages; inspecting the ${targetUrls.length} least recently inspected. ${skipped} pages will not have a verdict from this run.`
11306
11342
  });
11307
11343
  }
11308
11344
  const siteUrl = conn.siteUrl;
11309
- let inspected = 0;
11310
- let errors = 0;
11311
11345
  let lastInspectError;
11346
+ let lastInspectFailurePhase;
11312
11347
  const outcome = await inspectUrlsPaced(
11313
11348
  targetUrls,
11314
11349
  {
11315
- inspectOne: (pageUrl) => getUrlInfo(conn.apiKey, siteUrl, pageUrl),
11350
+ inspectOne: (pageUrl) => {
11351
+ phase = OutcomePhases["provider-request"];
11352
+ return getUrlInfo(conn.apiKey, siteUrl, pageUrl);
11353
+ },
11316
11354
  onResult: (pageUrl, result) => {
11355
+ phase = OutcomePhases.persistence;
11317
11356
  const inspectedAt = (/* @__PURE__ */ new Date()).toISOString();
11318
11357
  const httpCode = result.HttpStatus ?? result.HttpCode ?? null;
11319
11358
  const lastCrawledDate = parseBingDate(result.LastCrawledDate);
@@ -11346,12 +11385,13 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11346
11385
  discoveryDate
11347
11386
  }).run();
11348
11387
  inspected++;
11349
- log9.info("inspect.url-done", { runId, projectId, url: pageUrl, progress: `${inspected}/${targetUrls.length}` });
11388
+ log10.info("inspect.url-done", { runId, projectId, url: pageUrl, progress: `${inspected}/${targetUrls.length}` });
11350
11389
  },
11351
11390
  onError: (pageUrl, err) => {
11352
11391
  errors++;
11353
11392
  lastInspectError = err;
11354
- log9.error("inspect.url-failed", {
11393
+ lastInspectFailurePhase = phase;
11394
+ log10.error("inspect.url-failed", {
11355
11395
  runId,
11356
11396
  projectId,
11357
11397
  url: pageUrl,
@@ -11361,6 +11401,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11361
11401
  },
11362
11402
  {
11363
11403
  isRetryable: isRetryableHttpError,
11404
+ abortOnError: (err) => err instanceof BingApiError && err.isThrottle,
11364
11405
  concurrency: 1,
11365
11406
  // Bing meters the ACCOUNT, and one API key serves every project here,
11366
11407
  // so all sweeps on that key must queue behind one clock. Without this
@@ -11373,26 +11414,29 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11373
11414
  // attempts = 20 requests for one throttled URL, so the breaker's
11374
11415
  // five-failure budget spent ~100 requests and inspected nothing.
11375
11416
  maxRetries: 0,
11376
- log: log9,
11417
+ log: log10,
11377
11418
  ...opts.pacedDeps
11378
11419
  }
11379
11420
  );
11380
11421
  if (outcome.aborted) {
11381
- log9.error("inspect.circuit-break", {
11422
+ log10.error("inspect.circuit-break", {
11382
11423
  runId,
11383
11424
  projectId,
11384
11425
  inspected,
11385
11426
  errors,
11427
+ attempted: inspected + errors,
11428
+ remaining: total - inspected,
11386
11429
  note: "Bing inspection stopped early after sustained failures; the remaining pages were not attempted."
11387
11430
  });
11388
11431
  }
11389
- if (outcome.aborted && inspected === 0) {
11390
- abortCause = outcome.abortError;
11391
- const detail = describeError(outcome.abortError);
11432
+ if (inspected === 0 && errors > 0) {
11433
+ abortCause = outcome.abortError ?? lastInspectError;
11434
+ const detail = describeError(abortCause);
11392
11435
  throw new Error(
11393
11436
  `Bing inspection failed for every URL attempted (${errors} of ${targetUrls.length}); coverage was left unchanged rather than re-dated from stored inspections. Last error: ${detail}`
11394
11437
  );
11395
11438
  }
11439
+ phase = OutcomePhases.persistence;
11396
11440
  const allInspections = db.select().from(bingUrlInspections).where(eq13(bingUrlInspections.projectId, projectId)).orderBy(desc5(bingUrlInspections.inspectedAt)).all();
11397
11441
  const latestByUrl = /* @__PURE__ */ new Map();
11398
11442
  const definitiveByUrl = /* @__PURE__ */ new Map();
@@ -11435,38 +11479,50 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11435
11479
  syncRunId: runId
11436
11480
  }
11437
11481
  }).run();
11438
- const status = errors > 0 && errors >= targetUrls.length ? RunStatuses.failed : errors > 0 || outcome.aborted ? RunStatuses.partial : RunStatuses.completed;
11439
- const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped early after sustained failures; ${targetUrls.length - inspected} of ${targetUrls.length} pages were not inspected.` : `${errors} of ${targetUrls.length} pages could not be inspected.`;
11482
+ const status = errors > 0 || outcome.aborted || skipped > 0 ? RunStatuses.partial : RunStatuses.completed;
11483
+ const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped after provider failures; ${total - inspected} of ${total} pages were not inspected (${total - inspected - errors} not attempted).` : skipped > 0 ? `${total - inspected} of ${total} pages were not inspected in this run (${skipped} deferred by the per-run budget; ${errors} failed).` : `${errors} of ${targetUrls.length} pages could not be inspected.`;
11440
11484
  db.update(runs).set({ status, error: degradedReason, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq13(runs.id, runId)).run();
11441
- log9.info("inspect.completed", {
11485
+ log10.info("inspect.completed", {
11442
11486
  runId,
11443
11487
  projectId,
11444
11488
  inspected,
11445
11489
  errors,
11490
+ attempted: inspected + errors,
11491
+ remaining: total - inspected,
11446
11492
  total: sitemapUrls.length,
11447
11493
  newlyDiscovered: discovered.length,
11448
11494
  indexed: snapIndexed,
11449
11495
  notIndexed: snapNotIndexed,
11450
11496
  unknown: snapUnknown
11451
11497
  });
11452
- const counts = { urls: inspected, failures: errors, skipped };
11498
+ const counts = { urls: inspected, attempts: inspected + errors, failures: errors, skipped: total - inspected - errors };
11499
+ const diagnostics = buildOutcomeDiagnostics(lastInspectError ?? outcome.abortError, {
11500
+ phase: lastInspectFailurePhase ?? phase,
11501
+ remainingWork: total - inspected
11502
+ });
11453
11503
  if (status === RunStatuses.completed) {
11454
- reportOutcome({ status: OutcomeStatuses.succeeded, counts });
11504
+ reportOutcome({ status: OutcomeStatuses.succeeded, operationKind: OutcomeOperationKinds["url-coverage"], counts, diagnostics });
11455
11505
  } else {
11506
+ const failure2 = lastInspectError ?? outcome.abortError;
11456
11507
  reportOutcome({
11457
- status: status === RunStatuses.partial ? OutcomeStatuses.partial : OutcomeStatuses.failed,
11458
- ...bingRunFailure(lastInspectError ?? outcome.abortError),
11459
- counts
11508
+ status: OutcomeStatuses.partial,
11509
+ operationKind: OutcomeOperationKinds["url-coverage"],
11510
+ ...failure2 === void 0 ? { reasonCode: OutcomeReasonCodes.QUOTA_EXCEEDED } : bingRunFailure(failure2),
11511
+ counts,
11512
+ diagnostics
11460
11513
  });
11461
11514
  }
11462
11515
  } catch (err) {
11463
11516
  const errorMsg = describeError(err);
11464
11517
  db.update(runs).set({ status: RunStatuses.failed, error: errorMsg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq13(runs.id, runId)).run();
11465
- log9.error("inspect.failed", { runId, projectId, error: errorMsg });
11518
+ log10.error("inspect.failed", { runId, projectId, error: errorMsg });
11466
11519
  const failure2 = bingRunFailure(abortCause ?? err);
11467
11520
  reportOutcome({
11468
11521
  status: failure2.reasonCode === OutcomeReasonCodes.NO_DATA ? OutcomeStatuses.skipped : OutcomeStatuses.failed,
11469
- ...failure2
11522
+ operationKind: OutcomeOperationKinds["url-coverage"],
11523
+ ...failure2,
11524
+ ...total > 0 ? { counts: { urls: inspected, attempts: inspected + errors, failures: errors, skipped: total - inspected - errors } } : {},
11525
+ diagnostics: buildOutcomeDiagnostics(abortCause ?? err, { phase, ...total > 0 ? { remainingWork: total - inspected } : {} })
11470
11526
  });
11471
11527
  throw err;
11472
11528
  }
@@ -11475,7 +11531,7 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
11475
11531
  // src/bing-sync.ts
11476
11532
  import crypto17 from "crypto";
11477
11533
  import { and as and10, eq as eq14, notInArray as notInArray2, sql as sql5 } from "drizzle-orm";
11478
- var log10 = createLogger("BingSync");
11534
+ var log11 = createLogger("BingSync");
11479
11535
  var BING_SYNC_SPACING_MS = 2e3;
11480
11536
  var BING_KEYWORD_DEMAND_REFRESH_DAYS = 7;
11481
11537
  var BING_KEYWORD_DEMAND_MAX_PER_SYNC = 30;
@@ -11487,6 +11543,12 @@ var BingSyncThrottled = class extends Error {
11487
11543
  this.name = "BingSyncThrottled";
11488
11544
  }
11489
11545
  };
11546
+ var BingSectionReadFailure = class extends Error {
11547
+ constructor(message, cause) {
11548
+ super(message, { cause });
11549
+ this.name = "BingSectionReadFailure";
11550
+ }
11551
+ };
11490
11552
  function isThrottle(err) {
11491
11553
  return err instanceof BingApiError && (err.isThrottle || err.status === 429);
11492
11554
  }
@@ -11545,6 +11607,7 @@ function mergeWeekly(rows) {
11545
11607
  }
11546
11608
  async function executeBingSync(db, runId, projectId, opts) {
11547
11609
  const reportOutcome = startRunOutcome(db, runId, FeatureNames.bing, "sync");
11610
+ let phase = OutcomePhases.setup;
11548
11611
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
11549
11612
  const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
11550
11613
  db.update(runs).set({ status: RunStatuses.running, startedAt: now().toISOString() }).where(eq14(runs.id, runId)).run();
@@ -11572,9 +11635,12 @@ async function executeBingSync(db, runId, projectId, opts) {
11572
11635
  let throttled = false;
11573
11636
  async function call(read) {
11574
11637
  if (throttled) throw new BingSyncThrottled(new Error("Bing throttled this account earlier in the run"));
11638
+ phase = OutcomePhases["provider-request"];
11575
11639
  await gate.take(BING_SYNC_SPACING_MS, sleep3);
11576
11640
  try {
11577
- return await read();
11641
+ const result = await read();
11642
+ phase = OutcomePhases.persistence;
11643
+ return result;
11578
11644
  } catch (err) {
11579
11645
  if (isThrottle(err)) {
11580
11646
  throttled = true;
@@ -11585,14 +11651,31 @@ async function executeBingSync(db, runId, projectId, opts) {
11585
11651
  }
11586
11652
  const results = [];
11587
11653
  async function section(name, work) {
11654
+ if (throttled) {
11655
+ results.push({ section: name, ok: false, rows: 0, deferred: true, error: "Deferred until the account throttle clears" });
11656
+ log11.info("section.deferred", { runId, projectId, section: name, reason: "account-throttled" });
11657
+ return;
11658
+ }
11659
+ let savedRows = 0;
11660
+ phase = OutcomePhases.persistence;
11588
11661
  try {
11589
- const rows2 = await work();
11662
+ const rows2 = await work((rows3) => {
11663
+ savedRows = rows3;
11664
+ });
11590
11665
  results.push({ section: name, ok: true, rows: rows2 });
11591
- log10.info("section.completed", { runId, projectId, section: name, rows: rows2 });
11666
+ log11.info("section.completed", { runId, projectId, section: name, rows: rows2 });
11592
11667
  } catch (err) {
11593
11668
  const error2 = describeError(err);
11594
- results.push({ section: name, ok: false, rows: 0, error: error2 });
11595
- log10.warn("section.failed", { runId, projectId, section: name, error: error2, throttled: err instanceof BingSyncThrottled });
11669
+ const providerFailure = err instanceof BingSectionReadFailure || err instanceof BingSyncThrottled;
11670
+ results.push({
11671
+ section: name,
11672
+ ok: false,
11673
+ rows: savedRows,
11674
+ error: error2,
11675
+ cause: providerFailure ? err.cause : err,
11676
+ phase: providerFailure ? OutcomePhases["provider-request"] : phase
11677
+ });
11678
+ log11.warn("section.failed", { runId, projectId, section: name, error: error2, savedRows, throttled: err instanceof BingSyncThrottled });
11596
11679
  }
11597
11680
  }
11598
11681
  await section("traffic", async () => {
@@ -11701,7 +11784,7 @@ async function executeBingSync(db, runId, projectId, opts) {
11701
11784
  });
11702
11785
  return collected.size;
11703
11786
  });
11704
- await section("site", async () => {
11787
+ await section("site", async (saved) => {
11705
11788
  const reads = [
11706
11789
  {
11707
11790
  kind: BingSiteSnapshotKinds["url-submission-quota"],
@@ -11799,6 +11882,7 @@ async function executeBingSync(db, runId, projectId, opts) {
11799
11882
  ];
11800
11883
  let failed2 = 0;
11801
11884
  let stored = 0;
11885
+ let lastError;
11802
11886
  for (const { kind, read } of reads) {
11803
11887
  let status2 = "ok";
11804
11888
  let payload = null;
@@ -11810,18 +11894,25 @@ async function executeBingSync(db, runId, projectId, opts) {
11810
11894
  const unauthorized = err instanceof BingApiError && err.bingErrorCode === BING_NOT_AUTHORIZED;
11811
11895
  status2 = unauthorized ? "unauthorized" : "failed";
11812
11896
  error2 = unauthorized ? "This Bing key is not allowed to read this setting (owner-only)." : describeError(err);
11813
- if (!unauthorized) failed2 += 1;
11897
+ if (!unauthorized) {
11898
+ failed2 += 1;
11899
+ lastError = err;
11900
+ }
11814
11901
  }
11902
+ phase = OutcomePhases.persistence;
11815
11903
  const syncedAt = now().toISOString();
11816
11904
  const previous = status2 === "failed" ? db.select({ payload: bingSiteSnapshots.payload }).from(bingSiteSnapshots).where(and10(eq14(bingSiteSnapshots.projectId, projectId), eq14(bingSiteSnapshots.kind, kind))).get() : void 0;
11817
11905
  const values = { status: status2, payload: status2 === "failed" ? previous?.payload ?? null : payload, error: error2, syncRunId: runId, syncedAt };
11818
11906
  db.insert(bingSiteSnapshots).values({ id: crypto17.randomUUID(), projectId, kind, ...values }).onConflictDoUpdate({ target: [bingSiteSnapshots.projectId, bingSiteSnapshots.kind], set: values }).run();
11819
11907
  stored += 1;
11908
+ saved(stored);
11909
+ }
11910
+ if (failed2 > 0) {
11911
+ throw new BingSectionReadFailure(`${failed2} of ${reads.length} Bing site settings could not be read`, lastError);
11820
11912
  }
11821
- if (failed2 > 0) throw new Error(`${failed2} of ${reads.length} Bing site settings could not be read`);
11822
11913
  return stored;
11823
11914
  });
11824
- await section("keyword-demand", async () => {
11915
+ await section("keyword-demand", async (saved) => {
11825
11916
  const market = bingKeywordMarket(project.country, project.language);
11826
11917
  const tracked = db.select({ query: queries.query }).from(queries).where(eq14(queries.projectId, projectId)).all();
11827
11918
  if (tracked.length === 0) return 0;
@@ -11862,30 +11953,39 @@ async function executeBingSync(db, runId, projectId, opts) {
11862
11953
  tx.insert(bingKeywordDemand).values({ id: crypto17.randomUUID(), projectId, query, country: market.country, language: market.language, date, impressions: 0, broadImpressions: 0, syncRunId: runId, syncedAt }).onConflictDoNothing().run();
11863
11954
  }
11864
11955
  });
11956
+ saved(written);
11957
+ }
11958
+ if (failures > 0) {
11959
+ throw new BingSectionReadFailure(`${failures} of ${due.length} keyword demand reads failed; last: ${describeError(lastError)}`, lastError);
11865
11960
  }
11866
- if (failures > 0) throw new Error(`${failures} of ${due.length} keyword demand reads failed; last: ${describeError(lastError)}`);
11867
11961
  return written;
11868
11962
  });
11869
11963
  const failed = results.filter((r) => !r.ok);
11964
+ const lastFailure = [...failed].reverse().find((r) => !r.deferred);
11870
11965
  const status = failed.length === 0 ? RunStatuses.completed : failed.length === results.length ? RunStatuses.failed : RunStatuses.partial;
11871
11966
  const error = failed.length === 0 ? null : `${throttled ? "Bing throttled this account; stopped early. " : ""}${failed.map((r) => `${r.section}: ${r.error}`).join("; ")}`.slice(0, 2e3);
11967
+ phase = OutcomePhases.persistence;
11872
11968
  db.update(runs).set({ status, error, finishedAt: now().toISOString() }).where(eq14(runs.id, runId)).run();
11873
11969
  const rows = results.reduce((sum, r) => sum + r.rows, 0);
11874
- log10.info("sync.completed", { runId, projectId, status, rows, failedSections: failed.map((r) => r.section) });
11970
+ const deferred = failed.filter((r) => r.deferred).length;
11971
+ const counts = { rows, items: results.length, attempts: results.length - deferred, failures: failed.length - deferred, skipped: deferred };
11972
+ log11.info("sync.completed", { runId, projectId, status, rows, attemptedSections: counts.attempts, remainingSections: failed.length, deferredSections: deferred, failedSections: failed.filter((r) => !r.deferred).map((r) => r.section) });
11875
11973
  if (status === RunStatuses.completed) {
11876
- reportOutcome({ status: OutcomeStatuses.succeeded, counts: { rows, items: results.length } });
11974
+ reportOutcome({ status: OutcomeStatuses.succeeded, operationKind: OutcomeOperationKinds["data-refresh"], counts, diagnostics: { phase, remainingWork: 0 } });
11877
11975
  } else {
11878
11976
  reportOutcome({
11879
11977
  status: status === RunStatuses.partial ? OutcomeStatuses.partial : OutcomeStatuses.failed,
11880
- ...runFailure(new Error(error ?? "Bing sync failed"), throttled ? OutcomeReasonCodes.RATE_LIMITED : void 0),
11881
- counts: { rows, items: results.length, failures: failed.length }
11978
+ operationKind: OutcomeOperationKinds["data-refresh"],
11979
+ ...runFailure(lastFailure?.cause ?? new Error(error ?? "Bing sync failed"), throttled ? OutcomeReasonCodes.RATE_LIMITED : void 0),
11980
+ counts,
11981
+ diagnostics: buildOutcomeDiagnostics(lastFailure?.cause, { phase: lastFailure?.phase ?? OutcomePhases.unknown, remainingWork: failed.length })
11882
11982
  });
11883
11983
  }
11884
11984
  } catch (err) {
11885
11985
  const message = describeError(err);
11886
11986
  db.update(runs).set({ status: RunStatuses.failed, error: message, finishedAt: now().toISOString() }).where(eq14(runs.id, runId)).run();
11887
- log10.error("sync.failed", { runId, projectId, error: message });
11888
- reportOutcome({ status: OutcomeStatuses.failed, ...runFailure(err) });
11987
+ log11.error("sync.failed", { runId, projectId, error: message });
11988
+ reportOutcome({ status: OutcomeStatuses.failed, operationKind: OutcomeOperationKinds["data-refresh"], ...runFailure(err), diagnostics: buildOutcomeDiagnostics(err, { phase }) });
11889
11989
  throw err;
11890
11990
  }
11891
11991
  }
@@ -11893,7 +11993,7 @@ async function executeBingSync(db, runId, projectId, opts) {
11893
11993
  // src/coverage-refresh.ts
11894
11994
  import crypto18 from "crypto";
11895
11995
  import { and as and11, desc as desc6, eq as eq15, inArray as inArray7 } from "drizzle-orm";
11896
- var log11 = createLogger("CoverageRefresh");
11996
+ var log12 = createLogger("CoverageRefresh");
11897
11997
  var COVERAGE_REFRESH_MIN_INTERVAL_MS = 60 * 60 * 1e3;
11898
11998
  var COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS = 2 * 60 * 1e3;
11899
11999
  var ACTIVE_OR_DONE_STATUSES = [
@@ -11923,7 +12023,7 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
11923
12023
  )
11924
12024
  ).orderBy(desc6(runs.createdAt)).limit(1).get();
11925
12025
  if (inFlight) {
11926
- log11.info("skip.in-flight", { projectId });
12026
+ log12.info("skip.in-flight", { projectId });
11927
12027
  return null;
11928
12028
  }
11929
12029
  const windowMs = opts.userInitiated ? COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS : COVERAGE_REFRESH_MIN_INTERVAL_MS;
@@ -11937,7 +12037,7 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
11937
12037
  if (recent) {
11938
12038
  const ageMs = nowMs - Date.parse(recent.createdAt);
11939
12039
  if (Number.isFinite(ageMs) && ageMs < windowMs) {
11940
- log11.info("skip.recent", { projectId, ageMs, windowMs, userInitiated: opts.userInitiated === true });
12040
+ log12.info("skip.recent", { projectId, ageMs, windowMs, userInitiated: opts.userInitiated === true });
11941
12041
  return null;
11942
12042
  }
11943
12043
  }
@@ -11950,11 +12050,11 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
11950
12050
  trigger: RunTriggers.scheduled,
11951
12051
  createdAt: new Date(nowMs).toISOString()
11952
12052
  }).run();
11953
- log11.info("refresh.start", { projectId, runId });
12053
+ log12.info("refresh.start", { projectId, runId });
11954
12054
  try {
11955
12055
  await deps.executeInspectSitemap(db, runId, projectId, { config });
11956
12056
  } catch (err) {
11957
- log11.error("refresh.failed", {
12057
+ log12.error("refresh.failed", {
11958
12058
  projectId,
11959
12059
  runId,
11960
12060
  error: describeError(err)
@@ -11967,7 +12067,7 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
11967
12067
  import crypto19 from "crypto";
11968
12068
  import path5 from "path";
11969
12069
  import { and as and12, eq as eq16, sql as sql6 } from "drizzle-orm";
11970
- var log12 = createLogger("CommonCrawlSync");
12070
+ var log13 = createLogger("CommonCrawlSync");
11971
12071
  var INSERT_CHUNK_SIZE = 1e4;
11972
12072
  function defaultDeps2() {
11973
12073
  return {
@@ -12102,7 +12202,7 @@ async function executeReleaseSync(db, syncId, opts) {
12102
12202
  updatedAt: finishedAt,
12103
12203
  error: null
12104
12204
  }).where(eq16(ccReleaseSyncs.id, syncId)).run();
12105
- log12.info("sync.completed", {
12205
+ log13.info("sync.completed", {
12106
12206
  syncId,
12107
12207
  release,
12108
12208
  projectsProcessed: allProjects.length,
@@ -12120,7 +12220,7 @@ async function executeReleaseSync(db, syncId, opts) {
12120
12220
  try {
12121
12221
  deps.enqueueAutoExtract({ projectId: p.id, release });
12122
12222
  } catch (err) {
12123
- log12.error("auto-extract.enqueue-failed", {
12223
+ log13.error("auto-extract.enqueue-failed", {
12124
12224
  syncId,
12125
12225
  release,
12126
12226
  projectId: p.id,
@@ -12138,7 +12238,7 @@ async function executeReleaseSync(db, syncId, opts) {
12138
12238
  phaseDetail: null,
12139
12239
  updatedAt: finishedAt
12140
12240
  }).where(eq16(ccReleaseSyncs.id, syncId)).run();
12141
- log12.error("sync.failed", { syncId, release, error: errorMsg });
12241
+ log13.error("sync.failed", { syncId, release, error: errorMsg });
12142
12242
  trackFeatureCompleted({
12143
12243
  ...outcome,
12144
12244
  status: OutcomeStatuses.failed,
@@ -12204,7 +12304,7 @@ function groupByProject(rows, projectsByDomain) {
12204
12304
  import crypto20 from "crypto";
12205
12305
  import fs5 from "fs";
12206
12306
  import { and as and13, desc as desc7, eq as eq17 } from "drizzle-orm";
12207
- var log13 = createLogger("BacklinkExtract");
12307
+ var log14 = createLogger("BacklinkExtract");
12208
12308
  function defaultDeps3() {
12209
12309
  return {
12210
12310
  queryBacklinks,
@@ -12301,7 +12401,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12301
12401
  });
12302
12402
  const finishedAt = deps.now().toISOString();
12303
12403
  db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq17(runs.id, runId)).run();
12304
- log13.info("extract.completed", { runId, projectId, release, rows: rows.length });
12404
+ log14.info("extract.completed", { runId, projectId, release, rows: rows.length });
12305
12405
  const summary = computeSummary(rows);
12306
12406
  reportOutcome({ status: OutcomeStatuses.succeeded, counts: { domains: summary.totalLinkingDomains, links: summary.totalHosts } });
12307
12407
  } catch (err) {
@@ -12312,7 +12412,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
12312
12412
  error: errorMsg,
12313
12413
  finishedAt
12314
12414
  }).where(eq17(runs.id, runId)).run();
12315
- log13.error("extract.failed", { runId, projectId, error: errorMsg });
12415
+ log14.error("extract.failed", { runId, projectId, error: errorMsg });
12316
12416
  reportOutcome({ status: OutcomeStatuses.failed, ...outcomeFailure(err, refusal) });
12317
12417
  throw err;
12318
12418
  }
@@ -12324,7 +12424,7 @@ function computeSummary(rows) {
12324
12424
  // src/discovery-run.ts
12325
12425
  import crypto21 from "crypto";
12326
12426
  import { and as and14, eq as eq18 } from "drizzle-orm";
12327
- var log14 = createLogger("DiscoveryRun");
12427
+ var log15 = createLogger("DiscoveryRun");
12328
12428
  var DEFAULT_SEED_COUNT = 30;
12329
12429
  var EMBED_RETRY_MAX_RETRIES = 3;
12330
12430
  var EMBED_RETRY_MAX_DELAY_MS = 1e4;
@@ -12356,7 +12456,7 @@ async function embedWithRetry(fn) {
12356
12456
  isRetryable: isRetryableHttpError,
12357
12457
  maxDelayMs: EMBED_RETRY_MAX_DELAY_MS,
12358
12458
  onRetry: ({ attempt, delayMs }) => {
12359
- log14.warn("discovery.embed.retry", { attempt, delayMs });
12459
+ log15.warn("discovery.embed.retry", { attempt, delayMs });
12360
12460
  }
12361
12461
  }
12362
12462
  );
@@ -12413,7 +12513,7 @@ async function executeDiscoveryRun(opts) {
12413
12513
  result
12414
12514
  });
12415
12515
  opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq18(runs.id, opts.runId)).run();
12416
- log14.info("discovery.completed", {
12516
+ log15.info("discovery.completed", {
12417
12517
  runId: opts.runId,
12418
12518
  sessionId: opts.sessionId,
12419
12519
  buckets: result.buckets,
@@ -12430,7 +12530,7 @@ async function executeDiscoveryRun(opts) {
12430
12530
  });
12431
12531
  } catch (err) {
12432
12532
  const errorMsg = describeError(err);
12433
- log14.error("discovery.failed", { runId: opts.runId, sessionId: opts.sessionId, error: errorMsg });
12533
+ log15.error("discovery.failed", { runId: opts.runId, sessionId: opts.sessionId, error: errorMsg });
12434
12534
  markSessionFailed(opts.db, opts.sessionId, errorMsg);
12435
12535
  opts.db.update(runs).set({
12436
12536
  status: RunStatuses.failed,
@@ -13099,7 +13199,7 @@ function activePlanEntityRegistry(db, projectId) {
13099
13199
  }
13100
13200
 
13101
13201
  // src/execute-site-audit.ts
13102
- var log15 = createLogger("SiteAudit");
13202
+ var log16 = createLogger("SiteAudit");
13103
13203
  var SiteAuditCancelledError = class extends Error {
13104
13204
  name = "SiteAuditCancelledError";
13105
13205
  };
@@ -13290,6 +13390,10 @@ function trackSiteAuditOutcome(db, input) {
13290
13390
  "site_audit.completed",
13291
13391
  {
13292
13392
  ...buildSiteAuditCompletedProps(input),
13393
+ operationId: input.operationId,
13394
+ operationKind: OutcomeOperationKinds["site-audit"],
13395
+ diagnostics: buildOutcomeDiagnostics(input.error, { phase: input.phase }),
13396
+ ...input.observedPageCount !== void 0 ? { observedPages: input.observedPageCount, observedPageErrors: input.observedPageErrors } : {},
13293
13397
  ...input.status === "failed" ? describeRunFailure(input.error) : {}
13294
13398
  },
13295
13399
  errorCode ? { errorCode } : void 0
@@ -13305,7 +13409,7 @@ function trackSiteAuditOutcome(db, input) {
13305
13409
  pagesAuditedBucket: bucketOnboardingCount(pagesAudited)
13306
13410
  });
13307
13411
  } catch (error) {
13308
- log15.warn("telemetry.failed", { runId: input.runId, projectId: input.projectId, error: describeError(error) });
13412
+ log16.warn("telemetry.failed", { runId: input.runId, projectId: input.projectId, error: describeError(error) });
13309
13413
  }
13310
13414
  }
13311
13415
  async function executeSiteAudit(db, runId, projectId, opts = {}) {
@@ -13313,6 +13417,8 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13313
13417
  const claim = db.update(runs).set({ status: "running", startedAt }).where(and17(eq21(runs.id, runId), eq21(runs.projectId, projectId), eq21(runs.status, "queued"))).run();
13314
13418
  if (claim.changes === 0) return;
13315
13419
  const startTime = Date.now();
13420
+ const operationId = crypto22.randomUUID();
13421
+ let phase = OutcomePhases.setup;
13316
13422
  const trigger = db.select({ trigger: runs.trigger }).from(runs).where(eq21(runs.id, runId)).get()?.trigger ?? null;
13317
13423
  let canonicalDomain = null;
13318
13424
  const attemptNumber = (db.select({ value: sql7`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(eq21(siteCrawlAttempts.runId, runId)).get()?.value ?? 0) + 1;
@@ -13623,7 +13729,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13623
13729
  return { host, rootUrl: resolved.effectiveUrl, error: null };
13624
13730
  } catch (error) {
13625
13731
  if (isCancelled(error, opts.signal)) throw error;
13626
- log15.warn("extra-site.unreachable", { runId, projectId, host, error: describeError(error) });
13732
+ log16.warn("extra-site.unreachable", { runId, projectId, host, error: describeError(error) });
13627
13733
  return { host, rootUrl: null, error: describeError(error) };
13628
13734
  }
13629
13735
  })
@@ -13633,9 +13739,10 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13633
13739
  try {
13634
13740
  entities = activePlanEntityRegistry(db, projectId);
13635
13741
  } catch (error) {
13636
- log15.warn("entity-registry.unavailable", { runId, projectId, error: describeError(error) });
13742
+ log16.warn("entity-registry.unavailable", { runId, projectId, error: describeError(error) });
13637
13743
  }
13638
- log15.info("start", {
13744
+ log16.info("start", {
13745
+ operationId,
13639
13746
  runId,
13640
13747
  projectId,
13641
13748
  homepageUrl,
@@ -13647,6 +13754,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13647
13754
  entityPlanRevision: entities?.planRevision ?? null,
13648
13755
  extraSites: extraSites.map((site) => site.host)
13649
13756
  });
13757
+ phase = OutcomePhases.crawl;
13650
13758
  const report = await runSiteCrawl(crawlRootUrl, {
13651
13759
  mode: "summary",
13652
13760
  sitemapUrl: opts.sitemapUrl,
@@ -13660,12 +13768,17 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13660
13768
  ...additionalRoots.length > 0 ? { additionalRoots } : {},
13661
13769
  ...entities ? { entityRegistry: entities.registry } : {},
13662
13770
  signal: opts.signal,
13663
- onEvent: persistEvent
13771
+ onEvent: async (event) => {
13772
+ phase = OutcomePhases.persistence;
13773
+ await persistEvent(event);
13774
+ phase = OutcomePhases.crawl;
13775
+ }
13664
13776
  });
13665
13777
  const crawlSummary = report.summary;
13666
13778
  if (crawlSummary.complete && crawlSummary.auditRollup.auditedPages === 0) {
13667
13779
  throw emptyCompleteCrawlError(crawlSummary.rootUrl, crawlSummary.finalRootUrl, crawlSummary.pagesObserved);
13668
13780
  }
13781
+ phase = OutcomePhases.persistence;
13669
13782
  const placementRulesetVersion = crawlSummary.linkPlacementRulesetVersion ?? null;
13670
13783
  const templateLinks = classifySiteCrawlTemplateLinks(
13671
13784
  db,
@@ -13673,7 +13786,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13673
13786
  crawlSummary.pagesFetched,
13674
13787
  placementRulesetVersion
13675
13788
  );
13676
- log15.info("template-links", {
13789
+ log16.info("template-links", {
13677
13790
  runId,
13678
13791
  projectId,
13679
13792
  detection: templateLinks.detection,
@@ -13712,7 +13825,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13712
13825
  try {
13713
13826
  persistSiteCrawlGraphLayout(db, { projectId, runId, attemptId }, graphLayout, finishedAt);
13714
13827
  } catch (error) {
13715
- log15.warn("graph-layout.persist-failed", {
13828
+ log16.warn("graph-layout.persist-failed", {
13716
13829
  runId,
13717
13830
  projectId,
13718
13831
  error: describeError(error)
@@ -13730,7 +13843,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13730
13843
  edges: []
13731
13844
  }, finishedAt);
13732
13845
  } catch (markerError) {
13733
- log15.warn("graph-layout.marker-persist-failed", {
13846
+ log16.warn("graph-layout.marker-persist-failed", {
13734
13847
  runId,
13735
13848
  projectId,
13736
13849
  error: describeError(markerError)
@@ -13860,7 +13973,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13860
13973
  try {
13861
13974
  deleteSiteCrawlGraphLayout(db, { projectId, runId, attemptId });
13862
13975
  } catch (cleanupError) {
13863
- log15.warn("graph-layout.cleanup-failed", {
13976
+ log16.warn("graph-layout.cleanup-failed", {
13864
13977
  runId,
13865
13978
  projectId,
13866
13979
  error: describeError(cleanupError)
@@ -13870,7 +13983,8 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13870
13983
  if (current?.status === "cancelled") throw new SiteAuditCancelledError(`Site audit cancelled before publication: ${runId}`);
13871
13984
  throw new Error(`Site audit run was no longer running before publication: ${runId}`);
13872
13985
  }
13873
- log15.info("completed", {
13986
+ log16.info("completed", {
13987
+ operationId,
13874
13988
  runId,
13875
13989
  projectId,
13876
13990
  status: terminalStatus,
@@ -13885,6 +13999,8 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13885
13999
  }))
13886
14000
  });
13887
14001
  trackSiteAuditOutcome(db, {
14002
+ operationId,
14003
+ phase,
13888
14004
  runId,
13889
14005
  projectId,
13890
14006
  status: crawlSummary.complete ? "completed" : "partial",
@@ -13921,8 +14037,12 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
13921
14037
  finishedAt
13922
14038
  }).where(and17(eq21(runs.id, runId), eq21(runs.status, "running"))).run();
13923
14039
  });
13924
- log15.error("failed", { runId, projectId, cancelled, error: message });
14040
+ log16.error("failed", { operationId, runId, projectId, phase, cancelled, error: message });
13925
14041
  trackSiteAuditOutcome(db, {
14042
+ operationId,
14043
+ phase,
14044
+ observedPageCount: observedPages.size,
14045
+ observedPageErrors: observedErrorCount(observedPages.values()),
13926
14046
  runId,
13927
14047
  projectId,
13928
14048
  status: cancelled ? "cancelled" : "failed",
@@ -13957,7 +14077,7 @@ function createAnswerFieldRecomputeQueue(opts) {
13957
14077
 
13958
14078
  // src/competitor-auto-alias-runner.ts
13959
14079
  import { setImmediate as yieldToEventLoop3 } from "timers/promises";
13960
- var log16 = createLogger("CompetitorAutoAliases");
14080
+ var log17 = createLogger("CompetitorAutoAliases");
13961
14081
  function createCompetitorAutoAliasRunner(opts) {
13962
14082
  const reasons = /* @__PURE__ */ new Map();
13963
14083
  const queue = createProjectPassQueue(async (projectId) => {
@@ -13968,7 +14088,7 @@ function createCompetitorAutoAliasRunner(opts) {
13968
14088
  if (!result) return null;
13969
14089
  const added = result.detection.competitors.reduce((sum, competitor) => sum + competitor.added.length, 0);
13970
14090
  const removed = result.detection.competitors.reduce((sum, competitor) => sum + competitor.removed.length, 0);
13971
- log16.info("detection.completed", {
14091
+ log17.info("detection.completed", {
13972
14092
  projectId,
13973
14093
  reason,
13974
14094
  runs: result.detection.scan.runs,
@@ -13981,7 +14101,7 @@ function createCompetitorAutoAliasRunner(opts) {
13981
14101
  try {
13982
14102
  opts.onNamesChanged(projectId, result.detection.project);
13983
14103
  } catch (err) {
13984
- log16.error("names-changed.failed", { projectId, error: describeError(err) });
14104
+ log17.error("names-changed.failed", { projectId, error: describeError(err) });
13985
14105
  }
13986
14106
  }
13987
14107
  return result;
@@ -13993,14 +14113,14 @@ function createCompetitorAutoAliasRunner(opts) {
13993
14113
  return {
13994
14114
  schedule(projectId, reason) {
13995
14115
  enqueue(projectId, reason).catch((err) => {
13996
- log16.error("detection.failed", { projectId, reason, error: describeError(err) });
14116
+ log17.error("detection.failed", { projectId, reason, error: describeError(err) });
13997
14117
  });
13998
14118
  },
13999
14119
  async request(projectId, reason) {
14000
14120
  try {
14001
14121
  return await enqueue(projectId, reason);
14002
14122
  } catch (err) {
14003
- log16.error("detection.failed", { projectId, reason, error: describeError(err) });
14123
+ log17.error("detection.failed", { projectId, reason, error: describeError(err) });
14004
14124
  throw err;
14005
14125
  }
14006
14126
  },
@@ -14010,7 +14130,7 @@ function createCompetitorAutoAliasRunner(opts) {
14010
14130
 
14011
14131
  // src/install-state-telemetry.ts
14012
14132
  import { and as and18, count as count4, eq as eq22, gte as gte2, inArray as inArray9, isNotNull as isNotNull2, isNull as isNull2, ne as ne3, sql as sql8 } from "drizzle-orm";
14013
- var log17 = createLogger("InstallStateTelemetry");
14133
+ var log18 = createLogger("InstallStateTelemetry");
14014
14134
  var INSTALL_STATE_FIRST_DELAY_MS = 5 * 6e4;
14015
14135
  var INSTALL_STATE_INTERVAL_MS = 24 * 60 * 6e4;
14016
14136
  var KNOWN_PROVIDERS2 = new Set(PROVIDER_NAMES);
@@ -14175,7 +14295,7 @@ function startInstallStateTelemetry(sources) {
14175
14295
  try {
14176
14296
  if (isTelemetryEnabled()) trackInstallState(buildInstallState(sources, Date.now(), startedAt));
14177
14297
  } catch (err) {
14178
- log17.warn("telemetry.install-state-failed", { error: describeError(err) });
14298
+ log18.warn("telemetry.install-state-failed", { error: describeError(err) });
14179
14299
  }
14180
14300
  schedule(INSTALL_STATE_INTERVAL_MS);
14181
14301
  };
@@ -14298,7 +14418,7 @@ function createProviderModelCatalog(registry) {
14298
14418
  import crypto23 from "crypto";
14299
14419
  import cron from "node-cron";
14300
14420
  import { and as and19, eq as eq23, inArray as inArray10, notExists, sql as sql9 } from "drizzle-orm";
14301
- var log18 = createLogger("Scheduler");
14421
+ var log19 = createLogger("Scheduler");
14302
14422
  var SLOT_FIRED = { status: OutcomeStatuses.succeeded };
14303
14423
  var slotSkipped = (reasonCode) => ({ status: OutcomeStatuses.skipped, reasonCode });
14304
14424
  var slotFailed = (reasonCode) => ({ status: OutcomeStatuses.failed, reasonCode });
@@ -14388,7 +14508,7 @@ var Scheduler = class {
14388
14508
  if (ensureDefaultHealthSchedule(this.db, project.id, now)) seeded += 1;
14389
14509
  }
14390
14510
  if (seeded > 0) {
14391
- log18.info("health-schedule.seeded", { projectCount: seeded, cron: DEFAULT_HEALTH_CRON });
14511
+ log19.info("health-schedule.seeded", { projectCount: seeded, cron: DEFAULT_HEALTH_CRON });
14392
14512
  }
14393
14513
  }
14394
14514
  /**
@@ -14412,10 +14532,10 @@ var Scheduler = class {
14412
14532
  const current = ensureCurrentQueryBasketRevision(this.db, project.id);
14413
14533
  if (current !== null && current.revision !== previous) minted += 1;
14414
14534
  } catch (err) {
14415
- log18.warn("query-basket.mint-failed", { projectId: project.id, err: String(err) });
14535
+ log19.warn("query-basket.mint-failed", { projectId: project.id, err: String(err) });
14416
14536
  }
14417
14537
  }
14418
- if (minted > 0) log18.info("query-basket.ensured", { projectCount: minted });
14538
+ if (minted > 0) log19.info("query-basket.ensured", { projectCount: minted });
14419
14539
  }
14420
14540
  /** Load all enabled schedules from DB and register cron jobs. */
14421
14541
  start() {
@@ -14429,12 +14549,12 @@ var Scheduler = class {
14429
14549
  if (registered && missedRunAt && new Date(missedRunAt) < /* @__PURE__ */ new Date()) {
14430
14550
  const answerRecurrence = recurrence && schedule.kind === SchedulableRunKinds["answer-visibility"];
14431
14551
  if (!recurrence || answerRecurrence || this.claimCalendarOccurrence(schedule, missedRunAt, /* @__PURE__ */ new Date())) {
14432
- log18.info("run.catch-up", { projectId: schedule.projectId, kind: schedule.kind, missedRunAt });
14552
+ log19.info("run.catch-up", { projectId: schedule.projectId, kind: schedule.kind, missedRunAt });
14433
14553
  this.triggerRun(schedule.id, schedule.projectId, schedule.kind, answerRecurrence ? missedRunAt : void 0, OutcomeTriggers.startup);
14434
14554
  }
14435
14555
  }
14436
14556
  }
14437
- log18.info("started", { scheduleCount: allSchedules.length });
14557
+ log19.info("started", { scheduleCount: allSchedules.length });
14438
14558
  }
14439
14559
  /** Stop all cron tasks for graceful shutdown. */
14440
14560
  stop() {
@@ -14483,7 +14603,7 @@ var Scheduler = class {
14483
14603
  clearTimeout(pending);
14484
14604
  this.spreadTimers.delete(key);
14485
14605
  }
14486
- log18.info(`task.${verb.toLowerCase()}`, { key });
14606
+ log19.info(`task.${verb.toLowerCase()}`, { key });
14487
14607
  }
14488
14608
  /** Runtime timing writes must not restore a version already issued to a settings caller. */
14489
14609
  updateScheduleTiming(scheduleId, timing) {
@@ -14503,13 +14623,13 @@ var Scheduler = class {
14503
14623
  return true;
14504
14624
  }
14505
14625
  if (schedule.recurrence) {
14506
- log18.error("calendar.invalid", { projectId: schedule.projectId, kind: schedule.kind });
14626
+ log19.error("calendar.invalid", { projectId: schedule.projectId, kind: schedule.kind });
14507
14627
  return false;
14508
14628
  }
14509
14629
  const { id: scheduleId, projectId, cronExpr, timezone } = schedule;
14510
14630
  const kind = schedule.kind;
14511
14631
  if (!cron.validate(cronExpr)) {
14512
- log18.error("cron.invalid", { projectId, kind, cronExpr });
14632
+ log19.error("cron.invalid", { projectId, kind, cronExpr });
14513
14633
  return false;
14514
14634
  }
14515
14635
  const key = taskKey(projectId, kind);
@@ -14539,7 +14659,7 @@ var Scheduler = class {
14539
14659
  });
14540
14660
  }
14541
14661
  const label = schedule.preset ?? cronExpr;
14542
- log18.info("cron.registered", { projectId, kind, schedule: label, timezone });
14662
+ log19.info("cron.registered", { projectId, kind, schedule: label, timezone });
14543
14663
  return true;
14544
14664
  }
14545
14665
  /** Calendar schedules are checked at most once a minute so long intervals
@@ -14597,7 +14717,7 @@ var Scheduler = class {
14597
14717
  }
14598
14718
  if (options.preserveNextRunAt) arm(registeredNextRunAt);
14599
14719
  else timer = setTimeout(tick, 0);
14600
- log18.info("calendar.registered", { projectId, kind, recurrence, timezone });
14720
+ log19.info("calendar.registered", { projectId, kind, recurrence, timezone });
14601
14721
  }
14602
14722
  /** Atomically advance a due callback-only calendar occurrence before dispatch. */
14603
14723
  claimCalendarOccurrence(schedule, dueAt, now) {
@@ -14639,13 +14759,13 @@ var Scheduler = class {
14639
14759
  const now = (/* @__PURE__ */ new Date()).toISOString();
14640
14760
  const currentSchedule = this.db.select().from(schedules).where(eq23(schedules.id, scheduleId)).get();
14641
14761
  if (!currentSchedule || !currentSchedule.enabled) {
14642
- log18.warn("schedule.stale", { scheduleId, projectId, kind, msg: "schedule no longer exists or is disabled" });
14762
+ log19.warn("schedule.stale", { scheduleId, projectId, kind, msg: "schedule no longer exists or is disabled" });
14643
14763
  this.remove(projectId, kind);
14644
14764
  return slotSkipped(currentSchedule ? OutcomeReasonCodes.NOT_DUE : OutcomeReasonCodes.NOT_FOUND);
14645
14765
  }
14646
14766
  const recurrence = scheduleRecurrence(currentSchedule);
14647
14767
  if (claimedOccurrence && (!recurrence || currentSchedule.nextRunAt !== claimedOccurrence)) {
14648
- log18.info("calendar.stale-claim", { projectId, scheduleId, kind });
14768
+ log19.info("calendar.stale-claim", { projectId, scheduleId, kind });
14649
14769
  return slotSkipped(OutcomeReasonCodes.NOT_DUE);
14650
14770
  }
14651
14771
  const nextRunAt = nextRunFromSchedule({
@@ -14655,31 +14775,31 @@ var Scheduler = class {
14655
14775
  });
14656
14776
  const project = this.db.select().from(projects).where(eq23(projects.id, projectId)).get();
14657
14777
  if (!project) {
14658
- log18.error("project.not-found", { projectId, kind, msg: "skipping scheduled run" });
14778
+ log19.error("project.not-found", { projectId, kind, msg: "skipping scheduled run" });
14659
14779
  this.remove(projectId, kind);
14660
14780
  return slotSkipped(OutcomeReasonCodes.NOT_FOUND);
14661
14781
  }
14662
14782
  if (kind === SchedulableRunKinds["traffic-sync"]) {
14663
14783
  const sourceId = currentSchedule.sourceId;
14664
14784
  if (!sourceId) {
14665
- log18.warn("traffic-sync.missing-source", { scheduleId, projectId });
14785
+ log19.warn("traffic-sync.missing-source", { scheduleId, projectId });
14666
14786
  return slotFailed(OutcomeReasonCodes.VALIDATION);
14667
14787
  }
14668
14788
  if (!this.callbacks.onTrafficSyncRequested) {
14669
- log18.warn("traffic-sync.no-callback", { scheduleId, projectId, msg: "host did not register onTrafficSyncRequested" });
14789
+ log19.warn("traffic-sync.no-callback", { scheduleId, projectId, msg: "host did not register onTrafficSyncRequested" });
14670
14790
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14671
14791
  }
14672
14792
  this.updateScheduleTiming(currentSchedule.id, {
14673
14793
  lastRunAt: now,
14674
14794
  nextRunAt
14675
14795
  });
14676
- log18.info("traffic-sync.triggered", { projectName: project.name, sourceId });
14796
+ log19.info("traffic-sync.triggered", { projectName: project.name, sourceId });
14677
14797
  this.callbacks.onTrafficSyncRequested(project.name, sourceId);
14678
14798
  return SLOT_FIRED;
14679
14799
  }
14680
14800
  if (kind === SchedulableRunKinds["gbp-sync"]) {
14681
14801
  if (!this.callbacks.onGbpSyncRequested) {
14682
- log18.warn("gbp-sync.no-callback", { scheduleId, projectId, msg: "host did not register onGbpSyncRequested" });
14802
+ log19.warn("gbp-sync.no-callback", { scheduleId, projectId, msg: "host did not register onGbpSyncRequested" });
14683
14803
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14684
14804
  }
14685
14805
  const runId2 = crypto23.randomUUID();
@@ -14695,13 +14815,13 @@ var Scheduler = class {
14695
14815
  lastRunAt: now,
14696
14816
  nextRunAt
14697
14817
  });
14698
- log18.info("gbp-sync.triggered", { runId: runId2, projectName: project.name });
14818
+ log19.info("gbp-sync.triggered", { runId: runId2, projectName: project.name });
14699
14819
  this.callbacks.onGbpSyncRequested(runId2, projectId);
14700
14820
  return SLOT_FIRED;
14701
14821
  }
14702
14822
  if (kind === SchedulableRunKinds["ads-sync"]) {
14703
14823
  if (!this.callbacks.onAdsSyncRequested) {
14704
- log18.warn("ads-sync.no-callback", { scheduleId, projectId, msg: "host did not register onAdsSyncRequested" });
14824
+ log19.warn("ads-sync.no-callback", { scheduleId, projectId, msg: "host did not register onAdsSyncRequested" });
14705
14825
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14706
14826
  }
14707
14827
  const activeAdsRun = this.db.select({ id: runs.id }).from(runs).where(and19(
@@ -14710,7 +14830,7 @@ var Scheduler = class {
14710
14830
  inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
14711
14831
  )).get();
14712
14832
  if (activeAdsRun) {
14713
- log18.info("ads-sync.skipped-active", { projectName: project.name, activeRunId: activeAdsRun.id });
14833
+ log19.info("ads-sync.skipped-active", { projectName: project.name, activeRunId: activeAdsRun.id });
14714
14834
  this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
14715
14835
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14716
14836
  }
@@ -14727,13 +14847,13 @@ var Scheduler = class {
14727
14847
  lastRunAt: now,
14728
14848
  nextRunAt
14729
14849
  });
14730
- log18.info("ads-sync.triggered", { runId: runId2, projectName: project.name });
14850
+ log19.info("ads-sync.triggered", { runId: runId2, projectName: project.name });
14731
14851
  this.callbacks.onAdsSyncRequested(runId2, projectId);
14732
14852
  return SLOT_FIRED;
14733
14853
  }
14734
14854
  if (kind === SchedulableRunKinds["seo-sync"]) {
14735
14855
  if (!this.callbacks.onSeoSyncRequested) {
14736
- log18.warn("seo-sync.no-callback", { scheduleId, projectId, msg: "host did not register onSeoSyncRequested" });
14856
+ log19.warn("seo-sync.no-callback", { scheduleId, projectId, msg: "host did not register onSeoSyncRequested" });
14737
14857
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14738
14858
  }
14739
14859
  const activeSeoRun = this.db.select({ id: runs.id }).from(runs).where(and19(
@@ -14742,7 +14862,7 @@ var Scheduler = class {
14742
14862
  inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
14743
14863
  )).get();
14744
14864
  if (activeSeoRun) {
14745
- log18.info("seo-sync.skipped-active", { projectName: project.name, activeRunId: activeSeoRun.id });
14865
+ log19.info("seo-sync.skipped-active", { projectName: project.name, activeRunId: activeSeoRun.id });
14746
14866
  this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
14747
14867
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14748
14868
  }
@@ -14750,52 +14870,52 @@ var Scheduler = class {
14750
14870
  lastRunAt: now,
14751
14871
  nextRunAt
14752
14872
  });
14753
- log18.info("seo-sync.triggered", { projectName: project.name });
14873
+ log19.info("seo-sync.triggered", { projectName: project.name });
14754
14874
  this.callbacks.onSeoSyncRequested({ scheduleId, projectId, occurrence: now.slice(0, 16) });
14755
14875
  return SLOT_FIRED;
14756
14876
  }
14757
14877
  if (kind === SchedulableRunKinds["data-refresh"]) {
14758
14878
  if (!this.callbacks.onDataRefreshRequested) {
14759
- log18.warn("data-refresh.no-callback", { scheduleId, projectId, msg: "host did not register onDataRefreshRequested" });
14879
+ log19.warn("data-refresh.no-callback", { scheduleId, projectId, msg: "host did not register onDataRefreshRequested" });
14760
14880
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14761
14881
  }
14762
14882
  this.updateScheduleTiming(currentSchedule.id, {
14763
14883
  lastRunAt: now,
14764
14884
  nextRunAt
14765
14885
  });
14766
- log18.info("data-refresh.triggered", { projectName: project.name });
14886
+ log19.info("data-refresh.triggered", { projectName: project.name });
14767
14887
  this.callbacks.onDataRefreshRequested(project.name);
14768
14888
  return SLOT_FIRED;
14769
14889
  }
14770
14890
  if (kind === SchedulableRunKinds.doctor) {
14771
14891
  if (!this.callbacks.onDoctorRequested) {
14772
- log18.warn("doctor.no-callback", { scheduleId, projectId, msg: "host did not register onDoctorRequested" });
14892
+ log19.warn("doctor.no-callback", { scheduleId, projectId, msg: "host did not register onDoctorRequested" });
14773
14893
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14774
14894
  }
14775
14895
  this.updateScheduleTiming(currentSchedule.id, {
14776
14896
  lastRunAt: now,
14777
14897
  nextRunAt
14778
14898
  });
14779
- log18.info("doctor.triggered", { projectName: project.name });
14899
+ log19.info("doctor.triggered", { projectName: project.name });
14780
14900
  this.callbacks.onDoctorRequested(project.name);
14781
14901
  return SLOT_FIRED;
14782
14902
  }
14783
14903
  if (kind === SchedulableRunKinds["backlinks-sync"]) {
14784
14904
  if (!this.callbacks.onBacklinksSyncRequested) {
14785
- log18.warn("backlinks-sync.no-callback", { scheduleId, projectId, msg: "host did not register onBacklinksSyncRequested" });
14905
+ log19.warn("backlinks-sync.no-callback", { scheduleId, projectId, msg: "host did not register onBacklinksSyncRequested" });
14786
14906
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14787
14907
  }
14788
14908
  this.updateScheduleTiming(currentSchedule.id, {
14789
14909
  lastRunAt: now,
14790
14910
  nextRunAt
14791
14911
  });
14792
- log18.info("backlinks-sync.triggered", { projectName: project.name });
14912
+ log19.info("backlinks-sync.triggered", { projectName: project.name });
14793
14913
  this.callbacks.onBacklinksSyncRequested(project.name);
14794
14914
  return SLOT_FIRED;
14795
14915
  }
14796
14916
  if (kind === SchedulableRunKinds["site-audit"]) {
14797
14917
  if (!this.callbacks.onSiteAuditRequested) {
14798
- log18.warn("site-audit.no-callback", { scheduleId, projectId, msg: "host did not register onSiteAuditRequested" });
14918
+ log19.warn("site-audit.no-callback", { scheduleId, projectId, msg: "host did not register onSiteAuditRequested" });
14799
14919
  return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
14800
14920
  }
14801
14921
  const active = this.db.select({ id: runs.id }).from(runs).where(and19(
@@ -14804,7 +14924,7 @@ var Scheduler = class {
14804
14924
  inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
14805
14925
  )).get();
14806
14926
  if (active) {
14807
- log18.info("site-audit.skipped-active", { projectName: project.name, activeRunId: active.id });
14927
+ log19.info("site-audit.skipped-active", { projectName: project.name, activeRunId: active.id });
14808
14928
  this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
14809
14929
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14810
14930
  }
@@ -14833,7 +14953,7 @@ var Scheduler = class {
14833
14953
  lastRunAt: now,
14834
14954
  nextRunAt
14835
14955
  });
14836
- log18.info("site-audit.triggered", { runId: runId2, projectName: project.name });
14956
+ log19.info("site-audit.triggered", { runId: runId2, projectName: project.name });
14837
14957
  this.callbacks.onSiteAuditRequested(runId2, projectId, {
14838
14958
  maxPages: effectiveRequest.maxPages,
14839
14959
  checkDeadLinks: effectiveRequest.checkDeadLinks,
@@ -14848,7 +14968,7 @@ var Scheduler = class {
14848
14968
  if (project.defaultLocation) {
14849
14969
  const loc = projectLocations.find((l) => l.label === project.defaultLocation);
14850
14970
  if (!loc) {
14851
- log18.warn("default-location.stale", { scheduleId, projectId, label: project.defaultLocation });
14971
+ log19.warn("default-location.stale", { scheduleId, projectId, label: project.defaultLocation });
14852
14972
  return slotFailed(OutcomeReasonCodes.VALIDATION);
14853
14973
  }
14854
14974
  resolvedLocation = loc;
@@ -14857,7 +14977,7 @@ var Scheduler = class {
14857
14977
  const scheduleProviders = currentSchedule.providers;
14858
14978
  const providers = scheduleProviders.length > 0 ? scheduleProviders : void 0;
14859
14979
  if (claimedOccurrence && recurrence && !nextRunAt) {
14860
- log18.error("calendar.invalid", { projectId, kind, scheduleId });
14980
+ log19.error("calendar.invalid", { projectId, kind, scheduleId });
14861
14981
  return slotFailed(OutcomeReasonCodes.VALIDATION);
14862
14982
  }
14863
14983
  const queueResult = queueRunIfProjectIdle(this.db, {
@@ -14885,11 +15005,11 @@ var Scheduler = class {
14885
15005
  });
14886
15006
  if (queueResult.conflict) {
14887
15007
  if (queueResult.scheduleClaimed === false) {
14888
- log18.info("calendar.skipped-claimed", { projectName: project.name, scheduleId: currentSchedule.id });
15008
+ log19.info("calendar.skipped-claimed", { projectName: project.name, scheduleId: currentSchedule.id });
14889
15009
  return slotSkipped(OutcomeReasonCodes.NOT_DUE);
14890
15010
  }
14891
15011
  const batchPending = hasOutstandingProviderBatch(this.db, queueResult.activeRunId);
14892
- log18.info("run.skipped-active", {
15012
+ log19.info("run.skipped-active", {
14893
15013
  projectName: project.name,
14894
15014
  activeRunId: queueResult.activeRunId,
14895
15015
  ...batchPending ? { reason: "batch-pending" } : {}
@@ -14898,7 +15018,7 @@ var Scheduler = class {
14898
15018
  return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
14899
15019
  }
14900
15020
  if (queueResult.refused) {
14901
- log18.warn("run.skipped-providers-failing", {
15021
+ log19.warn("run.skipped-providers-failing", {
14902
15022
  projectName: project.name,
14903
15023
  scheduleId: currentSchedule.id,
14904
15024
  ...queueResult.refused
@@ -14917,7 +15037,7 @@ var Scheduler = class {
14917
15037
  const runId = queueResult.runId;
14918
15038
  for (const [provider, reason] of Object.entries(queueResult.dispatch.ineligible)) {
14919
15039
  if (!reason) continue;
14920
- log18.warn("run.dispatch-sync-fallback", {
15040
+ log19.warn("run.dispatch-sync-fallback", {
14921
15041
  runId,
14922
15042
  projectName: project.name,
14923
15043
  provider,
@@ -14931,7 +15051,7 @@ var Scheduler = class {
14931
15051
  lastRunAt: now,
14932
15052
  nextRunAt
14933
15053
  });
14934
- log18.info("run.triggered", {
15054
+ log19.info("run.triggered", {
14935
15055
  runId,
14936
15056
  projectName: project.name,
14937
15057
  providers: providers ?? "all",
@@ -14940,14 +15060,14 @@ var Scheduler = class {
14940
15060
  this.callbacks.onRunCreated(runId, projectId, providers, resolvedLocation);
14941
15061
  return SLOT_FIRED;
14942
15062
  } catch (err) {
14943
- log18.error("trigger.error", { scheduleId, projectId, kind, error: describeError(err) });
15063
+ log19.error("trigger.error", { scheduleId, projectId, kind, error: describeError(err) });
14944
15064
  return { status: OutcomeStatuses.failed, ...outcomeFailure(err) };
14945
15065
  }
14946
15066
  }
14947
15067
  };
14948
15068
 
14949
15069
  // src/site-liveness-loop.ts
14950
- var log19 = createLogger("SiteLiveness");
15070
+ var log20 = createLogger("SiteLiveness");
14951
15071
  var SITE_LIVENESS_INTERVAL_MS = 10 * 6e4;
14952
15072
  async function runSiteLivenessPass(deps) {
14953
15073
  const now = deps.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
@@ -14964,10 +15084,10 @@ async function runSiteLivenessPass(deps) {
14964
15084
  const event = await deps.notify(project.id, { check, checkedAt: now() });
14965
15085
  if (event) {
14966
15086
  events += 1;
14967
- log19.info("site-liveness.notified", { projectName: project.name, event, code: check.code });
15087
+ log20.info("site-liveness.notified", { projectName: project.name, event, code: check.code });
14968
15088
  }
14969
15089
  } catch (err) {
14970
- log19.warn("site-liveness.project-failed", { projectName: project.name, err: String(err) });
15090
+ log20.warn("site-liveness.project-failed", { projectName: project.name, err: String(err) });
14971
15091
  if (failed === 0) firstFailure = err;
14972
15092
  failed += 1;
14973
15093
  }
@@ -14999,14 +15119,14 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
14999
15119
  };
15000
15120
  const timer = setInterval(() => {
15001
15121
  if (running) {
15002
- log19.warn("site-liveness.pass-still-running", { intervalMs });
15122
+ log20.warn("site-liveness.pass-still-running", { intervalMs });
15003
15123
  report({ status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.OPERATION_IN_PROGRESS });
15004
15124
  return;
15005
15125
  }
15006
15126
  running = true;
15007
15127
  const elapsed = startOutcomeTimer();
15008
15128
  void runSiteLivenessPass(deps).then((result) => report({ ...livenessOutcome(result), durationBucket: elapsed() })).catch((err) => {
15009
- log19.warn("site-liveness.pass-failed", { err: String(err) });
15129
+ log20.warn("site-liveness.pass-failed", { err: String(err) });
15010
15130
  report({ status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() });
15011
15131
  }).finally(() => {
15012
15132
  running = false;
@@ -15019,7 +15139,7 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
15019
15139
  // src/review-webhook-delivery.ts
15020
15140
  import { createHash as createHash7 } from "crypto";
15021
15141
  import { and as and20, asc as asc4, eq as eq24, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
15022
- var log20 = createLogger("ReviewDelivery");
15142
+ var log21 = createLogger("ReviewDelivery");
15023
15143
  var hash = (value) => createHash7("sha256").update(JSON.stringify(value)).digest("hex");
15024
15144
  var REVIEW_DELIVERY_MAX_ATTEMPTS = 10;
15025
15145
  var REVIEW_CHAT_SENDS_PER_PASS = 3;
@@ -15126,7 +15246,7 @@ function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS
15126
15246
  if (running) return;
15127
15247
  running = true;
15128
15248
  void drain().catch((err) => {
15129
- log20.warn("review-delivery.drain-failed", { error: describeError(err) });
15249
+ log21.warn("review-delivery.drain-failed", { error: describeError(err) });
15130
15250
  }).finally(() => {
15131
15251
  running = false;
15132
15252
  });
@@ -15302,7 +15422,7 @@ async function deliverReviewEvent(options) {
15302
15422
 
15303
15423
  // src/unrecognized-agent-alerts.ts
15304
15424
  import { and as and21, desc as desc8, eq as eq25, gte as gte3, sql as sql10 } from "drizzle-orm";
15305
- var log21 = createLogger("UnrecognizedAgentAlerts");
15425
+ var log22 = createLogger("UnrecognizedAgentAlerts");
15306
15426
  var UNRECOGNIZED_AGENT_ALERT_WINDOW_MS = 7 * 864e5;
15307
15427
  var UNRECOGNIZED_AGENT_ALERT_MIN_HITS = 3;
15308
15428
  var UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS = 15 * 6e4;
@@ -15366,7 +15486,7 @@ function startUnrecognizedAgentAlertLoop(dispatch, intervalMs = UNRECOGNIZED_AGE
15366
15486
  if (running) return;
15367
15487
  running = true;
15368
15488
  void dispatch().catch((err) => {
15369
- log21.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
15489
+ log22.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
15370
15490
  }).finally(() => {
15371
15491
  running = false;
15372
15492
  });
@@ -15377,7 +15497,7 @@ function startUnrecognizedAgentAlertLoop(dispatch, intervalMs = UNRECOGNIZED_AGE
15377
15497
 
15378
15498
  // src/provider-batch-poller.ts
15379
15499
  import { and as and22, eq as eq26, inArray as inArray11, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql11 } from "drizzle-orm";
15380
- var log22 = createLogger("ProviderBatchPoller");
15500
+ var log23 = createLogger("ProviderBatchPoller");
15381
15501
  var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
15382
15502
  var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
15383
15503
  var PROVIDER_BATCH_CANCEL_GRACE_MS = 60 * 6e4;
@@ -15401,7 +15521,7 @@ var ProviderBatchPoller = class {
15401
15521
  try {
15402
15522
  if (await this.advance(row)) settledRuns.set(row.runId, row.projectId);
15403
15523
  } catch (err) {
15404
- log22.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15524
+ log23.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15405
15525
  this.reschedule(row.id, null);
15406
15526
  }
15407
15527
  }
@@ -15410,7 +15530,7 @@ var ProviderBatchPoller = class {
15410
15530
  try {
15411
15531
  this.deps.runner.finalizeBatchRun(runId, projectId);
15412
15532
  } catch (err) {
15413
- log22.warn("batch.finalize-failed", { runId, error: describeError(err) });
15533
+ log23.warn("batch.finalize-failed", { runId, error: describeError(err) });
15414
15534
  }
15415
15535
  }
15416
15536
  }
@@ -15441,10 +15561,10 @@ var ProviderBatchPoller = class {
15441
15561
  return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
15442
15562
  }
15443
15563
  } catch (err) {
15444
- log22.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15564
+ log23.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
15445
15565
  }
15446
15566
  } else {
15447
- log22.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
15567
+ log23.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
15448
15568
  }
15449
15569
  this.reschedule(row.id, status);
15450
15570
  return this.enforceDeadline(row, registered);
@@ -15466,12 +15586,12 @@ var ProviderBatchPoller = class {
15466
15586
  isNull4(providerBatches.cancelRequestedAt)
15467
15587
  )).run().changes === 1;
15468
15588
  if (!claimed) return false;
15469
- log22.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
15589
+ log23.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
15470
15590
  if (registered?.adapter.batch && row.providerBatchId) {
15471
15591
  try {
15472
15592
  await registered.adapter.batch.cancel(row.providerBatchId, registered.config);
15473
15593
  } catch (err) {
15474
- log22.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
15594
+ log23.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
15475
15595
  }
15476
15596
  }
15477
15597
  return false;
@@ -15483,7 +15603,7 @@ var ProviderBatchPoller = class {
15483
15603
  updatedAt: at
15484
15604
  }).where(and22(eq26(providerBatches.id, row.id), eq26(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
15485
15605
  this.schedule.delete(row.id);
15486
- if (gaveUp) log22.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
15606
+ if (gaveUp) log23.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
15487
15607
  return gaveUp;
15488
15608
  }
15489
15609
  async ingest(row) {
@@ -15492,7 +15612,7 @@ var ProviderBatchPoller = class {
15492
15612
  return result.kind !== "skipped";
15493
15613
  } catch (err) {
15494
15614
  const error = describeError(err);
15495
- log22.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
15615
+ log23.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
15496
15616
  const now = this.now();
15497
15617
  const unreadable = row.resultsExpireAt !== null && now >= Date.parse(row.resultsExpireAt);
15498
15618
  if (unreadable || now >= Date.parse(row.deadlineAt) + PROVIDER_BATCH_CANCEL_GRACE_MS) {
@@ -15534,7 +15654,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
15534
15654
  const timer = setInterval(() => {
15535
15655
  if (running) return;
15536
15656
  running = true;
15537
- void poller.tick().catch((err) => log22.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
15657
+ void poller.tick().catch((err) => log23.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
15538
15658
  running = false;
15539
15659
  });
15540
15660
  }, intervalMs);
@@ -15543,7 +15663,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
15543
15663
  }
15544
15664
 
15545
15665
  // src/data-refresh.ts
15546
- var log23 = createLogger("DataRefresh");
15666
+ var log24 = createLogger("DataRefresh");
15547
15667
  function gaRefreshDays(now = /* @__PURE__ */ new Date()) {
15548
15668
  const [reportMonth] = reportMonthsForDoctor(void 0, now);
15549
15669
  const reach = inclusiveDayCount(`${reportMonth}-01`, now.toISOString().slice(0, 10)) ?? 0;
@@ -15585,15 +15705,15 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
15585
15705
  if (result.status === "rejected") {
15586
15706
  const reason = result.reason;
15587
15707
  const message = describeError(reason);
15588
- log23.warn("integration.refresh-failed", { projectName, integration, error: message });
15708
+ log24.warn("integration.refresh-failed", { projectName, integration, error: message });
15589
15709
  return;
15590
15710
  }
15591
15711
  switch (completion) {
15592
15712
  case "synchronous":
15593
- log23.info("integration.refreshed", { projectName, integration });
15713
+ log24.info("integration.refreshed", { projectName, integration });
15594
15714
  return;
15595
15715
  case "queued":
15596
- log23.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
15716
+ log24.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
15597
15717
  return;
15598
15718
  default: {
15599
15719
  const _exhaustive = completion;
@@ -15683,7 +15803,7 @@ function writeSiteHealthNotifyState(db, input) {
15683
15803
  }
15684
15804
 
15685
15805
  // src/notifier.ts
15686
- var log24 = createLogger("Notifier");
15806
+ var log25 = createLogger("Notifier");
15687
15807
  var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
15688
15808
  function trackWebhookDelivery(input) {
15689
15809
  const sample = sampleDelivery(input.failure ? "failed" : "succeeded");
@@ -15803,26 +15923,26 @@ var Notifier = class {
15803
15923
  }
15804
15924
  /** Called after a run completes (success, partial, or failed). */
15805
15925
  async onRunCompleted(runId, projectId, opts) {
15806
- log24.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
15926
+ log25.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
15807
15927
  const notifs = this.db.select().from(notifications).where(eq28(notifications.projectId, projectId)).all().filter((n) => n.enabled);
15808
15928
  if (notifs.length === 0) {
15809
- log24.info("notifications.none-enabled", { projectId });
15929
+ log25.info("notifications.none-enabled", { projectId });
15810
15930
  return;
15811
15931
  }
15812
- log24.info("notifications.found", { projectId, count: notifs.length });
15932
+ log25.info("notifications.found", { projectId, count: notifs.length });
15813
15933
  const run = this.db.select().from(runs).where(eq28(runs.id, runId)).get();
15814
15934
  if (!run) {
15815
- log24.error("run.not-found", { runId, msg: "skipping notification dispatch" });
15935
+ log25.error("run.not-found", { runId, msg: "skipping notification dispatch" });
15816
15936
  return;
15817
15937
  }
15818
15938
  const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
15819
15939
  if (!project) {
15820
- log24.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
15940
+ log25.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
15821
15941
  return;
15822
15942
  }
15823
15943
  const transitions = this.computeTransitions(runId, projectId);
15824
15944
  const events = [];
15825
- log24.info("run.status", { runId: run.id, status: run.status, projectId });
15945
+ log25.info("run.status", { runId: run.id, status: run.status, projectId });
15826
15946
  if ((run.status === "completed" || run.status === "partial") && opts?.origin !== "fill") {
15827
15947
  events.push("run.completed");
15828
15948
  }
@@ -15838,7 +15958,7 @@ var Notifier = class {
15838
15958
  if (!config.url) continue;
15839
15959
  const subscribedEvents = config.events;
15840
15960
  const matchingEvents = events.filter((e) => subscribedEvents.includes(e));
15841
- log24.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
15961
+ log25.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
15842
15962
  if (matchingEvents.length === 0) continue;
15843
15963
  for (const event of matchingEvents) {
15844
15964
  const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : transitions;
@@ -15896,7 +16016,7 @@ var Notifier = class {
15896
16016
  async onHealthChecked(projectId, report) {
15897
16017
  const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
15898
16018
  if (!project) {
15899
- log24.error("project.not-found", { projectId, msg: "skipping health notification" });
16019
+ log25.error("project.not-found", { projectId, msg: "skipping health notification" });
15900
16020
  return null;
15901
16021
  }
15902
16022
  const rank = healthRank;
@@ -16092,7 +16212,7 @@ var Notifier = class {
16092
16212
  this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq28(doctorHealthState.projectId, projectId)).run();
16093
16213
  }
16094
16214
  if (urgentNotifs.length > 0) {
16095
- log24.info("health.urgent-notified", {
16215
+ log25.info("health.urgent-notified", {
16096
16216
  projectId,
16097
16217
  event: urgentEvent,
16098
16218
  codes: urgentEvent === "health.urgent" ? breachCodes(urgentNew) : breachCodes(urgentCleared),
@@ -16103,9 +16223,9 @@ var Notifier = class {
16103
16223
  }
16104
16224
  if (!event) {
16105
16225
  if (clearedThisPass.length > 0 || easedThisPass.length > 0) {
16106
- log24.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
16226
+ log25.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
16107
16227
  } else {
16108
- log24.info("health.unchanged", { projectId, status, code });
16228
+ log25.info("health.unchanged", { projectId, status, code });
16109
16229
  }
16110
16230
  return null;
16111
16231
  }
@@ -16135,7 +16255,7 @@ var Notifier = class {
16135
16255
  if (delivered > 0) {
16136
16256
  this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq28(doctorHealthState.projectId, projectId)).run();
16137
16257
  }
16138
- log24.info("health.notified", {
16258
+ log25.info("health.notified", {
16139
16259
  projectId,
16140
16260
  event,
16141
16261
  status,
@@ -16165,7 +16285,7 @@ var Notifier = class {
16165
16285
  if (check.status !== "ok" && check.status !== "fail") return null;
16166
16286
  const project = this.db.select().from(projects).where(eq28(projects.id, projectId)).get();
16167
16287
  if (!project) {
16168
- log24.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
16288
+ log25.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
16169
16289
  return null;
16170
16290
  }
16171
16291
  const previous = this.db.select().from(siteLivenessState).where(eq28(siteLivenessState.projectId, projectId)).get();
@@ -16249,7 +16369,7 @@ var Notifier = class {
16249
16369
  if (event === "health.degraded" && delivered > 0) {
16250
16370
  this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq28(siteLivenessState.projectId, projectId)).run();
16251
16371
  }
16252
- log24.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
16372
+ log25.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
16253
16373
  }
16254
16374
  for (const group of urgentGroups) {
16255
16375
  const { urgentEvent, urgentNotifs, generalIds } = group;
@@ -16264,7 +16384,7 @@ var Notifier = class {
16264
16384
  this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq28(siteLivenessState.projectId, projectId)).run();
16265
16385
  }
16266
16386
  if (urgentNotifs.length > 0 || generalIds.size > 0) {
16267
- log24.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
16387
+ log25.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
16268
16388
  }
16269
16389
  }
16270
16390
  return event;
@@ -16548,7 +16668,7 @@ var Notifier = class {
16548
16668
  delivered += accepted;
16549
16669
  }
16550
16670
  }
16551
- log24.info("reviews.dispatched", {
16671
+ log25.info("reviews.dispatched", {
16552
16672
  projectId,
16553
16673
  reviews: reviewsToSend.length,
16554
16674
  ratingDrops: ratingsToSend.length,
@@ -16561,7 +16681,7 @@ var Notifier = class {
16561
16681
  if (!thisRun) return [];
16562
16682
  const completeness = measurementRunCompleteness(this.db, runId);
16563
16683
  if (completeness.planned && !completeness.complete) {
16564
- log24.info("transitions.skipped-incomplete", {
16684
+ log25.info("transitions.skipped-incomplete", {
16565
16685
  runId,
16566
16686
  executed: completeness.executed,
16567
16687
  expected: completeness.expected
@@ -16756,7 +16876,7 @@ var Notifier = class {
16756
16876
  if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
16757
16877
  }
16758
16878
  if (!accepted) {
16759
- log24.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
16879
+ log25.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
16760
16880
  return null;
16761
16881
  }
16762
16882
  writeSiteHealthNotifyState(this.db, {
@@ -16776,7 +16896,7 @@ var Notifier = class {
16776
16896
  const targetLabel = redactNotificationUrl(url).urlDisplay;
16777
16897
  const targetCheck = await resolveWebhookTarget(url, { allowLoopback: this.allowLoopbackWebhooks });
16778
16898
  if (!targetCheck.ok) {
16779
- log24.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
16899
+ log25.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
16780
16900
  this.logDelivery(projectId, notificationId, payload.event, "failed", `SSRF: ${targetCheck.message}`);
16781
16901
  const reasonCode = webhookTargetRefusalReason(targetCheck);
16782
16902
  trackWebhookDelivery({
@@ -16789,7 +16909,7 @@ var Notifier = class {
16789
16909
  });
16790
16910
  return false;
16791
16911
  }
16792
- log24.info("webhook.send", { event: payload.event, url: targetLabel });
16912
+ log25.info("webhook.send", { event: payload.event, url: targetLabel });
16793
16913
  const maxRetries = 3;
16794
16914
  const delays = [1e3, 4e3, 16e3];
16795
16915
  let lastStatusClass = "network";
@@ -16798,13 +16918,13 @@ var Notifier = class {
16798
16918
  try {
16799
16919
  const response = await deliverWebhook(targetCheck.target, body, signingSecret);
16800
16920
  if (response.status >= 200 && response.status < 300) {
16801
- log24.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
16921
+ log25.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
16802
16922
  this.logDelivery(projectId, notificationId, payload.event, "sent", null);
16803
16923
  trackWebhookDelivery({ url, event: payload.event, attempts: attempt + 1, durationBucket: elapsed(), statusClass: "2xx" });
16804
16924
  return true;
16805
16925
  }
16806
16926
  const errorDetail = response.error ?? `HTTP ${response.status}`;
16807
- log24.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
16927
+ log25.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
16808
16928
  lastStatusClass = response.status === 0 && response.timedOut ? "timeout" : statusClassOf(response.status);
16809
16929
  lastFailure = { reasonCode: webhookResponseReason(response) ?? "UNKNOWN" };
16810
16930
  if (attempt === maxRetries - 1) {
@@ -16816,7 +16936,7 @@ var Notifier = class {
16816
16936
  lastFailure = outcomeFailure(err);
16817
16937
  if (attempt === maxRetries - 1) {
16818
16938
  this.logDelivery(projectId, notificationId, payload.event, "failed", errorDetail);
16819
- log24.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
16939
+ log25.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
16820
16940
  }
16821
16941
  }
16822
16942
  if (attempt < maxRetries - 1) {
@@ -16849,7 +16969,7 @@ var Notifier = class {
16849
16969
 
16850
16970
  // src/run-coordinator.ts
16851
16971
  import { eq as eq29 } from "drizzle-orm";
16852
- var log25 = createLogger("RunCoordinator");
16972
+ var log26 = createLogger("RunCoordinator");
16853
16973
  function reportInsightsGenerated(runTrigger, outcome) {
16854
16974
  trackFeatureCompleted({
16855
16975
  feature: "insights",
@@ -16885,19 +17005,19 @@ var RunCoordinator = class {
16885
17005
  const runRow = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
16886
17006
  const kind = runRow?.kind ?? RunKinds["answer-visibility"];
16887
17007
  if (runRow?.trigger === RunTriggers.probe) {
16888
- log25.info("probe.skip-side-effects", { runId, projectId, kind });
17008
+ log26.info("probe.skip-side-effects", { runId, projectId, kind });
16889
17009
  return;
16890
17010
  }
16891
17011
  if (kind === RunKinds["answer-visibility"] && (runRow?.status === RunStatuses.completed || runRow?.status === RunStatuses.partial) && this.onAnswersRecorded) {
16892
17012
  try {
16893
17013
  await this.onAnswersRecorded(runId, projectId);
16894
17014
  } catch (err) {
16895
- log25.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
17015
+ log26.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
16896
17016
  }
16897
17017
  }
16898
17018
  const completeness = measurementRunCompleteness(this.db, runId);
16899
17019
  if (completeness.planned && !completeness.complete) {
16900
- log25.info("measurement.incomplete-skip-derived", {
17020
+ log26.info("measurement.incomplete-skip-derived", {
16901
17021
  runId,
16902
17022
  projectId,
16903
17023
  executed: completeness.executed,
@@ -16906,7 +17026,7 @@ var RunCoordinator = class {
16906
17026
  try {
16907
17027
  await this.notifier.onRunCompleted(runId, projectId);
16908
17028
  } catch (err) {
16909
- log25.error("notifier.failed", { runId, error: describeError(err) });
17029
+ log26.error("notifier.failed", { runId, error: describeError(err) });
16910
17030
  }
16911
17031
  return;
16912
17032
  }
@@ -16914,7 +17034,7 @@ var RunCoordinator = class {
16914
17034
  try {
16915
17035
  await this.onSentimentCompleted(runId, projectId);
16916
17036
  } catch {
16917
- log25.error("sentiment.wakeup-failed", { runId, projectId });
17037
+ log26.error("sentiment.wakeup-failed", { runId, projectId });
16918
17038
  }
16919
17039
  }
16920
17040
  let insightCount = 0;
@@ -16934,12 +17054,12 @@ var RunCoordinator = class {
16934
17054
  try {
16935
17055
  await this.onInsightsGenerated(runId, projectId, result);
16936
17056
  } catch (err) {
16937
- log25.error("insight-webhook.failed", { runId, error: describeError(err) });
17057
+ log26.error("insight-webhook.failed", { runId, error: describeError(err) });
16938
17058
  }
16939
17059
  }
16940
17060
  }
16941
17061
  } catch (err) {
16942
- log25.error("intelligence.failed", { runId, error: describeError(err) });
17062
+ log26.error("intelligence.failed", { runId, error: describeError(err) });
16943
17063
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
16944
17064
  }
16945
17065
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
@@ -16957,30 +17077,30 @@ var RunCoordinator = class {
16957
17077
  try {
16958
17078
  await this.onInsightsGenerated(runId, projectId, analysisResultFromInsights(gbpInsights));
16959
17079
  } catch (err) {
16960
- log25.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
17080
+ log26.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
16961
17081
  }
16962
17082
  }
16963
17083
  } catch (err) {
16964
- log25.error("gbp-intelligence.failed", { runId, error: describeError(err) });
17084
+ log26.error("gbp-intelligence.failed", { runId, error: describeError(err) });
16965
17085
  insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
16966
17086
  }
16967
17087
  reportInsightsGenerated(runRow?.trigger, insightsOutcome);
16968
17088
  try {
16969
17089
  await this.notifier.dispatchReviewAlerts(projectId);
16970
17090
  } catch (err) {
16971
- log25.error("review-webhook.failed", { runId, error: describeError(err) });
17091
+ log26.error("review-webhook.failed", { runId, error: describeError(err) });
16972
17092
  }
16973
17093
  }
16974
17094
  try {
16975
17095
  await (opts ? this.notifier.onRunCompleted(runId, projectId, opts) : this.notifier.onRunCompleted(runId, projectId));
16976
17096
  } catch (err) {
16977
- log25.error("notifier.failed", { runId, error: describeError(err) });
17097
+ log26.error("notifier.failed", { runId, error: describeError(err) });
16978
17098
  }
16979
17099
  if (kind === RunKinds["site-audit"]) {
16980
17100
  try {
16981
17101
  await this.notifier.onSiteAuditCompleted(runId, projectId);
16982
17102
  } catch (err) {
16983
- log25.error("site-health-webhook.failed", { runId, error: describeError(err) });
17103
+ log26.error("site-health-webhook.failed", { runId, error: describeError(err) });
16984
17104
  }
16985
17105
  }
16986
17106
  if (this.onAeroEvent) {
@@ -16994,7 +17114,7 @@ var RunCoordinator = class {
16994
17114
  };
16995
17115
  await this.onAeroEvent(ctx);
16996
17116
  } catch (err) {
16997
- log25.error("aero.failed", { runId, error: describeError(err) });
17117
+ log26.error("aero.failed", { runId, error: describeError(err) });
16998
17118
  }
16999
17119
  }
17000
17120
  }
@@ -17053,12 +17173,12 @@ function analysisResultFromInsights(insights2) {
17053
17173
 
17054
17174
  // src/agent/session-registry.ts
17055
17175
  import crypto27 from "crypto";
17056
- import { eq as eq32 } from "drizzle-orm";
17176
+ import { and as and27, eq as eq32, gt as gt4, lte as lte3 } from "drizzle-orm";
17057
17177
 
17058
17178
  // src/agent/remote-mcp.ts
17059
17179
  import { Type } from "@earendil-works/pi-ai";
17060
17180
  import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
17061
- var log26 = createLogger("RemoteMcp");
17181
+ var log27 = createLogger("RemoteMcp");
17062
17182
  var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([]);
17063
17183
  async function connectStreamableHttp(server) {
17064
17184
  const transport = new StreamableHTTPClientTransport(new URL(server.url), {
@@ -17126,7 +17246,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17126
17246
  try {
17127
17247
  client = await connect(server);
17128
17248
  } catch (err) {
17129
- log26.error("external-mcp.connect-failed", {
17249
+ log27.error("external-mcp.connect-failed", {
17130
17250
  label,
17131
17251
  error: describeError(err)
17132
17252
  });
@@ -17136,7 +17256,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17136
17256
  try {
17137
17257
  listed = await client.listTools();
17138
17258
  } catch (err) {
17139
- log26.error("external-mcp.list-failed", {
17259
+ log27.error("external-mcp.list-failed", {
17140
17260
  label,
17141
17261
  error: describeError(err)
17142
17262
  });
@@ -17147,7 +17267,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
17147
17267
  if (!isReadOnly(tool)) continue;
17148
17268
  tools.push(adaptRemoteTool(client, tool));
17149
17269
  }
17150
- log26.info("external-mcp.loaded", {
17270
+ log27.info("external-mcp.loaded", {
17151
17271
  label,
17152
17272
  discovered: listed.tools.length,
17153
17273
  adopted: tools.length
@@ -17259,6 +17379,7 @@ function writeCompactionNote(db, args) {
17259
17379
  }
17260
17380
 
17261
17381
  // src/agent/turn-telemetry.ts
17382
+ var log28 = createLogger("AeroTurn");
17262
17383
  var PROVIDER_ERROR_REASONS = {
17263
17384
  PROVIDER_AUTH: "INVALID_CREDENTIALS",
17264
17385
  PROVIDER_BILLING: "BILLING",
@@ -17308,10 +17429,27 @@ function trackAeroTurn(agent, turn) {
17308
17429
  }
17309
17430
  }
17310
17431
  const modelProvider = agentProviderSlug(model.provider);
17432
+ const operationId = aeroTurnOperationId(agent);
17433
+ const httpStatus = agent.state.errorMessage ? extractProviderHttpStatus(agent.state.errorMessage) : void 0;
17434
+ const diagnostics = buildOutcomeDiagnostics(turn.error ?? (httpStatus ? { status: httpStatus } : void 0), {
17435
+ phase: turn.phase ?? (turn.error === void 0 && agent.state.errorMessage ? OutcomePhases["provider-request"] : OutcomePhases.unknown)
17436
+ });
17437
+ const outcome = turnOutcome(turn.error === void 0 ? status.reason : "error", turn.error, agent.state.errorMessage);
17438
+ log28.info("completed", {
17439
+ operationId,
17440
+ projectId: turn.projectId,
17441
+ provider: modelProvider,
17442
+ httpStatus: diagnostics.httpStatus,
17443
+ errorCode: outcome.reasonCode,
17444
+ msg: `Aero ${outcome.status}; phase ${diagnostics.phase}.`
17445
+ });
17311
17446
  trackFeatureCompleted({
17312
17447
  feature: FeatureNames.aero,
17313
17448
  operation: "turn",
17314
- ...turnOutcome(turn.error === void 0 ? status.reason : "error", turn.error, agent.state.errorMessage),
17449
+ operationKind: OutcomeOperationKinds["agent-turn"],
17450
+ operationId,
17451
+ diagnostics,
17452
+ ...outcome,
17315
17453
  trigger: turn.trigger,
17316
17454
  ...outcomeAttribution(turn.attribution),
17317
17455
  durationBucket: bucketDuration(status.durationMs),
@@ -17522,7 +17660,7 @@ async function compactMessages(args) {
17522
17660
  }
17523
17661
 
17524
17662
  // src/agent/session-registry.ts
17525
- var log27 = createLogger("SessionRegistry");
17663
+ var log29 = createLogger("SessionRegistry");
17526
17664
  var MAX_HYDRATE_NOTES = 20;
17527
17665
  var PROVIDER_ACCOUNT_COOLDOWN_MS = 24 * 60 * 60 * 1e3;
17528
17666
  var MAX_HYDRATE_BYTES = 32 * 1024;
@@ -17541,8 +17679,8 @@ function withoutPersistedToolDetails(messages) {
17541
17679
  var SessionRegistry = class {
17542
17680
  live = /* @__PURE__ */ new Map();
17543
17681
  pending = /* @__PURE__ */ new Map();
17544
- /** Shared across projects, scoped to the provider and a digest of its credential. */
17545
- providerCooldowns = /* @__PURE__ */ new Map();
17682
+ /** Keep suppressing wakes in this process if the durable pause cannot be written. */
17683
+ providerCooldownFallbacks = /* @__PURE__ */ new Map();
17546
17684
  /** Last tool scope used on the live Agent for a project. Read in getOrCreate to know when to swap. */
17547
17685
  scopes = /* @__PURE__ */ new Map();
17548
17686
  /** Last profile used on the live Agent for a project. Paired with scopes when rebuilding tools. */
@@ -17584,7 +17722,7 @@ var SessionRegistry = class {
17584
17722
  if (!this.externalToolsPromise) {
17585
17723
  this.externalToolsPromise = loadExternalMcpTools(this.opts.config.externalMcpServers).catch(
17586
17724
  (err) => {
17587
- log27.error("external-mcp.load-failed", {
17725
+ log29.error("external-mcp.load-failed", {
17588
17726
  error: describeError(err)
17589
17727
  });
17590
17728
  return [];
@@ -17616,6 +17754,25 @@ var SessionRegistry = class {
17616
17754
  getConfig() {
17617
17755
  return this.opts.config;
17618
17756
  }
17757
+ /** Stored account readiness for the active credentials; this never calls a provider. */
17758
+ providerOptions() {
17759
+ const response = buildAgentProvidersResponse(this.opts.config, { models: true });
17760
+ return {
17761
+ ...response,
17762
+ providers: response.providers.map((provider) => {
17763
+ const vendor = getAgentProvider(provider.id).piAiProvider;
17764
+ const cooldown = this.providerCooldown(this.providerAccountKey(vendor, resolveApiKeyFor(vendor, this.opts.config)));
17765
+ return {
17766
+ ...provider,
17767
+ backgroundPause: cooldown === null ? void 0 : cooldown ? {
17768
+ reason: cooldown.reason,
17769
+ retryAt: new Date(cooldown.retryAt).toISOString(),
17770
+ recovery: this.providerRecovery(cooldown.reason)
17771
+ } : null
17772
+ };
17773
+ })
17774
+ };
17775
+ }
17619
17776
  /**
17620
17777
  * Returns the live Agent for a project, hydrating from DB or creating
17621
17778
  * fresh. Applies caller preferences on fresh/hydrated construction. Does
@@ -17860,13 +18017,13 @@ ${lines.join("\n")}
17860
18017
  agent.state.messages = result.messages;
17861
18018
  setAeroSystemPrompt(agent, this.buildHydratedSystemPrompt(projectId, row.systemPrompt));
17862
18019
  this.save(projectName);
17863
- log27.info("compaction.completed", {
18020
+ log29.info("compaction.completed", {
17864
18021
  projectName,
17865
18022
  removedCount: result.removedCount,
17866
18023
  summaryBytes: Buffer.byteLength(result.summary, "utf8")
17867
18024
  });
17868
18025
  } catch (err) {
17869
- log27.error("compaction.failed", {
18026
+ log29.error("compaction.failed", {
17870
18027
  projectName,
17871
18028
  error: describeError(err)
17872
18029
  });
@@ -18038,16 +18195,17 @@ ${lines.join("\n")}
18038
18195
  if (this.providerCoolingDown(projectName)) return;
18039
18196
  const msgs = this.consumePending(projectName);
18040
18197
  if (msgs.length === 0) return;
18198
+ const projectId = this.projectIds.get(projectName) ?? this.tryResolveProjectId(projectName);
18041
18199
  await agent.prompt(msgs);
18042
18200
  try {
18043
18201
  this.save(projectName);
18044
18202
  } catch (err) {
18045
- trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, error: err });
18203
+ trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, error: err, phase: OutcomePhases.persistence, projectId });
18046
18204
  throw err;
18047
18205
  }
18048
- trackAeroTurn(agent, { trigger: OutcomeTriggers.agent });
18206
+ trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, projectId });
18049
18207
  } catch (err) {
18050
- log27.error("drain.failed", {
18208
+ log29.error("drain.failed", {
18051
18209
  projectName,
18052
18210
  error: describeError(err)
18053
18211
  });
@@ -18138,27 +18296,59 @@ ${lines.join("\n")}
18138
18296
  lastRequest = void 0;
18139
18297
  const apiKey = await resolveApiKey?.(provider);
18140
18298
  const accountKey = this.providerAccountKey(provider, apiKey);
18141
- lastRequest = { accountKey, cooldown: this.providerCooldowns.get(accountKey) };
18299
+ const { fallback, durable } = this.providerCooldownState(accountKey);
18300
+ lastRequest = {
18301
+ accountKey,
18302
+ fallbackFailureId: fallback?.failureId,
18303
+ durableFailureId: durable?.failureId,
18304
+ durableKnown: durable !== null
18305
+ };
18142
18306
  return apiKey;
18143
18307
  };
18144
18308
  agent.subscribe((event) => {
18145
18309
  if (event.type === "agent_start") lastRequest = void 0;
18146
18310
  if (event.type !== "agent_end") return;
18147
18311
  if (lastRequest) {
18148
- const { accountKey, cooldown } = lastRequest;
18312
+ const { accountKey, fallbackFailureId, durableFailureId, durableKnown } = lastRequest;
18149
18313
  const reason = classifyProviderErrorMessage(agent.state.errorMessage ?? "");
18150
- if (isProviderAccountFailure(reason)) {
18314
+ if (reason === ProviderErrorCodes.PROVIDER_AUTH || reason === ProviderErrorCodes.PROVIDER_BILLING) {
18151
18315
  const retryAt = Date.now() + PROVIDER_ACCOUNT_COOLDOWN_MS;
18152
- this.providerCooldowns.set(accountKey, { retryAt });
18153
- log27.warn("provider.background-paused", {
18316
+ const cooldown = { accountKey, failureId: crypto27.randomUUID(), retryAt, reason };
18317
+ let persisted = false;
18318
+ try {
18319
+ this.opts.db.transaction((tx) => {
18320
+ tx.delete(agentProviderCooldowns).where(lte3(agentProviderCooldowns.retryAt, Date.now())).run();
18321
+ tx.insert(agentProviderCooldowns).values(cooldown).onConflictDoUpdate({
18322
+ target: agentProviderCooldowns.accountKey,
18323
+ set: cooldown
18324
+ }).run();
18325
+ });
18326
+ this.providerCooldownFallbacks.delete(accountKey);
18327
+ persisted = true;
18328
+ } catch (error) {
18329
+ this.providerCooldownFallbacks.set(accountKey, cooldown);
18330
+ log29.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
18331
+ }
18332
+ log29.warn("provider.background-paused", {
18154
18333
  projectName,
18155
18334
  provider: agent.state.model.provider,
18156
18335
  reason,
18157
18336
  retryAt: new Date(retryAt).toISOString(),
18158
- recovery: "Fix the provider credentials or billing, then send Aero a prompt to retry now."
18337
+ recovery: this.providerRecovery(reason),
18338
+ msg: persisted ? "Automatic Aero work paused; the pause is saved for server restarts." : "Automatic Aero work paused in this process; the pause could not be saved for server restarts."
18159
18339
  });
18160
- } else if (aeroTurnStatus(agent)?.reason === "completed" && this.providerCooldowns.get(accountKey) === cooldown) {
18161
- this.providerCooldowns.delete(accountKey);
18340
+ } else if (aeroTurnStatus(agent)?.reason === "completed" && durableKnown && (fallbackFailureId || durableFailureId) && this.providerCooldownFallbacks.get(accountKey)?.failureId === fallbackFailureId) {
18341
+ try {
18342
+ if (durableFailureId) {
18343
+ this.opts.db.delete(agentProviderCooldowns).where(and27(
18344
+ eq32(agentProviderCooldowns.accountKey, accountKey),
18345
+ eq32(agentProviderCooldowns.failureId, durableFailureId)
18346
+ )).run();
18347
+ }
18348
+ this.providerCooldownFallbacks.delete(accountKey);
18349
+ } catch (error) {
18350
+ log29.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
18351
+ }
18162
18352
  }
18163
18353
  }
18164
18354
  if ((this.pending.get(projectName) ?? []).length === 0) return;
@@ -18171,13 +18361,34 @@ ${lines.join("\n")}
18171
18361
  return crypto27.createHash("sha256").update(JSON.stringify([vendor, apiKey ?? ""])).digest("hex");
18172
18362
  }
18173
18363
  providerCoolingDown(projectName) {
18174
- for (const [key, cooldown] of this.providerCooldowns) {
18175
- if (cooldown.retryAt <= Date.now()) this.providerCooldowns.delete(key);
18176
- }
18177
18364
  const provider = this.turnProvider(projectName);
18178
18365
  if (provider === void 0) return false;
18179
18366
  const vendor = getAgentProvider(provider).piAiProvider;
18180
- return this.providerCooldowns.has(this.providerAccountKey(vendor, resolveApiKeyFor(vendor, this.opts.config)));
18367
+ return !!this.providerCooldown(this.providerAccountKey(vendor, resolveApiKeyFor(vendor, this.opts.config)));
18368
+ }
18369
+ providerCooldown(accountKey) {
18370
+ const { fallback, durable } = this.providerCooldownState(accountKey);
18371
+ return fallback ?? durable;
18372
+ }
18373
+ providerCooldownState(accountKey) {
18374
+ for (const [key, cooldown] of this.providerCooldownFallbacks) {
18375
+ if (cooldown.retryAt <= Date.now()) this.providerCooldownFallbacks.delete(key);
18376
+ }
18377
+ const fallback = this.providerCooldownFallbacks.get(accountKey);
18378
+ try {
18379
+ const durable = this.opts.db.select().from(agentProviderCooldowns).where(and27(
18380
+ eq32(agentProviderCooldowns.accountKey, accountKey),
18381
+ gt4(agentProviderCooldowns.retryAt, Date.now())
18382
+ )).get();
18383
+ return { fallback, durable };
18384
+ } catch (error) {
18385
+ log29.warn("provider.background-pause.read-failed", { error: describeError(error) });
18386
+ return { fallback, durable: null };
18387
+ }
18388
+ }
18389
+ providerRecovery(reason) {
18390
+ const action = reason === ProviderErrorCodes.PROVIDER_BILLING ? "Restore credit or billing access in the provider account." : "Repair the provider key or account access; run canonry settings reload-providers if you changed config.yaml.";
18391
+ return `${action} Then send Aero a prompt to retry now. Automatic work can resume after the pause expires.`;
18181
18392
  }
18182
18393
  resolveProjectId(projectName) {
18183
18394
  const id = this.tryResolveProjectId(projectName);
@@ -18224,7 +18435,7 @@ ${lines.join("\n")}
18224
18435
 
18225
18436
  // src/agent/viewer-sessions.ts
18226
18437
  import crypto28 from "crypto";
18227
- import { and as and27, eq as eq33, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
18438
+ import { and as and28, eq as eq33, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
18228
18439
 
18229
18440
  // src/agent/chatgpt-plan.ts
18230
18441
  import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
@@ -18613,7 +18824,7 @@ var ViewerAeroSessions = class {
18613
18824
  */
18614
18825
  revokeOrphanedKeys() {
18615
18826
  try {
18616
- this.opts.db.delete(apiKeys).where(and27(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
18827
+ this.opts.db.delete(apiKeys).where(and28(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
18617
18828
  } catch {
18618
18829
  }
18619
18830
  }
@@ -18630,7 +18841,7 @@ var ViewerAeroSessions = class {
18630
18841
  // src/mcp-http.ts
18631
18842
  import crypto29 from "crypto";
18632
18843
  import { isIP } from "net";
18633
- import { and as and28, eq as eq34, isNull as isNull6 } from "drizzle-orm";
18844
+ import { and as and29, eq as eq34, isNull as isNull6 } from "drizzle-orm";
18634
18845
  import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node";
18635
18846
  import { McpServer, createMcpHandler, isInitializeRequest, isLegacyRequest } from "@modelcontextprotocol/server";
18636
18847
  var SESSION_IDLE_MS = 10 * 60 * 1e3;
@@ -18737,7 +18948,7 @@ function registerMcpHttpRoutes(scope, opts) {
18737
18948
  withoutLockWait(() => {
18738
18949
  opts.db.transaction((tx) => {
18739
18950
  tx.delete(dashboardSessions).where(eq34(dashboardSessions.apiKeyId, id)).run();
18740
- tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and28(eq34(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
18951
+ tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and29(eq34(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
18741
18952
  });
18742
18953
  if (remove) {
18743
18954
  try {
@@ -19171,17 +19382,20 @@ async function streamAgentTurn(reply, agent, turn) {
19171
19382
  });
19172
19383
  let failed = false;
19173
19384
  let failure2;
19385
+ let failurePhase;
19174
19386
  try {
19175
19387
  await agent.prompt(turn.batch);
19176
19388
  await agent.waitForIdle();
19177
19389
  } catch (err) {
19178
19390
  failed = true;
19179
19391
  failure2 = err;
19392
+ failurePhase = OutcomePhases.unknown;
19180
19393
  write({ type: "error", message: describeError(err) });
19181
19394
  } finally {
19182
19395
  try {
19183
19396
  turn.save();
19184
19397
  } catch (err) {
19398
+ if (!failed) failurePhase = OutcomePhases.persistence;
19185
19399
  failed = true;
19186
19400
  failure2 ??= err;
19187
19401
  write({ type: "error", message: describeError(err) });
@@ -19195,7 +19409,7 @@ async function streamAgentTurn(reply, agent, turn) {
19195
19409
  if (!reply.raw.writableEnded) {
19196
19410
  reply.raw.end();
19197
19411
  }
19198
- trackAeroTurn(agent, { trigger: OutcomeTriggers.manual, attribution: turn.attribution, status: reported, error: failure2 });
19412
+ trackAeroTurn(agent, { trigger: OutcomeTriggers.manual, attribution: turn.attribution, status: reported, error: failure2, phase: failurePhase, projectId: turn.projectId });
19199
19413
  }
19200
19414
  }
19201
19415
  async function streamViewerTurn(opts, project, viewerId, body, reply, attribution) {
@@ -19223,6 +19437,7 @@ async function streamViewerTurn(opts, project, viewerId, body, reply, attributio
19223
19437
  }
19224
19438
  try {
19225
19439
  await streamAgentTurn(reply, turn.agent, {
19440
+ projectId: project.id,
19226
19441
  batch: promptMessage(body.prompt, body.context),
19227
19442
  save: () => {
19228
19443
  },
@@ -19269,7 +19484,7 @@ function registerAgentRoutes(app, opts) {
19269
19484
  async (request) => {
19270
19485
  requireInstanceAdministrator(request);
19271
19486
  resolveProject(opts.db, request.params.name);
19272
- return buildAgentProvidersResponse(opts.sessionRegistry.getConfig(), { models: true });
19487
+ return opts.sessionRegistry.providerOptions();
19273
19488
  }
19274
19489
  );
19275
19490
  app.delete(
@@ -19347,6 +19562,7 @@ function registerAgentRoutes(app, opts) {
19347
19562
  const pending = opts.sessionRegistry.consumePending(project.name);
19348
19563
  const userMessage = promptMessage(promptText, body.context);
19349
19564
  await streamAgentTurn(reply, agent, {
19565
+ projectId: project.id,
19350
19566
  batch: pending.length > 0 ? [...pending, userMessage] : userMessage,
19351
19567
  save: () => opts.sessionRegistry.save(project.name),
19352
19568
  detach: () => reply.raw.off("close", onClose),
@@ -19724,7 +19940,7 @@ function stripHtml(html) {
19724
19940
  }
19725
19941
 
19726
19942
  // src/snapshot-service.ts
19727
- var log28 = createLogger("Snapshot");
19943
+ var log30 = createLogger("Snapshot");
19728
19944
  var ANALYSIS_PROVIDER_PRIORITY = ["openai", "claude", "gemini", "perplexity", "muse", "local"];
19729
19945
  var SNAPSHOT_QUERY_COUNT = 6;
19730
19946
  var SnapshotService = class {
@@ -19826,7 +20042,7 @@ var SnapshotService = class {
19826
20042
  return mapAuditReport(report);
19827
20043
  } catch (err) {
19828
20044
  const message = describeError(err);
19829
- log28.warn("audit.failed", { homepageUrl, error: message });
20045
+ log30.warn("audit.failed", { homepageUrl, error: message });
19830
20046
  return {
19831
20047
  url: homepageUrl,
19832
20048
  finalUrl: homepageUrl,
@@ -19855,7 +20071,7 @@ var SnapshotService = class {
19855
20071
  queries: parsedQueries
19856
20072
  };
19857
20073
  } catch (err) {
19858
- log28.warn("profile.generation-failed", {
20074
+ log30.warn("profile.generation-failed", {
19859
20075
  domain: ctx.domain,
19860
20076
  provider: ctx.analysisProvider.adapter.name,
19861
20077
  error: describeError(err)
@@ -20005,7 +20221,7 @@ var SnapshotService = class {
20005
20221
  recommendedActions: uniqueStrings2(parsed.recommendedActions ?? []).slice(0, 4)
20006
20222
  };
20007
20223
  } catch (err) {
20008
- log28.warn("response.analysis-failed", {
20224
+ log30.warn("response.analysis-failed", {
20009
20225
  provider: ctx.analysisProvider.adapter.name,
20010
20226
  error: describeError(err)
20011
20227
  });
@@ -20275,7 +20491,7 @@ function clipText(value, length) {
20275
20491
  }
20276
20492
 
20277
20493
  // src/research-runner.ts
20278
- import { and as and29, eq as eq36, inArray as inArray13, sql as sql13 } from "drizzle-orm";
20494
+ import { and as and30, eq as eq36, inArray as inArray13, sql as sql13 } from "drizzle-orm";
20279
20495
  var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
20280
20496
  function finalResearchRunStatus(completed, failed, waiting) {
20281
20497
  if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
@@ -20283,13 +20499,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
20283
20499
  return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
20284
20500
  }
20285
20501
  async function executeResearchRun(db, registry, runId, projectId, options = {}) {
20286
- const run = db.select().from(researchRuns).where(and29(eq36(researchRuns.id, runId), eq36(researchRuns.projectId, projectId))).get();
20502
+ const run = db.select().from(researchRuns).where(and30(eq36(researchRuns.id, runId), eq36(researchRuns.projectId, projectId))).get();
20287
20503
  if (!run || run.status !== ResearchRunStatuses.queued) return;
20288
20504
  const project = db.select().from(projects).where(eq36(projects.id, projectId)).get();
20289
20505
  if (!project) return;
20290
20506
  const provider = registry.get(run.provider);
20291
20507
  const now = (/* @__PURE__ */ new Date()).toISOString();
20292
- const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and29(eq36(researchRuns.id, runId), eq36(researchRuns.status, ResearchRunStatuses.queued))).run();
20508
+ const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and30(eq36(researchRuns.id, runId), eq36(researchRuns.status, ResearchRunStatuses.queued))).run();
20293
20509
  if (claim.changes !== 1) return;
20294
20510
  const elapsed = startOutcomeTimer();
20295
20511
  const requested = currentOutcomeOrigin();
@@ -20334,7 +20550,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20334
20550
  await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
20335
20551
  try {
20336
20552
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
20337
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and29(eq36(researchRunQueries.id, row.id), eq36(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
20553
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and30(eq36(researchRunQueries.id, row.id), eq36(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
20338
20554
  const raw = await gate.run(async () => {
20339
20555
  dispatched++;
20340
20556
  return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
@@ -20365,7 +20581,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
20365
20581
  rawResponse: raw.rawResponse,
20366
20582
  answerEvidence: raw.evidence ?? null,
20367
20583
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
20368
- }).where(and29(eq36(researchRunQueries.id, row.id), eq36(researchRunQueries.status, ResearchQueryStatuses.running))).run();
20584
+ }).where(and30(eq36(researchRunQueries.id, row.id), eq36(researchRunQueries.status, ResearchQueryStatuses.running))).run();
20369
20585
  if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
20370
20586
  } catch (error) {
20371
20587
  if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
@@ -20420,7 +20636,7 @@ function incrementResearchProgress(db, runId, column) {
20420
20636
  }
20421
20637
  function markResearchQueryFailed(db, runId, queryId, error) {
20422
20638
  const message = describeError(error);
20423
- const unfinished = and29(eq36(researchRunQueries.id, queryId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses));
20639
+ const unfinished = and30(eq36(researchRunQueries.id, queryId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses));
20424
20640
  if (error instanceof IncompleteAnswerError && error.resumable) {
20425
20641
  db.update(researchRunQueries).set({
20426
20642
  status: ResearchQueryStatuses["waiting-upstream"],
@@ -20436,7 +20652,7 @@ function markResearchQueryFailed(db, runId, queryId, error) {
20436
20652
  if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
20437
20653
  }
20438
20654
  function markUnfinishedResearchQueriesFailed(db, runId, error) {
20439
- db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and29(eq36(researchRunQueries.researchRunId, runId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
20655
+ db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and30(eq36(researchRunQueries.researchRunId, runId), inArray13(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
20440
20656
  }
20441
20657
  function finalizeResearchRun(db, runId, fatalError) {
20442
20658
  const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq36(researchRunQueries.researchRunId, runId)).all();
@@ -20456,7 +20672,7 @@ function finalizeResearchRun(db, runId, fatalError) {
20456
20672
  }
20457
20673
 
20458
20674
  // src/google-marketing-sync.ts
20459
- import { and as and30, eq as eq37, isNull as isNull7, sql as sql14 } from "drizzle-orm";
20675
+ import { and as and31, eq as eq37, isNull as isNull7, sql as sql14 } from "drizzle-orm";
20460
20676
  var RUNTIME_FAILURE_REASONS = {
20461
20677
  INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
20462
20678
  NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
@@ -20493,7 +20709,7 @@ function assertSnapshotContext(metadata, expected) {
20493
20709
  }
20494
20710
  }
20495
20711
  function requireSyncRun(db, runId, projectId, kind) {
20496
- const run = db.select().from(runs).where(and30(
20712
+ const run = db.select().from(runs).where(and31(
20497
20713
  eq37(runs.id, runId),
20498
20714
  eq37(runs.projectId, projectId),
20499
20715
  eq37(runs.kind, kind)
@@ -20512,7 +20728,7 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
20512
20728
  status: RunStatuses.failed,
20513
20729
  error: serializeRunError({ message: safeErrorMessage(error) }),
20514
20730
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
20515
- }).where(and30(
20731
+ }).where(and31(
20516
20732
  eq37(runs.id, runId),
20517
20733
  eq37(runs.projectId, projectId),
20518
20734
  eq37(runs.kind, kind),
@@ -20520,7 +20736,7 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
20520
20736
  )).run();
20521
20737
  }
20522
20738
  function claimSyncRun(db, runId, projectId, kind, startedAt) {
20523
- const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and30(
20739
+ const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and31(
20524
20740
  eq37(runs.id, runId),
20525
20741
  eq37(runs.projectId, projectId),
20526
20742
  eq37(runs.kind, kind),
@@ -20588,7 +20804,7 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
20588
20804
  status: RunStatuses.completed,
20589
20805
  finishedAt,
20590
20806
  error: null
20591
- }).where(and30(
20807
+ }).where(and31(
20592
20808
  eq37(runs.id, runId),
20593
20809
  eq37(runs.projectId, projectId),
20594
20810
  eq37(runs.kind, RunKinds["google-ads-sync"]),
@@ -20612,7 +20828,7 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
20612
20828
  lastMetricsSnapshotAt: result.metrics?.metadata.capturedAt ?? connection.lastMetricsSnapshotAt,
20613
20829
  lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
20614
20830
  updatedAt: finishedAt
20615
- }).where(and30(
20831
+ }).where(and31(
20616
20832
  eq37(googleAdsConnections.id, connection.id),
20617
20833
  eq37(googleAdsConnections.projectId, projectId),
20618
20834
  eq37(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
@@ -20697,7 +20913,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20697
20913
  status: RunStatuses.completed,
20698
20914
  finishedAt,
20699
20915
  error: null
20700
- }).where(and30(
20916
+ }).where(and31(
20701
20917
  eq37(runs.id, runId),
20702
20918
  eq37(runs.projectId, projectId),
20703
20919
  eq37(runs.kind, RunKinds["gtm-sync"]),
@@ -20722,7 +20938,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20722
20938
  lastSnapshotAt: snapshot.metadata.capturedAt,
20723
20939
  lastSnapshotId: snapshot.metadata.id,
20724
20940
  updatedAt: finishedAt
20725
- }).where(and30(
20941
+ }).where(and31(
20726
20942
  eq37(gtmConnections.id, connection.id),
20727
20943
  eq37(gtmConnections.projectId, projectId),
20728
20944
  eq37(gtmConnections.selectedAccountId, connection.selectedAccountId),
@@ -20766,7 +20982,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
20766
20982
  // src/server.ts
20767
20983
  var _require = createRequire(import.meta.url);
20768
20984
  var { version: PKG_VERSION } = _require("../package.json");
20769
- var log29 = createLogger("Server");
20985
+ var log31 = createLogger("Server");
20770
20986
  var runtimeStartupByServer = /* @__PURE__ */ new WeakMap();
20771
20987
  function waitForServerRuntimeStartup(app) {
20772
20988
  const startup = runtimeStartupByServer.get(app);
@@ -21018,7 +21234,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
21018
21234
  }
21019
21235
  if (migratedGoogle > 0) {
21020
21236
  persistConfigPatch({ google: config.google });
21021
- log29.info("credentials.migrated", { type: "google", count: migratedGoogle });
21237
+ log31.info("credentials.migrated", { type: "google", count: migratedGoogle });
21022
21238
  }
21023
21239
  let migratedGa4 = 0;
21024
21240
  for (const row of rows.ga4) {
@@ -21036,7 +21252,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
21036
21252
  }
21037
21253
  if (migratedGa4 > 0) {
21038
21254
  persistConfigPatch({ ga4: config.ga4 });
21039
- log29.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
21255
+ log31.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
21040
21256
  }
21041
21257
  }
21042
21258
  function isLoopbackPeerAddress(address) {
@@ -21138,7 +21354,7 @@ function cloneGtmConfig(config) {
21138
21354
  function createGoogleMarketingConfigCredentialStore(input) {
21139
21355
  const persistConfigPatch = input.saveConfigPatch ?? saveConfigPatch;
21140
21356
  const env = input.env ?? process.env;
21141
- const randomUUID2 = input.randomUUID ?? crypto30.randomUUID;
21357
+ const randomUUID3 = input.randomUUID ?? crypto30.randomUUID;
21142
21358
  const snapshot = () => ({
21143
21359
  googleAds: cloneGoogleAdsConfig(input.config.googleAds),
21144
21360
  gtm: cloneGtmConfig(input.config.gtm)
@@ -21186,7 +21402,7 @@ function createGoogleMarketingConfigCredentialStore(input) {
21186
21402
  upsertGoogleAdsConnection(input.config, {
21187
21403
  projectId: project.id,
21188
21404
  projectName: project.name,
21189
- credentialGeneration: randomUUID2(),
21405
+ credentialGeneration: randomUUID3(),
21190
21406
  ...credential.accessToken ? { accessToken: credential.accessToken } : {},
21191
21407
  refreshToken: credential.refreshToken ?? null,
21192
21408
  tokenExpiresAt: credential.expiresAt ?? null,
@@ -21198,7 +21414,7 @@ function createGoogleMarketingConfigCredentialStore(input) {
21198
21414
  upsertGtmConnection(input.config, {
21199
21415
  projectId: project.id,
21200
21416
  projectName: project.name,
21201
- credentialGeneration: randomUUID2(),
21417
+ credentialGeneration: randomUUID3(),
21202
21418
  ...credential.accessToken ? { accessToken: credential.accessToken } : {},
21203
21419
  refreshToken: credential.refreshToken ?? null,
21204
21420
  tokenExpiresAt: credential.expiresAt ?? null,
@@ -21319,17 +21535,17 @@ async function createServer(opts) {
21319
21535
  applyLegacyCredentials(legacyRows, opts.config, persistConfigPatch);
21320
21536
  dropLegacyCredentialColumns(opts.db);
21321
21537
  } catch (err) {
21322
- log29.warn("credentials.migration.failed", {
21538
+ log31.warn("credentials.migration.failed", {
21323
21539
  error: describeError(err)
21324
21540
  });
21325
21541
  }
21326
21542
  }
21327
- log29.info("providers.configured", {
21543
+ log31.info("providers.configured", {
21328
21544
  providers: registeredProviderNames({ providers, cdp: opts.config.cdp })
21329
21545
  });
21330
21546
  registry.replace(configuredProviderEntries(opts.config, API_ADAPTERS, cdpChatgptAdapter));
21331
21547
  for (const name of providersWithUnsupportedBatch(providers, (provider) => adapterMap[provider])) {
21332
- log29.warn("provider.batch.unsupported", {
21548
+ log31.warn("provider.batch.unsupported", {
21333
21549
  provider: name,
21334
21550
  message: `providers.${name}.batch.enabled is true, but the ${name} adapter has no batch API; its sweeps run sync.`
21335
21551
  });
@@ -21376,7 +21592,7 @@ async function createServer(opts) {
21376
21592
  settings: () => resolveChatGptSettings(opts.config)
21377
21593
  });
21378
21594
  if (opts.config.chatgpt && (opts.config.chatgpt.signIn || opts.config.chatgpt.planUsage) && !resolveChatGptSettings(opts.config)) {
21379
- log29.warn("chatgpt.disabled", {
21595
+ log31.warn("chatgpt.disabled", {
21380
21596
  reason: "Sign in with ChatGPT needs chatgpt.clientId and an HTTPS publicUrl; it stays off until both are set."
21381
21597
  });
21382
21598
  }
@@ -22182,13 +22398,13 @@ async function createServer(opts) {
22182
22398
  const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
22183
22399
  opts.db.delete(dashboardSessions).where(or4(
22184
22400
  eq38(dashboardSessions.apiKeyHash, ""),
22185
- and31(
22401
+ and32(
22186
22402
  isNotNull5(dashboardSessions.passwordFingerprint),
22187
22403
  ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
22188
22404
  )
22189
22405
  )).run();
22190
22406
  if (!opts.config.dashboardPasswordHash) {
22191
- const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and31(eq38(auditLog.entityType, "dashboard-password"), eq38(auditLog.action, action))).get()?.at ?? null;
22407
+ const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and32(eq38(auditLog.entityType, "dashboard-password"), eq38(auditLog.action, action))).get()?.at ?? null;
22192
22408
  const createdAt = lastPasswordEventAt("dashboard-password.created");
22193
22409
  const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
22194
22410
  if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
@@ -22202,7 +22418,7 @@ async function createServer(opts) {
22202
22418
  }
22203
22419
  const createSession = (key, passwordBased = false, db = opts.db) => {
22204
22420
  const now = /* @__PURE__ */ new Date();
22205
- db.delete(dashboardSessions).where(lte3(dashboardSessions.expiresAt, now.toISOString())).run();
22421
+ db.delete(dashboardSessions).where(lte4(dashboardSessions.expiresAt, now.toISOString())).run();
22206
22422
  const sessionId = crypto30.randomBytes(32).toString("hex");
22207
22423
  db.insert(dashboardSessions).values({
22208
22424
  tokenHash: hashSessionToken(sessionId),
@@ -22222,7 +22438,7 @@ async function createServer(opts) {
22222
22438
  currentApiKeyHash: apiKeys.keyHash,
22223
22439
  passwordFingerprint: dashboardSessions.passwordFingerprint,
22224
22440
  expiresAt: dashboardSessions.expiresAt
22225
- }).from(dashboardSessions).innerJoin(apiKeys, eq38(apiKeys.id, dashboardSessions.apiKeyId)).where(and31(eq38(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
22441
+ }).from(dashboardSessions).innerJoin(apiKeys, eq38(apiKeys.id, dashboardSessions.apiKeyId)).where(and32(eq38(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
22226
22442
  if (!session) return null;
22227
22443
  const expiresAt = Date.parse(session.expiresAt);
22228
22444
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
@@ -22470,7 +22686,7 @@ async function createServer(opts) {
22470
22686
  const sentimentPoller = createSentimentPoller(
22471
22687
  () => sentimentWorker.tick(),
22472
22688
  () => {
22473
- log29.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
22689
+ log31.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
22474
22690
  }
22475
22691
  );
22476
22692
  const pollSentiment = sentimentPoller.poll;
@@ -22503,7 +22719,7 @@ async function createServer(opts) {
22503
22719
  opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq38(projects.id, projectId)).run();
22504
22720
  if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
22505
22721
  } else if (debt.latestFull === 0) {
22506
- opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and31(eq38(projects.id, projectId), eq38(projects.answerFieldsRecompute, "full"))).run();
22722
+ opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and32(eq38(projects.id, projectId), eq38(projects.answerFieldsRecompute, "full"))).run();
22507
22723
  }
22508
22724
  } catch (err) {
22509
22725
  app.log.error({ err, projectId }, "could not clear the owed answer field recompute");