This commit is contained in:
eddiesoehnel committed 2026-10-06 14:47:01 -06:00
commit 8313c5c6b5
84 files changed
+4337

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
"""Offline durable scheduling component; external provider access is intentionally absent."""
from .ledger import Ledger, OperationState
__all__ = ["Ledger", "OperationState"]
+81
View File
@@ -0,0 +1,81 @@
from __future__ import annotations
import json
import os
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from .ledger import Ledger
def _json(handler: BaseHTTPRequestHandler, status: HTTPStatus, body: object) -> None:
payload = json.dumps(body).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json")
handler.send_header("Content-Length", str(len(payload)))
handler.end_headers()
handler.wfile.write(payload)
def make_handler(ledger: Ledger):
class Handler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: object) -> None:
return # Avoid request payloads in stdout logs.
def _body(self) -> dict:
length = int(self.headers.get("Content-Length", "0"))
if length > 16_384:
raise ValueError("request too large")
value = json.loads(self.rfile.read(length))
if not isinstance(value, dict):
raise ValueError("JSON object required")
return value
def do_GET(self) -> None:
if urlparse(self.path).path == "/health":
_json(self, HTTPStatus.OK, {"status": "ok"})
return
_json(self, HTTPStatus.NOT_FOUND, {"error": "not found"})
def do_POST(self) -> None:
path = urlparse(self.path).path
try:
body = self._body()
if path == "/transactions":
_json(self, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "HTTP intake is disabled; use a reviewed authenticated MCP transport"})
return
if path.startswith("/transactions/") and path.endswith("/claim"):
transaction_id = path.split("/")[2]
claim = ledger.claim(transaction_id, int(body.get("lease_seconds", 60)))
if claim is None:
_json(self, HTTPStatus.CONFLICT, {"error": "transaction already claimed or missing"})
else:
_json(self, HTTPStatus.OK, claim.__dict__)
return
if path == "/operations":
_json(self, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "HTTP provider operations are disabled; use reviewed MCP choreography"})
return
_json(self, HTTPStatus.NOT_FOUND, {"error": "not found"})
except (KeyError, ValueError, json.JSONDecodeError) as error:
_json(self, HTTPStatus.BAD_REQUEST, {"error": str(error)})
return Handler
def serve() -> None:
if os.environ.get("SCHEDULING_TRANSPORT_MODE") != "local-development":
raise RuntimeError("runtime is disabled pending authenticated transport provisioning")
host = os.environ.get("SCHEDULING_HOST", "localhost")
if host not in {"localhost", "::1"}:
raise RuntimeError("this service may bind only to a localhost address")
port = int(os.environ.get("SCHEDULING_PORT", "8765"))
database = Path(os.environ.get("SCHEDULING_DB", "state/scheduling-ledger.sqlite3"))
server = ThreadingHTTPServer((host, port), make_handler(Ledger(database)))
print(f"local scheduling core listening on {host}:{port}")
server.serve_forever()
if __name__ == "__main__":
serve()
+270
View File
@@ -0,0 +1,270 @@
from __future__ import annotations
from dataclasses import dataclass
from email.utils import parseaddr
from typing import Iterable
import re
class GmailValidationError(ValueError):
pass
def _address(value: str) -> str:
display, address = parseaddr(value)
if not address or "@" not in address or "," in value:
raise GmailValidationError("mail header does not contain one exact address")
return address.strip().casefold()
@dataclass(frozen=True)
class SanitizedGmailMetadata:
message_id: str
thread_id: str
sender: str
delivered_to: str
label: str
in_reply_to: str | None = None
references: tuple[str, ...] = ()
transaction_token: str | None = None
authenticated: bool = False
forwarded_requester: str | None = None
def validate_owner_forward_boundary(headers: Iterable[tuple[str, str]], owner_address: str, delivery_alias: str, *, authenticated_mailbox: bool, intake_label_present: bool) -> None:
"""Validate the canonical owner-forward boundary from provider metadata.
Alias forwarding may preserve any one of the canonical route headers. Body
content and an owner SENT copy alone do not add authority.
"""
if not authenticated_mailbox or not intake_label_present:
raise GmailValidationError("authenticated mailbox context or intake label is missing")
grouped: dict[str, list[str]] = {}
for name, value in headers:
grouped.setdefault(name.casefold(), []).append(value.strip())
if len(grouped.get("from", [])) != 1 or _address(grouped["from"][0]) != _address(owner_address):
raise GmailValidationError("outer owner does not match")
if any(value.strip().casefold() in {"bulk", "list", "junk"} for value in grouped.get("precedence", [])):
raise GmailValidationError("bulk or list mail cannot create scheduling authority")
routes = [_address(value) for name in ("to", "delivered-to", "envelope-to", "x-original-to") for value in grouped.get(name, [])]
if routes.count(_address(delivery_alias)) != 1:
raise GmailValidationError("canonical alias route is missing")
def validate_authenticated_outbound_reply(
headers: Iterable[tuple[str, str]],
*,
delivery_alias: str,
expected_rfc_message_id: str,
authenticated_mailbox: bool,
intake_label_present: bool,
) -> str:
"""Validate transient connector headers for a reply to a server-bound offer.
The returned sender is compared to the durable requester fingerprint by the
ledger caller. Gmail conversation IDs are deliberately not authorization:
a Postmark-originated offer can legitimately create a distinct thread.
"""
if not authenticated_mailbox or not intake_label_present:
raise GmailValidationError("authenticated mailbox context or intake label is missing")
grouped = _group_headers(headers)
sender = _address(_unique_header(grouped, "From"))
routes = [_address(value) for name in ("to", "delivered-to", "envelope-to", "x-original-to") for value in grouped.get(name, [])]
if routes.count(_address(delivery_alias)) != 1:
raise GmailValidationError("canonical alias route is missing")
if _unique_header(grouped, "In-Reply-To") != expected_rfc_message_id:
raise GmailValidationError("reply does not bind the durable outbound RFC message-id")
reference_ids = [value for header in grouped.get("references", []) for value in re.findall(r"<[^<>\s]+>", header)]
if expected_rfc_message_id not in reference_ids:
raise GmailValidationError("reply references do not bind the durable outbound RFC message-id")
if any(value.casefold() in {"bulk", "list", "junk"} for value in grouped.get("precedence", [])):
raise GmailValidationError("bulk or list mail cannot create scheduling authority")
if any(value.casefold() not in {"", "no"} for name in ("auto-submitted", "x-autoreply", "x-autorespond") for value in grouped.get(name, [])):
raise GmailValidationError("automated mail cannot create scheduling authority")
return sender
def _unique_header(grouped: dict[str, list[str]], name: str) -> str:
values = grouped.get(name.casefold(), [])
if len(values) != 1 or not values[0]:
raise GmailValidationError(f"exactly one {name} header is required")
return values[0]
def _group_headers(headers: Iterable[tuple[str, str]]) -> dict[str, list[str]]:
grouped: dict[str, list[str]] = {}
for name, value in headers:
grouped.setdefault(name.casefold(), []).append(value.strip())
return grouped
def _domain(address: str) -> str:
return _address(address).rsplit("@", 1)[1]
def _split_authentication_clauses(value: str) -> list[str]:
"""Split Authentication-Results clauses without trusting comment text.
Authentication-Results uses semicolons for clause boundaries, but Gmail
result comments and quoted strings may themselves contain semicolons. The
parser deliberately preserves the raw clause text for a second pass rather
than using global regular-expression searches.
"""
clauses: list[str] = []
start = 0
comment_depth = 0
quoted = False
escaped = False
for index, character in enumerate(value):
if escaped:
escaped = False
continue
if character == "\\" and (quoted or comment_depth):
escaped = True
elif quoted:
if character == '"':
quoted = False
elif comment_depth:
if character == "(":
comment_depth += 1
elif character == ")":
comment_depth -= 1
elif character == '"':
quoted = True
elif character == "(":
comment_depth = 1
elif character == ";":
clauses.append(value[start:index].strip())
start = index + 1
if quoted or comment_depth:
raise GmailValidationError("authentication result has unterminated quoted text or comment")
clauses.append(value[start:].strip())
return clauses
def _authentication_clause_without_comments(value: str) -> str:
"""Remove comments and quoted strings before recognizing result tokens."""
output: list[str] = []
comment_depth = 0
quoted = False
escaped = False
for character in value:
if escaped:
escaped = False
if not comment_depth and not quoted:
output.append(character)
continue
if character == "\\" and (quoted or comment_depth):
escaped = True
continue
if quoted:
if character == '"':
quoted = False
continue
if comment_depth:
if character == "(":
comment_depth += 1
elif character == ")":
comment_depth -= 1
continue
if character == '"':
quoted = True
elif character == "(":
comment_depth = 1
else:
output.append(character)
if quoted or comment_depth:
raise GmailValidationError("authentication result has unterminated quoted text or comment")
return "".join(output).strip()
def _require_authoritative_original_authentication(value: str, requester_address: str) -> None:
"""Check the locally enforceable shape of a Gmail-authenticated result.
This does not establish that a caller obtained the header from Gmail; the
cloud connector must establish that provenance. It rejects results that do
not exactly match the observed trusted issuer and requester-domain identity.
"""
parts = _split_authentication_clauses(value)
if not parts or parts[0].casefold() != "mx.google.com":
raise GmailValidationError("authentication result issuer is not trusted")
method_clauses: dict[str, str] = {}
for raw_clause in parts[1:]:
clause = _authentication_clause_without_comments(raw_clause)
match = re.match(r"^(dkim|spf|dmarc)\s*=\s*([A-Za-z]+)(?:\s|$)", clause, flags=re.IGNORECASE)
if not match:
continue
method, outcome = match.group(1).casefold(), match.group(2).casefold()
if method in method_clauses or outcome != "pass":
raise GmailValidationError("authentication result has missing, conflicting, or non-pass methods")
method_clauses[method] = clause
if set(method_clauses) != {"dkim", "spf", "dmarc"}:
raise GmailValidationError("authentication result has missing, conflicting, or non-pass methods")
requester_domain = _domain(requester_address)
identity_patterns = {
"dkim": r"\bheader\.i\s*=\s*@([A-Za-z0-9.-]+)\b",
"spf": r"\bsmtp\.mailfrom\s*=\s*[^\s;@]+@([A-Za-z0-9.-]+)\b",
"dmarc": r"\bheader\.from\s*=\s*([A-Za-z0-9.-]+)\b",
}
for method, pattern in identity_patterns.items():
identities = re.findall(pattern, method_clauses[method], flags=re.IGNORECASE)
if len(identities) != 1 or identities[0].casefold() != requester_domain:
raise GmailValidationError(f"{method} authentication identity is not aligned to requester domain")
def validate_owner_sent_forward_provenance(
*,
forward_headers: Iterable[tuple[str, str]],
original_headers: Iterable[tuple[str, str]],
owner_address: str,
requester_address: str,
original_rfc_message_id: str,
) -> None:
"""Validate a deliberate owner forward bound to an authenticated received original.
The caller remains responsible for authenticating Gmail provenance. This
function rejects ambiguous header sets and verifies the locally enforceable
cross-message identity and RFC threading relationships without retaining
either header set.
"""
if not original_rfc_message_id or not re.fullmatch(r"<[^<>\s]+>", original_rfc_message_id.strip()):
raise GmailValidationError("original RFC message id is invalid")
forward, original = _group_headers(forward_headers), _group_headers(original_headers)
if _address(_unique_header(forward, "From")) != _address(owner_address):
raise GmailValidationError("owner sent forward has wrong outer sender")
_unique_header(forward, "Message-ID")
if _address(_unique_header(original, "From")) != _address(requester_address):
raise GmailValidationError("received original has wrong requester")
if _address(_unique_header(original, "To")) != _address(owner_address):
raise GmailValidationError("received original has wrong recipient")
if _unique_header(original, "Message-ID") != original_rfc_message_id.strip():
raise GmailValidationError("original RFC message id does not bind the received original")
if _unique_header(forward, "In-Reply-To") != original_rfc_message_id.strip() or _unique_header(forward, "References") != original_rfc_message_id.strip():
raise GmailValidationError("owner sent forward does not exactly bind the received original")
_require_authoritative_original_authentication(_unique_header(original, "Authentication-Results"), requester_address)
for grouped in (forward, original):
if any(value.casefold() in {"bulk", "list", "junk"} for value in grouped.get("precedence", [])):
raise GmailValidationError("bulk or list mail cannot create scheduling authority")
if any(value.casefold() not in {"", "no"} for name in ("auto-submitted", "x-autoreply", "x-autorespond") for value in grouped.get(name, [])):
raise GmailValidationError("automated mail cannot create scheduling authority")
def validate_intake(metadata: SanitizedGmailMetadata, owner_sender: str, route: str, intake_label: str) -> SanitizedGmailMetadata:
"""Authorize only an authenticated owner-forwarded new request.
The cloud connector extracts the one forwarded requester from the permitted
forwarded metadata; body text itself never grants authority.
"""
if not metadata.authenticated or metadata.sender.casefold() != owner_sender.casefold() or metadata.delivered_to.casefold() != route.casefold() or metadata.label != intake_label:
raise GmailValidationError("intake metadata is not authorized")
if not metadata.message_id or not metadata.thread_id or not metadata.forwarded_requester:
raise GmailValidationError("message identity is required")
return metadata
def validate_reply_lineage(metadata: SanitizedGmailMetadata, bound_requester: str, route: str, intake_label: str, outbound_rfc_message_id: str, transaction_token: str) -> SanitizedGmailMetadata:
if not metadata.authenticated or metadata.sender.casefold() != bound_requester.casefold() or metadata.delivered_to.casefold() != route.casefold() or metadata.label != intake_label:
raise GmailValidationError("reply sender, route, or label is not bound")
if metadata.in_reply_to != outbound_rfc_message_id or outbound_rfc_message_id not in metadata.references or metadata.transaction_token != transaction_token:
raise GmailValidationError("reply lineage does not bind to recorded outbound message")
return metadata
+532
View File
@@ -0,0 +1,532 @@
from __future__ import annotations
import sqlite3
import uuid
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from enum import StrEnum
from pathlib import Path
import hashlib
import json
import re
from email.utils import parseaddr
from .policy import ValidatedIntent
class OperationState(StrEnum):
PENDING = "pending"
DISPATCHING = "dispatching"
ACCEPTED = "accepted"
COMPLETED = "completed"
FAILED = "failed"
UNCERTAIN = "uncertain"
@dataclass(frozen=True)
class Claim:
transaction_id: str
lease_token: str
lease_expires_at: str
class Ledger:
"""SQLite-backed transaction state. All writes use BEGIN IMMEDIATE as the writer gate."""
def __init__(self, database_path: str | Path) -> None:
self.path = Path(database_path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self._initialize()
def _connect(self) -> sqlite3.Connection:
connection = sqlite3.connect(self.path, timeout=10, isolation_level=None)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA journal_mode=WAL")
connection.execute("PRAGMA foreign_keys=ON")
return connection
@contextmanager
def _session(self):
connection = self._connect()
try:
with connection:
yield connection
finally:
connection.close()
def _initialize(self) -> None:
with self._session() as connection:
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS transactions (
id TEXT PRIMARY KEY,
state TEXT NOT NULL,
policy_revision TEXT NOT NULL,
intent_digest TEXT NOT NULL,
policy_evidence_json TEXT NOT NULL,
requester_fingerprint TEXT NOT NULL DEFAULT '',
sender TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL DEFAULT '',
max_exchanges INTEGER NOT NULL DEFAULT 0,
exchange_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
lease_token TEXT,
lease_expires_at TEXT
);
CREATE TABLE IF NOT EXISTS provider_operations (
id TEXT PRIMARY KEY,
transaction_id TEXT NOT NULL REFERENCES transactions(id),
operation_key TEXT NOT NULL UNIQUE,
provider TEXT NOT NULL,
action TEXT NOT NULL,
state TEXT NOT NULL,
provider_id TEXT,
rfc_message_id TEXT NOT NULL DEFAULT '',
provider_evidence_json TEXT NOT NULL DEFAULT '',
purpose TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(transaction_id, provider, action, operation_key)
);
CREATE INDEX IF NOT EXISTS idx_operations_reconcile
ON provider_operations(state, updated_at);
CREATE TABLE IF NOT EXISTS test_evidence (
test_key TEXT PRIMARY KEY,
evidence_digest TEXT NOT NULL,
recorded_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS exchange_messages (
transaction_id TEXT NOT NULL REFERENCES transactions(id),
message_key TEXT NOT NULL,
direction TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (transaction_id, message_key)
);
CREATE TABLE IF NOT EXISTS intake_message_bindings (
message_digest TEXT PRIMARY KEY,
transaction_id TEXT NOT NULL REFERENCES transactions(id),
created_at TEXT NOT NULL
);
"""
)
columns = {row["name"] for row in connection.execute("PRAGMA table_info(transactions)")}
for name, definition in {
"policy_revision": "TEXT NOT NULL DEFAULT ''",
"intent_digest": "TEXT NOT NULL DEFAULT ''",
"policy_evidence_json": "TEXT NOT NULL DEFAULT '{}'",
"requester_fingerprint": "TEXT NOT NULL DEFAULT ''",
"sender": "TEXT NOT NULL DEFAULT ''",
"expires_at": "TEXT NOT NULL DEFAULT ''",
"max_exchanges": "INTEGER NOT NULL DEFAULT 0",
"exchange_count": "INTEGER NOT NULL DEFAULT 0",
"booking_evidence_json": "TEXT NOT NULL DEFAULT ''",
"closing_reserve": "INTEGER NOT NULL DEFAULT 0",
"owner_fingerprint": "TEXT NOT NULL DEFAULT ''",
}.items():
if name not in columns:
connection.execute(f"ALTER TABLE transactions ADD COLUMN {name} {definition}")
operation_columns = {row["name"] for row in connection.execute("PRAGMA table_info(provider_operations)")}
if "provider_evidence_json" not in operation_columns:
connection.execute("ALTER TABLE provider_operations ADD COLUMN provider_evidence_json TEXT NOT NULL DEFAULT ''")
if "purpose" not in operation_columns:
connection.execute("ALTER TABLE provider_operations ADD COLUMN purpose TEXT NOT NULL DEFAULT ''")
if "rfc_message_id" not in operation_columns:
connection.execute("ALTER TABLE provider_operations ADD COLUMN rfc_message_id TEXT NOT NULL DEFAULT ''")
connection.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_postmark_closing_purpose ON provider_operations(transaction_id, purpose) WHERE provider='postmark' AND purpose IN ('confirmation', 'owner_summary')")
connection.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_postmark_rfc_message_id ON provider_operations(rfc_message_id) WHERE provider='postmark' AND rfc_message_id <> ''")
connection.execute("""CREATE TABLE IF NOT EXISTS reply_message_bindings (
message_digest TEXT PRIMARY KEY,
transaction_id TEXT NOT NULL REFERENCES transactions(id),
thread_digest TEXT NOT NULL,
created_at TEXT NOT NULL
)""")
@staticmethod
def _now() -> datetime:
return datetime.now(UTC)
@classmethod
def _timestamp(cls) -> str:
return cls._now().isoformat()
def create_transaction(self, intent: ValidatedIntent, policy_revision: str, max_exchanges: int, state: str = "received", owner: str | None = None) -> str:
if max_exchanges < 1:
raise ValueError("max_exchanges must be positive")
identifier = intent.transaction_id or str(uuid.uuid4())
now = self._timestamp()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute(
"""INSERT INTO transactions
(id, state, policy_revision, intent_digest, policy_evidence_json, requester_fingerprint, owner_fingerprint, sender, expires_at, max_exchanges, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(identifier, state, policy_revision, intent.intent_digest, "{}", intent.requester_fingerprint, hashlib.sha256(owner.strip().casefold().encode()).hexdigest() if owner else "", intent.sender, intent.expires_at, max_exchanges, now, now),
)
return identifier
def create_pending_negotiation(self, *, transaction_id: str, requester: str, sender: str, owner: str, authentication_evidence_id: str, gmail_thread_id: str, policy_revision: str, default_duration_minutes: int, max_exchanges: int, expires_at: datetime, intake_message_digests: tuple[str, ...] = (), intake_audit_digest: str = "") -> str:
"""Create a validated owner-forward negotiation before a slot is selected."""
if not all((transaction_id, requester, sender, owner, authentication_evidence_id, gmail_thread_id)) or default_duration_minutes <= 0 or max_exchanges < 1 or expires_at.tzinfo is None:
raise ValueError("pending negotiation is incomplete")
if (intake_message_digests and (len(set(intake_message_digests)) != len(intake_message_digests) or not all(re.fullmatch(r"[0-9a-f]{64}", digest) for digest in intake_message_digests))) or (intake_audit_digest and not re.fullmatch(r"[0-9a-f]{64}", intake_audit_digest)):
raise ValueError("intake audit bindings are invalid")
normalized = {"auth": authentication_evidence_id, "thread": gmail_thread_id, "duration": default_duration_minutes, "intake_audit_digest": intake_audit_digest}
intent_digest = hashlib.sha256(json.dumps(normalized, sort_keys=True).encode()).hexdigest()
now = self._timestamp()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute("INSERT INTO transactions (id,state,policy_revision,intent_digest,policy_evidence_json,requester_fingerprint,owner_fingerprint,sender,expires_at,max_exchanges,created_at,updated_at) VALUES (?, 'received', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (transaction_id, policy_revision, intent_digest, json.dumps(normalized), hashlib.sha256(requester.strip().casefold().encode()).hexdigest(), hashlib.sha256(owner.strip().casefold().encode()).hexdigest(), sender.strip(), expires_at.astimezone(UTC).isoformat(), max_exchanges, now, now))
for digest in intake_message_digests:
try:
connection.execute("INSERT INTO intake_message_bindings (message_digest, transaction_id, created_at) VALUES (?, ?, ?)", (digest, transaction_id, now))
except sqlite3.IntegrityError as error:
raise ValueError("intake message id is already bound to another transaction") from error
return transaction_id
def create_authorized_owner_delivery_test(
self,
*,
transaction_id: str,
sender: str,
recipient: str,
expires_at: datetime,
) -> str:
"""Create the one-message ledger record used by the reviewed owner test only.
This deliberately does not accept scheduling-intent fields and cannot book a
meeting. Production intake continues to require ``create_transaction`` with
a fully validated intent.
"""
if not transaction_id.startswith("authorized-owner-delivery-test-"):
raise ValueError("delivery test transaction id is not allow-listed")
if not sender.strip() or not recipient.strip() or expires_at.tzinfo is None:
raise ValueError("delivery test identity or expiry is invalid")
now = self._timestamp()
normalized = {
"kind": "authorized-owner-delivery-test-v1",
"sender": sender.strip().casefold(),
"recipient": recipient.strip().casefold(),
}
digest = hashlib.sha256(repr(sorted(normalized.items())).encode("utf-8")).hexdigest()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute(
"""INSERT INTO transactions
(id, state, policy_revision, intent_digest, policy_evidence_json, requester_fingerprint, sender, expires_at, max_exchanges, created_at, updated_at)
VALUES (?, 'authorized_delivery_test', 'authorized-owner-delivery-test-v1', ?, '{"authorized":true}', ?, ?, ?, 1, ?, ?)
ON CONFLICT(id) DO NOTHING""",
(
transaction_id,
digest,
hashlib.sha256(recipient.strip().casefold().encode()).hexdigest(),
sender.strip(),
expires_at.astimezone(UTC).isoformat(),
now,
now,
),
)
row = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if row["sender"].casefold() != sender.strip().casefold() or row["requester_fingerprint"] != hashlib.sha256(recipient.strip().casefold().encode()).hexdigest():
raise ValueError("delivery test id belongs to a different recipient or sender")
return transaction_id
def operation_for_key(self, operation_key: str) -> sqlite3.Row | None:
with self._session() as connection:
return connection.execute("SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)).fetchone()
def transaction_status(self, transaction_id: str) -> sqlite3.Row:
with self._session() as connection:
row = connection.execute(
"SELECT id, state, expires_at, exchange_count, max_exchanges, lease_expires_at FROM transactions WHERE id=?",
(transaction_id,),
).fetchone()
if row is None:
raise KeyError("unknown transaction")
return row
def require_bound_requester(self, transaction_id: str, requester: str) -> None:
if not requester:
raise ValueError("reply requester is required")
with self._session() as connection:
row = connection.execute("SELECT requester_fingerprint FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if row is None or row["requester_fingerprint"] != hashlib.sha256(requester.strip().casefold().encode()).hexdigest():
raise ValueError("reply sender is not the durable requester")
@staticmethod
def _require_lease_row(row: sqlite3.Row | None, lease_token: str, now: datetime) -> None:
if row is None or not lease_token or row["lease_token"] != lease_token or not row["lease_expires_at"] or datetime.fromisoformat(row["lease_expires_at"]) <= now.astimezone(UTC):
raise ValueError("valid transaction lease is required")
def record_owner_transport_evidence(self, test_key: str, evidence: dict[str, str]) -> None:
"""Store only a digest for a fixed, non-production owner transport test."""
if test_key != "authorized-owner-delivery-test-gmail-reply-v1":
raise ValueError("test evidence key is not allow-listed")
if set(evidence) != {"message_id", "thread_id", "sender", "recipient", "observed_at"} or not all(evidence.values()):
raise ValueError("test evidence fields are invalid")
digest = hashlib.sha256(repr(sorted(evidence.items())).encode("utf-8")).hexdigest()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute(
"INSERT INTO test_evidence (test_key, evidence_digest, recorded_at) VALUES (?, ?, ?) ON CONFLICT(test_key) DO NOTHING",
(test_key, digest, self._timestamp()),
)
def record_supervised_test_evidence(self, test_key: str, evidence: dict[str, str]) -> None:
if test_key not in {"authorized-supervised-calendar-invite-delivery-v1", "authorized-supervised-postmark-confirmation-delivery-v1"} or not evidence or not all(evidence.values()):
raise ValueError("supervised test evidence is invalid")
digest = hashlib.sha256(repr(sorted(evidence.items())).encode("utf-8")).hexdigest()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
connection.execute("INSERT INTO test_evidence (test_key, evidence_digest, recorded_at) VALUES (?, ?, ?) ON CONFLICT(test_key) DO NOTHING", (test_key, digest, self._timestamp()))
def claim(self, transaction_id: str, lease_seconds: int = 60, now: datetime | None = None) -> Claim | None:
if lease_seconds < 1:
raise ValueError("lease_seconds must be positive")
now = now or self._now()
now_text = now.isoformat()
token = str(uuid.uuid4())
expiry = (now + timedelta(seconds=lease_seconds)).isoformat()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
updated = connection.execute(
"""UPDATE transactions
SET lease_token=?, lease_expires_at=?, updated_at=?
WHERE id=? AND (lease_expires_at IS NULL OR lease_expires_at < ?)""",
(token, expiry, now_text, transaction_id, now_text),
).rowcount
return Claim(transaction_id, token, expiry) if updated else None
def require_lease(self, transaction_id: str, lease_token: str, now: datetime | None = None) -> None:
now = now or self._now()
with self._session() as connection:
row = connection.execute("SELECT lease_token, lease_expires_at FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(row, lease_token, now)
def require_lease_in_transaction(self, connection: sqlite3.Connection, transaction_id: str, lease_token: str, now: datetime | None = None) -> None:
now = now or self._now()
row = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(row, lease_token, now)
def record_inbound_exchange(self, transaction_id: str, lease_token: str, message_key: str, now: datetime | None = None) -> None:
if not message_key:
raise ValueError("inbound message id is required")
now = now or self._now()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(transaction, lease_token, now)
exists = connection.execute("SELECT 1 FROM exchange_messages WHERE transaction_id=? AND message_key=?", (transaction_id, message_key)).fetchone()
if exists:
return
if transaction["exchange_count"] >= transaction["max_exchanges"] - transaction["closing_reserve"]:
raise ValueError("exchange cap reached")
connection.execute("INSERT INTO exchange_messages (transaction_id,message_key,direction,created_at) VALUES (?,?,'inbound',?)", (transaction_id, message_key, now.isoformat()))
connection.execute("UPDATE transactions SET exchange_count=exchange_count+1, updated_at=? WHERE id=?", (now.isoformat(), transaction_id))
def ensure_inbound_exchange_capacity(self, transaction_id: str, lease_token: str, message_key: str, now: datetime | None = None) -> None:
now = now or self._now()
with self._session() as connection:
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(transaction, lease_token, now)
exists = connection.execute("SELECT 1 FROM exchange_messages WHERE transaction_id=? AND message_key=?", (transaction_id, message_key)).fetchone()
if not exists and transaction["exchange_count"] >= transaction["max_exchanges"] - transaction["closing_reserve"]:
raise ValueError("exchange cap reached")
def reserve_closing_capacity(self, transaction_id: str, lease_token: str, now: datetime | None = None) -> None:
now = now or self._now()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(transaction, lease_token, now)
if transaction["state"] != "booking_pending":
raise ValueError("closing capacity may be reserved only before booking")
if transaction["closing_reserve"] == 2:
return
if transaction["closing_reserve"] or transaction["exchange_count"] + 2 > transaction["max_exchanges"]:
raise ValueError("insufficient exchange capacity for confirmation and owner summary")
connection.execute("UPDATE transactions SET closing_reserve=2, updated_at=? WHERE id=?", (now.isoformat(), transaction_id))
def record_operation(self, transaction_id: str, operation_key: str, provider: str, action: str) -> sqlite3.Row:
"""Create an idempotent operation. This records intent only; it never calls a provider."""
if provider not in {"postmark", "calendar", "zoom"}:
raise ValueError("provider is not allow-listed")
if action not in {"send", "create_event", "verify_event", "reconcile"}:
raise ValueError("action is not allow-listed")
if provider in {"calendar", "zoom"} and action == "create_event":
raise ValueError("booking operations must use the fenced reservation API")
now = self._timestamp()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
exists = connection.execute("SELECT 1 FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if not exists:
raise KeyError("unknown transaction")
connection.execute(
"""INSERT INTO provider_operations
(id, transaction_id, operation_key, provider, action, state, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(operation_key) DO NOTHING""",
(str(uuid.uuid4()), transaction_id, operation_key, provider, action, OperationState.PENDING, now, now),
)
row = connection.execute(
"SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)
).fetchone()
if row["transaction_id"] != transaction_id or row["provider"] != provider or row["action"] != action:
raise ValueError("operation_key already belongs to a different intent")
return row
def reserve_booking_operation(self, transaction_id: str, lease_token: str, operation_key: str, provider: str) -> sqlite3.Row:
if provider not in {"calendar", "zoom"}:
raise ValueError("booking provider is not allow-listed")
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(transaction, lease_token, self._now())
if transaction["state"] != "booking_pending" or not transaction["booking_evidence_json"] or transaction["closing_reserve"] != 2:
raise ValueError("booking operation requires an accepted offered slot")
existing = connection.execute("SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)).fetchone()
if existing is not None:
if existing["transaction_id"] != transaction_id or existing["provider"] != provider or existing["action"] != "create_event":
raise ValueError("operation_key already belongs to a different intent")
return existing
prior = connection.execute(
"SELECT operation_key FROM provider_operations WHERE transaction_id=? AND provider=? AND action='create_event'",
(transaction_id, provider),
).fetchone()
if prior is not None:
raise ValueError("booking provider already has a fenced operation; replay its key or reconcile it")
now = self._timestamp()
connection.execute("INSERT INTO provider_operations (id, transaction_id, operation_key, provider, action, state, created_at, updated_at) VALUES (?, ?, ?, ?, 'create_event', ?, ?, ?) ON CONFLICT(operation_key) DO NOTHING", (str(uuid.uuid4()), transaction_id, operation_key, provider, OperationState.PENDING, now, now))
row = connection.execute("SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)).fetchone()
if row["transaction_id"] != transaction_id or row["provider"] != provider or row["action"] != "create_event":
raise ValueError("operation_key already belongs to a different intent")
return row
def record_postmark_send(self, transaction_id: str, lease_token: str, operation_key: str, sender: str, requester: str, now: datetime | None = None, purpose: str = "offer", closing: bool = False) -> sqlite3.Row:
"""Reserve one outbound message atomically; caller must reconcile before a retry."""
now = now or self._now()
closing_purposes = {"confirmation", "owner_summary"}
if purpose not in {"offer", "clarification", "alternative", "terminal", *closing_purposes} or closing != (purpose in closing_purposes):
raise ValueError("postmark purpose does not match closing reservation")
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if transaction is None:
raise KeyError("unknown transaction")
self._require_lease_row(transaction, lease_token, now)
if transaction["sender"].casefold() != sender.strip().casefold() or (purpose != "owner_summary" and transaction["requester_fingerprint"] != hashlib.sha256(requester.strip().casefold().encode()).hexdigest()):
raise ValueError("sender or requester is not bound to this transaction")
existing = connection.execute("SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)).fetchone()
if existing is not None:
if existing["transaction_id"] != transaction_id or existing["provider"] != "postmark" or existing["action"] != "send":
raise ValueError("operation_key already belongs to a different intent")
if existing["purpose"] != purpose:
raise ValueError("operation_key already belongs to a different message purpose")
if not existing["rfc_message_id"]:
raise ValueError("legacy outbound operation lacks a verified RFC message-id mapping")
return existing
if datetime.fromisoformat(transaction["expires_at"]) <= now.astimezone(UTC):
raise ValueError("transaction is expired")
limit = transaction["max_exchanges"] if closing else transaction["max_exchanges"] - transaction["closing_reserve"]
if transaction["exchange_count"] >= limit or (closing and transaction["closing_reserve"] < 1):
raise ValueError("exchange cap reached")
stamp = now.isoformat()
_, address = parseaddr(sender)
domain = address.rsplit("@", 1)[1] if "@" in address else "host.example.internal"
rfc_message_id = f"<sched-{uuid.uuid4()}@{domain}>"
try:
connection.execute("INSERT INTO provider_operations (id, transaction_id, operation_key, provider, action, state, purpose, rfc_message_id, created_at, updated_at) VALUES (?, ?, ?, 'postmark', 'send', ?, ?, ?, ?, ?)", (str(uuid.uuid4()), transaction_id, operation_key, OperationState.PENDING, purpose, rfc_message_id, stamp, stamp))
except sqlite3.IntegrityError as error:
if purpose in closing_purposes:
raise ValueError("closing message purpose is already reserved") from error
raise
connection.execute("UPDATE transactions SET exchange_count=exchange_count+1, updated_at=? WHERE id=?", (stamp, transaction_id))
connection.execute("INSERT INTO exchange_messages (transaction_id,message_key,direction,created_at) VALUES (?,?,'outbound',?)", (transaction_id, operation_key, stamp))
if closing:
connection.execute("UPDATE transactions SET closing_reserve=closing_reserve-1 WHERE id=?", (transaction_id,))
return connection.execute("SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)).fetchone()
def transition_operation(self, transaction_id: str, lease_token: str, operation_key: str, state: OperationState, provider_id: str | None = None, provider_readback: dict[str, str] | None = None) -> sqlite3.Row:
now = self._timestamp()
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
current = connection.execute(
"SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)
).fetchone()
if current is None:
raise KeyError("unknown operation")
if current["transaction_id"] != transaction_id:
raise ValueError("operation does not belong to transaction")
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(transaction, lease_token, self._now())
allowed = {
OperationState.PENDING: {OperationState.DISPATCHING, OperationState.FAILED, OperationState.UNCERTAIN},
OperationState.DISPATCHING: {OperationState.ACCEPTED, OperationState.FAILED, OperationState.UNCERTAIN},
OperationState.ACCEPTED: {OperationState.COMPLETED, OperationState.FAILED, OperationState.UNCERTAIN},
OperationState.UNCERTAIN: {OperationState.ACCEPTED, OperationState.COMPLETED, OperationState.FAILED},
OperationState.COMPLETED: set(),
OperationState.FAILED: set(),
}
old = OperationState(current["state"])
if old == OperationState.PENDING and current["provider"] in {"calendar", "zoom"}:
allowed[OperationState.PENDING] = {OperationState.ACCEPTED, OperationState.FAILED, OperationState.UNCERTAIN}
if state == old:
return current
if state not in allowed[old]:
raise ValueError(f"invalid operation transition: {old} -> {state}")
if state in {OperationState.ACCEPTED, OperationState.COMPLETED} and not provider_id and not current["provider_id"]:
raise ValueError("accepted and completed outcomes require a provider id")
if state == OperationState.COMPLETED and current["provider"] in {"calendar", "zoom"}:
booking = json.loads(transaction["booking_evidence_json"] or "{}")
if not booking or not transaction["owner_fingerprint"]:
raise ValueError("legacy booking rows cannot be completed without migration-era identity bindings")
if current["provider"] == "zoom":
required = {"meeting_id", "join_url_digest", "start_time", "duration_minutes", "timezone", "host_fingerprint"}
if not provider_readback or set(provider_readback) != required or provider_readback["meeting_id"] != (provider_id or current["provider_id"]) or not all(provider_readback[key] for key in required if key != "duration_minutes"):
raise ValueError("zoom completion requires normalized matching readback")
try:
start = datetime.fromisoformat(provider_readback["start_time"].replace("Z", "+00:00"))
duration = int(provider_readback["duration_minutes"])
except (TypeError, ValueError):
raise ValueError("zoom readback time is invalid") from None
booked_start = datetime.fromisoformat(booking["start_at"].replace("Z", "+00:00"))
booked_end = datetime.fromisoformat(booking["end_at"].replace("Z", "+00:00"))
if start.astimezone(UTC) != booked_start.astimezone(UTC) or duration != int((booked_end - booked_start).total_seconds() // 60):
raise ValueError("zoom readback does not match selected interval")
else:
required = {"event_id", "start_time", "end_time", "attendee_fingerprints", "status", "visibility", "join_url_candidates", "guests_can_modify"}
if not provider_readback or set(provider_readback) != required or provider_readback["event_id"] != (provider_id or current["provider_id"]) or provider_readback["start_time"] != booking.get("start_at") or provider_readback["end_time"] != booking.get("end_at") or provider_readback["status"] != "confirmed" or provider_readback["visibility"] != "private":
raise ValueError("calendar completion requires matching normalized readback")
if sorted(provider_readback["attendee_fingerprints"]) != sorted({transaction["requester_fingerprint"], transaction["owner_fingerprint"]}):
raise ValueError("calendar attendees do not match requester and configured owner")
zoom = connection.execute("SELECT * FROM provider_operations WHERE transaction_id=? AND provider='zoom' AND action='create_event'", (transaction_id,)).fetchone()
if zoom is None or zoom["state"] != OperationState.COMPLETED or not zoom["provider_id"]:
raise ValueError("zoom must be verified before calendar completion")
zoom_evidence = json.loads(zoom["provider_evidence_json"] or "{}")
if not zoom_evidence.get("join_url_digest") or zoom_evidence["join_url_digest"] not in provider_readback["join_url_candidates"]:
raise ValueError("calendar join URL does not match verified zoom meeting")
connection.execute(
"UPDATE provider_operations SET state=?, provider_id=COALESCE(?, provider_id), provider_evidence_json=COALESCE(?, provider_evidence_json), updated_at=? WHERE operation_key=?",
(state, provider_id, json.dumps(provider_readback, sort_keys=True) if provider_readback else None, now, operation_key),
)
return connection.execute("SELECT * FROM provider_operations WHERE operation_key=?", (operation_key,)).fetchone()
def record_booking_evidence(self, transaction_id: str, lease_token: str, evidence: dict[str, str], now: datetime | None = None) -> None:
now = now or self._now()
required = {"availability_evidence_id", "observed_at", "slot_id", "start_at", "end_at"}
if set(evidence) != required or not all(evidence.values()):
raise ValueError("booking availability evidence is incomplete")
with self._session() as connection:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
self._require_lease_row(row, lease_token, now)
if row["state"] != "booking_pending":
raise ValueError("availability can be confirmed only for a selected slot")
connection.execute("UPDATE transactions SET booking_evidence_json=?, updated_at=? WHERE id=?", (json.dumps(evidence, sort_keys=True), now.isoformat(), transaction_id))
def operations_needing_reconciliation(self) -> list[sqlite3.Row]:
with self._session() as connection:
return connection.execute(
"SELECT * FROM provider_operations WHERE state IN (?, ?, ?) ORDER BY updated_at", (OperationState.PENDING, OperationState.DISPATCHING, OperationState.UNCERTAIN)
).fetchall()
+345
View File
@@ -0,0 +1,345 @@
"""Minimal MCP-compatible JSON-RPC stdio adapter; no external MCP package required."""
from __future__ import annotations
import json
import os
import hashlib
import re
import sys
from datetime import UTC, datetime, timedelta
from pathlib import Path
from .ledger import Ledger, OperationState
from .policy import PolicyConfig, evaluate_intent, load_policy_config
from .postmark import BoundMessage, PostmarkAdapter, PostmarkClient, PostmarkHttpsClient, ProviderDisabled
from .message_templates import render_message
from .workflow import SchedulingWorkflow
from .gmail_validation import validate_authenticated_outbound_reply, validate_owner_forward_boundary, validate_owner_sent_forward_provenance
TOOL_DEFINITIONS = (
{"name": "create_pending_negotiation", "description": "Record one validated received-alias or explicitly bound owner-sent-forward negotiation before any slot is selected.", "inputSchema": {"type": "object", "properties": {"transaction_id":{"type":"string"},"sender":{"type":"string"},"expires_at":{"type":"string"},"intake_evidence":{"type":"object"}}, "required":["transaction_id","sender","expires_at","intake_evidence"], "additionalProperties":False}},
{"name": "claim_transaction", "description": "Acquire a short exclusive lease for one existing transaction.", "inputSchema": {"type": "object", "properties": {"transaction_id": {"type": "string"}, "lease_seconds": {"type": "integer", "minimum": 1, "maximum": 300}}, "required": ["transaction_id"], "additionalProperties": False}},
{"name":"begin_offer_round","description":"Persist exactly policy-valid offered slot intervals with fresh sanitized availability.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"},"slots":{"type":"array","items":{"type":"object"}},"busy_intervals":{"type":"array","items":{"type":"object"}},"observed_at":{"type":"string"},"gmail_thread_id":{"type":"string"}},"required":["transaction_id","lease_token","slots","busy_intervals","observed_at","gmail_thread_id"],"additionalProperties":False}},
{"name":"begin_clarification_round","description":"Create a reply-bound clarification round without a slot or booking.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"},"gmail_thread_id":{"type":"string"}},"required":["transaction_id","lease_token","gmail_thread_id"],"additionalProperties":False}},
{"name":"get_active_round_binding","description":"Return the lease-scoped opaque token and server-generated RFC reply anchor for the one active offer round.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"}},"required":["transaction_id","lease_token"],"additionalProperties":False}},
{"name":"accept_offer_selection","description":"Accept only a bound exact offered slot and authenticated requester reply with durable RFC lineage; never books.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"},"slot_id":{"type":"string"},"transaction_token":{"type":"string"},"reply_evidence":{"type":"object"}},"required":["transaction_id","lease_token","slot_id","transaction_token","reply_evidence"],"additionalProperties":False}},
{"name":"record_bound_reply","description":"Record a bound authenticated requester alternative or need-for-clarification with durable RFC lineage.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"},"reply_kind":{"type":"string","enum":["alternative","clarification"]},"transaction_token":{"type":"string"},"reply_evidence":{"type":"object"}},"required":["transaction_id","lease_token","reply_kind","transaction_token","reply_evidence"],"additionalProperties":False}},
{"name": "prepare_postmark_send", "description": "Execute one server-rendered, transaction-bound Postmark template only when the runtime send gate is explicitly enabled. No caller-provided subject or body is accepted.", "inputSchema": {"type": "object", "properties": {"transaction_id": {"type": "string"}, "lease_token":{"type":"string"}, "operation_key": {"type": "string"}, "sender": {"type": "string"}, "requester": {"type": "string"}, "purpose": {"type": "string", "enum": ["offer", "clarification", "alternative", "confirmation", "owner_summary", "terminal"]}, "reason":{"type":"string", "enum":["missing_preference","ambiguous_selection","availability_changed","expired","capacity_exhausted","availability_unresolved","manual_review"]}}, "required": ["transaction_id", "lease_token", "operation_key", "sender", "requester", "purpose"], "additionalProperties": False}},
{"name": "reserve_calendar_event", "description": "Persist one fenced Calendar event operation before a cloud Calendar call. Never calls Calendar.", "inputSchema": {"type": "object", "properties": {"transaction_id": {"type": "string"}, "lease_token":{"type":"string"}, "operation_key": {"type": "string"}}, "required": ["transaction_id", "lease_token", "operation_key"], "additionalProperties": False}},
{"name": "reserve_zoom_meeting", "description": "Persist one fenced Zoom operation before a cloud Zoom call. Never calls Zoom.", "inputSchema": {"type": "object", "properties": {"transaction_id": {"type": "string"}, "lease_token":{"type":"string"}, "operation_key": {"type": "string"}}, "required": ["transaction_id", "lease_token", "operation_key"], "additionalProperties": False}},
{"name":"confirm_booking_availability","description":"Record fresh complete availability for the selected durable slot before any booking reservation.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"},"availability_evidence_id":{"type":"string"},"observed_at":{"type":"string"},"busy_intervals":{"type":"array","items":{"type":"object"}}},"required":["transaction_id","lease_token","availability_evidence_id","observed_at","busy_intervals"],"additionalProperties":False}},
{"name":"reserve_closing_capacity","description":"Reserve final confirmation and configured owner-summary capacity before booking.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"}},"required":["transaction_id","lease_token"],"additionalProperties":False}},
{"name":"complete_booking","description":"Complete only after confirmed Calendar and Zoom operations.","inputSchema":{"type":"object","properties":{"transaction_id":{"type":"string"},"lease_token":{"type":"string"}},"required":["transaction_id","lease_token"],"additionalProperties":False}},
{"name": "record_provider_outcome", "description": "Record a fenced provider outcome for an existing operation.", "inputSchema": {"type": "object", "properties": {"transaction_id":{"type":"string"},"lease_token":{"type":"string"},"operation_key": {"type": "string"}, "state": {"type": "string", "enum": ["accepted", "completed", "failed", "uncertain"]}, "provider_id": {"type": "string"}, "provider_readback":{"type":"object"}}, "required": ["transaction_id","lease_token","operation_key", "state"], "additionalProperties": False}},
{"name": "get_transaction_status", "description": "Return non-content state needed for restart-safe orchestration of one transaction.", "inputSchema": {"type": "object", "properties": {"transaction_id": {"type": "string"}}, "required": ["transaction_id"], "additionalProperties": False}},
{"name": "list_reconciliation_work", "description": "List only opaque keys for operations requiring reconciliation.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
)
TOOLS = tuple(tool["name"] for tool in TOOL_DEFINITIONS)
def _validate_arguments(name: str, arguments: object) -> dict:
definition = next((tool for tool in TOOL_DEFINITIONS if tool["name"] == name), None)
if definition is None or not isinstance(arguments, dict):
raise ValueError("unknown tool or invalid arguments")
schema = definition["inputSchema"]
properties = schema["properties"]
if any(key not in properties for key in arguments) or any(key not in arguments for key in schema.get("required", ())):
raise ValueError("arguments do not match the narrow tool contract")
for key, value in arguments.items():
rule = properties[key]
expected = rule.get("type")
if expected == "string" and not isinstance(value, str):
raise ValueError(f"{key} must be a string")
if expected == "integer" and (not isinstance(value, int) or isinstance(value, bool)):
raise ValueError(f"{key} must be an integer")
if expected == "array" and not isinstance(value, list):
raise ValueError(f"{key} must be an array")
if expected == "object" and not isinstance(value, dict):
raise ValueError(f"{key} must be an object")
if "enum" in rule and value not in rule["enum"]:
raise ValueError(f"{key} is not an allowed value")
if "maxLength" in rule and isinstance(value, str) and len(value) > rule["maxLength"]:
raise ValueError(f"{key} exceeds its maximum length")
if "minimum" in rule and isinstance(value, int) and value < rule["minimum"]:
raise ValueError(f"{key} is below its minimum")
if "maximum" in rule and isinstance(value, int) and value > rule["maximum"]:
raise ValueError(f"{key} exceeds its maximum")
return arguments
def _digest(value: str) -> str:
return hashlib.sha256(value.strip().casefold().encode("utf-8")).hexdigest()
def _opaque_digest(value: str) -> str:
"""Hash immutable provider identifiers without normalizing their semantics."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def _validated_reply_evidence(value: object, policy: PolicyConfig, expected_rfc_message_id: str) -> tuple[str, str, str]:
"""Validate transient Gmail reply evidence and return digested replay keys.
The cloud connector establishes mailbox provenance; this local check binds
the authenticated requester/alias/RFC lineage without persisting raw Gmail
IDs, thread IDs, or headers.
"""
required = {"account_email", "message_id", "thread_id", "label", "headers", "authenticated_mailbox", "intake_label_present"}
text_fields = {"account_email", "message_id", "thread_id", "label"}
if not isinstance(value, dict) or set(value) != required or not all(isinstance(value[key], str) and value[key].strip() for key in text_fields) or not isinstance(value["headers"], list) or value["authenticated_mailbox"] is not True or value["intake_label_present"] is not True:
raise ValueError("connector reply evidence is incomplete")
if value["account_email"].casefold() != policy.owner_email.casefold() or value["label"] != policy.intake_label:
raise ValueError("reply owner account or label is not canonical")
headers = []
for item in value["headers"]:
if not isinstance(item, dict) or set(item) != {"name", "value"} or not isinstance(item["name"], str) or not isinstance(item["value"], str):
raise ValueError("connector reply headers are malformed")
headers.append((item["name"], item["value"]))
sender = validate_authenticated_outbound_reply(headers, delivery_alias=policy.delivery_alias, expected_rfc_message_id=expected_rfc_message_id, authenticated_mailbox=True, intake_label_present=True)
return sender, _opaque_digest(value["message_id"]), _opaque_digest(value["thread_id"])
def _normalize_provider_readback(provider: str, provider_id: str, readback: object) -> dict:
"""Validate raw cloud readback transiently and return safe hashes/digests only."""
if not isinstance(readback, dict):
raise ValueError("provider completion requires structured readback")
if provider == "zoom":
required = {"meeting_id", "join_url", "start_time", "duration_minutes", "timezone", "host"}
if set(readback) != required or not all(readback.values()) or not isinstance(readback["duration_minutes"], int):
raise ValueError("zoom readback fields are incomplete")
if str(readback["meeting_id"]) != provider_id or not str(readback["join_url"]).startswith("https://"):
raise ValueError("zoom readback does not match accepted meeting")
return {"meeting_id": provider_id, "join_url_digest": _digest(str(readback["join_url"])), "start_time": str(readback["start_time"]), "duration_minutes": readback["duration_minutes"], "timezone": str(readback["timezone"]), "host_fingerprint": _digest(str(readback["host"]))}
if provider == "calendar":
required = {"event_id", "start_time", "end_time", "attendees", "status", "visibility", "location", "description", "guests_can_modify"}
if set(readback) != required or str(readback["event_id"]) != provider_id or not isinstance(readback["attendees"], list) or not all(isinstance(email, str) and email for email in readback["attendees"]):
raise ValueError("calendar readback fields are incomplete")
if readback["status"] != "confirmed" or readback["visibility"] != "private":
raise ValueError("calendar must be private and confirmed")
# Calendar can omit guestsCanModify even when false was requested. It is
# therefore recorded as an observation, never used as completion proof.
if readback["guests_can_modify"] not in {False, None}:
raise ValueError("calendar guests_can_modify must be false or unavailable")
return {"event_id": provider_id, "start_time": str(readback["start_time"]), "end_time": str(readback["end_time"]), "attendee_fingerprints": sorted(_digest(email) for email in readback["attendees"]), "status": "confirmed", "visibility": "private", "join_url_candidates": [_digest(url) for url in re.findall(r"https://[^\s<>]+", str(readback["location"]) + "\n" + str(readback["description"]))], "guests_can_modify": readback["guests_can_modify"]}
raise ValueError("provider readback is not supported")
class Adapter:
def __init__(self, ledger: Ledger, policy: PolicyConfig, postmark_client: PostmarkClient | None = None, supervised_send_scope: dict | None = None) -> None:
self.ledger, self.policy, self.postmark_client = ledger, policy, postmark_client
if supervised_send_scope is not None:
if set(supervised_send_scope) != {"transaction_id", "requester", "owner"} or not all(isinstance(v, str) and v.strip() for v in supervised_send_scope.values()):
raise ValueError("supervised send scope is incomplete")
if supervised_send_scope["owner"].casefold() != policy.owner_email.casefold():
raise ValueError("supervised summary recipient must be the configured owner")
self.supervised_send_scope = supervised_send_scope
def call(self, name: str, arguments: dict) -> dict:
arguments = _validate_arguments(name, arguments)
if name == "prepare_postmark_send" and self.supervised_send_scope is not None:
scope = self.supervised_send_scope
recipient = scope["owner"] if arguments["purpose"] == "owner_summary" else scope["requester"]
if arguments["transaction_id"] != scope["transaction_id"] or arguments["requester"].casefold() != recipient.casefold():
raise ValueError("send is outside the approved supervised transaction or recipients")
workflow = SchedulingWorkflow(self.ledger)
if name == "create_pending_negotiation":
if arguments["sender"].casefold() != self.policy.fixed_sender.casefold():
raise ValueError("sender does not match fixed scheduling identity")
evidence = arguments["intake_evidence"]
common = {"provenance_mode", "account_email", "message_id", "thread_id", "label", "headers", "forwarded_requester", "forwarded_recipient", "authentication_evidence_id", "authenticated_mailbox", "intake_label_present"}
sent_forward = common | {"original_message_id", "original_thread_id", "original_rfc_message_id", "original_headers", "original_received", "original_authentication_evidence_id"}
if evidence.get("provenance_mode") == "received_alias":
required = common
elif evidence.get("provenance_mode") == "owner_sent_forward":
required = sent_forward
else:
raise ValueError("intake provenance mode is not supported")
if set(evidence) != required or not all(evidence[key] for key in required if key not in {"headers", "original_headers", "authenticated_mailbox", "intake_label_present", "original_received"}) or not isinstance(evidence["headers"], list) or evidence["authenticated_mailbox"] is not True or evidence["intake_label_present"] is not True:
raise ValueError("connector intake evidence is incomplete")
if evidence["account_email"].casefold() != self.policy.owner_email.casefold() or evidence["label"] != self.policy.intake_label or evidence["forwarded_recipient"].casefold() != self.policy.owner_email.casefold():
raise ValueError("owner account, label, or forwarded linkage is not canonical")
headers = []
for item in evidence["headers"]:
if not isinstance(item, dict) or set(item) != {"name", "value"} or not isinstance(item["name"], str) or not isinstance(item["value"], str):
raise ValueError("connector headers are malformed")
headers.append((item["name"], item["value"]))
if any(name.casefold() in {"auto-submitted", "x-autoreply", "x-autorespond"} and value.strip().casefold() not in {"", "no"} for name, value in headers):
raise ValueError("automated mail cannot create scheduling authority")
# These are connector assertions, not independently authenticated local facts.
validate_owner_forward_boundary(headers, self.policy.owner_email, self.policy.delivery_alias, authenticated_mailbox=evidence["authenticated_mailbox"], intake_label_present=evidence["intake_label_present"])
if evidence["provenance_mode"] == "owner_sent_forward":
if evidence["original_received"] is not True or evidence["original_thread_id"] != evidence["thread_id"] or evidence["original_message_id"] == evidence["message_id"] or evidence["original_authentication_evidence_id"] != evidence["authentication_evidence_id"] or not isinstance(evidence["original_headers"], list):
raise ValueError("owner sent forward provenance is incomplete or unbound")
original_headers = []
for item in evidence["original_headers"]:
if not isinstance(item, dict) or set(item) != {"name", "value"} or not isinstance(item["name"], str) or not isinstance(item["value"], str):
raise ValueError("original connector headers are malformed")
original_headers.append((item["name"], item["value"]))
validate_owner_sent_forward_provenance(forward_headers=headers, original_headers=original_headers, owner_address=self.policy.owner_email, requester_address=evidence["forwarded_requester"], original_rfc_message_id=evidence["original_rfc_message_id"])
expiry = datetime.fromisoformat(arguments["expires_at"].replace("Z", "+00:00"))
message_ids = (evidence["message_id"],) if evidence["provenance_mode"] == "received_alias" else (evidence["message_id"], evidence["original_message_id"])
audit_values = {"mode": evidence["provenance_mode"], "message_ids": message_ids, "thread_id": evidence["thread_id"], "authentication_evidence_id": evidence["authentication_evidence_id"]}
if evidence["provenance_mode"] == "owner_sent_forward":
audit_values["original_rfc_message_id"] = evidence["original_rfc_message_id"]
return {"transaction_id": self.ledger.create_pending_negotiation(transaction_id=arguments["transaction_id"], requester=evidence["forwarded_requester"], sender=arguments["sender"], owner=self.policy.owner_email, authentication_evidence_id=evidence["authentication_evidence_id"], gmail_thread_id=evidence["thread_id"], policy_revision=self.policy.revision, default_duration_minutes=self.policy.default_duration_minutes, max_exchanges=self.policy.max_exchange_messages, expires_at=expiry, intake_message_digests=tuple(_opaque_digest(value) for value in message_ids), intake_audit_digest=_opaque_digest(json.dumps(audit_values, sort_keys=True, separators=(",", ":"))))}
if name == "claim_transaction":
claim = self.ledger.claim(arguments["transaction_id"], int(arguments.get("lease_seconds", 60)))
return {} if claim is None else claim.__dict__
if name == "begin_offer_round":
now = datetime.now(UTC)
observed = datetime.fromisoformat(arguments["observed_at"].replace("Z", "+00:00"))
if observed.tzinfo is None or observed.astimezone(UTC) < now - timedelta(minutes=5) or observed.astimezone(UTC) > now + timedelta(minutes=1):
raise ValueError("availability observation is not fresh")
slots = arguments["slots"]
if len(slots) != self.policy.offer_count:
raise ValueError("offer has incorrect number of slots")
durable_slots = []
for slot in slots:
if set(slot) != {"slot_id", "intent"} or not isinstance(slot["slot_id"], str):
raise ValueError("offer slot shape is invalid")
intent = evaluate_intent(slot["intent"], self.policy, now, arguments["busy_intervals"])
if intent.transaction_id != arguments["transaction_id"]:
raise ValueError("offer slot belongs to another transaction")
durable_slots.append({"slot_id": slot["slot_id"], "start_at": intent.start_at, "end_at": intent.end_at, "expires_at": intent.expires_at, "availability_evidence_id": intent.availability_evidence_id, "authentication_evidence_id": intent.authentication_evidence_id})
result=workflow.begin_round(arguments["transaction_id"],durable_slots,min(datetime.fromisoformat(slot["expires_at"].replace("Z", "+00:00")) for slot in durable_slots),_opaque_digest(arguments["gmail_thread_id"]), now, arguments["lease_token"])
return result
if name == "begin_clarification_round":
return workflow.begin_clarification_round(arguments["transaction_id"], arguments["gmail_thread_id"], lease_token=arguments["lease_token"])
if name == "get_active_round_binding":
return workflow.active_round_binding(arguments["transaction_id"], arguments["lease_token"])
if name == "accept_offer_selection":
binding = workflow.active_round_binding(arguments["transaction_id"], arguments["lease_token"])
sender, reply_message_digest, reply_thread_digest = _validated_reply_evidence(arguments["reply_evidence"], self.policy, binding["outbound_rfc_message_id"])
self.ledger.require_bound_requester(arguments["transaction_id"], sender)
result = workflow.accept_selection_and_record_inbound(arguments["transaction_id"],slot_id=arguments["slot_id"],transaction_token=arguments["transaction_token"],in_reply_to=binding["outbound_rfc_message_id"],reply_message_id=reply_message_digest,reply_thread_digest=reply_thread_digest,references=[binding["outbound_rfc_message_id"]], lease_token=arguments["lease_token"])
return {"slot_id": result}
if name == "record_bound_reply":
binding = workflow.active_round_binding(arguments["transaction_id"], arguments["lease_token"])
sender, reply_message_digest, reply_thread_digest = _validated_reply_evidence(arguments["reply_evidence"], self.policy, binding["outbound_rfc_message_id"])
self.ledger.require_bound_requester(arguments["transaction_id"], sender)
workflow.register_bound_reply_and_record_inbound(arguments["transaction_id"], reply_message_id=reply_message_digest, reply_kind=arguments["reply_kind"], transaction_token=arguments["transaction_token"], in_reply_to=binding["outbound_rfc_message_id"], reply_thread_digest=reply_thread_digest, references=[binding["outbound_rfc_message_id"]], lease_token=arguments["lease_token"])
return {"status": "recorded"}
if name == "prepare_postmark_send":
if self.postmark_client is None:
return {"status": "disabled", "reason": "Postmark runtime send gate is disabled"}
state = self.ledger.transaction_status(arguments["transaction_id"])["state"]
self.ledger.require_lease(arguments["transaction_id"], arguments["lease_token"])
allowed_states = {"offer": {"awaiting_requester"}, "alternative": {"awaiting_requester"}, "clarification": {"awaiting_requester", "clarification_required"}, "confirmation": {"completed"}, "owner_summary": {"completed"}, "terminal": {"review_required", "expired"}}
if state not in allowed_states[arguments["purpose"]]:
raise ValueError("message purpose is not permitted in the transaction state")
recipient = arguments["requester"]
if arguments["purpose"] == "owner_summary":
if not self.policy.owner_email or recipient.casefold() != self.policy.owner_email.casefold():
raise ValueError("owner summary recipient must be the configured owner")
try:
purpose = arguments["purpose"]
slots = workflow.active_slots(arguments["transaction_id"]) if purpose == "offer" else ()
selected = workflow.selected_slot(arguments["transaction_id"]) if purpose in {"confirmation", "owner_summary"} else None
message = render_message(purpose, slots=slots, selected_slot=selected, reason=arguments.get("reason"))
on_reserved = (lambda rfc_message_id: workflow.bind_active_outbound_rfc(arguments["transaction_id"], rfc_message_id, arguments["lease_token"])) if purpose in {"offer", "clarification"} else None
provider_id = PostmarkAdapter(self.ledger, self.postmark_client).send_bound_message(arguments["transaction_id"], arguments["lease_token"], arguments["operation_key"], arguments["sender"], recipient, message, purpose=purpose, closing=purpose in {"confirmation", "owner_summary"}, on_reserved=on_reserved)
result = {"status": "uncertain" if provider_id is None else "accepted", "provider_id": provider_id}
if purpose in {"offer", "clarification"}:
result["outbound_rfc_message_id"] = self.ledger.operation_for_key(arguments["operation_key"])["rfc_message_id"]
return result
except ProviderDisabled as error:
return {"status": "disabled", "reason": str(error)}
if name == "reserve_calendar_event":
self.ledger.require_lease(arguments["transaction_id"], arguments["lease_token"])
row = self.ledger.reserve_booking_operation(arguments["transaction_id"], arguments["lease_token"], arguments["operation_key"], "calendar")
return {"state": row["state"], "operation_key": row["operation_key"]}
if name == "reserve_zoom_meeting":
self.ledger.require_lease(arguments["transaction_id"], arguments["lease_token"])
row = self.ledger.reserve_booking_operation(arguments["transaction_id"], arguments["lease_token"], arguments["operation_key"], "zoom")
return {"state": row["state"], "operation_key": row["operation_key"]}
if name == "confirm_booking_availability":
self.ledger.require_lease(arguments["transaction_id"], arguments["lease_token"])
slot = workflow.selected_slot(arguments["transaction_id"])
now = datetime.now(UTC)
observed = datetime.fromisoformat(arguments["observed_at"].replace("Z", "+00:00"))
if observed.tzinfo is None or observed.astimezone(UTC) < now - timedelta(minutes=5) or observed.astimezone(UTC) > now + timedelta(minutes=1):
raise ValueError("availability observation is not fresh")
raw = {"transaction_id":arguments["transaction_id"], "requester":"opaque-bound-requester", "sender":self.policy.fixed_sender, "start_at":slot["start_at"], "end_at":slot["end_at"], "expires_at":slot["expires_at"], "authentication_evidence_id":slot["authentication_evidence_id"], "availability_evidence_id":arguments["availability_evidence_id"]}
evaluate_intent(raw, self.policy, now, arguments["busy_intervals"])
self.ledger.record_booking_evidence(arguments["transaction_id"], arguments["lease_token"], {"availability_evidence_id":arguments["availability_evidence_id"], "observed_at":observed.astimezone(UTC).isoformat(), "slot_id":slot["slot_id"], "start_at":slot["start_at"], "end_at":slot["end_at"]}, now)
return {"status":"fresh"}
if name == "reserve_closing_capacity":
self.ledger.reserve_closing_capacity(arguments["transaction_id"], arguments["lease_token"])
return {"status":"reserved", "slots":2}
if name == "complete_booking":
self.ledger.require_lease(arguments["transaction_id"], arguments["lease_token"])
workflow.require_booking_confirmed(arguments["transaction_id"], arguments["lease_token"])
return {"status":"completed"}
if name == "record_provider_outcome":
operation = self.ledger.operation_for_key(arguments["operation_key"])
if operation is None:
raise KeyError("unknown operation")
readback = arguments.get("provider_readback")
if arguments["state"] == "completed" and operation["provider"] in {"calendar", "zoom"}:
if not arguments.get("provider_id"):
raise ValueError("provider completion requires a provider id")
readback = _normalize_provider_readback(operation["provider"], arguments["provider_id"], readback)
row = self.ledger.transition_operation(arguments["transaction_id"], arguments["lease_token"], arguments["operation_key"], OperationState(arguments["state"]), arguments.get("provider_id"), readback)
return {"state": row["state"], "provider_id": row["provider_id"]}
if name == "list_reconciliation_work":
return {"operations": [{"operation_key": row["operation_key"], "provider": row["provider"], "action": row["action"], "provider_id": row["provider_id"]} for row in self.ledger.operations_needing_reconciliation()]}
if name == "get_transaction_status":
row = self.ledger.transaction_status(arguments["transaction_id"])
return {"transaction_id": row["id"], "state": row["state"], "expires_at": row["expires_at"], "exchange_count": row["exchange_count"], "max_exchanges": row["max_exchanges"], "lease_expires_at": row["lease_expires_at"]}
raise ValueError("unknown or disallowed tool")
def handle_request(self, request: dict) -> dict:
"""Small JSON-RPC subset suitable for MCP tool discovery and calls in tests."""
request_id = request.get("id")
try:
if request["method"] == "initialize":
result = {"protocolVersion": "2025-06-18", "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": "petra-scheduling-local", "version": "0.1.0"}, "instructions": "Use only these scheduling ledger tools. Never infer permission for email, Calendar, Zoom, or arbitrary commands."}
elif request["method"] == "tools/list":
result = {"tools": list(TOOL_DEFINITIONS)}
elif request["method"] == "tools/call":
params = request["params"]
result = {"content": [{"type": "text", "text": json.dumps(self.call(params["name"], params.get("arguments", {})))}]}
elif request["method"].startswith("notifications/"):
return {}
elif request["method"] == "ping":
result = {}
else:
raise ValueError("method is not supported")
return {"jsonrpc": "2.0", "id": request_id, "result": result}
except (KeyError, ValueError) as error:
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": -32602, "message": str(error)}}
def main() -> None:
if os.environ.get("SCHEDULING_MCP_ENABLE") != "1":
raise RuntimeError("MCP runtime is disabled pending authenticated transport provisioning")
sender = os.environ.get("SCHEDULING_FIXED_SENDER")
if not sender:
raise RuntimeError("SCHEDULING_FIXED_SENDER is required")
root = Path(__file__).resolve().parents[2]
policy = load_policy_config(root / "config" / "scheduling-policy.json", sender)
database = Path(os.environ.get("SCHEDULING_DB", root / "state" / "scheduling-ledger.sqlite3"))
client = None
if os.environ.get("SCHEDULING_POSTMARK_ENABLE") == "1":
token = os.environ.get("POSTMARK_SERVER_TOKEN", "")
if not token:
raise RuntimeError("Postmark runtime gate requires a protected token")
client = PostmarkHttpsClient(secret_provider=lambda: token, enabled=True)
scope = json.loads(os.environ["SCHEDULING_SUPERVISED_SEND_SCOPE"]) if "SCHEDULING_SUPERVISED_SEND_SCOPE" in os.environ else None
ledger = Ledger(database)
SchedulingWorkflow(ledger)
adapter = Adapter(ledger, policy, client, supervised_send_scope=scope)
for line in sys.stdin:
try:
request = json.loads(line)
response = adapter.handle_request(request)
if not response:
continue
except (ValueError, TypeError, json.JSONDecodeError) as error:
response = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(error)}}
sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
"""Deterministic, non-free-form messages for the scheduling lifecycle."""
from __future__ import annotations
from datetime import datetime
from .postmark import BoundMessage
CLARIFICATION_REASONS = {"missing_preference", "ambiguous_selection", "availability_changed"}
TERMINAL_REASONS = {"expired", "capacity_exhausted", "availability_unresolved", "manual_review"}
PETRA_SIGNATURE = "\n\n— Petra Scheduling"
def _interval(slot: dict) -> str:
start = datetime.fromisoformat(slot["start_at"].replace("Z", "+00:00"))
end = datetime.fromisoformat(slot["end_at"].replace("Z", "+00:00"))
return f"{start.isoformat()} to {end.isoformat()}"
def render_message(purpose: str, *, slots: tuple[dict, ...] = (), selected_slot: dict | None = None, reason: str | None = None) -> BoundMessage:
"""Render only durable scheduling data and a small allow-listed reason enum."""
if purpose == "offer":
if not slots:
raise ValueError("offer template requires durable offered slots")
body = "Reply with one offered slot ID:\n" + "\n".join(f"- {slot['slot_id']}: {_interval(slot)}" for slot in slots) + PETRA_SIGNATURE
return BoundMessage("Scheduling options", body)
if purpose == "alternative":
return BoundMessage("Scheduling alternatives", "Your requested alternative was recorded. We will send eligible options if available." + PETRA_SIGNATURE)
if purpose == "clarification":
if reason not in CLARIFICATION_REASONS:
raise ValueError("clarification reason is not allow-listed")
return BoundMessage("Scheduling clarification", f"Scheduling needs clarification: {reason.replace('_', ' ')}. Please reply in this thread." + PETRA_SIGNATURE)
if purpose == "confirmation":
if selected_slot is None:
raise ValueError("confirmation template requires a selected slot")
return BoundMessage("Scheduling confirmed", f"Your meeting is confirmed for {_interval(selected_slot)}." + PETRA_SIGNATURE)
if purpose == "owner_summary":
if selected_slot is None:
raise ValueError("owner summary template requires a selected slot")
return BoundMessage("Scheduling booking summary", f"A scheduling booking was confirmed for {_interval(selected_slot)}." + PETRA_SIGNATURE)
if purpose == "terminal":
if reason not in TERMINAL_REASONS:
raise ValueError("terminal reason is not allow-listed")
return BoundMessage("Scheduling update", f"This scheduling request is closed: {reason.replace('_', ' ')}." + PETRA_SIGNATURE)
raise ValueError("message purpose is not allow-listed")
+118
View File
@@ -0,0 +1,118 @@
"""Pure validation for evidence produced by Petra's cloud connectors.
No connector client is included here. Cloud code must sanitize provider responses
to this contract before calling the narrow local MCP tools.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Iterable
from .gmail_validation import SanitizedGmailMetadata, validate_intake, validate_reply_lineage
class EvidenceError(ValueError):
pass
def _timestamp(value: str) -> datetime:
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as error:
raise EvidenceError("evidence timestamp is invalid") from error
if parsed.tzinfo is None:
raise EvidenceError("evidence timestamp requires an offset")
return parsed.astimezone(UTC)
@dataclass(frozen=True)
class CalendarEvidence:
evidence_id: str
observed_at: str
window_start: str
window_end: str
busy_intervals: tuple[dict[str, str], ...]
def require_fresh_after(self, not_before: datetime) -> None:
observed, start, end = (_timestamp(value) for value in (self.observed_at, self.window_start, self.window_end))
if not self.evidence_id or observed < not_before.astimezone(UTC) or end <= start:
raise EvidenceError("calendar evidence is missing, stale, or has an invalid window")
for interval in self.busy_intervals:
if set(interval) != {"start_at", "end_at"}:
raise EvidenceError("calendar busy interval is invalid")
if _timestamp(interval["end_at"]) <= _timestamp(interval["start_at"]):
raise EvidenceError("calendar busy interval is invalid")
def validate_calendar_availability_response(*, requested_calendar_ids: Iterable[str], requested_start: str, requested_end: str, request_started_at: datetime, response_received_at: datetime, calendars: Iterable[dict]) -> tuple[dict[str, str], ...]:
"""Validate the observed connector shape; missing/error calendars are unknown."""
start, end = _timestamp(requested_start), _timestamp(requested_end)
if end <= start or response_received_at.astimezone(UTC) < request_started_at.astimezone(UTC):
raise EvidenceError("calendar availability request timing is invalid")
expected = tuple(requested_calendar_ids)
values = list(calendars)
if len(expected) != len(set(expected)) or len(values) != len(expected):
raise EvidenceError("calendar coverage is incomplete")
by_id = {item.get("calendar_id"): item for item in values if isinstance(item, dict)}
if set(by_id) != set(expected) or any(item.get("errors") for item in values):
raise EvidenceError("calendar availability is unknown")
intervals: list[dict[str, str]] = []
for item in values:
for busy in item.get("busy", []):
if not isinstance(busy, dict) or set(busy) != {"start_at", "end_at"} or _timestamp(busy["end_at"]) <= _timestamp(busy["start_at"]):
raise EvidenceError("calendar busy interval is invalid")
intervals.append(busy)
return tuple(intervals)
@dataclass(frozen=True)
class ProviderConfirmation:
provider: str
transaction_id: str
operation_key: str
provider_id: str
observed_at: str
def validate(self) -> None:
if self.provider not in {"calendar", "zoom", "postmark"} or not all((self.transaction_id, self.operation_key, self.provider_id)):
raise EvidenceError("provider confirmation is incomplete")
_timestamp(self.observed_at)
def validate_authenticated_intake(
metadata: SanitizedGmailMetadata,
*,
authenticated: bool,
expected_sender: str,
route: str,
intake_label: str,
) -> SanitizedGmailMetadata:
if not authenticated:
raise EvidenceError("Gmail authentication evidence is insufficient")
return validate_intake(metadata, expected_sender, route, intake_label)
def validate_bound_reply(
metadata: SanitizedGmailMetadata,
*,
authenticated: bool,
bound_requester: str,
route: str,
intake_label: str,
outbound_rfc_message_id: str,
transaction_token: str,
) -> SanitizedGmailMetadata:
if not authenticated:
raise EvidenceError("Gmail authentication evidence is insufficient")
return validate_reply_lineage(metadata, bound_requester, route, intake_label, outbound_rfc_message_id, transaction_token)
def require_confirmations(confirmations: Iterable[ProviderConfirmation], transaction_id: str) -> dict[str, ProviderConfirmation]:
values = {value.provider: value for value in confirmations}
for provider in ("calendar", "zoom"):
value = values.get(provider)
if value is None or value.transaction_id != transaction_id:
raise EvidenceError(f"{provider} confirmation is required before completion")
value.validate()
return values
+147
View File
@@ -0,0 +1,147 @@
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Iterable
from zoneinfo import ZoneInfo
from pathlib import Path
class PolicyViolation(ValueError):
pass
def _parse_time(value: str) -> datetime:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
raise PolicyViolation("timestamps must include an offset")
return parsed.astimezone(UTC)
def _fingerprint(value: str) -> str:
return hashlib.sha256(value.strip().casefold().encode("utf-8")).hexdigest()
@dataclass(frozen=True)
class PolicyConfig:
revision: str
fixed_sender: str
owner_email: str = ""
intake_label: str = "Scheduling/Intake"
delivery_alias: str = ""
timezone: str = "UTC"
minimum_notice_minutes: int = 24 * 60
buffer_minutes: int = 15
max_exchange_messages: int = 8
allowed_duration_minutes: tuple[int, ...] = (15, 30, 45, 60, 90, 120)
maximum_booking_days: int = 21
offer_count: int = 3
offer_expiration_hours: int = 72
default_duration_minutes: int = 60
buffer_before_minutes: int = 15
buffer_after_minutes: int = 15
workday_start_hour: int = 9
workday_end_hour: int = 16
guests_can_invite_others: bool = True
def __post_init__(self) -> None:
if not self.revision or not self.fixed_sender:
raise PolicyViolation("policy revision and fixed sender are required")
ZoneInfo(self.timezone)
if min(self.minimum_notice_minutes, self.buffer_minutes, self.buffer_before_minutes, self.buffer_after_minutes, self.max_exchange_messages, self.maximum_booking_days, self.offer_count, self.offer_expiration_hours, self.default_duration_minutes) < 0:
raise PolicyViolation("policy limits cannot be negative")
if not self.allowed_duration_minutes or any(value <= 0 for value in self.allowed_duration_minutes):
raise PolicyViolation("allowed durations must be positive")
@dataclass(frozen=True)
class ValidatedIntent:
transaction_id: str
requester: str
sender: str
start_at: str
end_at: str
expires_at: str
authentication_evidence_id: str
availability_evidence_id: str
intent_digest: str
@property
def requester_fingerprint(self) -> str:
return _fingerprint(self.requester)
def digest_normalized_intent(value: dict[str, object]) -> str:
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()
def evaluate_intent(raw: dict[str, object], config: PolicyConfig, now: datetime, busy_intervals: Iterable[dict[str, str]]) -> ValidatedIntent:
"""Evaluate deterministic constraints; external source provenance remains trusted evidence."""
required = {"transaction_id", "requester", "sender", "start_at", "end_at", "expires_at", "authentication_evidence_id", "availability_evidence_id"}
if set(raw) != required:
raise PolicyViolation("intent fields do not match the narrow contract")
if not all(isinstance(raw[field], str) and raw[field].strip() for field in required):
raise PolicyViolation("intent fields must be non-empty strings")
if raw["sender"].strip().casefold() != config.fixed_sender.strip().casefold():
raise PolicyViolation("sender does not match fixed scheduling identity")
start, end, expiry = (_parse_time(raw[name]) for name in ("start_at", "end_at", "expires_at"))
now = now.astimezone(UTC)
duration = end - start
if duration <= timedelta() or duration.total_seconds() / 60 not in config.allowed_duration_minutes:
raise PolicyViolation("duration is not an allowed value")
if start < now + timedelta(minutes=config.minimum_notice_minutes):
raise PolicyViolation("meeting does not meet minimum notice")
if expiry <= now or expiry > now + timedelta(hours=config.offer_expiration_hours):
raise PolicyViolation("offer is expired or exceeds expiration window")
if start > now + timedelta(days=config.maximum_booking_days):
raise PolicyViolation("meeting exceeds booking horizon")
local_start, local_end = start.astimezone(ZoneInfo(config.timezone)), end.astimezone(ZoneInfo(config.timezone))
if local_start.date() != local_end.date() or local_start.weekday() > 4:
raise PolicyViolation("meeting crosses a local-date boundary")
if local_start.hour < config.workday_start_hour or (local_end.hour, local_end.minute) > (config.workday_end_hour, 0):
raise PolicyViolation("meeting is outside work window")
buffered_start = start - timedelta(minutes=config.buffer_before_minutes)
buffered_end = end + timedelta(minutes=config.buffer_after_minutes)
for busy in busy_intervals:
if set(busy) != {"start_at", "end_at"}:
raise PolicyViolation("busy interval fields are invalid")
busy_start, busy_end = _parse_time(busy["start_at"]), _parse_time(busy["end_at"])
if busy_end <= busy_start or (buffered_start < busy_end and busy_start < buffered_end):
raise PolicyViolation("meeting conflicts with buffered availability")
normalized = {name: raw[name].strip() for name in sorted(required)}
return ValidatedIntent(
transaction_id=normalized["transaction_id"], requester=normalized["requester"], sender=normalized["sender"],
start_at=normalized["start_at"], end_at=normalized["end_at"], expires_at=normalized["expires_at"],
authentication_evidence_id=normalized["authentication_evidence_id"], availability_evidence_id=normalized["availability_evidence_id"],
intent_digest=digest_normalized_intent(normalized),
)
def validate_offer_slots(slots: Iterable[dict[str, object]], config: PolicyConfig, now: datetime, busy_intervals: Iterable[dict[str, str]]) -> tuple[ValidatedIntent, ...]:
values = list(slots)
if len(values) != config.offer_count:
raise PolicyViolation("offer has incorrect number of slots")
evaluated = tuple(evaluate_intent(value, config, now, busy_intervals) for value in values)
if len({item.start_at for item in evaluated}) != len(evaluated):
raise PolicyViolation("offer slots must be distinct")
return evaluated
def load_policy_config(path: str | Path, fixed_sender: str) -> PolicyConfig:
"""Load only reviewed non-secret deterministic values from the project policy file."""
source = json.loads(Path(path).read_text(encoding="utf-8"))
meeting, limits = source["meeting"], source["limits"]
return PolicyConfig(
revision=source["policy_version"], fixed_sender=fixed_sender, timezone=source["timezone"], owner_email=source.get("owner_email", ""), intake_label=meeting.get("intake_label", "Scheduling/Intake"), delivery_alias=meeting.get("delivery_alias", ""),
minimum_notice_minutes=int(meeting["minimum_notice_hours"]) * 60,
buffer_minutes=int(meeting["buffer_before_minutes"]),
buffer_before_minutes=int(meeting["buffer_before_minutes"]), buffer_after_minutes=int(meeting["buffer_after_minutes"]),
default_duration_minutes=int(meeting["default_duration_minutes"]), max_exchange_messages=int(limits["maximum_exchange_messages"]),
allowed_duration_minutes=tuple(int(value) for value in meeting["allowed_duration_minutes"]),
maximum_booking_days=int(meeting["maximum_booking_days"]), offer_count=int(meeting["offer_count"]),
offer_expiration_hours=int(meeting["offer_expiration_hours"]),
workday_start_hour=int(meeting["workday_start"].split(":")[0]), workday_end_hour=int(meeting["workday_end"].split(":")[0]),
guests_can_invite_others=bool(meeting["guests_can_invite_others"]),
)
+98
View File
@@ -0,0 +1,98 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Protocol
import json
import urllib.error
import urllib.request
from .ledger import Ledger, OperationState
class PostmarkClient(Protocol):
def send(self, *, sender: str, recipient: str, operation_key: str, subject: str, text_body: str, reply_to: str, rfc_message_id: str) -> str: ...
class ProviderDisabled(RuntimeError):
pass
SecretProvider = Callable[[], str]
@dataclass(frozen=True)
class BoundMessage:
"""Message content produced by the deterministic scheduling workflow, not an MCP input."""
subject: str
text_body: str
def __post_init__(self) -> None:
if not self.subject or not self.text_body or len(self.subject) > 200 or len(self.text_body) > 10_000:
raise ValueError("bound message is empty or exceeds narrow limits")
if "\r" in self.subject or "\n" in self.subject:
raise ValueError("subject cannot contain line breaks")
@dataclass
class PostmarkHttpsClient:
"""Disabled-by-default HTTPS transport; token is obtained only at call time."""
secret_provider: SecretProvider
enabled: bool = False
endpoint: str = "https://api.postmarkapp.com/email"
def _request(self, url: str, payload: dict | None = None) -> dict:
if not self.enabled:
raise ProviderDisabled("Postmark HTTPS transport is disabled")
token = self.secret_provider()
if not isinstance(token, str) or not token:
raise ProviderDisabled("Postmark token is unavailable")
data = None if payload is None else json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url,
data=data,
headers={
"Accept": "application/json",
"X-Postmark-Server-Token": token,
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request, timeout=15) as response: # nosec: enabled only after approval
return json.loads(response.read())
def send(self, *, sender: str, recipient: str, operation_key: str, subject: str, text_body: str, reply_to: str, rfc_message_id: str) -> str:
response = self._request(self.endpoint, {"From": sender, "To": recipient, "ReplyTo": reply_to, "Subject": subject, "TextBody": text_body, "Headers": [{"Name": "Message-ID", "Value": rfc_message_id}], "Tag": operation_key, "MessageStream": "outbound"})
return str(response["MessageID"])
def status(self, provider_id: str) -> dict:
return self._request(f"https://api.postmarkapp.com/messages/outbound/{provider_id}/details")
@dataclass
class PostmarkAdapter:
ledger: Ledger
client: PostmarkClient | None = None
def send_bound_message(self, transaction_id: str, lease_token: str, operation_key: str, sender: str, requester: str, message: BoundMessage, purpose: str = "offer", closing: bool = False, on_reserved: Callable[[str], None] | None = None) -> str | None:
if self.client is None:
raise ProviderDisabled("Postmark is disabled until a reviewed credentialed adapter is provisioned")
operation = self.ledger.record_postmark_send(transaction_id, lease_token, operation_key, sender, requester, purpose=purpose, closing=closing)
if on_reserved is not None:
on_reserved(operation["rfc_message_id"])
if operation["state"] in {OperationState.ACCEPTED, OperationState.COMPLETED}:
return operation["provider_id"]
if operation["state"] in {OperationState.PENDING, OperationState.DISPATCHING, OperationState.UNCERTAIN} and operation["state"] != OperationState.PENDING:
return None
self.ledger.transition_operation(transaction_id, lease_token, operation_key, OperationState.DISPATCHING)
try:
provider_id = self.client.send(sender=sender, recipient=requester, operation_key=operation_key, subject=message.subject, text_body=message.text_body, reply_to=sender, rfc_message_id=operation["rfc_message_id"])
except TimeoutError:
self.ledger.transition_operation(transaction_id, lease_token, operation_key, OperationState.UNCERTAIN)
return None
except urllib.error.HTTPError:
self.ledger.transition_operation(transaction_id, lease_token, operation_key, OperationState.FAILED)
raise
except Exception:
# We cannot know whether a non-HTTP transport failure reached the provider.
self.ledger.transition_operation(transaction_id, lease_token, operation_key, OperationState.UNCERTAIN)
raise
return self.ledger.transition_operation(transaction_id, lease_token, operation_key, OperationState.ACCEPTED, provider_id)["provider_id"]
+26
View File
@@ -0,0 +1,26 @@
"""Deterministic offer and counteroffer validation over sanitized free/busy data."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
from .policy import PolicyConfig, PolicyViolation, evaluate_intent
def compliant_slots(*, transaction_id: str, requester: str, sender: str, authentication_evidence_id: str, availability_evidence_id: str, now: datetime, busy_intervals: list[dict[str,str]], config: PolicyConfig) -> tuple[dict[str,str], ...]:
tz=ZoneInfo(config.timezone); cursor=(now.astimezone(tz)+timedelta(minutes=config.minimum_notice_minutes)).replace(minute=0,second=0,microsecond=0)
if cursor.minute: cursor += timedelta(hours=1)
slots=[]
deadline=now.astimezone(tz)+timedelta(days=config.maximum_booking_days)
while cursor <= deadline and len(slots)<config.offer_count:
end=cursor+timedelta(minutes=config.default_duration_minutes)
if cursor.weekday()<5 and cursor.hour>=config.workday_start_hour and (end.hour,end.minute)<=(config.workday_end_hour,0):
raw={"transaction_id":transaction_id,"requester":requester,"sender":sender,"start_at":cursor.astimezone(UTC).isoformat(),"end_at":end.astimezone(UTC).isoformat(),"expires_at":(now+timedelta(hours=config.offer_expiration_hours)).isoformat(),"authentication_evidence_id":authentication_evidence_id,"availability_evidence_id":availability_evidence_id}
try:
evaluate_intent(raw,config,now,busy_intervals); slots.append({"slot_id":f"slot-{len(slots)+1}","start_at":raw["start_at"],"end_at":raw["end_at"]})
except PolicyViolation: pass
cursor += timedelta(minutes=15)
if len(slots)!=config.offer_count: raise PolicyViolation("insufficient compliant availability")
return tuple(slots)
def validate_counteroffer(candidate: dict[str,str], **kwargs):
raw={key:value for key,value in kwargs.items() if key not in {"config","now","busy_intervals"}}
raw.update(candidate)
return evaluate_intent(raw, kwargs["config"], kwargs["now"], kwargs["busy_intervals"])
+240
View File
@@ -0,0 +1,240 @@
"""Fail-closed local lifecycle for already-sanitized scheduling evidence.
This module never reads Gmail/Calendar/Zoom or renders/sends arbitrary mail.
"""
from __future__ import annotations
import json
import secrets
from datetime import UTC, datetime
from typing import Iterable
from .ledger import Ledger, OperationState
class WorkflowError(ValueError):
pass
class SchedulingWorkflow:
def __init__(self, ledger: Ledger) -> None:
self.ledger = ledger
with ledger._session() as connection:
connection.executescript(
"""
CREATE TABLE IF NOT EXISTS workflow_rounds (
transaction_id TEXT NOT NULL REFERENCES transactions(id),
round_number INTEGER NOT NULL,
state TEXT NOT NULL,
slot_ids_json TEXT NOT NULL,
expires_at TEXT NOT NULL,
transaction_token TEXT NOT NULL,
gmail_thread_id TEXT NOT NULL,
outbound_rfc_message_id TEXT NOT NULL DEFAULT '',
selected_slot_id TEXT,
PRIMARY KEY (transaction_id, round_number)
);
"""
)
columns = {row["name"] for row in connection.execute("PRAGMA table_info(workflow_rounds)")}
if "outbound_rfc_message_id" not in columns:
connection.execute("ALTER TABLE workflow_rounds ADD COLUMN outbound_rfc_message_id TEXT NOT NULL DEFAULT ''")
def begin_round(self, transaction_id: str, slot_ids: Iterable[object], expires_at: datetime, gmail_thread_id: str, now: datetime | None = None, lease_token: str | None = None) -> dict:
now = now or datetime.now(UTC)
slots = tuple(slot_ids)
ids = tuple(slot["slot_id"] if isinstance(slot, dict) else slot for slot in slots)
if not slots or len(set(ids)) != len(ids) or not all(ids) or not gmail_thread_id or expires_at.tzinfo is None or expires_at <= now:
raise WorkflowError("offer round is incomplete")
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
if lease_token is not None: self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
transaction = connection.execute("SELECT state FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if transaction is None or transaction["state"] in {"completed", "expired", "review_required"}:
raise WorkflowError("transaction cannot accept an offer round")
active = connection.execute("SELECT 1 FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester'", (transaction_id,)).fetchone()
if active:
raise WorkflowError("transaction already awaits a requester")
number = connection.execute("SELECT COALESCE(MAX(round_number), 0) + 1 AS number FROM workflow_rounds WHERE transaction_id=?", (transaction_id,)).fetchone()["number"]
token = secrets.token_urlsafe(18)
connection.execute("INSERT INTO workflow_rounds (transaction_id, round_number, state, slot_ids_json, expires_at, transaction_token, gmail_thread_id) VALUES (?, ?, 'awaiting_requester', ?, ?, ?, ?)", (transaction_id, number, json.dumps(slots), expires_at.astimezone(UTC).isoformat(), token, gmail_thread_id))
connection.execute("UPDATE transactions SET state='awaiting_requester', updated_at=? WHERE id=?", (now.isoformat(), transaction_id))
return {"round_number": number, "transaction_token": token, "slot_ids": ids}
def bind_active_outbound_rfc(self, transaction_id: str, rfc_message_id: str, lease_token: str) -> None:
if not rfc_message_id:
raise WorkflowError("outbound RFC message id is required")
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token)
row = connection.execute("SELECT round_number, outbound_rfc_message_id FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None or (row["outbound_rfc_message_id"] and row["outbound_rfc_message_id"] != rfc_message_id):
raise WorkflowError("outbound RFC message cannot be bound")
connection.execute("UPDATE workflow_rounds SET outbound_rfc_message_id=? WHERE transaction_id=? AND round_number=?", (rfc_message_id, transaction_id, row["round_number"]))
def bind_outbound(self, transaction_id: str, round_number: int, rfc_message_id: str, lease_token: str | None = None) -> None:
"""Test/internal helper; MCP never accepts caller-selected outbound IDs."""
if not rfc_message_id:
raise WorkflowError("outbound RFC message id is required")
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
if lease_token is not None:
self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token)
changed = connection.execute("UPDATE workflow_rounds SET outbound_rfc_message_id=? WHERE transaction_id=? AND round_number=? AND state='awaiting_requester' AND outbound_rfc_message_id=''", (rfc_message_id, transaction_id, round_number)).rowcount
if not changed:
raise WorkflowError("outbound RFC message cannot be bound")
def active_round_binding(self, transaction_id: str, lease_token: str) -> dict:
now = datetime.now(UTC)
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
row = connection.execute("SELECT r.round_number, r.transaction_token, r.outbound_rfc_message_id, r.expires_at AS round_expires_at, t.expires_at AS transaction_expires_at FROM workflow_rounds r JOIN transactions t ON t.id=r.transaction_id WHERE r.transaction_id=? AND r.state='awaiting_requester' ORDER BY r.round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None or not row["outbound_rfc_message_id"] or datetime.fromisoformat(row["round_expires_at"]) <= now or datetime.fromisoformat(row["transaction_expires_at"]) <= now:
raise WorkflowError("active round lacks a verified outbound RFC message-id mapping")
return {"round_number": row["round_number"], "transaction_token": row["transaction_token"], "outbound_rfc_message_id": row["outbound_rfc_message_id"]}
def begin_clarification_round(self, transaction_id: str, gmail_thread_id: str, now: datetime | None = None, lease_token: str | None = None) -> dict:
"""Create a reply-bound clarification round without inventing a time slot."""
now = now or datetime.now(UTC)
if not gmail_thread_id:
raise WorkflowError("clarification thread is required")
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
if lease_token is not None: self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
transaction = connection.execute("SELECT state, expires_at FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if transaction is None or transaction["state"] != "received" or datetime.fromisoformat(transaction["expires_at"]) <= now.astimezone(UTC):
raise WorkflowError("transaction cannot request clarification")
number = connection.execute("SELECT COALESCE(MAX(round_number), 0) + 1 AS number FROM workflow_rounds WHERE transaction_id=?", (transaction_id,)).fetchone()["number"]
token = secrets.token_urlsafe(18)
connection.execute("INSERT INTO workflow_rounds (transaction_id, round_number, state, slot_ids_json, expires_at, transaction_token, gmail_thread_id) VALUES (?, ?, 'awaiting_requester', '[]', ?, ?, ?)", (transaction_id, number, transaction["expires_at"], token, gmail_thread_id))
connection.execute("UPDATE transactions SET state='awaiting_requester', updated_at=? WHERE id=?", (now.isoformat(), transaction_id))
return {"round_number": number, "transaction_token": token, "slot_ids": ()}
def accept_selection(self, transaction_id: str, *, slot_id: str, transaction_token: str, in_reply_to: str, references: Iterable[str], thread_id: str | None = None, now: datetime | None = None, lease_token: str | None = None) -> str:
now = now or datetime.now(UTC)
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
if lease_token is not None: self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
row = connection.execute("SELECT * FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None or datetime.fromisoformat(row["expires_at"]) <= now.astimezone(UTC):
if row is not None:
connection.execute("UPDATE workflow_rounds SET state='expired' WHERE transaction_id=? AND round_number=?", (transaction_id, row["round_number"]))
connection.execute("UPDATE transactions SET state='expired', updated_at=? WHERE id=?", (now.isoformat(), transaction_id))
raise WorkflowError("offer is unavailable or expired")
slots = tuple(json.loads(row["slot_ids_json"]))
ids = {slot["slot_id"] if isinstance(slot, dict) else slot for slot in slots}
if slot_id not in ids or transaction_token != row["transaction_token"] or not row["outbound_rfc_message_id"] or in_reply_to != row["outbound_rfc_message_id"] or in_reply_to not in set(references):
raise WorkflowError("selection is not bound to the active offer")
connection.execute("UPDATE workflow_rounds SET state='selected', selected_slot_id=? WHERE transaction_id=? AND round_number=?", (slot_id, transaction_id, row["round_number"]))
connection.execute("UPDATE transactions SET state='booking_pending', updated_at=? WHERE id=?", (now.isoformat(), transaction_id))
return slot_id
def accept_selection_and_record_inbound(self, transaction_id: str, *, slot_id: str, transaction_token: str, in_reply_to: str, reply_message_id: str, reply_thread_digest: str, references: Iterable[str], lease_token: str, now: datetime | None = None) -> str:
"""Atomically consume a bound requester reply and select its offered slot."""
now = now or datetime.now(UTC)
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
if not reply_message_id:
raise WorkflowError("inbound message id is required")
existing = connection.execute("SELECT 1 FROM exchange_messages WHERE transaction_id=? AND message_key=?", (transaction_id, reply_message_id)).fetchone()
if not existing and transaction["exchange_count"] >= transaction["max_exchanges"] - transaction["closing_reserve"]:
raise WorkflowError("exchange cap reached")
row = connection.execute("SELECT * FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None or datetime.fromisoformat(row["expires_at"]) <= now.astimezone(UTC):
raise WorkflowError("offer is unavailable or expired")
slots = tuple(json.loads(row["slot_ids_json"]))
ids = {slot["slot_id"] if isinstance(slot, dict) else slot for slot in slots}
if slot_id not in ids or transaction_token != row["transaction_token"] or not row["outbound_rfc_message_id"] or in_reply_to != row["outbound_rfc_message_id"] or in_reply_to not in set(references):
raise WorkflowError("selection is not bound to the active offer")
binding = connection.execute("SELECT transaction_id FROM reply_message_bindings WHERE message_digest=?", (reply_message_id,)).fetchone()
if binding is not None and binding["transaction_id"] != transaction_id:
raise WorkflowError("reply Gmail message id is already bound to another transaction")
if binding is None:
connection.execute("INSERT INTO reply_message_bindings (message_digest, transaction_id, thread_digest, created_at) VALUES (?, ?, ?, ?)", (reply_message_id, transaction_id, reply_thread_digest, now.isoformat()))
connection.execute("UPDATE workflow_rounds SET state='selected', selected_slot_id=? WHERE transaction_id=? AND round_number=?", (slot_id, transaction_id, row["round_number"]))
connection.execute("UPDATE transactions SET state='booking_pending', exchange_count=exchange_count+?, updated_at=? WHERE id=?", (0 if existing else 1, now.isoformat(), transaction_id))
if not existing:
connection.execute("INSERT INTO exchange_messages (transaction_id,message_key,direction,created_at) VALUES (?,?,'inbound',?)", (transaction_id, reply_message_id, now.isoformat()))
return slot_id
def register_bound_reply_and_record_inbound(self, transaction_id: str, *, reply_message_id: str, reply_kind: str, transaction_token: str, in_reply_to: str, reply_thread_digest: str, references: Iterable[str], lease_token: str, now: datetime | None = None) -> None:
now = now or datetime.now(UTC)
if reply_kind not in {"alternative", "clarification"} or not reply_message_id:
raise WorkflowError("reply kind or inbound message id is invalid")
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
transaction = connection.execute("SELECT * FROM transactions WHERE id=?", (transaction_id,)).fetchone()
existing = connection.execute("SELECT 1 FROM exchange_messages WHERE transaction_id=? AND message_key=?", (transaction_id, reply_message_id)).fetchone()
if not existing and transaction["exchange_count"] >= transaction["max_exchanges"] - transaction["closing_reserve"]:
raise WorkflowError("exchange cap reached")
row = connection.execute("SELECT * FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None or datetime.fromisoformat(row["expires_at"]) <= now.astimezone(UTC) or transaction_token != row["transaction_token"] or not row["outbound_rfc_message_id"] or in_reply_to != row["outbound_rfc_message_id"] or in_reply_to not in set(references):
raise WorkflowError("reply is not bound to the active offer")
binding = connection.execute("SELECT transaction_id FROM reply_message_bindings WHERE message_digest=?", (reply_message_id,)).fetchone()
if binding is not None and binding["transaction_id"] != transaction_id:
raise WorkflowError("reply Gmail message id is already bound to another transaction")
if binding is None:
connection.execute("INSERT INTO reply_message_bindings (message_digest, transaction_id, thread_digest, created_at) VALUES (?, ?, ?, ?)", (reply_message_id, transaction_id, reply_thread_digest, now.isoformat()))
connection.execute("UPDATE workflow_rounds SET state=? WHERE transaction_id=? AND round_number=?", (reply_kind, transaction_id, row["round_number"]))
state = "received" if reply_kind == "alternative" else "clarification_required"
connection.execute("UPDATE transactions SET state=?, exchange_count=exchange_count+?, updated_at=? WHERE id=?", (state, 0 if existing else 1, now.isoformat(), transaction_id))
if not existing:
connection.execute("INSERT INTO exchange_messages (transaction_id,message_key,direction,created_at) VALUES (?,?,'inbound',?)", (transaction_id, reply_message_id, now.isoformat()))
def register_bound_reply(self, transaction_id: str, *, reply_kind: str, transaction_token: str, in_reply_to: str, references: Iterable[str], now: datetime | None = None, lease_token: str | None = None) -> None:
"""Advance only a reply that is bound to the active outbound offer."""
if reply_kind not in {"alternative", "clarification"}:
raise WorkflowError("reply kind is not supported")
now = now or datetime.now(UTC)
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
if lease_token is not None: self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token, now)
row = connection.execute("SELECT * FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None or datetime.fromisoformat(row["expires_at"]) <= now.astimezone(UTC) or transaction_token != row["transaction_token"] or not row["outbound_rfc_message_id"] or in_reply_to != row["outbound_rfc_message_id"] or in_reply_to not in set(references):
raise WorkflowError("reply is not bound to the active offer")
connection.execute("UPDATE workflow_rounds SET state=? WHERE transaction_id=? AND round_number=?", (reply_kind, transaction_id, row["round_number"]))
state = "received" if reply_kind == "alternative" else "clarification_required"
connection.execute("UPDATE transactions SET state=?, updated_at=? WHERE id=?", (state, now.isoformat(), transaction_id))
def selected_slot(self, transaction_id: str) -> dict[str, str]:
with self.ledger._session() as connection:
row = connection.execute("SELECT slot_ids_json, selected_slot_id FROM workflow_rounds WHERE transaction_id=? AND state='selected' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None:
raise WorkflowError("no selected offer slot")
for slot in json.loads(row["slot_ids_json"]):
if isinstance(slot, dict) and slot.get("slot_id") == row["selected_slot_id"]:
return slot
raise WorkflowError("selected slot has no durable interval")
def active_slots(self, transaction_id: str) -> tuple[dict, ...]:
"""Return the durable slots in the only reply-eligible round."""
with self.ledger._session() as connection:
row = connection.execute("SELECT slot_ids_json FROM workflow_rounds WHERE transaction_id=? AND state='awaiting_requester' ORDER BY round_number DESC LIMIT 1", (transaction_id,)).fetchone()
if row is None:
raise WorkflowError("no active offer round")
slots = tuple(json.loads(row["slot_ids_json"]))
if not slots or not all(isinstance(slot, dict) and {"slot_id", "start_at", "end_at"} <= set(slot) for slot in slots):
raise WorkflowError("active round has no offered intervals")
return slots
def require_booking_confirmed(self, transaction_id: str, lease_token: str | None = None) -> None:
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
if lease_token is not None: self.ledger.require_lease_in_transaction(connection, transaction_id, lease_token)
transaction = connection.execute("SELECT state FROM transactions WHERE id=?", (transaction_id,)).fetchone()
operations = connection.execute("SELECT provider, state, provider_id FROM provider_operations WHERE transaction_id=? AND provider IN ('calendar','zoom') AND action='create_event'", (transaction_id,)).fetchall()
complete = {row["provider"]: row for row in operations if row["state"] == OperationState.COMPLETED and row["provider_id"]}
if transaction is None or transaction["state"] != "booking_pending" or set(complete) != {"calendar", "zoom"}:
raise WorkflowError("calendar and zoom confirmations are required")
connection.execute("UPDATE transactions SET state='completed', updated_at=? WHERE id=?", (datetime.now(UTC).isoformat(), transaction_id))
def request_clarification(self, transaction_id: str) -> None:
with self.ledger._session() as connection:
connection.execute("BEGIN IMMEDIATE")
changed = connection.execute("UPDATE transactions SET state='clarification_required', updated_at=? WHERE id=? AND state IN ('received','awaiting_requester')", (datetime.now(UTC).isoformat(), transaction_id)).rowcount
if not changed:
raise WorkflowError("clarification is not available")