margin-core 0.1.0__tar.gz → 0.1.2__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.0 → margin_core-0.1.2}/.gitignore +2 -0
  2. margin_core-0.1.2/CHANGELOG.md +40 -0
  3. {margin_core-0.1.0 → margin_core-0.1.2}/PKG-INFO +1 -1
  4. {margin_core-0.1.0 → margin_core-0.1.2}/pyproject.toml +1 -1
  5. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/__init__.py +21 -2
  6. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/agent.py +88 -4
  7. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/errors.py +4 -0
  8. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/loaders/git.py +28 -3
  9. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/loaders/github.py +34 -9
  10. margin_core-0.1.2/src/margin_core/models.py +321 -0
  11. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/reporting/markdown_report.py +9 -0
  12. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_core_skeleton.py +1 -1
  13. margin_core-0.1.2/tests/test_questions.py +257 -0
  14. margin_core-0.1.2/tests/test_security.py +178 -0
  15. margin_core-0.1.0/CHANGELOG.md +0 -15
  16. margin_core-0.1.0/src/margin_core/models.py +0 -130
  17. {margin_core-0.1.0 → margin_core-0.1.2}/LICENSE +0 -0
  18. {margin_core-0.1.0 → margin_core-0.1.2}/README.md +0 -0
  19. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/_fs.py +0 -0
  20. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/config.py +0 -0
  21. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/inputs.py +0 -0
  22. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/__init__.py +0 -0
  23. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/_chat_completions.py +0 -0
  24. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/_http.py +0 -0
  25. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/anthropic.py +0 -0
  26. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/base.py +0 -0
  27. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/catalog.py +0 -0
  28. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/factory.py +0 -0
  29. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/local.py +0 -0
  30. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/mock.py +0 -0
  31. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/openai.py +0 -0
  32. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/llm/pricing.py +0 -0
  33. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/loaders/__init__.py +0 -0
  34. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/loaders/base.py +0 -0
  35. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/loaders/filters.py +0 -0
  36. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/loaders/local.py +0 -0
  37. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/logging.py +0 -0
  38. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/py.typed +0 -0
  39. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/registry.py +0 -0
  40. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/reporting/__init__.py +0 -0
  41. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/reporting/json_report.py +0 -0
  42. {margin_core-0.1.0 → margin_core-0.1.2}/src/margin_core/runner.py +0 -0
  43. {margin_core-0.1.0 → margin_core-0.1.2}/tests/conftest.py +0 -0
  44. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_agent.py +0 -0
  45. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_config.py +0 -0
  46. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_filters.py +0 -0
  47. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_github_loader.py +0 -0
  48. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_history_scope.py +0 -0
  49. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_inputs.py +0 -0
  50. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_llm.py +0 -0
  51. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_llm_session.py +0 -0
  52. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_local_llm.py +0 -0
  53. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_local_loader.py +0 -0
  54. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_models.py +0 -0
  55. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_preclone_check.py +0 -0
  56. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_registry.py +0 -0
  57. {margin_core-0.1.0 → margin_core-0.1.2}/tests/test_reporting.py +0 -0
  58. {margin_core-0.1.0 → margin_core-0.1.2}/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,40 @@
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
+ ## [0.1.2] - 2026-10-29
8
+
9
+ ### Added
10
+ - Agents can ask the person running them: `await ctx.ask(questions, title=...)` puts one or
11
+ more `Question`s (choice, multiple choice or text, with a default and evidence) to whoever
12
+ runs the agent and returns the answers. `RunContext(responder=...)` decides how they are
13
+ asked; without a responder, questions take their defaults.
14
+ - `AnswersInput`: a base input model with the standard `answers` (given up front, not asked)
15
+ and `assume_defaults` fields.
16
+ - `RunMetadata.answers` keeps every answer and who gave it (`user`, `preset` or `default`).
17
+ Defaults nobody confirmed are also reported as warnings. The Markdown report lists the
18
+ answers.
19
+ - `NoAnswerError` for a question that could not be answered.
20
+
21
+ ## [0.1.1] - 2026-10-21
22
+
23
+ ### Security
24
+ - A repository's own git config could make git run a program while margin read its history,
25
+ for example through `core.fsmonitor`. Every git command now overrides the repository's
26
+ config, turns hooks off and skips Git LFS downloads. This mattered most in Docker, where
27
+ git's own ownership check is turned off for the shared folder.
28
+ - Cancelling a run while a repository was being cloned could leave a half-written clone in
29
+ the temp folder. git now runs as a child process that is stopped before the folder is
30
+ deleted.
31
+
32
+ ## [0.1.0] - 2026-10-21
33
+
34
+ ### Added
35
+ - The agent contract (`BaseAgent`, `RunContext`), structured results with findings and evidence, and the agent registry (entry-point group `margin.agents`).
36
+ - 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.
37
+ - A model catalogue: list a provider's models, test a connection.
38
+ - Settings from environment variables, saved settings, `.env` and defaults, in that order.
39
+ - Code loaders: local folders and GitHub repositories, with filters, size limits, a pre-clone size check and git history.
40
+ - JSON and Markdown reports.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-core
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "margin-core"
3
- version = "0.1.0"
3
+ version = "0.1.2"
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.0"
48
+ __version__ = "0.1.2"
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})
@@ -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
 
