You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@magpie.apache.org by "sjyangkevin (via GitHub)" <gi...@apache.org> on 2026/09/11 04:39:47 UTC
[PR] feat(gemini): integrate gemini cli as runtime [magpie]
sjyangkevin opened a new pull request, #1199:
URL: https://github.com/apache/magpie/pull/1199
<!-- SPDX-License-Identifier: Apache-2.0
https://www.apache.org/licenses/LICENSE-2.0 -->
## Summary
- Connect Gemini CLI shell calls to Magpie's existing action guard through a `BeforeTool` adapter and project `.gemini/settings.json`. The hook uses a portable path and preserves the shared guard decisions.
- Import `AGENTS.md` from `GEMINI.md` and forward the requested output format through the existing Gemini spec-loop profile, reusing the canonical skill sources.
- Document the implemented runtime contract and update the runtime declarations and specs. Snapshot adopters still register the hook in their own settings; full policy and sandbox parity remain open.
## Type of change
<!-- Tick all that apply. -->
- [ ] Skill change (`.claude/skills/<name>/`) — eval fixtures updated below
- [ ] Tool / bridge contract (`tools/<system>/*.md`)
- [X] Python package (`tools/*/` with `pyproject.toml`)
- [ ] Groovy reference impl
- [ ] Cross-cutting (RFC, AGENTS.md, sandbox, privacy-LLM)
- [X] Documentation (`docs/`, `README.md`, `CONTRIBUTING.md`)
- [ ] Project template (`projects/_template/`)
- [X] CI / dev loop (`prek`, workflows, validators)
- [ ] Other:
## Test plan
<!--
How you verified the change. Be specific. The reviewer reads this to
decide what to spot-check vs trust. Empty "ran the tests" doesn't help.
-->
- [X] `prek run --all-files` passes
- [X] For Python packages touched: `uv run pytest` / `ruff check` / `mypy` passes
- [ ] For Groovy bridges touched: command-line invocation tested end-to-end
- [ ] For skill changes: eval suite passes for the affected skill
(`PYTHONPATH=tools/skill-evals/src python3 -m skill_evals.runner tools/skill-evals/evals/<skill>/`)
- [ ] For skill *behaviour* changes: a new or updated eval fixture is included in this PR
(a regression test for the bug fixed / the behaviour added — see CONTRIBUTING.md)
- [ ] Other:
## RFC-AI-0004 compliance
<!--
Tick the principles the change touches. Skip rows that don't apply.
RFC-AI-0004 is the framework's constitution — see
docs/rfcs/RFC-AI-0004.md.
-->
- [ ] **HITL** — any new mutation is gated on explicit user confirmation
- [ ] **Sandbox** — no new unrestricted host access; network reach declared in the adapter
- [X] **Vendor neutrality** — placeholders (`<PROJECT>`, `<tracker>`, `<upstream>`, `<security-list>`) used in all skill / tool prose (the `check-placeholders` prek hook is the mechanical gate)
- [ ] **Conversational + correctable** — agentic-override path documented if behaviour is adopter-tunable
- [X] **Write-access discipline** — no autonomous outbound messages; drafts only, sent on confirmation
- [ ] **Privacy LLM** — private content does not reach a non-approved LLM; redactor invoked where needed
## Linked issues
<!-- e.g. Closes #NNN, Refs #NNN. List every related issue. -->
Refs #314.
## Notes for reviewers (optional)
Metadata validation reports 38 existing advisory warnings. The workspace test run used temporary `jq` dependencies and a clean temporary directory to avoid an existing `/tmp/.git` in the local environment.
<!--
Anything specific you want the reviewer to look at. Areas of uncertainty.
Trade-offs you considered and rejected. Decisions that the agent and you
disagreed on during the authoring loop.
-->
**Generative AI disclosure:** Codex (GPT-6) assisted with implementation, documentation, tests, and preparation of this PR description.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gemini): integrate gemini cli as runtime [magpie]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk merged PR #1199:
URL: https://github.com/apache/magpie/pull/1199
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gemini): integrate gemini cli as runtime [magpie]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #1199:
URL: https://github.com/apache/magpie/pull/1199#discussion_r3996362071
##########
tools/agent-guard/tests/test_gemini.py:
##########
@@ -0,0 +1,220 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for Gemini CLI's BeforeTool adapter.
+
+Like the OpenCode and Kiro suites, these check the hook's transport and its
+agreement with the harness-neutral guard core. Guard rule details remain in
+test_guards.py and test_skill_guards.py.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import agent_guard
Review Comment:
Fixed.
##########
tools/agent-guard/tests/test_gemini.py:
##########
@@ -0,0 +1,220 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for Gemini CLI's BeforeTool adapter.
+
+Like the OpenCode and Kiro suites, these check the hook's transport and its
+agreement with the harness-neutral guard core. Guard rule details remain in
+test_guards.py and test_skill_guards.py.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import agent_guard
+from agent_guard import ALLOW_EXIT, DENY_EXIT, cli, dispatch, gemini_main
+
+
+@pytest.fixture(autouse=True)
+def _clear_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for name in (
+ "MAGPIE_GUARD_OFF",
+ "MAGPIE_GUARD_DIRS",
+ "MAGPIE_ALLOW_COAUTHOR",
+ "MAGPIE_ALLOW_EMPTY_PUSH",
+ "MAGPIE_ALLOW_NO_VERIFY",
+ ):
+ monkeypatch.delenv(name, raising=False)
+
+
+def _feed(monkeypatch: pytest.MonkeyPatch, payload: object) -> None:
+ text = payload if isinstance(payload, str) else json.dumps(payload)
+ monkeypatch.setattr("sys.stdin", io.StringIO(text))
+
+
+def _event(command: str) -> dict:
+ return {
+ "hook_event_name": "BeforeTool",
+ "cwd": ".",
+ "tool_name": "run_shell_command",
+ "tool_input": {"command": command},
+ }
+
+
+def test_cli_blocks_prohibited_trailer_without_executing_command(tmp_path: Path) -> None:
+ marker = tmp_path / "must-not-exist"
+ event = _event(f"git commit -m 'x\n\nCo-Authored-By: A <a...@b.c>'; touch '{marker}'")
+ event["cwd"] = str(tmp_path)
+ result = subprocess.run(
+ [sys.executable, agent_guard.__file__, "--gemini"],
+ input=json.dumps(event),
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ assert result.returncode == DENY_EXIT
+ assert "commit-trailer" in result.stderr
+ assert result.stdout == ""
+ assert not marker.exists()
+
+
+def test_allowed_command_is_silent(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ _feed(monkeypatch, _event("git status"))
+ assert cli(["--gemini"]) == ALLOW_EXIT
+ assert capsys.readouterr() == ("", "")
+
+
+@pytest.mark.parametrize(
+ "command, expected, reason",
+ [
+ ("git status --short", ALLOW_EXIT, ""),
+ ("git commit --dry-run --no-verify -m hook-probe", DENY_EXIT, "agent-guard[no-verify]"),
+ ],
+)
+def test_project_settings_hook_runs_from_a_checkout_path_with_spaces(
+ tmp_path: Path, command: str, expected: int, reason: str
+) -> None:
+ repo_root = Path(agent_guard.__file__).resolve().parents[4]
+ project = tmp_path / "checkout with spaces"
+ project.symlink_to(repo_root, target_is_directory=True)
+ settings = json.loads((project / ".gemini" / "settings.json").read_text())
+ event = _event(command)
+ event["cwd"] = str(project)
+ hooks = [
+ hook
+ for group in settings["hooks"]["BeforeTool"]
+ if re.search(group["matcher"], event["tool_name"])
+ for hook in group["hooks"]
+ ]
+ assert len(hooks) == 1
+ # Execute the registered command, never the proposed tool command.
+ result = subprocess.run(
+ hooks[0]["command"],
+ shell=True,
+ cwd=tmp_path,
+ env={**os.environ, "GEMINI_PROJECT_DIR": str(project)},
+ input=json.dumps(event),
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ assert result.returncode == expected
+ assert result.stdout == ""
+ if reason:
+ assert reason in result.stderr
+ else:
+ assert result.stderr == ""
+
+
+@pytest.mark.parametrize(
+ "command, expected",
+ [
+ ("git commit -m 'x\n\nCo-Authored-By: A <a...@b.c>'", DENY_EXIT),
+ ("git commit -m 'x' --no-verify", DENY_EXIT),
+ ("git commit -m 'x\n\nGenerated-by: Gemini CLI'", ALLOW_EXIT),
+ ("ls -la && echo hi", ALLOW_EXIT),
+ ],
+)
+def test_decision_and_reason_match_dispatch(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ command: str,
+ expected: int,
+) -> None:
+ # The adapter preserves the core's decision and emits its reason on stderr.
+ reason = dispatch(command, ".")
+ assert (reason is not None) == (expected == DENY_EXIT)
+
+ _feed(monkeypatch, _event(command))
+ assert gemini_main() == expected
+ gemini_output = capsys.readouterr()
+ assert gemini_output.err == (reason + "\n" if reason else "")
+ assert gemini_output.out == ""
+
+
+@pytest.mark.parametrize("cwd_kind", ["workspace", "missing", "invalid"])
+def test_git_checks_use_event_workspace(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ tmp_path: Path,
+ cwd_kind: str,
+) -> None:
+ # Follow the bundled empty-rebase test: stub Git reads, never execute a push.
+ seen = []
+
+ def fake_run(args: list[str], cwd: str | None = None) -> str | None:
Review Comment:
Fixed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gemini): integrate gemini cli as runtime [magpie]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #1199:
URL: https://github.com/apache/magpie/pull/1199#issuecomment-5645774662
Nice. Let me merge it - looks **good** and I am also testing few other CLIs - and preparing guides/installations - so I might test it a bit more today/tomorrow.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(gemini): integrate gemini cli as runtime [magpie]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #1199:
URL: https://github.com/apache/magpie/pull/1199#discussion_r3996156394
##########
tools/agent-guard/tests/test_gemini.py:
##########
@@ -0,0 +1,220 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for Gemini CLI's BeforeTool adapter.
+
+Like the OpenCode and Kiro suites, these check the hook's transport and its
+agreement with the harness-neutral guard core. Guard rule details remain in
+test_guards.py and test_skill_guards.py.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import agent_guard
+from agent_guard import ALLOW_EXIT, DENY_EXIT, cli, dispatch, gemini_main
+
+
+@pytest.fixture(autouse=True)
+def _clear_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for name in (
+ "MAGPIE_GUARD_OFF",
+ "MAGPIE_GUARD_DIRS",
+ "MAGPIE_ALLOW_COAUTHOR",
+ "MAGPIE_ALLOW_EMPTY_PUSH",
+ "MAGPIE_ALLOW_NO_VERIFY",
+ ):
+ monkeypatch.delenv(name, raising=False)
+
+
+def _feed(monkeypatch: pytest.MonkeyPatch, payload: object) -> None:
+ text = payload if isinstance(payload, str) else json.dumps(payload)
+ monkeypatch.setattr("sys.stdin", io.StringIO(text))
+
+
+def _event(command: str) -> dict:
+ return {
+ "hook_event_name": "BeforeTool",
+ "cwd": ".",
+ "tool_name": "run_shell_command",
+ "tool_input": {"command": command},
+ }
+
+
+def test_cli_blocks_prohibited_trailer_without_executing_command(tmp_path: Path) -> None:
+ marker = tmp_path / "must-not-exist"
+ event = _event(f"git commit -m 'x\n\nCo-Authored-By: A <a...@b.c>'; touch '{marker}'")
+ event["cwd"] = str(tmp_path)
+ result = subprocess.run(
+ [sys.executable, agent_guard.__file__, "--gemini"],
+ input=json.dumps(event),
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ assert result.returncode == DENY_EXIT
+ assert "commit-trailer" in result.stderr
+ assert result.stdout == ""
+ assert not marker.exists()
+
+
+def test_allowed_command_is_silent(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ _feed(monkeypatch, _event("git status"))
+ assert cli(["--gemini"]) == ALLOW_EXIT
+ assert capsys.readouterr() == ("", "")
+
+
+@pytest.mark.parametrize(
+ "command, expected, reason",
+ [
+ ("git status --short", ALLOW_EXIT, ""),
+ ("git commit --dry-run --no-verify -m hook-probe", DENY_EXIT, "agent-guard[no-verify]"),
+ ],
+)
+def test_project_settings_hook_runs_from_a_checkout_path_with_spaces(
+ tmp_path: Path, command: str, expected: int, reason: str
+) -> None:
+ repo_root = Path(agent_guard.__file__).resolve().parents[4]
+ project = tmp_path / "checkout with spaces"
+ project.symlink_to(repo_root, target_is_directory=True)
+ settings = json.loads((project / ".gemini" / "settings.json").read_text())
+ event = _event(command)
+ event["cwd"] = str(project)
+ hooks = [
+ hook
+ for group in settings["hooks"]["BeforeTool"]
+ if re.search(group["matcher"], event["tool_name"])
+ for hook in group["hooks"]
+ ]
+ assert len(hooks) == 1
+ # Execute the registered command, never the proposed tool command.
+ result = subprocess.run(
+ hooks[0]["command"],
+ shell=True,
+ cwd=tmp_path,
+ env={**os.environ, "GEMINI_PROJECT_DIR": str(project)},
+ input=json.dumps(event),
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+ assert result.returncode == expected
+ assert result.stdout == ""
+ if reason:
+ assert reason in result.stderr
+ else:
+ assert result.stderr == ""
+
+
+@pytest.mark.parametrize(
+ "command, expected",
+ [
+ ("git commit -m 'x\n\nCo-Authored-By: A <a...@b.c>'", DENY_EXIT),
+ ("git commit -m 'x' --no-verify", DENY_EXIT),
+ ("git commit -m 'x\n\nGenerated-by: Gemini CLI'", ALLOW_EXIT),
+ ("ls -la && echo hi", ALLOW_EXIT),
+ ],
+)
+def test_decision_and_reason_match_dispatch(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ command: str,
+ expected: int,
+) -> None:
+ # The adapter preserves the core's decision and emits its reason on stderr.
+ reason = dispatch(command, ".")
+ assert (reason is not None) == (expected == DENY_EXIT)
+
+ _feed(monkeypatch, _event(command))
+ assert gemini_main() == expected
+ gemini_output = capsys.readouterr()
+ assert gemini_output.err == (reason + "\n" if reason else "")
+ assert gemini_output.out == ""
+
+
+@pytest.mark.parametrize("cwd_kind", ["workspace", "missing", "invalid"])
+def test_git_checks_use_event_workspace(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ tmp_path: Path,
+ cwd_kind: str,
+) -> None:
+ # Follow the bundled empty-rebase test: stub Git reads, never execute a push.
+ seen = []
+
+ def fake_run(args: list[str], cwd: str | None = None) -> str | None:
Review Comment:
## CodeQL / Explicit returns mixed with implicit (fall through) returns
Mixing implicit and explicit returns may indicate an error, as implicit returns always return None.
[Show more details](https://github.com/apache/magpie/security/code-scanning/51)
##########
tools/agent-guard/tests/test_gemini.py:
##########
@@ -0,0 +1,220 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests for Gemini CLI's BeforeTool adapter.
+
+Like the OpenCode and Kiro suites, these check the hook's transport and its
+agreement with the harness-neutral guard core. Guard rule details remain in
+test_guards.py and test_skill_guards.py.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+import agent_guard
Review Comment:
## CodeQL / Module is imported with 'import' and 'import from'
Module 'agent_guard' is imported with both 'import' and 'import from'.
[Show more details](https://github.com/apache/magpie/security/code-scanning/52)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@magpie.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org