Manual
Almnck.
Price: 50ⓐ

P0 Production-Safety Cluster Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Close the four remaining P0 findings from the 2026-07-06 codebase critique — a deploy path with no deterministic gate (item 4), two backup-less DB overwrites (item 5), silently-dropped paid checkouts (item 6), and race-prone payment/visit state (item 6a) — so a broken build, a truncated DB, or a duplicate webhook can no longer reach or corrupt production undetected.

Architecture: A new bin/a-verify script is the single deterministic release gate; CI (Forgejo) and an interim git pre-push hook both invoke it, and prod-deploy depends on its fast variant. Deploy loops become fail-stopping and health-checked. DB overwrites stage → integrity-check → back up → atomic-swap. The Stripe webhook becomes atomic (credit + receipt in one transaction), quarantines un-creditable events instead of silently dropping them, and relies on unique constraints for idempotency under concurrent delivery.

Tech Stack: Bash scripts under bin/, GNU Make, Forgejo Actions YAML, FastAPI + SQLModel + SQLite (WAL), PyNaCl, Stripe SDK, pytest (site tests emit TAP; API tests are host-run in-memory).

Global Constraints

  • Python >=3.11; build backend is hatchling (not uv_build). Do not “correct” this to 3.10/uv_build.
  • Activate the environment with source bin/a-activate before running make targets; it sets ALMANACK_ROOT and the .venv.
  • Reproducible install is uv sync --locked --extra api. The dev dependency-group (pytest, ruff) installs by default with uv sync.
  • Site tests live in src/tests/ and MUST emit TAP (pytest via --tap-stream). API tests live in api/tests/ and run host-side against an in-memory SQLite DB.
  • The unified runner is bin/a-test; suites are combined into one TAP stream. Registered pytest markers: regression, browser, checkout, stress, layout_invariants.
  • Local rm/mv/cp are aliased to interactive -i; in non-interactive scripts escape them (\rm, \mv, \cp). This is only Danny’s local shell — commands sent to remote hosts are unaffected.
  • House rule: back up before any destructive DB operation, and confirm scope.
  • This is a public-except-secrets/ repo. Commits must not embed secrets, PII, or local-only paths. Keep each commit to a single concern.
  • Production topology: hosts sj (PROD_SERVER), dallas, boat, each running a podman-compose stack. The membership API DB is /var/local/api/members.db; the repo is checked out at /var/local/src/almnck. Remote git forge is Forgejo at code.almnck.com:3022. No CI runner is registered yet — until one is, the git pre-push hook (Task 5) is the live gate.
  • The API has no schema-migration framework; it builds tables via SQLModel.metadata.create_all. New columns/constraints therefore apply to freshly-created tables only; existing production DBs need the one-time SQL called out in Tasks 8–9.

File Structure

New files: - bin/a-verify — the deterministic release gate (full + --no-container fast mode). - bin/a-web-deploy — hardened web rsync + Caddy reload + per-host health check. - bin/a-db-swap — validate a staged SQLite snapshot and atomically replace a DB, backing up the outgoing file. - bin/a-install-hooks — install the repo’s git hooks (pre-push → fast gate). - .forgejo/workflows/verify.yml — Forgejo Actions pipeline that runs bin/a-verify. - doc/03-website/07-forgejo-runner.md — runbook for standing up the act_runner on boat. - Tests: src/tests/test_ci_gate.py, src/tests/test_verify_gate.py, src/tests/test_web_deploy_guard.py, src/tests/test_deploy_loop_hardening.py, src/tests/test_forgejo_workflow.py, src/tests/test_db_swap.py, api/tests/test_webhook_quarantine.py, api/tests/test_webhook_idempotency.py, api/tests/test_visit_idempotency.py.

Modified files: - bin/a-test — strict mode, api-unit suite, corrected unit marker, default-suite change. - Makefile — pipefail shell, verify/verify-fast/install-hooks targets, hardened prod-deploy/prod-api-deploy/prod-ipfs-deploy/prod-api-restore, deleted pre-deploy. - bin/a-db-sync — call a-db-swap for the validated replace. - api/models.py — QuarantinedEvent, Transaction.stripe_event_id unique, Visit unique constraint. - api/db.py — register QuarantinedEvent; SQLite WAL/busy_timeout/foreign_keys pragmas. - api/main.py — atomic idempotent webhook, quarantine, visit idempotency.


Task 1: Fix bin/a-test false-greens; run the API unit tests by default

Files: - Modify: bin/a-test:102-144 (suites + defaults), bin/a-test:198-213 (run_api_suite strict mode) - Modify: Makefile:1-13 (pipefail shell), Makefile:31 (help text) - Test: src/tests/test_ci_gate.py

Interfaces: - Produces: environment variable A_TEST_STRICT — when set to "1", bin/a-test’s api suite treats a missing/failed container runtime as a failure (not ok, exit 1) instead of a skip. Task 2’s bin/a-verify sets it. - Produces: new suite name api-unit running pytest api/tests --tap-stream -q; added to DEFAULT_SUITES.

Note (scope): correcting the unit suite marker here also resolves the bin/a-test half of critique item 15 (the “unit” filter currently collects the checkout/stress/layout_invariants tests). This is intentional and called out so it is not a silent fold; the separate re-marking of test_topup_integration.py (item 15’s other half) remains future work.

  • [ ] Step 1: Write the failing tests

Create src/tests/test_ci_gate.py:

"""bin/a-test gate behaviour: strict mode fails closed; api-unit runs by default."""

import os
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def _run_atest(args, extra_env=None):
    env = dict(os.environ)
    env["ALMANACK_ROOT"] = str(ROOT)
    if extra_env:
        env.update(extra_env)
    return subprocess.run(
        [sys.executable, str(ROOT / "bin" / "a-test"), *args],
        env=env,
        capture_output=True,
        text=True,
    )


def test_api_suite_strict_fails_without_runtime(tmp_path):
    # Empty PATH → shutil.which finds no podman/docker.
    result = _run_atest(
        ["--suite", "api"],
        extra_env={"PATH": str(tmp_path), "A_TEST_STRICT": "1"},
    )
    assert result.returncode == 1, result.stdout
    assert "not ok" in result.stdout


def test_api_suite_nonstrict_skips_without_runtime(tmp_path):
    result = _run_atest(
        ["--suite", "api"],
        extra_env={"PATH": str(tmp_path)},
    )
    assert result.returncode == 0, result.stdout
    assert "# SKIP" in result.stdout


def test_api_unit_suite_is_a_default():
    result = _run_atest(["--list"])
    assert result.returncode == 0
    lines = result.stdout.splitlines()
    assert any("api-unit" in ln and "(default)" in ln for ln in lines), result.stdout
  • [ ] Step 2: Run the tests to verify they fail

Run: pytest src/tests/test_ci_gate.py -v Expected: FAIL — api-unit is not a suite yet, and strict mode does not exist (the strict test sees exit 0 / a SKIP line).

  • [ ] Step 3: Add the api-unit suite and correct the unit marker

In bin/a-test, inside get_test_suites() (around line 105), change the unit entry’s marker expression and add api-unit after it:

        "unit": [
            "pytest", "src/tests/",
            "-m", "not regression and not browser and not checkout "
                  "and not stress and not layout_invariants",
            "--tap-stream", "-q",
        ],
        "api-unit": [
            "pytest", "api/tests",
            "--tap-stream", "-q",
        ],
  • [ ] Step 4: Make api-unit a default suite

Change the default-suites line (currently bin/a-test:144):

# Default suites to run (in order)
# 'api' (container smoke) is intentionally NOT default: it is slow and
# skip-prone. The fast 'api-unit' suite runs the real API logic instead;
# the container smoke is enforced by `bin/a-verify` / `make test-all`.
DEFAULT_SUITES = ["doc", "api-unit", "unit"]
  • [ ] Step 5: Add strict mode to run_api_suite

Replace the body of run_api_suite (bin/a-test:198-213) with:

