diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..69e45a1 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +.git/ +.env +.env.* +data/ +runtime/ +backups/ +logs/ +operations/private/ +operations/inbox/ +receipts/private/ +receipts/generated/ +previews/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.venv/ +tests/ +tasks/ diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b3273a9 --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# Copy to .env for local development or provide these values through the VM runtime. +EMAIL_LIST_DATA_DIR=./data +EMAIL_LIST_RECEIPTS_DIR=./receipts/generated +EMAIL_LIST_TIMEZONE=America/Denver +EMAIL_LIST_GIT_COMMIT=replace-with-reviewed-commit +EMAIL_LIST_PROVIDER=test +# Production: /srv/email-list-system/runtime +# This host directory holds the SQLite database, backups, logs, and private inbox. +EMAIL_LIST_HOST_DATA_DIR= + +# Production-only integrations. Never commit values for these keys. +POSTMARK_SERVER_TOKEN= +POSTMARK_BROADCAST_STREAM_ID=broadcast-list +POSTMARK_FROM_NAME=PaddleNET +POSTMARK_FROM_EMAIL=eddie@paddlenet.earth +POSTMARK_REPLY_TO=eddie@paddlenet.earth +TELEMETRY_BASE_URL= +TELEMETRY_API_TOKEN= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2e03da8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# Python and test artifacts +__pycache__/ +*.py[cod] +.pytest_cache/ +.coverage +coverage.xml +.venv/ + +# Local configuration and runtime state +.env +.env.* +!.env.example +data/ +runtime/ +*.sqlite +*.sqlite3 +*.db +backups/ +logs/ + +# Private subscriber operations and detailed receipts +operations/private/ +operations/inbox/ +receipts/private/ +receipts/generated/ + +# Rendered local previews +previews/ +# Public-publication guardrails +*.csv +*.jsonl +!operations/examples/subscriber-operations.jsonl +*.sql +*.tar.gz +*.pem +id_rsa +id_ed25519 \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a609114 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,47 @@ +# AI Agent Instructions + +## Repository Purpose + +This is a sanitized public reference implementation of PaddleNET's automation-based email-list system. Preserve its operational teaching value while preventing credentials, subscriber data, private paths, live infrastructure identifiers, and private telemetry from entering public output. + +## Read Order + +1. `README.md` +2. `AUTHOR.md` +3. `repository-variables.json` +4. `repository.json` +5. `PUBLICATION_WORKFLOW.md` and `sanitization-map.md` for publication work +6. `skills.md` +7. The relevant skill, documentation, schema, or source file + +## Task Routing + +- Repository metadata or structure: follow the task-plan workflow in `tasks/README.md`. +- Private-to-public sync: follow `PUBLICATION_WORKFLOW.md` and require human review before commit or push. +- Email operations: use the matching skill under `skills/` and its deterministic CLI commands. +- Security or leak review: run `scripts/leak-scan.ps1` and inspect each finding. + +## Safety Boundaries + +- Never commit credentials, subscriber data, private JSONL operations, databases, backups, raw telemetry, detailed receipts, private paths, or live infrastructure identifiers. +- Never send email, mutate subscribers, alter suppressions, deploy, schedule production jobs, or change infrastructure without the authorization required by the relevant skill and documentation. +- Do not edit production SQLite directly or bypass validation, authorization, backup, suppression, idempotency, or dry-run controls. +- Treat `UPDATES.md` as proposals, not approval. +- Do not commit, push, rewrite history, publish, or delete repository content without explicit authorization. + +## Validation + +Run: + +```text +python scripts/validate_repository.py . +python -m unittest discover -s tests -p "test_*.py" +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/leak-scan.ps1 +git diff --check +``` + +Also validate modified skills with the skill validator and run focused project checks for modified Python, Docker, schema, template, or workflow files. + +## Escalation + +Stop for human direction when authorization is ambiguous, a safety check fails, content or audience would materially change, private publication risk is unresolved, or an operational exception cannot be resolved safely. diff --git a/AUTHOR.md b/AUTHOR.md new file mode 100644 index 0000000..cced1ef --- /dev/null +++ b/AUTHOR.md @@ -0,0 +1,33 @@ +# Author And Publisher + +## Primary Author + +**Eddie Soehnel** + +## Publisher + +**adminprojects** + +## Maintainer + +**Eddie Soehnel** + +## Attribution + +```text +Automation-Based Email List System by Eddie Soehnel +``` + +Canonical repository: + +```text +https://projects.eddiesoehnel.com/adminprojects/automation-based-email-list-system-OPEN +``` + +## Public Derivative + +This repository contains a sanitized public reference derived from a private operational implementation. Attribution does not authorize publication of credentials, subscriber data, private source content, or infrastructure details. + +## Adapting This Repository + +Replace identity and publication values together in `repository-variables.json`, `AUTHOR.md`, `repository.json`, `CITATION.cff`, and `LICENSE`. Verify the license and canonical URL rather than inheriting them automatically. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..025d5c9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this repository are documented here. + +## [0.1.0] - 2026-08-15 + +### Added + +- Initial sanitized public application, Docker deployment files, deterministic CLI, schemas, tests, documentation, templates, and scoped AI operating skills. +- AI-ready software/automation repository metadata, agent instructions, governance files, validation tooling, and repository-structure task records. diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..95e628a --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,18 @@ +cff-version: 1.2.0 +message: "If you use this resource, please cite it as described below." +title: "Automation-Based Email List System" +type: software +version: 0.1.0 +date-released: 2026-08-15 +authors: + - family-names: "Soehnel" + given-names: "Eddie" +repository-code: "https://projects.eddiesoehnel.com/adminprojects/automation-based-email-list-system-OPEN" +url: "https://projects.eddiesoehnel.com/adminprojects/automation-based-email-list-system-OPEN" +license: MIT +keywords: + - email-automation + - postmark + - ai-agents + - subscriber-management + - campaign-operations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..93b02bb --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,31 @@ +# Contributing + +## Useful Contributions + +- Correct inaccurate documentation or unsafe operating guidance. +- Improve deterministic CLI behavior, tests, schemas, templates, and portability. +- Strengthen authorization, idempotency, suppression, privacy, backup, or publication controls. + +## Before You Submit + +Prepare a focused change and explain the problem, intended outcome, and validation performed. Keep unrelated edits separate. + +## Public-Safety Requirements + +Never submit credentials, subscriber data, private JSONL operations, databases, backups, raw telemetry, detailed receipts, private paths, repository URLs, hosts, IP addresses, SSH details, or live endpoints. Use synthetic examples and follow `PUBLICATION_WORKFLOW.md` and `sanitization-map.md`. + +## Repository Standards + +- Preserve stable metadata IDs and useful existing content. +- Keep `repository-variables.json`, `AUTHOR.md`, `repository.json`, `CITATION.cff`, and `LICENSE` aligned. +- Keep `VERSION`, `repository.json`, `CITATION.cff`, and `CHANGELOG.md` aligned for releases. +- Record completed work in `CHANGELOG.md`; future proposals belong in `UPDATES.md`. +- Update relevant tests and documentation with behavior changes. + +## Validation + +Run the commands in `AGENTS.md` and any focused tests for changed components. Review the final diff for accidental sensitive identifiers and generated files. + +## Rights And Review + +Contributions must be original or properly licensed for inclusion under the MIT License. Maintainer review is required. Email sends, subscriber mutations, infrastructure actions, public commits or pushes, history rewrites, and file deletions require separate explicit authorization. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b7cd66f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +FROM python:3.13-slim + +ARG APP_GIT_COMMIT=unknown +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + EMAIL_LIST_GIT_COMMIT=${APP_GIT_COMMIT} + +WORKDIR /app + +COPY pyproject.toml README.md ./ +COPY src ./src +COPY templates ./templates +COPY campaigns ./campaigns +COPY operations ./operations +RUN pip install --no-cache-dir . + +RUN useradd --create-home --uid 1000 appuser \ + && mkdir -p /data /config \ + && chown -R appuser:appuser /data /config +USER appuser + +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \ + CMD ["email-list", "system", "check", "--json"] + +ENTRYPOINT ["email-list"] +CMD ["system", "check", "--json"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..393840e --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +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. diff --git a/PUBLICATION_WORKFLOW.md b/PUBLICATION_WORKFLOW.md new file mode 100644 index 0000000..591c204 --- /dev/null +++ b/PUBLICATION_WORKFLOW.md @@ -0,0 +1,14 @@ +# Public Publication Workflow + +This repository is a sanitized public reference derived from a private operational implementation. It intentionally contains no private Git history. + +Before publishing an update: + +1. Copy only explicitly approved, tracked source files; never copy `.git/`, runtime directories, caches, databases, exports, backups, or generated receipts. +2. Replace live infrastructure identifiers, workstation paths, private repository URLs, SSH details, and public webhook endpoints with documented examples. +3. Keep credentials empty in `.env.example`; inject real values through environment variables or private configuration. +4. Confirm any JSONL retained under `operations/examples/` is synthetic and contains no real subscriber data. +5. Run `powershell -File scripts/leak-scan.ps1` and the project test suite. +6. Review `git diff` and obtain human approval before committing or pushing. + +Real brand and author references may remain when the project owner approves them. This permission does not extend to live infrastructure or personal subscriber data. \ No newline at end of file diff --git a/README.md b/README.md index e69de29..339961a 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,686 @@ +# Automation-Based Email List System + +> [!IMPORTANT] +> This public repository is a sanitized reference implementation. Supply real credentials only through environment variables or private runtime configuration. Never commit subscriber data, telemetry exports, databases, receipts containing personal data, or live operational endpoints. Values under `operations/examples/` are synthetic fixtures. + +A small, open-source, AI-operated email list system for PaddleNet. The human writes an email in Markdown and directs an authorized AI agent to send it and schedule the apparent-non-opener follow-up. From that handoff forward, the AI agent and deterministic scheduled jobs validate, send, monitor, reconcile, and report the campaign without routine human involvement. + +This project replaces Listmonk for this specific use case. It intentionally starts with a narrow feature set and keeps components isolated so they can be improved or replaced without redesigning the whole system. + +## Project Status + +Planning and specification stage. The first release should implement only the v1 scope defined below. + +## Goals + +- Operate from a Git repository rather than a dedicated administration dashboard. +- Give humans and AI agents the same safe command-line interface. +- Allow a properly authorized AI agent with persistent terminal access to operate the complete routine workflow. +- Keep human judgment at the initial authorization boundary and use deterministic scripts for execution. +- Send broadcast and welcome email through Postmark. +- Store live subscriber and campaign state safely in SQLite. +- Reuse the existing PaddleNet telemetry server and its Postmark webhook ingestion. +- Run as an isolated Docker container on the existing email-list VM. +- Keep modules small, testable, and replaceable. +- Produce sanitized, reviewable receipts for important operations. +- Remain simple enough for one person and AI agents to understand and operate. + +## Intended Operating Model + +The system is designed to remove the human from routine email-list operations after a clear handoff. + +### Campaign handoff + +1. The human writes the finished email in a Markdown campaign file. +2. The human tells the AI agent to send that campaign and specifies or accepts the normal apparent-non-opener delay, usually four or five days. +3. That instruction is the human's authorization for the exact campaign and its configured follow-up. A second human interaction is not normally required. +4. The AI agent validates the campaign, renders and inspects the preview, checks the audience and suppressions, records the authorization, sends the initial campaign, schedules the follow-up, verifies completion, and writes receipts. +5. At the scheduled time, the AI agent or cron-triggered command queries telemetry, builds the apparent-non-opener audience, rechecks suppressions, sends the authorized follow-up, and verifies the result. +6. The AI returns to the human only when a safety check fails, authorization is ambiguous, the content would need a material change, or an operational exception cannot be resolved safely. + +### Subscriber maintenance + +1. The human adds subscribe or unsubscribe operations to a simple private JSON or JSONL inbox file. +2. A scheduled cron job reads and validates the file. +3. The deterministic subscriber command applies each new operation exactly once to SQLite. +4. A new active subscriber receives the welcome email exactly once. +5. An unsubscribe is applied before any later campaign batch is allowed to send. +6. The job archives or marks processed operations and writes a sanitized receipt. Routine processing does not require the human or a live AI session. + +This creates two compatible operating modes: + +- **AI-operated work:** campaign interpretation, command orchestration, scheduling, exception handling, verification, and concise reporting. +- **Deterministic unattended work:** cron-triggered imports, welcome sends, suppression reconciliation, due follow-ups, backups, and receipts. + +The AI model, agent host, credential mechanism, and exact persistent-access design are intentionally unresolved infrastructure choices. The application exposes a stable CLI and permission boundary so those components can change without changing email-list business logic. + +## Non-Goals for v1 + +- A browser-based administration dashboard. +- A general-purpose replacement for every Listmonk feature. +- Complex audience segmentation or personalization. +- A/B testing. +- A custom analytics platform. +- A custom unsubscribe service. +- Distributed queues, Redis, PostgreSQL, Kubernetes, or a service mesh. +- Direct AI access to database internals or production secrets. + +## Operating Principles + +1. **Human architect, AI operator.** The human authors the content and gives the send-and-schedule directive. That directive authorizes the exact campaign workflow; the AI agent then executes and supervises it through documented deterministic commands. +2. **Review before mutation.** Mutating commands provide a plan or dry run, state their impact, verify recorded authorization, and verify the result. Routine steps covered by the original directive do not repeatedly interrupt the human. +3. **Small, single-purpose modules.** Business logic, storage, provider integrations, rendering, telemetry access, and receipts remain separate. +4. **Replaceable integrations.** Postmark, SQLite, the Markdown renderer, and the telemetry client are accessed through narrow contracts so a future implementation can be swapped in. +5. **Stable schemas and contracts.** Structured inputs, command output, database migrations, telemetry responses, and receipts have versioned schemas. +6. **Deterministic execution.** AI agents may prepare inputs and choose approved commands, but scripts perform validation, rendering, state changes, sending, and reconciliation. +7. **Idempotency by default.** Retrying an import, webhook synchronization, or campaign send must not duplicate a mutation or email. +8. **Private runtime state stays outside Git.** Subscriber data, raw telemetry, credentials, production databases, and private logs never enter the public repository. +9. **Prototype for 1X, build for 10X, engineer for 100X.** v1 stays small while preserving the boundaries needed to grow safely. +10. **Documentation and tests change with the architecture.** New features require tests; schema changes require migrations; architecture changes require documentation updates. + +## System Overview + +The system has four operational areas: + +1. **Repository and workstation:** campaign Markdown, templates, schemas, deterministic scripts, AI skills, tests, sanitized receipts, and documentation. +2. **Email-list VM:** the Dockerized Python application, command-line interface, scheduler entrypoint, SQLite state, backups, and provider adapters. +3. **Postmark:** broadcast delivery, welcome-email delivery, delivery suppression, and recipient unsubscribe handling. +4. **Existing telemetry server:** receives Postmark webhooks, stores campaign activity, and answers telemetry queries such as apparent non-openers. + +See [docs/system-map.md](docs/system-map.md) for the graphical system and data-flow map. + +## Sources of Truth + +| Information | Authoritative source | Notes | +| --- | --- | --- | +| Campaign content | Versioned Markdown in Git | Approved content is identified by its content hash and Git commit. | +| Email layout | Versioned templates in Git | The template version is recorded with each campaign. | +| Subscriber operational state | SQLite on the email-list VM | Accessed through commands; never committed to Git. | +| Delivery suppression | Postmark Broadcast Message Stream | Reconciled before sending and mirrored locally as needed. | +| Campaign engagement telemetry | Existing telemetry server | Receives Postmark webhooks; queried through a narrow adapter. | +| Campaign send state | SQLite on the email-list VM | Includes recipient snapshots, attempts, and Postmark identifiers. | +| Public execution evidence | Sanitized receipts in Git | Must not contain subscriber addresses or raw private telemetry. | + +## System Components + +### 1. Command-Line Interface + +The CLI is the only supported operational interface for humans and AI agents. It should provide: + +- machine-readable `--json` output; +- `--dry-run` for every meaningful mutation; +- stable exit codes; +- explicit impact summaries; +- clear validation errors; +- idempotent commands; +- receipts for completed mutations; +- Windows and Linux path-safe behavior in development and tests. + +Proposed command surface: + +```text +email-list system check --json + +email-list campaign validate --json +email-list campaign preview +email-list campaign approve --json +email-list campaign send --dry-run --json +email-list campaign send --json +email-list campaign status --json +email-list campaign schedule-non-openers --after-days 5 --json +email-list campaign run-due-followups --json +email-list campaign resend-non-openers --dry-run --json + +email-list subscriber add --source --dry-run --json +email-list subscriber unsubscribe --reason --dry-run --json +email-list subscriber status --json +email-list subscriber import --dry-run --json + +email-list suppression reconcile --dry-run --json +email-list telemetry sync --json +email-list backup create --json +``` + +### 2. Campaign Content Module + +The human writes email bodies as Markdown in the repository. An AI may edit campaign content only when separately instructed. Campaign metadata uses validated YAML front matter rather than free-form parsing. + +Example: + +```yaml +--- +schema_version: "1.0" +campaign_id: paddlenet-2026-08-august-update +subject: August from PaddleNet +preheader: New routes, stories, and project updates +from_name: PaddleNet +reply_to: hello@paddlenet.earth +audience: active +--- +``` + +The campaign ID is stable and unique. Validation rejects missing metadata, unsafe links, unknown audiences, unsupported fields, and duplicate IDs. + +### 3. Rendering and Validation Module + +This module: + +- validates campaign front matter against a versioned schema; +- converts Markdown into HTML; +- creates a plain-text alternative; +- merges content with the selected versioned template; +- verifies required footer content and unsubscribe behavior; +- checks referenced local media; +- creates a human-reviewable preview; +- calculates the content and template hashes used for authorization. + +Rendering has no authority to approve or send a campaign. + +### 4. Authorization Guard + +The authorization record binds together: + +- campaign ID; +- campaign content hash; +- template hash or version; +- Git commit; +- audience rule; +- expected recipient count; +- human send directive or authorization reference; +- authorized apparent-non-opener delay and subject strategy; +- authorizing human and authorization time. + +The human's instruction to send the finished Markdown campaign is the authorization event. It may also authorize one scheduled apparent-non-opener follow-up under recorded parameters. Any content, template, audience, or follow-up change outside those parameters invalidates the authorization. Sending without a valid matching authorization fails closed. + +Campaign states: + +```text +draft -> validated -> approved -> sending -> sent + | + +-> partial + +-> failed +``` + +### 5. Subscriber Module + +SQLite is the authoritative store for private subscriber and operational campaign records. SQLite is used instead of individual JSON files because it provides atomic updates, transactions, uniqueness constraints, queries, migrations, and straightforward backups without operating a separate database server. + +AI agents do not manipulate SQLite directly. They use the CLI, which accepts structured input and returns JSON. + +Minimum subscriber fields: + +- stable subscriber ID; +- normalized email address; +- current status; +- subscription source; +- consent timestamp and available consent note; +- subscribed timestamp; +- unsubscribed or suppressed timestamp; +- suppression reason; +- created and updated timestamps. + +Minimum statuses: + +```text +active +unsubscribed +hard_bounced +spam_complaint +manually_suppressed +``` + +Status changes are also recorded as an append-only history. A hard bounce, spam complaint, or unsubscribe takes precedence over an ordinary activation request unless a deliberate, allowed reactivation process is performed. + +### 6. Campaign and Send-State Module + +The database stores: + +- campaign identity and lifecycle state; +- approved content and template hashes; +- immutable recipient snapshot; +- per-recipient send state; +- Postmark request and message identifiers; +- attempt counts and errors; +- start, completion, and reconciliation timestamps. + +Each campaign-recipient pair is unique. A retry resumes unsent or safely retryable records rather than resending the entire audience. + +### 7. Postmark Adapter + +The application uses a narrow email-provider interface. The v1 implementation uses Postmark, but campaign logic must not depend directly on Postmark-specific code. + +Responsibilities: + +- submit broadcast batches; +- send individual welcome emails; +- attach campaign IDs and useful metadata; +- return provider message or request identifiers; +- expose provider errors in normalized form; +- query or reconcile delivery suppressions before sending. + +Postmark's Broadcast Message Stream manages visible unsubscribe links, one-click unsubscribe headers, and delivery suppression in v1. A custom unsubscribe website is intentionally deferred. + +### 8. Telemetry Adapter + +The existing telemetry server can receive Postmark campaign events through webhooks. This application does not duplicate that ingestion system. We will duplicate this process used in other domains for accepting telemetry data from Post Mark to the telemetry server. + +The telemetry adapter provides a narrow, read-oriented interface for: + +- campaign completion and activity summaries; +- delivered, opened, clicked, bounced, complained, and unsubscribed events; +- apparent non-opener selection; +- reconciliation results needed by the email-list application. + +Telemetry responses should use a documented versioned contract. The adapter isolates the rest of the application from the telemetry server's internal database and implementation. + +### 9. Private JSON Operations Inbox + +Markdown remains authoritative for campaign content. Subscriber mutations use validated JSON records so deterministic scripts do not interpret prose. The production inbox is a private mounted file such as `/data/inbox/subscriber-operations.jsonl`; it is never committed to the public repository. + +Example subscription operation: + +```json +{ + "schema_version": "1.0", + "operation_id": "subscribe-2026-08-11-example", + "operation": "subscribe", + "email": "person@example.com", + "source": "manual", + "requested_at": "2026-08-11T18:00:00Z" +} +``` + +An unsubscribe uses the same shape with `"operation": "unsubscribe"` and a reason. An operation ID prevents duplicate processing. Cron may safely reread the file because previously applied operation IDs are skipped. Processed private operation files are archived outside Git according to the retention policy. + +### 10. Receipt Module + +Every authorization, import, send, resend, suppression reconciliation, migration, and backup produces an execution receipt. + +Public receipts may include: + +- receipt ID; +- command and software version; +- campaign ID; +- content and template hashes; +- Git commit; +- counts of considered, excluded, accepted, failed, and completed records; +- human authorization reference; +- validation result; +- timestamps and known limitations. + +Public receipts must not include subscriber addresses, credentials, raw provider responses, or private telemetry. Detailed private runtime logs stay on the VM. + +### 11. Migration and Backup Module + +- All database schema changes use numbered, version-controlled migrations. +- The application records the installed schema version. +- Production migration requires a current backup and a reviewed dry run or migration plan. +- A backup is created before campaign sends and migrations. +- Restore procedures are documented and tested. +- SQLite and backup files live on a persistent Docker volume outside Git. + +### 12. Scheduler and Automation Entry Point + +The application may expose scheduled commands for the VM's existing scheduler or cron mechanism. Scheduling stays outside business logic. + +Initial scheduled work: + +- process private JSON/JSONL subscribe and unsubscribe operations; +- send welcome emails for newly activated subscribers; +- run authorized apparent-non-opener follow-ups when due; +- reconcile Postmark suppression state; +- create or prune backups according to policy; +- write completion or failure receipts. + +The scheduler calls the same CLI commands used interactively; it does not have a second implementation path. Cron is the persistent trigger. An AI agent may create or inspect schedules and handle exceptions, but routine scheduled execution must not depend on the model remaining connected. + +### 13. AI Skill + +The repository will contain a focused AI skill built from the established skill template. The skill enables an authorized agent to operate the routine system from the repository and, when granted, through persistent terminal access to the email-list VM. The skill explains: + +- when it applies; +- required inputs and authoritative sources; +- which deterministic commands it may call; +- validation and dry-run requirements; +- human authorization boundaries; +- expected receipts; +- failure and escalation conditions. + +The skill must never embed credentials, exceed its granted role, directly edit SQLite, or substitute model judgment for deterministic validation. It may execute production commands only when the deployed agent identity has the corresponding access right and the human directive or scheduled authorization covers the operation. + +## AI Agent Capability and Access Model + +The specific model and agent runtime are not selected yet. The system therefore defines capabilities and permissions rather than depending on one model vendor or hosting design. + +With the proper access rights, an AI agent can: + +- read campaign Markdown, templates, schemas, documentation, and prior sanitized receipts; +- validate and preview the exact human-authored campaign; +- translate the human's send directive into a recorded campaign authorization; +- run the initial send through the deterministic CLI; +- schedule the apparent-non-opener follow-up for the instructed or configured four-to-five-day delay; +- inspect campaign and telemetry status; +- run or supervise the due follow-up without returning to the human; +- inspect subscriber-import, welcome-send, suppression, backup, and health-check receipts; +- retry explicitly safe operations and resume interrupted sends; +- diagnose failures and report exceptions; +- update repository documentation or proposed campaign files through the normal Git workflow when separately authorized. + +An AI agent cannot, solely because it has terminal access: + +- create or materially rewrite campaign content without instruction; +- send a campaign for which no human directive is recorded; +- expand the audience or follow-up scope beyond the authorization; +- bypass suppression, schema, backup, authorization, or idempotency checks; +- read or expose credentials beyond what its execution role needs; +- directly mutate SQLite or the telemetry database; +- change production schemas without a migration and required review; +- silently continue after an unresolved safety or authorization failure. + +The likely initial deployment is a persistent AI agent with restricted terminal access to the email-list VM. It should receive only the commands, files, network endpoints, and credentials required by its role. The exact model, persistence mechanism, session lifecycle, terminal broker, and credential delivery remain future infrastructure decisions. + +## Core Data Contracts + +Versioned schemas should cover: + +- campaign front matter; +- subscriber import operations; +- CLI JSON results; +- telemetry queries and responses; +- sanitized receipts; +- provider-neutral send results. + +Schemas are the stable boundary. Implementations behind them may be replaced. + +## Core Processes + +### Create and Send a Campaign + +1. The human creates the finished campaign Markdown in Git. +2. The human directs the AI agent to send it and schedule the apparent-non-opener follow-up, normally four or five days later. +3. The AI records that directive as authorization for the exact content, template, audience, and follow-up parameters. +4. The AI runs deterministic validation, rendering, link, audience, and suppression checks. +5. If checks pass without requiring a material change, the AI runs the send command; otherwise it returns the exception to the human. +6. The send command creates an immutable recipient snapshot. +7. The application reconciles exclusions against current local status and Postmark suppression state. +8. The Postmark adapter submits safe, idempotent batches. +9. Per-recipient send state and provider identifiers are recorded. +10. The AI verifies initial completion, creates the due follow-up schedule, and writes a sanitized receipt. +11. Postmark delivers the email and sends activity webhooks to the existing telemetry server. + +### Add Subscribers and Send Welcome Email + +1. The human appends a subscribe record to the private JSON/JSONL operations inbox. +2. Cron invokes the deterministic import command on schedule. +3. The command validates the schema, operation ID, address, source, and available consent information. +4. The new operation is applied transactionally to SQLite exactly once. +5. The welcome-email command sends exactly once for the newly activated subscriber. +6. The operation is marked processed or archived privately, and a sanitized receipt is produced. +7. An AI agent with suitable access can inspect the receipt and handle exceptions, but routine success requires no human or live-agent action. + +### Unsubscribe and Suppress + +1. Postmark manages the visible one-click unsubscribe flow for broadcast email. +2. Postmark suppresses the recipient in its Broadcast Message Stream. +3. The existing telemetry server receives the Postmark subscription-change event. +4. The email-list application reconciles the change into local subscriber state. +5. Before every send batch, the application rechecks local status and Postmark suppression state. + +Manual administration uses the CLI with a dry run and receipt. The application never sends an unsubscribe-confirmation email. + +If the human becomes aware of an unsubscribe outside Postmark, the human appends an unsubscribe record to the same private JSON/JSONL inbox. Cron applies it idempotently on the next run. The cron frequency must be short enough to meet the project's unsubscribe-processing requirement, and pre-send reconciliation remains the final guard. + +### Resend to Apparent Non-Openers + +Open tracking is imperfect, so this audience is explicitly called **apparent non-openers**. + +1. The original human send directive records the follow-up delay, normally four or five days, and the allowed subject strategy. +2. Cron invokes the due-followup command at or after the scheduled time. +3. The AI agent or deterministic workflow queries the existing telemetry server through the telemetry adapter. +4. The system creates a linked follow-up using only the already authorized content and subject strategy. +5. It excludes unsubscribed, complained, bounced, suppressed, and newly ineligible recipients. +6. It validates that the original authorization still covers the follow-up and that no follow-up was already sent. +7. It permits no more than one apparent-non-opener resend for the original campaign in v1. +8. It sends through the normal pipeline, verifies completion, and writes a separate receipt without routine human involvement. +9. Any required material content, audience, timing, or subject change outside the recorded parameters returns to the human for a new directive. + +### Reconcile Suppressions + +1. Read current local subscriber states. +2. Read Postmark Broadcast Message Stream suppressions through the provider adapter. +3. Compare without mutating and produce a reconciliation plan. +4. Apply only the reviewed allowed changes. +5. Verify both sides and write a sanitized receipt. + +## Safety and Reliability Requirements + +- Default mutation commands to a preview or require explicit execution flags. +- Fail closed when authorization, schema validation, backup, or suppression checks fail. +- Never send to an address with an unresolved suppression conflict. +- Normalize email addresses consistently and enforce uniqueness. +- Use transactions for subscriber changes, recipient snapshots, and send-state transitions. +- Store timestamps in UTC using ISO 8601. +- Deduplicate imported operations and telemetry synchronization events. +- Never log secrets or full subscriber lists. +- Provide a test-mode Postmark adapter and synthetic fixtures. +- Support interruption and safe resumption of campaign sends. +- Bound retries and surface partial failures for human review. +- Back up before destructive or schema-changing operations. + +## Privacy and Security Boundaries + +Never commit to the public repository: + +- subscriber names or email addresses; +- production SQLite databases or backups; +- Postmark or telemetry credentials; +- raw webhook payloads; +- private logs; +- unsanitized subscriber-operation files; +- session data or access tokens. + +Runtime secrets are injected on the VM through environment variables or Docker secrets. The container runs as a non-root user with only the data and configuration it needs. Network access is limited to required Postmark and telemetry endpoints. + +## Docker Deployment + +Docker is appropriate here because the target email-list VM already operates containerized Listmonk applications and the new application benefits from isolated dependencies and a portable, repeatable runtime. + +The v1 deployment should use one application container and one persistent volume. It should not introduce an internal database container or queue. + +Runtime layout: + +```text +/app read-only application code +/config mounted non-secret configuration +/data/email-list.sqlite private persistent database +/data/backups/ private database backups +/data/logs/ private operational logs +/data/receipts/ private detailed receipts +``` + +The image should include a health check. Deployment documentation must define the image version, environment variables, mounted paths, backup location, update procedure, rollback procedure, and validation command. + +## Development and Release Process + +1. Work in an isolated development environment, never directly in production. +2. Inspect repository instructions and current Git state. +3. Write or update the specification and testing plan. +4. Implement bounded components with tests. +5. Run unit, integration, schema, migration, rendering, and safe-resume tests. +6. Review the change and documentation. +7. Commit and push through the normal Git workflow. +8. Deploy the reviewed revision to the VM. +9. Run health checks and a synthetic or test-mode send. +10. Validate production behavior and record the release. +11. Tag the validated release. + +## Required v1 Tests + +- Campaign schema validation and malformed input rejection. +- Markdown-to-HTML and plain-text rendering snapshots. +- Authorization invalidation after content, template, audience, or follow-up parameter changes. +- Duplicate subscriber and normalized-email handling. +- Subscriber status precedence and history. +- Import-operation idempotency. +- Cron reprocessing of an unchanged JSON/JSONL inbox without duplicate mutations or welcomes. +- Recipient-snapshot immutability. +- Duplicate-send prevention and interrupted-send resumption. +- Partial Postmark batch failure handling. +- Suppression reconciliation and fail-closed behavior. +- Telemetry adapter contract tests. +- Apparent non-opener resend limits and exclusions. +- Due-followup scheduling, authorized unattended execution, and exception escalation. +- AI role and command-permission enforcement. +- Database migration, backup, and restore tests. +- Secret and private-data exclusion checks for public receipts. +- Windows and Linux path handling where relevant. + +## Repository Structure + +This repository will use the open-source software/automation profile from `repo-template-OPEN`. The complete structure should be created through that template's review-and-approval workflow rather than copied mechanically. + +Planned project-specific structure: + +```text +automation-based-email-list-system/ +|-- README.md +|-- AGENTS.md +|-- AUTHOR.md +|-- repository-variables.json +|-- repository.json +|-- LICENSE +|-- CHANGELOG.md +|-- UPDATES.md +|-- VERSION +|-- CONTRIBUTING.md +|-- SECURITY.md +|-- CITATION.cff +|-- docs/ +| |-- README.md +| |-- architecture.md +| |-- deployment.md +| |-- data-model.md +| |-- system-map.md +| `-- glossary.md +|-- src/email_list/ +| |-- cli/ +| |-- campaigns/ +| |-- subscribers/ +| |-- authorizations/ +| |-- sending/ +| |-- storage/ +| |-- providers/ +| |-- telemetry/ +| |-- receipts/ +| `-- backups/ +|-- campaigns/ +| |-- drafts/ +| `-- sent/ +|-- templates/ +|-- operations/ +| `-- examples/ +|-- schemas/ +|-- scripts/ +|-- skills/ +|-- examples/ +|-- receipts/ +|-- tasks/ +|-- tests/ +|-- assets/ +| `-- diagrams/ +|-- pyproject.toml +|-- Dockerfile +|-- compose.yaml +|-- .env.example +`-- .gitignore +``` + +Real subscriber operations, runtime databases, detailed receipts, logs, backups, generated previews, and secrets remain outside the public repository even when similarly named directories contain schemas, synthetic examples, or sanitized artifacts. + +## v1 Definition of Done + +- A human and an AI agent can discover and understand the project from the repository entry points. +- The repository passes the approved `repo-template-OPEN` software/automation profile validation. +- A human can finish a Markdown campaign, issue one send-and-schedule directive, and leave routine execution to an authorized AI agent. +- The AI can validate, send, monitor, schedule, run the due apparent-non-opener follow-up, verify, and report through deterministic commands. +- Cron can process private JSON/JSONL subscribe and unsubscribe operations without a human or live AI session. +- A new subscriber receives one welcome email and reprocessing cannot duplicate it. +- An authorized operator can add or suppress a subscriber through a reviewed deterministic command. +- Interrupted or retried sends do not duplicate already accepted recipients. +- Current suppressions are checked before every batch. +- Welcome email processing is idempotent. +- Existing telemetry can be queried through the documented adapter contract. +- One previously authorized resend to apparent non-openers can be completed safely four or five days later without a second routine human approval. +- Private data and credentials remain outside Git. +- Migrations, backups, restore, health checks, tests, and deployment procedures are documented and verified. +- Sanitized campaign and operation receipts are produced. + +## Deferred Functionality + +- Custom unsubscribe pages and preference centers. +- Double opt-in workflows unless later required. +- Multiple lists and complex segmentation. +- Rich subscriber profiles and personalization. +- A general-purpose scheduling engine or calendar UI; v1 stores due times and lets cron invoke the deterministic due-followup command. +- A browser dashboard. +- A/B testing and automated optimization. +- Advanced reporting already supplied by Postmark or telemetry. +- Multiple email providers active at once. +- Distributed workers and databases. + +## Open Decisions Before Implementation + +- Confirm the canonical public repository URL and hosting organization. +- Confirm the open-source license rather than inheriting one from the template. +- Confirm sender identity, reply-to address, and Postmark Message Stream identifiers. +- Define the existing telemetry server's query contract and authentication method. +- Decide whether consent records need more fields for PaddleNet's actual signup sources. +- Define backup retention and off-VM backup location. +- Decide the scheduler used on the email-list VM. +- Confirm the expected maximum list size and normal campaign frequency for batch sizing and operational tests. +- Select the initial AI model and agent runtime. +- Define how the AI agent receives persistent terminal access to the email-list VM. +- Define the agent's Unix user, command allowlist, filesystem access, network access, and credential scope. +- Decide whether the AI agent remains continuously resident or is awakened by an external scheduler or task runner. +- Define how a human send directive is captured as a durable authorization record. +- Choose the default apparent-non-opener delay and approved follow-up subject strategy. + +## Relationship to Existing Systems + +- **Postmark:** replaceable delivery and suppression provider behind the provider adapter. +- **Existing telemetry server:** replaceable campaign-activity source behind the telemetry adapter. +- **Git host:** source control and review mechanism, not a store for private runtime data. +- **Email-list VM:** runtime host; deployment details must not leak into business logic. +- **Listmonk:** existing neighboring applications on the same VM, not a runtime dependency. + +## Current Task + +After review of this specification, apply `repo-template-OPEN` through its repository-local planning and approval workflow. Scaffold only the approved software/automation profile and project-specific files, then implement v1 as bounded, tested components. + +## Repository Guide + +The repository now implements the `repo-template-OPEN` software/automation profile. Start with: + +1. `README.md` for purpose, architecture, and operating model. +2. `AUTHOR.md` and `repository-variables.json` for verified identity and publication facts. +3. `repository.json` for machine-readable entry points and contents. +4. `AGENTS.md` for repository safety, routing, and validation rules. +5. `skills.md` and the relevant `skills/*/SKILL.md` for authorized operating workflows. +6. `PUBLICATION_WORKFLOW.md` and `sanitization-map.md` before public-source updates. + +Important implementation areas are `src/email_list/`, `docs/`, `schemas/`, `templates/`, and `tests/`. Private runtime data, credentials, subscriber operations, databases, backups, detailed receipts, logs, and telemetry remain outside Git. + +### Validation + +```text +python scripts/validate_repository.py . +python -m unittest discover -s tests -p "test_*.py" +powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/leak-scan.ps1 +git diff --check +``` + +### Version And License + +Current version: `0.1.0`. See `VERSION` and `CHANGELOG.md`. + +Licensed under the MIT License. See `LICENSE`. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..9359457 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policy + +## Supported Version + +The current version in `VERSION` is supported. + +## Reporting A Vulnerability + +Do not post credentials, subscriber data, private infrastructure details, or exploitable endpoints in a public issue. Contact the maintainer through a private channel available on the repository host and include only the minimum evidence required. + +## Credentials And Private Data + +Never commit passwords, tokens, API keys, private keys, cookies, production `.env` files, subscriber records, raw telemetry, databases, backups, private JSONL operations, detailed receipts, or production logs. Use environment variables, private runtime mounts, and synthetic examples. + +## Operational Safety + +Treat repository skills and workflows as controlled operating guidance, not standing authority to send email, mutate subscribers, change suppressions, deploy, schedule jobs, or alter infrastructure. Preserve the documented human authorization, dry-run, validation, backup, suppression, and idempotency gates. + +## Public Derivative Safety + +Follow `PUBLICATION_WORKFLOW.md` and `sanitization-map.md`. Run `scripts/leak-scan.ps1` before commit or publication and review findings manually. + +## Response Process + +The maintainer will assess the report, contain exposure, rotate affected credentials when needed, remove unsafe material, add a durable test or guardrail, validate the correction, and coordinate any publication or history remediation. diff --git a/UPDATES.md b/UPDATES.md new file mode 100644 index 0000000..e69de29 diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/campaigns/drafts/.gitkeep b/campaigns/drafts/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/campaigns/drafts/.gitkeep @@ -0,0 +1 @@ + diff --git a/campaigns/drafts/example-campaign.md b/campaigns/drafts/example-campaign.md new file mode 100644 index 0000000..c951ab4 --- /dev/null +++ b/campaigns/drafts/example-campaign.md @@ -0,0 +1,15 @@ +--- +schema_version: "1.0" +campaign_id: paddlenet-example-update +subject: PaddleNET example update +preheader: A synthetic preview for local validation +from_name: PaddleNET +reply_to: eddie@paddlenet.earth +audience: active +--- + +# PaddleNET example update + +This synthetic campaign confirms the local authoring and rendering path. + +Read more at [PaddleNET](https://paddlenet.earth). diff --git a/campaigns/sent/.gitkeep b/campaigns/sent/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/campaigns/sent/.gitkeep @@ -0,0 +1 @@ + diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..ffce261 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,20 @@ +services: + email-list: + build: + context: . + args: + APP_GIT_COMMIT: ${EMAIL_LIST_GIT_COMMIT:-unknown} + image: paddlenet-email-list-system:local + env_file: + - path: .env + required: false + environment: + EMAIL_LIST_DATA_DIR: /data + EMAIL_LIST_RECEIPTS_DIR: /data/receipts + volumes: + - ${EMAIL_LIST_HOST_DATA_DIR:-email-list-data}:/data + - ./config:/config:ro + restart: "no" + +volumes: + email-list-data: diff --git a/config/.gitkeep b/config/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/config/.gitkeep @@ -0,0 +1 @@ + diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..db2d5bb --- /dev/null +++ b/docs/README.md @@ -0,0 +1,12 @@ +# Documentation + +- [Architecture](architecture.md) +- [Deployment](deployment.md) +- [Data model and CLI contract](data-model.md) +- [System map](system-map.md) +- [Ops Monitor telemetry API](telemetry-api.md) +- [Scheduler](scheduler.md) +- [AI operating skill](ai-operator.md) +- [Release and deployment checklist](release-checklist.md) +- [Git deployment access](git-deployment-access.md) +- [Operational baseline](operational-baseline.md) diff --git a/docs/ai-operator.md b/docs/ai-operator.md new file mode 100644 index 0000000..a19ddf2 --- /dev/null +++ b/docs/ai-operator.md @@ -0,0 +1,9 @@ +# AI operating skills + +The repository contains three bounded production skills. They follow the `Prompt, Skill, And Self-Improving Agent Design Template` v0.3.1 by Eddie Soehnel, using the reusable-skill contract and ratchet framework from the local approved template copy. + +- [Add PaddleNET Subscriber](../skills/email-list-add-subscriber/SKILL.md): add one consented address through a private JSONL operation, dry run, and deterministic import. +- [Remove PaddleNET Subscriber](../skills/email-list-remove-subscriber/SKILL.md): remove one address through a private JSONL operation, dry run, and deterministic import. +- [PaddleNET Email-List Operator](../skills/email-list-operator/SKILL.md): prepare a Hub-derived campaign, obtain human approval, deploy, send, and schedule one authorized four-day apparent-non-opener follow-up. + +Use the narrow add/remove skills for subscriber changes. Use the operator skill only for campaign work and already authorized due follow-ups. None of these skills permits direct SQLite changes, exposure of private data, or bypassing deterministic validation, authorization, suppression, backup, and telemetry gates. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..4d53516 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,22 @@ +# Architecture + +The application is a deterministic Python command-line system. Humans and authorized AI agents use the same CLI; cron invokes that CLI for unattended work. + +## Runtime boundaries + +- Git contains application code, schemas, campaign Markdown, templates, documentation, and sanitized examples only. +- The email-list VM stores SQLite state, detailed receipts, logs, backups, private subscriber operations, and credentials outside Git. +- Postmark delivers email and provides current delivery suppressions. +- Ops Monitor receives Postmark events and exposes a separate authenticated, versioned read API for campaign summaries and apparent-non-opener selection. + +## Initial runtime choices + +- Sender: `PaddleNET `; replies go to the same address. +- Postmark stream: `broadcast-list` for broadcasts and welcome email. +- A follow-up is limited to one authorized resend, due four days after the initial campaign. +- Host cron invokes the Dockerized CLI. The application does not expose a public HTTP port. +- SQLite data and daily backups remain on the VM; daily backups are retained for 14 days and copied off-host manually in v1. + +Campaign Markdown is rendered into the versioned `templates/campaign.html` layout. It supplies PaddleNET's physical address and a visible Postmark-managed one-click unsubscribe link. The HTML and plain-text bodies must retain Postmark's `{{{ pm:unsubscribe }}}` placeholder; Postmark replaces it at send time and manages the resulting Broadcast Stream suppression. + +Campaign Markdown and templates are included in the reviewed container image. A campaign authorization in the next stage will bind its source and template hashes to the deployed Git revision. diff --git a/docs/data-model.md b/docs/data-model.md new file mode 100644 index 0000000..9d8cb86 --- /dev/null +++ b/docs/data-model.md @@ -0,0 +1,15 @@ +# Data model and CLI contract + +All runtime state is private SQLite data. The schemas in `schemas/` define stable boundary formats; `schema_version: "1.0"` is included in all machine-readable CLI results. + +## Database migrations + +Migrations are numbered, committed with the application, and run transactionally by `email-list system init`. The CLI defaults to a non-mutating check; initialization has an explicit `--dry-run` plan mode. + +The first migrations create subscriber state/history and idempotent operation records, campaign and authorization records, immutable recipient snapshots, individual send attempts, welcome attempts, durable follow-up schedules, and sanitized execution-receipt metadata. + +## State and privacy + +The database path is `EMAIL_LIST_DATA_DIR/email-list.sqlite`. It must be on the VM's persistent private volume and is excluded from Git and Docker build context. Schema files and synthetic examples may be committed; real subscriber operations never are. + +`email-list backup create --dry-run --json` previews the backup path. `email-list backup create --json` uses SQLite's backup API to write a consistent private backup under `EMAIL_LIST_DATA_DIR/backups/`. Scheduled retention/pruning will be added with the scheduler stage; v1 retains daily backups for 14 days. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..5d3969f --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,40 @@ +# Deployment + +Production runs on `10.0.0.10` from `/srv/email-list-system`. + +Deployment uses a reviewed Git revision, followed by a Docker Compose build on the VM. Secrets are supplied only through the VM's private `.env` file. The application has no public port; cron invokes its CLI commands. + +Before build, deployment sets `EMAIL_LIST_GIT_COMMIT` to the exact reviewed revision. Docker injects it into the image, allowing authorization records to bind campaign content and templates to that revision without copying `.git` into the image. + +## Private environment + +The VM's `.env` is a complete private configuration file. It must retain the runtime path and telemetry settings when Postmark settings are added or changed. Required production keys are: + +```dotenv +EMAIL_LIST_GIT_COMMIT= +EMAIL_LIST_PROVIDER=postmark +EMAIL_LIST_HOST_DATA_DIR=/srv/email-list-system/runtime +TELEMETRY_BASE_URL=http://10.0.0.20:8000 +TELEMETRY_API_TOKEN= +POSTMARK_SERVER_TOKEN= +POSTMARK_BROADCAST_STREAM_ID=broadcast-list +POSTMARK_FROM_NAME=PaddleNET +POSTMARK_FROM_EMAIL=eddie@paddlenet.earth +POSTMARK_REPLY_TO=eddie@paddlenet.earth +``` + +Never replace the file with only newly added keys. In particular, omitting `EMAIL_LIST_HOST_DATA_DIR` makes Docker use its empty named-volume fallback instead of the private runtime directory containing the production SQLite database. + +## Release procedure + +1. Pull the reviewed revision with the [HTTPS Git deployment procedure](git-deployment-access.md). +2. Update `EMAIL_LIST_GIT_COMMIT` in the VM's private `.env` to the pulled revision. +3. Run `docker compose build`. +4. Run `docker compose run --rm email-list system check --json`. +5. For a Postmark configuration or template change, run `docker compose run --rm email-list suppression reconcile --dry-run --json` and complete one separately authorized, single-recipient verification before any list-wide send. + +Set `EMAIL_LIST_HOST_DATA_DIR=/srv/email-list-system/runtime` in the VM's private `.env`. This mounts the private runtime directory at `/data`, including `/data/inbox/subscriber-operations.jsonl`; it must never be committed or copied into the image. + +The container runs as non-root UID `1000`, matching the deployed `deploy-user` account. Keep the runtime directory owned by that account so SQLite, backups, logs, and receipts can be written without granting the container root access. + +Before a production send, deployment validation must confirm the container health check, database backup creation, Postmark suppression access, delivery webhook health, and the Ops Monitor telemetry API contract. diff --git a/docs/git-deployment-access.md b/docs/git-deployment-access.md new file mode 100644 index 0000000..c98ae14 --- /dev/null +++ b/docs/git-deployment-access.md @@ -0,0 +1,35 @@ +# Git deployment access + +A deployment VM can clone this public repository over HTTPS using a dedicated, read-only Git access token when anonymous access is unavailable. The token is used as Git's password; it is never committed, placed in `.env`, included in a clone URL, or printed in receipts. + +## One-time clone + +1. In Gitea, create a dedicated token with repository read access only. Use a clear name such as `email-campaigns-prod-app-readonly`. +2. Connect interactively to the VM as `deploy-user`. +3. Run: + +```bash +git clone https://git.example.com/example-org/email-list-system.git /srv/email-list-system +``` + +4. At Git's prompts, enter the Gitea username and paste the token as the password. + +Do not use a URL containing `username:token`, because shell history, process listings, and copied terminal output can expose it. + +## Subsequent releases + +From the checked-out repository, first inspect the revision and working tree, then pull the reviewed branch: + +```bash +cd /srv/email-list-system +git status --short --branch +git pull --ff-only origin main +``` + +After a successful pull, update `EMAIL_LIST_GIT_COMMIT` in the VM's private `.env` to the exact checked-out revision before running `docker compose build`. Campaign approvals record this value, so it must match the reviewed code that is actually deployed. + +`--ff-only` prevents Git from creating an unexpected merge commit on the VM. If the token is not cached or has expired, Git prompts for the same username and token again. Rotate or revoke the token in Gitea if the VM is decommissioned or the token may have been exposed. + +## SSH deploy keys + +An SSH deploy key can be used only when the Git server's SSH clone endpoint is reachable from the VM. If a proxy or access layer intercepts that route, use a scoped HTTPS token instead. diff --git a/docs/operational-baseline.md b/docs/operational-baseline.md new file mode 100644 index 0000000..eee2c1b --- /dev/null +++ b/docs/operational-baseline.md @@ -0,0 +1,40 @@ +# Operational baseline + +This document records the sanitized shape of a verified v1 integration. The addresses, hostnames, user names, tunnel names, and repository URL are placeholders; it contains no credentials, private recipients, or raw telemetry. + +## Verified services + +- Email-list VM: `10.0.0.10`, deployed at `/srv/email-list-system`. +- Private runtime: `/srv/email-list-system/runtime`, mounted in the container as `/data`. +- Ops Monitor telemetry service: `10.0.0.20:8000`. +- Public Postmark webhook: `https://telemetry.example.com/postmark`. +- Delivery provider: Postmark Broadcast Message Stream `broadcast-list`, through the REST API. + +## Public webhook route + +Cloudflare Tunnel `example-tunnel` publishes `telemetry.example.com` to Caddy's loopback listener at `http://127.0.0.1:8080`. The Caddyfile must therefore include a host handler **inside** its `http://:8080` tunnel-ingress block: + +```caddy +@emaildata_paddlenet host telemetry.example.com +handle @emaildata_paddlenet { + reverse_proxy 10.0.0.20:8000 +} +``` + +An HTTPS site block for the hostname alone does not serve Cloudflare Tunnel traffic on port 8080; without the tunnel-ingress handler, Postmark receives HTTP 404 responses. + +## Verified delivery safeguards + +1. The email system reads Postmark suppressions before a send. +2. An approved campaign records its content hash, template hash, and `EMAIL_LIST_GIT_COMMIT`. +3. A dry-run confirms recipient count and exclusions before a real send. +4. A SQLite backup and a private sanitized receipt are created for a real send. +5. Postmark delivery webhooks are stored by Ops Monitor under the PaddleNET tenant. +6. Both HTML and plain-text messages include Postmark's `{{{ pm:unsubscribe }}}` placeholder. Its visible link was verified in a delivered message. + +## Deliberately not enabled + +- Welcome processing remains disabled until `templates/welcome.md` is replaced with approved copy. +- No cron entries are installed yet. +- No real subscriber list has been imported. +- No apparent-non-opener follow-up has been scheduled. diff --git a/docs/release-checklist.md b/docs/release-checklist.md new file mode 100644 index 0000000..1a38ec6 --- /dev/null +++ b/docs/release-checklist.md @@ -0,0 +1,38 @@ +# Release and deployment checklist + +## Before committing + +1. Review both working trees: the email-list system and the Ops Monitor companion change. +2. Run the complete unit suites and Docker acceptance tests using synthetic data only. +3. Confirm `.env`, runtime databases, private inbox files, logs, backups, and generated receipts are ignored. +4. Replace `templates/welcome.md` with approved PaddleNET copy before enabling welcome cron. + +## Ops Monitor deployment first + +1. Deploy the reviewed `email-telemetry` companion source to `/opt/example-email-telemetry` on Ops Monitor. +2. Add a distinct `EMAIL_TELEMETRY_API_TOKEN` to that service's private environment and restart it. +3. Create `telemetry.example.com` DNS/Caddy routing and configure the Postmark `broadcast-list` webhook. +4. Confirm webhook writes reach `/srv/example-telemetry/email/brand/raw/`. +5. Test both bearer-token read endpoints with synthetic event data. + +## Email-list VM deployment + +1. On `10.0.0.10`, create `/srv/email-list-system/runtime/inbox`. +2. Clone or pull the reviewed Git revision into `/srv/email-list-system` using the [Git deployment access procedure](git-deployment-access.md). +3. Create the private `.env` from `.env.example`; set the reviewed commit, private runtime path, `EMAIL_LIST_PROVIDER=postmark`, Postmark settings, and telemetry settings. +4. Build the image, run `system init --dry-run`, then `system init`. +5. Run `system check`, a Postmark suppression reconciliation dry run, and a synthetic/test-mode provider validation before any real subscriber import. +6. Import the initial private list with `subscriber import ... --no-welcome --dry-run`, review it, then execute it. +7. Install cron only after approved welcome copy and telemetry API validation are complete. + +## Release gate + +Do not enable live sends until a human reviews the exact campaign preview, dry-run recipient count/exclusions, Postmark stream configuration, sender identity, webhook health, backup result, and authorization reference. Tag the validated release only after these checks pass. + +## Operational baseline verified 2026-08-14 + +The initial production integration was verified with separately authorized, one-recipient test campaigns. The verified path is Postmark `broadcast-list` -> `https://telemetry.example.com/postmark` -> Cloudflare Tunnel -> Caddy -> Ops Monitor. Postmark accepted each test send, Ops Monitor recorded the delivery webhook, and the visible Postmark-managed unsubscribe link was verified after the template fix in commit ``. + +The production `.env` uses the Postmark REST API adapter, not SMTP. The initial test subscriber was imported with `--no-welcome`; no welcome email or apparent-non-opener follow-up was scheduled. + +Remaining pre-list tasks are to approve real welcome copy before enabling welcome processing, import the reviewed initial subscriber list with `--no-welcome`, and install cron only after a separate scheduler review. diff --git a/docs/scheduler.md b/docs/scheduler.md new file mode 100644 index 0000000..ee83939 --- /dev/null +++ b/docs/scheduler.md @@ -0,0 +1,15 @@ +# Scheduler + +Host cron invokes the same Docker CLI used by an operator. The production crontab is installed only after deployment review. + +Suggested v1 schedule: + +```cron +*/15 * * * * cd /srv/email-list-system && docker compose run --rm email-list subscriber import /data/inbox/subscriber-operations.jsonl --json +*/15 * * * * cd /srv/email-list-system && docker compose run --rm email-list welcome run --json +15 * * * * cd /srv/email-list-system && docker compose run --rm email-list suppression reconcile --json +30 * * * * cd /srv/email-list-system && docker compose run --rm email-list campaign run-due-followups --campaign-dir /app/campaigns/sent --json +10 2 * * * cd /srv/email-list-system && docker compose run --rm email-list backup create --json +``` + +The initial subscriber import uses `--no-welcome`. `welcome run` fails closed while `templates/welcome.md` remains the explicit placeholder. The due-follow-up command fails closed if telemetry is unavailable, no matching campaign artifact is present, the original authorization is invalid, or the Postmark suppression check fails. diff --git a/docs/system-map.md b/docs/system-map.md new file mode 100644 index 0000000..4679cd4 --- /dev/null +++ b/docs/system-map.md @@ -0,0 +1,241 @@ +# System Map + +This document shows the system boundaries, replaceable module contracts, and primary operating flows for the Automation-Based Email List System. + +## System Context + +```mermaid +flowchart LR + human["Human architect
writes Markdown + gives
send-and-schedule directive"] + agent["Persistent AI operator
documented skill + restricted
terminal access"] + repo[("Public Git repository
Markdown, templates, schemas,
code, tests, sanitized receipts")] + + subgraph emailvm["Email-list VM"] + container["Email-list Docker container
deterministic Python application"] + runtime[("Private persistent volume
SQLite, backups, logs,
detailed receipts")] + scheduler["Cron / VM scheduler
subscriber imports, welcomes,
due follow-ups, reconciliation"] + container <--> runtime + scheduler --> container + end + + postmark["Postmark
delivery, broadcast unsubscribe,
suppression"] + telemetry["Existing telemetry server
Postmark webhook ingestion
and campaign analysis"] + recipient["Email recipient"] + + human -->|"writes finished campaign"| repo + human -->|"one directive authorizes initial send
+ configured follow-up"| agent + agent -->|"reads, validates, schedules,
verifies, and reports"| repo + agent -->|"runs authorized deterministic commands"| container + repo -->|"Git deployment / checked-out content"| container + container -->|"provider adapter"| postmark + postmark -->|"email"| recipient + recipient -->|"open, click, unsubscribe,
complaint"| postmark + postmark -->|"existing webhooks"| telemetry + container <-->|"versioned telemetry contract"| telemetry + container -->|"sanitized receipts only"| repo +``` + +## Human Handoff and AI Operating Envelope + +```mermaid +flowchart LR + human["Human"] + handoff["Finished Markdown + directive
send now; resend apparent
non-openers in 4 or 5 days"] + agent["Authorized AI agent"] + cli["Deterministic CLI safety boundary"] + send["Validate + send initial campaign"] + schedule["Create durable follow-up schedule"] + monitor["Monitor + verify + write receipt"] + followup["Query telemetry + recheck suppressions
+ send one authorized follow-up"] + exception["Return only unresolved exception
or scope change to human"] + + human --> handoff --> agent --> cli + cli --> send --> schedule --> monitor --> followup --> monitor + cli -->|"failed check, ambiguous authority,
or material change required"| exception --> human +``` + +The intended steady state has one human handoff, not one approval per mechanical step. The CLI enforces the authorization and safety boundary while the AI handles orchestration and exceptions. + +## Application Modules and Replaceable Boundaries + +```mermaid +flowchart TB + cli["CLI contract
--dry-run, --json, exit codes"] + skill["AI skill
workflow, authorization,
and escalation rules"] + scheduler["Scheduler entrypoint"] + + cli --> usecases["Application use cases
campaigns, subscribers, resends,
reconciliation, backups"] + skill --> cli + scheduler --> cli + + usecases --> campaign["Campaign module"] + usecases --> subscriber["Subscriber module"] + usecases --> authorization["Authorization guard"] + usecases --> sendstate["Send-state module"] + usecases --> receipt["Receipt module"] + + campaign --> renderer{{"Renderer contract"}} + subscriber --> store{{"Storage contract"}} + sendstate --> provider{{"Email-provider contract"}} + usecases --> telemetrycontract{{"Telemetry contract"}} + + renderer --> markdown["v1: Markdown + templates"] + store --> sqlite[("v1: SQLite")] + provider --> postmark["v1: Postmark"] + telemetrycontract --> telemetry["v1: existing telemetry server"] + + migrations["Versioned migrations"] --> sqlite + backups["Backup / restore"] --> sqlite + schemas["Versioned schemas"] -. "validate boundaries" .-> cli + schemas -.-> renderer + schemas -.-> telemetrycontract + schemas -.-> receipt +``` + +The diamond-shaped contracts are deliberate swap points. Core campaign and subscriber rules depend on those contracts, not on Postmark, SQLite, a specific Markdown library, or the telemetry server's internal implementation. + +## Campaign Send Flow + +```mermaid +sequenceDiagram + participant Human as Human + participant Agent as Authorized AI agent + participant Repo as Git repository + participant CLI as Email-list CLI + participant Cron as Cron scheduler + participant DB as SQLite + participant PM as Postmark + participant TS as Telemetry server + + Human->>Repo: Write or revise campaign Markdown + Human->>Agent: Send campaign and follow up in 4 to 5 days + Agent->>CLI: Validate and preview exact campaign + CLI->>Repo: Read exact content and template + CLI-->>Agent: Rendered preview, checks, recipient estimate + Agent->>CLI: Record human directive and execute authorized send + CLI->>DB: Store authorization hashes and follow-up parameters + CLI->>DB: Create immutable recipient snapshot + CLI->>PM: Reconcile current suppressions + PM-->>CLI: Current suppression result + CLI->>DB: Exclude ineligible recipients + loop Idempotent batches + CLI->>PM: Submit unsent recipients + PM-->>CLI: Request and message identifiers + CLI->>DB: Record per-recipient acceptance or failure + end + Agent->>Cron: Schedule durable apparent-non-opener follow-up + Agent->>CLI: Verify initial completion and write receipt + PM-->>TS: Delivery and engagement webhooks + Cron->>CLI: Run due follow-ups + CLI->>TS: Query apparent non-openers + TS-->>CLI: Versioned campaign telemetry response + CLI->>PM: Recheck suppressions and send authorized follow-up + PM-->>CLI: Follow-up request and message identifiers + CLI->>DB: Record follow-up completion + Agent->>CLI: Inspect status and exceptions + CLI->>Repo: Write sanitized initial and follow-up receipts +``` + +## Subscriber and Welcome Flow + +```mermaid +flowchart LR + request["Human appends subscribe record
to private JSON / JSONL inbox"] + cron["Cron reads inbox on schedule"] + validate["CLI validates schema, operation ID,
source, consent, and duplication"] + apply["Transactional SQLite update
with status history"] + welcome["Exactly-once welcome send"] + postmark["Postmark"] + receipt["Sanitized receipt"] + agent["AI inspects exceptions
when needed"] + + request --> cron --> validate --> apply --> welcome --> postmark + apply --> receipt + welcome --> receipt + receipt --> agent +``` + +## Unsubscribe and Suppression Flow + +```mermaid +flowchart LR + recipient["Recipient"] + human["Human observes an external
unsubscribe request"] + inbox["Private JSON / JSONL
operations inbox"] + cron["Cron import"] + postmark["Postmark one-click unsubscribe
and Broadcast suppression"] + telemetry["Existing telemetry server
subscription-change webhook"] + reconcile["Email-list suppression
reconciliation command"] + sqlite[("Local SQLite status mirror")] + sendguard["Pre-batch suppression guard"] + + recipient -->|"unsubscribe or complaint"| postmark + human -->|"append unsubscribe operation"| inbox --> cron + cron -->|"idempotent local suppression"| sqlite + postmark -->|"webhook"| telemetry + telemetry -->|"versioned query response"| reconcile + postmark -->|"authoritative suppression query"| reconcile + reconcile -->|"reviewed, idempotent update"| sqlite + sqlite --> sendguard + postmark --> sendguard + sendguard -->|"only eligible recipients proceed"| send["Campaign send"] +``` + +## AI Access Rights + +```mermaid +flowchart TB + identity["Dedicated AI agent identity"] + terminal["Restricted persistent terminal
or task-runner access"] + repo["Read campaign and operational repo
write only through normal Git authority"] + commands["Allowed email-list CLI commands"] + status["Read health, receipts,
campaign and telemetry status"] + secrets["Runtime injects scoped secrets
secrets are not shown or committed"] + blocked["Blocked boundaries
no direct SQLite mutation
no telemetry DB access
no suppression bypass
no unauthorized send"] + + identity --> terminal + terminal --> repo + terminal --> commands + terminal --> status + secrets --> commands + terminal -. "enforced least privilege" .-> blocked +``` + +The model and persistent-agent implementation may change. These access boundaries remain stable and determine what any selected agent is allowed to do. + +## Trust and Data Boundaries + +| Boundary | May cross | Must not cross | +| --- | --- | --- | +| Public Git repository | Code, schemas, templates, campaign content, synthetic examples, sanitized receipts | Subscriber addresses, credentials, production databases, raw telemetry, private logs | +| AI/human to CLI | Validated structured input and documented commands | Direct production database manipulation or authorization bypass | +| AI agent identity to VM | Allowlisted CLI commands, required repository files, scoped runtime status, and approved network endpoints | General administrator access, unrelated applications, raw secrets, or unrestricted shell authority | +| Email app to Postmark | Required recipient and campaign delivery data | Database credentials or unrelated telemetry | +| Email app to telemetry server | Authenticated versioned queries and minimum necessary results | Direct access to the telemetry database | +| Docker container to host | Declared configuration, network endpoints, persistent-volume paths | Undeclared host filesystem or shared application dependencies | + +## Failure Boundaries + +- A telemetry outage prevents telemetry-dependent resends but does not corrupt subscriber or send state. +- A Postmark outage leaves recipients pending or safely retryable; it does not cause a whole-campaign resend. +- A renderer replacement cannot approve or send email. +- A scheduler failure can be recovered by running the same idempotent CLI command manually. +- A container replacement preserves state through the private persistent volume. +- A database migration is not allowed without a backup, versioned migration, and validation. +- An unresolved suppression mismatch fails closed for the affected recipient. + +## Deployment and Release Flow + +```mermaid +flowchart LR + dev["Isolated development
implementation + tests"] + review["Human review
docs, diff, tests, receipts"] + git["Git remote
approved revision"] + deploy["Email-list VM
pull/build pinned revision"] + migrate["Backup + versioned migration"] + validate["Health check + test-mode send"] + release["Validated release + version tag"] + + dev --> review --> git --> deploy --> migrate --> validate --> release + validate -->|"failure: roll back image and restore if needed"| deploy +``` diff --git a/docs/telemetry-api.md b/docs/telemetry-api.md new file mode 100644 index 0000000..641eb1e --- /dev/null +++ b/docs/telemetry-api.md @@ -0,0 +1,14 @@ +# Ops Monitor telemetry API contract + +Ops Monitor remains the owner of raw Postmark event ingestion. The email-list system consumes an authenticated bearer-token API rather than reading Ops Monitor files directly. + +## Required v1 endpoints + +- `GET /v1/email/paddlenet/campaigns/{campaign_id}/summary` +- `GET /v1/email/paddlenet/campaigns/{campaign_id}/apparent-non-openers` + +Both return `schema_version: "1.0"`. The apparent-non-opener response includes only normalized email addresses eligible for one authorized follow-up. The client applies current local and Postmark suppression checks again before delivery. + +The endpoint receives `Authorization: Bearer `. The token is distinct from Postmark credentials and is stored only in each VM's private `.env` file. + +The v1 follow-up uses the original authorized subject unchanged and runs at most once per campaign. A scheduled execution reads this endpoint, intersects the result with the original recipient snapshot, then rechecks active local status and current Postmark suppressions. diff --git a/operations/examples/.gitkeep b/operations/examples/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/operations/examples/.gitkeep @@ -0,0 +1 @@ + diff --git a/operations/examples/subscriber-operations.jsonl b/operations/examples/subscriber-operations.jsonl new file mode 100644 index 0000000..9805d33 --- /dev/null +++ b/operations/examples/subscriber-operations.jsonl @@ -0,0 +1 @@ +{"schema_version":"1.0","operation_id":"synthetic-subscriber-1","operation":"subscribe","email":"synthetic@example.com","source":"synthetic-test","requested_at":"2026-08-13T00:00:00Z"} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..76356d9 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,26 @@ +[build-system] +requires = ["hatchling>=1.25"] +build-backend = "hatchling.build" + +[project] +name = "paddlenet-email-list-system" +version = "0.1.0" +description = "Deterministic, CLI-operated email-list automation for PaddleNET." +readme = "README.md" +requires-python = ">=3.12" +license = "MIT" +authors = [{ name = "Eddie Soehnel" }] +dependencies = [] + +[project.optional-dependencies] +dev = ["pytest>=8.3"] + +[project.scripts] +email-list = "email_list.cli:main" + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = ["-ra"] + +[tool.hatch.build.targets.wheel] +packages = ["src/email_list"] diff --git a/receipts/.gitkeep b/receipts/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/receipts/.gitkeep @@ -0,0 +1 @@ + diff --git a/receipts/README.md b/receipts/README.md new file mode 100644 index 0000000..37b277c --- /dev/null +++ b/receipts/README.md @@ -0,0 +1,3 @@ +# Sanitized Receipts + +Only public-safe, sanitized example receipts may be committed here. Production receipts, subscriber identifiers, raw provider responses, credentials, and private telemetry remain in private runtime storage outside Git. diff --git a/repository-variables.json b/repository-variables.json new file mode 100644 index 0000000..69dde9a --- /dev/null +++ b/repository-variables.json @@ -0,0 +1,42 @@ +{ + "$schema": "./schemas/repository-variables.schema.json", + "schema_version": "1.0", + "purpose": "Verified stable inputs for maintaining the sanitized public automation-based email-list system.", + "repository_profile": "software-automation", + "identity": { + "authors": [ + { + "name": "Eddie Soehnel" + } + ], + "publisher": { + "name": "adminprojects" + }, + "maintainer": { + "name": "Eddie Soehnel" + } + }, + "repository": { + "repository_id": "adminprojects-automation-based-email-list-system-open", + "name": "automation-based-email-list-system-open", + "title": "Automation-Based Email List System", + "canonical_url": "https://projects.eddiesoehnel.com/adminprojects/automation-based-email-list-system-OPEN", + "organization": { + "id": "adminprojects", + "name": "adminprojects", + "url": "https://projects.eddiesoehnel.com/adminprojects" + } + }, + "rights": { + "license": "MIT", + "license_file": "LICENSE" + }, + "skill_defaults": { + "task_id": "structure-ai-ready-repository", + "require_plan_approval": true, + "preserve_existing_content": true, + "use_smallest_fitting_profile": true + }, + "verified_by": "Configured origin, Git author identity, public publication workflow, and the established MIT convention in the related email-campaigns-prod-app-OPEN repository; user requested template application on 2026-08-15", + "verified_at": "2026-08-15" +} diff --git a/repository.json b/repository.json new file mode 100644 index 0000000..1bc6f9e --- /dev/null +++ b/repository.json @@ -0,0 +1,238 @@ +{ + "$schema": "./schemas/repository.schema.json", + "schema_version": "1.0", + "repository_id": "adminprojects-automation-based-email-list-system-open", + "name": "automation-based-email-list-system-open", + "title": "Automation-Based Email List System", + "description": "A sanitized open-source Python system for AI-operated, human-authorized email-list and campaign workflows.", + "summary": "Provides deterministic CLI, SQLite, Docker, Postmark, telemetry, campaign, subscriber, backup, receipt, scheduling, and AI-skill components for operating a small email list while keeping human authorization, suppression safety, private runtime state, and publication hygiene explicit.", + "canonical_url": "https://projects.eddiesoehnel.com/adminprojects/automation-based-email-list-system-OPEN", + "organization": { + "id": "adminprojects", + "name": "adminprojects", + "url": "https://projects.eddiesoehnel.com/adminprojects" + }, + "repository_status": "active", + "visibility": "public", + "maturity": "beta", + "version": "0.1.0", + "created_at": "2026-08-13", + "updated_at": "2026-08-15", + "authors": [ + { + "name": "Eddie Soehnel" + } + ], + "publisher": { + "name": "adminprojects" + }, + "resource_types": [ + "software", + "application", + "script", + "skill", + "workflow", + "template", + "documentation" + ], + "topics": { + "technology": [ + "python", + "sqlite", + "docker", + "postmark", + "ai-agents" + ], + "business_function": [ + "email-marketing", + "email-operations", + "subscriber-management" + ], + "industry_context": [ + "outdoor-industry" + ], + "artifact_type": [ + "software", + "skill", + "workflow" + ], + "concepts": [ + "human-authorization", + "deterministic-automation", + "suppression-safety", + "apparent-non-openers" + ] + }, + "audiences": [ + "small organizations operating an email list", + "developers building safety-conscious email automation", + "AI agents operating reviewed deterministic workflows" + ], + "problems_solved": [ + "Operate campaigns and subscriber changes without a dedicated administration dashboard.", + "Bind consequential email actions to explicit human authorization and deterministic controls.", + "Keep subscriber data, credentials, telemetry, databases, and detailed receipts outside public Git history." + ], + "capabilities": [ + "Validate, render, authorize, send, and track Markdown-authored email campaigns.", + "Apply idempotent subscribe and unsubscribe operations through a private JSONL inbox.", + "Reconcile suppressions, create backups and receipts, and schedule approved follow-ups.", + "Operate through scoped AI skills backed by deterministic CLI commands." + ], + "use_cases": [ + "Send a reviewed campaign and schedule one authorized apparent-non-opener follow-up.", + "Add or remove an individual subscriber with consent and audit controls.", + "Deploy a compact Dockerized email-list system using private runtime configuration.", + "Study or adapt a sanitized AI-operated email workflow." + ], + "required_inputs": [ + { + "name": "Environment configuration", + "description": "Provider, sender, telemetry, filesystem, and credential values supplied outside Git.", + "required": true, + "sensitivity": "secret-or-private" + }, + { + "name": "Reviewed campaign or subscriber operation", + "description": "A validated Markdown campaign or private versioned JSON/JSONL operation.", + "required": true, + "sensitivity": "potentially-sensitive" + }, + { + "name": "Human authorization", + "description": "An explicit directive covering the exact consequential operation.", + "required": true, + "sensitivity": "non-sensitive" + } + ], + "expected_outputs": [ + { + "name": "Validated email operation", + "description": "A deterministic campaign, subscriber, suppression, backup, or follow-up result.", + "format": "json" + }, + { + "name": "Sanitized receipt", + "description": "A public-safe record of validation and execution without credentials or subscriber data.", + "format": "json-or-markdown" + } + ], + "entrypoints": { + "human": "README.md", + "ai": "AGENTS.md", + "primary_skill": "skills/email-list-operator/SKILL.md", + "primary_agent": null, + "primary_script": "src/email_list/cli.py", + "primary_template": "templates/campaign.html" + }, + "contents": [ + { + "path": "README.md", + "type": "documentation", + "title": "Repository Overview And System Specification", + "description": "Purpose, architecture, workflows, safeguards, and implementation expectations.", + "required_for_use": true + }, + { + "path": "src/email_list", + "type": "software", + "title": "Email List Application", + "description": "Python CLI and deterministic email-list operating modules.", + "required_for_use": true + }, + { + "path": "skills", + "type": "skill-collection", + "title": "Email List AI Skills", + "description": "Scoped operating skills for campaigns and subscriber changes.", + "required_for_use": false + }, + { + "path": "docs", + "type": "documentation", + "title": "Architecture And Operations Documentation", + "description": "Deployment, telemetry, scheduling, data-model, and operator guidance.", + "required_for_use": false + }, + { + "path": "schemas", + "type": "schema-collection", + "title": "Machine-Readable Contracts", + "description": "Repository metadata and email-operation JSON schemas.", + "required_for_use": false + }, + { + "path": "PUBLICATION_WORKFLOW.md", + "type": "governance", + "title": "Public Publication Workflow", + "description": "Sanitization and human-review rules for public updates.", + "required_for_use": true + } + ], + "relationships": { + "part_of": [ + "PaddleNET" + ], + "supports": [], + "depends_on": [ + "Postmark", + "an authenticated campaign telemetry service" + ], + "related_resources": [ + "https://projects.eddiesoehnel.com/adminprojects/email-campaigns-prod-app-OPEN" + ], + "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": "sanitized-public-derivative", + "creation_method": "human-authored-and-ai-assisted", + "contributors": [ + "Eddie Soehnel" + ], + "source_references": [] + }, + "maintenance": { + "maintainer": "Eddie Soehnel", + "review_frequency": "as-needed", + "last_reviewed_at": "2026-08-15", + "deprecated": false, + "archived": false + }, + "ai_retrieval": { + "read_first": [ + "README.md", + "AUTHOR.md", + "repository-variables.json", + "repository.json", + "AGENTS.md", + "PUBLICATION_WORKFLOW.md", + "sanitization-map.md", + "skills.md" + ], + "retrieve_as_needed": [ + "docs", + "skills", + "schemas", + "src/email_list", + "templates" + ], + "exclude_by_default": [ + "receipts/", + "tasks/", + "tests/" + ], + "instructions": "Read the declared entry points first, retrieve only files needed for the task, and never infer that private runtime values may be published or consequential email actions are authorized." + } +} diff --git a/sanitization-map.md b/sanitization-map.md new file mode 100644 index 0000000..1398e85 --- /dev/null +++ b/sanitization-map.md @@ -0,0 +1,20 @@ +# Sanitization Map + +The public tree uses these durable replacement classes: + +| Sensitive category | Public form | +| --- | --- | +| Email-list VM address | `10.0.0.10` | +| Telemetry service address | `10.0.0.20` | +| Live webhook host | `telemetry.example.com` | +| Deployment user | `deploy-user` | +| Deployment checkout | `/srv/email-list-system` | +| Private backup location | `/path/to/private-backups` | +| Local workstation files | `C:\path\to\...` or `/path/to/local/...` | +| Private Git remote | `https://git.example.com/example-org/email-list-system.git` | +| SSH key | `example_ssh_key` | +| Operations-monitor host | `ops-monitor-host` | +| Tunnel name | `example-tunnel` | +| Private source commit reference | `` | + +PaddleNET, Postmark, approved sender addresses, and author identity are intentionally retained under the publication policy. Synthetic addresses under `example.com` are fixtures, not subscriber data. \ No newline at end of file diff --git a/schemas/.gitkeep b/schemas/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/schemas/.gitkeep @@ -0,0 +1 @@ + diff --git a/schemas/README.md b/schemas/README.md new file mode 100644 index 0000000..5bf1cfc --- /dev/null +++ b/schemas/README.md @@ -0,0 +1,3 @@ +# Schemas + +This directory contains versioned email-operation contracts plus the AI-ready repository metadata schemas. Update a schema and its tests when a declared contract changes. diff --git a/schemas/cli-result-1.0.json b/schemas/cli-result-1.0.json new file mode 100644 index 0000000..290ddfb --- /dev/null +++ b/schemas/cli-result-1.0.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Email-list CLI result v1.0", + "type": "object", + "required": ["schema_version", "command", "status"], + "properties": { + "schema_version": {"const": "1.0"}, + "command": {"type": "string", "pattern": "^[a-z]+\\.[a-z_]+$"}, + "status": {"enum": ["ok", "planned", "failed"]}, + "dry_run": {"type": "boolean"} + }, + "additionalProperties": true +} diff --git a/schemas/repository-variables.schema.json b/schemas/repository-variables.schema.json new file mode 100644 index 0000000..2b012d6 --- /dev/null +++ b/schemas/repository-variables.schema.json @@ -0,0 +1,179 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://projects.eddiesoehnel.com/adminprojects/repo-template/schemas/repository-variables.schema.json", + "title": "Repository Structure Skill Variables", + "description": "Verified stable identity, repository, rights, profile, and workflow inputs reused by repository-structure skills.", + "type": "object", + "required": [ + "schema_version", + "purpose", + "repository_profile", + "identity", + "repository", + "rights", + "skill_defaults", + "verified_by", + "verified_at" + ], + "properties": { + "$schema": { + "type": "string" + }, + "schema_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+$" + }, + "purpose": { + "type": "string", + "minLength": 1 + }, + "repository_profile": { + "enum": [ + "documentation-guide", + "skill-workflow", + "software-automation", + "dataset", + "custom" + ] + }, + "identity": { + "type": "object", + "required": [ + "authors", + "publisher", + "maintainer" + ], + "properties": { + "authors": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/namedEntity" + } + }, + "publisher": { + "$ref": "#/$defs/namedEntity" + }, + "maintainer": { + "$ref": "#/$defs/namedEntity" + } + }, + "additionalProperties": false + }, + "repository": { + "type": "object", + "required": [ + "repository_id", + "name", + "title", + "canonical_url" + ], + "properties": { + "repository_id": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "title": { + "type": "string", + "minLength": 1 + }, + "canonical_url": { + "type": [ + "string", + "null" + ], + "format": "uri" + }, + "organization": { + "oneOf": [ + { + "$ref": "#/$defs/namedEntity" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "rights": { + "type": "object", + "required": [ + "license", + "license_file" + ], + "properties": { + "license": { + "type": "string", + "minLength": 1 + }, + "license_file": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "skill_defaults": { + "type": "object", + "required": [ + "task_id", + "require_plan_approval", + "preserve_existing_content", + "use_smallest_fitting_profile" + ], + "properties": { + "task_id": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "require_plan_approval": { + "type": "boolean" + }, + "preserve_existing_content": { + "type": "boolean" + }, + "use_smallest_fitting_profile": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "verified_by": { + "type": "string", + "minLength": 1 + }, + "verified_at": { + "type": "string", + "format": "date" + } + }, + "$defs": { + "namedEntity": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false +} diff --git a/schemas/repository.schema.json b/schemas/repository.schema.json new file mode 100644 index 0000000..906da9e --- /dev/null +++ b/schemas/repository.schema.json @@ -0,0 +1,397 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://projects.eddiesoehnel.com/adminprojects/repo-template/schemas/repository.schema.json", + "title": "AI-Ready Repository Manifest", + "description": "Machine-readable identity, discovery, rights, provenance, maintenance, and AI retrieval metadata for an AI-ready repository.", + "type": "object", + "required": [ + "schema_version", + "repository_id", + "name", + "title", + "description", + "authors", + "publisher", + "repository_status", + "visibility", + "maturity", + "version", + "resource_types", + "entrypoints", + "rights", + "maintenance", + "ai_retrieval" + ], + "properties": { + "$schema": { + "type": "string" + }, + "schema_version": { + "type": "string", + "pattern": "^\\d+\\.\\d+$" + }, + "repository_id": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "title": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 1 + }, + "summary": { + "type": "string" + }, + "canonical_url": { + "type": [ + "string", + "null" + ], + "format": "uri" + }, + "organization": { + "$ref": "#/$defs/namedEntity" + }, + "authors": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/namedEntity" + } + }, + "publisher": { + "$ref": "#/$defs/namedEntity" + }, + "repository_status": { + "enum": [ + "draft", + "active", + "deprecated", + "archived", + "superseded" + ] + }, + "visibility": { + "enum": [ + "public", + "restricted", + "private" + ] + }, + "maturity": { + "enum": [ + "concept", + "experimental", + "prototype", + "beta", + "stable", + "production" + ] + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?$" + }, + "created_at": { + "type": "string", + "format": "date" + }, + "updated_at": { + "type": "string", + "format": "date" + }, + "resource_types": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "topics": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + } + }, + "audiences": { + "$ref": "#/$defs/stringArray" + }, + "problems_solved": { + "$ref": "#/$defs/stringArray" + }, + "capabilities": { + "$ref": "#/$defs/stringArray" + }, + "use_cases": { + "$ref": "#/$defs/stringArray" + }, + "required_inputs": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "description", + "required", + "sensitivity" + ], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "sensitivity": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "expected_outputs": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "description", + "format" + ], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "format": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "entrypoints": { + "type": "object", + "required": [ + "human", + "ai" + ], + "properties": { + "human": { + "type": "string" + }, + "ai": { + "type": "string" + }, + "primary_skill": { + "type": [ + "string", + "null" + ] + }, + "primary_agent": { + "type": [ + "string", + "null" + ] + }, + "primary_script": { + "type": [ + "string", + "null" + ] + }, + "primary_template": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "contents": { + "type": "array", + "items": { + "type": "object", + "required": [ + "path", + "type", + "title", + "description", + "required_for_use" + ], + "properties": { + "path": { + "type": "string" + }, + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required_for_use": { + "type": "boolean" + } + }, + "additionalProperties": false + } + }, + "relationships": { + "type": "object", + "additionalProperties": { + "$ref": "#/$defs/stringArray" + } + }, + "access": { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + }, + "rights": { + "type": "object", + "required": [ + "license", + "license_file" + ], + "properties": { + "license": { + "type": "string" + }, + "license_file": { + "type": "string" + }, + "usage_guidance": { + "type": "string" + } + }, + "additionalProperties": false + }, + "provenance": { + "type": "object", + "properties": { + "origin_type": { + "type": "string" + }, + "creation_method": { + "type": "string" + }, + "contributors": { + "type": "array" + }, + "source_references": { + "$ref": "#/$defs/stringArray" + } + }, + "additionalProperties": false + }, + "maintenance": { + "type": "object", + "required": [ + "maintainer", + "review_frequency", + "deprecated", + "archived" + ], + "properties": { + "maintainer": { + "type": [ + "string", + "null" + ] + }, + "review_frequency": { + "type": "string" + }, + "last_reviewed_at": { + "type": [ + "string", + "null" + ], + "format": "date" + }, + "deprecated": { + "type": "boolean" + }, + "archived": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "ai_retrieval": { + "type": "object", + "required": [ + "read_first", + "retrieve_as_needed", + "exclude_by_default", + "instructions" + ], + "properties": { + "read_first": { + "$ref": "#/$defs/stringArray" + }, + "retrieve_as_needed": { + "$ref": "#/$defs/stringArray" + }, + "exclude_by_default": { + "$ref": "#/$defs/stringArray" + }, + "instructions": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "$defs": { + "stringArray": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "namedEntity": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false +} diff --git a/schemas/subscriber-operation-1.0.json b/schemas/subscriber-operation-1.0.json new file mode 100644 index 0000000..d279412 --- /dev/null +++ b/schemas/subscriber-operation-1.0.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Private subscriber operation v1.0", + "type": "object", + "required": ["schema_version", "operation_id", "operation", "email", "requested_at"], + "properties": { + "schema_version": {"const": "1.0"}, + "operation_id": {"type": "string", "minLength": 1}, + "operation": {"enum": ["subscribe", "unsubscribe"]}, + "email": {"type": "string", "format": "email"}, + "source": {"type": "string"}, + "reason": {"type": "string"}, + "requested_at": {"type": "string", "format": "date-time"}, + "consent_at": {"type": "string", "format": "date-time"}, + "consent_note": {"type": "string"} + }, + "additionalProperties": false +} diff --git a/schemas/telemetry-api-1.0.json b/schemas/telemetry-api-1.0.json new file mode 100644 index 0000000..ece10f6 --- /dev/null +++ b/schemas/telemetry-api-1.0.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Ops Monitor telemetry API v1.0", + "type": "object", + "required": ["schema_version", "campaign_id"], + "properties": { + "schema_version": {"const": "1.0"}, + "campaign_id": {"type": "string"}, + "apparent_non_openers": {"type": "array", "items": {"type": "string", "format": "email"}}, + "summary": {"type": "object"} + }, + "additionalProperties": false +} diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 0000000..f51afbc --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,6 @@ +# Repository Scripts + +- `validate_repository.py` validates AI-ready repository metadata, paths, identity, versions, and Markdown links. +- `leak-scan.ps1` scans the public tree for credentials, private data, and unsanitized operational identifiers. + +Run both before publication and inspect all findings rather than treating a clean exit as proof that content is safe. diff --git a/scripts/leak-scan.ps1 b/scripts/leak-scan.ps1 new file mode 100644 index 0000000..6d330a2 --- /dev/null +++ b/scripts/leak-scan.ps1 @@ -0,0 +1,13 @@ +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +Push-Location $repoRoot +try { + rg -n --hidden -i --glob '!.git/**' --glob '!scripts/leak-scan.ps1' '(password|passwd|secret|token|api[_-]?key|apikey|bearer|authorization|credential|private key|smtp_pass)' . + if ($LASTEXITCODE -gt 1) { exit $LASTEXITCODE } + rg -n --hidden --glob '!.git/**' --glob '!scripts/leak-scan.ps1' '((?:192\.168\.|172\.(?:1[6-9]|2[0-9]|3[01])\.|10\.)[0-9.]+|/mnt/c/Users|C:\\Users|/home/|/srv/data|\.csv|\.jsonl|\.sql|\.pem|id_rsa|id_ed25519)' . + if ($LASTEXITCODE -gt 1) { exit $LASTEXITCODE } + git ls-files | rg '(__pycache__|\.pyc$|\.env$|\.csv$|\.jsonl$|\.sql$|\.tar\.gz$|\.pem$|id_rsa|id_ed25519)' + if ($LASTEXITCODE -gt 1) { exit $LASTEXITCODE } +} finally { + Pop-Location +} \ No newline at end of file diff --git a/scripts/validate_repository.py b/scripts/validate_repository.py new file mode 100644 index 0000000..8b92825 --- /dev/null +++ b/scripts/validate_repository.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +"""Validate the implemented AI-ready repository template without dependencies.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import sys +from urllib.parse import unquote + + +REQUIRED_PATHS = ( + "AGENTS.md", + "AUTHOR.md", + "CHANGELOG.md", + "CITATION.cff", + "CONTRIBUTING.md", + "LICENSE", + "README.md", + "SECURITY.md", + "UPDATES.md", + "VERSION", + "docs/README.md", + "receipts/README.md", + "repository.json", + "repository-variables.json", + "schemas/README.md", + "schemas/repository.schema.json", + "schemas/repository-variables.schema.json", + "scripts/README.md", + "skills.md", + "skills/email-list-add-subscriber/SKILL.md", + "skills/email-list-operator/SKILL.md", + "skills/email-list-remove-subscriber/SKILL.md", + "tasks/README.md", + "tests/README.md", +) + +MANIFEST_REQUIRED_KEYS = ( + "schema_version", + "repository_id", + "name", + "title", + "description", + "authors", + "publisher", + "repository_status", + "visibility", + "maturity", + "version", + "resource_types", + "entrypoints", + "rights", + "maintenance", + "ai_retrieval", +) + +CONTENT_INDEX_REQUIRED_KEYS = ( + "schema_version", + "collection_id", + "title", + "description", + "updated_at", + "items", +) + +CONTENT_ITEM_REQUIRED_KEYS = ( + "content_id", + "title", + "description", + "content_type", + "path", + "status", +) + +MARKDOWN_LINK = re.compile(r"(? argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("repository", nargs="?", default=".", type=Path) + parser.add_argument("--json", action="store_true", help="Emit JSON") + return parser.parse_args() + + +def read_text(path: Path) -> str: + return path.read_text(encoding="utf-8-sig") + + +def add(findings: list[dict[str, str]], level: str, message: str) -> None: + findings.append({"level": level, "message": message}) + + +def validate_manifest(root: Path, findings: list[dict[str, str]]) -> dict | None: + path = root / "repository.json" + try: + manifest = json.loads(read_text(path)) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + add(findings, "error", f"repository.json is invalid: {exc}") + return None + + for key in MANIFEST_REQUIRED_KEYS: + if key not in manifest: + add(findings, "error", f"repository.json lacks required key: {key}") + + entrypoints = manifest.get("entrypoints") + if not isinstance(entrypoints, dict): + add(findings, "error", "repository.json entrypoints must be an object") + else: + for name in ("human", "ai"): + value = entrypoints.get(name) + if not isinstance(value, str) or not value: + add(findings, "error", f"Missing {name} entrypoint") + elif not (root / value).exists(): + add(findings, "error", f"Declared {name} entrypoint does not exist: {value}") + for name, value in entrypoints.items(): + if name in ("human", "ai") or value is None: + continue + if not isinstance(value, str) or not (root / value).exists(): + add(findings, "error", f"Declared entrypoint does not exist: {name}={value}") + + contents = manifest.get("contents", []) + if not isinstance(contents, list): + add(findings, "error", "repository.json contents must be an array") + else: + for item in contents: + declared = item.get("path") if isinstance(item, dict) else None + if not declared or not (root / declared).exists(): + add(findings, "error", f"Declared contents path does not exist: {declared}") + declared_paths = { + item.get("path") for item in contents if isinstance(item, dict) + } + if (root / "content-index.json").is_file() and "content-index.json" not in declared_paths: + add(findings, "error", "repository.json contents must declare content-index.json") + + retrieval = manifest.get("ai_retrieval", {}) + if isinstance(retrieval, dict): + for field in ("read_first", "retrieve_as_needed"): + for declared in retrieval.get(field, []): + normalized = declared.rstrip("/") + if normalized and not (root / normalized).exists(): + add(findings, "error", f"AI retrieval path does not exist: {declared}") + + author_text = read_text(root / "AUTHOR.md") if (root / "AUTHOR.md").is_file() else "" + citation_text = read_text(root / "CITATION.cff") if (root / "CITATION.cff").is_file() else "" + license_text = read_text(root / "LICENSE") if (root / "LICENSE").is_file() else "" + authors = manifest.get("authors", []) + if not isinstance(authors, list) or not authors: + add(findings, "error", "repository.json authors must be a non-empty array") + else: + for author in authors: + name = author.get("name") if isinstance(author, dict) else None + if not name: + add(findings, "error", "Every repository.json author must have a name") + continue + if name not in author_text: + add(findings, "error", f"Author is absent from AUTHOR.md: {name}") + parts = name.split() + if not all(part in citation_text for part in parts): + add(findings, "error", f"Author is not aligned with CITATION.cff: {name}") + if name not in license_text: + add(findings, "error", f"Author is absent from LICENSE copyright: {name}") + + publisher = manifest.get("publisher") + publisher_name = publisher.get("name") if isinstance(publisher, dict) else None + if not publisher_name: + add(findings, "error", "repository.json publisher must have a name") + elif publisher_name not in author_text: + add(findings, "error", f"Publisher is absent from AUTHOR.md: {publisher_name}") + + maintainer = manifest.get("maintenance", {}).get("maintainer") + if maintainer and maintainer not in author_text: + add(findings, "error", f"Maintainer is absent from AUTHOR.md: {maintainer}") + return manifest + + +def validate_content_index(root: Path, findings: list[dict[str, str]]) -> dict | None: + path = root / "content-index.json" + try: + index = json.loads(read_text(path)) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + add(findings, "error", f"content-index.json is invalid: {exc}") + return None + + for key in CONTENT_INDEX_REQUIRED_KEYS: + if key not in index: + add(findings, "error", f"content-index.json lacks required key: {key}") + + items = index.get("items") + if not isinstance(items, list): + add(findings, "error", "content-index.json items must be an array") + return index + + content_ids: set[str] = set() + paths: set[str] = set() + related_references: list[tuple[str, str]] = [] + for position, item in enumerate(items): + label = f"content-index.json item {position + 1}" + if not isinstance(item, dict): + add(findings, "error", f"{label} must be an object") + continue + for key in CONTENT_ITEM_REQUIRED_KEYS: + if key not in item: + add(findings, "error", f"{label} lacks required key: {key}") + + content_id = item.get("content_id") + if not isinstance(content_id, str) or not content_id: + add(findings, "error", f"{label} has an invalid content_id") + elif content_id in content_ids: + add(findings, "error", f"Duplicate content_id in content-index.json: {content_id}") + else: + content_ids.add(content_id) + + declared = item.get("path") + if not isinstance(declared, str) or not declared: + add(findings, "error", f"{label} has an invalid path") + else: + declared_path = Path(declared) + if declared_path.is_absolute() or ".." in declared_path.parts: + add(findings, "error", f"Unsafe content-index.json path: {declared}") + elif declared in paths: + add(findings, "error", f"Duplicate path in content-index.json: {declared}") + else: + paths.add(declared) + if not (root / declared_path).is_file(): + add(findings, "error", f"Indexed content path does not exist: {declared}") + + related = item.get("related_content_ids", []) + if not isinstance(related, list): + add(findings, "error", f"{label} related_content_ids must be an array") + elif isinstance(content_id, str): + related_references.extend((content_id, value) for value in related) + + for source_id, related_id in related_references: + if related_id not in content_ids: + add( + findings, + "error", + f"Unknown related_content_id in content-index.json: {source_id} -> {related_id}", + ) + return index + + +def validate_variables( + root: Path, manifest: dict | None, findings: list[dict[str, str]] +) -> dict | None: + path = root / "repository-variables.json" + try: + variables = json.loads(read_text(path)) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + add(findings, "error", f"repository-variables.json is invalid: {exc}") + return None + + required = ( + "schema_version", + "purpose", + "repository_profile", + "identity", + "repository", + "rights", + "skill_defaults", + "verified_by", + "verified_at", + ) + for key in required: + if key not in variables: + add(findings, "error", f"repository-variables.json lacks required key: {key}") + + if not manifest: + return 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) + ] + if variable_authors != manifest_authors: + add(findings, "error", "Authors differ between repository-variables.json and repository.json") + + variable_publisher = identity.get("publisher", {}).get("name") + manifest_publisher = manifest.get("publisher", {}).get("name") + if variable_publisher != manifest_publisher: + add(findings, "error", "Publisher differs between repository-variables.json and repository.json") + + variable_maintainer = identity.get("maintainer", {}).get("name") + manifest_maintainer = manifest.get("maintenance", {}).get("maintainer") + if variable_maintainer != manifest_maintainer: + add(findings, "error", "Maintainer differs between repository-variables.json and repository.json") + + repository = variables.get("repository", {}) + for key in ("repository_id", "name", "title", "canonical_url", "organization"): + if repository.get(key) != manifest.get(key): + add( + findings, + "error", + f"{key} differs between repository-variables.json and repository.json", + ) + + variable_rights = variables.get("rights", {}) + manifest_rights = manifest.get("rights", {}) + for key in ("license", "license_file"): + if variable_rights.get(key) != manifest_rights.get(key): + add( + findings, + "error", + f"{key} differs between repository-variables.json and repository.json", + ) + return variables + + +def validate_versions(root: Path, manifest: dict | None, findings: list[dict[str, str]]) -> None: + version = read_text(root / "VERSION").strip() + if not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?", version): + add(findings, "error", f"VERSION is not semantic: {version!r}") + + if manifest and manifest.get("version") != version: + add(findings, "error", "VERSION differs from repository.json") + + citation = read_text(root / "CITATION.cff") + match = CITATION_VERSION.search(citation) + if not match or match.group(1) != version: + add(findings, "error", "VERSION differs from or is absent in CITATION.cff") + + changelog = read_text(root / "CHANGELOG.md") + if f"## [{version}]" not in changelog: + add(findings, "error", f"CHANGELOG.md lacks release heading for {version}") + + if manifest: + manifest_license = manifest.get("rights", {}).get("license") + citation_match = CITATION_LICENSE.search(citation) + if citation_match and manifest_license != citation_match.group(1): + add(findings, "error", "License differs between repository.json and CITATION.cff") + + +def validate_markdown_links(root: Path, findings: list[dict[str, str]]) -> None: + for path in root.rglob("*.md"): + if ".git" in path.parts: + continue + text = read_text(path) + for raw_target in MARKDOWN_LINK.findall(text): + target = raw_target.strip().split(maxsplit=1)[0].strip("<>") + if ( + not target + or target.startswith(("#", "http://", "https://", "mailto:")) + or "{{" in target + ): + continue + local = unquote(target.split("#", 1)[0]) + if local and not (path.parent / local).resolve().exists(): + add( + findings, + "error", + f"Broken relative Markdown link in {path.relative_to(root)}: {target}", + ) + + +def validate(root: Path) -> dict: + findings: list[dict[str, str]] = [] + root = root.resolve() + if not root.is_dir(): + add(findings, "error", "Repository path is not a directory") + return {"repository": str(root), "passed": False, "findings": findings} + + for relative in REQUIRED_PATHS: + if not (root / relative).exists(): + add(findings, "error", f"Missing required path: {relative}") + + if findings: + missing_core = any( + item["message"].endswith(("repository.json", "VERSION", "CITATION.cff", "CHANGELOG.md")) + for item in findings + ) + else: + missing_core = False + + manifest = None if not (root / "repository.json").is_file() else validate_manifest(root, findings) + if (root / "content-index.json").is_file(): + validate_content_index(root, findings) + if (root / "repository-variables.json").is_file(): + validate_variables(root, manifest, findings) + if not missing_core: + validate_versions(root, manifest, findings) + validate_markdown_links(root, findings) + + return { + "repository": str(root), + "passed": not any(item["level"] == "error" for item in findings), + "findings": findings, + } + + +def emit_markdown(result: dict) -> None: + print("# Repository Validation") + print(f"\n- Repository: `{result['repository']}`") + print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`") + print("\n## Findings") + if not result["findings"]: + print("\n- No validation errors found.") + else: + for finding in result["findings"]: + print(f"\n- {finding['level'].upper()}: {finding['message']}") + + +def main() -> int: + args = parse_args() + result = validate(args.repository) + 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()) diff --git a/skills.md b/skills.md new file mode 100644 index 0000000..119478d --- /dev/null +++ b/skills.md @@ -0,0 +1,21 @@ +# Repository Skills + +## `email-list-operator` + +- Path: `skills/email-list-operator/SKILL.md` +- Use for creating, reviewing, authorizing, deploying, sending, and following up on campaigns. +- Requires explicit human review and authorization before a live send. + +## `email-list-add-subscriber` + +- Path: `skills/email-list-add-subscriber/SKILL.md` +- Use for adding one consented subscriber through a private JSONL operation and deterministic import. +- Subscriber data must remain outside Git. + +## `email-list-remove-subscriber` + +- Path: `skills/email-list-remove-subscriber/SKILL.md` +- Use for unsubscribing one address through a private JSONL operation and deterministic import. +- Subscriber data must remain outside Git. + +Read `AGENTS.md` first. Each skill's approval, privacy, dry-run, and validation rules are mandatory; the existence of a skill is not standing authorization for consequential actions. diff --git a/skills/email-list-add-subscriber/SKILL.md b/skills/email-list-add-subscriber/SKILL.md new file mode 100644 index 0000000..3762a20 --- /dev/null +++ b/skills/email-list-add-subscriber/SKILL.md @@ -0,0 +1,93 @@ +--- +name: email-list-add-subscriber +description: Add one consented subscriber to the PaddleNET email list through the private, idempotent JSONL inbox and deterministic CLI. Use when a human asks to add a specific email address and provides its source and available consent information. Do not use for an initial bulk-list import, campaign sending, or welcome-email processing. +--- + +# Add PaddleNET Subscriber + +## Skill Shape + +- `service`: one private subscriber-add operation. + +## Contract + +Add at most one explicitly requested, consented email address through the deterministic CLI. Validate before mutation, preserve private data outside Git, and never send a campaign or welcome email as part of this skill. + +## Requires + +- One valid email address. +- Subscription source and available consent information. +- Authorized access to the production email VM and its Docker CLI. +- Human instruction to add this exact address. + +Stop and ask for missing source or consent information. Route an approved initial list import to the campaign/operator workflow; it requires separate review and `--no-welcome`. + +## Ensures + +- One private `subscribe` JSONL operation with a new operation ID and UTC request time. +- A completed dry run before any mutation. +- A sanitized CLI result and private receipt for a completed import. +- No Git commit, direct SQLite change, campaign send, welcome run, or Postmark API call. + +## Inputs + +- Email address. +- Source, such as `event-signup`, `website-form`, or `manual-consent`. +- Available consent timestamp and note; state any unknown detail rather than inventing it. + +## State Scope + +- `project`: write one private operation file under `/srv/email-list-system/runtime/inbox/` and let the CLI update private SQLite state. + +Never store the address, consent note, operation file, receipt, or runtime output in Git, campaign Markdown, or a final public report. + +## Workflow + +### Phase 1: Confirm the request + +1. Confirm the exact address, source, and available consent information. +2. Normalize and validate the address through the CLI path; do not guess corrections. +3. Stop if the request is an initial list import, lacks consent/source details, or asks to reactivate a suppressed address. + +### Phase 2: Plan the private operation + +1. Run `email-list system check --json` on the email VM. +2. Create one private JSONL record with `schema_version: "1.0"`, a new unique `operation_id`, `operation: "subscribe"`, the address, source, consent fields when available, and `requested_at` in UTC. +3. Run `subscriber import --dry-run --json`. +4. Inspect the result. Expected outcomes are a planned first subscription, an idempotent existing operation, or a visible block caused by an existing terminal suppression. + +### Phase 3: Apply and report + +1. Run `subscriber import --json` only after the dry run is valid. +2. Inspect the JSON result and private receipt path. +3. Report only a sanitized status: added, already active, already applied, or blocked by suppression. Do not report the address or consent note back unless the human supplied it in the current request and needs confirmation. + +## Validation + +Before finishing, confirm all of the following: + +1. The operation is `subscribe`, has a unique ID, and includes source and UTC request time. +2. The dry run completed before the live import. +3. The live result is one expected idempotent outcome. +4. No `welcome run` or campaign command was called. +5. The final report contains no token, raw receipt, or additional subscriber data. + +## Edge Cases + +- Existing active address: report `already_active`; do not create a duplicate. +- Replayed operation ID: report `already_applied`; do not create a duplicate. +- Existing unsubscribe, bounce, complaint, or manual suppression: report the block; never reactivate through this skill. +- Invalid address or missing source: stop before creating a private operation. +- Placeholder welcome template: the addition may remain welcome-eligible, but this skill does not run welcomes. + +## Anti-Patterns + +Do not edit SQLite, commit subscriber data, import a bulk list, use `--no-welcome` for an ordinary new addition, call Postmark directly, or send any email from this skill. + +## Ratchet Rules + +Turn each recurring intake failure into a durable guardrail: a required-input rule, JSONL fixture, validation check, STOP gate, or documented anti-pattern. Rerun the dry-run path after changing the skill. + +## Run Receipt + +Record privately: skill name, operation ID, source category, command results, receipt path, validation outcome, and unresolved risk. Give the human only a sanitized completion summary. diff --git a/skills/email-list-add-subscriber/agents/openai.yaml b/skills/email-list-add-subscriber/agents/openai.yaml new file mode 100644 index 0000000..8b29406 --- /dev/null +++ b/skills/email-list-add-subscriber/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Add PaddleNET Subscriber" + short_description: "Safely add a consented subscriber" + default_prompt: "Use $email-list-add-subscriber to add this consented PaddleNET subscriber." diff --git a/skills/email-list-operator/SKILL.md b/skills/email-list-operator/SKILL.md new file mode 100644 index 0000000..c465012 --- /dev/null +++ b/skills/email-list-operator/SKILL.md @@ -0,0 +1,95 @@ +--- +name: email-list-operator +description: Prepare, validate, approve, send, and follow up on PaddleNET broadcast campaigns through the deterministic email-list CLI. Use when a human asks to turn an approved PaddleNET Hub update into a campaign preview, approve and send an exact campaign, or run an already authorized campaign follow-up. Use the separate subscriber add/remove skills for subscriber changes. +--- + +# PaddleNET Email-List Operator + +## Skill Shape + +- `service`: bounded campaign preparation, delivery, and authorized follow-up workflow. + +## Contract + +Prepare a versioned delivery artifact from the approved PaddleNET Hub update, validate it before mutation, record an exact human directive before an initial send, and stop on authorization, rendering, suppression, provider, backup, deployment, or telemetry failure. + +## Requires + +- A source update in `C:\projects\paddlenet-forge\paddlenet-hub\platform-updates` or an already prepared campaign Markdown file. +- Human review before an initial send and an exact send-and-follow-up directive before authorization. +- The deployed reviewed Git revision, complete private `.env`, and required email-VM CLI access. +- Explicit human instruction before materially changing source wording, sender identity, audience, or the original follow-up subject. + +## Ensures + +- A versioned campaign Markdown artifact under `campaigns/drafts/` for the reviewed delivery content. +- JSON CLI result and private sanitized receipt for each completed mutation. +- No direct SQLite or telemetry-database mutation. +- At most one scheduled four-day apparent-non-opener follow-up with the original authorized subject. + +## Inputs + +- Hub update source, campaign Markdown, and reviewed campaign template. +- Exact human directive/reference and authorizer for the initial send. +- Runtime health, Postmark suppression, backup, and Ops Monitor telemetry results. + +## State Scope + +- `project`: create or update reviewed campaign Markdown, commit and deploy only after the human approves the exact content, and update private runtime state only through the CLI. + +Never commit subscriber operations, runtime databases, receipts, raw telemetry, or credentials. + +## Workflow + +### Phase 1: Prepare the delivery artifact + +1. Read the selected Hub update and identify the exact source file used. +2. Create or update `campaigns/drafts/.md` with required front matter, stable campaign ID, subject, preheader, PaddleNET sender metadata, and the reviewed source-derived body. +3. Run `campaign validate` and `campaign preview`. +4. Present the rendered campaign for human review. Do not send, approve, or schedule a follow-up in this phase. + +### Phase 2: Review, commit, deploy, and authorize + +1. Apply requested content changes, then rerun validation and preview. +2. After the human approves the exact content and gives a send-and-follow-up directive, commit the campaign artifact, push it, deploy the reviewed revision, update `EMAIL_LIST_GIT_COMMIT`, and rebuild the container. +3. Run `system check --json` and `suppression reconcile --dry-run --json`. +4. Record the exact directive with `campaign approve`. + +### Phase 3: Send and schedule + +1. Run `campaign send --dry-run --json`; inspect recipient count and exclusions. +2. Run `campaign send --json` only when the approval, campaign hash, template hash, reviewed Git revision, sender, and audience still match. +3. Confirm backup path, accepted/duplicate counts, receipt path, and delivery webhook health. +4. Run `campaign schedule-non-openers --subject --json` to record the one authorized four-day follow-up. +5. If host cron is not enabled, report that the follow-up is recorded but cannot run unattended. + +### Phase 4: Run a due follow-up + +1. Run `campaign run-due-followups --dry-run --json` before a due production follow-up when an operator is present. +2. Require Ops Monitor telemetry, original authorization, recipient snapshot, active local status, and current Postmark suppression checks to pass. +3. Stop rather than resend if telemetry is unavailable, no eligible apparent non-openers remain, or any authorization/hash check fails. + +## Validation + +Before reporting completion, inspect JSON output and private receipt paths. For an initial send, confirm the backup, accepted/duplicate counts, Delivery webhook, and one follow-up schedule. Never expose addresses, tokens, raw telemetry, or private receipts. + +## Edge Cases + +- Changed campaign or template after approval: stop and require a new review and directive. +- Missing deployed commit or incomplete `.env`: stop before approval or send. +- Suppression conflict: exclude the recipient and reconcile; do not bypass it. +- Placeholder welcome template: do not run welcome processing. +- Cron disabled: schedule may be recorded, but no unattended follow-up occurs. +- Telemetry unavailable: do not send a follow-up. + +## Anti-Patterns + +Do not use this skill for subscriber add/remove work, directly edit SQLite, bypass dry runs or suppressions, invent authorization, substitute a follow-up subject, send a campaign from an unreviewed Hub file, or commit private runtime data. + +## Ratchet Rules + +Turn every important operational failure into a regression test, schema rule, fixture, STOP gate, routing example, or documented anti-pattern, then rerun the relevant validation. + +## Run Receipt + +Record privately: skill name, reviewed Git revision, source Hub file, campaign and template hashes, authorization reference, impact counts, validation, receipt paths, scheduler state, and unresolved risks. Use the final report only for sanitized summaries. diff --git a/skills/email-list-operator/agents/openai.yaml b/skills/email-list-operator/agents/openai.yaml new file mode 100644 index 0000000..f62fd18 --- /dev/null +++ b/skills/email-list-operator/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "PaddleNET Email Operator" + short_description: "Prepare and send approved campaigns" + default_prompt: "Use $email-list-operator to prepare this PaddleNET update for review and delivery." diff --git a/skills/email-list-remove-subscriber/SKILL.md b/skills/email-list-remove-subscriber/SKILL.md new file mode 100644 index 0000000..5b882cb --- /dev/null +++ b/skills/email-list-remove-subscriber/SKILL.md @@ -0,0 +1,87 @@ +--- +name: email-list-remove-subscriber +description: Remove one email address from the PaddleNET email list through the private, idempotent JSONL inbox and deterministic CLI. Use when a human asks to unsubscribe or suppress a specific address. Do not use for Postmark-managed click unsubscribes, campaign sending, or direct database changes. +--- + +# Remove PaddleNET Subscriber + +## Skill Shape + +- `service`: one private subscriber-removal operation. + +## Contract + +Apply one explicitly requested unsubscribe through the deterministic CLI. Validate before mutation, preserve the removal even when the address is unknown locally, and never send email or change a Postmark subscription directly. + +## Requires + +- One valid email address. +- Human instruction to remove this exact address. +- A reason when available; otherwise record `human removal request`. +- Authorized access to the production email VM and its Docker CLI. + +## Ensures + +- One private `unsubscribe` JSONL operation with a new operation ID and UTC request time. +- A completed dry run before any mutation. +- A sanitized CLI result and private receipt for a completed import. +- No direct SQLite change, campaign send, welcome run, Postmark API call, or Git commit. + +## Inputs + +- Email address. +- Optional reason, such as `recipient-request`, `manual-cleanup`, or `human removal request`. + +## State Scope + +- `project`: write one private operation file under `/srv/email-list-system/runtime/inbox/` and let the CLI update private SQLite state. + +## Workflow + +### Phase 1: Confirm the request + +1. Confirm the exact address and capture the available removal reason. +2. Normalize and validate the address through the CLI path; do not guess corrections. +3. Explain only if needed that a local removal prevents later system sends immediately; Postmark click unsubscribes remain managed by Postmark and synchronize separately. + +### Phase 2: Plan the private operation + +1. Run `email-list system check --json` on the email VM. +2. Create one private JSONL record with `schema_version: "1.0"`, a new unique `operation_id`, `operation: "unsubscribe"`, the address, reason, and `requested_at` in UTC. +3. Run `subscriber import --dry-run --json`. +4. Inspect the planned result without exposing other subscriber data. + +### Phase 3: Apply and report + +1. Run `subscriber import --json` only after the dry run is valid. +2. Inspect the JSON result and private receipt path. +3. Report only a sanitized status: removed, already applied, or removed as an unknown-address suppression. + +## Validation + +Before finishing, confirm all of the following: + +1. The operation is `unsubscribe`, has a unique ID, and has a UTC request time. +2. The dry run completed before the live import. +3. The live result is `unsubscribed`, `suppressed_unknown_address`, or `already_applied`. +4. No campaign, welcome, direct SQLite, or Postmark API command was called. +5. The final report contains no token, raw receipt, or additional subscriber data. + +## Edge Cases + +- Unknown address: retain a local unsubscribed record and report the safe suppression outcome. +- Replayed operation ID: report `already_applied`; do not create a duplicate. +- Invalid address: stop before creating a private operation. +- Postmark click unsubscribe: do not duplicate it manually unless the human separately requests a local removal; Postmark suppression reconciliation handles provider state. + +## Anti-Patterns + +Do not reactivate a suppressed address, edit SQLite, commit private data, delete subscriber history, send a confirmation message, or use a campaign command. + +## Ratchet Rules + +Turn each recurring removal failure into a durable guardrail: a required-input rule, JSONL fixture, validation check, STOP gate, or documented anti-pattern. Rerun the dry-run path after changing the skill. + +## Run Receipt + +Record privately: skill name, operation ID, reason category, command results, receipt path, validation outcome, and unresolved risk. Give the human only a sanitized completion summary. diff --git a/skills/email-list-remove-subscriber/agents/openai.yaml b/skills/email-list-remove-subscriber/agents/openai.yaml new file mode 100644 index 0000000..64ca46d --- /dev/null +++ b/skills/email-list-remove-subscriber/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Remove PaddleNET Subscriber" + short_description: "Safely remove a subscriber" + default_prompt: "Use $email-list-remove-subscriber to remove this PaddleNET subscriber." diff --git a/src/email_list/__init__.py b/src/email_list/__init__.py new file mode 100644 index 0000000..530a281 --- /dev/null +++ b/src/email_list/__init__.py @@ -0,0 +1,3 @@ +"""PaddleNET email-list automation package.""" + +__version__ = "0.1.0" diff --git a/src/email_list/backups.py b/src/email_list/backups.py new file mode 100644 index 0000000..bff90a8 --- /dev/null +++ b/src/email_list/backups.py @@ -0,0 +1,41 @@ +"""SQLite backups with explicit, reviewable impact.""" + +from __future__ import annotations + +import os +import sqlite3 +from contextlib import closing +from datetime import UTC, datetime +from pathlib import Path + + +def create_backup(*, dry_run: bool) -> dict[str, object]: + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + database_path = data_dir / "email-list.sqlite" + backup_dir = data_dir / "backups" + timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + backup_path = backup_dir / f"email-list-{timestamp}.sqlite" + if dry_run: + return { + "schema_version": "1.0", + "command": "backup.create", + "status": "planned", + "dry_run": True, + "database_path": str(database_path), + "backup_path": str(backup_path), + "impact": {"creates_backup": database_path.exists()}, + } + if not database_path.is_file(): + raise FileNotFoundError(f"Database is not initialized: {database_path}") + backup_dir.mkdir(parents=True, exist_ok=True) + with closing(sqlite3.connect(database_path)) as source, closing(sqlite3.connect(backup_path)) as target: + with source, target: + source.backup(target) + return { + "schema_version": "1.0", + "command": "backup.create", + "status": "ok", + "dry_run": False, + "database_path": str(database_path), + "backup_path": str(backup_path), + } diff --git a/src/email_list/campaign_workflow.py b/src/email_list/campaign_workflow.py new file mode 100644 index 0000000..013f551 --- /dev/null +++ b/src/email_list/campaign_workflow.py @@ -0,0 +1,103 @@ +"""Authorization, recipient snapshots, and retry-safe campaign delivery.""" + +from __future__ import annotations + +import subprocess +import os +import uuid +from pathlib import Path + +from email_list.campaigns import campaign_result +from email_list.providers.base import EmailProvider +from email_list.subscribers import utc_now + + +def git_commit(path: Path) -> str: + configured_commit = os.environ.get("EMAIL_LIST_GIT_COMMIT") + if configured_commit and configured_commit != "unknown": + return configured_commit + try: + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=path.parent, text=True, stderr=subprocess.DEVNULL).strip() + except (OSError, subprocess.CalledProcessError): + raise ValueError("A reviewed Git commit must be injected as EMAIL_LIST_GIT_COMMIT") + + +def approve_campaign(connection: object, path: Path, *, authorizer: str, directive_reference: str) -> dict[str, object]: + rendered = campaign_result(path) + now = utc_now() + commit = git_commit(path) + existing = connection.execute("SELECT * FROM campaigns WHERE campaign_id = ?", (rendered["campaign_id"],)).fetchone() + if existing and (existing["content_hash"] != rendered["content_hash"] or existing["template_hash"] != rendered["template_hash"]): + raise ValueError("Campaign ID already exists with different content or template") + with connection: + if not existing: + connection.execute( + "INSERT INTO campaigns(campaign_id, state, content_hash, template_hash, git_commit, audience_rule, created_at_utc, updated_at_utc, subject) VALUES (?, 'approved', ?, ?, ?, 'active', ?, ?, ?)", + (rendered["campaign_id"], rendered["content_hash"], rendered["template_hash"], commit, now, now, rendered["metadata"]["subject"]), + ) + authorization = connection.execute( + "SELECT authorization_id FROM campaign_authorizations WHERE campaign_id = ? AND invalidated_at_utc IS NULL", (rendered["campaign_id"],) + ).fetchone() + if not authorization: + connection.execute( + """INSERT INTO campaign_authorizations(authorization_id, campaign_id, authorizer, directive_reference, content_hash, template_hash, + git_commit, audience_rule, followup_after_days, authorized_at_utc) VALUES (?, ?, ?, ?, ?, ?, ?, 'active', 4, ?)""", + (str(uuid.uuid4()), rendered["campaign_id"], authorizer, directive_reference, rendered["content_hash"], rendered["template_hash"], commit, now), + ) + return {"campaign_id": rendered["campaign_id"], "state": "approved", "content_hash": rendered["content_hash"], "template_hash": rendered["template_hash"], "git_commit": commit} + + +def send_campaign(connection: object, path: Path, *, provider: EmailProvider, dry_run: bool) -> dict[str, object]: + rendered = campaign_result(path) + campaign = connection.execute("SELECT * FROM campaigns WHERE campaign_id = ?", (rendered["campaign_id"],)).fetchone() + authorization = connection.execute( + "SELECT * FROM campaign_authorizations WHERE campaign_id = ? AND invalidated_at_utc IS NULL", (rendered["campaign_id"],) + ).fetchone() + if not campaign or not authorization: + raise ValueError("Campaign requires a recorded authorization before sending") + if campaign["content_hash"] != rendered["content_hash"] or campaign["template_hash"] != rendered["template_hash"]: + raise ValueError("Campaign content or template changed after authorization") + if authorization["content_hash"] != rendered["content_hash"] or authorization["followup_after_days"] != 4: + raise ValueError("Campaign authorization is no longer valid") + suppressions = provider.suppressed_addresses() + candidates = connection.execute( + "SELECT subscriber_id, normalized_email FROM subscribers WHERE status = 'active' ORDER BY normalized_email" + ).fetchall() + recipients = [recipient for recipient in candidates if recipient["normalized_email"] not in suppressions] + if dry_run: + return {"campaign_id": rendered["campaign_id"], "status": "planned", "recipient_count": len(recipients), "suppressed_count": len(candidates) - len(recipients), "dry_run": True} + now = utc_now() + with connection: + for recipient in recipients: + connection.execute( + "INSERT OR IGNORE INTO campaign_recipients(campaign_id, subscriber_id, snapshot_at_utc, eligibility_status) VALUES (?, ?, ?, 'eligible')", + (rendered["campaign_id"], recipient["subscriber_id"], now), + ) + connection.execute("UPDATE campaigns SET state = 'sending', updated_at_utc = ? WHERE campaign_id = ?", (now, rendered["campaign_id"])) + snapshot = connection.execute( + """SELECT r.subscriber_id, s.normalized_email FROM campaign_recipients r JOIN subscribers s ON s.subscriber_id = r.subscriber_id + WHERE r.campaign_id = ? AND r.eligibility_status = 'eligible' ORDER BY s.normalized_email""", (rendered["campaign_id"],) + ).fetchall() + accepted = 0 + skipped = 0 + for recipient in snapshot: + existing = connection.execute( + "SELECT state FROM send_attempts WHERE campaign_id = ? AND subscriber_id = ? AND kind = 'campaign'", (rendered["campaign_id"], recipient["subscriber_id"]) + ).fetchone() + if existing and existing["state"] == "accepted": + skipped += 1 + continue + result = provider.send(recipient=recipient["normalized_email"], subject=rendered["metadata"]["subject"], html_body=rendered["rendered_html"], text_body=rendered["rendered_text"], metadata={"campaign_id": rendered["campaign_id"], "kind": "campaign"}) + now = utc_now() + with connection: + connection.execute( + """INSERT INTO send_attempts(attempt_id, campaign_id, subscriber_id, kind, state, provider_request_id, provider_message_id, attempt_count, created_at_utc, updated_at_utc) + VALUES (?, ?, ?, 'campaign', 'accepted', ?, ?, 1, ?, ?) + ON CONFLICT(campaign_id, subscriber_id, kind) DO UPDATE SET state = 'accepted', provider_request_id = excluded.provider_request_id, + provider_message_id = excluded.provider_message_id, attempt_count = send_attempts.attempt_count + 1, updated_at_utc = excluded.updated_at_utc""", + (str(uuid.uuid4()), rendered["campaign_id"], recipient["subscriber_id"], result.request_id, result.message_id, now, now), + ) + accepted += 1 + with connection: + connection.execute("UPDATE campaigns SET state = 'sent', updated_at_utc = ? WHERE campaign_id = ?", (utc_now(), rendered["campaign_id"])) + return {"campaign_id": rendered["campaign_id"], "status": "ok", "recipient_count": len(snapshot), "suppressed_count": len(candidates) - len(recipients), "accepted_count": accepted, "already_accepted_count": skipped, "dry_run": False} diff --git a/src/email_list/campaigns.py b/src/email_list/campaigns.py new file mode 100644 index 0000000..dab844e --- /dev/null +++ b/src/email_list/campaigns.py @@ -0,0 +1,87 @@ +"""Campaign front-matter validation and dependency-free rendering.""" + +from __future__ import annotations + +import hashlib +import html +import os +import re +from pathlib import Path + + +REQUIRED_FIELDS = {"schema_version", "campaign_id", "subject", "from_name", "reply_to", "audience"} +ALLOWED_FIELDS = REQUIRED_FIELDS | {"preheader"} +CAMPAIGN_ID = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$") + + +def parse_campaign(path: Path) -> tuple[dict[str, str], str]: + source = path.read_text(encoding="utf-8") + if not source.startswith("---\n"): + raise ValueError("Campaign must begin with YAML front matter") + try: + front_matter, body = source[4:].split("\n---\n", 1) + except ValueError as error: + raise ValueError("Campaign front matter must end with ---") from error + metadata: dict[str, str] = {} + for line in front_matter.splitlines(): + if not line.strip(): + continue + if ":" not in line: + raise ValueError(f"Invalid front-matter line: {line}") + key, value = line.split(":", 1) + metadata[key.strip()] = value.strip().strip('"') + missing = sorted(REQUIRED_FIELDS - metadata.keys()) + unknown = sorted(metadata.keys() - ALLOWED_FIELDS) + if missing: + raise ValueError(f"Missing campaign metadata: {', '.join(missing)}") + if unknown: + raise ValueError(f"Unsupported campaign metadata: {', '.join(unknown)}") + if metadata["schema_version"] != "1.0" or not CAMPAIGN_ID.fullmatch(metadata["campaign_id"]): + raise ValueError("Campaign schema_version or campaign_id is invalid") + if metadata["audience"] != "active" or "@" not in metadata["reply_to"]: + raise ValueError("Campaign audience or reply_to is invalid") + if not body.strip(): + raise ValueError("Campaign body may not be empty") + for url in re.findall(r"\[[^\]]+\]\(([^)]+)\)", body): + if not url.startswith("https://"): + raise ValueError("Campaign links must use https") + return metadata, body.strip() + + +def render_markdown(body: str) -> tuple[str, str]: + paragraphs = [part.strip() for part in re.split(r"\n\s*\n", body) if part.strip()] + html_parts: list[str] = [] + text_parts: list[str] = [] + for paragraph in paragraphs: + if paragraph.startswith("# "): + content = paragraph[2:].strip() + html_parts.append(f"

