orca-agent-workflow 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. orca_agent_workflow/__init__.py +3 -0
  2. orca_agent_workflow/__main__.py +3 -0
  3. orca_agent_workflow/adoption.py +33 -0
  4. orca_agent_workflow/check_sync.py +93 -0
  5. orca_agent_workflow/cli.py +83 -0
  6. orca_agent_workflow/codex_review.py +364 -0
  7. orca_agent_workflow/doctor.py +33 -0
  8. orca_agent_workflow/gate.Dockerfile +9 -0
  9. orca_agent_workflow/install.py +313 -0
  10. orca_agent_workflow/migrate.py +178 -0
  11. orca_agent_workflow/native.py +142 -0
  12. orca_agent_workflow/resume_dispatch.py +160 -0
  13. orca_agent_workflow/review_gate.py +291 -0
  14. orca_agent_workflow/run_gates.py +263 -0
  15. orca_agent_workflow/sensitive.json +19 -0
  16. orca_agent_workflow/start.py +293 -0
  17. orca_agent_workflow/task_plan.py +301 -0
  18. orca_agent_workflow/task_scope.py +1256 -0
  19. orca_agent_workflow/template/AGENTS.md +49 -0
  20. orca_agent_workflow/template/CLAUDE.md +4 -0
  21. orca_agent_workflow/template/agents/LICENSE +21 -0
  22. orca_agent_workflow/template/agents/README.md +78 -0
  23. orca_agent_workflow/template/agents/WORKFLOW.md +65 -0
  24. orca_agent_workflow/template/agents/docs/cross-provider.md +79 -0
  25. orca_agent_workflow/template/agents/docs/roles/implementer.md +15 -0
  26. orca_agent_workflow/template/agents/docs/task-permissions.md +124 -0
  27. orca_agent_workflow/template/agents/skills/project-handoff/SKILL.md +23 -0
  28. orca_agent_workflow/template/agents/skills/review-pr/SKILL.md +41 -0
  29. orca_agent_workflow/template/agents/skills/review-pr/references/record.example.json +31 -0
  30. orca_agent_workflow/template/agents/skills/review-pr/references/reviewer.md +20 -0
  31. orca_agent_workflow/template/agents/skills/session-recover/SKILL.md +17 -0
  32. orca_agent_workflow/template/agents/skills/session-recover/references/recovery.md +38 -0
  33. orca_agent_workflow/template/agents/skills/session-recover/scripts/session_context.py +239 -0
  34. orca_agent_workflow/template/agents/skills/spec-and-delegate/SKILL.md +37 -0
  35. orca_agent_workflow/template/agents/skills/spec-and-delegate/references/spec-template.md +46 -0
  36. orca_agent_workflow/template/agents/skills/start-task/SKILL.md +72 -0
  37. orca_agent_workflow/template/agents/workflow.json +64 -0
  38. orca_agent_workflow/template/agents/workflow.py +82 -0
  39. orca_agent_workflow/template/claude/skills/project-handoff/SKILL.md +12 -0
  40. orca_agent_workflow/template/claude/skills/review-pr/SKILL.md +12 -0
  41. orca_agent_workflow/template/claude/skills/session-recover/SKILL.md +12 -0
  42. orca_agent_workflow/template/claude/skills/spec-and-delegate/SKILL.md +12 -0
  43. orca_agent_workflow/template/claude/skills/start-task/SKILL.md +12 -0
  44. orca_agent_workflow/template/gitattributes +5 -0
  45. orca_agent_workflow/template/githooks/pre-push +11 -0
  46. orca_agent_workflow/template/gitignore +3 -0
  47. orca_agent_workflow/template/opencode/commands/project-handoff.md +7 -0
  48. orca_agent_workflow/template/opencode/commands/review-pr.md +7 -0
  49. orca_agent_workflow/template/opencode/commands/session-recover.md +7 -0
  50. orca_agent_workflow/template/opencode/commands/spec-and-delegate.md +7 -0
  51. orca_agent_workflow/template/opencode/commands/start-task.md +9 -0
  52. orca_agent_workflow-0.2.0.dist-info/METADATA +214 -0
  53. orca_agent_workflow-0.2.0.dist-info/RECORD +57 -0
  54. orca_agent_workflow-0.2.0.dist-info/WHEEL +5 -0
  55. orca_agent_workflow-0.2.0.dist-info/entry_points.txt +2 -0
  56. orca_agent_workflow-0.2.0.dist-info/licenses/LICENSE +21 -0
  57. orca_agent_workflow-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1256 @@