def run_api_suite(almanack_root: str, test_num: int) -> tuple[int, int]:
    """Run API container smoke with lifecycle management.

    When A_TEST_STRICT=1 a missing or broken container runtime is a FAILURE,
    not a skip — this is the mode CI uses so the API smoke cannot silently
    pass. Locally (unset) it stays a skip for convenience.
    """
    api_port = os.environ.get("API_PORT", "8000")
    strict = os.environ.get("A_TEST_STRICT") == "1"
    runtime = get_container_runtime()

    if not runtime:
        if strict:
            print(f"not ok {test_num} [api] container runtime required "
                  f"(A_TEST_STRICT=1) but none found", flush=True)
            return 1, 1
        print(f"ok {test_num} [api] # SKIP no container runtime (podman/docker) found", flush=True)
        return 1, 0

    with api_container(runtime, api_port, almanack_root) as started:
        if not started:
            if strict:
                print(f"not ok {test_num} [api] container failed to build/start "
                      f"(A_TEST_STRICT=1)", flush=True)
                return 1, 1
            print(f"ok {test_num} [api] # SKIP container failed to start", flush=True)
            return 1, 0

        cmd = ["bin/a-api-test", f"http://localhost:{api_port}"]
        return run_suite_streaming("api", cmd, almanack_root, test_num)
  • [ ] Step 6: Make Make pipelines fail-loud (pipefail)

At the top of Makefile, immediately after the colour variables (after line 4), add:

# Run recipes under bash with pipefail so a failing command in a
# `cmd | tapview` pipeline propagates instead of being masked by tapview's 0.
SHELL := bash
.SHELLFLAGS := -o pipefail -c

Also update the help text at Makefile:31 to drop the misleading timing/coverage claim:

    @echo "  test                Run fast tests: doc, api-unit, unit"
  • [ ] Step 7: Run the tests to verify they pass

Run: pytest src/tests/test_ci_gate.py -v Expected: PASS (3 tests).

Then confirm the runner still lists and runs cleanly: Run: bin/a-test --list Expected: output includes api-unit: pytest api/tests ... (default).

  • [ ] Step 8: Commit
git add bin/a-test Makefile src/tests/test_ci_gate.py
git commit -m "test: fail closed on missing API runtime; run api/tests by default

bin/a-test skipped the API suite (exit 0) when no container runtime was
present and never ran api/tests at all, so 'make test' could pass without
testing the API. Add A_TEST_STRICT, an api-unit suite, and pipefail so
failures surface."

Task 2: bin/a-verify deterministic gate + make verify / verify-fast

Files: - Create: bin/a-verify - Modify: Makefile (add verify, verify-fast targets near the testing section, after Makefile:240) - Test: src/tests/test_verify_gate.py

Interfaces: - Consumes: A_TEST_STRICT and the api suite from Task 1. - Produces: bin/a-verify [--no-container] — runs the full gate; exits non-zero on the first failing check; exits 2 on an unknown argument. make verify → full; make verify-fast → --no-container. Task 3 depends on verify-fast; Task 5 invokes both.

  • [ ] Step 1: Write the failing test

Create src/tests/test_verify_gate.py:

"""bin/a-verify argument handling and Makefile wiring."""

import os
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def test_verify_rejects_unknown_argument():
    result = subprocess.run(
        [str(ROOT / "bin" / "a-verify"), "--bogus"],
        env={**os.environ, "ALMANACK_ROOT": str(ROOT)},
        capture_output=True,
        text=True,
    )
    assert result.returncode == 2, result.stderr


def test_makefile_exposes_verify_targets():
    makefile = (ROOT / "Makefile").read_text()
    assert "\nverify:" in makefile
    assert "\nverify-fast:" in makefile
  • [ ] Step 2: Run the test to verify it fails

Run: pytest src/tests/test_verify_gate.py -v Expected: FAIL — bin/a-verify does not exist (non-zero from missing file, not 2) and the targets are absent.

  • [ ] Step 3: Create bin/a-verify
#!/usr/bin/env bash
# bin/a-verify — the deterministic release gate. Runs every check that must
# pass before a merge or deploy, and exits non-zero on the FIRST failure.
#
# Usage:
#   bin/a-verify                 # full gate — container API smoke REQUIRED
#   bin/a-verify --no-container  # fast gate — skip the container smoke
#
# CI must run the full form so a missing/broken container runtime FAILS
# rather than silently skipping. Deploys depend on the fast form
# (`make verify-fast`) so they don't need podman on the operator's laptop.
set -euo pipefail

ALMANACK_ROOT="${ALMANACK_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
export ALMANACK_ROOT
cd "$ALMANACK_ROOT"

CONTAINER=1
for arg in "$@"; do
    case "$arg" in
        --no-container) CONTAINER=0 ;;
        *) echo "a-verify: unknown argument: $arg" >&2; exit 2 ;;
    esac
done

step() { echo ""; echo "=== a-verify: $* ==="; }

# 1. Reproducible install from the lockfile.
step "uv sync --locked"
uv sync --locked --extra api

# 2. Documentation link check (offline).
step "doc link check"
uv run bin/a-test --suite doc

# 3. Site unit tests (marker-corrected: no browser/checkout/stress).
step "site unit tests"
uv run pytest src/tests \
    -m "not browser and not regression and not checkout and not stress and not layout_invariants" \
    --tap-stream -q

# 4. API unit tests (host, in-memory DB — no container needed).
step "api unit tests"
uv run pytest api/tests --tap-stream -q

# 5. Framework check + migrate + sync + build smoke.
step "django check / migrate / sync / build smoke"
( cd src && uv run python manage.py check )
( cd src && uv run python manage.py migrate --noinput )
( cd src && uv run python manage.py sync_with_repo )
( cd src && uv run python manage.py build_with_distill )
test -f "$ALMANACK_ROOT/web/index.html" \
    || { echo "a-verify: build produced no web/index.html" >&2; exit 1; }

# 6. Strict container API smoke (built image), unless explicitly skipped.
if [ "$CONTAINER" -eq 1 ]; then
    step "container API smoke (strict)"
    A_TEST_STRICT=1 uv run bin/a-test --suite api
else
    echo ""
    echo "=== a-verify: container API smoke SKIPPED (--no-container) ==="
fi

echo ""
echo "a-verify: all checks passed."

Make it executable:

chmod +x bin/a-verify
  • [ ] Step 4: Add the Makefile targets

After the last test-* target (after Makefile:240, the test-stress block), add:

.PHONY: verify
verify: check-activated
    @$(ALMANACK_ROOT)/bin/a-verify

.PHONY: verify-fast
verify-fast: check-activated
    @$(ALMANACK_ROOT)/bin/a-verify --no-container
  • [ ] Step 5: Run the test to verify it passes

Run: pytest src/tests/test_verify_gate.py -v Expected: PASS (2 tests).

  • [ ] Step 6: Smoke-test the fast gate end-to-end

Run: make verify-fast Expected: sections 1–5 print and end with a-verify: all checks passed. (This actually runs the doc/unit/api-unit/build checks; it is the gate proving itself. If any real check fails, fix it before continuing — that is the gate doing its job.)

  • [ ] Step 7: Commit
git add bin/a-verify Makefile src/tests/test_verify_gate.py
git commit -m "build: add bin/a-verify deterministic release gate

One non-interactive target that installs from the lockfile and runs doc,
site-unit, api-unit, a check/sync/build smoke, and (full mode) a strict
container API smoke. make verify / verify-fast wrap it."

Task 3: Harden the web deploy; make prod-deploy depend on the gate

Files: - Create: bin/a-web-deploy - Modify: Makefile:343-353 (delete pre-deploy; rewrite prod-deploy) - Test: src/tests/test_web_deploy_guard.py

