"""Repite secuencia con caché/reinicio para estudiar divergencia observada."""
import json
from pathlib import Path
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
root=Path('memory-lab')
rows=json.loads((root/'cache_live.json').read_text(encoding='utf8'))
case=next(r for r in rows if r['person']=='lina' and r['mode']=='mascara' and not r['cache'])
prompts=[e['serialized_prompt'] for e in case['result']['events'] if 'serialized_prompt' in e]
assert len(prompts)>=3
path=hf_hub_download('Qwen/Qwen2.5-0.5B-Instruct-GGUF','qwen2.5-0.5b-instruct-q4_k_m.gguf',revision='9217f5db79a29953eb74d5343926648285ec7e67')
llm=Llama(model_path=path,n_ctx=4096,n_threads=4,verbose=False)
out=[]
for repeat in range(5):
    for cache in (False,True):
        llm.reset();texts=[]
        for prompt in prompts[:3]:
            if not cache:llm.reset()
            texts.append(llm.create_completion(prompt=prompt,max_tokens=96,temperature=0)['choices'][0]['text'].strip())
        out.append({'repeat':repeat,'cache':cache,'texts':texts})
        (root/'cache_probe.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf8')
        print(repeat,cache,repr(texts[-1]),flush=True)
