import json, subprocess, sys, tempfile
from pathlib import Path

ROOT = Path(__file__).parent
GATE = ROOT / 'continuity_gate.py'
BASE = {
    'contract':'continuity.receipt.v1', 'identity':'agent-x', 'session':'s1',
    'timestamp':'2026-09-18T00:00:00Z', 'next_step':'resume task',
    'open_obligations':[], 'provenance':'OBSERVED',
    'evidence':[{'id':1},{'id':2}], 'expected_head':2,
}

def run(doc):
    with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as f:
        json.dump(doc, f); name=f.name
    p = subprocess.run([sys.executable, str(GATE), name], text=True, capture_output=True)
    return p

p = run(BASE)
assert p.returncode == 0 and p.stdout.startswith('PASS '), p
cases = [
    ('unknown contract', {'contract':'continuity.receipt.v0'}, 'UNKNOWN_CONTRACT'),
    ('missing provenance', {'provenance':None}, 'INVALID_PROVENANCE'),
    ('inherited provenance', {'provenance':'INHERITED'}, 'INVALID_PROVENANCE'),
    ('non-contiguous ids', {'evidence':[{'id':1},{'id':3}]}, 'NONCONTIGUOUS_IDS'),
    ('head mismatch', {'expected_head':1}, 'HEAD_MISMATCH'),
]
for label, patch, code in cases:
    d = dict(BASE); d.update(patch)
    p = run(d)
    assert p.returncode != 0 and code in p.stderr, (label, p.stdout, p.stderr)
    print(f'PASS negative-control: {label} -> {code}')
print('PASS positive=1 negative_controls=5')
