#!/usr/bin/env python3 """Read existing Cloud MCP inventory and verified finite-one-target operations. No planning, submit, approval, live inventory, job, VM access or service changes. Stored checkpoints supply immutable plan/zero-gate witnesses; MCP supplies the current authorized customer/device view and operation aggregate. A separate live same-nonce submit observation can be attached as an already saved receipt. """ import argparse import hashlib import json import os from pathlib import Path import cloud_mvp_acceptance as cloud require = cloud.contract.require READ_TOOLS = frozenset(('tenants.list', 'inventory.list_devices', 'inventory.get_device', 'monitoring.get_health', 'jobs.get')) class StoredBackend(cloud.Backend): def call(self, name, args): require(name in READ_TOOLS, 'stored-data tool allowlist') self.sequence += 1 response = self.request(dict(jsonrpc='2.0', id=self.sequence, method='tools/call', params=dict(name=name, arguments=args))) data = response.get('data') or {} require(response['status'] == 200 and 'result' in data and not data['result'].get('isError'), 'authorized stored MCP read failed') return data['result']['structuredContent'] def witness(path): path = Path(path).resolve() require(path.is_relative_to((cloud.ROOT/'devstate').resolve()), 'private evidence path required') data = cloud.contract.protected_json(path) return data, dict(path=str(path.relative_to(cloud.ROOT)), sha256=hashlib.sha256(path.read_bytes()).hexdigest()) def aggregate(counts): n = sum(counts.values()) if not n: return None if counts.get('unknown', 0): return 'needs_attention' if counts.get('succeeded', 0) == n: return 'succeeded' if sum(counts.get(s, 0) for s in ('succeeded', 'failed', 'cancelled', 'expired')) == n: return 'partially_succeeded' if counts.get('succeeded', 0) else ('cancelled' if counts.get('cancelled', 0) == n else 'failed') return 'running' if any(counts.get(s, 0) for s in ('running', 'verifying', 'awaiting_reboot')) else 'queued' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--read-stored-mcp', action='store_true', required=True) parser.add_argument('--checkpoint', type=Path, action='append', required=True) parser.add_argument('--idempotency-receipt', type=Path) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() require(len(args.checkpoint) <= 20, 'bounded existing operation references') output = args.output.resolve() require(output.is_relative_to((cloud.ROOT/'devstate').resolve()) and not output.exists(), 'new private output required') installed = cloud.contract.protected_json(cloud.ROOT/'devstate/remote-vm.json') identity = installed['identity'] backend = StoredBackend() tenants = backend.call('tenants.list', {}) require(not tenants['truncated'] and not tenants['next_cursor'] and any(t['tenant_id'] == cloud.TENANT for t in tenants['items']), 'authorized customer missing') pages = []; cursor = None; devices = []; seen = set() for _ in range(10): page = backend.call('inventory.list_devices', dict(tenant_id=cloud.TENANT, cursor=cursor, limit=100)) pages.append({k: page.get(k) for k in ('as_of', 'completeness', 'truncated', 'next_cursor')}) devices.extend(page['items']) cursor = page.get('next_cursor') if not cursor: require(not page['truncated'], 'device list lacks continuation') break require(cursor not in seen, 'repeated inventory cursor'); seen.add(cursor) else: require(False, 'device list exceeds bounded report') require(len({d['agent_id'] for d in devices}) == len(devices), 'duplicate device listing') selected = [d for d in devices if d['asset_id'] == identity['asset_id'] and d['agent_id'] == identity['agent_id']] require(len(selected) == 1, 'fixed permanent Cloud VM missing') device = backend.call('inventory.get_device', dict(tenant_id=cloud.TENANT, asset_id=identity['asset_id'])) inventory = device.get('inventory') or {} require(device['agent_id'] == identity['agent_id'] and device['presence'] == 'online' and inventory.get('architecture') == 'x86_64' and bool(inventory.get('os')) and not inventory['os'].startswith('Windows') and 0 <= (cloud.contract.now()-cloud.contract.timestamp(device['last_contact_at'])).total_seconds() < 90, 'fresh fixed Linux target unavailable') operations = []; submit_contexts = {} for path in args.checkpoint: checkpoint, source = witness(path) require(checkpoint.get('verified') is True, 'native checkpoint not verified') plan = checkpoint['plan']; job = checkpoint['job'] require(hashlib.sha256(bytes(plan['plan_payload_bytes'])).hexdigest() == plan['plan_hash'], 'immutable plan bytes mismatch') require(plan['resolved_targets'] == [identity] and len(plan['jobs']) == 1 and plan['jobs'][0] == job and job['agent_id'] == identity['agent_id'] and job['asset_id'] == identity['asset_id'], 'exact finite one-target plan required') require(all(checkpoint['preapproval'][k] == 0 for k in ('jobs', 'outbox', 'permits')), 'pending zero-gate witness missing') audit = checkpoint['audit'] require(audit['origin'] == 'dev_test_browser_simulation' and audit['simulation'] is True and audit['plan_hash'] == plan['plan_hash'], 'actual simulated UI audit missing') operation = backend.call('jobs.get', dict(tenant_id=cloud.TENANT, operation_id=checkpoint['operation_id'])) require(operation['plan_id'] == plan['plan_id'] and operation['plan_hash'] == plan['plan_hash'] and operation['planned_job_count'] == 1 and operation['job_count'] == 1 and len(operation['jobs']) == 1 and operation['jobs'][0]['job_id'] == job['job_id'] and operation['jobs'][0]['attempt_id'] == job['attempt_id'] and sum(operation['counts'].values()) == 1 and operation['execution_state'] == aggregate(operation['counts']), 'stored operation binding/aggregate mismatch') operations.append(dict(case=checkpoint['case'], source=source, fixed_target=identity, preapproval=checkpoint['preapproval'], audit=audit, operation=operation)) if checkpoint['case'] == 'offline_wait': submit_contexts[checkpoint['operation_id']] = dict( request=dict(tenant_id=cloud.TENANT, plan_id=plan['plan_id'], idempotency_key='offline-'+checkpoint['id']), valid_until=min(cloud.contract.timestamp(plan['expires_at']), cloud.contract.timestamp(job['payload']['start_before']))) receipt = None if args.idempotency_receipt: receipt, source = witness(args.idempotency_receipt) context = submit_contexts.get(receipt.get('operation_id')) require(receipt.get('verified') is True and receipt.get('case') == 'offline_wait' and context is not None and receipt.get('request') == context['request'] and receipt.get('response_operation_id') == receipt['operation_id'] and receipt.get('before_counts') == receipt.get('after_counts') and receipt.get('before_counts') == dict(jobs=1, outbox=1, permits=1) and cloud.contract.timestamp(receipt['observed_at']) < context['valid_until'], 'live existing-submit receipt not bound to selected operation') receipt = dict(source=source, observation=receipt) report = dict(schema_version=1, observed_at=cloud.contract.now().isoformat(), scope='one explicitly selected real Linux Cloud VM; no multi-device concurrency proof', tenants=tenants, list_pages=pages, selected_targets=[identity], selected_device=device, other_devices=[{k: d.get(k) for k in ('agent_id', 'asset_id', 'presence', 'source_id', 'observed_at', 'received_at')} for d in devices if d['agent_id'] != identity['agent_id']], health=backend.call('monitoring.get_health', dict(tenant_id=cloud.TENANT)), operations=operations, live_submit_idempotency=receipt, idempotency_status='observed' if receipt else 'not_attached', no_new_plans_jobs_or_approvals=True) output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'w') as stream: json.dump(report, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno()) print('PASS stored MCP reference: one fixed Linux target, '+str(len(operations))+' existing operations; idempotency '+report['idempotency_status']) if __name__ == '__main__': try: main() except Exception as error: print('MCP_REFERENCE_INCOMPLETE:'+ (str(error) if isinstance(error, cloud.contract.GuardError) else type(error).__name__)) raise SystemExit(2) from None