cmpatino HF Staff Claude Opus 5.5 commited on
Commit
291746a
·
1 Parent(s): 4c782d0

world: decide the open-budget exemption from the applied tree; accept only git-diff patches

Browse files

Also: drop open_pr's request-id cache (the branch-slug rule already stops a
duplicate PR), close a keep-alive connection whose body was never read, time
out idle connections, bound unknown-base fetches to one per 5 s, install a
hashed dependency lock, remove unused World.tools/knobs, and describe the
current credentials and routes in the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

README.md CHANGED
@@ -2,7 +2,7 @@
2
 
3
  A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Face
4
  dataset, changed only through pull requests that other agents review and merge. This repository
5
- holds both halves that a [legion](https://github.com/huggingface/legion) run needs:
6
 
7
  ```
8
  tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,
@@ -10,24 +10,27 @@ tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): i
10
  pybot_mcp.py (the pybot tools as an MCP server; task.toml starts it)
11
  world/ the shared world service (World API v1), one per run
12
  pybot.py the world: PRs, reviews, the merge queue, bot runs, world_status
 
13
  repository.py the world's bare git repository and the Hub client
14
  sandbox.py runs a bot or its tests isolated; `python sandbox.py serve` is the sidecar
15
  snapshot.py the world's state archive in a bucket (world.tar.gz)
16
  seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
17
  tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
18
  scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
19
- requirements.txt the world's Python deps with hashes (legion's uv.lock at the pinned commit)
20
- Dockerfile the world image (also the sidecar's), with legion pinned to a commit;
21
- entrypoint.sh starts the world
22
  ```
23
 
24
  ## The world
25
 
26
  Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They work
27
  through the pybot tools, which the task's MCP server `pybot_mcp.py` serves: it reads
28
- `WORLD_URL` and `WORLD_TOKEN`, lists the tools from `GET $WORLD_URL/manifest`, calls
29
- `POST $WORLD_URL/tools/<name>`, and adds the caller's clone to `open_pr` and `run_bot` as a
30
- patch against its merge-base with `origin/main` (at most 750 KB). Check it with
 
 
31
  `python3 tasks/pybot-agent/pybot_mcp.py --self-test`.
32
 
33
  | tool | what it does |
@@ -44,9 +47,18 @@ The Hub stays the git backend: the world keeps a bare clone, pushes PR heads and
44
  the Hub API, and writes its state to `PYBOT_BUCKET` (`world.tar.gz`, restored into an empty
45
  workspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit).
46
 
47
- The world serves `/healthz`, `/manifest`, `/tools/*`, `/metrics` and `/admin/*` on `$PORT`.
48
- `X-World-Token` is the world secret (`LEGION_WORLD_TOKEN`) or, on `/manifest` and tool calls,
49
- an agent's own token for its `X-Legion-Agent`: HMAC-SHA256(secret, `legion-world-agent\0<agent>`).
 
 
 
 
 
 
 
 
 
50
 
51
  Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in the
52
  sidecar, a second container of the same image with command `python sandbox.py serve` that gets
@@ -72,7 +84,7 @@ git push https://huggingface.co/datasets/<ns>/<name> main # a write token via
72
  World (one per run; give it about 30 s to stop, so the final push completes):
73
 
74
  ```sh
75
- docker run -p 7860:7860 -e HF_TOKEN -e LEGION_WORLD_TOKEN \
76
  -e PYBOT_REPO=<ns>/<name> -e PYBOT_BUCKET=hf://buckets/<ns>/<bucket>/<run> \
77
  -e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \
78
  <registry>/pybot-world:<tag>
@@ -86,8 +98,7 @@ docker run --name sandbox -e PYBOT_SANDBOX_TOKEN <registry>/pybot-world:<tag> py
86
 
87
  On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set
88
  `PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s in
89
- the URL). On Slurm, leave `PYBOT_SANDBOX_URL` unset and set `LEGION_WORLD_HOST_FILE` so legion's
90
- controller can follow the world's `host:port`.
91
 
92
  Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give the
93
  world about 28 CPUs and 54 GB.
@@ -100,11 +111,11 @@ needs only the required ones.
100
  | variable | default | |
101
  |---|---|---|
102
  | `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv |
103
- | `LEGION_WORLD_TOKEN` | required | the world secret (`X-World-Token`); legion's `resources.world.token_env` holds the same value |
104
  | `PYBOT_REPO` | required | `<ns>/<name>` of the code dataset |
105
  | `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets/<ns>/<bucket>/<prefix>` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) |
106
  | `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here |
107
- | `LEGION_WORLD_ADMIN_TOKEN` | empty: `/admin` off | admin secret for live knobs and lane pauses |
108
  | `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute |
109
  | `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited |
110
  | `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` |
@@ -127,60 +138,28 @@ needs only the required ones.
127
  | `PYBOT_ANON_FETCH` | `1` | fetch anonymously first; `0`: always with the token |
128
  | `PYBOT_FETCH_TTL_S` | `60` | cache of a fetched main |
129
  | `PYBOT_CALL_BUDGET_S` | `50` | seconds a tool call may spend on Hub waits and push retries (callers wait about 55 s) |
130
- | `PYBOT_REQUEST_TTL_S` | `21600` | how long `open_pr` idempotency keys are kept |
131
  | `PYBOT_MAX_FILE_BYTES` | `1048576` | largest file in an uploaded clone |
132
  | `PYBOT_SAVE_INTERVAL_S` | `2.0` | seconds between state saves (0: every change) |
133
  | `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) |
134
  | `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) |
135
  | `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `<ws>/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists |
136
- | `PORT`, `PYBOT_WORK`, `LEGION_WORLD_HOST_FILE`, `WORLD_HOST` | `7860`, `/work`, unset, `$HOSTNAME` | entrypoint only: the port, the state directory, and where to write `host:port` |
137
-
138
- ## How a legion spec uses it
139
-
140
- The world is a resource that the operator starts; every agent runs the task. The spec names the
141
- published task and the world's URL:
142
-
143
- ```yaml
144
- task:
145
- repo: https://huggingface.co/datasets/<ns>/pybot
146
- selector: pybot-agent
147
- revision: '<commit sha>'
148
- resources:
149
- world:
150
- url: '${WORLD_URL}' # the world's URL (HF Jobs: the world job's public URL)
151
- token_env: PYBOT_WORLD_TOKEN # same value as the world's LEGION_WORLD_TOKEN; a new one per run
152
- transport: http # backends without mounts (hf-sandbox); `unix` on docker/podman
153
- tools:
154
- - world.*
155
- workers:
156
- env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it
157
- ```
158
 
159
- ## The legion pin
160
-
161
- The world imports legion's World API library (`legion.world`, `legion.isolation`,
162
- `legion.worker.sync`) from the installed `legion` package. Its commit is pinned in one place, the
163
- `legion @ git+https://github.com/huggingface/legion@<commit>` line in `world/Dockerfile`, and
164
- `requirements.txt` is legion's own `uv.lock` at that commit, exported with hashes. To bump it,
165
- change the commit there and regenerate `requirements.txt` from a legion clone (in `world/`):
166
-
167
- ```sh
168
- lock=$(mktemp -d) && git -C /path/to/legion archive <commit> pyproject.toml uv.lock | tar -x -C "$lock"
169
- uv export -q --project "$lock" --frozen --no-emit-project --extra controller --no-dev --no-header \
170
- --prune harbor --prune podman-compose --prune msgboard -o requirements.txt
171
- ```
172
 
