margin-core 0.1.1__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 (60) hide show
  1. {margin_core-0.1.1 → margin_core-0.1.3}/.gitignore +2 -0
  2. margin_core-0.1.3/CHANGELOG.md +54 -0
  3. {margin_core-0.1.1 → margin_core-0.1.3}/PKG-INFO +4 -2
  4. {margin_core-0.1.1 → margin_core-0.1.3}/README.md +3 -1
  5. {margin_core-0.1.1 → margin_core-0.1.3}/pyproject.toml +1 -1
  6. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/__init__.py +21 -2
  7. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/agent.py +88 -4
  8. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/config.py +8 -4
  9. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/errors.py +4 -0
  10. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/loaders/git.py +14 -4
  11. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/loaders/github.py +1 -1
  12. margin_core-0.1.3/src/margin_core/models.py +321 -0
  13. margin_core-0.1.3/src/margin_core/reporting/__init__.py +6 -0
  14. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/reporting/json_report.py +5 -1
  15. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/reporting/markdown_report.py +18 -1
  16. margin_core-0.1.3/tests/test_config.py +33 -0
  17. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_core_skeleton.py +1 -1
  18. margin_core-0.1.3/tests/test_questions.py +257 -0
  19. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_security.py +119 -1
  20. margin_core-0.1.1/CHANGELOG.md +0 -26
  21. margin_core-0.1.1/src/margin_core/models.py +0 -130
  22. margin_core-0.1.1/src/margin_core/reporting/__init__.py +0 -6
  23. margin_core-0.1.1/tests/test_config.py +0 -26
  24. {margin_core-0.1.1 → margin_core-0.1.3}/LICENSE +0 -0
  25. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/_fs.py +0 -0
  26. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/inputs.py +0 -0
  27. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/__init__.py +0 -0
  28. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/_chat_completions.py +0 -0
  29. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/_http.py +0 -0
  30. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/anthropic.py +0 -0
  31. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/base.py +0 -0
  32. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/catalog.py +0 -0
  33. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/factory.py +0 -0
  34. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/local.py +0 -0
  35. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/mock.py +0 -0
  36. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/openai.py +0 -0
  37. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/llm/pricing.py +0 -0
  38. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/loaders/__init__.py +0 -0
  39. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/loaders/base.py +0 -0
  40. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/loaders/filters.py +0 -0
  41. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/loaders/local.py +0 -0
  42. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/logging.py +0 -0
  43. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/py.typed +0 -0
  44. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/registry.py +0 -0
  45. {margin_core-0.1.1 → margin_core-0.1.3}/src/margin_core/runner.py +0 -0
  46. {margin_core-0.1.1 → margin_core-0.1.3}/tests/conftest.py +0 -0
  47. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_agent.py +0 -0
  48. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_filters.py +0 -0
  49. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_github_loader.py +0 -0
  50. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_history_scope.py +0 -0
  51. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_inputs.py +0 -0
  52. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_llm.py +0 -0
  53. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_llm_session.py +0 -0
  54. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_local_llm.py +0 -0
  55. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_local_loader.py +0 -0
  56. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_models.py +0 -0
  57. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_preclone_check.py +0 -0
  58. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_registry.py +0 -0
  59. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_reporting.py +0 -0
  60. {margin_core-0.1.1 → margin_core-0.1.3}/tests/test_user_settings.py +0 -0
@@ -75,6 +75,8 @@ tmp/
75
75
 
76
76
  # Private planning notes (kept locally, not published)
77
77
  PLAN.md
78
+ # notes for Claude Code sessions; a CLAUDE.md in the repo is one of the detector's markers
79
+ CLAUDE.md
78
80
 
79
81
  # the web UI bundled into margin-api at release time (scripts/build_release.py)
80
82
  packages/api/src/margin_api/ui/
