Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): refund 1 credit for Alexandria feedback (#4980)
Nicolas8c9510ba7380
diff --git a/apps/api/src/__tests__/snips/v2/alexandria-feedback.test.ts b/apps/api/src/__tests__/snips/v2/alexandria-feedback.test.tsindex 226df7d6d..3b05afb50 100644--- a/apps/api/src/__tests__/snips/v2/alexandria-feedback.test.ts+++ b/apps/api/src/__tests__/snips/v2/alexandria-feedback.test.ts@@ -4,6 +4,7 @@ import { describeIf, TEST_API_URL, TEST_PRODUCTION } from "../lib";import { idmux, Identity } from "./lib";import { db } from "../../../db/connection";import * as schema from "../../../db/schema";+import { config } from "../../../config";const feedbackRows = async (feedbackId: string) => {const [[parent], providers, capabilities] = await Promise.all([@@ -55,10 +56,16 @@ describeIf(TEST_PRODUCTION)("Alexandria session feedback", () => {identity = await idmux({ name: "alexandria-feedback", credits: 1000 });});- it("records the minimum session feedback without any search or scrape job", async () => {+ // Billing confirms refunds, so environments without it report 0 credits.+ it("records the minimum session feedback without any search or scrape job and reports its refund", async () => {const response = await submit(body);expect(response.statusCode).toBe(200);- expect(response.body).toMatchObject({ success: true, creditsRefunded: 0 });+ expect(response.body).toMatchObject({+ success: true,+ creditsRefundedToday: expect.any(Number),+ dailyRefundCap: expect.any(Number),+ });+ expect([0, 1]).toContain(response.body.creditsRefunded);expect(response.body.feedbackId).toEqual(expect.any(String));try {const { parent, providers, capabilities } = await feedbackRows(@@ -76,6 +83,14 @@ describeIf(TEST_PRODUCTION)("Alexandria session feedback", () => {origin: "api",integration: null,schema_version: 2,+ credits_refunded: response.body.creditsRefunded,+ });+ expect(parent.refund_policy).toMatchObject({+ endpoint: "alexandria",+ matchedReason:+ response.body.creditsRefunded === 1+ ? "alexandria_feedback"+ : "refund_not_confirmed",});expect(providers).toEqual([]);expect(capabilities).toEqual([]);@@ -158,6 +173,54 @@ describeIf(TEST_PRODUCTION)("Alexandria session feedback", () => {}});+ it("stops refunding a website at its daily cap", async () => {+ const websiteCap = config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS;+ const website = {+ url: "https://www.usaspending.gov/search",+ requestedFunctionality: "List federal awards by recipient.",+ };+ const responses: request.Response[] = [];+ try {+ for (let i = 0; i <= websiteCap; i++) {+ responses.push(await submit({ ...body, requestedWebsite: website }));+ }+ for (const response of responses) {+ expect(response.statusCode).toBe(200);+ }+ const last = responses.at(-1)!;+ expect(last.body).toMatchObject({ success: true, creditsRefunded: 0 });+ const first = responses[0].body;+ if (first.creditsRefunded === 1) {+ // The team cap and earlier refunds today can stop refunds before the+ // website cap does.+ const teamRemaining =+ first.dailyRefundCap - (first.creditsRefundedToday - 1);+ const refunded = Math.min(websiteCap, teamRemaining);+ expect(responses.map(r => r.body.creditsRefunded)).toEqual([+ ...Array(refunded).fill(1),+ ...Array(websiteCap + 1 - refunded).fill(0),+ ]);+ if (websiteCap <= teamRemaining) {+ expect(last.body.websiteCapReached).toBe(true);+ }+ if (teamRemaining <= websiteCap) {+ expect(last.body.dailyCapReached).toBe(true);+ } else {+ expect(last.body.warning).toContain("www.usaspending.gov");+ }+ }+ const { parent } = await feedbackRows(last.body.feedbackId);+ expect(parent.credits_refunded).toBe(0);+ } finally {+ await Promise.all(+ responses+ .map(response => response.body.feedbackId)+ .filter(Boolean)+ .map(deleteFeedback),+ );+ }+ });+it.each(["endpoint", "rating", "requestedWebsite", "rationale"])("requires %s",async field => {diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex ea99bc37d..5df5a6bd9 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -222,6 +222,16 @@ const configSchema = z.object({FEEDBACK_MAX_AGE_SEC: z.coerce.number().int().positive().default(120),FEEDBACK_DAILY_CAP_CREDITS: z.coerce.number().int().nonnegative().default(50),FEEDBACK_REFUND_ENABLED: z.stringbool().default(true),+ ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS: z.coerce+ .number()+ .int()+ .nonnegative()+ .default(100),+ ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS: z.coerce+ .number()+ .int()+ .nonnegative()+ .default(10),// OAuth token introspectionOAUTH_INTROSPECT_URL: z.string().optional(),diff --git a/apps/api/src/controllers/v2/feedback/alexandria-refund.test.ts b/apps/api/src/controllers/v2/feedback/alexandria-refund.test.tsnew file mode 100644index 000000000..21804dcef--- /dev/null+++ b/apps/api/src/controllers/v2/feedback/alexandria-refund.test.ts@@ -0,0 +1,271 @@+import { PgDialect } from "drizzle-orm/pg-core";+import type { SQL } from "drizzle-orm";++const { mocks, updater } = vi.hoisted(() => {+ const mocks = {+ // Ordered log of lock, read, write, and billing calls.+ events: [] as string[],+ lock: vi.fn(),+ todayRows: vi.fn(),+ update: vi.fn(),+ refundCredits: vi.fn(),+ logError: vi.fn(),+ };+ const updater = (scope: string) => () => ({+ set: (values: Record<string, unknown>) => ({+ where: () => {+ mocks.events.push(`${scope}:update:${values.credits_refunded}`);+ return mocks.update(values);+ },+ }),+ });+ return { mocks, updater };+});+vi.mock("../../../db/connection", () => ({+ db: {+ transaction: async (run: (tx: unknown) => Promise<unknown>) =>+ run({+ execute: (query: unknown) => {+ mocks.events.push("tx:lock");+ return mocks.lock(query);+ },+ select: () => ({+ from: () => ({+ where: () => {+ mocks.events.push("tx:select");+ return mocks.todayRows();+ },+ }),+ }),+ update: updater("tx"),+ }),+ update: updater("db"),+ },+}));+vi.mock("../../../services/autumn/autumn.service", () => ({+ CREDITS_FEATURE_ID: "CREDITS",+ autumnService: {+ refundCredits: (params: unknown) => {+ mocks.events.push("billing");+ return mocks.refundCredits(params);+ },+ },+}));+vi.mock("../../../lib/logger", () => {+ const child = { info: vi.fn(), warn: vi.fn(), error: mocks.logError };+ return { logger: { child: () => child } };+});++import { config } from "../../../config";+import { refundAlexandriaFeedback } from "./alexandria-refund";++const teamId = "01933161-0000-7000-8000-000000000001";+const now = new Date("2026-10-06T18:00:00.000Z");+const original = {+ enabled: config.FEEDBACK_REFUND_ENABLED,+ cap: config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS,+ websiteCap: config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS,+};+const refund = (overrides: { orgId?: string | null; url?: string } = {}) =>+ refundAlexandriaFeedback({+ feedbackId: "feedback-1",+ teamId,+ orgId: overrides.orgId === undefined ? "org-1" : overrides.orgId,+ rating: "partial",+ requestedUrl: overrides.url ?? "https://SAM.gov/contracts",+ now,+ });+const persisted = () => mocks.update.mock.calls.at(-1)?.[0];++beforeEach(() => {+ vi.clearAllMocks();+ mocks.events.length = 0;+ config.FEEDBACK_REFUND_ENABLED = true;+ config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS = 10;+ config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS = 3;+ mocks.lock.mockResolvedValue(undefined);+ mocks.todayRows.mockResolvedValue([]);+ mocks.update.mockResolvedValue(undefined);+ mocks.refundCredits.mockResolvedValue(true);+});+afterAll(() => {+ config.FEEDBACK_REFUND_ENABLED = original.enabled;+ config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS = original.cap;+ config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS = original.websiteCap;+});++it("reserves the refund under a per-team lock before billing, then reports it", async () => {+ mocks.todayRows.mockResolvedValue([+ { requested_host: "data.gov", credits_refunded: 1 },+ ]);+ await expect(refund()).resolves.toEqual({+ creditsRefunded: 1,+ creditsRefundedToday: 2,+ dailyRefundCap: 10,+ });+ expect(mocks.events).toEqual([+ "tx:lock",+ "tx:select",+ "tx:update:1",+ "billing",+ ]);+ const lock = new PgDialect().sqlToQuery(mocks.lock.mock.calls[0][0] as SQL);+ expect(lock.sql).toBe(+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",+ );+ expect(lock.params).toEqual([`alexandria_feedback_refund:${teamId}`]);+ expect(mocks.refundCredits).toHaveBeenCalledExactlyOnceWith({+ teamId,+ orgId: "org-1",+ value: 1,+ idempotencyKey: "fc:refund:alexandria-feedback:feedback-1",+ featureId: "CREDITS",+ properties: {+ source: "feedback",+ endpoint: "alexandria",+ feedbackId: "feedback-1",+ rating: "partial",+ refundPolicy: "alexandria_feedback",+ },+ });+ expect(persisted()).toEqual({+ credits_refunded: 1,+ refund_policy: {+ version: "feedback_refund_v1",+ enabled: true,+ endpoint: "alexandria",+ mode: "flat",+ refundableRatings: ["good", "partial", "bad"],+ matchedReason: "alexandria_feedback",+ flatCredits: 1,+ maxCredits: 1,+ },+ updated_at: expect.any(String),+ });+});++it("keeps refunding the same website until its daily cap", async () => {+ mocks.todayRows.mockResolvedValue([+ { requested_host: "sam.gov", credits_refunded: 1 },+ { requested_host: "data.gov", credits_refunded: 1 },+ ]);+ await expect(refund()).resolves.toEqual({+ creditsRefunded: 1,+ creditsRefundedToday: 3,+ dailyRefundCap: 10,+ });+});++it("flags the website cap on the refund that fills it", async () => {+ mocks.todayRows.mockResolvedValue([+ { requested_host: "sam.gov", credits_refunded: 1 },+ { requested_host: "sam.gov", credits_refunded: 1 },+ ]);+ const result = await refund();+ expect(result).toMatchObject({+ creditsRefunded: 1,+ websiteCapReached: true,+ warning: expect.stringContaining("sam.gov"),+ });+ expect(result.dailyCapReached).toBeUndefined();+});++it("stops refunding a website at its daily cap, while other websites still refund", async () => {+ mocks.todayRows.mockResolvedValue([+ { requested_host: "sam.gov", credits_refunded: 1 },+ { requested_host: "sam.gov", credits_refunded: 1 },+ { requested_host: "sam.gov", credits_refunded: 1 },+ ]);+ const result = await refund({ url: "https://[email protected]:443/other" });+ expect(result).toMatchObject({+ creditsRefunded: 0,+ creditsRefundedToday: 3,+ websiteCapReached: true,+ warning: expect.stringContaining("sam.gov"),+ });+ expect(result.dailyCapReached).toBeUndefined();+ expect(mocks.events).toEqual(["tx:lock", "tx:select", "tx:update:0"]);+ expect(persisted()).toMatchObject({+ credits_refunded: 0,+ refund_policy: { mode: "none", matchedReason: "website_cap_reached" },+ });++ mocks.events.length = 0;+ await expect(refund({ url: "https://data.gov" })).resolves.toMatchObject({+ creditsRefunded: 1,+ creditsRefundedToday: 4,+ });+});++it("stops refunding at the daily Alexandria cap", async () => {+ config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS = 2;+ mocks.todayRows.mockResolvedValue([+ { requested_host: "a.example", credits_refunded: 1 },+ { requested_host: "b.example", credits_refunded: 1 },+ ]);+ const result = await refund();+ expect(result).toMatchObject({+ creditsRefunded: 0,+ creditsRefundedToday: 2,+ dailyRefundCap: 2,+ dailyCapReached: true,+ });+ expect(mocks.events).not.toContain("billing");+ expect(persisted()).toMatchObject({+ refund_policy: { matchedReason: "daily_cap_reached" },+ });+});++it("flags the cap as reached on the refund that fills it", async () => {+ config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS = 1;+ await expect(refund()).resolves.toMatchObject({+ creditsRefunded: 1,+ creditsRefundedToday: 1,+ dailyCapReached: true,+ });+});++it("records no refund when refunds are disabled", async () => {+ config.FEEDBACK_REFUND_ENABLED = false;+ await expect(refund()).resolves.toMatchObject({ creditsRefunded: 0 });+ expect(mocks.events).toEqual(["db:update:0"]);+ expect(persisted()).toMatchObject({+ refund_policy: { enabled: false, matchedReason: "refunds_disabled" },+ });+});++it("does not refund when the reservation fails", async () => {+ mocks.todayRows.mockRejectedValue(new Error("db unavailable"));+ await expect(refund()).resolves.toMatchObject({ creditsRefunded: 0 });+ expect(mocks.events).toEqual(["tx:lock", "tx:select", "db:update:0"]);+ expect(persisted()).toMatchObject({+ refund_policy: { matchedReason: "refund_totals_unavailable" },+ });+});++it.each([+ ["billing does not confirm", { orgId: "org-1", billed: false }],+ ["the team has no org", { orgId: null, billed: true }],+])("reports and keeps 0 credits when %s", async (_case, { orgId, billed }) => {+ mocks.refundCredits.mockResolvedValue(billed);+ const result = await refund({ orgId });+ expect(result).toMatchObject({+ creditsRefunded: 0,+ creditsRefundedToday: 0,+ });+ expect(result.dailyCapReached).toBeUndefined();+ expect(mocks.events.at(-1)).toBe("db:update:0");+ expect(persisted()).toMatchObject({+ credits_refunded: 0,+ refund_policy: { matchedReason: "refund_not_confirmed" },+ });+ if (orgId === null) expect(mocks.refundCredits).not.toHaveBeenCalled();+});++it("does not throw when resetting an unconfirmed refund fails", async () => {+ mocks.refundCredits.mockResolvedValue(false);+ mocks.update+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("write failed"));+ await expect(refund()).resolves.toMatchObject({ creditsRefunded: 0 });+});diff --git a/apps/api/src/controllers/v2/feedback/alexandria-refund.ts b/apps/api/src/controllers/v2/feedback/alexandria-refund.tsnew file mode 100644index 000000000..e8e18607b--- /dev/null+++ b/apps/api/src/controllers/v2/feedback/alexandria-refund.ts@@ -0,0 +1,267 @@+import { and, eq, gt, gte, sql } from "drizzle-orm";+import { config } from "../../../config";+import { db } from "../../../db/connection";+import * as schema from "../../../db/schema";+import { logger as _logger } from "../../../lib/logger";+import {+ autumnService,+ CREDITS_FEATURE_ID,+} from "../../../services/autumn/autumn.service";+import type { FeedbackRating, RefundPolicySnapshot } from "./internal-types";++const REFUND_CREDITS = 1;+const REFUNDABLE_RATINGS: FeedbackRating[] = ["good", "partial", "bad"];++type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];++type RefundOutcome =+ | "alexandria_feedback"+ | "refunds_disabled"+ | "refund_totals_unavailable"+ | "website_cap_reached"+ | "daily_cap_reached"+ | "refund_not_confirmed";++type AlexandriaRefundResult = {+ creditsRefunded: number;+ creditsRefundedToday: number;+ dailyRefundCap: number;+ dailyCapReached?: boolean;+ websiteCapReached?: boolean;+ warning?: string;+};++function startOfUtcDay(now: Date): Date {+ const start = new Date(now.getTime());+ start.setUTCHours(0, 0, 0, 0);+ return start;+}++function policyFor(outcome: RefundOutcome): RefundPolicySnapshot {+ const refunds = outcome === "alexandria_feedback";+ return {+ version: "feedback_refund_v1",+ enabled: config.FEEDBACK_REFUND_ENABLED,+ endpoint: "alexandria",+ mode: refunds ? "flat" : "none",+ refundableRatings: REFUNDABLE_RATINGS,+ matchedReason: outcome,+ ...(refunds+ ? { flatCredits: REFUND_CREDITS, maxCredits: REFUND_CREDITS }+ : {}),+ };+}++function refundWrite(feedbackId: string, outcome: RefundOutcome) {+ return {+ values: {+ credits_refunded: outcome === "alexandria_feedback" ? REFUND_CREDITS : 0,+ refund_policy: policyFor(outcome),+ updated_at: new Date().toISOString(),+ },+ where: eq(schema.alexandria_feedback.id, feedbackId),+ };+}++async function refundsToday(+ tx: Tx,+ teamId: string,+ now: Date,+): Promise<{ total: number; byHost: Map<string, number> }> {+ const rows = await tx+ .select({+ requested_host: schema.alexandria_feedback.requested_host,+ credits_refunded: schema.alexandria_feedback.credits_refunded,+ })+ .from(schema.alexandria_feedback)+ .where(+ and(+ eq(schema.alexandria_feedback.team_id, teamId),+ gte(+ schema.alexandria_feedback.created_at,+ startOfUtcDay(now).toISOString(),+ ),+ gt(schema.alexandria_feedback.credits_refunded, 0),+ ),+ );+ let total = 0;+ const byHost = new Map<string, number>();+ for (const row of rows) {+ const credits = row.credits_refunded ?? 0;+ total += credits;+ if (row.requested_host) {+ byHost.set(+ row.requested_host,+ (byHost.get(row.requested_host) ?? 0) + credits,+ );+ }+ }+ return { total, byHost };+}++/**+ * Decides the refund and, when it is granted, reserves it on the feedback row.+ * The per-team lock serializes concurrent submissions so both daily caps hold.+ */+async function reserveRefund(params: {+ feedbackId: string;+ teamId: string;+ host: string;+ dailyRefundCap: number;+ websiteRefundCap: number;+ now: Date;+}): Promise<{+ outcome: RefundOutcome;+ refundedTodayBefore: number;+ websiteRefundedBefore: number;+}> {+ const { feedbackId, teamId, host, dailyRefundCap, websiteRefundCap, now } =+ params;+ return db.transaction(async tx => {+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(hashtextextended(${`alexandria_feedback_refund:${teamId}`}, 0))`,+ );+ const today = await refundsToday(tx, teamId, now);+ const websiteRefundedBefore = today.byHost.get(host) ?? 0;+ const outcome: RefundOutcome =+ today.total + REFUND_CREDITS > dailyRefundCap+ ? "daily_cap_reached"+ : websiteRefundedBefore + REFUND_CREDITS > websiteRefundCap+ ? "website_cap_reached"+ : "alexandria_feedback";+ const write = refundWrite(feedbackId, outcome);+ await tx+ .update(schema.alexandria_feedback)+ .set(write.values)+ .where(write.where);+ return { outcome, refundedTodayBefore: today.total, websiteRefundedBefore };+ });+}++/**+ * Refunds 1 credit for a recorded Alexandria feedback row, within the team's+ * daily cap and the per-website daily cap (both per UTC day). Reports a refund+ * only when billing confirms it. Never throws.+ */+export async function refundAlexandriaFeedback(params: {+ feedbackId: string;+ teamId: string;+ orgId: string | null;+ rating: FeedbackRating;+ requestedUrl: string;+ now?: Date;+}): Promise<AlexandriaRefundResult> {+ const { feedbackId, teamId, orgId, rating } = params;+ const now = params.now ?? new Date();+ const dailyRefundCap = config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS;+ const websiteRefundCap = config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS;+ const host = new URL(params.requestedUrl).hostname.toLowerCase();+ const logger = _logger.child({+ module: "api/v2",+ method: "refundAlexandriaFeedback",+ feedbackId,+ teamId,+ });++ const persist = async (outcome: RefundOutcome) => {+ const write = refundWrite(feedbackId, outcome);+ try {+ await db+ .update(schema.alexandria_feedback)+ .set(write.values)+ .where(write.where);+ } catch (error) {+ logger.warn("Failed to persist Alexandria feedback refund details", {+ error,+ refundPolicy: outcome,+ });+ }+ };++ let outcome: RefundOutcome;+ let refundedTodayBefore = 0;+ let websiteRefundedBefore = 0;+ if (!config.FEEDBACK_REFUND_ENABLED) {+ outcome = "refunds_disabled";+ await persist(outcome);+ } else {+ try {+ ({ outcome, refundedTodayBefore, websiteRefundedBefore } =+ await reserveRefund({+ feedbackId,+ teamId,+ host,+ dailyRefundCap,+ websiteRefundCap,+ now,+ }));+ } catch (error) {+ logger.warn("Failed to reserve Alexandria feedback refund; no refund", {+ error,+ });+ outcome = "refund_totals_unavailable";+ await persist(outcome);+ }+ }++ if (outcome === "alexandria_feedback") {+ const confirmed =+ orgId !== null &&+ (await autumnService.refundCredits({+ teamId,+ orgId,+ value: REFUND_CREDITS,+ idempotencyKey: `fc:refund:alexandria-feedback:${feedbackId}`,+ featureId: CREDITS_FEATURE_ID,+ properties: {+ source: "feedback",+ endpoint: "alexandria",+ feedbackId,+ rating,+ refundPolicy: outcome,+ },+ }));+ if (!confirmed) {+ logger.warn("Alexandria feedback refund not confirmed by billing", {+ hasOrg: orgId !== null,+ });+ outcome = "refund_not_confirmed";+ await persist(outcome);+ }+ }++ const creditsRefunded =+ outcome === "alexandria_feedback" ? REFUND_CREDITS : 0;+ const creditsRefundedToday = refundedTodayBefore + creditsRefunded;+ const dailyCapReached =+ outcome === "daily_cap_reached" ||+ (dailyRefundCap > 0 && creditsRefundedToday >= dailyRefundCap);+ const websiteCapReached =+ outcome === "website_cap_reached" ||+ (websiteRefundCap > 0 &&+ websiteRefundedBefore + creditsRefunded >= websiteRefundCap);+ logger.info("Alexandria feedback refund processed", {+ creditsRefunded,+ refundPolicy: outcome,+ creditsRefundedToday,+ dailyRefundCap,+ websiteRefundCap,+ });++ return {+ creditsRefunded,+ creditsRefundedToday,+ dailyRefundCap,+ ...(dailyCapReached ? { dailyCapReached: true } : {}),+ ...(websiteCapReached ? { websiteCapReached: true } : {}),+ ...(dailyCapReached+ ? {+ warning: `Daily Alexandria feedback refund cap of ${dailyRefundCap} credits reached for this team (UTC day). Feedback was recorded; further Alexandria feedback today will not refund credits.`,+ }+ : websiteCapReached+ ? {+ warning: `Daily refund cap of ${websiteRefundCap} credits reached for Alexandria feedback about ${host} (UTC day). Feedback was recorded; further feedback about this website today will not refund credits.`,+ }+ : {}),+ };+}diff --git a/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts b/apps/api/src/controllers/v2/feedback/alexandria.integration.test.tsindex 2adb76b6d..ba32e554b 100644--- a/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts+++ b/apps/api/src/controllers/v2/feedback/alexandria.integration.test.ts@@ -13,6 +13,10 @@ vi.mock("./record", () => ({throw new Error("Alexandria must not enter the job/refund path");},}));+vi.mock("../../../services/autumn/autumn.service", () => ({+ CREDITS_FEATURE_ID: "CREDITS",+ autumnService: { refundCredits: async () => true },+}));// Opt in with a local PostgreSQL database. Each run owns an isolated schema// holding a copy of the Alexandria feedback tables, including constraints.@@ -32,7 +36,10 @@ CREATE TABLE alexandria_feedback (origin text,integration text,schema_version integer NOT NULL DEFAULT 2,- created_at timestamptz NOT NULL DEFAULT now()+ credits_refunded integer NOT NULL DEFAULT 0 CHECK (credits_refunded >= 0),+ refund_policy jsonb,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now());CREATE TABLE alexandria_feedback_providers (id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,@@ -122,16 +129,42 @@ suite("Alexandria feedback HTTP and PostgreSQL persistence", () => {});it("persists the minimum payload and independent sessions without inventing job IDs", async () => {- const first = await submit(minimal);- const second = await submit(minimal);+ const websiteCap = config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS;+ config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS = 1;+ let first: request.Response;+ let second: request.Response;+ try {+ first = await submit(minimal);+ second = await submit(minimal);+ } finally {+ config.ALEXANDRIA_FEEDBACK_WEBSITE_DAILY_CAP_CREDITS = websiteCap;+ }expect(first.status).toBe(200);expect(second.status).toBe(200);expect(second.body.feedbackId).not.toBe(first.body.feedbackId);+ expect(first.body).toMatchObject({+ creditsRefunded: 1,+ creditsRefundedToday: 1,+ });+ expect(second.body).toMatchObject({+ creditsRefunded: 0,+ creditsRefundedToday: 1,+ websiteCapReached: true,+ });const { rows } = await pool.query(- "SELECT * FROM alexandria_feedback WHERE team_id = $1",+ "SELECT * FROM alexandria_feedback WHERE team_id = $1 ORDER BY credits_refunded DESC",[teamId],);expect(rows).toHaveLength(2);+ expect(rows.map(row => row.id)).toEqual([+ first.body.feedbackId,+ second.body.feedbackId,+ ]);+ expect(rows.map(row => row.credits_refunded)).toEqual([1, 0]);+ expect(rows.map(row => row.refund_policy.matchedReason)).toEqual([+ "alexandria_feedback",+ "website_cap_reached",+ ]);for (const row of rows) {expect(row).toMatchObject({team_id: teamId,diff --git a/apps/api/src/controllers/v2/feedback/alexandria.test.ts b/apps/api/src/controllers/v2/feedback/alexandria.test.tsindex d9648d691..25293118b 100644--- a/apps/api/src/controllers/v2/feedback/alexandria.test.ts+++ b/apps/api/src/controllers/v2/feedback/alexandria.test.ts@@ -9,8 +9,12 @@ const mocks = vi.hoisted(() => ({// Receives (tableName, rows[]) for every insert issued inside the transaction.insert: vi.fn(),recordEndpointFeedback: vi.fn(),+ refundAlexandriaFeedback: vi.fn(),logError: vi.fn(),}));+vi.mock("./alexandria-refund", () => ({+ refundAlexandriaFeedback: mocks.refundAlexandriaFeedback,+}));vi.mock("../../../db/connection", () => ({db: { transaction: mocks.transaction },}));@@ -58,7 +62,7 @@ app.use(express.json());app.use((req, _res, next) => {Object.assign(req, {auth: { team_id: authTeam },- acuc: { api_key_id: 42, flags },+ acuc: { api_key_id: 42, org_id: "org-1", flags },});next();});@@ -74,23 +78,37 @@ beforeEach(() => {async (run: (tx: unknown) => Promise<void>) => run(tx),);mocks.insert.mockResolvedValue(undefined);+ mocks.refundAlexandriaFeedback.mockResolvedValue({+ creditsRefunded: 1,+ creditsRefundedToday: 1,+ dailyRefundCap: 10,+ });});afterAll(() => {config.USE_DB_AUTHENTICATION = originalDbAuthentication;});it.each(["good", "partial", "bad"])(- "records a %s session without job lookup or refund",+ "records a %s session without job lookup and refunds it",async rating => {const response = await submit({ ...minimal, rating });expect(response.status).toBe(200);expect(response.body).toEqual({success: true,feedbackId: expect.any(String),- creditsRefunded: 0,+ creditsRefunded: 1,+ creditsRefundedToday: 1,+ dailyRefundCap: 10,});expect(mocks.recordEndpointFeedback).not.toHaveBeenCalled();expect(mocks.transaction).toHaveBeenCalledTimes(1);+ expect(mocks.refundAlexandriaFeedback).toHaveBeenCalledExactlyOnceWith({+ feedbackId: response.body.feedbackId,+ teamId,+ orgId: "org-1",+ rating,+ requestedUrl: minimal.requestedWebsite.url,+ });expect(parentRows()).toEqual([{id: response.body.feedbackId,@@ -585,7 +603,27 @@ it.each([const response = await submit(minimal);expect(response.status).toBe(200);expect(response.body.feedbackId).toBe("00000000-0000-0000-0000-000000000000");+ expect(response.body.creditsRefunded).toBe(0);expect(mocks.transaction).not.toHaveBeenCalled();+ expect(mocks.refundAlexandriaFeedback).not.toHaveBeenCalled();+});++it("returns the refund outcome, including cap and duplicate warnings", async () => {+ const outcome = {+ creditsRefunded: 0,+ creditsRefundedToday: 10,+ dailyRefundCap: 10,+ dailyCapReached: true,+ warning: "Daily Alexandria feedback refund cap reached.",+ };+ mocks.refundAlexandriaFeedback.mockResolvedValueOnce(outcome);+ const response = await submit(minimal);+ expect(response.status).toBe(200);+ expect(response.body).toEqual({+ success: true,+ feedbackId: expect.any(String),+ ...outcome,+ });});it("honors team opt-out", async () => {@@ -594,6 +632,7 @@ it("honors team opt-out", async () => {expect(response.status).toBe(403);expect(response.body.feedbackErrorCode).toBe("TEAM_OPTED_OUT");expect(mocks.transaction).not.toHaveBeenCalled();+ expect(mocks.refundAlexandriaFeedback).not.toHaveBeenCalled();});it.each(["preview", "preview_example", "preview_keyless_example"])(@@ -644,6 +683,7 @@ it.each([);expect(JSON.stringify(mocks.logError.mock.calls)).not.toContain("sensitive");expect(mocks.recordEndpointFeedback).not.toHaveBeenCalled();+ expect(mocks.refundAlexandriaFeedback).not.toHaveBeenCalled();});it.each(["search", "scrape", "parse", "map"])(diff --git a/apps/api/src/controllers/v2/feedback/alexandria.ts b/apps/api/src/controllers/v2/feedback/alexandria.tsindex 4881fa3fe..4193e85c0 100644--- a/apps/api/src/controllers/v2/feedback/alexandria.ts+++ b/apps/api/src/controllers/v2/feedback/alexandria.ts@@ -8,6 +8,7 @@ import { getScrapeZDR, getSearchZDR } from "../../../lib/zdr-helpers";import type { RequestWithAuth, EndpointFeedbackErrorCode } from "../types";import type { FeedbackRecordResult } from "./internal-types";import type { AlexandriaFeedbackRequest } from "./alexandria-schema";+import { refundAlexandriaFeedback } from "./alexandria-refund";const failure = (status: number,@@ -59,6 +60,8 @@ export async function recordAlexandriaFeedback(success: true,feedbackId: "00000000-0000-0000-0000-000000000000",creditsRefunded: 0,+ creditsRefundedToday: 0,+ dailyRefundCap: config.ALEXANDRIA_FEEDBACK_DAILY_CAP_CREDITS,},};}@@ -126,8 +129,15 @@ export async function recordAlexandriaFeedback(});return failure(500, "INTERNAL", "Failed to record feedback.");}+ const refund = await refundAlexandriaFeedback({+ feedbackId,+ teamId,+ orgId: req.acuc?.org_id ?? null,+ rating: body.rating,+ requestedUrl: body.requestedWebsite.url,+ });return {status: 200,- body: { success: true, feedbackId, creditsRefunded: 0 },+ body: { success: true, feedbackId, ...refund },};}diff --git a/apps/api/src/controllers/v2/feedback/feedback-window.test.ts b/apps/api/src/controllers/v2/feedback/feedback-window.test.tsindex 489634064..b9a10244a 100644--- a/apps/api/src/controllers/v2/feedback/feedback-window.test.ts+++ b/apps/api/src/controllers/v2/feedback/feedback-window.test.ts@@ -28,6 +28,13 @@ vi.mock("../../../db/connection", () => ({vi.mock("./refund-totals", () => ({sumCreditsRefundedToday: fixture.refundedToday,}));+vi.mock("./alexandria-refund", () => ({+ refundAlexandriaFeedback: async () => ({+ creditsRefunded: 1,+ creditsRefundedToday: 1,+ dailyRefundCap: 10,+ }),+}));vi.mock("../../../services/autumn/autumn.service", () => ({SEARCH_CREDITS_FEATURE_ID: "SEARCH_CREDITS",featureIdForBillingEndpoint: (endpoint: string) =>@@ -192,7 +199,9 @@ it.each(stores)(expect(response.body).toEqual({success: true,feedbackId: expect.any(String),- creditsRefunded: 0,+ creditsRefunded: 1,+ creditsRefundedToday: 1,+ dailyRefundCap: 10,});expect(fixture.lookup).not.toHaveBeenCalled();expect(fixture.insert).not.toHaveBeenCalled();diff --git a/apps/api/src/controllers/v2/feedback/internal-types.ts b/apps/api/src/controllers/v2/feedback/internal-types.tsindex c2e9e1446..b9b196c4c 100644--- a/apps/api/src/controllers/v2/feedback/internal-types.ts+++ b/apps/api/src/controllers/v2/feedback/internal-types.ts@@ -62,7 +62,7 @@ export type FeedbackRecordResult = {export type RefundPolicySnapshot = {version: "feedback_refund_v1";enabled: boolean;- endpoint: EndpointFeedbackEndpoint;+ endpoint: EndpointFeedbackEndpoint | "alexandria";mode: "none" | "flat" | "percentage_with_cap";refundableRatings: FeedbackRating[];matchedReason: string;diff --git a/apps/api/src/controllers/v2/types.ts b/apps/api/src/controllers/v2/types.tsindex c4a202ef4..bb7a3537e 100644--- a/apps/api/src/controllers/v2/types.ts+++ b/apps/api/src/controllers/v2/types.ts@@ -2953,6 +2953,7 @@ export type EndpointFeedbackResponse =creditsRefunded: number;alreadySubmitted?: boolean;dailyCapReached?: boolean;+ websiteCapReached?: boolean;creditsRefundedToday?: number;dailyRefundCap?: number;warning?: string;diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.tsindex 5525ff708..569fdb273 100644--- a/apps/api/src/db/schema/public.ts+++ b/apps/api/src/db/schema/public.ts@@ -681,9 +681,16 @@ export const alexandria_feedback = pgTable(origin: text("origin"),integration: text("integration"),schema_version: integer("schema_version").notNull().default(2),+ credits_refunded: integer("credits_refunded").notNull().default(0),+ refund_policy: jsonb("refund_policy"),created_at: ts("created_at").notNull().defaultNow(),+ updated_at: ts("updated_at").notNull().defaultNow(),},table => [+ check(+ "alexandria_feedback_credits_refunded_check",+ sql`${table.credits_refunded} >= 0`,+ ),check("alexandria_feedback_rating_check",sql`${table.rating} IN ('good', 'partial', 'bad')`,diff --git a/apps/api/src/services/autumn/autumn.service.ts b/apps/api/src/services/autumn/autumn.service.tsindex 3fb1882ca..c94186989 100644--- a/apps/api/src/services/autumn/autumn.service.ts+++ b/apps/api/src/services/autumn/autumn.service.ts@@ -876,6 +876,7 @@ export class AutumnService {/*** Reverses a prior trackCredits call by tracking a negative usage event.+ * Never throws; resolves true only when billing accepted the refund.*/async refundCredits({teamId,@@ -885,16 +886,16 @@ export class AutumnService {idempotencyKey,externalRequestId,orgId,- }: TrackCreditsParams): Promise<void> {- if (!autumnClient) return;- if (this.isPreviewTeam(teamId)) return;+ }: TrackCreditsParams): Promise<boolean> {+ if (!autumnClient) return false;+ if (this.isPreviewTeam(teamId)) return false;try {const { customerId, routed } = await this.resolveBillingRoute(teamId,orgId,);- await this.track(+ return await this.track({customerId,entityId: teamId,@@ -911,6 +912,7 @@ export class AutumnService {"Autumn refundCredits failed — billing API may be unavailable",{ teamId, value, error },);+ return false;}}}