173
- The prunes drop what the world does not use: Harbor and the board client (msgboard is a git
174
- dependency, which pip's `--require-hashes` refuses). Then run the checks below, rebuild the image
175
- and bump this dataset's `revision` in the legion specs that use it.
 
 
 
176
 
177
  ## Checks
178
 
179
  ```sh
180
  cd world
181
  pip install --require-hashes --no-deps -r requirements.txt
182
- pip install --no-deps "$(grep -o 'legion @ git+[^"]*' Dockerfile)" # legion at the pinned commit
183
- pip install pytest pytest-asyncio
184
  python -m pytest # the world's tests (Python 3.12, git, prlimit)
185
  python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
186
  python scripts/check-sidecar.py # the sidecar's checks
 
2
 
3
  A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Face
4
  dataset, changed only through pull requests that other agents review and merge. This repository
5
+ holds both halves of a run:
6
 
7
  ```
8
  tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,
 
10
  pybot_mcp.py (the pybot tools as an MCP server; task.toml starts it)
11
  world/ the shared world service (World API v1), one per run
12
  pybot.py the world: PRs, reviews, the merge queue, bot runs, world_status
13
+ api.py, server.py the tool layer (schemas, knobs, lane pauses) and its HTTP API
14
  repository.py the world's bare git repository and the Hub client
15
  sandbox.py runs a bot or its tests isolated; `python sandbox.py serve` is the sidecar
16
  snapshot.py the world's state archive in a bucket (world.tar.gz)
17
  seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
18
  tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
19
  scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
20
+ requirements.txt the world's Python deps, a hashed lock of huggingface_hub (how to
21
+ regenerate it is at its top)
22
+ Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world
23
  ```
24
 
25
  ## The world
26
 
27
  Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They work
28
  through the pybot tools, which the task's MCP server `pybot_mcp.py` serves: it reads
29
+ `WORLD_URL` (the world's URL ending in `/world`) and `WORLD_TOKEN` (the agent's credential),
30
+ lists the tools from `GET $WORLD_URL/manifest`, calls `POST $WORLD_URL/tools/<name>`, and adds
31
+ the caller's clone to `open_pr` and `run_bot` as a patch against its merge-base with
32
+ `origin/main` (at most 750 KB). A call still running after 50 s answers with a ticket that the
33
+ client-side tool `pybot_wait` redeems (MCP hosts may give up on a call after 60 s). Check it with
34
  `python3 tasks/pybot-agent/pybot_mcp.py --self-test`.
35
 
36
  | tool | what it does |
 
47
  the Hub API, and writes its state to `PYBOT_BUCKET` (`world.tar.gz`, restored into an empty
48
  workspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit).
49
 
50
+ The world serves on `$PORT` (`world/server.py` has the details):
51
+
52
+ | route | |
53
+ |---|---|
54
+ | `POST /v1/tools/<name>` | flat arguments; the result, or a 4xx/429 error |
55
+ | `GET /world/manifest`, `POST /world/tools/<name>` | the tools, and calls with `{"args": ...}` answered `{"ok", "result" or "error"}` (what the client uses) |
56
+ | `GET /healthz` | no credential: `ready` or `parked` (still starting) |
57
+ | `GET /metrics`, `/admin/*` | `PYBOT_ADMIN_TOKEN` only; `/admin/*` and tool calls answer 503 while the world is still starting |
58
+
59
+ Agent seat `i` (`agent-<i+1, 3 digits>`: seat 0 is `agent-001`) authenticates with the value of
60
+ `PYBOT_TOKEN_<i>`, as `X-World-Token` or `Authorization: Bearer`. Each agent gets its own value
61
+ as `WORLD_TOKEN`; the admin token never reaches an agent.
62
 
63
  Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in the
64
  sidecar, a second container of the same image with command `python sandbox.py serve` that gets
 
84
  World (one per run; give it about 30 s to stop, so the final push completes):
85
 
86
  ```sh
87
+ docker run -p 7860:7860 -e HF_TOKEN -e PYBOT_TOKEN_0 -e PYBOT_TOKEN_1 -e PYBOT_ADMIN_TOKEN \
88
  -e PYBOT_REPO=<ns>/<name> -e PYBOT_BUCKET=hf://buckets/<ns>/<bucket>/<run> \
89
  -e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \
90
  <registry>/pybot-world:<tag>
 
98
 
99
  On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set
100
  `PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s in
101
+ the URL). Where `unshare` is allowed (e.g. Slurm), leave `PYBOT_SANDBOX_URL` unset.
 
102
 
103
  Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give the
104
  world about 28 CPUs and 54 GB.
 
111
  | variable | default | |
112
  |---|---|---|
113
  | `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv |
114
+ | `PYBOT_TOKEN_<seat>` | required, from seat 0 | each agent's credential (seat 0 is `agent-001`); a new set per run |
115
  | `PYBOT_REPO` | required | `<ns>/<name>` of the code dataset |
116
  | `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets/<ns>/<bucket>/<prefix>` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) |
117
  | `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here |
118
+ | `PYBOT_ADMIN_TOKEN` | empty: `/metrics` and `/admin` off | admin secret for metrics, live knobs and lane pauses |
119
  | `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute |
120
  | `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited |
121
  | `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` |
 
138
  | `PYBOT_ANON_FETCH` | `1` | fetch anonymously first; `0`: always with the token |
139
  | `PYBOT_FETCH_TTL_S` | `60` | cache of a fetched main |
140
  | `PYBOT_CALL_BUDGET_S` | `50` | seconds a tool call may spend on Hub waits and push retries (callers wait about 55 s) |
 
141
  | `PYBOT_MAX_FILE_BYTES` | `1048576` | largest file in an uploaded clone |
142
  | `PYBOT_SAVE_INTERVAL_S` | `2.0` | seconds between state saves (0: every change) |
143
  | `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) |
144
  | `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) |
145
  | `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `<ws>/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists |
146
+ | `PORT`, `PYBOT_WORK` | `7860`, `/work` | entrypoint only: the port and the state directory |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
+ ## Running the task
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ Start the world first; then run one Trial of `tasks/pybot-agent` per agent, each with its own
151
+ seat. The launcher's environment gives the task `PYBOT_REPO` (task.toml passes it on), and each
152
+ agent's environment needs `WORLD_URL` (`https://<world host>/world`) and `WORLD_TOKEN` (its
153
+ seat's `PYBOT_TOKEN_<i>` value) for the pybot MCP server, which task.toml fetches at a pinned
154
+ commit and checks by sha256. A change to `pybot_mcp.py` needs a new pin: commit it, then point
155
+ the commit and sha256 in task.toml at that commit.
156
 
157
  ## Checks
158
 
159
  ```sh
160
  cd world
161
  pip install --require-hashes --no-deps -r requirements.txt
162
+ pip install pytest
 
163
  python -m pytest # the world's tests (Python 3.12, git, prlimit)
164
  python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
165
  python scripts/check-sidecar.py # the sidecar's checks
world/Dockerfile CHANGED
@@ -2,7 +2,7 @@
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
- # 3.12+). The world's only Python dependency is huggingface_hub (requirements.txt).
6
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
7
 
8
  # git: the world's bare repo, fetches and pushes to the Hub.
@@ -12,7 +12,7 @@ RUN apt-get update \
12
  && rm -rf /var/lib/apt/lists/*
13
 
14
  COPY requirements.txt /opt/world/requirements.txt
15
- RUN pip install --no-cache-dir -r /opt/world/requirements.txt
16
 
17
  COPY *.py /opt/world/
18
  COPY seed/ /opt/world/seed/
 
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
+ # 3.12+). The world's only Python dependency is huggingface_hub (requirements.txt: a hashed lock).
6
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
7
 
8
  # git: the world's bare repo, fetches and pushes to the Hub.
 
12
  && rm -rf /var/lib/apt/lists/*
13
 
14
  COPY requirements.txt /opt/world/requirements.txt
15
+ RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
16
 
17
  COPY *.py /opt/world/
18
  COPY seed/ /opt/world/seed/
world/api.py CHANGED
@@ -26,10 +26,9 @@ POOLS = ("fast", "slow")
26
 
27
  @dataclass(frozen=True)
28
  class Agent:
29
- """Who calls: the agent's name (from its credential) and the request id, if one was sent."""
30
 
31
  name: str
32
- request_id: str = ""
33
 
34
 
35
  class ToolError(Exception):
@@ -291,8 +290,8 @@ class Admin:
291
  # ------------------------------------------------------------------ the base class
292
 
293
  class World:
294
- """Base class. Class attributes: `name`, `description` (shown to the agents); `concurrent`
295
- is informational (the server always runs calls concurrently: the world guards its state)."""
296
 
297
  name: typing.ClassVar[str] = "world"
298
  description: typing.ClassVar[str] = ""
@@ -321,10 +320,6 @@ class World:
321
  cls._manifest = {"name": cls.name, "description": cls.description, "tools": tools}
322
  return json.loads(json.dumps(cls._manifest))
323
 
324
- def tools(self) -> dict[str, Callable]:
325
- """The bound `@tool` methods, by name."""
326
- return {name: getattr(self, name) for name in self.tool_functions()}
327
-
328
  @classmethod
329
  def pool(cls, tool: str) -> str:
330
  fn = cls.tool_functions().get(tool)
@@ -362,11 +357,6 @@ class World:
362
  raise ValueError(f"knob {name}: type must be one of int, float, bool, str")
363
  return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
364
 
365
- @property
366
- def knobs(self) -> dict[str, Any]:
367
- """The knobs' current values, by name."""
368
- return self.admin.values
369
-
370
  def paused(self, lane: str) -> bool:
371
  """Did an operator pause `lane` (`POST /admin/pause`)?"""
372
  return lane in self.admin.paused
 
26
 
27
  @dataclass(frozen=True)
28
  class Agent:
29
+ """Who calls: the agent's name (from its credential)."""
30
 
31
  name: str
 
32
 
33
 
34
  class ToolError(Exception):
 
290
  # ------------------------------------------------------------------ the base class
291
 
292
  class World:
293
+ """Base class. Class attributes: `name`, `description` (shown to the agents). The server
294
+ runs calls concurrently: the world guards its state."""
295
 
296
  name: typing.ClassVar[str] = "world"
297
  description: typing.ClassVar[str] = ""
 
320
  cls._manifest = {"name": cls.name, "description": cls.description, "tools": tools}
321
  return json.loads(json.dumps(cls._manifest))
322
 
 
 
 
 
323
  @classmethod
324
  def pool(cls, tool: str) -> str:
325
  fn = cls.tool_functions().get(tool)
 
357
  raise ValueError(f"knob {name}: type must be one of int, float, bool, str")
358
  return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
359
 
 
 
 
 
 
360
  def paused(self, lane: str) -> bool:
361
  """Did an operator pause `lane` (`POST /admin/pause`)?"""
362
  return lane in self.admin.paused
world/pybot.py CHANGED
@@ -8,7 +8,6 @@ import collections
8
  import concurrent.futures
9
  import contextlib
10
  import functools
11
- import hashlib
12
  import inspect
13
  import json
14
  import logging
@@ -39,9 +38,6 @@ MODULE_FILE = re.compile(r"bot/modules/(?:[^/]+\.py|[^/]+/__init__\.py)")
39
  MAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20)))
40
  EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/",
41
  "*.egg-info/", ".DS_Store")
42
- MAX_REQUESTS = 5000 # open_pr idempotency keys (X-Request-Id) kept for retries (oldest dropped)
43
- # ... and for at most this long (a client retries within minutes).
44
- REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600"))
45
  # state.db (and prs.json, see save.legacy_json) is written by a background thread at most once
46
  # per this many seconds while the state changed (0: write synchronously on every change).
47
  # close() always writes it.
@@ -72,7 +68,7 @@ COMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub
72
  MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))
73
  # State rows in state.db (store.py): these top-level dicts get one row per entry;
74
  # every other top-level value (pr_opens, pr_merges) is one row of kind "_".
75
- KINDS = ("prs", "requests", "drafts", "inbox")
76
  COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this
77
  VERDICTS_MAX = 2000 # interview verdicts kept (oldest dropped)
78
  VERDICT_NOTES = 600 # note characters kept per verdict
@@ -201,9 +197,6 @@ class PybotWorld(World):
201
  for key, value in self.store.iter(kind):
202
  self.state.setdefault(kind, {})[key] = value
203
  self.state.update(self.store.iter("_"))
204
- # Pruning expects oldest first; an upsert keeps a re-cached key's first position.
205
- self.state["requests"] = dict(sorted(self.state["requests"].items(),
206
- key=lambda kv: kv[1].get("_ts", 0)))
207
  if old_json is not None and self.legacy_json and {**empty, **old_json} != self.state:
208
  log.warning("state: prs.json and state.db differ at start; using state.db")
209
  self.cold_branches = {rec["branch"] for _, rec in self.store.iter("prs", cold=True)}
@@ -244,7 +237,7 @@ class PybotWorld(World):
244
  # {"ts", "pr", "code"} and shared-test runs {"ts", "main_sha", "result", "seconds"}.
245
  self.merge_refusals = collections.deque(maxlen=1000)
246
  self.test_runs = collections.deque(maxlen=200)
247
- self.pending = {} # open_pr reservations: token -> (author, branch ref, pr or None, key)
248
  self.operators = {n.strip() for n in os.environ.get("PYBOT_OPERATORS", "").split(",") if n.strip()}
249
  # Pause open_pr/merge_pr: PYBOT_PRS_PAUSED=1 at start, or the flag file, checked per call.
250
  self.paused_env = os.environ.get("PYBOT_PRS_PAUSED", "").strip() not in ("", "0")
@@ -307,9 +300,6 @@ class PybotWorld(World):
307
  on_change=lambda v: setattr(self, "budget_floor", v))
308
  self.open_reserved = set() # new-PR calls past the budget check, Hub PR not yet created
309
  self.stopping = threading.Event()
310
- with self.lock: # cached results stored in full are slimmed: the first save is already small
311
- if self._slim_requests():
312
- self._save()
313
  with self.lock: # the archive may predate merges that already landed on the Hub
314
  for rec in self.state["prs"].values():
315
  if rec["state"] in ("closing", "merging"): # interrupted: the agent may retry
@@ -661,78 +651,6 @@ class PybotWorld(World):
661
  finally:
662
  tmp.unlink(missing_ok=True)
663
 
664
- # -- open_pr idempotency cache ----------------------------------------------------------
665
-
666
- @staticmethod
667
- def _digest(text):
668
- return hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()
669
-
670
- def _slim(self, entry, now):
671
- """Strip the description from a cached open_pr result (a replay rebuilds it, see
672
- _replay) and stamp it; returns True if the entry changed."""
673
- changed = False
674
- if not isinstance(entry.get("_ts"), (int, float)):
675
- entry["_ts"] = now
676
- changed = True
677
- if isinstance(entry.get("description"), str):
678
- entry["_description_sha256"] = self._digest(entry["description"])
679
- entry["description"] = None # keeps the key's place in the result
680
- changed = True
681
- return changed
682
-
683
- def _cache_request(self, key, result):
684
- """Cache an open_pr result for retries of the same request (call with the lock held)."""
685
- now = time.time()
686
- entry = dict(result)
687
- self._slim(entry, now)
688
- requests = self.state["requests"]
689
- requests.pop(key, None)
690
- requests[key] = entry
691
- self._dirty("requests", key)
692
- self._prune_requests(now)
693
-
694
- def _prune_requests(self, now):
695
- """Drop cached results older than REQUEST_TTL, then the oldest past MAX_REQUESTS
696
- (entries are in insertion order, so oldest first). Returns True if any was dropped."""
697
- requests = self.state["requests"]
698
- cut = now - REQUEST_TTL
699
- stale = []
700
- for key, entry in requests.items():
701
- if entry["_ts"] > cut:
702
- break
703
- stale.append(key)
704
- stale += list(requests)[len(stale):max(len(stale), len(requests) - MAX_REQUESTS)]
705
- for key in stale:
706
- del requests[key]
707
- self._dirty("requests", *stale)
708
- return bool(stale)
709
-
710
- def _slim_requests(self):
711
- """Startup: slim every cached result (full entries, which have no timestamp, get the
712
- current time) and prune. Returns True if the state changed."""
713
- now = time.time()
714
- changed = False
715
- for key, entry in self.state["requests"].items():
716
- if self._slim(entry, now):
717
- self._dirty("requests", key)
718
- changed = True
719
- return self._prune_requests(now) or changed
720
-
721
- def _replay(self, key, description):
722
- """The result an open_pr request already returned (call with the lock held). The
723
- description comes from the retried call (the same request carries the same one) or
724
- else from the PR record, whichever matches the digest stored with the result."""
725
- entry = self.state["requests"][key]
726
- result = {k: v for k, v in entry.items() if not k.startswith("_")}
727
- digest = entry.get("_description_sha256")
728
- if digest is not None:
729
- rec = self.state["prs"].get(str(entry.get("pr"))) or {}
730
- candidates = [description, rec.get("description")]
731
- result["description"] = next(
732
- (c for c in candidates if isinstance(c, str) and self._digest(c) == digest),
733
- description)
734
- return result
735
-
736
  def _event(self, action, agent, **data):
737
  with open(self.ws / "prs.jsonl", "a") as out:
738
  out.write(json.dumps({"ts": time.time(), "event": action, "agent": agent.name,
@@ -996,7 +914,7 @@ class PybotWorld(World):
996
  raise ToolError('workspace must be {"base_sha": "<40 hex>", "patch": "<base64>"}',
997
  "bad_workspace")
998
  if not self.repo.has_commit(base):
999
- self.repo.refresh(0)
1000
  if not self.repo.has_commit(base):
1001
  raise ToolError(f"unknown base {base[:12]}: fetch origin/main and rebase your branch",
1002
  "unknown_base")
@@ -1108,11 +1026,8 @@ class PybotWorld(World):
1108
  "which send it as workspace", "bad_workspace")
1109
  # Scope new_modules: a PR that adds no module is outside the budget.
1110
  exempt = self.budget_scope == "new_modules" and not self._adds_module(snapshot)
1111
- key = agent.request_id
1112
  branch_ref = f"agents/{agent.name}/{branch}"
1113
  with self.lock:
1114
- if key and key in self.state["requests"]:
1115
- return self._replay(key, description)
1116
  if pr is None and branch_ref not in self.state["drafts"] and not exempt:
1117
  self._check_budget(agent) # before any fetch, build or Hub call
1118
  # The lock is held only for state and the main check; fetches, copies, compiles,
@@ -1121,8 +1036,6 @@ class PybotWorld(World):
1121
  base = self._workspace(snapshot)
1122
  token = object()
1123
  with self.lock:
1124
- if key and key in self.state["requests"]:
1125
- return self._replay(key, description)
1126
  if not self.repo.ancestor(base, "main"):
1127
  raise ToolError("base is not a main commit; fetch main and rebase your branch")
1128
  # A parked draft (its Hub PR exists, its head never landed) is reused, never recreated.
@@ -1138,8 +1051,6 @@ class PybotWorld(World):
1138
  "module; open a new PR to add one", "open_budget")
1139
  number = draft["pr"] if draft else (pr if old else None)
1140
  pending = self.pending.values()
1141
- if key and any(p[3] == key for p in pending):
1142
- raise ToolError("this request is already in progress", "busy")
1143
  if number is not None and any(p[2] == number for p in pending):
1144
  raise ToolError("an update of this PR is already in progress; retry when it finishes")
1145
  if not old and not draft:
@@ -1158,11 +1069,12 @@ class PybotWorld(World):
1158
  self._check_budget(agent)
1159
  self.open_reserved.add(token)
1160
  old_head = old["head_sha"] if old else None
1161
- self.pending[token] = (agent.name, branch_ref, number, key)
1162
  try:
1163
  number, sha, main, old_head = self._publish(agent, snapshot, base, title, description,
1164
  branch_ref, number, old_head, started, token,
1165
- counted=not exempt)
 
1166
  with self.lock:
1167
  if old and (old["state"] != "open" or old["head_sha"] != old_head):
1168
  raise ToolError("the PR was merged or closed during the update")
@@ -1189,8 +1101,6 @@ class PybotWorld(World):
1189
  result["note"] = (f"rebased onto main {main[:12]}; run "
1190
  f"git -c protocol.version=0 fetch origin refs/pr/{number} "
1191
  "and continue from FETCH_HEAD")
1192
- if key:
1193
- self._cache_request(key, result)
1194
  self._save()
1195
  self._event("updated" if old else "opened", agent, **result)
1196
  return result
@@ -1199,25 +1109,32 @@ class PybotWorld(World):
1199
  self.pending.pop(token, None)
1200
  self.open_reserved.discard(token)
1201
 
1202
- def _build(self, agent, snapshot, base, title, main):
1203
- """Commit the upload on base, replayed onto main (outside the world lock)."""
 
1204
  with self._checkout_slot(), tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp:
1205
  tree = Path(tmp) / "tree"
1206
  self.repo.checkout(base, tree)
1207
  self._files(snapshot, tree)
1208
  self._contract(tree, self.repo.staged(tree))
 
 
 
 
 
 
1209
  # An older base is rebased onto main here, before anything exists on the Hub.
1210
  return self.repo.commit(tree, base, agent.name, title, onto=main)
1211
 
1212
  def _publish(self, agent, snapshot, base, title, description, branch_ref, pr, old_head, started,
1213
- token=None, counted=True):
1214
  """Publish the upload: update open PR pr (old_head set), finish parked draft pr, or
1215
  create one Hub PR. At most one create_pull_request per call, and a created PR is
1216
  never closed by the world: if its head cannot be pushed it is parked as a draft."""
1217
  deadline = None
1218
  for _attempt in range(3):
1219
  main = self.repo.sha()
1220
- sha = self._build(agent, snapshot, base, title, main)
1221
  if pr is None and self.repo.sha() != main: # nothing on the Hub yet: rebuild on a moved main
1222
  continue
1223
  if deadline is None:
@@ -1235,7 +1152,7 @@ class PybotWorld(World):
1235
  pr = self.repo.hub.open(title, f"Agent: {agent.name}\nBase: {main}\n\n{description}")
1236
  with self.lock: # the reservation becomes a counted open
1237
  self.open_reserved.discard(token)
1238
- if counted:
1239
  now = time.time()
1240
  self._recent(self.state["pr_opens"], now).append(now)
1241
  self._dirty("_", "pr_opens")
 
8
  import concurrent.futures
9
  import contextlib
10
  import functools
 
11
  import inspect
12
  import json
13
  import logging
 
38
  MAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20)))
39
  EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/",
40
  "*.egg-info/", ".DS_Store")
 
 
 
41
  # state.db (and prs.json, see save.legacy_json) is written by a background thread at most once
42
  # per this many seconds while the state changed (0: write synchronously on every change).
43
  # close() always writes it.
 
68
  MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))
69
  # State rows in state.db (store.py): these top-level dicts get one row per entry;
70
  # every other top-level value (pr_opens, pr_merges) is one row of kind "_".
71
+ KINDS = ("prs", "drafts", "inbox")
72
  COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this
73
  VERDICTS_MAX = 2000 # interview verdicts kept (oldest dropped)
74
  VERDICT_NOTES = 600 # note characters kept per verdict
 
197
  for key, value in self.store.iter(kind):
198
  self.state.setdefault(kind, {})[key] = value
199
  self.state.update(self.store.iter("_"))
 
 
 
200
  if old_json is not None and self.legacy_json and {**empty, **old_json} != self.state:
201
  log.warning("state: prs.json and state.db differ at start; using state.db")
202
  self.cold_branches = {rec["branch"] for _, rec in self.store.iter("prs", cold=True)}
 
237
  # {"ts", "pr", "code"} and shared-test runs {"ts", "main_sha", "result", "seconds"}.
238
  self.merge_refusals = collections.deque(maxlen=1000)
239
  self.test_runs = collections.deque(maxlen=200)
240
+ self.pending = {} # open_pr reservations: token -> (author, branch ref, pr or None)
241
  self.operators = {n.strip() for n in os.environ.get("PYBOT_OPERATORS", "").split(",") if n.strip()}
242
  # Pause open_pr/merge_pr: PYBOT_PRS_PAUSED=1 at start, or the flag file, checked per call.
243
  self.paused_env = os.environ.get("PYBOT_PRS_PAUSED", "").strip() not in ("", "0")
 
300
  on_change=lambda v: setattr(self, "budget_floor", v))
301
  self.open_reserved = set() # new-PR calls past the budget check, Hub PR not yet created
302
  self.stopping = threading.Event()
 
 
 
303
  with self.lock: # the archive may predate merges that already landed on the Hub
304
  for rec in self.state["prs"].values():
305
  if rec["state"] in ("closing", "merging"): # interrupted: the agent may retry
 
651
  finally:
652
  tmp.unlink(missing_ok=True)
653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654
  def _event(self, action, agent, **data):
655
  with open(self.ws / "prs.jsonl", "a") as out:
656
  out.write(json.dumps({"ts": time.time(), "event": action, "agent": agent.name,
 
914
  raise ToolError('workspace must be {"base_sha": "<40 hex>", "patch": "<base64>"}',
915
  "bad_workspace")
916
  if not self.repo.has_commit(base):
917
+ self.repo.fetch(max_age=5) # joins a running fetch; at most one new fetch per 5 s
918
  if not self.repo.has_commit(base):
919
  raise ToolError(f"unknown base {base[:12]}: fetch origin/main and rebase your branch",
920
  "unknown_base")
 
1026
  "which send it as workspace", "bad_workspace")
1027
  # Scope new_modules: a PR that adds no module is outside the budget.
1028
  exempt = self.budget_scope == "new_modules" and not self._adds_module(snapshot)
 
1029
  branch_ref = f"agents/{agent.name}/{branch}"
1030
  with self.lock:
 
 
1031
  if pr is None and branch_ref not in self.state["drafts"] and not exempt:
1032
  self._check_budget(agent) # before any fetch, build or Hub call
1033
  # The lock is held only for state and the main check; fetches, copies, compiles,
 
1036
  base = self._workspace(snapshot)
1037
  token = object()
1038
  with self.lock:
 
 
1039
  if not self.repo.ancestor(base, "main"):
1040
  raise ToolError("base is not a main commit; fetch main and rebase your branch")
1041
  # A parked draft (its Hub PR exists, its head never landed) is reused, never recreated.
 
1051
  "module; open a new PR to add one", "open_budget")
1052
  number = draft["pr"] if draft else (pr if old else None)
1053
  pending = self.pending.values()
 
 
1054
  if number is not None and any(p[2] == number for p in pending):
1055
  raise ToolError("an update of this PR is already in progress; retry when it finishes")
1056
  if not old and not draft:
 
1069
  self._check_budget(agent)
1070
  self.open_reserved.add(token)
1071
  old_head = old["head_sha"] if old else None
1072
+ self.pending[token] = (agent.name, branch_ref, number)
1073
  try:
1074
  number, sha, main, old_head = self._publish(agent, snapshot, base, title, description,
1075
  branch_ref, number, old_head, started, token,
1076
+ exempt=old.get("budget_exempt", False)
1077
+ if old else exempt)
1078
  with self.lock:
1079
  if old and (old["state"] != "open" or old["head_sha"] != old_head):
1080
  raise ToolError("the PR was merged or closed during the update")
 
1101
  result["note"] = (f"rebased onto main {main[:12]}; run "
1102
  f"git -c protocol.version=0 fetch origin refs/pr/{number} "
1103
  "and continue from FETCH_HEAD")
 
 
1104
  self._save()
1105
  self._event("updated" if old else "opened", agent, **result)
1106
  return result
 
1109
  self.pending.pop(token, None)
1110
  self.open_reserved.discard(token)
1111
 
1112
+ def _build(self, agent, snapshot, base, title, main, exempt=False):
1113
+ """Commit the upload on base, replayed onto main (outside the world lock). exempt: the
1114
+ PR is outside the open budget, so the applied change must add no module."""
1115
  with self._checkout_slot(), tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp:
1116
  tree = Path(tmp) / "tree"
1117
  self.repo.checkout(base, tree)
1118
  self._files(snapshot, tree)
1119
  self._contract(tree, self.repo.staged(tree))
1120
+ if exempt: # decided from the applied tree: the patch text may hide an added module
1121
+ added = self.repo.git("diff", "--cached", "--name-only", "-z", "--no-renames",
1122
+ "--diff-filter=A", "HEAD", at=tree).split("\0")
1123
+ if any(MODULE_FILE.fullmatch(name) for name in added):
1124
+ raise ToolError("this change adds a module, so it counts against the open "
1125
+ "budget: send your clone through the pybot tools", "open_budget")
1126
  # An older base is rebased onto main here, before anything exists on the Hub.
1127
  return self.repo.commit(tree, base, agent.name, title, onto=main)
1128
 
1129
  def _publish(self, agent, snapshot, base, title, description, branch_ref, pr, old_head, started,
1130
+ token=None, exempt=False):
1131
  """Publish the upload: update open PR pr (old_head set), finish parked draft pr, or
1132
  create one Hub PR. At most one create_pull_request per call, and a created PR is
1133
  never closed by the world: if its head cannot be pushed it is parked as a draft."""
1134
  deadline = None
1135
  for _attempt in range(3):
1136
  main = self.repo.sha()
1137
+ sha = self._build(agent, snapshot, base, title, main, exempt)
1138
  if pr is None and self.repo.sha() != main: # nothing on the Hub yet: rebuild on a moved main
1139
  continue
1140
  if deadline is None:
 
1152
  pr = self.repo.hub.open(title, f"Agent: {agent.name}\nBase: {main}\n\n{description}")
1153
  with self.lock: # the reservation becomes a counted open
1154
  self.open_reserved.discard(token)
1155
+ if not exempt:
1156
  now = time.time()
1157
  self._recent(self.state["pr_opens"], now).append(now)
1158
  self._dirty("_", "pr_opens")
world/repository.py CHANGED
@@ -137,12 +137,13 @@ class Repository:
137
  self.git("-c", "protocol.version=2", *options, "fetch", "--no-write-fetch-head",
138
  *self.negotiation(), remote, *specs, env=env)
139
 
140
- def fetch(self):
141
  """Fetch main only. The world writes refs/pr/N itself after every push (update_refs), so
142
  PR refs never come from the Hub here; a wildcard over refs/pr/* is also refused by the
143
  Hub's git backend once there are many PRs (hang-up / 'expected acknowledgments').
144
- A fetch that started after this call is as fresh as this one: waiters behind it return."""
145
- asked = time.monotonic()
 
146
  with self.refs_lock:
147
  if self.fetched > asked:
148
  return
 
137
  self.git("-c", "protocol.version=2", *options, "fetch", "--no-write-fetch-head",
138
  *self.negotiation(), remote, *specs, env=env)
139
 
140
+ def fetch(self, max_age=0.0):
141
  """Fetch main only. The world writes refs/pr/N itself after every push (update_refs), so
142
  PR refs never come from the Hub here; a wildcard over refs/pr/* is also refused by the
143
  Hub's git backend once there are many PRs (hang-up / 'expected acknowledgments').
144
+ A fetch that started after this call (or less than max_age seconds before it, also one
145
+ still running) is as fresh as this one: waiters behind it return."""
146
+ asked = time.monotonic() - max_age
147
  with self.refs_lock:
148
  if self.fetched > asked:
149
  return
world/requirements.txt CHANGED
@@ -1 +1,157 @@
1
- huggingface_hub==1.33.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # huggingface_hub==1.33.0 and its dependencies for the image (Python 3.12, Linux), installed
2
+ # with --require-hashes. Regenerate with:
3
+ # echo huggingface_hub==1.33.0 | uv pip compile --generate-hashes --python-version 3.12 \
4
+ # --python-platform linux --no-header - -o requirements.txt
5
+ anyio==4.16.0 \
6
+ --hash=sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb \
7
+ --hash=sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026
8
+ # via httpx
9
+ certifi==2026.11.20 \
10
+ --hash=sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f \
11
+ --hash=sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e
12
+ # via
13
+ # httpcore
14
+ # httpx
15
+ click==8.5.1 \
16
+ --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 \
17
+ --hash=sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4
18
+ # via huggingface-hub
19
+ filelock==4.3.2 \
20
+ --hash=sha256:02a8801bc6b2a80921bf3d7895c63084d53bae2a3c86783adce5ae2b89a1825b \
21
+ --hash=sha256:4f0a21c70447782453c06bb20a9863ee385ead1abaef22049af79289496851b3
22
+ # via huggingface-hub
23
+ fsspec==2026.9.0 \
24
+ --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \
25
+ --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f
26
+ # via huggingface-hub
27
+ h11==0.16.0 \
28
+ --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \
29
+ --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
30
+ # via httpcore
31
+ hf-xet==1.8.0 \
32
+ --hash=sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330 \
33
+ --hash=sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e \
34
+ --hash=sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01 \
35
+ --hash=sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa \
36
+ --hash=sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d \
37
+ --hash=sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4 \
38
+ --hash=sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba \
39
+ --hash=sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b \
40
+ --hash=sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740 \
41
+ --hash=sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b \
42
+ --hash=sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c \
43
+ --hash=sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f \
44
+ --hash=sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec \
45
+ --hash=sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c \
46
+ --hash=sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56 \
47
+ --hash=sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e \
48
+ --hash=sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01
49
+ # via huggingface-hub
50
+ httpcore==1.0.9 \
51
+ --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \
52
+ --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8
53
+ # via httpx
54
+ httpx==0.29.0 \
55
+ --hash=sha256:6734dcf742ced6e8018e45d3f9f7728975b6b3e1085a24f3e2c056069d858bd1 \
56
+ --hash=sha256:700928ee6c1f4213795e67c47eba8f8553639069fea89199f71d654e38edc593
57
+ # via huggingface-hub
58
+ huggingface-hub==1.33.0 \
59
+ --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \
60
+ --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e
61
+ idna==3.20 \
62
+ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
63
+ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
64
+ # via
65
+ # anyio
66
+ # httpx
67
+ packaging==26.4 \
68
+ --hash=sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2 \
69
+ --hash=sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a
70
+ # via huggingface-hub
71
+ pyyaml==6.0.4 \
72
+ --hash=sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a \
73
+ --hash=sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f \
74
+ --hash=sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318 \
75
+ --hash=sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788 \
76
+ --hash=sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8 \
77
+ --hash=sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531 \
78
+ --hash=sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43 \
79
+ --hash=sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91 \
80
+ --hash=sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe \
81
+ --hash=sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055 \
82
+ --hash=sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7 \
83
+ --hash=sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e \
84
+ --hash=sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1 \
85
+ --hash=sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1 \
86
+ --hash=sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36 \
87
+ --hash=sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd \
88
+ --hash=sha256:34edca7ab64b705ee7c80bf3f9ac609240677db11e83d9317191f483a4b5a433 \
89
+ --hash=sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6 \
90
+ --hash=sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3 \
91
+ --hash=sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e \
92
+ --hash=sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67 \
93
+ --hash=sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a \
94
+ --hash=sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56 \
95
+ --hash=sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa \
96
+ --hash=sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019 \
97
+ --hash=sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e \
98
+ --hash=sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794 \
99
+ --hash=sha256:52460c6dd874b22d49fda228fac59da74d7a7b06175ffcc80bfa3ba5389d7f73 \
100
+ --hash=sha256:5246a0feaaac497b09c9462aa926280ae02fc8791b0099c0a925ebd7c7f249a6 \
101
+ --hash=sha256:54c23934cf166bb2090d73d82b1388aadb1cead5e73885223dcfa4a459a22d43 \
102
+ --hash=sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25 \
103
+ --hash=sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399 \
104
+ --hash=sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1 \
105
+ --hash=sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e \
106
+ --hash=sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee \
107
+ --hash=sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865 \
108
+ --hash=sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6 \
109
+ --hash=sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768 \
110
+ --hash=sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39 \
111
+ --hash=sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028 \
112
+ --hash=sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed \
113
+ --hash=sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851 \
114
+ --hash=sha256:78be5a1b05a5d1fd46d0290393e5deeb581fa617585462c1b84f7c6b0cb1e489 \
115
+ --hash=sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70 \
116
+ --hash=sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70 \
117
+ --hash=sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd \
118
+ --hash=sha256:88a089e6424a8a256321270620d5a4328ad5227fb2061b07d33f596894336914 \
119
+ --hash=sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca \
120
+ --hash=sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7 \
121
+ --hash=sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0 \
122
+ --hash=sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03 \
123
+ --hash=sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace \
124
+ --hash=sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3 \
125
+ --hash=sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a \
126
+ --hash=sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33 \
127
+ --hash=sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175 \
128
+ --hash=sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520 \
129
+ --hash=sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b \
130
+ --hash=sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92 \
131
+ --hash=sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843 \
132
+ --hash=sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd \
133
+ --hash=sha256:c24097c0462f66358c99dc83d3e1850e005f6293cfa1df1edb243428da1668bf \
134
+ --hash=sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963 \
135
+ --hash=sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7 \
136
+ --hash=sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb \
137
+ --hash=sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886 \
138
+ --hash=sha256:d58fe9fa2056fed24f055b74d5dc808fa1f5d084c22e4118f0a08253fe677ffd \
139
+ --hash=sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a \
140
+ --hash=sha256:e39017e1cef43d03b2ba427f60213e4b36dbc6fb092235fa3de3a510ce064d3c \
141
+ --hash=sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b \
142
+ --hash=sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b \
143
+ --hash=sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45 \
144
+ --hash=sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f \
145
+ --hash=sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db \
146
+ --hash=sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7
147
+ # via huggingface-hub
148
+ tqdm==4.70.1 \
149
+ --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \
150
+ --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4
151
+ # via huggingface-hub
152
+ typing-extensions==4.16.0 \
153
+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
154
+ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
155
+ # via
156
+ # anyio
157
+ # huggingface-hub
world/server.py CHANGED
@@ -194,6 +194,7 @@ class Server(ThreadingHTTPServer):
194
 
195
  class Handler(BaseHTTPRequestHandler):
196
  protocol_version = "HTTP/1.1" # keep-alive: every answer has a Content-Length
 
197
 
198
  def log_message(self, format, *args): # no access log
199
  pass
@@ -203,6 +204,8 @@ class Handler(BaseHTTPRequestHandler):
203
  self.send_response(status)
204
  self.send_header("Content-Type", "application/json")
205
  self.send_header("Content-Length", str(len(data)))
 
 
206
  if retry_after_s is not None and status in (429, 503):
207
  self.send_header("Retry-After", str(max(1, math.ceil(retry_after_s))))
208
  self.end_headers()
@@ -219,6 +222,7 @@ class Handler(BaseHTTPRequestHandler):
219
  raise Refused(413, "too_large", f"the request body must be at most {limit} bytes "
220
  "(with Content-Length)")
221
  data = self.rfile.read(n)
 
222
  try:
223
  return json.loads(data) if data.strip() else {}
224
  except ValueError:
@@ -236,6 +240,7 @@ class Handler(BaseHTTPRequestHandler):
236
  def route(self, method: str) -> None:
237
  app, path = self.server.app, self.path.split("?", 1)[0]
238
  upstream = path.startswith("/v1/tools/")
 
239
  try:
240
  if method == "GET" and path == "/healthz":
241
  return self.send(200, {"status": "parked" if app.world is None else "ready"})
@@ -246,7 +251,7 @@ class Handler(BaseHTTPRequestHandler):
246
  app.agent(self.headers)
247
  return self.send(200, app.manifest)
248
  if method == "POST" and (upstream or path.startswith("/world/tools/")):
249
- agent = Agent(app.agent(self.headers), self.headers.get("X-Request-Id") or "")
250
  body = self.body(MAX_BODY)
251
  if upstream:
252
  args = body
@@ -266,6 +271,8 @@ class Handler(BaseHTTPRequestHandler):
266
  return self.send(status, {"error": error}, e.retry_after_s)
267
  return self.send(200, {"ok": False, "error": error})
268
  except Refused as e:
 
 
269
  error = {"code": e.code, "message": e.message}
270
  if e.retry_after_s is not None:
271
  error["retry_after_s"] = e.retry_after_s
 
194
 
195
  class Handler(BaseHTTPRequestHandler):
196
  protocol_version = "HTTP/1.1" # keep-alive: every answer has a Content-Length
197
+ timeout = 60 # per socket read: an idle or stalled connection is dropped
198
 
199
  def log_message(self, format, *args): # no access log
200
  pass
 
204
  self.send_response(status)
205
  self.send_header("Content-Type", "application/json")
206
  self.send_header("Content-Length", str(len(data)))
207
+ if self.close_connection: # so the client opens a new connection for its next request
208
+ self.send_header("Connection", "close")
209
  if retry_after_s is not None and status in (429, 503):
210
  self.send_header("Retry-After", str(max(1, math.ceil(retry_after_s))))
211
  self.end_headers()
 
222
  raise Refused(413, "too_large", f"the request body must be at most {limit} bytes "
223
  "(with Content-Length)")
224
  data = self.rfile.read(n)
225
+ self.body_read = True
226
  try:
227
  return json.loads(data) if data.strip() else {}
228
  except ValueError:
 
240
  def route(self, method: str) -> None:
241
  app, path = self.server.app, self.path.split("?", 1)[0]
242
  upstream = path.startswith("/v1/tools/")
243
+ self.body_read = False
244
  try:
245
  if method == "GET" and path == "/healthz":
246
  return self.send(200, {"status": "parked" if app.world is None else "ready"})
 
251
  app.agent(self.headers)
252
  return self.send(200, app.manifest)
253
  if method == "POST" and (upstream or path.startswith("/world/tools/")):
254
+ agent = Agent(app.agent(self.headers))
255
  body = self.body(MAX_BODY)
256
  if upstream:
257
  args = body
 
271
  return self.send(status, {"error": error}, e.retry_after_s)
272
  return self.send(200, {"ok": False, "error": error})
273
  except Refused as e:
274
+ if not self.body_read: # a body left unread would be taken as the next request
275
+ self.close_connection = True
276
  error = {"code": e.code, "message": e.message}
277
  if e.retry_after_s is not None:
278
  error["retry_after_s"] = e.retry_after_s
world/tests/test_pybot.py CHANGED
@@ -6,6 +6,7 @@ import json
6
  import os
7
  import re
8
  import shutil
 
9
  import subprocess
10
  import sys
11
  import threading
@@ -274,6 +275,15 @@ def test_http_routes_credentials_and_workspace(setup, monkeypatch):
274
  assert c.get("/metrics", headers={"X-World-Token": "a" * 40}).json()["world"]["open_prs"] == 1
275
  r = c.patch("/admin/knobs", json={"pr.open_floor": 3}, headers={"X-World-Token": "a" * 40})
276
  assert r.json()["ok"] and world.budget_floor == 3
 
 
 
 
 
 
 
 
 
277
  finally:
278
  httpd.shutdown()
279
  httpd.server_close()
@@ -622,7 +632,7 @@ def test_admin_lanes_and_knobs(setup):
622
  world, clone, _ = setup
623
  rec = submit(world, clone)
624
  approve(world, rec)
625
- assert world.knobs == {"save.interval_s": world.save_interval, "save.legacy_json": True,
626
  "review.max_reviewers": 0, "pr.open_floor": 20, "hub.push.slots": 1, "hub.merge.slots": 1, "hub.comment.slots": 1,
627
  "hub.comment.gap_s": 0.0}
628
  world.admin.set({"hub.push.slots": 2, "hub.comment.gap_s": 0.5})
@@ -787,9 +797,7 @@ def test_main_moving_while_the_hub_pr_is_created_keeps_one_pr(setup, monkeypatch
787
  assert git(remote, "rev-parse", f"refs/pr/{rec['pr']}") == rec["head_sha"]
788
 
789
 
790
- def test_refusals_are_logged_and_request_keys_are_bounded(setup, monkeypatch):
791
- import pybot
792
-
793
  world, clone, _ = setup
794
  rec = submit(world, clone)
795
  with pytest.raises(ToolError, match="self-review"):
@@ -803,14 +811,8 @@ def test_refusals_are_logged_and_request_keys_are_bounded(setup, monkeypatch):
803
  ("merge_pr_refused", "birch", rec["pr"], "tool_error")]
804
  from api import tool_schema
805
 
806
- schema = tool_schema(world.tools()["merge_pr"])
807
  assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema
808
- monkeypatch.setattr(pybot, "MAX_REQUESTS", 2)
809
- for i in range(3):
810
- call_workspace(world, "open_pr", {"branch": "greeting", "title": "Bounded keys",
811
- "description": "x", "pr": rec["pr"]},
812
- Agent("cedar", request_id=f"req-{i}"), capture(clone))
813
- assert list(world.state["requests"]) == ["req-1", "req-2"]
814
 
815
 
816
  def test_hub_failure_logs_status_and_headers_but_no_secrets(monkeypatch, caplog):
@@ -1820,20 +1822,15 @@ def test_inbox_is_capped_deduped_and_survives_a_restart(setup):
1820
  assert len(old.call("list_prs", {}, Agent("cedar"))["inbox"]) == 2
1821
 
1822
 
1823
- def test_inbox_age_and_idempotent_retry_keep_the_cached_result(setup):
1824
  world, clone, _ = setup
1825
  assert [PybotWorld._age(s) for s in (5, 180, 7200, 200000)] == [
1826
  "just now", "3 min ago", "2 h ago", "2 d ago"]
1827
- first = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
1828
- "description": "Tested."}, Agent("cedar", request_id="k1"),
1829
- capture(clone))
1830
- with world.lock:
1831
- world._notify("cedar", 99, "merged", "news")
1832
- retry = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
1833
- "description": "Tested."}, Agent("cedar", request_id="k1"),
1834
- capture(clone))
1835
- assert retry["inbox"] == ["news (just now)"] and retry["pr"] == first["pr"]
1836
- assert "inbox" not in world.state["requests"]["k1"]
1837
 
1838
 
1839
  def _wait(cond, timeout=10):
@@ -2447,59 +2444,6 @@ def test_saves_are_never_torn_under_concurrent_changes(setup):
2447
  assert world.db.read_text() == json.dumps(world.state)
2448
 
2449
 
2450
- def _open(world, clone, key, description="Tested a conversation.", pr=None, author="cedar"):
2451
- result = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
2452
- "description": description, "pr": pr},
2453
- Agent(author, request_id=key), capture(clone))
2454
- return {k: v for k, v in result.items() if k not in ("pr_budget", "inbox")}
2455
-
2456
-
2457
- def test_idempotent_replay_returns_the_same_result_from_a_slim_cache(setup):
2458
- world, clone, _ = setup
2459
- long = "Evidence:\n" + "transcript line\n" * 2000
2460
- first = _open(world, clone, "k1", long)
2461
- assert first["description"] == long
2462
- entry = world.state["requests"]["k1"]
2463
- assert entry["description"] is None and len(json.dumps(entry)) < 1500
2464
- assert _open(world, clone, "k1", long) == first
2465
- assert list(_open(world, clone, "k1", long)) == list(first) # same keys, same order
2466
- # The PR is updated with another description; a late retry of k1 still gets its own.
2467
- (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hi!"\n')
2468
- second = _open(world, clone, "k2", "Second version.", pr=first["pr"])
2469
- assert second["description"] == "Second version."
2470
- assert _open(world, clone, "k1", long) == first
2471
- restarted = PybotWorld(world.ws, world.repo) # replays from prs.json
2472
- assert _open(restarted, clone, "k1", long) == first
2473
- assert _open(restarted, clone, "k2", "Second version.", pr=first["pr"]) == second
2474
-
2475
-
2476
- def test_old_request_cache_is_slimmed_on_load_and_expires(setup, monkeypatch):
2477
- import pybot
2478
-
2479
- world, clone, _ = setup
2480
- first = _open(world, clone, "k1", "Original long description " * 200)
2481
- world.close()
2482
- state = _on_disk(world)
2483
- # A cached result stored in full, with no timestamp.
2484
- state["requests"]["k1"] = dict(first)
2485
- state["requests"]["old"] = {**first, "description": "y" * 10000}
2486
- _write_archive(world, state)
2487
- restarted = PybotWorld(world.ws, world.repo)
2488
- restarted.close()
2489
- on_disk = _on_disk(restarted)["requests"]
2490
- assert all(e["description"] is None and "_ts" in e for e in on_disk.values())
2491
- assert len(json.dumps(on_disk)) < 2000
2492
- again = PybotWorld(world.ws, world.repo)
2493
- assert _open(again, clone, "k1", "Original long description " * 200) == first
2494
- # The rebuilt description falls back to the PR record when the retry's differs.
2495
- assert _open(again, clone, "k1", "a different text")["description"] == first["description"]
2496
- monkeypatch.setattr(pybot, "REQUEST_TTL", 60)
2497
- with again.lock:
2498
- again.state["requests"]["k1"]["_ts"] -= 120
2499
- again._cache_request("new", {"pr": 9, "description": "z"})
2500
- assert list(again.state["requests"]) == ["old", "new"]
2501
-
2502
-
2503
  def test_merge_has_its_own_hub_slot(setup):
2504
  world, clone, remote = setup
2505
  rec = submit(world, clone)
@@ -3027,6 +2971,12 @@ def test_a_missing_base_is_fetched_from_the_hub_or_refused(setup, monkeypatch):
3027
  git(clone, "fetch", "-q")
3028
  (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n')
3029
  assert not world.repo.has_commit(capture(clone)["base_sha"])
 
 
 
 
 
 
3030
  out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
3031
  Agent("cedar"), capture(clone))
3032
  assert out["replies"] == ["Hey!"] and out["sha"] == git(remote, "rev-parse", "main")
@@ -3098,6 +3048,22 @@ def test_new_modules_scope_rations_only_prs_that_add_a_module(setup, monkeypatch
3098
  with pytest.raises(ToolError, match="open a new PR to add one") as exc:
3099
  submit(world, clone, "birch", "greeting-fix", pr=fix["pr"])
3100
  assert exc.value.code == "open_budget"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3101
  with pytest.raises(ValueError, match="all or new_modules"):
3102
  monkeypatch.setenv("PYBOT_PR_OPEN_BUDGET_SCOPE", "some")
3103
  PybotWorld(world.ws, world.repo)
 
6
  import os
7
  import re
8
  import shutil
9
+ import socket
10
  import subprocess
11
  import sys
12
  import threading
 
275
  assert c.get("/metrics", headers={"X-World-Token": "a" * 40}).json()["world"]["open_prs"] == 1
276
  r = c.patch("/admin/knobs", json={"pr.open_floor": 3}, headers={"X-World-Token": "a" * 40})
277
  assert r.json()["ok"] and world.budget_floor == 3
278
+ # a refusal before the body is read closes the connection: its body is no next request
279
+ with socket.create_connection(("127.0.0.1", httpd.server_port), timeout=10) as s:
280
+ junk = b"GET /healthz HTTP/1.1\r\nHost: x\r\n\r\n"
281
+ s.sendall(b"POST /world/tools/list_prs HTTP/1.1\r\nHost: x\r\n"
282
+ b"Content-Length: %d\r\n\r\n%s" % (len(junk), junk))
283
+ data = b""
284
+ while chunk := s.recv(65536):
285
+ data += chunk
286
+ assert data.startswith(b"HTTP/1.1 401") and data.count(b"HTTP/1.1 ") == 1, data
287
  finally:
288
  httpd.shutdown()
289
  httpd.server_close()
 
632
  world, clone, _ = setup
633
  rec = submit(world, clone)
634
  approve(world, rec)
635
+ assert world.admin.values == {"save.interval_s": world.save_interval, "save.legacy_json": True,
636
  "review.max_reviewers": 0, "pr.open_floor": 20, "hub.push.slots": 1, "hub.merge.slots": 1, "hub.comment.slots": 1,
637
  "hub.comment.gap_s": 0.0}
638
  world.admin.set({"hub.push.slots": 2, "hub.comment.gap_s": 0.5})
 
797
  assert git(remote, "rev-parse", f"refs/pr/{rec['pr']}") == rec["head_sha"]
798
 
799
 
800
+ def test_refusals_are_logged(setup):
 
 
801
  world, clone, _ = setup
802
  rec = submit(world, clone)
803
  with pytest.raises(ToolError, match="self-review"):
 
811
  ("merge_pr_refused", "birch", rec["pr"], "tool_error")]
812
  from api import tool_schema
813
 
814
+ schema = tool_schema(world.tool_functions()["merge_pr"])
815
  assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema
 
 
 
 
 
 
816
 
817
 
818
  def test_hub_failure_logs_status_and_headers_but_no_secrets(monkeypatch, caplog):
 
1822
  assert len(old.call("list_prs", {}, Agent("cedar"))["inbox"]) == 2
1823
 
1824
 
1825
+ def test_inbox_age_and_a_retried_open_pr_opens_no_second_pr(setup):
1826
  world, clone, _ = setup
1827
  assert [PybotWorld._age(s) for s in (5, 180, 7200, 200000)] == [
1828
  "just now", "3 min ago", "2 h ago", "2 d ago"]
1829
+ args = {"branch": "greeting", "title": "Improve greetings", "description": "Tested."}
1830
+ first = call_workspace(world, "open_pr", args, Agent("cedar"), capture(clone))
1831
+ with pytest.raises(ToolError, match="branch slug already used"):
1832
+ call_workspace(world, "open_pr", args, Agent("cedar"), capture(clone))
1833
+ assert world.repo.hub.n == first["pr"] and len(world.state["prs"]) == 1
 
 
 
 
 
1834
 
1835
 
1836
  def _wait(cond, timeout=10):
 
2444
  assert world.db.read_text() == json.dumps(world.state)
2445
 
2446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2447
  def test_merge_has_its_own_hub_slot(setup):
2448
  world, clone, remote = setup
2449
  rec = submit(world, clone)
 
2971
  git(clone, "fetch", "-q")
2972
  (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n')
2973
  assert not world.repo.has_commit(capture(clone)["base_sha"])
2974
+ world.repo.fetched = time.monotonic()
2975
+ with pytest.raises(ToolError) as e: # the last fetch is under 5 s old: no new one yet
2976
+ call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
2977
+ Agent("cedar"), capture(clone))
2978
+ assert e.value.code == "unknown_base"
2979
+ world.repo.fetched -= 5
2980
  out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
2981
  Agent("cedar"), capture(clone))
2982
  assert out["replies"] == ["Hey!"] and out["sha"] == git(remote, "rev-parse", "main")
 
3048
  with pytest.raises(ToolError, match="open a new PR to add one") as exc:
3049
  submit(world, clone, "birch", "greeting-fix", pr=fix["pr"])
3050
  assert exc.value.code == "open_budget"
3051
+ # A plain unified diff (no diff --git header) hides the new module from the patch reader:
3052
+ # refused as a workspace, and a module found in the applied tree is never exempt.
3053
+ (clone / "bot/modules/news.py").unlink()
3054
+ plain = (b"--- /dev/null\n+++ b/bot/modules/news.py\n@@ -0,0 +1,2 @@\n"
3055
+ b"+def respond(text, memory):\n+ return None\n")
3056
+ sneaky = {**capture(clone), "patch": base64.b64encode(plain).decode()}
3057
+ assert not world._adds_module(sneaky)
3058
+ with pytest.raises(ToolError, match="diff --git") as exc:
3059
+ call_workspace(world, "open_pr", {"branch": "news", "title": "News", "description": "x"},
3060
+ Agent("oak"), sneaky)
3061
+ assert exc.value.code == "bad_workspace"
3062
+ _module(clone, "news", None)
3063
+ monkeypatch.setattr(world, "_adds_module", lambda workspace: False)
3064
+ with pytest.raises(ToolError, match="adds a module") as exc:
3065
+ submit(world, clone, "oak", "news")
3066
+ assert exc.value.code == "open_budget" and len(world.state["pr_opens"]) == 1
3067
  with pytest.raises(ValueError, match="all or new_modules"):
3068
  monkeypatch.setenv("PYBOT_PR_OPEN_BUDGET_SCOPE", "some")
3069
  PybotWorld(world.ws, world.repo)
world/workspace.py CHANGED
@@ -40,6 +40,8 @@ def apply_patch(workspace: dict, tree: Path) -> list[str]:
40
  patch = base64.b64decode(workspace.get("patch") or "", validate=True)
41
  except (ValueError, TypeError) as exc:
42
  raise ValueError("invalid workspace patch") from exc
 
 
43
  if git(tree, "rev-parse", "HEAD") != workspace.get("base_sha"):
44
  raise ValueError("the tree is not a checkout of the patch's base")
45
  if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)):
@@ -47,7 +49,7 @@ def apply_patch(workspace: dict, tree: Path) -> list[str]:
47
  # shortcut: a binary delta can expand past its declared size, up to the file-size and
48
  # memory limits below, with at most APPLY_SLOTS applies at once; decode delta headers if
49
  # that bound is too loose.
50
- if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES
51
  or sum(int(n) for n in _SIZES.findall(patch)) > MAX_BYTES):
52
  raise ValueError("workspace snapshot exceeds 128 MiB or 10,000 files")
53
  if patch: # prlimit, not preexec_fn: the world's server is threaded
 
40
  patch = base64.b64decode(workspace.get("patch") or "", validate=True)
41
  except (ValueError, TypeError) as exc:
42
  raise ValueError("invalid workspace patch") from exc
43
+ if patch and not patch.startswith(b"diff --git "): # what the file count and checks parse
44
+ raise ValueError("the patch must be `git diff` output (starting with diff --git)")
45
  if git(tree, "rev-parse", "HEAD") != workspace.get("base_sha"):
46
  raise ValueError("the tree is not a checkout of the patch's base")
47
  if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)):
 
49
  # shortcut: a binary delta can expand past its declared size, up to the file-size and
50
  # memory limits below, with at most APPLY_SLOTS applies at once; decode delta headers if
51
  # that bound is too loose.
52
+ if (patch.count(b"\ndiff --git ") + bool(patch) > MAX_FILES
53
  or sum(int(n) for n in _SIZES.findall(patch)) > MAX_BYTES):
54
  raise ValueError("workspace snapshot exceeds 128 MiB or 10,000 files")
55
  if patch: # prlimit, not preexec_fn: the world's server is threaded