#!/usr/bin/env python3
"""Replayable fictional TS01 case. Uses the published engine; implements no rule.
Only a loopback demonstration server is contacted. The protocol archive is
provided by the operator and verified before extraction. Existing output is refused.
"""
import argparse
import hashlib
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
import shutil
import sys
import tempfile
import threading
import zipfile
ARCHIVE_SHA256 = '0d974698eb5016d94f9c8e0a0e5ef5d3c55a8db134b31c60522e798537a20d37'
PROTOCOL_SHA256 = '3af55b64677ccd74d3ccfcc49f3dbf469c90fb214844fe13c5f10773a11d9041'
RELEASE = 'https://github.com/web-evidence/tsep/releases/tag/v0.3.0-draft.9'
PATH = '/produits/p-42'
GOOD = '
Lampe AtelierLampe Atelier
Réf. P-42
Une lampe de bureau en métal.
\n'.encode('utf-8')
BAD = 'Produit introuvableProduit introuvable
Ce produit ne peut pas être affiché.
\n'.encode('utf-8')
def digest(data):
return hashlib.sha256(data).hexdigest()
def save(path, data):
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
class Shop(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
server_version = 'TSEP-Demonstration/1'
sys_version = ''
def log_message(self, *args):
pass
def do_GET(self):
# The correction is the restoration of this route's product mapping.
product = self.server.products.get(self.path)
body = GOOD if product == 'P-42' else BAD
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('Connection', 'close')
self.end_headers()
self.wfile.write(body)
self.close_connection = True
def run(archive, output):
if output.exists() or not output.parent.is_dir():
raise ValueError('Choose a NEW output directory with an existing parent.')
if digest(archive.read_bytes()) != ARCHIVE_SHA256:
raise ValueError('Published protocol archive fingerprint mismatch.')
output.mkdir()
with tempfile.TemporaryDirectory(prefix='tsep-example-engine-') as temporary:
root = Path(temporary)
with zipfile.ZipFile(archive) as bundle:
for name in bundle.namelist():
destination = (root / name).resolve()
if not destination.is_relative_to(root.resolve()):
raise ValueError('Unsafe archive member.')
bundle.extractall(root)
engine = root / 'tsep'
if digest((engine/'spec/protocol.json').read_bytes()) != PROTOCOL_SHA256:
raise ValueError('Protocol specification fingerprint mismatch.')
sys.path.insert(0, str(engine))
import tsep
from collectors import ts01
from conformance import evaluate as native
from conformance.evaluate import trace
server = ThreadingHTTPServer(('127.0.0.1', 0), Shop)
server.daemon_threads = True
server.products = {PATH: 'P-42'}
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
origin = 'http://127.0.0.1:' + str(server.server_port)
target = origin + PATH
settings = {
'urls': [target], 'origins': [origin],
'agent': 'TSEP-presentation-demo/1', 'accept_encoding': 'identity',
'timeout': 3, 'max_bytes': 16384, 'max_redirects': 0,
'allow_loopback': True, 'network': 'Synthetic loopback demonstration; no external requests',
'access': 'synthetic',
'selection_method': 'One fictional product URL, explicitly selected; no real site or client',
}
ts01.reference(settings, output/'reference')
criteria = {target: {'policy': 'markers', 'expected_final_url': target,
'required_markers': ['Lampe Atelier', 'Réf. P-42'],
'forbidden_markers': ['Produit introuvable']}}
save(output/'criteria.json', criteria)
ts01.seal(output/'reference/reference', output/'intent.json',
assessor='TSEP publisher — synthetic demonstration',
label='Fictional product P-42; one loopback URL; no independent validation',
criteria=criteria)
# Only after sealing the intent do we introduce the demonstration defect.
server.products = {}
ts01.evaluate(output/'reference/reference', output/'intent.json', output/'before')
correction = {'synthetic': True, 'at': ts01.now(),
'action': 'Restore /produits/p-42 -> P-42 in the demonstration route mapping.',
'unchanged': ['URL', 'HTTP 200 status', 'request context', 'sealed intent']}
save(output/'correction.json', correction)
server.products = {PATH: 'P-42'}
ts01.evaluate(output/'reference/reference', output/'intent.json', output/'after')
for phase in ('before', 'after'):
ts01.replay(output/phase, output/(phase+'-replay'))
reports = {phase: tsep.read_json(output/phase/'bundle/report.json') for phase in ('before','after')}
inputs = {phase: tsep.read_json(output/phase/'input.json') for phase in ('before','after')}
results = {phase: reports[phase]['results'][0] for phase in reports}
if (results['before']['status'], results['after']['status']) != ('NC','C'):
raise ValueError('Unexpected engine outcomes; inspect the retained dossier.')
summary = {
'kind': 'synthetic-demonstration', 'edition': '2026-10-28.1',
'title': 'The server says 200; the product was not found.',
'fictional_shop': 'Atelier Démo', 'protocol_version': '0.3.0-draft.9',
'protocol_commit': 'd6a6e73f5c21d52131d3f4e39cde309d97385cbc',
'protocol_sha256': PROTOCOL_SHA256, 'engine_archive_sha256': ARCHIVE_SHA256,
'release_url': RELEASE, 'collector_version': ts01.VERSION,
'interpreter_version': native.VERSION, 'target': target, 'path': PATH,
'intent_declared_at': inputs['before']['targets'][0]['intent']['declared_at'],
'correction_at': correction['at'],
'required_markers': criteria[target]['required_markers'],
'forbidden_markers': criteria[target]['forbidden_markers'],
'expected_body_sha256': digest(GOOD), 'reference_body_utf8': GOOD.decode(),
'phases': {}, 'replayed': True, 'external_requests': 0,
'limits': 'Constructed scenario, actual loopback responses, publisher engine. Not a client case or independent validation. TS01 only, one synthetic URL, retained captures only; no indexing, rankings or global conformity claim. Local timestamps are not trusted timestamping.',
}
for phase in ('before', 'after'):
row = inputs[phase]['targets'][0]
final_url, status, headers, body = trace(row['http'], row['url'], settings['agent'])
summary['phases'][phase] = {'observed_at': row['observed_at'],
'status': results[phase]['status'], 'rules': results[phase]['atomic_results'],
'http_status': status, 'final_url': final_url, 'headers': headers,
'body_utf8': body.decode(),
'body_sha256': digest(body), 'body_bytes': len(body)}
save(output/'summary.json', summary)
shutil.copyfile(__file__, output/'reproduce.py')
(output/'README.txt').write_text(
'TSEP TS01 — FICTIONAL DEMONSTRATION / DÉMONSTRATION FICTIVE\n'
'An intentionally constructed product-page defect, actual loopback HTTP responses.\n'
'Not a real client case or independent validation; TS01 only on one synthetic URL.\n'
'Download the exact release archive from '+RELEASE+'\n'
'Its SHA-256 must be '+ARCHIVE_SHA256+'\n'
'Python 3.9+; no pip dependency or external network request by this script.\n'
'Run: python3 reproduce.py --protocol-archive tsep-0.3.0-draft.9.zip --output new-dossier\n'
'A new collection uses a new local port and timestamps; the expected outcomes stay NC -> C.\n'
'For archived offline replay, use the same extracted release:\n'
'python3 tsep/collectors/ts01.py replay before --output replay-before --lang fr\n'
'python3 tsep/collectors/ts01.py replay after --output replay-after --lang fr\n'
'The archive includes reference, intent, original HTTP bytes, assessments and replay receipts.\n'
'SHA256SUMS detects byte changes; it does not authenticate the author or timestamps.\n', encoding='utf-8')
finally:
server.shutdown(); server.server_close(); thread.join()
files = sorted(p for p in output.rglob('*') if p.is_file())
(output/'SHA256SUMS').write_text(''.join(digest(p.read_bytes())+' '+str(p.relative_to(output))+'\n' for p in files))
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--protocol-archive', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
options = parser.parse_args()
run(options.protocol_archive.resolve(), options.output.resolve())