@@ -0,0 +1,54 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [Semantic Versioning](https://semver.org/).
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
+
21
+ ## [0.1.2] - 2026-10-29
22
+
23
+ ### Added
24
+ - Agents can ask the person running them: `await ctx.ask(questions, title=...)` puts one or
25
+ more `Question`s (choice, multiple choice or text, with a default and evidence) to whoever
26
+ runs the agent and returns the answers. `RunContext(responder=...)` decides how they are
27
+ asked; without a responder, questions take their defaults.
28
+ - `AnswersInput`: a base input model with the standard `answers` (given up front, not asked)
29
+ and `assume_defaults` fields.
30
+ - `RunMetadata.answers` keeps every answer and who gave it (`user`, `preset` or `default`).
31
+ Defaults nobody confirmed are also reported as warnings. The Markdown report lists the
32
+ answers.
33
+ - `NoAnswerError` for a question that could not be answered.
34
+
35
+ ## [0.1.1] - 2026-10-21
36
+
37
+ ### Security
38
+ - A repository's own git config could make git run a program while margin read its history,
39
+ for example through `core.fsmonitor`. Every git command now overrides the repository's
40
+ config, turns hooks off and skips Git LFS downloads. This mattered most in Docker, where
41
+ git's own ownership check is turned off for the shared folder.
42
+ - Cancelling a run while a repository was being cloned could leave a half-written clone in
43
+ the temp folder. git now runs as a child process that is stopped before the folder is
44
+ deleted.
45
+
46
+ ## [0.1.0] - 2026-10-21
47
+
48
+ ### Added
49
+ - The agent contract (`BaseAgent`, `RunContext`), structured results with findings and evidence, and the agent registry (entry-point group `margin.agents`).
50
+ - Model clients: local OpenAI-compatible servers (Ollama by default), Anthropic and OpenAI, with retries, token and cost tracking, per-run budgets, and a mock for tests.
51
+ - A model catalogue: list a provider's models, test a connection.
52
+ - Settings from environment variables, saved settings, `.env` and defaults, in that order.
53
+ - Code loaders: local folders and GitHub repositories, with filters, size limits, a pre-clone size check and git history.
54
+ - JSON and Markdown reports.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-core
3
- Version: 0.1.1
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.1"
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"
@@ -6,7 +6,13 @@ Public API::
6
6
  from margin_core import run_agent, list_agents, get_agent
7
7
  """
8
8
 
9
- from margin_core.agent import BaseAgent, CancellationToken, ProgressCallback, RunContext
9
+ from margin_core.agent import (
10
+ BaseAgent,
11
+ CancellationToken,
12
+ ProgressCallback,
13
+ Responder,
14
+ RunContext,
15
+ )
10
16
  from margin_core.errors import (
11
17
  AgentLoadError,
12
18
  AgentNotFoundError,
@@ -17,6 +23,7 @@ from margin_core.errors import (
17
23
  LimitExceededError,
18
24
  LLMError,
19
25
  LoaderError,
26
+ NoAnswerError,
20
27
  RunCancelledError,
21
28
  TransientLLMError,
22
29
  )
@@ -24,16 +31,21 @@ from margin_core.models import (
24
31
  AgentInfo,
25
32
  AgentInput,
26
33
  AgentResult,
34
+ Answer,
35
+ AnswersInput,
36
+ Choice,
27
37
  Evidence,
28
38
  Finding,
29
39
  ProgressEvent,
40
+ Question,
41
+ QuestionBatch,
30
42
  RunMetadata,
31
43
  TokenUsage,
32
44
  )
33
45
  from margin_core.registry import AgentRegistry, default_registry, get_agent, list_agents
34
46
  from margin_core.runner import run_agent
35
47
 
36
- __version__ = "0.1.1"
48
+ __version__ = "0.1.3"
37
49
 
38
50
  __all__ = [
39
51
  "AgentInfo",
@@ -43,9 +55,12 @@ __all__ = [
43
55
  "AgentRegistry",
44
56
  "AgentResult",
45
57
  "AgentsLibError",
58
+ "Answer",
59
+ "AnswersInput",
46
60
  "BaseAgent",
47
61
  "BudgetExceededError",
48
62
  "CancellationToken",
63
+ "Choice",
49
64
  "Evidence",
50
65
  "Finding",
51
66
  "InputValidationError",
@@ -53,8 +68,12 @@ __all__ = [
53
68
  "LLMError",
54
69
  "LimitExceededError",
55
70
  "LoaderError",
71
+ "NoAnswerError",
56
72
  "ProgressCallback",
57
73
  "ProgressEvent",
74
+ "Question",
75
+ "QuestionBatch",
76
+ "Responder",
58
77
  "RunCancelledError",
59
78
  "RunContext",
60
79
  "RunMetadata",
@@ -2,23 +2,27 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import asyncio
5
6
  import logging
6
7
  import time
7
8
  from abc import ABC, abstractmethod
8
- from collections.abc import Callable, Mapping, Sequence
9
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
9
10
  from datetime import UTC, datetime
10
11
  from typing import TYPE_CHECKING, Any, ClassVar
11
12
 
12
13
  from pydantic import BaseModel, ValidationError
13
14
 
14
- from margin_core.errors import InputValidationError, LLMError, RunCancelledError
15
+ from margin_core.errors import InputValidationError, LLMError, NoAnswerError, RunCancelledError
15
16
  from margin_core.llm.base import LLMClient
16
17
  from margin_core.logging import get_logger
17
18
  from margin_core.models import (
18
19
  AgentInfo,
19
20
  AgentResult,
21
+ Answer,
20
22
  Finding,
21
23
  ProgressEvent,
24
+ Question,
25
+ QuestionBatch,
22
26
  ResultStatus,
23
27
  TokenUsage,
24
28
  )
@@ -28,8 +32,12 @@ if TYPE_CHECKING:
28
32
  from margin_core.loaders.filters import FilterConfig
29
33
 
30
34
  ProgressCallback = Callable[[ProgressEvent], None]
35
+ Responder = Callable[[QuestionBatch], Awaitable[Mapping[str, Any]]]
36
+ """Puts a batch of questions to a person and returns the raw answers, by question id."""
31
37
 
32
- __all__ = ["BaseAgent", "CancellationToken", "ProgressCallback", "RunContext"]
38
+ _CANCEL_POLL_S = 0.2
39
+
40
+ __all__ = ["BaseAgent", "CancellationToken", "ProgressCallback", "Responder", "RunContext"]
33
41
 
34
42
 
35
43
  class CancellationToken:
@@ -51,7 +59,10 @@ class RunContext:
51
59
 
52
60
  During :meth:`BaseAgent.execute`, ``llm`` is a per-run :class:`LLMSession` opened from the
53
61
  configured client, limited by ``max_cost_usd``. Anything added with :meth:`warn` ends up in
54
- the result's ``warnings``.
62
+ the result's ``warnings``, and every answer from :meth:`ask` in its ``metadata.answers``.
63
+
64
+ ``responder`` is how :meth:`ask` reaches a person: the CLI asks in the terminal, the API
65
+ pauses the run until answers are posted. Without one, questions take their defaults.
55
66
  """
56
67
 
57
68
  def __init__(
@@ -62,13 +73,16 @@ class RunContext:
62
73
  cancel_token: CancellationToken | None = None,
63
74
  logger: logging.Logger | None = None,
64
75
  max_cost_usd: float | None = None,
76
+ responder: Responder | None = None,
65
77
  ) -> None:
66
78
  self.llm = llm
67
79
  self.progress = progress
68
80
  self.cancel_token = cancel_token or CancellationToken()
69
81
  self.logger = logger or get_logger("run")
70
82
  self.max_cost_usd = max_cost_usd
83
+ self.responder = responder
71
84
  self.warnings: list[str] = []
85
+ self.answers: list[Answer] = []
72
86
 
73
87
  def warn(self, message: str) -> None:
74
88
  """Record a warning for the result (duplicates are ignored)."""
@@ -110,6 +124,75 @@ class RunContext:
110
124
  if self.cancel_token.cancelled:
111
125
  raise RunCancelledError("Run was cancelled")
112
126
 
127
+ async def ask(
128
+ self,
129
+ questions: Sequence[Question],
130
+ *,
131
+ title: str,
132
+ detail: str | None = None,
133
+ preset: Mapping[str, Any] | None = None,
134
+ assume_defaults: bool = False,
135
+ ) -> dict[str, Answer]:
136
+ """Ask the person running the agent, wait for the answers, and return them by id.
137
+
138
+ All the questions are asked at once. Questions answered in ``preset`` (usually an
139
+ ``answers`` input field) are not asked. The rest go to the responder, unless there is
140
+ none or ``assume_defaults`` is set: then each takes its default, recorded as not
141
+ confirmed and reported as a warning. A required question without a default that
142
+ cannot be asked raises :class:`NoAnswerError`.
143
+ """
144
+ batch = QuestionBatch(title=title, detail=detail, questions=list(questions))
145
+ preset = preset or {}
146
+ answers: dict[str, Answer] = {}
147
+ for question in batch.questions:
148
+ if question.id in preset:
149
+ try:
150
+ value = question.check(preset[question.id])
151
+ except ValueError as exc:
152
+ raise InputValidationError(
153
+ f"The answer given for {question.id!r} is not valid: {exc}"
154
+ ) from exc
155
+ answers[question.id] = Answer.of(question, value, "preset")
156
+
157
+ remaining = [q for q in batch.questions if q.id not in answers]
158
+ if remaining and self.responder is not None and not assume_defaults:
159
+ pending = batch.model_copy(update={"questions": remaining})
160
+ self.check_cancelled()
161
+ raw = await self._wait_for_answers(self.responder(pending))
162
+ try:
163
+ answers.update(pending.resolve(raw, "user"))
164
+ except ValueError as exc:
165
+ raise InputValidationError(f"Invalid answers: {exc}") from exc
166
+ elif remaining:
167
+ unanswerable = [q.id for q in remaining if q.required and q.default is None]
168
+ if unanswerable:
169
+ raise NoAnswerError(
170
+ "These questions need an answer and there was no one to ask: "
171
+ f"{', '.join(unanswerable)}. Give the answers with the run's input."
172
+ )
173
+ for question in remaining:
174
+ answer = Answer.of(question, question.check(question.default), "default")
175
+ answers[question.id] = answer
176
+ if question.default is not None:
177
+ self.warn(f"Not confirmed: {question.prompt} Assumed: {answer.label}.")
178
+
179
+ ordered = {q.id: answers[q.id] for q in batch.questions}
180
+ self.answers.extend(ordered.values())
181
+ return ordered
182
+
183
+ async def _wait_for_answers(self, pending: Awaitable[Mapping[str, Any]]) -> Mapping[str, Any]:
184
+ """Await the responder, giving up as soon as the run is cancelled."""
185
+ task = asyncio.ensure_future(pending)
186
+ try:
187
+ while True:
188
+ done, _ = await asyncio.wait({task}, timeout=_CANCEL_POLL_S)
189
+ if done:
190
+ return task.result()
191
+ self.check_cancelled()
192
+ finally:
193
+ if not task.done():
194
+ task.cancel()
195
+
113
196
  def require_llm(self) -> LLMClient:
114
197
  """Return the LLM client or fail with a clear error if none was configured."""
115
198
  if self.llm is None:
@@ -241,6 +324,7 @@ class BaseAgent(ABC):
241
324
  "duration_s": round(time.perf_counter() - t0, 4),
242
325
  "model": result.metadata.model or used_model,
243
326
  "usage": session.usage if session else TokenUsage(),
327
+ "answers": [*result.metadata.answers, *ctx.answers],
244
328
  }
245
329
  )
246
330
  return result.model_copy(update={"metadata": metadata, "warnings": warnings})
@@ -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:
@@ -25,6 +25,10 @@ class RunCancelledError(AgentsLibError):
25
25
  """The run was cancelled through its cancellation token."""
26
26
 
27
27
 
28
+ class NoAnswerError(AgentsLibError):
29
+ """An agent's question could not be answered: nobody to ask, or no answer in time."""
30
+
31
+
28
32
  class LoaderError(AgentsLibError):
29
33
  """Base class for errors raised while loading a workspace."""
30
34
 
@@ -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