agentgate-ci 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. agentgate/__init__.py +0 -0
  2. agentgate/__main__.py +5 -0
  3. agentgate/adapters/__init__.py +0 -0
  4. agentgate/adapters/base.py +156 -0
  5. agentgate/cache.py +69 -0
  6. agentgate/ci/__init__.py +0 -0
  7. agentgate/ci/github.py +124 -0
  8. agentgate/ci/publish.py +117 -0
  9. agentgate/cli.py +1242 -0
  10. agentgate/config.py +281 -0
  11. agentgate/demo.py +185 -0
  12. agentgate/demo_bundle/agentgate.yaml +67 -0
  13. agentgate/demo_bundle/golden.jsonl +50 -0
  14. agentgate/demo_bundle/runs.json.gz +0 -0
  15. agentgate/demo_bundle/security.jsonl +25 -0
  16. agentgate/gate/__init__.py +0 -0
  17. agentgate/gate/aa.py +236 -0
  18. agentgate/gate/compare.py +255 -0
  19. agentgate/gate/data.py +144 -0
  20. agentgate/gate/orchestrate.py +466 -0
  21. agentgate/gate/planted.py +359 -0
  22. agentgate/gate/policy.py +321 -0
  23. agentgate/gate/security.py +92 -0
  24. agentgate/gate/versions.py +109 -0
  25. agentgate/load/__init__.py +0 -0
  26. agentgate/load/canary.py +55 -0
  27. agentgate/load/checkpoints.py +91 -0
  28. agentgate/load/commands.py +165 -0
  29. agentgate/load/report.py +203 -0
  30. agentgate/load/runner.py +151 -0
  31. agentgate/migrate.py +64 -0
  32. agentgate/provenance.py +81 -0
  33. agentgate/reads.py +514 -0
  34. agentgate/reporters/__init__.py +0 -0
  35. agentgate/reporters/json_report.py +46 -0
  36. agentgate/reporters/markdown.py +172 -0
  37. agentgate/runner.py +251 -0
  38. agentgate/scorers/__init__.py +0 -0
  39. agentgate/scorers/aggregate.py +139 -0
  40. agentgate/scorers/case_scorer.py +95 -0
  41. agentgate/scorers/deterministic.py +60 -0
  42. agentgate/scorers/judge.py +285 -0
  43. agentgate/scorers/rubrics.py +97 -0
  44. agentgate/security/__init__.py +0 -0
  45. agentgate/security/checks.py +65 -0
  46. agentgate/security/pii.py +77 -0
  47. agentgate/security/rubrics.py +61 -0
  48. agentgate/security/scorer.py +129 -0
  49. agentgate/security/similarity.py +25 -0
  50. agentgate/settings.py +34 -0
  51. agentgate/sql/0003_eval_runs.sql +55 -0
  52. agentgate/sql/0004_eval_run_scope.sql +5 -0
  53. agentgate/sql/0005_gate_decisions.sql +25 -0
  54. agentgate/sql/__init__.py +1 -0
  55. agentgate/stats/__init__.py +0 -0
  56. agentgate/stats/bootstrap.py +220 -0
  57. agentgate/stats/run_intervals.py +92 -0
  58. agentgate/store.py +415 -0
  59. agentgate/validation/__init__.py +0 -0
  60. agentgate/validation/agreement.py +295 -0
  61. agentgate/validation/commands.py +247 -0
  62. agentgate/validation/groundedness_sample.py +170 -0
  63. agentgate/validation/labeler.py +167 -0
  64. agentgate/validation/labels.py +62 -0
  65. agentgate/validation/rescore.py +130 -0
  66. agentgate/validation/sample.py +286 -0
  67. agentgate_ci-0.1.0.dist-info/METADATA +263 -0
  68. agentgate_ci-0.1.0.dist-info/RECORD +71 -0
  69. agentgate_ci-0.1.0.dist-info/WHEEL +4 -0
  70. agentgate_ci-0.1.0.dist-info/entry_points.txt +2 -0
  71. agentgate_ci-0.1.0.dist-info/licenses/LICENSE +21 -0
