@canonry/canonry 7.51.5 → 7.52.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 (141) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +8 -0
  2. package/assets/assets/{AccessControls-B5TqDgeq.js → AccessControls-CteIuEGI.js} +1 -1
  3. package/assets/assets/{AuditHistoryPanel-DgxiizOW.js → AuditHistoryPanel-DqJGiLsf.js} +1 -1
  4. package/assets/assets/{BacklinksPage-Ay6pdphx.js → BacklinksPage-DotWEPQt.js} +1 -1
  5. package/assets/assets/{HistoryPage-B11eFH21.js → HistoryPage-aOd198dT.js} +1 -1
  6. package/assets/assets/MeasurementPropertyPage-CuaKVK8x.js +4 -0
  7. package/assets/assets/{ProjectPage-DoY0hftd.js → ProjectPage-O9oufMgi.js} +4 -4
  8. package/assets/assets/{RunsPage-BPBmuQAS.js → RunsPage-DIXMrc-N.js} +1 -1
  9. package/assets/assets/{SettingsPage-ClKnP8xy.js → SettingsPage-BuGb6AGa.js} +1 -1
  10. package/assets/assets/SiteHealthSection-CweaKjCo.js +2 -0
  11. package/assets/assets/TrafficPage-B7MaQalp.js +40 -0
  12. package/assets/assets/{TrafficSourceDetailPage-DQu0YNt2.js → TrafficSourceDetailPage-BPtjnF9s.js} +1 -1
  13. package/assets/assets/{card-DYMyvhB9.js → card-DoV-8Txo.js} +1 -1
  14. package/assets/assets/{extract-error-message-BRM1I_3L.js → extract-error-message-DKQJJlZ-.js} +1 -1
  15. package/assets/assets/{format-helpers-DrkFERj3.js → format-helpers-BWnMmkiO.js} +1 -1
  16. package/assets/assets/index-Z63c4PeO.js +39 -0
  17. package/assets/assets/{query-client-gRFnU4VF.js → query-client-vB35tVTz.js} +1 -1
  18. package/assets/assets/{react-query-lH82FULK.js → react-query-BI0567qs.js} +1 -1
  19. package/assets/assets/{react-sigma_core.esm.min-D09H4byP.js → react-sigma_core.esm.min-hGyOC4V_.js} +1 -1
  20. package/assets/assets/{service-Cx0HSnE9.js → service-c4YvpVKX.js} +1 -1
  21. package/assets/index.html +6 -6
  22. package/dist/ads-MREK2AGL.js +544 -0
  23. package/dist/agent-4RUZ3MC4.js +70 -0
  24. package/dist/agent-ask-YLTYBEYH.js +139 -0
  25. package/dist/agent-conversations-QA6IKDGR.js +52 -0
  26. package/dist/agent-memory-MEQAJOB3.js +92 -0
  27. package/dist/agent-providers-AXYPDJHL.js +55 -0
  28. package/dist/agent-transcript-SMNQNYCD.js +77 -0
  29. package/dist/analytics-4OR64IGV.js +240 -0
  30. package/dist/apply-CQXCFXAH.js +175 -0
  31. package/dist/backfill-TMXCNVOB.js +41 -0
  32. package/dist/backlinks-6KFAQGYV.js +303 -0
  33. package/dist/bing-HFCACTAC.js +418 -0
  34. package/dist/bootstrap-SQVQXOJC.js +326 -0
  35. package/dist/cdp-IACL7EXU.js +162 -0
  36. package/dist/chunk-4MJYGB56.js +124 -0
  37. package/dist/chunk-5N6245R7.js +1160 -0
  38. package/dist/chunk-6BPZHNDC.js +617 -0
  39. package/dist/chunk-6GO5VVAC.js +15 -0
  40. package/dist/chunk-7244X3K6.js +609 -0
  41. package/dist/chunk-7XE2IRBG.js +204 -0
  42. package/dist/chunk-AOJU5LKX.js +8 -0
  43. package/dist/chunk-AWCWIQAU.js +2686 -0
  44. package/dist/{chunk-JBZZEIM2.js → chunk-BBOHY2DQ.js} +2 -13
  45. package/dist/{chunk-AZFPA7JV.js → chunk-BU3VAG5J.js} +6 -4
  46. package/dist/{chunk-4YCGZGA3.js → chunk-BYOK6Z4F.js} +2 -2
  47. package/dist/chunk-DSNSD5J3.js +971 -0
  48. package/dist/chunk-EGIZNSDA.js +94 -0
  49. package/dist/chunk-ELCLGWUT.js +83 -0
  50. package/dist/chunk-FC4XND45.js +38 -0
  51. package/dist/chunk-GNKOBKPW.js +58 -0
  52. package/dist/chunk-HEGXGCGL.js +524 -0
  53. package/dist/chunk-I6KNMZ77.js +232 -0
  54. package/dist/{chunk-HLVEB5TB.js → chunk-IIOEAJTV.js} +7 -5
  55. package/dist/chunk-ILDT4LPB.js +1273 -0
  56. package/dist/chunk-JY3RLZGB.js +30 -0
  57. package/dist/{chunk-PLYJX67A.js → chunk-K5I45PZI.js} +8084 -13939
  58. package/dist/chunk-KXAOMTXN.js +1034 -0
  59. package/dist/chunk-LK2BG6EX.js +145 -0
  60. package/dist/chunk-MJNUSPO4.js +15 -0
  61. package/dist/chunk-MKAC7HKH.js +9178 -0
  62. package/dist/chunk-MLKGABMK.js +9 -0
  63. package/dist/{chunk-SFMWHPMX.js → chunk-O4RMPA6H.js} +13765 -13737
  64. package/dist/chunk-O77IBNVO.js +8264 -0
  65. package/dist/chunk-OFL4PTYU.js +644 -0
  66. package/dist/chunk-QLPLENDT.js +133 -0
  67. package/dist/chunk-R2J4SNKF.js +78 -0
  68. package/dist/{chunk-KEATAHXH.js → chunk-RVUCY4ZV.js} +358 -581
  69. package/dist/chunk-SNFBJKAW.js +530 -0
  70. package/dist/chunk-TALC5DX5.js +420 -0
  71. package/dist/chunk-TSENU4GG.js +18 -0
  72. package/dist/{chunk-HAHXPJQ5.js → chunk-V5D4XNWV.js} +16 -1684
  73. package/dist/chunk-VJWDBFSL.js +69 -0
  74. package/dist/chunk-XEBKF4N5.js +8 -0
  75. package/dist/chunk-Y4GK7GCV.js +15376 -0
  76. package/dist/{chunk-A3WSAAQS.js → chunk-YSEC6TIB.js} +7917 -33199
  77. package/dist/chunk-Z7IUAJOF.js +13 -0
  78. package/dist/citations-NSBBWRZ4.js +106 -0
  79. package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-OFWJMNMD.js} +5 -3
  80. package/dist/cli-commands-WVBL337U.js +19 -0
  81. package/dist/cli.js +35 -29
  82. package/dist/competitor-V4OHORBC.js +561 -0
  83. package/dist/content-RUXRI5IC.js +257 -0
  84. package/dist/dashboard-JXB2YAQJ.js +71 -0
  85. package/dist/demo-55ZNUOXU.js +75 -0
  86. package/dist/{demo-server-GIWDJGJX.js → demo-server-XO7PHM4I.js} +22 -9
  87. package/dist/discover-JJQ564HS.js +372 -0
  88. package/dist/discover-eval-KLEKZ6U4.js +282 -0
  89. package/dist/doctor-JAMQZCMZ.js +152 -0
  90. package/dist/evidence-YRSB7GFE.js +57 -0
  91. package/dist/export-cmd-MHML4OYU.js +49 -0
  92. package/dist/ga-LSXPE2MN.js +911 -0
  93. package/dist/gbp-RMKMLOC7.js +370 -0
  94. package/dist/google-JQ4T6JTQ.js +946 -0
  95. package/dist/google-marketing-J6SEODYC.js +403 -0
  96. package/dist/health-cmd-MV2JM2C3.js +64 -0
  97. package/dist/history-SRRH7A2E.js +90 -0
  98. package/dist/index.d.ts +43 -4
  99. package/dist/index.js +29 -6
  100. package/dist/init-ZJZFUERV.js +432 -0
  101. package/dist/insights-PMMGNWZH.js +63 -0
  102. package/dist/intelligence-service-KCSU6ZUJ.js +15 -0
  103. package/dist/keys-TS7NZANS.js +116 -0
  104. package/dist/keyword-VNCKDUGC.js +164 -0
  105. package/dist/logs-VH3WOTZJ.js +30 -0
  106. package/dist/mcp-DG2RROB3.js +14 -0
  107. package/dist/mcp.js +14 -5
  108. package/dist/measurement-plan-4T35TUGG.js +42 -0
  109. package/dist/notify-BWHUSKL7.js +125 -0
  110. package/dist/organic-evidence-QX4SXXJP.js +53 -0
  111. package/dist/overview-7IHUTKUV.js +213 -0
  112. package/dist/project-JXLSWDE2.js +460 -0
  113. package/dist/query-S75EL25H.js +211 -0
  114. package/dist/research-KFTV3IP4.js +200 -0
  115. package/dist/results-export-GTKVBU34.js +27 -0
  116. package/dist/run-26HDIRHF.js +31 -0
  117. package/dist/schedule-N6G4SVHQ.js +177 -0
  118. package/dist/search-MI32EPYM.js +42 -0
  119. package/dist/serve-XLGE42AG.js +598 -0
  120. package/dist/session-W5DXWIYM.js +47 -0
  121. package/dist/settings-T7WI2UVE.js +107 -0
  122. package/dist/skills-F3WPKPTK.js +33 -0
  123. package/dist/snapshot-PD3EAVEX.js +538 -0
  124. package/dist/src-XDUXMJC3.js +316 -0
  125. package/dist/status-PUH7JFZ4.js +126 -0
  126. package/dist/support-ARF4HER7.js +24 -0
  127. package/dist/technical-aeo-AUFWWJIP.js +625 -0
  128. package/dist/telemetry-XBYT7G2K.js +118 -0
  129. package/dist/tools-GVHIRWSN.js +41 -0
  130. package/dist/traffic-B3HW2ZWG.js +1295 -0
  131. package/dist/users-M5HNQZYI.js +170 -0
  132. package/dist/visibility-stats-Y7GJKMHN.js +241 -0
  133. package/dist/wordpress-GCIURYPN.js +600 -0
  134. package/package.json +1 -1
  135. package/assets/assets/MeasurementPropertyPage-1UYI7mzP.js +0 -4
  136. package/assets/assets/SiteHealthSection-PWjKMmEn.js +0 -2
  137. package/assets/assets/TrafficPage-DkfGiJXR.js +0 -40
  138. package/assets/assets/index-CG1Jox52.js +0 -39
  139. package/dist/chunk-4QQYYRHV.js +0 -23082
  140. package/dist/cli-commands-FOJR3HHU.js +0 -15
  141. package/dist/intelligence-service-XQCNWAPL.js +0 -9
