@canonry/canonry 7.102.0 → 7.104.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/assets/agent-workspace/skills/aero/references/ai-traffic-tracking.md +32 -4
  2. package/assets/agent-workspace/skills/canonry/references/ai-traffic-tracking.md +32 -4
  3. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +20 -2
  4. package/assets/agent-workspace/skills/canonry/references/server-side-traffic.md +51 -15
  5. package/assets/assets/{AccessControls-CpSlWN3W.js → AccessControls-CBkDcxwx.js} +1 -1
  6. package/assets/assets/{AgentSetupPage-0le_Bx7d.js → AgentSetupPage-iGYETW-I.js} +1 -1
  7. package/assets/assets/{AuditHistoryPanel-BQH1dQ4V.js → AuditHistoryPanel-DiFMK7eE.js} +1 -1
  8. package/assets/assets/{BacklinksPage-_ffwmtrl.js → BacklinksPage-Cg9LQLMo.js} +1 -1
  9. package/assets/assets/{ChartPrimitives-6Yq_3ION.js → ChartPrimitives-DYS88Zzt.js} +1 -1
  10. package/assets/assets/{HistoryPage-DUR17GrK.js → HistoryPage-CmI5CX94.js} +1 -1
  11. package/assets/assets/{MeasurementPropertyPage-dutXSW7s.js → MeasurementPropertyPage-DshJzp9b.js} +1 -1
  12. package/assets/assets/{ProjectPage-DA-07-jJ.js → ProjectPage-DwVxUhxM.js} +9 -9
  13. package/assets/assets/{RunsPage-Bs4f0-sW.js → RunsPage-BqvrT8Xm.js} +1 -1
  14. package/assets/assets/{ServerTrafficSection-qMBbUI-0.js → ServerTrafficSection-CtFe7WDd.js} +1 -1
  15. package/assets/assets/{SettingsPage-Bccypqbr.js → SettingsPage-snu8wJ8l.js} +1 -1
  16. package/assets/assets/{ToneBadge-DvK4cIwq.js → ToneBadge-CkTo2T8d.js} +4 -4
  17. package/assets/assets/{TrafficPage-BPojOqd_.js → TrafficPage-BxiiQjwl.js} +1 -1
  18. package/assets/assets/TrafficSourceDetailPage-8BKFz7py.js +1 -0
  19. package/assets/assets/{account-context-evpXzY8L.js → account-context-BlfC71NP.js} +1 -1
  20. package/assets/assets/{agent-trust-copy-CkaSg2FT.js → agent-trust-copy-C_J3OmRg.js} +1 -1
  21. package/assets/assets/{card-01OafAPU.js → card-CeXmlLH2.js} +1 -1
  22. package/assets/assets/{index-StZErOkd.js → index-BKbmkmyo.js} +3 -3
  23. package/assets/assets/{query-client-D6xwAuZW.js → query-client-DWYnC2Lg.js} +1 -1
  24. package/assets/assets/{react-query-CdE7FNH6.js → react-query-CQhkmL4O.js} +1 -1
  25. package/assets/assets/{react-sigma_core.esm.min-DlfcmDYc.js → react-sigma_core.esm.min-YHPB9pkU.js} +1 -1
  26. package/assets/assets/{server-traffic-yEflW4RI.js → server-traffic-ChxoKQ0y.js} +1 -1
  27. package/assets/assets/{service-DfuRVpyN.js → service-u1pn5oyA.js} +1 -1
  28. package/assets/index.html +8 -8
  29. package/dist/{ads-UDJVYKHF.js → ads-ARJJACSH.js} +3 -3
  30. package/dist/{agent-EOB54XNS.js → agent-57EQMSOO.js} +7 -7
  31. package/dist/{agent-ask-5V4LX4VW.js → agent-ask-TF2WTRTO.js} +3 -3
  32. package/dist/{agent-conversations-OAF6RCFP.js → agent-conversations-5GXNREFK.js} +3 -3
  33. package/dist/{agent-journeys-GETB4UGM.js → agent-journeys-6CDPI4TE.js} +3 -3
  34. package/dist/{agent-memory-JXHPH6H5.js → agent-memory-X3FQ4YDE.js} +3 -3
  35. package/dist/{agent-providers-AAUCUOKY.js → agent-providers-32Z3YXO4.js} +3 -3
  36. package/dist/{agent-transcript-WT4QH3ZY.js → agent-transcript-2S64XPF2.js} +3 -3
  37. package/dist/{analytics-JEZWLRTZ.js → analytics-WPCHRXQZ.js} +3 -3
  38. package/dist/{apply-LDIMMO4N.js → apply-3WHRQBQB.js} +3 -3
  39. package/dist/{backfill-JOJHBVGV.js → backfill-QD3I5MYX.js} +10 -10
  40. package/dist/{backlinks-D2O3UM6F.js → backlinks-TRVNCPUB.js} +3 -3
  41. package/dist/{bing-BG7KZZPK.js → bing-F3B76XX5.js} +3 -3
  42. package/dist/{bootstrap-IXVATZLB.js → bootstrap-QOAGLWNN.js} +10 -10
  43. package/dist/{cdp-3AJG7OLP.js → cdp-4I3DNMLG.js} +7 -7
  44. package/dist/{chunk-C2YVADFC.js → chunk-2AECECUY.js} +1 -1
  45. package/dist/{chunk-S7ZOYNW3.js → chunk-2VNQKUCW.js} +2 -2
  46. package/dist/{chunk-N7773GJW.js → chunk-3V5Y2XTA.js} +1 -1
  47. package/dist/{chunk-DP3FE2OW.js → chunk-47QPY6Y3.js} +5 -5
  48. package/dist/{chunk-M25KDHD4.js → chunk-52D6WBCZ.js} +1 -1
  49. package/dist/{chunk-LGTSVS6Q.js → chunk-5FMZGO6R.js} +4 -4
  50. package/dist/{chunk-N4VEG6GB.js → chunk-5UHNDYUH.js} +4 -4
  51. package/dist/{chunk-QK4IICRM.js → chunk-6AW6ONTF.js} +2 -2
  52. package/dist/{chunk-YTR2S4MU.js → chunk-756RPVYB.js} +4 -4
  53. package/dist/{chunk-G4ODBZO7.js → chunk-7UQZCDYK.js} +1 -1
  54. package/dist/{chunk-7JJCFGL2.js → chunk-7VKVGR6X.js} +3 -3
  55. package/dist/{chunk-BG6TVNA6.js → chunk-7XJG2OTB.js} +366 -366
  56. package/dist/{chunk-7I2NJ4BH.js → chunk-BYYP43Q3.js} +128 -1
  57. package/dist/{chunk-AENOUFTF.js → chunk-CCHYRLX4.js} +2 -2
  58. package/dist/{chunk-O5AIKUW3.js → chunk-CJ55MGWI.js} +1 -1
  59. package/dist/{chunk-WNR3YQAD.js → chunk-D76TB5JS.js} +1 -1
  60. package/dist/{chunk-GLKR6C2L.js → chunk-DLZCOJCY.js} +1 -1
  61. package/dist/{chunk-66EXWVMN.js → chunk-FCUUJO3Z.js} +2 -2
  62. package/dist/{chunk-ONHBQYSA.js → chunk-FYRNKI3A.js} +46 -31
  63. package/dist/{chunk-RXWD25P7.js → chunk-HLM3GYK4.js} +1 -1
  64. package/dist/{chunk-4CF5536B.js → chunk-HPFT4IKN.js} +1 -1
  65. package/dist/{chunk-AG6BTE7R.js → chunk-HTGJSXCR.js} +5 -5
  66. package/dist/{chunk-UX6XWC4F.js → chunk-IHY4Q74C.js} +567 -185
  67. package/dist/{chunk-CZOGOHIN.js → chunk-K32GU473.js} +632 -462
  68. package/dist/{chunk-BDLHLE2F.js → chunk-LCZZACLE.js} +3 -3
  69. package/dist/{chunk-NAJ3ZYZ2.js → chunk-MDRAKMCV.js} +3 -3
  70. package/dist/{chunk-VH424YVI.js → chunk-NGGMSNF6.js} +1714 -1714
  71. package/dist/{chunk-ZIKPEZ3K.js → chunk-NI2JFXIS.js} +21 -21
  72. package/dist/{chunk-DRNBMKR5.js → chunk-PU5OA57Z.js} +6 -6
  73. package/dist/{chunk-FHK6M4RK.js → chunk-QRR5ZW22.js} +3 -3
  74. package/dist/{chunk-2YLTELT2.js → chunk-SZ64N26K.js} +1 -1
  75. package/dist/{chunk-EXPBZFN4.js → chunk-TCXITSDO.js} +1 -1
  76. package/dist/{chunk-NJZVDUKD.js → chunk-TFP6UJXW.js} +3 -3
  77. package/dist/{chunk-3TPHFDZN.js → chunk-WQQ4TNIY.js} +2 -2
  78. package/dist/{chunk-NHBXQWE3.js → chunk-WT22Z3I7.js} +63 -4
  79. package/dist/{chunk-IBRABPHA.js → chunk-ZJFLVXDZ.js} +2 -2
  80. package/dist/{citations-GM42U2ZH.js → citations-6CW3G5YP.js} +4 -4
  81. package/dist/{cli-catalog-EMZPMAJP.js → cli-catalog-6B2O2JQE.js} +3 -3
  82. package/dist/{cli-commands-VDMZAETM.js → cli-commands-O46WFSHZ.js} +7 -7
  83. package/dist/cli.js +13 -13
  84. package/dist/{competitor-4ZLKGNQW.js → competitor-D4BVO2KQ.js} +3 -3
  85. package/dist/{content-YJRMT4JW.js → content-H2PGFRWM.js} +3 -3
  86. package/dist/{dashboard-L4EE3C5T.js → dashboard-4KP7KKMY.js} +6 -6
  87. package/dist/{demo-3XDVCUT5.js → demo-NKCOCN6Z.js} +1 -1
  88. package/dist/{demo-server-7ZJWSGE2.js → demo-server-RQB6VRBH.js} +12 -12
  89. package/dist/{discover-SQGUDXSU.js → discover-K4GIXAN5.js} +4 -4
  90. package/dist/{discover-eval-BUNKP6EW.js → discover-eval-L4IF5XFV.js} +3 -3
  91. package/dist/{doctor-HPIGLMRX.js → doctor-OVJTEQCK.js} +3 -3
  92. package/dist/{evidence-JKEM5BYW.js → evidence-MXQK4YYL.js} +3 -3
  93. package/dist/{export-cmd-KTQM455W.js → export-cmd-Z3CWJALI.js} +3 -3
  94. package/dist/{ga-D7ZLTSSA.js → ga-347UNNJP.js} +3 -3
  95. package/dist/{gbp-OWBX2BFK.js → gbp-47MIYIQC.js} +3 -3
  96. package/dist/{google-UNAGUCXQ.js → google-7Q3FYNVP.js} +4 -4
  97. package/dist/{google-marketing-AZC7WHZR.js → google-marketing-TMKWY5AP.js} +1 -1
  98. package/dist/{health-cmd-XHEDL6CF.js → health-cmd-77TMLQ6T.js} +4 -4
  99. package/dist/{history-MKQDN6LY.js → history-Q756HPJM.js} +3 -3
  100. package/dist/index.d.ts +89 -70
  101. package/dist/index.js +25 -25
  102. package/dist/{init-W4LWSMCC.js → init-WDRQTCKK.js} +12 -12
  103. package/dist/{insights-HNJR7UEC.js → insights-TPNHIVNH.js} +3 -3
  104. package/dist/intelligence-service-DAUXHAOP.js +16 -0
  105. package/dist/{journeys-RQBYPWHU.js → journeys-F6UAVPVI.js} +3 -3
  106. package/dist/{keys-KNZAMXJU.js → keys-Q6VMDIAH.js} +3 -3
  107. package/dist/{keyword-7SUZG7RB.js → keyword-7BH5P5P7.js} +3 -3
  108. package/dist/{logs-RTQFOKLJ.js → logs-P2J6XFVJ.js} +3 -3
  109. package/dist/{mcp-JWBPAYR4.js → mcp-RPXFNAKS.js} +4 -4
  110. package/dist/mcp.js +9 -9
  111. package/dist/{measurement-plan-AETWMIGC.js → measurement-plan-KKUB6SLB.js} +5 -5
  112. package/dist/{notify-DGFNKFVG.js → notify-2IK6NR7Y.js} +3 -3
  113. package/dist/{organic-evidence-VA47O6HU.js → organic-evidence-N4HIUIHJ.js} +3 -3
  114. package/dist/{overview-SMXNZLPG.js → overview-FSNB42W5.js} +5 -5
  115. package/dist/{project-WXEDQJLS.js → project-D5ODS46C.js} +3 -3
  116. package/dist/{project-setup-VFBTUA5W.js → project-setup-X7NGKC4R.js} +3 -3
  117. package/dist/{query-C2VIB2XW.js → query-JGCEDLI2.js} +3 -3
  118. package/dist/{research-76TYES7M.js → research-3S5FLAFX.js} +3 -3
  119. package/dist/{results-export-F4FKVOQN.js → results-export-YMX4F2K6.js} +3 -3
  120. package/dist/{run-H6GGXFKQ.js → run-MCJAGAHJ.js} +5 -5
  121. package/dist/{schedule-KTQNJGMO.js → schedule-CLWDPYZG.js} +3 -3
  122. package/dist/{search-YRFUC7SW.js → search-X7SXPESS.js} +3 -3
  123. package/dist/{serve-PWIVPUX7.js → serve-UHEE443J.js} +26 -26
  124. package/dist/{session-LRR2N6IP.js → session-AS2VQ7VL.js} +13 -13
  125. package/dist/{settings-TLDN77K4.js → settings-UZEODHZ3.js} +3 -3
  126. package/dist/{sitemaps-BQ6JI4EW.js → sitemaps-SK2ZE5EJ.js} +3 -3
  127. package/dist/{skills-SQBKFXAN.js → skills-SI6C7MPT.js} +2 -2
  128. package/dist/{snapshot-ICGETMOY.js → snapshot-AOQUU5Q2.js} +3 -3
  129. package/dist/{src-XW5T4IQS.js → src-BXXLPHVZ.js} +2 -2
  130. package/dist/{status-VN65JTUD.js → status-TMKQNQ74.js} +5 -5
  131. package/dist/{technical-aeo-OBCWTN3M.js → technical-aeo-WBLZMCUY.js} +3 -3
  132. package/dist/{telemetry-ZU6REKKU.js → telemetry-DS22S3C3.js} +4 -4
  133. package/dist/{tools-RQDMCSZB.js → tools-YGKVGB5M.js} +11 -11
  134. package/dist/{traffic-YLZSRX5P.js → traffic-6AIRXYMI.js} +24 -7
  135. package/dist/{trends-OWWELIE2.js → trends-LEAXHSM6.js} +3 -3
  136. package/dist/{users-2ICURHTW.js → users-VCNIWES5.js} +3 -3
  137. package/dist/{visibility-stats-FJK3MDYE.js → visibility-stats-4XA2YZET.js} +4 -4
  138. package/dist/{wordpress-UQFA5TFU.js → wordpress-YG3ECQXW.js} +3 -3
  139. package/package.json +1 -1
  140. package/assets/assets/TrafficSourceDetailPage-DSoQk94d.js +0 -1
  141. package/dist/intelligence-service-SWQABQ3X.js +0 -16
