GitNexus/eval/agents/gitnexus_agent.py
John R. Eakin c68d7975e6
docs: agent development framework, GitHub templates, eval refactor (#479)
* ci: E2E workflow, web typecheck job, pre-commit hook, test suite

CI:
- ci.yml consolidated to reference ci-tests.yml
- ci-quality.yml: add typecheck-web job for gitnexus-web/
- ci-e2e.yml: E2E workflow with dorny/paths-filter (web changes only)
- ci-report.yml: remove dead integration-reports references
- CI gate allows skipped E2E status
- .gitignore: playwright artifacts, eval test artifacts

Pre-commit hook:
- .githooks/pre-commit: typecheck + unit tests for both packages
- Activated via git config core.hooksPath in prepare script

Test infrastructure:
- Vitest + React Testing Library: 58 unit tests
  (graph, server-connection, mermaid, settings, constants, utils, paths)
- Playwright E2E: 5 tests + manual recording harness
- vitest.config from vitest/config, engines.node >= 20
- Playwright artifacts retain-on-failure
- wait-on in devDependencies
- vitest/coverage-v8 aligned with vitest 4.x

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: update gitnexus-web package-lock.json

Reflects devDependency additions (vitest, playwright, wait-on,
@testing-library, etc.) from package.json changes in this PR.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(e2e): add missing process-list-loaded testid, increase CI timeouts

- Add data-testid="process-list-loaded" to ProcessesPanel (E2E tests
  were waiting for an element that didn't exist)
- Increase server connect timeouts from 5s to 10s for slower CI

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): run gitnexus-web unit tests in CI, remove unused variable

- Add gitnexus-web npm ci + vitest run to ci-tests.yml so web unit
  tests are gated by the CI status check (were only running locally)
- Remove unused IS_PLAYWRIGHT_AUTOMATION variable from E2E spec

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(e2e): add process-row testid, wait for networkidle on page load

- Add data-testid="process-row" to ProcessItem component (E2E tests
  referenced it but it didn't exist in the source)
- Use waitUntil: 'networkidle' on page.goto to ensure Vite dev server
  is fully ready before interacting (fixes first-test timeout in CI)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(e2e): add process-view-button and process-highlight-button testids

E2E tests referenced these data-testid attributes but they didn't
exist in ProcessItem. All 6 E2E testids now have matching source
elements: status-ready, process-list-loaded, process-row,
process-view-button, process-highlight-button, server-url-input.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(e2e): remove networkidle — Vite HMR WebSocket prevents it from resolving

networkidle waits for zero network activity for 500ms, but Vite's HMR
WebSocket stays open permanently, causing page.goto to timeout at 60s
on all tests after the first. The explicit toBeVisible waits on UI
elements are sufficient and deterministic.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(e2e): wait for Server button visibility, add CI retry, all 5 tests pass locally

Root cause: test 1 clicked the Server button before React hydrated,
so the tab content never rendered and the input wasn't found.

Fixes:
- Wait for Server button toBeVisible before clicking
- Increase input wait to 15s
- Remove networkidle (Vite HMR WebSocket prevents it from resolving)
- Add retries: 1 in CI for transient cold-start flakiness

Verified locally: all 5 E2E tests pass, 198 unit tests pass, typecheck clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): tolerate LadybugDB native crash during analyze step

gitnexus analyze can crash with "double free or corruption" (known
issue #273) during the LadybugDB native addon shutdown. The index is
usually written successfully before the crash. The workflow now:
1. Allows analyze to exit non-zero with a warning
2. Verifies .gitnexus index was actually created
3. Only fails if no index exists (real failure)

All tests verified locally: 198 unit, 5 E2E pass, typecheck clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): fix shell quoting in analyze step, simplify to || true

The previous echo string had special characters that broke bash
quoting in GitHub Actions. Simplified to: analyze || true, then
check if .gitnexus exists.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: add agent development framework, GitHub templates, eval refactor

Agent framework (layered docs for AI-assisted contributions):
- AGENTS.md: canonical instructions, impact analysis, MCP tools
- CLAUDE.md: Claude Code-specific deltas and hooks
- GUARDRAILS.md: safety boundaries, non-negotiables, escalation
- ARCHITECTURE.md: monorepo layout, data flow map
- TESTING.md: test structure, commands, categories
- RUNBOOK.md: copy-paste operations for dev/CI/MCP
- llms.txt: minimal LLM context pointer

Editor integration:
- .cursor/index.mdc + rules/100-monorepo.mdc

GitHub templates:
- PR template with areas-touched checkboxes
- Bug report + feature request issue forms

Eval harness:
- Refactored mcp_bridge, tool_registry, constants
- Error sanitization utilities
- Property-based tests via Hypothesis

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(eval): use format_exception instead of format_exc in sanitize_exception

format_exc() returns the currently handled exception traceback, which
may be unrelated if called outside an active except block. Using
format_exception(type(exc), exc, exc.__traceback__) reliably captures
the passed exception's traceback.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: update CONTRIBUTING.md and TESTING.md for current CI/hook setup

- CONTRIBUTING.md: add gitnexus-web typecheck command, pre-commit hook
  checklist item
- TESTING.md: add gitnexus-web typecheck command, pre-commit hook
  section (husky), update CI integration to list actual workflow files
  (ci-quality, ci-tests, ci-e2e)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: update testing docs to reflect CI/E2E changes from PR #486

- AGENTS.md: update test counts (CLI ~2000 unit, ~1850 integration),
  add gitnexus-web testing section (198 unit, 5 E2E with commands)
- RUNBOOK.md: fix Node requirement to >=20, fix E2E local repro command
- TESTING.md: E2E uses data-testid selectors + real servers, not mocks
- .cursor/rules/100-monorepo.mdc: add web test/E2E commands

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: address context engineering review — deduplicate tokens, expand Cursor rules

- Remove ~100-line gitnexus:start block from CLAUDE.md (was duplicated from AGENTS.md)
- Fix gitnexus:start block inlined inside AGENTS.md Reference Docs bullet (doubled)
- Replace CLAUDE.md scope table with pointer to AGENTS.md (single source of truth)
- Expand .cursor/index.mdc with 5 non-negotiable safety rules for always-on context
- Add .cursor/rules/200-eval.mdc with Python/eval commands (glob-scoped to eval/**)
- Improve llms.txt with priority annotations and descriptions
- Bump version headers to 1.2.0, last-reviewed to 2026-03-24

Saves ~1,400 tokens/session with zero information loss.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
2026-03-25 06:48:41 +00:00

199 lines
7.7 KiB
Python

"""
GitNexus-Enhanced Agent for SWE-bench Evaluation
Extends mini-swe-agent's DefaultAgent with:
1. Native augment mode: GitNexus tools via eval-server + grep enrichment (recommended)
2. Native mode: GitNexus tools via eval-server only
3. Baseline mode: Pure mini-swe-agent (no GitNexus — control group)
The agent class itself is minimal — the heavy lifting is in:
- Prompt selection (system + instance templates per mode)
- Observation post-processing (grep result augmentation)
- Metrics tracking (which tools the agent actually uses)
Template structure (matches mini-swe-agent's expectations):
system_template → system message: persona + format rules + tool reference
instance_template → first user message: task + workflow + rules + examples
"""
import logging
import re
import time
from enum import Enum
from pathlib import Path
from constants import AUGMENT_TIMEOUT_SECONDS
from minisweagent import Environment, Model
from minisweagent.agents.default import AgentConfig, DefaultAgent
from tool_registry import BINARIES_BY_KEY, TOOL_METRIC_KEYS
logger = logging.getLogger("gitnexus_agent")
PROMPTS_DIR = Path(__file__).parent.parent / "prompts"
class GitNexusMode(str, Enum):
"""Evaluation modes for GitNexus integration."""
BASELINE = "baseline" # No GitNexus — pure mini-swe-agent
NATIVE = "native" # GitNexus tools via eval-server
NATIVE_AUGMENT = "native_augment" # Native tools + grep enrichment (recommended)
class GitNexusAgentConfig(AgentConfig):
"""Extended config for GitNexus evaluation agent."""
gitnexus_mode: GitNexusMode = GitNexusMode.BASELINE
augment_timeout: float = AUGMENT_TIMEOUT_SECONDS
augment_min_pattern_length: int = 3
track_gitnexus_usage: bool = True
class GitNexusAgent(DefaultAgent):
"""
Agent that optionally enriches its capabilities with GitNexus code intelligence.
In BASELINE mode, behaves identically to DefaultAgent.
In NATIVE mode, GitNexus tools are available as bash commands via eval-server.
In NATIVE_AUGMENT mode, GitNexus tools + automatic grep result enrichment.
"""
def __init__(self, model: Model, env: Environment, *, config_class: type = GitNexusAgentConfig, **kwargs):
mode = kwargs.get("gitnexus_mode", GitNexusMode.BASELINE)
if isinstance(mode, str):
mode = GitNexusMode(mode)
# Load system template
system_file = PROMPTS_DIR / f"system_{mode.value}.jinja"
if system_file.exists() and "system_template" not in kwargs:
kwargs["system_template"] = system_file.read_text()
# Load instance template
instance_file = PROMPTS_DIR / f"instance_{mode.value}.jinja"
if instance_file.exists() and "instance_template" not in kwargs:
kwargs["instance_template"] = instance_file.read_text()
super().__init__(model, env, config_class=config_class, **kwargs)
self.gitnexus_mode = mode
self.gitnexus_metrics = GitNexusMetrics()
def execute_actions(self, message: dict) -> list[dict]:
"""Execute actions with optional GitNexus augmentation and tracking."""
if self.config.track_gitnexus_usage:
self._track_tool_usage(message)
outputs = [self.env.execute(action) for action in message.get("extra", {}).get("actions", [])]
# Augment grep/find observations in NATIVE_AUGMENT mode
if self.gitnexus_mode == GitNexusMode.NATIVE_AUGMENT:
actions = message.get("extra", {}).get("actions", [])
for i, (action, output) in enumerate(zip(actions, outputs)):
augmented = self._maybe_augment(action, output)
if augmented:
outputs[i] = augmented
return self.add_messages(
*self.model.format_observation_messages(message, outputs, self.get_template_vars())
)
def _maybe_augment(self, action: dict, output: dict) -> dict | None:
"""
If the action is a search command (grep, find, rg, ag), augment the output
with GitNexus knowledge graph context.
"""
command = action.get("command", "")
if not command:
return None
pattern = self._extract_search_pattern(command)
if not pattern or len(pattern) < self.config.augment_min_pattern_length:
return None
start = time.time()
try:
augment_result = self.env.execute({
"command": f'gitnexus-augment "{pattern}" 2>&1 || true',
"timeout": self.config.augment_timeout,
})
elapsed = time.time() - start
self.gitnexus_metrics.augmentation_calls += 1
self.gitnexus_metrics.augmentation_time += elapsed
augment_text = augment_result.get("output", "").strip()
if augment_text and "[GitNexus]" in augment_text:
original_output = output.get("output", "")
output = dict(output)
output["output"] = f"{original_output}\n\n{augment_text}"
self.gitnexus_metrics.augmentation_hits += 1
return output
except Exception as e:
logger.debug(f"Augmentation failed for pattern '{pattern}': {e}")
self.gitnexus_metrics.augmentation_errors += 1
return None
@staticmethod
def _extract_search_pattern(command: str) -> str | None:
"""Extract the search pattern from a grep/find/rg command."""
patterns = [
r'(?:grep|rg|ag)\s+(?:-[a-zA-Z]*\s+)*["\']([^"\']+)["\']',
r'(?:grep|rg|ag)\s+(?:-[a-zA-Z]*\s+)*(\S+)',
]
for pat in patterns:
match = re.search(pat, command)
if match:
result = match.group(1)
if result.startswith("/") or result.startswith("."):
continue
if result.startswith("-"):
continue
return result
return None
def _track_tool_usage(self, message: dict):
"""Track which GitNexus tools the agent uses."""
for action in message.get("extra", {}).get("actions", []):
command = action.get("command", "")
for key, binary in BINARIES_BY_KEY.items():
if binary in command and key in self.gitnexus_metrics.tool_calls:
self.gitnexus_metrics.tool_calls[key] += 1
break
def serialize(self, *extra_dicts) -> dict:
"""Serialize with GitNexus-specific metrics."""
gitnexus_data = {
"info": {
"gitnexus": {
"mode": self.gitnexus_mode.value,
"metrics": self.gitnexus_metrics.to_dict(),
},
},
}
return super().serialize(gitnexus_data, *extra_dicts)
class GitNexusMetrics:
"""Tracks GitNexus-specific metrics during evaluation."""
def __init__(self):
self.tool_calls: dict[str, int] = {key: 0 for key in TOOL_METRIC_KEYS}
self.augmentation_calls: int = 0
self.augmentation_hits: int = 0
self.augmentation_errors: int = 0
self.augmentation_time: float = 0.0
self.index_time: float = 0.0
@property
def total_tool_calls(self) -> int:
return sum(self.tool_calls.values())
def to_dict(self) -> dict:
return {
"tool_calls": dict(self.tool_calls),
"total_tool_calls": self.total_tool_calls,
"augmentation_calls": self.augmentation_calls,
"augmentation_hits": self.augmentation_hits,
"augmentation_errors": self.augmentation_errors,
"augmentation_time_seconds": round(self.augmentation_time, 2),
"index_time_seconds": round(self.index_time, 2),
}