margin-core 0.1.2__tar.gz → 0.1.3__tar.gz

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 (58) hide show
  1. {margin_core-0.1.2 → margin_core-0.1.3}/CHANGELOG.md +14 -0
  2. {margin_core-0.1.2 → margin_core-0.1.3}/PKG-INFO +4 -2
  3. {margin_core-0.1.2 → margin_core-0.1.3}/README.md +3 -1
  4. {margin_core-0.1.2 → margin_core-0.1.3}/pyproject.toml +1 -1
  5. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/__init__.py +1 -1
  6. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/config.py +8 -4
  7. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/loaders/git.py +14 -4
  8. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/loaders/github.py +1 -1
  9. margin_core-0.1.3/src/margin_core/reporting/__init__.py +6 -0
  10. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/reporting/json_report.py +5 -1
  11. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/reporting/markdown_report.py +9 -1
  12. margin_core-0.1.3/tests/test_config.py +33 -0
  13. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_core_skeleton.py +1 -1
  14. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_security.py +119 -1
  15. margin_core-0.1.2/src/margin_core/reporting/__init__.py +0 -6
  16. margin_core-0.1.2/tests/test_config.py +0 -26
  17. {margin_core-0.1.2 → margin_core-0.1.3}/.gitignore +0 -0
  18. {margin_core-0.1.2 → margin_core-0.1.3}/LICENSE +0 -0
  19. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/_fs.py +0 -0
  20. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/agent.py +0 -0
  21. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/errors.py +0 -0
  22. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/inputs.py +0 -0
  23. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/__init__.py +0 -0
  24. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/_chat_completions.py +0 -0
  25. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/_http.py +0 -0
  26. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/anthropic.py +0 -0
  27. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/base.py +0 -0
  28. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/catalog.py +0 -0
  29. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/factory.py +0 -0
  30. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/local.py +0 -0
  31. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/mock.py +0 -0
  32. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/openai.py +0 -0
  33. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/llm/pricing.py +0 -0
  34. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/loaders/__init__.py +0 -0
  35. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/loaders/base.py +0 -0
  36. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/loaders/filters.py +0 -0
  37. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/loaders/local.py +0 -0
  38. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/logging.py +0 -0
  39. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/models.py +0 -0
  40. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/py.typed +0 -0
  41. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/registry.py +0 -0
  42. {margin_core-0.1.2 → margin_core-0.1.3}/src/margin_core/runner.py +0 -0
  43. {margin_core-0.1.2 → margin_core-0.1.3}/tests/conftest.py +0 -0
  44. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_agent.py +0 -0
  45. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_filters.py +0 -0
  46. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_github_loader.py +0 -0
  47. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_history_scope.py +0 -0
  48. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_inputs.py +0 -0
  49. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_llm.py +0 -0
  50. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_llm_session.py +0 -0
  51. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_local_llm.py +0 -0
  52. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_local_loader.py +0 -0
  53. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_models.py +0 -0
  54. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_preclone_check.py +0 -0
  55. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_questions.py +0 -0
  56. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_registry.py +0 -0
  57. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_reporting.py +0 -0
  58. {margin_core-0.1.2 → margin_core-0.1.3}/tests/test_user_settings.py +0 -0
@@ -4,6 +4,20 @@ All notable changes to this package are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.3] - 2026-11-02
10
+
11
+ ### Security
12
+ - A folder being analysed could still make git run a program named in its `.git/config`, through
13
+ a signed commit (`log.showSignature` with `gpg.program`) or a missing object that made git
14
+ fetch (`core.sshCommand`, `remote.<name>.uploadpack`). Both are closed: signatures aren't
15
+ checked, and reading history never uses the network.
16
+ - A `.env` in the current folder was read automatically, so a repository could change margin's
17
+ settings, for example to send its code to another server. Now only a file named by
18
+ `MARGIN_ENV_FILE` is read. **If you keep settings in `.env`, set `MARGIN_ENV_FILE=.env`.**
19
+ - Reports no longer carry control characters, which could rewrite what a terminal shows.
20
+
7
21
  ## [0.1.2] - 2026-10-29
8
22
 
9
23
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-core
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: The shared core of margin: the agent contract, results with evidence, model clients and code loaders.
5
5
  Project-URL: Homepage, https://github.com/Waddah0-0/margin