@@ -1,15 +1,17 @@
1
1
  import {
2
2
  createLogger
3
- } from "./chunk-3TPHFDZN.js";
3
+ } from "./chunk-WQQ4TNIY.js";
4
4
  import {
5
5
  addLikelyFakeAgentHits,
6
6
  correctBackgroundCallJourneys,
7
7
  mergeSplitJourneyVisitors,
8
8
  repairAiReferralArrivalsOnStartup,
9
9
  writeUnrecognizedAgentBuckets
10
- } from "./chunk-VH424YVI.js";
10
+ } from "./chunk-NGGMSNF6.js";
11
11
  import {
12
12
  AGENT_TRUST_RULES_VERSION,
13
+ BROWSER_AGENT_BOT_IDS,
14
+ BROWSER_AGENT_REQUEST_RULES_VERSION,
13
15
  BROWSER_SHAPED_AGENT_MARKERS,
14
16
  DEFAULT_AI_CRAWLER_RULES,
15
17
  GENERIC_HTTP_CLIENTS,
@@ -18,26 +20,35 @@ import {
18
20
  SELF_TRAFFIC_USER_AGENT_PATTERNS,
19
21
  UNLISTED_AGENT_SKIPPED_EXTENSIONS,
20
22
  UNRECOGNIZED_AGENT_NAMING_VERSION,
23
+ browserAgentRequestKind,
21
24
  classifyAiUserFetch,
22
25
  classifyCrawler,
26
+ countsAsAiUserFetchHit,
27
+ isBrowserAgentId,
23
28
  isScannerPath,
24
29
  isSelfTraffic,
30
+ keepsBrowserAgentJourneyRequest,
25
31
  normalizeTrafficPathPattern,
32
+ rulesShareVerificationList,
26
33
  unrecognizedAgentName
27
- } from "./chunk-CZOGOHIN.js";
34
+ } from "./chunk-K32GU473.js";
28
35
  import {
29
36
  RawEventSampleEventTypes,
30
37
  agentJourneyCaptureDays,
31
38
  agentJourneyEvents,
32
39
  aiUserFetchEventsHourly,
40
+ aiUserFetchLikelyFakeHourly,
33
41
  aiUserFetchVerificationManifestsHourly,
34
42
  crawlerEventsHourly,
43
+ crawlerVerificationManifestsHourly,
35
44
  migrationsTable,
36
45
  parseJsonColumn,
46
+ projects,
37
47
  rawEventSamples,
38
48
  trafficReclassificationState,
49
+ trafficSources,
39
50
  unrecognizedAgentEventsHourly
40
- } from "./chunk-7I2NJ4BH.js";
51
+ } from "./chunk-BYYP43Q3.js";
41
52
  import {
42
53
  AI_ENGINE_DOMAINS,
43
54
  AI_ENGINE_SELF_DOMAINS,
@@ -70,9 +81,10 @@ import {
70
81
  registrableDomain,
71
82
  resolveProviderModel,
72
83
  retryAfterDelayMs,
84
+ sortedUnique,
73
85
  usageCount,
74
86
  withRetry
75
- } from "./chunk-NHBXQWE3.js";
87
+ } from "./chunk-WT22Z3I7.js";
76
88
 
77
89
  // ../provider-openai/src/normalize.ts
78
90
  import OpenAI from "openai";