Interfaces: - Consumes: make verify-fast from Task 2. - Produces: bin/a-web-deploy — rsyncs web/ to each destination and reloads Caddy, stopping on the first failed host and health-checking each reloaded server. Honours env overrides WEB_DESTINATIONS, WEB_SERVERS, WEB_HEALTH_URL (for tests). Refuses to run if web/index.html is missing.

  • [ ] Step 1: Write the failing tests

Create src/tests/test_web_deploy_guard.py:

"""bin/a-web-deploy refuses an empty build and no-ops cleanly with no hosts."""

import os
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def _run(root, extra_env=None):
    env = dict(os.environ)
    env["ALMANACK_ROOT"] = str(root)
    env["WEB_DESTINATIONS"] = ""
    env["WEB_SERVERS"] = ""
    if extra_env:
        env.update(extra_env)
    return subprocess.run(
        [str(ROOT / "bin" / "a-web-deploy")],
        env=env,
        capture_output=True,
        text=True,
    )


def test_refuses_without_index_html(tmp_path):
    (tmp_path / "web").mkdir()
    result = _run(tmp_path)
    assert result.returncode == 1
    assert "index.html" in result.stderr


def test_succeeds_with_index_and_no_hosts(tmp_path):
    web = tmp_path / "web"
    web.mkdir()
    (web / "index.html").write_text("<html></html>")
    result = _run(tmp_path)
    assert result.returncode == 0, result.stderr
    assert "all hosts deployed" in result.stdout
  • [ ] Step 2: Run the tests to verify they fail

Run: pytest src/tests/test_web_deploy_guard.py -v Expected: FAIL — bin/a-web-deploy does not exist.

  • [ ] Step 3: Create bin/a-web-deploy
#!/usr/bin/env bash
# bin/a-web-deploy — push web/ to every production host and reload Caddy,
# stopping on the first failed host and health-checking each reloaded server.
# Refuses to run if the build is empty (no web/index.html), so a broken
# `make build` can't rsync --delete a live site into nothing.
set -euo pipefail

ALMANACK_ROOT="${ALMANACK_ROOT:?ALMANACK_ROOT not set (source bin/a-activate)}"

DESTINATIONS="${WEB_DESTINATIONS-boat:/var/local/www/www.almnck.com/ dallas:/var/local/www/www.almnck.com/ sj:/var/local/www/www.almnck.com/}"
WEB_SERVERS="${WEB_SERVERS-sj dallas}"

RSYNC_OPTS=(-avz --delete --delete-after --filter='dir-merge,-n /.gitignore' -e a-ssh)

if [ ! -f "$ALMANACK_ROOT/web/index.html" ]; then
    echo "a-web-deploy: $ALMANACK_ROOT/web/index.html missing; refusing to deploy." >&2
    exit 1
fi

for dest in $DESTINATIONS; do
    echo "=== rsync web/ -> $dest ==="
    rsync "${RSYNC_OPTS[@]}" "$ALMANACK_ROOT/web/" "$dest"
done

for srv in $WEB_SERVERS; do
    echo "=== reloading Caddy on $srv ==="
    a-ssh "$srv" podman-compose exec -T almnck caddy reload --config /etc/caddy/Caddyfile
done

for srv in $WEB_SERVERS; do
    echo "=== health check: $srv ==="
    if ! a-ssh "$srv" 'curl -fsS -o /dev/null --max-time 10 http://localhost/'; then
        echo "a-web-deploy: $srv did not answer after reload." >&2
        exit 1
    fi
done

echo "a-web-deploy: all hosts deployed and healthy."

Note the ${WEB_DESTINATIONS-...} form (single dash): an explicitly-empty env value overrides the default, which is what the tests rely on. Make it executable:

chmod +x bin/a-web-deploy
  • [ ] Step 4: Delete the LLM pre-deploy target and rewrite prod-deploy

In Makefile, delete the pre-deploy target (Makefile:343-345) entirely — an interactive claude -p run is not a reproducible gate. Then replace the prod-deploy target (Makefile:347-353) with:

.PHONY: prod-deploy
prod-deploy: check-activated verify-fast update-finances sync celestial build
    @echo "$(RED)Deploying to production...$(RESET)"
    @$(ALMANACK_ROOT)/bin/a-web-deploy
    @echo "$(GREEN)Deploy complete.$(RESET)"
    @$(MAKE) indexnow

verify-fast now runs first; because recipes run under pipefail (Task 1) and a-web-deploy uses set -e, any failed host aborts the deploy before indexnow.

  • [ ] Step 5: Run the tests to verify they pass

Run: pytest src/tests/test_web_deploy_guard.py -v Expected: PASS (2 tests).

  • [ ] Step 6: Verify the Makefile still parses

Run: make -n prod-deploy-dry Expected: prints commands with no make syntax error (confirms the edited region parses).

  • [ ] Step 7: Commit
git add bin/a-web-deploy Makefile src/tests/test_web_deploy_guard.py
git commit -m "deploy: gate prod-deploy on verify-fast; fail-stop web deploy

The old foreach loops joined per-host rsync/reload with ';', so a failed
host still printed 'Deploy complete' and pinged IndexNow. bin/a-web-deploy
stops on the first failure, health-checks each reloaded host, and refuses to
push an empty build. Drops the non-reproducible claude -p pre-deploy target."

Task 4: Fail-stop the API and IPFS deploy loops

Files: - Modify: Makefile:372-396 (prod-api-deploy, prod-ipfs-deploy) - Test: src/tests/test_deploy_loop_hardening.py

Interfaces: - Consumes: nothing new. - Produces: prod-api-deploy and prod-ipfs-deploy abort on the first failed host and print the per-host success line only after that host actually succeeds; prod-api-deploy health-checks /health after each deploy.

  • [ ] Step 1: Write the failing test

Create src/tests/test_deploy_loop_hardening.py:

"""The multi-host deploy recipes must propagate per-host failure."""

import os
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def _recipe(target):
    """Return the raw recipe text for a Makefile target."""
    text = (ROOT / "Makefile").read_text()
    marker = f"\n{target}:"
    start = text.index(marker)
    # recipe runs until the next top-level '.PHONY' declaration
    end = text.index("\n.PHONY:", start + 1)
    return text[start:end]


def test_api_deploy_fails_on_bad_host():
    recipe = _recipe("prod-api-deploy")
    assert "exit 1" in recipe            # a failed host aborts
    assert "/health" in recipe           # deployed API is health-checked


def test_ipfs_deploy_fails_on_bad_host():
    recipe = _recipe("prod-ipfs-deploy")
    assert "exit 1" in recipe


