#!/usr/bin/env python3 """Public Go2 FL functional skill Python API and CLI (caller never imports Kit). Python: from scripts.go2_fl_skill import start, SkillRun CLI: go2_fl_skill.py validate | run | status | queue | stop Each run creates a new bound authority and config preparation; no grant reuse. """ import argparse import importlib import json from pathlib import Path import subprocess import sys from types import SimpleNamespace ROOT = Path(__file__).resolve().parents[1] if str(ROOT / 'scripts') not in sys.path: sys.path.insert(0, str(ROOT / 'scripts')) import skill_launch_v4 as launch def make_spec(command='validated_nominal', cycles=1, controller='analytic', *, sequence=None, queued=(), stop_at_tick=None, reject_at_tick=None, gui=False): launch.api().validate_request(command, cycles, controller) queued = tuple(launch.api().validate_command(c) for c in queued) if sequence is not None: if command != 'validated_nominal' or cycles != 1 or queued: raise ValueError('A named sequence supplies command/cycles/queue; do not combine overrides') if type(sequence) is not str or sequence not in launch.api().SEQUENCES: raise ValueError('Unknown sequence') commands = launch.api().SEQUENCES[sequence] command, queued = commands[0], commands[1:] cycles = 20 if sequence == 'nominal20' else 6 return launch.validate_spec({'command': command, 'cycles': cycles, 'controller': controller, 'queued': list(queued), 'sequence': sequence, 'stop_at_tick': stop_at_tick, 'reject_at_tick': reject_at_tick, 'gui': gui}) class SkillRun: def __init__(self, output, process=None): self.output = Path(output) self.process = process def query(self): """A detached JSON snapshot; sampled at 1 simulated second or failure/endpoint. Starting has no physical state yet. 'stopped' does not imply all requested cycles completed: inspect stop.reason and completed_cycles. Failure is published by both runtime and supervisor; success requires waited cleanup. """ status = self.output / 'mailbox/status.json' if status.exists(): value = launch.mailbox().read_json(status) if self.process is not None and self.process.poll() not in (None, 0): value.update(state='failed', returncode=self.process.returncode, failure=value.get('failure') or ['supervisor_abnormal_exit']) return value if self.process is not None and self.process.poll() is not None: return {'state': 'failed', 'failure': ['supervisor_exited_before_mailbox'], 'returncode': self.process.returncode} return {'state': 'starting', 'global_tick': 0, 'failure': []} def queue(self, command): launch.api().validate_command(command) self._require_process_live() return launch.mailbox().send(self.output / 'mailbox', 'queue', command) def request_stop(self): self._require_process_live() return launch.mailbox().send(self.output / 'mailbox', 'stop') def _require_process_live(self): if self.process is not None and self.process.poll() is not None: raise RuntimeError('Skill supervisor already exited') def wait(self, timeout=None): if self.process is None: raise RuntimeError('This handle did not launch the supervisor') return self.process.wait(timeout=timeout) def start(output, registration, *, command='validated_nominal', cycles=1, controller='analytic', sequence=None, queued=(), stop_at_tick=None, reject_at_tick=None, analytics_evidence=(), gpu_identity=None, gui=False): spec = make_spec(command, cycles, controller, sequence=sequence, queued=queued, stop_at_tick=stop_at_tick, reject_at_tick=reject_at_tick, gui=gui) output, registration = Path(output), Path(registration) launch.validate_root(output) # invalid requests/roots rejected before process or files launch.registration(registration) require_analytics(spec, analytics_evidence) command_line = ['/usr/bin/python3.12', str(Path(__file__).resolve()), '--campaign', '--output', str(output), '--registration', str(registration), '--spec-json', json.dumps(spec)] for evidence in analytics_evidence: command_line.extend(['--analytics-evidence', str(evidence)]) if gpu_identity is not None: command_line.extend(['--gpu-identity', str(gpu_identity)]) return SkillRun(output, subprocess.Popen(command_line, cwd=ROOT)) def require_analytics(spec, evidence): if spec['controller'] != 'u256': return found = set() for root in evidence: root = Path(root) result = launch.old.read(root / 'campaign-result.json') approval = launch.old.read(root / 'approval.json') if (result.get('success') is not True or approval.get('format') != launch.FORMAT or approval.get('sources') != launch.sources() or approval['spec']['controller'] != 'analytic'): raise PermissionError('Current-source successful supervised analytics required') rows = result.get('rows', []) if len(rows) != 2 or any(r.get('success') is not True for r in rows): raise PermissionError('Complete prepare/run supervised receipts required') row = rows[1] worker_path = root / 'run/worker-result.json' worker = launch.old.read(worker_path, row['worker_result_sha256']) if not launch.complete_analytic_prerequisite(worker, approval['spec']): raise PermissionError('Complete fixed-schedule analytic physics/integrity receipt required') for filename in ('trace.pt', 'initial-state.pt', 'events-and-seams.json'): if launch.b.digest(root / 'run' / filename) != row.get('artifact_sha256', {}).get(filename): raise PermissionError('Analytic evidence artifact changed: ' + filename) found.add(approval['spec']['sequence']) if not {'nominal20', 'S1', 'S2', 'S3'} <= found: raise PermissionError('Parent must supply nominal20/S1/S2/S3 analytic evidence before u256 S1') def execute(args): spec = launch.validate_spec(json.loads(args.spec_json)) require_analytics(spec, args.analytics_evidence) with launch.Reservation(args.registration, args.output, spec, args.gpu_identity) as reservation: import evaluate_cycle_functional_flow as runner return runner.campaign(SimpleNamespace(output=args.output, approval=reservation.path, trusted_approval_sha256=launch.b.digest(reservation.path), skill_v4=True, skill_reservation=reservation, followup_v3=False)) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--worker-fd', type=int, help=argparse.SUPPRESS) parser.add_argument('--campaign', action='store_true', help=argparse.SUPPRESS) parser.add_argument('--spec-json', help=argparse.SUPPRESS) parser.add_argument('--output', type=Path) parser.add_argument('--registration', type=Path) parser.add_argument('--gpu-identity', type=Path) parser.add_argument('--analytics-evidence', type=Path, action='append', default=[]) sub = parser.add_subparsers(dest='mode') validate = sub.add_parser('validate', help='CPU only; no authority, Kit, GPU, or physics') validate.add_argument('--verify-frozen', action='store_true', help='requires CPU Torch; unchanged verify_bundle') authorize = sub.add_parser('authorize', help='explicitly authorize NEW bounded local session; no Kit/GPU') authorize.add_argument('--registration', type=Path, required=True) run = sub.add_parser('run', help='launch new supervised run and wait') run.add_argument('--output', type=Path, required=True) run.add_argument('--registration', type=Path, required=True) run.add_argument('--gpu-identity', type=Path) run.add_argument('--analytics-evidence', type=Path, action='append', default=[]) run.add_argument('--command', default='validated_nominal') run.add_argument('--cycles', type=int, default=1) run.add_argument('--controller', choices=['analytic', 'u256'], default='analytic') run.add_argument('--sequence', choices=('nominal20', 'S1', 'S2', 'S3')) run.add_argument('--queued', action='append', default=[]) run.add_argument('--stop-at-tick', type=int) run.add_argument('--reject-at-tick', type=int) run.add_argument('--gui', action='store_true', help='real Kit window; hold final frame until close (max 10 min)') for operation in ('status', 'queue', 'stop'): child = sub.add_parser(operation) child.add_argument('--output', type=Path, required=True) if operation == 'queue': child.add_argument('command') args = parser.parse_args(argv) if args.worker_fd is not None: import evaluate_cycle_functional_flow as runner return runner.worker(launch.worker_payload(args.worker_fd)) if args.campaign: return execute(args) if args.mode == 'authorize': print(json.dumps(launch.new_registration(args.registration), indent=2)) return 0 if args.mode == 'validate': frozen = None if args.verify_frozen: replay = importlib.import_module(launch.api().__package__ + '.replay') _, frozen = replay.verify_bundle(ROOT) print(json.dumps({'execution_authorized': False, 'new_physics_calls': 0, 'commands': launch.api().COMMANDS, 'sequences': launch.api().SEQUENCES, 'sources': launch.sources(), 'frozen': frozen}, indent=2)) return 0 if args.mode == 'run': handle = start(args.output, args.registration, command=args.command, cycles=args.cycles, controller=args.controller, sequence=args.sequence, queued=args.queued, stop_at_tick=args.stop_at_tick, reject_at_tick=args.reject_at_tick, analytics_evidence=args.analytics_evidence, gpu_identity=args.gpu_identity, gui=args.gui) return handle.wait() if args.mode in ('status', 'queue', 'stop'): handle = SkillRun(args.output) value = (handle.query() if args.mode == 'status' else handle.queue(args.command) if args.mode == 'queue' else handle.request_stop()) print(json.dumps(value, indent=2)) return 0 parser.error('Choose validate/run/status/queue/stop') if __name__ == '__main__': raise SystemExit(main())