ReMe/plugins/home/tests/test_git_export.py
xyf2020 fa6d8fcef7
Some checks are pending
CI / macOS sandbox / Seatbelt - clt (push) Waiting to run
CI / macOS sandbox / Seatbelt - xcode (push) Waiting to run
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
CI and Release / Docker / Build and test / amd64 (push) Waiting to run
CI and Release / Docker / Build and test / arm64 (push) Waiting to run
CI and Release / Docker / Publish multi-platform tags (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
feat(home): add reproducible benchmark preparation and candidate evaluation (#693)
* Add sandboxed Python execution and home AutoBash plugin

* Harden read-only shell commands and filesystem sandboxes

* Group file sandbox backends in one package

* Fix macOS file sandbox isolation and runtime access

* Refine file sandbox limits and executor checks

* Harden AutoBash policy and macOS sandbox supervision

* fix(home): require ReMe release with file sandbox

* refactor(home): simplify sandbox calls and redundant tests

* fix(execution): bound output and clean up cancelled sandbox startup

* fix(tests): mock Seatbelt platform requirements on Linux

* fix(home): block Git help helpers and harden sandbox cleanup

* Fix sandbox runtime links and subprocess cleanup

* ci: cover Home plugin tests

* test: wait for pipeline descendants to exit after cancellation

* fix: align Home dependencies and preserve cleanup cancellation

Require ReMe 0.4.2.1 and verify isolated Home wheel installation in package CI. Share cancellation-safe cleanup with thread calls, retain AnyIO cancellation semantics, and record Bubblewrap mount targets during argument construction.

* feat(home): prepare self-evolution workspaces and benchmark inputs

* fix(home): load only selected cases for debug derivation

* feat(home): evaluate candidates with benchmark judges and prepare workspace docs

* refactor(home): organize workflows and unify debug evaluation mode

* fix(home): align Docker runtime and preserve evaluation failures

* refactor(home): align evaluation summaries with dev_meta

* feat(home): migrate agent, sampling and evidence inspection tooling

* feat(home): add case-study agent and query evidence tracing tools

- Add home_case_study job with CaseStudyAgentWrapper and a read-only
  sandboxed investigation step for per-case diagnostic reports
- Add home_trace_query_evidence job/step to locate a query's source
  evidence sessions, memory checkpoints and answer/score previews
- Compact evaluation summaries: record per-query failure errors, round
  scores to four decimals, expose scoring_enabled and observed means
- Slim run manifests: drop schema_version and trusted_judge fingerprint,
  exclude debug/sampling_policy options, keep construction_source only
  for query-only replay
- Simplify history index internals and update guide docs and tests

* feat(home): support multi-case case-study runs with dedicated LLM and Git sandbox

- Allow home_case_study to investigate up to eight ordered cases per
  invocation with a shared focus, one isolated agent per case, while
  keeping the legacy single-case selector as a deprecated alias
- Configure a dedicated home_case_study LLM component instead of the
  shared judge backend
- Wrap ReMe's OS file sandbox with a Home-specific Git runtime grant
  (developer directory on macOS) and argv-based child environment
- Tighten case-study prompts around evidence certainty, code-tool path
  scoping, citation form, and unresolved-cause reporting
- Extend evidence tracing and expand case-study/sandbox tests and docs

* feat(home): run case studies with bounded concurrency and fix sandbox test

* feat(home): guard repeated evaluations and preserve retry selections

* feat(home): migrate optimization workflows and evaluation budgets

* feat(home): add candidate admission gate and construction-equivalence replay

Add host-side candidate gate agent that reviews committed changes before
sampling, and construction-equivalence agent that compares a candidate
against its nearest reusable ancestor to select query-only replay with
60% probability when construction is unchanged. Wire both into
plugin.yaml application defaults, update optimizer prompt to explain the
new host behaviors, extend snapshot/evaluation components with reuse
support, and add focused tests.

* feat(home): add structured-report agent and gate/equivalence test coverage

Add StructuredReportAgent wrapper selectable via the
_structured_report_model option in BoundedAgentWrapper, plus its
dedicated unit tests. Extend candidate gate, construction equivalence,
evaluation history, sampling, and validation budget tests, and document
the new behavior in the plugin README.

* feat(home): add standalone benchmark test evaluation and fix compression recovery

* fix(home): preserve top-level answer failure classification

* refactor(home): rename max_validations to max_evaluations

* refactor(home): extract shared review_report workflow helper and bump version to 0.4.2.2

* fix(home): load runner credentials and localize dataset evaluation

* fix(benchmark): propagate Home sandbox memory limits

* refactor(home): consolidate Git exports and candidate validation

* fix(home): clarify branch and diff tool parameter contracts

* feat(home): bound case-study reports and migrate draft tools

* fix(home): align benchmark report limits with plugin defaults

* Fix Home evaluation recovery and cancellation boundaries

* fix(home): tolerate fenced optimizer results and finalize exhausted budgets

* fix(benchmark): align Docker runtime with AgentScope 2.0.11

* fix(home): unify history writes and cancellation cleanup

* refactor(home): reuse structured report parsing

* ci: remove redundant Home compatibility install check

* fix(home): preserve literal formatting in structured reports

---------

Co-authored-by: jinli.yl <jinli.yl@alibaba-inc.com>
2026-11-05 14:54:31 +08:00

127 lines
5.9 KiB
Python

"""Git exports preserve raw committed bytes, literal names, and executable modes."""
from pathlib import Path
from unittest.mock import Mock
import pytest
from reme_home.preparation import code
from reme_home.code import repository as candidate_repository, snapshot
def test_batch_export_bypasses_filters_and_checkout(tmp_path, monkeypatch):
"""One batch reads all selected blobs, including binary and large files."""
repository = tmp_path / "repo"
repository.mkdir()
code.git(repository, "init", "--template=")
contents = {
"space name": b"$Format:%H$\n",
'quotes"\tand\nnewline': b"\x00binary\xff\n",
"脚本": b"#!/bin/sh\nexit 0\n",
"large": b"x" * 5_000_001,
"empty": b"",
".gitattributes": b"* export-ignore export-subst filter=blocked\n",
}
for name, data in contents.items():
(repository / name).write_bytes(data)
(repository / "脚本").chmod(0o755)
code.git(repository, "add", "--all")
code.git(repository, "-c", "user.name=Test", "-c", "user.email=test@localhost", "commit", "-m", "files")
code.git(repository, "config", "filter.blocked.process", "/bin/false")
code.git(repository, "config", "filter.blocked.required", "true")
for name in contents:
(repository / name).write_bytes(b"dirty checkout")
run = Mock(wraps=code.git_bytes)
monkeypatch.setattr(code, "git_bytes", run)
destination = tmp_path / "export"
code.export_git_tree(repository, code.git_tree(repository, "HEAD"), lambda path: destination / path)
assert run.call_count == 2
assert run.call_args.args == (repository, "cat-file", "--batch")
for name, data in contents.items():
target = destination / name
assert target.read_bytes() == data
assert target.stat().st_mode & 0o777 == (0o755 if name == "脚本" else 0o644)
# Browsing and single-file export use the same committed objects while
# retaining their own size limits and streaming behavior.
objects = dict(snapshot.tree(repository, "HEAD"))
assert set(objects) == set(contents)
assert snapshot.blob(repository, objects['quotes"\tand\nnewline']) == contents['quotes"\tand\nnewline']
with pytest.raises(ValueError, match="exceeds 5 MB"):
snapshot.blob(repository, objects["large"])
streamed = tmp_path / "streamed"
snapshot.export_blob(repository, objects["large"], streamed)
assert streamed.read_bytes() == contents["large"]
@pytest.mark.parametrize("reader", ["preparation", "snapshot", "candidate"])
@pytest.mark.parametrize(
"mode,kind,name",
[
("120000", "blob", "link"),
("160000", "commit", "submodule"),
("100644", "blob", ".git/config"),
("100644", "blob", "../escape"),
("100644", "blob", "/escape"),
("100644", "blob", "~escape"),
("100644", "blob", "folder\\escape"),
("100644", "blob", "other:bad.py"),
],
)
def test_tree_rejects_unsafe_paths_and_nonregular_files(monkeypatch, mode, kind, name, reader):
"""Reject unsafe object metadata before any file is exported."""
monkeypatch.setattr(code, "git_bytes", Mock(return_value=f"{mode} {kind} {'a' * 40}\t{name}\0".encode()))
monkeypatch.setattr(candidate_repository, "git", Mock(return_value=""))
with pytest.raises(ValueError):
if reader == "preparation":
code.git_tree(Path("unused"), "HEAD")
elif reader == "snapshot":
snapshot.tree(Path("unused"), "HEAD")
else:
candidate_repository.validate_tree(
Path("unused"),
{"code": {"candidate_paths": ["plugin"], "initial_commit": "init"}},
"HEAD",
)
def test_tree_selection_uses_literal_roots(monkeypatch):
"""Ignore out-of-scope links without mistaking similar prefixes for selected roots."""
raw = (
f"100644 blob {'a' * 40}\tplugin/file\0"
f"120000 blob {'b' * 40}\tplugin-other/link\0"
f"160000 commit {'c' * 40}\tother\0"
).encode()
monkeypatch.setattr(code, "git_bytes", Mock(return_value=raw))
assert code.git_tree(Path("unused"), "HEAD", [Path("plugin")]) == [(Path("plugin/file"), "100644", "a" * 40)]
assert snapshot.tree(Path("unused"), "HEAD", "plugin") == [("plugin/file", "a" * 40)]
def test_snapshot_selection_treats_metacharacters_literally(monkeypatch):
"""A browsing prefix selects exact names and descendants, never glob matches."""
names = ['literal[ab]/quotes"\tand\nnewline', "literala/unselected", "literal[ab]-other/unselected"]
raw = "".join(f"100755 blob {'a' * 40}\t{name}\0" for name in names).encode()
monkeypatch.setattr(code, "git_bytes", Mock(return_value=raw))
assert snapshot.tree(Path("unused"), "HEAD", "literal[ab]") == [(names[0], "a" * 40)]
assert snapshot.tree(Path("unused"), "HEAD", names[0]) == [(names[0], "a" * 40)]
def test_snapshot_browsing_ignores_invalid_names_outside_selected_path(tmp_path):
"""Unrelated Git names cannot prevent browsing a valid literal directory."""
repository = tmp_path / "repo"
repository.mkdir()
code.git(repository, "init", "--template=")
(repository / "good").mkdir()
(repository / "good/file.py").write_text("value = 1\n")
(repository / "other:bad.py").write_text("outside browsing prefix\n")
code.git(repository, "add", "--all")
code.git(repository, "-c", "user.name=Test", "-c", "user.email=test@localhost", "commit", "-m", "files")
assert snapshot.list_code_tree(repository, {}, path="good")["paths"] == ["good/file.py"]
assert snapshot.read_code_file(repository, {}, path="good/file.py")["content"] == "value = 1\n"
assert snapshot.search_code(repository, {}, path="good", pattern="value")["occurrence_count"] == 1
with pytest.raises(ValueError, match="Invalid relative path"):
snapshot.tree(repository, "HEAD")
with pytest.raises(ValueError, match="Invalid relative path"):
code.git_tree(repository, "HEAD", [Path("good")])