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.
- orca_agent_workflow/__init__.py +3 -0
- orca_agent_workflow/__main__.py +3 -0
- orca_agent_workflow/adoption.py +33 -0
- orca_agent_workflow/check_sync.py +93 -0
- orca_agent_workflow/cli.py +83 -0
- orca_agent_workflow/codex_review.py +364 -0
- orca_agent_workflow/doctor.py +33 -0
- orca_agent_workflow/gate.Dockerfile +9 -0
- orca_agent_workflow/install.py +313 -0
- orca_agent_workflow/migrate.py +178 -0
- orca_agent_workflow/native.py +142 -0
- orca_agent_workflow/resume_dispatch.py +160 -0
- orca_agent_workflow/review_gate.py +291 -0
- orca_agent_workflow/run_gates.py +263 -0
- orca_agent_workflow/sensitive.json +19 -0
- orca_agent_workflow/start.py +293 -0
- orca_agent_workflow/task_plan.py +301 -0
- orca_agent_workflow/task_scope.py +1256 -0
- orca_agent_workflow/template/AGENTS.md +49 -0
- orca_agent_workflow/template/CLAUDE.md +4 -0
- orca_agent_workflow/template/agents/LICENSE +21 -0
- orca_agent_workflow/template/agents/README.md +78 -0
- orca_agent_workflow/template/agents/WORKFLOW.md +65 -0
- orca_agent_workflow/template/agents/docs/cross-provider.md +79 -0
- orca_agent_workflow/template/agents/docs/roles/implementer.md +15 -0
- orca_agent_workflow/template/agents/docs/task-permissions.md +124 -0
- orca_agent_workflow/template/agents/skills/project-handoff/SKILL.md +23 -0
- orca_agent_workflow/template/agents/skills/review-pr/SKILL.md +41 -0
- orca_agent_workflow/template/agents/skills/review-pr/references/record.example.json +31 -0
- orca_agent_workflow/template/agents/skills/review-pr/references/reviewer.md +20 -0
- orca_agent_workflow/template/agents/skills/session-recover/SKILL.md +17 -0
- orca_agent_workflow/template/agents/skills/session-recover/references/recovery.md +38 -0
- orca_agent_workflow/template/agents/skills/session-recover/scripts/session_context.py +239 -0
- orca_agent_workflow/template/agents/skills/spec-and-delegate/SKILL.md +37 -0
- orca_agent_workflow/template/agents/skills/spec-and-delegate/references/spec-template.md +46 -0
- orca_agent_workflow/template/agents/skills/start-task/SKILL.md +72 -0
- orca_agent_workflow/template/agents/workflow.json +64 -0
- orca_agent_workflow/template/agents/workflow.py +82 -0
- orca_agent_workflow/template/claude/skills/project-handoff/SKILL.md +12 -0
- orca_agent_workflow/template/claude/skills/review-pr/SKILL.md +12 -0
- orca_agent_workflow/template/claude/skills/session-recover/SKILL.md +12 -0
- orca_agent_workflow/template/claude/skills/spec-and-delegate/SKILL.md +12 -0
- orca_agent_workflow/template/claude/skills/start-task/SKILL.md +12 -0
- orca_agent_workflow/template/gitattributes +5 -0
- orca_agent_workflow/template/githooks/pre-push +11 -0
- orca_agent_workflow/template/gitignore +3 -0
- orca_agent_workflow/template/opencode/commands/project-handoff.md +7 -0
- orca_agent_workflow/template/opencode/commands/review-pr.md +7 -0
- orca_agent_workflow/template/opencode/commands/session-recover.md +7 -0
- orca_agent_workflow/template/opencode/commands/spec-and-delegate.md +7 -0
- orca_agent_workflow/template/opencode/commands/start-task.md +9 -0
- orca_agent_workflow-0.2.0.dist-info/METADATA +214 -0
- orca_agent_workflow-0.2.0.dist-info/RECORD +57 -0
- orca_agent_workflow-0.2.0.dist-info/WHEEL +5 -0
- orca_agent_workflow-0.2.0.dist-info/entry_points.txt +2 -0
- orca_agent_workflow-0.2.0.dist-info/licenses/LICENSE +21 -0
- orca_agent_workflow-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Install the workflow's project files; preview by default, never replace existing files."""
|
|
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 __version__, adoption, native, review_gate, task_scope
|
|
15
|
+
|
|
16
|
+
PACKAGE = Path(__file__).resolve().parent
|
|
17
|
+
TEMPLATE = PACKAGE / "template"
|
|
18
|
+
# Template paths drop leading dots so packaging keeps them; these names regain theirs.
|
|
19
|
+
DOTTED = {"agents", "claude", "opencode", "githooks", "gitignore", "gitattributes"}
|
|
20
|
+
OPTIONAL = {"opencode": "opencode/", "pre-push-hook": "githooks/"}
|
|
21
|
+
EXECUTABLE = {".agents/workflow.py", ".githooks/pre-push"}
|
|
22
|
+
RULE_FILES = {".gitignore", ".gitattributes"} # existing files get the missing lines appended
|
|
23
|
+
RUNTIME = ".agents/runtime/orca_agent_workflow"
|
|
24
|
+
MERGE_FOLDER = ".tmp/orca-agent-workflow/merge"
|
|
25
|
+
KIT_DOCS = "https://github.com/diarsabri/orca-agent-workflow/blob/"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def destination(stored: str) -> str:
|
|
29
|
+
first, _, rest = stored.partition("/")
|
|
30
|
+
first = "." + first if first in DOTTED else first
|
|
31
|
+
return f"{first}/{rest}" if rest else first
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def template_files(optional: tuple[str, ...] = ()) -> dict[str, Path]:
|
|
35
|
+
"""Installed path -> template source, for the default files and requested groups."""
|
|
36
|
+
unknown = set(optional) - set(OPTIONAL)
|
|
37
|
+
if unknown:
|
|
38
|
+
raise ValueError("Unknown optional files: " + ", ".join(sorted(unknown)))
|
|
39
|
+
files = {}
|
|
40
|
+
for source in sorted(TEMPLATE.rglob("*")):
|
|
41
|
+
stored = source.relative_to(TEMPLATE).as_posix()
|
|
42
|
+
if not source.is_file() or "__pycache__" in stored:
|
|
43
|
+
continue
|
|
44
|
+
group = next((g for g, prefix in OPTIONAL.items() if stored.startswith(prefix)), None)
|
|
45
|
+
if group is None or group in optional:
|
|
46
|
+
files[destination(stored)] = source
|
|
47
|
+
return files
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def runtime_files() -> dict[str, Path]:
|
|
51
|
+
"""The package itself, for `--vendor`: the launcher then prefers this copy."""
|
|
52
|
+
return {
|
|
53
|
+
f"{RUNTIME}/{source.relative_to(PACKAGE).as_posix()}": source
|
|
54
|
+
for source in sorted(PACKAGE.rglob("*"))
|
|
55
|
+
if source.is_file() and "__pycache__" not in source.parts and source.suffix != ".pyc"
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def load(path: Path) -> dict:
|
|
60
|
+
value = json.loads(path.read_text(encoding="utf-8"))
|
|
61
|
+
if not isinstance(value, dict):
|
|
62
|
+
raise ValueError(f"Expected an object in {path.name}")
|
|
63
|
+
return value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def detect(root: Path) -> tuple[str, list[str]]:
|
|
67
|
+
"""Suggestions only: never run application commands or install dependencies."""
|
|
68
|
+
if (root / "package.json").is_file():
|
|
69
|
+
package = load(root / "package.json")
|
|
70
|
+
manager = str(package.get("packageManager", "npm")).split("@")[0]
|
|
71
|
+
if manager not in ("npm", "pnpm", "yarn", "bun"):
|
|
72
|
+
manager = "npm"
|
|
73
|
+
scripts = package.get("scripts", {})
|
|
74
|
+
return "node", [f"{manager} run {key}" for key in ("check", "test") if key in scripts]
|
|
75
|
+
if (root / "pyproject.toml").is_file() or list(root.glob("*.py")) or (root / "tests").is_dir():
|
|
76
|
+
# Only suggest unittest when a real test module explicitly imports it.
|
|
77
|
+
tests = list((root / "tests").glob("test*.py"))
|
|
78
|
+
unittest_tests = tests and all(
|
|
79
|
+
"import unittest" in p.read_text(encoding="utf-8") for p in tests
|
|
80
|
+
)
|
|
81
|
+
return "python", ["python3 -m unittest discover -s tests"] if unittest_tests else []
|
|
82
|
+
return "other", []
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def origin_repository(target: Path) -> str | None:
|
|
86
|
+
if not (target / ".git").exists() or not shutil.which("git"):
|
|
87
|
+
return None
|
|
88
|
+
remote = subprocess.run(
|
|
89
|
+
["git", "-C", str(target), "config", "--get", "remote.origin.url"],
|
|
90
|
+
capture_output=True,
|
|
91
|
+
text=True,
|
|
92
|
+
timeout=15,
|
|
93
|
+
).stdout.strip()
|
|
94
|
+
match = re.fullmatch(
|
|
95
|
+
r"(?:https://github\.com/|git@github\.com:)([\w.-]+/[\w.-]+?)(?:\.git)?/?", remote
|
|
96
|
+
)
|
|
97
|
+
return match[1] if match else None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def render_config(target: Path, args: argparse.Namespace) -> bytes:
|
|
101
|
+
"""A new project's .agents/workflow.json; an existing one is never rewritten."""
|
|
102
|
+
config = json.loads((TEMPLATE / "agents/workflow.json").read_text(encoding="utf-8"))
|
|
103
|
+
stack, checks = detect(target) if target.exists() else ("other", [])
|
|
104
|
+
name = args.name or target.name.replace("-", " ").replace("_", " ").title()
|
|
105
|
+
repository = args.repository or origin_repository(target) or "local/" + re.sub(
|
|
106
|
+
r"[^a-z0-9]+", "-", target.name.lower()
|
|
107
|
+
).strip("-")
|
|
108
|
+
if not name.strip() or "\n" in name or "\r" in name:
|
|
109
|
+
raise ValueError("Use a non-empty, single-line project name")
|
|
110
|
+
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
|
|
111
|
+
raise ValueError("Repository must be owner/name")
|
|
112
|
+
checks = args.check if args.check is not None else checks
|
|
113
|
+
if any(not isinstance(c, str) or not c.strip() for c in checks):
|
|
114
|
+
raise ValueError("Verification commands must be non-empty")
|
|
115
|
+
agent = args.coordinator or (
|
|
116
|
+
"claude" if shutil.which("claude") else "codex" if shutil.which("codex") else "claude"
|
|
117
|
+
)
|
|
118
|
+
model = next(
|
|
119
|
+
p["model"]
|
|
120
|
+
for p in config["roles"]["planner"]
|
|
121
|
+
if p["agent"] == agent and p.get("enabled") is True
|
|
122
|
+
)
|
|
123
|
+
if not review_gate.exact_model(agent, model):
|
|
124
|
+
raise ValueError("The default coordinator profile needs an exact model ID")
|
|
125
|
+
config["runtime"]["version"] = __version__
|
|
126
|
+
config["project"] = {
|
|
127
|
+
"name": name,
|
|
128
|
+
"repository": repository,
|
|
129
|
+
"stack": args.stack or stack,
|
|
130
|
+
"checks": checks,
|
|
131
|
+
"coordinator": {"agent": agent, "model": model},
|
|
132
|
+
}
|
|
133
|
+
return (json.dumps(config, indent=2) + "\n").encode()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def proposed(relative: str, source: Path) -> bytes:
|
|
137
|
+
data = source.read_bytes()
|
|
138
|
+
if relative.endswith(".md"):
|
|
139
|
+
# Kit docs as they were for this version, not as they are on main today.
|
|
140
|
+
data = data.replace(
|
|
141
|
+
(KIT_DOCS + "main/").encode(), f"{KIT_DOCS}v{__version__}/".encode()
|
|
142
|
+
)
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def append_missing_lines(original: bytes, proposed: bytes) -> bytes:
|
|
147
|
+
"""Keep an existing rules file; add only the proposed rule lines it lacks."""
|
|
148
|
+
present = set(original.decode("utf-8").splitlines())
|
|
149
|
+
lines = proposed.decode("utf-8").splitlines()
|
|
150
|
+
missing = [s for s in lines if s and not s.startswith("#") and s not in present]
|
|
151
|
+
if not missing:
|
|
152
|
+
return original
|
|
153
|
+
header = next((s for s in lines if s.startswith("#")), "# Orca agent workflow")
|
|
154
|
+
data = original + (b"\n" if original and not original.endswith(b"\n") else b"")
|
|
155
|
+
return data + ("\n" + header + "\n" + "\n".join(missing) + "\n").encode()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def safe_path(root: Path, name: str) -> Path:
|
|
159
|
+
if not isinstance(name, str) or not name or "\\" in name:
|
|
160
|
+
raise ValueError("Managed paths must be relative POSIX paths")
|
|
161
|
+
if Path(name).is_absolute() or any(p in ("", ".", "..") for p in name.split("/")):
|
|
162
|
+
raise ValueError("Managed paths cannot be absolute or contain traversal")
|
|
163
|
+
path = root / name
|
|
164
|
+
current = path
|
|
165
|
+
while current != root:
|
|
166
|
+
if current.is_symlink():
|
|
167
|
+
raise ValueError(f"Refusing symlink: {current}")
|
|
168
|
+
if current != path and current.exists() and not current.is_dir():
|
|
169
|
+
raise ValueError(f"Managed parent is not a folder: {name}")
|
|
170
|
+
current = current.parent
|
|
171
|
+
if not path.resolve().is_relative_to(root):
|
|
172
|
+
raise ValueError("Managed path escapes the project")
|
|
173
|
+
return path
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def plan(target: Path, args: argparse.Namespace, config: bytes | None = None) -> list[dict]:
|
|
177
|
+
"""Every managed file's action; `config` supplies a new project's workflow.json."""
|
|
178
|
+
optional = tuple(
|
|
179
|
+
g for g, on in (("opencode", args.opencode), ("pre-push-hook", args.pre_push_hook)) if on
|
|
180
|
+
)
|
|
181
|
+
files = template_files(optional)
|
|
182
|
+
if args.vendor:
|
|
183
|
+
files.update(runtime_files())
|
|
184
|
+
operations = []
|
|
185
|
+
for relative, source in files.items():
|
|
186
|
+
path = safe_path(target, relative)
|
|
187
|
+
if path.exists() and not path.is_file():
|
|
188
|
+
raise ValueError(f"Expected a regular file: {relative}")
|
|
189
|
+
original = path.read_bytes() if path.is_file() else None
|
|
190
|
+
if relative == task_scope.CONFIG:
|
|
191
|
+
if original is not None:
|
|
192
|
+
pinned = task_scope.load_config(original)["runtime"].get("version")
|
|
193
|
+
note = "unchanged" if pinned == __version__ else f"keep (pins {pinned})"
|
|
194
|
+
operations.append({"path": relative, "action": note, "data": original})
|
|
195
|
+
continue
|
|
196
|
+
data = config if config is not None else render_config(target, args)
|
|
197
|
+
else:
|
|
198
|
+
data = proposed(relative, source)
|
|
199
|
+
if original == data:
|
|
200
|
+
action = "unchanged"
|
|
201
|
+
elif original is None:
|
|
202
|
+
action = "create"
|
|
203
|
+
elif relative in RULE_FILES:
|
|
204
|
+
data = append_missing_lines(original, data)
|
|
205
|
+
action = "unchanged" if data == original else "append-rules"
|
|
206
|
+
else:
|
|
207
|
+
action = "merge"
|
|
208
|
+
operations.append(
|
|
209
|
+
{
|
|
210
|
+
"path": relative,
|
|
211
|
+
"action": action,
|
|
212
|
+
"data": data,
|
|
213
|
+
"original": original,
|
|
214
|
+
"executable": relative in EXECUTABLE,
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
return operations
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def open_flags(path: Path, flags: int) -> int:
|
|
221
|
+
# Windows has no O_NOFOLLOW and opens descriptors in text mode by default.
|
|
222
|
+
nofollow = getattr(os, "O_NOFOLLOW", 0)
|
|
223
|
+
if not nofollow and path.is_symlink():
|
|
224
|
+
raise ValueError(f"Refusing to write through a symlink: {path}")
|
|
225
|
+
return flags | nofollow | getattr(os, "O_BINARY", 0)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def write(path: Path, data: bytes, executable: bool) -> None:
|
|
229
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
230
|
+
descriptor = os.open(
|
|
231
|
+
path, open_flags(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL), 0o755 if executable else 0o644
|
|
232
|
+
)
|
|
233
|
+
with os.fdopen(descriptor, "wb") as output:
|
|
234
|
+
output.write(data)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def apply(target: Path, operations: list[dict]) -> None:
|
|
238
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
239
|
+
for operation in operations:
|
|
240
|
+
path = safe_path(target, operation["path"])
|
|
241
|
+
if operation["action"] == "create":
|
|
242
|
+
write(path, operation["data"], operation["executable"])
|
|
243
|
+
elif operation["action"] == "append-rules":
|
|
244
|
+
if path.read_bytes() != operation["original"]:
|
|
245
|
+
raise ValueError(f"File changed after preflight: {path}")
|
|
246
|
+
extra = operation["data"][len(operation["original"]) :]
|
|
247
|
+
descriptor = os.open(path, open_flags(path, os.O_WRONLY | os.O_APPEND))
|
|
248
|
+
with os.fdopen(descriptor, "wb") as output:
|
|
249
|
+
output.write(extra)
|
|
250
|
+
elif operation["action"] == "merge":
|
|
251
|
+
# The custom file stays; the candidate sits beside it for a semantic merge.
|
|
252
|
+
candidate = safe_path(target, f"{MERGE_FOLDER}/{operation['path']}")
|
|
253
|
+
if candidate.exists():
|
|
254
|
+
candidate.unlink()
|
|
255
|
+
write(candidate, operation["data"], False)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def main() -> int:
|
|
259
|
+
parser = argparse.ArgumentParser(prog="orca-agent-workflow init", description=__doc__)
|
|
260
|
+
parser.add_argument("--target", type=Path, default=Path("."), help="Project folder")
|
|
261
|
+
parser.add_argument("--apply", action="store_true", help="Write; without it, only preview")
|
|
262
|
+
parser.add_argument("--name")
|
|
263
|
+
parser.add_argument("--repository", help="GitHub owner/name (default: origin)")
|
|
264
|
+
parser.add_argument("--stack", choices=("python", "node", "other"))
|
|
265
|
+
parser.add_argument("--check", action="append", help="Verification command; repeatable")
|
|
266
|
+
parser.add_argument("--coordinator", choices=("claude", "codex"))
|
|
267
|
+
parser.add_argument("--opencode", action="store_true", help="Also install OpenCode commands")
|
|
268
|
+
parser.add_argument(
|
|
269
|
+
"--pre-push-hook", action="store_true", help="Also install the protected-branch hook"
|
|
270
|
+
)
|
|
271
|
+
parser.add_argument(
|
|
272
|
+
"--vendor", action="store_true", help="Copy the runtime into .agents/runtime/"
|
|
273
|
+
)
|
|
274
|
+
args = parser.parse_args()
|
|
275
|
+
try:
|
|
276
|
+
if sys.version_info < (3, 11):
|
|
277
|
+
raise ValueError("Python 3.11 or newer is required")
|
|
278
|
+
if args.target.is_symlink():
|
|
279
|
+
raise ValueError("The target itself cannot be a symlink")
|
|
280
|
+
target = args.target.expanduser().resolve()
|
|
281
|
+
if target.exists() and not target.is_dir():
|
|
282
|
+
raise ValueError("Target must be a directory")
|
|
283
|
+
operations = plan(target, args)
|
|
284
|
+
if args.apply:
|
|
285
|
+
apply(target, operations)
|
|
286
|
+
merges = [op["path"] for op in operations if op["action"] == "merge"]
|
|
287
|
+
config = next(op["data"] for op in operations if op["path"] == task_scope.CONFIG)
|
|
288
|
+
report = {
|
|
289
|
+
"target": str(target),
|
|
290
|
+
"version": __version__,
|
|
291
|
+
"applied": args.apply,
|
|
292
|
+
"project": task_scope.load_config(config)["project"],
|
|
293
|
+
"current_revisions": adoption.revisions(target),
|
|
294
|
+
"files": [{"path": op["path"], "action": op["action"]} for op in operations],
|
|
295
|
+
"requires_merge": merges,
|
|
296
|
+
"executable": [op["path"] for op in operations if op.get("executable")],
|
|
297
|
+
"next": (
|
|
298
|
+
"Review and commit the files, merge the listed ones by hand (candidates in "
|
|
299
|
+
f"{MERGE_FOLDER}/), then run: python3 .agents/workflow.py check"
|
|
300
|
+
if args.apply
|
|
301
|
+
else "Nothing written. Re-run with --apply to install."
|
|
302
|
+
),
|
|
303
|
+
}
|
|
304
|
+
if suggestions := native.preview(target):
|
|
305
|
+
report["native_verification"] = suggestions
|
|
306
|
+
if args.apply and os.name == "nt":
|
|
307
|
+
report["windows_executable_bits"] = (
|
|
308
|
+
"Stage the files listed under executable with `git add --chmod=+x -- <paths>`."
|
|
309
|
+
)
|
|
310
|
+
print(json.dumps(report, indent=2))
|
|
311
|
+
except (OSError, ValueError, KeyError, StopIteration) as exc:
|
|
312
|
+
parser.exit(1, f"init: {exc}\n")
|
|
313
|
+
return 0
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Convert a project from the vendored v1 layout to the pinned runtime; never deletes files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from orca_agent_workflow import __version__, install, task_scope
|
|
11
|
+
|
|
12
|
+
V1_PROJECT = ".agents/project.json"
|
|
13
|
+
V1_POLICY = ".agents/orchestration.json"
|
|
14
|
+
V1_GATES = ".agents/gates.json"
|
|
15
|
+
V1_SENSITIVE = "scripts/agents/sensitive.json"
|
|
16
|
+
V1_DOCKERFILE = "scripts/agents/gate_sandbox/Dockerfile"
|
|
17
|
+
# Files only the kit installed, now replaced by the pinned runtime. Listed, never deleted.
|
|
18
|
+
V1_KIT_ONLY = (
|
|
19
|
+
"scaffold.py",
|
|
20
|
+
"kit-files.json",
|
|
21
|
+
".agents/project.json",
|
|
22
|
+
".agents/orchestration.json",
|
|
23
|
+
".agents/gates.json",
|
|
24
|
+
"specs/_TEMPLATE.md",
|
|
25
|
+
)
|
|
26
|
+
# Earlier installs also used these generic names; a project may own files called the same.
|
|
27
|
+
V1_MAYBE = (
|
|
28
|
+
"workflow.py",
|
|
29
|
+
"WORKFLOW.md",
|
|
30
|
+
"scripts/check_docs.py",
|
|
31
|
+
"scripts/scan_public.py",
|
|
32
|
+
"docs/architecture.md",
|
|
33
|
+
"docs/compatibility.md",
|
|
34
|
+
"docs/security.md",
|
|
35
|
+
"docs/validation.md",
|
|
36
|
+
"docs/getting-started.md",
|
|
37
|
+
)
|
|
38
|
+
V1_RUNTIME = (
|
|
39
|
+
"scripts/agents/task_scope.py",
|
|
40
|
+
"scripts/agents/task_plan.py",
|
|
41
|
+
"scripts/agents/review_gate.py",
|
|
42
|
+
"scripts/agents/codex_review.py",
|
|
43
|
+
"scripts/agents/check_sync.py",
|
|
44
|
+
"scripts/agents/doctor.py",
|
|
45
|
+
"scripts/agents/sensitive.json",
|
|
46
|
+
"scripts/agents/gate_sandbox/run_gates.py",
|
|
47
|
+
"scripts/agents/gate_sandbox/run_gates.sh",
|
|
48
|
+
"tests/agents/__init__.py",
|
|
49
|
+
"tests/agents/test_codex_review.py",
|
|
50
|
+
"tests/agents/test_review_gate.py",
|
|
51
|
+
"tests/agents/test_task_plan.py",
|
|
52
|
+
"tests/agents/test_task_scope.py",
|
|
53
|
+
"docs/agents/cross-provider.md",
|
|
54
|
+
"docs/agents/task-permissions.md",
|
|
55
|
+
"docs/agents/roles/implementer.md",
|
|
56
|
+
)
|
|
57
|
+
# Folders the kit shared with projects: other files there are the project's own.
|
|
58
|
+
V1_FOLDERS = ("scripts/agents", "tests/agents", "docs/agents")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def read(target: Path, relative: str) -> dict:
|
|
62
|
+
return install.load(install.safe_path(target, relative))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def convert(target: Path) -> tuple[bytes, list[str]]:
|
|
66
|
+
"""The equivalent .agents/workflow.json, and what the conversion could not carry over."""
|
|
67
|
+
policy = read(target, V1_POLICY)
|
|
68
|
+
notes = []
|
|
69
|
+
if install.safe_path(target, V1_PROJECT).is_file():
|
|
70
|
+
project = read(target, V1_PROJECT)
|
|
71
|
+
else:
|
|
72
|
+
# Pilot layouts kept identity in the policy and checks in their own docs.
|
|
73
|
+
project = {"name": target.name, "repository": policy.get("repository"), "checks": []}
|
|
74
|
+
notes.append("no .agents/project.json: set project.name and project.checks")
|
|
75
|
+
config = json.loads((install.TEMPLATE / "agents/workflow.json").read_text(encoding="utf-8"))
|
|
76
|
+
config["runtime"]["version"] = __version__
|
|
77
|
+
config["project"] = {
|
|
78
|
+
key: project[key]
|
|
79
|
+
for key in ("name", "repository", "stack", "checks", "coordinator")
|
|
80
|
+
if key in project
|
|
81
|
+
}
|
|
82
|
+
if policy.get("repository") != project.get("repository"):
|
|
83
|
+
notes.append("project.json and orchestration.json named different repositories")
|
|
84
|
+
config["roles"] = policy["roles"]
|
|
85
|
+
config["max_fix_rounds"] = policy.get("max_fix_rounds", 2)
|
|
86
|
+
if policy.get("reviewer_provider_differs_from_planner") != "preferred":
|
|
87
|
+
notes.append("reviewer_provider_differs_from_planner is now \"preferred\"")
|
|
88
|
+
gates_path = install.safe_path(target, V1_GATES)
|
|
89
|
+
stock = install.safe_path(target, V1_DOCKERFILE)
|
|
90
|
+
if gates_path.is_file() or stock.is_file():
|
|
91
|
+
gates = install.load(gates_path) if gates_path.is_file() else {"dockerfile": V1_DOCKERFILE}
|
|
92
|
+
dockerfile = gates.get("dockerfile")
|
|
93
|
+
default = install.PACKAGE / "gate.Dockerfile"
|
|
94
|
+
candidate = install.safe_path(target, dockerfile) if dockerfile else None
|
|
95
|
+
if candidate and candidate.is_file() and candidate.read_bytes() == default.read_bytes():
|
|
96
|
+
dockerfile = None # the starter image, now shipped with the runtime
|
|
97
|
+
elif dockerfile and dockerfile.startswith("scripts/agents/"):
|
|
98
|
+
notes.append(f"keep {dockerfile}: the gate image was customised")
|
|
99
|
+
config["gates"] = {
|
|
100
|
+
**config["gates"],
|
|
101
|
+
"dockerfile": dockerfile,
|
|
102
|
+
**{k: gates[k] for k in ("inputs", "timeout_seconds", "memory") if k in gates},
|
|
103
|
+
}
|
|
104
|
+
sensitive = install.safe_path(target, V1_SENSITIVE)
|
|
105
|
+
if sensitive.is_file():
|
|
106
|
+
defaults = set(task_scope.sensitive_patterns())
|
|
107
|
+
patterns = install.load(sensitive).get("patterns", [])
|
|
108
|
+
config["sensitive_patterns"] = [p for p in patterns if p.casefold() not in defaults]
|
|
109
|
+
task_scope.load_config(json.dumps(config).encode()) # refuse anything the runtime can't read
|
|
110
|
+
return (json.dumps(config, indent=2) + "\n").encode(), notes
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def leftovers(target: Path, keep: set[str]) -> tuple[list[str], list[str]]:
|
|
114
|
+
"""Files the kit installed that are now unused, and other files in its shared folders."""
|
|
115
|
+
known = [*V1_KIT_ONLY, *V1_RUNTIME, V1_DOCKERFILE]
|
|
116
|
+
removable = [p for p in known if (target / p).is_file() and p not in keep]
|
|
117
|
+
others = [p for p in V1_MAYBE if (target / p).is_file()]
|
|
118
|
+
for folder in V1_FOLDERS:
|
|
119
|
+
if (target / folder).is_dir():
|
|
120
|
+
others += sorted(
|
|
121
|
+
p.relative_to(target).as_posix()
|
|
122
|
+
for p in (target / folder).rglob("*")
|
|
123
|
+
if p.is_file() and "__pycache__" not in p.parts
|
|
124
|
+
)
|
|
125
|
+
return removable, [p for p in others if p not in known and p not in keep]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def main() -> int:
|
|
129
|
+
parser = argparse.ArgumentParser(prog="orca-agent-workflow migrate", description=__doc__)
|
|
130
|
+
parser.add_argument("--target", type=Path, default=Path("."), help="Project folder")
|
|
131
|
+
parser.add_argument("--apply", action="store_true", help="Write; without it, only preview")
|
|
132
|
+
parser.add_argument(
|
|
133
|
+
"--vendor", action="store_true", help="Copy the runtime into .agents/runtime/"
|
|
134
|
+
)
|
|
135
|
+
args = parser.parse_args()
|
|
136
|
+
try:
|
|
137
|
+
target = args.target.expanduser().resolve()
|
|
138
|
+
if (target / task_scope.CONFIG).is_file():
|
|
139
|
+
raise ValueError(f"{task_scope.CONFIG} exists already; use init to add missing files")
|
|
140
|
+
if not (target / V1_POLICY).is_file():
|
|
141
|
+
raise ValueError("No v1 configuration (.agents/orchestration.json)")
|
|
142
|
+
config, notes = convert(target)
|
|
143
|
+
options = argparse.Namespace(
|
|
144
|
+
opencode=(target / ".opencode/commands").is_dir(),
|
|
145
|
+
pre_push_hook=(target / ".githooks/pre-push").is_file(),
|
|
146
|
+
vendor=args.vendor,
|
|
147
|
+
)
|
|
148
|
+
operations = install.plan(target, options, config)
|
|
149
|
+
if args.apply:
|
|
150
|
+
install.apply(target, operations)
|
|
151
|
+
gates = json.loads(config)["gates"]
|
|
152
|
+
keep = {gates["dockerfile"], *gates.get("inputs", [])} - {None}
|
|
153
|
+
removable, unrecognised = leftovers(target, keep)
|
|
154
|
+
report = {
|
|
155
|
+
"target": str(target),
|
|
156
|
+
"version": __version__,
|
|
157
|
+
"applied": args.apply,
|
|
158
|
+
"files": [{"path": op["path"], "action": op["action"]} for op in operations],
|
|
159
|
+
"requires_merge": [op["path"] for op in operations if op["action"] == "merge"],
|
|
160
|
+
"notes": notes,
|
|
161
|
+
"removable": removable,
|
|
162
|
+
"review_before_removing": unrecognised,
|
|
163
|
+
"next": (
|
|
164
|
+
"Merge the listed files (candidates in "
|
|
165
|
+
f"{install.MERGE_FOLDER}/), delete the removable files once nothing of "
|
|
166
|
+
"yours remains in them, run python3 .agents/workflow.py check, and commit."
|
|
167
|
+
if args.apply
|
|
168
|
+
else "Nothing written. Re-run with --apply to migrate."
|
|
169
|
+
),
|
|
170
|
+
}
|
|
171
|
+
print(json.dumps(report, indent=2))
|
|
172
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
173
|
+
parser.exit(1, f"migrate: {exc}\n")
|
|
174
|
+
return 0
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
if __name__ == "__main__":
|
|
178
|
+
sys.exit(main())
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Discover shared Xcode schemes and run a coordinator-selected native test."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import xml.etree.ElementTree as ET
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from orca_agent_workflow import task_scope
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def preview(root: Path) -> dict | None:
|
|
18
|
+
candidates = sorted([*root.glob("*.xcodeproj"), *root.glob("*.xcworkspace")])
|
|
19
|
+
containers = [path for path in candidates if path.is_dir() and not path.is_symlink()]
|
|
20
|
+
if not containers:
|
|
21
|
+
return None
|
|
22
|
+
schemes = []
|
|
23
|
+
for container in containers:
|
|
24
|
+
for path in sorted(container.glob("xcshareddata/xcschemes/*.xcscheme")):
|
|
25
|
+
entry = {"container": container.name, "scheme": path.stem}
|
|
26
|
+
try:
|
|
27
|
+
if not path.resolve().is_relative_to(root):
|
|
28
|
+
raise ValueError("scheme resolves outside the project")
|
|
29
|
+
tree = ET.parse(path)
|
|
30
|
+
entry["test_targets"] = sorted({
|
|
31
|
+
target.attrib["BlueprintName"]
|
|
32
|
+
for target in tree.findall("./TestAction/Testables/TestableReference/BuildableReference")
|
|
33
|
+
if target.get("BlueprintName")
|
|
34
|
+
})
|
|
35
|
+
entry["test_plans"] = [
|
|
36
|
+
plan.get("reference") for plan in tree.findall("./TestAction/TestPlans/TestPlanReference")
|
|
37
|
+
]
|
|
38
|
+
except (OSError, ValueError, ET.ParseError) as exc:
|
|
39
|
+
entry["problem"] = str(exc)
|
|
40
|
+
schemes.append(entry)
|
|
41
|
+
locks = {*root.glob("Package.resolved"), *root.glob("Podfile.lock"), *root.glob("Cartfile.resolved")}
|
|
42
|
+
for container in containers:
|
|
43
|
+
locks.update(container.glob("xcshareddata/swiftpm/Package.resolved"))
|
|
44
|
+
locks.update(container.glob("project.xcworkspace/xcshareddata/swiftpm/Package.resolved"))
|
|
45
|
+
return {
|
|
46
|
+
"platform": "macOS",
|
|
47
|
+
"containers": [path.name for path in containers],
|
|
48
|
+
"shared_schemes": schemes,
|
|
49
|
+
"dependency_locks": sorted(path.relative_to(root).as_posix() for path in locks if path.is_file()),
|
|
50
|
+
"next": (
|
|
51
|
+
"Review the project, build phases, test plan and dependency setup. "
|
|
52
|
+
"Choose a scheme and simulator explicitly. Pass any required local build artifacts with --requires."
|
|
53
|
+
),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def checked_output(command: list[str], root: Path) -> str:
|
|
58
|
+
result = subprocess.run(command, cwd=root, capture_output=True, text=True, timeout=60)
|
|
59
|
+
if result.returncode:
|
|
60
|
+
raise ValueError(result.stderr.strip() or result.stdout.strip() or f"{command[0]} failed")
|
|
61
|
+
return result.stdout.strip()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def run(root: Path, args: argparse.Namespace, report: dict) -> None:
|
|
65
|
+
if sys.platform != "darwin":
|
|
66
|
+
raise ValueError("Native Xcode tests require a macOS host with Xcode and an installed simulator.")
|
|
67
|
+
container = root / task_scope.relative(args.container)
|
|
68
|
+
container_flag = {".xcodeproj": "-project", ".xcworkspace": "-workspace"}.get(container.suffix)
|
|
69
|
+
if not container_flag or not container.is_dir() or not container.resolve().is_relative_to(root):
|
|
70
|
+
raise ValueError("Select an existing .xcodeproj or .xcworkspace within the checkout.")
|
|
71
|
+
report["revision"] = task_scope.git_bytes(root, "rev-parse", "HEAD").decode().strip()
|
|
72
|
+
if task_scope.git_bytes(root, "status", "--porcelain"):
|
|
73
|
+
raise ValueError("Run the host check from a clean, committed checkout.")
|
|
74
|
+
missing = [value for value in args.requires if not (root / task_scope.relative(value)).exists()]
|
|
75
|
+
if missing:
|
|
76
|
+
raise ValueError("Missing required local build artifacts: " + ", ".join(missing))
|
|
77
|
+
|
|
78
|
+
report["xcode"] = checked_output(["/usr/bin/xcodebuild", "-version"], root)
|
|
79
|
+
output = Path(tempfile.mkdtemp(prefix="orca-native-check-")).resolve()
|
|
80
|
+
log = output / "xcodebuild.log"
|
|
81
|
+
result_bundle = output / "Tests.xcresult"
|
|
82
|
+
report.update(log=str(log), result_bundle=str(result_bundle))
|
|
83
|
+
command = [
|
|
84
|
+
"/usr/bin/xcodebuild", container_flag, str(container), "-scheme", args.scheme,
|
|
85
|
+
"-destination", args.destination, "-derivedDataPath", str(output / "DerivedData"),
|
|
86
|
+
"-resultBundlePath", str(result_bundle), "-disableAutomaticPackageResolution",
|
|
87
|
+
"-parallel-testing-enabled", "NO", "CODE_SIGNING_ALLOWED=NO", "test",
|
|
88
|
+
]
|
|
89
|
+
with log.open("w", encoding="utf-8") as stream:
|
|
90
|
+
result = subprocess.run(command, cwd=root, stdout=stream, stderr=subprocess.STDOUT, timeout=args.timeout)
|
|
91
|
+
report["xcode_exit"] = result.returncode
|
|
92
|
+
if not result_bundle.is_dir():
|
|
93
|
+
raise ValueError("Xcode produced no result bundle. Check the log for missing SDKs, simulators or dependencies.")
|
|
94
|
+
summary = json.loads(checked_output([
|
|
95
|
+
"/usr/bin/xcrun", "xcresulttool", "get", "test-results", "summary", "--path", str(result_bundle),
|
|
96
|
+
], root))
|
|
97
|
+
counts = {name: summary.get(name) for name in ("totalTestCount", "passedTests", "failedTests", "skippedTests")}
|
|
98
|
+
if any(type(count) is not int or count < 0 for count in counts.values()):
|
|
99
|
+
raise ValueError("Xcode did not report valid test counts.")
|
|
100
|
+
report.update(counts)
|
|
101
|
+
report["devices"] = [
|
|
102
|
+
entry.get("device", {}) for entry in summary.get("devicesAndConfigurations", [])
|
|
103
|
+
]
|
|
104
|
+
if counts["passedTests"] + counts["failedTests"] == 0:
|
|
105
|
+
raise ValueError("Xcode executed zero tests.")
|
|
106
|
+
if result.returncode or counts["failedTests"]:
|
|
107
|
+
raise ValueError("Xcode reported test or build failures.")
|
|
108
|
+
if (
|
|
109
|
+
report["revision"] != task_scope.git_bytes(root, "rev-parse", "HEAD").decode().strip()
|
|
110
|
+
or task_scope.git_bytes(root, "status", "--porcelain")
|
|
111
|
+
):
|
|
112
|
+
raise ValueError("The checkout changed during the host run.")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main() -> int:
|
|
116
|
+
parser = argparse.ArgumentParser(
|
|
117
|
+
description="Run reviewed application code and Xcode build phases on the coordinator's macOS host."
|
|
118
|
+
)
|
|
119
|
+
parser.add_argument("--container", required=True, help="Checkout-relative .xcodeproj or .xcworkspace")
|
|
120
|
+
parser.add_argument("--scheme", required=True)
|
|
121
|
+
parser.add_argument("--destination", required=True, help="An explicit simulator destination, such as platform=iOS Simulator,id=UUID")
|
|
122
|
+
parser.add_argument("--requires", action="append", default=[], help="Required checkout-relative local artifact; repeatable")
|
|
123
|
+
parser.add_argument("--timeout", type=int, default=900)
|
|
124
|
+
args = parser.parse_args()
|
|
125
|
+
if not simulator_destination(args.destination) or args.timeout <= 0:
|
|
126
|
+
parser.error("Choose a simulator by ID and a positive timeout.")
|
|
127
|
+
report = {"kind": "macOS host", "scheme": args.scheme, "destination": args.destination, "passed": False}
|
|
128
|
+
try:
|
|
129
|
+
run(task_scope.project_root(), args, report)
|
|
130
|
+
report["passed"] = True
|
|
131
|
+
except (ValueError, OSError, subprocess.SubprocessError) as exc:
|
|
132
|
+
report["problem"] = str(exc)
|
|
133
|
+
print(json.dumps(report, indent=2))
|
|
134
|
+
return 0 if report["passed"] else 1
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def simulator_destination(destination: str) -> bool:
|
|
138
|
+
return re.fullmatch(
|
|
139
|
+
r"platform=(?:iOS|watchOS|tvOS|visionOS) Simulator,"
|
|
140
|
+
r"id=[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}",
|
|
141
|
+
destination,
|
|
142
|
+
) is not None
|