def test_makefile_parses():
    result = subprocess.run(
        ["make", "-n", "prod-api-deploy"],
        cwd=ROOT,
        env={**os.environ, "ALMANACK_ROOT": str(ROOT)},
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0, result.stderr
  • [ ] Step 2: Run the test to verify it fails

Run: pytest src/tests/test_deploy_loop_hardening.py -v Expected: FAIL — the current recipes contain neither exit 1 nor /health.

  • [ ] Step 3: Harden prod-api-deploy

Replace the prod-api-deploy recipe body (Makefile:372-383) with:

.PHONY: prod-api-deploy
prod-api-deploy: check-activated
    @echo "$(RED)Deploying API to all servers...$(RESET)"
    @STRIPE_KEY="$$(PASSWORD_STORE_DIR=$(ALMANACK_ROOT)/secrets/ pass stripe/live-restricted-key)" && \
    STRIPE_WEBHOOK="$$(PASSWORD_STORE_DIR=$(ALMANACK_ROOT)/secrets/ pass stripe/live-webhook-secret)" && \
    for srv in $(API_SERVERS); do \
        echo "$(YELLOW)Deploying API to $$srv...$(RESET)"; \
        printf 'STRIPE_SECRET_KEY=%s\nSTRIPE_WEBHOOK_SECRET=%s\n' "$$STRIPE_KEY" "$$STRIPE_WEBHOOK" \
            | a-ssh $$srv 'cat > /var/local/api/.env && chmod 600 /var/local/api/.env' \
            || { echo "$(RED)env push to $$srv failed$(RESET)"; exit 1; }; \
        a-ssh $$srv 'cd /var/local/src/almnck && git pull && cd ~ && podman-compose stop membership-api 2>/dev/null; podman-compose rm -f membership-api 2>/dev/null; podman-compose up -d --build membership-api' \
            || { echo "$(RED)deploy to $$srv failed$(RESET)"; exit 1; }; \
        a-ssh $$srv 'curl -fsS -o /dev/null --max-time 15 http://localhost:8000/health' \
            || { echo "$(RED)$$srv API unhealthy after deploy$(RESET)"; exit 1; }; \
        echo "$(GREEN)API deployed to $$srv.$(RESET)"; \
    done
  • [ ] Step 4: Harden prod-ipfs-deploy

Replace the prod-ipfs-deploy recipe body (Makefile:385-396) with:

.PHONY: prod-ipfs-deploy
prod-ipfs-deploy: check-activated
    @echo "$(RED)Deploying IPFS cluster to all servers...$(RESET)"
    @CLUSTER_SECRET="$$(PASSWORD_STORE_DIR=$(ALMANACK_ROOT)/secrets/ pass ipfs/cluster-secret)" && \
    for srv in $(API_SERVERS); do \
        echo "$(YELLOW)Deploying IPFS to $$srv...$(RESET)"; \
        a-ssh $$srv 'mkdir -p /var/local/ipfs /var/local/ipfs-cluster' \
            || { echo "$(RED)mkdir on $$srv failed$(RESET)"; exit 1; }; \
        printf 'CLUSTER_SECRET=%s\n' "$$CLUSTER_SECRET" \
            | a-ssh $$srv 'cat > /var/local/ipfs-cluster/cluster.env && chmod 600 /var/local/ipfs-cluster/cluster.env' \
            || { echo "$(RED)secret push to $$srv failed$(RESET)"; exit 1; }; \
        a-ssh $$srv 'cd /var/local/src/almnck && git pull && cd ~ && podman-compose up -d ipfs ipfs-cluster' \
            || { echo "$(RED)IPFS deploy to $$srv failed$(RESET)"; exit 1; }; \
        echo "$(GREEN)IPFS deployed to $$srv.$(RESET)"; \
    done
  • [ ] Step 5: Run the tests to verify they pass

Run: pytest src/tests/test_deploy_loop_hardening.py -v Expected: PASS (3 tests).

  • [ ] Step 6: Commit
git add Makefile src/tests/test_deploy_loop_hardening.py
git commit -m "deploy: abort API/IPFS deploy on first failed host

Both recipes joined per-host commands so a failed secret push, git pull, or
container start still printed success and moved on. Propagate failure with
|| exit 1 and health-check the API after each deploy."

Task 5: Forgejo CI workflow + interim pre-push hook + runner runbook

Files: - Create: .forgejo/workflows/verify.yml - Create: bin/a-install-hooks - Create: doc/03-website/07-forgejo-runner.md - Modify: Makefile (add install-hooks target; add it to bootstrap deps at Makefile:117-118) - Test: src/tests/test_forgejo_workflow.py

Interfaces: - Consumes: bin/a-verify (Task 2). - Produces: .forgejo/workflows/verify.yml running bin/a-verify on push/PR; bin/a-install-hooks installing a pre-push hook that runs bin/a-verify --no-container; make install-hooks.

  • [ ] Step 1: Write the failing test

Create src/tests/test_forgejo_workflow.py:

"""The CI workflow parses and runs the gate; the hook installer works."""

import os
import subprocess
from pathlib import Path

import yaml

ROOT = Path(__file__).resolve().parents[2]


def test_workflow_parses_and_runs_verify():
    wf = yaml.safe_load((ROOT / ".forgejo" / "workflows" / "verify.yml").read_text())
    assert "verify" in wf["jobs"]
    steps = wf["jobs"]["verify"]["steps"]
    assert any("a-verify" in str(step.get("run", "")) for step in steps)


def test_install_hooks_creates_pre_push(tmp_path):
    subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)
    result = subprocess.run(
        [str(ROOT / "bin" / "a-install-hooks")],
        cwd=tmp_path,
        env={**os.environ},
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0, result.stderr
    hook = tmp_path / ".git" / "hooks" / "pre-push"
    assert hook.exists()
    assert "a-verify" in hook.read_text()
  • [ ] Step 2: Run the test to verify it fails

Run: pytest src/tests/test_forgejo_workflow.py -v Expected: FAIL — neither the workflow nor the installer exists.

  • [ ] Step 3: Create the Forgejo workflow

Create .forgejo/workflows/verify.yml:

name: verify
on:
  push:
  pull_request:

jobs:
  verify:
    runs-on: docker
    steps:
      - uses: actions/checkout@v4
      - name: Install uv
        run: curl -LsSf https://astral.sh/uv/install.sh | sh
      - name: Run the release gate
        run: |
          export PATH="$HOME/.local/bin:$PATH"
          ./bin/a-verify
  • [ ] Step 4: Create bin/a-install-hooks
#!/usr/bin/env bash
# bin/a-install-hooks — install this repo's git hooks.
#
# pre-push runs the fast deterministic gate (bin/a-verify --no-container) so a
# push can't carry a broken build. Bypass a single push with `git push
# --no-verify`. Installs into the current repo's hooks dir.
set -euo pipefail

HOOK_DIR="$(git rev-parse --git-path hooks)"
mkdir -p "$HOOK_DIR"

cat > "$HOOK_DIR/pre-push" <<'HOOK'
#!/usr/bin/env bash
# Almanack pre-push gate. Bypass with: git push --no-verify
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
echo "pre-push: running fast verify gate (bypass with git push --no-verify)..."
exec "$ROOT/bin/a-verify" --no-container
HOOK

chmod +x "$HOOK_DIR/pre-push"
echo "Installed pre-push hook -> $HOOK_DIR/pre-push"

Make it executable:

chmod +x bin/a-install-hooks
  • [ ] Step 5: Add the install-hooks target and wire it into bootstrap

In Makefile, add near the other setup targets (after install-dev-binaries, around Makefile:128):

.PHONY: install-hooks
install-hooks:
    @bin/a-install-hooks

Then extend the bootstrap prerequisites (Makefile:118) so a fresh clone gets the hook:

bootstrap: install install-dev-binaries install-hooks
  • [ ] Step 6: Write the runner runbook

Create doc/03-website/07-forgejo-runner.md:

# Forgejo Actions runner (boat)

The `verify` workflow (`.forgejo/workflows/verify.yml`) runs `bin/a-verify` on
every push and pull request. It needs a registered Forgejo Actions runner. We
host one on `boat`'s podman stack. Until it is registered the workflow is
inert; the git pre-push hook (`make install-hooks`) is the live gate in the
meantime.

## One-time setup on boat

1. In the Forgejo web UI: **Site Administration -> Actions -> Runners ->
   Create new runner**, and copy the registration token.
2. On boat, run `act_runner` as a rootful podman container (rootful is needed
   so the runner can build and run the API smoke container that `a-verify`
   requires):

   ```sh
   podman run -d --restart=always --name forgejo-runner \
     -v /var/local/forgejo-runner:/data \
     -v /run/podman/podman.sock:/var/run/docker.sock \
     -e GITEA_INSTANCE_URL=https://code.almnck.com \
     -e GITEA_RUNNER_REGISTRATION_TOKEN=<token> \
     -e GITEA_RUNNER_LABELS=docker \
     docker.io/gitea/act_runner:latest
   ```

   The `docker` label matches `runs-on: docker` in the workflow. Mapping the
   podman socket to `/var/run/docker.sock` lets the runner start the nested
   API smoke container.

3. Confirm the runner shows **Idle** in the Forgejo UI.

## Protect the deployment branch

In the repo settings, add a branch-protection rule on `main` that requires the
`verify` status check to pass before merge. This is what makes the gate
binding rather than advisory.

## Verifying

Push a trivial branch and confirm the `verify` job runs and goes green in the
Actions tab. If the container smoke step fails with a socket/permission error,
the runner is rootless or the socket mount is wrong — see step 2.
  • [ ] Step 7: Run the test to verify it passes

Run: pytest src/tests/test_forgejo_workflow.py -v Expected: PASS (2 tests).

Then confirm the new doc has no broken links: Run: bin/a-test --suite doc Expected: all link checks pass (the runbook uses only inline code, no outbound links to break).

  • [ ] Step 8: Install the hook locally and commit
make install-hooks
git add .forgejo/workflows/verify.yml bin/a-install-hooks doc/03-website/07-forgejo-runner.md Makefile src/tests/test_forgejo_workflow.py
git commit -m "ci: add Forgejo verify workflow, pre-push gate, runner runbook

verify.yml runs bin/a-verify on push/PR. Until the boat runner is registered,
bin/a-install-hooks wires a pre-push hook that runs the fast gate. Runbook
documents standing up act_runner and protecting main."

Task 6: bin/a-db-swap + backup-before-swap in a-db-sync

Files: - Create: bin/a-db-swap - Modify: bin/a-db-sync:71-77 (call a-db-swap for the validated replace; add REMOTE_ALMANACK) - Test: src/tests/test_db_swap.py

Interfaces: - Produces: bin/a-db-swap TMP DB — verifies PRAGMA integrity_check on the staged snapshot TMP, refuses a snapshot smaller than 50% of the current DB, backs up the outgoing DB to DB.bak-<timestamp> (keeping the newest DB_SWAP_KEEP, default 7), then atomically mvs TMP over DB. Exits non-zero and leaves DB untouched on any validation failure.

  • [ ] Step 1: Write the failing tests

Create src/tests/test_db_swap.py:

"""bin/a-db-swap validates a staged snapshot before replacing a live DB."""

import os
import sqlite3
import subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
SWAP = ROOT / "bin" / "a-db-swap"


def _make_db(path, rows):
    con = sqlite3.connect(path)
    con.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
    con.executemany("INSERT INTO t (v) VALUES (?)", [(f"row{i}",) for i in range(rows)])
    con.commit()
    con.close()


def _run(tmp, db):
    return subprocess.run(
        [str(SWAP), str(tmp), str(db)],
        env={**os.environ},
        capture_output=True,
        text=True,
    )


def test_valid_snapshot_replaces_and_backs_up(tmp_path):
    db = tmp_path / "members.db"
    tmp = tmp_path / "snap.db"
    _make_db(db, 100)
    _make_db(tmp, 120)
    original = db.read_bytes()

    result = _run(tmp, db)
    assert result.returncode == 0, result.stderr

    # DB now holds the snapshot's 120 rows.
    con = sqlite3.connect(db)
    assert con.execute("SELECT COUNT(*) FROM t").fetchone()[0] == 120
    con.close()
    # The outgoing DB was backed up.
    backups = list(tmp_path.glob("members.db.bak-*"))
    assert len(backups) == 1
    assert backups[0].read_bytes() == original
    # The staged snapshot was consumed.
    assert not tmp.exists()


def test_truncated_snapshot_is_refused(tmp_path):
    db = tmp_path / "members.db"
    tmp = tmp_path / "snap.db"
    _make_db(db, 100)
    tmp.write_bytes(b"")  # empty transfer

    result = _run(tmp, db)
    assert result.returncode == 1
    # Live DB untouched.
    con = sqlite3.connect(db)
    assert con.execute("SELECT COUNT(*) FROM t").fetchone()[0] == 100
    con.close()


def test_corrupt_snapshot_is_refused(tmp_path):
    db = tmp_path / "members.db"
    tmp = tmp_path / "snap.db"
    _make_db(db, 100)
    tmp.write_bytes(b"this is not a sqlite database" * 100)

    result = _run(tmp, db)
    assert result.returncode == 1
    con = sqlite3.connect(db)
    assert con.execute("SELECT COUNT(*) FROM t").fetchone()[0] == 100
    con.close()
  • [ ] Step 2: Run the tests to verify they fail

Run: pytest src/tests/test_db_swap.py -v Expected: FAIL — bin/a-db-swap does not exist.

  • [ ] Step 3: Create bin/a-db-swap
#!/usr/bin/env bash
# bin/a-db-swap TMP DB — validate a staged SQLite snapshot and atomically
# replace DB with it, backing up the outgoing file first.
#
# Refuses a snapshot that fails PRAGMA integrity_check or is smaller than 50%
# of the current DB (guards a truncated transfer). Keeps the newest
# DB_SWAP_KEEP (default 7) backups. On any failure DB is left untouched.
set -euo pipefail

tmp="${1:?usage: a-db-swap TMP DB}"
db="${2:?usage: a-db-swap TMP DB}"
keep="${DB_SWAP_KEEP:-7}"

filesize() { stat -c%s "$1" 2>/dev/null || stat -f%z "$1"; }

result="$(sqlite3 "$tmp" 'PRAGMA integrity_check;' 2>/dev/null || echo 'unreadable')"
if [ "$result" != "ok" ]; then
    echo "a-db-swap: integrity check failed: $result" >&2
    \rm -f "$tmp"
    exit 1
fi

newsize="$(filesize "$tmp")"
if [ -f "$db" ]; then
    oldsize="$(filesize "$db")"
    if [ "$newsize" -lt $(( oldsize / 2 )) ]; then
        echo "a-db-swap: snapshot ${newsize}B < 50% of current ${oldsize}B; refusing" >&2
        \rm -f "$tmp"
        exit 1
    fi
    \cp -p "$db" "${db}.bak-$(date +%Y%m%dT%H%M%S)"
    # Prune all but the newest $keep backups.
    ls -1t "${db}".bak-* 2>/dev/null | tail -n +$(( keep + 1 )) | xargs -r \rm -f
fi

\mv "$tmp" "$db"
echo "a-db-swap: replaced $db (was ${oldsize:-absent}B, now ${newsize}B)."

Make it executable:

chmod +x bin/a-db-swap
  • [ ] Step 4: Route a-db-sync’s replace through a-db-swap

In bin/a-db-sync, add a destination-repo path variable near the other constants (after line 17):

REMOTE_ALMANACK="/var/local/src/almnck"

Then replace the “4. Replace database” block (bin/a-db-sync:71-77) with:

# 4. Validate and atomically replace the database (integrity check, size
#    sanity, and a backup of the outgoing file — see bin/a-db-swap).
echo "Validating and replacing database..."
if [ "$LOCAL" = true ]; then
    "${REMOTE_ALMANACK}/bin/a-db-swap" "${REMOTE_TMP}" "${REMOTE_DB}"
else
    $SSH_CMD "$DST_HOST" "${REMOTE_ALMANACK}/bin/a-db-swap '${REMOTE_TMP}' '${REMOTE_DB}'"
fi
  • [ ] Step 5: Run the tests to verify they pass

Run: pytest src/tests/test_db_swap.py -v Expected: PASS (3 tests).

Then confirm a-db-sync still parses: Run: bash -n bin/a-db-sync Expected: no output, exit 0.

  • [ ] Step 6: Commit
git add bin/a-db-swap bin/a-db-sync src/tests/test_db_swap.py
git commit -m "db: validate and back up before replacing the replica DB

a-db-sync mv'd the transferred snapshot straight over the live failover
members.db with no integrity check or backup — a truncated transfer
silently destroyed the replica. Route the swap through bin/a-db-swap:
integrity_check, 50% size floor, timestamped backup, atomic mv."

Task 7: Server-side snapshot + integrity gate in prod-api-restore

Files: - Modify: Makefile:420-434 (prod-api-restore) - Test: src/tests/test_restore_safety.py

Interfaces: - Consumes: nothing new (restore’s own 50%-size guard is deliberately omitted — a restore is a manual, deliberate act; only the integrity check gates it). - Produces: make prod-api-restore DB_FILE=... snapshots the live production DB server-side before overwriting, and only swaps in the uploaded file if it passes PRAGMA integrity_check.

  • [ ] Step 1: Write the failing test

Create src/tests/test_restore_safety.py:

"""prod-api-restore must back up the live DB and integrity-check the upload."""

from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]