6
6
  Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/core
@@ -96,7 +96,9 @@ The full guide is
96
96
  ## Settings
97
97
 
98
98
  Model settings are read from environment variables first, then from settings saved in the
99
- web UI, then from a `.env` file. The ones you are likely to need are `DEFAULT_LLM_PROVIDER`
99
+ web UI, then from the file named by `MARGIN_ENV_FILE` (a `.env` in the current folder is not
100
+ read, because it may belong to a repository being analysed). The ones you are likely to need
101
+ are `DEFAULT_LLM_PROVIDER`
100
102
  (`local`, `anthropic` or `openai`), `LOCAL_LLM_BASE_URL`, `LOCAL_LLM_MODEL`,
101
103
  `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `MAX_COST_USD`.
102
104
  [.env.example](https://github.com/Waddah0-0/margin/blob/main/.env.example) lists them all.
@@ -69,7 +69,9 @@ The full guide is
69
69
  ## Settings
70
70
 
71
71
  Model settings are read from environment variables first, then from settings saved in the
72
- web UI, then from a `.env` file. The ones you are likely to need are `DEFAULT_LLM_PROVIDER`
72
+ web UI, then from the file named by `MARGIN_ENV_FILE` (a `.env` in the current folder is not
73
+ read, because it may belong to a repository being analysed). The ones you are likely to need
74
+ are `DEFAULT_LLM_PROVIDER`
73
75
  (`local`, `anthropic` or `openai`), `LOCAL_LLM_BASE_URL`, `LOCAL_LLM_MODEL`,
74
76
  `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and `MAX_COST_USD`.
