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,263 @@
1
+ #!/usr/bin/env python3
2
+ """Run coordinator checks in a disposable local container from a trusted Git ref."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import io
9
+ import json
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tarfile
16
+ import tempfile
17
+ import uuid
18
+ from pathlib import Path
19
+
20
+ from orca_agent_workflow import task_scope
21
+
22
+ DOCKER = "docker" # an absolute path on Windows; see main()
23
+
24
+
25
+ def git(root: Path, *args: str) -> bytes:
26
+ return task_scope.git_bytes(root, *args)
27
+
28
+
29
+ DEFAULT_DOCKERFILE = Path(__file__).resolve().parent / "gate.Dockerfile"
30
+
31
+
32
+ def default_dockerfile(root: Path, commit: str) -> bytes:
33
+ """The runtime's own image: from the trusted ref when the runtime is in the checkout
34
+ (the kit's source or a vendored copy), so a branch cannot supply its own image."""
35
+ packaged = DEFAULT_DOCKERFILE.resolve()
36
+ if packaged.is_relative_to(root.resolve()):
37
+ relative = packaged.relative_to(root.resolve()).as_posix()
38
+ return git(root, "show", f"{commit}:{relative}")
39
+ return packaged.read_bytes()
40
+
41
+
42
+ def trusted_config(root: Path, ref: str) -> tuple[dict, dict[str, bytes]]:
43
+ # Freeze ref to a full commit before reading config, Dockerfile or inputs.
44
+ commit = git(root, "rev-parse", "--verify", ref + "^{commit}").decode().strip()
45
+ config_data, workflow = task_scope.base_config(root, commit)
46
+ config = dict(workflow.get("gates") or {})
47
+ inputs = config.get("inputs", [])
48
+ if not isinstance(inputs, list):
49
+ raise ValueError("Unsupported gate configuration")
50
+ files = {task_scope.CONFIG: config_data}
51
+ if config.get("dockerfile") is None:
52
+ # The pinned runtime's standard-library image; a project names its own to change it.
53
+ if "Dockerfile" in inputs:
54
+ raise ValueError("Name the project's Dockerfile in gates.dockerfile")
55
+ config["dockerfile"] = "Dockerfile"
56
+ files["Dockerfile"] = default_dockerfile(root, commit)
57
+ paths = list(inputs)
58
+ else:
59
+ paths = [config["dockerfile"], *inputs]
60
+ if len(paths) != len(set(paths)):
61
+ raise ValueError("Gate build inputs must be unique")
62
+ for path in paths:
63
+ task_scope.relative(path)
64
+ files[path] = git(root, "show", commit + ":" + path)
65
+ timeout = config.get("timeout_seconds", 900)
66
+ if type(timeout) is not int or not 1 <= timeout <= 3600:
67
+ raise ValueError("Gate timeout must be an integer from 1 to 3600 seconds")
68
+ if not re.fullmatch(r"[1-9][0-9]*[mg]", config.get("memory", "2g")):
69
+ raise ValueError("Gate memory must be a positive m/g limit")
70
+ return config, files
71
+
72
+
73
+ def default_ref(root: Path) -> str:
74
+ """The remote's default branch: reviewed build inputs, never the branch under test."""
75
+ try:
76
+ ref = git(root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD").decode().strip()
77
+ except subprocess.CalledProcessError as exc:
78
+ raise ValueError(
79
+ "Could not find origin's default branch; pass --ref with the reviewed branch"
80
+ ) from exc
81
+ return ref
82
+
83
+
84
+ def index_modes(root: Path) -> dict[str, int]:
85
+ """Executable bits as Git records them; Windows working trees do not carry them."""
86
+ modes = {}
87
+ for entry in git(root, "ls-files", "-s", "-z").split(b"\0"):
88
+ if entry:
89
+ meta, name = entry.split(b"\t", 1)
90
+ modes[name.decode()] = 0o755 if meta.startswith(b"100755") else 0o644
91
+ return modes
92
+
93
+
94
+ def checkout_archive(root: Path) -> bytes:
95
+ """Copy only selected regular checkout files; omit metadata and credentials."""
96
+ names = git(root, "ls-files", "-z", "-c", "-o", "--exclude-standard").split(b"\0")
97
+ modes = index_modes(root)
98
+ stream = io.BytesIO()
99
+ with tarfile.open(fileobj=stream, mode="w") as archive:
100
+ for raw in sorted(set(names)):
101
+ if not raw:
102
+ continue
103
+ name = raw.decode()
104
+ try:
105
+ task_scope.relative(name)
106
+ except ValueError:
107
+ continue # credential-shaped paths and local data roots are omitted
108
+ path = root / name
109
+ if not path.exists() and not path.is_symlink():
110
+ continue
111
+ if path.resolve() != path or not path.is_file():
112
+ raise ValueError(f"Gate snapshots support regular files only: {name}")
113
+ info = archive.gettarinfo(path, arcname=name)
114
+ if name in modes:
115
+ info.mode = modes[name]
116
+ elif task_scope.WINDOWS:
117
+ info.mode = 0o644 # untracked and no executable bit to read
118
+ with path.open("rb") as data:
119
+ archive.addfile(info, data)
120
+ return stream.getvalue()
121
+
122
+
123
+ def ensure_local_docker() -> None:
124
+ host = os.environ.get("DOCKER_HOST")
125
+ if host and not host.startswith(("unix://", "npipe://")):
126
+ raise ValueError("This starter runs gates only on a local Docker endpoint")
127
+ result = subprocess.run(
128
+ [DOCKER, "context", "inspect"], capture_output=True, text=True, check=True
129
+ )
130
+ contexts = json.loads(result.stdout)
131
+ endpoint = contexts[0]["Endpoints"]["docker"]["Host"]
132
+ if not endpoint.startswith(("unix://", "npipe://")):
133
+ raise ValueError("This starter runs gates only on a local Docker endpoint")
134
+
135
+
136
+ def run_gate(tag: str, snapshot: bytes, command: str, config: dict) -> None:
137
+ name = "orca-gate-" + uuid.uuid4().hex
138
+ args = [
139
+ DOCKER,
140
+ "run",
141
+ "--rm",
142
+ "-i",
143
+ "--name",
144
+ name,
145
+ "--network",
146
+ "none",
147
+ "--cap-drop",
148
+ "ALL",
149
+ "--security-opt",
150
+ "no-new-privileges",
151
+ "--read-only",
152
+ "--user",
153
+ "10001:10001",
154
+ "--memory",
155
+ config.get("memory", "2g"),
156
+ "--pids-limit",
157
+ "256",
158
+ "--cpus",
159
+ "2",
160
+ "--tmpfs",
161
+ "/work:rw,nosuid,nodev,size=512m,uid=10001,gid=10001",
162
+ "--tmpfs",
163
+ "/tmp:rw,nosuid,nodev,size=256m,mode=1777",
164
+ tag,
165
+ "sh",
166
+ "-c",
167
+ 'tar --no-same-owner -xf - -C /work && cd /work && exec sh -c "$1"',
168
+ "sh",
169
+ command,
170
+ ]
171
+ try:
172
+ result = subprocess.run(args, input=snapshot, timeout=config.get("timeout_seconds", 900))
173
+ if result.returncode:
174
+ raise ValueError(f"Gate exited {result.returncode}: {command}")
175
+ finally:
176
+ # Exact unique owned name only; never prune containers or kill by process name.
177
+ subprocess.run(
178
+ [DOCKER, "rm", "--force", name],
179
+ stdout=subprocess.DEVNULL,
180
+ stderr=subprocess.DEVNULL,
181
+ check=False,
182
+ )
183
+
184
+
185
+ def main() -> int:
186
+ parser = argparse.ArgumentParser(description=__doc__)
187
+ parser.add_argument(
188
+ "--ref",
189
+ default=os.environ.get("GATE_DEPS_REF"),
190
+ help="Reviewed ref for gate build inputs (default: origin's default branch)",
191
+ )
192
+ parser.add_argument("--self-test", action="store_true")
193
+ parser.add_argument("commands", nargs="*")
194
+ args = parser.parse_args()
195
+ try:
196
+ root = Path(
197
+ subprocess.check_output(
198
+ [task_scope.git_executable(), "rev-parse", "--show-toplevel"], text=True
199
+ ).strip()
200
+ ).resolve()
201
+ global DOCKER
202
+ if task_scope.WINDOWS:
203
+ # Never the checkout's own docker.exe, which bare-name lookup would find first.
204
+ try:
205
+ DOCKER = task_scope.host_executable("docker", root)
206
+ except FileNotFoundError:
207
+ raise ValueError("docker.exe was not found on PATH; install Docker Desktop")
208
+ elif not shutil.which("docker"):
209
+ raise ValueError("docker was not found on PATH; install and start Docker Desktop")
210
+ ensure_local_docker()
211
+ config, files = trusted_config(root, args.ref or default_ref(root))
212
+ digest = hashlib.sha256()
213
+ for path, data in sorted(files.items()):
214
+ digest.update(path.encode() + b"\0" + data)
215
+ tag = "orca-workflow-gates:" + digest.hexdigest()[:20]
216
+ if subprocess.run(
217
+ [DOCKER, "image", "inspect", tag],
218
+ stdout=subprocess.DEVNULL,
219
+ stderr=subprocess.DEVNULL,
220
+ check=False,
221
+ ).returncode:
222
+ with tempfile.TemporaryDirectory(prefix="orca-gate-build-") as directory:
223
+ context = Path(directory)
224
+ for path, data in files.items():
225
+ destination = context / path
226
+ destination.parent.mkdir(parents=True, exist_ok=True)
227
+ destination.write_bytes(data)
228
+ print("Building trusted gate image; this build step uses network.", flush=True)
229
+ subprocess.run(
230
+ [
231
+ DOCKER,
232
+ "build",
233
+ "-f",
234
+ str(context / config["dockerfile"]),
235
+ "-t",
236
+ tag,
237
+ str(context),
238
+ ],
239
+ check=True,
240
+ timeout=900,
241
+ )
242
+ snapshot = checkout_archive(root)
243
+ if args.self_test:
244
+ tests = [
245
+ "python -c 'import sys; assert sys.flags.safe_path; print(\"safe import path: PASS\")'",
246
+ 'python -c \'import socket; s=socket.socket(); s.settimeout(2); r=s.connect_ex(("1.1.1.1",53)); s.close(); assert r != 0; print("network denial: PASS")\'',
247
+ 'python -c \'import os,re; assert not [k for k in os.environ if re.search("token|secret|password|api_key|aws_|anthropic|openai",k,re.I)]; print("credential environment: PASS")\'',
248
+ ]
249
+ for command in tests:
250
+ run_gate(tag, snapshot, command, config)
251
+ print("Gate self-test: PASS", flush=True)
252
+ if not args.commands and not args.self_test:
253
+ raise ValueError("Provide at least one check or --self-test")
254
+ for command in args.commands:
255
+ print("Gate:", command, flush=True)
256
+ run_gate(tag, snapshot, command, config)
257
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as exc:
258
+ parser.exit(1, f"gate-sandbox: {exc}\n")
259
+ return 0
260
+
261
+
262
+ if __name__ == "__main__":
263
+ raise SystemExit(main())
@@ -0,0 +1,19 @@
1
+ {
2
+ "comment": "Gate, build and deploy inputs. Workers may write these only when the approved spec lists them under Sensitive files and the manifest marks them sensitive; the reviewer must examine each one. Patterns without a slash match the file name; patterns with a slash match the whole path. A missing name means 'not highlighted', not 'uncontrolled'.",
3
+ "patterns": [
4
+ "makefile", "gnumakefile",
5
+ "pyproject.toml", "uv.lock", "uv.toml", ".python-version", ".python-versions",
6
+ "setup.cfg", "tox.ini", "noxfile.py", ".pre-commit-config.yaml",
7
+ ".flake8", "pytest.ini", ".pytest.ini", "pytest.toml", ".pytest.toml",
8
+ "mypy.ini", ".mypy.ini", "ruff.toml", ".ruff.toml", ".isort.cfg", ".editorconfig", ".coveragerc",
9
+ "conftest.py", "sitecustomize.py", "usercustomize.py",
10
+ ".gitignore", ".gitattributes", ".gitconfig",
11
+ "dockerfile*", "containerfile*", "*.dockerfile", "*.containerfile",
12
+ "docker-compose*.yml", "docker-compose*.yaml", "compose*.yml", "compose*.yaml", ".dockerignore",
13
+ "fly*.toml", "fly*/*.toml", "deploy/*", "vercel.json", "*.sha256",
14
+ "package.json", "package-lock.json", "next.config.*", "eslint.config.*",
15
+ "playwright*.config.*", "tsconfig.json", "postcss.config.*",
16
+ "*.vscode/*", "*.devcontainer/*", "*.idea/*",
17
+ "scripts/ci_*gate*.py", "tests/*/test_ci_*gate*.py"
18
+ ]
19
+ }
@@ -0,0 +1,293 @@
1
+ """Open a task in a fresh Orca worktree, or show what is missing before one can start."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from orca_agent_workflow import adoption, check_sync, review_gate, task_scope
15
+
16
+ LAUNCHER = "python3 .agents/workflow.py"
17
+
18
+
19
+ def ask(label: str, default: str = "", choices: tuple = ()) -> str:
20
+ while True:
21
+ answer = input(f"{label}" + (f" [{default}]" if default else "") + ": ").strip()
22
+ answer = answer or default
23
+ if not choices or answer in choices:
24
+ return answer
25
+ print("Choose " + " or ".join(choices) + ".")
26
+
27
+
28
+ def git(root: Path, *arguments: str) -> subprocess.CompletedProcess:
29
+ return subprocess.run(
30
+ ["git", "-C", str(root), *arguments], capture_output=True, text=True, timeout=15
31
+ )
32
+
33
+
34
+ def slug(text: str) -> str:
35
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:45].rstrip("-") or "project"
36
+
37
+
38
+ def configuration(root: Path) -> tuple[dict, dict]:
39
+ if not (root / task_scope.CONFIG).is_file():
40
+ raise ValueError(f"No {task_scope.CONFIG}. Run orca-agent-workflow init first.")
41
+ problems = check_sync.check(root)
42
+ if problems:
43
+ raise ValueError("Workflow configuration needs attention: " + "; ".join(problems))
44
+ config = task_scope.load_config((root / task_scope.CONFIG).read_bytes())
45
+ project = config["project"]
46
+ planners = config["roles"].get("planner", [])
47
+ coordinator = project.get("coordinator") or next(
48
+ (p for p in planners if p.get("enabled") is True), {}
49
+ )
50
+ if not review_gate.exact_model(coordinator.get("agent"), coordinator.get("model")) or not any(
51
+ p.get("enabled") is True
52
+ and p.get("agent") == coordinator.get("agent")
53
+ and p.get("model") == coordinator.get("model")
54
+ for p in planners
55
+ ):
56
+ raise ValueError("Choose an enabled exact coordinator profile in .agents/workflow.json.")
57
+ checks = project.get("checks", [])
58
+ if not isinstance(checks, list) or any(
59
+ not isinstance(c, str) or not c.strip() for c in checks
60
+ ):
61
+ raise ValueError("Project checks must be a list of non-empty commands.")
62
+ project = {**project, "checks": checks}
63
+ return project, {"agent": coordinator["agent"], "model": coordinator["model"]}
64
+
65
+
66
+ def readiness(root: Path, coordinator: dict) -> tuple[str | None, list[str]]:
67
+ problems = []
68
+ for tool in ("git", "orca", coordinator["agent"]):
69
+ if not shutil.which(tool):
70
+ problems.append(f"Install {tool} and make it available on PATH.")
71
+ head = None
72
+ if shutil.which("git"):
73
+ top = git(root, "rev-parse", "--show-toplevel")
74
+ if top.returncode or Path(top.stdout.strip()).resolve() != root:
75
+ problems.append(
76
+ "Initialize Git in the project folder and review/commit its files first."
77
+ )
78
+ else:
79
+ result = git(root, "rev-parse", "--verify", "HEAD")
80
+ head = result.stdout.strip() if result.returncode == 0 else None
81
+ tracked = git(
82
+ root, "ls-files", "--error-unmatch", ".agents/workflow.py", task_scope.CONFIG
83
+ )
84
+ if not head or tracked.returncode:
85
+ problems.append(
86
+ "Review and commit the generated workflow files first; worktrees copy committed files only."
87
+ )
88
+ if git(root, "status", "--porcelain").stdout.strip():
89
+ problems.append(
90
+ "This launcher needs a clean committed checkout. Preserve unrelated changes and use an isolated clean checkout; no files were changed."
91
+ )
92
+ return head, problems
93
+
94
+
95
+ def status() -> int:
96
+ root = task_scope.project_folder()
97
+ project, coordinator = configuration(root)
98
+ _, problems = readiness(root, coordinator)
99
+ print(
100
+ f"Project: {project['name']}\nCoordinator: {coordinator['agent']} / {coordinator['model']}"
101
+ )
102
+ print("Ready to open a planning task." if not problems else "Before starting:")
103
+ for problem in problems:
104
+ print("- " + problem)
105
+ revisions = adoption.revisions(root)
106
+ for role, revision in revisions.items():
107
+ print(f"{role}: {revision}")
108
+ if any(not revision.endswith("(policy present)") for revision in revisions.values()):
109
+ print(
110
+ "To use the default gate and worker policy after adoption, refresh origin's "
111
+ "default branch and check these revisions from the task checkout."
112
+ )
113
+ print(
114
+ "Checks: "
115
+ + (
116
+ "; ".join(project["checks"])
117
+ or "ask the coordinator to configure them before implementation"
118
+ )
119
+ )
120
+ print(
121
+ "Runtime/dependencies and scoped model access must be checked by the coordinator before worker dispatch."
122
+ )
123
+ return int(bool(problems))
124
+
125
+
126
+ def start(args: argparse.Namespace) -> int:
127
+ root = task_scope.project_folder()
128
+ project, coordinator = configuration(root)
129
+ task = args.task
130
+ if not task and not args.wait_for_task:
131
+ if not sys.stdin.isatty():
132
+ raise ValueError(
133
+ f'Describe the task: {LAUNCHER} start "Your task". '
134
+ f'To open a first coordinator and supply the task in Orca, run '
135
+ f'{LAUNCHER} start --wait-for-task.'
136
+ )
137
+ task = ask("What would you like to build or change?")
138
+ if not args.wait_for_task and not task.strip():
139
+ raise ValueError("Describe a non-empty task.")
140
+ head, problems = readiness(root, coordinator)
141
+ if args.wait_for_task:
142
+ workspace = "first-task"
143
+ prompt = (
144
+ "You are the coordinator for this newly adopted project. Read AGENTS.md, "
145
+ ".agents/WORKFLOW.md, .agents/workflow.json and .agents/skills/start-task/SKILL.md. "
146
+ "Then ask the user for their first task and wait. Only the user supplies the goal. "
147
+ "Do not edit files, draft a spec, launch workers or start another coordinator during this handoff."
148
+ )
149
+ else:
150
+ workspace = slug(task)
151
+ prompt = (
152
+ "Use start-task for this task. You are the coordinator in this task workspace; "
153
+ "reuse this session rather than launching another coordinator. Read AGENTS.md, "
154
+ ".agents/WORKFLOW.md and .agents/workflow.json, then inspect the existing project. "
155
+ "Help refine the goal into a bounded task and draft an understandable spec. "
156
+ "Check that the project's verification commands and trusted gate runtime/dependencies are meaningful; "
157
+ "if missing, help configure them before any implementation worker dispatch. "
158
+ "Confirm model availability and probe the scoped adapters before workers run. "
159
+ "Obtain explicit user approval and commit the spec before launching a cold implementer. "
160
+ "Follow the fresh independent review and human merge workflow.\n\nUser goal:\n" + task
161
+ )
162
+ command = [
163
+ "orca",
164
+ "worktree",
165
+ "create",
166
+ "--repo",
167
+ f"path:{root}",
168
+ "--name",
169
+ workspace,
170
+ "--base-branch",
171
+ head or "HEAD",
172
+ "--no-parent",
173
+ "--setup",
174
+ "skip",
175
+ "--agent",
176
+ coordinator["agent"],
177
+ "--model",
178
+ coordinator["model"],
179
+ "--prompt",
180
+ prompt,
181
+ "--activate",
182
+ "--json",
183
+ ]
184
+ if args.dry_run:
185
+ print(
186
+ json.dumps(
187
+ {
188
+ "project": project["name"],
189
+ "ready_for_planning": not problems,
190
+ "before_starting": problems,
191
+ "command": command,
192
+ "model_calls": 0,
193
+ },
194
+ indent=2,
195
+ )
196
+ )
197
+ return 0
198
+ if problems:
199
+ raise ValueError("\n".join(problems))
200
+ # Register only on the documented not-found response; never treat transport failure as absence.
201
+ result = subprocess.run(
202
+ resolved(["orca", "repo", "show", "--repo", f"path:{root}", "--json"]),
203
+ capture_output=True,
204
+ text=True,
205
+ timeout=30,
206
+ )
207
+ reply = json.loads(result.stdout)
208
+ if result.returncode or reply.get("ok") is False:
209
+ if reply.get("error", {}).get("code") != "repo_not_found":
210
+ raise ValueError(
211
+ "Orca could not inspect this project. " + result.stdout + result.stderr
212
+ )
213
+ result = subprocess.run(
214
+ resolved(["orca", "repo", "add", "--path", str(root), "--json"]),
215
+ capture_output=True,
216
+ text=True,
217
+ timeout=30,
218
+ )
219
+ if result.returncode or json.loads(result.stdout).get("ok") is False:
220
+ raise ValueError("Orca registration failed. " + result.stdout + result.stderr)
221
+ print("Opening a fresh planning worktree. Repository setup hooks are skipped.", flush=True)
222
+ result = subprocess.run(resolved(command), capture_output=True, text=True, timeout=60)
223
+ try:
224
+ reply = json.loads(result.stdout)
225
+ created = reply.get("result", {})
226
+ workspace_path = created.get("worktree", {}).get("path")
227
+ launch = created.get("launch", {})
228
+ outcome = launch.get("outcome", {})
229
+ confirmed = (
230
+ reply.get("ok") is True
231
+ and isinstance(workspace_path, str)
232
+ and bool(workspace_path.strip())
233
+ and outcome.get("kind") in ("structured", "terminal")
234
+ and bool(outcome.get("handle"))
235
+ and launch.get("prompt", {}).get("outcome") in ("journaled", "handed-to-terminal")
236
+ )
237
+ except (ValueError, AttributeError):
238
+ confirmed = False
239
+ if result.returncode or not confirmed:
240
+ print(result.stdout, end="")
241
+ print(result.stderr, end="", file=sys.stderr)
242
+ raise ValueError(
243
+ "Orca launch did not confirm success. Inspect the receipt above; do not retry as a fresh launch. Use Orca's --retry-launch operation ID if supplied."
244
+ )
245
+ print(f"Orca workspace: {workspace_path}")
246
+ print(f"Session: {outcome['handle']}")
247
+ print(f"Coordinator: {coordinator['agent']} / {coordinator['model']}")
248
+ if args.wait_for_task:
249
+ print("Continue in Orca by describing your first task in that session.")
250
+ else:
251
+ print(f"Task opened in Orca: {task}")
252
+ print("Continue in Orca: refine the plan and approve the spec before implementation.")
253
+ return 0
254
+
255
+
256
+ def resolved(command: list[str]) -> list[str]:
257
+ """Launch the CLI that `shutil.which` found; Windows only appends .exe itself."""
258
+ executable = shutil.which(command[0]) or command[0]
259
+ if os.name == "nt" and Path(executable).suffix.lower() in (".cmd", ".bat"):
260
+ # cmd.exe re-parses batch arguments, so task text could run as commands.
261
+ raise ValueError(
262
+ f"{executable} is a batch launcher; put Orca's native orca.exe first on PATH"
263
+ )
264
+ return [executable, *command[1:]]
265
+
266
+
267
+ def main() -> int:
268
+ parser = argparse.ArgumentParser(description=__doc__)
269
+ commands = parser.add_subparsers(dest="command")
270
+ begin = commands.add_parser("start", help="Open a planning task in a fresh Orca worktree")
271
+ goal = begin.add_mutually_exclusive_group()
272
+ goal.add_argument("task", nargs="?")
273
+ goal.add_argument(
274
+ "--wait-for-task", action="store_true",
275
+ help="Open the project coordinator and wait for the user's first task",
276
+ )
277
+ begin.add_argument("--dry-run", action="store_true", help="Show the launch without running it")
278
+ commands.add_parser("status", help="Show the next steps without launching anything")
279
+ args = parser.parse_args(sys.argv[1:] if len(sys.argv) > 1 else ["start"])
280
+ try:
281
+ if sys.version_info < (3, 11):
282
+ raise ValueError("Python 3.11 or newer is required.")
283
+ return start(args) if args.command == "start" else status()
284
+ except (OSError, ValueError, KeyError, TypeError, StopIteration) as exc:
285
+ parser.exit(1, f"orca-agent-workflow: {exc}\n")
286
+ except subprocess.TimeoutExpired:
287
+ parser.exit(
288
+ 1,
289
+ "orca-agent-workflow: Command timed out. A launch reply may be lost; inspect Orca before retrying. No automatic retry was made.\n",
290
+ )
291
+ except (EOFError, KeyboardInterrupt):
292
+ parser.exit(1, "\norca-agent-workflow: Cancelled.\n")
293
+ return 0