verify-voc-r2-install.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """Exercise the complete handoff at isolated local paths, never production."""
  2. import hashlib
  3. import importlib.util
  4. import json
  5. import os
  6. from pathlib import Path
  7. import shutil
  8. import subprocess
  9. import sys
  10. ROOT=Path(__file__).resolve().parents[1]
  11. WORK=ROOT/'work/voc-structure-20261105'
  12. PACKAGE=ROOT/'artifacts/康师傅VOC结构化入库-20261105/ksf-voc-library-20261105-r2'
  13. TARGET=WORK/'r2-install-acceptance-final'
  14. def digest(p):return hashlib.sha256(p.read_bytes()).hexdigest()
  15. def run(args,env=None):
  16. result=subprocess.run(args,capture_output=True,text=True,encoding='utf-8',env=env)
  17. assert result.returncode==0,(args,result.returncode,result.stdout,result.stderr)
  18. return json.loads(result.stdout)
  19. def write(p,x):
  20. p.parent.mkdir(parents=True,exist_ok=True)
  21. p.write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
  22. def main():
  23. assert not TARGET.exists(),'Do not overwrite previous acceptance evidence'
  24. spec=importlib.util.spec_from_file_location('install_voc',PACKAGE/'ops/install_voc.py')
  25. module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
  26. lib=TARGET/'library';skill=TARGET/'skills/ksf-voc-library'
  27. plan=module.install(PACKAGE,lib,skill)
  28. assert plan['readOnly'] and len(plan['newDirectories'])==2 and not TARGET.exists()
  29. applied=module.install(PACKAGE,lib,skill,True)
  30. assert applied['applied'] and applied['filesystemVerified']
  31. before=digest(lib/'library.sqlite')
  32. entry=skill/'scripts/query_voc.py'
  33. base=[sys.executable,'-X','utf8',str(entry)]
  34. env=dict(os.environ,KSF_VOC_DB=str(lib/'library.sqlite'))
  35. contract=run(base+['contract'],env)
  36. assert contract['schema']=='ksf.voc-library.v2'
  37. examples=[]
  38. for p in sorted((PACKAGE/'examples').glob('*.json')):
  39. command='facets' if p.name.startswith('14-') else 'aggregate' if p.name.startswith('15-') else 'search'
  40. result=run(base+[command,'--input',str(p)],env)
  41. assert result['ok'] and result['readOnly'] and result['databaseWrites']==0
  42. if command=='search':
  43. assert result['totalMatched']>0
  44. row=result['records'][0]
  45. detail=run(base+['get','--entity',row['entity'],'--id',row['record_id']],env)
  46. assert detail['record']['source_record_id']==row['source_record_id']
  47. source=run(base+['source','--id',row['source_record_id']],env)
  48. assert source['citation']['archiveSha256']==row['citation']['archiveSha256']
  49. examples.append(dict(file=p.name,command=command,ok=result['ok'],totalMatched=result.get('totalMatched')))
  50. assert digest(lib/'library.sqlite')==before
  51. assert not list(skill.rglob('__pycache__')),'Queries must not modify installed skill'
  52. repeated=module.install(PACKAGE,lib,skill,True)
  53. assert not repeated['applied'] and repeated['newDirectories']==[]
  54. rejected=run([sys.executable,'-B','-X','utf8',str(PACKAGE/'ops/install_voc.py'),'--package',str(PACKAGE),'--library-dir',str(lib),'--skill-dir',str(skill),'--check'])
  55. assert rejected['ok']
  56. write(PACKAGE/'receipts/install-validation.json',dict(ok=True,plan=plan,apply=applied,contractGeneration=contract['generation'],
  57. installedCliExamples=examples,installedGetAndSourceVerified=True,databaseShaBeforeAfter=before,
  58. queryCreatedBytecode=False,reinstallNoOp=True,productionInstalled=False))
  59. # Both permitted workshop documentation baselines, with isolated fake state.
  60. for label,baseline in [
  61. ('20261104-db-first',WORK/'workshop-baseline'),
  62. ('20261105-prepared-r1',PACKAGE.parent/'ksf-voc-library-20261105-r1/materials/skills/ksf-workshop-runtime')]:
  63. dest=TARGET/'workshop'/label/'skills/ksf-workshop-runtime'
  64. shutil.copytree(baseline,dest)
  65. (dest/'credential-binding.json').write_text('{"fixture":true}',encoding='utf-8')
  66. state=TARGET/'workshop'/label/'ksf-workshop-state/sessions'
  67. state.mkdir(parents=True)
  68. (state/'test.json').write_text('{"fixture":true,"sessionId":"local-only"}',encoding='utf-8')
  69. node_script=TARGET/'workshop-test.mjs'
  70. node_script.write_text('''import fs from 'node:fs';
  71. import path from 'node:path';
  72. import crypto from 'node:crypto';
  73. import {pathToFileURL} from 'node:url';
  74. const [packageRoot,workspace,targetRoot]=process.argv.slice(2);
  75. const {installWorkshopSkill}=await import(pathToFileURL(path.join(packageRoot,'materials/scripts/install-workshop-skill.mjs')));
  76. const hash=p=>crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
  77. const snapshots=[['20261104-db-first',path.join(workspace,'work/voc-structure-20261105/workshop-baseline')],
  78. ['20261105-prepared-r1',path.join(workspace,'artifacts/康师傅VOC结构化入库-20261105/ksf-voc-library-20261105-r1/materials/skills/ksf-workshop-runtime')]];
  79. const results=[];
  80. for(const [label,baseline] of snapshots){
  81. const dest=path.join(targetRoot,label,'skills/ksf-workshop-runtime');
  82. const binding=path.join(dest,'credential-binding.json');
  83. const session=path.join(targetRoot,label,'ksf-workshop-state/sessions/test.json');
  84. const a=hash(binding),b=hash(session),source=path.join(packageRoot,'materials/skills/ksf-workshop-runtime');
  85. const plan=installWorkshopSkill(source,dest,{apply:false});
  86. if(JSON.stringify(plan.changed.sort())!==JSON.stringify(['FILES.sha256','SKILL.md','references/workshop-tasks.md']))throw Error('UNEXPECTED_CHANGES');
  87. const apply=installWorkshopSkill(source,dest);
  88. if(hash(binding)!==a||hash(session)!==b)throw Error('FIXTURE_STATE_CHANGED');
  89. const noOp=installWorkshopSkill(source,dest,{apply:false});if(noOp.changed.length)throw Error('REINSTALL_NOT_NOOP');
  90. results.push({baseline:label,plan,apply,reinstallNoOp:true,credentialAndStateFixturePreserved:true});
  91. }
  92. console.log(JSON.stringify({ok:true,baselines:results,productionInstalled:false}));
  93. ''',encoding='utf-8')
  94. workshop=run(['node',str(node_script),str(PACKAGE),str(ROOT),str(TARGET/'workshop')])
  95. write(PACKAGE/'receipts/workshop-install-validation.json',workshop)
  96. validator=Path('C:/Users/JSHY/.codex/skills/.system/skill-creator/scripts/quick_validate.py')
  97. results=[]
  98. for folder in [ROOT/'skills/ksf-voc-library',PACKAGE/'skill',ROOT/'work/five-views-delivery-20261103/skills/ksf-workshop-runtime',PACKAGE/'materials/skills/ksf-workshop-runtime']:
  99. proc=subprocess.run([sys.executable,'-B','-X','utf8',str(validator),str(folder)],capture_output=True,text=True,encoding='utf-8')
  100. assert proc.returncode==0,proc.stdout+proc.stderr
  101. results.append(dict(path=str(folder),ok=True,output=proc.stdout.strip()))
  102. write(PACKAGE/'receipts/skill-validation.json',dict(ok=True,results=results))
  103. print(json.dumps(dict(ok=True,installedExamples=len(examples),getSourceVerified=True,workshopBaselines=2,skillValidations=4,productionInstalled=False),ensure_ascii=False,indent=2))
  104. if __name__=='__main__':main()