install-unified-skills.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Update the single workshop Skill and its non-Skill research runtime component."""
  2. import argparse
  3. import hashlib
  4. import json
  5. import os
  6. from pathlib import Path
  7. import re
  8. import sys
  9. sys.dont_write_bytecode = True
  10. ROOT = Path(__file__).resolve().parents[1]
  11. def need(ok, code):
  12. if not ok:
  13. raise ValueError(code)
  14. def sha(path):
  15. return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
  16. def safe(path):
  17. need(path.is_absolute() and not any(p.is_symlink() for p in (path, *path.parents)), 'PATH_REDIRECTED')
  18. def write(path, value):
  19. path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
  20. with path.open('x', encoding='utf-8') as f:
  21. json.dump(value, f, ensure_ascii=False, indent=2)
  22. f.write('\n')
  23. path.chmod(0o600)
  24. def payload(component):
  25. workshop = component == 'ksf-workshop-runtime'
  26. root = ROOT / 'skills' / component if workshop else ROOT / 'components/research-runtime'
  27. repository_source = not workshop and not root.is_dir()
  28. if repository_source:
  29. root = ROOT / 'skills/ksf-voc-library'
  30. result, bodies, protected = {}, {}, set()
  31. for line in (root / 'FILES.sha256').read_text('utf-8').splitlines():
  32. digest, name = line.split(' ', 1)
  33. need(re.fullmatch('[a-f0-9]{64}', digest) and re.fullmatch('[A-Za-z0-9_./-]+', name)
  34. and '..' not in Path(name).parts and not Path(name).is_absolute(), 'BAD_PAYLOAD_MANIFEST')
  35. if repository_source and not name.startswith('scripts/'):
  36. continue
  37. guarded = workshop and (name.startswith('scripts/') or name == 'runtime-lock.json')
  38. # Protected business code is hash-only in the migration package; never redistributed.
  39. need(guarded or sha(root / name) == digest, 'PAYLOAD_CHANGED')
  40. result[name] = digest
  41. if guarded:
  42. protected.add(name)
  43. else:
  44. bodies[name] = (root / name).read_bytes()
  45. if not workshop:
  46. need('SKILL.md' not in result and 'scripts/query_voc.py' in result, 'INVALID_RESEARCH_COMPONENT')
  47. manifest = ''.join(h + ' ' + n + '\n' for n, h in sorted(result.items())).encode('utf-8')
  48. if not repository_source:
  49. manifest = (root / 'FILES.sha256').read_bytes()
  50. bodies['FILES.sha256'] = manifest
  51. result['FILES.sha256'] = hashlib.sha256(manifest).hexdigest()
  52. return bodies, result, protected
  53. def main():
  54. p = argparse.ArgumentParser(description=__doc__)
  55. p.add_argument('command', choices=('plan', 'apply', 'verify'))
  56. selection = p.add_mutually_exclusive_group(required=True)
  57. selection.add_argument('--skill', choices=('ksf-workshop-runtime',))
  58. selection.add_argument('--component', choices=('research-runtime',))
  59. p.add_argument('--target', required=True)
  60. p.add_argument('--out', required=True, help='New private directory for plan/backups/receipt')
  61. p.add_argument('--plan', help='Required for apply, the previously reviewed plan.json')
  62. a = p.parse_args()
  63. component = a.skill or a.component
  64. workshop = bool(a.skill)
  65. target, output = Path(a.target).absolute(), Path(a.out).absolute()
  66. safe(target);safe(output)
  67. need(target.is_dir(), 'EXISTING_COMPONENT_REQUIRED')
  68. need((target / ('SKILL.md' if workshop else 'scripts/query_voc.py')).is_file(),
  69. 'EXISTING_SKILL_REQUIRED' if workshop else 'EXISTING_RESEARCH_RUNTIME_REQUIRED')
  70. need(not output.exists() and not output.is_relative_to(target), 'NEW_OUTPUT_OUTSIDE_TARGET_REQUIRED')
  71. bodies, after, protected = payload(component)
  72. # Archive any active legacy entry; an already retired runtime is also accepted.
  73. retire = {'SKILL.md': None} if not workshop else {}
  74. expected = {**after, **retire}
  75. for name in expected:
  76. safe(target / name)
  77. need(not (target / name).exists() or (target / name).is_file(), 'TARGET_NOT_FILE')
  78. need(all(sha(target / n) == after[n] for n in protected), 'PROTECTED_BUSINESS_RUNTIME_MISMATCH')
  79. rows = [{'path': n, 'beforeSha256': sha(target / n), 'afterSha256': h}
  80. for n, h in sorted(expected.items()) if n not in protected]
  81. if a.command == 'plan':
  82. result = {'schema': 'ksf.unified-components.v2', 'component': component, 'target': str(target),
  83. 'files': rows, 'protectedFiles': sorted(protected), 'applied': False}
  84. write(output / 'plan.json', result)
  85. elif a.command == 'verify':
  86. need(all(sha(target / n) == h for n, h in expected.items()), 'INSTALLED_HASH_MISMATCH')
  87. result = {'ok': True, 'component': component, 'filesVerified': len(after), 'databaseWrites': 0,
  88. 'legacySkillEntryAbsent': not workshop}
  89. write(output / 'receipt.json', result)
  90. else:
  91. need(a.plan, 'REVIEWED_PLAN_REQUIRED')
  92. plan = json.loads(Path(a.plan).read_text('utf-8'))
  93. need(plan.get('schema') == 'ksf.unified-components.v2' and plan.get('target') == str(target)
  94. and plan.get('component') == component and plan.get('files') == rows, 'PLAN_OR_BASELINE_CHANGED')
  95. output.mkdir(parents=True, mode=0o700)
  96. changed = sorted((r for r in rows if r['beforeSha256'] != r['afterSha256']),
  97. key=lambda r: r['path'] == 'SKILL.md')
  98. # Back up every overwritten file before the first replacement.
  99. for row in changed:
  100. if row['beforeSha256'] is not None:
  101. dest = output / 'before' / row['path'];dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
  102. dest.write_bytes((target / row['path']).read_bytes());dest.chmod(0o600)
  103. write(output / 'journal.json', {'state': 'applying', 'target': str(target), 'files': changed})
  104. applied = []
  105. try:
  106. for row in changed:
  107. dest = target / row['path'];safe(dest)
  108. need(sha(dest) == row['beforeSha256'], 'TARGET_CHANGED_DURING_APPLY')
  109. if row['afterSha256'] is None:
  110. dest.unlink();applied.append(row)
  111. continue
  112. dest.parent.mkdir(parents=True, exist_ok=True)
  113. temp = dest.with_name(dest.name + '.unified-new')
  114. need(not temp.exists(), 'TEMP_FILE_EXISTS')
  115. with temp.open('xb') as f:
  116. f.write(bodies[row['path']]);f.flush();os.fsync(f.fileno())
  117. temp.chmod(dest.stat().st_mode & 0o777 if dest.exists() else 0o600)
  118. os.replace(temp, dest);applied.append(row)
  119. need(all(sha(target / n) == h for n, h in expected.items()), 'INSTALLED_HASH_MISMATCH')
  120. except Exception:
  121. for row in reversed(applied):
  122. dest = target / row['path']
  123. need(sha(dest) == row['afterSha256'], 'CONCURRENT_CHANGE_PREVENTS_RESTORE')
  124. if row['beforeSha256'] is None:
  125. dest.unlink()
  126. else:
  127. dest.write_bytes((output / 'before' / row['path']).read_bytes())
  128. raise
  129. result = {'ok': True, 'component': component, 'applied': True, 'filesChanged': len(changed),
  130. 'filesVerified': len(after), 'protectedBusinessRuntimeUnchanged': True, 'databaseWrites': 0}
  131. write(output / 'receipt.json', result)
  132. print(json.dumps({'ok': True, 'command': a.command, 'component': component, 'out': str(output),
  133. 'filesChanged': result.get('filesChanged'), 'databaseWrites': 0}, ensure_ascii=False))
  134. if __name__ == '__main__':
  135. try:
  136. main()
  137. except Exception as e:
  138. code = str(e) if isinstance(e, ValueError) and re.fullmatch('[A-Z][A-Z0-9_]+', str(e)) else 'SKILL_UPDATE_FAILED'
  139. print(json.dumps({'ok': False, 'error': {'code': code}, 'databaseWrites': 0}))
  140. sys.exit(1)