def _recipe(target):
    text = (ROOT / "Makefile").read_text()
    start = text.index(f"\n{target}:")
    end = text.index("\n.PHONY:", start + 1)
    return text[start:end]


def test_restore_snapshots_before_overwrite():
    recipe = _recipe("prod-api-restore")
    assert "pre-restore-" in recipe          # server-side backup filename
    assert "integrity_check" in recipe       # uploaded file is validated
    assert ".incoming" in recipe             # staged, not written in place
  • [ ] Step 2: Run the test to verify it fails

Run: pytest src/tests/test_restore_safety.py -v Expected: FAIL — the current recipe pipes straight over members.db with no backup or check.

  • [ ] Step 3: Rewrite prod-api-restore

Replace the prod-api-restore recipe (Makefile:420-434) with:

.PHONY: prod-api-restore
prod-api-restore:
ifndef DB_FILE
    @echo "$(RED)Usage: make prod-api-restore DB_FILE=db-backups/members-YYYY-MM-DDTHH.db$(RESET)"
    @exit 1
endif
    @echo "$(RED)This will replace the production database with $(DB_FILE)$(RESET)"
    @read -p "Are you sure? [y/N] " confirm && [ "$$confirm" = "y" ] || (echo "Aborted." && exit 1)
    @echo "$(YELLOW)Stopping API...$(RESET)"
    ssh $(PROD_SERVER) 'cd ~ && podman-compose stop membership-api'
    @echo "$(YELLOW)Backing up the current production DB server-side...$(RESET)"
    ssh $(PROD_SERVER) 'cp -p /var/local/api/members.db /var/local/api/members.pre-restore-$$(date +%Y%m%dT%H%M%S).db' \
        || { echo "$(RED)Pre-restore backup failed; aborting (DB unchanged).$(RESET)"; ssh $(PROD_SERVER) 'cd ~ && podman-compose start membership-api'; exit 1; }
    @echo "$(YELLOW)Uploading and integrity-checking $(DB_FILE)...$(RESET)"
    cat $(DB_FILE) | ssh $(PROD_SERVER) 'cat > /var/local/api/members.db.incoming && \
        [ "$$(sqlite3 /var/local/api/members.db.incoming "PRAGMA integrity_check;")" = ok ] && \
        mv /var/local/api/members.db.incoming /var/local/api/members.db' \
        || { echo "$(RED)Uploaded DB failed integrity check; production DB unchanged.$(RESET)"; ssh $(PROD_SERVER) 'rm -f /var/local/api/members.db.incoming; cd ~ && podman-compose start membership-api'; exit 1; }
    @echo "$(YELLOW)Starting API...$(RESET)"
    ssh $(PROD_SERVER) 'cd ~ && podman-compose start membership-api'
    @echo "$(GREEN)Database restored from $(DB_FILE)$(RESET)"
  • [ ] Step 4: Run the test to verify it passes

