Skip to content

Commit e2b5601

Browse files
tildesrcclaude
andauthored
Clone a task's submodules from the repo's own checkout (#418)
Spawn-prep filled a per-task clone's submodules by fetching each one from its forge-resolved URL — paid by every task on the repo, and for a large submodule it dominates spawn-prep, while the superproject itself is nearly free (`clone --local` hardlinks the cache's objects). When the repo's `git_url` names a checkout on this host, that checkout already holds every submodule's objects, so clone them from it instead: a local clone with a hardlinked object store and no network. The donor is matched by path, never by URL (the donor and the per-task clone resolve relative `.gitmodules` URLs against different origins), so hydration walks the tree a level at a time — init, override the resolved URL with the donor's checkout, update this level, recurse — and finishes with one `submodule sync --recursive` that puts the canonical URLs back in the config and in each submodule's own origin. It is only an optimisation: no local checkout, a raise, or a submodule still uninitialized afterwards all fall back to the plain recursive update, which is exactly what a repo without a donor gets. Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 2edf8b7 commit e2b5601

8 files changed

Lines changed: 650 additions & 92 deletions

File tree

‎AGENTS.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,10 @@ src/panopticon/
4848
# agent pane's own oom_score_adj, `nice` for shell tasks, and the cgroup-flag
4949
# strip the runner degrades through on a daemon that refuses them); clones.py =
5050
# per-repo clone cache; spawn.py = spawn-prep (clone --local the per-task
51-
# checkout, mounted rw at /workspace; point origin at the forge, then init any
51+
# checkout, mounted rw at /workspace; point origin at the forge, then fill in any
5252
# submodules — in that order, since relative .gitmodules URLs resolve against
53-
# origin); spawner.py = the spawn loop (claim an unclaimed task → spawn its
53+
# origin — hardlink-cloning them out of the repo's own checkout on this host when
54+
# git_url names one, ADR 0011 §1c); spawner.py = the spawn loop (claim an unclaimed task → spawn its
5455
# container; prefills claude's input box with the task memo on a first spawn;
5556
# `pause` stops a snoozed task's container + releases its claim, and the same
5657
# snooze gate keeps spawn/reconcile/heal off it until the deadline lapses);
@@ -253,9 +254,14 @@ on every PR (the same commands the Makefile wraps).
253254
- `tests/test_spawn.py` — spawn-prep (ADR 0011): unit tests pin the `clone --local` of the
254255
per-task checkout and the idempotency gate (skips when the checkout already exists), plus the
255256
**submodule** init — emitted after the `origin` repoint, gated on `submodule status` reporting an
256-
uninitialized (`-`) submodule so it retries but never touches an initialized one; a `skipif`
257-
integration test fills in a real submodule and then **moves** the checkout, pinning that the
258-
recorded links stay relative (the ADR 0011 mounts-anywhere property).
257+
uninitialized (`-`) submodule so it retries but never touches an initialized one — and the
258+
**donor hydration** (ADR 0011 §1c): the per-level init/url-override/update/sync when the repo has
259+
a checkout on this host, and every fallback to the plain fetch (no donor, donor gone, hydration
260+
raised, a submodule still uninitialized). A `skipif` integration test fills in a real submodule
261+
and then **moves** the checkout, pinning that the recorded links stay relative (the ADR 0011
262+
mounts-anywhere property); another hydrates a nested submodule from a source repo whose
263+
submodules' own repos have been moved away, pinning that the objects are hardlinked from it and
264+
that `sync` leaves no donor path behind.
259265
- `tests/container/test_cli_base.py` — the agent-CLI seam, including the **resume fallback** (ADR
260266
0014 §4b): with the process runner and clock injected (no CLI is ever started), a resumed launch
261267
that exits non-zero fast quarantines the session and relaunches — recovering an older healthy

‎docs/design/BACKLOG.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,13 +81,13 @@ in the ADRs; this file is for the smaller stuff that doesn't have a home there y
8181
`docker buildx bake` (target inheritance, which maps cleanly onto base→workflow→repo). Not
8282
needed now; the fragment approach is the minimal thing that works. _(Slice 6, P3)_
8383

