#!/usr/bin/env python3 """ Submit .ai-log/session.jsonl to grading server. Called by git pre-push hook or manually. """ import json import os import sys import urllib.request import urllib.error from pathlib import Path try: from dotenv import load_dotenv load_dotenv() except ImportError: pass SERVER_URL = os.environ.get("AI_LOG_SERVER", "") API_KEY = os.environ.get("AI_LOG_API_KEY", "") LOG_FILE = Path(os.environ.get("AI_LOG_DIR", ".ai-log")) / "session.jsonl" def main(): if not SERVER_URL: print("[ai-log] AI_LOG_SERVER not set — skipping submission.", file=sys.stderr) sys.exit(0) if not LOG_FILE.exists() or LOG_FILE.stat().st_size == 0: print("[ai-log] No logs to submit.", file=sys.stderr) sys.exit(0) entries = [] with open(LOG_FILE, encoding="utf-8") as f: for line in f: line = line.strip() if line: try: entries.append(json.loads(line)) except json.JSONDecodeError: pass if not entries: print("[ai-log] No valid entries to submit.", file=sys.stderr) sys.exit(0) payload = json.dumps({"entries": entries}, ensure_ascii=False).encode("utf-8") headers = {"Content-Type": "application/json"} if API_KEY: headers["Authorization"] = f"Bearer {API_KEY}" req = urllib.request.Request( SERVER_URL, data=payload, headers=headers, method="POST", ) try: with urllib.request.urlopen(req, timeout=10) as resp: print(f"[ai-log] Submitted {len(entries)} entries → {resp.status}", file=sys.stderr) except urllib.error.URLError as e: print(f"[ai-log] Submit failed: {e} — logs kept locally.", file=sys.stderr) sys.exit(0) # Don't block push on server error if __name__ == "__main__": main()