OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M15-102): Per-module fixes: packages/core/src/modules/auth - R4, R13 and the findings no rule covers
ralphf3b52726783b
diff --git a/apps/start/src/agents/client.ts b/apps/start/src/agents/client.tsindex c3fe935d4..f96b37933 100644--- a/apps/start/src/agents/client.ts+++ b/apps/start/src/agents/client.ts@@ -14,11 +14,15 @@ import type { ChatApp } from '@openpanel/core';* entire agent definition (DB services, providers, etc.) along with it. It is* type-only, erased at build time — no runtime coupling, which is what* keeps it inside ADR-008's rule that only `*.constants.ts` may be- * VALUE-imported here. It used to reach `apps/api/src/agents/app`- * relatively; M9-004 deleted that wrapper and core's barrel exports the- * type. The shared schemas (context, client tool inputs, model- * whitelist) live in `@openpanel/core`'s assistant.constants so only this- * one type import crosses the app boundary.+ * VALUE-imported here. The barrel is the only door: `@openpanel/core`'s+ * exports map publishes `.` and `./modules/*.constants`, and `ChatApp`+ * cannot live in a constants file. The shared schemas (context, client+ * tool inputs, model whitelist) do live in+ * `@openpanel/core`'s assistant.constants, so this is the one type import+ * that crosses the app boundary — a second one past `AppRouter`, which+ * ADR-022 R12 says should be the only one. Recorded as an open R12+ * finding (M14-101 / M15-101): widening R12 to `AppRouter` + `ChatApp`+ * is an ADR amendment, not a code change.*/export type AppClient = ReturnType<typeof createClient<ChatApp>>;diff --git a/apps/start/src/components/chat/chat-runtime.tsx b/apps/start/src/components/chat/chat-runtime.tsxindex 6d81d6a9b..d5a5be897 100644--- a/apps/start/src/components/chat/chat-runtime.tsx+++ b/apps/start/src/components/chat/chat-runtime.tsx@@ -85,7 +85,8 @@ export function ChatRuntimeProvider({ children }: { children: ReactNode }) {hydrateFromServer: true,optimisticUserMessage: true,// Better Agent forwards tool calls for any tool declared via- // `.client()` on the server (see `apps/api/src/agents/tools/ui.ts`)+ // `.client()` on the server (see `@openpanel/core`'s+ // `modules/assistant/src/tools/ui.ts`)// to the matching entry here. Typed via `ToolHandlers<ChatApp>`// on the map itself, so this line stays cast-free.toolHandlers: chatToolHandlers,diff --git a/apps/start/src/components/chat/tool-results/chat-report-result.tsx b/apps/start/src/components/chat/tool-results/chat-report-result.tsxindex 726250a77..a1fada105 100644--- a/apps/start/src/components/chat/tool-results/chat-report-result.tsx+++ b/apps/start/src/components/chat/tool-results/chat-report-result.tsx@@ -150,17 +150,11 @@ function deriveTitleFromInput(toolType: string, input: unknown): string | null {}case 'tool-get_rolling_active_users': {- const w = args.windowDays ?? 1;- const label =- w === 1- ? 'DAU'- : w === 7- ? 'WAU'- : w === 30- ? 'MAU'- : `${w}-day active users`;+ // The chart this tool returns is daily uniques whatever `windowDays`+ // asked for — only the numeric summary honours the rolling window — so+ // the title must not say DAU/WAU/MAU.const days = args.days ?? 30;- return `${label} — last ${days} days`;+ return `Daily active users — last ${days} days`;}case 'tool-generate_report': {diff --git a/apps/start/src/contexts/page-context.tsx b/apps/start/src/contexts/page-context.tsxindex c82821de9..c1698e08f 100644--- a/apps/start/src/contexts/page-context.tsx+++ b/apps/start/src/contexts/page-context.tsx@@ -31,7 +31,8 @@ export type { PageContextPage };* `filters` / `reportDraft`. The validation* schema keeps those loose (`z.record(unknown)`) because Zod can't narrow* `IChartEventFilter` / `IReportInput` at the boundary; the server- * re-narrows in `apps/api/src/agents/tools/helpers.ts`.+ * re-narrows in `@openpanel/core`'s+ * `modules/assistant/src/tools/helpers.ts` (`pageContextFilters`).** Each target page calls `usePageContext({...})` in an effect; the* provider stores the latest value. The chat drawer reads it via a ref sodiff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.tsindex f06500509..02e07d867 100644--- a/packages/core/src/modules/assistant/assistant.constants.ts+++ b/packages/core/src/modules/assistant/assistant.constants.ts@@ -1,21 +1,20 @@import { z } from 'zod';/**- * Moved from packages/validation/src/chat.ts (M5-005, ADR-008's module map:- * assistant owns "C"). packages/validation/src/chat.ts becomes a re-export- * shim of this file (same shape as packages/validation/src/import.validation.ts- * since M5-004), so apps/start's model picker and the SDK-facing types keep- * resolving these symbols through packages/validation's existing barrel- * unchanged.+ * Moved from the V1 validation package (M5-005, ADR-008's module map:+ * assistant owns "C"). apps/start reaches these symbols through the+ * `@openpanel/core/modules/assistant/assistant.constants` subpath —+ * `src/agents/models.ts`, `src/contexts/page-context.tsx` and+ * `src/components/chat/tool-handlers.ts`.** Isomorphic by the AGENTS.md rule: zod and nothing else.** The full `ChatApp` type (Better Agent's inferred app type) lives in- * `./src/app.ts` — it's `typeof chatApp` and inherently bound to the- * server-side agent definition, so it stays out of this constants file- * (a Prisma/Better-Agent type would follow it into a browser bundle).- * `apps/api/src/agents/app.ts` re-exports it (DELEGATE PATTERN) for the- * frontend's narrow type-only import.+ * `./src/app.ts` — it's `ReturnType<typeof createChatApp>` and inherently+ * bound to the server-side agent definition, so it stays out of this+ * constants file (a Prisma/Better-Agent type would follow it into a browser+ * bundle). The frontend type-imports it from the core barrel instead+ * (`apps/start/src/agents/client.ts`); see that file for why.*/// ────────────────────────────────────────────────────────────────────@@ -69,10 +68,12 @@ export type PageContext = z.infer<typeof pageContextSchema>;export type PageContextPage = z.infer<typeof pageContextPageSchema>;/**- * Agent context shared by every agent. The client sends all three fields,- * but the auth plugin guard validates that the session user actually has- * access to (projectId, organizationId) and rejects mismatches before- * the agent ever runs. Tools may safely trust these values.+ * Agent context shared by every agent. The client sends all three fields;+ * `assistant.routes.ts` re-reads the body, checks the session user's access+ * to (projectId, organizationId) and 403s a mismatch before handing the+ * request to the agent — so tools may trust these values. That check is the+ * module's ONLY tenancy gate: all 65 server tools use `context.projectId` as+ * their key without re-checking it.*/export const chatContextSchema = z.object({projectId: z.string(),@@ -84,7 +85,7 @@ export type ChatAgentContext = z.infer<typeof chatContextSchema>;// ────────────────────────────────────────────────────────────────────// Model whitelist — single source of truth, consumed by:-// - apps/api (builds an agent per entry)+// - src/app.ts (builds an agent per entry)// - apps/start (model picker)// Adding a new model = add an entry here. No other changes required.// ────────────────────────────────────────────────────────────────────diff --git a/packages/core/src/modules/assistant/assistant.rpc.ts b/packages/core/src/modules/assistant/assistant.rpc.tsindex 2cd7199a0..95910aa21 100644--- a/packages/core/src/modules/assistant/assistant.rpc.ts+++ b/packages/core/src/modules/assistant/assistant.rpc.ts@@ -1,11 +1,9 @@-// Ported from packages/trpc/src/routers/chat.ts (M5-005).+// Ported from the V1 tRPC chat router (M5-005).//-// M11-001: every procedure is on its V1 twin's builder.-// `protectedProcedure` runs `enforceUserIsAuthed` + `enforceAccess` BEFORE-// the input parser, exactly as V1 does. The explicit checks in the handlers-// below stay: `enforceAccess` only sees a TOP-LEVEL `projectId` /-// `organizationId`, so anything resolved from another id needs its own-// (ADR-011).+// M11-001: every procedure is on its V1 twin's builder. `protectedProcedure`+// runs `enforceUserIsAuthed` + `enforceAccess` BEFORE the input parser,+// exactly as V1 does — `models` takes no input and needs no object-id check+// of its own, so the handler is the query and nothing else (ADR-022 R10).import { createTRPCRouter, protectedProcedure } from '../../rpc/base';import {diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex f2ff258cd..a837a1496 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -1,8 +1,8 @@-// Moved from apps/api/src/agents/* (the Better Agent chat app + its tools,-// prompt and Prisma persistence) and packages/trpc/src/agents/filter-command.ts-// (M5-005, ADR-007's module map: assistant owns "S"). The bulk of the logic-// lives under ./src — this file is the module's public entry point, the same-// shape as insight.service.ts drawing from insight/src/*.+// Moved from V1's agents directory (the Better Agent chat app + its tools,+// prompt and Prisma persistence) and V1's tRPC filter-command agent (M5-005,+// ADR-007's module map: assistant owns "S"). The bulk of the logic lives+// under ./src — this file is the module's public entry point, the same shape+// as insight.service.ts drawing from insight/src/*.//// M15-003: every export takes `deps`. `./src/app.ts` and// `./src/filter-command.ts` construct nothing at import time any more, so thediff --git a/packages/core/src/modules/assistant/src/app.ts b/packages/core/src/modules/assistant/src/app.tsindex d89accc1e..58111928b 100644--- a/packages/core/src/modules/assistant/src/app.ts+++ b/packages/core/src/modules/assistant/src/app.ts@@ -1,5 +1,5 @@-// Moved from apps/api/src/agents/app.ts (M5-005, ADR-007's module map:-// assistant owns "S").+// Moved from V1's agents/app.ts (M5-005, ADR-007's module map: assistant+// owns "S").//// M15-003: the app is BUILT from the `deps` `assistant.routes.ts` already// holds, not constructed at module scope (ADR-022 R6/R15). Importing thisdiff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.tsindex 729f7b9ca..9bf3ecfac 100644--- a/packages/core/src/modules/assistant/src/filter-command.ts+++ b/packages/core/src/modules/assistant/src/filter-command.ts@@ -1,6 +1,6 @@-// Moved from packages/trpc/src/agents/filter-command.ts (M5-005). The one-// caller is `overview.rpc.ts`'s `runFilterCommand` procedure, which reaches-// it through `ctx.services.assistant`.+// Moved from V1's tRPC filter-command agent (M5-005). The one caller is+// `overview.rpc.ts`'s `runFilterCommand` procedure, which reaches it through+// `ctx.services.assistant`.//// M15-003: the agent app and its five tools are BUILT from the `deps` that// procedure already holds (ADR-022 R6/R15) — importing this file constructs@@ -49,7 +49,7 @@ const operatorEnum = z.enum(objectToZodEnums(operators));const rangeEnum = zRange;const intervalEnum = z.enum(objectToZodEnums(intervals));-export const filterCommandOutputSchema = z.object({+const filterCommandOutputSchema = z.object({applyFilters: z.object({range: rangeEnum.nullable(),@@ -183,7 +183,7 @@ function defineServerTool<TSchema extends z.ZodTypeAny>(config: {ctx: FilterCommandContext) => Promise<unknown>;}): AgentToolDefinition {- // biome-ignore lint/suspicious/noExplicitAny: Zod schema instantiation depth — same dodge as apps/api/src/agents/tools/ui.ts+ // biome-ignore lint/suspicious/noExplicitAny: Zod schema instantiation depth — same dodge as `chatTool` in src/tools/helpers.tsconst contract: any = defineTool({name: config.name,description: config.description,@@ -385,7 +385,7 @@ function createFilterCommandApp(deps: ServiceDeps) {instruction: (ctx: FilterCommandContext) => buildInstruction(ctx),tools: () => FILTER_COMMAND_TOOLS.map((tool) => tool(deps)),maxSteps: 6,- // biome-ignore lint/suspicious/noExplicitAny: same dodge as apps/api/src/agents/app.ts+ // biome-ignore lint/suspicious/noExplicitAny: same dodge as `createChatAgent` in src/app.ts} as any);return betterAgent({ agents: [agent] });}@@ -406,7 +406,7 @@ export async function runFilterCommand(timezone: input.timezone,pageContext: input.pageContext as FilterCommandContext['pageContext'],},- // biome-ignore lint/suspicious/noExplicitAny: same dodge as apps/api/src/agents/app.ts+ // biome-ignore lint/suspicious/noExplicitAny: same dodge as `createChatAgent` in src/app.ts} as any)) as { structured?: FilterCommandResult };if (!result.structured) {diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.tsindex 18aed0af3..d202aaa76 100644--- a/packages/core/src/modules/assistant/src/persistence.ts+++ b/packages/core/src/modules/assistant/src/persistence.ts@@ -76,7 +76,7 @@ export function createConversationStore(deps: ServiceDeps): ConversationStore {const owner = chatRunContext.getStore();if (!owner) {throw new Error(- 'chatRunContext missing during save — the Fastify wrapper must run first'+ 'chatRunContext missing during save — assistant.routes.ts must run the handler inside chatRunContext.run()');}diff --git a/packages/core/src/modules/assistant/src/prompt.ts b/packages/core/src/modules/assistant/src/prompt.tsindex 6a7037156..9632c5d05 100644--- a/packages/core/src/modules/assistant/src/prompt.ts+++ b/packages/core/src/modules/assistant/src/prompt.ts@@ -142,9 +142,9 @@ When you call a chart tool, keep prose SHORT — a one-line caption like "Here's* function.*/export function buildSystemPrompt(context: ChatAgentContext): string {- return [buildBasePrompt(), buildPageContextSection(context.pageContext)]- .filter(Boolean)- .join('\n\n');+ return [buildBasePrompt(), buildPageContextSection(context.pageContext)].join(+ '\n\n'+ );}function buildPageContextSection(pc?: PageContext): string {diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.tsindex 32d93520e..43c69f49f 100644--- a/packages/core/src/modules/assistant/src/report-runner.ts+++ b/packages/core/src/modules/assistant/src/report-runner.ts@@ -1,5 +1,5 @@-// Ported from packages/mcp/src/tools/analytics/reports.ts's `runReport` /-// `runReportFromConfig` (M5-005).+// Ported from V1's MCP `runReport` / `runReportFromConfig` (M5-005), now+// `modules/mcp/src/tools/analytics/reports.ts`.//// ADR-007 explicitly defers unifying MCP's tool definitions with assistant's,// so `modules/mcp/src/tools/analytics/reports.ts` keeps its own copy of thisdiff --git a/packages/core/src/modules/assistant/src/run-context.ts b/packages/core/src/modules/assistant/src/run-context.tsindex 8dd321602..56d5a1761 100644--- a/packages/core/src/modules/assistant/src/run-context.ts+++ b/packages/core/src/modules/assistant/src/run-context.ts@@ -1,9 +1,9 @@import { AsyncLocalStorage } from 'node:async_hooks';/**- * Per-request context for chat runs. Populated by the Fastify route- * wrapper (which validates the session + project access) before the- * Better Agent handler runs, and read by:+ * Per-request context for chat runs. Populated by `assistant.routes.ts`+ * (which validates the session + project access) before the Better+ * Agent handler runs, and read by:* - the persistence store, to upsert the `Conversation` row with* the right owner on first save* - `resolveDateRange` / the prompt builder, to turn page-contextdiff --git a/packages/core/src/modules/assistant/src/tools/base.ts b/packages/core/src/modules/assistant/src/tools/base.tsindex eaeb8038d..aa0373c81 100644--- a/packages/core/src/modules/assistant/src/tools/base.ts+++ b/packages/core/src/modules/assistant/src/tools/base.ts@@ -37,6 +37,9 @@ import {truncateRows,} from './helpers';+/** Series label for `get_rolling_active_users`' chart — always daily uniques. */+const DAILY_ACTIVE_USERS_SERIES_LABEL = 'Daily active users';+// Helper, not vocabulary — ADR-008's ruling on objectToZodEnums: copy locally// rather than import from a module.function objectToZodEnums<K extends string>(@@ -643,7 +646,7 @@ export const getRollingActiveUsers = (deps: ServiceDeps) =>{name: 'get_rolling_active_users',description:- 'Rolling active-users trend (DAU/WAU/MAU). Returns BOTH the latest single value AND a renderable chart config (so the UI draws a line chart). Default is DAU over 30 days; pass `windowDays: 7` for WAU or `windowDays: 30` for MAU. ALWAYS supply a concise `title` (3-8 words) that describes what the chart shows.',+ 'Rolling active users (DAU/WAU/MAU). Returns TWO things that answer different questions: `summary` is the rolling active-user count over `windowDays` (1 = DAU, 7 = WAU, 30 = MAU — quote this for "how many MAU do we have?"), and the chart is a DAILY unique-users trend over the last `days` — it is NOT a rolling-window series, so do not describe the line as WAU/MAU. ALWAYS supply a concise `title` (3-8 words) that describes what the chart shows.',schema: z.object({/*** The rolling window. 1 = DAU (default), 7 = WAU, 30 = MAU.@@ -667,11 +670,16 @@ export const getRollingActiveUsers = (deps: ServiceDeps) =>// We use a user-segment on `screen_view` — OpenPanel's standard// pageview event — with a linear chart. The ChartEngine dedupes// per profile_id because of `segment: 'user'`.+ //+ // The chart is daily uniques regardless of `windowDays`: the chart+ // engine has no rolling-window series type. `windowDays` shapes the+ // `summary` below and nothing else, which is why the series is+ // labelled for what it is rather than for the requested window.const endDate = new Date().toISOString().slice(0, 10);const startDate = new Date(Date.now() - (range - 1) * 86_400_000).toISOString().slice(0, 10);- const label =+ const summaryLabel =window === 1? 'DAU': window === 7@@ -694,7 +702,7 @@ export const getRollingActiveUsers = (deps: ServiceDeps) =>id: '1',type: 'event' as const,name: 'screen_view',- displayName: label,+ displayName: DAILY_ACTIVE_USERS_SERIES_LABEL,segment: 'user' as const,filters: [],},@@ -717,9 +725,13 @@ export const getRollingActiveUsers = (deps: ServiceDeps) =>return {// `name` is the title the frontend `ChatReportResult` uses for// the card header. The model is asked to supply a `title` —- // we use it when present, falling back to a generic label.- name: title?.trim() || `${label} — last ${range} days`,- label,+ // we use it when present, falling back to a generic label. The+ // fallback names the CHART, not the summary: the two measure+ // different windows.+ name:+ title?.trim() ||+ `${DAILY_ACTIVE_USERS_SERIES_LABEL} — last ${range} days`,+ label: summaryLabel,window,summary,// Keys the frontend report renderer knows about.diff --git a/packages/core/src/modules/assistant/src/tools/groups.ts b/packages/core/src/modules/assistant/src/tools/groups.tsindex 02faaa68b..f5402532c 100644--- a/packages/core/src/modules/assistant/src/tools/groups.ts+++ b/packages/core/src/modules/assistant/src/tools/groups.ts@@ -8,6 +8,13 @@ import {} from '../../../group/group.service';import { chatTool, dashboardUrl, truncateRows } from './helpers';+/** How many members `get_group_metrics` pulls before bucketing activity. */+const GROUP_METRICS_MEMBER_LIMIT = 1000;+/** How many of those members' recent events back the 7d/30d activity counts. */+const GROUP_METRICS_EVENT_LIMIT = 1000;+/** How many same-type peers `compare_groups` looks at. */+const PEER_GROUP_LIMIT = 100;+export const getGroupFull = (deps: ServiceDeps) =>chatTool({@@ -133,8 +140,7 @@ export const getGroupMetrics = (deps: ServiceDeps) =>chatTool({name: 'get_group_metrics',- description:- 'Aggregate metrics for this group: total members, members active in the last 7d/30d, total revenue (sum of member.revenue), avg sessions per member.',+ description: `Aggregate metrics for this group: total members, and how many of them were active in the last 7 days / 30 days. Activity is derived from the group members' most recent ${GROUP_METRICS_EVENT_LIMIT} events, so very large groups are undercounted.`,schema: z.object({groupId: z.string().optional(),}),@@ -146,7 +152,7 @@ export const getGroupMetrics = (deps: ServiceDeps) =>const members = await getGroupMemberProfiles(deps, {projectId: context.projectId,groupId: id,- take: 1000,+ take: GROUP_METRICS_MEMBER_LIMIT,});if (members.data.length === 0) {@@ -164,7 +170,7 @@ export const getGroupMetrics = (deps: ServiceDeps) =>startDate: new Date(Date.now() - 30 * 86_400_000).toISOString().slice(0, 10),- limit: 1000,+ limit: GROUP_METRICS_EVENT_LIMIT,});const activeIds7d = new Set<string>();const activeIds30d = new Set<string>();@@ -193,7 +199,7 @@ export const compareGroups = (deps: ServiceDeps) =>{name: 'compare_groups',description:- 'Compare this group\'s member count and activity to other groups of the same type. Useful in B2B for "is this account active vs the rest?".',+ "Compare this group's member count against how many other groups of the same type exist, and list a few of those peers by name. Peer member counts and peer activity are NOT fetched — do not claim a ranking.",schema: z.object({groupId: z.string().optional(),}),@@ -211,7 +217,7 @@ export const compareGroups = (deps: ServiceDeps) =>const peers = await findGroupsCore(deps, {projectId: context.projectId,type: thisGroup.group.type,- limit: 100,+ limit: PEER_GROUP_LIMIT,});if (peers.length === 0) {diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.tsindex dfc97d39a..6d2567364 100644--- a/packages/core/src/modules/assistant/src/tools/helpers.ts+++ b/packages/core/src/modules/assistant/src/tools/helpers.ts@@ -186,9 +186,9 @@ const PRESET_RANGES: ReadonlySet<IChartRange> = new Set([* 3. Nothing → default to the last 30 days (via* `resolveDateRangeCore`).*- * Timezone comes from `chatRunContext` (populated by the Fastify- * wrapper once per request). Outside that context we fall back to UTC- * — only relevant in tests / direct calls.+ * Timezone comes from `chatRunContext` (populated by+ * `assistant.routes.ts` once per request). Outside that context we fall+ * back to UTC — only relevant in tests / direct calls.*/export function resolveDateRange(filters?: PageContext['filters']): {startDate: string;diff --git a/packages/core/src/modules/assistant/src/tools/profile.ts b/packages/core/src/modules/assistant/src/tools/profile.tsindex 0539206ff..d98980831 100644--- a/packages/core/src/modules/assistant/src/tools/profile.ts+++ b/packages/core/src/modules/assistant/src/tools/profile.ts@@ -10,6 +10,11 @@ import {} from '../../../profile/profile.service';import { chatTool, dashboardUrl, truncateRows } from './helpers';+/** How many other profiles `compare_profile_to_average` fetches to sample from. */+const AVERAGE_CANDIDATE_LIMIT = 100;+/** How many of those candidates actually get a metrics query. */+const AVERAGE_SAMPLE_SIZE = 30;+export const getProfileFull = (deps: ServiceDeps) =>chatTool({@@ -246,20 +251,24 @@ export const compareProfileToAverage = (deps: ServiceDeps) =>projectId: context.projectId,profileId: id,}).catch(() => null),- findProfilesCore(deps, { projectId: context.projectId, limit: 100 }),+ findProfilesCore(deps, {+ projectId: context.projectId,+ limit: AVERAGE_CANDIDATE_LIMIT,+ }),]);if (!thisMetrics) {return { error: 'Profile not found or has no events', profileId: id };}- // Compute averages from a sample of other profiles. We sample 100- // and compute their metrics in parallel; for a precise project-wide- // average we'd want a dedicated db helper, but this gives the LLM a- // useful comparison without extra schema work.+ // Compute averages from a sample of other profiles: of the+ // AVERAGE_CANDIDATE_LIMIT fetched above we query metrics for the first+ // AVERAGE_SAMPLE_SIZE, in parallel. For a precise project-wide average+ // we'd want a dedicated db helper, but this gives the LLM a useful+ // comparison without extra schema work.const sampleIds = allProfiles.filter((p) => p.id !== id)- .slice(0, 30)+ .slice(0, AVERAGE_SAMPLE_SIZE).map((p) => p.id);const sampleMetrics = await Promise.all(diff --git a/packages/core/src/modules/assistant/src/tools/session.ts b/packages/core/src/modules/assistant/src/tools/session.tsindex ecdbb94ce..0c3ec740b 100644--- a/packages/core/src/modules/assistant/src/tools/session.ts+++ b/packages/core/src/modules/assistant/src/tools/session.ts@@ -7,6 +7,11 @@ import {} from '../../../session/session.service';import { chatTool, dashboardUrl, truncateRows } from './helpers';+/** How many same-referrer sessions `get_session_referrer_context` samples. */+const REFERRER_SAMPLE_LIMIT = 20;+/** How many of that sample are returned in full. */+const REFERRER_SAMPLE_DETAIL_COUNT = 5;+export const getSessionFull = (deps: ServiceDeps) =>chatTool({@@ -104,7 +109,7 @@ export const getSimilarSessions = (deps: ServiceDeps) =>{name: 'get_similar_sessions',description:- 'Find sessions with similar device + country + entry path to this one. Returns up to 10. Useful for "is this typical?" questions.',+ 'Find sessions with the same device + country as this one. Returns up to 10. The reference session\'s entry path is reported back for context but is NOT used as a match criterion. Useful for "is this typical?" questions.',schema: z.object({sessionId: z.string().optional(),limit: z.number().min(1).max(20).default(10).optional(),@@ -217,8 +222,7 @@ export const getSessionReferrerContext = (deps: ServiceDeps) =>chatTool({name: 'get_session_referrer_context',- description:- 'Context about how the user arrived: total traffic this period from the same referrer, plus a few sample sessions from that referrer.',+ description: `Context about how the user arrived: a sample of up to ${REFERRER_SAMPLE_LIMIT} recent sessions from the same referrer, across all time (not the current date range), plus a few of them in full. \`sampled_from_referrer\` is that sample size, NOT a project total — never quote it as one.`,schema: z.object({sessionId: z.string().optional(),}),@@ -238,7 +242,7 @@ export const getSessionReferrerContext = (deps: ServiceDeps) =>const fromSameReferrer = await querySessionsCore(deps, {projectId: context.projectId,referrerName: session.referrerName ?? undefined,- limit: 20,+ limit: REFERRER_SAMPLE_LIMIT,});return {@@ -246,14 +250,17 @@ export const getSessionReferrerContext = (deps: ServiceDeps) =>referrer: session.referrer,referrer_name: session.referrerName,referrer_type: session.referrerType,- total_from_referrer: fromSameReferrer.length,- sample_sessions: fromSameReferrer.slice(0, 5).map((s) => ({- id: s.id,- created_at: s.created_at,- country: s.country,- is_bounce: s.is_bounce,- entry_path: s.entry_path,- })),+ sampled_from_referrer: fromSameReferrer.length,+ sample_limit: REFERRER_SAMPLE_LIMIT,+ sample_sessions: fromSameReferrer+ .slice(0, REFERRER_SAMPLE_DETAIL_COUNT)+ .map((s) => ({+ id: s.id,+ created_at: s.created_at,+ country: s.country,+ is_bounce: s.is_bounce,+ entry_path: s.entry_path,+ })),};});@@ -273,7 +280,7 @@ export const getSessionReplaySummary = (deps: ServiceDeps) =>const session = await getSessionById(deps, id, context.projectId);return {session_id: id,- available: session.hasReplay ?? false,+ available: session.hasReplay,replay_url: session.hasReplay? dashboardUrl(deps.config,diff --git a/packages/core/src/modules/auth/auth.routes.ts b/packages/core/src/modules/auth/auth.routes.tsindex 7ab1a0681..3783ee5ae 100644--- a/packages/core/src/modules/auth/auth.routes.ts+++ b/packages/core/src/modules/auth/auth.routes.ts@@ -1,10 +1,8 @@-// The github/google OAuth callbacks (M6-003). V1's Fastify controller-// (apps/api/src/controllers/oauth-callback.controller.tsx) stays the LIVE-// route (DELEGATE PATTERN) and delegates its token-exchange/session logic to-// auth.service.ts's `completeOAuthCallback` — the same function this route-// calls, same shape as gsc.routes.ts (M5-002). This route is not yet-// reachable: main.ts does not mount `dashboardRoutes` until a real `AppDeps`-// exists (P3/P4/P8).+// The github/google OAuth callbacks (M6-003), same shape as gsc.routes.ts+// (M5-002): DELEGATE PATTERN, token-exchange/session logic lives in+// auth.service.ts's `completeOAuthCallback`. `main.ts` mounts+// `dashboardRoutes` unconditionally on every HTTP-serving boot, so this route+// is live.//// NAMED GAP: per-route cookie signing is not wired yet (gsc.routes.ts's// header names the same gap), so `ctx.cookies.get()` here reads the raw,diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 86815b6cd..ff21b3dcf 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -170,48 +170,91 @@ export function createAuthService(deps: ServiceDeps,_services: () => Services) {- // Annotated as a whole rather than member by member: one annotation binds- // the ladder contract and gives all three members the explicit return type- // `ReturnType<typeof createAuthService>` needs (ADR-022 R5).- const accessChecks: ProjectAccessChecks = {- async requireProjectAccess(args) {- return (await getAccessChecks()).requireProjectAccess(args);- },- async requireOrganizationAdmin(args) {- return (await getAccessChecks()).requireOrganizationAdmin(args);- },- async requireProjectAdmin(args) {- return (await getAccessChecks()).requireProjectAdmin(args);- },- };+ // One function per member, closing over `deps`, so the return statement+ // below stays a plain index (ADR-022 R4) — nothing here is a `return { ... }`+ // literal with logic inside it.+ async function requireProjectAccess(+ args: Parameters<ProjectAccessChecks['requireProjectAccess']>[0]+ ): ReturnType<ProjectAccessChecks['requireProjectAccess']> {+ return (await getAccessChecks()).requireProjectAccess(args);+ }++ async function requireOrganizationAdmin(+ args: Parameters<ProjectAccessChecks['requireOrganizationAdmin']>[0]+ ): ReturnType<ProjectAccessChecks['requireOrganizationAdmin']> {+ return (await getAccessChecks()).requireOrganizationAdmin(args);+ }++ async function requireProjectAdmin(+ args: Parameters<ProjectAccessChecks['requireProjectAdmin']>[0]+ ): ReturnType<ProjectAccessChecks['requireProjectAdmin']> {+ return (await getAccessChecks()).requireProjectAdmin(args);+ }++ async function getProjectAccess(args: {+ userId: string;+ projectId: string;+ }): Promise<IProjectAccess | null> {+ return (await loadAccessLookups()).getProjectAccess(args);+ }++ async function getOrganizationAccess(+ ...args: Parameters<typeof GetOrganizationAccessFn>+ ): ReturnType<typeof GetOrganizationAccessFn> {+ return (await loadAccessLookups()).getOrganizationAccess(...args);+ }++ async function getClientAccess(+ ...args: Parameters<typeof GetClientAccessFn>+ ): ReturnType<typeof GetClientAccessFn> {+ return (await loadAccessLookups()).getClientAccess(...args);+ }++ /**+ * The session cookie's other half. `http/session.ts` reaches it here+ * rather than deep-importing `./src/login-session` (ADR-022 R22), which+ * is also what keeps the demo-user branch inside one function.+ */+ function checkSessionToken(+ token: string | null | undefined+ ): Promise<SessionValidationResult> {+ return validateSessionToken(deps, token);+ }++ function setSessionCookie(+ setCookie: ISetCookie,+ token: string,+ expiresAt: Date+ ): void {+ setSessionTokenCookie(deps.config, setCookie, token, expiresAt);+ }++ function setAuthProviderCookie(+ setCookie: ISetCookie,+ provider: string+ ): void {+ setLastAuthProviderCookie(deps.config, setCookie, provider);+ }++ function clearSessionCookie(setCookie: ISetCookie): void {+ deleteSessionTokenCookie(deps.config, setCookie);+ }++ function cookieDomainForUrl(+ url: string+ ): ReturnType<typeof parseCookieDomain> {+ return parseCookieDomain(deps.config, url);+ }return {- ...accessChecks,+ requireProjectAccess,+ requireOrganizationAdmin,+ requireProjectAdmin,requireLogin,- /**- * The session cookie's other half. `http/session.ts` reaches it here- * rather than deep-importing `./src/login-session` (ADR-022 R22), which- * is also what keeps the demo-user branch inside one function.- */- validateSessionToken: (- token: string | null | undefined- ): Promise<SessionValidationResult> => validateSessionToken(deps, token),- async getProjectAccess(args: {- userId: string;- projectId: string;- }): Promise<IProjectAccess | null> {- return (await loadAccessLookups()).getProjectAccess(args);- },- async getOrganizationAccess(- ...args: Parameters<typeof GetOrganizationAccessFn>- ): ReturnType<typeof GetOrganizationAccessFn> {- return (await loadAccessLookups()).getOrganizationAccess(...args);- },- async getClientAccess(- ...args: Parameters<typeof GetClientAccessFn>- ): ReturnType<typeof GetClientAccessFn> {- return (await loadAccessLookups()).getClientAccess(...args);- },+ validateSessionToken: checkSessionToken,+ getProjectAccess,+ getOrganizationAccess,+ getClientAccess,hashPassword,verifyPasswordHash,generateSessionToken,@@ -225,19 +268,10 @@ export function createAuthService(hashRecoveryCodes,normalizeRecoveryCode,consumeRecoveryCode,- setSessionTokenCookie: (- setCookie: ISetCookie,- token: string,- expiresAt: Date- ): void => setSessionTokenCookie(deps.config, setCookie, token, expiresAt),- setLastAuthProviderCookie: (- setCookie: ISetCookie,- provider: string- ): void => setLastAuthProviderCookie(deps.config, setCookie, provider),- deleteSessionTokenCookie: (setCookie: ISetCookie): void =>- deleteSessionTokenCookie(deps.config, setCookie),- parseCookieDomain: (url: string): ReturnType<typeof parseCookieDomain> =>- parseCookieDomain(deps.config, url),+ setSessionTokenCookie: setSessionCookie,+ setLastAuthProviderCookie: setAuthProviderCookie,+ deleteSessionTokenCookie: clearSessionCookie,+ parseCookieDomain: cookieDomainForUrl,};}diff --git a/packages/core/src/modules/auth/src/password.ts b/packages/core/src/modules/auth/src/password.tsindex b1b8c25ad..9b3377984 100644--- a/packages/core/src/modules/auth/src/password.ts+++ b/packages/core/src/modules/auth/src/password.ts@@ -1,6 +1,4 @@import { hash, verify } from '@node-rs/argon2';-import { sha1 } from '@oslojs/crypto/sha1';-import { encodeHexLowerCase } from '@oslojs/encoding';export async function hashPassword(password: string): Promise<string> {return await hash(password, {@@ -17,25 +15,3 @@ export async function verifyPasswordHash(): Promise<boolean> {return await verify(hash, password);}--export async function verifyPasswordStrength(- password: string-): Promise<boolean> {- if (password.length < 8 || password.length > 255) {- return false;- }- const hash = encodeHexLowerCase(sha1(new TextEncoder().encode(password)));- const hashPrefix = hash.slice(0, 5);- const response = await fetch(- `https://api.pwnedpasswords.com/range/${hashPrefix}`- );- const data = await response.text();- const items = data.split('\n');- for (const item of items) {- const hashSuffix = item.slice(0, 35).toLowerCase();- if (hash === hashPrefix + hashSuffix) {- return false;- }- }- return true;-}