Python
Let leads own repository setup and preserve configured targets
Rohit C Prasad89bdad221f7f
diff --git a/coworker/connectors/integration_tools.py b/coworker/connectors/integration_tools.pyindex 4c92f8e9..3a8a346d 100644--- a/coworker/connectors/integration_tools.py+++ b/coworker/connectors/integration_tools.py@@ -815,7 +815,9 @@ def make_integration_tools(}return path, None- def github_clone(owner: str, repo: str, directory: str = "") -> dict[str, Any]:+ def github_clone(owner: str, repo: str, directory: str = "", ref: str = "") -> dict[str, Any]:+ if ref and (ref.startswith("-") or any(c.isspace() for c in ref) or ":" in ref):+ return {"error": "ref must be a single branch, tag, commit SHA, or refs/pull/N/head"}target, err = _writable_target(directory, default_name=repo)if err:return err@@ -837,7 +839,18 @@ def make_integration_tools(shutil.rmtree(target)return {"error": "clone aborted: credentials would have persisted"}- head, _ = _run_git(["rev-parse", "--short", "HEAD"], cwd=target)+ if ref:+ _out, git_err = _run_git(+ [*_github_git_auth_args(secrets, owner), "fetch", "origin", ref], cwd=target+ )+ if git_err:+ return {"error": f"clone exists at {target}, but ref fetch failed: {git_err}", "path": str(target)}+ _out, git_err = _run_git(["checkout", "--detach", "FETCH_HEAD"], cwd=target)+ if git_err:+ return {"error": f"clone exists at {target}, but checkout failed: {git_err}", "path": str(target)}+ head, git_err = _run_git(["rev-parse", "HEAD"], cwd=target)+ if git_err:+ return {"error": f"clone has no readable HEAD: {git_err}", "path": str(target)}return {"ok": True, "path": str(target), "head": head}github_clone.__name__ = "github_clone"@@ -852,6 +865,10 @@ def make_integration_tools({"owner": {"type": "string"},"repo": {"type": "string"},+ "ref": {+ "type": "string",+ "description": "Optional branch, tag, commit SHA or refs/pull/N/head. Fetches and checks out that revision detached; omitted uses the default branch. Returns full HEAD SHA.",+ },"directory": {"type": "string","description": "absolute target path inside a granted folder (default: <primary>/<repo>)",diff --git a/coworker/personas/builtin/swe-lead/manifest.md b/coworker/personas/builtin/swe-lead/manifest.mdindex aab7f5d0..12d65296 100644--- a/coworker/personas/builtin/swe-lead/manifest.md+++ b/coworker/personas/builtin/swe-lead/manifest.md@@ -20,6 +20,20 @@ board. Your job is coordination and judgment: decompose, staff, assign, verify.NOT implement — you carry no shell or git on purpose. The board is the shared groundtruth; your context window is disposable, the board is not.+Repository setup is your responsibility, not an automatic harness action. A GitHub+event may only need connector reads or a reply; do not clone unnecessarily. When+local code is needed, use github_clone with your GitHub connector in the shared+team scratch directory. Reuse an existing clone only after checking its identity+and revision. For PR review use refs/pull/N/head, not the default branch; record+the full returned SHA. Ask for the connector if it is unavailable.+Give workers the absolute clone path and agreed base SHA. They create their own+worktrees under their returned scratch_directory/worktrees/<repo>/<task>, with+distinct branches, using local Git (no GitHub credentials needed). Multiple repos+are allowed. Do not edit the customer's .gitignore or create a worktree for them.+The team shares filesystem access, not a checkout: no concurrent edits to another+worker's checkout. Require checkout path, branch, base SHA and submitted SHA in the+board hand-off so verification and integration inspect the correct revision.+How you run a piece of work:1. UNDERSTAND: read enough of the repo (files, search) to decompose honestly. Theboard is per-PROJECT and outlives sessions — before proposing anything, read itdiff --git a/coworker/personas/builtin/swe-worker/manifest.md b/coworker/personas/builtin/swe-worker/manifest.mdindex 1931aec9..3ad9e6fb 100644--- a/coworker/personas/builtin/swe-worker/manifest.md+++ b/coworker/personas/builtin/swe-worker/manifest.md@@ -20,6 +20,14 @@ You are a software engineer working ON A TEAM under a lead coworker. Your interlis the LEAD, not the end user — you never use ask_user; questions become item comments (or @lead via post_chat when # team chat is enabled),and you keep working on what isn't blocked by the answer.+When the lead supplies a shared clone and base SHA, create your own worktree under+your worker scratch directory at worktrees/<repo>/<task>, on a distinct branch.+Never switch or reset the shared clone or another worker's checkout. Local worktree+creation needs filesystem access to the clone, not GitHub credentials. Use absolute+paths for file tools and `git -C <worktree>` / explicit shell cwd for commands:+shell cd does NOT change the session's primary directory or built-in Git tools.+Report checkout path, branch, base SHA and submitted SHA on the board at hand-off.+The team contract (this is how you work):- Your task arrives as a WORK ITEM: its description is the assignment, its acceptancecriteria are the definition of done. If criteria are ambiguous, say so in a commentdiff --git a/coworker/personas/builtin/test-worker/manifest.md b/coworker/personas/builtin/test-worker/manifest.mdindex 5f47911c..ed37d188 100644--- a/coworker/personas/builtin/test-worker/manifest.md+++ b/coworker/personas/builtin/test-worker/manifest.md@@ -22,6 +22,12 @@ ITS ACCEPTANCE CRITERIA — assume it doesn't until the evidence says otherwise.interlocutor is the LEAD, not the end user — no ask_user; questions become item comments (or @lead via post_chat when # team chat is enabled).How you verify:+- Use the builder's reported checkout path and submitted SHA, not the lead's primary+ folder by assumption. For isolated verification, create a worktree from the shared+ clone at that SHA under your worker scratch directory, worktrees/<repo>/<task>.+ Do not mutate or reset the builder's checkout. Use absolute file paths and+ `git -C <worktree>` / explicit shell cwd; shell cd does not reanchor built-in tools.+ Include the tested SHA and checkout path in your evidence.- Start from the item under verification: its criteria are your checklist, one by one.Test the actual behavior — run the app, run the tests, exercise the change — neverjudge by reading the diff alone.diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex a9bbd6d0..3aff6448 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -247,7 +247,17 @@ def configured_opening(event, thread_target: str, folder: str) -> str:if body:lines.append(f"Description:\n{body}")if folder:- lines.append(f"Your session folder is a checkout of the code under review: {folder}")+ lines.append(+ f"Your session directory is {folder}. No repository or worktree was created. "+ "If local code is needed, use github_clone in this directory; otherwise work through the connector."+ )+ is_pr = bool(frame.get("is_pr")) or kind in ("pr_open", "pr_merge")+ if is_pr and number.isdigit():+ lines.append(+ f"PR source: refs/pull/{number}/head. For review, clone with this ref, not the default branch. "+ "Record the returned full commit SHA; this is the fetched revision, not necessarily the event-time revision. "+ "For post-merge work, inspect the PR's merge commit and target branch through GitHub first."+ )src = getattr(event, "source", None)if src is not None:lines.append(origin_block(src, frame={**frame, "kind": kind}))@@ -576,6 +586,11 @@ class SessionManager:def _provision_scratch(self, session_id: str) -> str:"""Create (idempotently) and return this conversation's scratch directory."""d = self.scratch_base() / session_id+ record = self.session_store.load(session_id)+ team = (record.team if record else {}) or {}+ lead = str(team.get("lead_session") or "")+ if team.get("role") == "worker" and self._SESSION_ID_RE.fullmatch(lead) and lead not in {".", "..", session_id}:+ d = self.scratch_base() / lead / "workers" / session_idd.mkdir(parents=True, exist_ok=True)return str(d.resolve())@@ -766,6 +781,17 @@ class SessionManager:else:# A session id we won't put in a filesystem path: primary root only.roots = [{"path": ws, "writable": True, "label": "workspace"}, *extra]+ team = (record.team if record else {}) or {}+ if team.get("role") == "worker":+ lead = self.session_store.load(str(team.get("lead_session") or ""))+ if lead is not None:+ # Shared team filesystem, with a worker-owned directory for worktrees.+ for path, label in (+ (self._provision_scratch(lead.session_id), "team scratch"),+ (self._provision_scratch(session_id), "worker scratch"),+ ):+ if not any(Path(r["path"]).resolve() == Path(path).resolve() for r in roots):+ roots.append({"path": path, "writable": True, "label": label})engine = build_engine(agent=ag,workspace=ws,@@ -2968,6 +2994,7 @@ class SessionManager:"session_id": w.session_id,"connectors": sorted(self.effective_connectors(w.session_id, w.persona)),"approvals": "follow the lead",+ "scratch_directory": self._provision_scratch(w.session_id),}for w in workers],@@ -6092,6 +6119,12 @@ class SessionManager:)returnself._report_orphan_subscription(channel)+ if cfg:+ self.unrouted.record(+ src.target, who, text,+ reason=f"target session {target} is missing — select an existing session; no replacement was started",+ )+ returnsubs = self.subscriptions.for_channel(channel)# §31 mention router: a direct @-mention of the bot outranks the passive fan-out —# subscribed sessions must answer it; an unsubscribed channel spawns (or steers)@@ -6361,56 +6394,8 @@ class SessionManager:logger.warning("reply-only frame for %s failed: %s", src.chat_id, getattr(res, "error", ""))except Exception:logger.exception("reply-only frame for %s failed", src.chat_id)-- def _prepare_checkout(self, owner_repo: str, base_dir: str, *, number: str, kind: str, head_ref: str = "", worktree: bool = True, is_pr: bool | None = None) -> str:- """The folder a configuration-started session works in (spec §10.4).- Clone once at <base>/<repo>/main; with `worktree`, add <base>/<repo>/pr-N- (or issue-N) on the PR head, else the default branch. Returns the path.- Raises ValueError with a readable reason."""- from ..connectors.integration_tools import _github_git_auth_args, _github_git_base, _run_git-- if "/" not in owner_repo:- raise ValueError(f"not a repository: {owner_repo!r}")- owner, repo = owner_repo.split("/", 1)- root = Path(base_dir).expanduser()- try:- root = ensure_under_base(root, "base directory")- except OutsideBaseDir as exc:- raise ValueError(str(exc)) from None- clone = root / repo / "main"- auth = _github_git_auth_args(self.secrets, owner)- if not (clone / ".git").exists():- clone.parent.mkdir(parents=True, exist_ok=True)- _out, err = _run_git([*auth, "clone", f"{_github_git_base()}/{owner}/{repo}.git", str(clone)])- if err:- raise ValueError(f"clone failed: {err}")- else:- _run_git([*auth, "-C", str(clone), "fetch", "--prune", "origin"])- if not worktree:- return str(clone)- # A PR thread (opened, merged, or a mention on one) checks the PR head out;- # an issue works on the default branch.- pr = bool(is_pr) if is_pr is not None else kind in ("pr_open", "pr_merge")- tag = f"pr-{number}" if pr and number else (f"issue-{number}" if number else "work")- path = root / repo / tag- if path.exists():- return str(path)- if pr and number and kind != "pr_merge":- # The PR head by number works whether or not the branch name is known.- _out, err = _run_git([*auth, "-C", str(clone), "fetch", "origin", f"pull/{number}/head:refs/remotes/origin/{tag}"])- if err:- raise ValueError(f"fetch of PR #{number} failed: {err}")- start = f"origin/{tag}"- else:- head, err = _run_git(["-C", str(clone), "rev-parse", "--abbrev-ref", "HEAD"])- start = f"origin/{head}" if head else "HEAD"- _out, err = _run_git(["-C", str(clone), "worktree", "add", "-B", tag, str(path), start])- if err:- raise ValueError(f"worktree failed: {err}")- return str(path)-def _remove_spawn_worktree(self, session_id: str, record=None) -> None:- """A configuration-started session's worktree goes with it; the clone stays."""+ """Legacy harness-owned checkouts only; agent-owned work is never removed here."""from ..connectors.integration_tools import _run_gitrecord = record if record is not None else self.session_store.load(session_id)@@ -6428,7 +6413,7 @@ class SessionManager:async def _spawn_configured_session(self, event, ms: MessageSource, cfg: dict) -> None:"""A configuration's "new session" target (spec §10.4): coworker, first- runnable model, a checkout when a base directory was set, the listed+ runnable model, a fresh directory (never an automatic checkout), the listedskills, the instructions — then the opening turn."""import uuid@@ -6444,28 +6429,20 @@ class SessionManager:number = str(frame.get("number") or "")kind = str(cfg.get("event") or frame.get("kind") or "")owner_repo = str(frame.get("owner_repo") or src.chat_id.split("#", 1)[0])+ sid = uuid.uuid4().hexworkspace = None- clone = worktree = ""base_dir = str(spawn.get("base_dir") or "")if base_dir:try:- path = await asyncio.to_thread(- self._prepare_checkout,- owner_repo,- base_dir,- number=number,- kind=kind,- head_ref=str(frame.get("head_ref") or ""),- worktree=bool(spawn.get("worktree", True)),- is_pr=frame.get("is_pr") if "is_pr" in frame else None,- )- except ValueError as exc:- self.unrouted.record(src.target, who, event.text, reason=f"checkout failed: {exc}")+ root = ensure_under_base(Path(base_dir).expanduser(), "base directory")+ path = root / sid+ path.mkdir(parents=True, exist_ok=False)+ except (ValueError, OSError) as exc:+ self.unrouted.record(src.target, who, event.text, reason=f"session directory failed: {exc}")return- workspace = path- clone = str(Path(path).parent / "main") if bool(spawn.get("worktree", True)) else path- worktree = path if bool(spawn.get("worktree", True)) else ""- sid = uuid.uuid4().hex+ workspace = str(path.resolve())+ else:+ workspace = self._provision_scratch(sid)engine = self.get_engine(sid, workspace=workspace, agent=persona)if engine is None:self.unrouted.record(src.target, who, event.text, reason="could not start the configured session (folder needed?)")@@ -6502,8 +6479,7 @@ class SessionManager:"event": kind,"name": str(cfg.get("name") or ""),"instructions": str(spawn.get("instructions") or ""),- "clone": clone,- "worktree": worktree,+ "workspace_setup": "agent","owner_repo": owner_repo,"number": number,"approval_mode": mode.value,diff --git a/surfaces/gui/e2e/connectors-across.spec.ts b/surfaces/gui/e2e/connectors-across.spec.tsindex 030b6b46..f933a125 100644--- a/surfaces/gui/e2e/connectors-across.spec.ts+++ b/surfaces/gui/e2e/connectors-across.spec.ts@@ -220,6 +220,8 @@ test("Settings ▸ GitHub: the default row, a configuration row, Add with a new// The coworker's own models list is offered; the Ollama one is marked not here.await expect(dlg.getByTestId("cfg-model-ollama:qwen3-coder:30b")).toContainText("not here");await dlg.getByTestId("cfg-base-dir").fill("~/work");+ await expect(dlg.getByTestId("cfg-worktree")).toHaveCount(0);+ await expect(dlg).toContainText("no checkout is created automatically");// Spec §11.5: Approval mode defaults to Auto-approve and approvals go to the Inbox;// both are the user's to change here.await expect(dlg.getByTestId("cfg-approval-mode")).toHaveValue("auto-approve");@@ -229,7 +231,7 @@ test("Settings ▸ GitHub: the default row, a configuration row, Add with a newawait dlg.getByTestId("cfg-save").click();await expect.poll(() => calls.find((c) => c.method === "POST")?.body).toMatchObject({repos: ["acme/site"], event: "pr_open", who: ["nia"],- target: { kind: "new", machine_id: "desktop", persona: "security", base_dir: "~/work", worktree: true, models: ["anthropic:claude-opus-4-8"], approval_mode: "interactive", unattended: false },+ target: { kind: "new", machine_id: "desktop", persona: "security", base_dir: "~/work", models: ["anthropic:claude-opus-4-8"], approval_mode: "interactive", unattended: false },});await expect(page.getByTestId("cfg-dialog")).toHaveCount(0);await expect(page.getByTestId("glance-cfg-cfg2")).toBeVisible();diff --git a/surfaces/gui/src/components/TeamView.navigation.test.tsx b/surfaces/gui/src/components/TeamView.navigation.test.tsxindex bbf047b5..e3e530c4 100644--- a/surfaces/gui/src/components/TeamView.navigation.test.tsx+++ b/surfaces/gui/src/components/TeamView.navigation.test.tsx@@ -68,7 +68,7 @@ it("shows and answers an unattributed worker request without inventing a task",fireEvent.click(screen.getByRole("button", { name: "sam · Run regression tests" }));expect(await screen.findByTestId("approval-escalation")).toBeTruthy();expect(calls.inbox).toHaveBeenCalledWith("worker", "pending");- fireEvent.click(screen.getByRole("button", { name: "Allow once", exact: true }));+ fireEvent.click(screen.getByRole("button", { name: "Allow once" }));await vi.waitFor(() => expect(calls.resolve).toHaveBeenCalledWith("ask", "allow"));view.rerender(<TeamView summary={{ ...summary, pending_requests: [] }} sessionId="lead" sessions={[]} onClose={vi.fn()} onRefresh={refresh} />);expect(screen.queryByTestId("inbox-item-ask")).toBeNull();diff --git a/surfaces/gui/src/components/connectors/ConfigurationsSection.tsx b/surfaces/gui/src/components/connectors/ConfigurationsSection.tsxindex c5553825..0983fe5f 100644--- a/surfaces/gui/src/components/connectors/ConfigurationsSection.tsx+++ b/surfaces/gui/src/components/connectors/ConfigurationsSection.tsx@@ -99,7 +99,7 @@ export function ConfigurationsSection({tg.persona || t("connconfig.default_coworker_lower"),...(tg.models?.[0] ? [shortModel(tg.models[0])] : []),where,- ...(tg.base_dir ? [t(tg.worktree === false ? "connconfig.target_in_dir" : "connconfig.target_worktree_under", { dir: tg.base_dir })] : []),+ ...(tg.base_dir ? [t("connconfig.target_session_under", { dir: tg.base_dir })] : []),tg.unattended === false ? mode : t("connconfig.target_mode_to_inbox", { mode }),].join(" · ");};@@ -235,7 +235,6 @@ function ConfigurationDialog({const [persona, setPersona] = useState(cfg?.target.persona ?? "");const [models, setModels] = useState<string[]>(cfg?.target.models ?? []);const [baseDir, setBaseDir] = useState(cfg?.target.base_dir ?? "");- const [worktree, setWorktree] = useState(cfg?.target.worktree ?? true);// Spec §11.5 (owner rulings): Approval mode defaults to Auto-approve; "Send approvals to// Inbox" (the Unattended dial) defaults on — nobody is at the keyboard for these sessions.const [approvalMode, setApprovalMode] = useState(cfg?.target.approval_mode ?? "auto-approve");@@ -303,7 +302,7 @@ function ConfigurationDialog({const target = (): ConfigurationTarget =>kind === "existing"? { kind: "existing", machine_id: machineId, session_id: sessionId, title: sessionTitle }- : { kind: "new", machine_id: machineId, persona, models, base_dir: baseDir.trim(), worktree, skills, instructions: instructions.trim(), board: board.trim(), memory: memory.trim(), approval_mode: approvalMode, unattended };+ : { kind: "new", machine_id: machineId, persona, models, base_dir: baseDir.trim(), skills, instructions: instructions.trim(), board: board.trim(), memory: memory.trim(), approval_mode: approvalMode, unattended };const save = async () => {setErr(null);@@ -478,15 +477,7 @@ function ConfigurationDialog({<Label>{t("connconfig.label_base_dir")}</Label><div><input className={INPUT + " w-full"} value={baseDir} onChange={(e) => setBaseDir(e.target.value)} placeholder={t("connconfig.base_dir_placeholder", { machine: machine?.name ?? t("connconfig.the_machine") })} data-testid="cfg-base-dir" />- <label className="flex items-start gap-2 mt-2 text-ui">- <input type="checkbox" checked={worktree} onChange={(e) => setWorktree(e.target.checked)} data-testid="cfg-worktree" className="mt-1" />- <span>- {t("connconfig.worktree_per_session")}- <span className="block text-meta text-faint">- {t("connconfig.worktree_hint", { dir: baseDir || "~/work" })}- </span>- </span>- </label>+ <div className="mt-2 text-meta text-faint">{t("connconfig.session_directory_hint")}</div></div><Label>{t("connconfig.label_approvals")}</Label>diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 990a5c3e..18d2bf76 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -1862,6 +1862,8 @@"default_coworker": "Default coworker","default_coworker_lower": "default coworker","target_in_dir": "in {{dir}}",+ "target_session_under": "session directory under {{dir}}",+ "session_directory_hint": "Each new session gets its own directory. Leave blank to use the scratch area. The coworker decides whether to clone the repository using its GitHub connector; no checkout is created automatically.","target_worktree_under": "worktree under {{dir}}","target_mode_to_inbox": "{{mode}} → Inbox","all_repos": "All repositories",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 62e9d0b1..7f195c18 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -1824,6 +1824,8 @@"default_coworker": "默认同事","default_coworker_lower": "默认同事","target_in_dir": "位于 {{dir}}",+ "target_session_under": "会话目录位于 {{dir}} 下",+ "session_directory_hint": "每个新会话都有独立目录。留空则使用临时工作区。协作者自行决定是否通过 GitHub 连接器克隆仓库;系统不会自动创建检出目录。","target_worktree_under": "worktree 位于 {{dir}} 下","target_mode_to_inbox": "{{mode}} → 收件箱","all_repos": "所有仓库",diff --git a/tests/test_configured_spawn.py b/tests/test_configured_spawn.pyindex 48a01770..46faf61f 100644--- a/tests/test_configured_spawn.py+++ b/tests/test_configured_spawn.py@@ -109,7 +109,8 @@ def test_spawn_starts_a_session_from_the_spec(tmp_path, monkeypatch):assert rec.mode == "auto-approve" and rec.spawn["approval_mode"] == "auto-approve"assert mgr.unattended.is_unattended(sid) is True and mgr.reviewer_opted(sid) is Trueassert mgr.get_engine(sid).is_attended() is True- assert rec.spawn["worktree"] == "" and rec.spawn["clone"] == "" # no base directory+ assert rec.spawn["workspace_setup"] == "agent"+ assert Path(rec.workspace).is_dir()# Session-only: the instructions join the standing rules for this session, no other.assert "For this session: Correctness first" in mgr._user_rules_for(sid)other = mgr.get_engine("plain", agent="cowork")@@ -154,65 +155,44 @@ def _local_origin(tmp_path) -> Path:return tmp_path / "origin"-def test_spawn_checks_out_a_worktree_and_archive_removes_it(tmp_path, monkeypatch):- origin = _local_origin(tmp_path)- monkeypatch.setenv("GITHUB_GIT_URL", f"file://{origin}")+def test_spawn_provisions_only_a_directory_and_preserves_it(tmp_path, monkeypatch):monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)mgr = _mgr(tmp_path, monkeypatch)- delivered: list[tuple[str, str]] = []+ delivered = []- async def fake_deliver(session_id, message, *, source=None):- delivered.append((session_id, message))+ async def deliver(sid, message, *, source=None):+ delivered.append((sid, message))- monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)+ monkeypatch.setattr(mgr, "deliver_to_session", deliver)+ monkeypatch.setattr("coworker.connectors.integration_tools._run_git",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("harness must not run git")))base = tmp_path / "work"- cfg = {"config_id": "cfg2", "event": "pr_open", "spawn": {"kind": "new", "persona": "cowork", "models": [], "base_dir": str(base), "worktree": True}}+ cfg = {"config_id": "cfg2", "event": "pr_open",+ "spawn": {"kind": "new", "persona": "swe-lead", "base_dir": str(base), "worktree": True}}asyncio.run(mgr._dispatch_inbound(_github_event(configuration=cfg)))sid, opening = delivered[0]rec = mgr.session_store.load(sid)- clone, wt = base / "site" / "main", base / "site" / "pr-42"- assert rec.spawn["clone"] == str(clone) and rec.spawn["worktree"] == str(wt)- assert Path(rec.workspace).resolve() == wt.resolve()- assert (wt / "worker.ts").exists() and not (clone / "worker.ts").exists() # the PR head, not main- assert f"checkout of the code under review: {wt}" in opening- # No token at rest in the clone.- assert "AUTHORIZATION" not in (clone / ".git" / "config").read_text()- # Archive: the worktree goes, the clone stays.- assert mgr.set_session_flags(sid, archived=True)["ok"] is True- assert not wt.exists() and (clone / ".git").exists()- assert "pr-42" not in _git("-C", str(clone), "worktree", "list")---def test_spawn_without_a_worktree_works_in_the_clone(tmp_path, monkeypatch):- origin = _local_origin(tmp_path)- monkeypatch.setenv("GITHUB_GIT_URL", f"file://{origin}")- monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)- mgr = _mgr(tmp_path, monkeypatch)-- async def fake_deliver(session_id, message, *, source=None):- pass-- monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)- base = tmp_path / "work"- cfg = {"config_id": "cfg3", "event": "issue_open", "spawn": {"kind": "new", "persona": "cowork", "base_dir": str(base), "worktree": False}}- asyncio.run(mgr._dispatch_inbound(_github_event(kind="issue_open", number="9", configuration=cfg)))- rec = next(mgr.session_store.load(r["session_id"]) for r in mgr.list_sessions() if r["origin"] == "github")- assert Path(rec.workspace).resolve() == (base / "site" / "main").resolve()- assert rec.spawn["worktree"] == ""- # Deleting it keeps the clone (nothing to remove).- mgr.delete_session(rec.session_id)- assert (base / "site" / "main" / ".git").exists()---def test_checkout_outside_the_base_dir_is_refused(tmp_path, monkeypatch):+ directory = base / sid+ assert Path(rec.workspace) == directory.resolve()+ assert not list(directory.iterdir())+ assert rec.spawn["workspace_setup"] == "agent"+ assert "No repository or worktree was created" in opening+ assert "refs/pull/42/head" in opening+ (directory / "keep.txt").write_text("unfinished work")+ mgr.set_session_flags(sid, archived=True)+ mgr.delete_session(sid)+ assert (directory / "keep.txt").read_text() == "unfinished work"+++def test_session_directory_outside_the_base_dir_is_refused(tmp_path, monkeypatch):monkeypatch.setenv("OPENWORKER_BASE_DIR", str(tmp_path / "allowed"))(tmp_path / "allowed").mkdir()mgr = _mgr(tmp_path, monkeypatch)- recorded: list = []- monkeypatch.setattr(mgr.unrouted, "record", lambda *a, **k: recorded.append((a, k)))- cfg = {"config_id": "cfg4", "event": "pr_open", "spawn": {"kind": "new", "persona": "cowork", "base_dir": str(tmp_path / "elsewhere"), "worktree": True}}+ recorded = []+ monkeypatch.setattr(mgr.unrouted, "record", lambda *a, **k: recorded.append(k))+ cfg = {"event": "pr_open", "spawn": {"persona": "cowork", "base_dir": str(tmp_path / "elsewhere")}}asyncio.run(mgr._dispatch_inbound(_github_event(configuration=cfg)))- assert recorded and "checkout failed" in recorded[0][1]["reason"]+ assert recorded and "session directory failed" in recorded[0]["reason"]def test_configured_event_to_an_existing_session_carries_its_framing(tmp_path, monkeypatch):@@ -257,7 +237,7 @@ def test_configured_opening_reads_plainly():assert "Your session folder" not in text-def test_named_mention_on_a_pr_checks_out_the_pr_head(tmp_path, monkeypatch):+def test_named_mention_on_a_pr_describes_the_ref_without_cloning(tmp_path, monkeypatch):origin = _local_origin(tmp_path)monkeypatch.setenv("GITHUB_GIT_URL", f"file://{origin}")monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)@@ -273,8 +253,9 @@ def test_named_mention_on_a_pr_checks_out_the_pr_head(tmp_path, monkeypatch):ev.raw["is_pr"] = Trueasyncio.run(mgr._dispatch_inbound(ev))rec = next(mgr.session_store.load(r["session_id"]) for r in mgr.list_sessions() if r["origin"] == "github")- assert rec.spawn["worktree"] == str(base / "site" / "pr-42")- assert (base / "site" / "pr-42" / "worker.ts").exists() # the PR head, not main+ assert rec.spawn["workspace_setup"] == "agent"+ assert not (base / "site").exists()+ assert "refs/pull/42/head" in configured_opening(ev, "", rec.workspace)assert rec.title.startswith("PR mention #42")@@ -305,6 +286,41 @@ def test_swe_lead_is_reachable_on_github_and_slack():assert set(m.connectors) == {"github", "slack"}+def test_missing_target_is_parked_without_a_replacement_lead(tmp_path, monkeypatch):+ mgr = _mgr(tmp_path, monkeypatch)+ parked = []+ monkeypatch.setattr(mgr.unrouted, "record", lambda *a, **k: parked.append(k))+ async def no_spawn(*args):+ raise AssertionError("targeted events must not fall through to mention spawning")+ monkeypatch.setattr(mgr, "_route_mention", no_spawn)+ ev = _github_event(configuration={"config_id": "cfg", "event": "issue_open"})+ ev.target_session_id = "missing-lead"+ before = mgr.list_sessions()+ asyncio.run(mgr._dispatch_inbound(ev))+ assert mgr.list_sessions() == before+ assert "target session missing-lead is missing" in parked[0]["reason"]+++def test_worker_scratch_is_shared_with_lead_and_survives_rebuild(tmp_path, monkeypatch):+ monkeypatch.setenv("COWORKER_SCRATCH_BASE", str(tmp_path / "scratch"))+ mgr = _mgr(tmp_path, monkeypatch)+ mgr.save("lead", mgr.get_engine("lead", agent="swe-lead"))+ out = mgr.create_team("lead", [{"persona": "swe-worker", "name": "sam"}])+ worker = out["workers"][0]+ sid = worker["session_id"]+ scratch = Path(worker["scratch_directory"])+ assert scratch == tmp_path / "scratch" / "lead" / "workers" / sid+ marker = scratch / "evidence.txt"+ marker.write_text("verified")+ lead = mgr.get_engine("lead")+ engine = mgr.get_engine(sid)+ assert "verified" in str(lead.registry.get("read_file").func(str(marker)))+ assert "verified" in str(engine.registry.get("read_file").func(str(marker)))+ mgr._engines.pop(sid)+ assert mgr._provision_scratch(sid) == str(scratch)+ assert "verified" in str(mgr.get_engine(sid).registry.get("read_file").func(str(marker)))++def test_spawn_applies_the_configured_approval_mode_and_inbox_dial(tmp_path, monkeypatch):mgr = _mgr(tmp_path, monkeypatch)@@ -323,4 +339,3 @@ def test_spawn_applies_the_configured_approval_mode_and_inbox_dial(tmp_path, monasyncio.run(mgr._dispatch_inbound(_github_event(number="43", configuration=cfg)))sid = next(r["session_id"] for r in mgr.list_sessions() if r["title"].startswith("PR #43"))assert mgr.session_store.load(sid).mode == "bypass-approvals"-diff --git a/tests/test_github_installs.py b/tests/test_github_installs.pyindex f2cc8377..ed2f06fa 100644--- a/tests/test_github_installs.py+++ b/tests/test_github_installs.py@@ -608,6 +608,31 @@ def test_clone_pull_roundtrip_and_no_token_at_rest(tmp_path, monkeypatch, _origiassert (clone / "next.txt").read_text() == "more"+def test_clone_explicit_pr_ref_returns_full_sha(tmp_path, monkeypatch, _origin):+ from pathlib import Path+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))+ monkeypatch.setenv("GITHUB_GIT_URL", f"file://{_origin['base']}")+ work = _origin["work"]+ (work / "pr.txt").write_text("PR-only change")+ _git(["add", "."], cwd=work)+ _git(["commit", "-m", "PR revision"], cwd=work)+ _git(["push", "origin", "HEAD:refs/pull/42/head"], cwd=work)+ _, tools = _clone_tools(SecretStore(), tmp_path)+ out = tools["github_clone"]("acme", "site", ref="refs/pull/42/head")+ assert out.get("ok"), out+ assert len(out["head"]) == 40+ assert (Path(out["path"]) / "pr.txt").read_text() == "PR-only change"+ assert out["head"] == _git(["rev-parse", "HEAD"], cwd=work).stdout.strip()+++def test_clone_rejects_option_like_ref_before_git(tmp_path, monkeypatch):+ _, tools = _clone_tools(SecretStore(), tmp_path)+ monkeypatch.setattr("coworker.connectors.integration_tools._run_git",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("must not run git")))+ for ref in ("--upload-pack=command", "main:refs/heads/main", "main other"):+ assert "ref must be" in tools["github_clone"]("acme", "site", ref=ref)["error"]++def test_clone_refuses_paths_outside_granted_roots(tmp_path, monkeypatch, _origin):monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))monkeypatch.setenv("GITHUB_GIT_URL", f"file://{_origin['base']}")