@@ -1,4 +1,5 @@
1
- """Thin wrappers around the ``git`` CLI. Repository code is never executed."""
1
+ """Thin wrappers around the ``git`` CLI. Repository code is never executed: see
2
+ :data:`SAFE_GIT_CONFIG`."""
2
3
 
3
4
  from __future__ import annotations
4
5
 
@@ -29,8 +30,23 @@ def git_available() -> bool:
29
30
  return shutil.which("git") is not None
30
31
 
31
32
 
33
+ # Passed on every git command line, where they override any config, including a repository's
34
+ # own .git/config. A folder we are pointed at is untrusted: its config could name programs for
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.
37
+ SAFE_GIT_CONFIG = (
38
+ "core.fsmonitor=false",
39
+ "core.hooksPath=" + os.devnull,
40
+ "filter.lfs.smudge=",
41
+ "filter.lfs.process=",
42
+ "filter.lfs.required=false",
43
+ "i18n.logOutputEncoding=UTF-8",
44
+ )
45
+
46
+
32
47
  def safe_git_env() -> dict[str, str]:
33
- """Environment that prevents git from ever prompting (terminal, GUI, credential manager)."""
48
+ """Environment that prevents git from ever prompting (terminal, GUI, credential manager)
49
+ and from fetching Git LFS content."""
34
50
  env = dict(os.environ)
35
51
  env.update(
36
52
  {
@@ -38,14 +54,23 @@ def safe_git_env() -> dict[str, str]:
38
54
  "GIT_ASKPASS": "",
39
55
  "SSH_ASKPASS": "",
40
56
  "GCM_INTERACTIVE": "never",
57
+ "GIT_LFS_SKIP_SMUDGE": "1",
41
58
  }
42
59
  )
43
60
  return env
44
61
 
45
62
 
63
+ def git_command(args: list[str]) -> list[str]:
64
+ """``git <args>`` with the safety settings in front."""
65
+ cmd = ["git"]
66
+ for setting in SAFE_GIT_CONFIG:
67
+ cmd += ["-c", setting]
68
+ return cmd + args
69
+
70
+
46
71
  def run_git(args: list[str], cwd: Path | None = None, timeout_s: float = 60.0) -> str:
47
72
  """Run ``git <args>`` and return stdout (UTF-8). Raises :class:`GitCommandError`."""
