from pathlib import Path
import hashlib, json, platform, shutil, subprocess, sys
script=Path(__file__).resolve(); learner=script.parent; root=learner/'work/repository'
def h(p,alg='sha256'):
 if not p.exists() or not p.is_file(): return None
 d=p.read_bytes(); return hashlib.sha256(d).hexdigest() if alg=='sha256' else hashlib.sha512(d).hexdigest()
def tool(name,args):
 path=shutil.which(name); out={'available':bool(path),'resolved_executable':path}
 if path:
  r=subprocess.run([path,*args],capture_output=True,text=True); out['version']=(r.stdout or r.stderr).strip(); out['version_returncode']=r.returncode
 return out
files=sorted(list(root.glob('apps/*/package.json'))+list(root.glob('packages/*/package.json'))+list(root.glob('services/*/package.json'))+list(root.glob('libs/*/package.json')))
artifact_dir=root/'prepared_store/artifacts'; runtime_store=root/'prepared_store/pnpm-store'; inv=root/'prepared_store/store_inventory.json'
out={
 'schema':'TOL002_EXECUTION_CONTEXT_SNAPSHOT_v2',
 'execution_context':{
  'python':{'implementation':platform.python_implementation(),'version':platform.python_version(),'resolved_executable':str(Path(sys.executable).resolve())},
  'node':tool('node',['--version']),'pnpm':tool('pnpm',['--version']),
  'platform':{'system':platform.system(),'release':platform.release(),'machine':platform.machine()},
  'cwd':str(Path.cwd().resolve()),'fixture_root':str(root.resolve()),'inspector':str(script)
 },
 'declared_state':{'lock_hash':h(root/'pnpm-lock.yaml'),'workspace_hash':h(root/'pnpm-workspace.yaml'),'manifests':{str(p.relative_to(root)):h(p) for p in files}},
 'store_boundary':{
  'inventory_path':str(inv.resolve()),'inventory_sha256':h(inv),'artifact_dir':str(artifact_dir.resolve()),'isolated_runtime_store':str(runtime_store.resolve()),
  'artifacts':[{ 'path':str(p.relative_to(root)), 'sha256':h(p), 'sha512':h(p,'sha512'), 'bytes':p.stat().st_size } for p in sorted(artifact_dir.glob('*')) if p.is_file()],
  'runtime_store_exists':runtime_store.exists()
 },
 'installed_state':{'root_node_modules_exists':(root/'node_modules').exists()},
 'evidence_boundary':'No environment-variable dump, credentials, registry secret, or host/global store state is captured.'
}
print(json.dumps(out,indent=2))
