| 1 | #!/usr/bin/env python3 |
| 2 | """Exercise the real Workflow CLI, scripted provider, sealed oracle and bwrap.""" |
| 3 | |
| 4 | import argparse |
| 5 | import hashlib |
| 6 | import json |
| 7 | import os |
| 8 | import shutil |
| 9 | import subprocess |
| 10 | import tempfile |
| 11 | import threading |
| 12 | import time |
| 13 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 14 | from pathlib import Path |
| 15 | |
| 16 | |
| 17 | def git(cwd, *args): |
| 18 | return subprocess.run( |
| 19 | ["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True |
| 20 | ).stdout.strip() |
| 21 | |
| 22 | |
| 23 | def sse(content=None, tool=None, tool_name=None, call_id=None): |
| 24 | delta = {"content": content} if tool is None else { |
| 25 | "tool_calls": [{"index": 0, "id": call_id, "type": "function", |
| 26 | "function": {"name": tool_name, "arguments": json.dumps(tool)}}] |
| 27 | } |
| 28 | finish = "stop" if tool is None else "tool_calls" |
| 29 | chunks = [ |
| 30 | {"id": "local-evaluator", "choices": [{"index": 0, "delta": delta, |
| 31 | "finish_reason": None}]}, |
| 32 | {"id": "local-evaluator", "choices": [{"index": 0, "delta": {}, |
| 33 | "finish_reason": finish}]}, |
| 34 | {"id": "local-evaluator", "choices": [], |
| 35 | "usage": {"prompt_tokens": 12, "completion_tokens": 12, "total_tokens": 24}}, |
| 36 | ] |
| 37 | return ("".join("data: " + json.dumps(chunk, separators=(",", ":")) + "\n\n" |
| 38 | for chunk in chunks) + "data: [DONE]\n\n").encode() |
| 39 | |
| 40 | |
| 41 | def handler(programs, ledger, hidden_path, hidden_sentinel): |
| 42 | class Handler(BaseHTTPRequestHandler): |
| 43 | counts = {"cand_001": 0, "cand_002": 0} |
| 44 | lock = threading.Lock() |
| 45 | |
| 46 | def log_message(self, *_args): |
| 47 | pass |
| 48 | |
| 49 | def do_GET(self): |
| 50 | body = b'{"object":"list","data":[]}' |
| 51 | self.send_response(200) |
| 52 | self.send_header("Content-Type", "application/json") |
| 53 | self.send_header("Content-Length", str(len(body))) |
| 54 | self.end_headers() |
| 55 | self.wfile.write(body) |
| 56 | |
| 57 | def do_POST(self): |
| 58 | request = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0")))) |
| 59 | messages = json.dumps(request.get("messages", [])) |
| 60 | name = next((item for item in Handler.counts if item in messages), None) |
| 61 | with Handler.lock: |
| 62 | if name is not None: |
| 63 | call = Handler.counts[name] |
| 64 | Handler.counts[name] += 1 |
| 65 | else: |
| 66 | call = -1 |
| 67 | ledger.append({"candidate": name, "call": call, "path": self.path, |
| 68 | "model": request.get("model"), |
| 69 | "hidden_exposed": hidden_sentinel in messages}) |
| 70 | if name is not None and call == 0: |
| 71 | body = sse(tool={"action": "run", "command": f"cat {hidden_path}", |
| 72 | "timeout_ms": 1000}, tool_name="bash", |
| 73 | call_id=f"local-{name}-shell-hidden-probe") |
| 74 | elif name is not None and call == 1: |
| 75 | body = sse(tool={"path": str(hidden_path)}, tool_name="read", |
| 76 | call_id=f"local-{name}-hidden-probe") |
| 77 | elif name is not None and call == 2: |
| 78 | body = sse(tool={"path": "src/probe.py"}, tool_name="read", |
| 79 | call_id=f"local-{name}-read") |
| 80 | elif name is not None and call == 3: |
| 81 | body = sse(tool={"path": "src/probe.py", "content": programs[name]}, |
| 82 | tool_name="write", call_id=f"local-{name}-write") |
| 83 | elif name is not None: |
| 84 | body = sse(content=f"### SUMMARY\nScripted {name} candidate.\n\n" |
| 85 | "### CHANGES\n- src/probe.py\n\n" |
| 86 | "### EVIDENCE\n- Read and wrote src/probe.py with host tools.\n") |
| 87 | else: |
| 88 | body = sse(content="Unexpected request in local provider fixture.") |
| 89 | self.send_response(200) |
| 90 | self.send_header("Content-Type", "text/event-stream") |
| 91 | self.send_header("Content-Length", str(len(body))) |
| 92 | self.end_headers() |
| 93 | self.wfile.write(body) |
| 94 | |
| 95 | return Handler |
| 96 | |
| 97 | |
| 98 | def last_workflow(path): |
| 99 | if not path.is_file(): |
| 100 | return {} |
| 101 | records = [json.loads(line) for line in path.read_text().splitlines()] |
| 102 | runs = [record["run"] for record in records if "run" in record] |
| 103 | return runs[-1] if runs else {} |
| 104 | |
| 105 | |
| 106 | def descendant_pids(token): |
| 107 | found = [] |
| 108 | for cmdline in Path("/proc").glob("[0-9]*/cmdline"): |
| 109 | try: |
| 110 | if token.encode() in cmdline.read_bytes(): |
| 111 | found.append(int(cmdline.parent.name)) |
| 112 | except (OSError, ValueError): |
| 113 | continue |
| 114 | return found |
| 115 | |
| 116 | |
| 117 | def main(): |
| 118 | parser = argparse.ArgumentParser() |
| 119 | parser.add_argument("--codewhale", type=Path, required=True) |
| 120 | parser.add_argument("--workflow-source", type=Path, required=True) |
| 121 | parser.add_argument("--output", type=Path, required=True) |
| 122 | parser.add_argument("--source-sha", required=True) |
| 123 | args = parser.parse_args() |
| 124 | output = args.output.resolve() |
| 125 | output.mkdir(parents=True, exist_ok=False) |
| 126 | workspace = output / "workspace" |
| 127 | (workspace / "src").mkdir(parents=True) |
| 128 | (workspace / "src/probe.py").write_text( |
| 129 | "import json,sys\njson.load(sys.stdin)\nprint(json.dumps({'ok':False}))\n" |
| 130 | ) |
| 131 | (workspace / "README.md").write_text("Implement the JSON probe in src/probe.py.\n") |
| 132 | git(workspace, "init", "-q") |
| 133 | git(workspace, "add", ".") |
| 134 | git(workspace, "-c", "user.name=Native E2E", "-c", |
| 135 | "user.email=native@example.invalid", "commit", "-qm", "baseline") |
| 136 | baseline = git(workspace, "rev-parse", "HEAD") |
| 137 | sibling = output / "sibling" |
| 138 | git(workspace, "worktree", "add", "--detach", str(sibling), "HEAD") |
| 139 | (sibling / "sibling-secret").write_text("synthetic sibling secret\n") |
| 140 | parent_secret = workspace / ".codewhale" / "parent-secret" |
| 141 | parent_secret.parent.mkdir() |
| 142 | parent_secret.write_text("synthetic parent secret\n") |
| 143 | git_common_before = hashlib.sha256((workspace / ".git/config").read_bytes()).hexdigest() |
| 144 | host_secret = output / "host-secret" |
| 145 | host_secret.write_text("synthetic host secret\n") |
| 146 | home_secret = output / "host-home" / "home-secret" |
| 147 | home_secret.parent.mkdir() |
| 148 | home_secret.write_text("synthetic home secret\n") |
| 149 | hidden = output / "hidden.json" |
| 150 | public = output / "public.json" |
| 151 | targets = {"host": str(host_secret), "sibling": str(sibling / "sibling-secret"), |
| 152 | "parent": str(parent_secret), "git_common": str(workspace / ".git/config"), |
| 153 | "hidden": str(hidden), |
| 154 | "home": str(home_secret)} |
| 155 | inherited_fd = os.open(host_secret, os.O_RDONLY) |
| 156 | os.set_inheritable(inherited_fd, True) |
| 157 | orphan_token = "codewhale-evaluator-e2e-" + hashlib.sha256( |
| 158 | str(output).encode()).hexdigest()[:16] |
| 159 | program = ( |
| 160 | "import json,os,subprocess,sys\n" |
| 161 | "json.load(sys.stdin)\n" |
| 162 | f"targets={targets!r}\nfd={inherited_fd}\norphan_token={orphan_token!r}\n" |
| 163 | "def blocked(path, mode):\n" |
| 164 | " try:\n" |
| 165 | " with open(path, mode) as stream:\n" |
| 166 | " stream.read() if mode=='r' else stream.write('tampered')\n" |
| 167 | " return False\n" |
| 168 | " except OSError: return True\n" |
| 169 | "result={}\n" |
| 170 | "for name,path in targets.items():\n" |
| 171 | " result[name+'_read_blocked']=blocked(path,'r')\n" |
| 172 | " result[name+'_write_blocked']=blocked(path,'w')\n" |
| 173 | "result['credential_env_blocked']='DEEPSEEK_API_KEY' not in os.environ\n" |
| 174 | "try: result['inherited_fd_blocked']=b'synthetic host secret' not in os.read(fd,1024)\n" |
| 175 | "except OSError: result['inherited_fd_blocked']=True\n" |
| 176 | "child=subprocess.run([sys.executable,'-c','open(sys.argv[1]).read()',targets['host']],stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n" |
| 177 | "result['child_blocked']=child.returncode!=0\n" |
| 178 | "subprocess.Popen([sys.executable,'-c','import time; time.sleep(120)',orphan_token])\n" |
| 179 | "print(json.dumps(result))\n" |
| 180 | ) |
| 181 | compile(program, "<isolated-candidate>", "exec") |
| 182 | expected = {name + "_" + op + "_blocked": True |
| 183 | for name in targets for op in ("read", "write")} |
| 184 | expected.update({"credential_env_blocked": True, "inherited_fd_blocked": True, |
| 185 | "child_blocked": True}) |
| 186 | hidden_sentinel = "heldout-writer-sentinel-" + hashlib.sha256( |
| 187 | str(output).encode()).hexdigest()[:16] |
| 188 | public.write_text(json.dumps([{"input": {"case": i}, "expected": expected} |
| 189 | for i in range(2)]) + "\n") |
| 190 | hidden.write_text(json.dumps([{"input": {"case": 2, |
| 191 | "hidden_sentinel": hidden_sentinel}, |
| 192 | "expected": expected}]) + "\n") |
| 193 | spec = output / "evaluator.json" |
| 194 | spec.write_text(json.dumps({ |
| 195 | "version": 1, "objective": "Verify the isolated JSON probe", |
| 196 | "baseline_sha": baseline, "allowed_write_roots": ["src"], |
| 197 | "protected_paths": ["tests"], "isolation_backend": "linux-bwrap", |
| 198 | "max_wall_secs": 120, |
| 199 | "hard_gates": [ |
| 200 | {"candidate_argv": ["/usr/bin/python3", "src/probe.py"], |
| 201 | "cases_path": str(public), "timeout_secs": 20, "min_tests": 2, |
| 202 | "holdout": False}, |
| 203 | {"candidate_argv": ["/usr/bin/python3", "src/probe.py"], |
| 204 | "cases_path": str(hidden), "timeout_secs": 20, "min_tests": 1, |
| 205 | "holdout": True}, |
| 206 | ], |
| 207 | }, indent=2) + "\n") |
| 208 | claim = "import json,sys\njson.load(sys.stdin)\nprint(json.dumps({'status':'PASS','test_count':999}))\n" |
| 209 | compile(claim, "<self-reported-candidate>", "exec") |
| 210 | requests = [] |
| 211 | server = ThreadingHTTPServer(("127.0.0.1", 0), |
| 212 | handler({"cand_001": claim, "cand_002": program}, |
| 213 | requests, hidden, hidden_sentinel)) |
| 214 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 215 | thread.start() |
| 216 | config = output / "config.toml" |
| 217 | config.write_text('provider = "deepseek"\n[providers.deepseek]\n' |
| 218 | f'model = "deepseek-flash"\nbase_url = "http://127.0.0.1:{server.server_port}/v1"\n') |
| 219 | payload = {"action": "run", "script": args.workflow_source.read_text(), |
| 220 | "args": {"strategy": "search", "brief": "Verify the isolated JSON probe", |
| 221 | "n": 2, "model": "deepseek-flash", "writeRoots": ["src"], |
| 222 | "evaluator": {"manifestPath": str(spec)}}} |
| 223 | env = os.environ.copy() |
| 224 | env.update({"DEEPSEEK_API_KEY": "synthetic-local-only", |
| 225 | "CODEWHALE_HOME": str(output / "host-home"), |
| 226 | "CODEWHALE_TELEMETRY": "0", "CODEWHALE_NO_UPDATE_CHECK": "1", |
| 227 | "HTTPS_PROXY": "http://127.0.0.1:9", |
| 228 | "HTTP_PROXY": "http://127.0.0.1:9", |
| 229 | "NO_PROXY": "127.0.0.1,localhost"}) |
| 230 | before = set(Path(tempfile.gettempdir()).glob("codewhale-evaluator-workflow_*")) |
| 231 | command = [str(args.codewhale.resolve()), "--config", str(config), |
| 232 | "--workspace", str(workspace), "--provider", "deepseek", |
| 233 | "--model", "deepseek-flash", "--sandbox-mode", "workspace-write", |
| 234 | "workflow-tool", "--approval-source", "explicit-workflow-command", |
| 235 | "--input-json", json.dumps(payload, separators=(",", ":"))] |
| 236 | try: |
| 237 | completed = subprocess.run(command, cwd=workspace, env=env, |
| 238 | capture_output=True, text=True, timeout=240, |
| 239 | check=False, pass_fds=(inherited_fd,)) |
| 240 | finally: |
| 241 | os.close(inherited_fd) |
| 242 | server.shutdown() |
| 243 | thread.join(timeout=5) |
| 244 | (output / "stdout.log").write_text(completed.stdout) |
| 245 | (output / "stderr.log").write_text(completed.stderr) |
| 246 | (output / "mock_requests.json").write_text(json.dumps(requests, indent=2) + "\n") |
| 247 | time.sleep(2) |
| 248 | surviving_descendants = descendant_pids(orphan_token) |
| 249 | roots = [path for path in |
| 250 | set(Path(tempfile.gettempdir()).glob("codewhale-evaluator-workflow_*")) - before |
| 251 | if (path / "manifest.json").is_file()] |
| 252 | if len(roots) == 1: |
| 253 | shutil.copytree(roots[0], output / "sealed-evidence") |
| 254 | run = last_workflow(workspace / ".codewhale/workflow-runs.jsonl") |
| 255 | evaluation = {} |
| 256 | replay = {} |
| 257 | if len(roots) == 1: |
| 258 | root = roots[0] |
| 259 | for name, target in (("candidate_1", evaluation), ("candidate_2", replay)): |
| 260 | path = root / f"{name}-evaluation.json" |
| 261 | if path.is_file(): |
| 262 | target.update(json.loads(path.read_text())) |
| 263 | replay_path = root / "candidate_2-replay.json" |
| 264 | if replay_path.is_file(): |
| 265 | replay["replay"] = json.loads(replay_path.read_text()) |
| 266 | receipt = { |
| 267 | "schema_version": 1, "source_sha": args.source_sha, |
| 268 | "binary_sha256": hashlib.sha256(args.codewhale.read_bytes()).hexdigest(), |
| 269 | "exit_code": completed.returncode, "workflow_status": run.get("status"), |
| 270 | "evaluator_roots": [str(path) for path in roots], |
| 271 | "claim_status": evaluation.get("status"), |
| 272 | "isolated_status": replay.get("status"), |
| 273 | "replay_status": replay.get("replay", {}).get("status"), |
| 274 | "claim_tests": evaluation.get("test_count"), |
| 275 | "isolated_tests": replay.get("test_count"), |
| 276 | "replay_tests": replay.get("replay", {}).get("test_count"), |
| 277 | "provider_requests": requests, |
| 278 | "writer_hidden_exposed": any(item["hidden_exposed"] for item in requests), |
| 279 | "surviving_descendant_pids": surviving_descendants, |
| 280 | "descendants_reaped": not surviving_descendants, |
| 281 | "host_secret_untouched": host_secret.read_text() == "synthetic host secret\n", |
| 282 | "sibling_secret_untouched": (sibling / "sibling-secret").read_text() |
| 283 | == "synthetic sibling secret\n", |
| 284 | "parent_secret_untouched": parent_secret.read_text() == "synthetic parent secret\n", |
| 285 | "git_common_untouched": hashlib.sha256( |
| 286 | (workspace / ".git/config").read_bytes()).hexdigest() == git_common_before, |
| 287 | "hidden_unchanged": hashlib.sha256(hidden.read_bytes()).hexdigest() |
| 288 | == replay.get("replay", {}).get("oracle_sha256", [None, None])[1], |
| 289 | } |
| 290 | receipt["pass"] = all([ |
| 291 | completed.returncode == 0, len(roots) == 1, |
| 292 | receipt["claim_status"] == "FAIL", receipt["claim_tests"] == 2, |
| 293 | receipt["isolated_status"] == "PASS", receipt["isolated_tests"] == 2, |
| 294 | receipt["replay_status"] == "PASS", receipt["replay_tests"] == 3, |
| 295 | receipt["host_secret_untouched"], receipt["sibling_secret_untouched"], |
| 296 | receipt["parent_secret_untouched"], receipt["hidden_unchanged"], |
| 297 | receipt["git_common_untouched"], |
| 298 | not receipt["writer_hidden_exposed"], |
| 299 | receipt["descendants_reaped"], |
| 300 | len(requests) >= 4, |
| 301 | ]) |
| 302 | (output / "receipt.json").write_text(json.dumps(receipt, indent=2) + "\n") |
| 303 | print(json.dumps(receipt)) |
| 304 | return 0 if receipt["pass"] else 1 |
| 305 | |
| 306 | |
| 307 | if __name__ == "__main__": |
| 308 | raise SystemExit(main()) |
| 309 |