84-
- [ ] **Share submodule objects with the cache clone** — spawn-prep initializes a task's
85-
submodules from their forge-resolved URLs (ADR 0011 §1b), so every task pays a full submodule
86-
fetch. Sharing the repo cache's object store would avoid it, but the obvious lever
87-
(`submodule.alternateLocation=superproject`) derives the alternate from the superproject's
88-
`origin`, which spawn deliberately repoints at the forge before initializing — so it needs the
89-
per-submodule alternate paths (`<cache>/.git/modules/<name>`) passed explicitly, and the cache
90-
clone made submodule-aware. Only worth it for repos with large submodules. _(P3)_
84+
- [ ] **Share submodule objects for forge-hosted repos** — a task whose repo has a checkout on
85+
this host now hardlink-clones its submodules out of it (ADR 0011 §1c), but a repo whose `git_url`
86+
is a hosted forge has no local donor and still pays a full submodule fetch per task. Making the
87+
repo's **cache** clone submodule-aware would give those repos a donor too. The obvious lever
88+
(`submodule.alternateLocation=superproject`) isn't it: the alternate is derived from the
89+
superproject's `origin`, which spawn deliberately repoints at the forge — so it would be the same
90+
path-keyed hydration, pointed at the cache. Only worth it for repos with large submodules. _(P3)_
9191

9292
## Tracked elsewhere (pointers, do not duplicate)
9393

‎docs/design/decisions/0011-provisioning-per-task-clone.md‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,41 @@ The "mounts at any container path" property survives, because `submodule update`
6666
submodule's gitdir pointer (`gitdir: ../../.git/modules/<name>`) and its `core.worktree`
6767
**relatively** — nothing absolute to mirror, same as the superproject.
6868