Run: pytest src/tests/test_restore_safety.py -v Expected: PASS (1 test).

Then confirm the recipe parses: Run: make -n prod-api-restore DB_FILE=/tmp/x.db Expected: prints commands, exit 0.

  • [ ] Step 5: Commit
git add Makefile src/tests/test_restore_safety.py
git commit -m "db: snapshot prod DB and validate upload before restore

prod-api-restore overwrote the live DB over ssh with only a y/N prompt and
no server-side backup or check. Back up the current DB, stage the upload to
.incoming, integrity-check it, and swap only on success; restart the API on
any failure so a bad restore doesn't leave it stopped."

Task 8: Atomic, idempotent Stripe webhook that quarantines un-creditable events

Files: - Modify: api/models.py (add QuarantinedEvent; Transaction.stripe_event_id unique) - Modify: api/db.py:7 (register QuarantinedEvent in metadata import) - Modify: api/main.py:322-423 (webhook + handlers) - Test: api/tests/test_webhook_quarantine.py, api/tests/test_webhook_idempotency.py

Interfaces: - Consumes: existing Member, Transaction, WebhookEvent models and the _post_webhook test helper pattern in api/tests/test_webhook.py. - Produces: QuarantinedEvent(stripe_event_id, event_type, reason, payload, quarantined_at). Webhook contract: a valid event credits once and returns 200; an un-creditable event (no member, missing/malformed metadata, unmatched subscription) is recorded in QuarantinedEvent and receipted, then returns 200 (no infinite Stripe retry); a duplicate delivery returns 200 without double-crediting (enforced by the WebhookEvent PK and the new Transaction.stripe_event_id unique constraint); a genuine transient error propagates as 500 so Stripe retries.

  • [ ] Step 1: Write the failing tests

Create api/tests/test_webhook_quarantine.py:

# api/tests/test_webhook_quarantine.py
from unittest.mock import patch

from api.models import Member, QuarantinedEvent, WebhookEvent


def _event(event_id, event_type, obj):
    return {"id": event_id, "type": event_type, "data": {"object": obj}}


def _post(client, event, secret="whsec_test"):
    with (
        patch.dict("os.environ", {"STRIPE_WEBHOOK_SECRET": secret}),
        patch("stripe.Webhook.construct_event", return_value=event),
    ):
        return client.post(
            "/webhook/stripe",
            content=b"{}",
            headers={"stripe-signature": "t=1,v1=x"},
        )


def test_checkout_for_unknown_member_is_quarantined(client, session):
    event = _event("evt_q1", "checkout.session.completed",
                   {"metadata": {"pubkey": "age1ghost", "amount": "5000"}})
    resp = _post(client, event)
    assert resp.status_code == 200
    q = session.get(QuarantinedEvent, "evt_q1")
    assert q is not None and "member" in q.reason
    # Receipted so it won't be reprocessed.
    assert session.get(WebhookEvent, "evt_q1") is not None


def test_checkout_missing_amount_is_quarantined(client, session):
    m = Member(pubkey="age1x", name="X"); session.add(m); session.commit()
    event = _event("evt_q2", "checkout.session.completed",
                   {"metadata": {"pubkey": "age1x"}})
    resp = _post(client, event)
    assert resp.status_code == 200
    assert session.get(QuarantinedEvent, "evt_q2") is not None
    session.refresh(m)
    assert m.balance == 0  # not credited


def test_checkout_noninteger_amount_is_quarantined(client, session):
    m = Member(pubkey="age1y", name="Y"); session.add(m); session.commit()
    event = _event("evt_q3", "checkout.session.completed",
                   {"metadata": {"pubkey": "age1y", "amount": "lots"}})
    resp = _post(client, event)
    assert resp.status_code == 200
    q = session.get(QuarantinedEvent, "evt_q3")
    assert q is not None and "amount" in q.reason


def test_invoice_unmatched_subscription_is_quarantined(client, session):
    event = _event("evt_q4", "invoice.paid",
                   {"subscription": "sub_missing", "billing_reason": "subscription_cycle"})
    resp = _post(client, event)
    assert resp.status_code == 200
    assert session.get(QuarantinedEvent, "evt_q4") is not None


def test_valid_checkout_still_credits(client, session):
    m = Member(pubkey="age1ok", name="OK"); session.add(m); session.commit()
    event = _event("evt_ok", "checkout.session.completed",
                   {"metadata": {"pubkey": "age1ok", "amount": "5000"}})
    resp = _post(client, event)
    assert resp.status_code == 200
    session.refresh(m)
    assert m.balance == 5000
    assert session.get(QuarantinedEvent, "evt_ok") is None

Create api/tests/test_webhook_idempotency.py:

# api/tests/test_webhook_idempotency.py
import threading
from unittest.mock import patch

