Python
Fix device provenance and linked worker denial recovery
Rohit C Prasadcc728bcf7cfe
diff --git a/coworker/inbox.py b/coworker/inbox.pyindex 4d04b734..39a4cb0b 100644--- a/coworker/inbox.py+++ b/coworker/inbox.py@@ -406,9 +406,25 @@ class InboxStore:return Falseself._resolve_locked(item, resolution, by)resolved_ids = [item_id]+ source_id = item.data.get("worker_prompt_id")+ source = self._items.get(source_id) if isinstance(source_id, str) else None+ args = item.data.get("arguments") or {}+ # Server-stamped ownership link only. Denying permission to ALLOW a worker+ # action means deny that action, not leave it parked indefinitely. Never+ # invert a proposed denial into an allow, or propagate stop/delete/errors.+ if (resolution == "deny" and item.kind == KIND_APPROVAL+ and item.data.get("tool") == "decide_worker_call"+ and isinstance(args, dict) and args.get("decision") == "allow"+ and args.get("call_id") == source_id+ and source is not None and source.kind == KIND_APPROVAL+ and source.state == STATE_PENDING):+ self._resolve_locked(source, "deny", by)+ resolved_ids.append(source.id)+ if isinstance(item.data.get("worker_call"), dict):+ item.data["worker_call"] = {**item.data["worker_call"], "state": STATE_RESOLVED, "resolution": "deny"}for dependent in self._items.values():- if dependent.state == STATE_PENDING and dependent.data.get("worker_prompt_id") == item_id:- self._supersede_locked(dependent, item)+ if dependent.state == STATE_PENDING and dependent.data.get("worker_prompt_id") in resolved_ids:+ self._supersede_locked(dependent, self._items[dependent.data["worker_prompt_id"]])resolved_ids.append(dependent.id)self._save()for resolved_id in resolved_ids:diff --git a/coworker/provenance.py b/coworker/provenance.pyindex 19371dea..3d6a3234 100644--- a/coworker/provenance.py+++ b/coworker/provenance.py@@ -16,6 +16,7 @@ confidence.from __future__ import annotationsimport shlex+import statfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Optional@@ -235,9 +236,20 @@ class SessionFiles:write that raised left nothing on disk to run."""paths, origin = created_paths(tool_name, arguments, result)for path in paths:+ key = resolve(path, self.root)+ if self._is_device(key):+ continue # A null/device sink does not retain downloaded script bytes.# A later write or download over the same path wins — the newer bytes are the# ones that would execute.- self._files[resolve(path, self.root)] = Origin(step=step, kind=origin)+ self._files[key] = Origin(step=step, kind=origin)++ @staticmethod+ def _is_device(path: str) -> bool:+ try:+ mode = Path(path).stat().st_mode+ except (OSError, ValueError):+ return False # Unknown paths retain conservative provenance handling.+ return stat.S_ISCHR(mode) or stat.S_ISBLK(mode)def match(self, tool_name: str, arguments: dict[str, Any], *, step: int@@ -246,7 +258,10 @@ class SessionFiles:one whose contents the agent most recently controlled."""best: Optional[Match] = Nonefor path in referenced_paths(tool_name, arguments):- origin = self._files.get(resolve(path, self.root))+ key = resolve(path, self.root)+ if self._is_device(key):+ continue # Also ignore device entries recorded by an older runtime.+ origin = self._files.get(key)if origin is None:continuecandidate = Match(diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 143ac93c..db8d204e 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -1816,11 +1816,22 @@ class SessionManager:item = self.inbox.get(item_id)if item is not None:self.reconcile_obsolete_prompts(item.session_id)+ pending_before = {p.id: p for p in self.inbox.pending()}ok = self.inbox.resolve(item_id, resolution, by=by)if not ok or item is None:return ok- if not self.is_running(item.session_id):- await self._durable_resume(item)+ # Store resolution may atomically deny the original worker call and retire+ # sibling proxies too. Resume all affected idle sessions after a restart, not+ # just the lead whose card was clicked. Live waiters are released by the store.+ resumed_sessions = set()+ resumes = []+ for resolved in pending_before.values():+ if (resolved.state == "resolved" and resolved.session_id not in resumed_sessions+ and not self.is_running(resolved.session_id)):+ resumed_sessions.add(resolved.session_id)+ resumes.append(self._durable_resume(resolved))+ if resumes:+ await asyncio.gather(*resumes)return okasync def _durable_resume(self, item) -> None:diff --git a/surfaces/gui/e2e/worker-approval.spec.ts b/surfaces/gui/e2e/worker-approval.spec.tsindex 38dda6e6..08b5410a 100644--- a/surfaces/gui/e2e/worker-approval.spec.ts+++ b/surfaces/gui/e2e/worker-approval.spec.ts@@ -1,5 +1,25 @@import { expect } from "@playwright/test";-import { test } from "./fixtures";+import { test, sendSessionEvent } from "./fixtures";++for (const suggestion of ["allow", "deny"]) {+ test(`overriding a lead ${suggestion} answers the exact worker request`, async ({ page }) => {+ const answers: Array<{ id: string; resolution: string }> = [];+ await page.route("**/v1/inbox/*/resolve", async route => {+ const id = new URL(route.request().url()).pathname.split("/").at(-2)!;+ answers.push({ id, resolution: route.request().postDataJSON().resolution });+ await route.fulfill({ json: { ok: true } });+ });+ await page.goto("/");+ await sendSessionEvent(page, { type: "permission_required", data: {+ name: "decide_worker_call",+ arguments: { worker: "Maya", call_id: "sample-worker-prompt", decision: suggestion, note: "Verify the assigned task." },+ worker_call: { worker: "Maya", tool: "run_shell", arguments: { command: "npm test" }, state: "pending" },+ } });+ await page.getByTestId("workerdec-override").click();+ await expect.poll(() => answers.some(a => a.id === "sample-worker-prompt" &&+ a.resolution === (suggestion === "allow" ? "deny" : "allow"))).toBe(true);+ });+}test("a background lead approval shows the command and disappears when the worker request resolves", async ({ page }) => {let send: ((event: unknown) => void) | undefined;diff --git a/tests/test_provenance.py b/tests/test_provenance.pyindex 00e2b6f0..9ecf4721 100644--- a/tests/test_provenance.py+++ b/tests/test_provenance.py@@ -6,6 +6,7 @@ that file, and how long ago."""from __future__ import annotations+import osfrom pathlib import Pathimport pytest@@ -165,6 +166,28 @@ def test_download_over_a_written_path_becomes_a_download(files):assert files.match("run_shell", {"command": "bash tool.sh"}, step=7).downloaded+def test_device_download_sink_does_not_taint_later_health_checks(files):+ files.record("run_shell", {"command": f"curl -o {os.devnull} https://example.test"}, None, step=1)+ assert files.match("run_shell", {"command": f"curl -o {os.devnull} http://127.0.0.1:8000"}, step=2) is None+++def test_device_symlink_is_ignored_but_regular_null_named_script_is_not(files, tmp_path):+ alias = tmp_path / "sink.sh"+ alias.symlink_to(os.devnull)+ files.record("run_shell", {"command": "curl -o sink.sh https://example.test"}, None, step=1)+ assert files.match("run_shell", {"command": "bash sink.sh"}, step=2) is None+ (tmp_path / "null.sh").write_text("echo test")+ files.record("run_shell", {"command": "curl -o null.sh https://example.test"}, None, step=3)+ assert files.match("run_shell", {"command": "bash null.sh"}, step=4).downloaded+++def test_device_does_not_hide_a_real_download_or_keep_legacy_taint(files):+ files._files[prov.resolve(os.devnull, files.root)] = prov.Origin(step=9, kind=DOWNLOADED)+ files.record("run_shell", {"command": "curl -o tool.sh https://example.test"}, None, step=1)+ found = files.match("run_shell", {"command": f"bash tool.sh > {os.devnull}"}, step=10)+ assert found.path == "tool.sh" and found.downloaded++# -- the documented blind spot -------------------------------------------------def test_transitive_imports_are_a_known_miss(files):# The agent writes a helper and runs a pre-existing entry point that imports it. Nodiff --git a/tests/test_team_live_gaps.py b/tests/test_team_live_gaps.pyindex 618e5cd0..36455dbe 100644--- a/tests/test_team_live_gaps.py+++ b/tests/test_team_live_gaps.py@@ -131,6 +131,99 @@ def test_cross_team_or_mismatched_worker_cannot_link_or_disclose_prompt(manager)assert original.state == "pending"+def test_denied_lead_allow_atomically_denies_worker_and_retires_other_proxies(manager):+ original, request = request_for(manager)+ data = manager.approval_prompt_data("lead", request)+ parent = manager.inbox.add_approval("lead", "Decision", data=data)+ sibling = manager.inbox.add_approval("lead", "Other window", data=data)++ async def run():+ waits = [asyncio.create_task(manager.inbox.wait(i.id)) for i in (original, parent, sibling)]+ await asyncio.sleep(0)+ assert manager.inbox.resolve(parent.id, "deny", by="human")+ assert await asyncio.wait_for(asyncio.gather(*waits), 1) == ["deny", "deny", "superseded"]++ asyncio.run(run())+ assert original.resolved_by == "human"+ assert not manager.inbox.pending()+ assert not manager.inbox.resolve(original.id, "allow")+ loaded = InboxStore(manager.inbox.path)+ assert loaded.get(original.id).resolution == "deny"+ assert loaded.get(parent.id).resolution == "deny"++[email protected]("answer", ["allow", "interrupted", "session deleted"])+def test_non_denial_of_proxy_does_not_resolve_worker(manager, answer):+ original, request = request_for(manager)+ parent = manager.inbox.add_approval("lead", "Decision", data=manager.approval_prompt_data("lead", request))+ manager.inbox.resolve(parent.id, answer)+ assert original.state == "pending"+++def test_rejecting_a_lead_denial_never_implicitly_allows_worker(manager):+ original, request = request_for(manager)+ request.arguments["decision"] = "deny"+ parent = manager.inbox.add_approval("lead", "Decision", data=manager.approval_prompt_data("lead", request))+ manager.inbox.resolve(parent.id, "deny")+ assert original.state == "pending"+++def test_denial_after_restart_resumes_both_parked_sessions(manager, monkeypatch):+ original, request = request_for(manager)+ parent = manager.inbox.add_approval("lead", "Decision", data=manager.approval_prompt_data("lead", request))+ manager.inbox = InboxStore(manager.inbox.path)+ resumed = []++ async def resume(item):+ resumed.append((item.session_id, item.resolution))++ monkeypatch.setattr(manager, "_durable_resume", resume)+ monkeypatch.setattr(manager, "reconcile_obsolete_prompts", lambda sid: None)+ asyncio.run(manager.resolve_inbox(parent.id, "deny", by="human"))+ assert sorted(resumed) == [("lead", "deny"), ("worker", "deny")]+ assert manager.inbox.get(original.id).resolution == "deny"+++def test_rest_proxy_denial_is_visible_to_another_client_and_survives_reload(manager, monkeypatch):+ from fastapi.testclient import TestClient+ from coworker.server import create_app++ original, request = request_for(manager)+ parent = manager.inbox.add_approval("lead", "Decision", data=manager.approval_prompt_data("lead", request))+ monkeypatch.setattr(manager, "reconcile_obsolete_prompts", lambda sid: None)+ first = TestClient(create_app(manager))+ other = TestClient(create_app(manager))+ assert first.post(f"/v1/inbox/{parent.id}/resolve", json={"resolution": "deny"}).json()["ok"]+ rows = other.get("/v1/inbox", params={"session_id": "worker"}).json()["items"]+ assert next(i for i in rows if i["id"] == original.id)["resolution"] == "deny"+ assert not other.post(f"/v1/inbox/{original.id}/resolve", json={"resolution": "allow"}).json()["ok"]+ assert InboxStore(manager.inbox.path).get(original.id).resolution == "deny"+++def test_lead_proxy_denial_releases_live_engine_without_executing_decision(manager, monkeypatch):+ original, request = request_for(manager)+ manager.provider = ScriptedProvider([+ _tool_turn("decide_worker_call", request.arguments), _text_turn("The user denied it.")+ ])+ executed = []+ monkeypatch.setattr(manager, "decide_worker_call", lambda *a: executed.append(a))++ async def run():+ delivery = asyncio.create_task(manager.deliver_to_session("lead", "Review the waiting call."))+ for _ in range(200):+ pending = manager.inbox.pending("lead")+ if pending:+ break+ await asyncio.sleep(0.01)+ assert pending+ manager.inbox.resolve(pending[0].id, "deny", by="human")+ await asyncio.wait_for(delivery, 3)++ asyncio.run(run())+ assert original.resolution == "deny"+ assert not executed and not manager.inbox.pending()++def test_successful_self_wake_ends_turn_without_another_model_call(manager):manager.provider = ScriptedProvider([_tool_turn("sleep_for", {"seconds": 2})])engine = manager.get_engine("lead", agent="swe-lead")diff --git a/tests/test_team_rehearsal_fixes.py b/tests/test_team_rehearsal_fixes.pyindex 922dc748..16f95a30 100644--- a/tests/test_team_rehearsal_fixes.py+++ b/tests/test_team_rehearsal_fixes.py@@ -141,7 +141,9 @@ def test_unattributed_request_is_visible_and_forwarded_gate_is_not_double_counteassert [r["id"] for r in summary["pending_requests"]] == [forwarded.id]manager.inbox.resolve(forwarded.id, "deny")summary = manager.team_summary(team.team_id)- assert [r["id"] for r in summary["pending_requests"]] == [original.id]+ assert summary["pending_requests"] == []+ assert summary["totals"]["asks_waiting"] == 0+ assert original.resolution == "deny" # denying the lead's allow resolves both cardsdef test_runtime_facts_do_not_read_configuration_or_follow_workspace_symlinks(tmp_path, monkeypatch):