margin-core 0.1.2__tar.gz → 0.1.4__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.
- {margin_core-0.1.2 → margin_core-0.1.4}/.gitignore +3 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/CHANGELOG.md +19 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/PKG-INFO +4 -2
- {margin_core-0.1.2 → margin_core-0.1.4}/README.md +3 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/pyproject.toml +1 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/__init__.py +1 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/agent.py +2 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/config.py +8 -4
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/loaders/git.py +14 -4
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/loaders/github.py +1 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/models.py +6 -1
- margin_core-0.1.4/src/margin_core/reporting/__init__.py +6 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/reporting/json_report.py +5 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/reporting/markdown_report.py +9 -1
- margin_core-0.1.4/tests/test_config.py +33 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_core_skeleton.py +1 -1
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_questions.py +17 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_security.py +119 -1
- margin_core-0.1.2/src/margin_core/reporting/__init__.py +0 -6
- margin_core-0.1.2/tests/test_config.py +0 -26
- {margin_core-0.1.2 → margin_core-0.1.4}/LICENSE +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/_fs.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/errors.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/inputs.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/__init__.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/_chat_completions.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/_http.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/anthropic.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/base.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/catalog.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/factory.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/local.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/mock.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/openai.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/llm/pricing.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/loaders/__init__.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/loaders/base.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/loaders/filters.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/loaders/local.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/logging.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/py.typed +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/registry.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/src/margin_core/runner.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/conftest.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_agent.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_filters.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_github_loader.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_history_scope.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_inputs.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_llm.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_llm_session.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_local_llm.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_local_loader.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_models.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_preclone_check.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_registry.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_reporting.py +0 -0
- {margin_core-0.1.2 → margin_core-0.1.4}/tests/test_user_settings.py +0 -0
|
@@ -4,6 +4,25 @@ 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
|
+
## [0.1.4] - 2026-11-20
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- An answer with several choices reads as one list: sentence labels lose their full stop and
|
|
11
|
+
are kept apart with semicolons when they have commas of their own. The "Not confirmed"
|
|
12
|
+
warning no longer ends in two full stops.
|
|
13
|
+
|
|
14
|
+
## [0.1.3] - 2026-11-02
|
|
15
|
+
|
|
16
|
+
### Security
|
|
17
|
+
- A folder being analysed could still make git run a program named in its `.git/config`, through
|
|
18
|
+
a signed commit (`log.showSignature` with `gpg.program`) or a missing object that made git
|
|
19
|
+
fetch (`core.sshCommand`, `remote.<name>.uploadpack`). Both are closed: signatures aren't
|
|
20
|
+
checked, and reading history never uses the network.
|
|
21
|
+
- A `.env` in the current folder was read automatically, so a repository could change margin's
|
|
22
|
+
settings, for example to send its code to another server. Now only a file named by
|
|
23
|
+
`MARGIN_ENV_FILE` is read. **If you keep settings in `.env`, set `MARGIN_ENV_FILE=.env`.**
|
|
24
|
+
- Reports no longer carry control characters, which could rewrite what a terminal shows.
|
|
25
|
+
|
|
7
26
|
## [0.1.2] - 2026-10-29
|
|
8
27
|
|
|
9
28
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: margin-core
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
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`
|
|
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`
|
|
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.
|
|
@@ -174,7 +174,8 @@ class RunContext:
|
|
|
174
174
|
answer = Answer.of(question, question.check(question.default), "default")
|
|
175
175
|
answers[question.id] = answer
|
|
176
176
|
if question.default is not None:
|
|
177
|
-
|
|
177
|
+
end = "" if answer.label.endswith((".", "!", "?")) else "."
|
|
178
|
+
self.warn(f"Not confirmed: {question.prompt} Assumed: {answer.label}{end}")
|
|
178
179
|
|
|
179
180
|
ordered = {q.id: answers[q.id] for q in batch.questions}
|
|
180
181
|
self.answers.extend(ordered.values())
|
|
@@ -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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
73
|
-
|
|
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
|
|
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
|
|
@@ -166,7 +166,12 @@ class Question(_StrictModel):
|
|
|
166
166
|
for v in values:
|
|
167
167
|
choice = self._choice(v)
|
|
168
168
|
labels.append(choice.label if choice is not None else str(v))
|
|
169
|
-
|
|
169
|
+
if len(labels) == 1:
|
|
170
|
+
return labels[0]
|
|
171
|
+
# several answers: a label that is a whole sentence loses its full stop, and labels
|
|
172
|
+
# that have commas of their own are kept apart with semicolons
|
|
173
|
+
labels = [label.rstrip(".") for label in labels]
|
|
174
|
+
return ("; " if any("," in label for label in labels) else ", ").join(labels)
|
|
170
175
|
|
|
171
176
|
|
|
172
177
|
class Answer(_StrictModel):
|
|
@@ -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
|
-
|
|
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"
|
|
@@ -96,6 +96,23 @@ def test_other_text_is_accepted_only_when_allowed() -> None:
|
|
|
96
96
|
assert grain.describe("order line") == "order line"
|
|
97
97
|
|
|
98
98
|
|
|
99
|
+
def test_several_answers_read_as_one_list() -> None:
|
|
100
|
+
pick = Question(
|
|
101
|
+
id="pick", prompt="Which?", kind="multi_choice", default=["a", "b"],
|
|
102
|
+
choices=[
|
|
103
|
+
Choice(value="a", label="North is the largest region, with 31% of revenue."),
|
|
104
|
+
Choice(value="b", label="Juice grew 12%."),
|
|
105
|
+
Choice(value="c", label="Tea"),
|
|
106
|
+
Choice(value="d", label="Coffee"),
|
|
107
|
+
],
|
|
108
|
+
) # fmt: skip
|
|
109
|
+
assert pick.describe(["a", "b"]) == (
|
|
110
|
+
"North is the largest region, with 31% of revenue; Juice grew 12%"
|
|
111
|
+
)
|
|
112
|
+
assert pick.describe(["c", "d"]) == "Tea, Coffee"
|
|
113
|
+
assert pick.describe(["b"]) == "Juice grew 12%."
|
|
114
|
+
|
|
115
|
+
|
|
99
116
|
def test_resolve_fills_defaults_and_lists_every_problem() -> None:
|
|
100
117
|
batch = QuestionBatch(title="Check", questions=[FORMAT, COLUMNS, CONTEXT])
|
|
101
118
|
answers = batch.resolve({"date_format": "dmy"}, "user")
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|