75
77
  [.env.example](https://github.com/Waddah0-0/margin/blob/main/.env.example) lists them all.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "margin-core"
3
- version = "0.1.2"
3
+ version = "0.1.3"
4
4
  description = "The shared core of margin: the agent contract, results with evidence, model clients and code loaders."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -45,7 +45,7 @@ from margin_core.models import (
45
45
  from margin_core.registry import AgentRegistry, default_registry, get_agent, list_agents
46
46
  from margin_core.runner import run_agent
47
47
 
48
- __version__ = "0.1.2"
48
+ __version__ = "0.1.3"
49
49
 
50
50
  __all__ = [
51
51
  "AgentInfo",
@@ -3,9 +3,13 @@
3
3
  1. environment variables (for deployments and CI);
4
4
  2. settings saved by the user, e.g. from the web UI, in ``settings.json`` in the user's
5
5
  config folder (``MARGIN_CONFIG_FILE`` overrides the path; empty turns it off);
6
- 3. the ``.env`` file (``MARGIN_ENV_FILE`` chooses it; empty reads no file);
6
+ 3. the file named by ``MARGIN_ENV_FILE``, if any;
7
7
  4. the defaults below.
8
8
 
9
+ No file is read unless ``MARGIN_ENV_FILE`` names one. A ``.env`` in the current folder is not
10
+ trusted: that folder may be a repository being analysed, and its settings could send the code
11
+ to another server.
12
+
9
13
  Empty values are ignored, so ``ANTHROPIC_API_KEY=`` in a ``.env`` does not count as a key.
10
14
  Secrets never have defaults, and saved secrets are never sent back to a browser.
11
15
  """
@@ -31,7 +35,7 @@ from pydantic_settings import (
31
35
  ENV_FILE_VAR = "MARGIN_ENV_FILE"
32
36
  CONFIG_FILE_VAR = "MARGIN_CONFIG_FILE"
33
37
 
34
- # What the user may save (the rest is configured by environment or .env only).
38
+ # What the user may save (the rest is configured by environment or env file only).
35
39
  SAVEABLE = frozenset({
36
40
  "default_llm_provider",
37
41
  "local_llm_base_url", "local_llm_api_key", "local_llm_model",
@@ -116,7 +120,7 @@ class Settings(BaseSettings):
116
120
  """Global settings for margin."""
117
121
 
118
122
  model_config = SettingsConfigDict(
119
- env_file=".env", env_file_encoding="utf-8", extra="ignore", env_ignore_empty=True
123
+ env_file_encoding="utf-8", extra="ignore", env_ignore_empty=True
120
124
  )
121
125
 
122
126
  anthropic_api_key: SecretStr | None = None
@@ -156,7 +160,7 @@ class Settings(BaseSettings):
156
160
 
157
161
 
158
162
  def _env_file() -> str | None:
159
- return os.environ.get(ENV_FILE_VAR, ".env") or None
163
+ return os.environ.get(ENV_FILE_VAR) or None
160
164
 
161
165
 
162
166
  def get_settings() -> Settings:
@@ -33,16 +33,24 @@ def git_available() -> bool:
33
33
  # Passed on every git command line, where they override any config, including a repository's
34
34
  # own .git/config. A folder we are pointed at is untrusted: its config could name programs for
35
35
  # git to run (core.fsmonitor), hooks could run on checkout, and Git LFS could download files
36
- # from another server past our size limits.
36
+ # from another server past our size limits. log.showSignature would make ``git log`` run the
37
+ # program named by gpg.program on any signed commit.
37
38
  SAFE_GIT_CONFIG = (
38
39
  "core.fsmonitor=false",
39
40
  "core.hooksPath=" + os.devnull,
40
41
  "filter.lfs.smudge=",
41
42
  "filter.lfs.process=",
42
43
  "filter.lfs.required=false",
44
+ "log.showSignature=false",
43
45
  "i18n.logOutputEncoding=UTF-8",
44
46
  )
45
47
 
48
+ # Added when reading history, which never needs the network. A repository that declares a
49
+ # "promisor" remote and leaves out an object makes git fetch it, and a fetch runs programs the
50
+ # repository names (core.sshCommand, remote.<name>.uploadpack). A clone does fetch, so it goes
51
+ # without these.
52
+ READ_ONLY_GIT_CONFIG = ("protocol.allow=never",)
53
+
46
54
 
47
55
  def safe_git_env() -> dict[str, str]:
48
56
  """Environment that prevents git from ever prompting (terminal, GUI, credential manager)
@@ -69,14 +77,16 @@ def git_command(args: list[str]) -> list[str]:
69
77
 
70
78
 
71
79
  def run_git(args: list[str], cwd: Path | None = None, timeout_s: float = 60.0) -> str:
72
- """Run ``git <args>`` and return stdout (UTF-8). Raises :class:`GitCommandError`."""
73
- cmd = git_command(args)
80
+ """Run a command that only reads the repository, with no network, and return stdout (UTF-8).
81
+ Raises :class:`GitCommandError`."""
82
+ read_only = [arg for setting in READ_ONLY_GIT_CONFIG for arg in ("-c", setting)]
83
+ cmd = git_command([*read_only, *args])
74
84
  proc = subprocess.run(
75
85
  cmd,
76
86
  cwd=cwd,
77
87
  capture_output=True,
78
88
  timeout=timeout_s,
79
- env=safe_git_env(),
89
+ env={**safe_git_env(), "GIT_NO_LAZY_FETCH": "1"}, # git 2.45+; older ones have the config
80
90
  stdin=subprocess.DEVNULL,
81
91
  check=False,
82
92
  )
@@ -72,7 +72,7 @@ class GitHubLoader(Loader):
72
72
  self.allow_non_github_urls = allow_non_github_urls # tests only (file:// fixtures)
73
73
  self.api_base = api_base.rstrip("/")
74
74
  if github_token is None:
75
- secret = get_settings().github_token # GITHUB_TOKEN env var or .env
75
+ secret = get_settings().github_token # GITHUB_TOKEN env var or MARGIN_ENV_FILE
76
76
  github_token = secret.get_secret_value() if secret else None
77
77
  self.github_token = github_token or None
78
78
  self._http_client = http_client
@@ -0,0 +1,6 @@
1
+ """Report renderers for :class:`~margin_core.models.AgentResult`."""
2
+
3
+ from margin_core.reporting.json_report import to_json, write_json
4
+ from margin_core.reporting.markdown_report import strip_control, to_markdown, write_markdown
5
+
6
+ __all__ = ["strip_control", "to_json", "to_markdown", "write_json", "write_markdown"]
@@ -2,13 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from pathlib import Path
6
7
 
7
8
  from margin_core.models import AgentResult
8
9
 
9
10
 
10
11
  def to_json(result: AgentResult, *, indent: int | None = 2) -> str:
11
- return result.model_dump_json(indent=indent)
12
+ # pydantic escapes characters below 0x20; these reach a terminal as they are
13
+ return re.sub(
14
+ r"[\x7f-\x9f]", lambda m: f"\\u{ord(m[0]):04x}", result.model_dump_json(indent=indent)
15
+ )
12
16
 
13
17
 
14
18
  def write_json(result: AgentResult, path: str | Path, *, indent: int | None = 2) -> Path:
@@ -2,12 +2,20 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from pathlib import Path
6
7
 
7
8
  from margin_core.models import AgentResult, Evidence
8
9
 
9
10
  _STATUS_LABEL = {"ok": "ok", "partial": "partial", "error": "error"}
10
11
  _ANSWERED_BY = {"user": "you", "preset": "the run's input", "default": "default, not confirmed"}
12
+ _CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") # all but tab and newline
13
+
14
+
15
+ def strip_control(text: str) -> str:
16
+ """Remove control characters. Reports quote commit messages, file names and cells, and in
17
+ a terminal an escape sequence among them could rewrite what the reader sees."""
18
+ return _CONTROL.sub("", text)
11
19
 
12
20
 
13
21
  def _cell(text: object) -> str:
@@ -83,7 +91,7 @@ def to_markdown(result: AgentResult) -> str:
83
91
  md += [f"| {_cell(k)} | {_cell(v)} |" for k, v in rows]
84
92
  md.append("")
85
93
 
86
- return "\n".join(md).rstrip() + "\n"
94
+ return strip_control("\n".join(md)).rstrip() + "\n"
87
95
 
88
96
 
89
97
  def write_markdown(result: AgentResult, path: str | Path) -> Path:
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+ from margin_core.config import get_settings, setting_sources
7
+
8
+
9
+ def test_a_env_file_in_the_current_folder_is_not_trusted(
10
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
11
+ ) -> None:
12
+ # the folder may be a repository being analysed, and this would send its code elsewhere
13
+ (tmp_path / ".env").write_text(
14
+ "LOCAL_LLM_BASE_URL=https://attacker.example\nMAX_COST_USD=9999\n", encoding="utf-8"
15
+ )
16
+ monkeypatch.chdir(tmp_path)
17
+ monkeypatch.delenv("MARGIN_ENV_FILE", raising=False)
18
+ settings = get_settings()
19
+ assert settings.local_llm_base_url == "http://localhost:11434"
20
+ assert settings.max_cost_usd == 1.0
21
+ assert setting_sources()["local_llm_base_url"] == "default"
22
+
23
+
24
+ def test_env_file_can_be_chosen(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
25
+ env = tmp_path / "custom.env"
26
+ env.write_text("DEFAULT_LLM_MODEL=from-file\n", encoding="utf-8")
27
+ monkeypatch.setenv("MARGIN_ENV_FILE", str(env))
28
+ assert get_settings().default_llm_model == "from-file"
29
+
30
+
31
+ def test_environment_variables_win(monkeypatch: pytest.MonkeyPatch) -> None:
32
+ monkeypatch.setenv("DEFAULT_LLM_PROVIDER", "mock")
33
+ assert get_settings().default_llm_provider == "mock"
@@ -2,4 +2,4 @@ from margin_core import __version__
2
2
 
3
3
 
4
4
  def test_core_version() -> None:
5
- assert __version__ == "0.1.2"
5
+ assert __version__ == "0.1.3"
@@ -9,6 +9,7 @@
9
9
  from __future__ import annotations
10
10
 
11
11
  import asyncio
12
+ import json
12
13
  import logging
13
14
  import os
14
15
  import shutil
@@ -21,8 +22,10 @@ import pytest
21
22
  from margin_core.errors import InvalidTargetError
22
23
  from margin_core.loaders import load_workspace
23
24
  from margin_core.loaders.base import Workspace
24
- from margin_core.loaders.git import SAFE_GIT_CONFIG, git_command, run_git
25
+ from margin_core.loaders.git import SAFE_GIT_CONFIG, GitCommandError, git_command, run_git
25
26
  from margin_core.loaders.github import GitHubLoader
27
+ from margin_core.models import AgentResult, Evidence, Finding
28
+ from margin_core.reporting import to_json, to_markdown
26
29
 
27
30
  needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
28
31
 
@@ -68,14 +71,129 @@ async def test_a_repository_cannot_make_git_run_its_programs(tmp_path: Path) ->
68
71
  assert not marker.exists(), "margin let the repository run a program"
69
72
 
70
73
 
74
+ def _program(path: Path, marker: Path) -> str:
75
+ """A script for settings git runs directly, without a shell: leaves ``marker`` behind."""
76
+ path.write_text(f'#!/bin/sh\necho ran > "{marker.as_posix()}"\nexit 1\n', newline="\n")
77
+ path.chmod(0o755)
78
+ return path.as_posix()
79
+
80
+
81
+ def _commit_object(repo: Path, body: str) -> None:
82
+ """Point HEAD at a hand-written commit (``body`` is everything after the parent line)."""
83
+ parent = subprocess.run(
84
+ ["git", "rev-parse", "HEAD"], cwd=repo, check=True, capture_output=True, text=True
85
+ ).stdout.strip()
86
+ who = "t <t@example.com> 1700000000 +0000"
87
+ sha = subprocess.run(
88
+ ["git", "hash-object", "-t", "commit", "-w", "--stdin", "--literally"],
89
+ cwd=repo, check=True, capture_output=True,
90
+ input=body.format(parent=parent, who=who).encode(),
91
+ ).stdout.decode().strip() # fmt: skip
92
+ _git(repo, "update-ref", "HEAD", sha)
93
+
94
+
95
+ def _hostile_repo(root: Path) -> Path:
96
+ root.mkdir()
97
+ _git(root, "init", "-q")
98
+ (root / "app.py").write_text("x = 1\n", encoding="utf-8")
99
+ _git(root, "add", ".")
100
+ _git(root, "commit", "-q", "-m", "init")
101
+ return root
102
+
103
+
104
+ async def _read_history(repo: Path) -> None:
105
+ """All a run does with a folder's history; a failure is fine, a program running is not."""
106
+ try:
107
+ async with await load_workspace(str(repo)) as ws:
108
+ assert ws.git is not None
109
+ await ws.git.commits(max_count=10)
110
+ await ws.git.changed_files(max_count=10)
111
+ except GitCommandError:
112
+ pass
113
+
114
+
115
+ @needs_git
116
+ async def test_a_signed_commit_cannot_make_git_log_run_a_program(tmp_path: Path) -> None:
117
+ repo, marker = _hostile_repo(tmp_path / "hostile"), tmp_path / "gpg-ran"
118
+ _commit_object(
119
+ repo,
120
+ f"tree {_tree(repo)}\nparent {{parent}}\nauthor {{who}}\ncommitter {{who}}\n"
121
+ "gpgsig -----BEGIN PGP SIGNATURE-----\n \n abc\n -----END PGP SIGNATURE-----\n\n"
122
+ "signed\n",
123
+ )
124
+ _git(repo, "config", "log.showSignature", "true")
125
+ _git(repo, "config", "gpg.program", _program(tmp_path / "gpg.sh", marker))
126
+
127
+ # sanity: plain git runs it
128
+ subprocess.run(["git", "log", "--format=%H"], cwd=repo, capture_output=True, check=False) # noqa: ASYNC221
129
+ if not marker.exists():
130
+ pytest.skip("this git does not run gpg.program here; nothing to prove")
131
+ marker.unlink()
132
+
133
+ await _read_history(repo)
134
+ assert not marker.exists(), "margin let the repository run a program"
135
+
136
+
137
+ @needs_git
138
+ @pytest.mark.parametrize(
139
+ "url", ["ssh://example.invalid/x.git", "{local}"], ids=["core.sshCommand", "uploadpack"]
140
+ )
141
+ async def test_a_missing_object_cannot_make_git_fetch_and_run_a_program(
142
+ tmp_path: Path, url: str
143
+ ) -> None:
144
+ repo, marker = _hostile_repo(tmp_path / "hostile"), tmp_path / "fetch-ran"
145
+ program = _program(tmp_path / "fetch.sh", marker)
146
+ _git(repo, "config", "extensions.partialClone", "origin")
147
+ _git(repo, "config", "remote.origin.promisor", "true")
148
+ _git(repo, "config", "remote.origin.url", url.format(local=repo.as_posix()))
149
+ _git(repo, "config", "core.sshCommand", program)
150
+ _git(repo, "config", "remote.origin.uploadpack", program)
151
+ # a commit whose tree is not there: reading it asks the "promisor" remote for it
152
+ _commit_object(
153
+ repo,
154
+ f"tree {'1' * 40}\nparent {{parent}}\nauthor {{who}}\ncommitter {{who}}\n\nmissing\n",
155
+ )
156
+
157
+ # sanity: plain git runs it
158
+ subprocess.run( # noqa: ASYNC221
159
+ ["git", "log", "--name-only", "--format=%H"], cwd=repo, capture_output=True, check=False
160
+ )
161
+ if not marker.exists():
162
+ pytest.skip("this git does not fetch that way here; nothing to prove")
163
+ marker.unlink()
164
+
165
+ await _read_history(repo)
166
+ assert not marker.exists(), "margin let the repository run a program"
167
+
168
+
169
+ def _tree(repo: Path) -> str:
170
+ return subprocess.run(
171
+ ["git", "rev-parse", "HEAD^{tree}"], cwd=repo, check=True, capture_output=True, text=True
172
+ ).stdout.strip()
173
+
174
+
71
175
  def test_every_git_command_carries_the_safety_settings() -> None:
72
176
  cmd = git_command(["log"])
73
177
  for setting in SAFE_GIT_CONFIG:
74
178
  assert cmd[cmd.index(setting) - 1] == "-c"
75
179
  assert "core.fsmonitor=false" in cmd and "filter.lfs.smudge=" in cmd
180
+ assert "log.showSignature=false" in cmd
76
181
  assert cmd[-1] == "log"
77
182
 
78
183
 
184
+ def test_reports_carry_no_terminal_escape_sequences() -> None:
185
+ hostile = "\x1b]0;title\x07\x1b[2Jhidden\x9b31m"
186
+ result = AgentResult(
187
+ agent_id="x", agent_version="1", status="ok", summary=hostile,
188
+ findings=[Finding(title=hostile, summary=hostile,
189
+ evidence=[Evidence(kind="commit", detail=hostile)])],
190
+ ) # fmt: skip
191
+ for report in (to_markdown(result), to_json(result)):
192
+ assert "\x1b" not in report and "\x07" not in report and "\x9b" not in report
193
+ assert "hidden" in to_markdown(result)
194
+ assert json.loads(to_json(result))["summary"] == hostile # JSON keeps the value, escaped
195
+
196
+
79
197
  # ---- 2. reading outside the workspace ------------------------------------------------------
80
198
 
81
199
 
@@ -1,6 +0,0 @@
1
- """Report renderers for :class:`~margin_core.models.AgentResult`."""
2
-
3
- from margin_core.reporting.json_report import to_json, write_json
4
- from margin_core.reporting.markdown_report import to_markdown, write_markdown
5
-
6
- __all__ = ["to_json", "to_markdown", "write_json", "write_markdown"]
@@ -1,26 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- import pytest
6
- from margin_core.config import get_settings
7
-
8
-
9
- def test_defaults_without_env_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
10
- (tmp_path / ".env").write_text("DEFAULT_LLM_MODEL=from-dotenv\n", encoding="utf-8")
11
- monkeypatch.chdir(tmp_path)
12
- settings = get_settings() # the autouse fixture disables env files
13
- assert settings.default_llm_provider == "local"
14
- assert settings.default_llm_model is None
15
-
16
-
17
- def test_env_file_can_be_chosen(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
18
- env = tmp_path / "custom.env"
19
- env.write_text("DEFAULT_LLM_MODEL=from-file\n", encoding="utf-8")
20
- monkeypatch.setenv("MARGIN_ENV_FILE", str(env))
21
- assert get_settings().default_llm_model == "from-file"
22
-
23
-
24
- def test_environment_variables_win(monkeypatch: pytest.MonkeyPatch) -> None:
25
- monkeypatch.setenv("DEFAULT_LLM_PROVIDER", "mock")
26
- assert get_settings().default_llm_provider == "mock"
File without changes
File without changes