diff --git a/.agents/skills/gitnexus/gitnexus-cli/SKILL.md b/.agents/skills/gitnexus/gitnexus-cli/SKILL.md new file mode 100644 index 0000000..ee40c41 --- /dev/null +++ b/.agents/skills/gitnexus/gitnexus-cli/SKILL.md @@ -0,0 +1,83 @@ +--- +name: gitnexus-cli +description: "Use when the user needs to run GitNexus CLI commands like analyze/index a repo, check status, clean the index, generate a wiki, or list indexed repos. Examples: \"Index this repo\", \"Reanalyze the codebase\", \"Generate a wiki\"" +--- + +# GitNexus CLI Commands + +All commands work via `npx` — no global install required. + +## Commands + +### analyze — Build or refresh the index + +```bash +npx gitnexus analyze +``` + +Run from the project root. This parses all source files, builds the knowledge graph, writes it to `.gitnexus/`, and generates AGENTS.md / AGENTS.md context files. + +| Flag | Effect | +| -------------- | ---------------------------------------------------------------- | +| `--force` | Force full re-index even if up to date | +| `--embeddings` | Enable embedding generation for semantic search (off by default) | +| `--drop-embeddings` | Drop existing embeddings on rebuild. By default, an `analyze` without `--embeddings` preserves them. | + +**When to run:** First time in a project, after major code changes, or when `gitnexus://repo/{name}/context` reports the index is stale. In Codex, a PostToolUse hook runs `analyze` automatically after `git commit` and `git merge`, preserving embeddings if previously generated. + +### status — Check index freshness + +```bash +npx gitnexus status +``` + +Shows whether the current repo has a GitNexus index, when it was last updated, and symbol/relationship counts. Use this to check if re-indexing is needed. + +### clean — Delete the index + +```bash +npx gitnexus clean +``` + +Deletes the `.gitnexus/` directory and unregisters the repo from the global registry. Use before re-indexing if the index is corrupt or after removing GitNexus from a project. + +| Flag | Effect | +| --------- | ------------------------------------------------- | +| `--force` | Skip confirmation prompt | +| `--all` | Clean all indexed repos, not just the current one | + +### wiki — Generate documentation from the graph + +```bash +npx gitnexus wiki +``` + +Generates repository documentation from the knowledge graph using an LLM. Requires an API key (saved to `~/.gitnexus/config.json` on first use). + +| Flag | Effect | +| ------------------- | ----------------------------------------- | +| `--force` | Force full regeneration | +| `--model ` | LLM model (default: minimax/minimax-m2.5) | +| `--base-url ` | LLM API base URL | +| `--api-key ` | LLM API key | +| `--concurrency ` | Parallel LLM calls (default: 3) | +| `--gist` | Publish wiki as a public GitHub Gist | + +### list — Show all indexed repos + +```bash +npx gitnexus list +``` + +Lists all repositories registered in `~/.gitnexus/registry.json`. The MCP `list_repos` tool provides the same information. + +## After Indexing + +1. **Read `gitnexus://repo/{name}/context`** to verify the index loaded +2. Use the other GitNexus skills (`exploring`, `debugging`, `impact-analysis`, `refactoring`) for your task + +## Troubleshooting + +- **"Not inside a git repository"**: Run from a directory inside a git repo +- **Index is stale after re-analyzing**: Restart Codex to reload the MCP server +- **Embeddings slow**: Omit `--embeddings` (it's off by default) or set `OPENAI_API_KEY` for faster API-based embedding diff --git a/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md b/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md new file mode 100644 index 0000000..9510b97 --- /dev/null +++ b/.agents/skills/gitnexus/gitnexus-debugging/SKILL.md @@ -0,0 +1,89 @@ +--- +name: gitnexus-debugging +description: "Use when the user is debugging a bug, tracing an error, or asking why something fails. Examples: \"Why is X failing?\", \"Where does this error come from?\", \"Trace this bug\"" +--- + +# Debugging with GitNexus + +## When to Use + +- "Why is this function failing?" +- "Trace where this error comes from" +- "Who calls this method?" +- "This endpoint returns 500" +- Investigating bugs, errors, or unexpected behavior + +## Workflow + +``` +1. gitnexus_query({query: ""}) → Find related execution flows +2. gitnexus_context({name: ""}) → See callers/callees/processes +3. READ gitnexus://repo/{name}/process/{name} → Trace execution flow +4. gitnexus_cypher({query: "MATCH path..."}) → Custom traces if needed +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] Understand the symptom (error message, unexpected behavior) +- [ ] gitnexus_query for error text or related code +- [ ] Identify the suspect function from returned processes +- [ ] gitnexus_context to see callers and callees +- [ ] Trace execution flow via process resource if applicable +- [ ] gitnexus_cypher for custom call chain traces if needed +- [ ] Read source files to confirm root cause +``` + +## Debugging Patterns + +| Symptom | GitNexus Approach | +| -------------------- | ---------------------------------------------------------- | +| Error message | `gitnexus_query` for error text → `context` on throw sites | +| Wrong return value | `context` on the function → trace callees for data flow | +| Intermittent failure | `context` → look for external calls, async deps | +| Performance issue | `context` → find symbols with many callers (hot paths) | +| Recent regression | `detect_changes` to see what your changes affect | + +## Tools + +**gitnexus_query** — find code related to error: + +``` +gitnexus_query({query: "payment validation error"}) +→ Processes: CheckoutFlow, ErrorHandling +→ Symbols: validatePayment, handlePaymentError, PaymentException +``` + +**gitnexus_context** — full context for a suspect: + +``` +gitnexus_context({name: "validatePayment"}) +→ Incoming calls: processCheckout, webhookHandler +→ Outgoing calls: verifyCard, fetchRates (external API!) +→ Processes: CheckoutFlow (step 3/7) +``` + +**gitnexus_cypher** — custom call chain traces: + +```cypher +MATCH path = (a)-[:CodeRelation {type: 'CALLS'}*1..2]->(b:Function {name: "validatePayment"}) +RETURN [n IN nodes(path) | n.name] AS chain +``` + +## Example: "Payment endpoint returns 500 intermittently" + +``` +1. gitnexus_query({query: "payment error handling"}) + → Processes: CheckoutFlow, ErrorHandling + → Symbols: validatePayment, handlePaymentError + +2. gitnexus_context({name: "validatePayment"}) + → Outgoing calls: verifyCard, fetchRates (external API!) + +3. READ gitnexus://repo/my-app/process/CheckoutFlow + → Step 3: validatePayment → calls fetchRates (external) + +4. Root cause: fetchRates calls external API without proper timeout +``` diff --git a/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md b/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md new file mode 100644 index 0000000..927a4e4 --- /dev/null +++ b/.agents/skills/gitnexus/gitnexus-exploring/SKILL.md @@ -0,0 +1,78 @@ +--- +name: gitnexus-exploring +description: "Use when the user asks how code works, wants to understand architecture, trace execution flows, or explore unfamiliar parts of the codebase. Examples: \"How does X work?\", \"What calls this function?\", \"Show me the auth flow\"" +--- + +# Exploring Codebases with GitNexus + +## When to Use + +- "How does authentication work?" +- "What's the project structure?" +- "Show me the main components" +- "Where is the database logic?" +- Understanding code you haven't seen before + +## Workflow + +``` +1. READ gitnexus://repos → Discover indexed repos +2. READ gitnexus://repo/{name}/context → Codebase overview, check staleness +3. gitnexus_query({query: ""}) → Find related execution flows +4. gitnexus_context({name: ""}) → Deep dive on specific symbol +5. READ gitnexus://repo/{name}/process/{name} → Trace full execution flow +``` + +> If step 2 says "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] READ gitnexus://repo/{name}/context +- [ ] gitnexus_query for the concept you want to understand +- [ ] Review returned processes (execution flows) +- [ ] gitnexus_context on key symbols for callers/callees +- [ ] READ process resource for full execution traces +- [ ] Read source files for implementation details +``` + +## Resources + +| Resource | What you get | +| --------------------------------------- | ------------------------------------------------------- | +| `gitnexus://repo/{name}/context` | Stats, staleness warning (~150 tokens) | +| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores (~300 tokens) | +| `gitnexus://repo/{name}/cluster/{name}` | Area members with file paths (~500 tokens) | +| `gitnexus://repo/{name}/process/{name}` | Step-by-step execution trace (~200 tokens) | + +## Tools + +**gitnexus_query** — find execution flows related to a concept: + +``` +gitnexus_query({query: "payment processing"}) +→ Processes: CheckoutFlow, RefundFlow, WebhookHandler +→ Symbols grouped by flow with file locations +``` + +**gitnexus_context** — 360-degree view of a symbol: + +``` +gitnexus_context({name: "validateUser"}) +→ Incoming calls: loginHandler, apiMiddleware +→ Outgoing calls: checkToken, getUserById +→ Processes: LoginFlow (step 2/5), TokenRefresh (step 1/3) +``` + +## Example: "How does payment processing work?" + +``` +1. READ gitnexus://repo/my-app/context → 918 symbols, 45 processes +2. gitnexus_query({query: "payment processing"}) + → CheckoutFlow: processPayment → validateCard → chargeStripe + → RefundFlow: initiateRefund → calculateRefund → processRefund +3. gitnexus_context({name: "processPayment"}) + → Incoming: checkoutHandler, webhookHandler + → Outgoing: validateCard, chargeStripe, saveTransaction +4. Read src/payments/processor.ts for implementation details +``` diff --git a/.agents/skills/gitnexus/gitnexus-guide/SKILL.md b/.agents/skills/gitnexus/gitnexus-guide/SKILL.md new file mode 100644 index 0000000..937ac73 --- /dev/null +++ b/.agents/skills/gitnexus/gitnexus-guide/SKILL.md @@ -0,0 +1,64 @@ +--- +name: gitnexus-guide +description: "Use when the user asks about GitNexus itself — available tools, how to query the knowledge graph, MCP resources, graph schema, or workflow reference. Examples: \"What GitNexus tools are available?\", \"How do I use GitNexus?\"" +--- + +# GitNexus Guide + +Quick reference for all GitNexus MCP tools, resources, and the knowledge graph schema. + +## Always Start Here + +For any task involving code understanding, debugging, impact analysis, or refactoring: + +1. **Read `gitnexus://repo/{name}/context`** — codebase overview + check index freshness +2. **Match your task to a skill below** and **read that skill file** +3. **Follow the skill's workflow and checklist** + +> If step 1 warns the index is stale, run `npx gitnexus analyze` in the terminal first. + +## Skills + +| Task | Skill to read | +| -------------------------------------------- | ------------------- | +| Understand architecture / "How does X work?" | `gitnexus-exploring` | +| Blast radius / "What breaks if I change X?" | `gitnexus-impact-analysis` | +| Trace bugs / "Why is X failing?" | `gitnexus-debugging` | +| Rename / extract / split / refactor | `gitnexus-refactoring` | +| Tools, resources, schema reference | `gitnexus-guide` (this file) | +| Index, status, clean, wiki CLI commands | `gitnexus-cli` | + +## Tools Reference + +| Tool | What it gives you | +| ---------------- | ------------------------------------------------------------------------ | +| `query` | Process-grouped code intelligence — execution flows related to a concept | +| `context` | 360-degree symbol view — categorized refs, processes it participates in | +| `impact` | Symbol blast radius — what breaks at depth 1/2/3 with confidence | +| `detect_changes` | Git-diff impact — what do your current changes affect | +| `rename` | Multi-file coordinated rename with confidence-tagged edits | +| `cypher` | Raw graph queries (read `gitnexus://repo/{name}/schema` first) | +| `list_repos` | Discover indexed repos | + +## Resources Reference + +Lightweight reads (~100-500 tokens) for navigation: + +| Resource | Content | +| ---------------------------------------------- | ----------------------------------------- | +| `gitnexus://repo/{name}/context` | Stats, staleness check | +| `gitnexus://repo/{name}/clusters` | All functional areas with cohesion scores | +| `gitnexus://repo/{name}/cluster/{clusterName}` | Area members | +| `gitnexus://repo/{name}/processes` | All execution flows | +| `gitnexus://repo/{name}/process/{processName}` | Step-by-step trace | +| `gitnexus://repo/{name}/schema` | Graph schema for Cypher | + +## Graph Schema + +**Nodes:** File, Function, Class, Interface, Method, Community, Process +**Edges (via CodeRelation.type):** CALLS, IMPORTS, EXTENDS, IMPLEMENTS, DEFINES, MEMBER_OF, STEP_IN_PROCESS + +```cypher +MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "myFunc"}) +RETURN caller.name, caller.filePath +``` diff --git a/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md b/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md new file mode 100644 index 0000000..e19af28 --- /dev/null +++ b/.agents/skills/gitnexus/gitnexus-impact-analysis/SKILL.md @@ -0,0 +1,97 @@ +--- +name: gitnexus-impact-analysis +description: "Use when the user wants to know what will break if they change something, or needs safety analysis before editing code. Examples: \"Is it safe to change X?\", \"What depends on this?\", \"What will break?\"" +--- + +# Impact Analysis with GitNexus + +## When to Use + +- "Is it safe to change this function?" +- "What will break if I modify X?" +- "Show me the blast radius" +- "Who uses this code?" +- Before making non-trivial code changes +- Before committing — to understand what your changes affect + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → What depends on this +2. READ gitnexus://repo/{name}/processes → Check affected execution flows +3. gitnexus_detect_changes() → Map current git changes to affected flows +4. Assess risk and report to user +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklist + +``` +- [ ] gitnexus_impact({target, direction: "upstream"}) to find dependents +- [ ] Review d=1 items first (these WILL BREAK) +- [ ] Check high-confidence (>0.8) dependencies +- [ ] READ processes to check affected execution flows +- [ ] gitnexus_detect_changes() for pre-commit check +- [ ] Assess risk level and report to user +``` + +## Understanding Output + +| Depth | Risk Level | Meaning | +| ----- | ---------------- | ------------------------ | +| d=1 | **WILL BREAK** | Direct callers/importers | +| d=2 | LIKELY AFFECTED | Indirect dependencies | +| d=3 | MAY NEED TESTING | Transitive effects | + +## Risk Assessment + +| Affected | Risk | +| ------------------------------ | -------- | +| <5 symbols, few processes | LOW | +| 5-15 symbols, 2-5 processes | MEDIUM | +| >15 symbols or many processes | HIGH | +| Critical path (auth, payments) | CRITICAL | + +## Tools + +**gitnexus_impact** — the primary tool for symbol blast radius: + +``` +gitnexus_impact({ + target: "validateUser", + direction: "upstream", + minConfidence: 0.8, + maxDepth: 3 +}) + +→ d=1 (WILL BREAK): + - loginHandler (src/auth/login.ts:42) [CALLS, 100%] + - apiMiddleware (src/api/middleware.ts:15) [CALLS, 100%] + +→ d=2 (LIKELY AFFECTED): + - authRouter (src/routes/auth.ts:22) [CALLS, 95%] +``` + +**gitnexus_detect_changes** — git-diff based impact analysis: + +``` +gitnexus_detect_changes({scope: "staged"}) + +→ Changed: 5 symbols in 3 files +→ Affected: LoginFlow, TokenRefresh, APIMiddlewarePipeline +→ Risk: MEDIUM +``` + +## Example: "What breaks if I change validateUser?" + +``` +1. gitnexus_impact({target: "validateUser", direction: "upstream"}) + → d=1: loginHandler, apiMiddleware (WILL BREAK) + → d=2: authRouter, sessionManager (LIKELY AFFECTED) + +2. READ gitnexus://repo/my-app/processes + → LoginFlow and TokenRefresh touch validateUser + +3. Risk: 2 direct callers, 2 processes = MEDIUM +``` diff --git a/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md b/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md new file mode 100644 index 0000000..f48cc01 --- /dev/null +++ b/.agents/skills/gitnexus/gitnexus-refactoring/SKILL.md @@ -0,0 +1,121 @@ +--- +name: gitnexus-refactoring +description: "Use when the user wants to rename, extract, split, move, or restructure code safely. Examples: \"Rename this function\", \"Extract this into a module\", \"Refactor this class\", \"Move this to a separate file\"" +--- + +# Refactoring with GitNexus + +## When to Use + +- "Rename this function safely" +- "Extract this into a module" +- "Split this service" +- "Move this to a new file" +- Any task involving renaming, extracting, splitting, or restructuring code + +## Workflow + +``` +1. gitnexus_impact({target: "X", direction: "upstream"}) → Map all dependents +2. gitnexus_query({query: "X"}) → Find execution flows involving X +3. gitnexus_context({name: "X"}) → See all incoming/outgoing refs +4. Plan update order: interfaces → implementations → callers → tests +``` + +> If "Index is stale" → run `npx gitnexus analyze` in terminal. + +## Checklists + +### Rename Symbol + +``` +- [ ] gitnexus_rename({symbol_name: "oldName", new_name: "newName", dry_run: true}) — preview all edits +- [ ] Review graph edits (high confidence) and ast_search edits (review carefully) +- [ ] If satisfied: gitnexus_rename({..., dry_run: false}) — apply edits +- [ ] gitnexus_detect_changes() — verify only expected files changed +- [ ] Run tests for affected processes +``` + +### Extract Module + +``` +- [ ] gitnexus_context({name: target}) — see all incoming/outgoing refs +- [ ] gitnexus_impact({target, direction: "upstream"}) — find all external callers +- [ ] Define new module interface +- [ ] Extract code, update imports +- [ ] gitnexus_detect_changes() — verify affected scope +- [ ] Run tests for affected processes +``` + +### Split Function/Service + +``` +- [ ] gitnexus_context({name: target}) — understand all callees +- [ ] Group callees by responsibility +- [ ] gitnexus_impact({target, direction: "upstream"}) — map callers to update +- [ ] Create new functions/services +- [ ] Update callers +- [ ] gitnexus_detect_changes() — verify affected scope +- [ ] Run tests for affected processes +``` + +## Tools + +**gitnexus_rename** — automated multi-file rename: + +``` +gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) +→ 12 edits across 8 files +→ 10 graph edits (high confidence), 2 ast_search edits (review) +→ Changes: [{file_path, edits: [{line, old_text, new_text, confidence}]}] +``` + +**gitnexus_impact** — map all dependents first: + +``` +gitnexus_impact({target: "validateUser", direction: "upstream"}) +→ d=1: loginHandler, apiMiddleware, testUtils +→ Affected Processes: LoginFlow, TokenRefresh +``` + +**gitnexus_detect_changes** — verify your changes after refactoring: + +``` +gitnexus_detect_changes({scope: "all"}) +→ Changed: 8 files, 12 symbols +→ Affected processes: LoginFlow, TokenRefresh +→ Risk: MEDIUM +``` + +**gitnexus_cypher** — custom reference queries: + +```cypher +MATCH (caller)-[:CodeRelation {type: 'CALLS'}]->(f:Function {name: "validateUser"}) +RETURN caller.name, caller.filePath ORDER BY caller.filePath +``` + +## Risk Rules + +| Risk Factor | Mitigation | +| ------------------- | ----------------------------------------- | +| Many callers (>5) | Use gitnexus_rename for automated updates | +| Cross-area refs | Use detect_changes after to verify scope | +| String/dynamic refs | gitnexus_query to find them | +| External/public API | Version and deprecate properly | + +## Example: Rename `validateUser` to `authenticateUser` + +``` +1. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: true}) + → 12 edits: 10 graph (safe), 2 ast_search (review) + → Files: validator.ts, login.ts, middleware.ts, config.json... + +2. Review ast_search edits (config.json: dynamic reference!) + +3. gitnexus_rename({symbol_name: "validateUser", new_name: "authenticateUser", dry_run: false}) + → Applied 12 edits across 8 files + +4. gitnexus_detect_changes({scope: "all"}) + → Affected: LoginFlow, TokenRefresh + → Risk: MEDIUM — run tests for these flows +``` diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b981754..4359617 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,7 +1,7 @@ # Supervaizer Changelog > **Created:** 2025-08-05 -> **Updated:** 2026-05-17 +> **Updated:** 2026-05-18 All notable changes to this project will be documented in this file. @@ -18,6 +18,26 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Supervaizer v2 2️⃣ + +- **Supervaizer v2 case metadata** — `V2CaseSnapshot` now carries optional public `metadata` so agents can expose case-level business context such as contact interview links without adding agent-specific fields to the protocol. +- **Studio registration handshake validation** — After `server.register`, startup validates `supervaizer_handshake.controller_api_key_match` and fails when Studio persisted a different controller API key than the one this process is using (configured `SUPERVAIZER_API_KEY` or auto-generated key). +- **Controller API key reload stability** — Auto-generated controller keys are written to `SUPERVAIZER_API_KEY` before registration so Uvicorn reload keeps the same key; startup logs a short SHA-256 fingerprint instead of printing the full secret. + +### Tests + +- `tests/test_contracts.py` — `V2CaseSnapshot` accepts public `metadata`. +- `tests/test_server.py` — registration handshake accept/reject paths and generated API key export for reload. + +`just test` + +| Status | Count | +| ---------- | ----- | +| ✅ Passed | 616 | +| 🤔 Skipped | 0 | +| 🔴 Failed | 0 | +| ⏱️ in | 78s | + ## [1.0.0] - 2026-05-17 ### Supervaizer v2 2️⃣ diff --git a/src/supervaizer/contracts.py b/src/supervaizer/contracts.py index 5b6c9e2..d64e731 100644 --- a/src/supervaizer/contracts.py +++ b/src/supervaizer/contracts.py @@ -731,6 +731,7 @@ class V2CaseSnapshot(ContractModel): title: str | None = None status: str | None = None external_id: str | None = None + metadata: dict[str, Any] = Field(default_factory=dict) steps: list[V2StepSnapshot] = Field(default_factory=list) diff --git a/src/supervaizer/server.py b/src/supervaizer/server.py index dd94e6d..c790979 100644 --- a/src/supervaizer/server.py +++ b/src/supervaizer/server.py @@ -11,6 +11,7 @@ # https://mozilla.org/MPL/2.0/. import asyncio +from hashlib import sha256 import os import secrets import sys @@ -82,6 +83,12 @@ def _get_or_create_server_id() -> str: return new_id +def _controller_key_fingerprint(api_key: str | None) -> str | None: + if not api_key: + return None + return sha256(api_key.encode("utf-8")).hexdigest()[:12] + + def _get_or_create_private_key() -> RSAPrivateKey: """Use SUPERVAIZER_PRIVATE_KEY from env if set; else create key and set env.""" pem = os.getenv("SUPERVAIZER_PRIVATE_KEY") @@ -405,11 +412,19 @@ def __init__( port = int(os.getenv("SUPERVAIZER_PORT", "8000")) if public_url is None: public_url = os.getenv("SUPERVAIZER_PUBLIC_URL") or None + local_mode = is_local_mode() + api_key_was_generated = False if api_key is None: - api_key = os.getenv("SUPERVAIZER_API_KEY") or secrets.token_urlsafe(32) + api_key = os.getenv("SUPERVAIZER_API_KEY") + if not api_key: + if local_mode: + api_key = "local-dev" + else: + api_key = secrets.token_urlsafe(32) + os.environ["SUPERVAIZER_API_KEY"] = api_key + api_key_was_generated = True # Local mode: skip Studio, inject Hello World, default api_key - local_mode = is_local_mode() local_hello_world_slug: str | None = None if local_mode: if supervisor_account is not None: @@ -420,8 +435,6 @@ def __init__( supervisor_account = None a2a_endpoints = True admin_interface = True - if not os.environ.get("SUPERVAIZER_API_KEY"): - api_key = "local-dev" # Inject Hello World agent unless disabled or duplicate if os.environ.get("SUPERVAIZER_DISABLE_HELLO_WORLD", "").lower() != "true": @@ -601,8 +614,11 @@ async def get_current_server() -> "Server": if api_key: log.info("[Server launch] API Key authentication enabled") # Print the API key if it was generated - if os.getenv("SUPERVAIZER_API_KEY") is None: - log.warning(f"[Server launch] Using auto-generated API key: {api_key}") + if api_key_was_generated: + log.warning( + "[Server launch] Using auto-generated API key " + f"fingerprint={_controller_key_fingerprint(api_key)}" + ) else: log.info("[Server launch] API Key authentication disabled") @@ -726,6 +742,7 @@ def log_queue_handler(message: Any) -> None: assert isinstance( server_registration_result, ApiSuccess ) # If ApiError, exception should have been raised before + self._validate_registration_handshake(server_registration_result) # Get the agent details from the server for agent in self.agents: updated_agent = agent.update_agent_from_server(self) @@ -748,6 +765,40 @@ def instructions(self) -> None: server_url, f"Starting server on {server_url} \n Waiting for instructions.." ) + def _validate_registration_handshake(self, result: ApiSuccess) -> None: + detail = result.detail if isinstance(result.detail, dict) else {} + response_object = detail.get("object") + if not isinstance(response_object, dict): + raise RuntimeError( + "Studio registration handshake failed: server.register response did not " + "include a response object. Studio-to-agent API key persistence could not " + "be verified." + ) + handshake = response_object.get("supervaizer_handshake") + if not isinstance(handshake, dict): + response_keys = sorted(str(key) for key in response_object.keys()) + raise RuntimeError( + "Studio registration handshake failed: server.register response did not " + "include supervaizer_handshake. Studio-to-agent API key persistence could " + "not be verified. Check that SUPERVAIZE_API_URL points to a Studio " + "instance that supports the Supervaizer v2 registration handshake. " + f"response_keys={response_keys}" + ) + if handshake.get("controller_api_key_match") is True: + log.info( + "[Server launch] Studio registration handshake verified " + f"server_id={handshake.get('server_id')} " + f"controller_key_fingerprint={_controller_key_fingerprint(self.api_key)}" + ) + return + raise RuntimeError( + "Studio registration handshake failed: Studio did not persist the controller API key " + f"for server_id={handshake.get('server_id')}. " + f"controller_key_fingerprint={_controller_key_fingerprint(self.api_key)} " + f"studio_fingerprint={handshake.get('stored_controller_api_key_fingerprint')} " + f"reason={handshake.get('reason')}" + ) + def decrypt(self, encrypted_parameters: str) -> str: """Decrypt parameters using the server's private key.""" result = decrypt_value(encrypted_parameters, self.private_key) diff --git a/tests/test_contracts.py b/tests/test_contracts.py index f3a39a5..e7f42f8 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -28,6 +28,7 @@ V2ActionRequest, V2ActionResult, V2AwaitingState, + V2CaseSnapshot, V2DashboardWidgetDataRef, V2DashboardWidgetDefinition, V2DashboardWidgetVisualization, @@ -138,6 +139,17 @@ def test_v2_effect_has_typed_common_fields() -> None: } +def test_v2_case_snapshot_accepts_public_metadata() -> None: + case = V2CaseSnapshot( + id="enrollment-1", + metadata={"interview_url": "https://app.example.com/interview/tok-abc"}, + ) + + assert case.metadata == { + "interview_url": "https://app.example.com/interview/tok-abc" + } + + def test_v2_action_result_validates_job_state() -> None: with pytest.raises(ValidationError): V2ActionResult.model_validate({ diff --git a/tests/test_server.py b/tests/test_server.py index bb69f26..173c3e1 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -22,6 +22,7 @@ from supervaizer import Server from supervaizer.agent import Agent +from supervaizer.common import ApiSuccess from supervaizer.job import Job, JobContext from supervaizer.lifecycle import EntityStatus from supervaizer.parameter import ParametersSetup @@ -82,6 +83,77 @@ def test_server(server_fixture: Server) -> None: assert len(server_fixture.agents) == 1 +def test_server_registration_handshake_rejects_key_mismatch( + server_fixture: Server, +) -> None: + result = ApiSuccess( + message="POST Event SERVER_REGISTER sent", + detail={ + "object": { + "supervaizer_handshake": { + "server_id": "server-1", + "controller_api_key_match": False, + "stored_controller_api_key_fingerprint": "stored-key", + "reason": "stored_controller_api_key_mismatch", + } + } + }, + ) + + with pytest.raises(RuntimeError, match="Studio registration handshake failed"): + server_fixture._validate_registration_handshake(result) + + +def test_server_registration_handshake_accepts_key_match( + server_fixture: Server, +) -> None: + result = ApiSuccess( + message="POST Event SERVER_REGISTER sent", + detail={ + "object": { + "supervaizer_handshake": { + "server_id": "server-1", + "controller_api_key_match": True, + } + } + }, + ) + + server_fixture._validate_registration_handshake(result) + + +def test_server_registration_handshake_rejects_missing_handshake( + server_fixture: Server, +) -> None: + result = ApiSuccess( + message="POST Event SERVER_REGISTER sent", + detail={"object": {}}, + ) + + with pytest.raises(RuntimeError, match="did not include supervaizer_handshake"): + server_fixture._validate_registration_handshake(result) + + +def test_server_generated_api_key_is_exported_for_reload( + agent_fixture: Agent, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("SUPERVAIZER_API_KEY", raising=False) + monkeypatch.setenv("SUPERVAIZER_DISABLE_HELLO_WORLD", "true") + monkeypatch.setenv("SUPERVAIZER_LOCAL_MODE", "false") + + server = Server( + agents=[agent_fixture], + supervisor_account=None, + host="localhost", + port=8001, + environment="test", + ) + + assert server.api_key + assert os.environ["SUPERVAIZER_API_KEY"] == server.api_key + + def test_server_decrypt(server_fixture: Server) -> None: unencrypted_parameters = str({"KEY": "VALUE"}) encrypted_parameters = server_fixture.encrypt(unencrypted_parameters)