Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 9 additions & 19 deletions app/api/hellenistic/ask-seer/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
buildHellenisticState,
classifyHellenisticQuestion,
getHellenisticSliceForQuestionType,
type HellenisticQuestionType,

Check warning on line 10 in app/api/hellenistic/ask-seer/route.ts

View workflow job for this annotation

GitHub Actions / Lint + Jest

'HellenisticQuestionType' is defined but never used
} from '@/lib/hellenisticSeerState';
import { buildHellenisticSeerSystemPrompt } from '@/lib/hellenisticSeerPrompts';
import { GROQ_DEFAULT_TEXT_MODEL } from '@/lib/groqModels';
Expand All @@ -17,8 +17,8 @@
interface HellenisticSeerRequest {
userId: string;
question: string;
userProfile: any;

Check warning on line 20 in app/api/hellenistic/ask-seer/route.ts

View workflow job for this annotation

GitHub Actions / Lint + Jest

Unexpected any. Specify a different type
hellenisticContext?: any;

Check warning on line 21 in app/api/hellenistic/ask-seer/route.ts

View workflow job for this annotation

GitHub Actions / Lint + Jest

Unexpected any. Specify a different type
sessionId?: string;
}

Expand All @@ -28,26 +28,16 @@
export async function POST(request: NextRequest) {
try {
const body = (await request.json()) as HellenisticSeerRequest;
const __toolSeerGate = await enforceToolSeerGate(request, body, 'hellenistic_ask_seer');
const { userId, question, hellenisticContext } = body;
const missingContextError = !question || !question.trim()
? 'Question is required'
: !hellenisticContext
? 'Missing Hellenistic chart data. Please generate a reading first.'
: null;
const __toolSeerGate = await enforceToolSeerGate(request, body, 'hellenistic_ask_seer', {
missingContextError,
});
if (__toolSeerGate) return __toolSeerGate;
const { userId, question, userProfile, hellenisticContext, sessionId } = body;

if (!question || !question.trim()) {
return NextResponse.json(
{ success: false, error: 'Question is required' },
{ status: 400 }
);
}

if (!hellenisticContext) {
return NextResponse.json(
{
success: false,
error: 'Missing Hellenistic chart data. Please generate a reading first.',
},
{ status: 400 }
);
}

devLog.info('🔮 Hellenistic Seer API: Processing question for user:', userId, 'ask-hellenistic-seer');

Expand Down Expand Up @@ -123,7 +113,7 @@
},
}
);
} catch (error: any) {

Check warning on line 116 in app/api/hellenistic/ask-seer/route.ts

View workflow job for this annotation

GitHub Actions / Lint + Jest

Unexpected any. Specify a different type
devLog.error('Hellenistic Seer API error:', error);
return NextResponse.json(
{
Expand Down
17 changes: 17 additions & 0 deletions lib/enforceToolSeerGate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ export interface EnforceToolSeerGateOptions {
* - json: JSON body (e.g. medical-seer)
*/
blockedResponseFormat?: ToolSeerBlockedResponseFormat;
/**
* Route-specific required context (chart, reading, profile payload).
* When set, the gate returns 400 **before** rate-limit and billing so PAYG
* users are not charged for a question the tool cannot answer yet.
*/
missingContextError?: string | null;
}

/** Extract trimmed `question` from a tool Seer POST body. */
Expand Down Expand Up @@ -90,6 +96,17 @@ export async function enforceToolSeerGate(
rateUid = auth.uid;
}

const missingContextError =
typeof options?.missingContextError === 'string' ? options.missingContextError.trim() : '';
if (missingContextError) {
const res = NextResponse.json(
{ success: false, error: missingContextError },
{ status: 400 },
);
res.headers.set('X-Robots-Tag', 'noindex, nofollow, noarchive, nosnippet');
return res;
}

const rl = await checkRateLimitWithOptionalFirestore(
rateLimiters.ai,
`tool_seer_${routeLogicalKey}`,
Expand Down
51 changes: 51 additions & 0 deletions tests/unit/enforceToolSeerGate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
extractToolSeerQuestion,
} from '@/lib/enforceToolSeerGate';
import { SEER_INPUT_BLOCKED_MESSAGE } from '@/lib/seerInputGuard';
import { consumeBillingAction } from '@/lib/billingCreditsServer';

jest.mock('@/lib/userApiAuth', () => ({
verifyUserRequest: jest.fn(async () => ({ ok: true, uid: 'user-1' })),
Expand All @@ -27,6 +28,20 @@ jest.mock('@/lib/aiAuditEvents', () => ({
recordAiAuditEvent: jest.fn(),
}));

jest.mock('@/lib/billingCreditsServer', () => ({
consumeBillingAction: jest.fn(async () => ({
ok: true,
charged: true,
creditsCharged: 1,
creditBalance: 9,
usedFreeInstance: false,
})),
}));

const consumeBillingActionMock = consumeBillingAction as jest.MockedFunction<
typeof consumeBillingAction
>;

describe('enforceToolSeerGate', () => {
function post(body: Record<string, unknown>) {
return new NextRequest('http://localhost/api/ask-tarot-seer', {
Expand All @@ -36,6 +51,10 @@ describe('enforceToolSeerGate', () => {
});
}

beforeEach(() => {
consumeBillingActionMock.mockClear();
});

it('extractToolSeerQuestion trims question field', () => {
expect(extractToolSeerQuestion({ question: ' hello ' })).toBe('hello');
expect(extractToolSeerQuestion({})).toBe('');
Expand All @@ -55,6 +74,7 @@ describe('enforceToolSeerGate', () => {
expect(res!.headers.get('Content-Type')).toBe('text/event-stream');
const text = await res!.text();
expect(text).toBe(SEER_INPUT_BLOCKED_MESSAGE);
expect(consumeBillingActionMock).not.toHaveBeenCalled();
});

it('returns JSON when blockedResponseFormat is json', async () => {
Expand All @@ -70,6 +90,7 @@ describe('enforceToolSeerGate', () => {
const data = await res!.json();
expect(data.inputBlocked).toBe(true);
expect(data.response).toBe(SEER_INPUT_BLOCKED_MESSAGE);
expect(consumeBillingActionMock).not.toHaveBeenCalled();
});

it('passes through when question is empty (route handles 400)', async () => {
Expand All @@ -88,5 +109,35 @@ describe('enforceToolSeerGate', () => {
'ask_tarot_seer',
);
expect(res).toBeNull();
expect(consumeBillingActionMock).toHaveBeenCalledTimes(1);
});

it('rejects missing Hellenistic chart context before debiting credits', async () => {
const res = await enforceToolSeerGate(
post({
userId: 'user-1',
question: 'Which areas of my life are most active?',
userProfile: { displayName: 'Ada' },
hellenisticContext: null,
}),
{
userId: 'user-1',
question: 'Which areas of my life are most active?',
userProfile: { displayName: 'Ada' },
hellenisticContext: null,
},
'hellenistic_ask_seer',
{
missingContextError:
'Missing Hellenistic chart data. Please generate a reading first.',
},
);

expect(res).not.toBeNull();
expect(res!.status).toBe(400);
const data = await res!.json();
expect(data.success).toBe(false);
expect(data.error).toMatch(/Hellenistic chart data/);
expect(consumeBillingActionMock).not.toHaveBeenCalled();
});
});
Loading