1
+ #!/usr/bin/env python3
2
+ """File-only task MCP broker, frozen review inputs, and owned-client lifecycle.
3
+
4
+ No worker shell, test runner, recursive delegation, or infrastructure interface.
5
+ The coordinator runs quality gates and separately approves operational work.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import fnmatch
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import stat
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ import time
22
+ from pathlib import Path, PureWindowsPath
23
+ from typing import Any
24
+
25
+ SELF = Path(__file__).resolve()
26
+ LIMIT = 2_000_000
27
+ PAGE = 8_000
28
+ # Fixed worker boundary. The approved per-task allowlist is the primary control;
29
+ # these categories should not need routine updates (see .agents/docs/task-permissions.md).
30
+ WORKFLOW_DIRS = {".agents", ".claude", ".codex", ".opencode", ".github", ".githooks"}
31
+ WORKFLOW_FILES = {".mcp.json", "opencode.json", "opencode.jsonc"}
32
+ WORKFLOW_PREFIXES = {
33
+ ("scripts", "agents"),
34
+ ("src", "orca_agent_workflow"), # the runtime's own source, in the kit repository
35
+ ("tests", "agents"),
36
+ ("docs", "agents"),
37
+ (".tmp", "agent-reviews"),
38
+ }
39
+ SENSITIVE_FILE = SELF.parent / "sensitive.json"
40
+ CONFIG = ".agents/workflow.json"
41
+ # Backstop only: the coordinator's exact per-task allowlist is the primary control.
42
+ CREDENTIAL_DIRS = {".git", ".aws", ".ssh"}
43
+ CREDENTIAL_FILES = {".npmrc", ".netrc", ".pgpass"}
44
+ CREDENTIAL_PREFIXES = (".env", "id_rsa", "id_ed25519", "id_ecdsa")
45
+ CREDENTIAL_SUFFIXES = (
46
+ ".pem",
47
+ ".key",
48
+ ".p12",
49
+ ".pfx",
50
+ ".bak",
51
+ ".backup",
52
+ ".dump",
53
+ ".sql.gz",
54
+ ".sql.bz2",
55
+ ".sql.xz",
56
+ ".sql.zst",
57
+ )
58
+ CREDENTIAL_ROOTS = {"data", "backups", "dumps"}
59
+ WINDOWS = os.name == "nt"
60
+ # Names Windows maps to devices in any folder, with or without an extension.
61
+ WINDOWS_DEVICES = {"con", "prn", "aux", "nul", "conin$", "conout$"} | {
62
+ f"{kind}{n}" for kind in ("com", "lpt") for n in "123456789"
63
+ }
64
+ FILE_ATTRIBUTE_REPARSE_POINT = 0x400
65
+
66
+
67
+ def host_executable(name: str, root: Path | None = None, suffixes: tuple = (".exe",)) -> str:
68
+ """Absolute program from absolute PATH entries outside the checkout. Windows would
69
+ otherwise search the current directory first, which is often the branch under test."""
70
+ for entry in os.environ.get("PATH", "").split(os.pathsep):
71
+ folder = Path(entry.strip('"'))
72
+ if not folder.is_absolute():
73
+ continue
74
+ for suffix in suffixes:
75
+ candidate = folder / (name + suffix)
76
+ if candidate.is_file():
77
+ resolved = candidate.resolve()
78
+ if root is not None and resolved.is_relative_to(root.resolve()):
79
+ continue
80
+ return str(resolved)
81
+ raise FileNotFoundError(f"{name} was not found on PATH outside the checkout")
82
+
83
+
84
+ def claude_executable(root: Path) -> str | None:
85
+ if WINDOWS:
86
+ return host_executable("claude", root, (".exe", ".cmd"))
87
+ return shutil.which("claude")
88
+
89
+
90
+ def git_executable(root: Path | None = None) -> str:
91
+ """Absolute Git outside the checkout; never resolved through the checkout or cwd."""
92
+ if not WINDOWS:
93
+ return "/usr/bin/git"
94
+ try:
95
+ return host_executable("git", root)
96
+ except FileNotFoundError:
97
+ raise FileNotFoundError("git.exe was not found on PATH; install Git for Windows")
98
+
99
+
100
+ def project_folder() -> Path:
101
+ """The checkout, or the current folder of a project not yet under Git."""
102
+ try:
103
+ return project_root()
104
+ except (ValueError, OSError):
105
+ return Path.cwd().resolve()
106
+
107
+
108
+ def project_root(start: Path | None = None) -> Path:
109
+ """The Git checkout the command runs in; the runtime no longer lives inside it."""
110
+ folder = (start or Path.cwd()).resolve()
111
+ output = subprocess.run(
112
+ [git_executable(), "-C", str(folder), "rev-parse", "--show-toplevel"],
113
+ capture_output=True,
114
+ text=True,
115
+ check=False,
116
+ )
117
+ if output.returncode:
118
+ raise ValueError("Run this command inside the project's Git checkout")
119
+ return Path(output.stdout.strip()).resolve()
120
+
121
+
122
+ def final_path(fd: int) -> str:
123
+ """The real path Windows opened for this descriptor, after every link and junction."""
124
+ import ctypes
125
+ import msvcrt
126
+ from ctypes import wintypes
127
+
128
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
129
+ get = kernel32.GetFinalPathNameByHandleW
130
+ get.argtypes = [wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD]
131
+ get.restype = wintypes.DWORD
132
+ handle = msvcrt.get_osfhandle(fd)
133
+ size = 512
134
+ while True:
135
+ buffer = ctypes.create_unicode_buffer(size)
136
+ length = get(handle, buffer, size, 0)
137
+ if not length:
138
+ raise OSError(ctypes.get_last_error(), "Could not read the opened file's path")
139
+ if length < size:
140
+ break
141
+ size = length + 1
142
+ path = buffer.value
143
+ if path.startswith("\\\\?\\UNC\\"):
144
+ return "\\\\" + path[8:]
145
+ return path[4:] if path.startswith("\\\\?\\") else path
146
+
147
+
148
+ def windows_name_problem(segment: str) -> str | None:
149
+ """Path components Windows would silently reinterpret or map to a device."""
150
+ if ":" in segment:
151
+ return "Drive-relative paths and alternate data streams are forbidden"
152
+ if segment.endswith((".", " ")):
153
+ return "Trailing dots and spaces are forbidden"
154
+ if any(c in segment for c in '<>"|?*') or any(ord(c) < 32 for c in segment):
155
+ return "Characters Windows reserves are forbidden"
156
+ if segment.split(".", 1)[0].rstrip(" ").casefold() in WINDOWS_DEVICES:
157
+ return "Windows device names are forbidden"
158
+ return None
159
+
160
+
161
+ def is_credential(parts: tuple[str, ...]) -> bool:
162
+ """Casefolded path components name a credential-bearing file or local data store."""
163
+ return parts[0] in CREDENTIAL_ROOTS or any(
164
+ s in CREDENTIAL_DIRS
165
+ or s in CREDENTIAL_FILES
166
+ or s.startswith(CREDENTIAL_PREFIXES)
167
+ or s.endswith(CREDENTIAL_SUFFIXES)
168
+ for s in parts
169
+ )
170
+
171
+
172
+ def is_workflow_control(parts: tuple[str, ...]) -> bool:
173
+ """Casefolded components name the workflow's own policy, tooling, specs or evidence."""
174
+ name = parts[-1]
175
+ return (
176
+ parts[0] == "specs"
177
+ or parts[:2] in WORKFLOW_PREFIXES
178
+ or any(s in WORKFLOW_DIRS for s in parts)
179
+ or name in WORKFLOW_FILES
180
+ or (name.startswith(("agents", "claude")) and name.endswith(".md"))
181
+ )
182
+
183
+
184
+ def sensitive_patterns(extra: list[str] | tuple[str, ...] = ()) -> list[str]:
185
+ """The runtime's default patterns plus the project's own from its trusted config."""
186
+ data = json.loads(SENSITIVE_FILE.read_text(encoding="utf-8"))
187
+ if not isinstance(data, dict) or not all(
188
+ isinstance(p, str) and p for p in data.get("patterns", [None])
189
+ ):
190
+ raise ValueError("sensitive.json must hold a non-empty list of glob patterns")
191
+ return [p.casefold() for p in [*data["patterns"], *extra]]
192
+
193
+
194
+ def load_config(data: bytes) -> dict[str, Any]:
195
+ """Parse `.agents/workflow.json`: project, runtime pin, roles, gates and sensitive paths."""
196
+ config = json.loads(data.decode("utf-8"))
197
+ project = config.get("project") if isinstance(config, dict) else None
198
+ if (
199
+ not isinstance(config, dict)
200
+ or type(config.get("version")) is not int
201
+ or config["version"] != 1
202
+ or not isinstance(project, dict)
203
+ or not isinstance(project.get("repository"), str)
204
+ or not isinstance(config.get("roles"), dict)
205
+ or not isinstance(config.get("runtime"), dict)
206
+ ):
207
+ raise ValueError("Unsupported .agents/workflow.json; expected version 1")
208
+ extra = config.get("sensitive_patterns", [])
209
+ if not isinstance(extra, list) or not all(isinstance(p, str) and p for p in extra):
210
+ raise ValueError("sensitive_patterns must be a list of glob patterns")
211
+ return config
212
+
213
+
214
+ def roles_policy(config: dict[str, Any]) -> dict[str, Any]:
215
+ """The roles view that profile checks and the review gate validate against."""
216
+ return {
217
+ "version": 2,
218
+ "repository": config["project"]["repository"],
219
+ "max_fix_rounds": config.get("max_fix_rounds", 2),
220
+ "reviewer_provider_differs_from_planner": config.get(
221
+ "reviewer_provider_differs_from_planner"
222
+ ),
223
+ "roles": config["roles"],
224
+ }
225
+
226
+
227
+ def base_config(root: Path, ref: str) -> tuple[bytes, dict[str, Any]]:
228
+ """The configuration as committed at a reviewed ref, never the working tree."""
229
+ if not re.fullmatch(r"[0-9a-f]{40}", ref):
230
+ raise ValueError("The trusted policy ref must be a full commit SHA")
231
+ try:
232
+ data = git_bytes(root, "show", f"{ref}:{CONFIG}")
233
+ except subprocess.CalledProcessError as exc:
234
+ raise ValueError(
235
+ f"Cannot read {CONFIG} at the trusted revision {ref}. "
236
+ "Verify that the revision is available locally and contains the reviewed policy. "
237
+ "For default refs after adoption, check workflow.py status from the task checkout."
238
+ ) from exc
239
+ return data, load_config(data)
240
+
241
+
242
+ def is_sensitive(value: str, patterns: list[str]) -> bool:
243
+ """Gate, build and deploy inputs: allowed only when the approved spec marks them."""
244
+ path = value.casefold()
245
+ name = path.rsplit("/", 1)[-1]
246
+ # Patterns with a slash match the whole path; others match only the file name.
247
+ return any(fnmatch.fnmatchcase(path if "/" in p else name, p) for p in patterns)
248
+
249
+
250
+ class ScopeEnded(ValueError):
251
+ """The immutable task authority is no longer valid."""
252
+
253
+
254
+ def sha(data: bytes) -> str:
255
+ return hashlib.sha256(data).hexdigest()
256
+
257
+
258
+ def digest(path: Path) -> str:
259
+ return sha(path.read_bytes())
260
+
261
+
262
+ def atomic_json(path: Path, value: Any) -> None:
263
+ with tempfile.NamedTemporaryFile(
264
+ mode="w", encoding="utf-8", dir=path.parent, prefix=".scope-", delete=False, newline="\n"
265
+ ) as output:
266
+ target = Path(output.name)
267
+ json.dump(value, output, indent=2)
268
+ output.write("\n")
269
+ target.replace(path)
270
+
271
+
272
+ def git_bytes(root: Path, *args: str) -> bytes:
273
+ return subprocess.check_output(
274
+ [
275
+ git_executable(root),
276
+ "-c",
277
+ "core.fsmonitor=false",
278
+ "-c",
279
+ f"core.hooksPath={os.devnull}",
280
+ "-C",
281
+ str(root),
282
+ *args,
283
+ ],
284
+ stderr=subprocess.DEVNULL,
285
+ )
286
+
287
+
288
+ def git_ignored(root: Path, values: list[str]) -> set[str]:
289
+ """Paths Git ignores; writes there would not appear in the coordinator's diff."""
290
+ if not values:
291
+ return set()
292
+ result = subprocess.run(
293
+ [
294
+ git_executable(root),
295
+ "-c",
296
+ "core.fsmonitor=false",
297
+ "-c",
298
+ f"core.hooksPath={os.devnull}",
299
+ "-C",
300
+ str(root),
301
+ "check-ignore",
302
+ "--stdin",
303
+ "-z",
304
+ ],
305
+ input="\0".join(values).encode() + b"\0",
306
+ capture_output=True,
307
+ check=False,
308
+ )
309
+ if result.returncode not in (0, 1):
310
+ raise ValueError("Could not check ignored paths")
311
+ return {v.decode() for v in result.stdout.split(b"\0") if v}
312
+
313
+
314
+ def relative(value: Any, write: bool = False) -> str:
315
+ if not isinstance(value, str) or not value or "\\" in value or "\x00" in value:
316
+ raise ValueError("Expected a relative POSIX file path")
317
+ p = Path(value)
318
+ if p.is_absolute() or any(s in ("", ".", "..") for s in value.split("/")):
319
+ raise ValueError("Absolute paths, traversal, and ambiguous paths are forbidden")
320
+ if WINDOWS:
321
+ for segment in value.split("/"):
322
+ problem = windows_name_problem(segment)
323
+ if problem:
324
+ raise ValueError(problem)
325
+ parts = tuple(s.casefold() for s in value.split("/"))
326
+ if is_credential(parts):
327
+ raise ValueError("Credential paths are forbidden")
328
+ if write and is_workflow_control(parts):
329
+ raise ValueError(
330
+ "Workers cannot edit workflow controls, approved specs, or review evidence"
331
+ )
332
+ if write and len(parts) == 1 and parts[0].endswith(".py"):
333
+ raise ValueError("Workers cannot create root-level Python modules (module shadowing)")
334
+ return value
335
+
336
+
337
+ def chunk(text: str, offset: Any = 0, limit: Any = PAGE) -> dict[str, Any]:
338
+ if type(offset) is not int or offset < 0 or offset > len(text):
339
+ raise ValueError("offset must be a valid character offset")
340
+ if type(limit) is not int or not 1 <= limit <= 12_000:
341
+ raise ValueError("limit must be between 1 and 12000 characters")
342
+ end = min(len(text), offset + limit)
343
+ while True:
344
+ result = {
345
+ "text": text[offset:end],
346
+ "offset": offset,
347
+ "next_offset": end if end < len(text) else None,
348
+ "total_chars": len(text),
349
+ }
350
+ if len(json.dumps(result, ensure_ascii=False).encode()) <= 16_000:
351
+ return result
352
+ end = offset + max(1, (end - offset) // 2)
353
+
354
+
355
+ def orca_executable() -> str:
356
+ """The Orca CLI. On Windows only an absolute native executable: cmd.exe re-parses a
357
+ batch launcher's arguments, so worker-supplied question or report text could run."""
358
+ executable = os.environ.get("ORCA_CLI") or shutil.which("orca") or "orca"
359
+ if WINDOWS:
360
+ path = PureWindowsPath(executable)
361
+ # Compare the whole name: older Pythons report no suffix for "orca.cmd.", and
362
+ # Windows drops the trailing dot and runs the batch file.
363
+ if not path.is_absolute() or path.name.casefold() != "orca.exe":
364
+ raise ValueError(f"{executable} is not a native orca.exe; put it first on PATH")
365
+ return executable
366
+
367
+
368
+ def orca(*args: str) -> dict[str, Any]:
369
+ result = subprocess.run(
370
+ [orca_executable(), "orchestration", *args, "--json"],
371
+ capture_output=True,
372
+ text=True,
373
+ timeout=30,
374
+ check=False,
375
+ )
376
+ try:
377
+ data = json.loads(result.stdout)
378
+ except ValueError as exc:
379
+ raise ValueError("Orca returned no valid receipt") from exc
380
+ if not isinstance(data, dict):
381
+ raise ValueError("Orca returned an invalid receipt shape")
382
+ if result.returncode or data.get("ok") is not True:
383
+ raise ValueError("Orca operation failed: " + str(data.get("error", result.stderr[:300])))
384
+ if not isinstance(data.get("result"), dict):
385
+ raise ValueError("Orca returned an invalid result shape")
386
+ return data["result"]
387
+
388
+
389
+ class Scope:
390
+ def __init__(
391
+ self, manifest: Path, bundle: Path | None = None, probe_folder: str | None = None
392
+ ):
393
+ self.manifest = manifest.resolve(strict=True)
394
+ self.bundle = bundle.resolve(strict=True) if bundle else None
395
+ self.sha = digest(self.manifest)
396
+ self.data = json.loads(self.manifest.read_text(encoding="utf-8"))
397
+ d = self.data
398
+ fields = {
399
+ "version",
400
+ "root",
401
+ "head",
402
+ "role",
403
+ "approval_reference",
404
+ "expires_at",
405
+ "read",
406
+ "write",
407
+ "sensitive",
408
+ "commands",
409
+ "runtime_read",
410
+ "infrastructure",
411
+ "policy_base",
412
+ "sensitive_extra",
413
+ }
414
+ if (
415
+ not isinstance(d, dict)
416
+ or set(d) != fields
417
+ or type(d["version"]) is not int
418
+ or d["version"] != 3
419
+ ):
420
+ raise ValueError("Unsupported manifest fields/version")
421
+ if not isinstance(d["policy_base"], str) or not re.fullmatch(
422
+ r"[0-9a-f]{40}", d["policy_base"]
423
+ ):
424
+ raise ValueError("policy_base must be the full commit whose policy is trusted")
425
+ if not isinstance(d["sensitive_extra"], list) or not all(
426
+ isinstance(v, str) and v for v in d["sensitive_extra"]
427
+ ):
428
+ raise ValueError("sensitive_extra must list the project's sensitive patterns")
429
+ if (
430
+ d["role"] not in ("implementer", "reviewer")
431
+ or not isinstance(d["approval_reference"], str)
432
+ or not d["approval_reference"].strip()
433
+ ):
434
+ raise ValueError("Role and approval reference are required")
435
+ if (
436
+ type(d["expires_at"]) not in (float, int)
437
+ or not time.time() < d["expires_at"] <= time.time() + 8 * 3600
438
+ ):
439
+ raise ValueError("Task grants must expire within eight hours")
440
+ if d["commands"] != {} or d["runtime_read"] != []:
441
+ raise ValueError("Worker execution is unsupported; the coordinator runs quality gates")
442
+ if d["infrastructure"] != []:
443
+ raise ValueError("Infrastructure requires a separate task-specific user grant")
444
+ self.root = Path(d["root"]).resolve(strict=True)
445
+ if not self.root.is_dir() or str(self.root) != d["root"]:
446
+ raise ValueError("root must be a canonical directory")
447
+ if not isinstance(d["head"], str) or not re.fullmatch(r"[a-f0-9]{40}", d["head"]):
448
+ raise ValueError("A full Git head is required")
449
+ self.read = self.paths(d["read"], existing=True)
450
+ self.write = self.paths(d["write"], existing=False)
451
+ if d["role"] == "reviewer" and self.write:
452
+ raise ValueError("Reviewer grants cannot include writes")
453
+ # Ignored paths are invisible to diff inspection. Reviewers may read frozen
454
+ # evidence under .tmp/agent-reviews/; the broker probe uses one synthetic folder.
455
+ allowed_ignored = (".tmp/agent-reviews/",) if d["role"] == "reviewer" else ()
456
+ if probe_folder:
457
+ allowed_ignored += (probe_folder.rstrip("/") + "/",)
458
+ self.allowed_ignored = allowed_ignored
459
+ hidden = git_ignored(self.root, sorted(self.read | self.write))
460
+ if any(not v.startswith(allowed_ignored) for v in hidden):
461
+ raise ValueError("Git-ignored paths are forbidden; the diff cannot show them")
462
+ if (
463
+ not isinstance(d["sensitive"], list)
464
+ or not all(isinstance(v, str) for v in d["sensitive"])
465
+ or not set(d["sensitive"]) <= self.write
466
+ ):
467
+ raise ValueError("sensitive must list paths that are also approved writes")
468
+ self.sensitive = set(d["sensitive"])
469
+ patterns = sensitive_patterns(d["sensitive_extra"])
470
+ unmarked = [v for v in self.write if is_sensitive(v, patterns) and v not in self.sensitive]
471
+ if unmarked:
472
+ raise ValueError(
473
+ "Sensitive path not marked in the approved spec: " + ", ".join(sorted(unmarked))
474
+ )
475
+ self.inputs = json.loads((self.bundle / "inputs.json").read_text(encoding="utf-8")) if self.bundle else {}
476
+ self.mail: dict[str, dict[str, Any]] = {}
477
+ self.live()
478
+
479
+ def paths(self, values: Any, existing: bool) -> set[str]:
480
+ if (
481
+ not isinstance(values, list)
482
+ or not all(isinstance(v, str) for v in values)
483
+ or len(values) != len(set(values))
484
+ ):
485
+ raise ValueError("Paths must be a list of unique strings")
486
+ result = set()
487
+ for value in values:
488
+ relative(value, write=not existing)
489
+ p = self.root / value
490
+ if p.resolve() != p or not p.parent.is_dir():
491
+ raise ValueError("Path has a symlink or missing parent")
492
+ if p.exists():
493
+ info = p.stat()
494
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
495
+ raise ValueError("Only individual regular files with one link are supported")
496
+ elif existing:
497
+ raise ValueError("A declared input does not exist")
498
+ result.add(value)
499
+ return result
500
+
501
+ def live(self) -> None:
502
+ if digest(self.manifest) != self.sha or self.manifest.with_suffix(".revoked").exists():
503
+ raise ScopeEnded("Task authority changed or was revoked")
504
+ if time.time() >= self.data["expires_at"]:
505
+ raise ScopeEnded("Task grant expired")
506
+ try:
507
+ current = git_bytes(self.root, "rev-parse", "HEAD").decode().strip()
508
+ if current != self.data["head"]:
509
+ raise ScopeEnded("Checkout head changed")
510
+ if self.data["role"] == "reviewer":
511
+ git_bytes(
512
+ self.root, "diff", "--quiet", "--no-ext-diff", "--no-textconv", "HEAD", "--"
513
+ )
514
+ except subprocess.CalledProcessError as exc:
515
+ raise ScopeEnded("Reviewer requires a clean tracked checkout") from exc
516
+ # A granted .gitignore edit must not hide a later write from the diff.
517
+ if self.write and any(
518
+ not v.startswith(self.allowed_ignored)
519
+ for v in git_ignored(self.root, sorted(self.write))
520
+ ):
521
+ raise ScopeEnded("An approved write path became Git-ignored")
522
+
523
+ def open_file(self, value: str, write: bool = False) -> int:
524
+ self.live()
525
+ relative(value, write=write)
526
+ if value not in (self.write if write else self.read | self.write):
527
+ raise PermissionError("Path is outside the approved task scope")
528
+ if WINDOWS:
529
+ return self.open_file_windows(value, write)
530
+ fd = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
531
+ try:
532
+ parts = value.split("/")
533
+ for part in parts[:-1]:
534
+ child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
535
+ os.close(fd)
536
+ fd = child
537
+ flags = (os.O_WRONLY if write else os.O_RDONLY) | os.O_NOFOLLOW | os.O_NONBLOCK
538
+ try:
539
+ target = os.open(parts[-1], flags, dir_fd=fd)
540
+ except FileNotFoundError:
541
+ if not write:
542
+ raise
543
+ target = os.open(parts[-1], flags | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=fd)
544
+ info = os.fstat(target)
545
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
546
+ os.close(target)
547
+ raise PermissionError("Special file, symlink, or hardlink refused")
548
+ return target
549
+ finally:
550
+ os.close(fd)
551
+
552
+ def open_file_windows(self, value: str, write: bool) -> int:
553
+ """Windows has no dir_fd or O_NOFOLLOW. Refuse reparse points on the way in,
554
+ then trust only the path Windows reports for the handle actually opened, so a
555
+ swap between the checks and the open cannot redirect the read or write."""
556
+ expected = self.root.joinpath(*value.split("/"))
557
+ current = self.root
558
+ for part in value.split("/"):
559
+ current = current / part
560
+ try:
561
+ info = os.lstat(current)
562
+ except FileNotFoundError:
563
+ if not write or current != expected:
564
+ raise
565
+ break
566
+ if info.st_file_attributes & FILE_ATTRIBUTE_REPARSE_POINT:
567
+ raise PermissionError("Special file, symlink, or hardlink refused")
568
+ flags = (os.O_WRONLY if write else os.O_RDONLY) | os.O_BINARY | os.O_NOINHERIT
569
+ try:
570
+ target = os.open(expected, flags)
571
+ except FileNotFoundError:
572
+ if not write:
573
+ raise
574
+ target = os.open(expected, flags | os.O_CREAT | os.O_EXCL, 0o600)
575
+ try:
576
+ opened = final_path(target)
577
+ info = os.fstat(target)
578
+ except OSError:
579
+ os.close(target)
580
+ raise
581
+ if os.path.normcase(opened) != os.path.normcase(str(expected)):
582
+ os.close(target)
583
+ raise PermissionError("Special file, symlink, or hardlink refused")
584
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
585
+ os.close(target)
586
+ raise PermissionError("Special file, symlink, or hardlink refused")
587
+ return target
588
+
589
+ def read_bytes(self, value: str) -> bytes:
590
+ relative(value)
591
+ if value not in self.read | self.write:
592
+ raise PermissionError("Path is outside the approved task scope")
593
+ if self.data["role"] == "reviewer":
594
+ if not self.bundle or value not in self.inputs:
595
+ raise ValueError("Reviewer requires frozen inputs")
596
+ item = self.inputs[value]
597
+ name = item["file"]
598
+ if not re.fullmatch(r"[0-9]{4}\.bin", name):
599
+ raise ValueError("Invalid frozen input name")
600
+ data = (self.bundle / "inputs" / name).read_bytes()
601
+ if sha(data) != item["sha256"]:
602
+ raise ScopeEnded("Frozen review input changed")
603
+ else:
604
+ with os.fdopen(self.open_file(value), "rb") as f:
605
+ data = f.read(LIMIT + 1)
606
+ if len(data) > LIMIT:
607
+ raise ValueError("Input exceeds 2 MB; provide a smaller approved artifact")
608
+ return data
609
+
610
+ def own_dispatch(self, dispatch: Any, task: Any = None) -> dict[str, Any]:
611
+ handle = os.environ.get("ORCA_TERMINAL_HANDLE")
612
+ if (
613
+ not handle
614
+ or not isinstance(dispatch, str)
615
+ or not re.fullmatch(r"ctx_[a-z0-9]+", dispatch)
616
+ ):
617
+ raise ValueError("An Orca-owned terminal and valid dispatch are required")
618
+ state = orca("worker-show", "--dispatch", dispatch)
619
+ workspace = state.get("workspace")
620
+ if (
621
+ state.get("terminal") != handle
622
+ or not isinstance(workspace, str)
623
+ or not workspace.endswith("::" + str(self.root))
624
+ ):
625
+ raise PermissionError("Dispatch does not belong to this task terminal/workspace")
626
+ if task is not None and state.get("taskId") != task:
627
+ raise PermissionError("Task does not match the dispatch")
628
+ return state
629
+
630
+ def call(self, name: Any, arguments: Any) -> Any:
631
+ self.live()
632
+ if not isinstance(name, str) or not isinstance(arguments, dict):
633
+ raise ValueError("Tool name and argument object are required")
634
+ keys = set(arguments)
635
+ if name == "read_file" and {"path"} <= keys <= {"path", "offset", "limit"}:
636
+ text = self.read_bytes(arguments["path"]).decode("utf-8")
637
+ return chunk(text, arguments.get("offset", 0), arguments.get("limit", PAGE))
638
+ if name == "write_file" and keys == {"path", "content"}:
639
+ if not isinstance(arguments["content"], str):
640
+ raise ValueError("content must be UTF-8 text")
641
+ data = arguments["content"].encode()
642
+ if len(data) > LIMIT:
643
+ raise ValueError("Write exceeds 2 MB")
644
+ with os.fdopen(self.open_file(arguments["path"], True), "wb") as f:
645
+ f.truncate(0)
646
+ f.write(data)
647
+ return {"written": arguments["path"]}
648
+ if name == "request_scope" and keys == {"question"}:
649
+ if not os.environ.get("ORCA_TERMINAL_HANDLE") or not isinstance(
650
+ arguments["question"], str
651
+ ):
652
+ raise ValueError("Scope questions require an Orca terminal and text")
653
+ return orca(
654
+ "ask",
655
+ "--from",
656
+ os.environ["ORCA_TERMINAL_HANDLE"],
657
+ "--question",
658
+ arguments["question"],
659
+ )
660
+ if name == "mailbox" and {"dispatch_id"} <= keys <= {
661
+ "dispatch_id",
662
+ "message_id",
663
+ "offset",
664
+ "limit",
665
+ }:
666
+ self.own_dispatch(arguments["dispatch_id"])
667
+ message_id = arguments.get("message_id")
668
+ if message_id is None:
669
+ result = orca("check", "--terminal", os.environ["ORCA_TERMINAL_HANDLE"])
670
+ messages = result.get("messages", [])
671
+ if not isinstance(messages, list):
672
+ raise ValueError("Orca returned an invalid mailbox shape")
673
+ for message in messages:
674
+ if isinstance(message, dict) and isinstance(message.get("id"), str):
675
+ self.mail[message["id"]] = message
676
+ return {
677
+ "messages": [
678
+ {
679
+ "id": m["id"],
680
+ "type": m.get("type"),
681
+ "subject": m.get("subject"),
682
+ "body_chars": len(str(m.get("body", ""))),
683
+ }
684
+ for m in self.mail.values()
685
+ ]
686
+ }
687
+ if not isinstance(message_id, str) or message_id not in self.mail:
688
+ raise PermissionError("Message is not in this dispatch mailbox cache")
689
+ return chunk(
690
+ str(self.mail[message_id].get("body", "")),
691
+ arguments.get("offset", 0),
692
+ arguments.get("limit", PAGE),
693
+ )
694
+ if name == "report" and keys == {"outcome", "body", "task_id", "dispatch_id"}:
695
+ if arguments["outcome"] not in ("succeeded", "failed") or not all(
696
+ isinstance(arguments[k], str) for k in ("body", "task_id", "dispatch_id")
697
+ ):
698
+ raise ValueError("Invalid report")
699
+ self.own_dispatch(arguments["dispatch_id"], arguments["task_id"])
700
+ # Revoke once a send is attempted, even if its receipt is malformed,
701
+ # so a worker cannot retry into a duplicate report.
702
+ try:
703
+ return orca(
704
+ "send",
705
+ "--type",
706
+ "worker_done",
707
+ "--subject",
708
+ "Scoped worker report",
709
+ "--outcome",
710
+ arguments["outcome"],
711
+ "--body",
712
+ arguments["body"],
713
+ "--task-id",
714
+ arguments["task_id"],
715
+ "--dispatch-id",
716
+ arguments["dispatch_id"],
717
+ )
718
+ finally:
719
+ self.manifest.with_suffix(".revoked").touch()
720
+ raise PermissionError("Tool or argument shape is outside the approved interface")
721
+
722
+
723
+ def tools(scope: Scope) -> list[dict[str, Any]]:
724
+ def tool(
725
+ name: str, description: str, fields: dict[str, Any], required: list[str] | None = None
726
+ ) -> dict[str, Any]:
727
+ return {
728
+ "name": name,
729
+ "description": description,
730
+ "inputSchema": {
731
+ "type": "object",
732
+ "properties": fields,
733
+ "required": list(fields) if required is None else required,
734
+ "additionalProperties": False,
735
+ },
736
+ }
737
+
738
+ string = {"type": "string"}
739
+ pages = {
740
+ "offset": {"type": "integer", "minimum": 0},
741
+ "limit": {"type": "integer", "minimum": 1, "maximum": 12000},
742
+ }
743
+ result = [
744
+ tool(
745
+ "read_file",
746
+ "Read an approved file in bounded pages; follow next_offset until null.",
747
+ {"path": string, **pages},
748
+ ["path"],
749
+ ),
750
+ tool(
751
+ "request_scope",
752
+ "Ask the coordinator. End your turn; on wake use mailbox. This grants no access.",
753
+ {"question": string},
754
+ ),
755
+ tool(
756
+ "mailbox",
757
+ "Read only your dispatch mail on Orca wake. Fetch IDs, then page bodies by message_id; never poll.",
758
+ {"dispatch_id": string, "message_id": string, **pages},
759
+ ["dispatch_id"],
760
+ ),
761
+ tool(
762
+ "report",
763
+ "Complete this exact task/dispatch through Orca; revokes access and closes the scoped client.",
764
+ {
765
+ "outcome": {"enum": ["succeeded", "failed"]},
766
+ "body": string,
767
+ "task_id": string,
768
+ "dispatch_id": string,
769
+ },
770
+ ),
771
+ ]
772
+ if scope.write:
773
+ result.append(
774
+ tool(
775
+ "write_file",
776
+ "Write one approved UTF-8 file; no execution or directory operations.",
777
+ {"path": string, "content": string},
778
+ )
779
+ )
780
+ return result
781
+
782
+
783
+ def serve(scope: Scope) -> None:
784
+ def error(code: int, message: str, request_id: Any = None) -> dict[str, Any]:
785
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
786
+
787
+ while True:
788
+ raw = sys.stdin.buffer.readline(LIMIT + 1)
789
+ if not raw:
790
+ return
791
+ if len(raw) > LIMIT:
792
+ while raw and not raw.endswith(b"\n"):
793
+ raw = sys.stdin.buffer.readline(LIMIT + 1)
794
+ print(json.dumps(error(-32600, "Request exceeds 2 MB")), flush=True)
795
+ continue
796
+ try:
797
+ request = json.loads(raw)
798
+ except (ValueError, UnicodeError, RecursionError):
799
+ print(json.dumps(error(-32700, "Invalid JSON")), flush=True)
800
+ continue
801
+ if (
802
+ not isinstance(request, dict)
803
+ or request.get("jsonrpc") != "2.0"
804
+ or not isinstance(request.get("method"), str)
805
+ ):
806
+ print(json.dumps(error(-32600, "Invalid request")), flush=True)
807
+ continue
808
+ if "id" not in request:
809
+ continue
810
+ request_id = request["id"]
811
+ if request_id is not None and type(request_id) not in (str, int):
812
+ print(json.dumps(error(-32600, "Invalid request ID")), flush=True)
813
+ continue
814
+ response: dict[str, Any] = {"jsonrpc": "2.0", "id": request_id}
815
+ try:
816
+ scope.live()
817
+ method, params = request["method"], request.get("params", {})
818
+ if not isinstance(params, dict):
819
+ raise ValueError("params must be an object")
820
+ if method == "initialize":
821
+ version = params.get("protocolVersion")
822
+ if not isinstance(version, str):
823
+ raise ValueError("protocolVersion must be text")
824
+ result = {
825
+ "protocolVersion": version,
826
+ "capabilities": {"tools": {}},
827
+ "serverInfo": {"name": "orca-task-scope", "version": "2.0.0"},
828
+ }
829
+ elif method == "tools/list":
830
+ result = {"tools": tools(scope)}
831
+ elif method == "tools/call":
832
+ try:
833
+ output = scope.call(params.get("name"), params.get("arguments", {}))
834
+ result = {
835
+ "content": [
836
+ {"type": "text", "text": json.dumps(output, ensure_ascii=False)}
837
+ ]
838
+ }
839
+ except ScopeEnded:
840
+ raise
841
+ except Exception as exc: # one bad request must not end the broker loop
842
+ result = {"isError": True, "content": [{"type": "text", "text": str(exc)}]}
843
+ elif method == "ping":
844
+ result = {}
845
+ else:
846
+ raise ValueError("Unsupported MCP method")
847
+ response["result"] = result
848
+ except ScopeEnded as exc:
849
+ scope.manifest.with_suffix(".revoked").touch()
850
+ response = error(-32602, str(exc), request_id)
851
+ except Exception as exc: # one bad request must not end the broker loop
852
+ response = error(-32602, str(exc), request_id)
853
+ print(json.dumps(response), flush=True)
854
+
855
+
856
+ def require_supported_harness(harness: str | None) -> None:
857
+ if harness != "claude":
858
+ raise ValueError(
859
+ "Only scoped Claude workers are enabled; Codex native capability scope remains unverified"
860
+ )
861
+
862
+
863
+ def enabled_profile(policy: dict[str, Any], role: str, agent: str, model: str | None) -> bool:
864
+ """An exact, enabled role profile from the trusted policy; no aliases or fallbacks."""
865
+ profiles = policy.get("roles", {}).get(role) if policy.get("version") == 2 else None
866
+ return isinstance(profiles, list) and any(
867
+ isinstance(p, dict)
868
+ and p.get("agent") == agent
869
+ and p.get("model") == model
870
+ and p.get("enabled") is True
871
+ for p in profiles
872
+ )
873
+
874
+
875
+ def validate_model(role: str, model: str | None, policy: dict[str, Any]) -> None:
876
+ if (
877
+ not model
878
+ or not re.fullmatch(r"claude-[a-z0-9][a-z0-9._-]*", model)
879
+ or not enabled_profile(policy, role, "claude", model)
880
+ ):
881
+ raise ValueError(
882
+ "Model is not an enabled exact role profile; aliases/fallbacks are forbidden"
883
+ )
884
+
885
+
886
+ def prepare(
887
+ scope: Scope, bundle: Path, model: str | None, policy_path: Path | None = None
888
+ ) -> None:
889
+ if policy_path is None:
890
+ # The committed policy at the manifest's trusted base, never the working tree.
891
+ _, config = base_config(scope.root, scope.data["policy_base"])
892
+ else:
893
+ config = load_config(policy_path.read_bytes())
894
+ policy = roles_policy(config)
895
+ validate_model(scope.data["role"], model, policy)
896
+ bundle = bundle.resolve()
897
+ if bundle.exists() or bundle.is_relative_to(scope.root):
898
+ raise ValueError("Bundle must be a new coordinator-owned directory outside the checkout")
899
+ binaries = {}
900
+ claude = claude_executable(scope.root)
901
+ for name, candidate in [("claude", claude), ("python", sys.executable)]:
902
+ if not candidate:
903
+ raise ValueError("Required client executable is unavailable")
904
+ path = Path(candidate).resolve(strict=True)
905
+ binaries[name] = {"path": str(path), "sha256": digest(path)}
906
+ bundle.mkdir(parents=True, mode=0o700)
907
+ (bundle / "work").mkdir(mode=0o700)
908
+ (bundle / "inputs").mkdir(mode=0o700)
909
+ shutil.copyfile(SELF, bundle / "task_scope.py")
910
+ shutil.copyfile(scope.manifest, bundle / "manifest.json")
911
+ atomic_json(bundle / "orchestration.json", policy)
912
+ shutil.copyfile(SENSITIVE_FILE, bundle / "sensitive.json")
913
+ index = {}
914
+ if scope.data["role"] == "reviewer":
915
+ for i, path in enumerate(sorted(scope.read)):
916
+ if path.startswith(".tmp/"):
917
+ with os.fdopen(scope.open_file(path), "rb") as f:
918
+ data = f.read(LIMIT + 1)
919
+ else:
920
+ data = git_bytes(scope.root, "cat-file", "blob", scope.data["head"] + ":" + path)
921
+ if len(data) > LIMIT:
922
+ raise ValueError("Review input exceeds 2 MB")
923
+ name = f"{i:04}.bin"
924
+ (bundle / "inputs" / name).write_bytes(data)
925
+ index[path] = {"file": name, "sha256": sha(data), "head": scope.data["head"]}
926
+ scope.live()
927
+ atomic_json(bundle / "inputs.json", index)
928
+ atomic_json(bundle / "executables.json", binaries)
929
+ atomic_json(
930
+ bundle / "mcp.json",
931
+ {
932
+ "mcpServers": {
933
+ "task": {
934
+ "command": binaries["python"]["path"],
935
+ "args": [
936
+ "-I",
937
+ str(bundle / "task_scope.py"),
938
+ "serve",
939
+ "--manifest",
940
+ str(bundle / "manifest.json"),
941
+ "--bundle",
942
+ str(bundle),
943
+ ],
944
+ }
945
+ }
946
+ },
947
+ )
948
+ atomic_json(
949
+ bundle / "settings.json",
950
+ {
951
+ "autoMemoryEnabled": False,
952
+ "claudeMdExcludes": ["/**"],
953
+ "pluginConfigs": {
954
+ "cc-plugin-agents-md@builtin": {"options": {"instructionFiles": "managed-only"}}
955
+ },
956
+ },
957
+ )
958
+ argv = [
959
+ binaries["claude"]["path"],
960
+ "--restricted",
961
+ "--disable-slash-commands",
962
+ "--tools",
963
+ "",
964
+ "--strict-mcp-config",
965
+ "--mcp-config",
966
+ str(bundle / "mcp.json"),
967
+ "--setting-sources",
968
+ "",
969
+ "--permission-mode",
970
+ "manual",
971
+ "--settings",
972
+ str(bundle / "settings.json"),
973
+ "--model",
974
+ model,
975
+ "--allowedTools",
976
+ ]
977
+ argv += ["mcp__task__" + t["name"] for t in tools(scope)]
978
+ atomic_json(bundle / "claude-argv.json", argv)
979
+
980
+
981
+ def bundle_files(bundle: Path) -> set[str]:
982
+ files = {
983
+ "manifest.json",
984
+ "task_scope.py",
985
+ "orchestration.json",
986
+ "sensitive.json",
987
+ "inputs.json",
988
+ "executables.json",
989
+ "mcp.json",
990
+ "settings.json",
991
+ "claude-argv.json",
992
+ }
993
+ inputs = json.loads((bundle / "inputs.json").read_text(encoding="utf-8"))
994
+ for item in inputs.values():
995
+ name = item["file"]
996
+ if not re.fullmatch(r"[0-9]{4}\.bin", name):
997
+ raise ValueError("Invalid frozen input name")
998
+ files.add("inputs/" + name)
999
+ return files
1000
+
1001
+
1002
+ def verify_bundle(bundle: Path, scope: Scope) -> list[str]:
1003
+ receipt = json.loads((bundle / "probe.json").read_text(encoding="utf-8"))
1004
+ hashes = receipt.get("bundle_hashes")
1005
+ if receipt.get("passed") is not True or receipt.get("manifest_sha256") != scope.sha:
1006
+ raise ValueError("Missing or stale probe receipt")
1007
+ if not isinstance(hashes, dict) or set(hashes) != bundle_files(bundle):
1008
+ raise ValueError("Incomplete launch/input hash coverage")
1009
+ for name, expected in hashes.items():
1010
+ if digest(bundle / name) != expected:
1011
+ raise ValueError("Bundle changed after probing")
1012
+ if SELF != bundle / "task_scope.py":
1013
+ raise ValueError("Launch must use the frozen adapter")
1014
+ executables = json.loads((bundle / "executables.json").read_text(encoding="utf-8"))
1015
+ for item in executables.values():
1016
+ path = Path(item["path"])
1017
+ if path.resolve(strict=True) != path or digest(path) != item["sha256"]:
1018
+ raise ValueError("Pinned client/interpreter executable changed")
1019
+ argv = json.loads((bundle / "claude-argv.json").read_text(encoding="utf-8"))
1020
+ if argv[0] != executables["claude"]["path"]:
1021
+ raise ValueError("Client argv does not use the pinned executable")
1022
+ return argv
1023
+
1024
+
1025
+ def probe(scope: Scope, bundle: Path) -> dict[str, Any]:
1026
+ """Test the actual file broker using only fresh synthetic checkout fixtures."""
1027
+ scope.live()
1028
+ scratch = scope.root / ".tmp"
1029
+ if scratch.resolve() != scratch:
1030
+ raise ValueError("Probe scratch path must not be a symlink")
1031
+ scratch.mkdir(exist_ok=True)
1032
+ checks = []
1033
+ with tempfile.TemporaryDirectory(dir=scratch, prefix="scope-probe-") as tmp:
1034
+ folder = Path(tmp)
1035
+ allowed = folder / "read.txt"
1036
+ writable = folder / "write.txt"
1037
+ denied = folder / "denied.txt"
1038
+ allowed.write_text("approved input", encoding="utf-8", newline="\n")
1039
+ writable.write_text("before", encoding="utf-8", newline="\n")
1040
+ denied.write_text("synthetic private", encoding="utf-8", newline="\n")
1041
+ names = [p.relative_to(scope.root).as_posix() for p in (allowed, writable, denied)]
1042
+ data = {
1043
+ **scope.data,
1044
+ "role": "implementer",
1045
+ "read": [names[0]],
1046
+ "write": [names[1]],
1047
+ "sensitive": [],
1048
+ }
1049
+ manifest = folder / "probe.json"
1050
+ atomic_json(manifest, data)
1051
+ fixture = Scope(manifest, probe_folder=folder.relative_to(scope.root).as_posix())
1052
+ if fixture.call("read_file", {"path": names[0]})["text"] != "approved input":
1053
+ raise ValueError("Approved read failed")
1054
+ checks.append("approved_read")
1055
+ fixture.call("write_file", {"path": names[1], "content": "after"})
1056
+ if writable.read_text(encoding="utf-8") != "after":
1057
+ raise ValueError("Approved write failed")
1058
+ checks.append("approved_write")
1059
+ for check, tool, args in [
1060
+ ("denied_unlisted_sibling_read", "read_file", {"path": names[2]}),
1061
+ ("denied_read_only_write", "write_file", {"path": names[0], "content": "bad"}),
1062
+ ("denied_traversal", "read_file", {"path": "../outside"}),
1063
+ ("denied_execution", "run_check", {"id": "unapproved"}),
1064
+ ]:
1065
+ try:
1066
+ fixture.call(tool, args)
1067
+ except (ValueError, PermissionError):
1068
+ checks.append(check)
1069
+ else:
1070
+ raise ValueError("Broker allowed an unapproved operation")
1071
+ if allowed.read_text(encoding="utf-8") != "approved input" or denied.read_text(encoding="utf-8") != "synthetic private":
1072
+ raise ValueError("Negative probe changed a protected fixture")
1073
+ scope.live()
1074
+ return {
1075
+ "passed": True,
1076
+ "manifest_sha256": scope.sha,
1077
+ "checked_at": time.time(),
1078
+ "checks": checks,
1079
+ "bundle_hashes": {name: digest(bundle / name) for name in bundle_files(bundle)},
1080
+ }
1081
+
1082
+
1083
+ def controller_status(bundle: Path) -> dict[str, Any]:
1084
+ path = bundle / "controller.json"
1085
+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"state": "not_started"}
1086
+
1087
+
1088
+ def kill_on_close_job(process: subprocess.Popen) -> Any:
1089
+ """Windows: tie the client and the broker it starts to a job that dies with this
1090
+ supervisor. Cleanup only; a stray broker still refuses calls once revoked."""
1091
+ import ctypes
1092
+ from ctypes import wintypes
1093
+
1094
+ class Basic(ctypes.Structure):
1095
+ _fields_ = [
1096
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
1097
+ ("PerJobUserTimeLimit", ctypes.c_int64),
1098
+ ("LimitFlags", wintypes.DWORD),
1099
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
1100
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
1101
+ ("ActiveProcessLimit", wintypes.DWORD),
1102
+ ("Affinity", ctypes.c_size_t),
1103
+ ("PriorityClass", wintypes.DWORD),
1104
+ ("SchedulingClass", wintypes.DWORD),
1105
+ ]
1106
+
1107
+ class Extended(ctypes.Structure):
1108
+ _fields_ = [
1109
+ ("BasicLimitInformation", Basic),
1110
+ ("IoInfo", ctypes.c_uint64 * 6),
1111
+ ("ProcessMemoryLimit", ctypes.c_size_t),
1112
+ ("JobMemoryLimit", ctypes.c_size_t),
1113
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
1114
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
1115
+ ]
1116
+
1117
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
1118
+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE
1119
+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
1120
+ kernel32.SetInformationJobObject.argtypes = [
1121
+ wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD
1122
+ ]
1123
+ kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
1124
+ job = kernel32.CreateJobObjectW(None, None)
1125
+ if not job:
1126
+ raise OSError(ctypes.get_last_error(), "Could not create a job object")
1127
+ limits = Extended()
1128
+ limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
1129
+ if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)):
1130
+ raise OSError(ctypes.get_last_error(), "Could not configure the job object")
1131
+ if not kernel32.AssignProcessToJobObject(job, int(process._handle)):
1132
+ raise OSError(ctypes.get_last_error(), "Could not assign the client to its job")
1133
+ return job
1134
+
1135
+
1136
+ def close_job(job: Any) -> None:
1137
+ import ctypes
1138
+
1139
+ ctypes.WinDLL("kernel32").CloseHandle(job)
1140
+
1141
+
1142
+ def supervise(bundle: Path, scope: Scope, argv: list[str]) -> int:
1143
+ """Own precisely one newly created client; never adopt or signal other PIDs."""
1144
+ scope.live()
1145
+ process = subprocess.Popen(argv, cwd=bundle / "work")
1146
+ job = None
1147
+ if WINDOWS:
1148
+ try:
1149
+ job = kill_on_close_job(process)
1150
+ except OSError:
1151
+ process.kill()
1152
+ process.wait()
1153
+ raise
1154
+ state = {
1155
+ "state": "running",
1156
+ "pid": process.pid,
1157
+ "bundle": str(bundle),
1158
+ "manifest_sha256": scope.sha,
1159
+ "head": scope.data["head"],
1160
+ "terminal": os.environ.get("ORCA_TERMINAL_HANDLE"),
1161
+ "started_at": time.time(),
1162
+ }
1163
+ atomic_json(bundle / "controller.json", state)
1164
+ reason = "client_exit"
1165
+ try:
1166
+ while process.poll() is None:
1167
+ marker = scope.manifest.with_suffix(".revoked")
1168
+ if (
1169
+ marker.exists()
1170
+ or digest(scope.manifest) != scope.sha
1171
+ or time.time() >= scope.data["expires_at"]
1172
+ ):
1173
+ reason = "grant_ended"
1174
+ marker.touch()
1175
+ process.terminate()
1176
+ try:
1177
+ process.wait(timeout=5)
1178
+ except subprocess.TimeoutExpired:
1179
+ process.kill()
1180
+ break
1181
+ try:
1182
+ process.wait(timeout=0.2)
1183
+ except subprocess.TimeoutExpired:
1184
+ pass
1185
+ finally:
1186
+ if process.poll() is None:
1187
+ process.terminate()
1188
+ try:
1189
+ process.wait(timeout=5)
1190
+ except subprocess.TimeoutExpired:
1191
+ process.kill()
1192
+ result = process.wait()
1193
+ if job is not None:
1194
+ close_job(job) # ends any broker child the client left behind
1195
+ scope.manifest.with_suffix(".revoked").touch()
1196
+ atomic_json(
1197
+ bundle / "controller.json",
1198
+ {
1199
+ **state,
1200
+ "state": "exited",
1201
+ "returncode": result,
1202
+ "ended_at": time.time(),
1203
+ "reason": reason,
1204
+ },
1205
+ )
1206
+ return result
1207
+
1208
+
1209
+ def main() -> None:
1210
+ parser = argparse.ArgumentParser(description=__doc__)
1211
+ parser.add_argument(
1212
+ "action", choices=["serve", "validate", "prepare", "probe", "launch", "revoke", "status"]
1213
+ )
1214
+ parser.add_argument("--manifest", type=Path)
1215
+ parser.add_argument("--bundle", type=Path)
1216
+ parser.add_argument("--model")
1217
+ parser.add_argument("--policy", type=Path)
1218
+ parser.add_argument("--harness", choices=["claude", "codex"])
1219
+ args = parser.parse_args()
1220
+ bundle = args.bundle.resolve() if args.bundle else None
1221
+ if args.action in ("revoke", "status"):
1222
+ if not bundle or not (bundle / "manifest.json").is_file():
1223
+ parser.error("revoke/status requires a prepared --bundle")
1224
+ if args.action == "revoke":
1225
+ (bundle / "manifest.revoked").touch()
1226
+ print(json.dumps(controller_status(bundle)))
1227
+ return
1228
+ if not args.manifest:
1229
+ parser.error("--manifest is required")
1230
+ if args.action in ("prepare", "launch"):
1231
+ require_supported_harness(args.harness)
1232
+ scope = Scope(args.manifest, bundle if args.action in ("serve", "probe", "launch") else None)
1233
+ if args.action == "serve":
1234
+ serve(scope)
1235
+ elif args.action == "validate":
1236
+ print(json.dumps({"valid": True, "manifest_sha256": scope.sha}))
1237
+ elif args.action == "prepare":
1238
+ if not bundle:
1239
+ parser.error("prepare requires --bundle")
1240
+ prepare(scope, bundle, args.model, args.policy)
1241
+ print(json.dumps({"bundle": str(bundle), "status": "prepared_not_probed"}))
1242
+ elif args.action == "probe":
1243
+ if not bundle:
1244
+ parser.error("probe requires --bundle")
1245
+ receipt = probe(scope, bundle)
1246
+ atomic_json(bundle / "probe.json", receipt)
1247
+ print(json.dumps(receipt))
1248
+ elif args.action == "launch":
1249
+ if not bundle or scope.manifest != bundle / "manifest.json":
1250
+ parser.error("launch requires the frozen bundle manifest")
1251
+ argv = verify_bundle(bundle, scope)
1252
+ raise SystemExit(supervise(bundle, scope, argv))
1253
+
1254
+
1255
+ if __name__ == "__main__":
1256
+ main()