from api.models import Member, Transaction


def _event(event_id, obj):
    return {"id": event_id, "type": "checkout.session.completed", "data": {"object": obj}}


def _post(client, event):
    with (
        patch.dict("os.environ", {"STRIPE_WEBHOOK_SECRET": "whsec_test"}),
        patch("stripe.Webhook.construct_event", return_value=event),
    ):
        return client.post(
            "/webhook/stripe",
            content=b"{}",
            headers={"stripe-signature": "t=1,v1=x"},
        )


def test_duplicate_delivery_credits_once(client, session):
    m = Member(pubkey="age1dup", name="Dup"); session.add(m); session.commit()
    event = _event("evt_dup", {"metadata": {"pubkey": "age1dup", "amount": "5000"}})

    first = _post(client, event)
    second = _post(client, event)

    assert first.status_code == 200
    assert second.status_code == 200
    session.refresh(m)
    assert m.balance == 5000  # credited exactly once
    txns = session.query(Transaction).filter(Transaction.stripe_event_id == "evt_dup").all() \
        if hasattr(session, "query") else None
    # SQLModel Session lacks .query; count via exec below instead.


def test_transaction_event_id_is_unique(client, session):
    from sqlmodel import select
    m = Member(pubkey="age1u", name="U"); session.add(m); session.commit()
    event = _event("evt_u", {"metadata": {"pubkey": "age1u", "amount": "1000"}})
    _post(client, event)
    _post(client, event)
    rows = session.exec(select(Transaction).where(Transaction.stripe_event_id == "evt_u")).all()
    assert len(rows) == 1

Note: delete the dangling .query lines if your editor flags them — the second test is the authoritative idempotency assertion. (Kept minimal here; the reviewer may simplify test_duplicate_delivery_credits_once to assert only m.balance == 5000.)

  • [ ] Step 2: Run the tests to verify they fail

Run: pytest api/tests/test_webhook_quarantine.py api/tests/test_webhook_idempotency.py -v Expected: FAIL — QuarantinedEvent does not exist; un-creditable events are silently dropped.

  • [ ] Step 3: Add the model and the unique constraint

In api/models.py, change the Transaction.stripe_event_id field to be unique and add QuarantinedEvent:

class WebhookEvent(SQLModel, table=True):
    stripe_event_id: str = Field(primary_key=True)
    event_type: str
    processed_at: datetime


class QuarantinedEvent(SQLModel, table=True):
    stripe_event_id: str = Field(primary_key=True)
    event_type: str
    reason: str
    payload: str
    quarantined_at: datetime