@@ -2975,12 +2987,20 @@ function extractStoredAnswerAnchors(provider, rawResponse) {
2975
2987
  // src/traffic-reclassify.ts
2976
2988
  import { createHash } from "crypto";
2977
2989
  import { setImmediate as yieldToEventLoop } from "timers/promises";
2978
- import { and, eq, gte, inArray, lte, ne, sql } from "drizzle-orm";
2990
+ import { and, eq, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
2979
2991
  var log = createLogger("TrafficReclassify");
2980
2992
  var STATE_ID = "default";
2981
2993
  var BATCH_SIZE = 200;
2994
+ var SCAN_SPAN = 5e4;
2982
2995
  var UNRECOGNIZED_TABLE_MIGRATION = 201;
2983
2996
  var TRAFFIC_RECLASSIFY_START_DELAY_MS = 3e4;
2997
+ var HOUR_MS = 36e5;
2998
+ var RULE_IDS = new Set(DEFAULT_AI_CRAWLER_RULES.map((rule) => rule.id));
2999
+ var BROWSER_AGENT_REQUEST_RULES = {
3000
+ version: BROWSER_AGENT_REQUEST_RULES_VERSION,
3001
+ botIds: sortedUnique(BROWSER_AGENT_BOT_IDS)
3002
+ };
3003
+ var BROWSER_AGENT_REQUEST_RULES_KEY = "browserAgentRequestRules";
2984
3004
  function trafficClassificationFingerprint() {
2985
3005
  const pattern = (value) => `/${value.source}/${value.flags}`;
2986
3006
  return createHash("sha256").update(JSON.stringify({
@@ -2989,24 +3009,27 @@ function trafficClassificationFingerprint() {
2989
3009
  operator: rule.operator,
2990
3010
  product: rule.product,
2991
3011
  purpose: rule.purpose,
2992
- patterns: rule.userAgentPatterns.map(pattern)
3012
+ patterns: rule.userAgentPatterns.map(pattern),
3013
+ browser: rule.browser === true
2993
3014
  })),
2994
3015
  self: SELF_TRAFFIC_USER_AGENT_PATTERNS.map(pattern),
2995
3016
  naming: UNRECOGNIZED_AGENT_NAMING_VERSION,
2996
3017
  trust: AGENT_TRUST_RULES_VERSION,
2997
3018
  journeys: JOURNEY_RULES_VERSION,
3019
+ browserAgentRequests: BROWSER_AGENT_REQUEST_RULES,
2998
3020
  genericClients: GENERIC_HTTP_CLIENTS,
2999
3021
  browserMarkers: BROWSER_SHAPED_AGENT_MARKERS,
3000
3022
  skippedExtensions: UNLISTED_AGENT_SKIPPED_EXTENSIONS
3001
3023
  })).digest("hex");
3002
3024
  }