@@ -0,0 +1,971 @@
1
+ import {
2
+ OPENAI_RETRIEVAL_CONTRACT,
3
+ reparseStoredResult,
4
+ reparseStoredResult2,
5
+ reparseStoredResult3,
6
+ reparseStoredResult4,
7
+ reparseStoredResult5,
8
+ resolveStoredApiResponse
9
+ } from "./chunk-AWCWIQAU.js";
10
+ import {
11
+ loadConfig
12
+ } from "./chunk-OFL4PTYU.js";
13
+ import {
14
+ isMachineFormat
15
+ } from "./chunk-HGMYEDAQ.js";
16
+ import {
17
+ determineCitationState
18
+ } from "./chunk-FC4XND45.js";
19
+ import {
20
+ backfillProjectAnswerMentions,
21
+ competitorIdentityColumns,
22
+ createRunCompetitorResolver,
23
+ readMarketCompetitorNames,
24
+ refreshSnapshotMentionIdentity
25
+ } from "./chunk-YSEC6TIB.js";
26
+ import {
27
+ classifyAiUserFetch,
28
+ classifyCrawler
29
+ } from "./chunk-Y4GK7GCV.js";
30
+ import {
31
+ aiUserFetchEventsHourly,
32
+ auditLog,
33
+ competitors,
34
+ crawlerEventsHourly,
35
+ createClient,
36
+ gaAiReferrals,
37
+ gaTrafficSnapshots,
38
+ migrate,
39
+ parseJsonColumn,
40
+ projects,
41
+ querySnapshots,
42
+ rawEventSamples,
43
+ runs
44
+ } from "./chunk-MKAC7HKH.js";
45
+ import {
46
+ ProviderNames,
47
+ RetrievalContracts,
48
+ RunKinds,
49
+ TrafficEventConfidences,
50
+ TrafficEventKinds,
51
+ TrafficEvidenceKinds,
52
+ TrafficSourceTypes,
53
+ computeCompetitorOverlap,
54
+ countsAsMention,
55
+ determineAnswerMentioned,
56
+ effectiveBrandNames,
57
+ effectiveDomains,
58
+ extractRecommendedCompetitors,
59
+ normalizeUrlPath
60
+ } from "./chunk-O4RMPA6H.js";
61
+
62
+ // src/commands/backfill.ts
63
+ import { setImmediate as yieldToEventLoop } from "timers/promises";
64
+ import { and, asc, desc, eq, gt, inArray, isNull, lte, sql } from "drizzle-orm";
65
+ var SNAPSHOT_BATCH_SIZE = 500;
66
+ var PATH_REPAIR_PAGE_SIZE = 128;
67
+ async function backfillAnswerVisibilityCommand(opts) {
68
+ const config = loadConfig();
69
+ const db = createClient(config.database);
70
+ migrate(db);
71
+ const projectFilter = opts?.project?.trim();
72
+ const isDryRun = opts?.dryRun === true;
73
+ const scopedProjects = projectFilter ? db.select().from(projects).where(eq(projects.name, projectFilter)).all() : db.select().from(projects).all();
74
+ let examined = 0;
75
+ let updated = 0;
76
+ let wouldUpdate = 0;
77
+ let mentioned = 0;
78
+ let reparsed = 0;
79
+ let providerErrors = 0;
80
+ let retrievalRelabeled = 0;
81
+ if (scopedProjects.length > 0) {
82
+ const runRows = projectFilter ? db.select({ id: runs.id, projectId: runs.projectId, planVersionId: runs.measurementPlanVersionId }).from(runs).where(and(
83
+ eq(runs.kind, RunKinds["answer-visibility"]),
84
+ inArray(runs.projectId, scopedProjects.map((project) => project.id))
85
+ )).all() : db.select({ id: runs.id, projectId: runs.projectId, planVersionId: runs.measurementPlanVersionId }).from(runs).where(eq(runs.kind, RunKinds["answer-visibility"])).all();
86
+ const planVersionByRun = new Map(runRows.map((run) => [run.id, run.planVersionId]));
87
+ const runIdsByProject = /* @__PURE__ */ new Map();
88
+ for (const run of runRows) {
89
+ const existing = runIdsByProject.get(run.projectId);
90
+ if (existing) existing.push(run.id);
91
+ else runIdsByProject.set(run.projectId, [run.id]);
92
+ }
93
+ for (const project of scopedProjects) {
94
+ const competitorsForRun = createRunCompetitorResolver(db, db.select(competitorIdentityColumns).from(competitors).where(eq(competitors.projectId, project.id)).orderBy(competitors.domain).all(), readMarketCompetitorNames(db, project.id));
95
+ const runIds = runIdsByProject.get(project.id) ?? [];
96
+ if (runIds.length === 0) continue;
97
+ const projectDomains = effectiveDomains({
98
+ canonicalDomain: project.canonicalDomain,
99
+ ownedDomains: project.ownedDomains
100
+ });
101
+ const projectBrandNames = effectiveBrandNames({
102
+ displayName: project.displayName,
103
+ aliases: project.aliases
104
+ });
105
+ for (let offset = 0; offset < runIds.length; offset += SNAPSHOT_BATCH_SIZE) {
106
+ const batchRunIds = runIds.slice(offset, offset + SNAPSHOT_BATCH_SIZE);
107
+ const snapshotRows = db.select({
108
+ id: querySnapshots.id,
109
+ runId: querySnapshots.runId,
110
+ executionId: querySnapshots.measurementExecutionId,
111
+ provider: querySnapshots.provider,
112
+ citationState: querySnapshots.citationState,
113
+ answerMentioned: querySnapshots.answerMentioned,
114
+ mentionIdentity: querySnapshots.mentionIdentity,
115
+ answerText: querySnapshots.answerText,
116
+ citedDomains: querySnapshots.citedDomains,
117
+ competitorOverlap: querySnapshots.competitorOverlap,
118
+ recommendedCompetitors: querySnapshots.recommendedCompetitors,
119
+ rawResponse: querySnapshots.rawResponse,
120
+ retrievalStatus: querySnapshots.retrievalStatus,
121
+ retrievalContract: querySnapshots.retrievalContract
122
+ }).from(querySnapshots).where(inArray(querySnapshots.runId, batchRunIds)).all();
123
+ const pendingUpdates = [];
124
+ const rewrittenIds = [];
125
+ for (const snapshot of snapshotRows) {
126
+ examined++;
127
+ const reparsedResult = reparseProviderSnapshot(snapshot.provider, snapshot.rawResponse);
128
+ if (reparsedResult) reparsed++;
129
+ if (reparsedResult?.providerError) providerErrors++;
130
+ const answerText = reparsedResult?.answerText ?? snapshot.answerText ?? "";
131
+ const textChanged = (snapshot.answerText ?? "") !== answerText;
132
+ const nextValue = countsAsMention(
133
+ determineAnswerMentioned(answerText, projectBrandNames, projectDomains),
134
+ textChanged ? null : snapshot.mentionIdentity
135
+ );
136
+ if (nextValue) mentioned++;
137
+ const nextPatch = {};
138
+ if (snapshot.answerMentioned !== nextValue) {
139
+ nextPatch.answerMentioned = nextValue;
140
+ }
141
+ if (textChanged) {
142
+ nextPatch.answerText = answerText;
143
+ rewrittenIds.push(snapshot.id);
144
+ }
145
+ if (reparsedResult) {
146
+ const normalized = {
147
+ provider: snapshot.provider,
148
+ answerText,
149
+ citedDomains: reparsedResult.citedDomains,
150
+ groundingSources: reparsedResult.groundingSources,
151
+ searchQueries: reparsedResult.searchQueries,
152
+ // Only feeds the citation/mention helpers below, which ignore
153
+ // it. Retrieval is written back solely by the narrow OpenAI
154
+ // contract correction after this block.
155
+ retrievalStatus: "unknown"
156
+ };
157
+ const nextCitationState = determineCitationState(normalized, projectDomains);
158
+ const nextCitedDomains = reparsedResult.citedDomains;
159
+ const runCompetitors = competitorsForRun(planVersionByRun.get(snapshot.runId), snapshot.executionId);
160
+ const nextCompetitorOverlap = computeCompetitorOverlap(normalized, runCompetitors.domains, runCompetitors.aliases);
161
+ const nextRecommendedCompetitors = extractRecommendedCompetitors(
162
+ normalized.answerText,
163
+ projectDomains,
164
+ normalized.citedDomains,
165
+ runCompetitors.domains,
166
+ projectBrandNames,
167
+ runCompetitors.aliases
168
+ );
169
+ const nextRawResponse = stringifyStoredSnapshotEnvelope(
170
+ snapshot.rawResponse,
171
+ reparsedResult
172
+ );
173
+ if (snapshot.citationState !== nextCitationState) {
174
+ nextPatch.citationState = nextCitationState;
175
+ }
176
+ if (JSON.stringify(snapshot.citedDomains) !== JSON.stringify(nextCitedDomains)) {
177
+ nextPatch.citedDomains = nextCitedDomains;
178
+ }
179
+ if (JSON.stringify(snapshot.competitorOverlap) !== JSON.stringify(nextCompetitorOverlap)) {
180
+ nextPatch.competitorOverlap = nextCompetitorOverlap;
181
+ }
182
+ if (JSON.stringify(snapshot.recommendedCompetitors) !== JSON.stringify(nextRecommendedCompetitors)) {
183
+ nextPatch.recommendedCompetitors = nextRecommendedCompetitors;
184
+ }
185
+ if (snapshot.rawResponse !== nextRawResponse) {
186
+ nextPatch.rawResponse = nextRawResponse;
187
+ }
188
+ }
189
+ const retrievalCorrection = correctStoredOpenAIRetrieval(snapshot, reparsedResult);
190
+ if (retrievalCorrection) {
191
+ retrievalRelabeled++;
192
+ Object.assign(nextPatch, retrievalCorrection);
193
+ }
194
+ if (Object.keys(nextPatch).length > 0) {
195
+ pendingUpdates.push({ id: snapshot.id, patch: nextPatch });
196
+ }
197
+ }
198
+ if (pendingUpdates.length > 0) {
199
+ if (isDryRun) {
200
+ wouldUpdate += pendingUpdates.length;
201
+ } else {
202
+ db.transaction((tx) => {
203
+ for (const update of pendingUpdates) {
204
+ tx.update(querySnapshots).set(update.patch).where(eq(querySnapshots.id, update.id)).run();
205
+ }
206
+ if (rewrittenIds.length > 0) refreshSnapshotMentionIdentity(tx, rewrittenIds);
207
+ });
208
+ updated += pendingUpdates.length;
209
+ }
210
+ }
211
+ }
212
+ }
213
+ }
214
+ const result = {
215
+ project: projectFilter ?? null,
216
+ projects: scopedProjects.length,
217
+ examined,
218
+ updated,
219
+ mentioned,
220
+ reparsed,
221
+ providerErrors,
222
+ retrievalRelabeled
223
+ };
224
+ if (isDryRun) {
225
+ result.dryRun = true;
226
+ result.wouldUpdate = wouldUpdate;
227
+ }
228
+ if (isMachineFormat(opts?.format)) {
229
+ console.log(JSON.stringify(result, null, 2));
230
+ return;
231
+ }
232
+ console.log(`Answer visibility backfill ${isDryRun ? "preview" : "complete"}.
233
+ `);
234
+ if (projectFilter) {
235
+ console.log(` Project: ${projectFilter}`);
236
+ }
237
+ console.log(` Projects: ${scopedProjects.length}`);
238
+ console.log(` Examined: ${examined}`);
239
+ if (isDryRun) {
240
+ console.log(` Would update: ${wouldUpdate}`);
241
+ } else {
242
+ console.log(` Updated: ${updated}`);
243
+ }
244
+ console.log(` Mentioned: ${mentioned}`);
245
+ console.log(` Reparsed: ${reparsed}`);
246
+ console.log(` Errors: ${providerErrors}`);
247
+ console.log(` Relabeled: ${retrievalRelabeled} (OpenAI retrieval contract)`);
248
+ if (isDryRun) {
249
+ console.log(`
250
+ No DB writes performed. Re-run without --dry-run to apply.`);
251
+ }
252
+ }
253
+ function backfillNormalizedPaths(db, opts) {
254
+ return repairStoredPaths(db, gaTrafficSnapshots, opts);
255
+ }
256
+ async function repairStoredPaths(db, table, opts) {
257
+ const pageSize = opts?.pageSize ?? PATH_REPAIR_PAGE_SIZE;
258
+ const projectScope = opts?.projectId ? sql`+${table.projectId} = ${opts.projectId}` : void 0;
259
+ const lastId = db.select({ id: table.id }).from(table).where(projectScope).orderBy(desc(table.id)).limit(1).get()?.id;
260
+ if (lastId === void 0) return { examined: 0, updated: 0, unchanged: 0 };
261
+ let cursor;
262
+ let examined = 0;
263
+ let updated = 0;
264
+ for (; ; ) {
265
+ const rows = db.select({
266
+ id: table.id,
267
+ projectId: table.projectId,
268
+ landingPage: table.landingPage,
269
+ landingPageNormalized: table.landingPageNormalized
270
+ }).from(table).where(and(
271
+ projectScope,
272
+ lte(table.id, lastId),
273
+ cursor === void 0 ? void 0 : gt(table.id, cursor)
274
+ )).orderBy(asc(table.id)).limit(pageSize).all();
275
+ examined += rows.length;
276
+ const changes = rows.flatMap((row) => {
277
+ const next = normalizeUrlPath(row.landingPage);
278
+ return next === null || row.landingPageNormalized === next ? [] : [{ row, next }];
279
+ });
280
+ if (changes.length > 0) {
281
+ const written = db.transaction((tx) => {
282
+ let written2 = 0;
283
+ for (const { row, next } of changes) {
284
+ written2 += tx.update(table).set({ landingPageNormalized: next }).where(and(
285
+ eq(table.id, row.id),
286
+ eq(table.projectId, row.projectId),
287
+ eq(table.landingPage, row.landingPage),
288
+ row.landingPageNormalized === null ? isNull(table.landingPageNormalized) : eq(table.landingPageNormalized, row.landingPageNormalized)
289
+ )).run().changes;
290
+ }
291
+ return written2;
292
+ });
293
+ updated += written;
294
+ if (written < changes.length) opts?.onConflict?.();
295
+ }
296
+ if (rows.length < pageSize) break;
297
+ cursor = rows.at(-1).id;
298
+ if (cursor === lastId) break;
299
+ await yieldToEventLoop();
300
+ }
301
+ return { examined, updated, unchanged: examined - updated };
302
+ }
303
+ async function backfillNormalizedPathsCommand(opts) {
304
+ const config = loadConfig();
305
+ const db = createClient(config.database);
306
+ migrate(db);
307
+ const projectFilter = opts?.project?.trim();
308
+ let projectId;
309
+ if (projectFilter) {
310
+ const project = db.select({ id: projects.id }).from(projects).where(eq(projects.name, projectFilter)).get();
311
+ if (!project) {
312
+ const result2 = {
313
+ project: projectFilter,
314
+ examined: 0,
315
+ updated: 0,
316
+ unchanged: 0
317
+ };
318
+ if (isMachineFormat(opts?.format)) {
319
+ console.log(JSON.stringify(result2, null, 2));
320
+ return;
321
+ }
322
+ console.log(`Backfill normalized-paths: project "${projectFilter}" not found.`);
323
+ return;
324
+ }
325
+ projectId = project.id;
326
+ }
327
+ const { examined, updated, unchanged } = await backfillNormalizedPaths(db, { projectId });
328
+ const result = {
329
+ project: projectFilter ?? null,
330
+ examined,
331
+ updated,
332
+ unchanged
333
+ };
334
+ if (isMachineFormat(opts?.format)) {
335
+ console.log(JSON.stringify(result, null, 2));
336
+ return;
337
+ }
338
+ console.log("Normalized-path backfill complete.\n");
339
+ if (projectFilter) console.log(` Project: ${projectFilter}`);
340
+ console.log(` Examined: ${examined}`);
341
+ console.log(` Updated: ${updated}`);
342
+ console.log(` Unchanged: ${unchanged}`);
343
+ }
344
+ function backfillAiReferralPaths(db, opts) {
345
+ return repairStoredPaths(db, gaAiReferrals, opts);
346
+ }
347
+ async function backfillAiReferralPathsCommand(opts) {
348
+ const config = loadConfig();
349
+ const db = createClient(config.database);
350
+ migrate(db);
351
+ const projectFilter = opts?.project?.trim();
352
+ let projectId;
353
+ if (projectFilter) {
354
+ const project = db.select({ id: projects.id }).from(projects).where(eq(projects.name, projectFilter)).get();
355
+ if (!project) {
356
+ const result2 = {
357
+ project: projectFilter,
358
+ examined: 0,
359
+ updated: 0,
360
+ unchanged: 0
361
+ };
362
+ if (isMachineFormat(opts?.format)) {
363
+ console.log(JSON.stringify(result2, null, 2));
364
+ return;
365
+ }
366
+ console.log(`Backfill ai-referral-paths: project "${projectFilter}" not found.`);
367
+ return;
368
+ }
369
+ projectId = project.id;
370
+ }
371
+ const { examined, updated, unchanged } = await backfillAiReferralPaths(db, { projectId });
372
+ const result = {
373
+ project: projectFilter ?? null,
374
+ examined,
375
+ updated,
376
+ unchanged
377
+ };
378
+ if (isMachineFormat(opts?.format)) {
379
+ console.log(JSON.stringify(result, null, 2));
380
+ return;
381
+ }
382
+ console.log("AI referral landing-page backfill complete.\n");
383
+ if (projectFilter) console.log(` Project: ${projectFilter}`);
384
+ console.log(` Examined: ${examined}`);
385
+ console.log(` Updated: ${updated}`);
386
+ console.log(` Unchanged: ${unchanged}`);
387
+ }
388
+ async function backfillAnswerMentionsCommand(opts) {
389
+ const config = loadConfig();
390
+ const db = createClient(config.database);
391
+ migrate(db);
392
+ const projectFilter = opts?.project?.trim();
393
+ const isDryRun = opts?.dryRun === true;
394
+ const scopedProjects = projectFilter ? db.select().from(projects).where(eq(projects.name, projectFilter)).all() : db.select().from(projects).all();
395
+ let examined = 0;
396
+ let updated = 0;
397
+ let wouldUpdate = 0;
398
+ let mentioned = 0;
399
+ for (const project of scopedProjects) {
400
+ const result2 = backfillProjectAnswerMentions(db, project.id, { dryRun: isDryRun });
401
+ examined += result2.examined;
402
+ updated += result2.updated;
403
+ wouldUpdate += result2.wouldUpdate ?? 0;
404
+ mentioned += result2.mentioned;
405
+ }
406
+ const result = {
407
+ project: projectFilter ?? null,
408
+ projects: scopedProjects.length,
409
+ examined,
410
+ updated,
411
+ mentioned
412
+ };
413
+ if (isDryRun) {
414
+ result.dryRun = true;
415
+ result.wouldUpdate = wouldUpdate;
416
+ }
417
+ if (isMachineFormat(opts?.format)) {
418
+ console.log(JSON.stringify(result, null, 2));
419
+ return;
420
+ }
421
+ console.log(`Answer mentions backfill ${isDryRun ? "preview" : "complete"}.
422
+ `);
423
+ if (projectFilter) console.log(` Project: ${projectFilter}`);
424
+ console.log(` Projects: ${scopedProjects.length}`);
425
+ console.log(` Examined: ${examined}`);
426
+ if (isDryRun) {
427
+ console.log(` Would update: ${wouldUpdate}`);
428
+ } else {
429
+ console.log(` Updated: ${updated}`);
430
+ }
431
+ console.log(` Mentioned: ${mentioned}`);
432
+ if (isDryRun) {
433
+ console.log(`
434
+ No DB writes performed. Re-run without --dry-run to apply.`);
435
+ }
436
+ }
437
+ async function backfillInsightsCommand(project, opts) {
438
+ const { IntelligenceService } = await import("./intelligence-service-KCSU6ZUJ.js");
439
+ const config = loadConfig();
440
+ const db = createClient(config.database);
441
+ migrate(db);
442
+ const service = new IntelligenceService(db);
443
+ const isJson = isMachineFormat(opts?.format);
444
+ const isDryRun = opts?.dryRun === true;
445
+ if (!isJson) {
446
+ const scope = opts?.since ? ` (since ${opts.since})` : "";
447
+ const mode = isDryRun ? " [DRY RUN \u2014 no writes]" : "";
448
+ process.stderr.write(`Backfilling insights for "${project}"${scope}${mode}...
449
+ `);
450
+ }
451
+ const result = service.backfill(project, {
452
+ fromRunId: opts?.fromRun,
453
+ toRunId: opts?.toRun,
454
+ since: opts?.since,
455
+ dryRun: isDryRun
456
+ }, (info) => {
457
+ if (!isJson) {
458
+ process.stderr.write(` [${info.index}/${info.total}] ${info.runId} \u2014 ${info.insights} insights
459
+ `);
460
+ }
461
+ });
462
+ const output = {
463
+ project,
464
+ processed: result.processed,
465
+ skipped: result.skipped,
466
+ totalInsights: result.totalInsights
467
+ };
468
+ if (result.dryRun) {
469
+ output.dryRun = true;
470
+ output.delta = result.delta;
471
+ }
472
+ if (isJson) {
473
+ console.log(JSON.stringify(output, null, 2));
474
+ return;
475
+ }
476
+ console.log(`
477
+ Backfill ${isDryRun ? "preview" : "complete"}.`);
478
+ console.log(` Processed: ${result.processed}`);
479
+ console.log(` Skipped: ${result.skipped}`);
480
+ console.log(` Insights: ${result.totalInsights}`);
481
+ if (result.delta) {
482
+ console.log(` Delta: -${result.delta.wouldDelete} existing +${result.delta.wouldCreate} new (net ${result.delta.netChange >= 0 ? "+" : ""}${result.delta.netChange})`);
483
+ console.log(` No DB writes performed. Re-run without --dry-run to apply.`);
484
+ }
485
+ }
486
+ function replayQueryAuditLog(events) {
487
+ const active = [];
488
+ for (const ev of events) {
489
+ let diff;
490
+ try {
491
+ diff = ev.diff ? JSON.parse(ev.diff) : {};
492
+ } catch {
493
+ continue;
494
+ }
495
+ if (ev.action === "keywords.appended" || ev.action === "queries.appended") {
496
+ const added = Array.isArray(diff.added) ? diff.added : [];
497
+ for (const q of added) {
498
+ active.push({ text: q, addedAt: ev.createdAt, deletedAt: null });
499
+ }
500
+ } else if (ev.action === "keywords.deleted" || ev.action === "queries.deleted") {
501
+ const deleted = Array.isArray(diff.deleted) ? diff.deleted : [];
502
+ for (const q of deleted) {
503
+ for (let i = active.length - 1; i >= 0; i--) {
504
+ if (active[i].text === q && active[i].deletedAt === null) {
505
+ active[i].deletedAt = ev.createdAt;
506
+ break;
507
+ }
508
+ }
509
+ }
510
+ } else if (ev.action === "queries.replaced") {
511
+ const newSet = Array.isArray(diff.queries) ? diff.queries : [];
512
+ for (const e of active) {
513
+ if (e.deletedAt === null) e.deletedAt = ev.createdAt;
514
+ }
515
+ for (const q of newSet) {
516
+ active.push({ text: q, addedAt: ev.createdAt, deletedAt: null });
517
+ }
518
+ }
519
+ }
520
+ return active;
521
+ }
522
+ function activeQueriesAt(history, t) {
523
+ return history.filter((e) => e.addedAt <= t && (e.deletedAt === null || e.deletedAt > t)).map((e) => e.text);
524
+ }
525
+ var CONTENT_MATCH_STOPWORDS = /* @__PURE__ */ new Set([
526
+ "the",
527
+ "a",
528
+ "an",
529
+ "and",
530
+ "or",
531
+ "but",
532
+ "is",
533
+ "are",
534
+ "was",
535
+ "were",
536
+ "be",
537
+ "been",
538
+ "being",
539
+ "have",
540
+ "has",
541
+ "had",
542
+ "do",
543
+ "does",
544
+ "did",
545
+ "will",
546
+ "would",
547
+ "could",
548
+ "should",
549
+ "may",
550
+ "might",
551
+ "can",
552
+ "this",
553
+ "that",
554
+ "these",
555
+ "those",
556
+ "i",
557
+ "you",
558
+ "he",
559
+ "she",
560
+ "it",
561
+ "we",
562
+ "they",
563
+ "what",
564
+ "which",
565
+ "who",
566
+ "how",
567
+ "why",
568
+ "when",
569
+ "where",
570
+ "with",
571
+ "for",
572
+ "from",
573
+ "of",
574
+ "in",
575
+ "on",
576
+ "at",
577
+ "to",
578
+ "by",
579
+ "as",
580
+ "best",
581
+ "most"
582
+ ]);
583
+ function tokenizeForMatch(s) {
584
+ return s.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((t) => t.length >= 3 && !CONTENT_MATCH_STOPWORDS.has(t));
585
+ }
586
+ function contentMatchScore(queryText, answerText) {
587
+ const queryTokens = [...new Set(tokenizeForMatch(queryText))];
588
+ if (queryTokens.length === 0) return 0;
589
+ const answerHead = answerText.slice(0, 300).toLowerCase();
590
+ const hit = queryTokens.filter((t) => answerHead.includes(t)).length;
591
+ return hit / queryTokens.length;
592
+ }
593
+ async function backfillSnapshotAttributionCommand(opts) {
594
+ const config = loadConfig();
595
+ const db = createClient(config.database);
596
+ migrate(db);
597
+ const project = db.select().from(projects).where(eq(projects.name, opts.project)).get();
598
+ if (!project) {
599
+ throw new Error(`Project "${opts.project}" not found`);
600
+ }
601
+ const isJson = isMachineFormat(opts.format);
602
+ const isDryRun = opts.dryRun === true;
603
+ if (!isJson) {
604
+ const mode = isDryRun ? " [DRY RUN \u2014 no writes]" : "";
605
+ process.stderr.write(`Recovering orphan snapshot attribution for "${project.name}"${mode}...
606
+ `);
607
+ }
608
+ const events = db.select({ createdAt: auditLog.createdAt, action: auditLog.action, diff: auditLog.diff }).from(auditLog).where(and(
609
+ eq(auditLog.projectId, project.id),
610
+ inArray(auditLog.action, ["keywords.appended", "keywords.deleted", "queries.appended", "queries.deleted", "queries.replaced"])
611
+ )).orderBy(auditLog.createdAt).all();
612
+ const history = replayQueryAuditLog(events);
613
+ const orphanRuns = db.select({
614
+ runId: runs.id,
615
+ createdAt: runs.createdAt,
616
+ location: runs.location
617
+ }).from(runs).innerJoin(querySnapshots, eq(querySnapshots.runId, runs.id)).where(and(
618
+ eq(runs.projectId, project.id),
619
+ isNull(querySnapshots.queryId),
620
+ isNull(querySnapshots.queryText)
621
+ )).groupBy(runs.id).orderBy(runs.createdAt).all();
622
+ const result = {
623
+ project: project.name,
624
+ examinedRuns: orphanRuns.length,
625
+ orphanSnapshots: 0,
626
+ recoveredByPosition: 0,
627
+ recoveredByContent: 0,
628
+ unrecovered: 0,
629
+ dryRun: isDryRun,
630
+ perRun: []
631
+ };
632
+ const updates = [];
633
+ for (const run of orphanRuns) {
634
+ const activeAt = activeQueriesAt(history, run.createdAt);
635
+ const orphanSnaps = db.select({
636
+ id: querySnapshots.id,
637
+ provider: querySnapshots.provider,
638
+ createdAt: querySnapshots.createdAt,
639
+ answerText: querySnapshots.answerText
640
+ }).from(querySnapshots).where(and(
641
+ eq(querySnapshots.runId, run.runId),
642
+ isNull(querySnapshots.queryId),
643
+ isNull(querySnapshots.queryText)
644
+ )).orderBy(querySnapshots.provider, querySnapshots.createdAt).all();
645
+ const byProvider = /* @__PURE__ */ new Map();
646
+ for (const s of orphanSnaps) {
647
+ const arr = byProvider.get(s.provider);
648
+ if (arr) arr.push(s);
649
+ else byProvider.set(s.provider, [s]);
650
+ }
651
+ let runPosition = 0;
652
+ let runContent = 0;
653
+ let runUnrecovered = 0;
654
+ for (const [, snaps] of byProvider) {
655
+ if (snaps.length === activeAt.length) {
656
+ for (let i = 0; i < snaps.length; i++) {
657
+ updates.push({ id: snaps[i].id, queryText: activeAt[i] });
658
+ runPosition++;
659
+ }
660
+ } else if (snaps.length < activeAt.length) {
661
+ const LOOKAHEAD_LIMIT = 5;
662
+ let cidx = 0;
663
+ for (const snap of snaps) {
664
+ const answerText = snap.answerText ?? "";
665
+ let matchedIdx = -1;
666
+ for (let i = cidx; i < Math.min(activeAt.length, cidx + LOOKAHEAD_LIMIT); i++) {
667
+ if (contentMatchScore(activeAt[i], answerText) >= 1) {
668
+ matchedIdx = i;
669
+ break;
670
+ }
671
+ }
672
+ if (matchedIdx >= 0) {
673
+ updates.push({ id: snap.id, queryText: activeAt[matchedIdx] });
674
+ runContent++;
675
+ cidx = matchedIdx + 1;
676
+ } else {
677
+ runUnrecovered++;
678
+ }
679
+ }
680
+ } else {
681
+ runUnrecovered += snaps.length;
682
+ }
683
+ }
684
+ result.orphanSnapshots += orphanSnaps.length;
685
+ result.recoveredByPosition += runPosition;
686
+ result.recoveredByContent += runContent;
687
+ result.unrecovered += runUnrecovered;
688
+ result.perRun.push({
689
+ runId: run.runId,
690
+ runCreatedAt: run.createdAt,
691
+ activeQueryCount: activeAt.length,
692
+ orphanSnaps: orphanSnaps.length,
693
+ recoveredPosition: runPosition,
694
+ recoveredContent: runContent,
695
+ unrecovered: runUnrecovered
696
+ });
697
+ if (!isJson) {
698
+ process.stderr.write(
699
+ ` ${run.createdAt} loc=${run.location ?? "-"} \u2192 ${orphanSnaps.length} orphan; ${runPosition} position-matched, ${runContent} content-matched, ${runUnrecovered} unrecovered
700
+ `
701
+ );
702
+ }
703
+ }
704
+ if (!isDryRun && updates.length > 0) {
705
+ db.transaction((tx) => {
706
+ for (const u of updates) {
707
+ tx.update(querySnapshots).set({ queryText: u.queryText }).where(eq(querySnapshots.id, u.id)).run();
708
+ }
709
+ });
710
+ }
711
+ if (isJson) {
712
+ console.log(JSON.stringify(result, null, 2));
713
+ return;
714
+ }
715
+ console.log(`
716
+ Snapshot attribution ${isDryRun ? "preview" : "recovery"} complete.`);
717
+ console.log(` Examined runs: ${result.examinedRuns}`);
718
+ console.log(` Orphan snapshots: ${result.orphanSnapshots}`);
719
+ console.log(` Position-matched: ${result.recoveredByPosition}`);
720
+ console.log(` Content-matched: ${result.recoveredByContent}`);
721
+ console.log(` Unrecovered: ${result.unrecovered}`);
722
+ if (isDryRun) {
723
+ console.log(`
724
+ No DB writes performed. Re-run without --dry-run to apply.`);
725
+ }
726
+ }
727
+ function correctStoredOpenAIRetrieval(snapshot, reparsed) {
728
+ if (snapshot.provider !== ProviderNames.openai) return null;
729
+ if (snapshot.retrievalContract !== RetrievalContracts["native-auto-v1"]) return null;
730
+ return {
731
+ retrievalContract: OPENAI_RETRIEVAL_CONTRACT,
732
+ ...reparsed?.retrievalStatus === void 0 ? {} : { retrievalStatus: reparsed.retrievalStatus }
733
+ };
734
+ }
735
+ function reparseProviderSnapshot(provider, rawResponse) {
736
+ const envelope = parseJsonColumn(rawResponse, {});
737
+ const apiResponse = resolveStoredApiResponse(envelope);
738
+ if (!apiResponse) return null;
739
+ switch (provider) {
740
+ case ProviderNames.openai:
741
+ return reparseStoredResult(apiResponse);
742
+ case ProviderNames.claude:
743
+ return reparseStoredResult2(apiResponse);
744
+ case ProviderNames.gemini:
745
+ return reparseStoredResult3(apiResponse);
746
+ case ProviderNames.perplexity:
747
+ return reparseStoredResult4(apiResponse);
748
+ case ProviderNames.muse:
749
+ return reparseStoredResult5(apiResponse);
750
+ default:
751
+ return null;
752
+ }
753
+ }
754
+ function stringifyStoredSnapshotEnvelope(rawResponse, reparsed) {
755
+ const parsed = parseJsonColumn(rawResponse, {});
756
+ const apiResponse = resolveStoredApiResponse(parsed);
757
+ const envelope = apiResponse === parsed ? {} : { ...parsed };
758
+ delete envelope.answerText;
759
+ delete envelope.citedDomains;
760
+ delete envelope.competitorOverlap;
761
+ delete envelope.recommendedCompetitors;
762
+ delete envelope.providerError;
763
+ return JSON.stringify({
764
+ ...envelope,
765
+ groundingSources: reparsed.groundingSources,
766
+ searchQueries: reparsed.searchQueries,
767
+ ...reparsed.providerError ? { providerError: reparsed.providerError } : {},
768
+ ...apiResponse ? { apiResponse } : {}
769
+ });
770
+ }
771
+ async function backfillTrafficClassificationCommand(opts) {
772
+ const config = loadConfig();
773
+ const db = createClient(config.database);
774
+ migrate(db);
775
+ const projectFilter = opts?.project?.trim();
776
+ const isDryRun = opts?.dryRun === true;
777
+ const isJson = isMachineFormat(opts?.format);
778
+ const scopedProjects = projectFilter ? db.select().from(projects).where(eq(projects.name, projectFilter)).all() : db.select().from(projects).all();
779
+ if (scopedProjects.length === 0) {
780
+ if (projectFilter && !isJson) {
781
+ process.stderr.write(`No project named "${projectFilter}".
782
+ `);
783
+ }
784
+ if (isJson) console.log(JSON.stringify({ project: projectFilter ?? null, examined: 0, reclassified: 0 }));
785
+ return;
786
+ }
787
+ if (!isJson) {
788
+ const mode = isDryRun ? " [DRY RUN \u2014 no writes]" : "";
789
+ const scope = projectFilter ? `"${projectFilter}"` : "all projects";
790
+ process.stderr.write(`Re-classifying unknown traffic samples for ${scope}${mode}...
791
+ `);
792
+ }
793
+ const projectIds = scopedProjects.map((p) => p.id);
794
+ const result = {
795
+ project: projectFilter ?? null,
796
+ examined: 0,
797
+ reclassified: 0,
798
+ unknownBefore: 0,
799
+ unknownAfter: 0,
800
+ dryRun: isDryRun,
801
+ byBot: {}
802
+ };
803
+ const unknownCountRow = db.select({ n: sql`count(*)` }).from(rawEventSamples).where(and(
804
+ eq(rawEventSamples.eventType, "unknown"),
805
+ inArray(rawEventSamples.projectId, projectIds)
806
+ )).get();
807
+ result.unknownBefore = Number(unknownCountRow?.n ?? 0);
808
+ const unknownSamples = db.select({
809
+ id: rawEventSamples.id,
810
+ projectId: rawEventSamples.projectId,
811
+ sourceId: rawEventSamples.sourceId,
812
+ ts: rawEventSamples.ts,
813
+ userAgent: rawEventSamples.userAgent,
814
+ pathNormalized: rawEventSamples.pathNormalized,
815
+ status: rawEventSamples.status
816
+ }).from(rawEventSamples).where(and(
817
+ eq(rawEventSamples.eventType, "unknown"),
818
+ inArray(rawEventSamples.projectId, projectIds)
819
+ )).all();
820
+ result.examined = unknownSamples.length;
821
+ if (unknownSamples.length === 0) {
822
+ result.unknownAfter = result.unknownBefore;
823
+ emitTrafficClassificationReport(result, isJson);
824
+ return;
825
+ }
826
+ const now = (/* @__PURE__ */ new Date()).toISOString();
827
+ for (const snap of unknownSamples) {
828
+ if (!snap.userAgent) continue;
829
+ const probe = {
830
+ sourceType: TrafficSourceTypes["cloud-run"],
831
+ evidenceKind: TrafficEvidenceKinds["raw-request"],
832
+ confidence: TrafficEventConfidences.observed,
833
+ eventId: snap.id,
834
+ observedAt: snap.ts,
835
+ method: "GET",
836
+ requestUrl: `https://placeholder${snap.pathNormalized}`,
837
+ host: "placeholder",
838
+ path: snap.pathNormalized,
839
+ queryString: null,
840
+ status: snap.status ?? 200,
841
+ userAgent: snap.userAgent,
842
+ remoteIp: null,
843
+ referer: null,
844
+ latencyMs: null,
845
+ requestSizeBytes: null,
846
+ responseSizeBytes: null,
847
+ providerResource: { type: "cloud_run_revision", labels: {} },
848
+ providerLabels: {}
849
+ };
850
+ const userFetch = classifyAiUserFetch(probe);
851
+ const classified = userFetch ?? classifyCrawler(probe);
852
+ if (!classified) continue;
853
+ result.reclassified++;
854
+ result.byBot[classified.botId] = (result.byBot[classified.botId] ?? 0) + 1;
855
+ if (isDryRun) continue;
856
+ const tsHour = new Date(snap.ts);
857
+ tsHour.setUTCMinutes(0, 0, 0);
858
+ const tsHourIso = tsHour.toISOString();
859
+ const status = snap.status ?? 200;
860
+ db.transaction((tx) => {
861
+ tx.update(rawEventSamples).set({ eventType: userFetch ? TrafficEventKinds["ai-user-fetch"] : TrafficEventKinds.crawler }).where(eq(rawEventSamples.id, snap.id)).run();
862
+ if (userFetch) {
863
+ tx.insert(aiUserFetchEventsHourly).values({
864
+ projectId: snap.projectId,
865
+ sourceId: snap.sourceId,
866
+ tsHour: tsHourIso,
867
+ botId: userFetch.botId,
868
+ operator: userFetch.operator,
869
+ verificationStatus: userFetch.verificationStatus,
870
+ pathNormalized: snap.pathNormalized,
871
+ status,
872
+ hits: 1,
873
+ sampledUserAgent: snap.userAgent,
874
+ createdAt: now,
875
+ updatedAt: now
876
+ }).onConflictDoUpdate({
877
+ target: [
878
+ aiUserFetchEventsHourly.projectId,
879
+ aiUserFetchEventsHourly.sourceId,
880
+ aiUserFetchEventsHourly.tsHour,
881
+ aiUserFetchEventsHourly.botId,
882
+ aiUserFetchEventsHourly.verificationStatus,
883
+ aiUserFetchEventsHourly.pathNormalized,
884
+ aiUserFetchEventsHourly.status
885
+ ],
886
+ set: {
887
+ hits: sql`${aiUserFetchEventsHourly.hits} + 1`,
888
+ updatedAt: now
889
+ }
890
+ }).run();
891
+ } else {
892
+ tx.insert(crawlerEventsHourly).values({
893
+ projectId: snap.projectId,
894
+ sourceId: snap.sourceId,
895
+ tsHour: tsHourIso,
896
+ botId: classified.botId,
897
+ operator: classified.operator,
898
+ verificationStatus: classified.verificationStatus,
899
+ pathNormalized: snap.pathNormalized,
900
+ status,
901
+ hits: 1,
902
+ sampledUserAgent: snap.userAgent,
903
+ createdAt: now,
904
+ updatedAt: now
905
+ }).onConflictDoUpdate({
906
+ target: [
907
+ crawlerEventsHourly.projectId,
908
+ crawlerEventsHourly.sourceId,
909
+ crawlerEventsHourly.tsHour,
910
+ crawlerEventsHourly.botId,
911
+ crawlerEventsHourly.verificationStatus,
912
+ crawlerEventsHourly.pathNormalized,
913
+ crawlerEventsHourly.status
914
+ ],
915
+ set: {
916
+ hits: sql`${crawlerEventsHourly.hits} + 1`,
917
+ updatedAt: now
918
+ }
919
+ }).run();
920
+ }
921
+ });
922
+ }
923
+ if (!isDryRun) {
924
+ const afterRow = db.select({ n: sql`count(*)` }).from(rawEventSamples).where(and(
925
+ eq(rawEventSamples.eventType, "unknown"),
926
+ inArray(rawEventSamples.projectId, projectIds)
927
+ )).get();
928
+ result.unknownAfter = Number(afterRow?.n ?? 0);
929
+ } else {
930
+ result.unknownAfter = result.unknownBefore - result.reclassified;
931
+ }
932
+ emitTrafficClassificationReport(result, isJson);
933
+ }
934
+ function emitTrafficClassificationReport(result, isJson) {
935
+ if (isJson) {
936
+ console.log(JSON.stringify(result, null, 2));
937
+ return;
938
+ }
939
+ const verb = result.dryRun ? "Would re-classify" : "Re-classified";
940
+ console.log(`
941
+ Traffic classification ${result.dryRun ? "preview" : "recovery"} complete.`);
942
+ console.log(` Examined unknowns: ${result.examined}`);
943
+ console.log(` ${verb}: ${result.reclassified}`);
944
+ console.log(` Unknown before: ${result.unknownBefore}`);
945
+ console.log(` Unknown after: ${result.unknownAfter}`);
946
+ if (result.reclassified > 0) {
947
+ console.log(` By bot:`);
948
+ const sorted = Object.entries(result.byBot).sort(([, a], [, b]) => b - a);
949
+ for (const [bot, count] of sorted) {
950
+ console.log(` ${count.toString().padStart(5)} ${bot}`);
951
+ }
952
+ }
953
+ if (result.dryRun) {
954
+ console.log(`
955
+ No DB writes performed. Re-run without --dry-run to apply.`);
956
+ }
957
+ }
958
+
959
+ export {
960
+ backfillAnswerVisibilityCommand,
961
+ backfillNormalizedPaths,
962
+ backfillNormalizedPathsCommand,
963
+ backfillAiReferralPaths,
964
+ backfillAiReferralPathsCommand,
965
+ backfillAnswerMentionsCommand,
966
+ backfillInsightsCommand,
967
+ replayQueryAuditLog,
968
+ activeQueriesAt,
969
+ backfillSnapshotAttributionCommand,
970
+ backfillTrafficClassificationCommand
971
+ };