import hashlib import json import os import re import time from pathlib import Path from .config import ROOT, MODEL, EFFORT, frozen_settings SOURCE = Path(__file__).parent.resolve() TASKS = ROOT / 'tasks' def digest(data): return hashlib.sha256(data).hexdigest() def fingerprint(): source = b''.join(p.name.encode() + p.read_bytes() for p in sorted(SOURCE.iterdir()) if p.suffix in {'.py', '.md'}) return digest(source + json.dumps(frozen_settings(), sort_keys=True).encode()) def write(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + '.tmp') with tmp.open('w') as f: json.dump(value, f, ensure_ascii=False, indent=2) f.flush() os.fsync(f.fileno()) tmp.replace(path) def task_dir(tid): if not re.fullmatch(r'pcb-[0-9a-f]{24}', tid): raise ValueError('Invalid task ID') return TASKS / tid def load(tid): return json.loads((task_dir(tid) / 'state.json').read_text()) def save(t): t['updated_at'] = time.time() write(task_dir(t['id']) / 'state.json', t) def event(t, kind, data): t['cursor'] = t.get('cursor', 0) + 1 entry = {'seq': t['cursor'], 'at': time.time(), 'type': kind, 'data': data} with (task_dir(t['id']) / 'events.jsonl').open('a') as f: f.write(json.dumps(entry, ensure_ascii=False) + '\n') f.flush() save(t) return entry def events(tid, after=0): p = task_dir(tid) / 'events.jsonl' if not p.exists(): return [] result = [] for line in p.read_text().splitlines(): try: e = json.loads(line) if e['seq'] > after: result.append(e) except ValueError: pass return result[-400:] def workspace(t): return task_dir(t['id']) / 'workspace' def inside(root, name): path = (root / name).resolve() if not path.is_relative_to(root.resolve()) or path == root.resolve(): raise ValueError('File must be inside the task workspace') return path