fix(supabase): funkcje Edge wysyłające umowy do Gemini usunięte z repo (Z-05b)
analyze-contract, review-clause i _shared znikają (T1), a z config.toml sekcja [functions.analyze-contract]. Strażniki w tests/test_repo_hygiene.py pilnują braku funkcji i hosta Gemini poza tymczasowym wyjątkiem generate-company-details (S19). Wdrożone funkcje w chmurze usuwa operator (O4). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,2 @@
|
||||
|
||||
project_id = "qdbvsrzgxjewomfuvemo"
|
||||
|
||||
[functions.analyze-contract]
|
||||
verify_jwt = false
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
export const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
|
||||
import { corsHeaders } from '../_shared/cors.ts'
|
||||
|
||||
const GOOGLE_AI_API_KEY = Deno.env.get('GOOGLE_AI_API_KEY')
|
||||
const GEMINI_API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${GOOGLE_AI_API_KEY}`
|
||||
|
||||
const SYSTEM_PROMPT = `Analyze the provided contract document and extract the key information.
|
||||
Return the data as a single valid JSON object. Do not include any text, markdown, or code fences outside of the JSON object itself.
|
||||
The JSON object must have the following structure:
|
||||
{
|
||||
"title": "The title of the contract",
|
||||
"vendor": "The name of the vendor or second party",
|
||||
"value": "The total monetary value of the contract as a number (e.g., 50000), without currency symbols or commas",
|
||||
"startDate": "The start date of the contract in YYYY-MM-DD format",
|
||||
"endDate": "The end date of the contract in YYYY-MM-DD format",
|
||||
"status": "The status of the contract, must be one of: 'Active', 'Expired', 'Pending', 'Terminated'. Infer 'Pending' if not specified.",
|
||||
"representatives": [
|
||||
{ "name": "Full name of a representative from our organization", "role": "Role of the representative" }
|
||||
],
|
||||
"signees": [
|
||||
{ "name": "Full name of a signee", "email": "Email of the signee (if available)", "signedDate": "Date of signature in YYYY-MM-DD format" }
|
||||
],
|
||||
"keyClauses": {
|
||||
"liability": { "location": "e.g. Section 7.1, Page 5", "text": "The summarized text of the liability clause." },
|
||||
"ip": { "location": "e.g. Section 4.2, Page 2", "text": "The summarized text of the intellectual property clause." },
|
||||
"termination": { "location": "e.g. Section 10.3, Page 8", "text": "The summarized text of the termination clause." },
|
||||
"dataPrivacy": { "location": "", "text": "The summarized text of the data privacy clause." },
|
||||
"payment": { "location": "", "text": "The summarized text of the payment terms clause." },
|
||||
"delivery": { "location": "", "text": "The summarized text of the delivery clause." },
|
||||
"confidentiality": { "location": "", "text": "The summarized text of the confidentiality clause." },
|
||||
"renewal": { "location": "", "text": "The summarized text of the renewal clause." },
|
||||
"maintenance": { "location": "", "text": "The summarized text of the maintenance clause." },
|
||||
"scopeOfWork": { "location": "", "text": "The summarized text of the scope of work clause." },
|
||||
"sla": { "location": "", "text": "The summarized text of the service level agreement (SLA) clause." },
|
||||
"security": { "location": "", "text": "The summarized text of the security clause." },
|
||||
"mileage": { "location": "", "text": "The summarized text of the mileage/usage clause." },
|
||||
"other": { "location": "", "text": "Any other key clauses not covered above." }
|
||||
}
|
||||
}
|
||||
|
||||
- For "keyClauses", analyze the document for common clauses like liability, termination, intellectual property, etc. For each one found, provide its location (like section number) and a concise summary of the clause text. If a clause type is not found, do not include it in the keyClauses object.
|
||||
- If a value is not found, use an empty string "" for string fields, 0 for numeric fields, null for dates, and an empty array [] for lists.
|
||||
- For "value", extract only the number.
|
||||
- For dates, strictly use YYYY-MM-DD format.
|
||||
- For representatives and signees, extract all that are mentioned.
|
||||
`
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders })
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Attempting to use Google AI. Key is set: ${!!GOOGLE_AI_API_KEY}`);
|
||||
if (!GOOGLE_AI_API_KEY) {
|
||||
throw new Error("Google AI API key is not set in Supabase secrets.");
|
||||
}
|
||||
|
||||
const { fileContent, mimeType } = await req.json()
|
||||
|
||||
if (!fileContent || !mimeType) {
|
||||
throw new Error('Missing file content or mime type')
|
||||
}
|
||||
|
||||
const response = await fetch(GEMINI_API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{ text: SYSTEM_PROMPT },
|
||||
{
|
||||
inline_data: {
|
||||
mime_type: mimeType,
|
||||
data: fileContent,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
generationConfig: {
|
||||
response_mime_type: "application/json",
|
||||
}
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorBody = await response.text();
|
||||
console.error('Gemini API error response:', errorBody);
|
||||
throw new Error(`Gemini API request failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const extractedData = data.candidates[0].content.parts[0].text;
|
||||
|
||||
return new Response(extractedData, {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error in analyze-contract function:', error)
|
||||
return new Response(JSON.stringify({ error: error.message }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -1,117 +0,0 @@
|
||||
|
||||
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
|
||||
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||
import { corsHeaders } from '../_shared/cors.ts'
|
||||
|
||||
const GOOGLE_AI_API_KEY = Deno.env.get('GOOGLE_AI_API_KEY')
|
||||
const GEMINI_API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${GOOGLE_AI_API_KEY}`
|
||||
|
||||
const SYSTEM_PROMPT = `You are an expert legal assistant AI. Your task is to review a contract clause against a company's standard Clause Base.
|
||||
The Clause Base is provided as a JSON object with three categories of clauses: 'preferred', 'accepted', and 'non-acceptable'.
|
||||
|
||||
You will be given a single 'contractClauseText'.
|
||||
|
||||
Your analysis should follow these steps:
|
||||
1. Carefully read the 'contractClauseText'.
|
||||
2. Compare it against all clauses in the 'preferred' category. If it's semantically identical or very similar to a preferred clause, the review is positive.
|
||||
3. If not, compare it against the 'accepted' category. If it aligns with an accepted clause, it's acceptable but may require attention.
|
||||
4. If not, compare it against the 'non-acceptable' category. If it is similar to a non-acceptable clause, it is a high-risk issue.
|
||||
5. If it doesn't match any clause, analyze its content for potential risks or benefits.
|
||||
|
||||
Based on your analysis, you must return a single, valid JSON object with NO other text or markdown.
|
||||
The JSON object must have this structure:
|
||||
{
|
||||
"status": "Approved" | "Needs Attention" | "Rejected",
|
||||
"recommendation": "A concise explanation for your decision."
|
||||
}
|
||||
|
||||
- Use "Approved" if the clause is highly favorable, like matching a 'preferred' clause. The recommendation should state this.
|
||||
- Use "Needs Attention" if the clause is acceptable but not ideal, like matching an 'accepted' clause, or if it's a new, neutral clause that needs human review.
|
||||
- Use "Rejected" if the clause is unfavorable, like matching a 'non-acceptable' clause or containing clear risks.
|
||||
|
||||
Example Recommendation for 'Approved': "This clause aligns perfectly with our standard preferred liability terms."
|
||||
Example Recommendation for 'Needs Attention': "This clause is acceptable, but differs from our preferred version by not including a cap on liability. Manual review recommended."
|
||||
Example Recommendation for 'Rejected': "This clause is non-acceptable as it assigns unlimited liability to our company. This is a critical risk."`
|
||||
|
||||
serve(async (req) => {
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response('ok', { headers: corsHeaders })
|
||||
}
|
||||
|
||||
try {
|
||||
if (!GOOGLE_AI_API_KEY) {
|
||||
throw new Error("Google AI API key is not set in Supabase secrets.");
|
||||
}
|
||||
|
||||
const { clauseText } = await req.json()
|
||||
if (!clauseText) {
|
||||
throw new Error('Missing clauseText in request body')
|
||||
}
|
||||
|
||||
const supabaseAdmin = createClient(
|
||||
Deno.env.get('SUPABASE_URL') ?? '',
|
||||
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
|
||||
);
|
||||
|
||||
const { data: clauses, error: dbError } = await supabaseAdmin.from('clauses').select('*');
|
||||
if (dbError) throw dbError;
|
||||
|
||||
const groupedClauses = (clauses || []).reduce((acc, clause) => {
|
||||
const category = clause.category || 'uncategorized';
|
||||
if (!acc[category]) {
|
||||
acc[category] = [];
|
||||
}
|
||||
acc[category].push({ title: clause.title, content: clause.content });
|
||||
return acc;
|
||||
}, {} as Record<string, {title: string, content: string}[]>);
|
||||
|
||||
const promptPayload = `
|
||||
Contract Clause Text:
|
||||
\`\`\`
|
||||
${clauseText}
|
||||
\`\`\`
|
||||
|
||||
Clause Base:
|
||||
\`\`\`json
|
||||
${JSON.stringify(groupedClauses)}
|
||||
\`\`\`
|
||||
`
|
||||
const response = await fetch(GEMINI_API_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
contents: [
|
||||
{
|
||||
parts: [
|
||||
{ text: SYSTEM_PROMPT },
|
||||
{ text: promptPayload },
|
||||
],
|
||||
},
|
||||
],
|
||||
generationConfig: {
|
||||
response_mime_type: "application/json",
|
||||
}
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorBody = await response.text();
|
||||
console.error('Gemini API error response:', errorBody);
|
||||
throw new Error(`Gemini API request failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const extractedData = data.candidates[0].content.parts[0].text;
|
||||
|
||||
return new Response(extractedData, {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 200,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error in review-clause function:', error)
|
||||
return new Response(JSON.stringify({ error: error.message }), {
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -11,8 +11,11 @@ import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB_SRC = REPO_ROOT / "apps" / "web" / "src"
|
||||
FUNCTIONS = REPO_ROOT / "supabase" / "functions"
|
||||
GEMINI_HOST = "generativelanguage.googleapis.com"
|
||||
CONTRACT_FUNCTIONS = ("analyze-contract", "review-clause")
|
||||
# Wyjątek tymczasowy do decyzji S19 (2026-09-11): wysyła do Gemini nazwy kontrahentów, nie umowy.
|
||||
GEMINI_ALLOWED_FUNCTIONS = {"generate-company-details"}
|
||||
SOURCE_SUFFIXES = {".ts", ".tsx", ".js", ".mjs"}
|
||||
|
||||
|
||||
@@ -95,3 +98,22 @@ def test_web_does_not_send_contracts_to_gemini() -> None:
|
||||
if marker in text
|
||||
]
|
||||
assert hits == []
|
||||
|
||||
|
||||
def test_contract_functions_are_removed() -> None:
|
||||
config = (REPO_ROOT / "supabase" / "config.toml").read_text(encoding="utf-8")
|
||||
left = [
|
||||
name
|
||||
for name in CONTRACT_FUNCTIONS
|
||||
if (FUNCTIONS / name).exists() or f"[functions.{name}]" in config
|
||||
]
|
||||
assert left == []
|
||||
|
||||
|
||||
def test_gemini_host_only_in_allowed_functions() -> None:
|
||||
calling = {
|
||||
p.relative_to(FUNCTIONS).parts[0]
|
||||
for p, text in _sources(FUNCTIONS).items()
|
||||
if GEMINI_HOST in text
|
||||
}
|
||||
assert calling - GEMINI_ALLOWED_FUNCTIONS == set()
|
||||
|
||||
Reference in New Issue
Block a user