3003
- function probeRequest(userAgent, path, observedAt) {
3025
+ var STORED_REQUEST_TIME = (/* @__PURE__ */ new Date(0)).toISOString();
3026
+ function probeRequest(userAgent, path) {
3004
3027
  return {
3005
3028
  sourceType: TrafficSourceTypes["cloud-run"],
3006
3029
  evidenceKind: TrafficEvidenceKinds["raw-request"],
3007
3030
  confidence: TrafficEventConfidences.observed,
3008
3031
  eventId: "reclassify",
3009
- observedAt,
3032
+ observedAt: STORED_REQUEST_TIME,
3010
3033
  method: "GET",
3011
3034
  requestUrl: `https://placeholder${path.startsWith("/") ? path : "/"}`,
3012
3035
  host: "placeholder",
@@ -3014,7 +3037,6 @@ function probeRequest(userAgent, path, observedAt) {
3014
3037
  queryString: null,
3015
3038
  status: 200,
3016
3039
  userAgent,
3017
- // Stored traffic keeps no client address, so no replay can verify an IP.
3018
3040
  remoteIp: null,
3019
3041
  referer: null,
3020
3042
  latencyMs: null,
@@ -3024,8 +3046,8 @@ function probeRequest(userAgent, path, observedAt) {
3024
3046
  providerLabels: {}
3025
3047
  };
3026
3048
  }
3027
- function classifyStored(userAgent, path, observedAt) {
3028
- const request2 = probeRequest(userAgent, path, observedAt);
3049
+ function classifyStored(userAgent, path) {
3050
+ const request2 = probeRequest(userAgent, path);
3029
3051
  if (isSelfTraffic(request2)) return { kind: "self" };
3030
3052
  const fetch2 = classifyAiUserFetch(request2);
3031
3053
  if (fetch2) return { kind: "user-fetch", fetch: fetch2 };
@@ -3041,10 +3063,58 @@ function hourOf(iso) {
3041
3063
  hour.setUTCMinutes(0, 0, 0);
3042
3064
  return hour.toISOString();
3043
3065
  }
3066
+ function hourEnd(tsHour) {
3067
+ return new Date(Date.parse(tsHour) + HOUR_MS).toISOString();
3068
+ }
3044
3069
  function unrecognizedCountingStart(db) {
3045
3070
  const row = db.select({ appliedAt: migrationsTable.appliedAt }).from(migrationsTable).where(eq(migrationsTable.version, UNRECOGNIZED_TABLE_MIGRATION)).get();
3046
3071
  return row ? hourOf(sqliteUtcToIso(row.appliedAt)) : null;
3047
3072
  }
3073
+ function lastRowid(db, table) {
3074
+ return Number(db.select({ max: sql`max(rowid)` }).from(table).get()?.max ?? 0);
3075
+ }
3076
+ function rowidRange(after, bound) {
3077
+ return sql`rowid > ${after} and rowid <= ${bound}`;
3078
+ }
3079
+ function projectScope(column, projectIds) {
3080
+ return projectIds ? inArray(sql`+${column}`, [...projectIds]) : void 0;
3081
+ }
3082
+ async function* rowidPages(ctx, span, read) {
3083
+ let after = span.after ?? 0;
3084
+ for (; ; ) {
3085
+ if (ctx.shouldStop()) return;
3086
+ const rows = read(rowidRange(after, span.bound));
3087
+ if (rows.length === 0) return;
3088
+ after = rows[rows.length - 1].rowid;
3089
+ yield rows;
3090
+ await yieldToEventLoop();
3091
+ }
3092
+ }
3093
+ function inBatch(db, ctx, work) {
3094
+ return db.transaction(work, { behavior: ctx.dryRun ? "deferred" : "immediate" });
3095
+ }
3096
+ function isOrphan(ctx, owner, rows = 1) {
3097
+ if (ctx.liveProjectIds.has(owner.projectId) && ctx.liveSourceIds.has(owner.sourceId)) return false;
3098
+ ctx.orphans += rows;
3099
+ return true;
3100
+ }
3101
+ function addTo(counts, key, value) {
3102
+ counts[key] = (counts[key] ?? 0) + value;
3103
+ }
3104
+ function hourlyKeyColumns(table) {
3105
+ return [table.projectId, table.sourceId, table.tsHour, table.botId, table.verificationStatus, table.pathNormalized, table.status];
3106
+ }
3107
+ function hourlyRow(table, key) {
3108
+ return and(
3109
+ eq(table.projectId, key.projectId),
3110
+ eq(table.sourceId, key.sourceId),
3111
+ eq(table.tsHour, key.tsHour),
3112
+ eq(table.botId, key.botId),
3113
+ eq(table.verificationStatus, key.verificationStatus),
3114
+ eq(table.pathNormalized, key.pathNormalized),
3115
+ eq(table.status, key.status)
3116
+ );
3117
+ }
3048
3118
  function addHourlyHits(tx, opts) {
3049
3119
  const { projectId, sourceId, tsHour, verdict, pathNormalized, status, hits, sampledUserAgent, now } = opts;
3050
3120
  if (verdict.kind === "user-fetch" && verdict.fetch.trust === AgentTrustLevels.likely_fake) {
@@ -3072,30 +3142,52 @@ function addHourlyHits(tx, opts) {
3072
3142
  createdAt: now,
3073
3143
  updatedAt: now
3074
3144
  }).onConflictDoUpdate({
3075
- target: [table.projectId, table.sourceId, table.tsHour, table.botId, table.verificationStatus, table.pathNormalized, table.status],
3145
+ target: hourlyKeyColumns(table),
3076
3146
  set: { hits: sql`${table.hits} + ${hits}`, updatedAt: now }
3077
3147
  }).run();
3078
3148
  }
3149
+ function noteOlderCount(ends, sourceId, tsHour) {
3150
+ const end = hourEnd(tsHour);
3151
+ const known = ends.get(sourceId);
3152
+ if (known === void 0 || Date.parse(known) < Date.parse(end)) ends.set(sourceId, end);
3153
+ }
3154
+ function markUserFetchOlderCounts(tx, ends, now) {
3155
+ const nowMs = Date.parse(now);
3156
+ const column = trafficSources.aiUserFetchOlderCountUntil;
3157
+ let marked = 0;
3158
+ for (const [sourceId, end] of ends) {
3159
+ const until = Date.parse(end) < nowMs ? end : new Date(nowMs).toISOString();
3160
+ marked += tx.update(trafficSources).set({ aiUserFetchOlderCountUntil: until }).where(and(eq(trafficSources.id, sourceId), or(isNull(column), lt(column, until)))).run().changes;
3161
+ }
3162
+ return marked;
3163
+ }
3164
+ function lastBrowserAgentHourEnds(db) {
3165
+ const ends = /* @__PURE__ */ new Map();
3166
+ if (BROWSER_AGENT_BOT_IDS.length === 0) return ends;
3167
+ const ids = [...BROWSER_AGENT_BOT_IDS];
3168
+ const counted = db.select({ sourceId: aiUserFetchEventsHourly.sourceId, lastHour: sql`max(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(inArray(aiUserFetchEventsHourly.botId, ids)).groupBy(aiUserFetchEventsHourly.sourceId).all();
3169
+ const likelyFake = db.select({ sourceId: aiUserFetchLikelyFakeHourly.sourceId, lastHour: sql`max(${aiUserFetchLikelyFakeHourly.tsHour})` }).from(aiUserFetchLikelyFakeHourly).where(inArray(aiUserFetchLikelyFakeHourly.botId, ids)).groupBy(aiUserFetchLikelyFakeHourly.sourceId).all();
3170
+ for (const row of [...counted, ...likelyFake]) noteOlderCount(ends, row.sourceId, row.lastHour);
3171
+ return ends;
3172
+ }
3173
+ function countsBrowserAgentsAsRecorded(resultJson) {
3174
+ const recorded = asRecord(resultJson?.[BROWSER_AGENT_REQUEST_RULES_KEY]);
3175
+ if (!recorded || recorded.version !== BROWSER_AGENT_REQUEST_RULES.version || !Array.isArray(recorded.botIds)) return false;
3176
+ const botIds = sortedUnique(recorded.botIds.filter((id) => typeof id === "string"));
3177
+ return botIds.length === BROWSER_AGENT_REQUEST_RULES.botIds.length && botIds.every((id, index) => id === BROWSER_AGENT_REQUEST_RULES.botIds[index]);
3178
+ }
3079
3179
  function botIdOf(verdict) {
3080
3180
  return verdict.kind === "user-fetch" ? verdict.fetch.botId : verdict.crawler.botId;
3081
3181
  }
3082
- async function reclassifyUnrecognizedRows(db, opts) {
3182
+ async function reclassifyUnrecognizedRows(db, ctx) {
3083
3183
  const result = { examined: 0, moved: 0, movedHits: 0, renamed: 0, removed: 0, byBot: {} };
3084
3184
  const table = unrecognizedAgentEventsHourly;
3085
3185
  const verdicts = /* @__PURE__ */ new Map();
3086
- const lastStartingRowid = Number(db.select({ max: sql`max(rowid)` }).from(table).get()?.max ?? 0);
3087
- let lastRowid = 0;
3088
- for (; ; ) {
3089
- if (opts.shouldStop()) break;
3090
- const keys = db.select({ rowid: sql`rowid`, projectId: table.projectId, sourceId: table.sourceId, tsHour: table.tsHour, agentName: table.agentName }).from(table).where(and(
3091
- sql`rowid > ${lastRowid}`,
3092
- sql`rowid <= ${lastStartingRowid}`,
3093
- opts.projectIds ? inArray(table.projectId, [...opts.projectIds]) : void 0
3094
- )).orderBy(sql`rowid`).limit(BATCH_SIZE).all();
3095
- if (keys.length === 0) break;
3096
- lastRowid = keys[keys.length - 1].rowid;
3186
+ const pages = rowidPages(ctx, { bound: ctx.bounds.unrecognized }, (range) => db.select({ rowid: sql`rowid`, projectId: table.projectId, sourceId: table.sourceId, tsHour: table.tsHour, agentName: table.agentName }).from(table).where(and(range, projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3187
+ for await (const keys of pages) {
3097
3188
  result.examined += keys.length;
3098
- db.transaction((tx) => {
3189
+ inBatch(db, ctx, (tx) => {
3190
+ const olderCounts = /* @__PURE__ */ new Map();
3099
3191
  for (const key of keys) {
3100
3192
  const match = and(
3101
3193
  eq(table.projectId, key.projectId),
@@ -3108,20 +3200,20 @@ async function reclassifyUnrecognizedRows(db, opts) {
3108
3200
  const userAgent = row.sampledUserAgent;
3109
3201
  let verdict = verdicts.get(userAgent);
3110
3202
  if (!verdict) {
3111
- verdict = classifyStored(userAgent, "/", row.tsHour);
3203
+ verdict = classifyStored(userAgent, "/");
3112
3204
  verdicts.set(userAgent, verdict);
3113
3205
  }
3114
3206
  if (verdict.kind === "self") {
3115
3207
  result.removed++;
3116
- if (!opts.dryRun) tx.delete(table).where(match).run();
3208
+ if (!ctx.dryRun) tx.delete(table).where(match).run();
3117
3209
  continue;
3118
3210
  }
3119
3211
  if (verdict.kind === "user-fetch" || verdict.kind === "crawler") {
3212
+ if (isOrphan(ctx, row)) continue;
3120
3213
  result.moved++;
3121
3214
  result.movedHits += row.hits;
3122
- const botId = botIdOf(verdict);
3123
- result.byBot[botId] = (result.byBot[botId] ?? 0) + row.hits;
3124
- if (opts.dryRun) continue;
3215
+ addTo(result.byBot, botIdOf(verdict), row.hits);
3216
+ if (ctx.dryRun) continue;
3125
3217
  addHourlyHits(tx, {
3126
3218
  projectId: row.projectId,
3127
3219
  sourceId: row.sourceId,
@@ -3131,83 +3223,76 @@ async function reclassifyUnrecognizedRows(db, opts) {
3131
3223
  status: 0,
3132
3224
  hits: row.hits,
3133
3225
  sampledUserAgent: userAgent,
3134
- now: opts.now
3226
+ now: ctx.now
3135
3227
  });
3136
3228
  tx.delete(table).where(match).run();
3229
+ if (verdict.kind === "user-fetch" && verdict.fetch.browser) noteOlderCount(olderCounts, row.sourceId, row.tsHour);
3137
3230
  continue;
3138
3231
  }
3139
3232
  const name = unrecognizedAgentName({ method: "GET", path: row.sampledPath, userAgent });
3140
3233
  if (name === row.agentName) continue;
3141
3234
  if (name === null) {
3142
3235
  result.removed++;
3143
- if (!opts.dryRun) tx.delete(table).where(match).run();
3236
+ if (!ctx.dryRun) tx.delete(table).where(match).run();
3144
3237
  continue;
3145
3238
  }
3239
+ if (isOrphan(ctx, row)) continue;
3146
3240
  result.renamed++;
3147
- if (opts.dryRun) continue;
3241
+ if (ctx.dryRun) continue;
3148
3242
  tx.delete(table).where(match).run();
3149
3243
  writeUnrecognizedAgentBuckets(tx, {
3150
3244
  projectId: row.projectId,
3151
3245
  sourceId: row.sourceId,
3152
3246
  buckets: [{ tsHour: row.tsHour, agentName: name, hits: row.hits, sampledUserAgent: userAgent, sampledPath: row.sampledPath ?? "" }],
3153
- now: opts.now
3247
+ now: ctx.now
3154
3248
  });
3155
3249
  }
3156
- }, { behavior: "immediate" });
3157
- await yieldToEventLoop();
3250
+ if (!ctx.dryRun) markUserFetchOlderCounts(tx, olderCounts, ctx.now);
3251
+ });
3158
3252
  }
3159
3253
  return result;
3160
3254
  }
3161
- async function reclassifyUnknownSamples(db, opts) {
3255
+ async function reclassifyUnknownSamples(db, ctx) {
3162
3256
  const result = { examined: 0, reclassified: 0, counted: 0, removed: 0, byBot: {} };
3163
3257
  const countingStart = unrecognizedCountingStart(db);
3164
- const lastStartingRowid = Number(db.select({ max: sql`max(rowid)` }).from(rawEventSamples).get()?.max ?? 0);
3165
- let lastRowid = 0;
3166
- for (; ; ) {
3167
- if (opts.shouldStop()) break;
3168
- const samples = db.select({
3169
- rowid: sql`rowid`,
3170
- id: rawEventSamples.id,
3171
- projectId: rawEventSamples.projectId,
3172
- sourceId: rawEventSamples.sourceId,
3173
- ts: rawEventSamples.ts,
3174
- userAgent: rawEventSamples.userAgent,
3175
- pathNormalized: rawEventSamples.pathNormalized,
3176
- status: rawEventSamples.status
3177
- }).from(rawEventSamples).where(and(
3178
- eq(rawEventSamples.eventType, RawEventSampleEventTypes.unknown),
3179
- sql`rowid > ${lastRowid}`,
3180
- sql`rowid <= ${lastStartingRowid}`,
3181
- opts.projectIds ? inArray(rawEventSamples.projectId, [...opts.projectIds]) : void 0
3182
- )).orderBy(sql`rowid`).limit(BATCH_SIZE).all();
3183
- if (samples.length === 0) break;
3184
- lastRowid = samples[samples.length - 1].rowid;
3258
+ const table = rawEventSamples;
3259
+ const pages = rowidPages(ctx, { bound: ctx.bounds.samples }, (range) => db.select({
3260
+ rowid: sql`rowid`,
3261
+ id: table.id,
3262
+ projectId: table.projectId,
3263
+ sourceId: table.sourceId,
3264
+ ts: table.ts,
3265
+ userAgent: table.userAgent,
3266
+ pathNormalized: table.pathNormalized,
3267
+ status: table.status
3268
+ }).from(table).where(and(eq(table.eventType, RawEventSampleEventTypes.unknown), range, projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3269
+ for await (const samples of pages) {
3185
3270
  result.examined += samples.length;
3186
- db.transaction((tx) => {
3271
+ inBatch(db, ctx, (tx) => {
3187
3272
  for (const sample of samples) {
3188
3273
  if (!sample.userAgent) continue;
3189
- const verdict = classifyStored(sample.userAgent, sample.pathNormalized, sample.ts);
3274
+ const verdict = classifyStored(sample.userAgent, sample.pathNormalized);
3275
+ if (verdict.kind === "unknown") continue;
3190
3276
  if (verdict.kind === "self") {
3191
3277
  result.removed++;
3192
- if (!opts.dryRun) tx.delete(rawEventSamples).where(eq(rawEventSamples.id, sample.id)).run();
3278
+ if (!ctx.dryRun) tx.delete(table).where(eq(table.id, sample.id)).run();
3193
3279
  continue;
3194
3280
  }
3195
- if (verdict.kind === "unknown") continue;
3281
+ if (isOrphan(ctx, sample)) continue;
3196
3282
  result.reclassified++;
3197
- const botId = botIdOf(verdict);
3198
- result.byBot[botId] = (result.byBot[botId] ?? 0) + 1;
3283
+ addTo(result.byBot, botIdOf(verdict), 1);
3199
3284
  const tsHour = hourOf(sample.ts);
3200
- const countSample = countingStart === null || tsHour < countingStart || unrecognizedAgentName({ method: "GET", path: sample.pathNormalized, userAgent: sample.userAgent }) === null;
3285
+ const countSample = (countingStart === null || tsHour < countingStart || unrecognizedAgentName({ method: "GET", path: sample.pathNormalized, userAgent: sample.userAgent }) === null) && (verdict.kind === "crawler" || verdict.fetch.trust === AgentTrustLevels.likely_fake || countsAsAiUserFetchHit(verdict.fetch, { method: null, path: sample.pathNormalized, queryString: null }));
3201
3286
  if (countSample) result.counted++;
3202
- if (opts.dryRun) continue;
3203
- tx.update(rawEventSamples).set({
3287
+ if (ctx.dryRun) continue;
3288
+ tx.update(table).set({
3204
3289
  eventType: verdict.kind === "user-fetch" ? RawEventSampleEventTypes.aiUserFetch : RawEventSampleEventTypes.crawler,
3205
3290
  classifierDetailsJson: {
3206
3291
  crawler: verdict.kind === "crawler" ? { ...verdict.crawler, verificationManifest: null } : null,
3207
- aiUserFetch: verdict.kind === "user-fetch" ? { ...verdict.fetch, verificationManifest: null } : null,
3292
+ aiUserFetch: verdict.kind === "user-fetch" ? sampledUserFetch(verdict.fetch, sample.pathNormalized) : null,
3208
3293
  aiReferral: null
3209
3294
  }
3210
- }).where(eq(rawEventSamples.id, sample.id)).run();
3295
+ }).where(eq(table.id, sample.id)).run();
3211
3296
  if (!countSample) continue;
3212
3297
  addHourlyHits(tx, {
3213
3298
  projectId: sample.projectId,
@@ -3218,75 +3303,331 @@ async function reclassifyUnknownSamples(db, opts) {
3218
3303
  status: sample.status ?? 200,
3219
3304
  hits: 1,
3220
3305
  sampledUserAgent: sample.userAgent,
3221
- now: opts.now
3306
+ now: ctx.now
3307
+ });
3308
+ }
3309
+ });
3310
+ }
3311
+ return result;
3312
+ }
3313
+ function crawlerRekeyOf(botId, userAgent, verdicts) {
3314
+ if (!RULE_IDS.has(botId)) return { kind: "unknown-bot" };
3315
+ let verdict = verdicts.get(userAgent);
3316
+ if (!verdict) {
3317
+ verdict = classifyStored(userAgent, "/");
3318
+ if (verdict.kind === "user-fetch") {
3319
+ const crawler = classifyCrawler(probeRequest(userAgent, "/"));
3320
+ if (crawler) verdict = { kind: "crawler", crawler };
3321
+ }
3322
+ verdicts.set(userAgent, verdict);
3323
+ }
3324
+ switch (verdict.kind) {
3325
+ case "self":
3326
+ return { kind: "self" };
3327
+ case "crawler":
3328
+ return verdict.crawler.botId === botId ? { kind: "keep" } : { kind: "crawler", to: verdict.crawler };
3329
+ case "user-fetch":
3330
+ return { kind: "user-fetch" };
3331
+ case "unknown":
3332
+ return { kind: "unknown" };
3333
+ }
3334
+ }
3335
+ function moveCrawlerHour(tx, row, to, keepVerification) {
3336
+ const table = crawlerEventsHourly;
3337
+ const manifests = crawlerVerificationManifestsHourly;
3338
+ tx.insert(table).values({
3339
+ ...row,
3340
+ botId: to.botId,
3341
+ operator: to.operator,
3342
+ verificationStatus: keepVerification ? row.verificationStatus : VerificationStatuses.claimed_unverified
3343
+ }).onConflictDoUpdate({
3344
+ target: hourlyKeyColumns(table),
3345
+ set: { hits: sql`${table.hits} + ${row.hits}`, updatedAt: sql`max(${table.updatedAt}, excluded.updated_at)` }
3346
+ }).run();
3347
+ if (keepVerification) {
3348
+ for (const entry of tx.select().from(manifests).where(hourlyRow(manifests, row)).all()) {
3349
+ tx.insert(manifests).values({ ...entry, botId: to.botId }).onConflictDoUpdate({
3350
+ target: [...hourlyKeyColumns(manifests), manifests.manifestId],
3351
+ set: { hits: sql`${manifests.hits} + ${entry.hits}`, updatedAt: sql`max(${manifests.updatedAt}, excluded.updated_at)` }
3352
+ }).run();
3353
+ }
3354
+ }
3355
+ tx.delete(table).where(hourlyRow(table, row)).run();
3356
+ }
3357
+ function rekeyCrawlerHour(tx, key, userAgent, rekey, ctx, result, olderCounts) {
3358
+ const table = crawlerEventsHourly;
3359
+ const row = tx.select().from(table).where(hourlyRow(table, key)).get();
3360
+ if (!row || row.sampledUserAgent !== userAgent) return;
3361
+ let move;
3362
+ switch (rekey.kind) {
3363
+ case "self":
3364
+ move = rekey;
3365
+ break;
3366
+ case "crawler":
3367
+ move = { kind: "crawler", to: rekey.to, keepVerification: rulesShareVerificationList(row.botId, rekey.to.botId) };
3368
+ break;
3369
+ case "user-fetch": {
3370
+ const verdict = classifyStored(userAgent, row.pathNormalized);
3371
+ if (verdict.kind !== "user-fetch") return;
3372
+ move = { kind: "user-fetch", verdict };
3373
+ break;
3374
+ }
3375
+ case "unknown": {
3376
+ const agentName = unrecognizedAgentName({ method: "GET", path: row.pathNormalized, userAgent });
3377
+ if (agentName === null) return;
3378
+ move = { kind: "unknown", agentName };
3379
+ break;
3380
+ }
3381
+ }
3382
+ if (isOrphan(ctx, row)) return;
3383
+ const keepsVerification = move.kind === "crawler" && move.keepVerification;
3384
+ if (row.verificationStatus === VerificationStatuses.verified && !keepsVerification) {
3385
+ if (!ctx.allowVerificationLoss) {
3386
+ result.heldVerified++;
3387
+ result.heldVerifiedHits += row.hits;
3388
+ return;
3389
+ }
3390
+ result.unverifiedHits += row.hits;
3391
+ }
3392
+ const remove = () => tx.delete(table).where(hourlyRow(table, row)).run();
3393
+ switch (move.kind) {
3394
+ case "self":
3395
+ result.removed++;
3396
+ result.removedHits += row.hits;
3397
+ if (!ctx.dryRun) remove();
3398
+ return;
3399
+ case "crawler":
3400
+ result.moved++;
3401
+ result.movedHits += row.hits;
3402
+ addTo(result.byBot, move.to.botId, row.hits);
3403
+ if (!ctx.dryRun) moveCrawlerHour(tx, row, move.to, move.keepVerification);
3404
+ return;
3405
+ case "user-fetch":
3406
+ result.toUserFetch++;
3407
+ result.toUserFetchHits += row.hits;
3408
+ addTo(result.byBot, move.verdict.fetch.botId, row.hits);
3409
+ if (ctx.dryRun) return;
3410
+ addHourlyHits(tx, {
3411
+ projectId: row.projectId,
3412
+ sourceId: row.sourceId,
3413
+ tsHour: row.tsHour,
3414
+ verdict: move.verdict,
3415
+ pathNormalized: row.pathNormalized,
3416
+ status: row.status,
3417
+ hits: row.hits,
3418
+ sampledUserAgent: userAgent,
3419
+ now: ctx.now
3420
+ });
3421
+ remove();
3422
+ if (move.verdict.fetch.browser) noteOlderCount(olderCounts, row.sourceId, row.tsHour);
3423
+ return;
3424
+ case "unknown":
3425
+ result.toUnrecognized++;
3426
+ result.toUnrecognizedHits += row.hits;
3427
+ if (ctx.dryRun) return;
3428
+ writeUnrecognizedAgentBuckets(tx, {
3429
+ projectId: row.projectId,
3430
+ sourceId: row.sourceId,
3431
+ buckets: [{ tsHour: row.tsHour, agentName: move.agentName, hits: row.hits, sampledUserAgent: userAgent, sampledPath: row.pathNormalized }],
3432
+ now: ctx.now
3433
+ });
3434
+ remove();
3435
+ return;
3436
+ }
3437
+ }
3438
+ async function rekeyCrawlerHours(db, ctx) {
3439
+ const result = {
3440
+ examined: 0,
3441
+ moved: 0,
3442
+ movedHits: 0,
3443
+ toUserFetch: 0,
3444
+ toUserFetchHits: 0,
3445
+ toUnrecognized: 0,
3446
+ toUnrecognizedHits: 0,
3447
+ removed: 0,
3448
+ removedHits: 0,
3449
+ unverifiedHits: 0,
3450
+ heldVerified: 0,
3451
+ heldVerifiedHits: 0,
3452
+ unknownBot: 0,
3453
+ samplesRelabeled: 0,
3454
+ samplesNowUnknown: 0,
3455
+ samplesRemoved: 0,
3456
+ byBot: {}
3457
+ };
3458
+ const table = crawlerEventsHourly;
3459
+ const verdicts = /* @__PURE__ */ new Map();
3460
+ for (let from = 0; from < ctx.bounds.crawlers; from += SCAN_SPAN) {
3461
+ if (ctx.shouldStop()) return result;
3462
+ const to = Math.min(from + SCAN_SPAN, ctx.bounds.crawlers);
3463
+ const pairs = db.select({ botId: table.botId, userAgent: table.sampledUserAgent, rows: sql`count(*)` }).from(table).where(and(rowidRange(from, to), isNotNull(table.sampledUserAgent), projectScope(table.projectId, ctx.projectIds))).groupBy(table.botId, table.sampledUserAgent).all();
3464
+ for (const pair of pairs) {
3465
+ const userAgent = pair.userAgent;
3466
+ result.examined += pair.rows;
3467
+ const rekey = crawlerRekeyOf(pair.botId, userAgent, verdicts);
3468
+ if (rekey.kind === "keep") continue;
3469
+ if (rekey.kind === "unknown-bot") {
3470
+ result.unknownBot += pair.rows;
3471
+ continue;
3472
+ }
3473
+ const pages = rowidPages(ctx, { after: from, bound: to }, (range) => db.select({
3474
+ rowid: sql`rowid`,
3475
+ projectId: table.projectId,
3476
+ sourceId: table.sourceId,
3477
+ tsHour: table.tsHour,
3478
+ botId: table.botId,
3479
+ verificationStatus: table.verificationStatus,
3480
+ pathNormalized: table.pathNormalized,
3481
+ status: table.status
3482
+ }).from(table).where(and(range, eq(table.botId, pair.botId), eq(table.sampledUserAgent, userAgent), projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3483
+ for await (const keys of pages) {
3484
+ inBatch(db, ctx, (tx) => {
3485
+ const olderCounts = /* @__PURE__ */ new Map();
3486
+ for (const key of keys) rekeyCrawlerHour(tx, key, userAgent, rekey, ctx, result, olderCounts);
3487
+ if (!ctx.dryRun) markUserFetchOlderCounts(tx, olderCounts, ctx.now);
3222
3488
  });
3223
3489
  }
3224
- }, { behavior: "immediate" });
3490
+ }
3225
3491
  await yieldToEventLoop();
3226
3492
  }
3493
+ await relabelCrawlerSamples(db, ctx, verdicts, result);
3227
3494
  return result;
3228
3495
  }
3229
- function hourlyAgentRow(key) {
3230
- const table = aiUserFetchEventsHourly;
3231
- return and(
3232
- eq(table.projectId, key.projectId),
3233
- eq(table.sourceId, key.sourceId),
3234
- eq(table.tsHour, key.tsHour),
3235
- eq(table.botId, key.botId),
3236
- eq(table.verificationStatus, key.verificationStatus),
3237
- eq(table.pathNormalized, key.pathNormalized),
3238
- eq(table.status, key.status)
3239
- );
3496
+ function crawlerSampleRelabel(details, sample, rekey, ctx) {
3497
+ const label = asRecord(details.crawler);
3498
+ if (!label) return null;
3499
+ const keepsVerification = rekey.kind === "crawler" && rulesShareVerificationList(String(label.botId), rekey.to.botId);
3500
+ if (label.verificationStatus === VerificationStatuses.verified && !keepsVerification && !ctx.allowVerificationLoss) return null;
3501
+ switch (rekey.kind) {
3502
+ case "self":
3503
+ return { kind: "remove" };
3504
+ case "crawler":
3505
+ return {
3506
+ kind: "relabel",
3507
+ eventType: RawEventSampleEventTypes.crawler,
3508
+ details: {
3509
+ ...details,
3510
+ crawler: {
3511
+ ...label,
3512
+ botId: rekey.to.botId,
3513
+ operator: rekey.to.operator,
3514
+ product: rekey.to.product,
3515
+ purpose: rekey.to.purpose,
3516
+ ...keepsVerification ? {} : { verificationStatus: VerificationStatuses.claimed_unverified, verificationManifest: null }
3517
+ }
3518
+ }
3519
+ };
3520
+ case "user-fetch": {
3521
+ const verdict = classifyStored(sample.userAgent, sample.pathNormalized);
3522
+ if (verdict.kind !== "user-fetch") return null;
3523
+ return {
3524
+ kind: "relabel",
3525
+ eventType: RawEventSampleEventTypes.aiUserFetch,
3526
+ details: { ...details, crawler: null, aiUserFetch: sampledUserFetch(verdict.fetch, sample.pathNormalized) }
3527
+ };
3528
+ }
3529
+ case "unknown":
3530
+ return {
3531
+ kind: "relabel",
3532
+ eventType: details.aiReferral ? RawEventSampleEventTypes.aiReferral : RawEventSampleEventTypes.unknown,
3533
+ details: { ...details, crawler: null, aiUserFetch: null }
3534
+ };
3535
+ }
3240
3536
  }
3241
- async function reassessAgentHits(db, opts) {
3242
- const result = { examined: 0, moved: 0, movedHits: 0 };
3243
- const table = aiUserFetchEventsHourly;
3244
- const lastStartingRowid = Number(db.select({ max: sql`max(rowid)` }).from(table).get()?.max ?? 0);
3245
- let lastRowid = 0;
3246
- for (; ; ) {
3247
- if (opts.shouldStop()) break;
3248
- const rows = db.select({
3249
- rowid: sql`rowid`,
3250
- projectId: table.projectId,
3251
- sourceId: table.sourceId,
3252
- tsHour: table.tsHour,
3253
- botId: table.botId,
3254
- operator: table.operator,
3255
- verificationStatus: table.verificationStatus,
3256
- pathNormalized: table.pathNormalized,
3257
- status: table.status
3258
- }).from(table).where(and(
3259
- sql`rowid > ${lastRowid}`,
3260
- sql`rowid <= ${lastStartingRowid}`,
3261
- ne(table.verificationStatus, VerificationStatuses.verified),
3262
- opts.projectIds ? inArray(table.projectId, [...opts.projectIds]) : void 0
3263
- )).orderBy(sql`rowid`).limit(BATCH_SIZE).all();
3264
- if (rows.length === 0) break;
3265
- lastRowid = rows[rows.length - 1].rowid;
3266
- result.examined += rows.length;
3267
- const probes = rows.filter((row) => isScannerPath(row.pathNormalized));
3268
- if (probes.length > 0) {
3269
- db.transaction((tx) => {
3270
- for (const row of probes) {
3271
- const current = tx.select({ hits: table.hits }).from(table).where(hourlyAgentRow(row)).get();
3272
- if (!current) continue;
3273
- result.moved++;
3274
- result.movedHits += current.hits;
3275
- if (opts.dryRun) continue;
3276
- addLikelyFakeAgentHits(tx, {
3277
- projectId: row.projectId,
3278
- sourceId: row.sourceId,
3279
- buckets: [{ tsHour: row.tsHour, botId: row.botId, operator: row.operator, reason: AgentTrustReasons["scanner-path"], hits: current.hits }],
3280
- now: opts.now
3281
- });
3282
- tx.delete(table).where(hourlyAgentRow(row)).run();
3537
+ function sampledUserFetch(fetch2, pathNormalized) {
3538
+ const label = { ...fetch2, verificationManifest: null };
3539
+ return fetch2.browser ? { ...label, requestKind: browserAgentRequestKind({ method: null, path: pathNormalized, queryString: null }) } : label;
3540
+ }
3541
+ async function relabelCrawlerSamples(db, ctx, verdicts, result) {
3542
+ const table = rawEventSamples;
3543
+ const labelBotId = sql`CASE WHEN json_valid(${table.classifierDetailsJson}) THEN json_extract(${table.classifierDetailsJson}, '$.crawler.botId') END`;
3544
+ const crawlerSamples = eq(table.eventType, RawEventSampleEventTypes.crawler);
3545
+ for (let from = 0; from < ctx.bounds.samples; from += SCAN_SPAN) {
3546
+ if (ctx.shouldStop()) return;
3547
+ const to = Math.min(from + SCAN_SPAN, ctx.bounds.samples);
3548
+ const pairs = db.select({ userAgent: table.userAgent, botId: labelBotId }).from(table).where(and(crawlerSamples, rowidRange(from, to), isNotNull(table.userAgent), projectScope(table.projectId, ctx.projectIds))).groupBy(table.userAgent, labelBotId).all();
3549
+ for (const pair of pairs) {
3550
+ const userAgent = pair.userAgent;
3551
+ if (typeof pair.botId !== "string") continue;
3552
+ const rekey = crawlerRekeyOf(pair.botId, userAgent, verdicts);
3553
+ if (rekey.kind === "keep" || rekey.kind === "unknown-bot") continue;
3554
+ const pages = rowidPages(ctx, { after: from, bound: to }, (range) => db.select({ rowid: sql`rowid`, id: table.id, pathNormalized: table.pathNormalized, details: table.classifierDetailsJson }).from(table).where(and(crawlerSamples, range, eq(table.userAgent, userAgent), sql`${labelBotId} = ${pair.botId}`, projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3555
+ for await (const samples of pages) {
3556
+ const changes = samples.flatMap((sample) => {
3557
+ const change = crawlerSampleRelabel(sample.details, { userAgent, pathNormalized: sample.pathNormalized }, rekey, ctx);
3558
+ return change ? [{ id: sample.id, change }] : [];
3559
+ });
3560
+ for (const { change } of changes) {
3561
+ if (change.kind === "remove") {
3562
+ result.samplesRemoved++;
3563
+ continue;
3564
+ }
3565
+ result.samplesRelabeled++;
3566
+ if (change.eventType === RawEventSampleEventTypes.unknown) result.samplesNowUnknown++;
3283
3567
  }
3284
- }, { behavior: "immediate" });
3568
+ if (changes.length === 0 || ctx.dryRun) continue;
3569
+ inBatch(db, ctx, (tx) => {
3570
+ for (const { id, change } of changes) {
3571
+ if (change.kind === "remove") tx.delete(table).where(eq(table.id, id)).run();
3572
+ else tx.update(table).set({ eventType: change.eventType, classifierDetailsJson: change.details }).where(eq(table.id, id)).run();
3573
+ }
3574
+ });
3575
+ }
3285
3576
  }
3286
3577
  await yieldToEventLoop();
3287
3578
  }
3579
+ }
3580
+ async function reassessAgentHits(db, ctx) {
3581
+ const result = { examined: 0, moved: 0, movedHits: 0 };
3582
+ const table = aiUserFetchEventsHourly;
3583
+ const pages = rowidPages(ctx, { bound: ctx.bounds.userFetch }, (range) => db.select({
3584
+ rowid: sql`rowid`,
3585
+ projectId: table.projectId,
3586
+ sourceId: table.sourceId,
3587
+ tsHour: table.tsHour,
3588
+ botId: table.botId,
3589
+ operator: table.operator,
3590
+ verificationStatus: table.verificationStatus,
3591
+ pathNormalized: table.pathNormalized,
3592
+ status: table.status
3593
+ }).from(table).where(and(range, ne(table.verificationStatus, VerificationStatuses.verified), projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3594
+ for await (const rows of pages) {
3595
+ result.examined += rows.length;
3596
+ const probes = rows.filter((row) => isScannerPath(row.pathNormalized, { browser: isBrowserAgentId(row.botId) }));
3597
+ if (probes.length === 0) continue;
3598
+ inBatch(db, ctx, (tx) => {
3599
+ for (const row of probes) {
3600
+ const current = tx.select({ hits: table.hits }).from(table).where(hourlyRow(table, row)).get();
3601
+ if (!current || isOrphan(ctx, row)) continue;
3602
+ result.moved++;
3603
+ result.movedHits += current.hits;
3604
+ if (ctx.dryRun) continue;
3605
+ addLikelyFakeAgentHits(tx, {
3606
+ projectId: row.projectId,
3607
+ sourceId: row.sourceId,
3608
+ buckets: [{ tsHour: row.tsHour, botId: row.botId, operator: row.operator, reason: AgentTrustReasons["scanner-path"], hits: current.hits }],
3609
+ now: ctx.now
3610
+ });
3611
+ tx.delete(table).where(hourlyRow(table, row)).run();
3612
+ }
3613
+ });
3614
+ }
3288
3615
  return result;
3289
3616
  }
3617
+ function removeStoredAgentRequest(tx, row) {
3618
+ if (tx.delete(agentJourneyEvents).where(eq(agentJourneyEvents.id, row.id)).run().changes === 0) return false;
3619
+ tx.update(agentJourneyCaptureDays).set({ storedEvents: sql`max(${agentJourneyCaptureDays.storedEvents} - 1, 0)` }).where(and(
3620
+ eq(agentJourneyCaptureDays.projectId, row.projectId),
3621
+ eq(agentJourneyCaptureDays.sourceId, row.sourceId),
3622
+ eq(agentJourneyCaptureDays.day, row.ts.slice(0, 10))
3623
+ )).run();
3624
+ return true;
3625
+ }
3626
+ function wasCountedAsHit(row, olderCountUntil) {
3627
+ if (!isBrowserAgentId(row.agentId)) return true;
3628
+ if (olderCountUntil !== null && Date.parse(row.ts) < Date.parse(olderCountUntil)) return true;
3629
+ return countsAsAiUserFetchHit({ browser: true }, { method: row.method, path: row.path, queryString: null });
3630
+ }
3290
3631
  function moveAgentHitToBurst(tx, row, now) {
3291
3632
  const key = {
3292
3633
  projectId: row.projectId,
@@ -3298,24 +3639,15 @@ function moveAgentHitToBurst(tx, row, now) {
3298
3639
  status: row.status ?? 0
3299
3640
  };
3300
3641
  const table = aiUserFetchEventsHourly;
3301
- const taken = tx.update(table).set({ hits: sql`${table.hits} - 1`, updatedAt: now }).where(and(hourlyAgentRow(key), sql`${table.hits} > 0`)).run();
3642
+ const taken = tx.update(table).set({ hits: sql`${table.hits} - 1`, updatedAt: now }).where(and(hourlyRow(table, key), sql`${table.hits} > 0`)).run();
3302
3643
  if (taken.changes === 0) return;
3303
3644
  const manifests = aiUserFetchVerificationManifestsHourly;
3304
3645
  if (row.verificationManifest) {
3305
- const manifestRow = and(
3306
- eq(manifests.projectId, key.projectId),
3307
- eq(manifests.sourceId, key.sourceId),
3308
- eq(manifests.tsHour, key.tsHour),
3309
- eq(manifests.botId, key.botId),
3310
- eq(manifests.verificationStatus, key.verificationStatus),
3311
- eq(manifests.pathNormalized, key.pathNormalized),
3312
- eq(manifests.status, key.status),
3313
- eq(manifests.manifestId, row.verificationManifest.id)
3314
- );
3646
+ const manifestRow = and(hourlyRow(manifests, key), eq(manifests.manifestId, row.verificationManifest.id));
3315
3647
  tx.update(manifests).set({ hits: sql`${manifests.hits} - 1`, updatedAt: now }).where(and(manifestRow, sql`${manifests.hits} > 0`)).run();
3316
3648
  tx.delete(manifests).where(and(manifestRow, sql`${manifests.hits} <= 0`)).run();
3317
3649
  }
3318
- tx.delete(table).where(and(hourlyAgentRow(key), sql`${table.hits} <= 0`)).run();
3650
+ tx.delete(table).where(and(hourlyRow(table, key), sql`${table.hits} <= 0`)).run();
3319
3651
  addLikelyFakeAgentHits(tx, {
3320
3652
  projectId: row.projectId,
3321
3653
  sourceId: row.sourceId,
@@ -3323,39 +3655,31 @@ function moveAgentHitToBurst(tx, row, now) {
3323
3655
  now
3324
3656
  });
3325
3657
  }
3326
- async function reassessAgentRequests(db, opts) {
3658
+ async function reassessAgentRequests(db, ctx) {
3327
3659
  const result = { examined: 0, probes: 0, removed: 0 };
3660
+ const previewed = /* @__PURE__ */ new Set();
3328
3661
  const table = agentJourneyEvents;
3329
3662
  const clients = /* @__PURE__ */ new Map();
3330
- const lastStartingRowid = Number(db.select({ max: sql`max(rowid)` }).from(table).get()?.max ?? 0);
3331
- let lastRowid = 0;
3332
- for (; ; ) {
3333
- if (opts.shouldStop()) return result;
3334
- const rows = db.select({ rowid: sql`rowid`, projectId: table.projectId, sourceId: table.sourceId, correlationKey: table.correlationKey, ts: table.ts, path: table.path }).from(table).where(and(
3335
- sql`rowid > ${lastRowid}`,
3336
- sql`rowid <= ${lastStartingRowid}`,
3337
- ne(table.trust, AgentTrustLevels.verified),
3338
- opts.projectIds ? inArray(table.projectId, [...opts.projectIds]) : void 0
3339
- )).orderBy(sql`rowid`).limit(BATCH_SIZE).all();
3340
- if (rows.length === 0) break;
3341
- lastRowid = rows[rows.length - 1].rowid;
3663
+ const pages = rowidPages(ctx, { bound: ctx.bounds.agentRequests }, (range) => db.select({ rowid: sql`rowid`, projectId: table.projectId, sourceId: table.sourceId, correlationKey: table.correlationKey, agentId: table.agentId, ts: table.ts, path: table.path }).from(table).where(and(range, ne(table.trust, AgentTrustLevels.verified), projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3664
+ for await (const rows of pages) {
3342
3665
  result.examined += rows.length;
3343
3666
  for (const row of rows) {
3344
- if (!isScannerPath(row.path)) continue;
3667
+ if (!isScannerPath(row.path, { browser: isBrowserAgentId(row.agentId) })) continue;
3345
3668
  result.probes++;
3346
3669
  const id = JSON.stringify([row.projectId, row.sourceId, row.correlationKey]);
3347
3670
  const client = clients.get(id) ?? { projectId: row.projectId, sourceId: row.sourceId, correlationKey: row.correlationKey, probes: [] };
3348
3671
  client.probes.push(Date.parse(row.ts));
3349
3672
  clients.set(id, client);
3350
3673
  }
3351
- await yieldToEventLoop();
3352
3674
  }
3353
3675
  for (const client of clients.values()) {
3354
- if (opts.shouldStop()) break;
3676
+ if (ctx.shouldStop()) break;
3677
+ if (isOrphan(ctx, client, client.probes.length)) continue;
3355
3678
  const probes = client.probes.sort((a, b) => a - b);
3356
3679
  const from = new Date(probes[0] - SCANNER_BURST_WINDOW_MS).toISOString();
3357
3680
  const to = new Date(probes.at(-1) + SCANNER_BURST_WINDOW_MS).toISOString();
3358
- db.transaction((tx) => {
3681
+ inBatch(db, ctx, (tx) => {
3682
+ const olderCountUntil = tx.select({ until: trafficSources.aiUserFetchOlderCountUntil }).from(trafficSources).where(eq(trafficSources.id, client.sourceId)).get()?.until ?? null;
3359
3683
  const rows = tx.select().from(table).where(and(
3360
3684
  eq(table.projectId, client.projectId),
3361
3685
  eq(table.sourceId, client.sourceId),
@@ -3365,38 +3689,71 @@ async function reassessAgentRequests(db, opts) {
3365
3689
  ne(table.trust, AgentTrustLevels.verified)
3366
3690
  )).all();
3367
3691
  for (const row of rows) {
3368
- const probe = isScannerPath(row.path);
3692
+ const probe = isScannerPath(row.path, { browser: isBrowserAgentId(row.agentId) });
3369
3693
  const at = Date.parse(row.ts);
3370
3694
  if (!probe && !probes.some((t) => Math.abs(at - t) <= SCANNER_BURST_WINDOW_MS)) continue;
3695
+ if (ctx.dryRun) {
3696
+ result.removed++;
3697
+ previewed.add(row.id);
3698
+ continue;
3699
+ }
3700
+ if (!removeStoredAgentRequest(tx, row)) continue;
3371
3701
  result.removed++;
3372
- if (opts.dryRun) continue;
3373
- tx.delete(table).where(eq(table.id, row.id)).run();
3374
- tx.update(agentJourneyCaptureDays).set({ storedEvents: sql`max(${agentJourneyCaptureDays.storedEvents} - 1, 0)` }).where(and(
3375
- eq(agentJourneyCaptureDays.projectId, row.projectId),
3376
- eq(agentJourneyCaptureDays.sourceId, row.sourceId),
3377
- eq(agentJourneyCaptureDays.day, row.ts.slice(0, 10))
3378
- )).run();
3379
- if (!probe) moveAgentHitToBurst(tx, row, opts.now);
3702
+ if (!probe && wasCountedAsHit(row, olderCountUntil)) moveAgentHitToBurst(tx, row, ctx.now);
3380
3703
  }
3381
- }, { behavior: "immediate" });
3704
+ });
3382
3705
  await yieldToEventLoop();
3383
3706
  }
3384
- return result;
3707
+ return { result, previewed };
3708
+ }
3709
+ async function removeBrowserAgentPageResources(db, ctx, previewed) {
3710
+ if (BROWSER_AGENT_BOT_IDS.length === 0) return 0;
3711
+ const table = agentJourneyEvents;
3712
+ let removed = 0;
3713
+ const pages = rowidPages(ctx, { bound: ctx.bounds.agentRequests }, (range) => db.select({ rowid: sql`rowid`, id: table.id, projectId: table.projectId, sourceId: table.sourceId, ts: table.ts, method: table.method, path: table.path, status: table.status }).from(table).where(and(range, inArray(table.agentId, [...BROWSER_AGENT_BOT_IDS]), projectScope(table.projectId, ctx.projectIds))).orderBy(sql`rowid`).limit(BATCH_SIZE).all());
3714
+ for await (const rows of pages) {
3715
+ const leftOut = rows.filter((row) => !previewed.has(row.id) && !keepsBrowserAgentJourneyRequest({ method: row.method, path: row.path, queryString: null, status: row.status }));
3716
+ if (ctx.dryRun) {
3717
+ removed += leftOut.length;
3718
+ continue;
3719
+ }
3720
+ if (leftOut.length === 0) continue;
3721
+ inBatch(db, ctx, (tx) => {
3722
+ for (const row of leftOut) {
3723
+ if (removeStoredAgentRequest(tx, row)) removed++;
3724
+ }
3725
+ });
3726
+ }
3727
+ return removed;
3385
3728
  }
3386
3729
  async function reclassifyStoredTraffic(db, opts = {}) {
3387
- const shared = {
3730
+ const ctx = {
3388
3731
  projectIds: opts.projectIds,
3389
3732
  dryRun: opts.dryRun === true,
3390
3733
  now: opts.now ?? (/* @__PURE__ */ new Date()).toISOString(),
3391
- shouldStop: opts.shouldStop ?? (() => false)
3734
+ shouldStop: opts.shouldStop ?? (() => false),
3735
+ allowVerificationLoss: opts.allowVerificationLoss === true,
3736
+ bounds: {
3737
+ samples: lastRowid(db, rawEventSamples),
3738
+ unrecognized: lastRowid(db, unrecognizedAgentEventsHourly),
3739
+ crawlers: lastRowid(db, crawlerEventsHourly),
3740
+ userFetch: lastRowid(db, aiUserFetchEventsHourly),
3741
+ agentRequests: lastRowid(db, agentJourneyEvents)
3742
+ },
3743
+ liveProjectIds: new Set(db.select({ id: projects.id }).from(projects).all().map((row) => row.id)),
3744
+ liveSourceIds: new Set(db.select({ id: trafficSources.id }).from(trafficSources).all().map((row) => row.id)),
3745
+ orphans: 0
3392
3746
  };
3393
- const samples = await reclassifyUnknownSamples(db, shared);
3394
- const unrecognized = shared.shouldStop() ? { examined: 0, moved: 0, movedHits: 0, renamed: 0, removed: 0, byBot: {} } : await reclassifyUnrecognizedRows(db, shared);
3395
- const agentHits = shared.shouldStop() ? { examined: 0, moved: 0, movedHits: 0 } : await reassessAgentHits(db, shared);
3396
- const agentRequests = shared.shouldStop() ? { examined: 0, probes: 0, removed: 0 } : await reassessAgentRequests(db, shared);
3397
- const journeys = shared.shouldStop() ? { visitors: 0, visitorsRemoved: 0, visitsRemoved: 0, visitsRelanded: 0 } : correctBackgroundCallJourneys(db, shared);
3398
- const journeyMerges = shared.shouldStop() ? { visitorsMerged: 0, visitsJoined: 0 } : mergeSplitJourneyVisitors(db, shared);
3399
- return { dryRun: shared.dryRun, samples, unrecognized, agentHits, agentRequests, journeys, journeyMerges };
3747
+ const samples = await reclassifyUnknownSamples(db, ctx);
3748
+ const unrecognized = await reclassifyUnrecognizedRows(db, ctx);
3749
+ const crawlers = await rekeyCrawlerHours(db, ctx);
3750
+ const agentHits = await reassessAgentHits(db, ctx);
3751
+ const assessed = await reassessAgentRequests(db, ctx);
3752
+ const pageResources = await removeBrowserAgentPageResources(db, ctx, assessed.previewed);
3753
+ const agentRequests = { ...assessed.result, pageResources };
3754
+ const journeys = ctx.shouldStop() ? { visitors: 0, visitorsRemoved: 0, visitsRemoved: 0, visitsRelanded: 0 } : ctx.dryRun ? db.transaction(() => correctBackgroundCallJourneys(db, ctx), { behavior: "deferred" }) : correctBackgroundCallJourneys(db, ctx);
3755
+ const journeyMerges = ctx.shouldStop() ? { visitorsMerged: 0, visitsJoined: 0 } : mergeSplitJourneyVisitors(db, ctx);
3756
+ return { dryRun: ctx.dryRun, samples, unrecognized, crawlers, agentHits, agentRequests, journeys, journeyMerges, orphans: ctx.orphans };
3400
3757
  }
3401
3758
  async function reclassifyStoredTrafficIfRulesChanged(db, opts = {}) {
3402
3759
  const fingerprint = trafficClassificationFingerprint();
@@ -3404,21 +3761,28 @@ async function reclassifyStoredTrafficIfRulesChanged(db, opts = {}) {
3404
3761
  if (state?.fingerprint === fingerprint) return { ran: false };
3405
3762
  const now = opts.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
3406
3763
  const shouldStop = opts.shouldStop ?? (() => false);
3407
- const result = await reclassifyStoredTraffic(db, { now: now(), shouldStop });
3764
+ const startedAt = now();
3765
+ const result = await reclassifyStoredTraffic(db, { now: startedAt, shouldStop });
3408
3766
  if (shouldStop()) return { ran: false };
3767
+ const olderCountEnds = countsBrowserAgentsAsRecorded(state?.resultJson) ? /* @__PURE__ */ new Map() : lastBrowserAgentHourEnds(db);
3409
3768
  const completedAt = now();
3410
- db.insert(trafficReclassificationState).values({ id: STATE_ID, fingerprint, completedAt, resultJson: { ...result } }).onConflictDoUpdate({
3411
- target: trafficReclassificationState.id,
3412
- set: { fingerprint, completedAt, resultJson: { ...result } }
3413
- }).run();
3414
- return { ran: true, result };
3769
+ const resultJson = { ...result, [BROWSER_AGENT_REQUEST_RULES_KEY]: BROWSER_AGENT_REQUEST_RULES };
3770
+ const olderCountsMarked = db.transaction((tx) => {
3771
+ const marked = markUserFetchOlderCounts(tx, olderCountEnds, startedAt);
3772
+ tx.insert(trafficReclassificationState).values({ id: STATE_ID, fingerprint, completedAt, resultJson }).onConflictDoUpdate({
3773
+ target: trafficReclassificationState.id,
3774
+ set: { fingerprint, completedAt, resultJson }
3775
+ }).run();
3776
+ return marked;
3777
+ }, { behavior: "immediate" });
3778
+ return { ran: true, result, olderCountsMarked };
3415
3779
  }
3416
3780
  function startTrafficReclassification(opts) {
3417
3781
  let stopped = false;
3418
3782
  const timer = setTimeout(() => {
3419
3783
  reclassifyStoredTrafficIfRulesChanged(opts.db, { shouldStop: () => stopped }).then((outcome) => {
3420
3784
  if (!outcome.ran || !outcome.result) return;
3421
- logReclassification(outcome.result);
3785
+ logReclassification(outcome.result, outcome.olderCountsMarked ?? 0);
3422
3786
  }).then(() => {
3423
3787
  if (stopped) return;
3424
3788
  try {
@@ -3438,8 +3802,8 @@ function startTrafficReclassification(opts) {
3438
3802
  clearTimeout(timer);
3439
3803
  };
3440
3804
  }
3441
- function logReclassification(result) {
3442
- const { samples, unrecognized, agentHits, agentRequests, journeys, journeyMerges } = result;
3805
+ function logReclassification(result, olderCountsMarked) {
3806
+ const { samples, unrecognized, crawlers, agentHits, agentRequests, journeys, journeyMerges } = result;
3443
3807
  log.info("traffic-reclassify.completed", {
3444
3808
  samplesReclassified: samples.reclassified,
3445
3809
  samplesCounted: samples.counted,
@@ -3448,14 +3812,32 @@ function logReclassification(result) {
3448
3812
  unrecognizedMovedHits: unrecognized.movedHits,
3449
3813
  unrecognizedRenamed: unrecognized.renamed,
3450
3814
  unrecognizedRemoved: unrecognized.removed,
3815
+ crawlerRowsMoved: crawlers.moved,
3816
+ crawlerHitsMoved: crawlers.movedHits,
3817
+ crawlerRowsToUserFetch: crawlers.toUserFetch,
3818
+ crawlerRowsToUnrecognized: crawlers.toUnrecognized,
3819
+ crawlerRowsRemoved: crawlers.removed,
3820
+ crawlerHitsUnverified: crawlers.unverifiedHits,
3821
+ crawlerRowsUnknownBot: crawlers.unknownBot,
3822
+ crawlerSamplesRelabeled: crawlers.samplesRelabeled,
3451
3823
  agentHitsMoved: agentHits.movedHits,
3452
3824
  agentRequestsRemoved: agentRequests.removed,
3825
+ agentPageResourcesRemoved: agentRequests.pageResources,
3453
3826
  journeyVisitorsRemoved: journeys.visitorsRemoved,
3454
3827
  journeyVisitsRemoved: journeys.visitsRemoved,
3455
3828
  journeyVisitsRelanded: journeys.visitsRelanded,
3456
3829
  journeyVisitorsMerged: journeyMerges.visitorsMerged,
3457
- journeyVisitsJoined: journeyMerges.visitsJoined
3830
+ journeyVisitsJoined: journeyMerges.visitsJoined,
3831
+ olderCountsMarked,
3832
+ orphans: result.orphans
3458
3833
  });
3834
+ if (crawlers.heldVerified > 0) {
3835
+ log.warn("traffic-reclassify.verified-moves-held", {
3836
+ rows: crawlers.heldVerified,
3837
+ hits: crawlers.heldVerifiedHits,
3838
+ preview: "canonry backfill traffic-classification --dry-run"
3839
+ });
3840
+ }
3459
3841
  }
3460
3842
 
3461
3843
  export {