class Transaction(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    pubkey: str = Field(foreign_key="member.pubkey")
    stripe_event_id: str = Field(unique=True)
    amount: int
    transaction_type: str  # "purchase", "subscription_initial", "subscription_renewal"
    created_at: datetime = Field(default_factory=datetime.utcnow)

In api/db.py, add QuarantinedEvent to the metadata-registration import (line 7):

from .models import Member, QuarantinedEvent, Visit, WebhookEvent  # noqa: F401
  • [ ] Step 4: Rewrite the webhook and handlers

In api/main.py, add imports near the top (after the existing imports):

import json
import logging
from sqlalchemy.exc import IntegrityError

log = logging.getLogger("almanack.api")

Add QuarantinedEvent to the models import (api/main.py:15):

from .models import Member, QuarantinedEvent, Transaction, Visit, WebhookEvent

Replace the entire webhook section (api/main.py:325-423, from @app.post("/webhook/stripe") to end of file) with:

@app.post("/webhook/stripe")
async def stripe_webhook(request: Request, session: Session = Depends(get_session)):
    webhook_secret = os.environ.get("STRIPE_WEBHOOK_SECRET")
    if not webhook_secret:
        return Response(status_code=503, content="Webhook not configured")

    body = await request.body()
    sig_header = request.headers.get("stripe-signature", "")

    try:
        event = stripe.Webhook.construct_event(body, sig_header, webhook_secret)
    except (ValueError, stripe.SignatureVerificationError):
        return Response(status_code=400, content="Bad signature")

    # Fast path: already fully processed.
    if session.get(WebhookEvent, event["id"]):
        return Response(status_code=200)

    event_type = event["type"]
    try:
        reason = None
        if event_type == "checkout.session.completed":
            reason = _apply_checkout(event, session)
        elif event_type == "invoice.paid":
            reason = _apply_invoice(event, session)
        # Unhandled types: no state change, just receipt below.

        if reason:
            # Permanent bad data: retain for reconciliation, don't retry forever.
            _quarantine(event, reason, session)
            log.warning("Quarantined Stripe event %s (%s): %s",
                        event["id"], event_type, reason)

        # Receipt is written in the SAME transaction as the credit, so the two
        # can never disagree.
        _record_event(event, session)
        session.commit()
    except IntegrityError:
        # A concurrent delivery already claimed this event (WebhookEvent PK or
        # Transaction.stripe_event_id unique). It is/was processed exactly once.
        session.rollback()
        return Response(status_code=200)

    return Response(status_code=200)


def _apply_checkout(event: dict, session: Session) -> Optional[str]:
    """Credit a completed checkout. Returns a reason string if the event is
    permanently un-creditable (caller quarantines); returns None on success.
    Transient DB errors propagate so Stripe retries."""
    obj = event["data"]["object"]
    metadata = obj.get("metadata", {})
    pubkey = metadata.get("pubkey")
    amount = metadata.get("amount")

    if not pubkey or not amount:
        return "missing pubkey or amount in metadata"
    try:
        amount_int = int(amount)
    except (TypeError, ValueError):
        return f"non-integer amount: {amount!r}"

    member = session.get(Member, pubkey)
    if not member:
        return f"no member for pubkey {pubkey}"

    member.balance += amount_int
    is_recurring = metadata.get("recurring") == "monthly"
    if is_recurring:
        member.stripe_subscription_id = obj.get("subscription")
        member.recurring_almanickels = amount_int

    session.add(member)
    session.add(
        Transaction(
            pubkey=pubkey,
            stripe_event_id=event["id"],
            amount=amount_int,
            transaction_type="subscription_initial" if is_recurring else "purchase",
        )
    )
    return None


def _apply_invoice(event: dict, session: Session) -> Optional[str]:
    invoice = event["data"]["object"]
    if invoice.get("billing_reason") != "subscription_cycle":
        return None  # not a renewal we credit; receipt only

    subscription_id = invoice.get("subscription")
    if not subscription_id:
        return "invoice has no subscription id"

    stmt = select(Member).where(Member.stripe_subscription_id == subscription_id)
    member = session.exec(stmt).first()
    if not member:
        return f"no member for subscription {subscription_id}"

    member.balance += member.recurring_almanickels
    session.add(member)
    session.add(
        Transaction(
            pubkey=member.pubkey,
            stripe_event_id=event["id"],
            amount=member.recurring_almanickels,
            transaction_type="subscription_renewal",
        )
    )
    return None


def _quarantine(event: dict, reason: str, session: Session):
    session.add(
        QuarantinedEvent(
            stripe_event_id=event["id"],
            event_type=event["type"],
            reason=reason,
            payload=json.dumps(event.get("data", {}).get("object", {}))[:4000],
            quarantined_at=datetime.now(timezone.utc),
        )
    )


def _record_event(event: dict, session: Session):
    session.add(
        WebhookEvent(
            stripe_event_id=event["id"],
            event_type=event["type"],
            processed_at=datetime.now(timezone.utc),
        )
    )
  • [ ] Step 5: Run the tests to verify they pass

Run: pytest api/tests/test_webhook_quarantine.py api/tests/test_webhook_idempotency.py -v Expected: PASS.

Then confirm the existing webhook tests still pass (the credit path and sequential idempotency are unchanged in contract): Run: pytest api/tests/test_webhook.py -v Expected: PASS.

  • [ ] Step 6: Note the production index requirement

Because the API creates tables via SQLModel.metadata.create_all (no migrations), the new Transaction.stripe_event_id unique constraint applies only to freshly-created tables. For an existing production DB, add the index once (safe/idempotent):

CREATE UNIQUE INDEX IF NOT EXISTS ix_transaction_stripe_event
  ON "transaction"(stripe_event_id);

Record this in the deploy step for this change (run it against /var/local/api/members.db on each API server before deploying the new image, or reset the DB per the fresh-start decision).

  • [ ] Step 7: Commit
git add api/models.py api/db.py api/main.py \
    api/tests/test_webhook_quarantine.py api/tests/test_webhook_idempotency.py
git commit -m "api: atomic webhook, quarantine un-creditable Stripe events

The webhook acked (200) every event even when it couldn't credit it, so a
paid checkout for an unknown member vanished with no trace. Credit and
receipt now commit together; un-creditable events are recorded in
QuarantinedEvent and receipted; duplicate deliveries credit once via the
WebhookEvent PK and a new unique Transaction.stripe_event_id."

Task 9: Visit idempotency + SQLite concurrency configuration

Files: - Modify: api/models.py (unique constraint on Visit(pubkey, visited_on)) - Modify: api/db.py (WAL / busy_timeout / foreign_keys pragmas + timeout connect arg) - Modify: api/main.py:181-225 (visit idempotency) - Test: api/tests/test_visit_idempotency.py

Interfaces: - Consumes: the IntegrityError import added in Task 8. - Produces: visit debits at most once per (pubkey, visited_on) even under concurrent requests; a second same-day visit returns the current balance with debited=False. The file-DB engine runs in WAL mode with a 30 s busy timeout.

  • [ ] Step 1: Write the failing test

Create api/tests/test_visit_idempotency.py:

# api/tests/test_visit_idempotency.py
from api.tests.helpers import create_signed_member, make_signature
from api.models import Visit
from sqlmodel import select


def test_second_visit_same_day_does_not_double_debit(client, session):
    member = create_signed_member(client)

    first = client.post("/visit", json={
        "pubkey": member.pubkey,
        "timestamp": member.timestamp,
        "signature": member.signature,
    })
    assert first.status_code == 200
    assert first.json()["debited"] is True
    balance_after_first = first.json()["balance"]

    ts, sig = make_signature(member.signing_key)
    second = client.post("/visit", json={
        "pubkey": member.pubkey,
        "timestamp": ts,
        "signature": sig,
    })
    assert second.status_code == 200
    assert second.json()["debited"] is False
    assert second.json()["balance"] == balance_after_first

    rows = session.exec(select(Visit).where(Visit.pubkey == member.pubkey)).all()
    assert len(rows) == 1
  • [ ] Step 2: Run the test to verify it fails

Run: pytest api/tests/test_visit_idempotency.py -v Expected: The debited=False / single-row assertions already hold in the sequential case unless a race inserts two rows — so this test mainly guards the constraint. Run it; if it passes trivially, that is fine, but the constraint and IntegrityError handling below are what make it hold under concurrency. Proceed to add the constraint so the guarantee is structural, not incidental.

  • [ ] Step 3: Add the Visit unique constraint

In api/models.py, add the import and constraint:

from sqlmodel import Field, SQLModel, UniqueConstraint
class Visit(SQLModel, table=True):
    __table_args__ = (UniqueConstraint("pubkey", "visited_on"),)

    id: Optional[int] = Field(default=None, primary_key=True)
    pubkey: str = Field(foreign_key="member.pubkey")
    visited_on: date
    page_type: str = Field(default="article")
  • [ ] Step 4: Configure SQLite for the FastAPI thread model

Replace api/db.py lines 12-12 (the engine = ... line) with WAL/timeout configuration:

from sqlalchemy import event

engine = create_engine(DATABASE_URL, echo=False, connect_args={"timeout": 30})


# The FastAPI thread pool opens several SQLite connections. WAL lets readers
# run concurrently with the single writer; busy_timeout makes a would-be second
# writer wait rather than fail immediately. SQLite remains single-writer: the
# unique constraints (Transaction.stripe_event_id, Visit(pubkey, visited_on))
# plus IntegrityError handling are what make concurrent duplicates safe.
@event.listens_for(engine, "connect")
def _set_sqlite_pragma(dbapi_connection, _connection_record):
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA journal_mode=WAL")
    cursor.execute("PRAGMA busy_timeout=30000")
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.close()
  • [ ] Step 5: Make visit treat a duplicate as already-debited

Replace the commit tail of visit (api/main.py:222-225) so a concurrent same-day insert can’t double-debit:

    try:
        session.commit()
    except IntegrityError:
        # A concurrent request already recorded today's visit; its debit stands
        # and ours is rolled back — never debit twice for the same day.
        session.rollback()
        session.refresh(member)
        return VisitResponse(balance=member.balance, streak=member.streak, debited=False)

    session.refresh(member)
    return VisitResponse(balance=member.balance, streak=member.streak, debited=debited)
  • [ ] Step 6: Run the tests to verify they pass

Run: pytest api/tests/test_visit_idempotency.py api/tests/test_visit.py -v Expected: PASS (new test plus the existing visit tests).

Then run the whole API suite to confirm nothing regressed: Run: pytest api/tests -q Expected: all pass.

  • [ ] Step 7: Note the production index requirement

As in Task 8, add the constraint to an existing production DB once:

CREATE UNIQUE INDEX IF NOT EXISTS ix_visit_pubkey_day
  ON visit(pubkey, visited_on);
  • [ ] Step 8: Commit
git add api/models.py api/db.py api/main.py api/tests/test_visit_idempotency.py
git commit -m "api: make daily visits idempotent; configure SQLite for threads

Two concurrent visits could both see an old last_visit and debit twice. Add a
unique (pubkey, visited_on) constraint and treat its IntegrityError as an
already-debited visit. Enable WAL + busy_timeout so the API's thread pool
serialises cleanly on one writer."

Final Verification

After all nine tasks, run the full gate the way CI will:

Run: make verify Expected: every section passes, ending a-verify: all checks passed. (This exercises the container API smoke too, so it needs podman/docker locally; if absent, run make verify-fast and rely on the boat runner for the container step.)


Self-Review

Spec coverage (against critique items 4, 5, 6, 6a): - Item 4 — deterministic gate (Task 2), a-test false-greens/api/tests never run/pipefail (Task 1), deploy foreach ;-joins + index.html guard + health checks + drop LLM pre-deploy + deploy depends on gate (Tasks 3, 4), CI workflow + branch protection (Task 5). ✅ - Item 5 — a-db-sync stage/integrity/backup/swap (Task 6), prod-api-restore server-side snapshot (Task 7). ✅ - Item 6 — un-creditable checkout/invoice quarantined + logged, malformed int(amount) handled, receipt vs credit consistency (Task 8). ✅ - Item 6a — insert/receipt-in-one-transaction + IntegrityError idempotency, Transaction.stripe_event_id unique, Visit(pubkey, visited_on) unique + visit conflict handling, SQLite WAL/busy_timeout/single-writer note, concurrent/duplicate tests (Tasks 8, 9). ✅

Deliberately out of scope (not silent): the celestial/update-finances deploy-dependency untangling is critique item 16 (P1), left in the prod-deploy chain here. Re-marking test_topup_integration.py is item 15’s other half. The membership-manual corrections (items 6/27 docs) are item 28 (P3). Flag these to the human if they want them folded in.

Placeholder scan: every code step contains complete content; no TBD/”handle errors”/”similar to”. The one soft spot is the .query lines in test_webhook_idempotency.py::test_duplicate_delivery_credits_once, explicitly flagged for the implementer to simplify.

Type consistency: _apply_checkout/_apply_invoice return Optional[str]; _quarantine/_record_event add-without-commit; QuarantinedEvent fields match between model, _quarantine, and tests; A_TEST_STRICT/api-unit/verify-fast names are consistent across Tasks 1, 2, 3, 5.