agentgate/__init__.py ADDED
File without changes
agentgate/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """`python -m agentgate`: the entry point the gate uses to start its scoring workers."""
2
+
3
+ from agentgate.cli import app
4
+
5
+ app(prog_name="agentgate")
File without changes
@@ -0,0 +1,156 @@
1
+ """Framework-neutral types the gate uses to talk to any agent (PRD section 9).
2
+
3
+ This module must never import LangGraph or any agent framework: the gate only sees these types.
4
+
5
+ `AgentAdapter.run` takes a `RunContext` on top of PRD 9's `run(case, version)`: the runner needs a
6
+ unique session per repeat and has to pass the eval run id to the agent's tracing.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Literal, Protocol, Self, runtime_checkable
12
+
13
+ from pydantic import BaseModel, ConfigDict, Field, computed_field
14
+
15
+ AgentErrorKind = Literal[
16
+ "step_limit", "timeout", "token_budget", "llm_error", "tool_error", "internal_error"
17
+ ]
18
+ # "blocked": refused by the agent's own policy before any human was asked (e.g. a send guard).
19
+ ToolCallStatus = Literal["ok", "error", "rejected", "blocked"]
20
+ SecurityCheckName = Literal[
21
+ "no_unapproved_send",
22
+ "approval_gate",
23
+ "no_send_attempt",
24
+ "no_pii",
25
+ "terminates_cleanly",
26
+ "no_prompt_leak",
27
+ ]
28
+
29
+ OUTPUT_PREVIEW_CHARS = 500
30
+
31
+
32
+ class AgentVersion(BaseModel):
33
+ """The versioned tuple (prompt files, model, temperature, tool config, retrieval config,
34
+ and the agent's code)."""
35
+
36
+ model_config = ConfigDict(frozen=True)
37
+
38
+ version_id: str
39
+ model: str
40
+ temperature: str
41
+ prompt_hashes: dict[str, str]
42
+ tool_config: dict[str, Any]
43
+ retrieval_config: dict[str, Any]
44
+ # Content hash of the agent's source code. None for versions stored before 2026-11-29.
45
+ code_hash: str | None = None
46
+
47
+
48
+ class ToolCallRecord(BaseModel):
49
+ name: str
50
+ args: dict[str, Any]
51
+ status: ToolCallStatus
52
+ output_preview: str = Field(max_length=OUTPUT_PREVIEW_CHARS)
53
+ latency_ms: float
54
+ # Retrieval results of this call, in rank order (empty for non-retrieval tools).
55
+ doc_ids: list[str] = Field(default_factory=list)
56
+
57
+
58
+ class ApprovalRecord(BaseModel):
59
+ """A human-approval decision taken during a run (by a person, or by the eval policy)."""
60
+
61
+ decision: Literal["approve", "reject"]
62
+ reason: Literal["case_policy", "no_policy_default_reject", "round_limit"]
63
+ recipients: list[str]
64
+
65
+
66
+ class AgentError(BaseModel):
67
+ kind: AgentErrorKind
68
+ message: str
69
+
70
+
71
+ class Trajectory(BaseModel):
72
+ """Everything one agent invocation did, for scoring and tracing."""
73
+
74
+ version_id: str
75
+ session_id: str
76
+ final_answer: str | None = None
77
+ tool_calls: list[ToolCallRecord] = Field(default_factory=list)
78
+ retrieved_doc_ids: list[str] = Field(default_factory=list)
79
+ steps: int = 0
80
+ tokens_in: int = 0
81
+ tokens_out: int = 0
82
+ cost_usd: float = 0.0
83
+ # Wall time of this invocation only (a resumed run after approval is a separate invocation).
84
+ latency_ms: float = 0.0
85
+ trace_id: str | None = None
86
+ error: AgentError | None = None
87
+ # Text the agent retrieved (what groundedness is judged against).
88
+ retrieved_context: list[str] = Field(default_factory=list)
89
+ approvals: list[ApprovalRecord] = Field(default_factory=list)
90
+
91
+ @computed_field # type: ignore[prop-decorator]
92
+ @property
93
+ def tokens_total(self) -> int:
94
+ return self.tokens_in + self.tokens_out
95
+
96
+
97
+ class CaseApproval(BaseModel):
98
+ """What the (simulated) human decides when the case's agent asks to send an email."""
99
+
100
+ model_config = ConfigDict(extra="forbid", frozen=True)
101
+
102
+ decision: Literal["approve", "reject"]
103
+ to: str
104
+ expected_sent: bool
105
+
106
+
107
+ class SecuritySpec(BaseModel):
108
+ """How a security case is scored: the checks that must all pass (agentgate/security)."""
109
+
110
+ model_config = ConfigDict(extra="forbid", frozen=True)
111
+
112
+ checks: list[SecurityCheckName] = Field(min_length=1)
113
+ max_steps: int | None = Field(default=None, ge=1)
114
+
115
+
116
+ class Case(BaseModel):
117
+ """One dataset case (PRD 7.3). Framework-neutral: tool and category names are plain strings."""
118
+
119
+ model_config = ConfigDict(extra="forbid", frozen=True)
120
+
121
+ id: str
122
+ category: str
123
+ input: str = Field(min_length=1)
124
+ expected_answer: str
125
+ expected_tools: list[str] = Field(default_factory=list)
126
+ forbidden_tools: list[str] = Field(default_factory=list)
127
+ expected_doc_ids: list[str] = Field(default_factory=list)
128
+ tags: list[str] = Field(default_factory=list)
129
+ critical: bool = False
130
+ derivation: str | None = None
131
+ approval: CaseApproval | None = None
132
+ security: SecuritySpec | None = None
133
+
134
+
135
+ class RunContext(BaseModel):
136
+ """Which eval run and repeat an agent invocation belongs to."""
137
+
138
+ model_config = ConfigDict(frozen=True)
139
+
140
+ eval_run_id: str
141
+ repeat_idx: int = Field(ge=0)
142
+ # Retries of a case-run start a fresh session: never continue a failed attempt's history.
143
+ attempt: int = Field(default=1, ge=1)
144
+
145
+
146
+ @runtime_checkable
147
+ class AgentAdapter(Protocol):
148
+ """How the gate talks to any agent (PRD 9). Used as `async with adapter: ...`."""
149
+
150
+ async def __aenter__(self) -> Self: ...
151
+
152
+ async def __aexit__(self, *exc: object) -> None: ...
153
+
154
+ def load_version(self, ref: str) -> AgentVersion: ...
155
+
156
+ async def run(self, case: Case, version: AgentVersion, ctx: RunContext) -> Trajectory: ...
agentgate/cache.py ADDED
@@ -0,0 +1,69 @@
1
+ """Baseline result cache and the pre-run cost estimate (PRD 7.5).
2
+
3
+ Cache: a baseline is reused when a stored run matches the version, dataset hash, judge
4
+ fingerprint and repeats, finished `completed`, and covered the whole dataset (`case_limit IS
5
+ NULL`, same case count). Partial, failed and budget-exceeded runs are never baselines. Only the
6
+ baseline is cached; the candidate is always scored fresh, or an A/A run would compare a run with
7
+ itself.
8
+
9
+ Estimate: the per-case-run cost (agent + judge) of the newest complete run of this version with
10
+ this judge and dataset; else of any version with this judge and dataset; else the config's
11
+ fallback. The estimate guards the budget before any money is spent; the runner's hard cap still
12
+ stops a run that turns out more expensive (e.g. a pricier candidate model).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from typing import Literal
19
+
20
+ from pydantic import BaseModel
21
+
22
+ from agentgate.config import GateConfig
23
+ from agentgate.store import CacheKey, GateStore
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ EstimateSource = Literal["same_version", "same_judge", "config_fallback"]
28
+
29
+
30
+ class Estimate(BaseModel):
31
+ per_case_run: float
32
+ total: float
33
+ source: EstimateSource
34
+
35
+
36
+ async def lookup_baseline(store: GateStore, key: CacheKey) -> str | None:
37
+ run_id = await store.find_cached_run(key)
38
+ logger.info(
39
+ "gate.cache_lookup", extra={"version_id": key.version_id, "hit": run_id is not None}
40
+ )
41
+ return run_id
42
+
43
+
44
+ async def estimate_cost(
45
+ store: GateStore,
46
+ cfg: GateConfig,
47
+ *,
48
+ key: CacheKey,
49
+ case_runs: int,
50
+ fallback: float | None = None,
51
+ ) -> Estimate:
52
+ """`fallback` overrides `budget.fallback_usd_per_case_run` (the security suite has its own)."""
53
+ per: float | None = await store.cost_per_case_run(
54
+ judge_fingerprint=key.judge_fingerprint,
55
+ dataset_id=key.dataset_id,
56
+ version_id=key.version_id,
57
+ )
58
+ source: EstimateSource = "same_version"
59
+ if per is None:
60
+ per = await store.cost_per_case_run(
61
+ judge_fingerprint=key.judge_fingerprint, dataset_id=key.dataset_id, version_id=None
62
+ )
63
+ source = "same_judge"
64
+ if per is None:
65
+ per = fallback if fallback is not None else cfg.budget.fallback_usd_per_case_run
66
+ source = "config_fallback"
67
+ estimate = Estimate(per_case_run=per, total=per * case_runs, source=source)
68
+ logger.info("gate.estimate", extra=estimate.model_dump())
69
+ return estimate
File without changes
agentgate/ci/github.py ADDED
@@ -0,0 +1,124 @@
1
+ """The two GitHub REST calls the gate needs: keep ONE PR comment up to date, create a check run.
2
+
3
+ Sync httpx (one short-lived CLI call per workflow run). Errors name the method, the path
4
+ template and the HTTP status, never the token or a response body (it can echo user input).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import re
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ from agentgate.ci.publish import Conclusion
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ API_URL = "https://api.github.com"
20
+ API_VERSION = "2022-11-28"
21
+ PAGE_SIZE = 100
22
+ TIMEOUT_S = 30.0
23
+ # GitHub owners are letters, digits and hyphens; a repo name may not be "." or "..".
24
+ REPO_PATTERN = re.compile(r"^[A-Za-z0-9-]+/(?!\.\.?$)[\w.-]+$")
25
+
26
+
27
+ class GitHubError(RuntimeError):
28
+ """A GitHub API call failed. The message never contains the token."""
29
+
30
+
31
+ class GitHubClient:
32
+ def __init__(
33
+ self,
34
+ token: str,
35
+ repo: str,
36
+ api_url: str = API_URL,
37
+ *,
38
+ transport: httpx.BaseTransport | None = None,
39
+ ) -> None:
40
+ if not REPO_PATTERN.fullmatch(repo):
41
+ raise GitHubError(f"repository must look like owner/name, got {repo!r}")
42
+ self._repo = repo
43
+ self._http = httpx.Client(
44
+ base_url=api_url.rstrip("/"),
45
+ headers={
46
+ "Authorization": f"Bearer {token}",
47
+ "Accept": "application/vnd.github+json",
48
+ "X-GitHub-Api-Version": API_VERSION,
49
+ },
50
+ timeout=TIMEOUT_S,
51
+ transport=transport,
52
+ )
53
+
54
+ def close(self) -> None:
55
+ self._http.close()
56
+
57
+ def _call(self, method: str, template: str, path: str, **kwargs: Any) -> Any:
58
+ try:
59
+ resp = self._http.request(method, path, **kwargs)
60
+ except httpx.HTTPError as exc:
61
+ raise GitHubError(f"GitHub {method} {template} failed ({type(exc).__name__})") from None
62
+ if resp.status_code >= 300:
63
+ hint = " (read-only token: a forked PR?)" if resp.status_code == 403 else ""
64
+ raise GitHubError(f"GitHub {method} {template} failed (HTTP {resp.status_code}){hint}")
65
+ return resp.json() if resp.content else None
66
+
67
+ def find_comment(self, pr: int, marker: str) -> int | None:
68
+ """Id of the first PR comment whose body STARTS with `marker` (a quote doesn't count)."""
69
+ template = "/repos/{repo}/issues/{pr}/comments"
70
+ page = 1
71
+ while True:
72
+ items = self._call(
73
+ "GET",
74
+ template,
75
+ f"/repos/{self._repo}/issues/{pr}/comments",
76
+ params={"per_page": PAGE_SIZE, "page": page},
77
+ )
78
+ for item in items or []:
79
+ if str(item.get("body") or "").startswith(marker):
80
+ return int(item["id"])
81
+ if not items or len(items) < PAGE_SIZE:
82
+ return None
83
+ page += 1
84
+
85
+ def upsert_comment(self, pr: int, body: str, marker: str) -> tuple[int, bool]:
86
+ """(comment id, created?): edit the marked comment, or create it if there is none."""
87
+ existing = self.find_comment(pr, marker)
88
+ if existing is not None:
89
+ self._call(
90
+ "PATCH",
91
+ "/repos/{repo}/issues/comments/{id}",
92
+ f"/repos/{self._repo}/issues/comments/{existing}",
93
+ json={"body": body},
94
+ )
95
+ logger.info("ci.comment_updated", extra={"pr": pr, "comment_id": existing})
96
+ return existing, False
97
+ created = self._call(
98
+ "POST",
99
+ "/repos/{repo}/issues/{pr}/comments",
100
+ f"/repos/{self._repo}/issues/{pr}/comments",
101
+ json={"body": body},
102
+ )
103
+ comment_id = int(created["id"])
104
+ logger.info("ci.comment_created", extra={"pr": pr, "comment_id": comment_id})
105
+ return comment_id, True
106
+
107
+ def create_check_run(
108
+ self, *, head_sha: str, name: str, conclusion: Conclusion, title: str, summary: str
109
+ ) -> int:
110
+ created = self._call(
111
+ "POST",
112
+ "/repos/{repo}/check-runs",
113
+ f"/repos/{self._repo}/check-runs",
114
+ json={
115
+ "name": name,
116
+ "head_sha": head_sha,
117
+ "status": "completed",
118
+ "conclusion": conclusion,
119
+ "output": {"title": title[:250], "summary": summary},
120
+ },
121
+ )
122
+ check_id = int(created["id"])
123
+ logger.info("ci.check_created", extra={"check_id": check_id, "conclusion": conclusion})
124
+ return check_id
@@ -0,0 +1,117 @@
1
+ """Turn a gate report into what a PR shows: one comment body and a check conclusion (ADR 0007).
2
+
3
+ Pure functions: no I/O. agentgate/ci/github.py posts the results.
4
+
5
+ | verdict | check | exit |
6
+ |------------|-----------------------------------------|------|
7
+ | pass | success | 0 |
8
+ | warn | success (failure with fail_on_warn) | 0/1 |
9
+ | block | failure | 1 |
10
+ | no_verdict | neutral (PRD 17: infra noise is neutral) | 0 |
11
+ | no report | failure (the gate itself failed to run) | 1 |
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Literal
17
+
18
+ from pydantic import BaseModel
19
+
20
+ from agentgate.reporters.json_report import GateReport
21
+
22
+ MARKER = "<!-- agentgate:report -->"
23
+ MAX_BODY = 65_000 # GitHub caps comment bodies at 65,536 characters
24
+ MAX_SUMMARY = 60_000 # check-run output.summary caps at 65,535
25
+ TRUNCATED = "\n\n… (truncated; the full report is in the workflow run)"
26
+ Conclusion = Literal["success", "failure", "neutral"]
27
+
28
+
29
+ class Outcome(BaseModel):
30
+ conclusion: Conclusion
31
+ exit_code: int
32
+ title: str
33
+
34
+
35
+ def _first_reason(report: GateReport) -> str | None:
36
+ v = report.verdict
37
+ for m in v.metrics:
38
+ if m.verdict == "block":
39
+ return f"{m.comparison.metric}: {m.reason}"
40
+ for r in v.hard_rules:
41
+ if r.outcome in ("block", "no_verdict"):
42
+ return r.reason
43
+ for m in v.metrics:
44
+ if m.verdict == "warn":
45
+ return f"{m.comparison.metric}: {m.reason}"
46
+ return None
47
+
48
+
49
+ def outcome(report: GateReport, *, fail_on_warn: bool) -> Outcome:
50
+ verdict = report.verdict.verdict
51
+ reason = _first_reason(report)
52
+ if verdict == "block":
53
+ return Outcome(
54
+ conclusion="failure", exit_code=1, title=f"blocked: {reason or 'see report'}"
55
+ )
56
+ if verdict == "no_verdict":
57
+ return Outcome(conclusion="neutral", exit_code=0, title=f"no verdict: {reason or ''}")
58
+ if verdict == "warn":
59
+ failing = fail_on_warn
60
+ return Outcome(
61
+ conclusion="failure" if failing else "success",
62
+ exit_code=1 if failing else 0,
63
+ title=f"passed with warnings: {reason or ''}".rstrip(": "),
64
+ )
65
+ return Outcome(conclusion="success", exit_code=0, title="passed")
66
+
67
+
68
+ def _footer(run_url: str | None, head_sha: str) -> str:
69
+ parts = [f"updated for {head_sha[:7]}"]
70
+ if run_url:
71
+ parts.insert(0, f"[workflow run]({run_url})")
72
+ return "<sub>" + " · ".join(parts) + "</sub>"
73
+
74
+
75
+ def comment_body(markdown: str, *, run_url: str | None, head_sha: str) -> str:
76
+ """The marker on the first line, the report as-is, a footer; never over MAX_BODY."""
77
+ footer = _footer(run_url, head_sha)
78
+ head = MARKER + "\n"
79
+ room = MAX_BODY - len(head) - len(footer) - 2
80
+ if len(markdown) > room:
81
+ markdown = markdown[: room - len(TRUNCATED)] + TRUNCATED
82
+ return f"{head}{markdown}\n\n{footer}"
83
+
84
+
85
+ def summary(markdown: str) -> str:
86
+ """The check run's summary: the report, truncated to GitHub's limit."""
87
+ if len(markdown) <= MAX_SUMMARY:
88
+ return markdown
89
+ return markdown[: MAX_SUMMARY - len(TRUNCATED)] + TRUNCATED
90
+
91
+
92
+ def crashed_body(*, run_url: str | None, head_sha: str, detail: str) -> str:
93
+ text = (
94
+ "❌ AgentGate: the gate failed to run\n\n"
95
+ f"No report was produced ({detail}). This is not a verdict on the change: "
96
+ "open the workflow run for the error."
97
+ )
98
+ return comment_body(text, run_url=run_url, head_sha=head_sha)
99
+
100
+
101
+ def no_changes_body(*, run_url: str | None, head_sha: str, paths: str) -> str:
102
+ text = (
103
+ "✅ AgentGate: nothing to gate\n\n"
104
+ f"This pull request no longer changes the agent (`{paths}`) compared with its base, "
105
+ "so there is nothing to score. Any earlier report on this pull request no longer applies."
106
+ )
107
+ return comment_body(text, run_url=run_url, head_sha=head_sha)
108
+
109
+
110
+ def skipped_summary(reason: str) -> str:
111
+ return (
112
+ "⏸️ AgentGate skipped\n\n"
113
+ f"{reason}\n\n"
114
+ "Forked pull requests don't receive repository secrets, so the gate can't call the "
115
+ "model provider, and their read-only token can't comment either. A maintainer can run "
116
+ "the gate from a branch in this repository."
117
+ )