| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- """Update the single workshop Skill and its non-Skill research runtime component."""
- import argparse
- import hashlib
- import json
- import os
- from pathlib import Path
- import re
- import sys
- sys.dont_write_bytecode = True
- ROOT = Path(__file__).resolve().parents[1]
- def need(ok, code):
- if not ok:
- raise ValueError(code)
- def sha(path):
- return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
- def safe(path):
- need(path.is_absolute() and not any(p.is_symlink() for p in (path, *path.parents)), 'PATH_REDIRECTED')
- def write(path, value):
- path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
- with path.open('x', encoding='utf-8') as f:
- json.dump(value, f, ensure_ascii=False, indent=2)
- f.write('\n')
- path.chmod(0o600)
- def payload(component):
- workshop = component == 'ksf-workshop-runtime'
- root = ROOT / 'skills' / component if workshop else ROOT / 'components/research-runtime'
- repository_source = not workshop and not root.is_dir()
- if repository_source:
- root = ROOT / 'skills/ksf-voc-library'
- result, bodies, protected = {}, {}, set()
- for line in (root / 'FILES.sha256').read_text('utf-8').splitlines():
- digest, name = line.split(' ', 1)
- need(re.fullmatch('[a-f0-9]{64}', digest) and re.fullmatch('[A-Za-z0-9_./-]+', name)
- and '..' not in Path(name).parts and not Path(name).is_absolute(), 'BAD_PAYLOAD_MANIFEST')
- if repository_source and not name.startswith('scripts/'):
- continue
- guarded = workshop and (name.startswith('scripts/') or name == 'runtime-lock.json')
- # Protected business code is hash-only in the migration package; never redistributed.
- need(guarded or sha(root / name) == digest, 'PAYLOAD_CHANGED')
- result[name] = digest
- if guarded:
- protected.add(name)
- else:
- bodies[name] = (root / name).read_bytes()
- if not workshop:
- need('SKILL.md' not in result and 'scripts/query_voc.py' in result, 'INVALID_RESEARCH_COMPONENT')
- manifest = ''.join(h + ' ' + n + '\n' for n, h in sorted(result.items())).encode('utf-8')
- if not repository_source:
- manifest = (root / 'FILES.sha256').read_bytes()
- bodies['FILES.sha256'] = manifest
- result['FILES.sha256'] = hashlib.sha256(manifest).hexdigest()
- return bodies, result, protected
- def main():
- p = argparse.ArgumentParser(description=__doc__)
- p.add_argument('command', choices=('plan', 'apply', 'verify'))
- selection = p.add_mutually_exclusive_group(required=True)
- selection.add_argument('--skill', choices=('ksf-workshop-runtime',))
- selection.add_argument('--component', choices=('research-runtime',))
- p.add_argument('--target', required=True)
- p.add_argument('--out', required=True, help='New private directory for plan/backups/receipt')
- p.add_argument('--plan', help='Required for apply, the previously reviewed plan.json')
- a = p.parse_args()
- component = a.skill or a.component
- workshop = bool(a.skill)
- target, output = Path(a.target).absolute(), Path(a.out).absolute()
- safe(target);safe(output)
- need(target.is_dir(), 'EXISTING_COMPONENT_REQUIRED')
- need((target / ('SKILL.md' if workshop else 'scripts/query_voc.py')).is_file(),
- 'EXISTING_SKILL_REQUIRED' if workshop else 'EXISTING_RESEARCH_RUNTIME_REQUIRED')
- need(not output.exists() and not output.is_relative_to(target), 'NEW_OUTPUT_OUTSIDE_TARGET_REQUIRED')
- bodies, after, protected = payload(component)
- # Archive any active legacy entry; an already retired runtime is also accepted.
- retire = {'SKILL.md': None} if not workshop else {}
- expected = {**after, **retire}
- for name in expected:
- safe(target / name)
- need(not (target / name).exists() or (target / name).is_file(), 'TARGET_NOT_FILE')
- need(all(sha(target / n) == after[n] for n in protected), 'PROTECTED_BUSINESS_RUNTIME_MISMATCH')
- rows = [{'path': n, 'beforeSha256': sha(target / n), 'afterSha256': h}
- for n, h in sorted(expected.items()) if n not in protected]
- if a.command == 'plan':
- result = {'schema': 'ksf.unified-components.v2', 'component': component, 'target': str(target),
- 'files': rows, 'protectedFiles': sorted(protected), 'applied': False}
- write(output / 'plan.json', result)
- elif a.command == 'verify':
- need(all(sha(target / n) == h for n, h in expected.items()), 'INSTALLED_HASH_MISMATCH')
- result = {'ok': True, 'component': component, 'filesVerified': len(after), 'databaseWrites': 0,
- 'legacySkillEntryAbsent': not workshop}
- write(output / 'receipt.json', result)
- else:
- need(a.plan, 'REVIEWED_PLAN_REQUIRED')
- plan = json.loads(Path(a.plan).read_text('utf-8'))
- need(plan.get('schema') == 'ksf.unified-components.v2' and plan.get('target') == str(target)
- and plan.get('component') == component and plan.get('files') == rows, 'PLAN_OR_BASELINE_CHANGED')
- output.mkdir(parents=True, mode=0o700)
- changed = sorted((r for r in rows if r['beforeSha256'] != r['afterSha256']),
- key=lambda r: r['path'] == 'SKILL.md')
- # Back up every overwritten file before the first replacement.
- for row in changed:
- if row['beforeSha256'] is not None:
- dest = output / 'before' / row['path'];dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
- dest.write_bytes((target / row['path']).read_bytes());dest.chmod(0o600)
- write(output / 'journal.json', {'state': 'applying', 'target': str(target), 'files': changed})
- applied = []
- try:
- for row in changed:
- dest = target / row['path'];safe(dest)
- need(sha(dest) == row['beforeSha256'], 'TARGET_CHANGED_DURING_APPLY')
- if row['afterSha256'] is None:
- dest.unlink();applied.append(row)
- continue
- dest.parent.mkdir(parents=True, exist_ok=True)
- temp = dest.with_name(dest.name + '.unified-new')
- need(not temp.exists(), 'TEMP_FILE_EXISTS')
- with temp.open('xb') as f:
- f.write(bodies[row['path']]);f.flush();os.fsync(f.fileno())
- temp.chmod(dest.stat().st_mode & 0o777 if dest.exists() else 0o600)
- os.replace(temp, dest);applied.append(row)
- need(all(sha(target / n) == h for n, h in expected.items()), 'INSTALLED_HASH_MISMATCH')
- except Exception:
- for row in reversed(applied):
- dest = target / row['path']
- need(sha(dest) == row['afterSha256'], 'CONCURRENT_CHANGE_PREVENTS_RESTORE')
- if row['beforeSha256'] is None:
- dest.unlink()
- else:
- dest.write_bytes((output / 'before' / row['path']).read_bytes())
- raise
- result = {'ok': True, 'component': component, 'applied': True, 'filesChanged': len(changed),
- 'filesVerified': len(after), 'protectedBusinessRuntimeUnchanged': True, 'databaseWrites': 0}
- write(output / 'receipt.json', result)
- print(json.dumps({'ok': True, 'command': a.command, 'component': component, 'out': str(output),
- 'filesChanged': result.get('filesChanged'), 'databaseWrites': 0}, ensure_ascii=False))
- if __name__ == '__main__':
- try:
- main()
- except Exception as e:
- code = str(e) if isinstance(e, ValueError) and re.fullmatch('[A-Z][A-Z0-9_]+', str(e)) else 'SKILL_UPDATE_FAILED'
- print(json.dumps({'ok': False, 'error': {'code': code}, 'databaseWrites': 0}))
- sys.exit(1)
|