{html.escape(content)}

") + text_parts.append(content) + else: + content = html.escape(paragraph).replace("\n", "
") + content = re.sub(r"\[([^\]]+)\]\((https?://[^)\s]+)\)", r'\1', content) + html_parts.append(f"

{content}

") + text_parts.append(re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", paragraph)) + return "\n".join(html_parts), "\n\n".join(text_parts) + + +def campaign_result(path: Path) -> dict[str, object]: + metadata, body = parse_campaign(path) + rendered_html, rendered_text = render_markdown(body) + source = path.read_bytes() + template_path = Path(os.environ.get("EMAIL_LIST_TEMPLATE_DIR", "templates")) / "campaign.html" + if not template_path.is_file(): + raise FileNotFoundError(f"Campaign template is missing: {template_path}") + template = template_path.read_text(encoding="utf-8") + final_html = template.replace("{{subject}}", html.escape(metadata["subject"])) + final_html = final_html.replace("{{content}}", rendered_html) + rendered_text = rendered_text + "\n\nUnsubscribe: {{{ pm:unsubscribe }}}" + return { + "schema_version": "1.0", + "campaign_id": metadata["campaign_id"], + "metadata": metadata, + "content_hash": hashlib.sha256(source).hexdigest(), + "template_hash": hashlib.sha256(template.encode()).hexdigest(), + "rendered_html": final_html, + "rendered_text": rendered_text, + } diff --git a/src/email_list/cli.py b/src/email_list/cli.py new file mode 100644 index 0000000..38e5fcd --- /dev/null +++ b/src/email_list/cli.py @@ -0,0 +1,231 @@ +"""Stable command-line entry point for the email-list system.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +from typing import Sequence + +from email_list import __version__ +from email_list.backups import create_backup +from email_list.campaigns import campaign_result +from email_list.campaign_workflow import approve_campaign, send_campaign +from email_list.providers.postmark import PostmarkProvider +from email_list.providers.test_provider import TestProvider +from email_list.receipts import write_receipt +from email_list.scheduler import run_due_followups, run_welcomes, schedule_followup +from email_list.subscribers import apply_operation, load_operations, utc_now +from email_list.telemetry import TelemetryClient +from email_list.storage.database import Database +from email_list.storage.migrations import apply_migrations + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="email-list") + subparsers = parser.add_subparsers(dest="command", required=True) + + system = subparsers.add_parser("system", help="Inspect the local runtime.") + system_subparsers = system.add_subparsers(dest="system_command", required=True) + check = system_subparsers.add_parser("check", help="Run a non-mutating health check.") + check.add_argument("--json", action="store_true", dest="as_json") + initialize = system_subparsers.add_parser("init", help="Create or upgrade local state.") + initialize.add_argument("--dry-run", action="store_true") + initialize.add_argument("--json", action="store_true", dest="as_json") + backup = subparsers.add_parser("backup", help="Create a private SQLite backup.") + backup_subparsers = backup.add_subparsers(dest="backup_command", required=True) + create = backup_subparsers.add_parser("create", help="Create a point-in-time database backup.") + create.add_argument("--dry-run", action="store_true") + create.add_argument("--json", action="store_true", dest="as_json") + subscriber = subparsers.add_parser("subscriber", help="Manage private subscriber state.") + subscriber_subparsers = subscriber.add_subparsers(dest="subscriber_command", required=True) + imported = subscriber_subparsers.add_parser("import", help="Apply JSONL subscriber operations.") + imported.add_argument("file", type=Path) + imported.add_argument("--dry-run", action="store_true") + imported.add_argument("--no-welcome", action="store_true", help="Import subscribers without a welcome eligibility record.") + imported.add_argument("--json", action="store_true", dest="as_json") + campaign = subparsers.add_parser("campaign", help="Validate and preview campaign files.") + campaign_subparsers = campaign.add_subparsers(dest="campaign_command", required=True) + validate = campaign_subparsers.add_parser("validate", help="Validate campaign metadata and body.") + validate.add_argument("file", type=Path) + validate.add_argument("--json", action="store_true", dest="as_json") + preview = campaign_subparsers.add_parser("preview", help="Render campaign HTML and text.") + preview.add_argument("file", type=Path) + preview.add_argument("--json", action="store_true", dest="as_json") + approve = campaign_subparsers.add_parser("approve", help="Record a human campaign directive.") + approve.add_argument("file", type=Path) + approve.add_argument("--authorizer", required=True) + approve.add_argument("--directive-reference", required=True) + approve.add_argument("--json", action="store_true", dest="as_json") + send = campaign_subparsers.add_parser("send", help="Send an authorized campaign.") + send.add_argument("file", type=Path) + send.add_argument("--dry-run", action="store_true") + send.add_argument("--json", action="store_true", dest="as_json") + schedule = campaign_subparsers.add_parser("schedule-non-openers", help="Schedule the one authorized four-day follow-up.") + schedule.add_argument("campaign_id") + schedule.add_argument("--subject", required=True, help="Must be the original subject in v1.") + schedule.add_argument("--json", action="store_true", dest="as_json") + due = campaign_subparsers.add_parser("run-due-followups", help="Run due authorized follow-ups.") + due.add_argument("--campaign-dir", type=Path, default=Path("campaigns/sent")) + due.add_argument("--dry-run", action="store_true") + due.add_argument("--json", action="store_true", dest="as_json") + welcome = subparsers.add_parser("welcome", help="Process welcome emails for newly added subscribers.") + welcome_subparsers = welcome.add_subparsers(dest="welcome_command", required=True) + run_welcome = welcome_subparsers.add_parser("run", help="Send pending welcome emails exactly once.") + run_welcome.add_argument("--template", type=Path, default=Path("templates/welcome.md")) + run_welcome.add_argument("--dry-run", action="store_true") + run_welcome.add_argument("--json", action="store_true", dest="as_json") + suppression = subparsers.add_parser("suppression", help="Reconcile provider delivery suppressions.") + suppression_subparsers = suppression.add_subparsers(dest="suppression_command", required=True) + reconcile = suppression_subparsers.add_parser("reconcile", help="Compare provider suppressions with local state.") + reconcile.add_argument("--dry-run", action="store_true") + reconcile.add_argument("--json", action="store_true", dest="as_json") + return parser + + +def system_check() -> dict[str, object]: + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + receipts_dir = Path(os.environ.get("EMAIL_LIST_RECEIPTS_DIR", "./receipts/generated")) + database_path = data_dir / "email-list.sqlite" + return { + "schema_version": "1.0", + "command": "system.check", + "status": "ok", + "version": __version__, + "data_dir": str(data_dir), + "receipts_dir": str(receipts_dir), + "database_path": str(database_path), + "database_initialized": database_path.is_file(), + } + + +def system_init(dry_run: bool) -> dict[str, object]: + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + database_path = data_dir / "email-list.sqlite" + if dry_run: + return { + "schema_version": "1.0", + "command": "system.init", + "status": "planned", + "dry_run": True, + "database_path": str(database_path), + "impact": {"creates_database": not database_path.exists()}, + } + data_dir.mkdir(parents=True, exist_ok=True) + with Database(database_path) as database: + applied = apply_migrations(database.connection) + installed_version = database.schema_version() + return { + "schema_version": "1.0", + "command": "system.init", + "status": "ok", + "dry_run": False, + "database_path": str(database_path), + "applied_migrations": applied, + "installed_schema_version": installed_version, + } + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + if args.command == "system" and args.system_command == "check": + result = system_check() + if args.as_json: + print(json.dumps(result, sort_keys=True)) + else: + print(f"Email-list system {result['version']}: {result['status']}") + return 0 + if args.command == "system" and args.system_command == "init": + result = system_init(args.dry_run) + if args.as_json: + print(json.dumps(result, sort_keys=True)) + else: + print(f"Email-list database: {result['status']}") + return 0 + if args.command == "backup" and args.backup_command == "create": + result = create_backup(dry_run=args.dry_run) + if args.as_json: + print(json.dumps(result, sort_keys=True)) + else: + print(f"Database backup: {result['status']}") + return 0 + if args.command == "subscriber" and args.subscriber_command == "import": + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + database_path = data_dir / "email-list.sqlite" + if not database_path.exists(): + raise FileNotFoundError("Initialize the database before importing subscribers") + with Database(database_path) as database: + assert database.connection is not None + results = [apply_operation(database.connection, operation, dry_run=args.dry_run, welcome_eligible=not args.no_welcome) for operation in load_operations(args.file)] + result = {"schema_version": "1.0", "command": "subscriber.import", "status": "planned" if args.dry_run else "ok", "dry_run": args.dry_run, "results": results} + if not args.dry_run: + result["receipt_path"] = write_receipt(result) + print(json.dumps(result, sort_keys=True) if args.as_json else f"Subscriber import: {result['status']}") + return 0 + if args.command == "campaign" and args.campaign_command in {"validate", "preview"}: + rendered = campaign_result(args.file) + result = {"schema_version": "1.0", "command": f"campaign.{args.campaign_command}", "status": "ok", **rendered} + if args.campaign_command == "validate": + result.pop("rendered_html") + result.pop("rendered_text") + print(json.dumps(result, sort_keys=True) if args.as_json else f"Campaign {rendered['campaign_id']}: valid") + return 0 + if args.command == "campaign" and args.campaign_command in {"approve", "send", "schedule-non-openers", "run-due-followups"}: + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + database_path = data_dir / "email-list.sqlite" + if not database_path.exists(): + raise FileNotFoundError("Initialize the database before operating on campaigns") + with Database(database_path) as database: + assert database.connection is not None + provider = PostmarkProvider.from_environment() if os.environ.get("EMAIL_LIST_PROVIDER") == "postmark" else TestProvider() + if args.campaign_command == "approve": + outcome = approve_campaign(database.connection, args.file, authorizer=args.authorizer, directive_reference=args.directive_reference) + result = {"schema_version": "1.0", "command": "campaign.approve", "status": "ok", **outcome} + elif args.campaign_command == "send": + backup = create_backup(dry_run=False) if not args.dry_run else None + outcome = send_campaign(database.connection, args.file, provider=provider, dry_run=args.dry_run) + result = {"schema_version": "1.0", "command": "campaign.send", **outcome} + if backup: + result["backup_path"] = backup["backup_path"] + elif args.campaign_command == "schedule-non-openers": + result = {"schema_version": "1.0", "command": "campaign.schedule_non_openers", "status": "ok", **schedule_followup(database.connection, args.campaign_id, args.subject)} + else: + telemetry = TelemetryClient.from_environment() + result = {"schema_version": "1.0", "command": "campaign.run_due_followups", **run_due_followups(database.connection, provider, telemetry, args.campaign_dir, dry_run=args.dry_run)} + if args.campaign_command in {"approve", "send", "schedule-non-openers"} and not getattr(args, "dry_run", False): + result["receipt_path"] = write_receipt(result) + print(json.dumps(result, sort_keys=True) if args.as_json else f"Campaign {result['campaign_id']}: {result['status']}") + return 0 + if args.command == "welcome" and args.welcome_command == "run": + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + database_path = data_dir / "email-list.sqlite" + provider = PostmarkProvider.from_environment() if os.environ.get("EMAIL_LIST_PROVIDER") == "postmark" else TestProvider() + with Database(database_path) as database: + assert database.connection is not None + outcome = run_welcomes(database.connection, provider, args.template, dry_run=args.dry_run) + result = {"schema_version": "1.0", "command": "welcome.run", **outcome} + if not args.dry_run: + result["receipt_path"] = write_receipt(result) + print(json.dumps(result, sort_keys=True) if args.as_json else f"Welcome processing: {result['status']}") + return 0 + if args.command == "suppression" and args.suppression_command == "reconcile": + data_dir = Path(os.environ.get("EMAIL_LIST_DATA_DIR", "./data")) + database_path = data_dir / "email-list.sqlite" + provider = PostmarkProvider.from_environment() if os.environ.get("EMAIL_LIST_PROVIDER") == "postmark" else TestProvider() + with Database(database_path) as database: + assert database.connection is not None + suppressions = provider.suppressed_addresses() + local = database.connection.execute("SELECT subscriber_id, normalized_email, status FROM subscribers").fetchall() + changes = [row for row in local if row["normalized_email"] in suppressions and row["status"] == "active"] + if not args.dry_run: + now = utc_now() + with database.connection: + for row in changes: + database.connection.execute("UPDATE subscribers SET status = 'manually_suppressed', suppression_reason = ?, updated_at_utc = ? WHERE subscriber_id = ?", (suppressions[row["normalized_email"]], now, row["subscriber_id"])) + result = {"schema_version": "1.0", "command": "suppression.reconcile", "status": "planned" if args.dry_run else "ok", "dry_run": args.dry_run, "provider_suppression_count": len(suppressions), "local_changes": len(changes)} + if not args.dry_run: + result["receipt_path"] = write_receipt(result) + print(json.dumps(result, sort_keys=True) if args.as_json else f"Suppression reconciliation: {result['status']}") + return 0 + return 2 diff --git a/src/email_list/providers/__init__.py b/src/email_list/providers/__init__.py new file mode 100644 index 0000000..bc70a0d --- /dev/null +++ b/src/email_list/providers/__init__.py @@ -0,0 +1 @@ +"""Replaceable email delivery providers.""" diff --git a/src/email_list/providers/base.py b/src/email_list/providers/base.py new file mode 100644 index 0000000..b2810e5 --- /dev/null +++ b/src/email_list/providers/base.py @@ -0,0 +1,20 @@ +"""Provider-neutral delivery contract.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class SendResult: + request_id: str + message_id: str + + +class EmailProvider: + def send(self, *, recipient: str, subject: str, html_body: str, text_body: str, metadata: dict[str, str]) -> SendResult: + raise NotImplementedError + + def suppressed_addresses(self) -> dict[str, str]: + """Return normalized address-to-reason mappings from the provider.""" + raise NotImplementedError diff --git a/src/email_list/providers/postmark.py b/src/email_list/providers/postmark.py new file mode 100644 index 0000000..15ed05f --- /dev/null +++ b/src/email_list/providers/postmark.py @@ -0,0 +1,49 @@ +"""Postmark Broadcast Message Stream adapter.""" + +from __future__ import annotations + +import json +import os +from typing import Any +from urllib.request import Request, urlopen + +from email_list.providers.base import EmailProvider, SendResult +from email_list.subscribers import normalize_email + + +class PostmarkProvider(EmailProvider): + api_base_url = "https://api.postmarkapp.com" + + def __init__(self, *, token: str, stream_id: str, from_name: str, from_email: str, reply_to: str) -> None: + self.token = token + self.stream_id = stream_id + self.from_name = from_name + self.from_email = from_email + self.reply_to = reply_to + + @classmethod + def from_environment(cls) -> "PostmarkProvider": + values = {name: os.environ.get(name, "") for name in ("POSTMARK_SERVER_TOKEN", "POSTMARK_BROADCAST_STREAM_ID", "POSTMARK_FROM_NAME", "POSTMARK_FROM_EMAIL", "POSTMARK_REPLY_TO")} + missing = [name for name, value in values.items() if not value] + if missing: + raise ValueError(f"Postmark configuration is missing: {', '.join(missing)}") + return cls(token=values["POSTMARK_SERVER_TOKEN"], stream_id=values["POSTMARK_BROADCAST_STREAM_ID"], from_name=values["POSTMARK_FROM_NAME"], from_email=values["POSTMARK_FROM_EMAIL"], reply_to=values["POSTMARK_REPLY_TO"]) + + def _request(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]: + payload = json.dumps(body).encode("utf-8") if body is not None else None + request = Request(f"{self.api_base_url}{path}", data=payload, method=method, headers={"Accept": "application/json", "Content-Type": "application/json", "X-Postmark-Server-Token": self.token}) + with urlopen(request, timeout=30) as response: + return json.loads(response.read().decode("utf-8")) + + def send(self, *, recipient: str, subject: str, html_body: str, text_body: str, metadata: dict[str, str]) -> SendResult: + response = self._request("POST", "/email", {"From": f"{self.from_name} <{self.from_email}>", "To": recipient, "ReplyTo": self.reply_to, "Subject": subject, "HtmlBody": html_body, "TextBody": text_body, "MessageStream": self.stream_id, "Metadata": metadata}) + if response.get("ErrorCode") not in (None, 0): + raise RuntimeError(f"Postmark rejected message: {response.get('Message', 'unknown error')}") + message_id = response.get("MessageID") + if not message_id: + raise RuntimeError("Postmark response did not include MessageID") + return SendResult(request_id=message_id, message_id=message_id) + + def suppressed_addresses(self) -> dict[str, str]: + response = self._request("GET", f"/message-streams/{self.stream_id}/suppressions/dump") + return {normalize_email(item["EmailAddress"]): item["SuppressionReason"] for item in response.get("Suppressions", [])} diff --git a/src/email_list/providers/test_provider.py b/src/email_list/providers/test_provider.py new file mode 100644 index 0000000..894da81 --- /dev/null +++ b/src/email_list/providers/test_provider.py @@ -0,0 +1,17 @@ +"""Deterministic provider used by tests and local acceptance runs.""" + +from __future__ import annotations + +import hashlib + +from email_list.providers.base import EmailProvider, SendResult + + +class TestProvider(EmailProvider): + def send(self, *, recipient: str, subject: str, html_body: str, text_body: str, metadata: dict[str, str]) -> SendResult: + seed = "|".join((recipient, subject, metadata["campaign_id"], metadata["kind"])) + identifier = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:24] + return SendResult(request_id=f"test-request-{identifier}", message_id=f"test-message-{identifier}") + + def suppressed_addresses(self) -> dict[str, str]: + return {} diff --git a/src/email_list/receipts.py b/src/email_list/receipts.py new file mode 100644 index 0000000..04b4367 --- /dev/null +++ b/src/email_list/receipts.py @@ -0,0 +1,32 @@ +"""Sanitized, reviewable execution receipts.""" + +from __future__ import annotations + +import json +import os +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + + +PRIVATE_KEYS = {"email", "normalized_email", "recipient", "provider_message_id", "provider_request_id", "results"} + + +def sanitize(value: Any) -> Any: + if isinstance(value, dict): + return {key: sanitize(item) for key, item in value.items() if key not in PRIVATE_KEYS} + if isinstance(value, list): + return [sanitize(item) for item in value] + return value + + +def write_receipt(result: dict[str, Any]) -> str: + receipt_id = str(uuid.uuid4()) + created_at = datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z") + receipt = {"schema_version": "1.0", "receipt_id": receipt_id, "created_at_utc": created_at, "result": sanitize(result)} + directory = Path(os.environ.get("EMAIL_LIST_RECEIPTS_DIR", os.environ.get("EMAIL_LIST_DATA_DIR", "./data") + "/receipts")) + directory.mkdir(parents=True, exist_ok=True) + path = directory / f"{created_at.replace(':', '').replace('-', '')}-{receipt_id}.json" + path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8") + return str(path) diff --git a/src/email_list/scheduler.py b/src/email_list/scheduler.py new file mode 100644 index 0000000..1d49270 --- /dev/null +++ b/src/email_list/scheduler.py @@ -0,0 +1,74 @@ +"""Unattended welcome and authorized follow-up workflows.""" + +from __future__ import annotations + +import hashlib +import uuid +from datetime import UTC, datetime, timedelta +from pathlib import Path + +from email_list.campaigns import campaign_result +from email_list.providers.base import EmailProvider +from email_list.subscribers import utc_now +from email_list.telemetry import TelemetryClient + + +def schedule_followup(connection: object, campaign_id: str, subject: str) -> dict[str, object]: + campaign = connection.execute("SELECT state, subject FROM campaigns WHERE campaign_id = ?", (campaign_id,)).fetchone() + authorization = connection.execute("SELECT authorized_at_utc, followup_after_days FROM campaign_authorizations WHERE campaign_id = ? AND invalidated_at_utc IS NULL", (campaign_id,)).fetchone() + if not campaign or campaign["state"] != "sent" or not authorization: + raise ValueError("Only sent, authorized campaigns may receive a follow-up schedule") + if subject != campaign["subject"]: + raise ValueError("v1 follow-ups must keep the original authorized subject") + due_at = (datetime.fromisoformat(authorization["authorized_at_utc"].replace("Z", "+00:00")) + timedelta(days=authorization["followup_after_days"])).astimezone(UTC).isoformat().replace("+00:00", "Z") + with connection: + connection.execute("INSERT OR IGNORE INTO followup_schedules(campaign_id, due_at_utc, state, subject, created_at_utc) VALUES (?, ?, 'scheduled', ?, ?)", (campaign_id, due_at, subject, utc_now())) + return {"campaign_id": campaign_id, "due_at_utc": due_at, "subject": subject} + + +def run_welcomes(connection: object, provider: EmailProvider, welcome_path: Path, *, dry_run: bool) -> dict[str, object]: + source = welcome_path.read_text(encoding="utf-8").strip() + if source == "this is the welcome email. text to be modified.": + raise ValueError("The welcome template is still a placeholder") + recipients = connection.execute("""SELECT subscriber_id, normalized_email FROM subscribers s WHERE status = 'active' AND welcome_eligible = 1 + AND NOT EXISTS (SELECT 1 FROM welcome_attempts w WHERE w.subscriber_id = s.subscriber_id) ORDER BY normalized_email""").fetchall() + if dry_run: + return {"status": "planned", "recipient_count": len(recipients), "dry_run": True} + accepted = 0 + for recipient in recipients: + result = provider.send(recipient=recipient["normalized_email"], subject="Welcome to PaddleNET", html_body=f"

{source}

", text_body=source, metadata={"campaign_id": "welcome", "kind": "welcome"}) + with connection: + connection.execute("INSERT INTO welcome_attempts(attempt_id, subscriber_id, state, provider_request_id, provider_message_id, created_at_utc, updated_at_utc) VALUES (?, ?, 'accepted', ?, ?, ?, ?)", (str(uuid.uuid4()), recipient["subscriber_id"], result.request_id, result.message_id, utc_now(), utc_now())) + accepted += 1 + return {"status": "ok", "recipient_count": len(recipients), "accepted_count": accepted, "dry_run": False} + + +def run_due_followups(connection: object, provider: EmailProvider, telemetry: TelemetryClient, campaign_dir: Path, *, dry_run: bool) -> dict[str, object]: + due = connection.execute("SELECT campaign_id, subject FROM followup_schedules WHERE state = 'scheduled' AND due_at_utc <= ?", (utc_now(),)).fetchall() + results: list[dict[str, object]] = [] + for item in due: + matches = [path for path in campaign_dir.glob("*.md") if campaign_result(path)["campaign_id"] == item["campaign_id"]] + if len(matches) != 1: + raise ValueError(f"Expected exactly one campaign file for due follow-up {item['campaign_id']}") + rendered = campaign_result(matches[0]) + eligible_addresses = set(telemetry.apparent_non_openers(item["campaign_id"])) + suppressions = provider.suppressed_addresses() + recipients = connection.execute("""SELECT r.subscriber_id, s.normalized_email FROM campaign_recipients r JOIN subscribers s ON s.subscriber_id = r.subscriber_id + WHERE r.campaign_id = ? AND s.status = 'active'""", (item["campaign_id"],)).fetchall() + selected = [recipient for recipient in recipients if recipient["normalized_email"] in eligible_addresses and recipient["normalized_email"] not in suppressions] + if dry_run: + results.append({"campaign_id": item["campaign_id"], "recipient_count": len(selected), "status": "planned"}) + continue + accepted = 0 + for recipient in selected: + exists = connection.execute("SELECT state FROM send_attempts WHERE campaign_id = ? AND subscriber_id = ? AND kind = 'followup'", (item["campaign_id"], recipient["subscriber_id"])).fetchone() + if exists and exists["state"] == "accepted": + continue + sent = provider.send(recipient=recipient["normalized_email"], subject=item["subject"], html_body=rendered["rendered_html"], text_body=rendered["rendered_text"], metadata={"campaign_id": item["campaign_id"], "kind": "followup"}) + with connection: + connection.execute("INSERT INTO send_attempts(attempt_id, campaign_id, subscriber_id, kind, state, provider_request_id, provider_message_id, attempt_count, created_at_utc, updated_at_utc) VALUES (?, ?, ?, 'followup', 'accepted', ?, ?, 1, ?, ?) ON CONFLICT(campaign_id, subscriber_id, kind) DO NOTHING", (str(uuid.uuid4()), item["campaign_id"], recipient["subscriber_id"], sent.request_id, sent.message_id, utc_now(), utc_now())) + accepted += 1 + with connection: + connection.execute("UPDATE followup_schedules SET state = 'sent', completed_at_utc = ? WHERE campaign_id = ?", (utc_now(), item["campaign_id"])) + results.append({"campaign_id": item["campaign_id"], "recipient_count": len(selected), "accepted_count": accepted, "status": "ok"}) + return {"status": "planned" if dry_run else "ok", "due_count": len(due), "results": results, "dry_run": dry_run} diff --git a/src/email_list/storage/__init__.py b/src/email_list/storage/__init__.py new file mode 100644 index 0000000..ae580e9 --- /dev/null +++ b/src/email_list/storage/__init__.py @@ -0,0 +1 @@ +"""SQLite storage and migration utilities.""" diff --git a/src/email_list/storage/database.py b/src/email_list/storage/database.py new file mode 100644 index 0000000..b2b1178 --- /dev/null +++ b/src/email_list/storage/database.py @@ -0,0 +1,28 @@ +"""Connection and transaction helpers for private runtime state.""" + +from __future__ import annotations + +import sqlite3 +from pathlib import Path + + +class Database: + def __init__(self, path: Path) -> None: + self.path = path + self.connection: sqlite3.Connection | None = None + + def __enter__(self) -> "Database": + self.connection = sqlite3.connect(self.path) + self.connection.row_factory = sqlite3.Row + self.connection.execute("PRAGMA foreign_keys = ON") + self.connection.execute("PRAGMA journal_mode = WAL") + return self + + def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> None: + assert self.connection is not None + self.connection.close() + + def schema_version(self) -> int: + assert self.connection is not None + row = self.connection.execute("SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations").fetchone() + return int(row["version"]) diff --git a/src/email_list/storage/migrations.py b/src/email_list/storage/migrations.py new file mode 100644 index 0000000..9aaa098 --- /dev/null +++ b/src/email_list/storage/migrations.py @@ -0,0 +1,147 @@ +"""Numbered, transactional database migrations.""" + +from __future__ import annotations + +import sqlite3 +from collections.abc import Callable + + +Migration = tuple[int, str, Callable[[sqlite3.Connection], None]] + + +def _migration_1(connection: sqlite3.Connection) -> None: + connection.executescript( + """ + CREATE TABLE subscribers ( + subscriber_id TEXT PRIMARY KEY, + normalized_email TEXT NOT NULL UNIQUE, + status TEXT NOT NULL CHECK (status IN ('active', 'unsubscribed', 'hard_bounced', 'spam_complaint', 'manually_suppressed')), + source TEXT NOT NULL, + consent_at_utc TEXT, + consent_note TEXT, + subscribed_at_utc TEXT, + unsubscribed_at_utc TEXT, + suppression_reason TEXT, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL + ); + CREATE TABLE subscriber_status_history ( + history_id TEXT PRIMARY KEY, + subscriber_id TEXT NOT NULL REFERENCES subscribers(subscriber_id), + status TEXT NOT NULL, + reason TEXT, + changed_at_utc TEXT NOT NULL, + operation_id TEXT + ); + CREATE TABLE subscriber_operations ( + operation_id TEXT PRIMARY KEY, + operation_type TEXT NOT NULL CHECK (operation_type IN ('subscribe', 'unsubscribe')), + normalized_email TEXT NOT NULL, + source TEXT, + requested_at_utc TEXT NOT NULL, + applied_at_utc TEXT NOT NULL + ); + + CREATE TABLE campaigns ( + campaign_id TEXT PRIMARY KEY, + state TEXT NOT NULL CHECK (state IN ('draft', 'validated', 'approved', 'sending', 'sent', 'partial', 'failed')), + content_hash TEXT NOT NULL, + template_hash TEXT NOT NULL, + git_commit TEXT NOT NULL, + audience_rule TEXT NOT NULL, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL + ); + CREATE TABLE campaign_authorizations ( + authorization_id TEXT PRIMARY KEY, + campaign_id TEXT NOT NULL REFERENCES campaigns(campaign_id), + authorizer TEXT NOT NULL, + directive_reference TEXT NOT NULL, + content_hash TEXT NOT NULL, + template_hash TEXT NOT NULL, + git_commit TEXT NOT NULL, + audience_rule TEXT NOT NULL, + followup_after_days INTEGER NOT NULL CHECK (followup_after_days = 4), + authorized_at_utc TEXT NOT NULL, + invalidated_at_utc TEXT + ); + CREATE TABLE campaign_recipients ( + campaign_id TEXT NOT NULL REFERENCES campaigns(campaign_id), + subscriber_id TEXT NOT NULL REFERENCES subscribers(subscriber_id), + snapshot_at_utc TEXT NOT NULL, + eligibility_status TEXT NOT NULL, + PRIMARY KEY (campaign_id, subscriber_id) + ); + CREATE TABLE send_attempts ( + attempt_id TEXT PRIMARY KEY, + campaign_id TEXT NOT NULL REFERENCES campaigns(campaign_id), + subscriber_id TEXT NOT NULL REFERENCES subscribers(subscriber_id), + kind TEXT NOT NULL CHECK (kind IN ('campaign', 'followup', 'welcome')), + state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'failed')), + provider_request_id TEXT, + provider_message_id TEXT, + attempt_count INTEGER NOT NULL DEFAULT 0, + error_code TEXT, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL, + UNIQUE(campaign_id, subscriber_id, kind) + ); + CREATE TABLE execution_receipts ( + receipt_id TEXT PRIMARY KEY, + command TEXT NOT NULL, + result_json TEXT NOT NULL, + created_at_utc TEXT NOT NULL + ); + """ + ) + + +def _migration_2(connection: sqlite3.Connection) -> None: + connection.executescript( + """ + ALTER TABLE subscribers ADD COLUMN welcome_eligible INTEGER NOT NULL DEFAULT 0; + CREATE TABLE welcome_attempts ( + attempt_id TEXT PRIMARY KEY, + subscriber_id TEXT NOT NULL UNIQUE REFERENCES subscribers(subscriber_id), + state TEXT NOT NULL CHECK (state IN ('accepted', 'failed')), + provider_request_id TEXT, + provider_message_id TEXT, + created_at_utc TEXT NOT NULL, + updated_at_utc TEXT NOT NULL + ); + CREATE TABLE followup_schedules ( + campaign_id TEXT PRIMARY KEY REFERENCES campaigns(campaign_id), + due_at_utc TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('scheduled', 'sent', 'failed')), + subject TEXT NOT NULL, + created_at_utc TEXT NOT NULL, + completed_at_utc TEXT + ); + """ + ) + + +def _migration_3(connection: sqlite3.Connection) -> None: + connection.execute("ALTER TABLE campaigns ADD COLUMN subject TEXT NOT NULL DEFAULT ''") + + +MIGRATIONS: tuple[Migration, ...] = ((1, "initial_private_state", _migration_1), (2, "scheduled_welcomes_and_followups", _migration_2), (3, "campaign_subject_for_followups", _migration_3)) + + +def apply_migrations(connection: sqlite3.Connection) -> list[int]: + connection.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at_utc TEXT NOT NULL)" + ) + applied_versions = {row[0] for row in connection.execute("SELECT version FROM schema_migrations")} + applied: list[int] = [] + for version, name, migration in MIGRATIONS: + if version in applied_versions: + continue + with connection: + migration(connection) + connection.execute( + "INSERT INTO schema_migrations(version, name, applied_at_utc) VALUES (?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))", + (version, name), + ) + applied.append(version) + return applied diff --git a/src/email_list/subscribers.py b/src/email_list/subscribers.py new file mode 100644 index 0000000..3def6ae --- /dev/null +++ b/src/email_list/subscribers.py @@ -0,0 +1,122 @@ +"""Validated, idempotent subscriber operations.""" + +from __future__ import annotations + +import json +import re +import sqlite3 +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + + +EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") +TERMINAL_STATUSES = {"unsubscribed", "hard_bounced", "spam_complaint", "manually_suppressed"} + + +def utc_now() -> str: + return datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z") + + +def normalize_email(email: str) -> str: + normalized = email.strip().casefold() + if not EMAIL_PATTERN.fullmatch(normalized): + raise ValueError("A valid email address is required") + return normalized + + +def validate_operation(operation: dict[str, Any]) -> dict[str, Any]: + required = {"schema_version", "operation_id", "operation", "email", "requested_at"} + missing = sorted(required - operation.keys()) + if missing: + raise ValueError(f"Missing required fields: {', '.join(missing)}") + if operation["schema_version"] != "1.0": + raise ValueError("Unsupported operation schema_version") + if operation["operation"] not in {"subscribe", "unsubscribe"}: + raise ValueError("operation must be subscribe or unsubscribe") + if not isinstance(operation["operation_id"], str) or not operation["operation_id"].strip(): + raise ValueError("operation_id is required") + operation = dict(operation) + operation["email"] = normalize_email(str(operation["email"])) + if operation["operation"] == "subscribe" and not operation.get("source"): + raise ValueError("source is required for subscribe operations") + return operation + + +def apply_operation(connection: sqlite3.Connection, operation: dict[str, Any], *, dry_run: bool, welcome_eligible: bool = True) -> dict[str, Any]: + operation = validate_operation(operation) + existing = connection.execute( + "SELECT operation_id FROM subscriber_operations WHERE operation_id = ?", (operation["operation_id"],) + ).fetchone() + if existing: + return {"operation_id": operation["operation_id"], "email": operation["email"], "result": "already_applied"} + row = connection.execute( + "SELECT subscriber_id, status FROM subscribers WHERE normalized_email = ?", (operation["email"],) + ).fetchone() + if dry_run: + return { + "operation_id": operation["operation_id"], + "email": operation["email"], + "result": "planned", + "current_status": row["status"] if row else None, + } + now = utc_now() + with connection: + if operation["operation"] == "subscribe": + if row and row["status"] in TERMINAL_STATUSES: + result = "blocked_by_existing_suppression" + elif row: + result = "already_active" + else: + subscriber_id = str(uuid.uuid4()) + connection.execute( + """INSERT INTO subscribers(subscriber_id, normalized_email, status, source, consent_at_utc, consent_note, + subscribed_at_utc, welcome_eligible, created_at_utc, updated_at_utc) + VALUES (?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)""", + (subscriber_id, operation["email"], operation["source"], operation.get("consent_at"), operation.get("consent_note"), now, int(welcome_eligible), now, now), + ) + connection.execute( + "INSERT INTO subscriber_status_history(history_id, subscriber_id, status, reason, changed_at_utc, operation_id) VALUES (?, ?, 'active', ?, ?, ?)", + (str(uuid.uuid4()), subscriber_id, "subscribe", now, operation["operation_id"]), + ) + result = "subscribed" + elif row: + connection.execute( + "UPDATE subscribers SET status = 'unsubscribed', unsubscribed_at_utc = ?, suppression_reason = ?, updated_at_utc = ? WHERE subscriber_id = ?", + (now, operation.get("reason", "unsubscribe"), now, row["subscriber_id"]), + ) + connection.execute( + "INSERT INTO subscriber_status_history(history_id, subscriber_id, status, reason, changed_at_utc, operation_id) VALUES (?, ?, 'unsubscribed', ?, ?, ?)", + (str(uuid.uuid4()), row["subscriber_id"], operation.get("reason", "unsubscribe"), now, operation["operation_id"]), + ) + result = "unsubscribed" + else: + subscriber_id = str(uuid.uuid4()) + connection.execute( + """INSERT INTO subscribers(subscriber_id, normalized_email, status, source, unsubscribed_at_utc, suppression_reason, + created_at_utc, updated_at_utc) VALUES (?, ?, 'unsubscribed', 'manual', ?, ?, ?, ?)""", + (subscriber_id, operation["email"], now, operation.get("reason", "unsubscribe"), now, now), + ) + connection.execute( + "INSERT INTO subscriber_status_history(history_id, subscriber_id, status, reason, changed_at_utc, operation_id) VALUES (?, ?, 'unsubscribed', ?, ?, ?)", + (str(uuid.uuid4()), subscriber_id, operation.get("reason", "unsubscribe"), now, operation["operation_id"]), + ) + result = "suppressed_unknown_address" + connection.execute( + "INSERT INTO subscriber_operations(operation_id, operation_type, normalized_email, source, requested_at_utc, applied_at_utc) VALUES (?, ?, ?, ?, ?, ?)", + (operation["operation_id"], operation["operation"], operation["email"], operation.get("source"), operation["requested_at"], now), + ) + return {"operation_id": operation["operation_id"], "email": operation["email"], "result": result} + + +def load_operations(path: Path) -> list[dict[str, Any]]: + operations: list[dict[str, Any]] = [] + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + if not line.strip(): + continue + try: + operations.append(json.loads(line)) + except json.JSONDecodeError as error: + raise ValueError(f"Invalid JSON on line {number}: {error.msg}") from error + return operations diff --git a/src/email_list/telemetry.py b/src/email_list/telemetry.py new file mode 100644 index 0000000..9c522c8 --- /dev/null +++ b/src/email_list/telemetry.py @@ -0,0 +1,29 @@ +"""Authenticated client for the Ops Monitor read API.""" + +from __future__ import annotations + +import json +import os +from urllib.request import Request, urlopen + + +class TelemetryClient: + def __init__(self, base_url: str, token: str) -> None: + self.base_url = base_url.rstrip("/") + self.token = token + + @classmethod + def from_environment(cls) -> "TelemetryClient": + base_url = os.environ.get("TELEMETRY_BASE_URL", "") + token = os.environ.get("TELEMETRY_API_TOKEN", "") + if not base_url or not token: + raise ValueError("Telemetry configuration is missing") + return cls(base_url, token) + + def apparent_non_openers(self, campaign_id: str) -> list[str]: + request = Request(f"{self.base_url}/v1/email/paddlenet/campaigns/{campaign_id}/apparent-non-openers", headers={"Accept": "application/json", "Authorization": f"Bearer {self.token}"}) + with urlopen(request, timeout=30) as response: + payload = json.loads(response.read().decode("utf-8")) + if payload.get("schema_version") != "1.0" or payload.get("campaign_id") != campaign_id: + raise RuntimeError("Telemetry response failed contract validation") + return [str(address).strip().casefold() for address in payload.get("apparent_non_openers", [])] diff --git a/tasks/2026-08-13-initial-system-build-plan.md b/tasks/2026-08-13-initial-system-build-plan.md new file mode 100644 index 0000000..d4e75fb --- /dev/null +++ b/tasks/2026-08-13-initial-system-build-plan.md @@ -0,0 +1,166 @@ +The repository is still at the planning stage: it currently contains the specification and system map, with no application scaffold. Its main branch also tracks a remote that is currently marked gone, so we should resolve remote/deployment access before the first push. We’ll work through these stages, stopping after each for local testing, review, and your approval. + +# Foundation and decisions +Confirm the v1 choices that affect architecture: sender and Postmark stream, telemetry API/auth contract, default follow-up policy, scheduler, consent fields, backup retention, deployment host paths, and durable authorization-record format. Confirm the Git remote. + +- We will use Post Mark and credentials will be supplied in an .env file when needed +- telemetry is sent to ops monitor VM - details here: C:\projects\infra\software\ops-monitor +- default follow-up/send on non opens is 4-days +- I backup the server manually as needed for List Monk using these terminal commands. We will want to do something simple as well for this new email system + +````login to server and: ~/backup-listmonk.sh +from wsl workstation: scp -i ~/.ssh/example_ssh_key deploy-user@10.0.0.10:/path/to/private-backups/listmonk-*.tar.gz /path/to/local/backups/ +delete server files, but list first: ls -lh ~/backups/listmonk/ +delete with y : rm -i ~/backups/listmonk/listmonk-*.tar.gz. +```` +- the app will live in this machine: 10.0.0.10. Access latest fleetscan on details for this VM as needed: "C:\path\to\fleet-scan.json" + +- All skills built follow this template: C:\projects\productivity\ai-prompt-skill-agent-design-template-OPEN + +Sender configuration +PaddleNet from_name, from_email, reply_to, physical mailing address/footer copy, and the Postmark Broadcast Message Stream ID. Also confirm which Postmark stream sends welcome email. +- eddie@paddlenet.earth is from and reply_to +- 1494 S Perry Park Rd Sedalia CO 80135 +- postmark stream id: broadcast-list +- same stream sends welcom email + +Telemetry contract +The exact ops-monitor endpoint(s), authentication approach, and request/response shape for: +campaign activity / apparent non-openers +unsubscribe, bounce, and complaint state +A code location or existing endpoint implementation is ideal. +- see this file for the ops-monitor existing post mark ingestion that we are replicating: C:\projects\productivity\email-campaigns-prod-app\tasks-workflows\2026-06-08-indx-postmark-ops-monitor-ingestion-setup.md + +Authorization record +Confirm the durable form for a human directive. I recommend a CLI-recorded authorization containing your name, UTC time, an exact directive/reference, campaign hash, Git commit, and the fixed 4-day follow-up rule. +- approved + +Welcome email +Approved welcome-email Markdown/content and the rule for whether imported initial subscribers receive it. My recommendation: import them as active without automatically sending a welcome unless you explicitly opt in. +- when new subscribers added, they only get welcome. existing will not + +Initial subscribers and consent +The initial addresses must remain out of Git—including the task-plan file. Please provide them later through a private JSONL inbox plus a source/consent note for each (or one documented shared import source). I recommend removing that list from the committed plan now. +- done + +Scheduler and backups +Confirm that host cron is acceptable. For backups, choose a retention period and whether the existing manual workstation-copy routine is the v1 off-VM backup method. A practical starting point is daily local SQLite backups retained for 14 days, with manual workstation retrieval. +- approved for backup and rention policy as directed. Eventually we will automate that sends to internal NAS machine. + +Deployment convention +Confirm the server deployment directory and whether deployment is: pull the Git revision on the VM, then build with Docker Compose. We’ll keep secrets only in the VM’s .env, never in Git. +- approved + +Please clarify these items: + +1. Telemetry scope +May we extend Ops Monitor with an authenticated, versioned read API for: +apparent_non_openers(campaign_id) +- approved +campaign event summaries +If yes, should that work be included in this project’s delivery, or delivered as a small companion change in the Ops Monitor repository? +- approved - ammend this document as needed to reflect this + +2. PaddleNet webhook setup +Should we create telemetry.example.com, route it through Caddy to Ops Monitor, and configure the Postmark webhook during deployment? +I recommend enabling Delivery, Bounce, Spam Complaint, Open, Link Click, and Subscription Change events. +- approved + +2. Sender display name +What should recipients see as the sender name—“PaddleNet,” “PaddleNet Earth,” or another exact value? +- PaddleNET + +4. Welcome email +Please provide or point me to the approved welcome-email Markdown. Without it, I can build the welcome mechanism and test it, but cannot create the final production template. +- Here is the file placeholder for now: C:\projects\paddlenet-closed\paddlenet-app\paddlenet-email-list-system\templates\welcome.md + +5. VM deployment path +What exact directory should the application use on 10.0.0.10? I can use /srv/email-list-system if that is your preference. +- approved + +# Repository scaffold +- Apply the approved repo-template-OPEN software/automation profile - we do not need to do this yet. This email repo is internal for paddlenet. When I create andf open source copy, we can then apply the repo-template to standardize it. +add the Python project, Docker files, ignore rules, public/private-data protections, documentation skeleton, and test tooling. + +# Core contracts and CLI shell +Define versioned schemas and stable JSON CLI results, exit codes, dry-run behavior, configuration loading, health/system checks, and structured receipts. + +# SQLite foundation +Build migrations, transaction helpers, subscriber/campaign/send-state tables, status history, backups, restore verification, and test database fixtures. + +# Campaign authoring and rendering +Implement Markdown + YAML front-matter validation, HTML/plain-text rendering, templates, preview output, content/template hashing, link/footer checks, and rendering snapshot tests. +- we can use this simpel html template when emails are built from the markdown source of truth: "C:\path\to\email-template.html" + +# Subscriber operations +Implement normalized subscriber records, status precedence, private JSONL import, exact-once operation processing, subscribe/unsubscribe CLI commands, and sanitized receipts. + +# Authorization and campaign lifecycle +Record a directive bound to exact content, template, audience, Git revision, and follow-up parameters; enforce fail-closed approval checks and immutable recipient snapshots. + +# Provider boundary and Postmark integration +Create provider-neutral interfaces, a safe test adapter, then the Postmark adapter for broadcasts, welcome messages, idempotency keys, batch failures, and suppressions. + +# Sending and safe recovery +Implement the initial campaign send pipeline: backup, suppression reconciliation, recipient selection, per-recipient state, retries/resume, status, and receipts. + +# Telemetry and follow-ups +Define and test the telemetry adapter contract with the existing server; implement due follow-up selection, one-follow-up limit, eligibility rechecks, and exception behavior. + +# Scheduler and AI operating skill +Add cron-compatible entry points for imports, welcomes, reconciliation, backups, and due follow-ups; document the restricted AI command workflow and escalation boundary. + +# Docker, WSL acceptance, and release +Build and run the container locally in WSL; run the full automated suite plus synthetic/test-mode sends, migration/restore, restart/resume, and privacy checks. Then review, commit, push, deploy to the VM, run health and test-mode validation, and tag the release. + +For every implementation stage, the gate is: automated tests pass, a focused local scenario passes, documentation is updated, and we review the diff before proceeding. +We should begin with Step 1, because it resolves the few choices that cannot safely be guessed and prevents rework in the schema and deployment layers. + +## Deployment Handoff - 2026-08-13 + +### Completed and verified + +- Email-list system is committed and pushed. Current production checkout revision on `email-campaigns-prod-app` is `8783ce6`. +- Ops Monitor companion telemetry API is committed and pushed as `af1ceab`. +- Email-list repository is cloned at `/srv/email-list-system` on `10.0.0.10`. +- The email-list Docker image builds successfully on the VM. +- Private runtime directory is `/srv/email-list-system/runtime`; its SQLite database is initialized at schema version 3. +- The VM health check and test-provider suppression dry-run passed. No real subscribers or emails have been processed or sent. +- The container runs non-root as UID 1000, matching the VM account and writable private runtime directory. +- Ops Monitor source is staged at `/opt/example-email-telemetry` on `ops-monitor-host`; its on-host telemetry test passed. +- `email-telemetry.service` is active. +- The authenticated Ops Monitor API path from the email VM was verified with HTTP 200. Do not expose or rotate the shared telemetry token unless needed; both services must use the same private value. + +### Git deployment workaround and ongoing procedure + +The public Git URL is Cloudflare-proxied and does not expose Gitea SSH. The internal Tailscale route intercepts SSH as Tailscale SSH rather than routing the `git` user to Gitea. A Gitea SSH deploy key was created but is not the v1 deployment path. + +Use a dedicated, read-only Gitea HTTPS access token for this VM instead: + +```bash +cd /srv/email-list-system +git status --short --branch +git pull --ff-only origin main +``` + +Git prompts for the Gitea username and the read-only token as its password when the credential is not cached. Never put this token in a clone URL, `.env`, shell command, source file, Git history, or receipt. Full procedure: `docs/git-deployment-access.md`. + +### Remaining deployment checklist for tomorrow + +1. On `ops-monitor-host`, add the Caddy route for `telemetry.example.com` forwarding to `10.0.0.20:8000`; validate and reload Caddy. +2. In Cloudflare, create the matching `telemetry.example.com` DNS record using the existing email telemetry domain pattern. +3. In Postmark, configure a `broadcast-list` webhook at `https://telemetry.example.com/postmark` for Delivery, Bounce, Spam Complaint, Open, Link Click, and Subscription Change. +4. On the email VM, add the private Postmark settings to `/srv/email-list-system/.env`: + +```ini +EMAIL_LIST_PROVIDER=postmark +POSTMARK_SERVER_TOKEN= +POSTMARK_BROADCAST_STREAM_ID=broadcast-list +POSTMARK_FROM_NAME=PaddleNET +POSTMARK_FROM_EMAIL=eddie@paddlenet.earth +POSTMARK_REPLY_TO=eddie@paddlenet.earth +``` + +5. Resume with read-only Postmark suppression verification and webhook health checks. Do not send a real campaign or import real subscribers yet. +6. Replace `templates/welcome.md` with approved PaddleNET copy before enabling welcome cron. +7. Complete the remaining release checklist in `docs/release-checklist.md`, including initial subscriber import with `--no-welcome`, only after the live integrations and human review gates pass. diff --git a/tasks/2026-08-14-production-build-and-skill-handoff.md b/tasks/2026-08-14-production-build-and-skill-handoff.md new file mode 100644 index 0000000..41ac473 --- /dev/null +++ b/tasks/2026-08-14-production-build-and-skill-handoff.md @@ -0,0 +1,71 @@ +# PaddleNET Email-List Production Build and Skill Handoff + +Date: 2026-08-14 + +## Outcome + +The PaddleNET email-list system is operational for controlled, human-authorized campaign delivery. Production integration, delivery webhooks, and visible Postmark-managed unsubscribe links were verified with one-recipient test campaigns. No production subscriber list, cron job, welcome workflow, or automated follow-up is enabled. + +## Completed application and integration work + +- Built the Python CLI, SQLite runtime, private JSONL subscriber operations, campaign validation and rendering, campaign authorization, suppression reconciliation, backup creation, Postmark REST adapter, and Ops Monitor telemetry adapter. +- Deployed the email application to `10.0.0.10` at `/srv/email-list-system`. +- Deployed the Ops Monitor telemetry companion to `10.0.0.20:8000`. +- Configured the public Postmark webhook path: `https://telemetry.example.com/postmark`. +- Configured the existing Cloudflare Tunnel and Caddy tunnel-ingress handler so that `telemetry.example.com` forwards to Ops Monitor. +- Configured Postmark Broadcast Message Stream `broadcast-list` for PaddleNET delivery. +- Confirmed the production `.env` uses the Postmark REST adapter and separate private telemetry credentials. SMTP is not used. +- Corrected the Caddy routing requirement: the hostname handler must be inside Caddy's `http://:8080` tunnel-ingress block, not only in a separate HTTPS site block. +- Corrected the Docker runtime configuration rule: `EMAIL_LIST_HOST_DATA_DIR` must remain in the complete private `.env`, or Docker uses an empty named-volume fallback instead of the private SQLite runtime directory. + +## Production verification performed + +- Docker build, runtime initialization, health check, and Postmark suppression dry run passed on the email VM. +- The Ops Monitor authenticated telemetry route was verified from the email VM. +- A one-recipient delivery verification was accepted by Postmark and produced a Delivery webhook event in Ops Monitor. +- The first verification exposed a footer defect: it displayed a static unsubscribe sentence without a link. +- Commit `` replaced that sentence with Postmark's `{{{ pm:unsubscribe }}}` placeholder in both HTML and plain-text messages and added a regression test. +- The local container suite passed: 12 tests. +- A second one-recipient verification confirmed the visible, clickable Postmark-managed unsubscribe link and its delivery webhook. + +## Documentation and workflow updates + +- Commit `3c6d9bd` documented the verified production baseline, private `.env` requirements, Git deployment procedure, Caddy/Tunnel route requirement, and remaining release gates. +- The parent PaddleNET README now describes the operational email system and its production flow. +- The human-facing content source is `C:\projects\paddlenet-forge\paddlenet-hub\platform-updates`. +- The exact delivery artifact is a reviewed campaign Markdown file in `campaigns/drafts/` within this repository. It is committed, deployed, and bound to the campaign authorization before a send. + +## Production skills + +Commit `92dab17` added and validated three skill artifacts based on the Prompt, Skill, And Self-Improving Agent Design Template v0.3.1: + +- `skills/email-list-add-subscriber/SKILL.md`: add one consented subscriber via a private JSONL operation, dry run, and deterministic import. +- `skills/email-list-remove-subscriber/SKILL.md`: remove one address via a private JSONL unsubscribe operation, dry run, and deterministic import. +- `skills/email-list-operator/SKILL.md`: create a Hub-derived campaign draft, obtain review and explicit approval, deploy the reviewed revision, send safely, and record one authorized four-day apparent-non-opener follow-up. + +All three skills passed the template validator. They never permit direct SQLite changes, Git storage of subscriber data, suppression bypasses, or unapproved sends. + +## Current operating rules + +1. Add or remove individual subscribers through an authorized Codex prompt. The operator writes a private runtime JSONL operation, dry-runs it, then applies it. Do not put subscriber data in Git or PaddleNET Hub. +2. Create editorial updates in PaddleNET Hub first. The operator creates the reviewed, versioned campaign Markdown delivery artifact from that source. +3. A human must review the rendered campaign and give an exact send-and-follow-up directive before authorization or delivery. +4. Before every live send: validate and preview the campaign, confirm the deployed Git revision and complete private `.env`, run a suppression dry run, record authorization, review the recipient-count dry run, then send. +5. The system creates a backup and private sanitized receipt for a live send. Confirm the Delivery webhook in Ops Monitor. +6. A follow-up schedule may be recorded for four days later, but no unattended follow-up will execute until host cron is separately reviewed and installed. + +## Deferred work + +- Replace `templates/welcome.md` with approved PaddleNET welcome copy before enabling welcome processing. +- Review and import the initial real subscriber list using `--no-welcome`. +- Review and install host cron for subscriber operations, welcome processing, suppression reconciliation, backup retention, and due follow-ups. +- Design a separate authenticated intake before allowing a dedicated email address to add or remove subscribers. +- Before every code release on the VM, pull with the documented HTTPS Gitea token, set `EMAIL_LIST_GIT_COMMIT` to the pulled revision in private `.env`, rebuild, and run the documented verification checks. + +## References + +- `docs/operational-baseline.md` +- `docs/deployment.md` +- `docs/release-checklist.md` +- `docs/git-deployment-access.md` +- `docs/ai-operator.md` diff --git a/tasks/README.md b/tasks/README.md new file mode 100644 index 0000000..b43f64c --- /dev/null +++ b/tasks/README.md @@ -0,0 +1,3 @@ +# Repository Tasks + +Repository-structure plans, implementation receipts, and validation results live under a stable task ID. Task records document scope and approval but do not authorize unrelated operational actions. diff --git a/tasks/structure-ai-ready-repository/implementation-receipt.md b/tasks/structure-ai-ready-repository/implementation-receipt.md new file mode 100644 index 0000000..aeaf652 --- /dev/null +++ b/tasks/structure-ai-ready-repository/implementation-receipt.md @@ -0,0 +1,22 @@ +# Implementation Receipt + +- Task: `structure-ai-ready-repository` +- Approved revision: 1 +- Implemented: 2026-08-15 +- Status: implemented + +## Actions + +- Added verified repository identity, manifest, author, license, version, citation, changelog, contribution, security, agent, and skill entry points. +- Added repository metadata schemas, validator, tests, and collection indexes. +- Added a concise repository guide to the existing README without replacing its application specification. +- Aligned Python package author and license metadata with the verified public repository identity and MIT license. +- Preserved all project-native application, documentation, publication, skill, schema, template, and test content. + +## Deviations + +None. `content-index.json` and unused ceremonial directories remain intentionally absent as planned. + +## Rollback + +Because the template additions are new, uncommitted files plus a bounded README addition, rollback consists of removing only the files listed as created in the approved plan and reverting only the appended README repository-guide section. Preserve all pre-existing working-tree content. diff --git a/tasks/structure-ai-ready-repository/repository-structure-plan.md b/tasks/structure-ai-ready-repository/repository-structure-plan.md new file mode 100644 index 0000000..8de39d3 --- /dev/null +++ b/tasks/structure-ai-ready-repository/repository-structure-plan.md @@ -0,0 +1,51 @@ +# Repository Structure Plan + +- Task ID: `structure-ai-ready-repository` +- Revision: 1 +- Status: implemented +- Target: `C:\projects\productivity\automation-based-email-list-system-OPEN` +- Approval evidence: On 2026-08-15, the user explicitly requested that `repo-template-OPEN` be applied to this repository. + +## Current State And Profile + +The existing repository is a substantial sanitized Python/Docker email-list application with project documentation, schemas, templates, tests, operational examples, publication guardrails, and three AI operating skills. The selected profile is `software-automation`; a content index is intentionally omitted because the repository is application-centric and its principal collections fit cleanly in `repository.json`. + +## Proposed Tree + +Preserve the existing application tree and add the standard root metadata and governance entry points, repository schemas and validator, metadata tests, indexes for existing folders, and this task's implementation records. + +## File Actions + +| Action | Paths | Purpose | +| --- | --- | --- | +| Create | `AGENTS.md`, `AUTHOR.md`, `repository-variables.json`, `repository.json`, `LICENSE`, `CHANGELOG.md`, `CONTRIBUTING.md`, `SECURITY.md`, `CITATION.cff`, `VERSION`, `skills.md` | Add human/AI entry points, verified identity, machine-readable metadata, licensing, security, contribution, version, and skill guidance. | +| Create | `schemas/repository.schema.json`, `schemas/repository-variables.schema.json` | Add machine-readable contracts for repository metadata. | +| Create | `scripts/validate_repository.py`, `tests/test_repository_metadata.py` | Add deterministic repository validation and regression coverage. | +| Create | `scripts/README.md`, `schemas/README.md`, `tests/README.md`, `tasks/README.md`, `receipts/README.md` | Index existing repository collections and their safety boundaries. | +| Create | `tasks/structure-ai-ready-repository/implementation-receipt.md`, `tasks/structure-ai-ready-repository/validation-results.md` | Record implementation, validation, deviations, and rollback guidance. | +| Modify | `README.md`, `pyproject.toml` | Add a compact current repository map, AI retrieval order, validation commands, version, and license; align Python package license and author metadata with verified repository identity. Preserve the existing specification and operating guidance. | +| Preserve | Existing application, configuration, campaigns, documentation, operational examples, receipts, schemas, scripts, skills, source, templates, tests, task records, and publication files | Retain all project-native content and unrelated user work. | +| Leave absent | `content-index.json`, `assets/`, `data/`, `examples/`, host-specific issue/PR templates | Avoid ceremonial or unnecessary structure; individual documents do not require a separate content catalog yet. | + +## Identity And Publication Facts + +- Author and maintainer: Eddie Soehnel. +- Publisher and organization: adminprojects. +- Canonical URL: `https://projects.eddiesoehnel.com/adminprojects/automation-based-email-list-system-OPEN`. +- License: MIT, following the established convention in the directly related public `email-campaigns-prod-app-OPEN` repository. +- Verification date: 2026-08-15. + +## Validation And Definition Of Done + +Run the repository validator, all unit tests, the public leak scan, JSON parsing/schema checks included by the validator, and `git diff --check`. The work is complete when required entry points exist, metadata and versions align, declared paths resolve, links validate, project tests pass, and no unresolved leak finding is introduced by the template work. + +## Risks, Assumptions, And Scope + +- Existing working-tree changes are preserved and remain uncommitted. +- No email, subscriber, infrastructure, deployment, Git history, remote, branch, commit, or push action is authorized. +- The public repository is treated as a sanitized derivative; real operational values remain outside Git. +- MIT is based on the established adjacent public email repository convention rather than copied blindly from the template. + +## Completion + +Revision 1 was implemented on 2026-08-15 with no material departure from the approved scope. See `implementation-receipt.md` and `validation-results.md` in this task directory. diff --git a/tasks/structure-ai-ready-repository/validation-results.md b/tasks/structure-ai-ready-repository/validation-results.md new file mode 100644 index 0000000..d34418e --- /dev/null +++ b/tasks/structure-ai-ready-repository/validation-results.md @@ -0,0 +1,21 @@ +# Validation Results + +- Task: `structure-ai-ready-repository` +- Date: 2026-08-15 +- Status: passed + +## Results + +| Check | Result | Evidence | +| --- | --- | --- | +| Software/automation structural audit | Pass | No structural errors found. | +| `python scripts/validate_repository.py .` | Pass | No repository validation errors found. | +| `python -m unittest discover -s tests -p "test_*.py"` with `PYTHONPATH=src` | Pass | 15 tests passed. | +| `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/leak-scan.ps1` | Reviewed | The scanner reported expected keyword and documented placeholder matches; no new credential, subscriber record, private endpoint, database, backup, raw telemetry, or private receipt was introduced. The script is a review aid and does not classify matches automatically. | +| `git diff --check` | Pass | No whitespace errors; Git emitted only the existing Windows line-ending advisory for `README.md`. | + +## Coverage And Limitations + +- The validator parsed the repository JSON files, checked identity and version alignment, verified declared entry points and contents, and checked relative Markdown links. +- Application tests ran with the source-tree import path because the package was not installed into the active Python environment. +- No Docker build, live provider request, telemetry request, email send, subscriber mutation, deployment, scheduled job, commit, or push was performed; those actions were outside scope. diff --git a/templates/campaign.html b/templates/campaign.html new file mode 100644 index 0000000..6e3aa90 --- /dev/null +++ b/templates/campaign.html @@ -0,0 +1,18 @@ + + + + + + {{subject}} + + +
+ {{content}} +
+ +
+ + diff --git a/templates/welcome.md b/templates/welcome.md new file mode 100644 index 0000000..1a79eb0 --- /dev/null +++ b/templates/welcome.md @@ -0,0 +1 @@ +this is the welcome email. text to be modified. \ No newline at end of file diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..2c16e29 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,3 @@ +# Tests + +The test suite covers application behavior and repository metadata. Run `python -m unittest discover -s tests -p "test_*.py"` from the repository root. diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..d17e28d --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,248 @@ +import io +import json +import os +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path + +from email_list.cli import main +from email_list.providers.test_provider import TestProvider +from email_list.scheduler import run_due_followups +from email_list.storage.database import Database +from email_list.receipts import sanitize +from email_list.receipts import write_receipt + +class SystemCheckTests(unittest.TestCase): + def test_receipts_exclude_private_recipient_fields(self) -> None: + receipt = sanitize({"email": "person@example.com", "results": [{"email": "other@example.com"}], "accepted_count": 1}) + self.assertEqual(receipt, {"accepted_count": 1}) + + def test_written_receipt_is_sanitized(self) -> None: + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_RECEIPTS_DIR") + os.environ["EMAIL_LIST_RECEIPTS_DIR"] = directory + try: + path = write_receipt({"command": "subscriber.import", "email": "person@example.com", "results": [{"email": "other@example.com"}], "status": "ok"}) + with open(path, encoding="utf-8") as file: + saved = file.read() + self.assertNotIn("@example.com", saved) + self.assertIn("subscriber.import", saved) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_RECEIPTS_DIR", None) + else: + os.environ["EMAIL_LIST_RECEIPTS_DIR"] = original + def test_system_check_json(self) -> None: + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["system", "check", "--json"]), 0) + + result = json.loads(output.getvalue()) + self.assertEqual(result["schema_version"], "1.0") + self.assertEqual(result["command"], "system.check") + self.assertEqual(result["status"], "ok") + + def test_system_init_plans_without_creating_database(self) -> None: + with tempfile.TemporaryDirectory() as directory: + database = os.path.join(directory, "email-list.sqlite") + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + try: + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["system", "init", "--dry-run", "--json"]), 0) + result = json.loads(output.getvalue()) + self.assertEqual(result["status"], "planned") + self.assertFalse(os.path.exists(database)) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original + + def test_system_init_applies_migration_once(self) -> None: + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + try: + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["system", "init", "--json"]), 0) + result = json.loads(output.getvalue()) + self.assertEqual(result["applied_migrations"], [1, 2, 3]) + self.assertEqual(result["installed_schema_version"], 3) + + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["system", "init", "--json"]), 0) + self.assertEqual(json.loads(output.getvalue())["applied_migrations"], []) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original + + def test_backup_requires_initialized_database_and_copies_it(self) -> None: + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + try: + with self.assertRaises(FileNotFoundError): + main(["backup", "create", "--json"]) + with redirect_stdout(io.StringIO()): + main(["system", "init", "--json"]) + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["backup", "create", "--json"]), 0) + result = json.loads(output.getvalue()) + self.assertEqual(result["status"], "ok") + self.assertTrue(os.path.isfile(result["backup_path"])) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original + + def test_test_provider_suppression_reconcile_is_safe(self) -> None: + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + try: + with redirect_stdout(io.StringIO()): + main(["system", "init", "--json"]) + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["suppression", "reconcile", "--dry-run", "--json"]), 0) + result = json.loads(output.getvalue()) + self.assertEqual(result["status"], "planned") + self.assertEqual(result["provider_suppression_count"], 0) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original + + def test_subscriber_import_is_dry_run_then_idempotent(self) -> None: + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + operations = os.path.join(directory, "operations.jsonl") + with open(operations, "w", encoding="utf-8") as file: + file.write('{"schema_version":"1.0","operation_id":"example-1","operation":"subscribe","email":"PERSON@Example.com","source":"test","requested_at":"2026-08-13T00:00:00Z"}\n') + try: + with redirect_stdout(io.StringIO()): + main(["system", "init", "--json"]) + output = io.StringIO() + with redirect_stdout(output): + main(["subscriber", "import", operations, "--dry-run", "--json"]) + self.assertEqual(json.loads(output.getvalue())["results"][0]["result"], "planned") + with redirect_stdout(io.StringIO()): + main(["subscriber", "import", operations, "--json"]) + output = io.StringIO() + with redirect_stdout(output): + main(["subscriber", "import", operations, "--json"]) + self.assertEqual(json.loads(output.getvalue())["results"][0]["result"], "already_applied") + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original + + def test_campaign_validate_and_preview(self) -> None: + path = os.path.join(os.path.dirname(__file__), "..", "campaigns", "drafts", "example-campaign.md") + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["campaign", "validate", path, "--json"]), 0) + self.assertEqual(json.loads(output.getvalue())["campaign_id"], "paddlenet-example-update") + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["campaign", "preview", path, "--json"]), 0) + preview = json.loads(output.getvalue()) + self.assertIn("

PaddleNET example update

", preview["rendered_html"]) + self.assertIn('href="{{{ pm:unsubscribe }}}"', preview["rendered_html"]) + self.assertIn("Unsubscribe: {{{ pm:unsubscribe }}}", preview["rendered_text"]) + + def test_campaign_rejects_non_https_link(self) -> None: + with tempfile.NamedTemporaryFile("w", suffix=".md", encoding="utf-8", delete=False) as file: + file.write('---\nschema_version: "1.0"\ncampaign_id: unsafe-link\nsubject: Test\nfrom_name: PaddleNET\nreply_to: eddie@paddlenet.earth\naudience: active\n---\n\n[Test](http://example.com)') + path = file.name + try: + with self.assertRaises(ValueError): + main(["campaign", "validate", path, "--json"]) + finally: + os.unlink(path) + + def test_authorized_campaign_send_is_retry_safe(self) -> None: + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + operations = os.path.join(directory, "operations.jsonl") + path = os.path.join(os.path.dirname(__file__), "..", "campaigns", "drafts", "example-campaign.md") + with open(operations, "w", encoding="utf-8") as file: + file.write('{"schema_version":"1.0","operation_id":"recipient-1","operation":"subscribe","email":"person@example.com","source":"test","requested_at":"2026-08-13T00:00:00Z"}\n') + try: + with redirect_stdout(io.StringIO()): + main(["system", "init", "--json"]) + main(["subscriber", "import", operations, "--json"]) + with self.assertRaises(ValueError): + main(["campaign", "send", path, "--json"]) + with redirect_stdout(io.StringIO()): + main(["campaign", "approve", path, "--authorizer", "Eddie", "--directive-reference", "test directive", "--json"]) + output = io.StringIO() + with redirect_stdout(output): + main(["campaign", "send", path, "--dry-run", "--json"]) + self.assertEqual(json.loads(output.getvalue())["recipient_count"], 1) + with redirect_stdout(io.StringIO()): + main(["campaign", "send", path, "--json"]) + output = io.StringIO() + with redirect_stdout(output): + main(["campaign", "send", path, "--json"]) + result = json.loads(output.getvalue()) + self.assertEqual(result["accepted_count"], 0) + self.assertEqual(result["already_accepted_count"], 1) + self.assertTrue(os.path.isfile(result["backup_path"])) + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(main(["campaign", "schedule-non-openers", "paddlenet-example-update", "--subject", "PaddleNET example update", "--json"]), 0) + self.assertEqual(json.loads(output.getvalue())["subject"], "PaddleNET example update") + with self.assertRaises(ValueError): + main(["campaign", "schedule-non-openers", "paddlenet-example-update", "--subject", "Changed subject", "--json"]) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original + + def test_due_followup_uses_snapshot_and_runs_once(self) -> None: + class FakeTelemetry: + def apparent_non_openers(self, campaign_id: str) -> list[str]: + if campaign_id != "paddlenet-example-update": + raise AssertionError("Unexpected campaign ID") + return ["person@example.com"] + + with tempfile.TemporaryDirectory() as directory: + original = os.environ.get("EMAIL_LIST_DATA_DIR") + os.environ["EMAIL_LIST_DATA_DIR"] = directory + operations = os.path.join(directory, "operations.jsonl") + path = os.path.join(os.path.dirname(__file__), "..", "campaigns", "drafts", "example-campaign.md") + with open(operations, "w", encoding="utf-8") as file: + file.write('{"schema_version":"1.0","operation_id":"followup-recipient","operation":"subscribe","email":"person@example.com","source":"test","requested_at":"2026-08-13T00:00:00Z"}\n') + try: + with redirect_stdout(io.StringIO()): + main(["system", "init", "--json"]) + main(["subscriber", "import", operations, "--no-welcome", "--json"]) + main(["campaign", "approve", path, "--authorizer", "Eddie", "--directive-reference", "test directive", "--json"]) + main(["campaign", "send", path, "--json"]) + main(["campaign", "schedule-non-openers", "paddlenet-example-update", "--subject", "PaddleNET example update", "--json"]) + with Database(Path(directory) / "email-list.sqlite") as database: + assert database.connection is not None + database.connection.execute("UPDATE followup_schedules SET due_at_utc = '2000-01-01T00:00:00Z'") + outcome = run_due_followups(database.connection, TestProvider(), FakeTelemetry(), Path(os.path.dirname(path)), dry_run=False) + self.assertEqual(outcome["results"][0]["accepted_count"], 1) + self.assertEqual(run_due_followups(database.connection, TestProvider(), FakeTelemetry(), Path(os.path.dirname(path)), dry_run=False)["due_count"], 0) + finally: + if original is None: + os.environ.pop("EMAIL_LIST_DATA_DIR", None) + else: + os.environ["EMAIL_LIST_DATA_DIR"] = original diff --git a/tests/test_repository_metadata.py b/tests/test_repository_metadata.py new file mode 100644 index 0000000..286e7dc --- /dev/null +++ b/tests/test_repository_metadata.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path +import shutil +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +VALIDATOR_PATH = ROOT / "scripts" / "validate_repository.py" +SPEC = importlib.util.spec_from_file_location("validate_repository", VALIDATOR_PATH) +VALIDATOR = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +SPEC.loader.exec_module(VALIDATOR) + + +class RepositoryValidationTests(unittest.TestCase): + def test_current_repository_passes(self) -> None: + result = VALIDATOR.validate(ROOT) + self.assertTrue(result["passed"], result["findings"]) + + def test_missing_repository_fails(self) -> None: + with tempfile.TemporaryDirectory() as directory: + result = VALIDATOR.validate(Path(directory)) + self.assertFalse(result["passed"]) + self.assertTrue( + any("Missing required path" in item["message"] for item in result["findings"]) + ) + + def test_variable_identity_mismatch_fails(self) -> None: + with tempfile.TemporaryDirectory() as directory: + copy = Path(directory) / "repository" + shutil.copytree(ROOT, copy, ignore=shutil.ignore_patterns(".git", "__pycache__")) + variables_path = copy / "repository-variables.json" + variables = json.loads(variables_path.read_text(encoding="utf-8")) + variables["identity"]["publisher"]["name"] = "Different Publisher" + variables_path.write_text(json.dumps(variables, indent=2) + "\n", encoding="utf-8") + result = VALIDATOR.validate(copy) + self.assertFalse(result["passed"]) + self.assertTrue( + any( + "Publisher differs between repository-variables.json and repository.json" + in item["message"] + for item in result["findings"] + ) + ) + + +if __name__ == "__main__": + unittest.main()