69-
The repo's **cache** clone stays submodule-free: the per-task clone fetches submodules from their
70-
forge-resolved URLs, so cache-side submodule checkouts would be disk and time for nothing. The cost
71-
is one submodule fetch per task; sharing the cache's object store instead
72-
(`submodule.alternateLocation=superproject`) computes the alternate from the superproject's *origin*,
73-
which is exactly what we repoint at the forge — so it needs more than a flag. Backlogged.
69+
### 1c. Submodules come from the repo's own checkout when there is one
70+
71+
Fetching each submodule from its URL is paid by **every** task on the repo, and for a large
72+
submodule it dominates spawn-prep — while the superproject itself is nearly free (`clone --local`
73+
hardlinks the cache's objects). When the repo's `git_url` names a checkout on this host (the
74+
local-git flow), that checkout already holds every submodule's objects, so spawn-prep clones them
75+
**from it** — a local clone, hardlinked object store, no network (`hydrate_submodules`).
76+
77+
The donor is matched **by path**, never by URL: the donor resolved its relative `.gitmodules` URLs
78+
against *its own* `origin` while the per-task clone resolves them against `git_url`, so the same
79+
submodule can legitimately have two different URLs. Per superproject level:
80+
81+
1. `submodule init` — git resolves the declared URLs into `submodule.<name>.url`;
82+
2. for each submodule the donor has checked out, that resolved URL is overwritten with the donor's
83+
path (one the donor lacks keeps its own URL and is simply fetched);
84+
3. `submodule update` for **this level only** — a nested submodule's URL cannot be resolved, let
85+
alone redirected, before its parent exists;
86+
4. recurse into each submodule against the matching donor level.
87+
88+
Then, once at the top, `submodule sync --recursive` restores the canonical URLs — in the config
89+
*and* in each submodule's own `origin` — so no host path from the donor reaches the container, and
90+
the agent fetches and pushes where it should.
91+
92+
It is **only** an optimisation, never a precondition: if there's no local checkout, if hydration
93+
raises, or if it leaves any submodule uninitialized (a donor behind the recorded commit), spawn-prep
94+
falls back to the plain `submodule update --init --recursive` above. Hardlinks make the task's
95+
objects independent of a later `git gc` in the donor — the same property `clone --local` already
96+
relies on for the superproject — and a cross-filesystem donor degrades to a copy, still local.
97+
98+
The repo's **cache** clone stays submodule-free: it is not the donor, and cache-side submodule
99+
checkouts would be disk and time for nothing. A repo whose `git_url` is a hosted forge has no local
100+
donor and still pays one submodule fetch per task; making the cache clone submodule-aware would
101+
close that too (backlogged) — `submodule.alternateLocation=superproject` isn't the lever, since it
102+
computes the alternate from the superproject's *origin*, which is exactly what we repoint at the
103+
forge.
74104

75105
### 2. Provisioning = branch whatever's there
76106

‎src/panopticon/core/git.py‎

Lines changed: 128 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,48 @@
1818
import subprocess
1919
from collections.abc import Sequence
2020
from dataclasses import dataclass
21+
from pathlib import Path
2122
from typing import Protocol
2223

2324
#: Feature-branch namespace (PARITY §8/§14, renamed from cloude-cade's ``cloude/``).
2425
BRANCH_PREFIX = "panopticon"
2526

27+
#: URL schemes that mean a networked (hosted-forge) remote rather than a local path.
28+
_FORGE_SCHEMES = ("https://", "http://", "ssh://", "git://", "ftp://", "ftps://")
29+
30+
31+
def is_forge_url(git_url: str) -> bool:
32+
"""True when ``git_url`` names a hosted-forge remote (network push/PR/CI), not a local path.
33+
34+
Recognizes URL-scheme remotes (``https://…``, ``ssh://…``, …) and scp-like ``user@host:path``
35+
remotes; treats a bare filesystem path or a ``file://`` URL as local-only.
36+
"""
37+
url = git_url.strip()
38+
if url.lower().startswith("file://"):
39+
return False
40+
if url.lower().startswith(_FORGE_SCHEMES):
41+
return True
42+
# scp-like syntax: user@host:path — an '@' and a ':' before any '/'. A Windows drive path
43+
# (``C:\…``) has the ':' but no '@', so it stays local.
44+
at, colon, slash = url.find("@"), url.find(":"), url.find("/")
45+
return at != -1 and colon > at and (slash == -1 or colon < slash)
46+
47+
48+
def local_repo_path(git_url: str) -> str | None:
49+
"""The filesystem path ``git_url`` names, or ``None`` when it names a networked remote.
50+
51+
The counterpart of :func:`is_forge_url`: a bare path or a ``file://`` URL is somewhere on this
52+
host — which is what makes panopticon's host-side push, and cloning a task's submodules from
53+
the repo's own checkout (:func:`panopticon.sessionservice.spawn.hydrate_submodules`), possible
54+
at all.
55+
"""
56+
if is_forge_url(git_url):
57+
return None
58+
url = git_url.strip()
59+
if url.lower().startswith("file://"):
60+
url = url[len("file://") :]
61+
return str(Path(url).expanduser()) if url else None
62+
2663

2764
class GitError(RuntimeError):
2865
"""A ``git`` command that exited non-zero, carrying its ``stderr``.
@@ -87,6 +124,27 @@ def parse_submodule_status(output: str) -> dict[str, str]:
87124
return states
88125

89126

127+
def parse_submodule_paths(output: str) -> dict[str, str]:
128+
"""Parse ``git config --get-regexp`` output into ``{submodule name: path}``.
129+
130+
Each line is ``submodule.<name>.path <path>`` — read from ``.gitmodules`` rather than from
131+
``git submodule status`` because it answers *before* ``submodule init`` has run and for
132+
submodules that aren't checked out. The name is whatever sits between the ``submodule.``
133+
prefix and the ``.path`` suffix (it usually **is** the path, dots and slashes included), and
134+
the value is the rest of the line, so a path containing spaces survives. Lines that don't
135+
match the shape are skipped.
136+
"""
137+
paths: dict[str, str] = {}
138+
for line in output.splitlines():
139+
key, _, value = line.partition(" ")
140+
if not value or not key.startswith("submodule.") or not key.endswith(".path"):
141+
continue
142+
name = key[len("submodule.") : -len(".path")]
143+
if name:
144+
paths[name] = value
145+
return paths
146+
147+
90148
@dataclass(frozen=True)
91149
class Worktree:
92150
"""A created worktree: its branch and on-disk path."""
@@ -164,8 +222,59 @@ def submodule_status(self, *, repo_path: str) -> dict[str, str]:
164222
out = self._run(["git", "-C", repo_path, "submodule", "status", "--recursive"])
165223
return parse_submodule_status(out)
166224

167-
def update_submodules(self, *, repo_path: str) -> None:
168-
"""``git -C <repo> submodule update --init --recursive`` — fill in the submodule checkouts.
225+
def submodule_paths(self, *, repo_path: str) -> dict[str, str]:
226+
"""The submodules this repo *declares* — ``{name: path}``, empty when there are none.
227+
228+
Reads ``.gitmodules`` (``git config --file``), not ``git submodule status``: the caller
229+
overriding a submodule's URL (:meth:`set_submodule_url`) needs the **name** git keys that
230+
config on, and needs it for a submodule that isn't checked out yet. Only this level's
231+
submodules — a nested one is declared in its own superproject's ``.gitmodules``, so the
232+
caller recurses. ``check=False`` because ``git config`` exits non-zero when the file (or a
233+
match) is absent, which is just "no submodules".
234+
"""
235+
out = self._run(
236+
[
237+
"git",
238+
"-C",
239+
repo_path,
240+
"config",
241+
"--file",
242+
".gitmodules",
243+
"--get-regexp",
244+
"^submodule\\..*\\.path$",
245+
],
246+
check=False,
247+
)
248+
return parse_submodule_paths(out)
249+
250+
def init_submodules(self, *, repo_path: str) -> None:
251+
"""``git -C <repo> submodule init`` — resolve each declared URL into ``submodule.<n>.url``.
252+
253+
Separated from ``update`` so a caller can *override* the resolved URL in between (the
254+
donor hydration in ``sessionservice.spawn``); ``update --init`` would clone before the
255+
override could land.
256+
"""
257+
self._run(["git", "-C", repo_path, "submodule", "init"])
258+
259+
def set_submodule_url(self, *, repo_path: str, name: str, url: str) -> None:
260+
"""``git -C <repo> config submodule.<name>.url <url>`` — where ``update`` clones from.
261+
262+
The config value wins over ``.gitmodules`` until :meth:`sync_submodules` restores it.
263+
"""
264+
self._run(["git", "-C", repo_path, "config", f"submodule.{name}.url", url])
265+
266+
def sync_submodules(self, *, repo_path: str) -> None:
267+
"""``git -C <repo> submodule sync --recursive`` — restore the canonical submodule URLs.
268+
269+
Rewrites every ``submodule.<name>.url`` from ``.gitmodules`` (resolved against the
270+
superproject's ``origin``) **and** repoints each checked-out submodule's own
271+
``remote.origin.url`` at it — so a temporary local-donor override leaves nothing of the
272+
host's paths behind in the checkout the container gets.
273+
"""
274+
self._run(["git", "-C", repo_path, "submodule", "sync", "--recursive"])
275+
276+
def update_submodules(self, *, repo_path: str, recursive: bool = True) -> None:
277+
"""``git -C <repo> submodule update --init [--recursive]`` — fill in the submodule checkouts.
169278
170279
``protocol.file.allow=always`` is **required**, not cosmetic: since git 2.38 a submodule
171280
whose resolved URL is a local path is refused (``transport 'file' not allowed``,
@@ -178,20 +287,24 @@ def update_submodules(self, *, repo_path: str) -> None:
178287
Submodule URLs are resolved against the superproject's ``remote.origin.url`` *here*, so the
179288
caller must point ``origin`` at the forge first (:meth:`set_origin`) — resolving a relative
180289
URL against the cache path would look for the submodule next to the cache clone.
290+
291+
``recursive=False`` updates **this level only**: a nested submodule's URL can't be resolved
292+
(or overridden) before its parent exists, so the donor hydration walks the tree a level at
293+
a time instead.
181294
"""
182-
self._run(
183-
[
184-
"git",
185-
"-C",
186-
repo_path,
187-
"-c",
188-
"protocol.file.allow=always",
189-
"submodule",
190-
"update",
191-
"--init",
192-
"--recursive",
193-
]
194-
)
295+
args = [
296+
"git",
297+
"-C",
298+
repo_path,
299+
"-c",
300+
"protocol.file.allow=always",
301+
"submodule",
302+
"update",
303+
"--init",
304+
]
305+
if recursive:
306+
args.append("--recursive")
307+
self._run(args)
195308

196309
def push(self, *, repo_path: str, remote: str, branch: str) -> None:
197310
"""``git -C <repo> push <remote> <branch>`` — send one branch, as-is (never forced).

0 commit comments

Comments
 (0)