"""ForgetMe, as the demo's personal agent hosts it. ForgetMe is the button and flow a person and their personal AI agent use to make "forget this" really happen and show what happened. ForgetProof is the engine behind it: the scanner, the eraser, the signed receipts. This module is Pim's side of that: the host contract under `/forget-me/v1/` (preview, submit, operation status, evidence), the opaque references Pim issues for every memory item it writes, and the durable, at-most-once operations that erase through ForgetProof and sign receipts with this site's key. The holders are Pim's own stores and, at the cross-provider level, the recipients Pim shared a memory with. Toward a recipient Company Pim is a Poppy 1.0 Personal Agent (`recipients.py`, `poppy_agent.py`): it negotiates the extensions, carries a verified Session and an access token, and performs a withdrawal there only with the person's approval of the exact terms the Company stated (Operations extension, version 3). The person approves in the button: the preview shows the Company's terms word for word, and confirming them is the approval Pim records in its ledger and sends. The namespace `stellarminds.ai/forget-me` is provisional. ForgetMe is a third-party proposal targeting Poppy 1.0; it is not approved, adopted or reviewed by anyone. What is simulated, and labelled as such on the pages: - the signed-in session: a synthetic session this demo issues for its fictional user, John Reyes, when a scenario starts; it is a labelled fixture, never a general identity provider; - the courier ("Bay Parcel"): a delivery company simulated inside the run, so the page can show which address Pim hands out before and after the forget; - the recorded example the landing page shows before anyone clicks. What is never faked: approval and authorization (every call is checked against the session that owns the reference or the operation), the stores (real Chroma, mem0, SQLite and JSONL files, built fresh per scenario), the erasure (ForgetProof's own forget()), and the receipts (signed, verifiable in the browser). On disk, under the site's runs directory: `forget-me//` holds `scenario.json`, the private `references.json`, Pim's `world/`, the `operations/*.json`, the idempotency index and `pim/receipts/`. Scenarios expire after SCENARIO_TTL seconds and are removed, world and all. """ from __future__ import annotations import asyncio import hashlib import hmac import json import os import re import secrets import shutil import threading import time from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from pathlib import Path from forgetproof import forget as forget_mod, forgetme as wire, receipt from forgetproof.scanner import scan from forgetproof.subject import subject as make_subject if __package__: from . import recipients as rcp from .world import JOHN, NEW_ADDRESS, OLD_ADDRESS, World else: # pragma: no cover - `python demo/forgetme.py` import recipients as rcp # type: ignore from world import JOHN, NEW_ADDRESS, OLD_ADDRESS, World # type: ignore NAMESPACE = wire.NAMESPACE VERSION = wire.VERSION ISSUER = "Pim (this demo)" # receipts are signed with this site's key, published at /forget-me/v1 and /.well-known/forgetproof.json ENDPOINT = "/forget-me/v1" COURIER = "Bay Parcel (simulated)" OWNER = "john" # the one fictional user the synthetic session signs in SCENARIO_TTL = int(os.environ.get("FORGETME_SCENARIO_TTL", str(30 * 60))) MAX_LIVE_SCENARIOS = int(os.environ.get("FORGETME_MAX_SCENARIOS", "12")) REFERENCE = re.compile(r"^fmr_[A-Za-z0-9_-]{16,48}$") OPERATION = re.compile(r"^fmo_[A-Za-z0-9_-]{16,48}$") SCENARIO_ID = re.compile(r"^[a-f0-9]{16}$") SCOPES = ("item", "account") CHOICES = ("keep", "delete") # The outcome vocabulary (shared with the component and with phase 2). Worst first. OUTCOMES = ("error", "bytes-still-found", "queued", "unsupported", "intentionally-retained", "inspected-and-clear") HOLDERS = { "memory": ("Pim's long-term memory", "chroma", "the record, Chroma's write log, the vector index and the free pages of its SQLite file"), "mem0": ("Pim's memory history", "mem0", "the history rows mem0 keeps for added, updated and deleted memories"), "notes": ("Pim's notes", "sqlite", "the note row and the free pages of the notes database"), "graph": ("Pim's knowledge graph", "files", "the JSONL line; a text file keeps no hidden copy"), } EPHEMERAL_HOLDER = {"holder": "conversation", "title": "Pim's conversation window", "kind": "ephemeral", "retention": "none", "what": "Pim keeps no transcript of your chats: nothing to erase there, and nothing to verify."} def now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def _in(seconds: int) -> str: return (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat(timespec="seconds") def _past(iso: str) -> bool: return datetime.fromisoformat(iso) <= datetime.now(timezone.utc) def _hash(text: str) -> str: return hashlib.sha256(text.encode()).hexdigest() def _write_json(path: Path, data) -> None: tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(data, indent=1), encoding="utf-8") os.replace(tmp, path) def _read_json(path: Path, default=None): """Read a JSON file written by `_write_json`. On Windows a reader can hit a sharing violation while another thread's `os.replace` lands (the executing operation saves itself between steps while a status read loads it), so a transient OSError is retried briefly; a missing file is not.""" for attempt in range(6): try: return json.loads(path.read_text(encoding="utf-8")) except FileNotFoundError: return default except (OSError, ValueError): if attempt == 5: return default time.sleep(0.02 * (attempt + 1)) return default class ContractError(Exception): """An error the contract documents: HTTP status, machine code, human description.""" def __init__(self, status: int, code: str, description: str, **extra): super().__init__(description) self.status, self.code, self.description, self.extra = status, code, description, extra def body(self) -> dict: return {"error": self.code, "error_description": self.description, **self.extra} @dataclass class Scenario: id: str dir: Path owner: str session_hash: str created_at: str expires_at: str status: str = "building" # building | ready | error error: str | None = None references: dict[str, dict] = field(default_factory=dict) # private: reference -> record timeline: list[dict] = field(default_factory=list) recipients: dict[str, dict] = field(default_factory=dict) # private: who Pim shared memories with, and how to ask them lock: threading.Lock = field(default_factory=threading.Lock) # one erase at a time on this world io_lock: threading.Lock = field(default_factory=threading.Lock) # operation files: a status read never overlaps a save @property def world_dir(self) -> Path: return self.dir / "world" def persist(self) -> None: _write_json(self.dir / "scenario.json", {"id": self.id, "owner": self.owner, "session_hash": self.session_hash, "created_at": self.created_at, "expires_at": self.expires_at, "status": self.status, "error": self.error}) _write_json(self.dir / "references.json", self.references) _write_json(self.dir / "recipients.json", self.recipients) _write_json(self.dir / "timeline.json", self.timeline[-200:]) def public_recipients(self) -> list[dict]: """What the pages may know about the recipients: never a token, never the Session id.""" return [{"id": r["id"], "party": r["party"], "kind": r["kind"], "simulated": r["simulated"], "status": r.get("status"), "issuer": r.get("issuer"), "endpoint": r.get("endpoint") if not r["simulated"] else None, "poppy": None if r["simulated"] else {"identifier": r.get("identifier"), "declares": r.get("declares"), "operations": r.get("operations"), "client_id": r.get("client_id"), "why": r.get("why")}, "holds": [self.references[k]["label"] for k in r.get("shares", {}) if k in self.references and not self.references[k]["forgotten_at"]]} for r in self.recipients.values()] def log(self, actor: str, text: str) -> None: self.timeline.append({"actor": actor, "text": text, "at": now()}) def public(self) -> dict: return {"scenario": self.id, "status": self.status, "error": self.error, "expires_at": self.expires_at, "owner": {"name": JOHN["name"], "session": "synthetic session issued by this demo for its fictional user"}, "stores": [{"holder": h, "title": t, "kind": k} for h, (t, k, _) in HOLDERS.items()]} def world(self, log=None) -> World: return World(self.dir, log or (lambda actor, text: self.log(actor, text))) # -- operations on disk --------------------------------------------------------------------------- @property def ops_dir(self) -> Path: return self.dir / "operations" def op_path(self, op_id: str) -> Path: return self.ops_dir / f"{op_id}.json" def load_op(self, op_id: str) -> dict | None: if not OPERATION.match(op_id or ""): return None with self.io_lock: return _read_json(self.op_path(op_id)) def save_op(self, op: dict) -> None: with self.io_lock: self.ops_dir.mkdir(parents=True, exist_ok=True) _write_json(self.op_path(op["id"]), op) def ops(self) -> list[dict]: with self.io_lock: return [o for p in sorted(self.ops_dir.glob("fmo_*.json")) if (o := _read_json(p))] if self.ops_dir.is_dir() else [] class ForgetMe: """Pim's ForgetMe host. One instance per server; everything durable lives under `root`.""" def __init__(self, root: Path): self.root = Path(root) self.root.mkdir(parents=True, exist_ok=True) self.scenarios: dict[str, Scenario] = {} self.building = 0 self._alocks: dict[str, asyncio.Lock] = {} for d in sorted(self.root.iterdir()): meta = _read_json(d / "scenario.json") if not d.is_dir() or not meta or not SCENARIO_ID.match(d.name): continue s = Scenario(meta["id"], d, meta["owner"], meta["session_hash"], meta["created_at"], meta["expires_at"], meta.get("status", "error"), meta.get("error"), _read_json(d / "references.json", {}), _read_json(d / "timeline.json", []), _read_json(d / "recipients.json", {})) if s.status == "building": # the server went away mid-build: the world is not trustworthy s.status, s.error = "error", "the server restarted while this scenario was being built" s.persist() self.scenarios[s.id] = s self.sweep() # -- lifecycle ----------------------------------------------------------------------------------- def sweep(self) -> int: """Remove expired scenarios, world and all. Called on start and whenever one is created.""" gone = 0 for sid in list(self.scenarios): s = self.scenarios[sid] if _past(s.expires_at): self.scenarios.pop(sid) self._alocks.pop(sid, None) shutil.rmtree(s.dir, ignore_errors=True) gone += 1 return gone def live(self) -> int: return sum(1 for s in self.scenarios.values() if s.status != "error") def alock(self, sid: str) -> asyncio.Lock: return self._alocks.setdefault(sid, asyncio.Lock()) async def start(self, owner: str = OWNER) -> tuple[Scenario, str]: """Issue a synthetic signed-in session for the fictional user and build Pim's memory for it.""" self.sweep() if self.live() >= MAX_LIVE_SCENARIOS: raise ContractError(429, "busy", f"{MAX_LIVE_SCENARIOS} fresh scenarios are live right now; try again in a few minutes") sid = secrets.token_hex(8) token = secrets.token_urlsafe(24) s = Scenario(sid, self.root / sid, owner, _hash(token), now(), _in(SCENARIO_TTL)) s.dir.mkdir(parents=True) s.log("site", f"Synthetic session issued for {JOHN['name']} (a labelled fixture, not an identity provider). " f"Expires {s.expires_at}.") s.persist() self.scenarios[sid] = s self.building += 1 def build() -> None: try: w = s.world() records = w.seed(alice=False, moved=True) for r in records: ref = "fmr_" + secrets.token_urlsafe(18) s.references[ref] = {"owner": owner, "record": r["id"], "kind": r["kind"], "label": r["label"], "text": r["text"], "values": r["values"], "stores": r["stores"], "issued_at": now(), "expires_at": s.expires_at, "forgotten_at": None, "operation": None, "withdrawn_at": None, "shared_with": []} s.log("Pim", f"Every memory I wrote got an opaque reference ({len(records)} of them). The button gets a reference, " "never a value, and a missing reference never means everything.") if rcp.enabled(): self._open_recipients(s, owner) s.status = "ready" except Exception as e: # a failed build is reported, never half-served s.status, s.error = "error", f"{type(e).__name__}: {e}" s.log("fault", s.error) finally: s.persist() self.building -= 1 asyncio.create_task(asyncio.to_thread(build)) return s, f"{sid}.{token}" def _open_recipients(self, s: Scenario, owner: str) -> None: """The cross-provider level: John's old address was shared months ago with Bay Parcel (the reference Company, its own process) and with two recipients this demo simulates. Each share is an opaque recipient-specific reference on the memory record; the credential for John's Company account is a labelled fixture and stays private to the scenario.""" old_ref, old = next((k, r) for k, r in s.references.items() if r["kind"] == "address" and OLD_ADDRESS in r["text"]) try: company = rcp.open_account(rcp.company_url(), JOHN["name"], s.id, {"record": old_ref, "label": "Delivery address, saved in March", "line": OLD_ADDRESS}) except rcp.Unreachable as e: company = {"id": rcp.COMPANY_ID, "party": "Bay Parcel", "kind": "forget-me", "simulated": False, "origin": rcp.company_url(), "status": "unreachable", "why": str(e), "shares": {old_ref: None}, "account_share": rcp.new_share()} s.log("Pim", f"Bay Parcel ({rcp.company_url()}) did not answer while I was setting up: {e}. I will ask it when the time comes and retry if it is still down.") s.recipients[company["id"]] = company for rid, meta in rcp.SIMULATED.items(): s.recipients[rid] = {"id": rid, "party": meta["party"], "kind": meta["kind"], "simulated": True, "origin": None, "status": "ready", "what": meta["what"], "shares": {old_ref: f"fmr_{rid}_" + secrets.token_urlsafe(12)}, "account_share": rcp.new_share()} for rid, r in s.recipients.items(): if old_ref in r.get("shares", {}): old["shared_with"].append({"share": rcp.new_share(), "recipient": rid, "shared_at": "2026-03-04T09:12:00+00:00"}) who = ", ".join(r["party"] for r in s.recipients.values()) if company.get("status") == "ready": s.log("Pim", f"John's old address was shared, months ago, with {who}. Bay Parcel is a real second party on its own origin " f"({company['origin']}; issuer {company['issuer']}); the other two are simulated inside this demo and say so. " "Each share is an opaque reference the recipient issued; I never use an email or an address to point at a record.") s.log("Pim", f"Poppy 1.0 with Bay Parcel: its poppy.json speaks for {rcp._domain_of(company['origin'])} and names issuer {company['identifier']}, " f"confirmed by the issuer's own metadata. I hold a Session there as {company['client_id']} (a fresh Session JWT per request, " f"Poppy-Version 1.0, Poppy-Extensions {rcp.poppy_agent.extensions_header(company.get('declares') or {})}) and an access token " f"for John's account (scopes: {company.get('scope')}), from a refresh token the demo's fixture minted in place of a sign-in. " f"{'It lists the Operations extension, version 3: a withdrawal there needs your approval of its exact terms.' if company.get('operations') else 'It lists no Operations extension: it cannot be asked to withdraw anything from here.'}") elif company.get("status") in ("no-poppy", "no-forget-me"): s.log("Pim", f"Bay Parcel ({company.get('origin')}) cannot be asked: {company.get('why')}. Nothing is sent there.") def session(self, credential: str | None) -> tuple[Scenario, str] | None: """Resolve a session credential (`.`) to (scenario, owner), or None.""" if not credential or "." not in credential: return None sid, token = credential.split(".", 1) s = self.scenarios.get(sid) if not s or not hmac.compare_digest(s.session_hash, _hash(token)): return None return s, s.owner @staticmethod def require_ready(s: Scenario) -> None: if _past(s.expires_at): raise ContractError(410, "scenario_expired", "this scenario has expired; start a fresh one") if s.status == "building": raise ContractError(503, "not_ready", "Pim is still building this scenario's memory; try again in a moment") if s.status == "error": raise ContractError(500, "scenario_failed", s.error or "the scenario failed to build") # -- Pim's own UI API (the host's side, not the contract) ----------------------------------------- def memory(self, s: Scenario, owner: str) -> list[dict]: self.require_ready(s) kinds = {"address": 0, "note": 1, "contact": 2} items = [{"reference": ref, "label": r["label"], "text": r["text"], "kind": r["kind"], "saved_at": r["issued_at"], "holders": sorted(r["stores"]), "shared_with": [{"party": s.recipients[x["recipient"]]["party"], "simulated": s.recipients[x["recipient"]]["simulated"]} for x in r.get("shared_with", []) if x["recipient"] in s.recipients]} for ref, r in s.references.items() if r["owner"] == owner and not r["forgotten_at"] and not r.get("withdrawn_at")] return sorted(items, key=lambda i: (kinds.get(i["kind"], 9), i["label"])) def _withdrawn_ids(self, s: Scenario) -> list[str]: return [r["record"] for r in s.references.values() if r.get("withdrawn_at") and not r["forgotten_at"]] def book_delivery(self, s: Scenario) -> dict: """The courier asks Pim where John lives and books a delivery there. With the reference Company configured, Bay Parcel is that courier: Pim shares the address it believes (and gets an opaque reference back for it), and the booking shows what the Company's own records now say. Without it, the courier is simulated inside the run, and labelled so.""" self.require_ready(s) with s.lock: found = s.world().pim_address(exclude=self._withdrawn_ids(s)) company = s.recipients.get(rcp.COMPANY_ID) real = bool(company and company.get("status") == "ready") booking = {"courier": "Bay Parcel (reference Company)" if real else COURIER, "simulated": not real, "booked_at": now(), "address": found["address"] if found else None, "address_memories": found["address_memories"] if found else 0, "which": "new" if found and found["address"] == NEW_ADDRESS else "old" if found and found["address"] == OLD_ADDRESS else None} if found: s.log("Pim", f"{booking['courier']} asked where to deliver. I hold {found['address_memories']} address memor" f"{'y' if found['address_memories'] == 1 else 'ies'} and answer with the first: {found['address']}.") if real: ref_id, record = next(((k, r) for k, r in s.references.items() if r["record"] == found["record"]), (None, None)) if record is not None and ref_id not in company.get("shares", {}): got = rcp.share_address(company, ref_id, found["address"], record["label"]) if got: record.setdefault("shared_with", []).append({"share": rcp.new_share(), "recipient": company["id"], "shared_at": now()}) s.log("Bay Parcel", f"Booked. We now hold this address for John and issued Pim a reference for the record ({got[:12]}…); " "Pim can ask us to withdraw it by that reference.") booking["recipient"] = {"party": company["party"], "simulated": False, "holds": rcp.lookup(company)} else: s.log("Pim", f"{booking['courier']} asked where to deliver. I hold no address for John and said so.") path = s.dir / "deliveries.json" _write_json(path, [*_read_json(path, []), booking][-20:]) s.persist() return booking # -- the contract: preview ------------------------------------------------------------------------ def _reference(self, s: Scenario, owner: str, ref) -> tuple[str, dict]: if not isinstance(ref, str) or not REFERENCE.match(ref): raise ContractError(400, "missing_reference", "scope 'item' needs the opaque reference Pim issued for the memory; " "a request without one is refused, it never means account-wide") r = s.references.get(ref) if not r or r["owner"] != owner: # another owner's reference looks exactly like an unknown one raise ContractError(404, "unknown_reference", "no memory with that reference for the signed-in user") if _past(r["expires_at"]): raise ContractError(410, "reference_expired", "that reference has expired; ask Pim for the memory again") return ref, r def _scope(self, body: dict) -> str: scope = body.get("scope", "item") if scope not in SCOPES: raise ContractError(400, "bad_scope", f"scope must be one of {list(SCOPES)}; account-wide erasure is scope 'account', asked for explicitly") if scope == "account" and body.get("reference") is not None: raise ContractError(400, "bad_scope", "scope 'account' takes no reference") return scope def _exceptions_for(self, s: Scenario, owner: str, target: dict | None, values: list[str]) -> list[dict]: """Other live items of the owner that contain one of the values: the person decides each one.""" out = [] for ref, r in s.references.items(): if r["owner"] != owner or r["forgotten_at"] or r is target: continue if any(v and v in r["text"] for v in values): out.append({"id": ref, "label": r["label"], "text": r["text"], "holders": sorted(r["stores"]), "default": "keep", "options": [{"value": "keep", "label": f"Keep the {r['label'].lower()}"}, {"value": "delete", "label": f"Delete the {r['label'].lower()} too"}]}) return out def _recipient_asks(self, s: Scenario, target: dict | None, records: list[str]) -> list[dict]: """The recipients Pim shared the record(s) with, each as an exception the person decides: ask it to withdraw too (the default), or leave it. For scope account, every recipient, account-wide.""" out = [] if target is None: # account scope for rid, r in s.recipients.items(): out.append({"recipient": rid, "share": r["account_share"], "scope": "account", "reference": None}) return out for x in s.references[records[0]].get("shared_with", []): r = s.recipients.get(x["recipient"]) if r: out.append({"recipient": x["recipient"], "share": x["share"], "scope": "item", "reference": r.get("shares", {}).get(records[0])}) return out def _recipient_exception(self, s: Scenario, ask: dict) -> dict: r = s.recipients[ask["recipient"]] party = r["party"] if r["kind"] == "forget-me": if ask.get("offer"): text = (f"{party} holds a copy of this address as a delivery record (and summaries derived from it) and speaks ForgetMe over Poppy. " f"It stated the exact terms below; confirming here is your approval of them, which Pim sends with the request. " f"It answers with its own signed evidence.") elif r.get("status") == "ready" and not r.get("operations"): text = f"{party} holds a copy and speaks ForgetMe, but lists no approval exchange (Operations extension); Pim cannot ask it from here." elif r.get("status") == "ready": text = (f"{party} holds a copy and speaks ForgetMe over Poppy, but could not state its terms just now; without terms you have seen and " f"approved, nothing is performed there. Open the preview again to retry.") else: text = f"{party} holds a copy; it did not answer when Pim last tried, so Pim will retry and this row stays pending until it does." else: what = r.get("what", "") text = f"{party} holds a copy. {what[:1].upper() + what[1:]}" out = {"id": ask["share"], "label": f"{party} holds a copy" if ask["scope"] == "item" else f"{party}: everything it holds for you", "text": text, "holders": [party], "party": party, "default": "delete" if r["kind"] == "forget-me" else "keep", "options": [{"value": "delete", "label": f"Ask {party.split(' (')[0]} to withdraw it too"}, {"value": "keep", "label": f"Leave it with {party.split(' (')[0]}"}]} if ask.get("offer"): op = ask["offer"]["operation"] out["approval"] = {"party": party, "protocol": "operations/3", "approver": "user", "operation_id": op["operation_id"], "revision": op["revision"], "summary": op.get("summary"), "terms": op["terms"], "expires_at": op["expires_at"]} return out def _recipient_holder(self, s: Scenario, ask: dict) -> dict: r = s.recipients[ask["recipient"]] if r["kind"] == "forget-me": retention, what = "persistent", (f"a recipient on its own origin ({r.get('issuer') or r['party']}); its address book, delivery summaries, invoices and legacy export" if r.get("status") == "ready" else "a recipient that did not answer; what it keeps can't be previewed until it does") elif r["kind"] == "api-only": retention, what = "unknown", "a recipient that acknowledges deletions through a plain API; what it keeps can't be inspected from here" else: retention, what = "unknown", "a recipient that is offline right now; what it keeps can't be previewed" return {"holder": ask["recipient"], "title": r["party"], "kind": "recipient", "retention": retention, "what": what, "party": r["party"], "recipient": ask["recipient"]} def _resolve(self, s: Scenario, owner: str, body: dict, *, offer: bool = False) -> dict: """Validate scope and reference; return what the operation is about. With `offer`, ask each recipient that speaks Poppy for the exact terms it would perform (the Company stores the offered operation; nothing is performed), so the preview can show them and the person's confirmation can approve exactly those.""" for k in body: if k not in ("scope", "reference", "exceptions", "idempotency_key", "approvals"): raise ContractError(400, "bad_request", f"unknown field {k!r}") scope = self._scope(body) if scope == "item": ref, r = self._reference(s, owner, body.get("reference")) values = list(r["values"]) target = {"reference": ref, "label": r["label"], "text": r["text"], "kind": r["kind"], "saved_at": r["issued_at"]} holders = sorted(r["stores"]) exceptions = self._exceptions_for(s, owner, r, values) records = [ref] asks = self._recipient_asks(s, target, records) else: mine = {ref: r for ref, r in s.references.items() if r["owner"] == owner and not r["forgotten_at"]} values = sorted({v for r in mine.values() for v in r["values"]}) target = {"reference": None, "label": "Everything Pim remembers about you", "kind": "account", "text": f"{len(mine)} memory items and {len(values)} exact values", "saved_at": None} holders = sorted(HOLDERS) exceptions = [] records = sorted(mine) asks = self._recipient_asks(s, None, records) if offer: for a in asks: r = s.recipients.get(a["recipient"]) if r and r["kind"] == "forget-me" and r.get("status") == "ready": a["offer"] = rcp.offer(r, a) exceptions = exceptions + [self._recipient_exception(s, a) for a in asks] return {"scope": scope, "target": target, "values": values, "holders": holders, "exceptions": exceptions, "records": records, "asks": asks} def preview(self, s: Scenario, owner: str, body: dict) -> dict: self.require_ready(s) what = self._resolve(s, owner, body, offer=True) if any(a.get("offer") for a in what["asks"]): s.persist() # the offers Pim showed, so a confirmation can be matched to them after a restart for a in what["asks"]: if a.get("offer"): op = a["offer"]["operation"] s.log(s.recipients[a["recipient"]]["party"], f"Approval needed before anything is performed here: operation {op['operation_id']}, " f"revision {op['revision']}, valid until {op['expires_at']}. {op.get('summary', '')}") holders = [{"holder": h, "title": HOLDERS[h][0], "kind": HOLDERS[h][1], "retention": "persistent", "what": HOLDERS[h][2], "party": "Pim"} for h in what["holders"]] + [EPHEMERAL_HOLDER] + [self._recipient_holder(s, a) for a in what["asks"]] n = len(what["holders"]) changes = [ f"Pim stops answering with this memory at once, then deletes the record through its own APIs in {n} store{'s' if n != 1 else ''}, by the ids it wrote it under", "ForgetProof erases what that deletion leaves on disk: write logs, index tombstones, history rows, free pages", f"every byte of every store is then scanned for the exact text ({len(what['values'])} value{'s' if len(what['values']) != 1 else ''}; the receipt carries the count, never the text)", "one signed portable receipt per holder, verifiable in your browser against the keys this site publishes; no path or value in it", ] if what["asks"]: changes.append("each recipient you choose is asked by the opaque reference it issued; its own evidence is shown as received, one row per holder, " "and a recipient that can't answer shows as pending or unverified, never as clear") if any(a.get("offer") for a in what["asks"]): changes.append("a recipient that speaks Poppy performs its withdrawal only with your approval of the exact terms it states below; " "confirming here is that approval, sent by Pim with the request and recorded in Pim's ledger; Pim never approves for you") terms = {"reference": what["target"]["reference"], "scope": what["scope"], "exceptions": {e["id"]: e["default"] for e in what["exceptions"]}} note = "The holders are Pim's own stores on this server" + (", and the recipients Pim shared this with" if what["asks"] else "") + ". Nothing has been changed by this preview." return {"namespace": NAMESPACE, "version": VERSION, "scope": what["scope"], "item": what["target"], "holders": holders, "retention": "persistent", "changes": changes, "exceptions": what["exceptions"], "terms": terms, "note": note} # -- the contract: submit ------------------------------------------------------------------------- @staticmethod def _terms_hash(terms: dict) -> str: return _hash(json.dumps(terms, sort_keys=True, separators=(",", ":"))) def _active_or_done_for(self, s: Scenario, records: list[str]) -> dict | None: wanted = set(records) for op in s.ops(): if not wanted & set(op.get("records", [])): continue if op["state"] in ("accepted", "running"): return op if op["state"] == "done" and op["outcome"]["overall"] in ("inspected-and-clear", "intentionally-retained"): return op return None async def submit(self, s: Scenario, owner: str, body: dict) -> tuple[int, dict]: """Validate the exact terms and record the operation exactly once; the erase runs in the background.""" self.require_ready(s) key = body.get("idempotency_key") if not isinstance(key, str) or not wire.IDEMPOTENCY.match(key): raise ContractError(400, "bad_request", "idempotency_key must be 8 to 128 printable ASCII characters, chosen by the client") what = self._resolve(s, owner, body) given = body.get("exceptions", {}) if not isinstance(given, dict) or len(given) > wire.MAX_EXCEPTIONS or any(not isinstance(k, str) or v not in CHOICES for k, v in given.items()): raise ContractError(400, "bad_request", "exceptions must map each exception id to 'keep' or 'delete'") approvals = body.get("approvals", {}) if not isinstance(approvals, dict) or len(approvals) > wire.MAX_EXCEPTIONS or any( not isinstance(k, str) or not isinstance(v, dict) or not isinstance(v.get("operation_id"), str) or not isinstance(v.get("revision"), str) or not (v.get("input_type") is None or (isinstance(v["input_type"], str) and len(v["input_type"]) <= 32)) for k, v in approvals.items()): raise ContractError(400, "bad_request", "approvals must map an exception id to {operation_id, revision[, input_type]}, as the preview offered") expected = {e["id"] for e in what["exceptions"]} if set(given) != expected: raise ContractError(400, "terms_incomplete", "decide every exception the preview listed, and only those", missing=sorted(expected - set(given)), unexpected=sorted(set(given) - expected)) # A recipient that stated its terms is asked only with the person's approval of exactly those terms (the preview's # `approval`): the operation id and revision it offered, still valid. Pim never fills this in by itself. approved: dict[str, dict] = {} for a in what["asks"]: rec = s.recipients.get(a["recipient"]) if not rec or rec["kind"] != "forget-me" or given.get(a["share"]) != "delete" or not rec.get("offers", {}).get(a["share"]): continue chosen = approvals.get(a["share"]) off = rcp.offered(rec, a["share"], chosen["operation_id"], chosen["revision"]) if chosen else None if off is None: raise ContractError(400, "terms_incomplete", f"asking {rec['party']} needs your approval of the exact terms it stated in the preview " "(approvals[] = {operation_id, revision}); open the preview again if they expired", missing=[a["share"]], unexpected=[]) approved[a["share"]] = {"offer": off, "input_type": chosen.get("input_type")} unexpected = sorted(set(approvals) - {a["share"] for a in what["asks"]}) if unexpected: raise ContractError(400, "terms_incomplete", "approvals name an exception that is not a recipient of this preview", missing=[], unexpected=unexpected) terms = {"reference": what["target"]["reference"], "scope": what["scope"], "exceptions": {k: given[k] for k in sorted(given)}} terms_hash = self._terms_hash(terms) async with self.alock(s.id): index = s.dir / "idempotency" index.mkdir(exist_ok=True) marker = index / _hash(f"{owner}:{key}") if marker.exists(): op = s.load_op(marker.read_text(encoding="utf-8").strip()) if op and op["terms_hash"] == terms_hash: return 200, self._status_body(op) raise ContractError(409, "conflict", "this idempotency key was already used with different terms", operation=op["id"] if op else None) clash = self._active_or_done_for(s, what["records"]) if clash: raise ContractError(409, "double_submit", "that memory already has an operation; follow it instead of submitting again", operation=clash["id"], state=clash["state"]) op_id = "fmo_" + secrets.token_urlsafe(18) # Retrieval stops at accept: Pim no longer answers with these memories. The bytes go later, and are recorded apart. stopped = now() for ref in what["records"]: s.references[ref]["withdrawn_at"] = stopped remote = [{**a, "idempotency_key": f"{op_id}:{a['recipient']}", "attempts": 0, "pending": None, "remote_operation": None, "asked": given.get(a["share"]) == "delete"} for a in what["asks"]] ledger = [] for a in remote: if a["share"] in approved: off = approved[a["share"]]["offer"] op_ = off["operation"] entry = {"reference": "apr_" + secrets.token_urlsafe(12), "operation_id": op_["operation_id"], "revision": op_["revision"], "approver": "user", "approved_at": int(time.time()), "input_type": approved[a["share"]]["input_type"] or "tap", "party": s.recipients[a["recipient"]]["party"], "summary": op_.get("summary"), "terms": op_["terms"], "expires_at": op_["expires_at"], "pim_operation": op_id, "approved_via": "the ForgetMe button's confirmation, with the terms shown"} a["approval"] = {k: entry[k] for k in ("operation_id", "revision", "approver", "approved_at", "input_type", "reference")} a["body"] = off["body"] ledger.append(entry) approval_log = [] if ledger: path = s.dir / "pim" / "approvals.json" path.parent.mkdir(parents=True, exist_ok=True) _write_json(path, [*_read_json(path, []), *ledger][-200:]) for e in ledger: text = (f"John approved {e['party']}'s exact terms in the button (operation {e['operation_id']}, revision {e['revision']}, " f"{e['input_type']}); recorded in my ledger as {e['reference']} and sent with the request. I never approve on his behalf.") s.log("Pim", text) approval_log.append({"actor": "Pim", "text": text, "at": now()}) op = {"id": op_id, "namespace": NAMESPACE, "version": VERSION, "scenario": s.id, "owner": owner, "terms": terms, "terms_hash": terms_hash, "records": what["records"], "values_count": len(what["values"]), "item": what["target"], "exceptions": what["exceptions"], "state": "accepted", "submitted_at": now(), "retrieval_stopped_at": stopped, "started_at": None, "erase_started_at": None, "finished_at": None, "updated_at": stopped, "outcome": None, "evidence": [], "observations": [], "remote": remote, "log": approval_log} s.save_op(op) s.persist() fd = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL) with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(op["id"]) asyncio.create_task(asyncio.to_thread(self.execute, s, op["id"])) return 202, self._status_body(op) # -- execution ----------------------------------------------------------------------------------- def execute(self, s: Scenario, op_id: str) -> dict: """Run one accepted operation to completion. Exactly one thread runs this for a given op id.""" with s.lock: op = s.load_op(op_id) if not op or op["state"] != "accepted": return op or {} op["state"], op["started_at"] = "running", now() s.save_op(op) log = op["log"] def say(actor: str, text: str) -> None: log.append({"actor": actor, "text": text, "at": now()}) s.log(actor, text) try: w = s.world(say) to_delete = [s.references[r] for r in op["records"]] deleted_exceptions = [s.references[k] for k, v in op["terms"]["exceptions"].items() if v == "delete" and k in s.references] kept_exceptions = [s.references[k] for k, v in op["terms"]["exceptions"].items() if v == "keep" and k in s.references] values = sorted({v for r in to_delete for v in r["values"]}) asked = [a for a in op.get("remote", []) if a["asked"]] left = [a for a in op.get("remote", []) if not a["asked"]] say("John", f"Forget this: {op['item']['label']}." + (f" Keep: {', '.join(r['label'] for r in kept_exceptions)}." if kept_exceptions else "") + (f" Delete too: {', '.join(r['label'] for r in deleted_exceptions)}." if deleted_exceptions else "") + (f" Ask: {', '.join(s.recipients[a['recipient']]['party'] for a in asked)}." if asked else "") + (f" Leave with: {', '.join(s.recipients[a['recipient']]['party'] for a in left)}." if left else "")) w.pim_forgets_records(to_delete + deleted_exceptions) op["erase_started_at"] = now() s.save_op(op) say("forgetproof", "Now the files, not the APIs: erasing what the deletion left behind, store by store.") subj = make_subject(values) holders = [] for name, root in w.stores.items(): try: r = forget_mod.forget(root, subj, also_live=False, queue_dir=w.queue_dir, correlation_id=op["id"], issuer=ISSUER) except Exception as e: # one store failing must not hide the others' outcomes holders.append(self._holder(name, "error", None, f"{type(e).__name__}: {e}", action="erase failed", unresolved="the erase failed; nothing is claimed")) say("fault", f"{name}: {type(e).__name__}: {e}") continue if isinstance(r, forget_mod.Queued): holders.append(self._holder(name, "queued", None, "the store is open in another process; Pim finishes it at its next start", action="queued", unresolved="finishes at Pim's next start")) say("forgetproof", f"{name}: queued, the store is open elsewhere.") continue for a in r["actions"]: say("forgetproof", f"{name}: {a}") kept_here = [k for k in kept_exceptions if name in k["stores"]] if r["verdict"] == "CLEAN": outcome, detail, unresolved = "inspected-and-clear", "every byte scanned, the exact text is in none of them", None elif kept_here: outcome, detail, unresolved = "intentionally-retained", f"{', '.join(k['label'] for k in kept_here)} kept, as you chose; the exact text stays in it", f"{', '.join(k['label'] for k in kept_here)} still carries it, as you chose" else: where = ", ".join(f for c in r["canaries"] for f in c["found_in"]) or "the store" outcome, detail, unresolved = "bytes-still-found", f"the exact text was still found in {where}", "not done: the erase must run again" rid = self._store_receipt(s, op, name, r, outcome, kept=bool(kept_here), rebuilt=bool(to_delete)) holders.append(self._holder(name, outcome, rid, detail, action="deleted and erased" if outcome != "bytes-still-found" else "deleted; not clear", unresolved=unresolved)) for r in to_delete + deleted_exceptions: r["forgotten_at"], r["operation"] = now(), op["id"] # the recipients Pim shared the memory with: asked by the reference each one issued, or left, as the person chose for a in op.get("remote", []): rec = s.recipients.get(a["recipient"]) if not rec: continue if not a["asked"]: holders.append(rcp.kept_row(rec)) continue holders += self._ask(s, op, rec, a, say) op["outcome"] = self._outcome(op["item"]["label"], holders, kept_exceptions, deleted_exceptions, s) op["outcome"]["kept"] = {"memories": w.live_count(), "note": "what Pim still remembers after this operation"} op["evidence"] = [h["receipt_id"] for h in holders if h.get("receipt_id")] op["state"] = "done" say("Pim", op["outcome"]["sentence"]) except Exception as e: # pragma: no cover - the harness itself failing op["state"] = "error" op["outcome"] = {"overall": "error", "sentence": f"The operation failed: {type(e).__name__}: {e}", "holders": [], "uncertain": True} say("fault", f"{type(e).__name__}: {e}") finally: op["finished_at"] = now() op["updated_at"] = op["finished_at"] s.save_op(op) s.persist() return op def _ask(self, s: Scenario, op: dict, rec: dict, a: dict, say) -> list[dict]: """One recipient, once: its rows and receipts go on the operation; an unreachable one is queued for retry.""" try: if rec["simulated"]: result = rcp.ask_simulated(rec, a, say, lambda holder, kind, outcome, actions, coverage: self._sign_portable( s, op, holder, kind, outcome, actions, coverage, retrieval_stopped_at=None, physical_cleanup_at=None)) else: if rec.get("status") != "ready": rec.update(rcp.discover(rec["origin"])) # it was down when the scenario started: try again now if rec.get("status") == "ready" and not rec.get("credential"): rec.update({k: v for k, v in rcp.open_account(rec["origin"], JOHN["name"], s.id, {"record": op["records"][0], "label": op["item"]["label"], "line": op["item"]["text"]}).items() if k != "id"}) a["reference"] = rec["shares"].get(op["records"][0]) if rec.get("status") == "no-forget-me": a["pending"] = False obs = {"holder": rec["id"], "party": rec["party"], "outcome": "unsupported", "observed_by": ISSUER, "text": f"publishes no ForgetMe endpoint ({rec.get('why', '')}); nothing can be asked or verified", "at": now()} op["observations"].append(obs) say("Pim", f"{rec['party']} publishes no ForgetMe endpoint: an observation of mine, not evidence from it.") return [{"holder": rec["id"], "title": rec["party"], "kind": "recipient", "outcome": "unsupported", "party": rec["party"], "detail": obs["text"], "action": "not asked: no ForgetMe endpoint", "evidence": None, "unresolved": "unverifiable", "at": now()}] result = rcp.ask_company(rec, a, say) except rcp.Unreachable as e: a["pending"] = True a["why"] = str(e) say("Pim", f"{rec['party']} did not answer ({e}). The row stays pending and I retry under the same operation id.") return [rcp.unreachable_row(rec, a, str(e))] for r in result["receipts"]: self._store_remote_receipt(s, r) if result.get("observation"): op["observations"].append(result["observation"]) return result["rows"] def advance(self, s: Scenario, op: dict) -> dict: """On a status read of a done operation with outstanding recipient rows: retry what is due, re-poll what is pending, and update the rows under the same operation id. Returns the (possibly updated) op.""" due = [a for a in op.get("remote", []) if a["asked"] and a.get("pending") and (not a.get("last_attempt_at") or (datetime.now(timezone.utc) - datetime.fromisoformat(a["last_attempt_at"])).total_seconds() >= rcp.retry_after()) and a.get("attempts", 0) < rcp.MAX_ATTEMPTS] if op["state"] != "done" or not due: return op with s.lock: op = s.load_op(op["id"]) log = op["log"] def say(actor: str, text: str) -> None: log.append({"actor": actor, "text": text, "at": now()}) s.log(actor, text) rows = op["outcome"]["holders"] for a in due: live = next((x for x in op["remote"] if x["share"] == a["share"]), a) rec = s.recipients.get(live["recipient"]) if not rec: continue new_rows = self._ask(s, op, rec, live, say) prefix = rec["id"] rows[:] = [r for r in rows if not (r["holder"] == prefix or r["holder"].startswith(prefix + "-"))] + new_rows kept = [s.references[k] for k, v in op["terms"]["exceptions"].items() if v == "keep" and k in s.references] deleted = [s.references[k] for k, v in op["terms"]["exceptions"].items() if v == "delete" and k in s.references] memories = op["outcome"].get("kept") op["outcome"] = self._outcome(op["item"]["label"], rows, kept, deleted, s) if memories: op["outcome"]["kept"] = memories op["evidence"] = [h["receipt_id"] for h in rows if h.get("receipt_id")] op["updated_at"] = now() if not op["outcome"]["outstanding"]: say("Pim", op["outcome"]["sentence"]) s.save_op(op) s.persist() return op @staticmethod def _holder(name: str, outcome: str, receipt_id: str | None, detail: str, *, action: str = "", unresolved: str | None = None) -> dict: title, kind, _ = HOLDERS[name] d = {"holder": name, "title": title, "kind": kind, "outcome": outcome, "detail": detail, "party": "Pim", "action": action or outcome.replace("-", " "), "evidence": receipt_id, "unresolved": unresolved, "at": now()} if receipt_id: d["receipt_id"] = receipt_id return d def _sign_portable(self, s: Scenario, op: dict, holder: str, kind: str, outcome: str, actions: list[str], coverage: dict, *, before: dict | None = None, after: dict | None = None, retrieval_stopped_at: str | None, physical_cleanup_at: str | None, source: dict | None = None) -> dict: """Pim's portable receipt for one holder of one operation, signed with the site key. Counts, timestamps and vocabulary words only; the engine's full receipt stays private on this server.""" rid = f"{op['id']}.{holder}" if kind != "api" else f"{holder}.acknowledgment" rec = wire.issue(issuer=ISSUER, operation=op["id"], holder=holder, kind=kind, scope=op["terms"]["scope"], outcome=outcome, actions=actions, before=before or {}, after=after or {}, coverage={**coverage, "scope": "your records and their residue"}, subject_values=op.get("values_count", 0), key=receipt.load_or_create_key(), retrieval_stopped_at=retrieval_stopped_at, physical_cleanup_at=physical_cleanup_at, restore={"coverage": "unsupported"}, source_receipt=source) wire.check_portable(rec, [v for r in op["records"] for v in s.references.get(r, {}).get("values", [])]) d = s.dir / "pim" / "portable" d.mkdir(parents=True, exist_ok=True) _write_json(d / f"{rid}.json", {"receipt_id": rid, "holder": holder, "party": "Pim", "issuer": ISSUER, "issuer_key_url": ENDPOINT, "fingerprint": receipt.fingerprint(rec["public_key"]), "receipt": rec}) return rec def _store_receipt(self, s: Scenario, op: dict, store: str, rec: dict, outcome: str, *, kept: bool, rebuilt: bool, reconciled: bool = False) -> str: """Keep the engine's full receipt privately and sign the portable projection the wire carries.""" d = s.dir / "pim" / "receipts" d.mkdir(parents=True, exist_ok=True) rid = f"{op['id']}.{store}" _write_json(d / f"{rid}.json", rec) if reconciled: actions = ["scanned again after a restart; nothing erased again"] else: actions = ["active retrieval of the record stopped", "record deleted through the holder's own API, by id", "residue the deletion left behind erased", "every byte of the holder scanned for the exact text afterwards"] if kept: actions.append("record kept, as the person chose") kind = HOLDERS[store][1] self._sign_portable(s, op, store, kind, outcome, actions, {"inspected": True, "checks": sorted({*rec["before"]["findings"], *rec["after"]["findings"], "exact-text"}), "limits": [] if rec["after"]["incomplete"] is None else ["the scan could not check everything in this holder"]}, before={"residue": sum(rec["before"]["findings"].values()), "exact_text_in_your_records": True}, after={"residue": sum(rec["after"]["findings"].values()), "exact_text_in_your_records": bool(kept) or rec["after"]["canaries_found"] > 0}, retrieval_stopped_at=op.get("retrieval_stopped_at"), physical_cleanup_at=None if reconciled else now(), source=rec) return rid @staticmethod def _store_remote_receipt(s: Scenario, entry: dict) -> None: d = s.dir / "pim" / "portable" d.mkdir(parents=True, exist_ok=True) _write_json(d / f"{entry['receipt_id']}.json", entry) @staticmethod def _outcome(label: str, holders: list[dict], kept: list[dict], deleted: list[dict], s: Scenario | None = None) -> dict: """Worst outcome wins; one clean store never overrides an outstanding one. Then the human sentence.""" overall = min((h["outcome"] for h in holders), key=OUTCOMES.index, default="unsupported") names = lambda o: ", ".join(h["title"] for h in holders if h["outcome"] == o) # noqa: E731 mine = [h for h in holders if h.get("party", "Pim") == "Pim"] local = min((h["outcome"] for h in mine), key=OUTCOMES.index, default="unsupported") if local in ("inspected-and-clear", "intentionally-retained"): sentence = f"{label} removed from Pim." elif local == "queued": sentence = f"{label}: Pim has a store open, so the erase is queued there ({names('queued')}) and finishes at Pim's next start." elif local == "bytes-still-found": sentence = f"{label}: the exact text was still found in {names('bytes-still-found')}. Not done." elif local == "unsupported": sentence = f"{label}: {names('unsupported') or 'a holder'} can't be inspected from here." else: sentence = f"{label}: the erase failed in {names('error')}." if kept: sentence += f" {'One' if len(kept) == 1 else len(kept)} {kept[0]['label'].lower() if len(kept) == 1 else 'items'} kept, as you chose." if deleted: sentence += f" {', '.join(d['label'] for d in deleted)} deleted too, as you chose." others = [h for h in holders if h.get("party", "Pim") != "Pim"] if others: parties = {} for h in others: parties.setdefault(h["party"], []).append(h["outcome"]) parts = [] for party, outs in parties.items(): o = min(outs, key=OUTCOMES.index) short = party.split(" (")[0] parts.append({"inspected-and-clear": f"withdrawn from {short}", "intentionally-retained": f"{short}: withdrawn, with a disclosed retention" if any(x == "inspected-and-clear" for x in outs) else f"left with {short}, as you chose", "queued": f"{short} still pending", "unsupported": f"{short} unverified", "bytes-still-found": f"{short} not done", "error": f"{short} failed"}[o]) joined = "; ".join(parts) sentence += " " + joined[0].upper() + joined[1:] + "." counts = {o: sum(1 for h in holders if h["outcome"] == o) for o in OUTCOMES if any(h["outcome"] == o for h in holders)} outstanding = sum(1 for h in holders if h["outcome"] == "queued") return {"overall": overall, "sentence": sentence, "holders": holders, "counts": counts, "outstanding": outstanding} # -- status and evidence -------------------------------------------------------------------------- def _status_body(self, op: dict) -> dict: return {"operation": op["id"], "namespace": NAMESPACE, "version": VERSION, "state": op["state"], "terms": op["terms"], "item": op["item"], "submitted_at": op["submitted_at"], "started_at": op["started_at"], "finished_at": op["finished_at"], "updated_at": op.get("updated_at"), "retrieval_stopped_at": op.get("retrieval_stopped_at"), "outcome": op["outcome"], "log": op["log"], "reconciled": op.get("reconciled"), "status_url": f"{ENDPOINT}/operations/{op['id']}", "evidence_url": f"{ENDPOINT}/operations/{op['id']}/evidence"} def operation(self, s: Scenario, owner: str, op_id: str) -> dict: op = s.load_op(op_id) if not op or op["owner"] != owner: # another owner's operation looks exactly like an unknown one raise ContractError(404, "unknown_operation", "no operation with that id for the signed-in user") return op def status(self, s: Scenario, owner: str, op_id: str) -> dict: op = self.operation(s, owner, op_id) if op["state"] == "done" and op.get("outcome", {}).get("outstanding"): op = self.advance(s, op) return self._status_body(op) def evidence(self, s: Scenario, owner: str, op_id: str) -> dict: op = self.operation(s, owner, op_id) if op["state"] == "done" and op.get("outcome", {}).get("outstanding"): op = self.advance(s, op) receipts = [] for rid in op.get("evidence", []): entry = _read_json(s.dir / "pim" / "portable" / f"{rid}.json") if entry: receipts.append(entry) return {"operation": op["id"], "state": op["state"], "issuer": ISSUER, "issuer_key_url": ENDPOINT, "receipts": receipts, "observations": op.get("observations", []), "reconciled": op.get("reconciled"), "note": "Each receipt is one holder's signed statement: counts, timestamps and vocabulary words, never a path or a value. " "A recipient's receipt is shown as received, signed by the recipient; Pim checked it against the keys the recipient publishes."} # -- restart reconciliation ------------------------------------------------------------------------- def unfinished(self) -> list[tuple[Scenario, dict]]: return [(s, op) for s in self.scenarios.values() for op in s.ops() if op["state"] in ("accepted", "running")] def reconcile(self) -> list[dict]: """After a restart: finish what never started, and for an operation interrupted between erasing and signing, scan again instead of erasing again, and say so. Never guess.""" done = [] for s, op in self.unfinished(): if op["state"] == "accepted": done.append(self.execute(s, op["id"])) continue with s.lock: op = s.load_op(op["id"]) if not op or op["state"] != "running": continue note = "the server restarted during this operation" if not op["erase_started_at"] or not s.world_dir.is_dir(): op["state"] = "error" op["outcome"] = {"overall": "error", "uncertain": True, "holders": [], "counts": {}, "outstanding": 0, "sentence": f"{op['item']['label']}: {note} before anything was verified, and what it left " "behind can't be checked any more. Nothing is claimed. Submit it again to be sure."} op["reconciled"] = f"{note}; uncertain, not re-run" else: values = sorted({v for r in op["records"] for v in s.references[r]["values"]}) kept = [s.references[k] for k, v in op["terms"]["exceptions"].items() if v == "keep" and k in s.references] holders = [] w = s.world(lambda a, t: None) for name, root in w.stores.items(): try: report = scan(root, make_subject(values).needles) except Exception as e: # pragma: no cover holders.append(self._holder(name, "error", None, f"{type(e).__name__}: {e}", action="scan failed", unresolved="nothing is claimed")) continue summary = report.summary() canaries = [{"canary": c.number, "found_in": c.found_in} for c in report.canaries] rec = receipt.issue(root, summary, summary, [f"reconciled after a restart: scanned again, nothing erased again ({note})"], canaries, label=str(root), correlation_id=op["id"], issuer=ISSUER, subject_values=len(values), copies=[]) kept_here = any(name in k["stores"] for k in kept) if rec["verdict"] == "CLEAN": outcome, detail, unresolved = "inspected-and-clear", "scanned again after the restart; the exact text is in no byte", None elif kept_here: outcome, detail, unresolved = "intentionally-retained", "kept, as you chose; checked again after the restart", "kept, as you chose" else: outcome, detail, unresolved = "bytes-still-found", "still found after the restart; the erase did not finish", "not done" rid = self._store_receipt(s, op, name, rec, outcome, kept=kept_here, rebuilt=False, reconciled=True) holders.append(self._holder(name, outcome, rid, detail, action="scanned again", unresolved=unresolved)) for a in op.get("remote", []): rec_ = s.recipients.get(a["recipient"]) if rec_ and not a["asked"]: holders.append(rcp.kept_row(rec_)) elif rec_: a["pending"], a["attempts"] = True, a.get("attempts", 0) holders.append(rcp.unreachable_row(rec_, a, "not asked before the restart")) op["outcome"] = self._outcome(op["item"]["label"], holders, kept, [], s) op["outcome"]["sentence"] += f" (Checked again after a restart: {note}.)" op["evidence"] = [h["receipt_id"] for h in holders if h.get("receipt_id")] op["state"] = "done" op["reconciled"] = f"{note}; the stores were scanned again and the outcome comes from that scan" if op["outcome"]["overall"] in ("inspected-and-clear", "intentionally-retained") or all( h["outcome"] in ("inspected-and-clear", "intentionally-retained") for h in holders if h.get("party", "Pim") == "Pim"): for r in op["records"]: s.references[r]["forgotten_at"], s.references[r]["operation"] = now(), op["id"] op["finished_at"] = now() op["updated_at"] = op["finished_at"] s.save_op(op) s.persist() done.append(op) return done # --- running the flow without HTTP: the recorded example -------------------------------------------------- async def record_example(root: Path, out: Path) -> dict: """Run the landing page's scenario twice, once per lease choice, and write what happened for the page to show before anyone clicks. Receipts are signed with whatever key FORGETPROOF_HOME holds. With FORGETME_COMPANY_URL set (the __main__ below starts the reference Company on a loopback port when it isn't), the recorded runs include the cross-provider rows: Bay Parcel's own receipts, the simulated recipients, the pending row resolving on a later poll.""" fm = ForgetMe(root) example: dict = {"recorded_at": now(), "label": "Recorded example", "namespace": NAMESPACE, "version": VERSION, "note": "Recorded from a real run of this demo's own stores; the live button runs a fresh one on request.", "cross_provider": rcp.enabled(), "runs": []} for choice in ("keep", "delete"): steps: list[dict] = [] # click to signed outcome, as the button's host calls would make them (the audit hand-off) def step(what: str, call: str, **detail) -> None: steps.append({"at": now(), "what": what, "call": call, **detail}) s, cred = await fm.start() step("the person is signed in", "POST /pim/sessions", scenario=s.id, note="a synthetic session this demo issues for its fictional user; a host has its own sign-in") while s.status == "building": await asyncio.sleep(0.2) assert s.status == "ready", s.error owner = OWNER memory = fm.memory(s, owner) step("the host lists the memories with their opaque references", "GET /pim/memory", items=len(memory)) old = next(i for i in memory if i["kind"] == "address" and OLD_ADDRESS in i["text"]) before = fm.book_delivery(s) step("the courier books a delivery and gets the stale address", "POST /pim/deliveries", address_which=before.get("which")) recipients = s.public_recipients() # as they were before the button: who held the old address step("the person presses the button; the host asks for the preview", "POST /forget-me/v1/preview", reference=old["reference"], scope="item") pv = fm.preview(s, owner, {"reference": old["reference"], "scope": "item"}) step("the preview shows the holders, the exceptions and any recipient's exact terms; nothing has changed", "preview received", holders=len(pv["holders"]), exceptions=[e["id"] for e in pv["exceptions"]], offers=[e["approval"]["operation_id"] for e in pv["exceptions"] if e.get("approval")]) # the lease note gets this run's choice; every recipient is asked, so the recording shows every kind of row; a # recipient that stated its exact terms gets the approval the button would send (operation id and revision shown) exceptions = {e["id"]: ("delete" if e.get("party") else choice) for e in pv["exceptions"]} approvals = {e["id"]: {"operation_id": e["approval"]["operation_id"], "revision": e["approval"]["revision"], "input_type": "tap"} for e in pv["exceptions"] if e.get("approval") and exceptions[e["id"]] == "delete"} terms = {**pv["terms"], "exceptions": exceptions, "idempotency_key": f"recorded-{choice}-{s.id}", **({"approvals": approvals} if approvals else {})} step("the person decides every exception and confirms the exact terms (and approves the recipient's terms, if any)", "POST /forget-me/v1/submit", terms={k: v for k, v in terms.items() if k != "approvals"}, approvals=approvals) code, st = await fm.submit(s, owner, terms) assert code == 202, st step("the host accepts the operation; retrieval of the record stops at once", f"{code} accepted", operation=st["operation"], retrieval_stopped_at=st.get("retrieval_stopped_at")) polls = 0 while (op := fm.status(s, owner, st["operation"]))["state"] in ("accepted", "running"): polls += 1 await asyncio.sleep(0.3) first = op step("the button polls until the state is final", f"GET /forget-me/v1/operations/{st['operation']}", polls=polls, state=op["state"], overall=op["outcome"]["overall"], outstanding=op["outcome"].get("outstanding")) for _ in range(20): # the offline recipient resolves on a later poll under the same id if not op["outcome"].get("outstanding"): break await asyncio.sleep(max(rcp.retry_after(), 1.0) + 0.2) op = fm.status(s, owner, st["operation"]) if first is not op: step("a later poll under the same id resolves the pending recipient row", f"GET /forget-me/v1/operations/{st['operation']}", overall=op["outcome"]["overall"], outstanding=op["outcome"].get("outstanding")) ev = fm.evidence(s, owner, st["operation"]) step("the receipt is a secondary action: the host serves the signed portable receipts", f"GET /forget-me/v1/operations/{st['operation']}/evidence", receipts=len(ev["receipts"]), observations=len(ev.get("observations", [])), issuers=sorted({str(r.get("issuer") or r["receipt"].get("issuer")) for r in ev["receipts"]})) verified = 0 for r in ev["receipts"]: try: wire.verify(r["receipt"], None) verified += 1 except ValueError: pass step("every receipt's signature verifies; the issuer is confirmed through each issuer's own index", "forgetproof-verify: verifyEvidence(receipt, {issuer})", verified=f"{verified}/{len(ev['receipts'])}") after = fm.book_delivery(s) step("the next delivery goes to the new address", "POST /pim/deliveries", address_which=after.get("which")) example["runs"].append({"choice": choice, "memory": [i for i in memory if i["kind"] in ("address", "note")], "recipients": recipients, "delivery_before": before, "preview": pv, "operation_first": first if first is not op else None, "operation": op, "evidence": ev, "steps": steps, "delivery_after": after, "memory_after": [i for i in fm.memory(s, owner) if i["kind"] in ("address", "note")]}) shutil.rmtree(s.dir, ignore_errors=True) fm.scenarios.pop(s.id, None) key = receipt.load_or_create_key() pub = receipt.public_key_b64(key) example["signing_key"] = {"public_key": pub, "fingerprint": receipt.fingerprint(pub), "note": "the key of the machine that recorded this example"} if rcp.enabled(): try: disc = rcp.discover(rcp.company_url()) example["company_keys"] = {"issuer": disc.get("issuer"), "keys": disc.get("keys", []), "note": "the keys the reference Company published when this example was recorded"} except rcp.Unreachable: pass out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(example, indent=1) + "\n", encoding="utf-8") return example def _serve(app, port: int, lifespan: str): import threading import time import uvicorn server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning", lifespan=lifespan)) threading.Thread(target=server.run, daemon=True).start() for _ in range(100): if server.started: break time.sleep(0.1) return server def _free_port() -> int: import socket with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1] def _run_company_for_recording(data_dir: Path) -> tuple[object, str]: """The reference Company on a loopback port, in a thread, for `python -m demo.forgetme`: its own origin and key. It accepts Pim's loopback client_id (COMPANY_DEV_CLIENTS), as a local development Company does.""" port = _free_port() os.environ["COMPANY_DATA"] = str(data_dir) os.environ["COMPANY_ORIGIN"] = f"http://127.0.0.1:{port}" os.environ["COMPANY_DEV_CLIENTS"] = "1" from company import app as company_app # noqa: PLC0415 return _serve(company_app.app, port, "on"), f"http://127.0.0.1:{port}" def _run_pim_for_recording(runs_dir: Path) -> tuple[object, str]: """Pim's own server on a loopback port, so the Company can fetch Pim's Poppy client metadata document (spec 4.1) while the recorder drives the flow in-process. Only /poppy/agent.json and /poppy/jwks.json are used.""" port = _free_port() os.environ["PIM_ORIGIN"] = f"http://127.0.0.1:{port}" os.environ.setdefault("FORGETPROOF_SITE_RUNS", str(runs_dir)) from . import server as pim_server # noqa: PLC0415 return _serve(pim_server.app, port, "off"), f"http://127.0.0.1:{port}" if __name__ == "__main__": # python -m demo.forgetme demo/public/recorded/forget-me.json [--local-only] import sys import tempfile args = [a for a in sys.argv[1:] if not a.startswith("--")] target = Path(args[0] if args else "demo/public/recorded/forget-me.json") with tempfile.TemporaryDirectory(prefix="forgetme-record-") as d: servers = [] if "--local-only" not in sys.argv and not rcp.enabled(): server, url = _run_company_for_recording(Path(d) / "company") servers.append(server) os.environ["FORGETME_COMPANY_URL"] = url os.environ.setdefault("FORGETME_RECIPIENT_RETRY", "1") if "--local-only" not in sys.argv: servers.append(_run_pim_for_recording(Path(d) / "site-runs")[0]) try: ex = asyncio.run(record_example(Path(d) / "pim", target)) finally: for server in servers: server.should_exit = True print(f"recorded {len(ex['runs'])} runs to {target} ({'cross-provider' if ex['cross_provider'] else 'local only'})")