| 1 | import argparse |
| 2 | import hashlib |
| 3 | import json |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import shutil |
| 7 | import signal |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import time |
| 11 | |
| 12 | HERE = Path(__file__).resolve().parent |
| 13 | |
| 14 | |
| 15 | def sha(path): |
| 16 | with path.open('rb') as handle: |
| 17 | return hashlib.file_digest(handle, 'sha256').hexdigest() |
| 18 | |
| 19 | |
| 20 | def rows(path): |
| 21 | return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] |
| 22 | |
| 23 | |
| 24 | def credential(args): |
| 25 | key = os.environ.get('DEEPSEEK_API_KEY', '').strip() |
| 26 | if not key and args.codewhale_secret_store: |
| 27 | path = args.codewhale_secret_store.resolve() |
| 28 | if path.stat().st_mode & 0o077: |
| 29 | raise RuntimeError('Credential store must be private (0600)') |
| 30 | key = json.loads(path.read_text())['entries']['deepseek'].strip() |
| 31 | if not key: |
| 32 | raise RuntimeError('Set DEEPSEEK_API_KEY or pass --codewhale-secret-store explicitly') |
| 33 | return key |
| 34 | |
| 35 | |
| 36 | def task(args, role, capability, key, expires): |
| 37 | directory = args.output |
| 38 | state = directory / f'{role}-state' |
| 39 | workspace = directory / f'{role}-workspace' |
| 40 | state.mkdir(mode=0o700) |
| 41 | workspace.mkdir(mode=0o700) |
| 42 | runtime = directory / 'runtime' |
| 43 | runtime.mkdir(exist_ok=True) |
| 44 | mcp = state / 'mcp.json' |
| 45 | tools = ['profile_training', 'publish_detector'] if role == 'creator' else ['discover_capability', 'apply_detector'] |
| 46 | mcp.write_text(json.dumps({'servers': {'whalenet': { |
| 47 | 'command': shutil.which('node'), 'args': [str(HERE / 'server.mts')], 'cwd': str(workspace), |
| 48 | 'env': {'WHALENET_ROLE': role, 'WHALENET_DIRECTORY': str(directory), 'WHALENET_EXPIRES_AT': str(expires), |
| 49 | 'WHALENET_PYTHON': sys.executable, **({'WHALENET_CAPABILITY': capability} if capability else {})}, |
| 50 | 'disabled': False, 'connect_timeout': 10, 'execute_timeout': 10, |
| 51 | }}}, indent=2) + '\n') |
| 52 | config = state / 'config.toml' |
| 53 | config.write_text('telemetry = false\nprovider = "deepseek"\nmodel = "deepseek-flash"\n' |
| 54 | 'reasoning_effort = "off"\n' |
| 55 | '[providers.deepseek]\nbase_url = "https://api.deepseek.com"\n' |
| 56 | '[tools]\nalways_load = ' + json.dumps(['mcp_whalenet_' + tool for tool in tools]) + '\n' |
| 57 | '[retry]\nenabled = false\nmax_retries = 0\n' |
| 58 | '[stream_recovery]\nmax_resumes = 0\nmax_transparent_retries = 0\n') |
| 59 | prompt = workspace / 'task.txt' |
| 60 | if role == 'creator': |
| 61 | text = ('Create a reusable detector for unusually slow build jobs from the supplied historical fixture. ' |
| 62 | 'Use your admitted MCP tools to inspect the training profile, then choose and publish one sensible ' |
| 63 | 'robust duration-regression capability. Choose its name, sensitivity and rationale yourself. ' |
| 64 | 'Avoid fitting to individual noisy measurements. A later independent task must be able to apply ' |
| 65 | 'the saved rule without your conversation or live Python state. Only the listed tools are admitted. ' |
| 66 | 'Do not use shell, files, network, subagents or external coordination. Finish with the actual ' |
| 67 | 'capability hash, thresholds and brief rationale from the tool result; do not invent results.') |
| 68 | else: |
| 69 | text = ('A previous task left a duration-regression capability admitted to this task. Discover it and ' |
| 70 | 'apply it to the later held-out build batch using your MCP tools. Report which measurements ' |
| 71 | 'exceed their saved thresholds and cite the capability hash. You have no access to the previous ' |
| 72 | 'conversation and cannot publish or modify capabilities. Only the listed tools are admitted. ' |
| 73 | 'Do not use shell, files, network, subagents or external coordination. Use actual tool results.') |
| 74 | prompt.write_text(text + '\n') |
| 75 | env = {name: os.environ[name] for name in ('PATH', 'SYSTEMROOT') if name in os.environ} |
| 76 | env.update({'CODEWHALE_HOME': str(state), 'CODEWHALE_CONFIG_PATH': str(config), |
| 77 | 'CODEWHALE_MCP_CONFIG': str(mcp), 'CODEWHALE_RUNTIME_DIR': str(runtime), |
| 78 | 'CODEWHALE_MAX_OUTPUT_TOKENS': '4096', 'DEEPSEEK_API_KEY': key, 'NO_COLOR': '1', 'TERM': 'dumb'}) |
| 79 | command = [str(args.binary), 'exec', '--provider', 'deepseek', '--model', 'deepseek-flash', |
| 80 | '--reasoning-effort', 'off', '--auto', '--sandbox', 'workspace-write' if role == 'creator' else 'read-only', |
| 81 | '--allowed-tools', ','.join('mcp_whalenet_' + tool for tool in tools), |
| 82 | '--max-turns', '6', '--max-tool-calls', '2', '--output-format', 'stream-json', '--prompt-file', str(prompt)] |
| 83 | (directory / f'{role}-launch.json').write_text(json.dumps({'command': command, 'workspace': str(workspace), |
| 84 | 'config_sha256': sha(config), 'mcp_config_sha256': sha(mcp), 'prompt_sha256': sha(prompt), |
| 85 | 'max_seconds': 180, 'max_turns': 6, 'max_calls_per_turn': 2, 'max_output_tokens_per_call': 4096}, indent=2) + '\n') |
| 86 | print(f'Starting real DeepSeek {role} task', flush=True) |
| 87 | started = time.monotonic() |
| 88 | with (directory / f'{role}-stream.jsonl').open('w') as stdout, (directory / f'{role}-stderr.log').open('w') as stderr: |
| 89 | process = subprocess.Popen(command, cwd=workspace, env=env, stdout=stdout, stderr=stderr, start_new_session=True) |
| 90 | try: |
| 91 | code = process.wait(timeout=180) |
| 92 | except BaseException: |
| 93 | os.killpg(process.pid, signal.SIGTERM) |
| 94 | try: |
| 95 | process.wait(timeout=5) |
| 96 | except subprocess.TimeoutExpired: |
| 97 | os.killpg(process.pid, signal.SIGKILL) |
| 98 | process.wait() |
| 99 | raise |
| 100 | stream = [] |
| 101 | for line in (directory / f'{role}-stream.jsonl').read_text().splitlines(): |
| 102 | try: |
| 103 | stream.append(json.loads(line)) |
| 104 | except ValueError: |
| 105 | pass |
| 106 | terminal = [event['meta'] for event in stream if event.get('type') == 'metadata' and event.get('meta', {}).get('receipt_kind') == 'terminal'] |
| 107 | receipt = {'role': role, 'exit_code': code, 'duration_seconds': round(time.monotonic() - started, 2), 'terminal': terminal} |
| 108 | (directory / f'{role}-receipt.json').write_text(json.dumps(receipt, indent=2) + '\n') |
| 109 | if code != 0 or len(terminal) != 1 or terminal[0].get('provider') != 'deepseek': |
| 110 | raise RuntimeError(f'{role} did not return one successful DeepSeek terminal receipt; inspect retained logs') |
| 111 | events = rows(directory / f'{role}.jsonl') |
| 112 | starts = [event for event in events if event['event'] == 'start'] |
| 113 | if len(starts) != 1: |
| 114 | raise RuntimeError(f'{role} did not use exactly one TypeScript/Python worker') |
| 115 | for field in ('node_pid', 'python_pid'): |
| 116 | pid = starts[0][field] |
| 117 | for _ in range(30): |
| 118 | try: |
| 119 | os.kill(pid, 0) |
| 120 | except ProcessLookupError: |
| 121 | break |
| 122 | time.sleep(0.1) |
| 123 | else: |
| 124 | raise RuntimeError(f'{role} {field} remained alive after task completion') |
| 125 | return terminal[0], events |
| 126 | |
| 127 | |
| 128 | def main(): |
| 129 | parser = argparse.ArgumentParser(description='Run two real DeepSeek Codewhale tasks with Python, TypeScript, MCP and durable reuse.') |
| 130 | parser.add_argument('--binary', type=Path, required=True) |
| 131 | parser.add_argument('--output', type=Path, required=True) |
| 132 | parser.add_argument('--codewhale-secret-store', type=Path) |
| 133 | args = parser.parse_args() |
| 134 | args.binary = args.binary.resolve(strict=True) |
| 135 | args.output = args.output.resolve() |
| 136 | if shutil.which('node') is None or not (HERE / 'node_modules/@modelcontextprotocol/server').is_dir(): |
| 137 | raise RuntimeError('Install Node.js 22.18+ and run npm ci --ignore-scripts in the demo directory') |
| 138 | key = credential(args) |
| 139 | args.output.mkdir(parents=True, exist_ok=False, mode=0o700) |
| 140 | sources = {path.name: sha(path) for path in HERE.iterdir() if path.is_file()} |
| 141 | summary = {'status': 'in_progress', 'binary': str(args.binary), 'binary_sha256': sha(args.binary), 'source_hashes': sources} |
| 142 | summary_path = args.output / 'summary.json' |
| 143 | summary_path.write_text(json.dumps(summary, indent=2) + '\n') |
| 144 | try: |
| 145 | expires = int(time.time() * 1000) + 3600000 |
| 146 | creator, creation = task(args, 'creator', None, key, expires) |
| 147 | published = [e['result'] for e in creation if e['event'] == 'tool_result' and e['tool'] == 'publish_detector'] |
| 148 | if len(published) != 1: |
| 149 | raise RuntimeError('Creator did not publish exactly one capability') |
| 150 | capability = published[0]['capability_sha256'] |
| 151 | if sha(args.output / f'{capability}.json') != capability: |
| 152 | raise RuntimeError('Published capability digest mismatch') |
| 153 | summary.update({'capability_sha256': capability, 'creator': creator}) |
| 154 | summary_path.write_text(json.dumps(summary, indent=2) + '\n') |
| 155 | consumer, consumption = task(args, 'consumer', capability, key, expires) |
| 156 | applied = [e['result'] for e in consumption if e['event'] == 'tool_result' and e['tool'] == 'apply_detector'] |
| 157 | if len(applied) != 1 or applied[0]['capability_sha256'] != capability: |
| 158 | raise RuntimeError('Later task did not reuse the admitted capability') |
| 159 | fitted = [e for e in creation if e['event'] == 'python_result'] |
| 160 | scored = [e for e in consumption if e['event'] == 'python_result'] |
| 161 | if len(fitted) < 2 or fitted[0]['python_pid'] != fitted[1]['python_pid'] or fitted[1]['sequence'] <= fitted[0]['sequence']: |
| 162 | raise RuntimeError('Creator did not retain Python state across calls') |
| 163 | if not scored or scored[0]['python_pid'] == fitted[0]['python_pid'] or consumer.get('session_id') == creator.get('session_id'): |
| 164 | raise RuntimeError('Later task was not a fresh Codewhale session and Python worker') |
| 165 | if [row['regression'] for row in applied[0]['results']] != [False, True, False, True]: |
| 166 | raise RuntimeError('Saved detector did not identify the held-out regressions') |
| 167 | if any(sha(HERE / name) != value for name, value in sources.items()): |
| 168 | raise RuntimeError('Demo source changed during execution') |
| 169 | summary.update({'status': 'passed', 'consumer': consumer, 'later_results': applied[0], |
| 170 | 'persistent_python_within_first_task': True, 'fresh_worker_for_later_task': True, |
| 171 | 'children_stopped_between_tasks': True, 'fixture_data': True, 'transport': 'local_stdio'}) |
| 172 | except BaseException as error: |
| 173 | summary.update({'status': 'failed', 'error_type': type(error).__name__, 'error': str(error)}) |
| 174 | raise |
| 175 | finally: |
| 176 | summary_path.write_text(json.dumps(summary, indent=2) + '\n') |
| 177 | print(f'Receipt: {summary_path}', flush=True) |
| 178 | |
| 179 | |
| 180 | if __name__ == '__main__': |
| 181 | main() |
| 182 |