@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.
- package/dist/ads-ABAT3K4K.js +544 -0
- package/dist/agent-5G4DRLYX.js +70 -0
- package/dist/agent-ask-UDVCZRO7.js +139 -0
- package/dist/agent-conversations-5E4JP2QZ.js +52 -0
- package/dist/agent-memory-7IIJ4HGZ.js +92 -0
- package/dist/agent-providers-BOXPUXZ4.js +55 -0
- package/dist/agent-transcript-4O56G6PQ.js +77 -0
- package/dist/analytics-PKMWX5XL.js +240 -0
- package/dist/apply-OK4XEBDA.js +175 -0
- package/dist/backfill-2OT56CX2.js +41 -0
- package/dist/backlinks-547WCHND.js +303 -0
- package/dist/bing-ZVBV4ZD5.js +418 -0
- package/dist/bootstrap-HUB7XQ73.js +326 -0
- package/dist/cdp-KQKQ4PWJ.js +162 -0
- package/dist/chunk-2G6IP3MO.js +517 -0
- package/dist/chunk-42D2LE2B.js +1273 -0
- package/dist/chunk-4MJYGB56.js +124 -0
- package/dist/chunk-63ISSSGX.js +9150 -0
- package/dist/{chunk-PLYJX67A.js → chunk-6G6FTDWC.js} +8080 -13939
- package/dist/chunk-6GO5VVAC.js +15 -0
- package/dist/{chunk-4YCGZGA3.js → chunk-73P65KPW.js} +2 -2
- package/dist/chunk-7B2Q4NJE.js +133 -0
- package/dist/{chunk-JBZZEIM2.js → chunk-7WZ2FPB4.js} +2 -13
- package/dist/chunk-AOJU5LKX.js +8 -0
- package/dist/chunk-B2FR2ZQ4.js +420 -0
- package/dist/{chunk-HAHXPJQ5.js → chunk-B5J675KK.js} +16 -1684
- package/dist/{chunk-SFMWHPMX.js → chunk-D6COIM3U.js} +17128 -17143
- package/dist/{chunk-A3WSAAQS.js → chunk-DGVUTH7W.js} +9086 -34522
- package/dist/chunk-ELCLGWUT.js +83 -0
- package/dist/chunk-GO2J7SYT.js +1034 -0
- package/dist/chunk-HACZUMGM.js +145 -0
- package/dist/chunk-HM4NNKLG.js +94 -0
- package/dist/chunk-I3A56PFP.js +58 -0
- package/dist/chunk-I77PLCWG.js +961 -0
- package/dist/chunk-ISOQPVPY.js +232 -0
- package/dist/chunk-KFT5LOP2.js +610 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-MMEO22MF.js +38 -0
- package/dist/chunk-NHQ2U5I4.js +78 -0
- package/dist/chunk-PCXRFT3N.js +530 -0
- package/dist/chunk-PITHTCAX.js +15376 -0
- package/dist/chunk-QWKPSFGL.js +30 -0
- package/dist/chunk-RKIXES2B.js +609 -0
- package/dist/chunk-TSENU4GG.js +18 -0
- package/dist/{chunk-HLVEB5TB.js → chunk-TUTKNUMV.js} +7 -5
- package/dist/chunk-U3AHE2RT.js +1160 -0
- package/dist/chunk-UQ3MOZGC.js +644 -0
- package/dist/{chunk-AZFPA7JV.js → chunk-VBCE4CLX.js} +6 -4
- package/dist/chunk-VJWDBFSL.js +69 -0
- package/dist/chunk-VYMZ3QXG.js +8264 -0
- package/dist/chunk-WAULJDKO.js +2686 -0
- package/dist/chunk-WDFI5YMD.js +204 -0
- package/dist/chunk-XEBKF4N5.js +8 -0
- package/dist/chunk-Z7IUAJOF.js +13 -0
- package/dist/{chunk-KEATAHXH.js → chunk-ZWJRY5UI.js} +358 -581
- package/dist/chunk-ZXUAWVWM.js +15 -0
- package/dist/citations-UYB2RU5U.js +106 -0
- package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-F6FI7NB2.js} +5 -3
- package/dist/cli-commands-ZG5ILKDA.js +19 -0
- package/dist/cli.js +35 -29
- package/dist/competitor-EKP4R7YY.js +561 -0
- package/dist/content-DREE6JF3.js +257 -0
- package/dist/dashboard-ZALEOLLU.js +71 -0
- package/dist/demo-JG4Y22O4.js +75 -0
- package/dist/{demo-server-GIWDJGJX.js → demo-server-3A4J2C65.js} +22 -9
- package/dist/discover-W6GMD2HS.js +372 -0
- package/dist/discover-eval-CKFZHRBW.js +282 -0
- package/dist/doctor-TNGBSUMA.js +152 -0
- package/dist/evidence-3H2GFQBZ.js +57 -0
- package/dist/export-cmd-WUIKU5GK.js +49 -0
- package/dist/ga-JI6REFO4.js +911 -0
- package/dist/gbp-4ENDM5NS.js +370 -0
- package/dist/google-HKQSCLOC.js +946 -0
- package/dist/google-marketing-KQR5J2S4.js +403 -0
- package/dist/health-cmd-TS7EMMCS.js +64 -0
- package/dist/history-MSD5DK6K.js +90 -0
- package/dist/index.d.ts +47 -47
- package/dist/index.js +29 -6
- package/dist/init-L6WAEOWX.js +432 -0
- package/dist/insights-RTZ3IZTD.js +63 -0
- package/dist/intelligence-service-TH52PCNJ.js +15 -0
- package/dist/keys-625DZBRM.js +116 -0
- package/dist/keyword-CW46RNRR.js +164 -0
- package/dist/logs-V33SHBIW.js +30 -0
- package/dist/mcp-DFEDPSEG.js +14 -0
- package/dist/mcp.js +14 -5
- package/dist/measurement-plan-6W37RUOP.js +42 -0
- package/dist/notify-DSUOT7WO.js +125 -0
- package/dist/organic-evidence-BMN6L4OB.js +53 -0
- package/dist/overview-WRRMBZ6S.js +213 -0
- package/dist/project-2GJIU3FE.js +460 -0
- package/dist/query-3XPMGJUA.js +211 -0
- package/dist/research-V433CKJ4.js +200 -0
- package/dist/results-export-RGBU7QQQ.js +27 -0
- package/dist/run-NIAC6OJN.js +31 -0
- package/dist/schedule-KDWXRIE7.js +177 -0
- package/dist/search-626MPUJN.js +42 -0
- package/dist/serve-73SMMASI.js +557 -0
- package/dist/session-7WWOETZB.js +47 -0
- package/dist/settings-VKFQO6F2.js +107 -0
- package/dist/skills-5HC5H7TE.js +33 -0
- package/dist/snapshot-BSJUHFBC.js +538 -0
- package/dist/src-F6HM73TN.js +316 -0
- package/dist/status-V4OWP7LZ.js +126 -0
- package/dist/support-ARF4HER7.js +24 -0
- package/dist/technical-aeo-TG7CGU3F.js +625 -0
- package/dist/telemetry-O2IUNUBW.js +118 -0
- package/dist/tools-2GJIDKND.js +41 -0
- package/dist/traffic-XV4I3UPH.js +1295 -0
- package/dist/users-VGBLDL5K.js +170 -0
- package/dist/visibility-stats-UKJYJ6PP.js +241 -0
- package/dist/wordpress-JZA7CGC6.js +600 -0
- package/package.json +1 -1
- package/dist/chunk-4QQYYRHV.js +0 -23082
- package/dist/cli-commands-FOJR3HHU.js +0 -15
- package/dist/intelligence-service-XQCNWAPL.js +0 -9
|
@@ -0,0 +1,1034 @@
|
|
|
1
|
+
import {
|
|
2
|
+
pickProjectCitedDomain
|
|
3
|
+
} from "./chunk-MMEO22MF.js";
|
|
4
|
+
import {
|
|
5
|
+
GBP_INSIGHT_PROVIDER,
|
|
6
|
+
PERSISTENT_GAP_THRESHOLD,
|
|
7
|
+
analyzeGbp,
|
|
8
|
+
analyzeRuns,
|
|
9
|
+
buildGbpSummary,
|
|
10
|
+
classifyRegressionSeverity,
|
|
11
|
+
competitorIdentityColumns,
|
|
12
|
+
compileCompetitiveSignalResolver,
|
|
13
|
+
extractPlaceAmenities,
|
|
14
|
+
mergeGscQueryTotalsWithFallback,
|
|
15
|
+
readGscQueryDailyRows,
|
|
16
|
+
readLatestGscDataDate
|
|
17
|
+
} from "./chunk-DGVUTH7W.js";
|
|
18
|
+
import {
|
|
19
|
+
getRequestContext
|
|
20
|
+
} from "./chunk-7B2Q4NJE.js";
|
|
21
|
+
import {
|
|
22
|
+
competitors,
|
|
23
|
+
gbpDailyMetrics,
|
|
24
|
+
gbpKeywordMonthly,
|
|
25
|
+
gbpLocations,
|
|
26
|
+
gbpLodgingSnapshots,
|
|
27
|
+
gbpPlaceActions,
|
|
28
|
+
gbpPlaceDetails,
|
|
29
|
+
groupRunsByCreatedAt,
|
|
30
|
+
gscSearchData,
|
|
31
|
+
healthSnapshots,
|
|
32
|
+
insights,
|
|
33
|
+
parseJsonColumn,
|
|
34
|
+
projects,
|
|
35
|
+
queries,
|
|
36
|
+
querySnapshots,
|
|
37
|
+
runs
|
|
38
|
+
} from "./chunk-63ISSSGX.js";
|
|
39
|
+
import {
|
|
40
|
+
CitationStates,
|
|
41
|
+
RunKinds,
|
|
42
|
+
RunStatuses,
|
|
43
|
+
RunTriggers,
|
|
44
|
+
diagnosticIdentity,
|
|
45
|
+
effectiveDomains,
|
|
46
|
+
redactLogString,
|
|
47
|
+
redactLogValue
|
|
48
|
+
} from "./chunk-D6COIM3U.js";
|
|
49
|
+
|
|
50
|
+
// src/intelligence-service.ts
|
|
51
|
+
import { eq, desc, asc, and, ne, or, inArray, gte, lte, isNull, sql, exists } from "drizzle-orm";
|
|
52
|
+
import crypto from "crypto";
|
|
53
|
+
|
|
54
|
+
// ../api-routes/src/runtime-logger.ts
|
|
55
|
+
import { format } from "util";
|
|
56
|
+
var IS_TTY = process.stdout.isTTY === true;
|
|
57
|
+
var MAX_IDENTITY_LENGTH = 512;
|
|
58
|
+
var RESERVED_FIELDS = /* @__PURE__ */ new Set([
|
|
59
|
+
"ts",
|
|
60
|
+
"level",
|
|
61
|
+
"module",
|
|
62
|
+
"action",
|
|
63
|
+
"msg",
|
|
64
|
+
"requestId",
|
|
65
|
+
"actor",
|
|
66
|
+
"credentialId",
|
|
67
|
+
"userAgent",
|
|
68
|
+
"actorSession",
|
|
69
|
+
"__runtimeRequestId"
|
|
70
|
+
]);
|
|
71
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
72
|
+
function addLogListener(listener) {
|
|
73
|
+
listeners.add(listener);
|
|
74
|
+
return () => listeners.delete(listener);
|
|
75
|
+
}
|
|
76
|
+
function createLogger(module) {
|
|
77
|
+
const emit = (level, action, context) => {
|
|
78
|
+
const msg = context ? safeProperty(context, "msg") : void 0;
|
|
79
|
+
emitRuntimeLog({ level, module, action, context, ...typeof msg === "string" ? { msg } : {} });
|
|
80
|
+
};
|
|
81
|
+
return {
|
|
82
|
+
info: (action, ctx) => emit("info", action, ctx),
|
|
83
|
+
warn: (action, ctx) => emit("warn", action, ctx),
|
|
84
|
+
error: (action, ctx) => emit("error", action, ctx)
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function createFastifyLogger(options = {}) {
|
|
88
|
+
return buildFastifyLogger(options.module ?? "HTTP", options.enabled !== false, {});
|
|
89
|
+
}
|
|
90
|
+
var LEVELS = { trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60, silent: Infinity };
|
|
91
|
+
function buildFastifyLogger(module, enabled, bindings, inheritedLevel = "info") {
|
|
92
|
+
let level = inheritedLevel;
|
|
93
|
+
const emit = (severity, args) => {
|
|
94
|
+
if (LEVELS[severity] >= LEVELS[level]) logFastify(severity, module, enabled, bindings, args);
|
|
95
|
+
};
|
|
96
|
+
const logger = {
|
|
97
|
+
get level() {
|
|
98
|
+
return level;
|
|
99
|
+
},
|
|
100
|
+
set level(value) {
|
|
101
|
+
if (Object.hasOwn(LEVELS, value)) level = value;
|
|
102
|
+
},
|
|
103
|
+
trace: (...args) => emit("trace", args),
|
|
104
|
+
debug: (...args) => emit("debug", args),
|
|
105
|
+
info: (...args) => emit("info", args),
|
|
106
|
+
warn: (...args) => emit("warn", args),
|
|
107
|
+
error: (...args) => emit("error", args),
|
|
108
|
+
fatal: (...args) => emit("fatal", args),
|
|
109
|
+
silent: () => void 0,
|
|
110
|
+
child: (childBindings) => buildFastifyLogger(module, enabled, mergeBindings(bindings, childBindings), level)
|
|
111
|
+
};
|
|
112
|
+
return logger;
|
|
113
|
+
}
|
|
114
|
+
function logFastify(level, module, enabled, bindings, args) {
|
|
115
|
+
const { context, msg } = normalizePinoArgs(args);
|
|
116
|
+
emitRuntimeLog({
|
|
117
|
+
level,
|
|
118
|
+
module,
|
|
119
|
+
action: `fastify.${level}`,
|
|
120
|
+
msg,
|
|
121
|
+
context: { ...bindings, ...context },
|
|
122
|
+
trustedRequestId: asBoundString(bindings.__runtimeRequestId),
|
|
123
|
+
enabled
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
function normalizePinoArgs(args) {
|
|
127
|
+
const first = args[0];
|
|
128
|
+
const second = args[1];
|
|
129
|
+
if (typeof first === "string") return { context: {}, msg: safeFormat(first, args.slice(1)) };
|
|
130
|
+
if (first instanceof Error) {
|
|
131
|
+
return { context: { err: first }, msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
|
|
132
|
+
}
|
|
133
|
+
if (isObject(first)) {
|
|
134
|
+
return { context: copyOwnData(first), msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
|
|
135
|
+
}
|
|
136
|
+
return { context: {}, msg: typeof second === "string" ? safeFormat(second, args.slice(2)) : void 0 };
|
|
137
|
+
}
|
|
138
|
+
function emitRuntimeLog({
|
|
139
|
+
level,
|
|
140
|
+
module,
|
|
141
|
+
action,
|
|
142
|
+
msg,
|
|
143
|
+
context,
|
|
144
|
+
trustedRequestId,
|
|
145
|
+
enabled = true
|
|
146
|
+
}) {
|
|
147
|
+
const safeContext = sanitizeContext(context);
|
|
148
|
+
const error = safeContext.err ?? safeContext.error;
|
|
149
|
+
const errorMessage = typeof error === "string" ? error : isRecord(error) && typeof error.message === "string" ? error.message : void 0;
|
|
150
|
+
const message = errorMessage && errorMessage !== msg ? [msg, errorMessage].filter(Boolean).join(": ") : msg;
|
|
151
|
+
const entry = {
|
|
152
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
153
|
+
level,
|
|
154
|
+
module: boundText(module, "Runtime"),
|
|
155
|
+
action: boundText(action, "log"),
|
|
156
|
+
...message === void 0 ? {} : { msg: redactLogString(message) },
|
|
157
|
+
...safeContext,
|
|
158
|
+
...trustedAttribution(getRequestContext(trustedRequestId), trustedRequestId)
|
|
159
|
+
};
|
|
160
|
+
if (enabled) writeEntry(entry);
|
|
161
|
+
for (const listener of listeners) {
|
|
162
|
+
try {
|
|
163
|
+
listener(entry);
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function sanitizeContext(context) {
|
|
169
|
+
if (!context) return {};
|
|
170
|
+
const output = {};
|
|
171
|
+
for (const key of safeKeys(context).slice(0, 100)) {
|
|
172
|
+
if (RESERVED_FIELDS.has(key)) continue;
|
|
173
|
+
const value = safeProperty(context, key);
|
|
174
|
+
if (key === "req" || key === "request") {
|
|
175
|
+
Object.assign(output, normalizeRequest(value));
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (key === "res" || key === "reply") {
|
|
179
|
+
Object.assign(output, normalizeReply(value));
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (key === "responseTime" || key === "duration") {
|
|
183
|
+
if (typeof value === "number" && Number.isFinite(value)) output.durationMs = value;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
output[key] = value;
|
|
187
|
+
}
|
|
188
|
+
delete output.__runtimeRequestId;
|
|
189
|
+
const redacted = redactLogValue(output);
|
|
190
|
+
return isRecord(redacted) ? redacted : {};
|
|
191
|
+
}
|
|
192
|
+
function trustedAttribution(context, trustedRequestId) {
|
|
193
|
+
const requestId = boundOptional(context?.requestId) ?? trustedRequestId;
|
|
194
|
+
const actor = diagnosticIdentity("actor", context?.actor);
|
|
195
|
+
const credentialId = diagnosticIdentity("credentialId", context?.credentialId);
|
|
196
|
+
const userAgent = boundOptional(context?.userAgent);
|
|
197
|
+
const actorSession = boundOptional(context?.actorSession);
|
|
198
|
+
const method = boundOptional(context?.method);
|
|
199
|
+
const route = boundOptional(context?.route);
|
|
200
|
+
return {
|
|
201
|
+
...requestId ? { requestId } : {},
|
|
202
|
+
...actor ? { actor } : {},
|
|
203
|
+
...credentialId ? { credentialId } : {},
|
|
204
|
+
...userAgent ? { userAgent } : {},
|
|
205
|
+
...actorSession ? { actorSession } : {},
|
|
206
|
+
...method ? { method } : {},
|
|
207
|
+
...route ? { route } : {},
|
|
208
|
+
...context?.statusCode === void 0 ? {} : { statusCode: context.statusCode }
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function mergeBindings(parent, child) {
|
|
212
|
+
const merged = { ...parent };
|
|
213
|
+
if (!isObject(child)) return merged;
|
|
214
|
+
for (const key of safeKeys(child).slice(0, 100)) {
|
|
215
|
+
const value = safeProperty(child, key);
|
|
216
|
+
if (key === "req" || key === "request") Object.assign(merged, normalizeRequest(value));
|
|
217
|
+
else if (key === "res" || key === "reply") Object.assign(merged, normalizeReply(value));
|
|
218
|
+
else if (key === "reqId") {
|
|
219
|
+
merged.reqId = value;
|
|
220
|
+
merged.__runtimeRequestId = value;
|
|
221
|
+
} else if (!RESERVED_FIELDS.has(key)) merged[key] = value;
|
|
222
|
+
}
|
|
223
|
+
return merged;
|
|
224
|
+
}
|
|
225
|
+
function normalizeRequest(value) {
|
|
226
|
+
if (!isObject(value)) return {};
|
|
227
|
+
const id = asBoundString(safeProperty(value, "id"));
|
|
228
|
+
const method = asBoundString(safeProperty(value, "method"));
|
|
229
|
+
const routeOptions = safeProperty(value, "routeOptions");
|
|
230
|
+
const route = isObject(routeOptions) ? asBoundString(safeProperty(routeOptions, "url")) : void 0;
|
|
231
|
+
return {
|
|
232
|
+
...id ? { reqId: id, __runtimeRequestId: id } : {},
|
|
233
|
+
...method ? { method } : {},
|
|
234
|
+
...route ? { route } : {}
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function normalizeReply(value) {
|
|
238
|
+
if (!isObject(value)) return {};
|
|
239
|
+
const statusCode = safeProperty(value, "statusCode");
|
|
240
|
+
return typeof statusCode === "number" && Number.isFinite(statusCode) ? { statusCode } : {};
|
|
241
|
+
}
|
|
242
|
+
function writeEntry(entry) {
|
|
243
|
+
const stream = entry.level === "error" || entry.level === "fatal" ? process.stderr : process.stdout;
|
|
244
|
+
const line = IS_TTY ? formatTTY(entry) : JSON.stringify(entry);
|
|
245
|
+
try {
|
|
246
|
+
stream.write(`${line}
|
|
247
|
+
`);
|
|
248
|
+
} catch {
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function formatTTY(entry) {
|
|
252
|
+
const { ts, level, module, action, msg, ...context } = entry;
|
|
253
|
+
const levelTag = level === "fatal" || level === "error" ? "ERR" : level === "warn" ? "WRN" : "INF";
|
|
254
|
+
const parts = safeKeys(context).map((key) => `${key}=${safeDisplay(safeProperty(context, key))}`);
|
|
255
|
+
return `${ts.slice(11, 19)} ${levelTag} [${module}] ${action}${msg ? ` ${msg}` : ""}${parts.length ? ` ${parts.join(" ")}` : ""}`;
|
|
256
|
+
}
|
|
257
|
+
function safeDisplay(value) {
|
|
258
|
+
try {
|
|
259
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
260
|
+
} catch {
|
|
261
|
+
return "[UNSERIALIZABLE]";
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function safeFormat(message, args) {
|
|
265
|
+
try {
|
|
266
|
+
return args.length ? format(message, ...args) : message;
|
|
267
|
+
} catch {
|
|
268
|
+
return message;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
function isObject(value) {
|
|
272
|
+
return value !== null && typeof value === "object";
|
|
273
|
+
}
|
|
274
|
+
function isRecord(value) {
|
|
275
|
+
return isObject(value) && !Array.isArray(value);
|
|
276
|
+
}
|
|
277
|
+
function safeKeys(value) {
|
|
278
|
+
try {
|
|
279
|
+
return Object.keys(value);
|
|
280
|
+
} catch {
|
|
281
|
+
return [];
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function safeProperty(value, key) {
|
|
285
|
+
try {
|
|
286
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
287
|
+
return descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
288
|
+
} catch {
|
|
289
|
+
return void 0;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function copyOwnData(value) {
|
|
293
|
+
const output = {};
|
|
294
|
+
for (const key of safeKeys(value)) output[key] = safeProperty(value, key);
|
|
295
|
+
return output;
|
|
296
|
+
}
|
|
297
|
+
function boundText(value, fallback) {
|
|
298
|
+
return boundOptional(value) ?? fallback;
|
|
299
|
+
}
|
|
300
|
+
function asBoundString(value) {
|
|
301
|
+
return typeof value === "string" ? boundOptional(value) : void 0;
|
|
302
|
+
}
|
|
303
|
+
function boundOptional(value) {
|
|
304
|
+
if (typeof value !== "string") return void 0;
|
|
305
|
+
const redacted = redactLogString(value).replace(/[\r\n]+/g, " ").trim().slice(0, MAX_IDENTITY_LENGTH);
|
|
306
|
+
return redacted || void 0;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/intelligence-service.ts
|
|
310
|
+
var RECURRENCE_LOOKBACK_RUNS = 5;
|
|
311
|
+
var HISTORY_WINDOW_RUNS = Math.max(PERSISTENT_GAP_THRESHOLD, 5);
|
|
312
|
+
var log = createLogger("IntelligenceService");
|
|
313
|
+
var runChronologyKey = sql`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
|
|
314
|
+
function analyzableRunPredicates(projectId) {
|
|
315
|
+
return [
|
|
316
|
+
eq(runs.projectId, projectId),
|
|
317
|
+
// Only this kind writes query_snapshots.
|
|
318
|
+
eq(runs.kind, RunKinds["answer-visibility"]),
|
|
319
|
+
or(eq(runs.status, RunStatuses.completed), eq(runs.status, RunStatuses.partial)),
|
|
320
|
+
// Defensive: RunCoordinator already skips probes before analyzeAndPersist
|
|
321
|
+
// is called, but a future call site invoking it directly for a probe must
|
|
322
|
+
// still not pollute the intelligence window.
|
|
323
|
+
ne(runs.trigger, RunTriggers.probe)
|
|
324
|
+
];
|
|
325
|
+
}
|
|
326
|
+
function readStoredGroundingSources(rawResponse) {
|
|
327
|
+
const parsed = parseJsonColumn(rawResponse, {});
|
|
328
|
+
const sources = parsed.groundingSources;
|
|
329
|
+
if (!Array.isArray(sources)) return [];
|
|
330
|
+
return sources.flatMap((source) => {
|
|
331
|
+
if (!source || typeof source !== "object") return [];
|
|
332
|
+
const uri = source.uri;
|
|
333
|
+
return typeof uri === "string" ? [{ uri }] : [];
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
function gbpInsightSlot(typeOrSlot) {
|
|
337
|
+
return typeOrSlot === "gbp-lodging-gap" || typeOrSlot === "gbp-listing-discrepancy" ? "lodging" : typeOrSlot;
|
|
338
|
+
}
|
|
339
|
+
function gbpInsightId(projectId, locationName, type) {
|
|
340
|
+
return `${projectId}::gbp::${locationName}::${gbpInsightSlot(type)}`;
|
|
341
|
+
}
|
|
342
|
+
function parseGbpInsightId(id) {
|
|
343
|
+
const parts = id.split("::");
|
|
344
|
+
if (parts.length !== 4 || parts[1] !== "gbp") return null;
|
|
345
|
+
return { location: parts[2], slot: gbpInsightSlot(parts[3]) };
|
|
346
|
+
}
|
|
347
|
+
var SEVERITY_GSC_WINDOW_DAYS = 30;
|
|
348
|
+
function severityGscWindow(endDate) {
|
|
349
|
+
const end = /* @__PURE__ */ new Date(`${endDate}T00:00:00Z`);
|
|
350
|
+
end.setUTCDate(end.getUTCDate() - (SEVERITY_GSC_WINDOW_DAYS - 1));
|
|
351
|
+
return { startDate: end.toISOString().slice(0, 10), endDate };
|
|
352
|
+
}
|
|
353
|
+
var IntelligenceService = class {
|
|
354
|
+
constructor(db) {
|
|
355
|
+
this.db = db;
|
|
356
|
+
}
|
|
357
|
+
db;
|
|
358
|
+
/**
|
|
359
|
+
* Analyze a completed run and persist insights + health snapshot.
|
|
360
|
+
* Idempotent: deletes prior results for the same runId before inserting.
|
|
361
|
+
* Returns the analysis result for the coordinator to inspect (e.g. for webhook dispatch).
|
|
362
|
+
*/
|
|
363
|
+
analyzeAndPersist(runId, projectId) {
|
|
364
|
+
const currentRunRecord = this.db.select().from(runs).where(and(eq(runs.id, runId), ...analyzableRunPredicates(projectId))).get();
|
|
365
|
+
if (!currentRunRecord) {
|
|
366
|
+
log.info("intelligence.skip", { runId, reason: "run not eligible for analysis" });
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
const currentLocation = currentRunRecord.location ?? null;
|
|
370
|
+
const recentRuns = this.db.select().from(runs).where(
|
|
371
|
+
and(
|
|
372
|
+
...analyzableRunPredicates(projectId),
|
|
373
|
+
currentLocation === null ? isNull(runs.location) : eq(runs.location, currentLocation),
|
|
374
|
+
// Never look forward. The window is this run's own past, so
|
|
375
|
+
// re-analyzing a historical run compares it against its true
|
|
376
|
+
// predecessor rather than against sweeps that came after it.
|
|
377
|
+
lte(runChronologyKey, currentRunRecord.finishedAt ?? currentRunRecord.createdAt),
|
|
378
|
+
// MEASUREMENT: only runs that actually wrote snapshots — see above.
|
|
379
|
+
// Index seek on idx_snapshots_run, short-circuited on the first row.
|
|
380
|
+
exists(
|
|
381
|
+
this.db.select({ one: sql`1` }).from(querySnapshots).where(eq(querySnapshots.runId, runs.id))
|
|
382
|
+
)
|
|
383
|
+
)
|
|
384
|
+
).orderBy(desc(runs.finishedAt), desc(runs.createdAt)).limit(HISTORY_WINDOW_RUNS).all();
|
|
385
|
+
const trackedCompetitors = this.loadTrackedCompetitors(projectId);
|
|
386
|
+
const trackedCompetitorDomains = trackedCompetitors.map((competitor) => competitor.domain);
|
|
387
|
+
const currentRun = this.buildRunData(
|
|
388
|
+
runId,
|
|
389
|
+
projectId,
|
|
390
|
+
currentRunRecord.finishedAt ?? currentRunRecord.createdAt,
|
|
391
|
+
currentRunRecord.location ?? null,
|
|
392
|
+
trackedCompetitors
|
|
393
|
+
);
|
|
394
|
+
if (currentRun.snapshots.length === 0) {
|
|
395
|
+
log.info("intelligence.skip", { runId, reason: "no snapshots" });
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
const orderedRecent = [...recentRuns].reverse();
|
|
399
|
+
const currentIdx = orderedRecent.findIndex((r) => r.id === runId);
|
|
400
|
+
const previousRunRecord = currentIdx > 0 ? orderedRecent[currentIdx - 1] : null;
|
|
401
|
+
const previousRun = previousRunRecord ? this.buildRunData(
|
|
402
|
+
previousRunRecord.id,
|
|
403
|
+
projectId,
|
|
404
|
+
previousRunRecord.finishedAt ?? previousRunRecord.createdAt,
|
|
405
|
+
previousRunRecord.location ?? null,
|
|
406
|
+
trackedCompetitors
|
|
407
|
+
) : null;
|
|
408
|
+
const history = orderedRecent.slice(0, currentIdx + 1).map((r) => r.id === runId ? currentRun : this.buildRunData(
|
|
409
|
+
r.id,
|
|
410
|
+
projectId,
|
|
411
|
+
r.finishedAt ?? r.createdAt,
|
|
412
|
+
r.location ?? null,
|
|
413
|
+
trackedCompetitors
|
|
414
|
+
));
|
|
415
|
+
if (!previousRun) {
|
|
416
|
+
const result2 = analyzeRuns(currentRun, currentRun, { trackedCompetitors: trackedCompetitorDomains, history });
|
|
417
|
+
log.info("intelligence.analyzed", {
|
|
418
|
+
runId,
|
|
419
|
+
regressions: 0,
|
|
420
|
+
gains: 0,
|
|
421
|
+
citedRate: result2.health.overallCitedRate,
|
|
422
|
+
insights: 0
|
|
423
|
+
});
|
|
424
|
+
this.persistResult(this.emptyAnalysisResult(result2), runId, projectId);
|
|
425
|
+
return result2;
|
|
426
|
+
}
|
|
427
|
+
const result = analyzeRuns(currentRun, previousRun, { trackedCompetitors: trackedCompetitorDomains, history });
|
|
428
|
+
log.info("intelligence.analyzed", {
|
|
429
|
+
runId,
|
|
430
|
+
regressions: result.regressions.length,
|
|
431
|
+
gains: result.gains.length,
|
|
432
|
+
firstCitations: result.firstCitations.length,
|
|
433
|
+
providerPickups: result.providerPickups.length,
|
|
434
|
+
persistentGaps: result.persistentGaps.length,
|
|
435
|
+
competitorGains: result.competitorGains.length,
|
|
436
|
+
competitorLosses: result.competitorLosses.length,
|
|
437
|
+
citedRate: result.health.overallCitedRate,
|
|
438
|
+
insights: result.insights.length
|
|
439
|
+
});
|
|
440
|
+
const tieredResult = this.tierResult(result, runId, projectId);
|
|
441
|
+
this.persistResult(tieredResult, runId, projectId);
|
|
442
|
+
return tieredResult;
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Analyze a completed `gbp-sync` run and persist location-scoped GBP insights.
|
|
446
|
+
*
|
|
447
|
+
* Point-in-time (no previous-run comparison): for each SELECTED location it
|
|
448
|
+
* derives signals from the shared GBP summary math (metric week-over-week,
|
|
449
|
+
* Lodging API readable-group state, place-action CTAs) plus the accumulating
|
|
450
|
+
* keyword monthly series (month-over-month keyword drop), then runs the pure
|
|
451
|
+
* `analyzeGbp` analyzer. Persists insights ONLY — no health snapshot, which is
|
|
452
|
+
* an answer-visibility concept. Idempotent per `runId`; dismissals are
|
|
453
|
+
* preserved across re-analysis of the same run by the stable insight id.
|
|
454
|
+
* Returns the persisted insights so the coordinator can count critical/high.
|
|
455
|
+
*/
|
|
456
|
+
analyzeAndPersistGbp(runId, projectId) {
|
|
457
|
+
const runRow = this.db.select({ createdAt: runs.createdAt, startedAt: runs.startedAt, finishedAt: runs.finishedAt }).from(runs).where(eq(runs.id, runId)).get();
|
|
458
|
+
if (!runRow) {
|
|
459
|
+
log.info("gbp-intelligence.skip", { runId, reason: "run not found" });
|
|
460
|
+
this.persistGbpInsights(runId, projectId, [], []);
|
|
461
|
+
return [];
|
|
462
|
+
}
|
|
463
|
+
const windowStart = runRow.startedAt ?? runRow.createdAt;
|
|
464
|
+
const windowEnd = runRow.finishedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
465
|
+
const selected = this.db.select().from(gbpLocations).where(and(
|
|
466
|
+
eq(gbpLocations.projectId, projectId),
|
|
467
|
+
eq(gbpLocations.selected, true),
|
|
468
|
+
gte(gbpLocations.syncedAt, windowStart),
|
|
469
|
+
lte(gbpLocations.syncedAt, windowEnd)
|
|
470
|
+
)).all();
|
|
471
|
+
if (selected.length === 0) {
|
|
472
|
+
log.info("gbp-intelligence.skip", { runId, reason: "no locations synced during run" });
|
|
473
|
+
this.persistGbpInsights(runId, projectId, [], []);
|
|
474
|
+
return [];
|
|
475
|
+
}
|
|
476
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
477
|
+
const signals = selected.map(
|
|
478
|
+
(loc) => this.buildGbpLocationSignals(projectId, loc.locationName, loc.displayName, today)
|
|
479
|
+
);
|
|
480
|
+
const drafts = analyzeGbp(signals);
|
|
481
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
482
|
+
const builtInsights = drafts.map((d) => ({
|
|
483
|
+
// Stable, run-independent id per (project, location, slot) so each sync
|
|
484
|
+
// REPLACES the prior insight for that slot instead of appending a per-run
|
|
485
|
+
// copy. The lodging slot is shared by gbp-lodging-gap and its
|
|
486
|
+
// gbp-listing-discrepancy upgrade, so the latter supersedes the former.
|
|
487
|
+
id: gbpInsightId(projectId, d.locationName, d.type),
|
|
488
|
+
type: d.type,
|
|
489
|
+
severity: d.severity,
|
|
490
|
+
title: d.title,
|
|
491
|
+
query: d.query,
|
|
492
|
+
provider: d.provider,
|
|
493
|
+
recommendation: d.recommendation,
|
|
494
|
+
createdAt: now
|
|
495
|
+
}));
|
|
496
|
+
this.persistGbpInsights(runId, projectId, builtInsights, signals.map((s) => s.locationName));
|
|
497
|
+
log.info("gbp-intelligence.analyzed", { runId, locations: selected.length, insights: builtInsights.length });
|
|
498
|
+
return builtInsights;
|
|
499
|
+
}
|
|
500
|
+
/** Build the per-location signal bundle the GBP analyzer consumes. */
|
|
501
|
+
buildGbpLocationSignals(projectId, locationName, displayName, fallbackDate) {
|
|
502
|
+
const metricRows = this.db.select({ metric: gbpDailyMetrics.metric, date: gbpDailyMetrics.date, value: gbpDailyMetrics.value }).from(gbpDailyMetrics).where(and(eq(gbpDailyMetrics.projectId, projectId), eq(gbpDailyMetrics.locationName, locationName))).all();
|
|
503
|
+
const placeActionRows = this.db.select({ placeActionType: gbpPlaceActions.placeActionType, providerType: gbpPlaceActions.providerType }).from(gbpPlaceActions).where(and(eq(gbpPlaceActions.projectId, projectId), eq(gbpPlaceActions.locationName, locationName))).all();
|
|
504
|
+
const lodgingRow = this.db.select({ populatedGroupCount: gbpLodgingSnapshots.populatedGroupCount }).from(gbpLodgingSnapshots).where(and(eq(gbpLodgingSnapshots.projectId, projectId), eq(gbpLodgingSnapshots.locationName, locationName))).orderBy(desc(gbpLodgingSnapshots.syncedAt)).limit(1).get();
|
|
505
|
+
const ownerRow = this.db.select({ description: gbpLocations.description }).from(gbpLocations).where(and(eq(gbpLocations.projectId, projectId), eq(gbpLocations.locationName, locationName))).get();
|
|
506
|
+
const descriptionMissing = !(ownerRow?.description ?? "").trim();
|
|
507
|
+
const placeRow = this.db.select({ attributes: gbpPlaceDetails.attributes }).from(gbpPlaceDetails).where(and(eq(gbpPlaceDetails.projectId, projectId), eq(gbpPlaceDetails.locationName, locationName))).orderBy(desc(gbpPlaceDetails.syncedAt)).limit(1).get();
|
|
508
|
+
const placesAmenities = placeRow ? extractPlaceAmenities(placeRow.attributes) : [];
|
|
509
|
+
const summary = buildGbpSummary({
|
|
510
|
+
locationName,
|
|
511
|
+
locationCount: 1,
|
|
512
|
+
asOfDate: fallbackDate,
|
|
513
|
+
dailyMetrics: metricRows,
|
|
514
|
+
keywords: [],
|
|
515
|
+
// keyword coverage is unused here; the trend uses the monthly series below
|
|
516
|
+
placeActions: placeActionRows.map((r) => ({ placeActionType: r.placeActionType, providerType: r.providerType ?? null })),
|
|
517
|
+
lodging: lodgingRow ? [{ locationName, populatedGroupCount: lodgingRow.populatedGroupCount }] : [],
|
|
518
|
+
// The analyzer consumes metric/keyword/place-action/lodging signals, not
|
|
519
|
+
// the profile-completeness scorecard, so it is left empty here.
|
|
520
|
+
locationProfiles: []
|
|
521
|
+
});
|
|
522
|
+
const trend = this.buildGbpKeywordTrend(projectId, locationName);
|
|
523
|
+
return {
|
|
524
|
+
locationName,
|
|
525
|
+
displayName,
|
|
526
|
+
metricRecent7d: summary.performance.recent7d,
|
|
527
|
+
metricPrior7d: summary.performance.prior7d,
|
|
528
|
+
metricDeltaPct: summary.performance.deltaPct,
|
|
529
|
+
lodgingCapable: summary.lodging.lodgingLocationCount > 0,
|
|
530
|
+
lodgingEmpty: summary.lodging.emptyLodgingCount > 0,
|
|
531
|
+
descriptionMissing,
|
|
532
|
+
placesAmenities,
|
|
533
|
+
placeActionCount: summary.placeActions.total,
|
|
534
|
+
hasDirectMerchantCta: summary.placeActions.hasDirectMerchantCta,
|
|
535
|
+
keywordRecentMonth: trend.recentMonth,
|
|
536
|
+
keywordPriorMonth: trend.priorMonth,
|
|
537
|
+
keywordPoints: trend.points
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
/** Build the month-over-month keyword series for a location from the
|
|
541
|
+
* accumulating gbp_keyword_monthly table (latest complete month vs prior). */
|
|
542
|
+
buildGbpKeywordTrend(projectId, locationName) {
|
|
543
|
+
const rows = this.db.select({ month: gbpKeywordMonthly.month, keyword: gbpKeywordMonthly.keyword, valueCount: gbpKeywordMonthly.valueCount }).from(gbpKeywordMonthly).where(and(eq(gbpKeywordMonthly.projectId, projectId), eq(gbpKeywordMonthly.locationName, locationName))).all();
|
|
544
|
+
if (rows.length === 0) return { recentMonth: null, priorMonth: null, points: [] };
|
|
545
|
+
const months = [...new Set(rows.map((r) => r.month))].sort().reverse();
|
|
546
|
+
const recentMonth = months[0] ?? null;
|
|
547
|
+
const priorMonth = months[1] ?? null;
|
|
548
|
+
if (!recentMonth || !priorMonth) return { recentMonth, priorMonth: null, points: [] };
|
|
549
|
+
const recentByKeyword = /* @__PURE__ */ new Map();
|
|
550
|
+
const priorByKeyword = /* @__PURE__ */ new Map();
|
|
551
|
+
for (const r of rows) {
|
|
552
|
+
if (r.month === recentMonth) recentByKeyword.set(r.keyword, r.valueCount);
|
|
553
|
+
else if (r.month === priorMonth) priorByKeyword.set(r.keyword, r.valueCount);
|
|
554
|
+
}
|
|
555
|
+
const points = [];
|
|
556
|
+
for (const [keyword, recent] of recentByKeyword) {
|
|
557
|
+
points.push({ keyword, recent: recent ?? null, prior: priorByKeyword.get(keyword) ?? null });
|
|
558
|
+
}
|
|
559
|
+
return { recentMonth, priorMonth, points };
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Persist GBP insights as CURRENT STATE for the locations a sync evaluated.
|
|
563
|
+
* GBP insights are point-in-time profile facts, not run-to-run transitions, so
|
|
564
|
+
* each sync REPLACES the prior insights for the locations it covered — keyed by
|
|
565
|
+
* the run-independent `${projectId}::gbp::${location}::${slot}` id — instead of
|
|
566
|
+
* appending a fresh per-run copy. This collapses run-over-run duplicates,
|
|
567
|
+
* supersedes `gbp-lodging-gap` with `gbp-listing-discrepancy` (shared `lodging`
|
|
568
|
+
* slot), and clears a location's stale insight once its gap is resolved.
|
|
569
|
+
* Dismissals are preserved by (location, slot). Locations NOT covered by this
|
|
570
|
+
* run (e.g. a `--location`-scoped sync) are left untouched.
|
|
571
|
+
*/
|
|
572
|
+
persistGbpInsights(runId, projectId, gbpInsights, coveredLocationNames) {
|
|
573
|
+
const covered = new Set(coveredLocationNames);
|
|
574
|
+
const existing = this.db.select({ id: insights.id, dismissed: insights.dismissed }).from(insights).where(and(eq(insights.projectId, projectId), eq(insights.provider, GBP_INSIGHT_PROVIDER))).all();
|
|
575
|
+
const staleIds = [];
|
|
576
|
+
const dismissedSlots = /* @__PURE__ */ new Set();
|
|
577
|
+
for (const row of existing) {
|
|
578
|
+
const parsed = parseGbpInsightId(row.id);
|
|
579
|
+
if (!parsed) continue;
|
|
580
|
+
if (covered.has(parsed.location)) staleIds.push(row.id);
|
|
581
|
+
if (row.dismissed) dismissedSlots.add(`${parsed.location}::${parsed.slot}`);
|
|
582
|
+
}
|
|
583
|
+
this.db.transaction((tx) => {
|
|
584
|
+
for (const id of staleIds) {
|
|
585
|
+
tx.delete(insights).where(eq(insights.id, id)).run();
|
|
586
|
+
}
|
|
587
|
+
for (const insight of gbpInsights) {
|
|
588
|
+
const parsed = parseGbpInsightId(insight.id);
|
|
589
|
+
const dismissed = parsed ? dismissedSlots.has(`${parsed.location}::${parsed.slot}`) : false;
|
|
590
|
+
tx.insert(insights).values({
|
|
591
|
+
id: insight.id,
|
|
592
|
+
projectId,
|
|
593
|
+
runId,
|
|
594
|
+
type: insight.type,
|
|
595
|
+
severity: insight.severity,
|
|
596
|
+
title: insight.title,
|
|
597
|
+
query: insight.query,
|
|
598
|
+
provider: insight.provider,
|
|
599
|
+
recommendation: insight.recommendation ?? null,
|
|
600
|
+
cause: insight.cause ?? null,
|
|
601
|
+
dismissed,
|
|
602
|
+
createdAt: insight.createdAt
|
|
603
|
+
}).run();
|
|
604
|
+
}
|
|
605
|
+
});
|
|
606
|
+
log.info("gbp-intelligence.persisted", { runId, insights: gbpInsights.length, replaced: staleIds.length });
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Analyze a single run given an explicit previous run (or null for first run).
|
|
610
|
+
* Used by backfill where we control the run ordering.
|
|
611
|
+
*
|
|
612
|
+
* `dryRun: true` skips the DB write — `persistResult` is not called and
|
|
613
|
+
* dismissed flags / health rows are untouched. Callers receive the same
|
|
614
|
+
* AnalysisResult they would have, suitable for previewing what a write
|
|
615
|
+
* would have produced.
|
|
616
|
+
*/
|
|
617
|
+
analyzeRunWithPrevious(runRecord, previousRunRecord, historyRecords, opts) {
|
|
618
|
+
const trackedCompetitors = this.loadTrackedCompetitors(runRecord.projectId);
|
|
619
|
+
const trackedCompetitorDomains = trackedCompetitors.map((competitor) => competitor.domain);
|
|
620
|
+
const currentRun = this.buildRunData(
|
|
621
|
+
runRecord.id,
|
|
622
|
+
runRecord.projectId,
|
|
623
|
+
runRecord.finishedAt ?? runRecord.createdAt,
|
|
624
|
+
runRecord.location ?? null,
|
|
625
|
+
trackedCompetitors
|
|
626
|
+
);
|
|
627
|
+
if (currentRun.snapshots.length === 0) {
|
|
628
|
+
return null;
|
|
629
|
+
}
|
|
630
|
+
const previousRun = previousRunRecord ? this.buildRunData(
|
|
631
|
+
previousRunRecord.id,
|
|
632
|
+
previousRunRecord.projectId,
|
|
633
|
+
previousRunRecord.finishedAt ?? previousRunRecord.createdAt,
|
|
634
|
+
previousRunRecord.location ?? null,
|
|
635
|
+
trackedCompetitors
|
|
636
|
+
) : null;
|
|
637
|
+
const history = (historyRecords ?? []).map((r) => r.id === runRecord.id ? currentRun : this.buildRunData(
|
|
638
|
+
r.id,
|
|
639
|
+
r.projectId,
|
|
640
|
+
r.finishedAt ?? r.createdAt,
|
|
641
|
+
r.location ?? null,
|
|
642
|
+
trackedCompetitors
|
|
643
|
+
));
|
|
644
|
+
if (!previousRun) {
|
|
645
|
+
const result2 = analyzeRuns(currentRun, currentRun, { trackedCompetitors: trackedCompetitorDomains, history });
|
|
646
|
+
const emptyResult = this.emptyAnalysisResult(result2);
|
|
647
|
+
if (!opts?.dryRun) this.persistResult(emptyResult, runRecord.id, runRecord.projectId);
|
|
648
|
+
return result2;
|
|
649
|
+
}
|
|
650
|
+
const result = analyzeRuns(currentRun, previousRun, { trackedCompetitors: trackedCompetitorDomains, history });
|
|
651
|
+
const tieredResult = this.tierResult(result, runRecord.id, runRecord.projectId);
|
|
652
|
+
if (!opts?.dryRun) this.persistResult(tieredResult, runRecord.id, runRecord.projectId);
|
|
653
|
+
return tieredResult;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Backfill intelligence for all completed/partial runs of a project.
|
|
657
|
+
* Processes runs in chronological order so each run compares against its predecessor.
|
|
658
|
+
*
|
|
659
|
+
* Scoping options:
|
|
660
|
+
* - `fromRunId` / `toRunId`: bound the target range by exact run ID.
|
|
661
|
+
* - `since`: bound the target range by `finishedAt >= <date>`. Accepts
|
|
662
|
+
* any string that `Date.parse` understands (ISO 8601, `YYYY-MM-DD`,
|
|
663
|
+
* etc.). Runs before the cutoff are *not* re-processed but stay
|
|
664
|
+
* available for predecessor lookup, so transition detection at the
|
|
665
|
+
* boundary stays correct. Composes with `fromRunId` / `toRunId` —
|
|
666
|
+
* all three filters intersect.
|
|
667
|
+
* - `dryRun`: compute the analysis without writing. The return value
|
|
668
|
+
* includes a `delta` describing what would change (rows to delete vs
|
|
669
|
+
* create per run + aggregate). DB is left untouched.
|
|
670
|
+
*/
|
|
671
|
+
backfill(projectName, opts, onProgress) {
|
|
672
|
+
const project = this.db.select().from(projects).where(eq(projects.name, projectName)).get();
|
|
673
|
+
if (!project) {
|
|
674
|
+
throw new Error(`Project "${projectName}" not found`);
|
|
675
|
+
}
|
|
676
|
+
let sinceTimestamp = null;
|
|
677
|
+
if (opts?.since !== void 0) {
|
|
678
|
+
const parsed = Date.parse(opts.since);
|
|
679
|
+
if (Number.isNaN(parsed)) {
|
|
680
|
+
throw new Error(`Invalid --since value "${opts.since}": expected a parseable date (ISO 8601 or YYYY-MM-DD)`);
|
|
681
|
+
}
|
|
682
|
+
sinceTimestamp = parsed;
|
|
683
|
+
}
|
|
684
|
+
const allRuns = this.db.select().from(runs).where(and(...analyzableRunPredicates(project.id))).orderBy(asc(runs.finishedAt)).all();
|
|
685
|
+
const measuredRunIds = this.runIdsWithSnapshots(allRuns.map((r) => r.id));
|
|
686
|
+
const measuredRuns = allRuns.filter((r) => measuredRunIds.has(r.id));
|
|
687
|
+
let startIdx = 0;
|
|
688
|
+
let endIdx = allRuns.length;
|
|
689
|
+
if (opts?.fromRunId) {
|
|
690
|
+
const idx = allRuns.findIndex((r) => r.id === opts.fromRunId);
|
|
691
|
+
if (idx === -1) throw new Error(`Run "${opts.fromRunId}" not found in project`);
|
|
692
|
+
startIdx = idx;
|
|
693
|
+
}
|
|
694
|
+
if (opts?.toRunId) {
|
|
695
|
+
const idx = allRuns.findIndex((r) => r.id === opts.toRunId);
|
|
696
|
+
if (idx === -1) throw new Error(`Run "${opts.toRunId}" not found in project`);
|
|
697
|
+
endIdx = idx + 1;
|
|
698
|
+
}
|
|
699
|
+
let targetRuns = allRuns.slice(startIdx, endIdx);
|
|
700
|
+
if (sinceTimestamp !== null) {
|
|
701
|
+
targetRuns = targetRuns.filter((r) => {
|
|
702
|
+
const ts = r.finishedAt ?? r.createdAt;
|
|
703
|
+
const t = Date.parse(ts);
|
|
704
|
+
return !Number.isNaN(t) && t >= sinceTimestamp;
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
let processed = 0;
|
|
708
|
+
let skipped = 0;
|
|
709
|
+
let totalInsights = 0;
|
|
710
|
+
const isDryRun = opts?.dryRun === true;
|
|
711
|
+
const perRunDelta = [];
|
|
712
|
+
let wouldDeleteTotal = 0;
|
|
713
|
+
const existingByRunId = /* @__PURE__ */ new Map();
|
|
714
|
+
if (isDryRun && targetRuns.length > 0) {
|
|
715
|
+
const rows = this.db.select({ runId: insights.runId }).from(insights).where(inArray(insights.runId, targetRuns.map((r) => r.id))).all();
|
|
716
|
+
for (const r of rows) {
|
|
717
|
+
if (r.runId == null) continue;
|
|
718
|
+
existingByRunId.set(r.runId, (existingByRunId.get(r.runId) ?? 0) + 1);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
for (let i = 0; i < targetRuns.length; i++) {
|
|
722
|
+
const run = targetRuns[i];
|
|
723
|
+
const runLocation = run.location ?? null;
|
|
724
|
+
const sameLocationRuns = measuredRuns.filter((r) => (r.location ?? null) === runLocation);
|
|
725
|
+
const sameLocIdx = sameLocationRuns.indexOf(run);
|
|
726
|
+
const previousRun = sameLocIdx > 0 ? sameLocationRuns[sameLocIdx - 1] : null;
|
|
727
|
+
const historyStart = Math.max(0, sameLocIdx - (HISTORY_WINDOW_RUNS - 1));
|
|
728
|
+
const historyRecords = sameLocationRuns.slice(historyStart, sameLocIdx + 1);
|
|
729
|
+
const result = this.analyzeRunWithPrevious(run, previousRun, historyRecords, { dryRun: isDryRun });
|
|
730
|
+
if (result) {
|
|
731
|
+
processed++;
|
|
732
|
+
totalInsights += result.insights.length;
|
|
733
|
+
if (isDryRun) {
|
|
734
|
+
const existing = existingByRunId.get(run.id) ?? 0;
|
|
735
|
+
wouldDeleteTotal += existing;
|
|
736
|
+
perRunDelta.push({ runId: run.id, existingInsights: existing, newInsights: result.insights.length });
|
|
737
|
+
}
|
|
738
|
+
onProgress?.({ runId: run.id, index: i + 1, total: targetRuns.length, insights: result.insights.length });
|
|
739
|
+
} else {
|
|
740
|
+
skipped++;
|
|
741
|
+
onProgress?.({ runId: run.id, index: i + 1, total: targetRuns.length, insights: 0 });
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (isDryRun) {
|
|
745
|
+
return {
|
|
746
|
+
processed,
|
|
747
|
+
skipped,
|
|
748
|
+
totalInsights,
|
|
749
|
+
dryRun: true,
|
|
750
|
+
delta: {
|
|
751
|
+
wouldDelete: wouldDeleteTotal,
|
|
752
|
+
wouldCreate: totalInsights,
|
|
753
|
+
netChange: totalInsights - wouldDeleteTotal,
|
|
754
|
+
perRun: perRunDelta
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
return { processed, skipped, totalInsights };
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* The project's tracked competitors with every name they answer to
|
|
762
|
+
* (curated and auto-detected aliases, minus blocked), so competitive
|
|
763
|
+
* signals match the same identities the dashboard and reports do.
|
|
764
|
+
*/
|
|
765
|
+
loadTrackedCompetitors(projectId) {
|
|
766
|
+
return this.db.select(competitorIdentityColumns).from(competitors).where(eq(competitors.projectId, projectId)).orderBy(competitors.domain).all();
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Which of `runIds` actually wrote query snapshots. One grouped read, so
|
|
770
|
+
* callers can drop the runs that measured nothing before paying to build
|
|
771
|
+
* RunData for them. An empty input returns an empty set without querying.
|
|
772
|
+
*/
|
|
773
|
+
runIdsWithSnapshots(runIds) {
|
|
774
|
+
if (runIds.length === 0) return /* @__PURE__ */ new Set();
|
|
775
|
+
const rows = this.db.select({ runId: querySnapshots.runId }).from(querySnapshots).where(inArray(querySnapshots.runId, [...runIds])).groupBy(querySnapshots.runId).all();
|
|
776
|
+
return new Set(rows.map((r) => r.runId));
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Wipe transition signals from an analysis result while keeping health.
|
|
780
|
+
* Used when there's no baseline (first run) to avoid emitting false transitions.
|
|
781
|
+
*/
|
|
782
|
+
emptyAnalysisResult(result) {
|
|
783
|
+
return {
|
|
784
|
+
...result,
|
|
785
|
+
insights: [],
|
|
786
|
+
regressions: [],
|
|
787
|
+
gains: [],
|
|
788
|
+
firstCitations: [],
|
|
789
|
+
providerPickups: [],
|
|
790
|
+
persistentGaps: [],
|
|
791
|
+
competitorGains: [],
|
|
792
|
+
competitorLosses: []
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
persistResult(result, runId, projectId) {
|
|
796
|
+
const previouslyDismissed = /* @__PURE__ */ new Set();
|
|
797
|
+
const existingInsights = this.db.select({ query: insights.query, provider: insights.provider, type: insights.type, dismissed: insights.dismissed }).from(insights).where(eq(insights.runId, runId)).all();
|
|
798
|
+
for (const row of existingInsights) {
|
|
799
|
+
if (row.dismissed) {
|
|
800
|
+
previouslyDismissed.add(`${row.query}:${row.provider}:${row.type}`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
this.db.transaction((tx) => {
|
|
804
|
+
tx.delete(insights).where(eq(insights.runId, runId)).run();
|
|
805
|
+
tx.delete(healthSnapshots).where(eq(healthSnapshots.runId, runId)).run();
|
|
806
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
807
|
+
for (const insight of result.insights) {
|
|
808
|
+
const wasDismissed = previouslyDismissed.has(`${insight.query}:${insight.provider}:${insight.type}`);
|
|
809
|
+
tx.insert(insights).values({
|
|
810
|
+
id: insight.id,
|
|
811
|
+
projectId,
|
|
812
|
+
runId,
|
|
813
|
+
type: insight.type,
|
|
814
|
+
severity: insight.severity,
|
|
815
|
+
title: insight.title,
|
|
816
|
+
query: insight.query,
|
|
817
|
+
provider: insight.provider,
|
|
818
|
+
recommendation: insight.recommendation ?? null,
|
|
819
|
+
cause: insight.cause ?? null,
|
|
820
|
+
dismissed: wasDismissed,
|
|
821
|
+
createdAt: insight.createdAt
|
|
822
|
+
}).run();
|
|
823
|
+
}
|
|
824
|
+
tx.insert(healthSnapshots).values({
|
|
825
|
+
id: crypto.randomUUID(),
|
|
826
|
+
projectId,
|
|
827
|
+
runId,
|
|
828
|
+
overallCitedRate: String(result.health.overallCitedRate),
|
|
829
|
+
overallMentionRate: String(result.health.overallMentionRate),
|
|
830
|
+
totalPairs: result.health.totalPairs,
|
|
831
|
+
citedPairs: result.health.citedPairs,
|
|
832
|
+
mentionedPairs: result.health.mentionedPairs,
|
|
833
|
+
providerBreakdown: result.health.providerBreakdown,
|
|
834
|
+
createdAt: now
|
|
835
|
+
}).run();
|
|
836
|
+
});
|
|
837
|
+
log.info("intelligence.persisted", { runId, insights: result.insights.length });
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Per-(date, query) rows folded from the page-keyed table, for days the
|
|
841
|
+
* accurate per-query table has not backfilled. Impressions here are a page
|
|
842
|
+
* fanout sum and therefore an over-count; this exists only so an un-backfilled
|
|
843
|
+
* day reads as "some demand" rather than "none".
|
|
844
|
+
*/
|
|
845
|
+
readGscPageSummedFallback(projectId, window) {
|
|
846
|
+
const rows = this.db.select({
|
|
847
|
+
date: gscSearchData.date,
|
|
848
|
+
query: gscSearchData.query,
|
|
849
|
+
clicks: gscSearchData.clicks,
|
|
850
|
+
impressions: gscSearchData.impressions,
|
|
851
|
+
position: gscSearchData.position
|
|
852
|
+
}).from(gscSearchData).where(and(
|
|
853
|
+
eq(gscSearchData.projectId, projectId),
|
|
854
|
+
gte(gscSearchData.date, window.startDate),
|
|
855
|
+
lte(gscSearchData.date, window.endDate)
|
|
856
|
+
)).all();
|
|
857
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
858
|
+
for (const r of rows) {
|
|
859
|
+
if (!r.query) continue;
|
|
860
|
+
const key = `${r.date}\0${r.query}`;
|
|
861
|
+
const acc = byDay.get(key) ?? { date: r.date, query: r.query, clicks: 0, impressions: 0, weighted: 0 };
|
|
862
|
+
acc.clicks += r.clicks;
|
|
863
|
+
acc.impressions += r.impressions;
|
|
864
|
+
acc.weighted += (Number(r.position) || 0) * r.impressions;
|
|
865
|
+
byDay.set(key, acc);
|
|
866
|
+
}
|
|
867
|
+
return [...byDay.values()].map((a) => ({
|
|
868
|
+
date: a.date,
|
|
869
|
+
query: a.query,
|
|
870
|
+
clicks: a.clicks,
|
|
871
|
+
impressions: a.impressions,
|
|
872
|
+
position: a.impressions > 0 ? a.weighted / a.impressions : 0
|
|
873
|
+
}));
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Apply severity tiering to the insights of an AnalysisResult and return a
|
|
877
|
+
* new result. Wraps `applySeverityTiering` so callers (analyzeAndPersist,
|
|
878
|
+
* analyzeRunWithPrevious) can pass the same tiered shape both into the DB
|
|
879
|
+
* write and back to the RunCoordinator / webhook dispatcher.
|
|
880
|
+
*/
|
|
881
|
+
tierResult(result, runId, projectId) {
|
|
882
|
+
if (result.insights.length === 0) return result;
|
|
883
|
+
return { ...result, insights: this.applySeverityTiering(result.insights, runId, projectId) };
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Re-classify each regression insight's severity using GSC traffic +
|
|
887
|
+
* recurrence signals via the pure `classifyRegressionSeverity` primitive
|
|
888
|
+
* in @canonry/canonry-intelligence. Non-regression insights are returned
|
|
889
|
+
* untouched.
|
|
890
|
+
*/
|
|
891
|
+
applySeverityTiering(rawInsights, excludeRunId, projectId) {
|
|
892
|
+
const regressions = rawInsights.filter((i) => i.type === "regression");
|
|
893
|
+
if (regressions.length === 0) return rawInsights;
|
|
894
|
+
const gscEnd = readLatestGscDataDate(this.db, projectId);
|
|
895
|
+
const gscWindow = gscEnd ? severityGscWindow(gscEnd) : null;
|
|
896
|
+
const gscTotals = gscWindow ? mergeGscQueryTotalsWithFallback(
|
|
897
|
+
readGscQueryDailyRows(this.db, projectId, gscWindow.startDate, gscWindow.endDate),
|
|
898
|
+
this.readGscPageSummedFallback(projectId, gscWindow)
|
|
899
|
+
) : [];
|
|
900
|
+
const gscConnected = gscEnd !== null;
|
|
901
|
+
const gscImpressionsByQuery = /* @__PURE__ */ new Map();
|
|
902
|
+
for (const row of gscTotals) {
|
|
903
|
+
const key = row.query.toLowerCase();
|
|
904
|
+
gscImpressionsByQuery.set(key, (gscImpressionsByQuery.get(key) ?? 0) + row.impressions);
|
|
905
|
+
}
|
|
906
|
+
const projectRow = this.db.select({ locations: projects.locations }).from(projects).where(eq(projects.id, projectId)).get();
|
|
907
|
+
const locationCount = Math.max(
|
|
908
|
+
1,
|
|
909
|
+
(projectRow?.locations ?? []).length
|
|
910
|
+
);
|
|
911
|
+
const ROWS_PER_GROUP_BUDGET = Math.max(2, locationCount);
|
|
912
|
+
const recentRunRows = this.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(
|
|
913
|
+
and(
|
|
914
|
+
eq(runs.projectId, projectId),
|
|
915
|
+
eq(runs.kind, RunKinds["answer-visibility"]),
|
|
916
|
+
or(eq(runs.status, "completed"), eq(runs.status, "partial")),
|
|
917
|
+
// Defensive — see top of file.
|
|
918
|
+
ne(runs.trigger, RunTriggers.probe)
|
|
919
|
+
)
|
|
920
|
+
).orderBy(desc(runs.createdAt), desc(runs.id)).limit((RECURRENCE_LOOKBACK_RUNS + 1) * ROWS_PER_GROUP_BUDGET).all();
|
|
921
|
+
const recentGroups = groupRunsByCreatedAt(recentRunRows);
|
|
922
|
+
const recentRunIds = [];
|
|
923
|
+
const recentRunIdToCreatedAt = /* @__PURE__ */ new Map();
|
|
924
|
+
let consumedGroups = 0;
|
|
925
|
+
for (const group of recentGroups) {
|
|
926
|
+
const groupIds = group.map((r) => r.id);
|
|
927
|
+
if (groupIds.includes(excludeRunId)) continue;
|
|
928
|
+
for (const r of group) recentRunIdToCreatedAt.set(r.id, r.createdAt);
|
|
929
|
+
recentRunIds.push(...groupIds);
|
|
930
|
+
consumedGroups++;
|
|
931
|
+
if (consumedGroups >= RECURRENCE_LOOKBACK_RUNS) break;
|
|
932
|
+
}
|
|
933
|
+
const haveHistory = recentRunIds.length > 0;
|
|
934
|
+
const priorRegressionsByPair = /* @__PURE__ */ new Map();
|
|
935
|
+
if (haveHistory) {
|
|
936
|
+
const priorRows = this.db.select({ query: insights.query, provider: insights.provider, runId: insights.runId }).from(insights).where(and(eq(insights.type, "regression"), inArray(insights.runId, recentRunIds))).all();
|
|
937
|
+
const regressionGroups = /* @__PURE__ */ new Map();
|
|
938
|
+
for (const row of priorRows) {
|
|
939
|
+
if (!row.runId) continue;
|
|
940
|
+
const key = `${row.query}:${row.provider}`;
|
|
941
|
+
const groupKey = recentRunIdToCreatedAt.get(row.runId) ?? row.runId;
|
|
942
|
+
let groups = regressionGroups.get(key);
|
|
943
|
+
if (!groups) {
|
|
944
|
+
groups = /* @__PURE__ */ new Set();
|
|
945
|
+
regressionGroups.set(key, groups);
|
|
946
|
+
}
|
|
947
|
+
groups.add(groupKey);
|
|
948
|
+
}
|
|
949
|
+
for (const [key, groups] of regressionGroups) {
|
|
950
|
+
priorRegressionsByPair.set(key, groups.size);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
return rawInsights.map((insight) => {
|
|
954
|
+
if (insight.type !== "regression") return insight;
|
|
955
|
+
const gscImpressions = gscConnected ? gscImpressionsByQuery.get(insight.query.toLowerCase()) ?? 0 : void 0;
|
|
956
|
+
const recurrenceCount = haveHistory ? priorRegressionsByPair.get(`${insight.query}:${insight.provider}`) ?? 0 : void 0;
|
|
957
|
+
const severity = classifyRegressionSeverity({
|
|
958
|
+
gscImpressions,
|
|
959
|
+
recurrenceCount
|
|
960
|
+
});
|
|
961
|
+
return { ...insight, severity };
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
buildRunData(runId, projectId, completedAt, location = null, trackedCompetitors = []) {
|
|
965
|
+
const projectDomainRow = this.db.select({ canonicalDomain: projects.canonicalDomain, ownedDomains: projects.ownedDomains }).from(projects).where(eq(projects.id, projectId)).get();
|
|
966
|
+
const projectDomains = projectDomainRow ? effectiveDomains({
|
|
967
|
+
canonicalDomain: projectDomainRow.canonicalDomain,
|
|
968
|
+
ownedDomains: projectDomainRow.ownedDomains
|
|
969
|
+
}) : [];
|
|
970
|
+
const competitiveSignalResolver = compileCompetitiveSignalResolver(trackedCompetitors);
|
|
971
|
+
const rows = this.db.select({
|
|
972
|
+
query: queries.query,
|
|
973
|
+
// Denormalized query text persisted by v58 — the fallback when the
|
|
974
|
+
// joined queries.query has been hard-deleted (or the query_id was
|
|
975
|
+
// nulled by the v58 dangling-FK cleanup).
|
|
976
|
+
queryText: querySnapshots.queryText,
|
|
977
|
+
provider: querySnapshots.provider,
|
|
978
|
+
citationState: querySnapshots.citationState,
|
|
979
|
+
answerMentioned: querySnapshots.answerMentioned,
|
|
980
|
+
citedDomains: querySnapshots.citedDomains,
|
|
981
|
+
rawResponse: querySnapshots.rawResponse,
|
|
982
|
+
snapshotLocation: querySnapshots.location
|
|
983
|
+
}).from(querySnapshots).leftJoin(queries, eq(querySnapshots.queryId, queries.id)).where(eq(querySnapshots.runId, runId)).all();
|
|
984
|
+
const snapshots = [];
|
|
985
|
+
let orphanCount = 0;
|
|
986
|
+
for (const r of rows) {
|
|
987
|
+
const resolvedQuery = r.query ?? r.queryText ?? null;
|
|
988
|
+
if (!resolvedQuery) {
|
|
989
|
+
orphanCount++;
|
|
990
|
+
continue;
|
|
991
|
+
}
|
|
992
|
+
const domains = r.citedDomains;
|
|
993
|
+
const citedCompetitorDomains = competitiveSignalResolver.resolve({
|
|
994
|
+
citedDomains: domains,
|
|
995
|
+
groundingSources: readStoredGroundingSources(r.rawResponse)
|
|
996
|
+
}).citedCompetitorDomains;
|
|
997
|
+
snapshots.push({
|
|
998
|
+
query: resolvedQuery,
|
|
999
|
+
provider: r.provider,
|
|
1000
|
+
cited: r.citationState === CitationStates.cited,
|
|
1001
|
+
// Independent answer-text signal. Tri-state passes through untouched
|
|
1002
|
+
// (true / false / null = "not checked"); computeHealth counts only
|
|
1003
|
+
// exact `true`. Never coerce null→false here.
|
|
1004
|
+
answerMentioned: r.answerMentioned,
|
|
1005
|
+
// The project's OWN cited domain — never a co-cited competitor that
|
|
1006
|
+
// happens to sort first in the full citedDomains set.
|
|
1007
|
+
citationUrl: pickProjectCitedDomain(domains, projectDomains),
|
|
1008
|
+
// Snapshots carry their own location for downstream detectors. In
|
|
1009
|
+
// practice every snapshot in a single runId shares the run's
|
|
1010
|
+
// location; the per-row column is the same value duplicated, but
|
|
1011
|
+
// we read it from the snapshot row so a stale runs.location can't
|
|
1012
|
+
// mask snapshot truth.
|
|
1013
|
+
location: r.snapshotLocation ?? location ?? null,
|
|
1014
|
+
citedCompetitorDomains,
|
|
1015
|
+
// citedDomains is the FULL set (tracked competitors + third-party
|
|
1016
|
+
// sources). Cause analysis uses it to name the displacing source
|
|
1017
|
+
// when no tracked competitor appears in the response.
|
|
1018
|
+
citedDomains: domains
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
if (orphanCount > 0) {
|
|
1022
|
+
log.warn("snapshot.orphan-skip", { runId, projectId, orphanCount });
|
|
1023
|
+
}
|
|
1024
|
+
return { runId, projectId, completedAt, location, snapshots };
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
|
|
1028
|
+
export {
|
|
1029
|
+
addLogListener,
|
|
1030
|
+
createLogger,
|
|
1031
|
+
createFastifyLogger,
|
|
1032
|
+
HISTORY_WINDOW_RUNS,
|
|
1033
|
+
IntelligenceService
|
|
1034
|
+
};
|