caelum0x a3377e9fde feat(console): per-app event-volume anomaly classification on Usage page
Adds lib/eventAnomaly.ts: classifies each app's current-period event volume
against its own trailing 30-day baseline (normal_variance / traffic_spike /
traffic_drop, with a severity score) via Evren's /v1/systemone gateway
(model "laya"), same wire contract and module shape as bidstage-tenders'
evren-fit.ts, sahibinden's evren-risk.ts and homeplan's architectFit.ts.

The current/baseline features (current_events, baseline_mean_daily, ratio,
day_of_week, app_age_days) are plain arithmetic over two real
insightsClient.summary() calls, never trusted to the model.
groundEventAnomalyReason/finalizeEventAnomalyReason clamp the model's
claimed reasonCode against that real ratio in both directions (unsupported
spike/drop claim downgraded; a normal_variance call contradicted by a
clearly extreme real ratio upgraded) -- live-verified against the real
gateway (2026-11-05) that this correction is not just defensive: on 6 real
test vectors spanning normal/spike/drop/no-baseline/borderline cases, the
model's own `reason` choice answered `severe_drop` in 5 of 6 regardless of
the real evidence (gateway-reported confidence ~0.04, near-uniform
probabilities every time) -- the ground+finalize pipeline is what makes the
final per-app classification correct in every case, not the raw model call.

Wires into apps/console/lib/config.ts (EVREN_LLM_API_KEY, optional,
fail-open, added to SECRET_ENV) and lib/deps.ts, and surfaces the worst
real per-app anomaly as a badge on the Usage page next to "Events this
month", reusing the existing capMessage/insightsView wiring point.
Additive only: a gateway outage, bad response, or missing key never
changes the existing event count or cap note. Not deployed.
2026-11-05 00:20:01 +03:00

106 lines
4.8 KiB
TypeScript

// Server wiring: config, repository and payment client for route handlers
// and server components. Server-only (never imported by a "use client" file).
import { readConfig, type Config } from "./config.ts";
import { Dodo } from "./dodo.ts";
import { mintClient, type MintClient } from "./mint.ts";
import { giteaClient, type GiteaClient } from "./gitea.ts";
import { PostgrestRepo } from "./postgrest-repo.ts";
import type { Repo } from "./repo.ts";
import { insightsClient, type InsightsClient } from "./insights.ts";
import type { EventAnomalyDeps } from "./eventAnomaly.ts";
import { productAnalyticsFromEnv, type ProductAnalyticsClient } from "./product-analytics.ts";
import { kvSites, type SitesStore } from "./sites.ts";
import { PostgrestFlagsStore } from "./flags/store.ts";
import { TableFlagsBackend } from "./flags/table-backend.ts";
import { FlagsmithBackend } from "./flags/flagsmith-backend.ts";
import type { FlagsDeps } from "./flags/service.ts";
import { PostgrestWatchStore } from "./watch/store.ts";
import { noMailer, rallySend } from "./watch/mail.ts";
import type { WatchDeps } from "./watch/service.ts";
import { CloudflareOAuth, DEFAULT_SCOPES } from "./ship/cloudflare.ts";
import { GithubApp } from "./ship/github.ts";
import { githubOidcKeys } from "./ship/http.ts";
import type { ShipDeps } from "./ship/service.ts";
import { PostgrestShipStore } from "./ship/store.ts";
export interface Deps {
cfg: Config;
repo: Repo;
dodo: Dodo;
sites: SitesStore;
insights: InsightsClient | null;
/** Event-volume anomaly severity (lib/eventAnomaly.ts); null until EVREN_LLM_API_KEY is set. Fail-open and additive -- never required for the Usage page's real event count. */
eventAnomaly: EventAnomalyDeps | null;
/** Product analytics (QY1.2); null while the service is not connected. */
productAnalytics: ProductAnalyticsClient | null;
flags: FlagsDeps;
watch: WatchDeps;
/** Ship on push (PY3.1); null until its GitHub App and Cloudflare client are configured. */
ship: ShipDeps | null;
/** Mint self-serve account provisioning (backlog item 11); null until MINT_URL/MINT_API_KEY are set. */
mint: MintClient | null;
/** Rithub self-serve provisioning (backlog item 4); null until GITEA_API_URL/GITEA_ADMIN_TOKEN are set. */
gitea: GiteaClient | null;
}
function flagsDeps(cfg: Config): FlagsDeps {
const store = new PostgrestFlagsStore({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey });
const table = new TableFlagsBackend(store);
const flagsmith = cfg.flags ? new FlagsmithBackend({ apiUrl: cfg.flags.apiUrl, adminToken: cfg.flags.adminToken }) : null;
return { store, backend: flagsmith ?? table, backends: flagsmith ? { table, flagsmith } : { table } };
}
function shipDeps(cfg: Config, repo: Repo, sites: SitesStore): ShipDeps | null {
if (!cfg.ship) return null;
return {
store: new PostgrestShipStore({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey }),
repo,
github: new GithubApp(cfg.ship.github),
cloudflare: new CloudflareOAuth({
clientId: cfg.ship.cloudflare.clientId,
clientSecret: cfg.ship.cloudflare.clientSecret,
redirectUri: `${cfg.consoleUrl}/api/v1/github/cloudflare/callback`,
scopes: cfg.ship.cloudflare.scopes ?? DEFAULT_SCOPES,
}),
oidcKeys: githubOidcKeys(),
consoleUrl: cfg.consoleUrl,
credentialsKey: cfg.ship.credentialsKey,
sessionSecret: cfg.sessionSecret,
sites,
};
}
let cached: Deps | null = null;
export function deps(): Deps {
if (cached) return cached;
const cfg = readConfig();
const repo = new PostgrestRepo({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey });
const sites = kvSites();
cached = {
cfg,
repo,
dodo: new Dodo({ base: cfg.dodoBase, apiKey: cfg.dodoApiKey, allowLive: cfg.dodoAllowLive }),
sites,
insights: cfg.insightsApi ? insightsClient({ apiUrl: cfg.insightsApi.url, token: cfg.insightsApi.token }) : null,
eventAnomaly: cfg.eventAnomaly
? { baseUrl: cfg.eventAnomaly.baseUrl, apiKey: cfg.eventAnomaly.apiKey, fetch: globalThis.fetch.bind(globalThis), log: (event, detail) => console.error(`${event}${detail ? ` ${JSON.stringify(detail)}` : ""}`) }
: null,
productAnalytics: productAnalyticsFromEnv(),
flags: flagsDeps(cfg),
watch: {
store: new PostgrestWatchStore({ url: cfg.scribaseUrl, serviceRoleKey: cfg.scribaseServiceRoleKey }),
repo,
mailer: cfg.rallySend ? rallySend(cfg.rallySend) : noMailer,
consoleUrl: cfg.consoleUrl,
agentToken: cfg.watchAgentToken,
live: cfg.watchLive,
},
ship: shipDeps(cfg, repo, sites),
mint: cfg.mint ? mintClient({ url: cfg.mint.url, apiKey: cfg.mint.apiKey }) : null,
gitea: cfg.gitea ? giteaClient({ apiUrl: cfg.gitea.apiUrl, adminToken: cfg.gitea.adminToken }) : null,
};
return cached;
}