diff --git a/PROTO.md b/PROTO.md index cb398e3..96a98c3 100644 --- a/PROTO.md +++ b/PROTO.md @@ -206,7 +206,9 @@ the list routes, and passed as GraphQL variables. - **`@tool` docstrings must be PLAIN string literals** — an f-string docstring makes `__doc__` None and the tool ships with no description (the model can't see it). - **Every tool requires an `owner/name` repo** — validate with `bad_repo()`. The - fallback when the arg is omitted is the LIVE configured default (`default_repo` > + fallback when the arg is omitted is the task's SCOPED default if a caller set one + (`gh_issue.scoped_default_repo(repo)`, a context manager another plugin wraps around a job + bound to one repo — the pr-reviewer's review round), else the LIVE configured default (`default_repo` > first picker entry; the picker = `github.repos` ∪ the host's `projects:` registry ∪ the `origin` remote of each registered checkout / `project_board.repo`), then the `GITHUB_DEFAULT_REPO` / `GH_REPO` env **logged at INFO when it fires**. No repo diff --git a/gh_issue.py b/gh_issue.py index 4161434..bc4fa18 100644 --- a/gh_issue.py +++ b/gh_issue.py @@ -28,6 +28,8 @@ from __future__ import annotations +import contextlib +import contextvars import logging import os import re @@ -173,15 +175,42 @@ def default_repo_error(value: str) -> str | None: ) +# The default repo for the CURRENT task, when a caller scoped one (#72). A host plugin that runs a +# job bound to one repo — the pr-reviewer's review round — sets it for the job's duration, so a +# tool call inside that job that omits `repo` resolves to the job's repo instead of the agent-wide +# default. Without it, a finder reviewing mythxengine that dropped `repo` read the first entry of +# `github.repos` (protoAgent) and reviewed the wrong codebase (pr-reviewer-plugin#367). A context +# variable, so it follows the job into the tasks and subagents it starts and nowhere else. +_SCOPED_DEFAULT: contextvars.ContextVar[str] = contextvars.ContextVar("github_scoped_default_repo", default="") + + +@contextlib.contextmanager +def scoped_default_repo(repo: str): + """Make `repo` the default for tool calls in this context (and the tasks it starts). An + explicit `repo` argument still wins; a malformed or empty `repo` scopes nothing.""" + value = (repo or "").strip() + token = _SCOPED_DEFAULT.set(value if REPO_RE.match(value) else _SCOPED_DEFAULT.get()) + try: + yield + finally: + _SCOPED_DEFAULT.reset(token) + + +def scoped_default() -> str: + """The repo scoped for the current task by `scoped_default_repo`, else ``""``.""" + return _SCOPED_DEFAULT.get() + + def resolve_repo(explicit: str | None, default_repo="") -> str | None: - """Target repo: explicit ``--repo`` > configured default > GITHUB_DEFAULT_REPO - / GH_REPO env > ``None`` (caller errors — there is no silent default). + """Target repo: explicit ``--repo`` > the task's scoped default (`scoped_default_repo`) > + configured default > GITHUB_DEFAULT_REPO / GH_REPO env > ``None`` (caller errors — there + is no silent default). ``default_repo`` may be a string or a zero-arg getter (evaluated only when no explicit repo was passed — see ``current_default``). The env step is the only source a person can't see in Settings, so it's logged at INFO whenever it's what actually decided the repo (never silently).""" - chosen = (explicit or "").strip() or current_default(default_repo) + chosen = (explicit or "").strip() or scoped_default() or current_default(default_repo) if chosen: return chosen for var in ("GITHUB_DEFAULT_REPO", "GH_REPO"): diff --git a/protoagent.plugin.yaml b/protoagent.plugin.yaml index ba67f6c..1378c4f 100644 --- a/protoagent.plugin.yaml +++ b/protoagent.plugin.yaml @@ -2,7 +2,7 @@ # Keep `version` in lockstep with pyproject.toml (tests/test_version.py asserts it). id: github name: GitHub (read/write tools) -version: 0.11.0 +version: 0.12.0 description: >- Read AND write GitHub tools over the `gh` CLI, with PER-AGENT write gating. The read tools (PRs — list + merge readiness, issues, comments, search-before-filing, diff --git a/pyproject.toml b/pyproject.toml index cd9fc38..ee111cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "github-plugin" -version = "0.11.0" +version = "0.12.0" description = "Read/write GitHub tools for protoAgent over the gh CLI, with per-agent write gating." requires-python = ">=3.11" diff --git a/read_tools.py b/read_tools.py index 9b1c60f..c0e9dc7 100644 --- a/read_tools.py +++ b/read_tools.py @@ -22,7 +22,7 @@ from langchain_core.tools import tool from .gh_cli import bad_repo, check_gh_error, dicts, error_kind, parse_json, run_gh -from .gh_issue import current_default, default_repo_error, resolve_repo +from .gh_issue import current_default, default_repo_error, resolve_repo, scoped_default # Error-relevant lines to surface from a failed CI log (github_run_failure). _CI_ERR_RE = re.compile( @@ -848,6 +848,11 @@ async def github_status() -> str: text = summarize_status(st) if bad := default_repo_error(default): text += f" NOTE: {bad}" + # Inside a job that scoped its own default (#72) the tools resolve an omitted `repo` to + # THAT repo, not the configured one — say so, or the model is told the wrong default. + # The operator banner (`compute_and_report` above) keeps the configured default. + if (scoped := scoped_default()) and scoped != default: + text += f" In this job the github_* tools default to {scoped} (configured default: {default or 'none'})." return text return [ diff --git a/tests/test_gh_issue.py b/tests/test_gh_issue.py index eca332d..3eb6dc0 100644 --- a/tests/test_gh_issue.py +++ b/tests/test_gh_issue.py @@ -239,3 +239,82 @@ async def test_gh_failure_surfaces_error(): with patch("ghplugin.gh_issue.run_gh", fake): out = await run_issue_command(f"Crash on empty --bug --repo o/n\n{_GOOD_BUG_BODY}", default_repo="") assert out.startswith("Error (gh exit 1):") and "forbidden" in out + + +# ── a task-scoped default repo (#72; pr-reviewer-plugin#367) ─────────────────────────────────── + + +def test_a_scoped_default_wins_over_the_configured_one_but_not_over_an_explicit_repo(monkeypatch): + from ghplugin.gh_issue import scoped_default, scoped_default_repo + + monkeypatch.delenv("GITHUB_DEFAULT_REPO", raising=False) + monkeypatch.delenv("GH_REPO", raising=False) + assert scoped_default() == "" + with scoped_default_repo("o/bound"): + assert resolve_repo(None, "o/default") == "o/bound" # the job's repo, not the agent's + assert resolve_repo("", lambda: "o/default") == "o/bound" + assert resolve_repo("o/explicit", "o/default") == "o/explicit" # explicit still wins + with scoped_default_repo("o/inner"): + assert resolve_repo(None, "o/default") == "o/inner" + assert resolve_repo(None, "o/default") == "o/bound" # restored on exit + assert resolve_repo(None, "o/default") == "o/default" # and gone after the job + assert scoped_default() == "" + + +@pytest.mark.parametrize("bad", ["", " ", "not-a-repo", "a/b/c", None]) +def test_a_malformed_scope_changes_nothing(bad): + from ghplugin.gh_issue import scoped_default_repo + + with scoped_default_repo(bad): + assert resolve_repo(None, "o/default") == "o/default" + + +async def test_the_scope_follows_the_job_into_the_tasks_it_starts_and_nowhere_else(): + import asyncio + + from ghplugin.gh_issue import scoped_default_repo + + seen: dict[str, str | None] = {} + + async def tool_call(name): + await asyncio.sleep(0) + seen[name] = resolve_repo(None, "o/default") + + outside = asyncio.ensure_future(asyncio.sleep(0.01)) # a task started before the scope + with scoped_default_repo("o/bound"): + await asyncio.gather(tool_call("subagent-a"), tool_call("subagent-b")) + await outside + await tool_call("after") + assert seen == {"subagent-a": "o/bound", "subagent-b": "o/bound", "after": "o/default"} + + +async def test_a_read_tool_inside_the_scope_targets_the_scoped_repo(): + from ghplugin import read_tools + from ghplugin.gh_issue import scoped_default_repo + + calls = [] + + async def fake_gh(args, *a, **k): + calls.append(args) + return 0, "{}", "" + + tools = {t.name: t for t in read_tools.get_read_tools("o/default")} + with patch.object(read_tools, "run_gh", fake_gh): + with scoped_default_repo("o/bound"): + await tools["github_get_pr"].ainvoke({"number": 7}) + await tools["github_get_pr"].ainvoke({"number": 7}) + repos = [a[a.index("--repo") + 1] for a in calls if "--repo" in a] + assert repos[0] == "o/bound" and repos[-1] == "o/default" + + +async def test_github_status_names_the_scoped_default_inside_a_scoped_job(): + from ghplugin import read_tools + from ghplugin.gh_issue import scoped_default_repo + + tools = {t.name: t for t in read_tools.get_read_tools("o/default", ["o/default"])} + with patch("ghplugin.status.resolve_gh", return_value=None): + outside = await tools["github_status"].ainvoke({}) + with scoped_default_repo("o/bound"): + inside = await tools["github_status"].ainvoke({}) + assert "In this job" not in outside + assert "In this job the github_* tools default to o/bound (configured default: o/default)." in inside diff --git a/uv.lock b/uv.lock index 259fa5c..a54c656 100644 --- a/uv.lock +++ b/uv.lock @@ -4,5 +4,5 @@ requires-python = ">=3.11" [[package]] name = "github-plugin" -version = "0.11.0" +version = "0.12.0" source = { virtual = "." }