added
This commit is contained in:
commit
4608e60d8d
84 files changed
+4337
No files matched your search
+28
@@ -0,0 +1,28 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
state/
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
*.log
|
||||||
|
logs/
|
||||||
|
*.csv
|
||||||
|
*.jsonl
|
||||||
|
*.sql
|
||||||
|
*.dump
|
||||||
|
*.bak
|
||||||
|
*.backup
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.pfx
|
||||||
|
*.p12
|
||||||
|
id_rsa*
|
||||||
|
id_ed25519*
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# AI Agent Instructions
|
||||||
|
|
||||||
|
## Read order
|
||||||
|
|
||||||
|
1. `README.md`
|
||||||
|
2. `AUTHOR.md`
|
||||||
|
3. `repository-variables.json`
|
||||||
|
4. `repository.json`
|
||||||
|
5. `content-index.json` when locating a document
|
||||||
|
6. `skills.md`
|
||||||
|
7. The relevant skill or documentation
|
||||||
|
|
||||||
|
## Project boundaries
|
||||||
|
|
||||||
|
- Treat the repository as an experimental reference implementation, not a live scheduler or a production deployment.
|
||||||
|
- Preserve synthetic example values. Keep real addresses, credentials, provider IDs, account settings, and operational records out of source control.
|
||||||
|
- Do not run scripts that send messages, access provider accounts, or change local services unless the user explicitly requests that action and the exact scope is clear.
|
||||||
|
- Before adapting provider code, inspect its side effects and failure handling. Unknown external outcomes require reconciliation, not a blind retry.
|
||||||
|
- Do not alter the private source repository when working from this public copy.
|
||||||
|
- Keep repository metadata, attribution, citation, license, version, and changelog aligned.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Author, Publisher, and Maintainer
|
||||||
|
|
||||||
|
## Primary author
|
||||||
|
|
||||||
|
**Eddie Soehnel**
|
||||||
|
|
||||||
|
## Publisher and maintainer
|
||||||
|
|
||||||
|
**Eddie Soehnel**
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
```text
|
||||||
|
AI Calendar Scheduling Toolkit by Eddie Soehnel
|
||||||
|
```
|
||||||
|
|
||||||
|
## Canonical repository
|
||||||
|
|
||||||
|
Not set yet. The hosting URL has not been confirmed for this public repository.
|
||||||
|
|
||||||
|
## Reuse and adaptation
|
||||||
|
|
||||||
|
This repository is licensed under the MIT License. Preserve the copyright and license notice when redistributing the software. See [LICENSE](LICENSE).
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 0.1.0 — 2026-10-06
|
||||||
|
|
||||||
|
- Prepared the initial sanitized public repository baseline.
|
||||||
|
- Added human and AI entrypoints, machine-readable repository metadata, and a content index.
|
||||||
|
- Generalized operational guidance and removed private provider evidence and hard-coded account details.
|
||||||
|
- Added public-safe script gates and excluded local state and secret artifacts.
|
||||||
|
|
||||||
|
This is a repository baseline on a review branch; no hosted release has been created.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
cff-version: 1.2.0
|
||||||
|
message: "If you use this software, please cite it using this metadata."
|
||||||
|
title: "AI Calendar Scheduling Toolkit"
|
||||||
|
type: software
|
||||||
|
version: 0.1.0
|
||||||
|
authors:
|
||||||
|
- family-names: "Soehnel"
|
||||||
|
given-names: "Eddie"
|
||||||
|
license: MIT
|
||||||
|
keywords:
|
||||||
|
- artificial intelligence
|
||||||
|
- calendar scheduling
|
||||||
|
- Python
|
||||||
|
- workflow automation
|
||||||
|
- scheduling policy
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Contributing
|
||||||
|
|
||||||
|
Contributions should keep examples synthetic, preserve the fail-closed workflow principles, and describe any provider-specific behavior accurately.
|
||||||
|
|
||||||
|
Before opening a change:
|
||||||
|
|
||||||
|
1. Explain the problem and the intended behavior.
|
||||||
|
2. Keep account data, credentials, private endpoints, and real provider identifiers out of the change.
|
||||||
|
3. Review scripts for external side effects and require explicit configuration for any send or write operation.
|
||||||
|
4. Update the README, machine-readable metadata, content index, changelog, and version when applicable.
|
||||||
|
5. Run the relevant project checks in an isolated environment and report the exact commands and results.
|
||||||
|
|
||||||
|
Do not include private vulnerability details in a public issue. See [SECURITY.md](SECURITY.md).
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Eddie Soehnel
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# AI Calendar Scheduling Toolkit
|
||||||
|
|
||||||
|
A Python prototype for AI-assisted calendar scheduling workflows. It combines scheduling policy, time-slot selection, orchestration, a durable SQLite ledger, provider-oriented helpers, a local MCP interface, and synthetic fixtures.
|
||||||
|
|
||||||
|
This repository is a reference implementation. It is not a hosted scheduler, does not include a live account connection, and does not automatically authorize calendar or email changes. Some optional scripts can contact external services when deliberately enabled and supplied with credentials. Review them before use and test with accounts and data you control.
|
||||||
|
|
||||||
|
## Start here
|
||||||
|
|
||||||
|
- Setup and safety guidance: this README
|
||||||
|
- AI-agent entrypoint: [AGENTS.md](AGENTS.md)
|
||||||
|
- Repository metadata: [repository.json](repository.json)
|
||||||
|
- Searchable document catalog: [content-index.json](content-index.json)
|
||||||
|
- Scheduling workflow skill: [skills/petra-scheduling-orchestrator/SKILL.md](skills/petra-scheduling-orchestrator/SKILL.md)
|
||||||
|
- Design and policy notes: [docs/](docs/)
|
||||||
|
|
||||||
|
## What is included
|
||||||
|
|
||||||
|
- `src/scheduling_core/`: policy evaluation, slotting, orchestration, provider adapters, and a SQLite-backed operation ledger.
|
||||||
|
- `config/`: a sample scheduling policy with synthetic identities and labels.
|
||||||
|
- `fixtures/` and `tests/`: sample inputs and the project's existing test suite.
|
||||||
|
- `scripts/`: local development helpers and explicitly gated integration examples. Read each script before running it.
|
||||||
|
- `skills/`: an AI workflow guide and its evidence contract.
|
||||||
|
- `archive/`: historical design notes retained for context. Archived procedures are not a deployment guide.
|
||||||
|
|
||||||
|
The connector design notes describe general safeguards and do not report a live or hosted service in this repository.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.11 or newer.
|
||||||
|
- SQLite support from the Python standard library.
|
||||||
|
- Provider credentials only if you intentionally configure an integration example.
|
||||||
|
|
||||||
|
## Local setup
|
||||||
|
|
||||||
|
From the repository root, create an isolated Python environment and install the project:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python -m venv .venv
|
||||||
|
python -m pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
The package requires Python 3.11 or newer. For direct source-tree development, set `PYTHONPATH=src` in your shell; PowerShell users can use `$env:PYTHONPATH = "src"`.
|
||||||
|
|
||||||
|
Copy and adapt `config/scheduling-policy.json` for your own use. Replace every `example.test` address, sample label, timezone, and placeholder with values for an account you control. Store credentials outside the repository. Never commit secrets, account exports, calendar data, or a live SQLite ledger.
|
||||||
|
|
||||||
|
## Safety boundaries
|
||||||
|
|
||||||
|
- The sample configuration is not connected to any real account.
|
||||||
|
- Scripts named `send-*` or `send_*` can cause external effects if configured and explicitly run. Their environment-variable gates are not a substitute for reviewing the target account, recipient, content, and operation scope.
|
||||||
|
- Do not use archived local-tunnel or token-management procedures as production setup instructions.
|
||||||
|
- Unknown results from an external write require manual reconciliation; do not repeat an action merely because a response is missing.
|
||||||
|
- This prototype has not been independently security-reviewed or declared production-ready.
|
||||||
|
|
||||||
|
## License and attribution
|
||||||
|
|
||||||
|
The repository is provided under the MIT License. See [LICENSE](LICENSE) and [AUTHOR.md](AUTHOR.md).
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Check repository structure and metadata with:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python scripts/audit_repository.py --profile software-automation --json .
|
||||||
|
```
|
||||||
|
|
||||||
|
Run the existing unit suite in an isolated environment with:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m unittest discover -s tests -p "test_*.py"
|
||||||
|
```
|
||||||
|
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# Security and privacy
|
||||||
|
|
||||||
|
This prototype handles workflows that may involve private messages, calendars, and provider credentials. It has not been independently security-reviewed and must not be assumed production-ready.
|
||||||
|
|
||||||
|
- Never commit passwords, API keys, access tokens, private keys, session data, account exports, message bodies, or live calendar records.
|
||||||
|
- Keep credentials in an approved external secret manager or protected process environment. Do not paste secrets into issues, examples, or logs.
|
||||||
|
- Use synthetic fixtures and isolated test accounts. Review each script before running it; some examples can cause external effects after explicit configuration.
|
||||||
|
- Treat uncertain provider writes as reconciliation work. Do not automatically retry sends or event creation.
|
||||||
|
|
||||||
|
For a vulnerability, use the private reporting mechanism offered by the repository host. Do not publish exploit details in a public issue. No dedicated security contact is configured in this repository.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Proposed updates
|
||||||
|
|
||||||
|
These are future ideas, not approved implementation work:
|
||||||
|
|
||||||
|
- Add provider sandbox walkthroughs using synthetic accounts and test data.
|
||||||
|
- Document cross-platform setup and recovery exercises.
|
||||||
|
- Review whether archived examples should be further reduced after community feedback.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Archived local prototype material
|
||||||
|
|
||||||
|
This directory contains historical reference material for an earlier local scheduling prototype. It is retained to preserve design context; it is not a supported deployment path or an instruction to run archived scripts.
|
||||||
|
|
||||||
|
The earlier prototype explored a local operation ledger, an MCP interface, provider adapters, and explicit send gates. The reusable policy ideas are summarized in [the current design notes](../docs/README.md). Host-specific details, credentials, account data, and live service endpoints do not belong in this public repository.
|
||||||
|
|
||||||
|
Before adapting any archived code, review its dependencies, side effects, error handling, and provider assumptions. Use synthetic data and isolated test accounts. Do not copy secrets or operational identifiers into issues, pull requests, or examples.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Archived design notes
|
||||||
|
|
||||||
|
These files preserve historical technical context for the local prototype. They may contain obsolete assumptions and must not be used as operational instructions. Current reusable guidance is in `docs/`.
|
||||||
|
|
||||||
|
Review each note before adapting it. Replace example identities and settings with synthetic values, keep credentials out of source control, and verify every provider operation in an isolated environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: gmail-canonical-comparison
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: legacy-local-mcp-archive
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: live-connector-evidence
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: policy-coverage
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: postmark-secret-handoff
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: release-checklist
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: rule-coverage
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: task-scheduler
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: task-summary-2026-10-03-legacy
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: transport-decision
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Historical reference: tunnel-handoff
|
||||||
|
|
||||||
|
This document is retained as historical context for the local scheduling prototype. Its former operational details are intentionally not reproduced in this public copy. It is not a current runbook and must not be used to access accounts, send messages, create calendar events, or configure a host.
|
||||||
|
|
||||||
|
For reusable design guidance, see [the connector policy](../../../docs/direct-connector-policy.md) and [project status](../../../docs/task-summary-2026-10-03.md). Before adapting archived code, review provider behavior, authorization, privacy, error handling, and external side effects in an isolated test environment.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"policy_version": "0.1.0-example",
|
||||||
|
"timezone": "UTC",
|
||||||
|
"owner_email": "[email protected]",
|
||||||
|
"meeting": {
|
||||||
|
"default_duration_minutes": 60,
|
||||||
|
"allowed_duration_minutes": [15, 30, 45, 60, 90, 120],
|
||||||
|
"minimum_notice_hours": 24,
|
||||||
|
"maximum_booking_days": 21,
|
||||||
|
"buffer_before_minutes": 15,
|
||||||
|
"buffer_after_minutes": 15,
|
||||||
|
"offer_count": 3,
|
||||||
|
"offer_expiration_hours": 72,
|
||||||
|
"allowed_weekdays": ["monday", "tuesday", "wednesday", "thursday", "friday"],
|
||||||
|
"workday_start": "09:00",
|
||||||
|
"workday_end": "17:00",
|
||||||
|
"tentative_holds": false,
|
||||||
|
"intake_label": "Scheduling/Intake",
|
||||||
|
"delivery_alias": "[email protected]",
|
||||||
|
"guests_can_invite_others": true
|
||||||
|
},
|
||||||
|
"limits": { "maximum_exchange_messages": 8 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
{
|
||||||
|
"schema_version": "1.0",
|
||||||
|
"collection_id": "ai-calendar-scheduling-documents",
|
||||||
|
"title": "AI Calendar Scheduling Toolkit Documents",
|
||||||
|
"description": "A compact catalog of the public setup, design, policy, and AI workflow documents.",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"items": [
|
||||||
|
{
|
||||||
|
"content_id": "calendar-scheduling-readme",
|
||||||
|
"title": "AI Calendar Scheduling Toolkit README",
|
||||||
|
"description": "Purpose, contents, setup, and safety boundaries.",
|
||||||
|
"content_type": "readme",
|
||||||
|
"path": "README.md",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"status": "draft",
|
||||||
|
"author": "Eddie Soehnel",
|
||||||
|
"topics": ["python", "calendar-scheduling", "ai", "prototype"],
|
||||||
|
"related_content_ids": ["connector-policy", "scheduling-skill"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"content_id": "connector-policy",
|
||||||
|
"title": "Connector Policy",
|
||||||
|
"description": "Generic authority, booking, read-back, and recovery safeguards.",
|
||||||
|
"content_type": "policy-guide",
|
||||||
|
"path": "docs/direct-connector-policy.md",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"status": "draft",
|
||||||
|
"author": "Eddie Soehnel",
|
||||||
|
"topics": ["authorization", "calendar", "email", "recovery"],
|
||||||
|
"related_content_ids": ["connector-transition", "scheduling-skill"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"content_id": "connector-transition",
|
||||||
|
"title": "Connector Transition Notes",
|
||||||
|
"description": "Generic design checklist for adapting a local prototype to provider-native connectors.",
|
||||||
|
"content_type": "design-guide",
|
||||||
|
"path": "docs/direct-connector-cutover.md",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"status": "draft",
|
||||||
|
"author": "Eddie Soehnel",
|
||||||
|
"topics": ["provider-integrations", "architecture", "prototype"],
|
||||||
|
"related_content_ids": ["connector-policy"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"content_id": "project-status",
|
||||||
|
"title": "Project Status and Limitations",
|
||||||
|
"description": "Scope, prototype boundaries, and known validation needs.",
|
||||||
|
"content_type": "status-guide",
|
||||||
|
"path": "docs/task-summary-2026-10-03.md",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"status": "draft",
|
||||||
|
"author": "Eddie Soehnel",
|
||||||
|
"topics": ["limitations", "prototype", "validation"],
|
||||||
|
"related_content_ids": ["connector-transition"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"content_id": "scheduling-skill",
|
||||||
|
"title": "Petra Scheduling Orchestrator",
|
||||||
|
"description": "AI workflow reference for adapting the scheduling core under human authorization.",
|
||||||
|
"content_type": "ai-skill",
|
||||||
|
"path": "skills/petra-scheduling-orchestrator/SKILL.md",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"status": "draft",
|
||||||
|
"author": "Eddie Soehnel",
|
||||||
|
"topics": ["ai", "workflow", "calendar-scheduling", "safety"],
|
||||||
|
"related_content_ids": ["connector-policy"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Scheduling core documentation
|
||||||
|
|
||||||
|
The application source and tests are under `src/scheduling_core/` and `tests/`. This project uses the Python standard library for its core implementation. Provider credentials and account-specific settings are intentionally not supplied.
|
||||||
|
|
||||||
|
See [README.md](../README.md) for setup and safety boundaries, [the connector policy](direct-connector-policy.md) for adaptation guidance, and [the status note](task-summary-2026-10-03.md) for known limitations.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Connector transition notes
|
||||||
|
|
||||||
|
This note is a generic design checklist for teams moving scheduling logic from a local prototype to provider-native connectors. It does not describe a live migration or prove that any provider action has occurred.
|
||||||
|
|
||||||
|
## Before a transition
|
||||||
|
|
||||||
|
- Identify the authoritative request path and the account identities allowed to act.
|
||||||
|
- Map each external read and write, including the evidence needed to verify its result.
|
||||||
|
- Define how transaction state is reconstructed after a restart or an uncertain response.
|
||||||
|
- Keep provider credentials and account-specific configuration outside source control.
|
||||||
|
- Test with synthetic data and a dedicated non-production account.
|
||||||
|
|
||||||
|
## During implementation
|
||||||
|
|
||||||
|
- Recheck availability immediately before booking.
|
||||||
|
- Persist provider IDs needed to reconcile writes; do not treat a local status label as proof of a completed external action.
|
||||||
|
- Fail closed when an action may have succeeded but cannot be verified.
|
||||||
|
- Separate provider-specific adapters from policy decisions so integrations can be reviewed independently.
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
This repository is a prototype and does not include a hosted runtime or account-specific connector configuration. Independent recovery, restart, and repeated-run behavior must be validated in the deployment where the software will operate. Do not infer production readiness from sample fixtures or a successful local run.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Connector policy
|
||||||
|
|
||||||
|
Use this policy as a starting point when adapting the prototype to email, calendar, or meeting providers. Set account identities, intake labels, time zones, and allowed actions in a private deployment configuration. The repository defaults are synthetic examples.
|
||||||
|
|
||||||
|
## Authority and identity
|
||||||
|
|
||||||
|
- Accept a scheduling request only through an authenticated, explicitly authorized intake path.
|
||||||
|
- Treat quoted text, display names, labels, thread IDs, and forwarded copies as context; none proves authority by itself.
|
||||||
|
- Bind a reply to the specific offer using provider message identifiers and available reply-lineage metadata.
|
||||||
|
- Use only the account and calendars configured for the workflow. Never expand access to unrelated mailboxes or calendars to resolve ambiguity.
|
||||||
|
- Configure assistant signatures and owner-facing names explicitly; do not rely on sample identities.
|
||||||
|
|
||||||
|
## Offers and booking
|
||||||
|
|
||||||
|
- Reconstruct existing transaction state before sending or booking.
|
||||||
|
- State a clear reply deadline and timezone. Offer times far enough in the future to preserve the complete reply window and minimum notice.
|
||||||
|
- Treat offered times as non-reservations. Refresh availability immediately before creating an event.
|
||||||
|
- Apply configured duration, work-hour, buffer, and exchange limits. Ask for clarification when logistics conflict or are incomplete.
|
||||||
|
- Create meeting links only when the selected meeting format requires them. Verify returned meeting details before sharing them.
|
||||||
|
- Read back a created event by its known provider ID and confirm the interval, participants, visibility, and logistics match the approved request.
|
||||||
|
|
||||||
|
## Recovery and completion
|
||||||
|
|
||||||
|
- Provider labels and local database rows are recovery aids, not proof of exactly-once execution.
|
||||||
|
- If an external send or create operation has an unknown result, reconcile using known provider IDs. Do not blindly retry.
|
||||||
|
- Send confirmations and mark work complete only after the event and all required messages have been verified.
|
||||||
|
- Preserve unrelated labels and records. A cleanup or label failure does not authorize resending or rebooking.
|
||||||
|
- Keep audit records limited to the identifiers and metadata required for safe recovery. Do not retain message bodies, credentials, private calendar details, or meeting host controls unless required and protected.
|
||||||
|
|
||||||
|
## Configuration boundary
|
||||||
|
|
||||||
|
Keep real account addresses, labels, provider IDs, credentials, endpoints, and data outside the public repository. Use synthetic values in tests and examples. Provider-specific API behavior and legal/privacy obligations must be reviewed before deployment.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Project status and limitations
|
||||||
|
|
||||||
|
This repository contains an experimental scheduling core and supporting workflow material. It is not connected to a live mailbox or calendar, and it does not include a hosted or automatically enabled scheduler.
|
||||||
|
|
||||||
|
The implementation explores policy checks, time-slot selection, request orchestration, provider adapters, and durable operation tracking. The design notes describe safeguards for authorized intake, fresh availability checks, read-back verification, and conservative handling of uncertain external results.
|
||||||
|
|
||||||
|
Known limitations include provider-specific assumptions, incomplete proof of recovery across all failure modes, and the need for deployment-specific security and privacy review. Use synthetic fixtures for development. Any integration with real accounts requires explicit configuration, review, and a controlled test environment.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"unauthenticated_gmail": {"authenticated": false},
|
||||||
|
"stale_calendar": {"observed_at": "2030-12-31T15:59:59Z"},
|
||||||
|
"missing_zoom_confirmation": [{"provider": "calendar", "transaction_id": "simulation-tx", "operation_key": "calendar-create-1", "provider_id": "calendar-event-1", "observed_at": "2030-12-31T16:01:00Z"}]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"now": "2030-12-31T16:00:00Z",
|
||||||
|
"gmail": {"message_id": "inbound-1", "thread_id": "thread-1", "sender": "[email protected]", "delivered_to": "[email protected]", "label": "intake", "authenticated": true},
|
||||||
|
"calendar": {"evidence_id": "calendar-1", "observed_at": "2030-12-31T16:00:00Z", "window_start": "2031-01-01T18:00:00Z", "window_end": "2031-01-01T19:00:00Z", "busy_intervals": []},
|
||||||
|
"intent": {"transaction_id": "simulation-tx", "requester": "[email protected]", "sender": "[email protected]", "start_at": "2031-01-01T18:00:00Z", "end_at": "2031-01-01T19:00:00Z", "expires_at": "2031-01-02T00:00:00Z", "authentication_evidence_id": "gmail-1", "availability_evidence_id": "calendar-1"},
|
||||||
|
"confirmations": [{"provider": "calendar", "transaction_id": "simulation-tx", "operation_key": "calendar-create-1", "provider_id": "calendar-event-1", "observed_at": "2030-12-31T16:01:00Z"}, {"provider": "zoom", "transaction_id": "simulation-tx", "operation_key": "zoom-create-1", "provider_id": "zoom-meeting-1", "observed_at": "2030-12-31T16:01:00Z"}]
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"fixture_scope":"supervised-intake-only","authenticated_mailbox":true,"intake_label_present":true,"gmail_message_id":"1a102fd4a4197dd1","gmail_thread_id":"1a102fcecdc0dcd8","headers":[["From","[email protected]"],["To","[email protected]"]],"forwarded_requester":"[email protected]","forwarded_to":"[email protected]","automated":false,"rfc_lineage_verified":true,"duration_or_slots_supplied":false}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=68"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "ai-calendar-scheduling"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "An experimental policy-driven toolkit for AI-assisted calendar scheduling workflows"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
license = { text = "MIT" }
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
|
|
||||||
|
[tool.unittest]
|
||||||
|
start-directory = "tests"
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"schema_version": "1.0",
|
||||||
|
"purpose": "Verified stable identity, publication, rights, and profile inputs for this repository.",
|
||||||
|
"repository_profile": "software-automation",
|
||||||
|
"identity": {
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Eddie Soehnel"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"publisher": {
|
||||||
|
"name": "Eddie Soehnel"
|
||||||
|
},
|
||||||
|
"maintainer": {
|
||||||
|
"name": "Eddie Soehnel"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"repository_id": "ai-calendar-scheduling-toolkit",
|
||||||
|
"name": "calendar-scheduling-open",
|
||||||
|
"title": "AI Calendar Scheduling Toolkit",
|
||||||
|
"canonical_url": null,
|
||||||
|
"organization": null
|
||||||
|
},
|
||||||
|
"rights": {
|
||||||
|
"license": "MIT",
|
||||||
|
"license_file": "LICENSE"
|
||||||
|
},
|
||||||
|
"skill_defaults": {
|
||||||
|
"task_id": "calendar-scheduling-publication",
|
||||||
|
"require_plan_approval": true,
|
||||||
|
"preserve_existing_content": true,
|
||||||
|
"use_smallest_fitting_profile": true
|
||||||
|
},
|
||||||
|
"verified_by": "User-provided publication decisions",
|
||||||
|
"verified_at": "2026-10-06"
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
{
|
||||||
|
"schema_version": "1.0",
|
||||||
|
"repository_id": "ai-calendar-scheduling-toolkit",
|
||||||
|
"name": "calendar-scheduling-open",
|
||||||
|
"title": "AI Calendar Scheduling Toolkit",
|
||||||
|
"description": "An experimental Python toolkit for policy-driven, AI-assisted calendar scheduling workflows.",
|
||||||
|
"summary": "A downloadable reference implementation combining scheduling policy, slot selection, orchestration, a durable SQLite ledger, provider adapters, synthetic fixtures, and an AI workflow skill. It is not a hosted or production-ready scheduler.",
|
||||||
|
"canonical_url": null,
|
||||||
|
"repository_status": "draft",
|
||||||
|
"visibility": "public",
|
||||||
|
"maturity": "prototype",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"created_at": "2026-10-06",
|
||||||
|
"updated_at": "2026-10-06",
|
||||||
|
"authors": [{ "name": "Eddie Soehnel" }],
|
||||||
|
"publisher": { "name": "Eddie Soehnel" },
|
||||||
|
"resource_types": ["software", "automation", "workflow", "source-code"],
|
||||||
|
"topics": {
|
||||||
|
"technology": ["python", "ai", "mcp", "sqlite"],
|
||||||
|
"business_function": ["calendar-scheduling", "workflow-automation"],
|
||||||
|
"industry_context": [],
|
||||||
|
"artifact_type": ["software", "reference-implementation", "ai-skill"],
|
||||||
|
"concepts": ["human-authorization", "provider-integrations", "safe-retries", "time-slot-selection"]
|
||||||
|
},
|
||||||
|
"audiences": ["Python developers", "AI workflow designers", "researchers evaluating scheduling automation"],
|
||||||
|
"problems_solved": ["Provides a reference structure for evaluating policy-driven scheduling workflows and their recovery behavior."],
|
||||||
|
"capabilities": ["Evaluate scheduling policy", "Select candidate time slots", "Track workflow operations", "Demonstrate provider adapter boundaries"],
|
||||||
|
"use_cases": ["Study an AI-assisted scheduling prototype", "Adapt policy and orchestration concepts for a controlled test environment"],
|
||||||
|
"required_inputs": [
|
||||||
|
{ "name": "Scheduling policy", "description": "A user-reviewed policy adapted from synthetic defaults.", "required": true, "sensitivity": "May contain private account and availability settings; keep deployment values outside this public repository." },
|
||||||
|
{ "name": "Provider configuration", "description": "Optional credentials and account settings for integrations that a user deliberately enables.", "required": false, "sensitivity": "Secret; provide through an approved external secret manager or protected environment." }
|
||||||
|
],
|
||||||
|
"expected_outputs": [
|
||||||
|
{ "name": "Candidate schedule slots", "description": "Policy-constrained slot suggestions for a request.", "format": "structured data" },
|
||||||
|
{ "name": "Workflow evidence", "description": "Minimal operation state used for recovery and review.", "format": "SQLite or structured data" }
|
||||||
|
],
|
||||||
|
"entrypoints": {
|
||||||
|
"human": "README.md",
|
||||||
|
"ai": "AGENTS.md",
|
||||||
|
"primary_skill": "skills/petra-scheduling-orchestrator/SKILL.md",
|
||||||
|
"primary_agent": null,
|
||||||
|
"primary_script": "scripts/start-local.ps1",
|
||||||
|
"primary_template": null
|
||||||
|
},
|
||||||
|
"contents": [
|
||||||
|
{ "path": "src/scheduling_core/", "type": "source-code", "title": "Scheduling core", "description": "Policy, slotting, orchestration, provider adapters, and ledger.", "required_for_use": true },
|
||||||
|
{ "path": "config/scheduling-policy.json", "type": "configuration-example", "title": "Sample scheduling policy", "description": "Synthetic defaults that require user adaptation.", "required_for_use": false },
|
||||||
|
{ "path": "docs/", "type": "documentation", "title": "Design notes", "description": "Generic policy, transition, setup, and limitation guidance.", "required_for_use": false },
|
||||||
|
{ "path": "skills/petra-scheduling-orchestrator/SKILL.md", "type": "skill", "title": "Scheduling orchestrator skill", "description": "AI workflow guidance for adapting the prototype safely.", "required_for_use": false },
|
||||||
|
{ "path": "scripts/", "type": "scripts", "title": "Development and integration helpers", "description": "Local helpers; external actions require explicit configuration and review.", "required_for_use": false },
|
||||||
|
{ "path": "tests/", "type": "tests", "title": "Existing unit tests", "description": "Project tests using synthetic fixtures.", "required_for_use": false }
|
||||||
|
],
|
||||||
|
"relationships": { "part_of": [], "supports": [], "depends_on": [], "related_resources": [], "supersedes": [], "superseded_by": [] },
|
||||||
|
"access": { "public": true, "authentication_required": false, "payment_required": false, "registration_required": false },
|
||||||
|
"rights": { "license": "MIT", "license_file": "LICENSE", "usage_guidance": "README.md" },
|
||||||
|
"provenance": { "origin_type": "original", "creation_method": "Author-provided software adapted and sanitized for public distribution.", "contributors": ["Eddie Soehnel"], "source_references": [] },
|
||||||
|
"maintenance": { "maintainer": "Eddie Soehnel", "review_frequency": "as-needed", "last_reviewed_at": "2026-10-06", "deprecated": false, "archived": false },
|
||||||
|
"ai_retrieval": {
|
||||||
|
"read_first": ["README.md", "AUTHOR.md", "repository-variables.json", "repository.json", "content-index.json", "AGENTS.md", "skills.md"],
|
||||||
|
"retrieve_as_needed": ["docs/", "skills/", "config/", "src/", "scripts/"],
|
||||||
|
"exclude_by_default": ["archive/", "tasks/", "tests/"],
|
||||||
|
"instructions": "Start with the entrypoints. Treat this as a prototype, use synthetic data, and inspect any script with external side effects before adapting or running it."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Scripts
|
||||||
|
|
||||||
|
Scripts are development helpers and integration examples, not a deployment system. Read each script before running it.
|
||||||
|
|
||||||
|
- `start-local.ps1` and `start-mcp.ps1` launch local development interfaces.
|
||||||
|
- `send-*.ps1` require explicit confirmation and caller-supplied credentials, sender, recipient, and content.
|
||||||
|
- `record-*.ps1` record caller-supplied non-production evidence in an isolated local ledger.
|
||||||
|
- Host-specific tunnel, startup-task, and token-file helpers are disabled in this public distribution.
|
||||||
|
- `verify-postmark-readonly.ps1` and its Python module demonstrate a read-only provider check when separately configured.
|
||||||
|
|
||||||
|
No script should be run against a real account without reviewing its exact effects and configuration.
|
||||||
@@ -0,0 +1,370 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Read-only structural audit for an AI-ready repository."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
PROFILES = {
|
||||||
|
"documentation-guide": {
|
||||||
|
"README.md",
|
||||||
|
"AUTHOR.md",
|
||||||
|
"repository-variables.json",
|
||||||
|
"repository.json",
|
||||||
|
"LICENSE",
|
||||||
|
"CHANGELOG.md",
|
||||||
|
"UPDATES.md",
|
||||||
|
"VERSION",
|
||||||
|
"CITATION.cff",
|
||||||
|
"docs",
|
||||||
|
},
|
||||||
|
"skill-workflow": {
|
||||||
|
"README.md",
|
||||||
|
"AUTHOR.md",
|
||||||
|
"repository-variables.json",
|
||||||
|
"repository.json",
|
||||||
|
"LICENSE",
|
||||||
|
"CHANGELOG.md",
|
||||||
|
"UPDATES.md",
|
||||||
|
"VERSION",
|
||||||
|
"AGENTS.md",
|
||||||
|
"skills.md",
|
||||||
|
"skills",
|
||||||
|
"templates",
|
||||||
|
"examples",
|
||||||
|
},
|
||||||
|
"software-automation": {
|
||||||
|
"README.md",
|
||||||
|
"AUTHOR.md",
|
||||||
|
"repository-variables.json",
|
||||||
|
"repository.json",
|
||||||
|
"LICENSE",
|
||||||
|
"CHANGELOG.md",
|
||||||
|
"UPDATES.md",
|
||||||
|
"VERSION",
|
||||||
|
"CONTRIBUTING.md",
|
||||||
|
"SECURITY.md",
|
||||||
|
"AGENTS.md",
|
||||||
|
"docs",
|
||||||
|
"scripts",
|
||||||
|
"tests",
|
||||||
|
},
|
||||||
|
"dataset": {
|
||||||
|
"README.md",
|
||||||
|
"AUTHOR.md",
|
||||||
|
"repository-variables.json",
|
||||||
|
"repository.json",
|
||||||
|
"LICENSE",
|
||||||
|
"CHANGELOG.md",
|
||||||
|
"UPDATES.md",
|
||||||
|
"VERSION",
|
||||||
|
"CITATION.cff",
|
||||||
|
"data",
|
||||||
|
"schemas",
|
||||||
|
"docs",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("repository", type=Path, help="Repository root to inspect")
|
||||||
|
parser.add_argument(
|
||||||
|
"--profile",
|
||||||
|
choices=sorted(PROFILES),
|
||||||
|
required=True,
|
||||||
|
help="Approved repository profile",
|
||||||
|
)
|
||||||
|
parser.add_argument("--json", action="store_true", help="Emit JSON")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def read_version_from_citation(path: Path) -> str | None:
|
||||||
|
if not path.is_file():
|
||||||
|
return None
|
||||||
|
match = re.search(
|
||||||
|
r"(?m)^version:\s*[\"']?([^\"'\s#]+)",
|
||||||
|
path.read_text(encoding="utf-8-sig"),
|
||||||
|
)
|
||||||
|
return match.group(1) if match else None
|
||||||
|
|
||||||
|
|
||||||
|
def audit_content_index(root: Path, findings: list[dict[str, str]]) -> None:
|
||||||
|
path = root / "content-index.json"
|
||||||
|
if not path.is_file():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
index = json.loads(path.read_text(encoding="utf-8-sig"))
|
||||||
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||||
|
findings.append({"level": "error", "message": f"content-index.json is invalid: {exc}"})
|
||||||
|
return
|
||||||
|
|
||||||
|
items = index.get("items")
|
||||||
|
if not isinstance(items, list):
|
||||||
|
findings.append(
|
||||||
|
{"level": "error", "message": "content-index.json items must be an array"}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
content_ids: set[str] = set()
|
||||||
|
paths: set[str] = set()
|
||||||
|
for position, item in enumerate(items):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"content-index.json item {position + 1} must be an object",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
content_id = item.get("content_id")
|
||||||
|
declared = item.get("path")
|
||||||
|
if not content_id:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"content-index.json item {position + 1} lacks content_id",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif content_id in content_ids:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"Duplicate content_id in content-index.json: {content_id}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
content_ids.add(content_id)
|
||||||
|
if not declared:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"content-index.json item {position + 1} lacks path",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
elif declared in paths:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"Duplicate path in content-index.json: {declared}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
paths.add(declared)
|
||||||
|
declared_path = Path(declared)
|
||||||
|
if (
|
||||||
|
declared_path.is_absolute()
|
||||||
|
or ".." in declared_path.parts
|
||||||
|
or not (root / declared_path).is_file()
|
||||||
|
):
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"Indexed content path does not exist or is unsafe: {declared}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def audit(root: Path, profile: str) -> dict:
|
||||||
|
findings: list[dict[str, str]] = []
|
||||||
|
if not root.is_dir():
|
||||||
|
return {
|
||||||
|
"repository": str(root),
|
||||||
|
"profile": profile,
|
||||||
|
"passed": False,
|
||||||
|
"findings": [{"level": "error", "message": "Repository path is not a directory"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
for relative in sorted(PROFILES[profile]):
|
||||||
|
if not (root / relative).exists():
|
||||||
|
findings.append({"level": "error", "message": f"Missing required path: {relative}"})
|
||||||
|
|
||||||
|
manifest_path = root / "repository.json"
|
||||||
|
manifest = None
|
||||||
|
if manifest_path.is_file():
|
||||||
|
try:
|
||||||
|
manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
|
||||||
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||||
|
findings.append({"level": "error", "message": f"repository.json is invalid: {exc}"})
|
||||||
|
else:
|
||||||
|
for key in ("schema_version", "repository_id", "title", "description", "version", "entrypoints"):
|
||||||
|
if key not in manifest:
|
||||||
|
findings.append({"level": "error", "message": f"repository.json lacks key: {key}"})
|
||||||
|
entrypoints = manifest.get("entrypoints", {})
|
||||||
|
if isinstance(entrypoints, dict):
|
||||||
|
for audience in ("human", "ai"):
|
||||||
|
declared = entrypoints.get(audience)
|
||||||
|
if not declared:
|
||||||
|
findings.append(
|
||||||
|
{"level": "error", "message": f"Missing {audience} entrypoint declaration"}
|
||||||
|
)
|
||||||
|
elif not (root / declared).exists():
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"Declared {audience} entrypoint does not exist: {declared}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
findings.append({"level": "error", "message": "entrypoints must be an object"})
|
||||||
|
|
||||||
|
variables_path = root / "repository-variables.json"
|
||||||
|
variables = None
|
||||||
|
if variables_path.is_file():
|
||||||
|
try:
|
||||||
|
variables = json.loads(variables_path.read_text(encoding="utf-8-sig"))
|
||||||
|
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||||
|
findings.append(
|
||||||
|
{"level": "error", "message": f"repository-variables.json is invalid: {exc}"}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
for key in (
|
||||||
|
"schema_version",
|
||||||
|
"repository_profile",
|
||||||
|
"identity",
|
||||||
|
"repository",
|
||||||
|
"rights",
|
||||||
|
"skill_defaults",
|
||||||
|
"verified_by",
|
||||||
|
"verified_at",
|
||||||
|
):
|
||||||
|
if key not in variables:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"repository-variables.json lacks key: {key}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if manifest and variables:
|
||||||
|
identity = variables.get("identity", {})
|
||||||
|
variable_authors = [
|
||||||
|
item.get("name")
|
||||||
|
for item in identity.get("authors", [])
|
||||||
|
if isinstance(item, dict)
|
||||||
|
]
|
||||||
|
manifest_authors = [
|
||||||
|
item.get("name")
|
||||||
|
for item in manifest.get("authors", [])
|
||||||
|
if isinstance(item, dict)
|
||||||
|
]
|
||||||
|
comparisons = (
|
||||||
|
("authors", variable_authors, manifest_authors),
|
||||||
|
(
|
||||||
|
"publisher",
|
||||||
|
identity.get("publisher", {}).get("name"),
|
||||||
|
manifest.get("publisher", {}).get("name"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"maintainer",
|
||||||
|
identity.get("maintainer", {}).get("name"),
|
||||||
|
manifest.get("maintenance", {}).get("maintainer"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"repository",
|
||||||
|
variables.get("repository"),
|
||||||
|
{
|
||||||
|
key: manifest.get(key)
|
||||||
|
for key in (
|
||||||
|
"repository_id",
|
||||||
|
"name",
|
||||||
|
"title",
|
||||||
|
"canonical_url",
|
||||||
|
"organization",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"rights",
|
||||||
|
variables.get("rights"),
|
||||||
|
{
|
||||||
|
key: manifest.get("rights", {}).get(key)
|
||||||
|
for key in ("license", "license_file")
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for label, variable_value, manifest_value in comparisons:
|
||||||
|
if variable_value != manifest_value:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": (
|
||||||
|
f"{label} differs between repository-variables.json "
|
||||||
|
"and repository.json"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if variables and variables.get("repository_profile") != profile:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": (
|
||||||
|
"repository_profile differs between repository-variables.json "
|
||||||
|
f"({variables.get('repository_profile')}) and requested audit ({profile})"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
audit_content_index(root, findings)
|
||||||
|
|
||||||
|
version_path = root / "VERSION"
|
||||||
|
version = version_path.read_text(encoding="utf-8-sig").strip() if version_path.is_file() else None
|
||||||
|
if version and manifest and manifest.get("version") != version:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"VERSION ({version}) differs from repository.json ({manifest.get('version')})",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
citation_version = read_version_from_citation(root / "CITATION.cff")
|
||||||
|
if version and citation_version and citation_version != version:
|
||||||
|
findings.append(
|
||||||
|
{
|
||||||
|
"level": "error",
|
||||||
|
"message": f"VERSION ({version}) differs from CITATION.cff ({citation_version})",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
readme = root / "README.md"
|
||||||
|
if readme.is_file() and not readme.read_text(encoding="utf-8-sig").strip():
|
||||||
|
findings.append({"level": "error", "message": "README.md is empty"})
|
||||||
|
|
||||||
|
return {
|
||||||
|
"repository": str(root.resolve()),
|
||||||
|
"profile": profile,
|
||||||
|
"passed": not any(item["level"] == "error" for item in findings),
|
||||||
|
"findings": findings,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def emit_markdown(result: dict) -> None:
|
||||||
|
print(f"# Repository Audit\n\n- Repository: `{result['repository']}`")
|
||||||
|
print(f"- Profile: `{result['profile']}`")
|
||||||
|
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
|
||||||
|
print("\n## Findings")
|
||||||
|
if not result["findings"]:
|
||||||
|
print("\n- No structural errors found.")
|
||||||
|
else:
|
||||||
|
for finding in result["findings"]:
|
||||||
|
print(f"\n- {finding['level'].upper()}: {finding['message']}")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
result = audit(args.repository, args.profile)
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps(result, indent=2))
|
||||||
|
else:
|
||||||
|
emit_markdown(result)
|
||||||
|
return 0 if result["passed"] else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Write-Error "This historical host-specific helper is disabled in the public distribution. Configure and review your own infrastructure; no tunnel or host profile is created by this script."
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
if ([string]::IsNullOrWhiteSpace($env:SCHEDULING_TEST_DATABASE)) { throw "Set SCHEDULING_TEST_DATABASE to an isolated test ledger." }
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
try { & $pythonCommand.Source (Join-Path $PSScriptRoot "record_authorized_gmail_reply_test.py"); exit $LASTEXITCODE } finally { Remove-Item Env:\PYTHONPATH -ErrorAction SilentlyContinue }
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
if ([string]::IsNullOrWhiteSpace($env:SCHEDULING_TEST_DATABASE)) { throw "Set SCHEDULING_TEST_DATABASE to an isolated test ledger." }
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
try { & $pythonCommand.Source (Join-Path $PSScriptRoot "record_authorized_postmark_test_delivery.py"); exit $LASTEXITCODE } finally { Remove-Item Env:\PYTHONPATH -ErrorAction SilentlyContinue }
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true)][string]$CalendarEventId,
|
||||||
|
[Parameter(Mandatory=$true)][string]$MeetingId,
|
||||||
|
[Parameter(Mandatory=$true)][string]$MessageId
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
foreach ($name in @('SCHEDULING_TEST_DATABASE')) { if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) { throw "Required isolated test configuration is missing: $name" } }
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
$env:SCHEDULING_TEST_CALENDAR_EVENT_ID = $CalendarEventId
|
||||||
|
$env:SCHEDULING_TEST_MEETING_ID = $MeetingId
|
||||||
|
$env:SCHEDULING_TEST_MESSAGE_ID = $MessageId
|
||||||
|
try { & $pythonCommand.Source (Join-Path $PSScriptRoot "record_supervised_calendar_invite_delivery.py"); exit $LASTEXITCODE } finally { Remove-Item Env:\PYTHONPATH,Env:\SCHEDULING_TEST_CALENDAR_EVENT_ID,Env:\SCHEDULING_TEST_MEETING_ID,Env:\SCHEDULING_TEST_MESSAGE_ID -ErrorAction SilentlyContinue }
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true)][string]$MessageId,
|
||||||
|
[Parameter(Mandatory=$true)][string]$Recipient
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
if ([string]::IsNullOrWhiteSpace($env:SCHEDULING_TEST_DATABASE)) { throw "Set SCHEDULING_TEST_DATABASE to an isolated test ledger." }
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
$env:SCHEDULING_TEST_MESSAGE_ID = $MessageId
|
||||||
|
$env:SCHEDULING_TEST_RECIPIENT = $Recipient
|
||||||
|
try { & $pythonCommand.Source (Join-Path $PSScriptRoot "record_supervised_postmark_confirmation_delivery.py"); exit $LASTEXITCODE } finally { Remove-Item Env:\PYTHONPATH,Env:\SCHEDULING_TEST_MESSAGE_ID,Env:\SCHEDULING_TEST_RECIPIENT -ErrorAction SilentlyContinue }
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Record caller-supplied, non-production reply-routing evidence in an isolated ledger."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from scheduling_core.ledger import Ledger
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
required = {
|
||||||
|
"database": os.environ.get("SCHEDULING_TEST_DATABASE", ""),
|
||||||
|
"message_id": os.environ.get("SCHEDULING_TEST_MESSAGE_ID", ""),
|
||||||
|
"thread_id": os.environ.get("SCHEDULING_TEST_THREAD_ID", ""),
|
||||||
|
"sender": os.environ.get("SCHEDULING_TEST_SENDER", ""),
|
||||||
|
"recipient": os.environ.get("SCHEDULING_TEST_RECIPIENT", ""),
|
||||||
|
"observed_at": os.environ.get("SCHEDULING_TEST_OBSERVED_AT", ""),
|
||||||
|
}
|
||||||
|
if not all(required.values()):
|
||||||
|
print("FAIL isolated database and evidence fields are required")
|
||||||
|
return 1
|
||||||
|
evidence = {key: value for key, value in required.items() if key != "database"}
|
||||||
|
Ledger(Path(required["database"])).record_owner_transport_evidence(
|
||||||
|
"authorized-owner-delivery-test-gmail-reply-v1", evidence
|
||||||
|
)
|
||||||
|
print("recorded_nonproduction_transport_evidence")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Record a caller-verified message ID for a non-production delivery test."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from scheduling_core.ledger import Ledger, OperationState
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
database = os.environ.get("SCHEDULING_TEST_DATABASE", "")
|
||||||
|
operation_key = os.environ.get("SCHEDULING_TEST_OPERATION_KEY", "")
|
||||||
|
message_id = os.environ.get("SCHEDULING_TEST_MESSAGE_ID", "")
|
||||||
|
if not all((database, operation_key, message_id)):
|
||||||
|
print("FAIL isolated database, operation key, and message ID are required")
|
||||||
|
return 1
|
||||||
|
ledger = Ledger(Path(database))
|
||||||
|
operation = ledger.operation_for_key(operation_key)
|
||||||
|
if operation is None or operation["provider_id"] != message_id:
|
||||||
|
print("FAIL operation does not match the supplied provider message ID")
|
||||||
|
return 1
|
||||||
|
if operation["state"] == OperationState.COMPLETED:
|
||||||
|
print("completed")
|
||||||
|
return 0
|
||||||
|
if operation["state"] != OperationState.ACCEPTED:
|
||||||
|
print(f"FAIL operation is {operation['state']}")
|
||||||
|
return 1
|
||||||
|
ledger.transition_operation(operation_key, OperationState.COMPLETED, message_id)
|
||||||
|
print("completed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""Record caller-supplied sample evidence for an isolated calendar/meeting test."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from scheduling_core.ledger import Ledger
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
database = os.environ.get("SCHEDULING_TEST_DATABASE", "")
|
||||||
|
event_id = os.environ.get("SCHEDULING_TEST_CALENDAR_EVENT_ID", "")
|
||||||
|
meeting_id = os.environ.get("SCHEDULING_TEST_MEETING_ID", "")
|
||||||
|
message_id = os.environ.get("SCHEDULING_TEST_MESSAGE_ID", "")
|
||||||
|
if not all((database, event_id, meeting_id, message_id)):
|
||||||
|
print("FAIL isolated database and sample provider IDs are required")
|
||||||
|
return 1
|
||||||
|
Ledger(Path(database)).record_supervised_test_evidence(
|
||||||
|
"authorized-supervised-calendar-invite-delivery-v1",
|
||||||
|
{
|
||||||
|
"calendar_event_id": event_id,
|
||||||
|
"meeting_id": meeting_id,
|
||||||
|
"provider_message_id": message_id,
|
||||||
|
"confirmation": "caller-confirmed-test-only",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
print("recorded_nonproduction_supervised_evidence")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Record caller-supplied sample evidence for a non-production delivery test."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from scheduling_core.ledger import Ledger
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
database = os.environ.get("SCHEDULING_TEST_DATABASE", "")
|
||||||
|
message_id = os.environ.get("SCHEDULING_TEST_MESSAGE_ID", "")
|
||||||
|
recipient = os.environ.get("SCHEDULING_TEST_RECIPIENT", "")
|
||||||
|
if not all((database, message_id, recipient)):
|
||||||
|
print("FAIL isolated database, sample message ID, and recipient are required")
|
||||||
|
return 1
|
||||||
|
Ledger(Path(database)).record_supervised_test_evidence(
|
||||||
|
"authorized-supervised-postmark-confirmation-delivery-v1",
|
||||||
|
{
|
||||||
|
"provider_message_id": message_id,
|
||||||
|
"recipient": recipient,
|
||||||
|
"confirmation": "caller-confirmed-test-only",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
print("recorded_nonproduction_supervised_evidence")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Write-Error "This historical host-specific helper is disabled in the public distribution. Configure and review your own infrastructure; no tunnel or host profile is created by this script."
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Write-Error "This historical host-specific helper is disabled in the public distribution. Configure and review your own infrastructure; no tunnel or host profile is created by this script."
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Write-Error "This historical host-specific helper is disabled in the public distribution. Configure and review your own infrastructure; no tunnel or host profile is created by this script."
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Write-Error "This historical host-specific helper is disabled in the public distribution. Configure and review your own infrastructure; no tunnel or host profile is created by this script."
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
Write-Error "This historical host-specific helper is disabled in the public distribution. Configure and review your own infrastructure; no tunnel or host profile is created by this script."
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true)][switch]$ConfirmExternalSend
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
foreach ($name in @('POSTMARK_SERVER_TOKEN','SCHEDULING_TEST_DATABASE','SCHEDULING_TEST_SENDER','SCHEDULING_TEST_RECIPIENT')) {
|
||||||
|
if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) { throw "Required environment configuration is missing: $name" }
|
||||||
|
}
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$prior = $env:SCHEDULING_AUTHORIZED_POSTMARK_TEST
|
||||||
|
try {
|
||||||
|
$env:SCHEDULING_AUTHORIZED_POSTMARK_TEST = "1"
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
& $pythonCommand.Source (Join-Path $PSScriptRoot "send_authorized_postmark_test.py")
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
} finally {
|
||||||
|
$env:SCHEDULING_AUTHORIZED_POSTMARK_TEST = $prior
|
||||||
|
Remove-Item Env:\PYTHONPATH -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param([Parameter(Mandatory=$true)][switch]$ConfirmExternalSend)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
foreach ($name in @('POSTMARK_SERVER_TOKEN','SCHEDULING_TEST_DATABASE','SCHEDULING_TEST_SENDER','SCHEDULING_TEST_RECIPIENT','SCHEDULING_TEST_SUBJECT','SCHEDULING_TEST_MESSAGE_BODY')) {
|
||||||
|
if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) { throw "Required environment configuration is missing: $name" }
|
||||||
|
}
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$prior = $env:SCHEDULING_AUTHORIZED_SUPERVISED_TEST
|
||||||
|
try {
|
||||||
|
$env:SCHEDULING_AUTHORIZED_SUPERVISED_TEST = "1"
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
& $pythonCommand.Source (Join-Path $PSScriptRoot "send_supervised_invite_confirmation.py")
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
} finally {
|
||||||
|
$env:SCHEDULING_AUTHORIZED_SUPERVISED_TEST = $prior
|
||||||
|
Remove-Item Env:\PYTHONPATH -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""One explicitly authorized, one-shot provider delivery test; never part of normal scheduling."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.ledger import Ledger, OperationState
|
||||||
|
from scheduling_core.postmark import BoundMessage, PostmarkAdapter, PostmarkHttpsClient
|
||||||
|
|
||||||
|
TRANSACTION_ID = "public-sample-provider-delivery-test-v1"
|
||||||
|
OPERATION_KEY = "public-sample-provider-delivery-test-send-v1"
|
||||||
|
SUBJECT = "Scheduling integration test"
|
||||||
|
BODY = "This is an explicitly authorized integration test. No meeting is being booked."
|
||||||
|
|
||||||
|
|
||||||
|
def delivery_status(client: PostmarkHttpsClient, message_id: str) -> str:
|
||||||
|
"""Read status after acceptance; never resends when status is unavailable."""
|
||||||
|
try:
|
||||||
|
details = client.status(message_id)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
return f"accepted; delivery_status_unavailable_http_{error.code}"
|
||||||
|
except (TimeoutError, urllib.error.URLError, ValueError):
|
||||||
|
return "accepted; delivery_status_unavailable"
|
||||||
|
events = details.get("MessageEvents", []) if isinstance(details, dict) else []
|
||||||
|
kinds = {event.get("Type", "").casefold() for event in events if isinstance(event, dict)}
|
||||||
|
return "delivered" if "delivered" in kinds else "accepted; delivery_pending"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if os.environ.get("SCHEDULING_AUTHORIZED_POSTMARK_TEST") != "1":
|
||||||
|
print("FAIL one-shot authorization gate is not enabled")
|
||||||
|
return 1
|
||||||
|
token = os.environ.get("POSTMARK_SERVER_TOKEN", "")
|
||||||
|
sender = os.environ.get("SCHEDULING_TEST_SENDER", "")
|
||||||
|
recipient = os.environ.get("SCHEDULING_TEST_RECIPIENT", "")
|
||||||
|
database = os.environ.get("SCHEDULING_TEST_DATABASE", "")
|
||||||
|
if not token or not sender or not recipient or not database:
|
||||||
|
print("FAIL token, test sender, test recipient, and database configuration are required")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
ledger = Ledger(Path(database))
|
||||||
|
expires_at = datetime.now(UTC) + timedelta(minutes=15)
|
||||||
|
ledger.create_authorized_owner_delivery_test(
|
||||||
|
transaction_id=TRANSACTION_ID,
|
||||||
|
sender=sender,
|
||||||
|
recipient=recipient,
|
||||||
|
expires_at=expires_at,
|
||||||
|
)
|
||||||
|
existing = ledger.operation_for_key(OPERATION_KEY)
|
||||||
|
if existing is not None and existing["state"] in {OperationState.UNCERTAIN, OperationState.PENDING}:
|
||||||
|
print(f"NO_SEND state={existing['state']} reconciliation_required")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
client = PostmarkHttpsClient(secret_provider=lambda: token, enabled=True)
|
||||||
|
adapter = PostmarkAdapter(ledger, client)
|
||||||
|
try:
|
||||||
|
message_id = adapter.send_bound_message(
|
||||||
|
TRANSACTION_ID,
|
||||||
|
OPERATION_KEY,
|
||||||
|
sender,
|
||||||
|
recipient,
|
||||||
|
BoundMessage(SUBJECT, BODY),
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
print(f"FAIL provider HTTP {error.code}")
|
||||||
|
return 1
|
||||||
|
except Exception:
|
||||||
|
operation = ledger.operation_for_key(OPERATION_KEY)
|
||||||
|
print(f"NO_SEND state={operation['state'] if operation else 'unknown'} reconciliation_required")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
operation = ledger.operation_for_key(OPERATION_KEY)
|
||||||
|
if message_id is None or operation is None or operation["state"] != OperationState.ACCEPTED:
|
||||||
|
print("NO_SEND state=uncertain reconciliation_required")
|
||||||
|
return 2
|
||||||
|
status = delivery_status(client, message_id)
|
||||||
|
print(json.dumps({"message_id": message_id, "accepted_at": operation["updated_at"], "status": status}, sort_keys=True))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""One explicitly authorized provider confirmation example with caller-supplied content."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import urllib.error
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.ledger import Ledger, OperationState
|
||||||
|
from scheduling_core.postmark import BoundMessage, PostmarkAdapter, PostmarkHttpsClient
|
||||||
|
|
||||||
|
TRANSACTION_ID = "public-sample-confirmation-test-v1"
|
||||||
|
OPERATION_KEY = "public-sample-confirmation-test-send-v1"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if os.environ.get("SCHEDULING_AUTHORIZED_SUPERVISED_TEST") != "1":
|
||||||
|
print("FAIL one-shot authorization gate is not enabled")
|
||||||
|
return 1
|
||||||
|
token = os.environ.get("POSTMARK_SERVER_TOKEN", "")
|
||||||
|
sender = os.environ.get("SCHEDULING_TEST_SENDER", "")
|
||||||
|
recipient = os.environ.get("SCHEDULING_TEST_RECIPIENT", "")
|
||||||
|
subject = os.environ.get("SCHEDULING_TEST_SUBJECT", "")
|
||||||
|
body = os.environ.get("SCHEDULING_TEST_MESSAGE_BODY", "")
|
||||||
|
database = os.environ.get("SCHEDULING_TEST_DATABASE", "")
|
||||||
|
if not all((token, sender, recipient, subject, body, database)):
|
||||||
|
print("FAIL token, test sender, recipient, subject, message body, and database configuration are required")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
ledger = Ledger(Path(database))
|
||||||
|
ledger.create_authorized_owner_delivery_test(
|
||||||
|
transaction_id=TRANSACTION_ID,
|
||||||
|
sender=sender,
|
||||||
|
recipient=recipient,
|
||||||
|
expires_at=datetime.now(UTC) + timedelta(minutes=15),
|
||||||
|
)
|
||||||
|
existing = ledger.operation_for_key(OPERATION_KEY)
|
||||||
|
if existing is not None and existing["state"] in {OperationState.PENDING, OperationState.UNCERTAIN}:
|
||||||
|
print(f"NO_SEND state={existing['state']} reconciliation_required")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
client = PostmarkHttpsClient(secret_provider=lambda: token, enabled=True)
|
||||||
|
try:
|
||||||
|
message_id = PostmarkAdapter(ledger, client).send_bound_message(
|
||||||
|
TRANSACTION_ID,
|
||||||
|
OPERATION_KEY,
|
||||||
|
sender,
|
||||||
|
recipient,
|
||||||
|
BoundMessage(subject, body),
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
print(f"FAIL provider HTTP {error.code}")
|
||||||
|
return 1
|
||||||
|
except Exception:
|
||||||
|
operation = ledger.operation_for_key(OPERATION_KEY)
|
||||||
|
print(f"NO_SEND state={operation['state'] if operation else 'unknown'} reconciliation_required")
|
||||||
|
return 2
|
||||||
|
operation = ledger.operation_for_key(OPERATION_KEY)
|
||||||
|
if message_id is None or operation is None or operation["state"] != OperationState.ACCEPTED:
|
||||||
|
print("NO_SEND state=uncertain reconciliation_required")
|
||||||
|
return 2
|
||||||
|
print(json.dumps({"message_id": message_id, "accepted_at": operation["updated_at"], "status": "accepted"}, sort_keys=True))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param([string]$DatabasePath)
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
if (-not $DatabasePath) { $DatabasePath = Join-Path $projectRoot "state\scheduling-ledger.sqlite3" }
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
$env:SCHEDULING_DB = $DatabasePath
|
||||||
|
try { & $pythonCommand.Source -m scheduling_core.api } finally { Remove-Item Env:\PYTHONPATH,Env:\SCHEDULING_DB -ErrorAction SilentlyContinue }
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$true)][string]$FixedSender,
|
||||||
|
[string]$DatabasePath,
|
||||||
|
[switch]$EnablePostmarkSend,
|
||||||
|
[switch]$ConfirmExternalSend,
|
||||||
|
[string]$SupervisedTransactionId,
|
||||||
|
[string]$SupervisedRequester,
|
||||||
|
[string]$SupervisedOwner
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
if ($EnablePostmarkSend -and -not $ConfirmExternalSend) { throw "External sending requires -ConfirmExternalSend." }
|
||||||
|
if ($EnablePostmarkSend -and [string]::IsNullOrWhiteSpace($env:POSTMARK_SERVER_TOKEN)) { throw "Set POSTMARK_SERVER_TOKEN using your approved secret manager." }
|
||||||
|
$priorPostmarkEnable = $env:SCHEDULING_POSTMARK_ENABLE
|
||||||
|
$priorSupervisedScope = $env:SCHEDULING_SUPERVISED_SEND_SCOPE
|
||||||
|
Remove-Item Env:\SCHEDULING_POSTMARK_ENABLE,Env:\SCHEDULING_SUPERVISED_SEND_SCOPE -ErrorAction SilentlyContinue
|
||||||
|
if ($SupervisedTransactionId -or $SupervisedRequester -or $SupervisedOwner) {
|
||||||
|
if (-not $EnablePostmarkSend -or -not $SupervisedTransactionId -or -not $SupervisedRequester -or -not $SupervisedOwner) { throw "Supervised send requires explicit enablement, transaction, requester, and owner." }
|
||||||
|
$env:SCHEDULING_SUPERVISED_SEND_SCOPE = @{ transaction_id=$SupervisedTransactionId; requester=$SupervisedRequester; owner=$SupervisedOwner } | ConvertTo-Json -Compress
|
||||||
|
}
|
||||||
|
$scriptRoot = Split-Path -Parent $PSCommandPath
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $scriptRoot "..")).Path
|
||||||
|
if (-not $DatabasePath) { $DatabasePath = Join-Path $projectRoot "state\scheduling-ledger.sqlite3" }
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
$env:SCHEDULING_DB = $DatabasePath
|
||||||
|
$env:SCHEDULING_MCP_ENABLE = "1"
|
||||||
|
$env:SCHEDULING_FIXED_SENDER = $FixedSender
|
||||||
|
if ($EnablePostmarkSend) { $env:SCHEDULING_POSTMARK_ENABLE = "1" }
|
||||||
|
try { & $pythonCommand.Source -m scheduling_core.mcp_stdio } finally {
|
||||||
|
if ($null -ne $priorPostmarkEnable) { $env:SCHEDULING_POSTMARK_ENABLE = $priorPostmarkEnable }
|
||||||
|
else { Remove-Item Env:\SCHEDULING_POSTMARK_ENABLE -ErrorAction SilentlyContinue }
|
||||||
|
if ($null -ne $priorSupervisedScope) { $env:SCHEDULING_SUPERVISED_SEND_SCOPE = $priorSupervisedScope }
|
||||||
|
else { Remove-Item Env:\SCHEDULING_SUPERVISED_SEND_SCOPE -ErrorAction SilentlyContinue }
|
||||||
|
Remove-Item Env:\SCHEDULING_DB,Env:\SCHEDULING_MCP_ENABLE,Env:\SCHEDULING_FIXED_SENDER,Env:\PYTHONPATH -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[CmdletBinding()]
|
||||||
|
param()
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
if ([string]::IsNullOrWhiteSpace($env:POSTMARK_SERVER_TOKEN)) { throw "Set POSTMARK_SERVER_TOKEN using your approved secret manager." }
|
||||||
|
$projectRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
|
||||||
|
$pythonCommand = Get-Command python -ErrorAction SilentlyContinue
|
||||||
|
if (-not $pythonCommand) { throw "Python 3.11 or newer must be available on PATH." }
|
||||||
|
$env:PYTHONPATH = Join-Path $projectRoot "src"
|
||||||
|
try { & $pythonCommand.Source (Join-Path $PSScriptRoot "verify_postmark_readonly.py"); exit $LASTEXITCODE } finally { Remove-Item Env:\PYTHONPATH -ErrorAction SilentlyContinue }
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Read-only Postmark prerequisite verifier. Never prints tokens or response bodies."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
BASE = "https://api.postmarkapp.com"
|
||||||
|
|
||||||
|
|
||||||
|
def build_readonly_request(path: str, token: str) -> urllib.request.Request:
|
||||||
|
"""Construct a server-token GET request without logging credential material."""
|
||||||
|
return urllib.request.Request(
|
||||||
|
f"{BASE}{path}",
|
||||||
|
headers={
|
||||||
|
"Accept": "application/json",
|
||||||
|
"X-Postmark-Server-Token": token,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get(path: str, token: str) -> object:
|
||||||
|
request = build_readonly_request(path, token)
|
||||||
|
with urllib.request.urlopen(request, timeout=15) as response:
|
||||||
|
return json.loads(response.read())
|
||||||
|
|
||||||
|
|
||||||
|
def safe_http_failure(error: urllib.error.HTTPError, path: str) -> str:
|
||||||
|
"""Return only documented Postmark error fields; never emit request data."""
|
||||||
|
error_code = None
|
||||||
|
message = None
|
||||||
|
try:
|
||||||
|
body = json.loads(error.read())
|
||||||
|
if isinstance(body, dict):
|
||||||
|
raw_code = body.get("ErrorCode")
|
||||||
|
raw_message = body.get("Message")
|
||||||
|
error_code = raw_code if isinstance(raw_code, int) else None
|
||||||
|
message = raw_message if isinstance(raw_message, str) else None
|
||||||
|
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
pass
|
||||||
|
detail = f" endpoint={path}"
|
||||||
|
if error_code is not None:
|
||||||
|
detail += f" postmark_error_code={error_code}"
|
||||||
|
if message:
|
||||||
|
detail += f" postmark_message={message!r}"
|
||||||
|
return f"FAIL Postmark HTTP {error.code}{detail}"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
token = os.environ.get("POSTMARK_SERVER_TOKEN", "")
|
||||||
|
if not token:
|
||||||
|
print("FAIL token unavailable")
|
||||||
|
return 1
|
||||||
|
for path in ("/server", "/message-streams/outbound"):
|
||||||
|
try:
|
||||||
|
response = get(path, token)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
print(safe_http_failure(error, path))
|
||||||
|
return 1
|
||||||
|
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
||||||
|
print(f"FAIL Postmark read-only request unavailable endpoint={path}")
|
||||||
|
return 1
|
||||||
|
if path == "/server":
|
||||||
|
server = response
|
||||||
|
else:
|
||||||
|
stream = response
|
||||||
|
server_ok = isinstance(server, dict) and bool(server.get("Name"))
|
||||||
|
stream_ok = isinstance(stream, dict) and stream.get("ID") == "outbound" and stream.get("MessageStreamType") == "Transactional"
|
||||||
|
# Sender-signature inspection is deliberately excluded: /senders requires
|
||||||
|
# an account token, while this component is restricted to a server token.
|
||||||
|
print(f"server={'ok' if server_ok else 'fail'} stream={'ok' if stream_ok else 'fail'}")
|
||||||
|
return 0 if server_ok and stream_ok else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# AI workflow skill index
|
||||||
|
|
||||||
|
| Skill | Trigger | Purpose | Entry point |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Petra scheduling orchestrator | Use when adapting the sample policy and orchestration flow for an AI-assisted scheduling workflow. | Describes authenticated request handling, safe slot offers, provider read-back, recovery, and limits. Requires human configuration before any external action. | [skills/petra-scheduling-orchestrator/SKILL.md](skills/petra-scheduling-orchestrator/SKILL.md) |
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
name: petra-scheduling-orchestrator
|
||||||
|
description: Reference workflow for adapting the scheduling prototype to authenticated, human-authorized calendar operations. Requires private configuration and review before any external action.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Petra scheduling orchestrator
|
||||||
|
|
||||||
|
Use this skill as a design reference when adapting the scheduling core. Read [the connector policy](../../docs/direct-connector-policy.md) first. This skill does not connect to accounts, enable a scheduler, or authorize provider writes.
|
||||||
|
|
||||||
|
## Adaptation sequence
|
||||||
|
|
||||||
|
1. Define the authenticated intake path, owner identity, allowed calendar, timezone, work hours, and provider settings in private configuration. Do not put real account values in this repository.
|
||||||
|
2. Reconstruct the existing request state before taking action. Require verified authority and bind each reply to its offer using provider identifiers and reply-lineage metadata.
|
||||||
|
3. Use a configured assistant identity and signature. Keep owner names and email addresses out of shared fixtures and logs.
|
||||||
|
4. Offer only policy-compliant slots. State a complete reply window and timezone, treat options as non-reservations, and refresh availability immediately before booking.
|
||||||
|
5. Create provider resources only when explicitly requested. Verify the returned details and read back the created calendar event by its known ID.
|
||||||
|
6. Send confirmations only after a verified booking. Mark the request complete only after required messages are read back and all relevant state is reconciled.
|
||||||
|
|
||||||
|
## Fail-closed rules
|
||||||
|
|
||||||
|
- A label, display name, quoted message, thread ID, or token alone does not prove authorization.
|
||||||
|
- Do not blindly retry a send or create operation with an unknown result. Reconcile with known provider IDs or pause for human review.
|
||||||
|
- Do not revive expired, ambiguous, or historical transactions automatically.
|
||||||
|
- Never expose credentials, message bodies, private calendar details, or meeting host controls.
|
||||||
|
- Keep the scheduler cadence and activation controls in the deployment system; this skill does not activate or modify them.
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
This repository is an experimental reference implementation. Provider-specific behavior, recovery, privacy controls, and production readiness require independent review in an isolated environment.
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Evidence contract
|
||||||
|
|
||||||
|
Use this contract when adapting the prototype to providers that expose message, calendar, or meeting identifiers.
|
||||||
|
|
||||||
|
- Authenticate the request source and confirm it has authority to request a scheduling action.
|
||||||
|
- Bind a selection reply to a verified outbound offer using provider message identifiers and available reply-lineage metadata.
|
||||||
|
- Refresh availability immediately before booking. Preserve the known event identifier for read-back.
|
||||||
|
- Verify the created event's interval, participants, visibility, and requested logistics before sending confirmations.
|
||||||
|
- Treat uncertain send/create outcomes as reconciliation work. An empty search result or status label does not authorize a retry.
|
||||||
|
- Store only the minimal synthetic or protected metadata needed for recovery. Never commit real message, event, or meeting identifiers.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""Offline durable scheduling component; external provider access is intentionally absent."""
|
||||||
|
|
||||||
|
from .ledger import Ledger, OperationState
|
||||||
|
|
||||||
|
__all__ = ["Ledger", "OperationState"]
|
||||||
@@ -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()
|
||||||
@@ -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
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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")
|
||||||
@@ -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
|
||||||
@@ -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"]),
|
||||||
|
)
|
||||||
@@ -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"]
|
||||||
@@ -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"])
|
||||||
@@ -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")
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Repository task records
|
||||||
|
|
||||||
|
Task plans and implementation records document repository maintenance. Keep these records free of private source paths, account data, secrets, and live operational evidence.
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
# Repository Structure Plan
|
||||||
|
|
||||||
|
## Plan Control
|
||||||
|
|
||||||
|
- Task ID: `calendar-scheduling-publication`
|
||||||
|
- Target repository: `/path/to/public-repository`
|
||||||
|
- Repository mode: `existing` (empty Git repository)
|
||||||
|
- Profile: `software-automation`
|
||||||
|
- Revision: `1`
|
||||||
|
- Status: `approved`
|
||||||
|
- Created: `2026-10-06`
|
||||||
|
- Updated: `2026-10-06`
|
||||||
|
- Approval evidence: `User approved revision 1 on 2026-10-06.`
|
||||||
|
|
||||||
|
## Outcome
|
||||||
|
|
||||||
|
Create a sanitized, downloadable public version of the AI calendar scheduling project that explains its purpose and safe setup to people and AI agents, exposes searchable repository metadata, and preserves reusable scheduling logic without disclosing private operational details.
|
||||||
|
|
||||||
|
## Identity And Publication
|
||||||
|
|
||||||
|
- Author(s): `Eddie Soehnel`
|
||||||
|
- Publisher: `Eddie Soehnel` (per user's identity selection)
|
||||||
|
- Maintainer: `Eddie Soehnel` (per user's identity selection)
|
||||||
|
- Canonical repository URL: `Unset; user selected URL unknown. The observed Git remote is not treated as confirmation of the canonical URL.`
|
||||||
|
- License: `MIT`
|
||||||
|
- Repository variables: `Create repository-variables.json using confirmed identity, software-automation profile, MIT rights, and canonical_url null/unset.`
|
||||||
|
- Identity source: `User response`
|
||||||
|
- Publication intent: `mixed` (reusable software, scripts, skill/workflow, and docs)
|
||||||
|
- Brand exposure: `Keep product and integration names`
|
||||||
|
- Author exposure: `Eddie Soehnel allowed as repository author/publisher/maintainer; sanitize personal identifiers in operational content.`
|
||||||
|
- Public output branch: `codex/calendar-scheduling-publication` (requested; create only after this plan is approved)
|
||||||
|
- Review receipt folder: `<publication-receipt-folder>`
|
||||||
|
- Source selection: `All tracked source files except .git/, runtime state, caches, generated/private data, and machine-specific artifacts; each copied file must pass sanitization review.`
|
||||||
|
- Anonymization map: `Replace private user and host paths with /path/to/project; private addresses with distinct synthetic [email protected] values (or [email protected]/[email protected]); private domains/hostnames with example.org or host.example.internal; IPs with localhost or a marked placeholder; key names/credentials with generic placeholders; private repository URLs with https://code.example.org/organization/calendar-scheduling; redact third-party personal and business identifiers. Keep product/integration names.`
|
||||||
|
|
||||||
|
## Current State
|
||||||
|
|
||||||
|
### Facts
|
||||||
|
|
||||||
|
- The source repository is `<private source repository>`; its Git working tree is clean and it has 65 tracked files.
|
||||||
|
- The source has a runtime `state/` directory excluded by its `.gitignore`; it will not be copied. `.git/`, generated caches, and machine-specific artifacts are excluded as well.
|
||||||
|
- The source contains Python scheduling code, a scheduling skill, policy/configuration, fixtures, tests, scripts for provider verification and authorized/supervised sends, and historical operational documentation.
|
||||||
|
- Several source documents contain private email addresses, personal paths, operational details, dates, and provider/tunnel configuration. These require sanitization before public inclusion. Product and integration names may remain.
|
||||||
|
- The destination has no tracked files or working changes and is currently on `main`. It has an `origin` remote, but the user selected canonical URL unknown; this plan leaves the canonical URL unset pending explicit confirmation.
|
||||||
|
- The template's baseline audit was run with `software-automation`; it reports the expected required paths missing from the empty destination.
|
||||||
|
- The template instructions require a repository-local plan and explicit approval before structural changes. No source files have been copied.
|
||||||
|
|
||||||
|
### Assumptions
|
||||||
|
|
||||||
|
- `software-automation` is the smallest suitable template profile for an executable Python scheduling tool with scripts and tests.
|
||||||
|
- Documentation is large enough to benefit from `content-index.json`; the index will list authoritative public docs and skill entry points rather than every code file.
|
||||||
|
- All non-excluded tracked source files remain in scope, but any file found to contain sensitive or unsafe live operational defaults will be sanitized or marked for omission with rationale before it is added.
|
||||||
|
- MIT applies to the new public repository as instructed; source licensing/provenance will be reviewed before an MIT license file is written.
|
||||||
|
|
||||||
|
### Baseline Audit
|
||||||
|
|
||||||
|
- Command: `python audit_repository.py --profile software-automation --json /path/to/public-repository`
|
||||||
|
- Result: `Failed as expected for an empty repo; 14 findings report missing software-automation profile files and paths.`
|
||||||
|
|
||||||
|
## Profile Decision
|
||||||
|
|
||||||
|
Select `software-automation`: this is a Python scheduling application with reusable source, operational scripts, configuration, tests, documentation, and a workflow skill. A skill-only profile would underdescribe the software; a larger dataset/documentation profile would not fit.
|
||||||
|
|
||||||
|
## Proposed Structure
|
||||||
|
|
||||||
|
```text
|
||||||
|
calendar-scheduling-OPEN/
|
||||||
|
├── README.md
|
||||||
|
├── AUTHOR.md
|
||||||
|
├── repository-variables.json
|
||||||
|
├── repository.json
|
||||||
|
├── content-index.json
|
||||||
|
├── AGENTS.md
|
||||||
|
├── CHANGELOG.md
|
||||||
|
├── UPDATES.md
|
||||||
|
├── VERSION
|
||||||
|
├── LICENSE
|
||||||
|
├── CONTRIBUTING.md
|
||||||
|
├── SECURITY.md
|
||||||
|
├── skills.md
|
||||||
|
├── CITATION.cff
|
||||||
|
├── .gitignore
|
||||||
|
├── pyproject.toml
|
||||||
|
├── src/scheduling_core/ # sanitized reusable scheduler code
|
||||||
|
├── config/ # sanitized policy defaults
|
||||||
|
├── fixtures/orchestration/ # synthetic/anonymized fixtures only
|
||||||
|
├── docs/ # public policy, setup, architecture, and migration guidance
|
||||||
|
├── skills/petra-scheduling-orchestrator/
|
||||||
|
├── scripts/ # reviewed, placeholder-based scripts
|
||||||
|
├── tests/ # existing tests, sanitized where needed
|
||||||
|
├── archive/ # reviewed historical documentation, clearly marked inactive
|
||||||
|
└── tasks/calendar-scheduling-publication/
|
||||||
|
└── repository-structure-plan.md
|
||||||
|
```
|
||||||
|
|
||||||
|
No files will be committed or pushed. No remote settings or hosting topics will be changed.
|
||||||
|
|
||||||
|
## File Actions
|
||||||
|
|
||||||
|
| Path | Action | Purpose and planned content | Existing-content treatment |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `src/`, `config/`, `fixtures/`, `docs/`, `skills/`, `scripts/`, `tests/`, `archive/`, `pyproject.toml` | `create` | Copy the in-scope tracked software, policy, examples, user docs, skills, scripts, and tests. | Copy without `.git/`; review each file for secrets, private identifiers, unsafe live defaults, and operational history. Replace private values with approved generic placeholders. Preserve useful historical material with clear inactive/archive context. |
|
||||||
|
| `.gitignore` | `create` | Exclude secrets, local state, caches, logs, databases, virtual environments, exports, and transient files. | Adapt source ignore rules and add public-safe guards. |
|
||||||
|
| `README.md` | `modify` | Explain tool purpose, audience, architecture, setup, configuration, safe use, limitations, and human/AI entry points. | Rewrite from source overview; remove private run evidence, dates, email addresses, and private scheduler references. |
|
||||||
|
| `AUTHOR.md`, `repository-variables.json`, `repository.json`, `CITATION.cff`, `LICENSE` | `create` | Provide aligned verified identity, machine-readable discoverability, repository metadata, citation, and MIT terms. | Use user-confirmed Eddie Soehnel attribution and MIT. Keep canonical URL unset; do not invent a public URL. Confirm source licensing/provenance before assigning MIT. |
|
||||||
|
| `content-index.json` | `create` | Catalog the primary setup guide, architecture/policy docs, migration notes, and skill entry point for search and retrieval. | Use stable IDs and paths; include only files actually included in the public repo. |
|
||||||
|
| `AGENTS.md`, `skills.md` | `create` | Define safe AI retrieval order and index the scheduling skill and relevant scripts. | Scope instructions to the public project; exclude private operations and live credentials. |
|
||||||
|
| `CHANGELOG.md`, `UPDATES.md`, `VERSION` | `create` | Record initial sanitized publication, future proposals, and aligned initial version. | Do not claim a release or publication; mark version as initial pre-release/baseline if supported by repository standard. |
|
||||||
|
| `CONTRIBUTING.md`, `SECURITY.md` | `create` | Explain contribution validation and safe vulnerability reporting. | Do not invent a security contact; direct private reports through repository host only if an actual supported route is confirmed, otherwise use a placeholder or omit contact details. |
|
||||||
|
| `tasks/calendar-scheduling-publication/repository-structure-plan.md` | `create` | Reviewable implementation plan. | Created as the only repository write before approval. |
|
||||||
|
| `tasks/calendar-scheduling-publication/implementation-receipt.md`, `tasks/calendar-scheduling-publication/validation-results.md` | `create` | Record approved implementation actions, validation, deviations, and unresolved items. | Create after implementation, after approval. |
|
||||||
|
| `<publication-receipt-folder>\2026-10-06-calendar-scheduling-publication-receipt.md` | `create` | Required publication receipt for copied files, sanitization, scans, findings, and remaining risks. | Create after sanitation and validation; do not claim safe-to-publish while blockers remain. |
|
||||||
|
|
||||||
|
## Human and AI Entry Points
|
||||||
|
|
||||||
|
- Human starts at: `README.md`
|
||||||
|
- AI agent starts at: `AGENTS.md`, which directs to `README.md`, `AUTHOR.md`, `repository-variables.json`, `repository.json`, `content-index.json`, `skills.md`, then relevant docs/code.
|
||||||
|
- Authoritative manifest: `repository.json`
|
||||||
|
- Verified repository variables: `repository-variables.json`
|
||||||
|
- Retrieve next: `content-index.json`, `skills.md`, `docs/README.md`, then relevant architecture/policy documentation and `skills/petra-scheduling-orchestrator/SKILL.md`.
|
||||||
|
|
||||||
|
## Hosting Platform Choices
|
||||||
|
|
||||||
|
- Existing host remote observed: `existing origin URL intentionally omitted`; user has not confirmed it as canonical, so it stays unset in repository metadata.
|
||||||
|
- Prepare branch `codex/calendar-scheduling-publication` only after approval.
|
||||||
|
- Do not push, publish, create a release, or change remote/hosting settings.
|
||||||
|
- Add no host-specific issue/CI files unless needed by existing project conventions.
|
||||||
|
|
||||||
|
## Validation and Definition of Done
|
||||||
|
|
||||||
|
- [ ] The approved source scope is copied; excluded state, `.git/`, caches, and generated/private data are absent.
|
||||||
|
- [ ] Private identifiers, credentials, paths, service endpoints, and operational details are sanitized or documented as unresolved review items.
|
||||||
|
- [ ] No live sending or calendar-write behavior is enabled by private defaults; public configuration uses explicit placeholders and safe setup instructions.
|
||||||
|
- [ ] Template metadata agrees on author, publisher, maintainer, canonical URL state, MIT license, profile, and version.
|
||||||
|
- [ ] The README, agent entrypoint, manifest, skill index, and content index resolve to actual files.
|
||||||
|
- [ ] Template structural audit passes for `software-automation` or any residual findings are explained.
|
||||||
|
- [ ] Leak scans, generated-file checks, link checks, and repository status/diff review are recorded.
|
||||||
|
- [ ] No tests are added or run unless separately requested; existing test files may be copied and sanitized.
|
||||||
|
- [ ] Publication receipt, implementation receipt, and validation results are complete and accurately state unresolved risks.
|
||||||
|
- [ ] No commit or push occurs.
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
|
||||||
|
- Template profile audit for `software-automation`.
|
||||||
|
- Secret, email, IP, hostname, workstation-path, and generated-data scans.
|
||||||
|
- Machine-readable metadata parsing and Git status/diff review.
|
||||||
|
|
||||||
|
## Risks and Preservation Notes
|
||||||
|
|
||||||
|
- Operational docs include private evidence and real-world scheduling references; user-approved names/integrations may remain, but addresses, personal paths, dates and identifiers must be reviewed and generalized.
|
||||||
|
- Some scripts can send email, create calendar events, manage tokens, configure tunnels, or register startup tasks. Their public behavior/defaults require individual review; placeholders alone do not establish safe operation.
|
||||||
|
- Source provenance/license has not yet been independently established. MIT was selected by the user for the public repository; confirm rights to all copied source, tests, and documentation during implementation. Flag any third-party or provenance uncertainty rather than silently licensing it.
|
||||||
|
- The destination had an existing remote, but its URL is intentionally omitted from the publication plan; canonical URL is expressly unset.
|
||||||
|
- The destination will receive a new publication branch after approval; `main` remains the pre-publication state unless the user later requests otherwise.
|
||||||
|
|
||||||
|
## Out of Scope
|
||||||
|
|
||||||
|
- Running the scheduler, sending email, creating calendar events, authenticating provider accounts, or using any secrets.
|
||||||
|
- Publishing, pushing, releasing, changing remotes, or changing host settings.
|
||||||
|
- Editing the private source repository.
|
||||||
|
- Creating or updating persistent memory.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
- No blocking intake questions remain. Sanitization findings that cannot be safely resolved while preserving utility will be listed as review items in the receipt.
|
||||||
|
|
||||||
|
## Approval
|
||||||
|
|
||||||
|
Approve revision 1 of this plan before implementation. Amendments create a new revision and return the plan to `awaiting approval`.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.ledger import Ledger
|
||||||
|
from scheduling_core.policy import PolicyConfig, PolicyViolation, evaluate_intent
|
||||||
|
from scheduling_core.postmark import BoundMessage, PostmarkAdapter, ProviderDisabled
|
||||||
|
from scheduling_core.mcp_stdio import Adapter
|
||||||
|
from scheduling_core.workflow import SchedulingWorkflow
|
||||||
|
|
||||||
|
NOW = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||||
|
CONFIG = PolicyConfig(revision="offline-test", fixed_sender="[email protected]", max_exchange_messages=2)
|
||||||
|
|
||||||
|
|
||||||
|
def raw_intent(**changes):
|
||||||
|
value = {"transaction_id": "tx-1", "requester": "[email protected]", "sender": "[email protected]", "start_at": "2031-01-01T18:00:00Z", "end_at": "2031-01-01T19:00:00Z", "expires_at": "2031-01-02T00:00:00Z", "authentication_evidence_id": "auth-opaque", "availability_evidence_id": "freebusy-opaque"}
|
||||||
|
value.update(changes)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class LedgerTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.ledger = Ledger(Path(self.temp.name) / "ledger.sqlite3")
|
||||||
|
intent = evaluate_intent(raw_intent(), CONFIG, NOW, [])
|
||||||
|
self.ledger.create_transaction(intent, CONFIG.revision, CONFIG.max_exchange_messages)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.temp.cleanup()
|
||||||
|
|
||||||
|
def lease(self):
|
||||||
|
return self.ledger.claim("tx-1", 300).lease_token
|
||||||
|
|
||||||
|
def test_invalid_expired_and_buffered_inputs_rejected(self):
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(raw_intent(expires_at="2030-12-31T15:00:00Z"), CONFIG, NOW, [])
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(raw_intent(), CONFIG, NOW, [{"start_at": "2031-01-01T17:50:00Z", "end_at": "2031-01-01T18:10:00Z"}])
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(raw_intent(sender="[email protected]"), CONFIG, NOW, [])
|
||||||
|
|
||||||
|
def test_bound_sender_recipient_cap_and_duplicate_are_enforced(self):
|
||||||
|
lease = self.lease()
|
||||||
|
first = self.ledger.record_postmark_send("tx-1", lease, "send-1", "[email protected]", "[email protected]")
|
||||||
|
same = self.ledger.record_postmark_send("tx-1", lease, "send-1", "[email protected]", "[email protected]")
|
||||||
|
self.assertEqual(first["id"], same["id"])
|
||||||
|
self.ledger.record_postmark_send("tx-1", lease, "send-2", "[email protected]", "[email protected]")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.ledger.record_postmark_send("tx-1", lease, "send-3", "[email protected]", "[email protected]")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.ledger.record_postmark_send("tx-1", lease, "send-x", "[email protected]", "[email protected]")
|
||||||
|
|
||||||
|
def test_crash_or_timeout_is_reconciliation_not_resend(self):
|
||||||
|
class TimeoutClient:
|
||||||
|
def send(self, **_):
|
||||||
|
raise TimeoutError()
|
||||||
|
adapter = PostmarkAdapter(self.ledger, TimeoutClient())
|
||||||
|
lease = self.lease()
|
||||||
|
self.assertIsNone(adapter.send_bound_message("tx-1", lease, "send-1", "[email protected]", "[email protected]", BoundMessage("Subject", "Body")))
|
||||||
|
self.assertEqual(self.ledger.operations_needing_reconciliation()[0]["operation_key"], "send-1")
|
||||||
|
self.assertIsNone(adapter.send_bound_message("tx-1", lease, "send-1", "[email protected]", "[email protected]", BoundMessage("Subject", "Body")))
|
||||||
|
|
||||||
|
def test_stranded_dispatch_is_never_retried(self):
|
||||||
|
lease = self.lease()
|
||||||
|
self.ledger.record_postmark_send("tx-1", lease, "send-crash", "[email protected]", "[email protected]")
|
||||||
|
self.ledger.transition_operation("tx-1", lease, "send-crash", "dispatching")
|
||||||
|
class Client:
|
||||||
|
def send(self, **_): raise AssertionError("must reconcile, not resend")
|
||||||
|
self.assertIsNone(PostmarkAdapter(self.ledger, Client()).send_bound_message("tx-1", lease, "send-crash", "[email protected]", "[email protected]", BoundMessage("Subject", "Body")))
|
||||||
|
self.assertIn("send-crash", [row["operation_key"] for row in self.ledger.operations_needing_reconciliation()])
|
||||||
|
|
||||||
|
def test_disabled_adapter_never_sends(self):
|
||||||
|
with self.assertRaises(ProviderDisabled):
|
||||||
|
PostmarkAdapter(self.ledger).send_bound_message("tx-1", self.lease(), "send-disabled", "[email protected]", "[email protected]", BoundMessage("Subject", "Body"))
|
||||||
|
self.assertEqual(self.ledger.operations_needing_reconciliation(), [])
|
||||||
|
|
||||||
|
def test_claim_is_exclusive(self):
|
||||||
|
self.assertIsNotNone(self.ledger.claim("tx-1", 30))
|
||||||
|
self.assertIsNone(self.ledger.claim("tx-1", 30))
|
||||||
|
|
||||||
|
def test_mcp_adapter_exposes_only_narrow_tools(self):
|
||||||
|
response = Adapter(self.ledger, CONFIG).handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
|
||||||
|
self.assertIn("confirm_booking_availability", {tool["name"] for tool in response["result"]["tools"]})
|
||||||
|
self.assertIn("complete_booking", {tool["name"] for tool in response["result"]["tools"]})
|
||||||
|
|
||||||
|
def test_mcp_rejects_extra_or_untyped_arguments(self):
|
||||||
|
adapter = Adapter(self.ledger, CONFIG)
|
||||||
|
response = adapter.handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "claim_transaction", "arguments": {"transaction_id": "tx-1", "lease_seconds": "60"}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
response = adapter.handle_request({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "claim_transaction", "arguments": {"transaction_id": "tx-1", "unexpected": True}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
|
||||||
|
def test_mcp_reserves_calendar_and_zoom_without_calling_providers(self):
|
||||||
|
adapter = Adapter(self.ledger, CONFIG)
|
||||||
|
workflow = SchedulingWorkflow(self.ledger)
|
||||||
|
offer = workflow.begin_round("tx-1", ("slot-a",), datetime.now(UTC) + timedelta(hours=1), "thread")
|
||||||
|
workflow.bind_outbound("tx-1", offer["round_number"], "outbound")
|
||||||
|
workflow.accept_selection("tx-1", slot_id="slot-a", transaction_token=offer["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",))
|
||||||
|
lease=adapter.call("claim_transaction", {"transaction_id":"tx-1"})["lease_token"]
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
adapter.call("reserve_calendar_event", {"transaction_id": "tx-1", "lease_token":lease,"operation_key": "calendar-1"})
|
||||||
|
|
||||||
|
def test_mcp_postmark_execution_requires_injected_runtime_client(self):
|
||||||
|
lease = self.lease()
|
||||||
|
arguments = {"transaction_id": "tx-1", "lease_token":lease, "operation_key": "postmark-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "offer"}
|
||||||
|
disabled = Adapter(self.ledger, CONFIG).call("prepare_postmark_send", arguments)
|
||||||
|
self.assertEqual(disabled["status"], "disabled")
|
||||||
|
self.assertIsNone(self.ledger.operation_for_key("postmark-1"))
|
||||||
|
class Client:
|
||||||
|
def send(self, **kwargs):
|
||||||
|
self.kwargs = kwargs
|
||||||
|
return "postmark-provider-id"
|
||||||
|
workflow = SchedulingWorkflow(self.ledger)
|
||||||
|
workflow.begin_round("tx-1", ({"slot_id":"slot-a", "start_at":"2031-01-01T18:00:00Z", "end_at":"2031-01-01T19:00:00Z"},), datetime.now(UTC) + timedelta(hours=1), "thread")
|
||||||
|
client = Client()
|
||||||
|
result = Adapter(self.ledger, CONFIG, client).call("prepare_postmark_send", arguments)
|
||||||
|
self.assertEqual(result["status"], "accepted")
|
||||||
|
self.assertEqual(result["provider_id"], "postmark-provider-id")
|
||||||
|
self.assertRegex(result["outbound_rfc_message_id"], r"^<sched-[0-9a-f-]+@example\.test>$")
|
||||||
|
self.assertEqual(client.kwargs["recipient"], "[email protected]")
|
||||||
|
|
||||||
|
def test_mcp_rejects_calendar_or_postmark_before_offer_acceptance(self):
|
||||||
|
adapter = Adapter(self.ledger, CONFIG)
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
adapter.call("reserve_calendar_event", {"transaction_id": "tx-1", "lease_token":"bad", "operation_key": "calendar-early"})
|
||||||
|
class Client:
|
||||||
|
def send(self, **_): return "unexpected"
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
adapter = Adapter(self.ledger, CONFIG, Client())
|
||||||
|
adapter.call("prepare_postmark_send", {"transaction_id":"tx-1","lease_token":self.lease(),"operation_key":"mail-early","sender":"[email protected]","requester":"[email protected]","purpose":"offer","subject":"s","text_body":"b"})
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from scheduling_core.ledger import Ledger
|
||||||
|
from scheduling_core.mcp_stdio import Adapter
|
||||||
|
from scheduling_core.policy import PolicyConfig
|
||||||
|
|
||||||
|
|
||||||
|
class MockPostmark:
|
||||||
|
def __init__(self):
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def send(self, **kwargs):
|
||||||
|
self.calls.append(kwargs)
|
||||||
|
return f"postmark-{len(self.calls)}"
|
||||||
|
|
||||||
|
|
||||||
|
class McpOnlyLifecycleTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.client = MockPostmark()
|
||||||
|
# Four is the minimum viable budget here: offer, requester reply, requester
|
||||||
|
# confirmation, and owner summary. It makes closing-cap exhaustion explicit.
|
||||||
|
self.adapter = Adapter(Ledger(Path(self.temp.name) / "ledger.sqlite3"), PolicyConfig(revision="integration", fixed_sender="[email protected]", owner_email="[email protected]", delivery_alias="[email protected]", max_exchange_messages=4), self.client)
|
||||||
|
local = datetime.now(ZoneInfo("UTC")) + timedelta(days=2)
|
||||||
|
while local.weekday() > 4:
|
||||||
|
local += timedelta(days=1)
|
||||||
|
self.start = local.replace(hour=10, minute=0, second=0, microsecond=0).astimezone(UTC)
|
||||||
|
self.expiry = datetime.now(UTC) + timedelta(hours=70)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.temp.cleanup()
|
||||||
|
|
||||||
|
def invoke(self, name, arguments):
|
||||||
|
# The public MCP contract has no caller-provided message content. Existing
|
||||||
|
# lifecycle fixtures intentionally use only their transaction metadata.
|
||||||
|
arguments = {key: value for key, value in arguments.items() if key not in {"subject", "text_body"}}
|
||||||
|
if name == "prepare_postmark_send" and arguments.get("purpose") == "clarification":
|
||||||
|
arguments.setdefault("reason", "missing_preference")
|
||||||
|
response = self.adapter.handle_request({"jsonrpc": "2.0", "id": name, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
|
||||||
|
self.assertNotIn("error", response, response)
|
||||||
|
return json.loads(response["result"]["content"][0]["text"])
|
||||||
|
|
||||||
|
def intent(self, number):
|
||||||
|
start = self.start + timedelta(days=number)
|
||||||
|
return {"transaction_id": "mcp-lifecycle", "requester": "[email protected]", "sender": "[email protected]", "start_at": start.isoformat(), "end_at": (start + timedelta(minutes=60)).isoformat(), "expires_at": self.expiry.isoformat(), "authentication_evidence_id": "auth-1", "availability_evidence_id": "availability-offer-1"}
|
||||||
|
|
||||||
|
def create_pending(self):
|
||||||
|
return self.invoke("create_pending_negotiation", {"transaction_id":"mcp-lifecycle", "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":{"provenance_mode":"received_alias", "account_email":"[email protected]", "message_id":"intake-1", "thread_id":"thread", "label":"Scheduling/Intake", "headers":[{"name":"From", "value":"[email protected]"}, {"name":"To", "value":"[email protected]"}], "forwarded_requester":"[email protected]", "forwarded_recipient":"[email protected]", "authentication_evidence_id":"auth-1", "authenticated_mailbox":True, "intake_label_present":True}})
|
||||||
|
|
||||||
|
def owner_sent_forward_evidence(self):
|
||||||
|
return {"provenance_mode":"owner_sent_forward", "account_email":"[email protected]", "message_id":"forward-gmail-id", "thread_id":"thread", "label":"Scheduling/Intake", "headers":[{"name":"From", "value":"[email protected]"}, {"name":"To", "value":"[email protected]"}, {"name":"Message-ID", "value":"<[email protected]>"}, {"name":"In-Reply-To", "value":"<[email protected]>"}, {"name":"References", "value":"<[email protected]>"}], "forwarded_requester":"[email protected]", "forwarded_recipient":"[email protected]", "authentication_evidence_id":"original-auth-id", "authenticated_mailbox":True, "intake_label_present":True, "original_message_id":"original-gmail-id", "original_thread_id":"thread", "original_rfc_message_id":"<[email protected]>", "original_headers":[{"name":"From", "value":"[email protected]"}, {"name":"To", "value":"[email protected]"}, {"name":"Message-ID", "value":"<[email protected]>"}, {"name":"Authentication-Results", "value":"mx.google.com; dkim=pass [email protected] header.s=20251104 header.b=example; arc=pass (i=1); spf=pass (google.com: domain of [email protected] designates mail.example.test as permitted sender) [email protected]; dmarc=pass (p=NONE sp=QUARANTINE dis=NONE) header.from=gmail.com; dara=pass [email protected]"}], "original_received":True, "original_authentication_evidence_id":"original-auth-id"}
|
||||||
|
|
||||||
|
def reply_evidence(self, rfc_message_id, *, message_id="reply-1", sender="[email protected]", route="[email protected]", references=None):
|
||||||
|
return {"account_email":"[email protected]", "message_id":message_id, "thread_id":"different-reply-thread", "label":"Scheduling/Intake", "headers":[{"name":"From", "value":sender}, {"name":"Delivered-To", "value":route}, {"name":"In-Reply-To", "value":rfc_message_id}, {"name":"References", "value":references if references is not None else "<[email protected]> " + rfc_message_id}], "authenticated_mailbox":True, "intake_label_present":True}
|
||||||
|
|
||||||
|
def prepare_booking(self):
|
||||||
|
self.create_pending()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle", "lease_seconds": 300})["lease_token"]
|
||||||
|
slots = [{"slot_id": f"slot-{index}", "intent": self.intent(index)} for index in range(3)]
|
||||||
|
offer = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":slots, "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||||
|
sent = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-1", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer", "subject":"Offer", "text_body":"Choose."})
|
||||||
|
self.invoke("accept_offer_selection", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slot_id":"slot-1", "transaction_token":offer["transaction_token"], "reply_evidence":self.reply_evidence(sent["outbound_rfc_message_id"])})
|
||||||
|
self.invoke("confirm_booking_availability", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "availability_evidence_id":"fresh", "observed_at":datetime.now(UTC).isoformat(), "busy_intervals":[]})
|
||||||
|
self.invoke("reserve_closing_capacity", {"transaction_id":"mcp-lifecycle", "lease_token":lease})
|
||||||
|
return lease
|
||||||
|
|
||||||
|
def test_mcp_decline_replacement_and_clarification_roundtrip(self):
|
||||||
|
self.adapter = Adapter(Ledger(Path(self.temp.name) / "rounds.sqlite3"), PolicyConfig(revision="rounds", fixed_sender="[email protected]", owner_email="[email protected]", delivery_alias="[email protected]", max_exchange_messages=8), self.client)
|
||||||
|
self.create_pending()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id":"mcp-lifecycle"})["lease_token"]
|
||||||
|
clarification = self.invoke("begin_clarification_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "gmail_thread_id":"thread"})
|
||||||
|
sent = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"clarify-1", "sender":"[email protected]", "requester":"[email protected]", "purpose":"clarification", "subject":"Clarify", "text_body":"Please clarify."})
|
||||||
|
self.invoke("record_bound_reply", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "reply_kind":"clarification", "transaction_token":clarification["transaction_token"], "reply_evidence":self.reply_evidence(sent["outbound_rfc_message_id"], message_id="clarify-reply")})
|
||||||
|
replacement = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"replacement-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||||
|
replacement_send = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-replacement", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer", "subject":"Options", "text_body":"Choose."})
|
||||||
|
self.invoke("record_bound_reply", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "reply_kind":"alternative", "transaction_token":replacement["transaction_token"], "reply_evidence":self.reply_evidence(replacement_send["outbound_rfc_message_id"], message_id="decline-1")})
|
||||||
|
next_round = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"next-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||||
|
self.assertEqual(next_round["round_number"], 3)
|
||||||
|
|
||||||
|
def test_owner_sent_forward_requires_exact_authenticated_cross_message_binding(self):
|
||||||
|
evidence = self.owner_sent_forward_evidence()
|
||||||
|
result = self.invoke("create_pending_negotiation", {"transaction_id":"mcp-lifecycle", "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":evidence})
|
||||||
|
self.assertEqual(result["transaction_id"], "mcp-lifecycle")
|
||||||
|
with self.adapter.ledger._session() as connection:
|
||||||
|
stored = connection.execute("SELECT policy_evidence_json FROM transactions WHERE id='mcp-lifecycle'").fetchone()["policy_evidence_json"]
|
||||||
|
bindings = connection.execute("SELECT COUNT(*) AS count FROM intake_message_bindings WHERE transaction_id='mcp-lifecycle'").fetchone()["count"]
|
||||||
|
self.assertEqual(bindings, 2)
|
||||||
|
self.assertNotIn("forward-gmail-id", stored)
|
||||||
|
self.assertNotIn("original-gmail-id", stored)
|
||||||
|
self.assertNotIn("[email protected]", stored)
|
||||||
|
replay = self.adapter.handle_request({"jsonrpc":"2.0", "id":"replay", "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"replayed-intake", "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":evidence}}})
|
||||||
|
self.assertIn("error", replay)
|
||||||
|
for key, value in (("original_received", False), ("original_thread_id", "different"), ("original_authentication_evidence_id", "different")):
|
||||||
|
bad = {**evidence, key:value}
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":key, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + key, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
for header_name, replacement in (("In-Reply-To", "<[email protected]>"), ("Authentication-Results", "mx.example.test; dkim=pass; spf=fail; dmarc=pass")):
|
||||||
|
bad = {**evidence, "headers":[{**item, "value":replacement} if item["name"] == header_name else item for item in evidence["headers"]], "original_headers":[{**item, "value":replacement} if item["name"] == header_name else item for item in evidence["original_headers"]]}
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":header_name, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + header_name, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
for suffix, original_headers in (("duplicate-auth", evidence["original_headers"] + [{"name":"Authentication-Results", "value":"mx.example.test; dkim=pass; spf=pass; dmarc=pass"}]), ("wrong-requester", [{**item, "value":"[email protected]"} if item["name"] == "From" else item for item in evidence["original_headers"]])):
|
||||||
|
bad = {**evidence, "original_headers":original_headers}
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":suffix, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + suffix, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
auth_variants = {
|
||||||
|
"untrusted-issuer": "mail.example.test; dkim=pass [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
"pass-substring": "mx.google.com; dkim=passive [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
"conflicting-result": "mx.google.com; dkim=pass [email protected]; dkim=fail [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
"wrong-alignment": "mx.google.com; dkim=pass [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
"dara-only-dkim-identity": "mx.google.com; dkim=pass header.s=20251104; spf=pass [email protected]; dmarc=pass header.from=gmail.com; dara=pass [email protected]",
|
||||||
|
"comment-pass-token": "mx.google.com; dkim=fail (dkim=pass [email protected]); spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
"comment-only-dkim-pass": "mx.google.com; (dkim=pass [email protected]); spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
"duplicate-method": "mx.google.com; dkim=pass [email protected]; dkim=pass [email protected]; spf=pass [email protected]; dmarc=pass header.from=gmail.com",
|
||||||
|
}
|
||||||
|
for suffix, value in auth_variants.items():
|
||||||
|
bad = {**evidence, "original_headers":[{**item, "value":value} if item["name"] == "Authentication-Results" else item for item in evidence["original_headers"]]}
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":suffix, "method":"tools/call", "params":{"name":"create_pending_negotiation", "arguments":{"transaction_id":"bad-" + suffix, "sender":"[email protected]", "expires_at":self.expiry.isoformat(), "intake_evidence":bad}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
|
||||||
|
def test_uncertain_calendar_and_zoom_operations_cannot_be_re_reserved(self):
|
||||||
|
lease = self.prepare_booking()
|
||||||
|
for provider, reserve, key in (("calendar", "reserve_calendar_event", "calendar-crash"), ("zoom", "reserve_zoom_meeting", "zoom-crash")):
|
||||||
|
self.invoke(reserve, {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key})
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key, "state":"uncertain"})
|
||||||
|
self.assertEqual(self.invoke(reserve, {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key})["operation_key"], key)
|
||||||
|
with self.assertRaises(AssertionError):
|
||||||
|
self.invoke(reserve, {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":key + "-retry"})
|
||||||
|
|
||||||
|
def test_complete_lifecycle_uses_mcp_and_requires_fresh_recheck(self):
|
||||||
|
self.create_pending()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle", "lease_seconds": 300})["lease_token"]
|
||||||
|
slots = [{"slot_id": f"slot-{index}", "intent": self.intent(index)} for index in range(3)]
|
||||||
|
offer = self.invoke("begin_offer_round", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "slots": slots, "busy_intervals": [], "observed_at": datetime.now(UTC).isoformat(), "gmail_thread_id": "gmail-thread-1"})
|
||||||
|
sent = self.invoke("prepare_postmark_send", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "offer-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "offer", "subject": "Choose a time", "text_body": "Choose one slot."})
|
||||||
|
self.invoke("accept_offer_selection", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "slot_id": "slot-1", "transaction_token": offer["transaction_token"], "reply_evidence":self.reply_evidence(sent["outbound_rfc_message_id"], message_id="requester-reply-1")})
|
||||||
|
stale = {"transaction_id": "mcp-lifecycle", "lease_token": lease, "availability_evidence_id": "availability-book-1", "observed_at": (datetime.now(UTC) - timedelta(minutes=6)).isoformat(), "busy_intervals": []}
|
||||||
|
self.assertIn("error", self.adapter.handle_request({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "confirm_booking_availability", "arguments": stale}}))
|
||||||
|
newly_busy = {**stale, "observed_at": datetime.now(UTC).isoformat(), "busy_intervals": [{"start_at": self.intent(1)["start_at"], "end_at": self.intent(1)["end_at"]}]}
|
||||||
|
self.assertIn("error", self.adapter.handle_request({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "confirm_booking_availability", "arguments": newly_busy}}))
|
||||||
|
self.invoke("confirm_booking_availability", {**stale, "observed_at": datetime.now(UTC).isoformat()})
|
||||||
|
self.invoke("reserve_closing_capacity", {"transaction_id": "mcp-lifecycle", "lease_token": lease})
|
||||||
|
self.invoke("reserve_calendar_event", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "calendar-1"})
|
||||||
|
self.invoke("reserve_zoom_meeting", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "zoom-1"})
|
||||||
|
# Zoom completion precedes Calendar completion because Calendar must
|
||||||
|
# contain the exact verified join URL.
|
||||||
|
for operation, provider_id in (("zoom-1", "zoom-meeting-1"), ("calendar-1", "calendar-event-1")):
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": operation, "state": "accepted", "provider_id": provider_id})
|
||||||
|
readback = ({"event_id":"calendar-event-1", "start_time":self.intent(1)["start_at"], "end_time":self.intent(1)["end_at"], "attendees":["[email protected]", "[email protected]"], "status":"confirmed", "visibility":"private", "location":"https://zoom.test/j/zoom-meeting-1", "description":"https://zoom.test/j/zoom-meeting-1", "guests_can_modify":None} if operation == "calendar-1" else {"meeting_id":"zoom-meeting-1", "join_url":"https://zoom.test/j/zoom-meeting-1", "start_time":self.intent(1)["start_at"], "duration_minutes":60, "timezone":"UTC", "host":"[email protected]"})
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": operation, "state": "completed", "provider_id": provider_id, "provider_readback": readback})
|
||||||
|
self.assertEqual(self.invoke("complete_booking", {"transaction_id": "mcp-lifecycle", "lease_token": lease})["status"], "completed")
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "confirmation-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "confirmation", "subject": "Confirmed", "text_body": "Your meeting is confirmed."})
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id": "mcp-lifecycle", "lease_token": lease, "operation_key": "owner-summary-1", "sender": "[email protected]", "requester": "[email protected]", "purpose": "owner_summary", "subject": "Booked", "text_body": "A meeting was booked."})
|
||||||
|
status = self.invoke("get_transaction_status", {"transaction_id": "mcp-lifecycle"})
|
||||||
|
self.assertEqual((status["state"], status["exchange_count"], len(self.client.calls)), ("completed", 4, 3))
|
||||||
|
self.assertEqual(status["exchange_count"], status["max_exchanges"])
|
||||||
|
self.assertEqual(self.client.calls[-1]["recipient"], "[email protected]")
|
||||||
|
|
||||||
|
def test_closing_messages_are_role_specific_idempotent_and_fenced(self):
|
||||||
|
self.test_complete_lifecycle_uses_mcp_and_requires_fresh_recheck()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle", "lease_seconds": 300})
|
||||||
|
self.assertEqual(lease, {})
|
||||||
|
# The first lease remains valid; a second caller cannot use a fabricated token.
|
||||||
|
with self.assertRaises(AssertionError):
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":"takeover","operation_key":"confirmation-2","sender":"[email protected]","requester":"[email protected]","purpose":"confirmation","subject":"x","text_body":"x"})
|
||||||
|
# Replaying the durable operation key is a restart-safe read, but another closing purpose cannot be duplicated.
|
||||||
|
row = self.invoke("get_transaction_status", {"transaction_id": "mcp-lifecycle"})
|
||||||
|
with self.adapter.ledger._session() as connection:
|
||||||
|
active = connection.execute("SELECT lease_token FROM transactions WHERE id='mcp-lifecycle'").fetchone()["lease_token"]
|
||||||
|
replay = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":active,"operation_key":"confirmation-1","sender":"[email protected]","requester":"[email protected]","purpose":"confirmation","subject":"Confirmed","text_body":"Your meeting is confirmed."})
|
||||||
|
self.assertEqual(replay["provider_id"], "postmark-2")
|
||||||
|
with self.assertRaises(AssertionError):
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":active,"operation_key":"owner-summary-2","sender":"[email protected]","requester":"[email protected]","purpose":"owner_summary","subject":"Again","text_body":"Again"})
|
||||||
|
with self.assertRaises(AssertionError):
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle","lease_token":active,"operation_key":"wrong-owner","sender":"[email protected]","requester":"[email protected]","purpose":"owner_summary","subject":"Wrong","text_body":"Wrong"})
|
||||||
|
self.assertEqual(row["exchange_count"], 4)
|
||||||
|
|
||||||
|
def test_postmark_rejects_arbitrary_content_and_renders_durable_offer(self):
|
||||||
|
self.create_pending()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id": "mcp-lifecycle"})["lease_token"]
|
||||||
|
offer = self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"slot-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"thread"})
|
||||||
|
bad = self.adapter.handle_request({"jsonrpc":"2.0", "id":1, "method":"tools/call", "params":{"name":"prepare_postmark_send", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"mail", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer", "subject":"injected", "text_body":"injected"}}})
|
||||||
|
self.assertIn("error", bad)
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"mail", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer"})
|
||||||
|
self.assertEqual(self.client.calls[-1]["subject"], "Scheduling options")
|
||||||
|
self.assertIn("slot-0", self.client.calls[-1]["text_body"])
|
||||||
|
self.assertEqual(offer["round_number"], 1)
|
||||||
|
|
||||||
|
def test_outbound_rfc_lineage_is_server_generated_restart_safe_and_reply_bound(self):
|
||||||
|
self.create_pending()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id":"mcp-lifecycle", "lease_seconds":300})["lease_token"]
|
||||||
|
self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"slot-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"intake-thread"})
|
||||||
|
legacy = self.adapter.handle_request({"jsonrpc":"2.0", "id":"legacy", "method":"tools/call", "params":{"name":"get_active_round_binding", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease}}})
|
||||||
|
self.assertIn("error", legacy)
|
||||||
|
sent = self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-rfc", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer"})
|
||||||
|
binding = self.invoke("get_active_round_binding", {"transaction_id":"mcp-lifecycle", "lease_token":lease})
|
||||||
|
self.assertEqual(binding["outbound_rfc_message_id"], sent["outbound_rfc_message_id"])
|
||||||
|
self.assertNotEqual(binding["outbound_rfc_message_id"], sent["provider_id"])
|
||||||
|
self.assertEqual(self.client.calls[-1]["rfc_message_id"], binding["outbound_rfc_message_id"])
|
||||||
|
self.assertIn("Petra Scheduling", self.client.calls[-1]["text_body"])
|
||||||
|
restarted = Adapter(Ledger(Path(self.temp.name) / "ledger.sqlite3"), self.adapter.policy, self.client)
|
||||||
|
recovered = json.loads(restarted.handle_request({"jsonrpc":"2.0", "id":1, "method":"tools/call", "params":{"name":"get_active_round_binding", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease}}})["result"]["content"][0]["text"])
|
||||||
|
self.assertEqual(recovered, binding)
|
||||||
|
|
||||||
|
def rejected(name, evidence):
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":name, "method":"tools/call", "params":{"name":"accept_offer_selection", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease, "slot_id":"slot-1", "transaction_token":binding["transaction_token"], "reply_evidence":evidence}}})
|
||||||
|
self.assertIn("error", response, response)
|
||||||
|
|
||||||
|
rejected("wrong-sender", self.reply_evidence(binding["outbound_rfc_message_id"], sender="[email protected]"))
|
||||||
|
rejected("wrong-route", self.reply_evidence(binding["outbound_rfc_message_id"], route="[email protected]"))
|
||||||
|
rejected("missing-reference", self.reply_evidence(binding["outbound_rfc_message_id"], references="<[email protected]>"))
|
||||||
|
rejected("wrong-rfc", self.reply_evidence("<[email protected]>"))
|
||||||
|
rejected("api-id-as-rfc", self.reply_evidence(sent["provider_id"]))
|
||||||
|
|
||||||
|
accepted = self.invoke("accept_offer_selection", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slot_id":"slot-1", "transaction_token":binding["transaction_token"], "reply_evidence":self.reply_evidence(binding["outbound_rfc_message_id"], message_id="unique-reply")})
|
||||||
|
self.assertEqual(accepted["slot_id"], "slot-1")
|
||||||
|
with self.adapter.ledger._session() as connection:
|
||||||
|
stored = connection.execute("SELECT message_digest, thread_digest FROM reply_message_bindings").fetchone()
|
||||||
|
self.assertNotIn("unique-reply", stored["message_digest"])
|
||||||
|
self.assertNotIn("different-reply-thread", stored["thread_digest"])
|
||||||
|
|
||||||
|
def test_active_rfc_reply_binding_fails_closed_when_round_expires(self):
|
||||||
|
self.create_pending()
|
||||||
|
lease = self.invoke("claim_transaction", {"transaction_id":"mcp-lifecycle", "lease_seconds":300})["lease_token"]
|
||||||
|
self.invoke("begin_offer_round", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "slots":[{"slot_id":f"slot-{i}", "intent":self.intent(i)} for i in range(3)], "busy_intervals":[], "observed_at":datetime.now(UTC).isoformat(), "gmail_thread_id":"intake-thread"})
|
||||||
|
self.invoke("prepare_postmark_send", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"offer-expired", "sender":"[email protected]", "requester":"[email protected]", "purpose":"offer"})
|
||||||
|
with self.adapter.ledger._session() as connection:
|
||||||
|
connection.execute("UPDATE workflow_rounds SET expires_at=? WHERE transaction_id=?", ((datetime.now(UTC) - timedelta(seconds=1)).isoformat(), "mcp-lifecycle"))
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":"expired", "method":"tools/call", "params":{"name":"get_active_round_binding", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease}}})
|
||||||
|
self.assertIn("error", response)
|
||||||
|
|
||||||
|
def test_provider_completion_rejects_mismatches_and_persists_no_pii(self):
|
||||||
|
lease = self.prepare_booking()
|
||||||
|
self.invoke("reserve_zoom_meeting", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"zoom"})
|
||||||
|
self.invoke("reserve_calendar_event", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"calendar"})
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"zoom", "state":"accepted", "provider_id":"zoom-1"})
|
||||||
|
zoom = {"meeting_id":"zoom-1", "join_url":"https://zoom.test/j/zoom-1", "start_time":self.intent(1)["start_at"], "duration_minutes":60, "timezone":"UTC", "host":"[email protected]"}
|
||||||
|
def rejected(operation, readback):
|
||||||
|
response = self.adapter.handle_request({"jsonrpc":"2.0", "id":operation, "method":"tools/call", "params":{"name":"record_provider_outcome", "arguments":{"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":operation, "state":"completed", "provider_id":"zoom-1" if operation == "zoom" else "calendar-1", "provider_readback":readback}}})
|
||||||
|
self.assertIn("error", response, response)
|
||||||
|
rejected("zoom", {**zoom, "start_time":self.intent(0)["start_at"]})
|
||||||
|
rejected("zoom", {key:value for key,value in zoom.items() if key != "host"})
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"zoom", "state":"completed", "provider_id":"zoom-1", "provider_readback":zoom})
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"calendar", "state":"accepted", "provider_id":"calendar-1"})
|
||||||
|
calendar = {"event_id":"calendar-1", "start_time":self.intent(1)["start_at"], "end_time":self.intent(1)["end_at"], "attendees":["[email protected]", "[email protected]"], "status":"confirmed", "visibility":"private", "location":"https://zoom.test/j/zoom-1", "description":"", "guests_can_modify":None}
|
||||||
|
rejected("calendar", {**calendar, "attendees":["[email protected]", "[email protected]"]})
|
||||||
|
rejected("calendar", {**calendar, "visibility":"default"})
|
||||||
|
rejected("calendar", {**calendar, "end_time":self.intent(0)["end_at"]})
|
||||||
|
rejected("calendar", {**calendar, "location":"https://zoom.test/j/a-different-meeting"})
|
||||||
|
rejected("calendar", {key:value for key,value in calendar.items() if key != "location"})
|
||||||
|
self.invoke("record_provider_outcome", {"transaction_id":"mcp-lifecycle", "lease_token":lease, "operation_key":"calendar", "state":"completed", "provider_id":"calendar-1", "provider_readback":calendar})
|
||||||
|
with self.adapter.ledger._session() as connection:
|
||||||
|
stored = connection.execute("SELECT provider_evidence_json FROM provider_operations WHERE operation_key='calendar'").fetchone()["provider_evidence_json"]
|
||||||
|
self.assertNotIn("[email protected]", stored)
|
||||||
|
self.assertNotIn("https://zoom.test", stored)
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.gmail_validation import SanitizedGmailMetadata
|
||||||
|
from scheduling_core.orchestration import CalendarEvidence, EvidenceError, ProviderConfirmation, require_confirmations, validate_authenticated_intake, validate_bound_reply, validate_calendar_availability_response
|
||||||
|
from scheduling_core.policy import PolicyConfig, PolicyViolation, evaluate_intent
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class OrchestrationSimulationTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.happy = json.loads((ROOT / "fixtures" / "orchestration" / "happy-path.json").read_text())
|
||||||
|
self.failures = json.loads((ROOT / "fixtures" / "orchestration" / "failure-cases.json").read_text())
|
||||||
|
self.now = datetime.fromisoformat(self.happy["now"].replace("Z", "+00:00"))
|
||||||
|
self.config = PolicyConfig(revision="simulation", fixed_sender="[email protected]")
|
||||||
|
|
||||||
|
def test_happy_path_is_authenticated_fresh_and_confirmed(self):
|
||||||
|
gmail = self.happy["gmail"]
|
||||||
|
metadata = SanitizedGmailMetadata(gmail["message_id"], gmail["thread_id"], gmail["sender"], gmail["delivered_to"], gmail["label"], authenticated=True, forwarded_requester="[email protected]")
|
||||||
|
validate_authenticated_intake(metadata, authenticated=gmail["authenticated"], expected_sender="[email protected]", route="[email protected]", intake_label="intake")
|
||||||
|
calendar_payload = dict(self.happy["calendar"])
|
||||||
|
calendar_payload["busy_intervals"] = tuple(calendar_payload["busy_intervals"])
|
||||||
|
calendar = CalendarEvidence(**calendar_payload)
|
||||||
|
calendar.require_fresh_after(self.now)
|
||||||
|
checked = evaluate_intent(self.happy["intent"], self.config, self.now, calendar.busy_intervals)
|
||||||
|
confirmations = [ProviderConfirmation(**item) for item in self.happy["confirmations"]]
|
||||||
|
self.assertEqual(require_confirmations(confirmations, checked.transaction_id)["zoom"].provider_id, "zoom-meeting-1")
|
||||||
|
|
||||||
|
def test_fail_closed_on_auth_stale_calendar_or_missing_zoom(self):
|
||||||
|
gmail = self.happy["gmail"]
|
||||||
|
metadata = SanitizedGmailMetadata(gmail["message_id"], gmail["thread_id"], gmail["sender"], gmail["delivered_to"], gmail["label"], authenticated=True, forwarded_requester="[email protected]")
|
||||||
|
with self.assertRaises(EvidenceError):
|
||||||
|
validate_authenticated_intake(metadata, authenticated=self.failures["unauthenticated_gmail"]["authenticated"], expected_sender="[email protected]", route="[email protected]", intake_label="intake")
|
||||||
|
calendar = CalendarEvidence("calendar-1", self.failures["stale_calendar"]["observed_at"], "2031-01-01T18:00:00Z", "2031-01-01T19:00:00Z", ())
|
||||||
|
with self.assertRaises(EvidenceError):
|
||||||
|
calendar.require_fresh_after(self.now)
|
||||||
|
with self.assertRaises(EvidenceError):
|
||||||
|
require_confirmations([ProviderConfirmation(**item) for item in self.failures["missing_zoom_confirmation"]], "simulation-tx")
|
||||||
|
|
||||||
|
def test_reply_requires_authenticated_thread_lineage(self):
|
||||||
|
reply = SanitizedGmailMetadata("reply-1", "thread-1", "[email protected]", "[email protected]", "intake", "outbound-message-1", ("outbound-message-1",), "token", True)
|
||||||
|
self.assertEqual(validate_bound_reply(reply, authenticated=True, bound_requester="[email protected]", route="[email protected]", intake_label="intake", outbound_rfc_message_id="outbound-message-1", transaction_token="token").message_id, "reply-1")
|
||||||
|
with self.assertRaises(EvidenceError):
|
||||||
|
validate_bound_reply(reply, authenticated=False, bound_requester="[email protected]", route="[email protected]", intake_label="intake", outbound_rfc_message_id="outbound-message-1", transaction_token="token")
|
||||||
|
|
||||||
|
def test_canonical_policy_rejections_remain_local_and_deterministic(self):
|
||||||
|
raw = dict(self.happy["intent"])
|
||||||
|
raw["start_at"] = (self.now + timedelta(hours=2)).isoformat()
|
||||||
|
raw["end_at"] = (self.now + timedelta(hours=3)).isoformat()
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(raw, self.config, self.now, [])
|
||||||
|
|
||||||
|
def test_calendar_response_requires_complete_error_free_coverage(self):
|
||||||
|
busy = validate_calendar_availability_response(requested_calendar_ids=("primary",), requested_start="2031-01-01T18:00:00Z", requested_end="2031-01-01T19:00:00Z", request_started_at=self.now, response_received_at=self.now, calendars=({"calendar_id":"primary", "busy":[], "errors":[]},))
|
||||||
|
self.assertEqual(busy, ())
|
||||||
|
with self.assertRaises(EvidenceError):
|
||||||
|
validate_calendar_availability_response(requested_calendar_ids=("primary",), requested_start="2031-01-01T18:00:00Z", requested_end="2031-01-01T19:00:00Z", request_started_at=self.now, response_received_at=self.now, calendars=({"calendar_id":"primary", "busy":[], "errors":["denied"]},))
|
||||||
|
raw = dict(self.happy["intent"])
|
||||||
|
raw["sender"] = "[email protected]"
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(raw, self.config, self.now, [])
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.gmail_validation import GmailValidationError, SanitizedGmailMetadata, validate_intake, validate_reply_lineage, validate_owner_forward_boundary
|
||||||
|
from scheduling_core.ledger import Ledger, OperationState
|
||||||
|
from scheduling_core.policy import PolicyConfig, PolicyViolation, evaluate_intent, load_policy_config, validate_offer_slots
|
||||||
|
from scheduling_core.postmark import PostmarkHttpsClient, ProviderDisabled
|
||||||
|
|
||||||
|
|
||||||
|
NOW = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||||
|
CONFIG = PolicyConfig(revision="test", fixed_sender="[email protected]")
|
||||||
|
|
||||||
|
|
||||||
|
def intent(number="1", **overrides):
|
||||||
|
data = {"transaction_id": f"tx-{number}", "requester": "[email protected]", "sender": "[email protected]", "start_at": f"2031-01-0{number}T18:00:00Z", "end_at": f"2031-01-0{number}T19:00:00Z", "expires_at": "2031-01-02T00:00:00Z", "authentication_evidence_id": "auth-id", "availability_evidence_id": "busy-id"}
|
||||||
|
data.update(overrides)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class PolicyAndRecoveryTests(unittest.TestCase):
|
||||||
|
def test_duration_horizon_workweek_and_offer_count(self):
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(intent(end_at="2031-01-01T19:20:00Z"), CONFIG, NOW, [])
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
evaluate_intent(intent(start_at="2031-01-23T18:00:00Z", end_at="2031-01-23T19:00:00Z"), CONFIG, NOW, [])
|
||||||
|
with self.assertRaises(PolicyViolation):
|
||||||
|
validate_offer_slots([intent()], CONFIG, NOW, [])
|
||||||
|
slots = [intent("1"), intent("2"), intent("3")]
|
||||||
|
self.assertEqual(len(validate_offer_slots(slots, CONFIG, NOW, [])), 3)
|
||||||
|
|
||||||
|
def test_dst_offsets_are_evaluated_in_denver_local_work_hours(self):
|
||||||
|
before_spring_forward = datetime(2031, 3, 7, 16, tzinfo=UTC)
|
||||||
|
spring = intent("1", start_at="2031-03-10T15:00:00Z", end_at="2031-03-10T16:00:00Z", expires_at="2031-03-10T15:30:00Z")
|
||||||
|
self.assertEqual(evaluate_intent(spring, CONFIG, before_spring_forward, []).start_at, "2031-03-10T15:00:00Z")
|
||||||
|
before_fall_back = datetime(2031, 10, 31, 16, 30, tzinfo=UTC)
|
||||||
|
fall = intent("2", start_at="2031-11-03T16:00:00Z", end_at="2031-11-03T17:00:00Z", expires_at="2031-11-03T16:20:00Z")
|
||||||
|
self.assertEqual(evaluate_intent(fall, CONFIG, before_fall_back, []).start_at, "2031-11-03T16:00:00Z")
|
||||||
|
|
||||||
|
def test_gmail_metadata_is_bound_without_retaining_headers(self):
|
||||||
|
intake = SanitizedGmailMetadata("m1", "t1", "[email protected]", "[email protected]", "intake", authenticated=True, forwarded_requester="[email protected]")
|
||||||
|
self.assertEqual(validate_intake(intake, "[email protected]", "[email protected]", "intake").message_id, "m1")
|
||||||
|
reply = SanitizedGmailMetadata("m2", "t1", "[email protected]", "[email protected]", "intake", "outbound-1", ("outbound-1",), "token", True)
|
||||||
|
self.assertEqual(validate_reply_lineage(reply, "[email protected]", "[email protected]", "intake", "outbound-1", "token").message_id, "m2")
|
||||||
|
with self.assertRaises(GmailValidationError):
|
||||||
|
validate_reply_lineage(reply, "[email protected]", "[email protected]", "intake", "other", "token")
|
||||||
|
|
||||||
|
def test_owner_forward_boundary_uses_canonical_route_and_provider_context(self):
|
||||||
|
headers = (("From", "[email protected]"), ("To", "[email protected]"))
|
||||||
|
validate_owner_forward_boundary(headers, "[email protected]", "[email protected]", authenticated_mailbox=True, intake_label_present=True)
|
||||||
|
with self.assertRaises(GmailValidationError):
|
||||||
|
validate_owner_forward_boundary(headers, "[email protected]", "[email protected]", authenticated_mailbox=False, intake_label_present=True)
|
||||||
|
|
||||||
|
def test_restart_recovers_expired_lease_and_uncertain_operation(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
path = Path(directory) / "ledger.sqlite3"
|
||||||
|
ledger = Ledger(path)
|
||||||
|
checked = evaluate_intent(intent(), CONFIG, NOW, [])
|
||||||
|
ledger.create_transaction(checked, CONFIG.revision, CONFIG.max_exchange_messages)
|
||||||
|
self.assertIsNotNone(ledger.claim("tx-1", 1, NOW))
|
||||||
|
# Simulate a new process after the lease has elapsed.
|
||||||
|
restarted = Ledger(path)
|
||||||
|
self.assertIsNotNone(restarted.claim("tx-1", 1, NOW + timedelta(seconds=2)))
|
||||||
|
lease = restarted.claim("tx-1", 60, NOW + timedelta(seconds=4)).lease_token
|
||||||
|
restarted.record_postmark_send("tx-1", lease, "op-1", "[email protected]", "[email protected]", NOW + timedelta(seconds=4))
|
||||||
|
restarted.transition_operation("tx-1", lease, "op-1", OperationState.UNCERTAIN)
|
||||||
|
self.assertEqual(restarted.operations_needing_reconciliation()[0]["operation_key"], "op-1")
|
||||||
|
|
||||||
|
def test_existing_postmark_operation_remains_idempotent_after_expiry(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||||
|
checked = evaluate_intent(intent(), CONFIG, NOW, [])
|
||||||
|
ledger.create_transaction(checked, CONFIG.revision, CONFIG.max_exchange_messages)
|
||||||
|
lease = ledger.claim("tx-1", 60, NOW).lease_token
|
||||||
|
first = ledger.record_postmark_send("tx-1", lease, "send-1", "[email protected]", "[email protected]", NOW)
|
||||||
|
expired_lease = ledger.claim("tx-1", 60, datetime(2031, 1, 3, tzinfo=UTC)).lease_token
|
||||||
|
same = ledger.record_postmark_send("tx-1", expired_lease, "send-1", "[email protected]", "[email protected]", datetime(2031, 1, 3, tzinfo=UTC))
|
||||||
|
self.assertEqual(first["id"], same["id"])
|
||||||
|
|
||||||
|
def test_https_client_cannot_call_without_explicit_enablement(self):
|
||||||
|
client = PostmarkHttpsClient(lambda: "not-used")
|
||||||
|
with self.assertRaises(ProviderDisabled):
|
||||||
|
client.status("message-id")
|
||||||
|
|
||||||
|
def test_reviewed_policy_file_loads_approved_defaults(self):
|
||||||
|
config = load_policy_config(Path("config/scheduling-policy.json"), "[email protected]")
|
||||||
|
self.assertEqual(config.minimum_notice_minutes, 24 * 60)
|
||||||
|
self.assertEqual(config.offer_count, 3)
|
||||||
|
self.assertTrue(config.guests_can_invite_others)
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.ledger import Ledger
|
||||||
|
from scheduling_core.policy import PolicyConfig, evaluate_intent
|
||||||
|
from scheduling_core.postmark import BoundMessage, PostmarkAdapter
|
||||||
|
from scripts.verify_postmark_readonly import build_readonly_request
|
||||||
|
|
||||||
|
|
||||||
|
class CapturingClient:
|
||||||
|
def __init__(self): self.calls = []
|
||||||
|
def send(self, **kwargs): self.calls.append(kwargs); return "postmark-id"
|
||||||
|
|
||||||
|
|
||||||
|
class PostmarkExecutionTests(unittest.TestCase):
|
||||||
|
def test_owner_delivery_test_is_bound_to_one_sender_recipient_and_exchange(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||||
|
transaction_id = ledger.create_authorized_owner_delivery_test(
|
||||||
|
transaction_id="authorized-owner-delivery-test-unit-v1",
|
||||||
|
sender="Petra - Scheduling <[email protected]>",
|
||||||
|
recipient="[email protected]",
|
||||||
|
expires_at=datetime(2031, 1, 1, tzinfo=UTC),
|
||||||
|
)
|
||||||
|
lease = ledger.claim(transaction_id, 60, datetime(2030, 12, 31, tzinfo=UTC)).lease_token
|
||||||
|
first = ledger.record_postmark_send(transaction_id, lease, "test-send", "Petra - Scheduling <[email protected]>", "[email protected]", now=datetime(2030, 12, 31, tzinfo=UTC))
|
||||||
|
self.assertEqual(first["state"], "pending")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
ledger.record_postmark_send(transaction_id, lease, "second-send", "Petra - Scheduling <[email protected]>", "[email protected]", now=datetime(2030, 12, 31, tzinfo=UTC))
|
||||||
|
|
||||||
|
def test_owner_reply_evidence_is_digest_only_and_not_a_transaction(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||||
|
ledger.record_owner_transport_evidence(
|
||||||
|
"authorized-owner-delivery-test-gmail-reply-v1",
|
||||||
|
{"message_id": "m", "thread_id": "t", "sender": "[email protected]", "recipient": "[email protected]", "observed_at": "2030-01-01T00:00:00Z"},
|
||||||
|
)
|
||||||
|
with ledger._session() as connection:
|
||||||
|
evidence = connection.execute("SELECT evidence_digest FROM test_evidence").fetchone()
|
||||||
|
transactions = connection.execute("SELECT COUNT(*) AS count FROM transactions").fetchone()
|
||||||
|
self.assertIsNotNone(evidence["evidence_digest"])
|
||||||
|
self.assertEqual(transactions["count"], 0)
|
||||||
|
|
||||||
|
def test_readonly_request_uses_the_documented_server_token_contract(self):
|
||||||
|
request = build_readonly_request("/server", "dummy-token")
|
||||||
|
self.assertEqual(request.full_url, "https://api.postmarkapp.com/server")
|
||||||
|
self.assertEqual(request.get_header("Accept"), "application/json")
|
||||||
|
self.assertEqual(request.get_header("X-postmark-server-token"), "dummy-token")
|
||||||
|
|
||||||
|
def test_bound_execution_forces_message_stream_contract(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
ledger = Ledger(Path(directory) / "ledger.sqlite3")
|
||||||
|
config = PolicyConfig(revision="test", fixed_sender="[email protected]")
|
||||||
|
now = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||||
|
intent = evaluate_intent({"transaction_id":"tx","requester":"[email protected]","sender":"[email protected]","start_at":"2031-01-01T18:00:00Z","end_at":"2031-01-01T19:00:00Z","expires_at":"2031-01-02T00:00:00Z","authentication_evidence_id":"a","availability_evidence_id":"b"}, config, now, [])
|
||||||
|
ledger.create_transaction(intent, config.revision, config.max_exchange_messages)
|
||||||
|
client = CapturingClient()
|
||||||
|
lease = ledger.claim("tx", 60).lease_token
|
||||||
|
result = PostmarkAdapter(ledger, client).send_bound_message("tx", lease, "send", "[email protected]", "[email protected]", BoundMessage("Offer", "Select a slot."))
|
||||||
|
self.assertEqual(result, "postmark-id")
|
||||||
|
self.assertEqual(client.calls[0]["reply_to"], "[email protected]")
|
||||||
|
self.assertEqual(client.calls[0]["recipient"], "[email protected]")
|
||||||
|
self.assertRegex(client.calls[0]["rfc_message_id"], r"^<sched-[0-9a-f-]+@example\.test>$")
|
||||||
|
operation = ledger.operation_for_key("send")
|
||||||
|
self.assertEqual(operation["provider_id"], "postmark-id")
|
||||||
|
self.assertEqual(operation["rfc_message_id"], client.calls[0]["rfc_message_id"])
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import unittest
|
||||||
|
from datetime import UTC,datetime
|
||||||
|
from scheduling_core.policy import PolicyConfig,PolicyViolation
|
||||||
|
from scheduling_core.slotting import compliant_slots
|
||||||
|
class SlotTests(unittest.TestCase):
|
||||||
|
def test_offers_three_default_duration_slots_and_rejects_no_availability(self):
|
||||||
|
c=PolicyConfig(revision='x',fixed_sender='[email protected]'); now=datetime(2030,12,31,16,tzinfo=UTC)
|
||||||
|
slots=compliant_slots(transaction_id='x',requester='[email protected]',sender='[email protected]',authentication_evidence_id='a',availability_evidence_id='b',now=now,busy_intervals=[],config=c)
|
||||||
|
self.assertEqual(len(slots),3)
|
||||||
|
blocked=[{'start_at':'2031-01-01T00:00:00Z','end_at':'2031-01-22T00:00:00Z'}]
|
||||||
|
with self.assertRaises(PolicyViolation): compliant_slots(transaction_id='y',requester='[email protected]',sender='[email protected]',authentication_evidence_id='a',availability_evidence_id='b',now=now,busy_intervals=blocked,config=c)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import patch
|
||||||
|
from scheduling_core.mcp_stdio import Adapter
|
||||||
|
|
||||||
|
class SupervisedSendScopeTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.scope = {'transaction_id':'approved-test', 'requester':'[email protected]', 'owner':'[email protected]'}
|
||||||
|
self.policy = SimpleNamespace(owner_email='[email protected]')
|
||||||
|
self.adapter = Adapter(object(), self.policy, object(), supervised_send_scope=self.scope)
|
||||||
|
self.args = {'transaction_id':'approved-test', 'lease_token':'lease', 'operation_key':'operation', 'sender':'[email protected]', 'requester':'[email protected]', 'purpose':'offer'}
|
||||||
|
|
||||||
|
def test_other_transaction_and_recipient_rejected_before_ledger_or_transport(self):
|
||||||
|
for change in ({'transaction_id':'other'}, {'requester':'[email protected]'}, {'purpose':'owner_summary'}):
|
||||||
|
with self.subTest(change=change), patch('scheduling_core.mcp_stdio.SchedulingWorkflow', side_effect=AssertionError('Ledger must not be accessed')):
|
||||||
|
with self.assertRaisesRegex(ValueError, 'outside the approved'):
|
||||||
|
self.adapter.call('prepare_postmark_send', {**self.args, **change})
|
||||||
|
|
||||||
|
def test_approved_requester_and_owner_continue_to_existing_safeguards(self):
|
||||||
|
for change in ({}, {'purpose':'confirmation'}, {'purpose':'owner_summary','requester':'[email protected]'}):
|
||||||
|
with self.subTest(change=change), patch('scheduling_core.mcp_stdio.SchedulingWorkflow', side_effect=RuntimeError('Existing safeguards reached')):
|
||||||
|
with self.assertRaisesRegex(RuntimeError, 'Existing safeguards reached'):
|
||||||
|
self.adapter.call('prepare_postmark_send', {**self.args, **change})
|
||||||
|
|
||||||
|
def test_incomplete_scope_and_different_owner_fail_closed(self):
|
||||||
|
for scope in ({'transaction_id':'approved-test'}, {**self.scope,'owner':'[email protected]'}):
|
||||||
|
with self.subTest(scope=scope), self.assertRaises(ValueError):
|
||||||
|
Adapter(object(), self.policy, object(), supervised_send_scope=scope)
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from scheduling_core.ledger import Ledger, OperationState
|
||||||
|
from scheduling_core.policy import PolicyConfig, evaluate_intent
|
||||||
|
from scheduling_core.workflow import SchedulingWorkflow, WorkflowError
|
||||||
|
|
||||||
|
|
||||||
|
NOW = datetime(2030, 12, 31, 16, tzinfo=UTC)
|
||||||
|
CONFIG = PolicyConfig(revision="test", fixed_sender="[email protected]", max_exchange_messages=8)
|
||||||
|
|
||||||
|
|
||||||
|
def intent():
|
||||||
|
return evaluate_intent({"transaction_id":"workflow-tx","requester":"[email protected]","sender":"[email protected]","start_at":"2031-01-01T18:00:00Z","end_at":"2031-01-01T19:00:00Z","expires_at":"2031-01-02T00:00:00Z","authentication_evidence_id":"auth","availability_evidence_id":"calendar"}, CONFIG, NOW, [])
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.ledger = Ledger(Path(self.temp.name) / "ledger.sqlite3")
|
||||||
|
self.ledger.create_transaction(intent(), CONFIG.revision, CONFIG.max_exchange_messages, owner="[email protected]")
|
||||||
|
self.workflow = SchedulingWorkflow(self.ledger)
|
||||||
|
|
||||||
|
def tearDown(self): self.temp.cleanup()
|
||||||
|
|
||||||
|
def test_offer_selection_booking_and_confirmation(self):
|
||||||
|
slots = tuple({"slot_id": name, "start_at":"2031-01-01T18:00:00Z", "end_at":"2031-01-01T19:00:00Z", "expires_at":"2031-01-02T00:00:00Z", "availability_evidence_id":"calendar", "authentication_evidence_id":"auth"} for name in ("slot-a", "slot-b", "slot-c"))
|
||||||
|
round_data = self.workflow.begin_round("workflow-tx", slots, NOW + timedelta(hours=2), "gmail-thread", NOW)
|
||||||
|
self.workflow.bind_outbound("workflow-tx", round_data["round_number"], "postmark-outbound")
|
||||||
|
self.assertEqual(self.workflow.accept_selection("workflow-tx", slot_id="slot-b", transaction_token=round_data["transaction_token"], thread_id="gmail-thread", in_reply_to="postmark-outbound", references=("postmark-outbound",), now=NOW), "slot-b")
|
||||||
|
lease = self.ledger.claim("workflow-tx", 60, NOW).lease_token
|
||||||
|
self.ledger.record_booking_evidence("workflow-tx", lease, {"availability_evidence_id":"fresh", "observed_at":NOW.isoformat(), "slot_id":"slot-b", "start_at":"2031-01-01T18:00:00Z", "end_at":"2031-01-01T19:00:00Z"}, NOW)
|
||||||
|
self.ledger.reserve_closing_capacity("workflow-tx", lease, NOW)
|
||||||
|
self.ledger.reserve_booking_operation("workflow-tx", lease, "calendar-op", "calendar")
|
||||||
|
self.ledger.reserve_booking_operation("workflow-tx", lease, "zoom-op", "zoom")
|
||||||
|
self.ledger.transition_operation("workflow-tx", lease, "zoom-op", OperationState.ACCEPTED, "zoom-id")
|
||||||
|
import hashlib
|
||||||
|
digest = lambda value: hashlib.sha256(value.strip().casefold().encode()).hexdigest()
|
||||||
|
self.ledger.transition_operation("workflow-tx", lease, "zoom-op", OperationState.COMPLETED, "zoom-id", {"meeting_id":"zoom-id", "join_url_digest":digest("https://zoom.test/j/zoom-id"), "start_time":"2031-01-01T18:00:00+00:00", "duration_minutes":60, "timezone":"UTC", "host_fingerprint":digest("[email protected]")})
|
||||||
|
self.ledger.transition_operation("workflow-tx", lease, "calendar-op", OperationState.ACCEPTED, "calendar-id")
|
||||||
|
self.ledger.transition_operation("workflow-tx", lease, "calendar-op", OperationState.COMPLETED, "calendar-id", {"event_id":"calendar-id", "start_time":"2031-01-01T18:00:00Z", "end_time":"2031-01-01T19:00:00Z", "attendee_fingerprints":sorted([digest("[email protected]"), digest("[email protected]")]), "status":"confirmed", "visibility":"private", "join_url_candidates":[digest("https://zoom.test/j/zoom-id")], "guests_can_modify":None})
|
||||||
|
self.workflow.require_booking_confirmed("workflow-tx")
|
||||||
|
self.assertEqual(self.ledger.transaction_status("workflow-tx")["state"], "completed")
|
||||||
|
|
||||||
|
def test_pending_negotiation_uses_default_duration_then_offers_before_selection(self):
|
||||||
|
ledger = Ledger(Path(self.temp.name) / "negotiation.sqlite3")
|
||||||
|
ledger.create_pending_negotiation(transaction_id="negotiation", requester="[email protected]", sender="[email protected]", owner="[email protected]", authentication_evidence_id="auth", gmail_thread_id="thread", policy_revision="test", default_duration_minutes=60, max_exchanges=8, expires_at=NOW + timedelta(hours=72))
|
||||||
|
workflow = SchedulingWorkflow(ledger)
|
||||||
|
offer = workflow.begin_round("negotiation", ("slot-1", "slot-2", "slot-3"), NOW + timedelta(hours=72), "thread", NOW)
|
||||||
|
self.assertEqual(offer["slot_ids"], ("slot-1", "slot-2", "slot-3"))
|
||||||
|
self.assertEqual(ledger.transaction_status("negotiation")["state"], "awaiting_requester")
|
||||||
|
|
||||||
|
def test_rejects_unbound_duplicate_or_expired_selection(self):
|
||||||
|
round_data = self.workflow.begin_round("workflow-tx", ("slot-a",), NOW + timedelta(hours=1), "thread", NOW)
|
||||||
|
self.workflow.bind_outbound("workflow-tx", 1, "outbound")
|
||||||
|
with self.assertRaises(WorkflowError):
|
||||||
|
self.workflow.accept_selection("workflow-tx", slot_id="other", transaction_token=round_data["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW)
|
||||||
|
self.workflow.accept_selection("workflow-tx", slot_id="slot-a", transaction_token=round_data["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW)
|
||||||
|
with self.assertRaises(WorkflowError):
|
||||||
|
self.workflow.accept_selection("workflow-tx", slot_id="slot-a", transaction_token=round_data["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW)
|
||||||
|
self.ledger.create_transaction(evaluate_intent({"transaction_id":"expired-tx","requester":"[email protected]","sender":"[email protected]","start_at":"2031-01-01T18:00:00Z","end_at":"2031-01-01T19:00:00Z","expires_at":"2031-01-02T00:00:00Z","authentication_evidence_id":"auth","availability_evidence_id":"calendar"}, CONFIG, NOW, []), CONFIG.revision, CONFIG.max_exchange_messages)
|
||||||
|
expired = self.workflow.begin_round("expired-tx", ("slot-a",), NOW + timedelta(minutes=1), "thread", NOW)
|
||||||
|
self.workflow.bind_outbound("expired-tx", 1, "outbound")
|
||||||
|
with self.assertRaises(WorkflowError):
|
||||||
|
self.workflow.accept_selection("expired-tx", slot_id="slot-a", transaction_token=expired["transaction_token"], thread_id="thread", in_reply_to="outbound", references=("outbound",), now=NOW + timedelta(minutes=2))
|
||||||
Reference in new issue
Block a user