upgrade.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """Strict known-baseline, documentation-only upgrade of the original workshop Agent."""
  2. import argparse
  3. import importlib.util
  4. import json
  5. import os
  6. from pathlib import Path
  7. import shutil
  8. import sys
  9. HERE = Path(__file__).resolve().parent
  10. def core_at(package):
  11. spec = importlib.util.spec_from_file_location('workshop_installer_core', package / 'install.py')
  12. module = importlib.util.module_from_spec(spec)
  13. spec.loader.exec_module(module)
  14. return module
  15. def snapshot(core, target):
  16. values = {}
  17. for path in sorted(target.rglob('*')):
  18. core.plain_path(path)
  19. if path.is_file():
  20. values[path.relative_to(target).as_posix()] = {
  21. 'sha256': core.digest(path.read_bytes()), 'mode': path.stat().st_mode & 0o777}
  22. else:
  23. core.require(path.is_dir(), 'SPECIAL_FILE_NOT_SUPPORTED')
  24. return values
  25. def write(core, path, value):
  26. path.write_bytes(core.encode(value))
  27. path.chmod(0o600)
  28. def load(core, package):
  29. package = core.plain_path(package)
  30. for line in (package / 'FILES.sha256').read_text('utf-8').splitlines():
  31. h, name = line.split(' ', 1)
  32. core.require(core.safe_name(name), 'INVALID_PACKAGE_PATH')
  33. p = core.plain_path(package / name)
  34. core.require(p.is_file() and core.digest(p.read_bytes()) == h, 'PACKAGE_HASH_MISMATCH')
  35. meta = json.loads((package / 'release.json').read_bytes())
  36. core.require(meta['schema'] == 'ksf.workshop-onboarding.v1', 'INVALID_RELEASE')
  37. candidate = meta['workshop']['files']
  38. meta['candidate'] = candidate
  39. meta['baselines'] = meta['upgradeFrom']
  40. meta['protectedFiles'] = meta['workshop']['protectedFiles']
  41. core.require(len(candidate) == 45 and candidate['SKILL.md'] ==
  42. 'e295ddffbae954586ad87309524f3cb954085e752e35f7d2ddc293d86b04d2a0', 'UNKNOWN_TARGET')
  43. content = {}
  44. for name, expected in candidate.items():
  45. core.require(core.safe_name(name), 'INVALID_PACKAGE_PATH')
  46. data = core.plain_path(package / 'skills/ksf-workshop-runtime' / name).read_bytes()
  47. core.require(core.digest(data) == expected, 'CANDIDATE_HASH_MISMATCH')
  48. content[name] = data
  49. protected = {n for n in candidate if n.startswith('scripts/') or n == 'runtime-lock.json'}
  50. core.require(len(protected) == 7 and set(meta['protectedFiles']) == protected, 'PROTECTED_FILE_LAYOUT')
  51. for baseline in meta['baselines'].values():
  52. core.require(all(baseline.get(n) == candidate[n] for n in protected), 'PROTECTED_RUNTIME_CHANGED')
  53. return meta, content
  54. def run(command, target, output, package=HERE):
  55. package = Path(package).resolve()
  56. core = core_at(package)
  57. core.require(Path(target).is_absolute() and Path(output).is_absolute(), 'ABSOLUTE_PATH_REQUIRED')
  58. target, output = core.plain_path(target), core.plain_path(output)
  59. core.require(target.is_dir() and target.name == 'ksf-workshop-runtime', 'EXISTING_WORKSHOP_TARGET_REQUIRED')
  60. core.require(not output.is_relative_to(target.parent) and not package.is_relative_to(target)
  61. and not output.is_relative_to(package), 'RESULT_TARGET_OVERLAP')
  62. core.plain_path(target / 'credential-binding.json')
  63. core.require((target / 'credential-binding.json').is_file(), 'EXISTING_BINDING_REQUIRED')
  64. if os.name != 'nt':
  65. core.require(os.geteuid() == target.stat().st_uid, 'TARGET_OWNER_REQUIRED')
  66. core.require((target / 'credential-binding.json').stat().st_mode & 0o777 == 0o600,
  67. 'PRIVATE_BINDING_PERMISSIONS')
  68. meta, content = load(core, package)
  69. files = {'ksf-workshop-runtime': content}
  70. if command == 'inventory':
  71. public = {n: core.digest(core.plain_path(target / n).read_bytes())
  72. if core.plain_path(target / n).is_file() else None for n in content}
  73. return {'ok': True, 'readOnly': True, 'publicFilesOnly': True,
  74. 'files': public, 'bindingIncluded': False, 'businessWrites': 0}
  75. if command == 'plan':
  76. core.require(not output.exists(), 'NEW_RESULT_DIRECTORY_REQUIRED')
  77. actions = core.plan(target.parent, files, meta['baselines'])
  78. output.mkdir(parents=True, mode=0o700)
  79. output.chmod(0o700)
  80. record = {'schema': 'ksf.workshop-platform-upgrade-plan.v1', 'releaseId': meta['releaseId'],
  81. 'target': str(target), 'candidate': meta['candidate'], 'actions': actions,
  82. 'before': snapshot(core, target)}
  83. write(core, output / 'plan.json', record)
  84. action = actions[0]
  85. baseline = action.get('before', meta['candidate'])
  86. changed = [n for n in content if baseline.get(n) != meta['candidate'][n]]
  87. result = {'ok': True, 'readOnly': True, 'action': action['action'],
  88. 'baselineId': action.get('fromVersion', 'r13'), 'changes': len(changed),
  89. 'creates': len(set(content) - set(baseline)), 'changedFiles': changed,
  90. 'protectedFilesModified': 0, 'vocModified': False, 'businessWrites': 0}
  91. write(core, output / 'plan-summary.json', result)
  92. return result
  93. record = json.loads((output / 'plan.json').read_bytes())
  94. core.require(record['target'] == str(target) and record['candidate'] == meta['candidate'], 'PLAN_MISMATCH')
  95. def verify():
  96. core.verify_component(target, content)
  97. after = snapshot(core, target)
  98. for name, old in record['before'].items():
  99. if name not in content or name in meta['protectedFiles']:
  100. core.require(after.get(name) == old, 'PRESERVED_FILE_CHANGED')
  101. return {'ok': True, 'workshopVersion': 'r13', 'publicFilesVerified': 45,
  102. 'protectedFilesModified': 0, 'localFilesPreserved': True,
  103. 'agentLoaded': False, 'vocModified': False, 'businessWrites': 0}
  104. if command == 'verify':
  105. result = verify()
  106. write(core, output / 'verify.json', result)
  107. return result
  108. core.require(command == 'apply', 'UNKNOWN_COMMAND')
  109. if (output / 'apply.json').exists():
  110. old = json.loads((output / 'apply.json').read_bytes())
  111. core.require(old.get('ok') is True, 'PRIOR_APPLY_REQUIRES_REVIEW')
  112. return {**verify(), 'alreadyApplied': True}
  113. core.require(snapshot(core, target) == record['before'], 'TARGET_CHANGED_SINCE_PLAN')
  114. actions = core.plan(target.parent, files, meta['baselines'])
  115. core.require(actions == record['actions'], 'PLAN_CHANGED')
  116. if actions[0]['action'] == 'verify-only':
  117. return {**verify(), 'alreadyApplied': True}
  118. backup = output / 'before-full'
  119. core.require(not backup.exists(), 'PRIOR_BACKUP_REQUIRES_REVIEW')
  120. shutil.copytree(target, backup, copy_function=shutil.copy2)
  121. backup.chmod(0o700)
  122. core.require(snapshot(core, backup) == record['before'], 'BACKUP_VERIFY_FAILED')
  123. core.require(snapshot(core, target) == record['before'], 'TARGET_CHANGED_SINCE_PLAN')
  124. try:
  125. core.install_files(target.parent, files, actions, output / 'before-changed')
  126. result = {**verify(), 'applied': True, 'fullBackupVerified': True}
  127. write(core, output / 'apply.json', result)
  128. return result
  129. except Exception:
  130. restored = snapshot(core, target) == record['before']
  131. write(core, output / 'apply.json', {'ok': False, 'originalRestored': restored})
  132. raise
  133. if __name__ == '__main__':
  134. p = argparse.ArgumentParser(description=__doc__)
  135. p.add_argument('command', choices=['plan', 'apply', 'verify', 'inventory'])
  136. p.add_argument('--target-dir', required=True)
  137. p.add_argument('--out', required=True)
  138. args = p.parse_args()
  139. try:
  140. print(json.dumps(run(args.command, args.target_dir, args.out), ensure_ascii=False, indent=2))
  141. except Exception as exc:
  142. allowed = str(exc)
  143. code = allowed if allowed and all(c.isupper() or c.isdigit() or c == '_' for c in allowed) else 'PLATFORM_UPGRADE_STOPPED'
  144. print(json.dumps({'ok': False, 'errorCode': code}), file=sys.stderr)
  145. sys.exit(1)