@canonry/canonry 7.51.5 → 7.51.6

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