48
- cmd = ["git", "-c", "i18n.logOutputEncoding=UTF-8", *args]
73
+ cmd = git_command(args)
49
74
  proc = subprocess.run(
50
75
  cmd,
51
76
  cwd=cwd,
@@ -14,8 +14,8 @@ it is never given to ``git``.
14
14
  from __future__ import annotations
15
15
 
16
16
  import asyncio
17
+ import contextlib
17
18
  import re
18
- import subprocess
19
19
  import tempfile
20
20
  from collections.abc import Sequence
21
21
  from pathlib import Path
@@ -27,7 +27,7 @@ from margin_core.config import get_settings
27
27
  from margin_core.errors import InvalidTargetError, LimitExceededError, LoaderError
28
28
  from margin_core.loaders.base import Loader, LoaderLimits, Workspace
29
29
  from margin_core.loaders.filters import FilterConfig
30
- from margin_core.loaders.git import GitCommandError, git_available, run_git
30
+ from margin_core.loaders.git import git_available, git_command, safe_git_env
31
31
  from margin_core.loaders.local import LocalLoader
32
32
 
33
33
  GITHUB_URL_RE = re.compile(
@@ -129,7 +129,7 @@ class GitHubLoader(Loader):
129
129
  )
130
130
  return None
131
131
 
132
- def _clone(self, url: str, dest: Path, branch: str | None) -> None:
132
+ def _clone_command(self, url: str, dest: Path, branch: str | None) -> list[str]:
133
133
  args = [
134
134
  "-c",
135
135
  "core.symlinks=false",
@@ -143,15 +143,32 @@ class GitHubLoader(Loader):
143
143
  ]
144
144
  if branch:
145
145
  args += ["--branch", branch]
146
- args += ["--", url, str(dest)]
146
+ return git_command([*args, "--", url, str(dest)])
147
+
148
+ async def _clone(self, url: str, dest: Path, branch: str | None) -> None:
149
+ """Clone as a child process we can kill. If the run is cancelled or the clone times
150
+ out, git is stopped and waited for before anything is deleted, so a half-written clone
151
+ never outlives the run."""
152
+ proc = await asyncio.create_subprocess_exec(
153
+ *self._clone_command(url, dest, branch),
154
+ stdin=asyncio.subprocess.DEVNULL,
155
+ stdout=asyncio.subprocess.DEVNULL,
156
+ stderr=asyncio.subprocess.PIPE,
157
+ env=safe_git_env(),
158
+ )
147
159
  try:
148
- run_git(args, timeout_s=self.limits.clone_timeout_s)
149
- except subprocess.TimeoutExpired as exc:
160
+ _, stderr = await asyncio.wait_for(proc.communicate(), self.limits.clone_timeout_s)
161
+ except TimeoutError as exc:
162
+ await _stop(proc)
150
163
  raise LimitExceededError(
151
164
  f"Clone timed out after {self.limits.clone_timeout_s:.0f}s"
152
165
  ) from exc
153
- except GitCommandError as exc:
154
- raise LoaderError(f"Could not clone {url}: {exc}") from exc
166
+ except BaseException: # cancelled
167
+ await _stop(proc)
168
+ raise
169
+ if proc.returncode != 0:
170
+ message = stderr.decode("utf-8", errors="replace").strip()
171
+ raise LoaderError(f"Could not clone {url}: {message}")
155
172
 
156
173
  async def load(
157
174
  self,
@@ -169,7 +186,7 @@ class GitHubLoader(Loader):
169
186
  tmp = Path(tempfile.mkdtemp(prefix="margin-"))
170
187
  try:
171
188
  dest = tmp / "repo"
172
- await asyncio.to_thread(self._clone, url, dest, branch)
189
+ await self._clone(url, dest, branch)
173
190
  size = await asyncio.to_thread(directory_size, dest)
174
191
  if size > self.limits.max_repo_size_bytes:
175
192
  raise LimitExceededError(
@@ -184,3 +201,11 @@ class GitHubLoader(Loader):
184
201
  if size_warning:
185
202
  ws.warnings.append(size_warning)
186
203
  return ws
204
+
205
+
206
+ async def _stop(proc: asyncio.subprocess.Process) -> None:
207
+ """Kill a child process and wait until it has really exited."""
208
+ if proc.returncode is None:
209
+ with contextlib.suppress(ProcessLookupError):
210
+ proc.kill()
211
+ await asyncio.shield(proc.wait())