@canonry/canonry 7.123.0 → 7.123.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +1 -1
- package/dist/{backfill-5E2D3HFJ.js → backfill-WGEXXMFQ.js} +3 -3
- package/dist/{chunk-FLUYAMPP.js → chunk-7KQESJWH.js} +5 -0
- package/dist/{chunk-7E2TDSUH.js → chunk-7OYOUVZS.js} +14 -14
- package/dist/{chunk-7G4YTMZE.js → chunk-CQSLBPR2.js} +3 -3
- package/dist/{chunk-R2P6XGND.js → chunk-DLJAUCAU.js} +1 -1
- package/dist/{chunk-ITX7ELLK.js → chunk-NDVKLJXW.js} +1 -1
- package/dist/{chunk-TCHIEN67.js → chunk-NI5THOYW.js} +1 -1
- package/dist/{chunk-DPUAVYEG.js → chunk-NNJ6PD64.js} +1 -1
- package/dist/{chunk-RBUT6DJG.js → chunk-TSCCU54X.js} +1 -1
- package/dist/{chunk-AMVQA6NC.js → chunk-WRWTDHSO.js} +603 -545
- package/dist/{cli-commands-AHQK2WVB.js → cli-commands-KWRHN6M5.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{dashboard-S4KT2J34.js → dashboard-2DBFBHAU.js} +1 -1
- package/dist/{demo-E4Q6WQ5R.js → demo-UFZBEKZC.js} +1 -1
- package/dist/{demo-server-GYJZICT7.js → demo-server-3YTYVGJU.js} +2 -2
- package/dist/index.d.ts +30 -30
- package/dist/index.js +6 -6
- package/dist/{init-ZRVCNBSL.js → init-IZ3ANN2I.js} +1 -1
- package/dist/{intelligence-service-G3EHHS35.js → intelligence-service-A6B7TKOX.js} +2 -2
- package/dist/{serve-LWXCQAA2.js → serve-365C4I42.js} +7 -7
- package/dist/{session-4FP4QJTN.js → session-ZB2BI6VG.js} +3 -3
- package/dist/{tools-46YC2R4V.js → tools-57J55S4A.js} +2 -2
- package/package.json +1 -1
|
@@ -24,14 +24,14 @@ import {
|
|
|
24
24
|
resolveConfiguredAgentProvider,
|
|
25
25
|
resolveSessionProviderAndModel,
|
|
26
26
|
setAeroSystemPrompt
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-NI5THOYW.js";
|
|
28
28
|
import {
|
|
29
29
|
AeroToolProfiles,
|
|
30
30
|
AeroToolScopes,
|
|
31
31
|
buildAeroStateTools,
|
|
32
32
|
isAeroToolProfile,
|
|
33
33
|
truncateToolResult
|
|
34
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-NDVKLJXW.js";
|
|
35
35
|
import {
|
|
36
36
|
answerServiceAdapters,
|
|
37
37
|
answerServiceDescriptors
|
|
@@ -69,7 +69,7 @@ import {
|
|
|
69
69
|
openrouterAdapter,
|
|
70
70
|
perplexityAdapter,
|
|
71
71
|
startTrafficReclassification
|
|
72
|
-
} from "./chunk-
|
|
72
|
+
} from "./chunk-TSCCU54X.js";
|
|
73
73
|
import {
|
|
74
74
|
classifyUsageSurface,
|
|
75
75
|
createApiUsageTelemetry,
|
|
@@ -169,7 +169,7 @@ import {
|
|
|
169
169
|
} from "./chunk-DMFFERXC.js";
|
|
170
170
|
import {
|
|
171
171
|
IntelligenceService
|
|
172
|
-
} from "./chunk-
|
|
172
|
+
} from "./chunk-DLJAUCAU.js";
|
|
173
173
|
import {
|
|
174
174
|
computeCitedCompetitorDomains,
|
|
175
175
|
determineCitationState
|
|
@@ -180,6 +180,7 @@ import {
|
|
|
180
180
|
createLogger
|
|
181
181
|
} from "./chunk-LWGO6ETW.js";
|
|
182
182
|
import {
|
|
183
|
+
BING_THROTTLE_COOLDOWN_MS,
|
|
183
184
|
BingApiError,
|
|
184
185
|
CC_CACHE_DIR,
|
|
185
186
|
ChatGptAccounts,
|
|
@@ -211,6 +212,7 @@ import {
|
|
|
211
212
|
bingDateToDay,
|
|
212
213
|
bingKeywordMarket,
|
|
213
214
|
bingPositionOrNull,
|
|
215
|
+
bingThrottleCooldownRemainingMs,
|
|
214
216
|
blockedAddressReason,
|
|
215
217
|
buildLocationProfileFields,
|
|
216
218
|
captureSimpleMeasurementDefinition,
|
|
@@ -332,7 +334,7 @@ import {
|
|
|
332
334
|
webhookTargetRefusalReason,
|
|
333
335
|
webhookUserAgent,
|
|
334
336
|
writeAuditLog
|
|
335
|
-
} from "./chunk-
|
|
337
|
+
} from "./chunk-7KQESJWH.js";
|
|
336
338
|
import {
|
|
337
339
|
OperationalLogStore,
|
|
338
340
|
SentimentIdempotencyConflict,
|
|
@@ -3407,7 +3409,7 @@ import path6 from "path";
|
|
|
3407
3409
|
import { isIP as isIP2 } from "net";
|
|
3408
3410
|
import { fileURLToPath } from "url";
|
|
3409
3411
|
import { setImmediate as yieldToEventLoop4 } from "timers/promises";
|
|
3410
|
-
import { and as and33, eq as
|
|
3412
|
+
import { and as and33, eq as eq40, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql16 } from "drizzle-orm";
|
|
3411
3413
|
|
|
3412
3414
|
// src/seo-runtime.ts
|
|
3413
3415
|
import { eq, inArray } from "drizzle-orm";
|
|
@@ -6469,7 +6471,7 @@ function nonBlank(value) {
|
|
|
6469
6471
|
return trimmed ? trimmed : void 0;
|
|
6470
6472
|
}
|
|
6471
6473
|
function resolveBuildCommit(env = process.env) {
|
|
6472
|
-
const embedded = true ? "
|
|
6474
|
+
const embedded = true ? "91d25b44bae8ffb4644c4890c5270d3fefa0ecb6" : void 0;
|
|
6473
6475
|
return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
|
|
6474
6476
|
}
|
|
6475
6477
|
function resolveInstanceIdentity(env = process.env) {
|
|
@@ -11273,6 +11275,7 @@ function bingRunFailure(err) {
|
|
|
11273
11275
|
return runFailure(err, err instanceof BingApiError && err.isThrottle ? OutcomeReasonCodes.RATE_LIMITED : void 0);
|
|
11274
11276
|
}
|
|
11275
11277
|
var BING_INSPECT_SPACING_MS = 2e3;
|
|
11278
|
+
var BING_INSPECT_RUN_MAX_URLS = 20;
|
|
11276
11279
|
async function executeBingInspectSitemap(db, runId, projectId, opts) {
|
|
11277
11280
|
const reportOutcome = startRunOutcome(db, runId, FeatureNames.bing, "inspect");
|
|
11278
11281
|
let abortCause;
|
|
@@ -11347,20 +11350,17 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
|
|
|
11347
11350
|
if (err instanceof BingApiError && err.isThrottle) throw err;
|
|
11348
11351
|
blockedUrls = /* @__PURE__ */ new Set();
|
|
11349
11352
|
}
|
|
11350
|
-
const skipped = Math.max(0, sitemapUrls.length - INSPECT_SWEEP_MAX_URLS);
|
|
11351
11353
|
const dueUrls = [...sitemapUrls].sort((a, b) => (lastInspected.get(a) ?? "").localeCompare(lastInspected.get(b) ?? ""));
|
|
11352
|
-
const targetUrls = dueUrls.slice(0,
|
|
11353
|
-
|
|
11354
|
-
|
|
11355
|
-
|
|
11356
|
-
|
|
11357
|
-
|
|
11358
|
-
|
|
11359
|
-
|
|
11360
|
-
|
|
11361
|
-
|
|
11362
|
-
});
|
|
11363
|
-
}
|
|
11354
|
+
const targetUrls = dueUrls.slice(0, BING_INSPECT_RUN_MAX_URLS);
|
|
11355
|
+
const rotated = sitemapUrls.length - targetUrls.length;
|
|
11356
|
+
log10.info("inspect.batch", {
|
|
11357
|
+
runId,
|
|
11358
|
+
projectId,
|
|
11359
|
+
sitemapUrls: sitemapUrls.length,
|
|
11360
|
+
inspecting: targetUrls.length,
|
|
11361
|
+
neverInspected: discovered.length,
|
|
11362
|
+
rotated
|
|
11363
|
+
});
|
|
11364
11364
|
const siteUrl = conn.siteUrl;
|
|
11365
11365
|
let lastInspectError;
|
|
11366
11366
|
let lastInspectFailurePhase;
|
|
@@ -11499,8 +11499,8 @@ async function executeBingInspectSitemap(db, runId, projectId, opts) {
|
|
|
11499
11499
|
syncRunId: runId
|
|
11500
11500
|
}
|
|
11501
11501
|
}).run();
|
|
11502
|
-
const status = errors > 0 || outcome.aborted
|
|
11503
|
-
const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped after provider failures; ${
|
|
11502
|
+
const status = errors > 0 || outcome.aborted ? RunStatuses.partial : RunStatuses.completed;
|
|
11503
|
+
const degradedReason = status === RunStatuses.completed ? null : outcome.aborted ? `Stopped after provider failures; ${targetUrls.length - inspected} of ${targetUrls.length} pages in this run's batch were not inspected (${targetUrls.length - inspected - errors} not attempted).` : `${errors} of ${targetUrls.length} pages could not be inspected.`;
|
|
11504
11504
|
db.update(runs).set({ status, error: degradedReason, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq13(runs.id, runId)).run();
|
|
11505
11505
|
log10.info("inspect.completed", {
|
|
11506
11506
|
runId,
|
|
@@ -12010,10 +12010,58 @@ async function executeBingSync(db, runId, projectId, opts) {
|
|
|
12010
12010
|
}
|
|
12011
12011
|
}
|
|
12012
12012
|
|
|
12013
|
+
// src/bing-job-lane.ts
|
|
12014
|
+
import { eq as eq15 } from "drizzle-orm";
|
|
12015
|
+
var log12 = createLogger("BingJobLane");
|
|
12016
|
+
var BING_LANE_MAX_COOLDOWN_WAIT_MS = BING_THROTTLE_COOLDOWN_MS + 6e4;
|
|
12017
|
+
var lanes = /* @__PURE__ */ new Map();
|
|
12018
|
+
function acquire(key, kind) {
|
|
12019
|
+
const lane = lanes.get(key);
|
|
12020
|
+
if (!lane) {
|
|
12021
|
+
lanes.set(key, { waiting: [] });
|
|
12022
|
+
return Promise.resolve();
|
|
12023
|
+
}
|
|
12024
|
+
log12.info("lane.wait", { kind, ahead: lane.waiting.length + 1 });
|
|
12025
|
+
return new Promise((start) => lane.waiting.push({ kind, start }));
|
|
12026
|
+
}
|
|
12027
|
+
function release(key) {
|
|
12028
|
+
const lane = lanes.get(key);
|
|
12029
|
+
if (!lane) return;
|
|
12030
|
+
const syncIndex = lane.waiting.findIndex((waiter) => waiter.kind === "sync");
|
|
12031
|
+
const next = syncIndex >= 0 ? lane.waiting.splice(syncIndex, 1)[0] : lane.waiting.shift();
|
|
12032
|
+
if (next) next.start();
|
|
12033
|
+
else lanes.delete(key);
|
|
12034
|
+
}
|
|
12035
|
+
var realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
12036
|
+
async function runInBingLane(apiKey, kind, work, deps = {}) {
|
|
12037
|
+
const key = credentialGateKey("bing", apiKey);
|
|
12038
|
+
await acquire(key, kind);
|
|
12039
|
+
try {
|
|
12040
|
+
const cooling = bingThrottleCooldownRemainingMs(apiKey);
|
|
12041
|
+
if (cooling > 0) {
|
|
12042
|
+
const waitMs = Math.min(cooling, BING_LANE_MAX_COOLDOWN_WAIT_MS);
|
|
12043
|
+
log12.info("lane.cooldown-wait", { kind, waitMs });
|
|
12044
|
+
await (deps.sleep ?? realSleep)(waitMs);
|
|
12045
|
+
}
|
|
12046
|
+
return await work();
|
|
12047
|
+
} finally {
|
|
12048
|
+
release(key);
|
|
12049
|
+
}
|
|
12050
|
+
}
|
|
12051
|
+
function bingApiKeyForProject(db, config, projectId) {
|
|
12052
|
+
const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq15(projects.id, projectId)).get();
|
|
12053
|
+
if (!project) return null;
|
|
12054
|
+
return config.bing?.connections?.find((conn) => conn.domain === project.canonicalDomain)?.apiKey ?? null;
|
|
12055
|
+
}
|
|
12056
|
+
async function runBingJob(db, config, projectId, kind, work, deps = {}) {
|
|
12057
|
+
const apiKey = bingApiKeyForProject(db, config, projectId);
|
|
12058
|
+
return apiKey ? await runInBingLane(apiKey, kind, work, deps) : await work();
|
|
12059
|
+
}
|
|
12060
|
+
|
|
12013
12061
|
// src/coverage-refresh.ts
|
|
12014
12062
|
import crypto18 from "crypto";
|
|
12015
|
-
import { and as and11, desc as desc6, eq as
|
|
12016
|
-
var
|
|
12063
|
+
import { and as and11, desc as desc6, eq as eq16, inArray as inArray7 } from "drizzle-orm";
|
|
12064
|
+
var log13 = createLogger("CoverageRefresh");
|
|
12017
12065
|
var COVERAGE_REFRESH_MIN_INTERVAL_MS = 60 * 60 * 1e3;
|
|
12018
12066
|
var COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS = 2 * 60 * 1e3;
|
|
12019
12067
|
var ACTIVE_OR_DONE_STATUSES = [
|
|
@@ -12024,12 +12072,12 @@ var ACTIVE_OR_DONE_STATUSES = [
|
|
|
12024
12072
|
];
|
|
12025
12073
|
var IN_FLIGHT_STATUSES = [RunStatuses.queued, RunStatuses.running];
|
|
12026
12074
|
function runWasUserInitiated(db, runId) {
|
|
12027
|
-
const row = db.select({ trigger: runs.trigger }).from(runs).where(
|
|
12075
|
+
const row = db.select({ trigger: runs.trigger }).from(runs).where(eq16(runs.id, runId)).get();
|
|
12028
12076
|
return row?.trigger === RunTriggers.manual;
|
|
12029
12077
|
}
|
|
12030
12078
|
var defaultDeps = { executeInspectSitemap };
|
|
12031
12079
|
async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps, nowMs = Date.now(), opts = {}) {
|
|
12032
|
-
const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(
|
|
12080
|
+
const project = db.select({ canonicalDomain: projects.canonicalDomain }).from(projects).where(eq16(projects.id, projectId)).get();
|
|
12033
12081
|
if (!project) return null;
|
|
12034
12082
|
const { clientId, clientSecret } = getGoogleAuthConfig(config);
|
|
12035
12083
|
if (!clientId || !clientSecret) return null;
|
|
@@ -12037,27 +12085,27 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
|
|
|
12037
12085
|
if (!conn?.refreshToken || !conn.propertyId) return null;
|
|
12038
12086
|
const inFlight = db.select({ createdAt: runs.createdAt }).from(runs).where(
|
|
12039
12087
|
and11(
|
|
12040
|
-
|
|
12041
|
-
|
|
12088
|
+
eq16(runs.projectId, projectId),
|
|
12089
|
+
eq16(runs.kind, RunKinds["inspect-sitemap"]),
|
|
12042
12090
|
inArray7(runs.status, IN_FLIGHT_STATUSES)
|
|
12043
12091
|
)
|
|
12044
12092
|
).orderBy(desc6(runs.createdAt)).limit(1).get();
|
|
12045
12093
|
if (inFlight) {
|
|
12046
|
-
|
|
12094
|
+
log13.info("skip.in-flight", { projectId });
|
|
12047
12095
|
return null;
|
|
12048
12096
|
}
|
|
12049
12097
|
const windowMs = opts.userInitiated ? COVERAGE_REFRESH_MANUAL_MIN_INTERVAL_MS : COVERAGE_REFRESH_MIN_INTERVAL_MS;
|
|
12050
12098
|
const recent = db.select({ createdAt: runs.createdAt }).from(runs).where(
|
|
12051
12099
|
and11(
|
|
12052
|
-
|
|
12053
|
-
|
|
12100
|
+
eq16(runs.projectId, projectId),
|
|
12101
|
+
eq16(runs.kind, RunKinds["inspect-sitemap"]),
|
|
12054
12102
|
inArray7(runs.status, ACTIVE_OR_DONE_STATUSES)
|
|
12055
12103
|
)
|
|
12056
12104
|
).orderBy(desc6(runs.createdAt)).limit(1).get();
|
|
12057
12105
|
if (recent) {
|
|
12058
12106
|
const ageMs = nowMs - Date.parse(recent.createdAt);
|
|
12059
12107
|
if (Number.isFinite(ageMs) && ageMs < windowMs) {
|
|
12060
|
-
|
|
12108
|
+
log13.info("skip.recent", { projectId, ageMs, windowMs, userInitiated: opts.userInitiated === true });
|
|
12061
12109
|
return null;
|
|
12062
12110
|
}
|
|
12063
12111
|
}
|
|
@@ -12070,11 +12118,11 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
|
|
|
12070
12118
|
trigger: RunTriggers.scheduled,
|
|
12071
12119
|
createdAt: new Date(nowMs).toISOString()
|
|
12072
12120
|
}).run();
|
|
12073
|
-
|
|
12121
|
+
log13.info("refresh.start", { projectId, runId });
|
|
12074
12122
|
try {
|
|
12075
12123
|
await deps.executeInspectSitemap(db, runId, projectId, { config });
|
|
12076
12124
|
} catch (err) {
|
|
12077
|
-
|
|
12125
|
+
log13.error("refresh.failed", {
|
|
12078
12126
|
projectId,
|
|
12079
12127
|
runId,
|
|
12080
12128
|
error: describeError(err)
|
|
@@ -12086,8 +12134,8 @@ async function maybeRefreshGscCoverage(db, config, projectId, deps = defaultDeps
|
|
|
12086
12134
|
// src/commoncrawl-sync.ts
|
|
12087
12135
|
import crypto19 from "crypto";
|
|
12088
12136
|
import path5 from "path";
|
|
12089
|
-
import { and as and12, eq as
|
|
12090
|
-
var
|
|
12137
|
+
import { and as and12, eq as eq17, sql as sql6 } from "drizzle-orm";
|
|
12138
|
+
var log14 = createLogger("CommonCrawlSync");
|
|
12091
12139
|
var INSERT_CHUNK_SIZE = 1e4;
|
|
12092
12140
|
function defaultDeps2() {
|
|
12093
12141
|
return {
|
|
@@ -12100,7 +12148,7 @@ function defaultDeps2() {
|
|
|
12100
12148
|
}
|
|
12101
12149
|
async function executeReleaseSync(db, syncId, opts) {
|
|
12102
12150
|
const deps = { ...defaultDeps2(), ...opts.deps };
|
|
12103
|
-
const
|
|
12151
|
+
const release2 = opts.release;
|
|
12104
12152
|
const outcome = {
|
|
12105
12153
|
feature: "backlinks",
|
|
12106
12154
|
operation: "sync",
|
|
@@ -12109,9 +12157,9 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12109
12157
|
const elapsed = startOutcomeTimer();
|
|
12110
12158
|
let invalidRelease = false;
|
|
12111
12159
|
try {
|
|
12112
|
-
if (!isValidReleaseId(
|
|
12160
|
+
if (!isValidReleaseId(release2)) {
|
|
12113
12161
|
invalidRelease = true;
|
|
12114
|
-
throw new Error(`Invalid release id: ${
|
|
12162
|
+
throw new Error(`Invalid release id: ${release2}`);
|
|
12115
12163
|
}
|
|
12116
12164
|
if (db.select({ id: projects.id }).from(projects).limit(1).get()) deps.loadDuckdb();
|
|
12117
12165
|
const downloadStartedAt = deps.now().toISOString();
|
|
@@ -12121,9 +12169,9 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12121
12169
|
phaseDetail: "downloading vertices + edges",
|
|
12122
12170
|
updatedAt: downloadStartedAt,
|
|
12123
12171
|
error: null
|
|
12124
|
-
}).where(
|
|
12125
|
-
const paths = ccReleasePaths(
|
|
12126
|
-
const releaseCacheDir = path5.join(deps.cacheDir,
|
|
12172
|
+
}).where(eq17(ccReleaseSyncs.id, syncId)).run();
|
|
12173
|
+
const paths = ccReleasePaths(release2);
|
|
12174
|
+
const releaseCacheDir = path5.join(deps.cacheDir, release2);
|
|
12127
12175
|
const vertexPath = path5.join(releaseCacheDir, paths.vertexFilename);
|
|
12128
12176
|
const edgesPath = path5.join(releaseCacheDir, paths.edgesFilename);
|
|
12129
12177
|
const [vertex, edges] = await Promise.all([
|
|
@@ -12144,7 +12192,7 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12144
12192
|
vertexSha256: vertex.sha256,
|
|
12145
12193
|
edgesSha256: edges.sha256,
|
|
12146
12194
|
updatedAt: downloadFinishedAt
|
|
12147
|
-
}).where(
|
|
12195
|
+
}).where(eq17(ccReleaseSyncs.id, syncId)).run();
|
|
12148
12196
|
const allProjects = db.select().from(projects).all();
|
|
12149
12197
|
const targets = Array.from(new Set(allProjects.map((p) => p.canonicalDomain)));
|
|
12150
12198
|
let rows = [];
|
|
@@ -12160,8 +12208,8 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12160
12208
|
}
|
|
12161
12209
|
const queriedAt = deps.now().toISOString();
|
|
12162
12210
|
db.transaction((tx) => {
|
|
12163
|
-
tx.delete(backlinkDomains).where(
|
|
12164
|
-
tx.delete(backlinkSummaries).where(
|
|
12211
|
+
tx.delete(backlinkDomains).where(eq17(backlinkDomains.releaseSyncId, syncId)).run();
|
|
12212
|
+
tx.delete(backlinkSummaries).where(eq17(backlinkSummaries.releaseSyncId, syncId)).run();
|
|
12165
12213
|
const expanded = [];
|
|
12166
12214
|
for (const r of rows) {
|
|
12167
12215
|
const projectIds = projectsByDomain.get(r.targetDomain);
|
|
@@ -12171,7 +12219,7 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12171
12219
|
id: crypto19.randomUUID(),
|
|
12172
12220
|
projectId,
|
|
12173
12221
|
releaseSyncId: syncId,
|
|
12174
|
-
release,
|
|
12222
|
+
release: release2,
|
|
12175
12223
|
targetDomain: r.targetDomain,
|
|
12176
12224
|
linkingDomain: r.linkingDomain,
|
|
12177
12225
|
numHosts: r.numHosts,
|
|
@@ -12192,7 +12240,7 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12192
12240
|
projectId: p.id,
|
|
12193
12241
|
releaseSyncId: syncId,
|
|
12194
12242
|
source: BacklinkSources.commoncrawl,
|
|
12195
|
-
release,
|
|
12243
|
+
release: release2,
|
|
12196
12244
|
targetDomain: p.canonicalDomain,
|
|
12197
12245
|
totalLinkingDomains: summary.totalLinkingDomains,
|
|
12198
12246
|
totalHosts: summary.totalHosts,
|
|
@@ -12221,10 +12269,10 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12221
12269
|
domainsDiscovered: rows.length,
|
|
12222
12270
|
updatedAt: finishedAt,
|
|
12223
12271
|
error: null
|
|
12224
|
-
}).where(
|
|
12225
|
-
|
|
12272
|
+
}).where(eq17(ccReleaseSyncs.id, syncId)).run();
|
|
12273
|
+
log14.info("sync.completed", {
|
|
12226
12274
|
syncId,
|
|
12227
|
-
release,
|
|
12275
|
+
release: release2,
|
|
12228
12276
|
projectsProcessed: allProjects.length,
|
|
12229
12277
|
domainsDiscovered: rows.length
|
|
12230
12278
|
});
|
|
@@ -12238,11 +12286,11 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12238
12286
|
const autoExtractProjects = allProjects.filter((p) => p.autoExtractBacklinks);
|
|
12239
12287
|
for (const p of autoExtractProjects) {
|
|
12240
12288
|
try {
|
|
12241
|
-
deps.enqueueAutoExtract({ projectId: p.id, release });
|
|
12289
|
+
deps.enqueueAutoExtract({ projectId: p.id, release: release2 });
|
|
12242
12290
|
} catch (err) {
|
|
12243
|
-
|
|
12291
|
+
log14.error("auto-extract.enqueue-failed", {
|
|
12244
12292
|
syncId,
|
|
12245
|
-
release,
|
|
12293
|
+
release: release2,
|
|
12246
12294
|
projectId: p.id,
|
|
12247
12295
|
error: describeError(err)
|
|
12248
12296
|
});
|
|
@@ -12257,8 +12305,8 @@ async function executeReleaseSync(db, syncId, opts) {
|
|
|
12257
12305
|
error: errorMsg,
|
|
12258
12306
|
phaseDetail: null,
|
|
12259
12307
|
updatedAt: finishedAt
|
|
12260
|
-
}).where(
|
|
12261
|
-
|
|
12308
|
+
}).where(eq17(ccReleaseSyncs.id, syncId)).run();
|
|
12309
|
+
log14.error("sync.failed", { syncId, release: release2, error: errorMsg });
|
|
12262
12310
|
trackFeatureCompleted({
|
|
12263
12311
|
...outcome,
|
|
12264
12312
|
status: OutcomeStatuses.failed,
|
|
@@ -12290,7 +12338,7 @@ async function syncLatestReleaseOnSchedule(projectName, deps) {
|
|
|
12290
12338
|
if (probed === null) report({ status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_FOUND });
|
|
12291
12339
|
return;
|
|
12292
12340
|
}
|
|
12293
|
-
const alreadySynced = deps.db.select().from(ccReleaseSyncs).where(and12(
|
|
12341
|
+
const alreadySynced = deps.db.select().from(ccReleaseSyncs).where(and12(eq17(ccReleaseSyncs.release, probed.release), eq17(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready))).limit(1).get();
|
|
12294
12342
|
if (alreadySynced) {
|
|
12295
12343
|
deps.log.info({ projectName, release: probed.release }, "Scheduled backlinks sync: already up to date, skipping");
|
|
12296
12344
|
report({ status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NOT_DUE });
|
|
@@ -12323,8 +12371,8 @@ function groupByProject(rows, projectsByDomain) {
|
|
|
12323
12371
|
// src/backlink-extract.ts
|
|
12324
12372
|
import crypto20 from "crypto";
|
|
12325
12373
|
import fs5 from "fs";
|
|
12326
|
-
import { and as and13, desc as desc7, eq as
|
|
12327
|
-
var
|
|
12374
|
+
import { and as and13, desc as desc7, eq as eq18 } from "drizzle-orm";
|
|
12375
|
+
var log15 = createLogger("BacklinkExtract");
|
|
12328
12376
|
function defaultDeps3() {
|
|
12329
12377
|
return {
|
|
12330
12378
|
queryBacklinks,
|
|
@@ -12337,14 +12385,14 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
|
|
|
12337
12385
|
const startedAt = deps.now().toISOString();
|
|
12338
12386
|
const reportOutcome = startRunOutcome(db, runId, "backlinks", "extract");
|
|
12339
12387
|
let refusal;
|
|
12340
|
-
db.update(runs).set({ status: RunStatuses.running, startedAt }).where(
|
|
12388
|
+
db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq18(runs.id, runId)).run();
|
|
12341
12389
|
try {
|
|
12342
|
-
const project = db.select().from(projects).where(
|
|
12390
|
+
const project = db.select().from(projects).where(eq18(projects.id, projectId)).get();
|
|
12343
12391
|
if (!project) {
|
|
12344
12392
|
refusal = OutcomeReasonCodes.NOT_FOUND;
|
|
12345
12393
|
throw new Error(`Project not found: ${projectId}`);
|
|
12346
12394
|
}
|
|
12347
|
-
const sync = opts.release ? db.select().from(ccReleaseSyncs).where(
|
|
12395
|
+
const sync = opts.release ? db.select().from(ccReleaseSyncs).where(eq18(ccReleaseSyncs.release, opts.release)).get() : db.select().from(ccReleaseSyncs).where(eq18(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready)).orderBy(desc7(ccReleaseSyncs.createdAt)).limit(1).get();
|
|
12348
12396
|
refusal = OutcomeReasonCodes.NO_DATA;
|
|
12349
12397
|
if (!sync) {
|
|
12350
12398
|
throw new Error("No ready release sync available \u2014 run `canonry backlinks sync` first");
|
|
@@ -12370,14 +12418,14 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
|
|
|
12370
12418
|
});
|
|
12371
12419
|
const queriedAt = deps.now().toISOString();
|
|
12372
12420
|
const syncId = sync.id;
|
|
12373
|
-
const
|
|
12421
|
+
const release2 = sync.release;
|
|
12374
12422
|
const targetDomain = project.canonicalDomain;
|
|
12375
12423
|
db.transaction((tx) => {
|
|
12376
12424
|
tx.delete(backlinkDomains).where(
|
|
12377
12425
|
and13(
|
|
12378
|
-
|
|
12379
|
-
|
|
12380
|
-
|
|
12426
|
+
eq18(backlinkDomains.projectId, projectId),
|
|
12427
|
+
eq18(backlinkDomains.source, BacklinkSources.commoncrawl),
|
|
12428
|
+
eq18(backlinkDomains.release, release2)
|
|
12381
12429
|
)
|
|
12382
12430
|
).run();
|
|
12383
12431
|
if (rows.length > 0) {
|
|
@@ -12386,7 +12434,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
|
|
|
12386
12434
|
projectId,
|
|
12387
12435
|
releaseSyncId: syncId,
|
|
12388
12436
|
source: BacklinkSources.commoncrawl,
|
|
12389
|
-
release,
|
|
12437
|
+
release: release2,
|
|
12390
12438
|
targetDomain,
|
|
12391
12439
|
linkingDomain: r.linkingDomain,
|
|
12392
12440
|
numHosts: r.numHosts,
|
|
@@ -12400,7 +12448,7 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
|
|
|
12400
12448
|
projectId,
|
|
12401
12449
|
releaseSyncId: syncId,
|
|
12402
12450
|
source: BacklinkSources.commoncrawl,
|
|
12403
|
-
release,
|
|
12451
|
+
release: release2,
|
|
12404
12452
|
targetDomain,
|
|
12405
12453
|
totalLinkingDomains: summary2.totalLinkingDomains,
|
|
12406
12454
|
totalHosts: summary2.totalHosts,
|
|
@@ -12420,8 +12468,8 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
|
|
|
12420
12468
|
}).run();
|
|
12421
12469
|
});
|
|
12422
12470
|
const finishedAt = deps.now().toISOString();
|
|
12423
|
-
db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(
|
|
12424
|
-
|
|
12471
|
+
db.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq18(runs.id, runId)).run();
|
|
12472
|
+
log15.info("extract.completed", { runId, projectId, release: release2, rows: rows.length });
|
|
12425
12473
|
const summary = computeSummary(rows);
|
|
12426
12474
|
reportOutcome({ status: OutcomeStatuses.succeeded, counts: { domains: summary.totalLinkingDomains, links: summary.totalHosts } });
|
|
12427
12475
|
} catch (err) {
|
|
@@ -12431,8 +12479,8 @@ async function executeBacklinkExtract(db, runId, projectId, opts = {}) {
|
|
|
12431
12479
|
status: RunStatuses.failed,
|
|
12432
12480
|
error: errorMsg,
|
|
12433
12481
|
finishedAt
|
|
12434
|
-
}).where(
|
|
12435
|
-
|
|
12482
|
+
}).where(eq18(runs.id, runId)).run();
|
|
12483
|
+
log15.error("extract.failed", { runId, projectId, error: errorMsg });
|
|
12436
12484
|
reportOutcome({ status: OutcomeStatuses.failed, ...outcomeFailure(err, refusal) });
|
|
12437
12485
|
throw err;
|
|
12438
12486
|
}
|
|
@@ -12443,8 +12491,8 @@ function computeSummary(rows) {
|
|
|
12443
12491
|
|
|
12444
12492
|
// src/discovery-run.ts
|
|
12445
12493
|
import crypto21 from "crypto";
|
|
12446
|
-
import { and as and14, eq as
|
|
12447
|
-
var
|
|
12494
|
+
import { and as and14, eq as eq19 } from "drizzle-orm";
|
|
12495
|
+
var log16 = createLogger("DiscoveryRun");
|
|
12448
12496
|
var DEFAULT_SEED_COUNT = 30;
|
|
12449
12497
|
var EMBED_RETRY_MAX_RETRIES = 3;
|
|
12450
12498
|
var EMBED_RETRY_MAX_DELAY_MS = 1e4;
|
|
@@ -12476,7 +12524,7 @@ async function embedWithRetry(fn) {
|
|
|
12476
12524
|
isRetryable: isRetryableHttpError,
|
|
12477
12525
|
maxDelayMs: EMBED_RETRY_MAX_DELAY_MS,
|
|
12478
12526
|
onRetry: ({ attempt, delayMs }) => {
|
|
12479
|
-
|
|
12527
|
+
log16.warn("discovery.embed.retry", { attempt, delayMs });
|
|
12480
12528
|
}
|
|
12481
12529
|
}
|
|
12482
12530
|
);
|
|
@@ -12486,11 +12534,11 @@ async function executeDiscoveryRun(opts) {
|
|
|
12486
12534
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
12487
12535
|
const reportOutcome = startRunOutcome(opts.db, opts.runId, "discovery", "run");
|
|
12488
12536
|
let notConfigured = false;
|
|
12489
|
-
opts.db.update(runs).set({ status: RunStatuses.running, startedAt }).where(
|
|
12537
|
+
opts.db.update(runs).set({ status: RunStatuses.running, startedAt }).where(eq19(runs.id, opts.runId)).run();
|
|
12490
12538
|
try {
|
|
12491
|
-
const projectRow = opts.db.select().from(projects).where(
|
|
12539
|
+
const projectRow = opts.db.select().from(projects).where(eq19(projects.id, opts.projectId)).get();
|
|
12492
12540
|
if (!projectRow) throw new Error(`Project ${opts.projectId} not found`);
|
|
12493
|
-
const projectCompetitors = opts.db.select({ domain: competitors.domain }).from(competitors).where(
|
|
12541
|
+
const projectCompetitors = opts.db.select({ domain: competitors.domain }).from(competitors).where(eq19(competitors.projectId, opts.projectId)).orderBy(competitors.domain).all().map((r) => r.domain.toLowerCase());
|
|
12494
12542
|
const canonicalDomains = effectiveDomains({
|
|
12495
12543
|
canonicalDomain: projectRow.canonicalDomain,
|
|
12496
12544
|
ownedDomains: projectRow.ownedDomains
|
|
@@ -12532,8 +12580,8 @@ async function executeDiscoveryRun(opts) {
|
|
|
12532
12580
|
seedProvider: result.seedProvider,
|
|
12533
12581
|
result
|
|
12534
12582
|
});
|
|
12535
|
-
opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
|
|
12536
|
-
|
|
12583
|
+
opts.db.update(runs).set({ status: RunStatuses.completed, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq19(runs.id, opts.runId)).run();
|
|
12584
|
+
log16.info("discovery.completed", {
|
|
12537
12585
|
runId: opts.runId,
|
|
12538
12586
|
sessionId: opts.sessionId,
|
|
12539
12587
|
buckets: result.buckets,
|
|
@@ -12550,13 +12598,13 @@ async function executeDiscoveryRun(opts) {
|
|
|
12550
12598
|
});
|
|
12551
12599
|
} catch (err) {
|
|
12552
12600
|
const errorMsg = describeError(err);
|
|
12553
|
-
|
|
12601
|
+
log16.error("discovery.failed", { runId: opts.runId, sessionId: opts.sessionId, error: errorMsg });
|
|
12554
12602
|
markSessionFailed(opts.db, opts.sessionId, errorMsg);
|
|
12555
12603
|
opts.db.update(runs).set({
|
|
12556
12604
|
status: RunStatuses.failed,
|
|
12557
12605
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
12558
12606
|
error: errorMsg
|
|
12559
|
-
}).where(
|
|
12607
|
+
}).where(eq19(runs.id, opts.runId)).run();
|
|
12560
12608
|
const failure2 = classifyProviderOutcomeError(err);
|
|
12561
12609
|
reportOutcome({
|
|
12562
12610
|
status: OutcomeStatuses.failed,
|
|
@@ -12826,9 +12874,9 @@ function writeDiscoveryInsight(db, input) {
|
|
|
12826
12874
|
});
|
|
12827
12875
|
db.transaction((tx) => {
|
|
12828
12876
|
tx.update(insights).set({ dismissed: true }).where(and14(
|
|
12829
|
-
|
|
12830
|
-
|
|
12831
|
-
|
|
12877
|
+
eq19(insights.projectId, input.projectId),
|
|
12878
|
+
eq19(insights.type, "discovery.basket-divergence"),
|
|
12879
|
+
eq19(insights.dismissed, false)
|
|
12832
12880
|
)).run();
|
|
12833
12881
|
tx.insert(insights).values({
|
|
12834
12882
|
id: crypto21.randomUUID(),
|
|
@@ -12868,7 +12916,7 @@ function buildDiscoveryInsightTitle(input) {
|
|
|
12868
12916
|
|
|
12869
12917
|
// src/execute-site-audit.ts
|
|
12870
12918
|
import crypto22 from "crypto";
|
|
12871
|
-
import { and as and17, eq as
|
|
12919
|
+
import { and as and17, eq as eq22, ne as ne2, sql as sql7 } from "drizzle-orm";
|
|
12872
12920
|
import { runSiteCrawl } from "@canonry/agent-readiness";
|
|
12873
12921
|
|
|
12874
12922
|
// src/site-audit-root.ts
|
|
@@ -13056,7 +13104,7 @@ async function requestPinnedSiteAuditRoot(target, options) {
|
|
|
13056
13104
|
}
|
|
13057
13105
|
|
|
13058
13106
|
// src/site-crawl-template-links.ts
|
|
13059
|
-
import { and as and15, asc as asc3, eq as
|
|
13107
|
+
import { and as and15, asc as asc3, eq as eq20, gt as gt2, inArray as inArray8 } from "drizzle-orm";
|
|
13060
13108
|
var TEMPLATE_LINK_READ_BATCH = 2e3;
|
|
13061
13109
|
var TEMPLATE_LINK_WRITE_BATCH = 500;
|
|
13062
13110
|
function placementOccurrencesOf(row) {
|
|
@@ -13079,9 +13127,9 @@ function* streamAttemptEdges(db, scope) {
|
|
|
13079
13127
|
placementContentOccurrences: siteCrawlEdges.placementContentOccurrences,
|
|
13080
13128
|
placementUnknownOccurrences: siteCrawlEdges.placementUnknownOccurrences
|
|
13081
13129
|
}).from(siteCrawlEdges).where(and15(
|
|
13082
|
-
|
|
13083
|
-
|
|
13084
|
-
|
|
13130
|
+
eq20(siteCrawlEdges.projectId, scope.projectId),
|
|
13131
|
+
eq20(siteCrawlEdges.runId, scope.runId),
|
|
13132
|
+
eq20(siteCrawlEdges.attemptId, scope.attemptId),
|
|
13085
13133
|
gt2(siteCrawlEdges.edgeKey, after)
|
|
13086
13134
|
)).orderBy(asc3(siteCrawlEdges.edgeKey)).limit(TEMPLATE_LINK_READ_BATCH).all();
|
|
13087
13135
|
if (rows.length === 0) return;
|
|
@@ -13107,9 +13155,9 @@ function writeGroupKey(isTemplate, templateRatio) {
|
|
|
13107
13155
|
}
|
|
13108
13156
|
function classifySiteCrawlTemplateLinks(db, scope, pagesFetched, placementRulesetVersion) {
|
|
13109
13157
|
const scopeFilter = and15(
|
|
13110
|
-
|
|
13111
|
-
|
|
13112
|
-
|
|
13158
|
+
eq20(siteCrawlEdges.projectId, scope.projectId),
|
|
13159
|
+
eq20(siteCrawlEdges.runId, scope.runId),
|
|
13160
|
+
eq20(siteCrawlEdges.attemptId, scope.attemptId)
|
|
13113
13161
|
);
|
|
13114
13162
|
const placementAvailable = templateLinkPlacementAvailable(placementRulesetVersion);
|
|
13115
13163
|
const ubiquityAvailable = templateLinkUbiquityAvailable(pagesFetched);
|
|
@@ -13180,7 +13228,7 @@ function buildSiteCrawlIssueEvidence(siteIssues, pages) {
|
|
|
13180
13228
|
}
|
|
13181
13229
|
|
|
13182
13230
|
// src/site-audit-entity-registry.ts
|
|
13183
|
-
import { and as and16, eq as
|
|
13231
|
+
import { and as and16, eq as eq21 } from "drizzle-orm";
|
|
13184
13232
|
function entityMatcher(matcher) {
|
|
13185
13233
|
switch (matcher.kind) {
|
|
13186
13234
|
case "prefix":
|
|
@@ -13208,9 +13256,9 @@ function planEntityRegistry(plan) {
|
|
|
13208
13256
|
};
|
|
13209
13257
|
}
|
|
13210
13258
|
function activePlanEntityRegistry(db, projectId) {
|
|
13211
|
-
const pointer = db.select({ versionId: measurementPlans.activeVersionId }).from(measurementPlans).where(
|
|
13259
|
+
const pointer = db.select({ versionId: measurementPlans.activeVersionId }).from(measurementPlans).where(eq21(measurementPlans.projectId, projectId)).get();
|
|
13212
13260
|
if (!pointer) return null;
|
|
13213
|
-
const version = db.select({ revision: measurementPlanVersions.revision, canonicalJson: measurementPlanVersions.canonicalJson }).from(measurementPlanVersions).where(and16(
|
|
13261
|
+
const version = db.select({ revision: measurementPlanVersions.revision, canonicalJson: measurementPlanVersions.canonicalJson }).from(measurementPlanVersions).where(and16(eq21(measurementPlanVersions.projectId, projectId), eq21(measurementPlanVersions.id, pointer.versionId))).get();
|
|
13214
13262
|
if (!version) return null;
|
|
13215
13263
|
const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
|
|
13216
13264
|
if (plan.schemaVersion !== MEASUREMENT_PLAN_V2_SCHEMA_VERSION) return null;
|
|
@@ -13219,7 +13267,7 @@ function activePlanEntityRegistry(db, projectId) {
|
|
|
13219
13267
|
}
|
|
13220
13268
|
|
|
13221
13269
|
// src/execute-site-audit.ts
|
|
13222
|
-
var
|
|
13270
|
+
var log17 = createLogger("SiteAudit");
|
|
13223
13271
|
var SiteAuditCancelledError = class extends Error {
|
|
13224
13272
|
name = "SiteAuditCancelledError";
|
|
13225
13273
|
};
|
|
@@ -13420,7 +13468,7 @@ function trackSiteAuditOutcome(db, input) {
|
|
|
13420
13468
|
);
|
|
13421
13469
|
const pagesAudited = input.crawl?.pagesAudited ?? 0;
|
|
13422
13470
|
if (pagesAudited === 0 || input.trigger === RunTriggers.probe) return;
|
|
13423
|
-
const prior = db.select({ id: siteAuditSnapshots.id }).from(siteAuditSnapshots).where(and17(
|
|
13471
|
+
const prior = db.select({ id: siteAuditSnapshots.id }).from(siteAuditSnapshots).where(and17(eq22(siteAuditSnapshots.projectId, input.projectId), ne2(siteAuditSnapshots.runId, input.runId))).limit(1).get();
|
|
13424
13472
|
if (prior) return;
|
|
13425
13473
|
trackEvent("activation.completed", {
|
|
13426
13474
|
flowVersion: ONBOARDING_FLOW_VERSION,
|
|
@@ -13429,19 +13477,19 @@ function trackSiteAuditOutcome(db, input) {
|
|
|
13429
13477
|
pagesAuditedBucket: bucketOnboardingCount(pagesAudited)
|
|
13430
13478
|
});
|
|
13431
13479
|
} catch (error) {
|
|
13432
|
-
|
|
13480
|
+
log17.warn("telemetry.failed", { runId: input.runId, projectId: input.projectId, error: describeError(error) });
|
|
13433
13481
|
}
|
|
13434
13482
|
}
|
|
13435
13483
|
async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
13436
13484
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
13437
|
-
const claim = db.update(runs).set({ status: "running", startedAt }).where(and17(
|
|
13485
|
+
const claim = db.update(runs).set({ status: "running", startedAt }).where(and17(eq22(runs.id, runId), eq22(runs.projectId, projectId), eq22(runs.status, "queued"))).run();
|
|
13438
13486
|
if (claim.changes === 0) return;
|
|
13439
13487
|
const startTime = Date.now();
|
|
13440
13488
|
const operationId = crypto22.randomUUID();
|
|
13441
13489
|
let phase = OutcomePhases.setup;
|
|
13442
|
-
const trigger = db.select({ trigger: runs.trigger }).from(runs).where(
|
|
13490
|
+
const trigger = db.select({ trigger: runs.trigger }).from(runs).where(eq22(runs.id, runId)).get()?.trigger ?? null;
|
|
13443
13491
|
let canonicalDomain = null;
|
|
13444
|
-
const attemptNumber = (db.select({ value: sql7`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(
|
|
13492
|
+
const attemptNumber = (db.select({ value: sql7`coalesce(max(${siteCrawlAttempts.attemptNumber}), 0)` }).from(siteCrawlAttempts).where(eq22(siteCrawlAttempts.runId, runId)).get()?.value ?? 0) + 1;
|
|
13445
13493
|
const attemptId = crypto22.randomUUID();
|
|
13446
13494
|
db.insert(siteCrawlAttempts).values({
|
|
13447
13495
|
id: attemptId,
|
|
@@ -13477,22 +13525,22 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13477
13525
|
const nodeKey = nodeKeyByUrl.get(url);
|
|
13478
13526
|
if (!nodeKey) continue;
|
|
13479
13527
|
const scope = [
|
|
13480
|
-
|
|
13481
|
-
|
|
13482
|
-
|
|
13528
|
+
eq22(siteCrawlEdges.projectId, projectId),
|
|
13529
|
+
eq22(siteCrawlEdges.runId, runId),
|
|
13530
|
+
eq22(siteCrawlEdges.attemptId, attemptId)
|
|
13483
13531
|
];
|
|
13484
13532
|
tx.update(siteCrawlEdges).set({ sourceNodeKey: nodeKey, updatedAt: now }).where(and17(
|
|
13485
13533
|
...scope,
|
|
13486
|
-
|
|
13534
|
+
eq22(siteCrawlEdges.sourceUrl, url)
|
|
13487
13535
|
)).run();
|
|
13488
13536
|
tx.update(siteCrawlEdges).set({ targetNodeKey: nodeKey, updatedAt: now }).where(and17(
|
|
13489
13537
|
...scope,
|
|
13490
|
-
|
|
13538
|
+
eq22(siteCrawlEdges.targetUrl, url)
|
|
13491
13539
|
)).run();
|
|
13492
13540
|
const pageScope = [
|
|
13493
|
-
|
|
13494
|
-
|
|
13495
|
-
|
|
13541
|
+
eq22(siteCrawlPages.projectId, projectId),
|
|
13542
|
+
eq22(siteCrawlPages.runId, runId),
|
|
13543
|
+
eq22(siteCrawlPages.attemptId, attemptId)
|
|
13496
13544
|
];
|
|
13497
13545
|
const canonicalTargets = tx.select({
|
|
13498
13546
|
id: siteCrawlPages.id,
|
|
@@ -13500,13 +13548,13 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13500
13548
|
fetchState: siteCrawlPages.fetchState,
|
|
13501
13549
|
indexabilityState: siteCrawlPages.indexabilityState,
|
|
13502
13550
|
indexabilityReasons: siteCrawlPages.indexabilityReasons
|
|
13503
|
-
}).from(siteCrawlPages).where(and17(...pageScope,
|
|
13551
|
+
}).from(siteCrawlPages).where(and17(...pageScope, eq22(siteCrawlPages.canonicalUrl, url))).all();
|
|
13504
13552
|
for (const target of canonicalTargets) {
|
|
13505
13553
|
tx.update(siteCrawlPages).set({
|
|
13506
13554
|
canonicalNodeKey: nodeKey,
|
|
13507
13555
|
healthState: deriveSiteHealthState({ ...target, canonicalNodeKey: nodeKey }),
|
|
13508
13556
|
updatedAt: now
|
|
13509
|
-
}).where(
|
|
13557
|
+
}).where(eq22(siteCrawlPages.id, target.id)).run();
|
|
13510
13558
|
}
|
|
13511
13559
|
}
|
|
13512
13560
|
};
|
|
@@ -13668,19 +13716,19 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13668
13716
|
linkScoreNormalized: metrics.linkScore,
|
|
13669
13717
|
updatedAt: now
|
|
13670
13718
|
}).where(and17(
|
|
13671
|
-
|
|
13672
|
-
|
|
13673
|
-
|
|
13674
|
-
|
|
13719
|
+
eq22(siteCrawlPages.projectId, projectId),
|
|
13720
|
+
eq22(siteCrawlPages.runId, runId),
|
|
13721
|
+
eq22(siteCrawlPages.attemptId, attemptId),
|
|
13722
|
+
eq22(siteCrawlPages.nodeKey, key)
|
|
13675
13723
|
)).run();
|
|
13676
13724
|
};
|
|
13677
13725
|
const persistEvent = async (event) => {
|
|
13678
13726
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
13679
13727
|
db.transaction((tx) => {
|
|
13680
13728
|
const receipt = tx.select({ checksum: siteCrawlEventReceipts.checksum }).from(siteCrawlEventReceipts).where(and17(
|
|
13681
|
-
|
|
13682
|
-
|
|
13683
|
-
|
|
13729
|
+
eq22(siteCrawlEventReceipts.attemptId, attemptId),
|
|
13730
|
+
eq22(siteCrawlEventReceipts.sequence, event.sequence),
|
|
13731
|
+
eq22(siteCrawlEventReceipts.batchId, event.batchId)
|
|
13684
13732
|
)).get();
|
|
13685
13733
|
if (receipt) {
|
|
13686
13734
|
if (receipt.checksum !== event.checksum) {
|
|
@@ -13715,18 +13763,18 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13715
13763
|
urlVersionsSkipped: event.type === "summary" ? event.summary.urlVersions?.skipped ?? 0 : sql7`${siteCrawlAttempts.urlVersionsSkipped}`,
|
|
13716
13764
|
edgesDiscovered: progress.edgesObserved,
|
|
13717
13765
|
updatedAt: now
|
|
13718
|
-
}).where(
|
|
13766
|
+
}).where(eq22(siteCrawlAttempts.id, attemptId)).run();
|
|
13719
13767
|
} else {
|
|
13720
13768
|
tx.update(siteCrawlAttempts).set({
|
|
13721
13769
|
lastEventSequence: event.sequence,
|
|
13722
13770
|
lastEventChecksum: event.checksum,
|
|
13723
13771
|
updatedAt: now
|
|
13724
|
-
}).where(
|
|
13772
|
+
}).where(eq22(siteCrawlAttempts.id, attemptId)).run();
|
|
13725
13773
|
}
|
|
13726
13774
|
});
|
|
13727
13775
|
};
|
|
13728
13776
|
try {
|
|
13729
|
-
const project = db.select().from(projects).where(
|
|
13777
|
+
const project = db.select().from(projects).where(eq22(projects.id, projectId)).get();
|
|
13730
13778
|
if (!project) throw new Error(`Project not found: ${projectId}`);
|
|
13731
13779
|
canonicalDomain = project.canonicalDomain;
|
|
13732
13780
|
const homepageUrl = toHomepageUrl(project.canonicalDomain);
|
|
@@ -13749,7 +13797,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13749
13797
|
return { host, rootUrl: resolved.effectiveUrl, error: null };
|
|
13750
13798
|
} catch (error) {
|
|
13751
13799
|
if (isCancelled(error, opts.signal)) throw error;
|
|
13752
|
-
|
|
13800
|
+
log17.warn("extra-site.unreachable", { runId, projectId, host, error: describeError(error) });
|
|
13753
13801
|
return { host, rootUrl: null, error: describeError(error) };
|
|
13754
13802
|
}
|
|
13755
13803
|
})
|
|
@@ -13759,9 +13807,9 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13759
13807
|
try {
|
|
13760
13808
|
entities = activePlanEntityRegistry(db, projectId);
|
|
13761
13809
|
} catch (error) {
|
|
13762
|
-
|
|
13810
|
+
log17.warn("entity-registry.unavailable", { runId, projectId, error: describeError(error) });
|
|
13763
13811
|
}
|
|
13764
|
-
|
|
13812
|
+
log17.info("start", {
|
|
13765
13813
|
operationId,
|
|
13766
13814
|
runId,
|
|
13767
13815
|
projectId,
|
|
@@ -13806,7 +13854,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13806
13854
|
crawlSummary.pagesFetched,
|
|
13807
13855
|
placementRulesetVersion
|
|
13808
13856
|
);
|
|
13809
|
-
|
|
13857
|
+
log17.info("template-links", {
|
|
13810
13858
|
runId,
|
|
13811
13859
|
projectId,
|
|
13812
13860
|
detection: templateLinks.detection,
|
|
@@ -13845,7 +13893,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13845
13893
|
try {
|
|
13846
13894
|
persistSiteCrawlGraphLayout(db, { projectId, runId, attemptId }, graphLayout, finishedAt);
|
|
13847
13895
|
} catch (error) {
|
|
13848
|
-
|
|
13896
|
+
log17.warn("graph-layout.persist-failed", {
|
|
13849
13897
|
runId,
|
|
13850
13898
|
projectId,
|
|
13851
13899
|
error: describeError(error)
|
|
@@ -13863,7 +13911,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13863
13911
|
edges: []
|
|
13864
13912
|
}, finishedAt);
|
|
13865
13913
|
} catch (markerError) {
|
|
13866
|
-
|
|
13914
|
+
log17.warn("graph-layout.marker-persist-failed", {
|
|
13867
13915
|
runId,
|
|
13868
13916
|
projectId,
|
|
13869
13917
|
error: describeError(markerError)
|
|
@@ -13871,7 +13919,7 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13871
13919
|
}
|
|
13872
13920
|
}
|
|
13873
13921
|
const published = db.transaction((tx) => {
|
|
13874
|
-
const claim2 = tx.update(runs).set({ status: terminalStatus, finishedAt }).where(and17(
|
|
13922
|
+
const claim2 = tx.update(runs).set({ status: terminalStatus, finishedAt }).where(and17(eq22(runs.id, runId), eq22(runs.status, "running"))).run();
|
|
13875
13923
|
if (claim2.changes === 0) return false;
|
|
13876
13924
|
if (aggregateScore !== null) {
|
|
13877
13925
|
tx.insert(siteAuditSnapshots).values({
|
|
@@ -13986,24 +14034,24 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
13986
14034
|
edgesDiscovered: crawlSummary.edgesObserved,
|
|
13987
14035
|
finishedAt,
|
|
13988
14036
|
updatedAt: finishedAt
|
|
13989
|
-
}).where(
|
|
14037
|
+
}).where(eq22(siteCrawlAttempts.id, attemptId)).run();
|
|
13990
14038
|
return true;
|
|
13991
14039
|
});
|
|
13992
14040
|
if (!published) {
|
|
13993
14041
|
try {
|
|
13994
14042
|
deleteSiteCrawlGraphLayout(db, { projectId, runId, attemptId });
|
|
13995
14043
|
} catch (cleanupError) {
|
|
13996
|
-
|
|
14044
|
+
log17.warn("graph-layout.cleanup-failed", {
|
|
13997
14045
|
runId,
|
|
13998
14046
|
projectId,
|
|
13999
14047
|
error: describeError(cleanupError)
|
|
14000
14048
|
});
|
|
14001
14049
|
}
|
|
14002
|
-
const current = db.select({ status: runs.status }).from(runs).where(
|
|
14050
|
+
const current = db.select({ status: runs.status }).from(runs).where(eq22(runs.id, runId)).get();
|
|
14003
14051
|
if (current?.status === "cancelled") throw new SiteAuditCancelledError(`Site audit cancelled before publication: ${runId}`);
|
|
14004
14052
|
throw new Error(`Site audit run was no longer running before publication: ${runId}`);
|
|
14005
14053
|
}
|
|
14006
|
-
|
|
14054
|
+
log17.info("completed", {
|
|
14007
14055
|
operationId,
|
|
14008
14056
|
runId,
|
|
14009
14057
|
projectId,
|
|
@@ -14050,14 +14098,14 @@ async function executeSiteAudit(db, runId, projectId, opts = {}) {
|
|
|
14050
14098
|
error: message,
|
|
14051
14099
|
finishedAt,
|
|
14052
14100
|
updatedAt: finishedAt
|
|
14053
|
-
}).where(
|
|
14101
|
+
}).where(eq22(siteCrawlAttempts.id, attemptId)).run();
|
|
14054
14102
|
tx.update(runs).set({
|
|
14055
14103
|
status: cancelled ? "cancelled" : "failed",
|
|
14056
14104
|
error: message,
|
|
14057
14105
|
finishedAt
|
|
14058
|
-
}).where(and17(
|
|
14106
|
+
}).where(and17(eq22(runs.id, runId), eq22(runs.status, "running"))).run();
|
|
14059
14107
|
});
|
|
14060
|
-
|
|
14108
|
+
log17.error("failed", { operationId, runId, projectId, phase, cancelled, error: message });
|
|
14061
14109
|
trackSiteAuditOutcome(db, {
|
|
14062
14110
|
operationId,
|
|
14063
14111
|
phase,
|
|
@@ -14097,7 +14145,7 @@ function createAnswerFieldRecomputeQueue(opts) {
|
|
|
14097
14145
|
|
|
14098
14146
|
// src/competitor-auto-alias-runner.ts
|
|
14099
14147
|
import { setImmediate as yieldToEventLoop3 } from "timers/promises";
|
|
14100
|
-
var
|
|
14148
|
+
var log18 = createLogger("CompetitorAutoAliases");
|
|
14101
14149
|
function createCompetitorAutoAliasRunner(opts) {
|
|
14102
14150
|
const reasons = /* @__PURE__ */ new Map();
|
|
14103
14151
|
const queue = createProjectPassQueue(async (projectId) => {
|
|
@@ -14108,7 +14156,7 @@ function createCompetitorAutoAliasRunner(opts) {
|
|
|
14108
14156
|
if (!result) return null;
|
|
14109
14157
|
const added = result.detection.competitors.reduce((sum, competitor) => sum + competitor.added.length, 0);
|
|
14110
14158
|
const removed = result.detection.competitors.reduce((sum, competitor) => sum + competitor.removed.length, 0);
|
|
14111
|
-
|
|
14159
|
+
log18.info("detection.completed", {
|
|
14112
14160
|
projectId,
|
|
14113
14161
|
reason,
|
|
14114
14162
|
runs: result.detection.scan.runs,
|
|
@@ -14121,7 +14169,7 @@ function createCompetitorAutoAliasRunner(opts) {
|
|
|
14121
14169
|
try {
|
|
14122
14170
|
opts.onNamesChanged(projectId, result.detection.project);
|
|
14123
14171
|
} catch (err) {
|
|
14124
|
-
|
|
14172
|
+
log18.error("names-changed.failed", { projectId, error: describeError(err) });
|
|
14125
14173
|
}
|
|
14126
14174
|
}
|
|
14127
14175
|
return result;
|
|
@@ -14133,14 +14181,14 @@ function createCompetitorAutoAliasRunner(opts) {
|
|
|
14133
14181
|
return {
|
|
14134
14182
|
schedule(projectId, reason) {
|
|
14135
14183
|
enqueue(projectId, reason).catch((err) => {
|
|
14136
|
-
|
|
14184
|
+
log18.error("detection.failed", { projectId, reason, error: describeError(err) });
|
|
14137
14185
|
});
|
|
14138
14186
|
},
|
|
14139
14187
|
async request(projectId, reason) {
|
|
14140
14188
|
try {
|
|
14141
14189
|
return await enqueue(projectId, reason);
|
|
14142
14190
|
} catch (err) {
|
|
14143
|
-
|
|
14191
|
+
log18.error("detection.failed", { projectId, reason, error: describeError(err) });
|
|
14144
14192
|
throw err;
|
|
14145
14193
|
}
|
|
14146
14194
|
},
|
|
@@ -14149,8 +14197,8 @@ function createCompetitorAutoAliasRunner(opts) {
|
|
|
14149
14197
|
}
|
|
14150
14198
|
|
|
14151
14199
|
// src/install-state-telemetry.ts
|
|
14152
|
-
import { and as and18, count as count4, eq as
|
|
14153
|
-
var
|
|
14200
|
+
import { and as and18, count as count4, eq as eq23, gte as gte2, inArray as inArray9, isNotNull as isNotNull2, isNull as isNull2, ne as ne3, sql as sql8 } from "drizzle-orm";
|
|
14201
|
+
var log19 = createLogger("InstallStateTelemetry");
|
|
14154
14202
|
var INSTALL_STATE_FIRST_DELAY_MS = 5 * 6e4;
|
|
14155
14203
|
var INSTALL_STATE_INTERVAL_MS = 24 * 60 * 6e4;
|
|
14156
14204
|
var KNOWN_PROVIDERS2 = new Set(PROVIDER_NAMES);
|
|
@@ -14175,7 +14223,7 @@ function buildInstallState(sources, now, startedAt) {
|
|
|
14175
14223
|
const googleByType = new Map(db.select({ type: googleConnections.connectionType, value: count4() }).from(googleConnections).groupBy(googleConnections.connectionType).all().map((row) => [row.type, whole(row.value)]));
|
|
14176
14224
|
const gaServiceAccounts = total(db.select({ value: count4() }).from(gaConnections));
|
|
14177
14225
|
const trafficByType = db.select({ type: trafficSources.sourceType, value: count4() }).from(trafficSources).where(and18(isNull2(trafficSources.archivedAt), ne3(trafficSources.status, TrafficSourceStatuses.archived))).groupBy(trafficSources.sourceType).all();
|
|
14178
|
-
const webhookSources = db.select({ config: notifications.config }).from(notifications).where(
|
|
14226
|
+
const webhookSources = db.select({ config: notifications.config }).from(notifications).where(eq23(notifications.enabled, true)).all().map((row) => row.config.source);
|
|
14179
14227
|
const agentWebhooks = webhookSources.filter((source) => source === AGENT_WEBHOOK_SOURCE).length;
|
|
14180
14228
|
const webhooks = webhookSources.length - agentWebhooks;
|
|
14181
14229
|
const bing = total(db.select({ value: count4() }).from(bingConnections));
|
|
@@ -14189,7 +14237,7 @@ function buildInstallState(sources, now, startedAt) {
|
|
|
14189
14237
|
queries: total(db.select({ value: count4() }).from(queries)),
|
|
14190
14238
|
competitors: total(db.select({ value: count4() }).from(competitors)),
|
|
14191
14239
|
locations: total(db.select({ value: sql8`coalesce(sum(json_array_length(${projects.locations})), 0)` }).from(projects)),
|
|
14192
|
-
schedules: total(db.select({ value: count4() }).from(schedules).where(
|
|
14240
|
+
schedules: total(db.select({ value: count4() }).from(schedules).where(eq23(schedules.enabled, true))),
|
|
14193
14241
|
webhooks,
|
|
14194
14242
|
agentWebhooks,
|
|
14195
14243
|
trafficSources: trafficByType.reduce((sum, row) => sum + whole(row.value), 0),
|
|
@@ -14251,13 +14299,13 @@ function buildInstallState(sources, now, startedAt) {
|
|
|
14251
14299
|
const usage24h = {
|
|
14252
14300
|
sweeps: total(db.select({ value: count4() }).from(runs).where(and18(
|
|
14253
14301
|
inArray9(runs.projectId, projectIds),
|
|
14254
|
-
|
|
14302
|
+
eq23(runs.kind, RunKinds["answer-visibility"]),
|
|
14255
14303
|
gte2(runs.createdAt, since),
|
|
14256
14304
|
ne3(runs.trigger, RunTriggers.probe)
|
|
14257
14305
|
))),
|
|
14258
14306
|
audits: total(db.select({ value: count4() }).from(runs).where(and18(
|
|
14259
14307
|
inArray9(runs.projectId, projectIds),
|
|
14260
|
-
|
|
14308
|
+
eq23(runs.kind, RunKinds["site-audit"]),
|
|
14261
14309
|
gte2(runs.createdAt, since)
|
|
14262
14310
|
))),
|
|
14263
14311
|
providerCalls: [...providerCalls.values()].reduce((sum, calls) => sum + calls, 0)
|
|
@@ -14274,14 +14322,14 @@ function buildInstallState(sources, now, startedAt) {
|
|
|
14274
14322
|
inputTokens: sql8`coalesce(sum(${llmUsageEvents.inputTokens}), 0)`,
|
|
14275
14323
|
outputTokens: sql8`coalesce(sum(${llmUsageEvents.outputTokens}), 0)`,
|
|
14276
14324
|
costMillicents: sql8`coalesce(sum(${llmUsageEvents.costMillicents}), 0)`
|
|
14277
|
-
}).from(llmUsageEvents).where(and18(
|
|
14325
|
+
}).from(llmUsageEvents).where(and18(eq23(llmUsageEvents.feature, AeroLlmUsageFeatures.turn), gte2(llmUsageEvents.createdAt, since))).get();
|
|
14278
14326
|
const aeroCalls = whole(aero?.calls);
|
|
14279
14327
|
usage24h.aeroModelCalls = aeroCalls;
|
|
14280
14328
|
usage24h.aeroInputTokens = whole(aero?.inputTokens);
|
|
14281
14329
|
usage24h.aeroOutputTokens = whole(aero?.outputTokens);
|
|
14282
14330
|
const aeroMillicents = whole(aero?.costMillicents);
|
|
14283
14331
|
if (aeroCalls === 0 || aeroMillicents > 0) usage24h.aeroCostMicros = aeroMillicents * 10;
|
|
14284
|
-
usage24h.webhookDeliveries = total(db.select({ value: count4() }).from(auditLog).where(and18(gte2(auditLog.createdAt, since),
|
|
14332
|
+
usage24h.webhookDeliveries = total(db.select({ value: count4() }).from(auditLog).where(and18(gte2(auditLog.createdAt, since), eq23(auditLog.action, WEBHOOK_DELIVERED_ACTION))));
|
|
14285
14333
|
const providerCalls24h = Object.fromEntries(PROVIDER_NAMES.flatMap((name) => providerCalls.has(name) ? [[name, providerCalls.get(name)]] : []));
|
|
14286
14334
|
return {
|
|
14287
14335
|
providers: registeredProviderNames(config).filter((name) => KNOWN_PROVIDERS2.has(name)),
|
|
@@ -14315,7 +14363,7 @@ function startInstallStateTelemetry(sources) {
|
|
|
14315
14363
|
try {
|
|
14316
14364
|
if (isTelemetryEnabled()) trackInstallState(buildInstallState(sources, Date.now(), startedAt));
|
|
14317
14365
|
} catch (err) {
|
|
14318
|
-
|
|
14366
|
+
log19.warn("telemetry.install-state-failed", { error: describeError(err) });
|
|
14319
14367
|
}
|
|
14320
14368
|
schedule(INSTALL_STATE_INTERVAL_MS);
|
|
14321
14369
|
};
|
|
@@ -14437,8 +14485,8 @@ function createProviderModelCatalog(registry) {
|
|
|
14437
14485
|
// src/scheduler.ts
|
|
14438
14486
|
import crypto23 from "crypto";
|
|
14439
14487
|
import cron from "node-cron";
|
|
14440
|
-
import { and as and19, eq as
|
|
14441
|
-
var
|
|
14488
|
+
import { and as and19, eq as eq24, inArray as inArray10, notExists, sql as sql9 } from "drizzle-orm";
|
|
14489
|
+
var log20 = createLogger("Scheduler");
|
|
14442
14490
|
var SLOT_FIRED = { status: OutcomeStatuses.succeeded };
|
|
14443
14491
|
var slotSkipped = (reasonCode) => ({ status: OutcomeStatuses.skipped, reasonCode });
|
|
14444
14492
|
var slotFailed = (reasonCode) => ({ status: OutcomeStatuses.failed, reasonCode });
|
|
@@ -14517,8 +14565,8 @@ var Scheduler = class {
|
|
|
14517
14565
|
ensureHealthSchedules() {
|
|
14518
14566
|
const projectsWithoutHealth = this.db.select({ id: projects.id }).from(projects).where(notExists(
|
|
14519
14567
|
this.db.select({ one: sql9`1` }).from(schedules).where(and19(
|
|
14520
|
-
|
|
14521
|
-
|
|
14568
|
+
eq24(schedules.projectId, projects.id),
|
|
14569
|
+
eq24(schedules.kind, SchedulableRunKinds.doctor)
|
|
14522
14570
|
))
|
|
14523
14571
|
)).all();
|
|
14524
14572
|
if (projectsWithoutHealth.length === 0) return;
|
|
@@ -14528,7 +14576,7 @@ var Scheduler = class {
|
|
|
14528
14576
|
if (ensureDefaultHealthSchedule(this.db, project.id, now)) seeded += 1;
|
|
14529
14577
|
}
|
|
14530
14578
|
if (seeded > 0) {
|
|
14531
|
-
|
|
14579
|
+
log20.info("health-schedule.seeded", { projectCount: seeded, cron: DEFAULT_HEALTH_CRON });
|
|
14532
14580
|
}
|
|
14533
14581
|
}
|
|
14534
14582
|
/**
|
|
@@ -14552,16 +14600,16 @@ var Scheduler = class {
|
|
|
14552
14600
|
const current = ensureCurrentQueryBasketRevision(this.db, project.id);
|
|
14553
14601
|
if (current !== null && current.revision !== previous) minted += 1;
|
|
14554
14602
|
} catch (err) {
|
|
14555
|
-
|
|
14603
|
+
log20.warn("query-basket.mint-failed", { projectId: project.id, err: String(err) });
|
|
14556
14604
|
}
|
|
14557
14605
|
}
|
|
14558
|
-
if (minted > 0)
|
|
14606
|
+
if (minted > 0) log20.info("query-basket.ensured", { projectCount: minted });
|
|
14559
14607
|
}
|
|
14560
14608
|
/** Load all enabled schedules from DB and register cron jobs. */
|
|
14561
14609
|
start() {
|
|
14562
14610
|
this.ensureHealthSchedules();
|
|
14563
14611
|
this.ensureQueryBaskets();
|
|
14564
|
-
const allSchedules = this.db.select().from(schedules).where(
|
|
14612
|
+
const allSchedules = this.db.select().from(schedules).where(eq24(schedules.enabled, true)).all();
|
|
14565
14613
|
for (const schedule of allSchedules) {
|
|
14566
14614
|
const missedRunAt = schedule.nextRunAt;
|
|
14567
14615
|
const recurrence = scheduleRecurrence(schedule);
|
|
@@ -14569,12 +14617,12 @@ var Scheduler = class {
|
|
|
14569
14617
|
if (registered && missedRunAt && new Date(missedRunAt) < /* @__PURE__ */ new Date()) {
|
|
14570
14618
|
const answerRecurrence = recurrence && schedule.kind === SchedulableRunKinds["answer-visibility"];
|
|
14571
14619
|
if (!recurrence || answerRecurrence || this.claimCalendarOccurrence(schedule, missedRunAt, /* @__PURE__ */ new Date())) {
|
|
14572
|
-
|
|
14620
|
+
log20.info("run.catch-up", { projectId: schedule.projectId, kind: schedule.kind, missedRunAt });
|
|
14573
14621
|
this.triggerRun(schedule.id, schedule.projectId, schedule.kind, answerRecurrence ? missedRunAt : void 0, OutcomeTriggers.startup);
|
|
14574
14622
|
}
|
|
14575
14623
|
}
|
|
14576
14624
|
}
|
|
14577
|
-
|
|
14625
|
+
log20.info("started", { scheduleCount: allSchedules.length });
|
|
14578
14626
|
}
|
|
14579
14627
|
/** Stop all cron tasks for graceful shutdown. */
|
|
14580
14628
|
stop() {
|
|
@@ -14595,7 +14643,7 @@ var Scheduler = class {
|
|
|
14595
14643
|
this.stopTask(key, existing, "Stopped");
|
|
14596
14644
|
this.tasks.delete(key);
|
|
14597
14645
|
}
|
|
14598
|
-
const schedule = this.db.select().from(schedules).where(and19(
|
|
14646
|
+
const schedule = this.db.select().from(schedules).where(and19(eq24(schedules.projectId, projectId), eq24(schedules.kind, kind))).get();
|
|
14599
14647
|
if (schedule && schedule.enabled) {
|
|
14600
14648
|
this.registerCronTask(schedule);
|
|
14601
14649
|
}
|
|
@@ -14623,17 +14671,17 @@ var Scheduler = class {
|
|
|
14623
14671
|
clearTimeout(pending);
|
|
14624
14672
|
this.spreadTimers.delete(key);
|
|
14625
14673
|
}
|
|
14626
|
-
|
|
14674
|
+
log20.info(`task.${verb.toLowerCase()}`, { key });
|
|
14627
14675
|
}
|
|
14628
14676
|
/** Runtime timing writes must not restore a version already issued to a settings caller. */
|
|
14629
14677
|
updateScheduleTiming(scheduleId, timing) {
|
|
14630
14678
|
this.db.transaction((tx) => {
|
|
14631
|
-
const current = tx.select({ updatedAt: schedules.updatedAt }).from(schedules).where(
|
|
14679
|
+
const current = tx.select({ updatedAt: schedules.updatedAt }).from(schedules).where(eq24(schedules.id, scheduleId)).get();
|
|
14632
14680
|
if (!current) return;
|
|
14633
14681
|
tx.update(schedules).set({
|
|
14634
14682
|
...timing,
|
|
14635
14683
|
updatedAt: nextScheduleUpdatedAt(current.updatedAt)
|
|
14636
|
-
}).where(
|
|
14684
|
+
}).where(eq24(schedules.id, scheduleId)).run();
|
|
14637
14685
|
});
|
|
14638
14686
|
}
|
|
14639
14687
|
registerCronTask(schedule, options = {}) {
|
|
@@ -14643,13 +14691,13 @@ var Scheduler = class {
|
|
|
14643
14691
|
return true;
|
|
14644
14692
|
}
|
|
14645
14693
|
if (schedule.recurrence) {
|
|
14646
|
-
|
|
14694
|
+
log20.error("calendar.invalid", { projectId: schedule.projectId, kind: schedule.kind });
|
|
14647
14695
|
return false;
|
|
14648
14696
|
}
|
|
14649
14697
|
const { id: scheduleId, projectId, cronExpr, timezone } = schedule;
|
|
14650
14698
|
const kind = schedule.kind;
|
|
14651
14699
|
if (!cron.validate(cronExpr)) {
|
|
14652
|
-
|
|
14700
|
+
log20.error("cron.invalid", { projectId, kind, cronExpr });
|
|
14653
14701
|
return false;
|
|
14654
14702
|
}
|
|
14655
14703
|
const key = taskKey(projectId, kind);
|
|
@@ -14679,7 +14727,7 @@ var Scheduler = class {
|
|
|
14679
14727
|
});
|
|
14680
14728
|
}
|
|
14681
14729
|
const label = schedule.preset ?? cronExpr;
|
|
14682
|
-
|
|
14730
|
+
log20.info("cron.registered", { projectId, kind, schedule: label, timezone });
|
|
14683
14731
|
return true;
|
|
14684
14732
|
}
|
|
14685
14733
|
/** Calendar schedules are checked at most once a minute so long intervals
|
|
@@ -14709,7 +14757,7 @@ var Scheduler = class {
|
|
|
14709
14757
|
};
|
|
14710
14758
|
const tick = () => {
|
|
14711
14759
|
if (stopped) return;
|
|
14712
|
-
const current = this.db.select().from(schedules).where(
|
|
14760
|
+
const current = this.db.select().from(schedules).where(eq24(schedules.id, scheduleId)).get();
|
|
14713
14761
|
if (!current || !current.enabled || !scheduleRecurrence(current)) {
|
|
14714
14762
|
this.remove(projectId, kind);
|
|
14715
14763
|
return;
|
|
@@ -14727,7 +14775,7 @@ var Scheduler = class {
|
|
|
14727
14775
|
this.triggerRun(scheduleId, projectId, kind);
|
|
14728
14776
|
}
|
|
14729
14777
|
}
|
|
14730
|
-
arm(this.db.select({ nextRunAt: schedules.nextRunAt }).from(schedules).where(
|
|
14778
|
+
arm(this.db.select({ nextRunAt: schedules.nextRunAt }).from(schedules).where(eq24(schedules.id, scheduleId)).get()?.nextRunAt);
|
|
14731
14779
|
};
|
|
14732
14780
|
this.tasks.set(key, task);
|
|
14733
14781
|
let registeredNextRunAt = schedule.nextRunAt;
|
|
@@ -14737,12 +14785,12 @@ var Scheduler = class {
|
|
|
14737
14785
|
}
|
|
14738
14786
|
if (options.preserveNextRunAt) arm(registeredNextRunAt);
|
|
14739
14787
|
else timer = setTimeout(tick, 0);
|
|
14740
|
-
|
|
14788
|
+
log20.info("calendar.registered", { projectId, kind, recurrence, timezone });
|
|
14741
14789
|
}
|
|
14742
14790
|
/** Atomically advance a due callback-only calendar occurrence before dispatch. */
|
|
14743
14791
|
claimCalendarOccurrence(schedule, dueAt, now) {
|
|
14744
14792
|
return this.db.transaction((tx) => {
|
|
14745
|
-
const current = tx.select().from(schedules).where(
|
|
14793
|
+
const current = tx.select().from(schedules).where(eq24(schedules.id, schedule.id)).get();
|
|
14746
14794
|
if (!current || !current.enabled || current.updatedAt !== schedule.updatedAt || current.nextRunAt !== dueAt) return false;
|
|
14747
14795
|
const recurrence = scheduleRecurrence(current);
|
|
14748
14796
|
if (!recurrence) return false;
|
|
@@ -14752,10 +14800,10 @@ var Scheduler = class {
|
|
|
14752
14800
|
nextRunAt,
|
|
14753
14801
|
updatedAt: nextScheduleUpdatedAt(current.updatedAt)
|
|
14754
14802
|
}).where(and19(
|
|
14755
|
-
|
|
14756
|
-
|
|
14757
|
-
|
|
14758
|
-
|
|
14803
|
+
eq24(schedules.id, current.id),
|
|
14804
|
+
eq24(schedules.enabled, true),
|
|
14805
|
+
eq24(schedules.nextRunAt, dueAt),
|
|
14806
|
+
eq24(schedules.updatedAt, schedule.updatedAt)
|
|
14759
14807
|
)).run();
|
|
14760
14808
|
return result.changes === 1;
|
|
14761
14809
|
});
|
|
@@ -14777,15 +14825,15 @@ var Scheduler = class {
|
|
|
14777
14825
|
fireSlot(scheduleId, projectId, kind, claimedOccurrence) {
|
|
14778
14826
|
try {
|
|
14779
14827
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
14780
|
-
const currentSchedule = this.db.select().from(schedules).where(
|
|
14828
|
+
const currentSchedule = this.db.select().from(schedules).where(eq24(schedules.id, scheduleId)).get();
|
|
14781
14829
|
if (!currentSchedule || !currentSchedule.enabled) {
|
|
14782
|
-
|
|
14830
|
+
log20.warn("schedule.stale", { scheduleId, projectId, kind, msg: "schedule no longer exists or is disabled" });
|
|
14783
14831
|
this.remove(projectId, kind);
|
|
14784
14832
|
return slotSkipped(currentSchedule ? OutcomeReasonCodes.NOT_DUE : OutcomeReasonCodes.NOT_FOUND);
|
|
14785
14833
|
}
|
|
14786
14834
|
const recurrence = scheduleRecurrence(currentSchedule);
|
|
14787
14835
|
if (claimedOccurrence && (!recurrence || currentSchedule.nextRunAt !== claimedOccurrence)) {
|
|
14788
|
-
|
|
14836
|
+
log20.info("calendar.stale-claim", { projectId, scheduleId, kind });
|
|
14789
14837
|
return slotSkipped(OutcomeReasonCodes.NOT_DUE);
|
|
14790
14838
|
}
|
|
14791
14839
|
const nextRunAt = nextRunFromSchedule({
|
|
@@ -14793,33 +14841,33 @@ var Scheduler = class {
|
|
|
14793
14841
|
timezone: currentSchedule.timezone,
|
|
14794
14842
|
recurrence
|
|
14795
14843
|
});
|
|
14796
|
-
const project = this.db.select().from(projects).where(
|
|
14844
|
+
const project = this.db.select().from(projects).where(eq24(projects.id, projectId)).get();
|
|
14797
14845
|
if (!project) {
|
|
14798
|
-
|
|
14846
|
+
log20.error("project.not-found", { projectId, kind, msg: "skipping scheduled run" });
|
|
14799
14847
|
this.remove(projectId, kind);
|
|
14800
14848
|
return slotSkipped(OutcomeReasonCodes.NOT_FOUND);
|
|
14801
14849
|
}
|
|
14802
14850
|
if (kind === SchedulableRunKinds["traffic-sync"]) {
|
|
14803
14851
|
const sourceId = currentSchedule.sourceId;
|
|
14804
14852
|
if (!sourceId) {
|
|
14805
|
-
|
|
14853
|
+
log20.warn("traffic-sync.missing-source", { scheduleId, projectId });
|
|
14806
14854
|
return slotFailed(OutcomeReasonCodes.VALIDATION);
|
|
14807
14855
|
}
|
|
14808
14856
|
if (!this.callbacks.onTrafficSyncRequested) {
|
|
14809
|
-
|
|
14857
|
+
log20.warn("traffic-sync.no-callback", { scheduleId, projectId, msg: "host did not register onTrafficSyncRequested" });
|
|
14810
14858
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14811
14859
|
}
|
|
14812
14860
|
this.updateScheduleTiming(currentSchedule.id, {
|
|
14813
14861
|
lastRunAt: now,
|
|
14814
14862
|
nextRunAt
|
|
14815
14863
|
});
|
|
14816
|
-
|
|
14864
|
+
log20.info("traffic-sync.triggered", { projectName: project.name, sourceId });
|
|
14817
14865
|
this.callbacks.onTrafficSyncRequested(project.name, sourceId);
|
|
14818
14866
|
return SLOT_FIRED;
|
|
14819
14867
|
}
|
|
14820
14868
|
if (kind === SchedulableRunKinds["gbp-sync"]) {
|
|
14821
14869
|
if (!this.callbacks.onGbpSyncRequested) {
|
|
14822
|
-
|
|
14870
|
+
log20.warn("gbp-sync.no-callback", { scheduleId, projectId, msg: "host did not register onGbpSyncRequested" });
|
|
14823
14871
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14824
14872
|
}
|
|
14825
14873
|
const runId2 = crypto23.randomUUID();
|
|
@@ -14835,22 +14883,22 @@ var Scheduler = class {
|
|
|
14835
14883
|
lastRunAt: now,
|
|
14836
14884
|
nextRunAt
|
|
14837
14885
|
});
|
|
14838
|
-
|
|
14886
|
+
log20.info("gbp-sync.triggered", { runId: runId2, projectName: project.name });
|
|
14839
14887
|
this.callbacks.onGbpSyncRequested(runId2, projectId);
|
|
14840
14888
|
return SLOT_FIRED;
|
|
14841
14889
|
}
|
|
14842
14890
|
if (kind === SchedulableRunKinds["ads-sync"]) {
|
|
14843
14891
|
if (!this.callbacks.onAdsSyncRequested) {
|
|
14844
|
-
|
|
14892
|
+
log20.warn("ads-sync.no-callback", { scheduleId, projectId, msg: "host did not register onAdsSyncRequested" });
|
|
14845
14893
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14846
14894
|
}
|
|
14847
14895
|
const activeAdsRun = this.db.select({ id: runs.id }).from(runs).where(and19(
|
|
14848
|
-
|
|
14849
|
-
|
|
14896
|
+
eq24(runs.projectId, projectId),
|
|
14897
|
+
eq24(runs.kind, RunKinds["ads-sync"]),
|
|
14850
14898
|
inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
|
|
14851
14899
|
)).get();
|
|
14852
14900
|
if (activeAdsRun) {
|
|
14853
|
-
|
|
14901
|
+
log20.info("ads-sync.skipped-active", { projectName: project.name, activeRunId: activeAdsRun.id });
|
|
14854
14902
|
this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
|
|
14855
14903
|
return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
|
|
14856
14904
|
}
|
|
@@ -14867,22 +14915,22 @@ var Scheduler = class {
|
|
|
14867
14915
|
lastRunAt: now,
|
|
14868
14916
|
nextRunAt
|
|
14869
14917
|
});
|
|
14870
|
-
|
|
14918
|
+
log20.info("ads-sync.triggered", { runId: runId2, projectName: project.name });
|
|
14871
14919
|
this.callbacks.onAdsSyncRequested(runId2, projectId);
|
|
14872
14920
|
return SLOT_FIRED;
|
|
14873
14921
|
}
|
|
14874
14922
|
if (kind === SchedulableRunKinds["seo-sync"]) {
|
|
14875
14923
|
if (!this.callbacks.onSeoSyncRequested) {
|
|
14876
|
-
|
|
14924
|
+
log20.warn("seo-sync.no-callback", { scheduleId, projectId, msg: "host did not register onSeoSyncRequested" });
|
|
14877
14925
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14878
14926
|
}
|
|
14879
14927
|
const activeSeoRun = this.db.select({ id: runs.id }).from(runs).where(and19(
|
|
14880
|
-
|
|
14881
|
-
|
|
14928
|
+
eq24(runs.projectId, projectId),
|
|
14929
|
+
eq24(runs.kind, RunKinds["seo-sync"]),
|
|
14882
14930
|
inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
|
|
14883
14931
|
)).get();
|
|
14884
14932
|
if (activeSeoRun) {
|
|
14885
|
-
|
|
14933
|
+
log20.info("seo-sync.skipped-active", { projectName: project.name, activeRunId: activeSeoRun.id });
|
|
14886
14934
|
this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
|
|
14887
14935
|
return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
|
|
14888
14936
|
}
|
|
@@ -14890,61 +14938,61 @@ var Scheduler = class {
|
|
|
14890
14938
|
lastRunAt: now,
|
|
14891
14939
|
nextRunAt
|
|
14892
14940
|
});
|
|
14893
|
-
|
|
14941
|
+
log20.info("seo-sync.triggered", { projectName: project.name });
|
|
14894
14942
|
this.callbacks.onSeoSyncRequested({ scheduleId, projectId, occurrence: now.slice(0, 16) });
|
|
14895
14943
|
return SLOT_FIRED;
|
|
14896
14944
|
}
|
|
14897
14945
|
if (kind === SchedulableRunKinds["data-refresh"]) {
|
|
14898
14946
|
if (!this.callbacks.onDataRefreshRequested) {
|
|
14899
|
-
|
|
14947
|
+
log20.warn("data-refresh.no-callback", { scheduleId, projectId, msg: "host did not register onDataRefreshRequested" });
|
|
14900
14948
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14901
14949
|
}
|
|
14902
14950
|
this.updateScheduleTiming(currentSchedule.id, {
|
|
14903
14951
|
lastRunAt: now,
|
|
14904
14952
|
nextRunAt
|
|
14905
14953
|
});
|
|
14906
|
-
|
|
14954
|
+
log20.info("data-refresh.triggered", { projectName: project.name });
|
|
14907
14955
|
this.callbacks.onDataRefreshRequested(project.name);
|
|
14908
14956
|
return SLOT_FIRED;
|
|
14909
14957
|
}
|
|
14910
14958
|
if (kind === SchedulableRunKinds.doctor) {
|
|
14911
14959
|
if (!this.callbacks.onDoctorRequested) {
|
|
14912
|
-
|
|
14960
|
+
log20.warn("doctor.no-callback", { scheduleId, projectId, msg: "host did not register onDoctorRequested" });
|
|
14913
14961
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14914
14962
|
}
|
|
14915
14963
|
this.updateScheduleTiming(currentSchedule.id, {
|
|
14916
14964
|
lastRunAt: now,
|
|
14917
14965
|
nextRunAt
|
|
14918
14966
|
});
|
|
14919
|
-
|
|
14967
|
+
log20.info("doctor.triggered", { projectName: project.name });
|
|
14920
14968
|
this.callbacks.onDoctorRequested(project.name);
|
|
14921
14969
|
return SLOT_FIRED;
|
|
14922
14970
|
}
|
|
14923
14971
|
if (kind === SchedulableRunKinds["backlinks-sync"]) {
|
|
14924
14972
|
if (!this.callbacks.onBacklinksSyncRequested) {
|
|
14925
|
-
|
|
14973
|
+
log20.warn("backlinks-sync.no-callback", { scheduleId, projectId, msg: "host did not register onBacklinksSyncRequested" });
|
|
14926
14974
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14927
14975
|
}
|
|
14928
14976
|
this.updateScheduleTiming(currentSchedule.id, {
|
|
14929
14977
|
lastRunAt: now,
|
|
14930
14978
|
nextRunAt
|
|
14931
14979
|
});
|
|
14932
|
-
|
|
14980
|
+
log20.info("backlinks-sync.triggered", { projectName: project.name });
|
|
14933
14981
|
this.callbacks.onBacklinksSyncRequested(project.name);
|
|
14934
14982
|
return SLOT_FIRED;
|
|
14935
14983
|
}
|
|
14936
14984
|
if (kind === SchedulableRunKinds["site-audit"]) {
|
|
14937
14985
|
if (!this.callbacks.onSiteAuditRequested) {
|
|
14938
|
-
|
|
14986
|
+
log20.warn("site-audit.no-callback", { scheduleId, projectId, msg: "host did not register onSiteAuditRequested" });
|
|
14939
14987
|
return slotFailed(OutcomeReasonCodes.UNSUPPORTED);
|
|
14940
14988
|
}
|
|
14941
14989
|
const active = this.db.select({ id: runs.id }).from(runs).where(and19(
|
|
14942
|
-
|
|
14943
|
-
|
|
14990
|
+
eq24(runs.projectId, projectId),
|
|
14991
|
+
eq24(runs.kind, RunKinds["site-audit"]),
|
|
14944
14992
|
inArray10(runs.status, [RunStatuses.queued, RunStatuses.running])
|
|
14945
14993
|
)).get();
|
|
14946
14994
|
if (active) {
|
|
14947
|
-
|
|
14995
|
+
log20.info("site-audit.skipped-active", { projectName: project.name, activeRunId: active.id });
|
|
14948
14996
|
this.updateScheduleTiming(currentSchedule.id, { nextRunAt });
|
|
14949
14997
|
return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
|
|
14950
14998
|
}
|
|
@@ -14973,7 +15021,7 @@ var Scheduler = class {
|
|
|
14973
15021
|
lastRunAt: now,
|
|
14974
15022
|
nextRunAt
|
|
14975
15023
|
});
|
|
14976
|
-
|
|
15024
|
+
log20.info("site-audit.triggered", { runId: runId2, projectName: project.name });
|
|
14977
15025
|
this.callbacks.onSiteAuditRequested(runId2, projectId, {
|
|
14978
15026
|
maxPages: effectiveRequest.maxPages,
|
|
14979
15027
|
checkDeadLinks: effectiveRequest.checkDeadLinks,
|
|
@@ -14988,7 +15036,7 @@ var Scheduler = class {
|
|
|
14988
15036
|
if (project.defaultLocation) {
|
|
14989
15037
|
const loc = projectLocations.find((l) => l.label === project.defaultLocation);
|
|
14990
15038
|
if (!loc) {
|
|
14991
|
-
|
|
15039
|
+
log20.warn("default-location.stale", { scheduleId, projectId, label: project.defaultLocation });
|
|
14992
15040
|
return slotFailed(OutcomeReasonCodes.VALIDATION);
|
|
14993
15041
|
}
|
|
14994
15042
|
resolvedLocation = loc;
|
|
@@ -14997,7 +15045,7 @@ var Scheduler = class {
|
|
|
14997
15045
|
const scheduleProviders = currentSchedule.providers;
|
|
14998
15046
|
const providers = scheduleProviders.length > 0 ? scheduleProviders : void 0;
|
|
14999
15047
|
if (claimedOccurrence && recurrence && !nextRunAt) {
|
|
15000
|
-
|
|
15048
|
+
log20.error("calendar.invalid", { projectId, kind, scheduleId });
|
|
15001
15049
|
return slotFailed(OutcomeReasonCodes.VALIDATION);
|
|
15002
15050
|
}
|
|
15003
15051
|
const queueResult = queueRunIfProjectIdle(this.db, {
|
|
@@ -15025,11 +15073,11 @@ var Scheduler = class {
|
|
|
15025
15073
|
});
|
|
15026
15074
|
if (queueResult.conflict) {
|
|
15027
15075
|
if (queueResult.scheduleClaimed === false) {
|
|
15028
|
-
|
|
15076
|
+
log20.info("calendar.skipped-claimed", { projectName: project.name, scheduleId: currentSchedule.id });
|
|
15029
15077
|
return slotSkipped(OutcomeReasonCodes.NOT_DUE);
|
|
15030
15078
|
}
|
|
15031
15079
|
const batchPending = hasOutstandingProviderBatch(this.db, queueResult.activeRunId);
|
|
15032
|
-
|
|
15080
|
+
log20.info("run.skipped-active", {
|
|
15033
15081
|
projectName: project.name,
|
|
15034
15082
|
activeRunId: queueResult.activeRunId,
|
|
15035
15083
|
...batchPending ? { reason: "batch-pending" } : {}
|
|
@@ -15038,7 +15086,7 @@ var Scheduler = class {
|
|
|
15038
15086
|
return slotSkipped(OutcomeReasonCodes.OPERATION_IN_PROGRESS);
|
|
15039
15087
|
}
|
|
15040
15088
|
if (queueResult.refused) {
|
|
15041
|
-
|
|
15089
|
+
log20.warn("run.skipped-providers-failing", {
|
|
15042
15090
|
projectName: project.name,
|
|
15043
15091
|
scheduleId: currentSchedule.id,
|
|
15044
15092
|
...queueResult.refused
|
|
@@ -15057,7 +15105,7 @@ var Scheduler = class {
|
|
|
15057
15105
|
const runId = queueResult.runId;
|
|
15058
15106
|
for (const [provider, reason] of Object.entries(queueResult.dispatch.ineligible)) {
|
|
15059
15107
|
if (!reason) continue;
|
|
15060
|
-
|
|
15108
|
+
log20.warn("run.dispatch-sync-fallback", {
|
|
15061
15109
|
runId,
|
|
15062
15110
|
projectName: project.name,
|
|
15063
15111
|
provider,
|
|
@@ -15071,7 +15119,7 @@ var Scheduler = class {
|
|
|
15071
15119
|
lastRunAt: now,
|
|
15072
15120
|
nextRunAt
|
|
15073
15121
|
});
|
|
15074
|
-
|
|
15122
|
+
log20.info("run.triggered", {
|
|
15075
15123
|
runId,
|
|
15076
15124
|
projectName: project.name,
|
|
15077
15125
|
providers: providers ?? "all",
|
|
@@ -15080,14 +15128,14 @@ var Scheduler = class {
|
|
|
15080
15128
|
this.callbacks.onRunCreated(runId, projectId, providers, resolvedLocation);
|
|
15081
15129
|
return SLOT_FIRED;
|
|
15082
15130
|
} catch (err) {
|
|
15083
|
-
|
|
15131
|
+
log20.error("trigger.error", { scheduleId, projectId, kind, error: describeError(err) });
|
|
15084
15132
|
return { status: OutcomeStatuses.failed, ...outcomeFailure(err) };
|
|
15085
15133
|
}
|
|
15086
15134
|
}
|
|
15087
15135
|
};
|
|
15088
15136
|
|
|
15089
15137
|
// src/site-liveness-loop.ts
|
|
15090
|
-
var
|
|
15138
|
+
var log21 = createLogger("SiteLiveness");
|
|
15091
15139
|
var SITE_LIVENESS_INTERVAL_MS = 10 * 6e4;
|
|
15092
15140
|
async function runSiteLivenessPass(deps) {
|
|
15093
15141
|
const now = deps.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
|
|
@@ -15104,10 +15152,10 @@ async function runSiteLivenessPass(deps) {
|
|
|
15104
15152
|
const event = await deps.notify(project.id, { check, checkedAt: now() });
|
|
15105
15153
|
if (event) {
|
|
15106
15154
|
events += 1;
|
|
15107
|
-
|
|
15155
|
+
log21.info("site-liveness.notified", { projectName: project.name, event, code: check.code });
|
|
15108
15156
|
}
|
|
15109
15157
|
} catch (err) {
|
|
15110
|
-
|
|
15158
|
+
log21.warn("site-liveness.project-failed", { projectName: project.name, err: String(err) });
|
|
15111
15159
|
if (failed === 0) firstFailure = err;
|
|
15112
15160
|
failed += 1;
|
|
15113
15161
|
}
|
|
@@ -15139,14 +15187,14 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
|
|
|
15139
15187
|
};
|
|
15140
15188
|
const timer = setInterval(() => {
|
|
15141
15189
|
if (running) {
|
|
15142
|
-
|
|
15190
|
+
log21.warn("site-liveness.pass-still-running", { intervalMs });
|
|
15143
15191
|
report({ status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.OPERATION_IN_PROGRESS });
|
|
15144
15192
|
return;
|
|
15145
15193
|
}
|
|
15146
15194
|
running = true;
|
|
15147
15195
|
const elapsed = startOutcomeTimer();
|
|
15148
15196
|
void runSiteLivenessPass(deps).then((result) => report({ ...livenessOutcome(result), durationBucket: elapsed() })).catch((err) => {
|
|
15149
|
-
|
|
15197
|
+
log21.warn("site-liveness.pass-failed", { err: String(err) });
|
|
15150
15198
|
report({ status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() });
|
|
15151
15199
|
}).finally(() => {
|
|
15152
15200
|
running = false;
|
|
@@ -15158,8 +15206,8 @@ function startSiteLivenessLoop(deps, intervalMs = SITE_LIVENESS_INTERVAL_MS) {
|
|
|
15158
15206
|
|
|
15159
15207
|
// src/review-webhook-delivery.ts
|
|
15160
15208
|
import { createHash as createHash7 } from "crypto";
|
|
15161
|
-
import { and as and20, asc as asc4, eq as
|
|
15162
|
-
var
|
|
15209
|
+
import { and as and20, asc as asc4, eq as eq25, isNull as isNull3, lte as lte2, or } from "drizzle-orm";
|
|
15210
|
+
var log22 = createLogger("ReviewDelivery");
|
|
15163
15211
|
var hash = (value) => createHash7("sha256").update(JSON.stringify(value)).digest("hex");
|
|
15164
15212
|
var REVIEW_DELIVERY_MAX_ATTEMPTS = 10;
|
|
15165
15213
|
var REVIEW_CHAT_SENDS_PER_PASS = 3;
|
|
@@ -15186,20 +15234,20 @@ function reviewEventId(projectId, review) {
|
|
|
15186
15234
|
function reviewEventRefusal(db, projectId, payload, notification, targetDigest, now) {
|
|
15187
15235
|
if (!notification?.enabled || !notification.config.events.includes("review.negative")) return "destination_disabled";
|
|
15188
15236
|
if (targetDigest !== void 0 && hash(notification.config.url) !== targetDigest) return "destination_changed";
|
|
15189
|
-
const project = db.select().from(projects).where(
|
|
15237
|
+
const project = db.select().from(projects).where(eq25(projects.id, projectId)).get();
|
|
15190
15238
|
if (!project || project.name !== payload.project.name || project.canonicalDomain !== payload.project.canonicalDomain) return "project_changed";
|
|
15191
15239
|
const review = payload.reviews[0];
|
|
15192
15240
|
const location = db.select().from(gbpLocations).where(and20(
|
|
15193
|
-
|
|
15194
|
-
|
|
15195
|
-
|
|
15241
|
+
eq25(gbpLocations.projectId, projectId),
|
|
15242
|
+
eq25(gbpLocations.locationName, review.location.name),
|
|
15243
|
+
eq25(gbpLocations.selected, true)
|
|
15196
15244
|
)).get();
|
|
15197
15245
|
if (!location || review.origin === "gbp" && !review.reviewName.startsWith(`${location.accountName}/${location.locationName}/reviews/`)) return "location_removed_or_deselected";
|
|
15198
15246
|
const current = db.select().from(gbpReviews).where(and20(
|
|
15199
|
-
|
|
15200
|
-
|
|
15201
|
-
|
|
15202
|
-
|
|
15247
|
+
eq25(gbpReviews.projectId, projectId),
|
|
15248
|
+
eq25(gbpReviews.origin, review.origin),
|
|
15249
|
+
eq25(gbpReviews.reviewName, review.reviewName),
|
|
15250
|
+
eq25(gbpReviews.locationName, review.location.name)
|
|
15203
15251
|
)).get();
|
|
15204
15252
|
if (!current) return "review_removed";
|
|
15205
15253
|
if (!isWithinAlertWindow(review.updateTime, now) || !isWithinAlertWindow(current.updateTime, now)) return "review_expired";
|
|
@@ -15208,9 +15256,9 @@ function reviewEventRefusal(db, projectId, payload, notification, targetDigest,
|
|
|
15208
15256
|
if (["baseline", "skipped", "suppressed", "stale", "none"].includes(current.alertState)) return "review_suppressed";
|
|
15209
15257
|
if (review.origin === "places") {
|
|
15210
15258
|
const v4HasWorked = db.select({ id: gbpReviewRatings.id }).from(gbpReviewRatings).where(and20(
|
|
15211
|
-
|
|
15212
|
-
|
|
15213
|
-
|
|
15259
|
+
eq25(gbpReviewRatings.projectId, projectId),
|
|
15260
|
+
eq25(gbpReviewRatings.locationName, review.location.name),
|
|
15261
|
+
eq25(gbpReviewRatings.origin, "gbp")
|
|
15214
15262
|
)).get() !== void 0;
|
|
15215
15263
|
if (businessProfileReviewsCover(location.reviewsAccess, v4HasWorked)) return "review_origin_superseded";
|
|
15216
15264
|
}
|
|
@@ -15219,8 +15267,8 @@ function reviewEventRefusal(db, projectId, payload, notification, targetDigest,
|
|
|
15219
15267
|
function cancelReviewDelivery(db, id, reason) {
|
|
15220
15268
|
db.transaction((tx) => {
|
|
15221
15269
|
const canceled = tx.update(reviewWebhookDeliveries).set({ state: ReviewDeliveryStates.Canceled, retryAt: null }).where(and20(
|
|
15222
|
-
|
|
15223
|
-
|
|
15270
|
+
eq25(reviewWebhookDeliveries.id, id),
|
|
15271
|
+
eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending)
|
|
15224
15272
|
)).returning({ projectId: reviewWebhookDeliveries.projectId, eventId: reviewWebhookDeliveries.eventId, notificationId: reviewWebhookDeliveries.notificationId, targetDigest: reviewWebhookDeliveries.targetDigest }).get();
|
|
15225
15273
|
if (canceled) writeAuditLog(tx, {
|
|
15226
15274
|
projectId: canceled.projectId,
|
|
@@ -15237,9 +15285,9 @@ function deferReviewDelivery(db, saved, now) {
|
|
|
15237
15285
|
const waited = now - Date.parse(saved.createdAt);
|
|
15238
15286
|
const delay = Math.min(Math.max(RETRY_BASE_MS, Number.isFinite(waited) ? waited / 4 : RETRY_BASE_MS), RETRY_MAX_MS);
|
|
15239
15287
|
db.update(reviewWebhookDeliveries).set({ retryAt: new Date(now + delay).toISOString() }).where(and20(
|
|
15240
|
-
|
|
15241
|
-
|
|
15242
|
-
|
|
15288
|
+
eq25(reviewWebhookDeliveries.id, saved.id),
|
|
15289
|
+
eq25(reviewWebhookDeliveries.state, saved.state),
|
|
15290
|
+
eq25(reviewWebhookDeliveries.attempts, saved.attempts)
|
|
15243
15291
|
)).run();
|
|
15244
15292
|
}
|
|
15245
15293
|
function auditUndelivered(db, saved, outcome) {
|
|
@@ -15256,8 +15304,8 @@ function dueReviewDeliveryProjects(db, now) {
|
|
|
15256
15304
|
const at = new Date(now).toISOString();
|
|
15257
15305
|
const staleAttempt = new Date(now - 6e4).toISOString();
|
|
15258
15306
|
return db.selectDistinct({ projectId: reviewWebhookDeliveries.projectId }).from(reviewWebhookDeliveries).where(or(
|
|
15259
|
-
and20(
|
|
15260
|
-
and20(
|
|
15307
|
+
and20(eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending), or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at))),
|
|
15308
|
+
and20(eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
|
|
15261
15309
|
)).all().map((row) => row.projectId);
|
|
15262
15310
|
}
|
|
15263
15311
|
function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS) {
|
|
@@ -15266,7 +15314,7 @@ function startReviewDeliveryLoop(drain, intervalMs = REVIEW_DELIVERY_INTERVAL_MS
|
|
|
15266
15314
|
if (running) return;
|
|
15267
15315
|
running = true;
|
|
15268
15316
|
void drain().catch((err) => {
|
|
15269
|
-
|
|
15317
|
+
log22.warn("review-delivery.drain-failed", { error: describeError(err) });
|
|
15270
15318
|
}).finally(() => {
|
|
15271
15319
|
running = false;
|
|
15272
15320
|
});
|
|
@@ -15279,11 +15327,11 @@ async function drainReviewDeliveries(options) {
|
|
|
15279
15327
|
const at = new Date(now).toISOString();
|
|
15280
15328
|
const staleAttempt = new Date(now - 6e4).toISOString();
|
|
15281
15329
|
const ready = options.db.select().from(reviewWebhookDeliveries).where(and20(
|
|
15282
|
-
|
|
15330
|
+
eq25(reviewWebhookDeliveries.projectId, options.projectId),
|
|
15283
15331
|
or(isNull3(reviewWebhookDeliveries.retryAt), lte2(reviewWebhookDeliveries.retryAt, at)),
|
|
15284
15332
|
or(
|
|
15285
|
-
|
|
15286
|
-
and20(
|
|
15333
|
+
eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
|
|
15334
|
+
and20(eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting), lte2(reviewWebhookDeliveries.attemptedAt, staleAttempt))
|
|
15287
15335
|
)
|
|
15288
15336
|
)).orderBy(asc4(reviewWebhookDeliveries.retryAt), asc4(reviewWebhookDeliveries.attemptedAt), asc4(reviewWebhookDeliveries.createdAt), asc4(reviewWebhookDeliveries.id)).limit(100).all();
|
|
15289
15337
|
let delivered = 0;
|
|
@@ -15308,14 +15356,14 @@ async function deliverReviewEvent(options) {
|
|
|
15308
15356
|
return false;
|
|
15309
15357
|
const notification = db.select().from(notifications).where(
|
|
15310
15358
|
and20(
|
|
15311
|
-
|
|
15312
|
-
|
|
15359
|
+
eq25(notifications.id, notificationId),
|
|
15360
|
+
eq25(notifications.projectId, projectId)
|
|
15313
15361
|
)
|
|
15314
15362
|
).get();
|
|
15315
15363
|
const id = hash([projectId, notificationId, payload.eventId]);
|
|
15316
15364
|
const now = options.now ?? Date.now;
|
|
15317
15365
|
const at = new Date(now()).toISOString();
|
|
15318
|
-
let saved = db.select().from(reviewWebhookDeliveries).where(
|
|
15366
|
+
let saved = db.select().from(reviewWebhookDeliveries).where(eq25(reviewWebhookDeliveries.id, id)).get();
|
|
15319
15367
|
const event = saved?.payload ?? payload;
|
|
15320
15368
|
const refusal = reviewEventRefusal(db, projectId, event, notification, saved?.targetDigest, new Date(now()));
|
|
15321
15369
|
if (refusal) {
|
|
@@ -15334,7 +15382,7 @@ async function deliverReviewEvent(options) {
|
|
|
15334
15382
|
payload,
|
|
15335
15383
|
createdAt: at
|
|
15336
15384
|
}).onConflictDoNothing().run();
|
|
15337
|
-
saved = db.select().from(reviewWebhookDeliveries).where(
|
|
15385
|
+
saved = db.select().from(reviewWebhookDeliveries).where(eq25(reviewWebhookDeliveries.id, id)).get();
|
|
15338
15386
|
if (!saved || saved.targetDigest !== targetDigest) return false;
|
|
15339
15387
|
if (saved.state === ReviewDeliveryStates.Sent) return true;
|
|
15340
15388
|
if (saved.state === ReviewDeliveryStates.Uncertain || saved.state === ReviewDeliveryStates.Canceled) return false;
|
|
@@ -15350,16 +15398,16 @@ async function deliverReviewEvent(options) {
|
|
|
15350
15398
|
const state2 = destination.signed ? ReviewDeliveryStates.Pending : ReviewDeliveryStates.Uncertain;
|
|
15351
15399
|
const moved = db.update(reviewWebhookDeliveries).set({ state: state2 }).where(
|
|
15352
15400
|
and20(
|
|
15353
|
-
|
|
15354
|
-
|
|
15355
|
-
|
|
15356
|
-
|
|
15401
|
+
eq25(reviewWebhookDeliveries.id, id),
|
|
15402
|
+
eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
|
|
15403
|
+
eq25(reviewWebhookDeliveries.attempts, saved.attempts),
|
|
15404
|
+
eq25(reviewWebhookDeliveries.attemptedAt, saved.attemptedAt)
|
|
15357
15405
|
)
|
|
15358
15406
|
).returning({ id: reviewWebhookDeliveries.id }).get();
|
|
15359
15407
|
if (moved && state2 === ReviewDeliveryStates.Uncertain) {
|
|
15360
15408
|
auditUndelivered(db, saved, { state: state2, reason: "interrupted_attempt", attempts: saved.attempts });
|
|
15361
15409
|
}
|
|
15362
|
-
saved = db.select().from(reviewWebhookDeliveries).where(
|
|
15410
|
+
saved = db.select().from(reviewWebhookDeliveries).where(eq25(reviewWebhookDeliveries.id, id)).get();
|
|
15363
15411
|
if (!saved || saved.state !== ReviewDeliveryStates.Pending) return false;
|
|
15364
15412
|
}
|
|
15365
15413
|
if (saved.retryAt && Date.parse(saved.retryAt) > now()) return false;
|
|
@@ -15382,8 +15430,8 @@ async function deliverReviewEvent(options) {
|
|
|
15382
15430
|
}
|
|
15383
15431
|
const latest = db.select().from(notifications).where(
|
|
15384
15432
|
and20(
|
|
15385
|
-
|
|
15386
|
-
|
|
15433
|
+
eq25(notifications.id, notificationId),
|
|
15434
|
+
eq25(notifications.projectId, projectId)
|
|
15387
15435
|
)
|
|
15388
15436
|
).get();
|
|
15389
15437
|
const latestRefusal = reviewEventRefusal(db, projectId, saved.payload, latest, targetDigest, new Date(now()));
|
|
@@ -15397,9 +15445,9 @@ async function deliverReviewEvent(options) {
|
|
|
15397
15445
|
attemptedAt: new Date(now()).toISOString()
|
|
15398
15446
|
}).where(
|
|
15399
15447
|
and20(
|
|
15400
|
-
|
|
15401
|
-
|
|
15402
|
-
|
|
15448
|
+
eq25(reviewWebhookDeliveries.id, id),
|
|
15449
|
+
eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Pending),
|
|
15450
|
+
eq25(reviewWebhookDeliveries.attempts, saved.attempts)
|
|
15403
15451
|
)
|
|
15404
15452
|
).returning({ id: reviewWebhookDeliveries.id }).get();
|
|
15405
15453
|
if (!claimed) return false;
|
|
@@ -15427,9 +15475,9 @@ async function deliverReviewEvent(options) {
|
|
|
15427
15475
|
retryAt: state === ReviewDeliveryStates.Pending ? new Date(now() + retryDelayMs(attempts, result.retryAfterSeconds)).toISOString() : null
|
|
15428
15476
|
}).where(
|
|
15429
15477
|
and20(
|
|
15430
|
-
|
|
15431
|
-
|
|
15432
|
-
|
|
15478
|
+
eq25(reviewWebhookDeliveries.id, id),
|
|
15479
|
+
eq25(reviewWebhookDeliveries.state, ReviewDeliveryStates.Attempting),
|
|
15480
|
+
eq25(reviewWebhookDeliveries.attempts, attempts)
|
|
15433
15481
|
)
|
|
15434
15482
|
).run();
|
|
15435
15483
|
if (state === ReviewDeliveryStates.Uncertain || state === ReviewDeliveryStates.Failed) {
|
|
@@ -15441,7 +15489,7 @@ async function deliverReviewEvent(options) {
|
|
|
15441
15489
|
}
|
|
15442
15490
|
|
|
15443
15491
|
// src/unrecognized-agent-alerts.ts
|
|
15444
|
-
import { and as and21, desc as desc8, eq as
|
|
15492
|
+
import { and as and21, desc as desc8, eq as eq26, gte as gte3, sql as sql10 } from "drizzle-orm";
|
|
15445
15493
|
|
|
15446
15494
|
// src/alert-loop.ts
|
|
15447
15495
|
function startAlertLoop(dispatch, intervalMs, onError) {
|
|
@@ -15458,7 +15506,7 @@ function startAlertLoop(dispatch, intervalMs, onError) {
|
|
|
15458
15506
|
}
|
|
15459
15507
|
|
|
15460
15508
|
// src/unrecognized-agent-alerts.ts
|
|
15461
|
-
var
|
|
15509
|
+
var log23 = createLogger("UnrecognizedAgentAlerts");
|
|
15462
15510
|
var UNRECOGNIZED_AGENT_ALERT_WINDOW_MS = 7 * 864e5;
|
|
15463
15511
|
var UNRECOGNIZED_AGENT_ALERT_MIN_HITS = 3;
|
|
15464
15512
|
var UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS = 15 * 6e4;
|
|
@@ -15473,13 +15521,13 @@ function projectsWithRecentUnrecognizedAgents(db, now) {
|
|
|
15473
15521
|
return db.selectDistinct({ projectId: unrecognizedAgentEventsHourly.projectId }).from(unrecognizedAgentEventsHourly).where(gte3(unrecognizedAgentEventsHourly.tsHour, since)).all().map((row) => row.projectId);
|
|
15474
15522
|
}
|
|
15475
15523
|
function undecidedUnrecognizedAgents(db, projectId, now) {
|
|
15476
|
-
const decided = new Set(db.select({ agentName: unrecognizedAgentNotifyState.agentName }).from(unrecognizedAgentNotifyState).where(
|
|
15524
|
+
const decided = new Set(db.select({ agentName: unrecognizedAgentNotifyState.agentName }).from(unrecognizedAgentNotifyState).where(eq26(unrecognizedAgentNotifyState.projectId, projectId)).all().map((row) => row.agentName));
|
|
15477
15525
|
const totals = db.select({
|
|
15478
15526
|
name: unrecognizedAgentEventsHourly.agentName,
|
|
15479
15527
|
hits: sql10`SUM(${unrecognizedAgentEventsHourly.hits})`,
|
|
15480
15528
|
firstSeenAt: sql10`MIN(${unrecognizedAgentEventsHourly.tsHour})`,
|
|
15481
15529
|
lastSeenAt: sql10`MAX(${unrecognizedAgentEventsHourly.tsHour})`
|
|
15482
|
-
}).from(unrecognizedAgentEventsHourly).where(
|
|
15530
|
+
}).from(unrecognizedAgentEventsHourly).where(eq26(unrecognizedAgentEventsHourly.projectId, projectId)).groupBy(unrecognizedAgentEventsHourly.agentName).all();
|
|
15483
15531
|
const windowStart = new Date(now - UNRECOGNIZED_AGENT_ALERT_WINDOW_MS).toISOString();
|
|
15484
15532
|
const recordingStart = totals.reduce((earliest, total) => earliest === null || total.firstSeenAt < earliest ? total.firstSeenAt : earliest, null);
|
|
15485
15533
|
const baselineEnd = recordingStart === null ? null : new Date(Date.parse(recordingStart) + UNRECOGNIZED_AGENT_ALERT_WINDOW_MS).toISOString();
|
|
@@ -15497,7 +15545,7 @@ function undecidedUnrecognizedAgents(db, projectId, now) {
|
|
|
15497
15545
|
continue;
|
|
15498
15546
|
}
|
|
15499
15547
|
if (Number(total.hits) < UNRECOGNIZED_AGENT_ALERT_MIN_HITS) continue;
|
|
15500
|
-
const latest = db.select({ sampledUserAgent: unrecognizedAgentEventsHourly.sampledUserAgent, sampledPath: unrecognizedAgentEventsHourly.sampledPath }).from(unrecognizedAgentEventsHourly).where(and21(
|
|
15548
|
+
const latest = db.select({ sampledUserAgent: unrecognizedAgentEventsHourly.sampledUserAgent, sampledPath: unrecognizedAgentEventsHourly.sampledPath }).from(unrecognizedAgentEventsHourly).where(and21(eq26(unrecognizedAgentEventsHourly.projectId, projectId), eq26(unrecognizedAgentEventsHourly.agentName, total.name))).orderBy(desc8(unrecognizedAgentEventsHourly.tsHour)).limit(1).get();
|
|
15501
15549
|
due.push({
|
|
15502
15550
|
name: total.name,
|
|
15503
15551
|
hits: Number(total.hits),
|
|
@@ -15518,13 +15566,13 @@ function recordUnrecognizedAgentDecisions(db, projectId, names, state, now) {
|
|
|
15518
15566
|
}
|
|
15519
15567
|
function startUnrecognizedAgentAlertLoop(dispatch, intervalMs = UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS) {
|
|
15520
15568
|
return startAlertLoop(dispatch, intervalMs, (err) => {
|
|
15521
|
-
|
|
15569
|
+
log23.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
|
|
15522
15570
|
});
|
|
15523
15571
|
}
|
|
15524
15572
|
|
|
15525
15573
|
// src/sentiment-alerts.ts
|
|
15526
|
-
import { and as and22, asc as asc5, eq as
|
|
15527
|
-
var
|
|
15574
|
+
import { and as and22, asc as asc5, eq as eq27, gte as gte4, inArray as inArray11, sql as sql11 } from "drizzle-orm";
|
|
15575
|
+
var log24 = createLogger("SentimentAlerts");
|
|
15528
15576
|
var SENTIMENT_ALERT_WINDOW_MS = 7 * 864e5;
|
|
15529
15577
|
var SENTIMENT_ALERT_INTERVAL_MS = 5 * 6e4;
|
|
15530
15578
|
var SentimentAlertStates = {
|
|
@@ -15545,7 +15593,7 @@ function settledSentimentRuns(db, now) {
|
|
|
15545
15593
|
open: sql11`SUM(${sentimentJobs.pendingItems} + ${sentimentJobs.runningItems})`,
|
|
15546
15594
|
lastReceipt,
|
|
15547
15595
|
reconciled: sentimentSettings.reconciledSequence
|
|
15548
|
-
}).from(sentimentJobs).innerJoin(runs, and22(
|
|
15596
|
+
}).from(sentimentJobs).innerJoin(runs, and22(eq27(runs.projectId, sentimentJobs.projectId), sql11`${runs.id} = ${jobRunId}`)).leftJoin(sentimentSettings, eq27(sentimentSettings.projectId, sentimentJobs.projectId)).where(and22(eq27(sentimentJobs.action, AUTOMATIC), gte4(sentimentJobs.createdAt, since), notProbeRun())).groupBy(sentimentJobs.projectId, runs.id).orderBy(asc5(runs.createdAt), asc5(runs.id)).all();
|
|
15549
15597
|
const settled = /* @__PURE__ */ new Map();
|
|
15550
15598
|
const waiting = /* @__PURE__ */ new Set();
|
|
15551
15599
|
for (const row of rows) {
|
|
@@ -15563,8 +15611,8 @@ function settledSentimentRuns(db, now) {
|
|
|
15563
15611
|
}
|
|
15564
15612
|
function undecidedSentimentRuns(db, projectId, runIds) {
|
|
15565
15613
|
if (runIds.length === 0) return { undecided: [], firstPass: false };
|
|
15566
|
-
const decided = new Set(db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(and22(
|
|
15567
|
-
const firstPass = db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(
|
|
15614
|
+
const decided = new Set(db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(and22(eq27(sentimentAlertRuns.projectId, projectId), inArray11(sentimentAlertRuns.runId, [...runIds]))).all().map((row) => row.runId));
|
|
15615
|
+
const firstPass = db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(eq27(sentimentAlertRuns.projectId, projectId)).limit(1).get() === void 0;
|
|
15568
15616
|
return { undecided: runIds.filter((runId) => !decided.has(runId)), firstPass };
|
|
15569
15617
|
}
|
|
15570
15618
|
function recordSentimentAlertRuns(db, projectId, runIds, state, now) {
|
|
@@ -15575,13 +15623,13 @@ function recordSentimentAlertRuns(db, projectId, runIds, state, now) {
|
|
|
15575
15623
|
}
|
|
15576
15624
|
function startSentimentAlertLoop(dispatch, intervalMs = SENTIMENT_ALERT_INTERVAL_MS) {
|
|
15577
15625
|
return startAlertLoop(dispatch, intervalMs, (err) => {
|
|
15578
|
-
|
|
15626
|
+
log24.warn("sentiment-alerts.dispatch-failed", { error: describeError(err) });
|
|
15579
15627
|
});
|
|
15580
15628
|
}
|
|
15581
15629
|
|
|
15582
15630
|
// src/provider-batch-poller.ts
|
|
15583
|
-
import { and as and23, eq as
|
|
15584
|
-
var
|
|
15631
|
+
import { and as and23, eq as eq28, inArray as inArray12, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql12 } from "drizzle-orm";
|
|
15632
|
+
var log25 = createLogger("ProviderBatchPoller");
|
|
15585
15633
|
var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
|
|
15586
15634
|
var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
|
|
15587
15635
|
var PROVIDER_BATCH_CANCEL_GRACE_MS = 60 * 6e4;
|
|
@@ -15605,7 +15653,7 @@ var ProviderBatchPoller = class {
|
|
|
15605
15653
|
try {
|
|
15606
15654
|
if (await this.advance(row)) settledRuns.set(row.runId, row.projectId);
|
|
15607
15655
|
} catch (err) {
|
|
15608
|
-
|
|
15656
|
+
log25.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
|
|
15609
15657
|
this.reschedule(row.id, null);
|
|
15610
15658
|
}
|
|
15611
15659
|
}
|
|
@@ -15614,7 +15662,7 @@ var ProviderBatchPoller = class {
|
|
|
15614
15662
|
try {
|
|
15615
15663
|
this.deps.runner.finalizeBatchRun(runId, projectId);
|
|
15616
15664
|
} catch (err) {
|
|
15617
|
-
|
|
15665
|
+
log25.warn("batch.finalize-failed", { runId, error: describeError(err) });
|
|
15618
15666
|
}
|
|
15619
15667
|
}
|
|
15620
15668
|
}
|
|
@@ -15623,7 +15671,7 @@ var ProviderBatchPoller = class {
|
|
|
15623
15671
|
* outstanding (ingested or cancelled), so its run may now finalize.
|
|
15624
15672
|
*/
|
|
15625
15673
|
async advance(row) {
|
|
15626
|
-
const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(
|
|
15674
|
+
const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq28(runs.id, row.runId)).get()?.status;
|
|
15627
15675
|
if (runStatus !== RunStatuses.running) {
|
|
15628
15676
|
await this.deps.runner.abandonProviderBatches([row.id], "Cancelled because its run is no longer running.");
|
|
15629
15677
|
this.schedule.delete(row.id);
|
|
@@ -15640,15 +15688,15 @@ var ProviderBatchPoller = class {
|
|
|
15640
15688
|
status = poll.status;
|
|
15641
15689
|
if (poll.status === "ended") {
|
|
15642
15690
|
const endedAt = poll.endedAt ?? new Date(this.now()).toISOString();
|
|
15643
|
-
const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and23(
|
|
15691
|
+
const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and23(eq28(providerBatches.id, row.id), eq28(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
|
|
15644
15692
|
this.schedule.delete(row.id);
|
|
15645
15693
|
return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
|
|
15646
15694
|
}
|
|
15647
15695
|
} catch (err) {
|
|
15648
|
-
|
|
15696
|
+
log25.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
|
|
15649
15697
|
}
|
|
15650
15698
|
} else {
|
|
15651
|
-
|
|
15699
|
+
log25.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
|
|
15652
15700
|
}
|
|
15653
15701
|
this.reschedule(row.id, status);
|
|
15654
15702
|
return this.enforceDeadline(row, registered);
|
|
@@ -15665,17 +15713,17 @@ var ProviderBatchPoller = class {
|
|
|
15665
15713
|
if (row.cancelRequestedAt === null) {
|
|
15666
15714
|
if (now < Date.parse(row.deadlineAt)) return false;
|
|
15667
15715
|
const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and23(
|
|
15668
|
-
|
|
15669
|
-
|
|
15716
|
+
eq28(providerBatches.id, row.id),
|
|
15717
|
+
eq28(providerBatches.status, ProviderBatchStatuses.submitted),
|
|
15670
15718
|
isNull4(providerBatches.cancelRequestedAt)
|
|
15671
15719
|
)).run().changes === 1;
|
|
15672
15720
|
if (!claimed) return false;
|
|
15673
|
-
|
|
15721
|
+
log25.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
|
|
15674
15722
|
if (registered?.adapter.batch && row.providerBatchId) {
|
|
15675
15723
|
try {
|
|
15676
15724
|
await registered.adapter.batch.cancel(row.providerBatchId, registered.config);
|
|
15677
15725
|
} catch (err) {
|
|
15678
|
-
|
|
15726
|
+
log25.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
|
|
15679
15727
|
}
|
|
15680
15728
|
}
|
|
15681
15729
|
return false;
|
|
@@ -15685,9 +15733,9 @@ var ProviderBatchPoller = class {
|
|
|
15685
15733
|
status: ProviderBatchStatuses.cancelled,
|
|
15686
15734
|
error: `The provider batch did not end within an hour of being cancelled at its deadline; its ${row.requestCount} answer(s) were not recorded.`,
|
|
15687
15735
|
updatedAt: at
|
|
15688
|
-
}).where(and23(
|
|
15736
|
+
}).where(and23(eq28(providerBatches.id, row.id), eq28(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
|
|
15689
15737
|
this.schedule.delete(row.id);
|
|
15690
|
-
if (gaveUp)
|
|
15738
|
+
if (gaveUp) log25.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
|
|
15691
15739
|
return gaveUp;
|
|
15692
15740
|
}
|
|
15693
15741
|
async ingest(row) {
|
|
@@ -15696,7 +15744,7 @@ var ProviderBatchPoller = class {
|
|
|
15696
15744
|
return result.kind !== "skipped";
|
|
15697
15745
|
} catch (err) {
|
|
15698
15746
|
const error = describeError(err);
|
|
15699
|
-
|
|
15747
|
+
log25.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
|
|
15700
15748
|
const now = this.now();
|
|
15701
15749
|
const unreadable = row.resultsExpireAt !== null && now >= Date.parse(row.resultsExpireAt);
|
|
15702
15750
|
if (unreadable || now >= Date.parse(row.deadlineAt) + PROVIDER_BATCH_CANCEL_GRACE_MS) {
|
|
@@ -15726,9 +15774,9 @@ var ProviderBatchPoller = class {
|
|
|
15726
15774
|
finalizableRuns() {
|
|
15727
15775
|
const holding = [ProviderBatchStatuses.submitting, ...OUTSTANDING_PROVIDER_BATCH_STATUSES];
|
|
15728
15776
|
return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and23(
|
|
15729
|
-
|
|
15777
|
+
eq28(runs.status, RunStatuses.running),
|
|
15730
15778
|
isNotNull3(runs.pendingProviderErrors),
|
|
15731
|
-
notExists2(this.deps.db.select({ one: sql12`1` }).from(providerBatches).where(and23(
|
|
15779
|
+
notExists2(this.deps.db.select({ one: sql12`1` }).from(providerBatches).where(and23(eq28(providerBatches.runId, runs.id), inArray12(providerBatches.status, holding))))
|
|
15732
15780
|
)).all();
|
|
15733
15781
|
}
|
|
15734
15782
|
};
|
|
@@ -15738,7 +15786,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
|
|
|
15738
15786
|
const timer = setInterval(() => {
|
|
15739
15787
|
if (running) return;
|
|
15740
15788
|
running = true;
|
|
15741
|
-
void poller.tick().catch((err) =>
|
|
15789
|
+
void poller.tick().catch((err) => log25.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
|
|
15742
15790
|
running = false;
|
|
15743
15791
|
});
|
|
15744
15792
|
}, intervalMs);
|
|
@@ -15747,7 +15795,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
|
|
|
15747
15795
|
}
|
|
15748
15796
|
|
|
15749
15797
|
// src/data-refresh.ts
|
|
15750
|
-
var
|
|
15798
|
+
var log26 = createLogger("DataRefresh");
|
|
15751
15799
|
function gaRefreshDays(now = /* @__PURE__ */ new Date()) {
|
|
15752
15800
|
const [reportMonth] = reportMonthsForDoctor(void 0, now);
|
|
15753
15801
|
const reach = inclusiveDayCount(`${reportMonth}-01`, now.toISOString().slice(0, 10)) ?? 0;
|
|
@@ -15789,15 +15837,15 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
|
|
|
15789
15837
|
if (result.status === "rejected") {
|
|
15790
15838
|
const reason = result.reason;
|
|
15791
15839
|
const message = describeError(reason);
|
|
15792
|
-
|
|
15840
|
+
log26.warn("integration.refresh-failed", { projectName, integration, error: message });
|
|
15793
15841
|
return;
|
|
15794
15842
|
}
|
|
15795
15843
|
switch (completion) {
|
|
15796
15844
|
case "synchronous":
|
|
15797
|
-
|
|
15845
|
+
log26.info("integration.refreshed", { projectName, integration });
|
|
15798
15846
|
return;
|
|
15799
15847
|
case "queued":
|
|
15800
|
-
|
|
15848
|
+
log26.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
|
|
15801
15849
|
return;
|
|
15802
15850
|
default: {
|
|
15803
15851
|
const _exhaustive = completion;
|
|
@@ -15808,12 +15856,12 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
|
|
|
15808
15856
|
}
|
|
15809
15857
|
|
|
15810
15858
|
// src/notifier.ts
|
|
15811
|
-
import { eq as
|
|
15859
|
+
import { eq as eq30, desc as desc10, and as and25, inArray as inArray13, or as or2, isNull as isNull5 } from "drizzle-orm";
|
|
15812
15860
|
import crypto25 from "crypto";
|
|
15813
15861
|
|
|
15814
15862
|
// src/site-health-alerts.ts
|
|
15815
15863
|
import crypto24 from "crypto";
|
|
15816
|
-
import { and as and24, asc as asc6, desc as desc9, eq as
|
|
15864
|
+
import { and as and24, asc as asc6, desc as desc9, eq as eq29, gt as gt3 } from "drizzle-orm";
|
|
15817
15865
|
var ISSUE_TITLES = {
|
|
15818
15866
|
"missing-h1": "Missing H1",
|
|
15819
15867
|
"multiple-h1": "Multiple H1 tags",
|
|
@@ -15826,12 +15874,12 @@ function siteHealthProblemKey(code, url) {
|
|
|
15826
15874
|
return `${code}|${crypto24.createHash("sha256").update(url).digest("hex").slice(0, 16)}`;
|
|
15827
15875
|
}
|
|
15828
15876
|
function readSiteHealthScan(db, projectId, runId) {
|
|
15829
|
-
const snapshot = db.select().from(siteCrawlSnapshots).where(and24(
|
|
15877
|
+
const snapshot = db.select().from(siteCrawlSnapshots).where(and24(eq29(siteCrawlSnapshots.projectId, projectId), eq29(siteCrawlSnapshots.runId, runId))).orderBy(desc9(siteCrawlSnapshots.updatedAt)).limit(1).get();
|
|
15830
15878
|
if (!snapshot?.detailsAvailable || !snapshot.attemptId) return null;
|
|
15831
15879
|
const scope = and24(
|
|
15832
|
-
|
|
15833
|
-
|
|
15834
|
-
|
|
15880
|
+
eq29(siteCrawlPages.projectId, projectId),
|
|
15881
|
+
eq29(siteCrawlPages.runId, runId),
|
|
15882
|
+
eq29(siteCrawlPages.attemptId, snapshot.attemptId)
|
|
15835
15883
|
);
|
|
15836
15884
|
const pagesByCode = /* @__PURE__ */ new Map();
|
|
15837
15885
|
const keys = /* @__PURE__ */ new Set();
|
|
@@ -15879,7 +15927,7 @@ function settledSiteHealthKeys(scan, reported) {
|
|
|
15879
15927
|
return [...scan.complete ? scan.keys : /* @__PURE__ */ new Set([...reported, ...scan.keys])].sort(compareText);
|
|
15880
15928
|
}
|
|
15881
15929
|
function readSiteHealthNotifyState(db, projectId) {
|
|
15882
|
-
return db.select().from(siteHealthNotifyState).where(
|
|
15930
|
+
return db.select().from(siteHealthNotifyState).where(eq29(siteHealthNotifyState.projectId, projectId)).get() ?? null;
|
|
15883
15931
|
}
|
|
15884
15932
|
function writeSiteHealthNotifyState(db, input) {
|
|
15885
15933
|
const values = { reportedKeys: input.reportedKeys, runId: input.runId, updatedAt: input.updatedAt, notifiedAt: input.notifiedAt };
|
|
@@ -15887,7 +15935,7 @@ function writeSiteHealthNotifyState(db, input) {
|
|
|
15887
15935
|
}
|
|
15888
15936
|
|
|
15889
15937
|
// src/notifier.ts
|
|
15890
|
-
var
|
|
15938
|
+
var log27 = createLogger("Notifier");
|
|
15891
15939
|
var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
|
|
15892
15940
|
function trackWebhookDelivery(input) {
|
|
15893
15941
|
const sample = sampleDelivery(input.failure ? "failed" : "succeeded");
|
|
@@ -16018,26 +16066,26 @@ var Notifier = class {
|
|
|
16018
16066
|
}
|
|
16019
16067
|
/** Called after a run completes (success, partial, or failed). */
|
|
16020
16068
|
async onRunCompleted(runId, projectId, opts) {
|
|
16021
|
-
|
|
16022
|
-
const notifs = this.db.select().from(notifications).where(
|
|
16069
|
+
log27.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
|
|
16070
|
+
const notifs = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled);
|
|
16023
16071
|
if (notifs.length === 0) {
|
|
16024
|
-
|
|
16072
|
+
log27.info("notifications.none-enabled", { projectId });
|
|
16025
16073
|
return;
|
|
16026
16074
|
}
|
|
16027
|
-
|
|
16028
|
-
const run = this.db.select().from(runs).where(
|
|
16075
|
+
log27.info("notifications.found", { projectId, count: notifs.length });
|
|
16076
|
+
const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
|
|
16029
16077
|
if (!run) {
|
|
16030
|
-
|
|
16078
|
+
log27.error("run.not-found", { runId, msg: "skipping notification dispatch" });
|
|
16031
16079
|
return;
|
|
16032
16080
|
}
|
|
16033
|
-
const project = this.db.select().from(projects).where(
|
|
16081
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
16034
16082
|
if (!project) {
|
|
16035
|
-
|
|
16083
|
+
log27.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
|
|
16036
16084
|
return;
|
|
16037
16085
|
}
|
|
16038
16086
|
const transitions = this.computeTransitions(runId, project);
|
|
16039
16087
|
const events = [];
|
|
16040
|
-
|
|
16088
|
+
log27.info("run.status", { runId: run.id, status: run.status, projectId });
|
|
16041
16089
|
if ((run.status === "completed" || run.status === "partial") && opts?.origin !== "fill") {
|
|
16042
16090
|
events.push("run.completed");
|
|
16043
16091
|
}
|
|
@@ -16057,7 +16105,7 @@ var Notifier = class {
|
|
|
16057
16105
|
if (!config.url) continue;
|
|
16058
16106
|
const subscribedEvents = config.events;
|
|
16059
16107
|
const matchingEvents = events.filter((e) => subscribedEvents.includes(e));
|
|
16060
|
-
|
|
16108
|
+
log27.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
|
|
16061
16109
|
if (matchingEvents.length === 0) continue;
|
|
16062
16110
|
for (const event of matchingEvents) {
|
|
16063
16111
|
const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : event === "mention.lost" ? lostMentions : event === "mention.gained" ? gainedMentions : transitions.citation;
|
|
@@ -16113,9 +16161,9 @@ var Notifier = class {
|
|
|
16113
16161
|
* than inferred from the absence of a webhook.
|
|
16114
16162
|
*/
|
|
16115
16163
|
async onHealthChecked(projectId, report) {
|
|
16116
|
-
const project = this.db.select().from(projects).where(
|
|
16164
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
16117
16165
|
if (!project) {
|
|
16118
|
-
|
|
16166
|
+
log27.error("project.not-found", { projectId, msg: "skipping health notification" });
|
|
16119
16167
|
return null;
|
|
16120
16168
|
}
|
|
16121
16169
|
const rank = healthRank;
|
|
@@ -16146,7 +16194,7 @@ var Notifier = class {
|
|
|
16146
16194
|
const status = noSignal ? "warn" : worst ? worst.status : "ok";
|
|
16147
16195
|
const code = noSignal ? HEALTH_NO_SIGNAL_CODE : worst?.code ?? "health.ok";
|
|
16148
16196
|
const summary = noSignal ? `No health check produced a result (${healthChecks.length} skipped) \u2014 health is unknown, not confirmed.` : worst?.summary ?? `All ${graded.length} health check(s) passing.`;
|
|
16149
|
-
const previous = this.db.select().from(doctorHealthState).where(
|
|
16197
|
+
const previous = this.db.select().from(doctorHealthState).where(eq30(doctorHealthState.projectId, projectId)).get();
|
|
16150
16198
|
const previousStatus = previous?.status ?? null;
|
|
16151
16199
|
const failingSignature = failing.map((c) => `${c.status}:${c.code}`).join(",");
|
|
16152
16200
|
const failingNow = failing.map((c) => ({ id: c.id, code: c.code, rank: rank(c.status) }));
|
|
@@ -16216,7 +16264,7 @@ var Notifier = class {
|
|
|
16216
16264
|
const urgentById = new Map(urgentItems.map((item) => [item.id, item]));
|
|
16217
16265
|
const generalEvent = event;
|
|
16218
16266
|
const urgentRecord = previous?.urgentNotified ?? null;
|
|
16219
|
-
const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(
|
|
16267
|
+
const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
|
|
16220
16268
|
const listedEvents = (notif) => notif.config.events;
|
|
16221
16269
|
const hasUrl = (notif) => Boolean(notif.config.url);
|
|
16222
16270
|
const urgentSubscribers = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
|
|
@@ -16264,7 +16312,7 @@ var Notifier = class {
|
|
|
16264
16312
|
if (previous === void 0) {
|
|
16265
16313
|
this.db.insert(doctorHealthState).values({ ...observation, notifiedAt: null }).run();
|
|
16266
16314
|
} else {
|
|
16267
|
-
this.db.update(doctorHealthState).set(observation).where(
|
|
16315
|
+
this.db.update(doctorHealthState).set(observation).where(eq30(doctorHealthState.projectId, projectId)).run();
|
|
16268
16316
|
}
|
|
16269
16317
|
for (const group of urgentGroups) {
|
|
16270
16318
|
const { urgentEvent, urgentTold, urgentNew, urgentCleared, urgentNotifs, urgentSettled } = group;
|
|
@@ -16308,10 +16356,10 @@ var Notifier = class {
|
|
|
16308
16356
|
}
|
|
16309
16357
|
if (accepted > 0) {
|
|
16310
16358
|
recordUrgentReceipts(urgentReceipts, group.subscribers, formatUrgentBreaches(urgentSettled) || null);
|
|
16311
|
-
this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(
|
|
16359
|
+
this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq30(doctorHealthState.projectId, projectId)).run();
|
|
16312
16360
|
}
|
|
16313
16361
|
if (urgentNotifs.length > 0) {
|
|
16314
|
-
|
|
16362
|
+
log27.info("health.urgent-notified", {
|
|
16315
16363
|
projectId,
|
|
16316
16364
|
event: urgentEvent,
|
|
16317
16365
|
codes: urgentEvent === "health.urgent" ? breachCodes(urgentNew) : breachCodes(urgentCleared),
|
|
@@ -16322,9 +16370,9 @@ var Notifier = class {
|
|
|
16322
16370
|
}
|
|
16323
16371
|
if (!event) {
|
|
16324
16372
|
if (clearedThisPass.length > 0 || easedThisPass.length > 0) {
|
|
16325
|
-
|
|
16373
|
+
log27.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
|
|
16326
16374
|
} else {
|
|
16327
|
-
|
|
16375
|
+
log27.info("health.unchanged", { projectId, status, code });
|
|
16328
16376
|
}
|
|
16329
16377
|
return null;
|
|
16330
16378
|
}
|
|
@@ -16352,9 +16400,9 @@ var Notifier = class {
|
|
|
16352
16400
|
if (await this.sendWebhook(config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) delivered += 1;
|
|
16353
16401
|
}
|
|
16354
16402
|
if (delivered > 0) {
|
|
16355
|
-
this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(
|
|
16403
|
+
this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq30(doctorHealthState.projectId, projectId)).run();
|
|
16356
16404
|
}
|
|
16357
|
-
|
|
16405
|
+
log27.info("health.notified", {
|
|
16358
16406
|
projectId,
|
|
16359
16407
|
event,
|
|
16360
16408
|
status,
|
|
@@ -16382,12 +16430,12 @@ var Notifier = class {
|
|
|
16382
16430
|
async onSiteLivenessChecked(projectId, result) {
|
|
16383
16431
|
const { check, checkedAt } = result;
|
|
16384
16432
|
if (check.status !== "ok" && check.status !== "fail") return null;
|
|
16385
|
-
const project = this.db.select().from(projects).where(
|
|
16433
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
16386
16434
|
if (!project) {
|
|
16387
|
-
|
|
16435
|
+
log27.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
|
|
16388
16436
|
return null;
|
|
16389
16437
|
}
|
|
16390
|
-
const previous = this.db.select().from(siteLivenessState).where(
|
|
16438
|
+
const previous = this.db.select().from(siteLivenessState).where(eq30(siteLivenessState.projectId, projectId)).get();
|
|
16391
16439
|
const sincePrevious = previous ? Date.parse(checkedAt) - Date.parse(previous.checkedAt) : Number.NaN;
|
|
16392
16440
|
const countsAsRepeat = Number.isFinite(sincePrevious) && sincePrevious >= SITE_LIVENESS_MIN_PASS_GAP_MS && sincePrevious <= SITE_LIVENESS_MAX_PASS_GAP_MS;
|
|
16393
16441
|
const failures = check.status === "fail" ? countsAsRepeat ? (previous?.consecutiveFailures ?? 0) + 1 : 1 : 0;
|
|
@@ -16397,7 +16445,7 @@ var Notifier = class {
|
|
|
16397
16445
|
if (check.status === "ok" && outagePaged) event = "health.recovered";
|
|
16398
16446
|
const confirmed = check.status === "fail" && failures >= SITE_LIVENESS_FAILURES_TO_PAGE;
|
|
16399
16447
|
const urgentRecord = previous?.urgentNotifiedAt ?? null;
|
|
16400
|
-
const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(
|
|
16448
|
+
const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
|
|
16401
16449
|
const listedEvents = (notif) => notif.config.events;
|
|
16402
16450
|
const hasUrl = (notif) => Boolean(notif.config.url);
|
|
16403
16451
|
const scoped = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
|
|
@@ -16430,7 +16478,7 @@ var Notifier = class {
|
|
|
16430
16478
|
if (previous === void 0) {
|
|
16431
16479
|
this.db.insert(siteLivenessState).values(observation).run();
|
|
16432
16480
|
} else {
|
|
16433
|
-
this.db.update(siteLivenessState).set(observation).where(
|
|
16481
|
+
this.db.update(siteLivenessState).set(observation).where(eq30(siteLivenessState.projectId, projectId)).run();
|
|
16434
16482
|
}
|
|
16435
16483
|
if (!event && urgentGroups.every((group) => group.urgentEvent === null)) return null;
|
|
16436
16484
|
const payloadFor = (name) => {
|
|
@@ -16466,9 +16514,9 @@ var Notifier = class {
|
|
|
16466
16514
|
}
|
|
16467
16515
|
}
|
|
16468
16516
|
if (event === "health.degraded" && delivered > 0) {
|
|
16469
|
-
this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(
|
|
16517
|
+
this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq30(siteLivenessState.projectId, projectId)).run();
|
|
16470
16518
|
}
|
|
16471
|
-
|
|
16519
|
+
log27.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
|
|
16472
16520
|
}
|
|
16473
16521
|
for (const group of urgentGroups) {
|
|
16474
16522
|
const { urgentEvent, urgentNotifs, generalIds } = group;
|
|
@@ -16480,10 +16528,10 @@ var Notifier = class {
|
|
|
16480
16528
|
}
|
|
16481
16529
|
if (accepted > 0) {
|
|
16482
16530
|
recordUrgentReceipts(urgentReceipts, group.subscribers, group.settled);
|
|
16483
|
-
this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(
|
|
16531
|
+
this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq30(siteLivenessState.projectId, projectId)).run();
|
|
16484
16532
|
}
|
|
16485
16533
|
if (urgentNotifs.length > 0 || generalIds.size > 0) {
|
|
16486
|
-
|
|
16534
|
+
log27.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
|
|
16487
16535
|
}
|
|
16488
16536
|
}
|
|
16489
16537
|
return event;
|
|
@@ -16506,7 +16554,7 @@ var Notifier = class {
|
|
|
16506
16554
|
*/
|
|
16507
16555
|
isNewInsightNews(projectId, insight) {
|
|
16508
16556
|
const key = insightNotifyKey(projectId, insight);
|
|
16509
|
-
const previous = this.db.select().from(insightNotifyState).where(
|
|
16557
|
+
const previous = this.db.select().from(insightNotifyState).where(eq30(insightNotifyState.key, key)).get();
|
|
16510
16558
|
if (!previous) return true;
|
|
16511
16559
|
if (severityRank(insight.severity) > severityRank(previous.severity)) return true;
|
|
16512
16560
|
const magnitude = insightMagnitude(insight);
|
|
@@ -16528,9 +16576,9 @@ var Notifier = class {
|
|
|
16528
16576
|
magnitude: insightMagnitude(insight),
|
|
16529
16577
|
notifiedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
16530
16578
|
};
|
|
16531
|
-
const existing = this.db.select().from(insightNotifyState).where(
|
|
16579
|
+
const existing = this.db.select().from(insightNotifyState).where(eq30(insightNotifyState.key, key)).get();
|
|
16532
16580
|
if (existing) {
|
|
16533
|
-
this.db.update(insightNotifyState).set(row).where(
|
|
16581
|
+
this.db.update(insightNotifyState).set(row).where(eq30(insightNotifyState.key, key)).run();
|
|
16534
16582
|
} else {
|
|
16535
16583
|
this.db.insert(insightNotifyState).values(row).run();
|
|
16536
16584
|
}
|
|
@@ -16544,11 +16592,11 @@ var Notifier = class {
|
|
|
16544
16592
|
if (criticalInsights.length > 0) insightEvents.push("insight.critical");
|
|
16545
16593
|
if (highInsights.length > 0) insightEvents.push("insight.high");
|
|
16546
16594
|
if (insightEvents.length === 0) return;
|
|
16547
|
-
const notifs = this.db.select().from(notifications).where(
|
|
16595
|
+
const notifs = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled);
|
|
16548
16596
|
if (notifs.length === 0) return;
|
|
16549
|
-
const run = this.db.select().from(runs).where(
|
|
16597
|
+
const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
|
|
16550
16598
|
if (!run) return;
|
|
16551
|
-
const project = this.db.select().from(projects).where(
|
|
16599
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
16552
16600
|
if (!project) return;
|
|
16553
16601
|
for (const notif of notifs) {
|
|
16554
16602
|
const config = notif.config;
|
|
@@ -16629,9 +16677,9 @@ var Notifier = class {
|
|
|
16629
16677
|
return delivered;
|
|
16630
16678
|
}
|
|
16631
16679
|
async dispatchQueuedReviewAlerts(projectId) {
|
|
16632
|
-
const pendingReviews = this.db.select().from(gbpReviews).where(and25(
|
|
16633
|
-
const pendingRatings = this.db.select().from(gbpReviewRatings).where(and25(
|
|
16634
|
-
const project = this.db.select().from(projects).where(
|
|
16680
|
+
const pendingReviews = this.db.select().from(gbpReviews).where(and25(eq30(gbpReviews.projectId, projectId), eq30(gbpReviews.alertState, "pending"))).all();
|
|
16681
|
+
const pendingRatings = this.db.select().from(gbpReviewRatings).where(and25(eq30(gbpReviewRatings.projectId, projectId), eq30(gbpReviewRatings.alertState, "pending"))).all();
|
|
16682
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
16635
16683
|
if (!project) return { reviews: 0, ratingDrops: 0, delivered: 0 };
|
|
16636
16684
|
const chatSendsLeft = /* @__PURE__ */ new Map();
|
|
16637
16685
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -16643,10 +16691,10 @@ var Notifier = class {
|
|
|
16643
16691
|
displayName: gbpLocations.displayName,
|
|
16644
16692
|
mapsUri: gbpLocations.mapsUri,
|
|
16645
16693
|
reviewsAccess: gbpLocations.reviewsAccess
|
|
16646
|
-
}).from(gbpLocations).where(
|
|
16694
|
+
}).from(gbpLocations).where(eq30(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
|
|
16647
16695
|
);
|
|
16648
16696
|
const v4HasWorked = new Set(
|
|
16649
|
-
this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and25(
|
|
16697
|
+
this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and25(eq30(gbpReviewRatings.projectId, projectId), eq30(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
|
|
16650
16698
|
);
|
|
16651
16699
|
const coveredByBusinessProfile = (locationName) => businessProfileReviewsCover(locations.get(locationName)?.reviewsAccess ?? null, v4HasWorked.has(locationName));
|
|
16652
16700
|
const locationRef = (locationName) => {
|
|
@@ -16675,7 +16723,7 @@ var Notifier = class {
|
|
|
16675
16723
|
else if (row.rating === null || row.previousRating === null) setRatingState([row.id], "none");
|
|
16676
16724
|
else ratingsToSend.push(row);
|
|
16677
16725
|
}
|
|
16678
|
-
const enabled = this.db.select().from(notifications).where(
|
|
16726
|
+
const enabled = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
|
|
16679
16727
|
const subscribedTo = (event) => enabled.filter((n) => (n.config.events ?? []).includes(event));
|
|
16680
16728
|
const projectRef = { name: project.name, canonicalDomain: project.canonicalDomain };
|
|
16681
16729
|
const dashboardUrl = `${this.serverUrl}/projects/${project.name}`;
|
|
@@ -16730,12 +16778,12 @@ var Notifier = class {
|
|
|
16730
16778
|
}
|
|
16731
16779
|
if (all) {
|
|
16732
16780
|
this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and25(
|
|
16733
|
-
|
|
16734
|
-
|
|
16735
|
-
|
|
16736
|
-
review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) :
|
|
16737
|
-
review.comment === null ? isNull5(gbpReviews.comment) :
|
|
16738
|
-
review.starRating === null ? isNull5(gbpReviews.starRating) :
|
|
16781
|
+
eq30(gbpReviews.id, review.id),
|
|
16782
|
+
eq30(gbpReviews.alertState, "pending"),
|
|
16783
|
+
eq30(gbpReviews.updateTime, review.updateTime),
|
|
16784
|
+
review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq30(gbpReviews.alertStateAt, review.alertStateAt),
|
|
16785
|
+
review.comment === null ? isNull5(gbpReviews.comment) : eq30(gbpReviews.comment, review.comment),
|
|
16786
|
+
review.starRating === null ? isNull5(gbpReviews.starRating) : eq30(gbpReviews.starRating, review.starRating)
|
|
16739
16787
|
)).run();
|
|
16740
16788
|
}
|
|
16741
16789
|
}
|
|
@@ -16767,7 +16815,7 @@ var Notifier = class {
|
|
|
16767
16815
|
delivered += accepted;
|
|
16768
16816
|
}
|
|
16769
16817
|
}
|
|
16770
|
-
|
|
16818
|
+
log27.info("reviews.dispatched", {
|
|
16771
16819
|
projectId,
|
|
16772
16820
|
reviews: reviewsToSend.length,
|
|
16773
16821
|
ratingDrops: ratingsToSend.length,
|
|
@@ -16778,15 +16826,15 @@ var Notifier = class {
|
|
|
16778
16826
|
computeTransitions(runId, project) {
|
|
16779
16827
|
const none = { citation: [], mention: [] };
|
|
16780
16828
|
const projectId = project.id;
|
|
16781
|
-
const thisRun = this.db.select().from(runs).where(
|
|
16829
|
+
const thisRun = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
|
|
16782
16830
|
if (!thisRun) return none;
|
|
16783
16831
|
if (isScopedRun(thisRun)) {
|
|
16784
|
-
|
|
16832
|
+
log27.info("transitions.skipped-spot-check", { runId });
|
|
16785
16833
|
return none;
|
|
16786
16834
|
}
|
|
16787
16835
|
const completeness = measurementRunCompleteness(this.db, runId);
|
|
16788
16836
|
if (completeness.planned && !completeness.complete) {
|
|
16789
|
-
|
|
16837
|
+
log27.info("transitions.skipped-incomplete", {
|
|
16790
16838
|
runId,
|
|
16791
16839
|
executed: completeness.executed,
|
|
16792
16840
|
expected: completeness.expected
|
|
@@ -16794,9 +16842,9 @@ var Notifier = class {
|
|
|
16794
16842
|
return none;
|
|
16795
16843
|
}
|
|
16796
16844
|
const groupSiblings = this.db.select().from(runs).where(and25(
|
|
16797
|
-
|
|
16798
|
-
|
|
16799
|
-
|
|
16845
|
+
eq30(runs.projectId, projectId),
|
|
16846
|
+
eq30(runs.kind, thisRun.kind),
|
|
16847
|
+
eq30(runs.createdAt, thisRun.createdAt),
|
|
16800
16848
|
notProbeRun()
|
|
16801
16849
|
)).all();
|
|
16802
16850
|
const stillPending = groupSiblings.some((r) => r.status === "queued" || r.status === "running");
|
|
@@ -16821,9 +16869,9 @@ var Notifier = class {
|
|
|
16821
16869
|
const RECENT_FETCH_LIMIT = Math.max(8, locationCount * 4);
|
|
16822
16870
|
const recentRuns = this.db.select().from(runs).where(
|
|
16823
16871
|
and25(
|
|
16824
|
-
|
|
16825
|
-
|
|
16826
|
-
or2(
|
|
16872
|
+
eq30(runs.projectId, projectId),
|
|
16873
|
+
eq30(runs.kind, thisRun.kind),
|
|
16874
|
+
or2(eq30(runs.status, "completed"), eq30(runs.status, "partial")),
|
|
16827
16875
|
notProbeRun(),
|
|
16828
16876
|
// The previous sweep, never a spot check between the two: diffed
|
|
16829
16877
|
// against a 2-query check, every other query's change is lost.
|
|
@@ -16848,7 +16896,7 @@ var Notifier = class {
|
|
|
16848
16896
|
answerText: querySnapshots.answerText,
|
|
16849
16897
|
answerMentioned: querySnapshots.answerMentioned,
|
|
16850
16898
|
mentionIdentity: querySnapshots.mentionIdentity
|
|
16851
|
-
}).from(querySnapshots).leftJoin(queries,
|
|
16899
|
+
}).from(querySnapshots).leftJoin(queries, eq30(querySnapshots.queryId, queries.id)).where(inArray13(querySnapshots.runId, currentRunIds)).all();
|
|
16852
16900
|
const previousSnapshots = this.db.select({
|
|
16853
16901
|
queryId: querySnapshots.queryId,
|
|
16854
16902
|
provider: querySnapshots.provider,
|
|
@@ -16915,12 +16963,12 @@ var Notifier = class {
|
|
|
16915
16963
|
try {
|
|
16916
16964
|
read = readAdvancedSignalTransitions(this.db, projectId, runId);
|
|
16917
16965
|
} catch (error) {
|
|
16918
|
-
|
|
16966
|
+
log27.error("transitions.advanced-unreadable", { runId, error: describeError(error) });
|
|
16919
16967
|
return { citation: [], mention: [] };
|
|
16920
16968
|
}
|
|
16921
16969
|
if (read === null) return null;
|
|
16922
16970
|
if (read.state === "unavailable") {
|
|
16923
|
-
|
|
16971
|
+
log27.info("transitions.advanced-not-comparable", { runId, reason: read.reason });
|
|
16924
16972
|
return { citation: [], mention: [] };
|
|
16925
16973
|
}
|
|
16926
16974
|
const wire = (t) => ({
|
|
@@ -16957,12 +17005,12 @@ var Notifier = class {
|
|
|
16957
17005
|
recordUnrecognizedAgentDecisions(this.db, projectId, baseline, UnrecognizedAgentNotifyStates.baseline, now);
|
|
16958
17006
|
if (due.length === 0) continue;
|
|
16959
17007
|
const names = due.map((agent) => agent.name);
|
|
16960
|
-
const subscribed = this.db.select().from(notifications).where(
|
|
17008
|
+
const subscribed = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("traffic.agent.discovered"));
|
|
16961
17009
|
if (subscribed.length === 0) {
|
|
16962
17010
|
recordUnrecognizedAgentDecisions(this.db, projectId, names, UnrecognizedAgentNotifyStates.skipped, now);
|
|
16963
17011
|
continue;
|
|
16964
17012
|
}
|
|
16965
|
-
const project = this.db.select().from(projects).where(
|
|
17013
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
16966
17014
|
if (!project) continue;
|
|
16967
17015
|
const payload = {
|
|
16968
17016
|
source: "canonry",
|
|
@@ -17013,12 +17061,12 @@ var Notifier = class {
|
|
|
17013
17061
|
recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.baseline, now);
|
|
17014
17062
|
continue;
|
|
17015
17063
|
}
|
|
17016
|
-
const subscribed = this.db.select().from(notifications).where(
|
|
17064
|
+
const subscribed = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("sentiment.unfavorable"));
|
|
17017
17065
|
if (subscribed.length === 0) {
|
|
17018
17066
|
recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.skipped, now);
|
|
17019
17067
|
continue;
|
|
17020
17068
|
}
|
|
17021
|
-
const project = this.db.select().from(projects).where(
|
|
17069
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
17022
17070
|
if (!project) continue;
|
|
17023
17071
|
for (const runId of undecided) {
|
|
17024
17072
|
let answers = this.undeliveredSentimentAlerts.get(runId) ?? null;
|
|
@@ -17026,7 +17074,7 @@ var Notifier = class {
|
|
|
17026
17074
|
try {
|
|
17027
17075
|
answers = service.newlyUnfavorable(projectId, runId);
|
|
17028
17076
|
} catch (error) {
|
|
17029
|
-
|
|
17077
|
+
log27.error("sentiment-alerts.unreadable", { projectId, runId, error: describeError(error) });
|
|
17030
17078
|
continue;
|
|
17031
17079
|
}
|
|
17032
17080
|
}
|
|
@@ -17035,7 +17083,7 @@ var Notifier = class {
|
|
|
17035
17083
|
recordSentimentAlertRuns(this.db, projectId, [runId], SentimentAlertStates.quiet, now);
|
|
17036
17084
|
continue;
|
|
17037
17085
|
}
|
|
17038
|
-
const run = this.db.select().from(runs).where(
|
|
17086
|
+
const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
|
|
17039
17087
|
if (!run) continue;
|
|
17040
17088
|
const payload = {
|
|
17041
17089
|
source: "canonry",
|
|
@@ -17079,12 +17127,12 @@ var Notifier = class {
|
|
|
17079
17127
|
* observable in tests.
|
|
17080
17128
|
*/
|
|
17081
17129
|
async onSiteAuditCompleted(runId, projectId) {
|
|
17082
|
-
const run = this.db.select().from(runs).where(
|
|
17130
|
+
const run = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
|
|
17083
17131
|
if (!run || run.kind !== RunKinds["site-audit"]) return null;
|
|
17084
17132
|
if (run.status !== RunStatuses.completed && run.status !== RunStatuses.partial) return null;
|
|
17085
|
-
const subscribed = this.db.select().from(notifications).where(
|
|
17133
|
+
const subscribed = this.db.select().from(notifications).where(eq30(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("site-health.issue.new"));
|
|
17086
17134
|
if (subscribed.length === 0) return null;
|
|
17087
|
-
const project = this.db.select().from(projects).where(
|
|
17135
|
+
const project = this.db.select().from(projects).where(eq30(projects.id, projectId)).get();
|
|
17088
17136
|
if (!project) return null;
|
|
17089
17137
|
const scan = readSiteHealthScan(this.db, projectId, runId);
|
|
17090
17138
|
if (!scan) return null;
|
|
@@ -17118,7 +17166,7 @@ var Notifier = class {
|
|
|
17118
17166
|
if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
|
|
17119
17167
|
}
|
|
17120
17168
|
if (!accepted) {
|
|
17121
|
-
|
|
17169
|
+
log27.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
|
|
17122
17170
|
return null;
|
|
17123
17171
|
}
|
|
17124
17172
|
writeSiteHealthNotifyState(this.db, {
|
|
@@ -17138,7 +17186,7 @@ var Notifier = class {
|
|
|
17138
17186
|
const targetLabel = redactNotificationUrl(url).urlDisplay;
|
|
17139
17187
|
const targetCheck = await resolveWebhookTarget(url, { allowLoopback: this.allowLoopbackWebhooks });
|
|
17140
17188
|
if (!targetCheck.ok) {
|
|
17141
|
-
|
|
17189
|
+
log27.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
|
|
17142
17190
|
this.logDelivery(projectId, notificationId, payload.event, "failed", `SSRF: ${targetCheck.message}`);
|
|
17143
17191
|
const reasonCode = webhookTargetRefusalReason(targetCheck);
|
|
17144
17192
|
trackWebhookDelivery({
|
|
@@ -17151,7 +17199,7 @@ var Notifier = class {
|
|
|
17151
17199
|
});
|
|
17152
17200
|
return false;
|
|
17153
17201
|
}
|
|
17154
|
-
|
|
17202
|
+
log27.info("webhook.send", { event: payload.event, url: targetLabel });
|
|
17155
17203
|
const maxRetries = 3;
|
|
17156
17204
|
const delays = [1e3, 4e3, 16e3];
|
|
17157
17205
|
let lastStatusClass = "network";
|
|
@@ -17160,13 +17208,13 @@ var Notifier = class {
|
|
|
17160
17208
|
try {
|
|
17161
17209
|
const response = await deliverWebhook(targetCheck.target, body, signingSecret, { userAgent: webhookUserAgent(PACKAGE_VERSION) });
|
|
17162
17210
|
if (response.status >= 200 && response.status < 300) {
|
|
17163
|
-
|
|
17211
|
+
log27.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
|
|
17164
17212
|
this.logDelivery(projectId, notificationId, payload.event, "sent", null);
|
|
17165
17213
|
trackWebhookDelivery({ url, event: payload.event, attempts: attempt + 1, durationBucket: elapsed(), statusClass: "2xx" });
|
|
17166
17214
|
return true;
|
|
17167
17215
|
}
|
|
17168
17216
|
const errorDetail = response.error ?? `HTTP ${response.status}`;
|
|
17169
|
-
|
|
17217
|
+
log27.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
|
|
17170
17218
|
lastStatusClass = response.status === 0 && response.timedOut ? "timeout" : statusClassOf(response.status);
|
|
17171
17219
|
lastFailure = { reasonCode: webhookResponseReason(response) ?? "UNKNOWN" };
|
|
17172
17220
|
if (attempt === maxRetries - 1) {
|
|
@@ -17178,7 +17226,7 @@ var Notifier = class {
|
|
|
17178
17226
|
lastFailure = outcomeFailure(err);
|
|
17179
17227
|
if (attempt === maxRetries - 1) {
|
|
17180
17228
|
this.logDelivery(projectId, notificationId, payload.event, "failed", errorDetail);
|
|
17181
|
-
|
|
17229
|
+
log27.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
|
|
17182
17230
|
}
|
|
17183
17231
|
}
|
|
17184
17232
|
if (attempt < maxRetries - 1) {
|
|
@@ -17210,8 +17258,8 @@ var Notifier = class {
|
|
|
17210
17258
|
};
|
|
17211
17259
|
|
|
17212
17260
|
// src/run-coordinator.ts
|
|
17213
|
-
import { eq as
|
|
17214
|
-
var
|
|
17261
|
+
import { eq as eq31 } from "drizzle-orm";
|
|
17262
|
+
var log28 = createLogger("RunCoordinator");
|
|
17215
17263
|
function reportInsightsGenerated(runTrigger, outcome) {
|
|
17216
17264
|
trackFeatureCompleted({
|
|
17217
17265
|
feature: "insights",
|
|
@@ -17244,31 +17292,31 @@ var RunCoordinator = class {
|
|
|
17244
17292
|
*/
|
|
17245
17293
|
onAnswersRecorded;
|
|
17246
17294
|
async onRunCompleted(runId, projectId, opts) {
|
|
17247
|
-
const runRow = this.db.select().from(runs).where(
|
|
17295
|
+
const runRow = this.db.select().from(runs).where(eq31(runs.id, runId)).get();
|
|
17248
17296
|
const kind = runRow?.kind ?? RunKinds["answer-visibility"];
|
|
17249
17297
|
if (runRow?.trigger === RunTriggers.probe) {
|
|
17250
|
-
|
|
17298
|
+
log28.info("probe.skip-side-effects", { runId, projectId, kind });
|
|
17251
17299
|
return;
|
|
17252
17300
|
}
|
|
17253
17301
|
if (kind === RunKinds["answer-visibility"] && (runRow?.status === RunStatuses.completed || runRow?.status === RunStatuses.partial) && this.onAnswersRecorded) {
|
|
17254
17302
|
try {
|
|
17255
17303
|
await this.onAnswersRecorded(runId, projectId);
|
|
17256
17304
|
} catch (err) {
|
|
17257
|
-
|
|
17305
|
+
log28.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
|
|
17258
17306
|
}
|
|
17259
17307
|
}
|
|
17260
17308
|
if (kind === RunKinds["answer-visibility"] && runRow && isScopedRun(runRow)) {
|
|
17261
|
-
|
|
17309
|
+
log28.info("spot-check.skip-derived", { runId, projectId });
|
|
17262
17310
|
try {
|
|
17263
17311
|
await this.notifier.onRunCompleted(runId, projectId);
|
|
17264
17312
|
} catch (err) {
|
|
17265
|
-
|
|
17313
|
+
log28.error("notifier.failed", { runId, error: describeError(err) });
|
|
17266
17314
|
}
|
|
17267
17315
|
return;
|
|
17268
17316
|
}
|
|
17269
17317
|
const completeness = measurementRunCompleteness(this.db, runId);
|
|
17270
17318
|
if (completeness.planned && !completeness.complete) {
|
|
17271
|
-
|
|
17319
|
+
log28.info("measurement.incomplete-skip-derived", {
|
|
17272
17320
|
runId,
|
|
17273
17321
|
projectId,
|
|
17274
17322
|
executed: completeness.executed,
|
|
@@ -17277,7 +17325,7 @@ var RunCoordinator = class {
|
|
|
17277
17325
|
try {
|
|
17278
17326
|
await this.notifier.onRunCompleted(runId, projectId);
|
|
17279
17327
|
} catch (err) {
|
|
17280
|
-
|
|
17328
|
+
log28.error("notifier.failed", { runId, error: describeError(err) });
|
|
17281
17329
|
}
|
|
17282
17330
|
return;
|
|
17283
17331
|
}
|
|
@@ -17285,7 +17333,7 @@ var RunCoordinator = class {
|
|
|
17285
17333
|
try {
|
|
17286
17334
|
await this.onSentimentCompleted(runId, projectId);
|
|
17287
17335
|
} catch {
|
|
17288
|
-
|
|
17336
|
+
log28.error("sentiment.wakeup-failed", { runId, projectId });
|
|
17289
17337
|
}
|
|
17290
17338
|
}
|
|
17291
17339
|
let insightCount = 0;
|
|
@@ -17305,12 +17353,12 @@ var RunCoordinator = class {
|
|
|
17305
17353
|
try {
|
|
17306
17354
|
await this.onInsightsGenerated(runId, projectId, result);
|
|
17307
17355
|
} catch (err) {
|
|
17308
|
-
|
|
17356
|
+
log28.error("insight-webhook.failed", { runId, error: describeError(err) });
|
|
17309
17357
|
}
|
|
17310
17358
|
}
|
|
17311
17359
|
}
|
|
17312
17360
|
} catch (err) {
|
|
17313
|
-
|
|
17361
|
+
log28.error("intelligence.failed", { runId, error: describeError(err) });
|
|
17314
17362
|
insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
|
|
17315
17363
|
}
|
|
17316
17364
|
reportInsightsGenerated(runRow?.trigger, insightsOutcome);
|
|
@@ -17328,30 +17376,30 @@ var RunCoordinator = class {
|
|
|
17328
17376
|
try {
|
|
17329
17377
|
await this.onInsightsGenerated(runId, projectId, analysisResultFromInsights(gbpInsights));
|
|
17330
17378
|
} catch (err) {
|
|
17331
|
-
|
|
17379
|
+
log28.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
|
|
17332
17380
|
}
|
|
17333
17381
|
}
|
|
17334
17382
|
} catch (err) {
|
|
17335
|
-
|
|
17383
|
+
log28.error("gbp-intelligence.failed", { runId, error: describeError(err) });
|
|
17336
17384
|
insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
|
|
17337
17385
|
}
|
|
17338
17386
|
reportInsightsGenerated(runRow?.trigger, insightsOutcome);
|
|
17339
17387
|
try {
|
|
17340
17388
|
await this.notifier.dispatchReviewAlerts(projectId);
|
|
17341
17389
|
} catch (err) {
|
|
17342
|
-
|
|
17390
|
+
log28.error("review-webhook.failed", { runId, error: describeError(err) });
|
|
17343
17391
|
}
|
|
17344
17392
|
}
|
|
17345
17393
|
try {
|
|
17346
17394
|
await (opts ? this.notifier.onRunCompleted(runId, projectId, opts) : this.notifier.onRunCompleted(runId, projectId));
|
|
17347
17395
|
} catch (err) {
|
|
17348
|
-
|
|
17396
|
+
log28.error("notifier.failed", { runId, error: describeError(err) });
|
|
17349
17397
|
}
|
|
17350
17398
|
if (kind === RunKinds["site-audit"]) {
|
|
17351
17399
|
try {
|
|
17352
17400
|
await this.notifier.onSiteAuditCompleted(runId, projectId);
|
|
17353
17401
|
} catch (err) {
|
|
17354
|
-
|
|
17402
|
+
log28.error("site-health-webhook.failed", { runId, error: describeError(err) });
|
|
17355
17403
|
}
|
|
17356
17404
|
}
|
|
17357
17405
|
if (this.onAeroEvent) {
|
|
@@ -17365,7 +17413,7 @@ var RunCoordinator = class {
|
|
|
17365
17413
|
};
|
|
17366
17414
|
await this.onAeroEvent(ctx);
|
|
17367
17415
|
} catch (err) {
|
|
17368
|
-
|
|
17416
|
+
log28.error("aero.failed", { runId, error: describeError(err) });
|
|
17369
17417
|
}
|
|
17370
17418
|
}
|
|
17371
17419
|
}
|
|
@@ -17380,7 +17428,7 @@ var RunCoordinator = class {
|
|
|
17380
17428
|
* so the Aero queue is never starved of a follow-up.
|
|
17381
17429
|
*/
|
|
17382
17430
|
buildDiscoveryAeroContext(runId, projectId, status, error) {
|
|
17383
|
-
const session = this.db.select().from(discoverySessions).where(
|
|
17431
|
+
const session = this.db.select().from(discoverySessions).where(eq31(discoverySessions.runId, runId)).get();
|
|
17384
17432
|
const competitorMap = session ? session.competitorMap : [];
|
|
17385
17433
|
return {
|
|
17386
17434
|
kind: RunKinds["aeo-discover-probe"],
|
|
@@ -17424,12 +17472,12 @@ function analysisResultFromInsights(insights2) {
|
|
|
17424
17472
|
|
|
17425
17473
|
// src/agent/session-registry.ts
|
|
17426
17474
|
import crypto27 from "crypto";
|
|
17427
|
-
import { and as and28, eq as
|
|
17475
|
+
import { and as and28, eq as eq34, gt as gt4, lte as lte3 } from "drizzle-orm";
|
|
17428
17476
|
|
|
17429
17477
|
// src/agent/remote-mcp.ts
|
|
17430
17478
|
import { Type } from "@earendil-works/pi-ai";
|
|
17431
17479
|
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
17432
|
-
var
|
|
17480
|
+
var log29 = createLogger("RemoteMcp");
|
|
17433
17481
|
var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([]);
|
|
17434
17482
|
async function connectStreamableHttp(server) {
|
|
17435
17483
|
const transport = new StreamableHTTPClientTransport(new URL(server.url), {
|
|
@@ -17497,7 +17545,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17497
17545
|
try {
|
|
17498
17546
|
client = await connect(server);
|
|
17499
17547
|
} catch (err) {
|
|
17500
|
-
|
|
17548
|
+
log29.error("external-mcp.connect-failed", {
|
|
17501
17549
|
label,
|
|
17502
17550
|
error: describeError(err)
|
|
17503
17551
|
});
|
|
@@ -17507,7 +17555,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17507
17555
|
try {
|
|
17508
17556
|
listed = await client.listTools();
|
|
17509
17557
|
} catch (err) {
|
|
17510
|
-
|
|
17558
|
+
log29.error("external-mcp.list-failed", {
|
|
17511
17559
|
label,
|
|
17512
17560
|
error: describeError(err)
|
|
17513
17561
|
});
|
|
@@ -17518,7 +17566,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17518
17566
|
if (!isReadOnly(tool)) continue;
|
|
17519
17567
|
tools.push(adaptRemoteTool(client, tool));
|
|
17520
17568
|
}
|
|
17521
|
-
|
|
17569
|
+
log29.info("external-mcp.loaded", {
|
|
17522
17570
|
label,
|
|
17523
17571
|
discovered: listed.tools.length,
|
|
17524
17572
|
adopted: tools.length
|
|
@@ -17529,7 +17577,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17529
17577
|
|
|
17530
17578
|
// src/agent/memory-store.ts
|
|
17531
17579
|
import crypto26 from "crypto";
|
|
17532
|
-
import { and as and26, desc as desc11, eq as
|
|
17580
|
+
import { and as and26, desc as desc11, eq as eq32, like, sql as sql13, or as or3 } from "drizzle-orm";
|
|
17533
17581
|
var COMPACTION_KEY_PREFIX = "compaction:";
|
|
17534
17582
|
var COMPACTION_NOTES_PER_SESSION = 3;
|
|
17535
17583
|
function rowToDto(row) {
|
|
@@ -17543,7 +17591,7 @@ function rowToDto(row) {
|
|
|
17543
17591
|
};
|
|
17544
17592
|
}
|
|
17545
17593
|
function listMemoryEntries(db, projectId, opts = {}) {
|
|
17546
|
-
const query = db.select().from(agentMemory).where(
|
|
17594
|
+
const query = db.select().from(agentMemory).where(eq32(agentMemory.projectId, projectId)).orderBy(desc11(agentMemory.updatedAt));
|
|
17547
17595
|
const rows = opts.limit === void 0 ? query.all() : query.limit(opts.limit).all();
|
|
17548
17596
|
return rows.map(rowToDto);
|
|
17549
17597
|
}
|
|
@@ -17574,12 +17622,12 @@ function upsertMemoryEntry(db, args) {
|
|
|
17574
17622
|
updatedAt: now
|
|
17575
17623
|
}
|
|
17576
17624
|
}).run();
|
|
17577
|
-
const row = db.select().from(agentMemory).where(and26(
|
|
17625
|
+
const row = db.select().from(agentMemory).where(and26(eq32(agentMemory.projectId, args.projectId), eq32(agentMemory.key, args.key))).get();
|
|
17578
17626
|
if (!row) throw new Error("memory upsert produced no row");
|
|
17579
17627
|
return rowToDto(row);
|
|
17580
17628
|
}
|
|
17581
17629
|
function deleteMemoryEntry(db, projectId, key) {
|
|
17582
|
-
const result = db.delete(agentMemory).where(and26(
|
|
17630
|
+
const result = db.delete(agentMemory).where(and26(eq32(agentMemory.projectId, projectId), eq32(agentMemory.key, key))).run();
|
|
17583
17631
|
const changes = result.changes ?? 0;
|
|
17584
17632
|
return changes > 0;
|
|
17585
17633
|
}
|
|
@@ -17587,7 +17635,7 @@ function loadRecentForHydrate(db, projectId, limit, sessionId) {
|
|
|
17587
17635
|
if (sessionId === void 0) return listMemoryEntries(db, projectId, { limit });
|
|
17588
17636
|
const sessionPrefix = `compaction:${sessionId ?? ""}:`;
|
|
17589
17637
|
return db.select().from(agentMemory).where(and26(
|
|
17590
|
-
|
|
17638
|
+
eq32(agentMemory.projectId, projectId),
|
|
17591
17639
|
or3(sql13`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql13`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
|
|
17592
17640
|
)).orderBy(desc11(agentMemory.updatedAt)).limit(limit).all().map(rowToDto);
|
|
17593
17641
|
}
|
|
@@ -17614,7 +17662,7 @@ function writeCompactionNote(db, args) {
|
|
|
17614
17662
|
const sessionPrefix = `${COMPACTION_KEY_PREFIX}${args.sessionId}:`;
|
|
17615
17663
|
const existing = tx.select({ id: agentMemory.id, updatedAt: agentMemory.updatedAt }).from(agentMemory).where(
|
|
17616
17664
|
and26(
|
|
17617
|
-
|
|
17665
|
+
eq32(agentMemory.projectId, args.projectId),
|
|
17618
17666
|
like(agentMemory.key, `${sessionPrefix}%`)
|
|
17619
17667
|
)
|
|
17620
17668
|
).orderBy(desc11(agentMemory.updatedAt)).all();
|
|
@@ -17622,7 +17670,7 @@ function writeCompactionNote(db, args) {
|
|
|
17622
17670
|
if (stale.length > 0) {
|
|
17623
17671
|
tx.delete(agentMemory).where(sql13`${agentMemory.id} IN (${sql13.join(stale.map((s) => sql13`${s}`), sql13`, `)})`).run();
|
|
17624
17672
|
}
|
|
17625
|
-
const row = tx.select().from(agentMemory).where(and26(
|
|
17673
|
+
const row = tx.select().from(agentMemory).where(and26(eq32(agentMemory.projectId, args.projectId), eq32(agentMemory.key, key))).get();
|
|
17626
17674
|
if (row) inserted = rowToDto(row);
|
|
17627
17675
|
});
|
|
17628
17676
|
if (!inserted) throw new Error("compaction note write produced no row");
|
|
@@ -17630,7 +17678,7 @@ function writeCompactionNote(db, args) {
|
|
|
17630
17678
|
}
|
|
17631
17679
|
|
|
17632
17680
|
// src/agent/turn-telemetry.ts
|
|
17633
|
-
var
|
|
17681
|
+
var log30 = createLogger("AeroTurn");
|
|
17634
17682
|
var PROVIDER_ERROR_REASONS = {
|
|
17635
17683
|
PROVIDER_AUTH: "INVALID_CREDENTIALS",
|
|
17636
17684
|
PROVIDER_BILLING: "BILLING",
|
|
@@ -17686,7 +17734,7 @@ function trackAeroTurn(agent, turn) {
|
|
|
17686
17734
|
phase: turn.phase ?? (turn.error === void 0 && agent.state.errorMessage ? OutcomePhases["provider-request"] : OutcomePhases.unknown)
|
|
17687
17735
|
});
|
|
17688
17736
|
const outcome = turnOutcome(turn.error === void 0 ? status.reason : "error", turn.error, agent.state.errorMessage);
|
|
17689
|
-
|
|
17737
|
+
log30.info("completed", {
|
|
17690
17738
|
operationId,
|
|
17691
17739
|
projectId: turn.projectId,
|
|
17692
17740
|
provider: modelProvider,
|
|
@@ -17714,7 +17762,7 @@ function trackAeroTurn(agent, turn) {
|
|
|
17714
17762
|
}
|
|
17715
17763
|
|
|
17716
17764
|
// src/agent/project-shape.ts
|
|
17717
|
-
import { and as and27, count as count5, eq as
|
|
17765
|
+
import { and as and27, count as count5, eq as eq33 } from "drizzle-orm";
|
|
17718
17766
|
var ADVANCED_TOOLS = [
|
|
17719
17767
|
"canonry_measurement_portfolio_summary",
|
|
17720
17768
|
"canonry_measurement_overview",
|
|
@@ -17741,10 +17789,10 @@ var ADVANCED_ROUTES = [
|
|
|
17741
17789
|
];
|
|
17742
17790
|
function aeroProjectShape(db, projectId) {
|
|
17743
17791
|
try {
|
|
17744
|
-
const pointer = db.select().from(measurementPlans).where(
|
|
17792
|
+
const pointer = db.select().from(measurementPlans).where(eq33(measurementPlans.projectId, projectId)).get();
|
|
17745
17793
|
const version = pointer ? db.select().from(measurementPlanVersions).where(and27(
|
|
17746
|
-
|
|
17747
|
-
|
|
17794
|
+
eq33(measurementPlanVersions.projectId, projectId),
|
|
17795
|
+
eq33(measurementPlanVersions.id, pointer.activeVersionId)
|
|
17748
17796
|
)).get() : void 0;
|
|
17749
17797
|
if (version) {
|
|
17750
17798
|
const plan = JSON.parse(version.canonicalJson);
|
|
@@ -17771,7 +17819,7 @@ canonry_visibility_report describes the whole project, not one Property. canonry
|
|
|
17771
17819
|
pinned: ADVANCED_TOOLS
|
|
17772
17820
|
};
|
|
17773
17821
|
}
|
|
17774
|
-
const tracked = db.select({ total: count5() }).from(queries).where(
|
|
17822
|
+
const tracked = db.select({ total: count5() }).from(queries).where(eq33(queries.projectId, projectId)).get()?.total ?? 0;
|
|
17775
17823
|
return {
|
|
17776
17824
|
prompt: `
|
|
17777
17825
|
|
|
@@ -17911,7 +17959,7 @@ async function compactMessages(args) {
|
|
|
17911
17959
|
}
|
|
17912
17960
|
|
|
17913
17961
|
// src/agent/session-registry.ts
|
|
17914
|
-
var
|
|
17962
|
+
var log31 = createLogger("SessionRegistry");
|
|
17915
17963
|
var MAX_HYDRATE_NOTES = 20;
|
|
17916
17964
|
var PROVIDER_ACCOUNT_COOLDOWN_MS = 24 * 60 * 60 * 1e3;
|
|
17917
17965
|
var MAX_HYDRATE_BYTES = 32 * 1024;
|
|
@@ -17973,7 +18021,7 @@ var SessionRegistry = class {
|
|
|
17973
18021
|
if (!this.externalToolsPromise) {
|
|
17974
18022
|
this.externalToolsPromise = loadExternalMcpTools(this.opts.config.externalMcpServers).catch(
|
|
17975
18023
|
(err) => {
|
|
17976
|
-
|
|
18024
|
+
log31.error("external-mcp.load-failed", {
|
|
17977
18025
|
error: describeError(err)
|
|
17978
18026
|
});
|
|
17979
18027
|
return [];
|
|
@@ -18049,7 +18097,7 @@ var SessionRegistry = class {
|
|
|
18049
18097
|
modelProvider: effectiveProvider,
|
|
18050
18098
|
modelId: effectiveModelId,
|
|
18051
18099
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
18052
|
-
}).where(
|
|
18100
|
+
}).where(eq34(agentSessions.projectId, projectId)).run();
|
|
18053
18101
|
}
|
|
18054
18102
|
const agent2 = createAeroSession({
|
|
18055
18103
|
projectName,
|
|
@@ -18268,13 +18316,13 @@ ${lines.join("\n")}
|
|
|
18268
18316
|
agent.state.messages = result.messages;
|
|
18269
18317
|
setAeroSystemPrompt(agent, this.buildHydratedSystemPrompt(projectId, row.systemPrompt));
|
|
18270
18318
|
this.save(projectName);
|
|
18271
|
-
|
|
18319
|
+
log31.info("compaction.completed", {
|
|
18272
18320
|
projectName,
|
|
18273
18321
|
removedCount: result.removedCount,
|
|
18274
18322
|
summaryBytes: Buffer.byteLength(result.summary, "utf8")
|
|
18275
18323
|
});
|
|
18276
18324
|
} catch (err) {
|
|
18277
|
-
|
|
18325
|
+
log31.error("compaction.failed", {
|
|
18278
18326
|
projectName,
|
|
18279
18327
|
error: describeError(err)
|
|
18280
18328
|
});
|
|
@@ -18368,7 +18416,7 @@ ${lines.join("\n")}
|
|
|
18368
18416
|
modelProvider: nextProvider,
|
|
18369
18417
|
modelId: nextModelId,
|
|
18370
18418
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
18371
|
-
}).where(
|
|
18419
|
+
}).where(eq34(agentSessions.projectId, projectId)).run();
|
|
18372
18420
|
}
|
|
18373
18421
|
/** Snapshot pending work without consuming it before an atomic conversation switch. */
|
|
18374
18422
|
prepareConversationChange(projectName) {
|
|
@@ -18456,7 +18504,7 @@ ${lines.join("\n")}
|
|
|
18456
18504
|
}
|
|
18457
18505
|
trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, projectId });
|
|
18458
18506
|
} catch (err) {
|
|
18459
|
-
|
|
18507
|
+
log31.error("drain.failed", {
|
|
18460
18508
|
projectName,
|
|
18461
18509
|
error: describeError(err)
|
|
18462
18510
|
});
|
|
@@ -18578,9 +18626,9 @@ ${lines.join("\n")}
|
|
|
18578
18626
|
persisted = true;
|
|
18579
18627
|
} catch (error) {
|
|
18580
18628
|
this.providerCooldownFallbacks.set(accountKey, cooldown);
|
|
18581
|
-
|
|
18629
|
+
log31.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
|
|
18582
18630
|
}
|
|
18583
|
-
|
|
18631
|
+
log31.warn("provider.background-paused", {
|
|
18584
18632
|
projectName,
|
|
18585
18633
|
provider: agent.state.model.provider,
|
|
18586
18634
|
reason,
|
|
@@ -18592,13 +18640,13 @@ ${lines.join("\n")}
|
|
|
18592
18640
|
try {
|
|
18593
18641
|
if (durableFailureId) {
|
|
18594
18642
|
this.opts.db.delete(agentProviderCooldowns).where(and28(
|
|
18595
|
-
|
|
18596
|
-
|
|
18643
|
+
eq34(agentProviderCooldowns.accountKey, accountKey),
|
|
18644
|
+
eq34(agentProviderCooldowns.failureId, durableFailureId)
|
|
18597
18645
|
)).run();
|
|
18598
18646
|
}
|
|
18599
18647
|
this.providerCooldownFallbacks.delete(accountKey);
|
|
18600
18648
|
} catch (error) {
|
|
18601
|
-
|
|
18649
|
+
log31.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
|
|
18602
18650
|
}
|
|
18603
18651
|
}
|
|
18604
18652
|
}
|
|
@@ -18628,12 +18676,12 @@ ${lines.join("\n")}
|
|
|
18628
18676
|
const fallback = this.providerCooldownFallbacks.get(accountKey);
|
|
18629
18677
|
try {
|
|
18630
18678
|
const durable = this.opts.db.select().from(agentProviderCooldowns).where(and28(
|
|
18631
|
-
|
|
18679
|
+
eq34(agentProviderCooldowns.accountKey, accountKey),
|
|
18632
18680
|
gt4(agentProviderCooldowns.retryAt, Date.now())
|
|
18633
18681
|
)).get();
|
|
18634
18682
|
return { fallback, durable };
|
|
18635
18683
|
} catch (error) {
|
|
18636
|
-
|
|
18684
|
+
log31.warn("provider.background-pause.read-failed", { error: describeError(error) });
|
|
18637
18685
|
return { fallback, durable: null };
|
|
18638
18686
|
}
|
|
18639
18687
|
}
|
|
@@ -18647,11 +18695,11 @@ ${lines.join("\n")}
|
|
|
18647
18695
|
return id;
|
|
18648
18696
|
}
|
|
18649
18697
|
tryResolveProjectId(projectName) {
|
|
18650
|
-
const row = this.opts.db.select({ id: projects.id }).from(projects).where(
|
|
18698
|
+
const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq34(projects.name, projectName)).get();
|
|
18651
18699
|
return row?.id;
|
|
18652
18700
|
}
|
|
18653
18701
|
loadRow(projectId) {
|
|
18654
|
-
const row = this.opts.db.select().from(agentSessions).where(
|
|
18702
|
+
const row = this.opts.db.select().from(agentSessions).where(eq34(agentSessions.projectId, projectId)).get();
|
|
18655
18703
|
return row ?? null;
|
|
18656
18704
|
}
|
|
18657
18705
|
insertRow(params) {
|
|
@@ -18671,7 +18719,7 @@ ${lines.join("\n")}
|
|
|
18671
18719
|
}
|
|
18672
18720
|
updateRow(projectId, patch) {
|
|
18673
18721
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
18674
|
-
this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(
|
|
18722
|
+
this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq34(agentSessions.projectId, projectId)).run();
|
|
18675
18723
|
}
|
|
18676
18724
|
/**
|
|
18677
18725
|
* Store a refreshed prompt snapshot without touching `updatedAt`, which the
|
|
@@ -18680,13 +18728,13 @@ ${lines.join("\n")}
|
|
|
18680
18728
|
* recently used right after an upgrade.
|
|
18681
18729
|
*/
|
|
18682
18730
|
persistPromptSnapshot(projectId, systemPrompt) {
|
|
18683
|
-
this.opts.db.update(agentSessions).set({ systemPrompt }).where(
|
|
18731
|
+
this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq34(agentSessions.projectId, projectId)).run();
|
|
18684
18732
|
}
|
|
18685
18733
|
};
|
|
18686
18734
|
|
|
18687
18735
|
// src/agent/viewer-sessions.ts
|
|
18688
18736
|
import crypto28 from "crypto";
|
|
18689
|
-
import { and as and29, eq as
|
|
18737
|
+
import { and as and29, eq as eq35, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
|
|
18690
18738
|
|
|
18691
18739
|
// src/agent/chatgpt-plan.ts
|
|
18692
18740
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
@@ -19057,12 +19105,12 @@ var ViewerAeroSessions = class {
|
|
|
19057
19105
|
*/
|
|
19058
19106
|
removeKey(id) {
|
|
19059
19107
|
try {
|
|
19060
|
-
this.opts.db.delete(apiKeys).where(
|
|
19108
|
+
this.opts.db.delete(apiKeys).where(eq35(apiKeys.id, id)).run();
|
|
19061
19109
|
} catch {
|
|
19062
19110
|
try {
|
|
19063
19111
|
this.opts.db.transaction((tx) => {
|
|
19064
|
-
tx.delete(dashboardSessions).where(
|
|
19065
|
-
tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(
|
|
19112
|
+
tx.delete(dashboardSessions).where(eq35(dashboardSessions.apiKeyId, id)).run();
|
|
19113
|
+
tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq35(apiKeys.id, id)).run();
|
|
19066
19114
|
});
|
|
19067
19115
|
} catch {
|
|
19068
19116
|
}
|
|
@@ -19092,7 +19140,7 @@ var ViewerAeroSessions = class {
|
|
|
19092
19140
|
// src/mcp-http.ts
|
|
19093
19141
|
import crypto29 from "crypto";
|
|
19094
19142
|
import { isIP } from "net";
|
|
19095
|
-
import { and as and30, eq as
|
|
19143
|
+
import { and as and30, eq as eq36, isNull as isNull6 } from "drizzle-orm";
|
|
19096
19144
|
import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node";
|
|
19097
19145
|
import { McpServer, createMcpHandler, isInitializeRequest, isLegacyRequest } from "@modelcontextprotocol/server";
|
|
19098
19146
|
var SESSION_IDLE_MS = 10 * 60 * 1e3;
|
|
@@ -19198,12 +19246,12 @@ function registerMcpHttpRoutes(scope, opts) {
|
|
|
19198
19246
|
try {
|
|
19199
19247
|
withoutLockWait(() => {
|
|
19200
19248
|
opts.db.transaction((tx) => {
|
|
19201
|
-
tx.delete(dashboardSessions).where(
|
|
19202
|
-
tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and30(
|
|
19249
|
+
tx.delete(dashboardSessions).where(eq36(dashboardSessions.apiKeyId, id)).run();
|
|
19250
|
+
tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and30(eq36(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
|
|
19203
19251
|
});
|
|
19204
19252
|
if (remove) {
|
|
19205
19253
|
try {
|
|
19206
|
-
opts.db.delete(apiKeys).where(
|
|
19254
|
+
opts.db.delete(apiKeys).where(eq36(apiKeys.id, id)).run();
|
|
19207
19255
|
} catch (error) {
|
|
19208
19256
|
scope.log.warn({ err: error, keyId: id }, "Retained revoked MCP request key after deletion failed");
|
|
19209
19257
|
}
|
|
@@ -19254,14 +19302,14 @@ function registerMcpHttpRoutes(scope, opts) {
|
|
|
19254
19302
|
withoutLockWait(() => {
|
|
19255
19303
|
const cutoff = now() - SESSION_IDLE_MS;
|
|
19256
19304
|
for (const session of legacyServers) {
|
|
19257
|
-
const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(
|
|
19305
|
+
const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq36(apiKeys.id, session.sessionKeyId)).get() : void 0;
|
|
19258
19306
|
if (session.lastSeenAt < cutoff || session.expiresAt !== void 0 && session.expiresAt <= now() || session.sessionKeyId && (!key || key.revokedAt)) {
|
|
19259
19307
|
void session.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP session"));
|
|
19260
19308
|
}
|
|
19261
19309
|
}
|
|
19262
19310
|
for (const exchange of modernExchanges) {
|
|
19263
19311
|
if (!exchange.sessionKey) continue;
|
|
19264
|
-
const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(
|
|
19312
|
+
const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq36(apiKeys.id, exchange.sessionKey.id)).get();
|
|
19265
19313
|
if (!key || key.revokedAt || exchange.sessionKey.expiresAt <= now()) {
|
|
19266
19314
|
void exchange.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP request"));
|
|
19267
19315
|
}
|
|
@@ -19547,7 +19595,7 @@ function resolveChatGptSettings(config, env = process.env) {
|
|
|
19547
19595
|
}
|
|
19548
19596
|
|
|
19549
19597
|
// src/agent/agent-routes.ts
|
|
19550
|
-
import { eq as
|
|
19598
|
+
import { eq as eq37 } from "drizzle-orm";
|
|
19551
19599
|
function viewerAeroCaller(request, opts) {
|
|
19552
19600
|
if (!opts.viewerSessions) return null;
|
|
19553
19601
|
const principal = request.principal;
|
|
@@ -19590,7 +19638,7 @@ function turnAttribution(request) {
|
|
|
19590
19638
|
};
|
|
19591
19639
|
}
|
|
19592
19640
|
function resolveProject(db, name) {
|
|
19593
|
-
const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(
|
|
19641
|
+
const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq37(projects.name, name)).get();
|
|
19594
19642
|
if (!row) throw notFound("project", name);
|
|
19595
19643
|
return row;
|
|
19596
19644
|
}
|
|
@@ -19713,7 +19761,7 @@ function registerAgentRoutes(app, opts) {
|
|
|
19713
19761
|
}
|
|
19714
19762
|
requireInstanceAdministrator(request);
|
|
19715
19763
|
const project = resolveProject(opts.db, request.params.name);
|
|
19716
|
-
const row = opts.db.select().from(agentSessions).where(
|
|
19764
|
+
const row = opts.db.select().from(agentSessions).where(eq37(agentSessions.projectId, project.id)).get();
|
|
19717
19765
|
const nextTurn = opts.sessionRegistry.nextTurnModel(project.name);
|
|
19718
19766
|
if (!row) {
|
|
19719
19767
|
return { conversationId: null, messages: [], modelProvider: null, modelId: null, nextTurn, updatedAt: null };
|
|
@@ -19755,7 +19803,7 @@ function registerAgentRoutes(app, opts) {
|
|
|
19755
19803
|
const project = resolveProject(opts.db, request.params.name);
|
|
19756
19804
|
if (opts.sessionRegistry.isBusy(project.name)) throw agentBusy(project.name);
|
|
19757
19805
|
opts.sessionRegistry.reset(project.name);
|
|
19758
|
-
opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
|
|
19806
|
+
opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq37(agentSessions.projectId, project.id)).run();
|
|
19759
19807
|
return { status: "reset" };
|
|
19760
19808
|
}
|
|
19761
19809
|
);
|
|
@@ -19779,7 +19827,7 @@ function registerAgentRoutes(app, opts) {
|
|
|
19779
19827
|
return streamViewerTurn(opts, project, viewerId, body, reply, turnAttribution(request));
|
|
19780
19828
|
}
|
|
19781
19829
|
if (body.conversationId !== void 0) {
|
|
19782
|
-
const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(
|
|
19830
|
+
const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq37(agentSessions.projectId, project.id)).get();
|
|
19783
19831
|
if ((current?.id ?? null) !== body.conversationId) throw validationError("The active conversation changed. Reload the conversation before sending.");
|
|
19784
19832
|
}
|
|
19785
19833
|
const promptText = body.prompt;
|
|
@@ -20191,7 +20239,7 @@ function stripHtml(html) {
|
|
|
20191
20239
|
}
|
|
20192
20240
|
|
|
20193
20241
|
// src/snapshot-service.ts
|
|
20194
|
-
var
|
|
20242
|
+
var log32 = createLogger("Snapshot");
|
|
20195
20243
|
var ANALYSIS_PROVIDER_PRIORITY = ["openai", "claude", "gemini", "perplexity", "muse", "local"];
|
|
20196
20244
|
var SNAPSHOT_QUERY_COUNT = 6;
|
|
20197
20245
|
var SnapshotService = class {
|
|
@@ -20293,7 +20341,7 @@ var SnapshotService = class {
|
|
|
20293
20341
|
return mapAuditReport(report);
|
|
20294
20342
|
} catch (err) {
|
|
20295
20343
|
const message = describeError(err);
|
|
20296
|
-
|
|
20344
|
+
log32.warn("audit.failed", { homepageUrl, error: message });
|
|
20297
20345
|
return {
|
|
20298
20346
|
url: homepageUrl,
|
|
20299
20347
|
finalUrl: homepageUrl,
|
|
@@ -20322,7 +20370,7 @@ var SnapshotService = class {
|
|
|
20322
20370
|
queries: parsedQueries
|
|
20323
20371
|
};
|
|
20324
20372
|
} catch (err) {
|
|
20325
|
-
|
|
20373
|
+
log32.warn("profile.generation-failed", {
|
|
20326
20374
|
domain: ctx.domain,
|
|
20327
20375
|
provider: ctx.analysisProvider.adapter.name,
|
|
20328
20376
|
error: describeError(err)
|
|
@@ -20472,7 +20520,7 @@ var SnapshotService = class {
|
|
|
20472
20520
|
recommendedActions: uniqueStrings2(parsed.recommendedActions ?? []).slice(0, 4)
|
|
20473
20521
|
};
|
|
20474
20522
|
} catch (err) {
|
|
20475
|
-
|
|
20523
|
+
log32.warn("response.analysis-failed", {
|
|
20476
20524
|
provider: ctx.analysisProvider.adapter.name,
|
|
20477
20525
|
error: describeError(err)
|
|
20478
20526
|
});
|
|
@@ -20742,7 +20790,7 @@ function clipText(value, length) {
|
|
|
20742
20790
|
}
|
|
20743
20791
|
|
|
20744
20792
|
// src/research-runner.ts
|
|
20745
|
-
import { and as and31, eq as
|
|
20793
|
+
import { and as and31, eq as eq38, inArray as inArray14, sql as sql14 } from "drizzle-orm";
|
|
20746
20794
|
var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
|
|
20747
20795
|
function finalResearchRunStatus(completed, failed, waiting) {
|
|
20748
20796
|
if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
|
|
@@ -20750,13 +20798,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
|
|
|
20750
20798
|
return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
|
|
20751
20799
|
}
|
|
20752
20800
|
async function executeResearchRun(db, registry, runId, projectId, options = {}) {
|
|
20753
|
-
const run = db.select().from(researchRuns).where(and31(
|
|
20801
|
+
const run = db.select().from(researchRuns).where(and31(eq38(researchRuns.id, runId), eq38(researchRuns.projectId, projectId))).get();
|
|
20754
20802
|
if (!run || run.status !== ResearchRunStatuses.queued) return;
|
|
20755
|
-
const project = db.select().from(projects).where(
|
|
20803
|
+
const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
|
|
20756
20804
|
if (!project) return;
|
|
20757
20805
|
const provider = registry.get(run.provider);
|
|
20758
20806
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
20759
|
-
const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and31(
|
|
20807
|
+
const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and31(eq38(researchRuns.id, runId), eq38(researchRuns.status, ResearchRunStatuses.queued))).run();
|
|
20760
20808
|
if (claim.changes !== 1) return;
|
|
20761
20809
|
const elapsed = startOutcomeTimer();
|
|
20762
20810
|
const requested = currentOutcomeOrigin();
|
|
@@ -20790,8 +20838,8 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
|
|
|
20790
20838
|
}
|
|
20791
20839
|
reserved = run.totalQueries;
|
|
20792
20840
|
reservation = { scope, period };
|
|
20793
|
-
const rows = db.select().from(researchRunQueries).where(
|
|
20794
|
-
const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(
|
|
20841
|
+
const rows = db.select().from(researchRunQueries).where(eq38(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
|
|
20842
|
+
const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq38(competitors.projectId, projectId)).orderBy(competitors.domain).all();
|
|
20795
20843
|
const competitorDomains = competitorRows.map((row) => row.domain);
|
|
20796
20844
|
const competitorAliases = new Map(competitorRows.map((row) => [row.domain, competitorIdentityAliases(row)]).filter(([, aliases]) => aliases.length > 0));
|
|
20797
20845
|
const domains = effectiveDomains(project);
|
|
@@ -20801,7 +20849,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
|
|
|
20801
20849
|
await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
|
|
20802
20850
|
try {
|
|
20803
20851
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
20804
|
-
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and31(
|
|
20852
|
+
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and31(eq38(researchRunQueries.id, row.id), eq38(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
|
|
20805
20853
|
const raw = await gate.run(async () => {
|
|
20806
20854
|
dispatched++;
|
|
20807
20855
|
return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
|
|
@@ -20832,7 +20880,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
|
|
|
20832
20880
|
rawResponse: raw.rawResponse,
|
|
20833
20881
|
answerEvidence: raw.evidence ?? null,
|
|
20834
20882
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
20835
|
-
}).where(and31(
|
|
20883
|
+
}).where(and31(eq38(researchRunQueries.id, row.id), eq38(researchRunQueries.status, ResearchQueryStatuses.running))).run();
|
|
20836
20884
|
if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
|
|
20837
20885
|
} catch (error) {
|
|
20838
20886
|
if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
|
|
@@ -20883,11 +20931,11 @@ function researchOutcomeStatus(status) {
|
|
|
20883
20931
|
}
|
|
20884
20932
|
}
|
|
20885
20933
|
function incrementResearchProgress(db, runId, column) {
|
|
20886
|
-
db.update(researchRuns).set({ [column]: sql14`${researchRuns[column]} + 1` }).where(
|
|
20934
|
+
db.update(researchRuns).set({ [column]: sql14`${researchRuns[column]} + 1` }).where(eq38(researchRuns.id, runId)).run();
|
|
20887
20935
|
}
|
|
20888
20936
|
function markResearchQueryFailed(db, runId, queryId, error) {
|
|
20889
20937
|
const message = describeError(error);
|
|
20890
|
-
const unfinished = and31(
|
|
20938
|
+
const unfinished = and31(eq38(researchRunQueries.id, queryId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses));
|
|
20891
20939
|
if (error instanceof IncompleteAnswerError && error.resumable) {
|
|
20892
20940
|
db.update(researchRunQueries).set({
|
|
20893
20941
|
status: ResearchQueryStatuses["waiting-upstream"],
|
|
@@ -20903,10 +20951,10 @@ function markResearchQueryFailed(db, runId, queryId, error) {
|
|
|
20903
20951
|
if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
|
|
20904
20952
|
}
|
|
20905
20953
|
function markUnfinishedResearchQueriesFailed(db, runId, error) {
|
|
20906
|
-
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and31(
|
|
20954
|
+
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and31(eq38(researchRunQueries.researchRunId, runId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
|
|
20907
20955
|
}
|
|
20908
20956
|
function finalizeResearchRun(db, runId, fatalError) {
|
|
20909
|
-
const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(
|
|
20957
|
+
const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq38(researchRunQueries.researchRunId, runId)).all();
|
|
20910
20958
|
const completed = rows.filter((row) => row.status === ResearchQueryStatuses.completed).length;
|
|
20911
20959
|
const failed = rows.filter((row) => row.status === ResearchQueryStatuses.failed).length;
|
|
20912
20960
|
const waiting = rows.filter((row) => row.status === ResearchQueryStatuses["waiting-upstream"]).length;
|
|
@@ -20918,12 +20966,12 @@ function finalizeResearchRun(db, runId, fatalError) {
|
|
|
20918
20966
|
error: fatalError ?? (failed === rows.length ? "Every research query failed." : null),
|
|
20919
20967
|
// A run waiting on upstream jobs has not finished.
|
|
20920
20968
|
finishedAt: waiting > 0 ? null : (/* @__PURE__ */ new Date()).toISOString()
|
|
20921
|
-
}).where(
|
|
20969
|
+
}).where(eq38(researchRuns.id, runId)).run();
|
|
20922
20970
|
return { status, total: rows.length, completed, failed };
|
|
20923
20971
|
}
|
|
20924
20972
|
|
|
20925
20973
|
// src/google-marketing-sync.ts
|
|
20926
|
-
import { and as and32, eq as
|
|
20974
|
+
import { and as and32, eq as eq39, isNull as isNull7, sql as sql15 } from "drizzle-orm";
|
|
20927
20975
|
var RUNTIME_FAILURE_REASONS = {
|
|
20928
20976
|
INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
|
|
20929
20977
|
NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
|
|
@@ -20961,9 +21009,9 @@ function assertSnapshotContext(metadata, expected) {
|
|
|
20961
21009
|
}
|
|
20962
21010
|
function requireSyncRun(db, runId, projectId, kind) {
|
|
20963
21011
|
const run = db.select().from(runs).where(and32(
|
|
20964
|
-
|
|
20965
|
-
|
|
20966
|
-
|
|
21012
|
+
eq39(runs.id, runId),
|
|
21013
|
+
eq39(runs.projectId, projectId),
|
|
21014
|
+
eq39(runs.kind, kind)
|
|
20967
21015
|
)).get();
|
|
20968
21016
|
if (!run) throw withOutcomeReason(new Error(`Run ${runId} is not a ${kind} run for this project.`), OutcomeReasonCodes.NOT_FOUND);
|
|
20969
21017
|
if (run.status !== RunStatuses.queued) {
|
|
@@ -20980,18 +21028,18 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
|
|
|
20980
21028
|
error: serializeRunError({ message: safeErrorMessage(error) }),
|
|
20981
21029
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
20982
21030
|
}).where(and32(
|
|
20983
|
-
|
|
20984
|
-
|
|
20985
|
-
|
|
20986
|
-
|
|
21031
|
+
eq39(runs.id, runId),
|
|
21032
|
+
eq39(runs.projectId, projectId),
|
|
21033
|
+
eq39(runs.kind, kind),
|
|
21034
|
+
eq39(runs.status, expectedStatus)
|
|
20987
21035
|
)).run();
|
|
20988
21036
|
}
|
|
20989
21037
|
function claimSyncRun(db, runId, projectId, kind, startedAt) {
|
|
20990
21038
|
const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and32(
|
|
20991
|
-
|
|
20992
|
-
|
|
20993
|
-
|
|
20994
|
-
|
|
21039
|
+
eq39(runs.id, runId),
|
|
21040
|
+
eq39(runs.projectId, projectId),
|
|
21041
|
+
eq39(runs.kind, kind),
|
|
21042
|
+
eq39(runs.status, RunStatuses.queued)
|
|
20995
21043
|
)).run();
|
|
20996
21044
|
return claim.changes === 1;
|
|
20997
21045
|
}
|
|
@@ -21001,9 +21049,9 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
|
|
|
21001
21049
|
let evidenceCollected = false;
|
|
21002
21050
|
try {
|
|
21003
21051
|
requireSyncRun(db, runId, projectId, RunKinds["google-ads-sync"]);
|
|
21004
|
-
const project = db.select().from(projects).where(
|
|
21052
|
+
const project = db.select().from(projects).where(eq39(projects.id, projectId)).get();
|
|
21005
21053
|
if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
|
|
21006
|
-
const connection = db.select().from(googleAdsConnections).where(
|
|
21054
|
+
const connection = db.select().from(googleAdsConnections).where(eq39(googleAdsConnections.projectId, projectId)).get();
|
|
21007
21055
|
if (!connection?.selectedCustomerId) {
|
|
21008
21056
|
throw withOutcomeReason(new Error("Google Ads needs a selected customer before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
|
|
21009
21057
|
}
|
|
@@ -21056,10 +21104,10 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
|
|
|
21056
21104
|
finishedAt,
|
|
21057
21105
|
error: null
|
|
21058
21106
|
}).where(and32(
|
|
21059
|
-
|
|
21060
|
-
|
|
21061
|
-
|
|
21062
|
-
|
|
21107
|
+
eq39(runs.id, runId),
|
|
21108
|
+
eq39(runs.projectId, projectId),
|
|
21109
|
+
eq39(runs.kind, RunKinds["google-ads-sync"]),
|
|
21110
|
+
eq39(runs.status, RunStatuses.running)
|
|
21063
21111
|
)).run();
|
|
21064
21112
|
if (terminalClaim.changes !== 1) {
|
|
21065
21113
|
throw withOutcomeReason(
|
|
@@ -21080,11 +21128,11 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
|
|
|
21080
21128
|
lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
|
|
21081
21129
|
updatedAt: finishedAt
|
|
21082
21130
|
}).where(and32(
|
|
21083
|
-
|
|
21084
|
-
|
|
21085
|
-
|
|
21086
|
-
connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) :
|
|
21087
|
-
|
|
21131
|
+
eq39(googleAdsConnections.id, connection.id),
|
|
21132
|
+
eq39(googleAdsConnections.projectId, projectId),
|
|
21133
|
+
eq39(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
|
|
21134
|
+
connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) : eq39(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
|
|
21135
|
+
eq39(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
|
|
21088
21136
|
)).run();
|
|
21089
21137
|
if (connectionClaim.changes !== 1) {
|
|
21090
21138
|
throw withOutcomeReason(
|
|
@@ -21124,9 +21172,9 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
21124
21172
|
let evidenceCollected = false;
|
|
21125
21173
|
try {
|
|
21126
21174
|
requireSyncRun(db, runId, projectId, RunKinds["gtm-sync"]);
|
|
21127
|
-
const project = db.select().from(projects).where(
|
|
21175
|
+
const project = db.select().from(projects).where(eq39(projects.id, projectId)).get();
|
|
21128
21176
|
if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
|
|
21129
|
-
const connection = db.select().from(gtmConnections).where(
|
|
21177
|
+
const connection = db.select().from(gtmConnections).where(eq39(gtmConnections.projectId, projectId)).get();
|
|
21130
21178
|
if (!connection?.selectedAccountId || !connection.selectedContainerId) {
|
|
21131
21179
|
throw withOutcomeReason(new Error("GTM needs a selected account and container before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
|
|
21132
21180
|
}
|
|
@@ -21165,10 +21213,10 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
21165
21213
|
finishedAt,
|
|
21166
21214
|
error: null
|
|
21167
21215
|
}).where(and32(
|
|
21168
|
-
|
|
21169
|
-
|
|
21170
|
-
|
|
21171
|
-
|
|
21216
|
+
eq39(runs.id, runId),
|
|
21217
|
+
eq39(runs.projectId, projectId),
|
|
21218
|
+
eq39(runs.kind, RunKinds["gtm-sync"]),
|
|
21219
|
+
eq39(runs.status, RunStatuses.running)
|
|
21172
21220
|
)).run();
|
|
21173
21221
|
if (terminalClaim.changes !== 1) {
|
|
21174
21222
|
throw withOutcomeReason(
|
|
@@ -21190,12 +21238,12 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
21190
21238
|
lastSnapshotId: snapshot.metadata.id,
|
|
21191
21239
|
updatedAt: finishedAt
|
|
21192
21240
|
}).where(and32(
|
|
21193
|
-
|
|
21194
|
-
|
|
21195
|
-
|
|
21196
|
-
|
|
21197
|
-
connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) :
|
|
21198
|
-
|
|
21241
|
+
eq39(gtmConnections.id, connection.id),
|
|
21242
|
+
eq39(gtmConnections.projectId, projectId),
|
|
21243
|
+
eq39(gtmConnections.selectedAccountId, connection.selectedAccountId),
|
|
21244
|
+
eq39(gtmConnections.selectedContainerId, connection.selectedContainerId),
|
|
21245
|
+
connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) : eq39(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
|
|
21246
|
+
eq39(gtmConnections.selectionGeneration, connection.selectionGeneration)
|
|
21199
21247
|
)).run();
|
|
21200
21248
|
if (connectionClaim.changes !== 1) {
|
|
21201
21249
|
throw withOutcomeReason(
|
|
@@ -21233,7 +21281,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
21233
21281
|
// src/server.ts
|
|
21234
21282
|
var _require = createRequire(import.meta.url);
|
|
21235
21283
|
var { version: PKG_VERSION } = _require("../package.json");
|
|
21236
|
-
var
|
|
21284
|
+
var log33 = createLogger("Server");
|
|
21237
21285
|
var runtimeStartupByServer = /* @__PURE__ */ new WeakMap();
|
|
21238
21286
|
function waitForServerRuntimeStartup(app) {
|
|
21239
21287
|
const startup = runtimeStartupByServer.get(app);
|
|
@@ -21485,7 +21533,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
|
|
|
21485
21533
|
}
|
|
21486
21534
|
if (migratedGoogle > 0) {
|
|
21487
21535
|
persistConfigPatch({ google: config.google });
|
|
21488
|
-
|
|
21536
|
+
log33.info("credentials.migrated", { type: "google", count: migratedGoogle });
|
|
21489
21537
|
}
|
|
21490
21538
|
let migratedGa4 = 0;
|
|
21491
21539
|
for (const row of rows.ga4) {
|
|
@@ -21503,7 +21551,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
|
|
|
21503
21551
|
}
|
|
21504
21552
|
if (migratedGa4 > 0) {
|
|
21505
21553
|
persistConfigPatch({ ga4: config.ga4 });
|
|
21506
|
-
|
|
21554
|
+
log33.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
|
|
21507
21555
|
}
|
|
21508
21556
|
}
|
|
21509
21557
|
function isLoopbackPeerAddress(address) {
|
|
@@ -21786,17 +21834,17 @@ async function createServer(opts) {
|
|
|
21786
21834
|
applyLegacyCredentials(legacyRows, opts.config, persistConfigPatch);
|
|
21787
21835
|
dropLegacyCredentialColumns(opts.db);
|
|
21788
21836
|
} catch (err) {
|
|
21789
|
-
|
|
21837
|
+
log33.warn("credentials.migration.failed", {
|
|
21790
21838
|
error: describeError(err)
|
|
21791
21839
|
});
|
|
21792
21840
|
}
|
|
21793
21841
|
}
|
|
21794
|
-
|
|
21842
|
+
log33.info("providers.configured", {
|
|
21795
21843
|
providers: registeredProviderNames({ providers, cdp: opts.config.cdp })
|
|
21796
21844
|
});
|
|
21797
21845
|
registry.replace(configuredProviderEntries(opts.config, API_ADAPTERS, cdpChatgptAdapter));
|
|
21798
21846
|
for (const name of providersWithUnsupportedBatch(providers, (provider) => adapterMap[provider])) {
|
|
21799
|
-
|
|
21847
|
+
log33.warn("provider.batch.unsupported", {
|
|
21800
21848
|
provider: name,
|
|
21801
21849
|
message: `providers.${name}.batch.enabled is true, but the ${name} adapter has no batch API; its sweeps run sync.`
|
|
21802
21850
|
});
|
|
@@ -21847,7 +21895,7 @@ async function createServer(opts) {
|
|
|
21847
21895
|
settings: () => resolveChatGptSettings(opts.config)
|
|
21848
21896
|
});
|
|
21849
21897
|
if (opts.config.chatgpt && (opts.config.chatgpt.signIn || opts.config.chatgpt.planUsage) && !resolveChatGptSettings(opts.config)) {
|
|
21850
|
-
|
|
21898
|
+
log33.warn("chatgpt.disabled", {
|
|
21851
21899
|
reason: "Sign in with ChatGPT needs chatgpt.clientId and an HTTPS publicUrl; it stays off until both are set."
|
|
21852
21900
|
});
|
|
21853
21901
|
}
|
|
@@ -21867,7 +21915,7 @@ async function createServer(opts) {
|
|
|
21867
21915
|
async (ctx) => {
|
|
21868
21916
|
if (!sessionRegistry) return;
|
|
21869
21917
|
if (!agentProactive) return;
|
|
21870
|
-
const project = opts.db.select({ name: projects.name }).from(projects).where(
|
|
21918
|
+
const project = opts.db.select({ name: projects.name }).from(projects).where(eq40(projects.id, ctx.projectId)).get();
|
|
21871
21919
|
if (!project) return;
|
|
21872
21920
|
let content;
|
|
21873
21921
|
if (ctx.kind === RunKinds["aeo-discover-probe"]) {
|
|
@@ -22342,7 +22390,7 @@ async function createServer(opts) {
|
|
|
22342
22390
|
void (async () => {
|
|
22343
22391
|
try {
|
|
22344
22392
|
const report = await schedulerClient.runDoctor({ project: projectName, checkIds: scheduledHealthCheckIds() });
|
|
22345
|
-
const project = opts.db.select().from(projects).where(
|
|
22393
|
+
const project = opts.db.select().from(projects).where(eq40(projects.name, projectName)).get();
|
|
22346
22394
|
if (!project) {
|
|
22347
22395
|
app.log.warn({ projectName }, "doctor schedule fired for an unknown project");
|
|
22348
22396
|
return;
|
|
@@ -22364,7 +22412,7 @@ async function createServer(opts) {
|
|
|
22364
22412
|
db: opts.db,
|
|
22365
22413
|
// Probe directly (not the 5-min cache) so each tick sees fresh results.
|
|
22366
22414
|
probe: () => probeLatestRelease(),
|
|
22367
|
-
requestSync: (
|
|
22415
|
+
requestSync: (release2) => schedulerClient.backlinksTriggerSync(release2),
|
|
22368
22416
|
scheduledReleases: scheduledBacklinkReleases,
|
|
22369
22417
|
log: app.log
|
|
22370
22418
|
});
|
|
@@ -22619,7 +22667,7 @@ async function createServer(opts) {
|
|
|
22619
22667
|
})();
|
|
22620
22668
|
if (opts.config.apiKey) {
|
|
22621
22669
|
const keyHash = hashApiKey(opts.config.apiKey);
|
|
22622
|
-
const existing = opts.db.select().from(apiKeys).where(
|
|
22670
|
+
const existing = opts.db.select().from(apiKeys).where(eq40(apiKeys.keyHash, keyHash)).get();
|
|
22623
22671
|
if (!existing) {
|
|
22624
22672
|
const prefix = opts.config.apiKey.slice(0, 12);
|
|
22625
22673
|
opts.db.insert(apiKeys).values({
|
|
@@ -22638,14 +22686,14 @@ async function createServer(opts) {
|
|
|
22638
22686
|
);
|
|
22639
22687
|
const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
|
|
22640
22688
|
opts.db.delete(dashboardSessions).where(or4(
|
|
22641
|
-
|
|
22689
|
+
eq40(dashboardSessions.apiKeyHash, ""),
|
|
22642
22690
|
and33(
|
|
22643
22691
|
isNotNull5(dashboardSessions.passwordFingerprint),
|
|
22644
22692
|
ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
|
|
22645
22693
|
)
|
|
22646
22694
|
)).run();
|
|
22647
22695
|
if (!opts.config.dashboardPasswordHash) {
|
|
22648
|
-
const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and33(
|
|
22696
|
+
const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and33(eq40(auditLog.entityType, "dashboard-password"), eq40(auditLog.action, action))).get()?.at ?? null;
|
|
22649
22697
|
const createdAt = lastPasswordEventAt("dashboard-password.created");
|
|
22650
22698
|
const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
|
|
22651
22699
|
if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
|
|
@@ -22679,23 +22727,23 @@ async function createServer(opts) {
|
|
|
22679
22727
|
currentApiKeyHash: apiKeys.keyHash,
|
|
22680
22728
|
passwordFingerprint: dashboardSessions.passwordFingerprint,
|
|
22681
22729
|
expiresAt: dashboardSessions.expiresAt
|
|
22682
|
-
}).from(dashboardSessions).innerJoin(apiKeys,
|
|
22730
|
+
}).from(dashboardSessions).innerJoin(apiKeys, eq40(apiKeys.id, dashboardSessions.apiKeyId)).where(and33(eq40(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
|
|
22683
22731
|
if (!session) return null;
|
|
22684
22732
|
const expiresAt = Date.parse(session.expiresAt);
|
|
22685
22733
|
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
|
|
22686
|
-
opts.db.delete(dashboardSessions).where(
|
|
22734
|
+
opts.db.delete(dashboardSessions).where(eq40(dashboardSessions.tokenHash, tokenHash)).run();
|
|
22687
22735
|
return null;
|
|
22688
22736
|
}
|
|
22689
22737
|
return session.apiKeyId;
|
|
22690
22738
|
};
|
|
22691
22739
|
const clearSession = (sessionId) => {
|
|
22692
22740
|
if (sessionId) {
|
|
22693
|
-
opts.db.delete(dashboardSessions).where(
|
|
22741
|
+
opts.db.delete(dashboardSessions).where(eq40(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
|
|
22694
22742
|
}
|
|
22695
22743
|
};
|
|
22696
22744
|
const getDefaultApiKey = () => {
|
|
22697
22745
|
if (!opts.config.apiKey) return void 0;
|
|
22698
|
-
return opts.db.select().from(apiKeys).where(
|
|
22746
|
+
return opts.db.select().from(apiKeys).where(eq40(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
|
|
22699
22747
|
};
|
|
22700
22748
|
const setSessionCookie = (reply, sessionId) => {
|
|
22701
22749
|
reply.header(
|
|
@@ -22856,12 +22904,12 @@ async function createServer(opts) {
|
|
|
22856
22904
|
return reply.send({ authenticated: true });
|
|
22857
22905
|
}
|
|
22858
22906
|
if (apiKey) {
|
|
22859
|
-
const key = opts.db.select().from(apiKeys).where(
|
|
22907
|
+
const key = opts.db.select().from(apiKeys).where(eq40(apiKeys.keyHash, hashApiKey(apiKey))).get();
|
|
22860
22908
|
if (!key || key.revokedAt) {
|
|
22861
22909
|
const err2 = authInvalid();
|
|
22862
22910
|
return reply.status(err2.statusCode).send(err2.toJSON());
|
|
22863
22911
|
}
|
|
22864
|
-
opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
|
|
22912
|
+
opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq40(apiKeys.id, key.id)).run();
|
|
22865
22913
|
setSessionCookie(reply, createSession(key));
|
|
22866
22914
|
return reply.send({ authenticated: true });
|
|
22867
22915
|
}
|
|
@@ -22927,7 +22975,7 @@ async function createServer(opts) {
|
|
|
22927
22975
|
const sentimentPoller = createSentimentPoller(
|
|
22928
22976
|
() => sentimentWorker.tick(),
|
|
22929
22977
|
() => {
|
|
22930
|
-
|
|
22978
|
+
log33.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
|
|
22931
22979
|
}
|
|
22932
22980
|
);
|
|
22933
22981
|
const pollSentiment = sentimentPoller.poll;
|
|
@@ -22939,7 +22987,7 @@ async function createServer(opts) {
|
|
|
22939
22987
|
const recomputeDebts = /* @__PURE__ */ new Map();
|
|
22940
22988
|
let recomputeSequence = 0;
|
|
22941
22989
|
const markAnswerFieldRecompute = (projectId, full) => {
|
|
22942
|
-
opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql16`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(
|
|
22990
|
+
opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql16`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq40(projects.id, projectId)).run();
|
|
22943
22991
|
};
|
|
22944
22992
|
const requestAnswerFieldRecompute = (projectId, projectName, scope, reason) => {
|
|
22945
22993
|
const sequence = ++recomputeSequence;
|
|
@@ -22957,10 +23005,10 @@ async function createServer(opts) {
|
|
|
22957
23005
|
if (pass.full && debt.latestFull <= sequence) debt.latestFull = 0;
|
|
22958
23006
|
try {
|
|
22959
23007
|
if (debt.latest === sequence && debt.latestFull === 0) {
|
|
22960
|
-
opts.db.update(projects).set({ answerFieldsRecompute: null }).where(
|
|
23008
|
+
opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq40(projects.id, projectId)).run();
|
|
22961
23009
|
if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
|
|
22962
23010
|
} else if (debt.latestFull === 0) {
|
|
22963
|
-
opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and33(
|
|
23011
|
+
opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and33(eq40(projects.id, projectId), eq40(projects.answerFieldsRecompute, "full"))).run();
|
|
22964
23012
|
}
|
|
22965
23013
|
} catch (err) {
|
|
22966
23014
|
app.log.error({ err, projectId }, "could not clear the owed answer field recompute");
|
|
@@ -22997,7 +23045,7 @@ async function createServer(opts) {
|
|
|
22997
23045
|
await yieldToEventLoop4();
|
|
22998
23046
|
const reason = (competitorAutoAliasReasons.get(projectId) ?? []).join(",");
|
|
22999
23047
|
competitorAutoAliasReasons.delete(projectId);
|
|
23000
|
-
const project = opts.db.select().from(projects).where(
|
|
23048
|
+
const project = opts.db.select().from(projects).where(eq40(projects.id, projectId)).get();
|
|
23001
23049
|
if (!project || project.competitorAutoAliases === "off") return;
|
|
23002
23050
|
if (project.competitorAutoAliases === "apply") {
|
|
23003
23051
|
await competitorAutoAliases.request(projectId, reason).catch(() => void 0);
|
|
@@ -23222,8 +23270,8 @@ async function createServer(opts) {
|
|
|
23222
23270
|
getAgentPin: () => describeAgentPin(opts.config),
|
|
23223
23271
|
getGoogleMarketingDoctorInput: (ctx) => {
|
|
23224
23272
|
if (!ctx.project) return null;
|
|
23225
|
-
const googleAds = opts.db.select().from(googleAdsConnections).where(
|
|
23226
|
-
const gtm = opts.db.select().from(gtmConnections).where(
|
|
23273
|
+
const googleAds = opts.db.select().from(googleAdsConnections).where(eq40(googleAdsConnections.projectId, ctx.project.id)).get();
|
|
23274
|
+
const gtm = opts.db.select().from(gtmConnections).where(eq40(gtmConnections.projectId, ctx.project.id)).get();
|
|
23227
23275
|
const googleAdsCredential = getGoogleAdsConnection(opts.config, ctx.project.id);
|
|
23228
23276
|
const gtmCredential = getGtmConnection(opts.config, ctx.project.id);
|
|
23229
23277
|
const googleAdsConnected = Boolean(googleAdsCredential?.accessToken);
|
|
@@ -23345,10 +23393,10 @@ async function createServer(opts) {
|
|
|
23345
23393
|
alreadyPresent: result.alreadyPresent
|
|
23346
23394
|
};
|
|
23347
23395
|
},
|
|
23348
|
-
onReleaseSyncRequested: (syncId,
|
|
23396
|
+
onReleaseSyncRequested: (syncId, release2) => {
|
|
23349
23397
|
executeReleaseSync(opts.db, syncId, {
|
|
23350
|
-
release,
|
|
23351
|
-
trigger: scheduledBacklinkReleases.delete(
|
|
23398
|
+
release: release2,
|
|
23399
|
+
trigger: scheduledBacklinkReleases.delete(release2) ? OutcomeTriggers.scheduled : OutcomeTriggers.manual,
|
|
23352
23400
|
deps: {
|
|
23353
23401
|
enqueueAutoExtract: ({ projectId, release: r }) => {
|
|
23354
23402
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -23375,8 +23423,8 @@ async function createServer(opts) {
|
|
|
23375
23423
|
app.log.error({ syncId, err }, "Common Crawl release sync failed");
|
|
23376
23424
|
});
|
|
23377
23425
|
},
|
|
23378
|
-
onBacklinkExtractRequested: (runId, projectId,
|
|
23379
|
-
executeBacklinkExtract(opts.db, runId, projectId, { release }).catch(
|
|
23426
|
+
onBacklinkExtractRequested: (runId, projectId, release2) => {
|
|
23427
|
+
executeBacklinkExtract(opts.db, runId, projectId, { release: release2 }).catch(
|
|
23380
23428
|
(err) => {
|
|
23381
23429
|
app.log.error({ runId, err }, "Backlink extract failed");
|
|
23382
23430
|
}
|
|
@@ -23429,11 +23477,11 @@ async function createServer(opts) {
|
|
|
23429
23477
|
onSiteAuditRequested: (runId, projectId, auditOpts) => {
|
|
23430
23478
|
runSiteAudit(runId, projectId, auditOpts);
|
|
23431
23479
|
},
|
|
23432
|
-
onBacklinksPruneCache: (
|
|
23480
|
+
onBacklinksPruneCache: (release2) => {
|
|
23433
23481
|
try {
|
|
23434
|
-
pruneCachedRelease(
|
|
23482
|
+
pruneCachedRelease(release2);
|
|
23435
23483
|
} catch (err) {
|
|
23436
|
-
app.log.error({ release, err }, "Failed to prune cached release");
|
|
23484
|
+
app.log.error({ release: release2, err }, "Failed to prune cached release");
|
|
23437
23485
|
}
|
|
23438
23486
|
},
|
|
23439
23487
|
listCachedReleases: () => {
|
|
@@ -23469,11 +23517,17 @@ async function createServer(opts) {
|
|
|
23469
23517
|
bingSettingsSummary,
|
|
23470
23518
|
bingConnectionStore,
|
|
23471
23519
|
onBingInspectSitemapRequested: (runId, projectId, inspectOpts) => {
|
|
23472
|
-
|
|
23473
|
-
|
|
23474
|
-
|
|
23475
|
-
|
|
23476
|
-
|
|
23520
|
+
runBingJob(
|
|
23521
|
+
opts.db,
|
|
23522
|
+
opts.config,
|
|
23523
|
+
projectId,
|
|
23524
|
+
"inspect",
|
|
23525
|
+
() => executeBingInspectSitemap(opts.db, runId, projectId, {
|
|
23526
|
+
...inspectOpts,
|
|
23527
|
+
config: opts.config
|
|
23528
|
+
})
|
|
23529
|
+
).then(() => {
|
|
23530
|
+
const finished = opts.db.select({ status: runs.status }).from(runs).where(eq40(runs.id, runId)).get();
|
|
23477
23531
|
if (finished?.status === RunStatuses.completed || finished?.status === RunStatuses.partial) {
|
|
23478
23532
|
return maybeRefreshGscCoverage(
|
|
23479
23533
|
opts.db,
|
|
@@ -23490,11 +23544,15 @@ async function createServer(opts) {
|
|
|
23490
23544
|
});
|
|
23491
23545
|
},
|
|
23492
23546
|
onBingSyncRequested: (runId, projectId) => {
|
|
23493
|
-
|
|
23494
|
-
|
|
23495
|
-
|
|
23496
|
-
|
|
23497
|
-
|
|
23547
|
+
runBingJob(
|
|
23548
|
+
opts.db,
|
|
23549
|
+
opts.config,
|
|
23550
|
+
projectId,
|
|
23551
|
+
"sync",
|
|
23552
|
+
() => executeBingSync(opts.db, runId, projectId, { config: opts.config })
|
|
23553
|
+
).catch((err) => {
|
|
23554
|
+
app.log.error({ runId, err }, "Bing sync failed");
|
|
23555
|
+
});
|
|
23498
23556
|
},
|
|
23499
23557
|
wordpressConnectionStore,
|
|
23500
23558
|
ga4CredentialStore,
|
|
@@ -23973,7 +24031,7 @@ async function createServer(opts) {
|
|
|
23973
24031
|
isBacklinksInstalled: () => isDuckdbInstalled()
|
|
23974
24032
|
});
|
|
23975
24033
|
}
|
|
23976
|
-
for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(
|
|
24034
|
+
for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq40(researchRuns.status, ResearchRunStatuses.queued)).all()) {
|
|
23977
24035
|
dispatchResearchRun(run.id, run.projectId, OutcomeTriggers.startup);
|
|
23978
24036
|
}
|
|
23979
24037
|
runtimeStartupSettled = true;
|