diff --git a/.github/test-suite-registry.json b/.github/test-suite-registry.json index 2138e41448..44279e99c4 100644 --- a/.github/test-suite-registry.json +++ b/.github/test-suite-registry.json @@ -629,14 +629,13 @@ "id": "quota-exporters", "paths": [ "pm-stack/opencode-usage-export/opencode-usage-export.test.mjs", - "pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs", - "pm-stack/supabase-export/supabase-quota-export.test.mjs" + "pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs" ], "invocation": "Node/Bun tests; exact per-package commands not established", "venue": null, "status": "uncovered", "phase2_issue": 6084, - "reason": "Three exporter suites have no venue." + "reason": "Two exporter suites have no venue." }, { "id": "github-backup.worker", diff --git a/.github/workflows/pm-stack-tests.yml b/.github/workflows/pm-stack-tests.yml index 73d40539f6..406eb16ec4 100644 --- a/.github/workflows/pm-stack-tests.yml +++ b/.github/workflows/pm-stack-tests.yml @@ -252,16 +252,6 @@ jobs: - name: Test cloudflare-export suite run: node --test pm-stack/cloudflare-export/cloudflare-quota-export.test.mjs - # supabase-export: bun test (12 tests) - - name: Test supabase-export suite - working-directory: pm-stack/supabase-export - run: | - if [ ! -f supabase-quota-export.test.mjs ]; then - echo "::error::Missing suite file pm-stack/supabase-export/supabase-quota-export.test.mjs — the supabase suite was not run." - exit 1 - fi - bun test - # meta-exporter: node --test (suite for #6344; the explicit file # path is required — the directory form fails on Node 24). The # file is asserted to exist first, so a green run cannot be a diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index fc9144736a..c5d4a6a845 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -4492,7 +4492,7 @@ // seat is the CLAUDE bucket, same stage, equal weight 10. // 2026-11-09 (Drew, AA-match rule): the Sonnet seat drops // #high -> #medium. A pool is matched by its AA score, not - // its effort label. AA v5 (Supabase ainventory via the + // its effort label. AA v5 (ainventory via the // aggregator collector's aa-last-good, generated // 2026-11-10T00:40Z, read tonight): this pool sits at Luna // #xhigh II 23, Gemini 3.8 Flash #high II 31, and Spark diff --git a/home/openclaw/workspace/FLEET.md b/home/openclaw/workspace/FLEET.md index ce97a5ad6f..9e7333f3ab 100644 --- a/home/openclaw/workspace/FLEET.md +++ b/home/openclaw/workspace/FLEET.md @@ -26,4 +26,4 @@ Standing repo rules: merge commits only · never force-push main · **never touc - **mcpx** — Drew's MCP gateway: one daemon fronts the fleet's MCP servers (codedb, fff, chrome-devtools, context7, desktop-commander, …). This gateway also has direct MCP wiring to the most useful of those (see openclaw.json `mcp.servers`). - **Notes system** — Emanote Zettelkasten: `dezren39/zettel` + `developing-today/zettel`. Drew brain-dumps; agents explode into small interlinked notes and push. - **Basement lab cluster** (goal, in progress) — Talos + Cozystack + TALM, Postgres (CNPG), RustFS, ~12 Threadripper machines. **Hard rule: no HashiCorp tooling.** -- **Supabase `muse-dev`** — Muse's platform project (backups to R2). Not OpenClaw's concern unless asked. +- **Fleet data** — Turso is the fleet's only database platform (Supabase is retired). Not OpenClaw's concern unless asked. diff --git a/nixos/home/laptop-backups.nix b/nixos/home/laptop-backups.nix index fbcb549221..6296889cab 100644 --- a/nixos/home/laptop-backups.nix +++ b/nixos/home/laptop-backups.nix @@ -12,7 +12,8 @@ # Jobs: # - pm-dashboard-backup (daily ~04:30): the PM dashboard / orchestration # state set as a dated tar.zst with a sha256 manifest to the local -# backup dir, Cloudflare R2 (supabase-backups) and Google Drive +# backup dir, Cloudflare R2 (bucket supabase-backups, a legacy R2 +# bucket name) and Google Drive # (Cloud/cold-store/db-backups/pm-aggregator//), every copy # sha256-verified, 30-day retention. Runs the code#1514 DB-dump script # first when it exists at ~/tools/pm-stack-db-backup.sh, and its dumps @@ -46,12 +47,6 @@ # The agent state DB is snapshotted with sqlite3 .backup so the # archived copy is transaction-consistent. Script: # ./openclaw-backup.sh (vendored here; same credential pattern). -# - supabase-backup (twice daily 04:42 + 16:42): pg_dump of the muse-dev -# Supabase project to R2 (supabase-backups), content-hashed names. -# Migrated from the sandbox 2026-10-28 (developing-today/code#1723); -# the unit is declared here per Drew's all-services-in-nix rule the -# same day. Script: ~/tools/supabase-backup.sh (wrapper; the dump -# program + config live in ~/tools/supabase-backup/). # - atlas-backup (daily ~04:47): the canonical local atlas.db # (~/atlas/turso-atlas/data/atlas.db) snapshotted with sqlite3 # .backup, gzipped deterministically, and filed to the local backup @@ -141,7 +136,7 @@ let in { options.services.laptop-backups = { - enable = lib.mkEnableOption "the laptop backup jobs (dashboard, repo archive, openclaw, supabase, cold-store, atlas)"; + enable = lib.mkEnableOption "the laptop backup jobs (dashboard, repo archive, openclaw, cold-store, atlas)"; dashboard = { enable = lib.mkOption { @@ -187,27 +182,6 @@ in }; }; - supabase = { - enable = lib.mkOption { - type = lib.types.bool; - default = true; - description = "Twice-daily pg_dump backup of the muse-dev Supabase project to R2 (code#1723)."; - }; - onCalendar = lib.mkOption { - type = lib.types.listOf lib.types.str; - default = [ - "04:42" - "16:42" - ]; - description = "Daily run times (local) for the Supabase backup."; - }; - script = lib.mkOption { - type = lib.types.str; - default = "${home}/tools/supabase-backup.sh"; - description = "Path of the Supabase backup wrapper script to run."; - }; - }; - atlas = { enable = lib.mkOption { type = lib.types.bool; @@ -337,16 +311,6 @@ in }; }; }) - (lib.mkIf cfg.supabase.enable { - supabase-backup = { - Unit.Description = "Twice-daily Supabase muse-dev pg_dump backup to R2 (code#1723)"; - Service = { - Type = "oneshot"; - ExecStart = cfg.supabase.script; - TimeoutStartSec = "30m"; - }; - }; - }) (lib.mkIf cfg.atlas.enable { atlas-backup = { Unit.Description = "Daily atlas.db backup - local + R2 + Drive (code#1515)"; @@ -458,17 +422,6 @@ in Install.WantedBy = [ "timers.target" ]; }; }) - (lib.mkIf cfg.supabase.enable { - supabase-backup = { - Unit.Description = "Run the Supabase muse-dev backup twice daily"; - Timer = { - OnCalendar = cfg.supabase.onCalendar; - Persistent = true; - RandomizedDelaySec = "15m"; - }; - Install.WantedBy = [ "timers.target" ]; - }; - }) (lib.mkIf cfg.atlas.enable { atlas-backup = { Unit.Description = "Run the atlas backup daily (code#1515)"; diff --git a/nixos/home/laptop-state-backup.md b/nixos/home/laptop-state-backup.md index 8c589e6ca8..e641aeeede 100644 --- a/nixos/home/laptop-state-backup.md +++ b/nixos/home/laptop-state-backup.md @@ -27,7 +27,7 @@ recovery source found. | `pm-stack/.env` | sops | rendered by `deploy.sh` from `secrets/pm-stack.sops.yaml` | | `pm-stack/grist/.env` | sops | `secrets/pm-stack.sops.yaml` (`grist` keys); Bitwarden `grist.*` | | `pm-stack/pad/.env` | sops | `secrets/pm-stack.sops.yaml`; Bitwarden `pad.*` | -| `pm-stack/dispatch/.env` | vault + sops | `DISPATCH_API_TOKEN` from `pm-dispatch.api-token`; `SUPABASE_URL` / `SUPABASE_SERVICE_ROLE_KEY` from `supabase.muse-dev2.project-url` / `supabase.muse-dev2.service-role-key`; GitHub App key from `secrets/pm-stack.sops.yaml` | +| `pm-stack/dispatch/.env` | vault + sops | `DISPATCH_API_TOKEN` from `pm-dispatch.api-token`; GitHub App key from `secrets/pm-stack.sops.yaml` | | `secrets/dispatch.env` (+ two `.bak-*`) | vault | `pm-dispatch.api-token` (README: restore from vault before `install.sh`) | | `pm-stack/retired-2026-10-27/aggregator-deployed-copy/.env` | retired | not restored; no recovery needed (retired tree) | | `pm-stack/dispatch/` source, `compose.yml`, `deploy.sh`, `pad/`, `grist/` scripts | repo | in git (`developing-today/code`) | diff --git a/nixos/home/pm-dashboard-backup-manifest.test.sh b/nixos/home/pm-dashboard-backup-manifest.test.sh index cff26f44fc..060c95d266 100755 --- a/nixos/home/pm-dashboard-backup-manifest.test.sh +++ b/nixos/home/pm-dashboard-backup-manifest.test.sh @@ -8,7 +8,7 @@ # The script now declares the expected set once (EXPECTED_SET): # 12 aggregator state files are REQUIRED (decisions.json and # decision-events.jsonl since #10293), meta-quota-export files are -# OPTIONAL, db-dumps and the five #6815 Supabase store exports are +# OPTIONAL, db-dumps and the Turso store exports are # required when their step ran (optional when it did not). The # snapshots tree + 2 journal logs are OPTIONAL. # manifest.json records every member's status, and the verify step @@ -56,8 +56,7 @@ mkdir -p "$BIN" printf '#!%s\n' "$BASH" cat <<'STUB' if [[ "${1:-} ${2:-}" == "secret list" ]]; then - # The #6815 Supabase store export reads these two by key name only. - printf '%s\n' '[{"key":"cloudflare.r2-backups-access-key-id","value":"fake-access-key-id"},{"key":"cloudflare.r2-backups-secret-access-key","value":"fake-secret-access-key"},{"key":"cloudflare.r2-endpoint","value":"https://example.invalid"},{"key":"supabase.muse-dev2.db-password","value":"fake-db-password"},{"key":"supabase.muse-dev2.project-ref","value":"fake-project-ref"}]' + printf '%s\n' '[{"key":"cloudflare.r2-backups-access-key-id","value":"fake-access-key-id"},{"key":"cloudflare.r2-backups-secret-access-key","value":"fake-secret-access-key"},{"key":"cloudflare.r2-endpoint","value":"https://example.invalid"}]' exit 0 fi echo "stub bws: unsupported args: $*" >&2 @@ -152,7 +151,7 @@ run_backup() { RCLONE_STUB_DIR="$TMP_ROOT/$name/rclone-store" \ RCLONE_CALLS_LOG="$TMP_ROOT/$name/rclone-calls.log" \ PM_DB_DUMP_SCRIPT="$DUMP_SCRIPT_ARG" \ - PM_AGG_SUPABASE_EXPORT=off \ + PM_AGG_STORE_EXPORT=off \ "$@" \ bash "$SCRIPT" 2026-10-28 >"$TMP_ROOT/$name.log" 2>&1 RC=$? @@ -231,13 +230,10 @@ else fi assert_member missing-optional aggregator/snapshots optional missing assert_member missing-optional db-dumps optional missing -# #6815: the canonical Supabase store exports are conditionally required -# only when the export ran (backend=file in this harness, so optional). -assert_member missing-optional supabase/agg_actions.json optional missing -assert_member missing-optional supabase/agg_activity_ingestion.json optional missing -assert_member missing-optional supabase/agg_activity_gaps.json optional missing -assert_member missing-optional supabase/agg_usage_snapshots.json optional missing -assert_member missing-optional supabase/agg_store_documents.json optional missing +# The Turso store exports are conditionally required only when the +# export ran (backend=file in this harness, so optional). +assert_member missing-optional turso/agg_actions.json optional missing +assert_member missing-optional turso/orch_runs.json optional missing assert_member missing-optional aggregator/actions.json required present assert_member missing-optional meta-quota-export/latest.json optional missing assert_member missing-optional meta-quota-export/history.jsonl optional missing @@ -250,11 +246,11 @@ fi if manifest_json missing-optional | python3 -c ' import json, sys m = json.load(sys.stdin) -sys.exit(0 if len(m.get("expected", [])) == 46 else 1) +sys.exit(0 if len(m.get("expected", [])) == 41 else 1) '; then - ok "missing-optional: manifest lists all 46 expected members" + ok "missing-optional: manifest lists all 41 expected members" else - fail "missing-optional: manifest expected list is not the full 46-member set" + fail "missing-optional: manifest expected list is not the full 41-member set" fi # --- decisions ledger is required (#10293) ----------------------------------- @@ -340,144 +336,34 @@ assert_member dump-ran-with-dir db-dumps required present assert_member dump-ran-with-dir meta-quota-export/latest.json optional present assert_member dump-ran-with-dir meta-quota-export/history.jsonl optional present -# --- file backend: Supabase export not applicable -------------------------------- -# Default PM_AGG_SUPABASE_EXPORT=auto with no $AGG/.env (or a backend=file -# .env) runs no Supabase step: the five #6815 store exports stay -# conditional/optional, the run is green, and no bws keys are needed. +# --- file backend: remote store export not applicable --------------------------- +# Default PM_AGG_STORE_EXPORT=auto with no $AGG/.env (or a backend=file +# .env) runs no store export: the turso/ members stay conditional/optional +# and the run is green. setup_home file-backend -run_backup file-backend env -u PM_AGG_SUPABASE_EXPORT +run_backup file-backend env -u PM_AGG_STORE_EXPORT if [[ $RC -eq 0 ]]; then ok "file-backend: script exited 0" else fail "file-backend: expected exit 0, got $RC; log: $(cat "$TMP_ROOT/file-backend.log")" fi -assert_member file-backend supabase/agg_actions.json optional missing -if grep -q 'Supabase store export not applicable' "$TMP_ROOT/file-backend.log"; then - ok "file-backend: log names the skipped Supabase export" +assert_member file-backend turso/agg_actions.json optional missing +if grep -q 'remote store export not applicable' "$TMP_ROOT/file-backend.log"; then + ok "file-backend: log names the skipped store export" else fail "file-backend: log does not name the skipped export: $(cat "$TMP_ROOT/file-backend.log")" fi -# --- supabase backend, export off: still not applicable ------------------------- -# An explicit PM_AGG_STORE_BACKEND=supabase .env opts back in via -# PM_AGG_SUPABASE_EXPORT=off: same green run, optional members, no creds. -setup_home supabase-backend-off -printf 'PM_AGG_STORE_BACKEND=supabase\n' >"$RUN_HOME/.local/state/pm-aggregator/.env" -run_backup supabase-backend-off +# --- turso backend, export off: not applicable ---------------------------------- +setup_home turso-backend-off +printf 'PM_AGG_STORE_BACKEND=turso\n' >"$RUN_HOME/.local/state/pm-aggregator/.env" +run_backup turso-backend-off if [[ $RC -eq 0 ]]; then - ok "supabase-backend-off: script exited 0" + ok "turso-backend-off: script exited 0" else - fail "supabase-backend-off: expected exit 0, got $RC; log: $(cat "$TMP_ROOT/supabase-backend-off.log")" -fi -assert_member supabase-backend-off supabase/agg_actions.json optional missing -if grep -q 'Supabase store export not applicable' "$TMP_ROOT/supabase-backend-off.log"; then - ok "supabase-backend-off: log names the skipped Supabase export" -else - fail "supabase-backend-off: log does not name the skipped export: $(cat "$TMP_ROOT/supabase-backend-off.log")" -fi - -# --- supabase backend, psql missing: fail-closed --------------------------------- -# No silent skip: a supabase backend that cannot be exported fails the run -# before any upload, with the journal marker unchanged. -setup_home supabase-no-psql -printf 'PM_AGG_STORE_BACKEND=supabase\n' >"$RUN_HOME/.local/state/pm-aggregator/.env" -if command -v psql >/dev/null 2>&1; then - EMPTY_BIN="$TMP_ROOT/supabase-no-psql/empty-bin" - mkdir -p "$EMPTY_BIN" - # A PATH with everything this script may call EXCEPT psql: link every - # executable from the real PATH dirs, skipping psql, so the run reaches - # the export step and finds the tool genuinely missing. - while IFS= read -r dir; do - [ -d "$dir" ] || continue - for p in "$dir"/*; do - b="${p##*/}" - [ "$b" = "psql" ] && continue - [ -x "$p" ] && [ ! -e "$EMPTY_BIN/$b" ] && ln -s "$p" "$EMPTY_BIN/$b" - done - done < <(printf '%s\n' "$PATH" | tr ':' '\n') - ln -sf "$BIN/bws" "$EMPTY_BIN/bws" - PATH="$EMPTY_BIN" \ - HOME="$RUN_HOME" BWS_ACCESS_TOKEN="fake-token" \ - RCLONE_STUB_DIR="$TMP_ROOT/supabase-no-psql/rclone-store" \ - RCLONE_CALLS_LOG="$TMP_ROOT/supabase-no-psql/rclone-calls.log" \ - PM_DB_DUMP_SCRIPT="$DUMP_SCRIPT_ARG" \ - bash "$SCRIPT" 2026-10-28 >"$TMP_ROOT/supabase-no-psql.log" 2>&1 - RC=$? - MARKER_AFTER="$(cat "$RUN_HOME/backups/dashboard/.last-run-epoch" 2>/dev/null || echo missing)" - if [[ $RC -ne 0 ]] && grep -q 'psql not found' "$TMP_ROOT/supabase-no-psql.log"; then - ok "supabase-no-psql: run failed naming the missing psql" - else - fail "supabase-no-psql: expected non-zero + psql line, got rc=$RC: $(cat "$TMP_ROOT/supabase-no-psql.log")" - fi - if [[ $MARKER_AFTER == "$PRESET" ]] && no_upload supabase-no-psql; then - ok "supabase-no-psql: marker unchanged, nothing uploaded" - else - fail "supabase-no-psql: marker moved or an upload was attempted" - fi -else - ok "supabase-no-psql: psql genuinely absent; skipped (host already proves the case)" -fi - -# --- supabase backend, export on: stub psql exports five tables ----------------- -# A stub psql answers the JSON-array query for each table from fixture -# files, so the REQUIRED members are staged and the manifest records -# them present; SUPA_COUNTS names every table in the log. -setup_home supabase-export -printf 'PM_AGG_STORE_BACKEND=supabase\n' >"$RUN_HOME/.local/state/pm-aggregator/.env" -# The stub dir only SHADOWS psql; everything else resolves from the real PATH. -EXPORT_BIN="$TMP_ROOT/supabase-export/bin-stub" -mkdir -p "$EXPORT_BIN/supabase-fixtures" -ln -sf "$BIN/bws" "$EXPORT_BIN/bws" -ln -sf "$BIN/rclone" "$EXPORT_BIN/rclone" -printf '[{"id":"act-1"}]' >"$EXPORT_BIN/supabase-fixtures/agg_actions" -printf '[{"source":"cron"}]' >"$EXPORT_BIN/supabase-fixtures/agg_activity_ingestion" -printf '[]' >"$EXPORT_BIN/supabase-fixtures/agg_activity_gaps" -printf '[{"snapshot_key":"k"}]' >"$EXPORT_BIN/supabase-fixtures/agg_usage_snapshots" -printf '[{"store":"aa-last-good"}]' >"$EXPORT_BIN/supabase-fixtures/agg_store_documents" -cat >"$EXPORT_BIN/psql" <<'STUBEOF' -#!/usr/bin/env bash -# Stub psql: implement only the export call shape (args include -c). -# The table name is the last public. mention in the -c argument. -args="$*" -table="$(printf '%s' "$args" | grep -o 'public\.[a-z_]*' | tail -1 | sed 's/^public\.//')" -if [[ -n "$table" && -f "${PSQL_FIXTURES:?}/$table" ]]; then - cat "$PSQL_FIXTURES/$table" - echo - exit 0 -fi -echo "stub psql: unsupported invocation: $args" >&2 -exit 1 -STUBEOF -chmod +x "$EXPORT_BIN/psql" -PATH="$EXPORT_BIN:$PATH" \ - HOME="$RUN_HOME" BWS_ACCESS_TOKEN="fake-token" \ - RCLONE_STUB_DIR="$TMP_ROOT/supabase-export/rclone-store" \ - RCLONE_CALLS_LOG="$TMP_ROOT/supabase-export/rclone-calls.log" \ - PM_DB_DUMP_SCRIPT="$DUMP_SCRIPT_ARG" \ - PSQL_FIXTURES="$EXPORT_BIN/supabase-fixtures" \ - bash "$SCRIPT" 2026-10-28 >"$TMP_ROOT/supabase-export.log" 2>&1 -RC=$? -MARKER_AFTER="$(cat "$RUN_HOME/backups/dashboard/.last-run-epoch" 2>/dev/null || echo missing)" -if [[ $RC -eq 0 ]]; then - ok "supabase-export: script exited 0" -else - fail "supabase-export: expected exit 0, got $RC; log: $(cat "$TMP_ROOT/supabase-export.log")" -fi -assert_member supabase-export supabase/agg_actions.json required present -assert_member supabase-export supabase/agg_store_documents.json required present -D_SUPA="$TMP_ROOT/supabase-export-extract" -mkdir -p "$D_SUPA" -tar -I zstd -xf "$RUN_HOME/backups/dashboard/2026-10-28/dashboard-2026-10-28.tar.zst" -C "$D_SUPA" 2>/dev/null -if [[ "$(cat "$D_SUPA/supabase/agg_actions.json" 2>/dev/null)" == '[{"id":"act-1"}]' ]]; then - ok "supabase-export: staged agg_actions.json carries the exported rows" -else - fail "supabase-export: staged agg_actions.json wrong: $(cat "$D_SUPA/supabase/agg_actions.json" 2>/dev/null || echo missing)" -fi -if grep -q 'canonical aggregator stores exported from Supabase: .*agg_actions=1.*agg_activity_gaps=0' "$TMP_ROOT/supabase-export.log"; then - ok "supabase-export: log names the exported per-table counts" -else - fail "supabase-export: log lacks the per-table counts: $(cat "$TMP_ROOT/supabase-export.log")" + fail "turso-backend-off: expected exit 0, got $RC; log: $(cat "$TMP_ROOT/turso-backend-off.log")" fi +assert_member turso-backend-off turso/agg_actions.json optional missing # --- Turso exporter stages every required table, no credentials in fixtures --- setup_home turso-export diff --git a/nixos/home/pm-dashboard-backup.sh b/nixos/home/pm-dashboard-backup.sh index 4b77f41d51..67b3203822 100755 --- a/nixos/home/pm-dashboard-backup.sh +++ b/nixos/home/pm-dashboard-backup.sh @@ -6,7 +6,7 @@ # script's archive build, unchanged: a dated tar.zst with a sha256 manifest # in ~/backups/dashboard//, verified against its own manifest, 30-day # retention. The offsite legs copy the same archive to Cloudflare R2 -# (supabase-backups bucket, dashboard//) and to Google Drive +# (bucket supabase-backups, a legacy R2 bucket name, dashboard//) and to Google Drive # (Cloud/cold-store/db-backups/pm-aggregator//), each verified by # sha256 against the local archive, with the same 30-day retention. # @@ -37,14 +37,9 @@ # while the rest of projector.db (a rebuildable projection) is never # archived. # -# The archive also carries the canonical copy of the four aggregator -# stores that #6815 moved to Supabase muse-dev2 (actions, activity -# ingestion, usage snapshots, aa-last-good). When the deployed backend -# is supabase the local files are only a rebuildable cache, so the -# archive exports the five tables as JSON (supabase/agg_*.json) and -# records them as conditionally-required manifest members — required -# whenever the export ran. This is the RPO path recorded on code#6815 -# for #1514: without it a restore would have no store to restore from. +# The archive also carries a JSON export of the canonical aggregator +# stores (Turso is the store) as conditionally-required manifest members: +# required whenever the export ran. # # Credentials come from Bitwarden Secrets Manager at runtime, referenced # by key name only and never logged (the repo-archive-backup pattern): @@ -343,9 +338,9 @@ mkdir -p "$STAGE/aggregator" "$STAGE/meta-quota-export" "$STAGE/journals" "$OUTD # are required (their WARN-for-missing becomes a failed run at verify); # retired meta-quota-export files, the snapshots tree and active journal # logs are optional; journals keep their tolerated-unavailable -# placeholder, but are now recorded; db-dumps and the supabase/ table +# placeholder, but are now recorded; db-dumps and the turso/ table # exports are CONDITIONALLY required — required when their step ran -# (DUMP_RAN=1 / SUPA_RAN=1), optional otherwise. +# (DUMP_RAN=1 / TURSO_RAN=1), optional otherwise. EXPECTED_SET="required file aggregator/actions.json required file aggregator/comments.json required file aggregator/fleet-feed.json @@ -372,11 +367,6 @@ optional file aggregator/prefix-program.json optional tree aggregator/digests optional file meta-quota-export/latest.json optional file meta-quota-export/history.jsonl -conditional file supabase/agg_actions.json -conditional file supabase/agg_activity_ingestion.json -conditional file supabase/agg_activity_gaps.json -conditional file supabase/agg_usage_snapshots.json -conditional file supabase/agg_store_documents.json conditional file turso/agg_actions.json conditional file turso/agg_activity_ingestion.json conditional file turso/agg_activity_gaps.json @@ -603,81 +593,26 @@ else log "no projector DB at $PMP_DB — pmp_links export not applicable" fi -# --- canonical remote stores (#6815, the #1514 RPO path) ----------------- -# While the deployed backend is PM_AGG_STORE_BACKEND=file the four stores -# live in $AGG as files and the copies above are the backup. Once it is -# supabase they are canonical in muse-dev2 and a restore can only come -# from an export of those tables — the local files may be absent (fresh -# state dir) or stale. Read the backend from the aggregator .env the unit -# actually loads (LAST assignment wins, same rule as the pmp_links -# DATABASE_URL read) and export the five tables as JSON when it is -# supabase. PM_AGG_SUPABASE_EXPORT=off opts out (tests, deliberate -# file-only hosts); the default is auto. -# -# Transport is psql through the project's pooler host: the direct -# db..supabase.co hostname is IPv6-only on this network, the pooler -# is dual-stack. User/host/port are muse-dev2 facts, overridable for a -# relocated project; the password and project ref come from Bitwarden by -# key name only and are never logged. -SUPA_RAN=0 +# --- canonical remote stores (Turso is the store) ----------------------- +# While the deployed backend is PM_AGG_STORE_BACKEND=file the stores live +# in $AGG as files and the copies above are the backup. When it is turso +# they are canonical there, so export the tables as JSON. Read the backend +# from the aggregator .env the unit actually loads (LAST assignment wins, +# same rule as the pmp_links DATABASE_URL read). PM_AGG_STORE_EXPORT=off +# opts out (tests, deliberate file-only hosts); the default is auto. TURSO_RAN=0 -SUPA_MODE="${PM_AGG_SUPABASE_EXPORT:-auto}" -case "$SUPA_MODE" in +STORE_EXPORT_MODE="${PM_AGG_STORE_EXPORT:-auto}" +case "$STORE_EXPORT_MODE" in auto | off) ;; -*) fail "PM_AGG_SUPABASE_EXPORT must be auto or off, got '$SUPA_MODE'" ;; +*) fail "PM_AGG_STORE_EXPORT must be auto or off, got '$STORE_EXPORT_MODE'" ;; esac -SUPA_BACKEND="${PM_AGG_STORE_BACKEND:-}" -if [ -z "$SUPA_BACKEND" ] && [ -f "$AGG/.env" ]; then - SUPA_BACKEND="$(grep -E '^[[:space:]]*(export[[:space:]]+)?PM_AGG_STORE_BACKEND[[:space:]]*=' "$AGG/.env" 2>/dev/null | +STORE_BACKEND="${PM_AGG_STORE_BACKEND:-}" +if [ -z "$STORE_BACKEND" ] && [ -f "$AGG/.env" ]; then + STORE_BACKEND="$(grep -E '^[[:space:]]*(export[[:space:]]+)?PM_AGG_STORE_BACKEND[[:space:]]*=' "$AGG/.env" 2>/dev/null | tail -n 1 | sed -E 's/^[[:space:]]*(export[[:space:]]+)?PM_AGG_STORE_BACKEND[[:space:]]*=[[:space:]]*//')" - SUPA_BACKEND="$(pmp_trim_value "$SUPA_BACKEND")" + STORE_BACKEND="$(pmp_trim_value "$STORE_BACKEND")" fi -if [ "$SUPA_MODE" = "auto" ] && [ "$SUPA_BACKEND" = "supabase" ]; then - command -v psql >/dev/null 2>&1 || - fail "psql not found — cannot export the canonical aggregator stores from Supabase" - SUPA_HOST="${PM_AGG_SUPABASE_POOLER_HOST:-aws-0-us-east-2.pooler.supabase.com}" - SUPA_PORT="${PM_AGG_SUPABASE_POOLER_PORT:-6543}" - SUPA_PASSWORD="$(bws_get supabase.muse-dev2.db-password)" - SUPA_REF="$(bws_get supabase.muse-dev2.project-ref)" - [ -n "$SUPA_PASSWORD" ] && [ -n "$SUPA_REF" ] || - fail "Supabase credentials incomplete in Bitwarden (supabase.muse-dev2.db-password / .project-ref)" - mkdir -p "$STAGE/supabase" - # Ordered so a restore can replay rows in FK-safe order; agg_actions has - # a self-FK (supersedes/duplicate_of), so it is ordered by creation. - supa_export() { #
- PGSSLMODE=require PGPASSWORD="$SUPA_PASSWORD" \ - psql -X -q -h "$SUPA_HOST" -p "$SUPA_PORT" -U "postgres.$SUPA_REF" -d postgres \ - -v ON_ERROR_STOP=1 -tA \ - -c "select coalesce(jsonb_agg(t), '[]'::jsonb)::text from (select * from public.$1 order by $2) t" \ - >"$STAGE/supabase/$1.json" || - fail "Supabase export failed: $1" - } - supa_export agg_actions "created_at, id" - supa_export agg_activity_ingestion "source" - supa_export agg_activity_gaps "id" - supa_export agg_usage_snapshots "snapshot_key" - supa_export agg_store_documents "store" - # An export that wrote something psql did not print as a JSON array is - # a failed export, not a backup of zero rows. - SUPA_COUNTS="$( - python3 - "$STAGE/supabase" <<'PYEOF' -import json, os, sys -d = sys.argv[1] -out = [] -for name in sorted(os.listdir(d)): - if not name.endswith(".json"): - continue - with open(os.path.join(d, name)) as fh: - rows = json.load(fh) - if not isinstance(rows, list): - sys.exit(f"{name}: not a JSON array") - out.append(f"{name[:-5]}={len(rows)}") -print(" ".join(out)) -PYEOF - )" || fail "Supabase export produced unreadable JSON" - SUPA_RAN=1 - log "canonical aggregator stores exported from Supabase: $SUPA_COUNTS" -elif [ "$SUPA_MODE" = "auto" ] && [ "$SUPA_BACKEND" = "turso" ]; then +if [ "$STORE_EXPORT_MODE" = "auto" ] && [ "$STORE_BACKEND" = "turso" ]; then TURSO_EXPORT_BIN="${PM_AGG_TURSO_EXPORT_BIN:-pm-aggregator-export-turso-stores}" command -v "$TURSO_EXPORT_BIN" >/dev/null 2>&1 || fail "Turso exporter not found" "$TURSO_EXPORT_BIN" --output-dir "$STAGE/turso" || fail "Turso canonical store export failed" @@ -693,7 +628,7 @@ PYEOF TURSO_RAN=1 log "canonical aggregator stores exported from Turso" else - log "aggregator store backend is '${SUPA_BACKEND:-file}' — Supabase store export not applicable" + log "aggregator store backend is '${STORE_BACKEND:-file}' — remote store export not applicable" fi # --- journals: window start = min(last successful run, 24h ago) --- @@ -713,7 +648,7 @@ done # --- manifest (files as staged + the expected set's per-member status) --- AGG_DIR="$AGG" AGG_DERIVED="$AGG_DERIVED" \ EXPECTED_SET="$EXPECTED_SET" DUMP_RAN="$DUMP_RAN" PMP_RAN="$PMP_RAN" \ - SUPA_RAN="$SUPA_RAN" TURSO_RAN="$TURSO_RAN" \ + TURSO_RAN="$TURSO_RAN" \ python3 - "$STAGE" "$DATE" "$CREATED_AT" <<'PYEOF' import hashlib, json, os, sys stage, date, created = sys.argv[1], sys.argv[2], sys.argv[3] @@ -740,9 +675,7 @@ for line in os.environ.get("EXPECTED_SET", "").splitlines(): continue cls, kind, rel = parts if cls == "conditional": - if rel.startswith("supabase/"): - ran = os.environ.get("SUPA_RAN") - elif rel.startswith("turso/"): + if rel.startswith("turso/"): ran = os.environ.get("TURSO_RAN") elif rel.startswith("projector/"): ran = os.environ.get("PMP_RAN") diff --git a/nixos/home/supabase-turso-coord-mirror.nix b/nixos/home/supabase-turso-coord-mirror.nix deleted file mode 100644 index f82dd2bf4c..0000000000 --- a/nixos/home/supabase-turso-coord-mirror.nix +++ /dev/null @@ -1,76 +0,0 @@ -# supabase-turso-coord-mirror — the daily Supabase -> Turso coord -# mirror (developing-today/code#1723, item 3 remainder). -# -# Home-manager module: imported by the amd host config -# (nixos/hosts/default.nix) with -# services.supabase-turso-coord-mirror.enable = true. -# -# The mirror tooling moved to the laptop with the Tier-2 execution -# migration (code#1723) but was never scheduled: no timer and no -# cron ran it, and its state.json watermark sat at 2026-10-28 while -# the duty silently did not happen. Declared here per Drew's rule -# that all laptop services are made by the code flake (code#1723), -# following the cold-store / supabase-backup pattern in -# laptop-backups.nix: the script stays at -# ~/tools/supabase-mirror/sync_agent_to_turso.py, the path its -# author maintains, and credentials come from Bitwarden by name at -# runtime (the script's own bws fetches), never from the store. -{ - config, - lib, - pkgs, - ... -}: -let - cfg = config.services.supabase-turso-coord-mirror; - home = config.home.homeDirectory; - servicePath = lib.makeBinPath [ - pkgs.coreutils - pkgs.curl - pkgs.python3 - pkgs.systemd - ]; -in -{ - options.services.supabase-turso-coord-mirror = { - enable = lib.mkEnableOption "the daily Supabase -> Turso coord mirror (code#1723)"; - - onCalendar = lib.mkOption { - type = lib.types.str; - default = "04:24"; - description = "Daily run time (local) for the coord mirror."; - }; - - script = lib.mkOption { - type = lib.types.str; - default = "${home}/tools/supabase-mirror/sync_agent_to_turso.py"; - description = "Path of the coord-mirror sync script to run."; - }; - }; - - config = lib.mkIf cfg.enable { - systemd.user.services.supabase-turso-coord-mirror = { - Unit = { - Description = "Supabase -> Turso coord mirror (daily sync_agent_to_turso) (code#1723)"; - After = [ "network-online.target" ]; - }; - Service = { - Type = "oneshot"; - ExecStart = cfg.script; - TimeoutStartSec = "30m"; - Environment = "PATH=${servicePath}:${home}/tools/bin:/run/current-system/sw/bin"; - }; - }; - - systemd.user.timers.supabase-turso-coord-mirror = { - Unit.Description = "Run the Supabase -> Turso coord mirror daily (code#1723)"; - Timer = { - OnCalendar = cfg.onCalendar; - Persistent = true; - RandomizedDelaySec = "15m"; - Unit = "supabase-turso-coord-mirror.service"; - }; - Install.WantedBy = [ "timers.target" ]; - }; - }; -} diff --git a/nixos/hosts/default.nix b/nixos/hosts/default.nix index d2eefbd8d1..81dee8bbd3 100644 --- a/nixos/hosts/default.nix +++ b/nixos/hosts/default.nix @@ -147,8 +147,6 @@ in home-manager.users.user = { imports = [ ../home/laptop-backups.nix ]; services.laptop-backups.enable = true; - # muse-dev2 deleted; preserve existing dumps, retire failed source backup. - services.laptop-backups.supabase.enable = false; }; } { @@ -224,21 +222,6 @@ in services.cloudflare-quota-export.enable = true; }; } - { - # Supabase -> Turso coord mirror (code#1723): the daily - # sync_agent_to_turso duty that moved to the laptop with - # the Tier-2 migration but was never scheduled (its - # watermark sat at 2026-10-28). Declared in this flake - # (nixos/home/supabase-turso-coord-mirror.nix) per Drew's - # all-laptop-services-in-nix rule. The identical hand - # units were installed 2026-11-11 ahead of the switch so - # the schedule was live; the switch replaces them with - # the store units below. - home-manager.users.user = { - imports = [ ../home/supabase-turso-coord-mirror.nix ]; - services.supabase-turso-coord-mirror.enable = false; # source retired 2026-11-18 - }; - } { # Dashboard backup, laptop leg (code#1459) — the older # ~/tools job, distinct from pm-dashboard-backup above. diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 9179c1b36e..721b26bf7b 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -43,8 +43,8 @@ # ~/pm-stack/dispatch/.env (rendered by pm-stack/dispatch/install.sh # from the same SOPS file — it carries the GitHub App material and the # queue broker URL; the queue itself is the Turso-backed fleet queue -# broker, reached with the token in ~/.config/queue-broker/token, so no -# Supabase config is read anymore, #9028) and ~/secrets/dispatch.env +# broker, reached with the token in ~/.config/queue-broker/token) and +# ~/secrets/dispatch.env # (operator-only secrets that are not in SOPS: DISPATCH_API_TOKEN). install.sh remains the env # renderer and the fallback installer; this module owns the unit # lifecycle. @@ -353,8 +353,7 @@ in # unit's semantics — a missing operator file degrades the # service instead of crash-looping it. systemd applies the # files in order, so the operator file wins on a collision. - # Leftover SUPABASE_* lines in either file are ignored since - # #9028 (install.sh warns about them). The build version in + # The build version in # /health comes from the package wrapper, not these files. EnvironmentFile = [ "${stackDir}/dispatch/.env" diff --git a/pkgs/agent-backup/README.md b/pkgs/agent-backup/README.md index 7fda98bb85..1c5dcc1127 100644 --- a/pkgs/agent-backup/README.md +++ b/pkgs/agent-backup/README.md @@ -7,14 +7,8 @@ Drew 2026-10-28. Runs as an agent cron job `runtime-db-export` every 6 hours runtime DB (per-exec mount namespaces hide the socket); the only source route is the `muse.db` tool inside an agent run. -**Repointed 2026-11-06** (code#5691): the landing side moved from muse-dev2 -Supabase (`agent.mirror_*`) to the dedicated Turso DB `muse-mirror` -(`agent_mirror_*`), whose initial contents are the migration copy of the PG -tables (219,105 rows, parity-verified). The job was paused for the migration -and is **safe to unpause** — see the status banner at the top of JOB-BODY.md -for the first-run checks. Nothing in this directory writes to Postgres -anymore; `load_rows_pg.py` / `run_sql_pg.py` are the retired PG versions, -kept for reference/rollback only. +Turso is the store: everything here lands in the Turso DB `muse-mirror` +(`agent_mirror_*`). ## Files @@ -41,8 +35,6 @@ kept for reference/rollback only. `agent_mirror_export_state`. - `spec_m1..m8.json`, `spec_r1.json`, `spec_r2.json`, `spec_s5.json` — loader specs for the saved-output flow. -- `schema.sql`, `schema2.sql` — the original PG DDL for all landing tables - (historical; the live SQLite DDL lives in `turso_client.py`). - `state.json` — per-unit watermarks/status (mirrored in muse-mirror). - `progress/` — backfill logs per unit (build record). - `merge_s5.py` — S5 merge helper from the build (superseded by the JOB-BODY diff --git a/pkgs/agent-backup/load_rows.py b/pkgs/agent-backup/load_rows.py index d11d3121df..6736e56eb4 100644 --- a/pkgs/agent-backup/load_rows.py +++ b/pkgs/agent-backup/load_rows.py @@ -1,9 +1,7 @@ #!/usr/bin/env python3 """Generic loader: read a JSON spec from stdin, build upsert SQL, and run -it against the Turso DB `fleet-mirror` (repointed 2026-11-06 from -muse-dev2 Supabase; the PG version is kept alongside as load_rows_pg.py -for reference/rollback, and run_sql_pg.py / schema.sql document the old -landing side). Used by the runtime-db-export job for every unit. +it against the Turso DB `fleet-mirror` (Turso is the store). Used by +the runtime-db-export job for every unit. Spec (JSON on stdin) — unchanged from the PG loader: { diff --git a/pkgs/agent-backup/load_rows_pg.py b/pkgs/agent-backup/load_rows_pg.py deleted file mode 100644 index 736b12dea6..0000000000 --- a/pkgs/agent-backup/load_rows_pg.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python3 -"""Generic loader: read a JSON spec from stdin, build upsert SQL, and run it -against muse-dev Supabase via ~/tools/supabase-exec.py (proxy env loaded the -recorder way when absent). Used by the runtime-db-export job for every unit. - -Spec (JSON on stdin): -{ - "table": "agent.mirror_scheduler_jobs", // landing table - "conflict": ["job_id"], // PK columns - "jsonb_cols": ["payload"], // columns cast to jsonb - "hash_payload": true, // add payload_hash=md5(payload::text) + exported_at - "history_table": "agent.mirror_history_scheduler_jobs" | null, - "mode": "update" | "nothing", // ON CONFLICT behavior (default "update") - "epoch_day": {"day_epoch": "day"}, // optional: rename col, emit (to_timestamp(v*86400) AT TIME ZONE 'UTC')::date - "epoch_hour": {"hour_epoch": "hour"}, // optional: rename col, emit to_timestamp(v*3600) - "rows": [ {col: value, ...}, ... ] // muse.db result rows, uniform columns -} - -With history_table set (mutable mirrors only): before the upsert, the OLD -mirror version of every row whose payload_hash differs is appended to the -history table with valid_from = the old row's exported_at, valid_to = now(). -Unchanged rows are not touched (the upsert carries a hash-difference WHERE). - -Exit 0 on success (prints "loaded N rows into
"), 1 on failure -(prints the error tail to stderr). A failed call changes nothing else. -""" - -import hashlib -import json -import os -import subprocess -import sys -import tempfile - -SUPABASE_EXEC = os.path.expanduser("~/tools/supabase-exec.py") -PROXY_ENV_FILE = os.path.expanduser("~/tools/secrets.d/mcpx-daemon.env") -PROXY_KEYS = ( - "HTTPS_PROXY", - "https_proxy", - "HTTP_PROXY", - "http_proxy", - "ALL_PROXY", - "all_proxy", - "NO_PROXY", - "no_proxy", -) - - -def flush_env(): - env = dict(os.environ) - if not (env.get("HTTPS_PROXY") or env.get("https_proxy")): - try: - with open(PROXY_ENV_FILE) as f: - for line in f: - k, sep, v = line.strip().partition("=") - if sep and k in PROXY_KEYS and k not in env: - env[k] = v.strip().strip('"').strip("'") - except OSError: - pass - return env - - -def lit(v): - if v is None: - return "NULL" - if isinstance(v, bool): - return "true" if v else "false" - if isinstance(v, (int, float)): - return repr(v) - return "'" + str(v).replace("'", "''") + "'" - - -def run_sql(sql): - fd, fname = tempfile.mkstemp(suffix=".sql", prefix="mirror-load-") - try: - with os.fdopen(fd, "w") as f: - f.write(sql) - p = subprocess.run( - [sys.executable, SUPABASE_EXEC, fname], - capture_output=True, - text=True, - timeout=300, - env=flush_env(), - ) - if p.returncode != 0: - tail = (p.stderr or "").strip().splitlines() - head = (p.stdout or "").strip().splitlines() - err = tail[-1] if tail else (head[-1] if head else "unknown failure") - raise SystemExit(f"supabase-exec exit {p.returncode}: {err}"[:400]) - finally: - try: - os.unlink(fname) - except OSError: - pass - - -def main(): - spec = json.load(sys.stdin) - rows = [ - {k: v for k, v in r.items() if not k.startswith("_")} - for r in (spec.get("rows") or []) - ] - table = spec["table"] - if not rows: - print(f"loaded 0 rows into {table} (empty page)") - return - conflict = spec.get("conflict", "update") - jsonb_cols = set(spec.get("jsonb_cols") or []) - hash_payload = bool(spec.get("hash_payload")) - mode = spec.get("mode", "update") - epoch_maps = {} - for spec_key, mult in (("epoch_day", 86400), ("epoch_hour", 3600)): - m = spec.get(spec_key) - if m: - for src, dst in m.items(): - epoch_maps[src] = (dst, mult) - cols = [] - for c in rows[0].keys(): - cols.append(epoch_maps[c][0] if c in epoch_maps else c) - - def tuple_sql(r): - parts = [] - for c in rows[0].keys(): - v = r[c] - if c in epoch_maps: - if epoch_maps[c][1] == 86400: - # pin to UTC: the Supabase session TZ otherwise shifts - # the date one day early (found in the 2026-10-29 build) - parts.append( - f"(to_timestamp({int(v)} * 86400) AT TIME ZONE 'UTC')::date" - ) - else: - parts.append(f"to_timestamp({int(v)} * {epoch_maps[c][1]})") - elif c in jsonb_cols: - parts.append(lit(json.dumps(v)) + "::jsonb") - else: - parts.append(lit(v)) - return "(" + ", ".join(parts) + ")" - - values = ",\n".join(tuple_sql(r) for r in rows) - col_list = ", ".join(cols) - hist = spec.get("history_table") - - if hist: - if not hash_payload: - raise SystemExit("history_table requires hash_payload") - join = " AND ".join(f"m.{k} = i.{k}" for k in conflict) - hist_sql = f""" -WITH incoming AS (SELECT * FROM (VALUES -{values} -) AS v({col_list})) -INSERT INTO {hist} ({", ".join(conflict)}, payload, payload_hash, valid_from, valid_to) -SELECT {", ".join("m." + k for k in conflict)}, m.payload, m.payload_hash, m.exported_at, now() -FROM {table} m JOIN incoming i ON {join} -WHERE m.payload_hash <> md5(i.payload::text); -""" - run_sql(hist_sql) - - extra_cols = "" - select_cols = col_list - if hash_payload: - extra_cols = ", payload_hash, exported_at" - select_cols = col_list + ", md5(payload::text), now()" - elif spec.get("no_exported_at"): - extra_cols = "" - select_cols = col_list - elif "exported_at" not in cols: - extra_cols = ", exported_at" - select_cols = col_list + ", now()" - - if hist: - upsert_sql = f""" -WITH incoming AS (SELECT * FROM (VALUES -{values} -) AS v({col_list})) -INSERT INTO {table} ({col_list}{extra_cols}) -SELECT {select_cols} FROM incoming -ON CONFLICT ({", ".join(conflict)}) DO UPDATE SET - {", ".join(f"{c} = EXCLUDED.{c}" for c in cols if c not in conflict)}, - payload_hash = EXCLUDED.payload_hash, exported_at = now() -WHERE {table}.payload_hash <> EXCLUDED.payload_hash; -""" - elif mode == "nothing": - upsert_sql = f""" -INSERT INTO {table} ({col_list}{extra_cols}) -VALUES -{values} -ON CONFLICT ({", ".join(conflict)}) DO NOTHING; -""" - if extra_cols: - # rebuild values with the extra columns appended per-tuple - tup = [] - for r in rows: - base = tuple_sql(r)[:-1] # strip ')' - if hash_payload: - pj = json.dumps(r.get("payload")) - h = hashlib.md5(pj.encode()).hexdigest() - tup.append(base + f", '{h}', now())") - else: - tup.append(base + ", now())") - upsert_sql = f""" -INSERT INTO {table} ({col_list}{extra_cols}) -VALUES -{", ".join(tup)} -ON CONFLICT ({", ".join(conflict)}) DO NOTHING; -""" - else: - set_cols = [c for c in cols if c not in conflict] - assignments = ", ".join(f"{c} = EXCLUDED.{c}" for c in set_cols) - if hash_payload: - assignments += ", payload_hash = EXCLUDED.payload_hash" - if not spec.get("no_exported_at"): - assignments += ", exported_at = now()" - tup = [] - for r in rows: - base = tuple_sql(r)[:-1] - if hash_payload: - pj = json.dumps(r.get("payload")) - h = hashlib.md5(pj.encode()).hexdigest() - tup.append(base + f", '{h}', now())") - elif spec.get("no_exported_at"): - tup.append(base + ")") - else: - tup.append(base + ", now())") - upsert_sql = f""" -INSERT INTO {table} ({col_list}{extra_cols}) -VALUES -{", ".join(tup)} -ON CONFLICT ({", ".join(conflict)}) DO UPDATE SET {assignments}; -""" - run_sql(upsert_sql) - print(f"loaded {len(rows)} rows into {table}") - - -if __name__ == "__main__": - main() diff --git a/pkgs/agent-backup/run_sql.py b/pkgs/agent-backup/run_sql.py index 425d5437d4..09dc2567df 100755 --- a/pkgs/agent-backup/run_sql.py +++ b/pkgs/agent-backup/run_sql.py @@ -1,6 +1,5 @@ #!/usr/bin/env python3 -"""Run a SQL file against the Turso DB `fleet-mirror` (repointed -2026-11-06 from muse-dev2 Supabase; PG version kept as run_sql_pg.py). +"""Run a SQL file against the Turso DB `fleet-mirror` (Turso is the store). Usage: run_sql.py The job's SQL files are written in the old PG dialect; this runner diff --git a/pkgs/agent-backup/run_sql_pg.py b/pkgs/agent-backup/run_sql_pg.py deleted file mode 100755 index 1843f39dd5..0000000000 --- a/pkgs/agent-backup/run_sql_pg.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 -"""Run a SQL file against muse-dev Supabase via ~/tools/supabase-exec.py, -loading the egress proxy from ~/tools/secrets.d/mcpx-daemon.env into the -subprocess env when the caller has none (recorder/fleet-feed pattern). -Usage: run_sql.py (exit code = supabase-exec exit code) -""" - -import os -import subprocess -import sys - -SUPABASE_EXEC = os.path.expanduser("~/tools/supabase-exec.py") -PROXY_ENV_FILE = os.path.expanduser("~/tools/secrets.d/mcpx-daemon.env") -PROXY_KEYS = ( - "HTTPS_PROXY", - "https_proxy", - "HTTP_PROXY", - "http_proxy", - "ALL_PROXY", - "all_proxy", - "NO_PROXY", - "no_proxy", -) - - -def flush_env(): - env = dict(os.environ) - if not (env.get("HTTPS_PROXY") or env.get("https_proxy")): - try: - with open(PROXY_ENV_FILE) as f: - for line in f: - k, sep, v = line.strip().partition("=") - if sep and k in PROXY_KEYS and k not in env: - env[k] = v.strip().strip('"').strip("'") - except OSError: - pass - return env - - -def main(): - if len(sys.argv) < 2: - raise SystemExit(__doc__) - p = subprocess.run( - [sys.executable, SUPABASE_EXEC, sys.argv[1]], env=flush_env(), timeout=300 - ) - sys.exit(p.returncode) - - -if __name__ == "__main__": - main() diff --git a/pkgs/agent-backup/schema.sql b/pkgs/agent-backup/schema.sql deleted file mode 100644 index 5adde0bf58..0000000000 --- a/pkgs/agent-backup/schema.sql +++ /dev/null @@ -1,152 +0,0 @@ --- runtime-db-export landing tables (muse-dev Supabase, agent schema). --- Created 2026-10-28. Mirrors of the Muse runtime records DB, exported --- through the muse.db window by the runtime-db-export cron job. --- payload_hash = md5(payload::text) computed in SQL on write. - -CREATE TABLE IF NOT EXISTS agent.mirror_export_state ( - table_name text PRIMARY KEY, - watermark text, - last_run_at timestamptz, - last_row_count bigint, - last_status text, - last_error text -); - --- scheduler.jobs (snapshot + history) -CREATE TABLE IF NOT EXISTS agent.mirror_scheduler_jobs ( - job_id text PRIMARY KEY, - is_heartbeat boolean, source_path text, schedule_kind text, enabled boolean, - schedule_expr text, timezone text, last_status text, - consecutive_failures bigint, next_run_at_utc bigint, - last_run_at_utc bigint, last_success_at_utc bigint, - payload jsonb NOT NULL, payload_hash text NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE TABLE IF NOT EXISTS agent.mirror_history_scheduler_jobs ( - job_id text NOT NULL, - payload jsonb NOT NULL, payload_hash text NOT NULL, - valid_from timestamptz, valid_to timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX IF NOT EXISTS mirror_history_scheduler_jobs_key_idx - ON agent.mirror_history_scheduler_jobs (job_id, valid_to); - --- scheduler.job_runs (incremental; mutable status, no history per design) -CREATE TABLE IF NOT EXISTS agent.mirror_scheduler_job_runs ( - run_id text PRIMARY KEY, - job_id text, job_definition_id bigint, - scheduled_for_utc bigint, started_at_utc bigint, finished_at_utc bigint, - status text, attempt integer, worker_phase text, - worker_agent_id text, worker_history_agent_id text, - payload jsonb NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX IF NOT EXISTS mirror_scheduler_job_runs_job_idx - ON agent.mirror_scheduler_job_runs (job_id, scheduled_for_utc); - --- agent.agents (incremental, REDUCED payload + history: spawn_metadata_json --- averages ~29KB/row and last_assistant_message ~4KB/row at source, so the --- payload carries scalar/identity columns, the extracted scheduler-cron --- attribution, and byte lengths of the big text columns instead of content) -CREATE TABLE IF NOT EXISTS agent.mirror_agent_agents ( - agent_id text PRIMARY KEY, - id text, session_id text, kind text, parent_id text, parent_agent_id text, - root_session_id text, request_id text, model text, status text, - depth integer, ephemeral boolean, agent_type text, - created_at bigint, updated_at bigint, - scheduler_cron_job_id text, scheduler_cron_worker_phase text, - payload jsonb NOT NULL, payload_hash text NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE TABLE IF NOT EXISTS agent.mirror_history_agent_agents ( - agent_id text NOT NULL, - payload jsonb NOT NULL, payload_hash text NOT NULL, - valid_from timestamptz, valid_to timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX IF NOT EXISTS mirror_history_agent_agents_key_idx - ON agent.mirror_history_agent_agents (agent_id, valid_to); - --- goals.goals (snapshot + history) -CREATE TABLE IF NOT EXISTS agent.mirror_goals_goals ( - goal_id text PRIMARY KEY, - slug text, title text, status text, momentum_status text, - parent_goal_id text, source text, updated_at text, - payload jsonb NOT NULL, payload_hash text NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE TABLE IF NOT EXISTS agent.mirror_history_goals_goals ( - goal_id text NOT NULL, - payload jsonb NOT NULL, payload_hash text NOT NULL, - valid_from timestamptz, valid_to timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX IF NOT EXISTS mirror_history_goals_goals_key_idx - ON agent.mirror_history_goals_goals (goal_id, valid_to); - --- goals.updates (incremental + history) -CREATE TABLE IF NOT EXISTS agent.mirror_goals_updates ( - update_id text PRIMARY KEY, - goal_id text, created_at text, updated_at text, author_source text, - payload jsonb NOT NULL, payload_hash text NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE TABLE IF NOT EXISTS agent.mirror_history_goals_updates ( - update_id text NOT NULL, - payload jsonb NOT NULL, payload_hash text NOT NULL, - valid_from timestamptz, valid_to timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX IF NOT EXISTS mirror_history_goals_updates_key_idx - ON agent.mirror_history_goals_updates (update_id, valid_to); - --- scheduler.job_definitions (incremental, metadata only: job_definition_id, --- job_id, version, timestamps + task_text byte length and md5; the prompt --- bodies themselves are not mirrored. Source rows are immutable versions, --- so upserts are DO NOTHING. Source table was EMPTY at build time.) -CREATE TABLE IF NOT EXISTS agent.mirror_scheduler_job_definitions ( - job_definition_id bigint PRIMARY KEY, - job_id text, version integer, prompt_template_id bigint, - created_at timestamptz, retired_at timestamptz, - task_text_bytes integer, task_text_md5 text, - payload jsonb NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); - --- token usage rollups (recomputed over a rolling window each run) -CREATE TABLE IF NOT EXISTS agent.mirror_token_usage_daily ( - day date NOT NULL, dimension text NOT NULL, key text NOT NULL, - input_tokens bigint, output_tokens bigint, messages bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, dimension, key) -); -CREATE TABLE IF NOT EXISTS agent.mirror_token_usage_hourly ( - hour timestamptz NOT NULL, dimension text NOT NULL, key text NOT NULL, - input_tokens bigint, output_tokens bigint, messages bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (hour, dimension, key) -); - --- session rollups -CREATE TABLE IF NOT EXISTS agent.mirror_session_activity_hourly ( - hour timestamptz PRIMARY KEY, - active_sessions bigint, new_sessions bigint, messages bigint, - input_tokens bigint, output_tokens bigint, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE TABLE IF NOT EXISTS agent.mirror_session_stats_daily ( - day date PRIMARY KEY, - sessions bigint, - msgs_min bigint, msgs_max bigint, msgs_avg double precision, msgs_median double precision, - toks_min bigint, toks_max bigint, toks_avg double precision, toks_median double precision, - exported_at timestamptz NOT NULL DEFAULT now() -); - --- per-session summaries (derived from agent.agents + token usage; --- agent.sessions is EMPTY at source, so sessions are derived from --- coalesce(root_session_id, session_id) over agent.agents) -CREATE TABLE IF NOT EXISTS agent.mirror_sessions ( - session_id text PRIMARY KEY, - root_agent_id text, root_kind text, scheduler_cron_job_id text, - root_model text, model_count bigint, agent_count bigint, - created_at_epoch bigint, updated_at_epoch bigint, - message_count bigint, input_tokens bigint, output_tokens bigint, - payload jsonb NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); diff --git a/pkgs/agent-backup/schema2.sql b/pkgs/agent-backup/schema2.sql deleted file mode 100644 index d30673f687..0000000000 --- a/pkgs/agent-backup/schema2.sql +++ /dev/null @@ -1,140 +0,0 @@ --- runtime-db-export expansion (2026-10-28, Drew): full sessions mirror, --- per-conversation rollups, and the export-time-only statistics family. --- Percentiles are nearest-rank picks via row_number() windows (no --- percentile_cont in the muse.db vocabulary). - --- reshape session stats: add grain + full percentile/duration columns -DROP TABLE IF EXISTS agent.mirror_session_stats_daily; -CREATE TABLE agent.mirror_session_stats_daily ( - day date NOT NULL, grain text NOT NULL, key text NOT NULL, - sessions_active bigint, sessions_started bigint, - msgs_min bigint, msgs_max bigint, msgs_avg double precision, - msgs_p50 bigint, msgs_p90 bigint, msgs_p95 bigint, msgs_p99 bigint, - toks_min bigint, toks_max bigint, toks_avg double precision, - toks_p50 bigint, toks_p90 bigint, toks_p95 bigint, toks_p99 bigint, - dur_min_s bigint, dur_max_s bigint, dur_avg_s double precision, - dur_p50_s bigint, dur_p90_s bigint, dur_p95_s bigint, dur_p99_s bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, grain, key) -); - --- full mirror of agent.sessions (EMPTY at source at build time; the --- derived per-session summary lives in agent.mirror_sessions) -CREATE TABLE IF NOT EXISTS agent.mirror_agent_sessions ( - session_id text PRIMARY KEY, - root_request_id text, - created_at timestamptz, updated_at timestamptz, archived_at timestamptz, - payload jsonb NOT NULL, payload_hash text NOT NULL, - exported_at timestamptz NOT NULL DEFAULT now() -); -CREATE TABLE IF NOT EXISTS agent.mirror_history_agent_sessions ( - session_id text NOT NULL, - payload jsonb NOT NULL, payload_hash text NOT NULL, - valid_from timestamptz, valid_to timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX IF NOT EXISTS mirror_history_agent_sessions_key_idx - ON agent.mirror_history_agent_sessions (session_id, valid_to); - --- derived sessions gain their chat link (chat_id = root agent's session_id --- when a chat.chats row exists; only 38 chats exist at build time) -ALTER TABLE agent.mirror_sessions ADD COLUMN IF NOT EXISTS chat_id text; - --- per-message token distribution (global + per scheduler job) -CREATE TABLE IF NOT EXISTS agent.mirror_message_token_stats_daily ( - day date NOT NULL, grain text NOT NULL, key text NOT NULL, - messages bigint, - in_min bigint, in_max bigint, in_avg double precision, - in_p50 bigint, in_p90 bigint, in_p95 bigint, in_p99 bigint, - out_min bigint, out_max bigint, out_avg double precision, - out_p50 bigint, out_p90 bigint, out_p95 bigint, out_p99 bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, grain, key) -); - --- job-run outcomes + duration distribution (job_id '' = global) -CREATE TABLE IF NOT EXISTS agent.mirror_run_stats_daily ( - day date NOT NULL, job_id text NOT NULL, - runs bigint, succeeded bigint, failed bigint, timeout bigint, - cancelled bigint, other bigint, - finished_runs bigint, - dur_min_s bigint, dur_max_s bigint, dur_avg_s double precision, - dur_p50_s bigint, dur_p90_s bigint, dur_p95_s bigint, dur_p99_s bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, job_id) -); - --- fixed-bucket histograms (bucket_hi NULL = open-ended top bucket) -CREATE TABLE IF NOT EXISTS agent.mirror_histograms_daily ( - day date NOT NULL, grain text NOT NULL, key text NOT NULL, - metric text NOT NULL, bucket_lo bigint NOT NULL, bucket_hi bigint, - count bigint, exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, grain, key, metric, bucket_lo) -); - --- peak concurrency per hour (exact event-sweep maxima) -CREATE TABLE IF NOT EXISTS agent.mirror_concurrency_hourly ( - hour timestamptz PRIMARY KEY, - max_concurrent_runs bigint, max_concurrent_sessions bigint, - exported_at timestamptz NOT NULL DEFAULT now() -); - --- distinct counts per day (global + per job) -CREATE TABLE IF NOT EXISTS agent.mirror_distincts_daily ( - day date NOT NULL, grain text NOT NULL, key text NOT NULL, - models_used bigint, sessions_active bigint, agents_active bigint, - chats_active bigint, tools_used bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, grain, key) -); - --- top-10 lists per day -CREATE TABLE IF NOT EXISTS agent.mirror_top_daily ( - day date NOT NULL, kind text NOT NULL, rank integer NOT NULL, - ref text, label text, tokens bigint, messages bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, kind, rank) -); - --- tool-call aggregates (source runtime.tool_calls/outputs EMPTY at build; --- error rule is provisional until data exists: output error_text NOT NULL --- or output status not in ('success','completed','ok')) -CREATE TABLE IF NOT EXISTS agent.mirror_tool_stats_daily ( - day date NOT NULL, tool_name text NOT NULL, server_name text NOT NULL, - calls bigint, errors bigint, - dur_avg_s double precision, dur_p95_s double precision, dur_max_s double precision, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, tool_name, server_name) -); - --- compaction stats (global + per job) -CREATE TABLE IF NOT EXISTS agent.mirror_compaction_stats_daily ( - day date NOT NULL, grain text NOT NULL, key text NOT NULL, - compactions bigint, - tokens_before_avg double precision, tokens_before_p95 bigint, - tokens_after_avg double precision, tokens_after_p95 bigint, - saved_avg double precision, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, grain, key) -); - --- subagent shape per day (global; depth + children distributions also --- land in mirror_histograms_daily as spawn_depth / children_per_parent) -CREATE TABLE IF NOT EXISTS agent.mirror_subagent_stats_daily ( - day date PRIMARY KEY, - spawns bigint, parents bigint, - children_avg double precision, children_max bigint, - children_p50 bigint, children_p90 bigint, children_p95 bigint, children_p99 bigint, - exported_at timestamptz NOT NULL DEFAULT now() -); - --- per-conversation (per chat) daily rollup -CREATE TABLE IF NOT EXISTS agent.mirror_conversation_stats_daily ( - day date NOT NULL, chat_id text NOT NULL, - sessions bigint, messages bigint, - input_tokens bigint, output_tokens bigint, - first_activity_epoch bigint, last_activity_epoch bigint, - sess_msgs_p50 bigint, sess_msgs_p90 bigint, - sess_toks_p50 bigint, sess_toks_p90 bigint, - exported_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (day, chat_id) -); diff --git a/pkgs/agent-backup/turso_client.py b/pkgs/agent-backup/turso_client.py index fd98591fb4..3054cd5386 100644 --- a/pkgs/agent-backup/turso_client.py +++ b/pkgs/agent-backup/turso_client.py @@ -1,10 +1,7 @@ #!/usr/bin/env python3 """Shared Turso transport + landing-table DDL for the runtime-db-export -loader, repointed 2026-11-06 from muse-dev2 Postgres (agent.mirror_*) -to the dedicated Turso DB `fleet-mirror` (agent_mirror_* tables; -renamed from `muse-mirror` and converted libsql->TursoDB 2026-11-07, -code#6619). -Decision + evidence: developing-today/code#5691 (repoint, not retire). +loader. Turso is the store: the dedicated Turso DB `fleet-mirror` +(agent_mirror_* tables; renamed from `muse-mirror`, code#6619). Target access: - HTTP pipeline (libsql /v2/pipeline) at the fleet-mirror host. The @@ -35,10 +32,8 @@ TOKEN_NAME = "turso.fleet-mirror-rw-token" FLEET = os.path.expanduser("~/tools/fleet") -# SQLite DDL for every landing table (translated from schema.sql + -# schema2.sql; PG types mapped per the Turso migration's typemap: -# bigint/integer -> INTEGER, double -> REAL, boolean -> INTEGER, -# date/timestamptz/jsonb -> TEXT). The 20 tables already in fleet-mirror +# SQLite DDL for every landing table (types: bigint/integer -> INTEGER, +# double -> REAL, boolean -> INTEGER, date/timestamptz/jsonb -> TEXT). The 20 tables already in fleet-mirror # make CREATE IF NOT EXISTS a no-op; the 5 history tables and 3 shells # the migration deliberately did not copy are created here on first use. DDL = { diff --git a/pkgs/cold-store-reaper/README.md b/pkgs/cold-store-reaper/README.md index 0678db3047..c7570d5e16 100644 --- a/pkgs/cold-store-reaper/README.md +++ b/pkgs/cold-store-reaper/README.md @@ -80,7 +80,6 @@ cold-store status # counts, cold bytes, last cold-store sync-manifest # push the local manifest into D1 cold-store sync-manifest --dry-run # ... or just print the statement counts cold-store backup-d1 # export the D1 manifest DB into db-backups/d1/ -cold-store backup-supabase # file the newest Supabase dump from R2 into db-backups/supabase/ cold-store evict-scan # dry-run: which R2 objects are safe to evict? (never deletes) cold-store evict --apply # delete the evictable ones (each re-verified first) cold-store prune-backups # retention plan (dry-run) @@ -111,19 +110,17 @@ not marked `uploading`. Database dumps are a separate, simpler class: single self-describing files, uploaded **unbundled** into `db-backups//` under the app-owned root -(`ensure-folders` creates the `supabase/`, `turso/`, and `d1/` subfolders, +(`ensure-folders` creates the `turso/` and `d1/` subfolders, idempotently). Files land with dated names — `--` — and every upload writes a `backup-upload` row to the transfer ledger. ```sh -cold-store put-backup supabase pgdump-2026-10-26.sql.zst # prints the Drive file id +cold-store put-backup d1 d1-export-2026-10-26.sql # prints the Drive file id cold-store list-backups # all DBs, newest first cold-store list-backups --db turso cold-store backup-d1 # export the D1 manifest DB itself # (REST query API) and file it under d1/ -cold-store backup-supabase # file the newest R2 Supabase dump - # under supabase/ (see "R2" below) cold-store get-backup d1 d1-<...>-cold-store-manifest-export.sql ./restored.sql ``` @@ -178,10 +175,6 @@ environment only): `CLOUDFLARE_API_TOKEN` in the environment (materialize from Bitwarden into the cron env); `TURSO_PLATFORM_API_TOKEN` is optional (it gates the Turso step). - The nightly `backup-supabase` filing is retired (2026-11-19): the - Supabase project was replaced by Turso, so no new dump reaches R2. - Existing `supabase/` filings keep their retention, and - `cold-store backup-supabase` still works by hand. - `scripts/export-turso.sh` — the Turso step: discovers every database in the Turso organization through the Platform API (no `turso` CLI needed), mints a per-database auth token, downloads @@ -214,50 +207,27 @@ environment only): and a final verdict; exits non-zero on any failure. Requires `REHYDRATOR_API_KEY` and `CLOUDFLARE_API_TOKEN` in the environment. -## R2: Supabase filings and the eviction trial +## R2: the eviction trial -The `supabase-backups` R2 bucket is wired in both directions: the -nightly job files its newest dump into Drive, and the reaper can evict +The `supabase-backups` R2 bucket (a legacy bucket name; Turso is the +database store) is the eviction trial bucket: the reaper can evict bucket objects the cold store provably holds. Access is a minimal stdlib S3 client (SigV4) at the account's R2 host, with bucket-scoped -credentials from the environment only — materialize from Bitwarden, -never store: - -```sh -R2_ACCESS_KEY_ID= \ -R2_SECRET_ACCESS_KEY= \ - cold-store backup-supabase -``` - -The host defaults to the account's `*.r2.cloudflarestorage.com` -endpoint (override with `COLD_STORE_R2_HOST`; tests stub the whole -base with `COLD_STORE_S3_BASE`). - -### backup-supabase - -Lists the bucket (paginated ListObjectsV2), picks the **newest backup -object by LastModified** — `pg/muse-dev/manifest.json` excluded; it is -the backup system's own index, not a dump — downloads it, and files it -via `put-backup` as a `supabase` backup. The download is verified -against the response's Content-Length, and a truncated body (observed -live through this sandbox's egress proxy) retries the whole GET, up -to 3 attempts. Filing is point-in-time, like `backup-d1`: unchanged -content is filed again, and the command prints the content sha256 so -the duplication is visible rather than silent. - -If urllib still cannot deliver the object whole, the download falls -back to **one `curl` attempt** (curl does its own SigV4 signing via -`--aws-sigv4` and reads the proxy from the environment). Why: through -this sandbox's egress proxy, small responses truncate only -intermittently — retries absorb those — but multi-megabyte responses -truncate _systematically_ (live: every attempt cut at exactly -409,600 bytes), and curl is immune; the Supabase backup tooling -established the same replay-with-curl precedent, and the reaper -already shells out to a CLI for compression (`zstd`). The curl body -gets the same byte-count verification (the listing's size, or a HEAD -Content-Length when the caller has none), credentials are scrubbed -from any error text, and a missing or failing curl surfaces as a -named `ColdStoreError`, never a traceback. +credentials from the environment only — materialize from Bitwarden +(`cloudflare.r2-backups-access-key-id` / +`cloudflare.r2-backups-secret-access-key`), never store. The host +defaults to the account's `*.r2.cloudflarestorage.com` endpoint +(override with `COLD_STORE_R2_HOST`; tests stub the whole base with +`COLD_STORE_S3_BASE`). + +Object downloads (`s3_get_object`) are verified against the response's +Content-Length; a truncated body retries the whole GET, up to 3 +attempts, then falls back to **one `curl` attempt** (curl does its own +SigV4 signing via `--aws-sigv4`), because multi-megabyte responses +truncate systematically through this sandbox's egress proxy while curl +is immune. The curl body gets the same byte-count verification, +credentials are scrubbed from any error text, and a missing or failing +curl surfaces as a named `ColdStoreError`, never a traceback. ### Eviction diff --git a/pkgs/cold-store-reaper/cold_store.py b/pkgs/cold-store-reaper/cold_store.py index 6c63925191..5fd44d9f45 100755 --- a/pkgs/cold-store-reaper/cold_store.py +++ b/pkgs/cold-store-reaper/cold_store.py @@ -63,7 +63,12 @@ # DB-backup class (DESIGN.md section 5): nightly dumps live unbundled under # db-backups//, one subfolder per database. -BACKUP_DBS = ("supabase", "turso", "d1") +BACKUP_DBS = ("turso", "d1") +# Retired families: no longer filed, but dumps already under +# db-backups// stay listable, retrievable and under retention. +# Their folder is found, never created. +LEGACY_BACKUP_DBS = ("supabase",) +READ_BACKUP_DBS = BACKUP_DBS + LEGACY_BACKUP_DBS # Backup families whose folder holds one file per source database per # run, named --.: retention runs per # source database (keyed by the name after the stamp), not across the @@ -109,9 +114,8 @@ D1_SYNC_BACKOFF_CAP_SECONDS = 30.0 -# R2 (DESIGN.md sections 4-5): the supabase-backups bucket is both a -# nightly filing source (backup-supabase) and the first eviction trial -# bucket. Access is the S3 API at the account's R2 host, with +# R2 (DESIGN.md sections 4-5): the supabase-backups bucket (a legacy +# R2 bucket name) is the first eviction trial bucket. Access is the S3 API at the account's R2 host, with # bucket-scoped credentials from the environment only. DEFAULT_R2_HOST = "234b866b99ce2b142d7963d8d139cbfa.r2.cloudflarestorage.com" DEFAULT_R2_BUCKET = "supabase-backups" @@ -940,6 +944,12 @@ def ensure_folders(self) -> dict: folders[key] = self._find_folder( db, folders["db-backups"] ) or self._create_folder(db, folders["db-backups"]) + for db in LEGACY_BACKUP_DBS: + key = f"db-backups/{db}" + if not folders.get(key): + found = self._find_folder(db, folders["db-backups"]) + if found: + folders[key] = found state["folders"] = folders self.save_state(state) return folders @@ -950,6 +960,21 @@ def _folder_id(self, key: str) -> str: folders = self.ensure_folders() return folders[key] + def _legacy_backup_folder_id(self, db: str) -> str | None: + """Folder id of a retired backup family, or None when this + install never filed one (legacy folders are never created).""" + folders = self.load_state().get("folders") or {} + key = f"db-backups/{db}" + if key not in folders: + folders = self.ensure_folders() + return folders.get(key) + + def _readable_backup_dbs(self) -> list[str]: + """Active families plus each retired family that has a folder.""" + return list(BACKUP_DBS) + [ + db for db in LEGACY_BACKUP_DBS if self._legacy_backup_folder_id(db) + ] + # ------------------------------------------------------------------ pack def _run_zstd(self, args, **kwargs): try: @@ -1397,14 +1422,19 @@ def verification_failed(message: str) -> ColdStoreError: } def list_backups(self, db_name: str | None = None) -> list[dict]: - if db_name is not None and db_name not in BACKUP_DBS: + if db_name is not None and db_name not in READ_BACKUP_DBS: raise ColdStoreError( - f"unknown backup db {db_name!r} — expected one of {', '.join(BACKUP_DBS)}" + f"unknown backup db {db_name!r} — expected one of {', '.join(READ_BACKUP_DBS)}" ) - dbs = [db_name] if db_name else list(BACKUP_DBS) + dbs = [db_name] if db_name else self._readable_backup_dbs() out = [] for db in dbs: - folder_id = self._folder_id(f"db-backups/{db}") + if db in LEGACY_BACKUP_DBS: + folder_id = self._legacy_backup_folder_id(db) + if not folder_id: + continue + else: + folder_id = self._folder_id(f"db-backups/{db}") q = f"'{folder_id}' in parents and trashed = false" page_token = None seen_tokens = set() @@ -1568,11 +1598,11 @@ def prune_backups( transfer_ledger row per file is written (direction 'trash', kind 'backup-prune', ref = filename). """ - if db_name is not None and db_name not in BACKUP_DBS: + if db_name is not None and db_name not in READ_BACKUP_DBS: raise ColdStoreError( - f"unknown backup db {db_name!r} — expected one of {', '.join(BACKUP_DBS)}" + f"unknown backup db {db_name!r} — expected one of {', '.join(READ_BACKUP_DBS)}" ) - dbs = [db_name] if db_name else list(BACKUP_DBS) + dbs = [db_name] if db_name else self._readable_backup_dbs() plans = [] for db in dbs: rows = self.list_backups(db) @@ -1632,13 +1662,18 @@ def prune_backups( def get_backup(self, db_name: str, name: str, out_path: str) -> dict: """Download one backup file, in full, by its exact Drive name.""" - if db_name not in BACKUP_DBS: + if db_name not in READ_BACKUP_DBS: raise ColdStoreError( - f"unknown backup db {db_name!r} — expected one of {', '.join(BACKUP_DBS)}" + f"unknown backup db {db_name!r} — expected one of {', '.join(READ_BACKUP_DBS)}" ) if "'" in name: raise ColdStoreError("backup name must not contain a single quote") - folder_id = self._folder_id(f"db-backups/{db_name}") + if db_name in LEGACY_BACKUP_DBS: + folder_id = self._legacy_backup_folder_id(db_name) + if not folder_id: + raise ColdStoreError(f"no {db_name} backups on this install") + else: + folder_id = self._folder_id(f"db-backups/{db_name}") q = f"'{folder_id}' in parents and name = '{name}' and trashed = false" url = ( self.drive_base @@ -1999,7 +2034,7 @@ def _s3_request(self, method, bucket, key=None, query=None, curl_fallback=True): method is GET, make exactly ONE curl attempt for the same URL (_s3_request_via_curl) before giving up: on a hostile-proxy night every urllib retry can truncate at a different offset - (seen live 2026-10-28, when backup-supabase died at its LIST), + (seen live 2026-10-28, when an R2 filing died at its LIST), while curl is immune. The curl response returns through the same (status, headers, body) shape, so callers' status handling (_s3_check) sees an HTTP error from curl exactly as @@ -2122,10 +2157,9 @@ def s3_get_object( truncate intermittently and retries absorb them, but multi-megabyte responses truncate systematically through this proxy (every attempt cut at the same byte count), while curl - is immune — the same reason the Supabase backup tooling - replays downloads with curl. `expected_size`, when the caller - knows it (backup-supabase has it from the listing), is the - byte count the curl body is verified against. + is immune. `expected_size`, when the caller knows it (e.g. from + the listing), is the byte count the curl body is verified + against. """ problem = "no attempt made" for _attempt in range(S3_GET_ATTEMPTS): @@ -2297,38 +2331,6 @@ def s3_delete_object(self, bucket: str, key: str) -> None: status, _h, resp = self._s3_request("DELETE", bucket, key=key) self._s3_check(status, resp, f"DELETE {bucket}/{key}") - # ---------------------------------------------------------- backup from R2 - def backup_supabase(self, bucket: str = DEFAULT_R2_BUCKET) -> dict: - """File the newest Supabase backup object from R2 as a supabase - backup (DESIGN section 5), via the put-backup machinery. - - 'Newest' is by S3 LastModified among the bucket's backup - objects; manifest.json is excluded — it is the backup system's - own index, not a dump. The download is byte-count verified - (s3_get_object). Filing is point-in-time, exactly like - backup-d1: unchanged content is filed again, and the content - sha256 is reported so the duplication is visible. - """ - epoch = datetime.min.replace(tzinfo=timezone.utc) - objects = [ - o - for o in self.s3_list_objects(bucket) - if o["key"].rsplit("/", 1)[-1] != "manifest.json" - ] - if not objects: - raise ColdStoreError(f"no backup objects found in R2 bucket {bucket}") - newest = max(objects, key=lambda o: (o["last_modified"] or epoch, o["key"])) - data = self.s3_get_object(bucket, newest["key"], expected_size=newest["size"]) - staging = self.home / "staging" - staging.mkdir(parents=True, exist_ok=True) - path = staging / newest["key"].rsplit("/", 1)[-1] - path.write_bytes(data) - result = self.put_backup("supabase", str(path)) - result["sha256"] = hashlib.sha256(data).hexdigest() - result["source_bucket"] = bucket - result["source_key"] = newest["key"] - return result - # --------------------------------------------------------------- eviction def _object_cold_verified(self, conn, obj_hash: str): """(manifest state or None, member of a verified bundle?) — @@ -2574,7 +2576,7 @@ def main(argv=None) -> int: p_list_backups = sub.add_parser( "list-backups", help="list DB backups in Drive, newest first" ) - p_list_backups.add_argument("--db", choices=BACKUP_DBS, default=None) + p_list_backups.add_argument("--db", choices=READ_BACKUP_DBS, default=None) p_sync = sub.add_parser( "sync-manifest", help="push the local manifest to the D1 cold-store-manifest database (idempotent upserts)", @@ -2588,7 +2590,7 @@ def main(argv=None) -> int: "prune-backups", help="enforce backup retention (30 daily / 12 weekly / 12 monthly, trash-not-delete); dry-run unless --apply", ) - p_prune.add_argument("--db", choices=BACKUP_DBS, default=None) + p_prune.add_argument("--db", choices=READ_BACKUP_DBS, default=None) p_prune.add_argument( "--apply", action="store_true", @@ -2597,18 +2599,13 @@ def main(argv=None) -> int: p_get_backup = sub.add_parser( "get-backup", help="download one backup file in full by its exact name" ) - p_get_backup.add_argument("db", choices=BACKUP_DBS) + p_get_backup.add_argument("db", choices=READ_BACKUP_DBS) p_get_backup.add_argument("name") p_get_backup.add_argument("out_path") sub.add_parser( "backup-d1", help="export the D1 cold-store-manifest database and file it as a d1 backup", ) - p_backup_sb = sub.add_parser( - "backup-supabase", - help="file the newest Supabase backup object from R2 into db-backups/supabase/", - ) - p_backup_sb.add_argument("--bucket", default=DEFAULT_R2_BUCKET) p_evict_scan = sub.add_parser( "evict-scan", help="dry-run: verdict per R2 object — evictable only if cold in a verified bundle, old enough, and not among the newest kept (never deletes)", @@ -2744,14 +2741,6 @@ def main(argv=None) -> int: f"uploaded to Drive as {result['drive_file_id']} " f"({result['rows']} row(s) across {len(result['tables'])} table(s))" ) - elif args.cmd == "backup-supabase": - result = store.backup_supabase(args.bucket) - print( - f"backup {result['name']}: {_human(result['bytes'])}, " - f"sha256 {result['sha256']}, " - f"uploaded to Drive as {result['drive_file_id']} " - f"(from r2://{result['source_bucket']}/{result['source_key']})" - ) elif args.cmd == "evict-scan": scan = store.evict_scan(args.bucket, args.min_age_days, args.keep_newest) _print_evict_scan(scan) diff --git a/pkgs/cold-store-reaper/scripts/nightly-backup.sh b/pkgs/cold-store-reaper/scripts/nightly-backup.sh index 70ed2e0829..bea73f5915 100755 --- a/pkgs/cold-store-reaper/scripts/nightly-backup.sh +++ b/pkgs/cold-store-reaper/scripts/nightly-backup.sh @@ -18,12 +18,6 @@ # tonight's ledger rows) to D1 # 5. cold-store status one-screen summary (head) # -# The former step 2, `cold-store backup-supabase`, is retired: the -# Supabase project it filed dumps of has been replaced by Turso (Drew, -# 2026-11-18), so no new dump reaches R2. Filings already in -# db-backups/supabase/ keep their retention under prune-backups, and -# `cold-store backup-supabase` stays available to run by hand. -# # Steps are ISOLATED: a step that fails never starves the steps after # it (the 2026-10-27 run lost retention, manifest sync, and status to # one failed Turso export). Each step prints a per-step outcome line diff --git a/pkgs/cold-store-reaper/tests/test_cold_store.py b/pkgs/cold-store-reaper/tests/test_cold_store.py index a30c227429..6dab63642a 100644 --- a/pkgs/cold-store-reaper/tests/test_cold_store.py +++ b/pkgs/cold-store-reaper/tests/test_cold_store.py @@ -577,8 +577,8 @@ def test_ensure_folders_idempotent(self): first = self.store.ensure_folders() second = self.store.ensure_folders() self.assertEqual(first, second) - # root + 3 subfolders + 3 db-backup subfolders (supabase/turso/d1) - self.assertEqual(len(self.fake.folders), 7) + # root + 3 subfolders + 2 db-backup subfolders (turso/d1) + self.assertEqual(len(self.fake.folders), 6) def test_upload_verify_and_fetch_roundtrip(self): # force multi-chunk resumable uploads against the fake (308 path) @@ -1293,7 +1293,7 @@ def corrupt_after_upload(src, name, folder_id): with self.assertRaisesRegex( cold_store.ColdStoreError, "verification mismatch" ): - self.store.put_backup("supabase", str(dump)) + self.store.put_backup("d1", str(dump)) conn = self.store.db() rows = conn.execute( @@ -1315,7 +1315,7 @@ def fail_metadata_readback(method, url, *args, **kwargs): with self.assertRaisesRegex( cold_store.ColdStoreError, "files.get after backup upload failed" ): - self.store.put_backup("supabase", str(dump)) + self.store.put_backup("d1", str(dump)) conn = self.store.db() rows = conn.execute( @@ -1343,7 +1343,7 @@ def corrupt_after_upload(src, name, folder_id): with self.assertRaisesRegex( cold_store.ColdStoreError, "verification mismatch" ): - self.store.put_backup("supabase", str(dump)) + self.store.put_backup("d1", str(dump)) self.assertEqual(len(uploaded), 1) self.assertTrue(self.fake.file_meta[uploaded[0]]["trashed"]) @@ -1362,7 +1362,7 @@ def fail_metadata_readback(method, url, *args, **kwargs): with self.assertRaisesRegex( cold_store.ColdStoreError, "files.get after backup upload failed" ): - self.store.put_backup("supabase", str(dump)) + self.store.put_backup("d1", str(dump)) self.assertEqual(len(self.fake.trashed_calls), 1) trashed_id = self.fake.trashed_calls[0]["id"] @@ -1394,16 +1394,16 @@ def fail_trash(method, url, *args, **kwargs): cold_store.ColdStoreError, "verification mismatch.*ALSO failed to trash", ): - self.store.put_backup("supabase", str(dump)) + self.store.put_backup("d1", str(dump)) self.assertEqual(len(uploaded), 1) def test_put_backup_naming_routing_ledger(self): - dump = self.write_src("dump.sql", b"-- fake supabase dump\n" * 10) - result = self.store.put_backup("supabase", str(dump)) - self.assertRegex(result["name"], r"^supabase-\d{8}T\d{6}Z-dump\.sql$") + dump = self.write_src("dump.sql", b"-- fake d1 dump\n" * 10) + result = self.store.put_backup("d1", str(dump)) + self.assertRegex(result["name"], r"^d1-\d{8}T\d{6}Z-dump\.sql$") folders = self.store.ensure_folders() meta = self.fake.file_meta[result["drive_file_id"]] - self.assertEqual(meta["parents"], [folders["db-backups/supabase"]]) + self.assertEqual(meta["parents"], [folders["db-backups/d1"]]) self.assertEqual(meta["name"], result["name"]) self.assertEqual(self.fake.files[result["drive_file_id"]], dump.read_bytes()) conn = self.store.db() @@ -1424,23 +1424,23 @@ def test_put_backup_rejects_unknown_db(self): def test_list_backups_newest_first_and_filtered(self): a = self.write_src("a.sql", b"a") b = self.write_src("b.sql", b"b") - self.store.put_backup("supabase", str(a)) + self.store.put_backup("d1", str(a)) self.store.put_backup("turso", str(b)) all_rows = self.store.list_backups() self.assertEqual(len(all_rows), 2) self.assertEqual(all_rows[0]["db"], "turso") # later createdTime first - self.assertEqual(all_rows[1]["db"], "supabase") - only = self.store.list_backups("supabase") + self.assertEqual(all_rows[1]["db"], "d1") + only = self.store.list_backups("d1") self.assertEqual(len(only), 1) - self.assertEqual(only[0]["db"], "supabase") + self.assertEqual(only[0]["db"], "d1") def test_list_backups_follows_drive_pages(self): - folder = self.store.ensure_folders()["db-backups/supabase"] + folder = self.store.ensure_folders()["db-backups/d1"] self.fake.page_cap = 2 names = [ - "supabase-20260301T020000Z-export.sql", - "supabase-20260302T020000Z-export.sql", - "supabase-20260303T020000Z-export.sql", + "d1-20260301T020000Z-export.sql", + "d1-20260302T020000Z-export.sql", + "d1-20260303T020000Z-export.sql", ] for day, name in enumerate(names, start=1): self.seed_drive_file( @@ -1449,7 +1449,7 @@ def test_list_backups_follows_drive_pages(self): created=f"2026-03-0{day}T02:00:00.000Z", ) - rows = self.store.list_backups("supabase") + rows = self.store.list_backups("d1") self.assertEqual([row["name"] for row in rows], list(reversed(names))) @@ -1540,7 +1540,7 @@ def test_list_backups_rejects_wrong_response_shapes(self): with self.assertRaisesRegex( cold_store.ColdStoreError, "files.list for backups" ): - self.store.list_backups("supabase") + self.store.list_backups("d1") def test_get_backup_rejects_wrong_response_shapes(self): invalid_bodies = ( @@ -1563,7 +1563,7 @@ def test_get_backup_rejects_wrong_response_shapes(self): "files.list for get-backup", ): self.store.get_backup( - "supabase", + "d1", "backup.sql", str(Path(self.tmp.name) / "out.sql"), ) @@ -2042,6 +2042,40 @@ def test_prune_all_dbs_and_unknown_db(self): self.store.prune_backups("oracle") +class TestLegacyBackupFamily(ColdStoreTestBase): + """Supabase is retired: nothing new is filed, no folder is created, + but dumps already in db-backups/supabase/ stay readable and pruned.""" + + def test_fresh_install_creates_no_legacy_folder(self): + folders = self.store.ensure_folders() + self.assertNotIn("db-backups/supabase", folders) + self.assertFalse(any(f["name"] == "supabase" for f in self.fake.folders)) + self.assertEqual(self.store.list_backups("supabase"), []) + plans = self.store.prune_backups() + self.assertEqual([p["db"] for p in plans], list(cold_store.BACKUP_DBS)) + with self.assertRaisesRegex(cold_store.ColdStoreError, "no supabase backups"): + self.store.get_backup("supabase", "x", str(Path(self.tmp.name) / "x")) + + def test_existing_legacy_backups_stay_readable(self): + parent = self.store.ensure_folders()["db-backups"] + legacy = self.store._create_folder("supabase", parent) + name = "supabase-20261001T020000Z-db.backup.gz" + self.seed_drive_file(name, legacy, data=b"old dump") + + rows = self.store.list_backups("supabase") + self.assertEqual([r["name"] for r in rows], [name]) + self.assertIn("supabase", [r["db"] for r in self.store.list_backups()]) + out = Path(self.tmp.name) / "old.gz" + self.store.get_backup("supabase", name, str(out)) + self.assertEqual(out.read_bytes(), b"old dump") + plans = self.store.prune_backups() + self.assertEqual([p["db"] for p in plans], ["turso", "d1", "supabase"]) + + dump = self.write_src("dump.sql", b"x") + with self.assertRaises(cold_store.ColdStoreError): + self.store.put_backup("supabase", str(dump)) + + class TestGetBackup(ColdStoreTestBase): def test_get_backup_roundtrip(self): data = b"-- turso dump\n" + bytes(range(256)) * 4 @@ -2218,7 +2252,7 @@ class TestS3TransportRetry(S3TestBase): egress proxy, R2 responses are intermittently truncated mid-body or dropped outright, and before the fix those escaped _s3_request as raw http.client tracebacks that killed - backup-supabase / evict-scan at the LIST step. Backoff is zeroed + evict-scan at the LIST step. Backoff is zeroed in S3TestBase.setUp, so these run instantly.""" def _put_five(self): @@ -2282,38 +2316,17 @@ def flaky_http(method, url, headers=None, data=None, timeout=120): self.assertEqual(self.s3.deleted, ["pg/muse-dev/a.bin"]) -class TestBackupSupabase(S3TestBase): - def test_files_newest_non_manifest_with_truncation_retry(self): - older = b"older backup " * 40 - newest = b"newest backup payload " * 60 - old_key = self.key_for(hashlib.sha256(older).hexdigest()) - new_key = self.key_for(hashlib.sha256(newest).hexdigest()) - self.s3.put(old_key, older, "2026-10-20T02:00:00.000Z") - self.s3.put(new_key, newest, "2026-10-21T02:00:00.000Z") - # the bucket manifest is newer still — and is never a dump filing - self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-22T02:00:00.000Z") - # the first GET of the newest object arrives truncated (the - # live proxy failure mode); the client must retry the whole GET - self.s3.truncate_once.add(new_key) - result = self.store.backup_supabase() - self.assertEqual(result["source_key"], new_key) - self.assertRegex( - result["name"], - r"^supabase-\d{8}T\d{6}Z-" + re.escape(new_key.rsplit("/", 1)[-1]) + r"$", - ) - self.assertEqual(result["sha256"], hashlib.sha256(newest).hexdigest()) - folders = self.store.ensure_folders() - meta = self.fake.file_meta[result["drive_file_id"]] - self.assertEqual(meta["parents"], [folders["db-backups/supabase"]]) - # byte-count verification did its job: the filed copy is the - # whole object, not the truncated first response - self.assertEqual(self.fake.files[result["drive_file_id"]], newest) - self.assertGreaterEqual(len(self.s3.get_requests(new_key)), 2) - - def test_no_backup_objects_errors(self): - self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-22T02:00:00.000Z") - with self.assertRaises(cold_store.ColdStoreError): - self.store.backup_supabase() +class TestS3GetObject(S3TestBase): + def test_truncated_first_get_is_retried_and_byte_verified(self): + body = b"newest backup payload " * 60 + key = self.key_for(hashlib.sha256(body).hexdigest()) + self.s3.put(key, body, "2026-10-21T02:00:00.000Z") + # the first GET arrives truncated (the live proxy failure mode); + # the client must retry the whole GET + self.s3.truncate_once.add(key) + data = self.store.s3_get_object("supabase-backups", key, expected_size=len(body)) + self.assertEqual(data, body) + self.assertGreaterEqual(len(self.s3.get_requests(key)), 2) class TestS3CurlFallback(S3TestBase): @@ -2359,11 +2372,13 @@ def fake_fetch(url, access, secret): return mock.patch.object(self.store, "_curl_fetch", fake_fetch), calls - def test_fallback_after_urllib_exhaustion_files_backup(self): + def test_fallback_after_urllib_exhaustion_delivers_object(self): key = self._persistent_truncation() patcher, calls = self._stub_curl(self.BODY) with patcher: - result = self.store.backup_supabase() + data = self.store.s3_get_object( + "supabase-backups", key, expected_size=len(self.BODY) + ) # exactly one curl attempt, and only after urllib was fully # exhausted: S3_GET_ATTEMPTS outer loops, each burning # S3_TRANSPORT_ATTEMPTS transport attempts on the object GET @@ -2374,25 +2389,23 @@ def test_fallback_after_urllib_exhaustion_files_backup(self): ) self.assertTrue(calls[0]["url"].endswith("/" + key)) self.assertEqual(calls[0]["access"], "test-access-key") - # the fallback body was byte-verified and filed whole - self.assertEqual(result["source_key"], key) - self.assertEqual(result["sha256"], hashlib.sha256(self.BODY).hexdigest()) - self.assertEqual(self.fake.files[result["drive_file_id"]], self.BODY) + # the fallback body was byte-verified and delivered whole + self.assertEqual(data, self.BODY) - def test_short_curl_body_named_error_nothing_filed(self): + def test_short_curl_body_named_error(self): key = self._persistent_truncation() - files_before = dict(self.fake.files) patcher, calls = self._stub_curl(self.BODY[:100]) with patcher: with self.assertRaises(cold_store.ColdStoreError) as ctx: - self.store.backup_supabase() + self.store.s3_get_object( + "supabase-backups", key, expected_size=len(self.BODY) + ) self.assertEqual(len(calls), 1) message = str(ctx.exception) self.assertIn("supabase-backups", message) self.assertIn(key, message) self.assertIn("curl fallback delivered 100 of", message) self.assertNotIn("test-secret-key", message) - self.assertEqual(self.fake.files, files_before) def test_curl_never_invoked_on_urllib_happy_path(self): body = b"small backup " * 20 @@ -2400,9 +2413,9 @@ def test_curl_never_invoked_on_urllib_happy_path(self): self.s3.put(key, body, "2026-10-21T02:00:00.000Z") patcher, calls = self._stub_curl(body) with patcher: - result = self.store.backup_supabase() + data = self.store.s3_get_object("supabase-backups", key, expected_size=len(body)) self.assertEqual(calls, []) - self.assertEqual(result["sha256"], hashlib.sha256(body).hexdigest()) + self.assertEqual(data, body) def test_curl_fetch_keeps_credentials_out_of_argv(self): """The spawned curl argv must never carry the credentials @@ -2451,8 +2464,8 @@ class TestS3RequestCurlFallback(S3TestBase): """The curl fallback inside _s3_request for GET-class requests: on a hostile-proxy night (live 2026-10-28) EVERY urllib attempt at the bucket LIST truncated at a different offset, so the - transport retry loop exhausted and backup-supabase / evict-scan - died before their first object — the object-download fallback in + transport retry loop exhausted and evict-scan + died before its first object — the object-download fallback in TestS3CurlFallback never got a chance to run. A GET whose urllib attempts all fail at the transport level now gets exactly one curl attempt (stubbed here at the _curl_fetch_status transport @@ -2520,26 +2533,6 @@ def test_list_truncated_on_all_attempts_falls_back_to_curl(self): self.assertEqual(calls[0]["access"], "test-access-key") self.assertEqual(self.s3.list_attempts, cold_store.S3_TRANSPORT_ATTEMPTS) - def test_backup_supabase_proceeds_when_list_falls_back(self): - body = b"newest backup payload " * 60 - key = self.key_for(hashlib.sha256(body).hexdigest()) - self.s3.put(key, body, "2026-10-21T02:00:00.000Z") - self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-22T02:00:00.000Z") - self.s3.list_failures = ["truncate"] * cold_store.S3_TRANSPORT_ATTEMPTS - xml = self._list_xml( - [ - (key, len(body), "2026-10-21T02:00:00.000Z"), - ("pg/muse-dev/manifest.json", 2, "2026-10-22T02:00:00.000Z"), - ] - ) - patcher, calls = self._stub_curl_status((200, xml)) - with patcher: - result = self.store.backup_supabase() - self.assertEqual(len(calls), 1) - self.assertEqual(result["source_key"], key) - self.assertEqual(result["sha256"], hashlib.sha256(body).hexdigest()) - self.assertEqual(self.fake.files[result["drive_file_id"]], body) - def test_curl_http_error_surfaces_as_s3_error_not_transport(self): self.s3.put("pg/muse-dev/a.bin", b"x", "2026-10-01T00:00:00.000Z") self.s3.list_failures = ["truncate"] * cold_store.S3_TRANSPORT_ATTEMPTS @@ -2877,25 +2870,6 @@ def test_valid_page_pagination_and_stamp_unchanged(self): self.assertEqual(token, "tok2") -class TestOffsetLessBackupPick(S3TestBase): - """backup_supabase picks the newest by LastModified with max(): - a mixed listing used to crash the pick outright (#2110).""" - - def test_newest_pick_ignores_offset_less_stamp(self): - aware_body = b"aware backup payload " * 10 - aware_key = self.key_for(hashlib.sha256(aware_body).hexdigest()) - naive_body = b"naive backup payload " * 10 - naive_key = self.key_for(hashlib.sha256(naive_body).hexdigest()) - self.s3.put(aware_key, aware_body, "2026-10-21T02:00:00.000Z") - # a later wall-clock reading, but its zone is unknown, so it - # is not evidence of newness and must not win the pick - self.s3.put(naive_key, naive_body, "2026-10-23T02:00:00.000") - self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-22T02:00:00.000Z") - result = self.store.backup_supabase() - self.assertEqual(result["source_key"], aware_key) - self.assertEqual(result["sha256"], hashlib.sha256(aware_body).hexdigest()) - - class TestEvictApply(EvictTestBase): def test_apply_deletes_only_evictable_and_records(self): scan = self.store.evict_scan(min_age_days=14, keep_newest=2) @@ -3851,8 +3825,8 @@ def test_drive_fresh_token_stream_hits_page_bound(self): mock.patch.object(self.store, "_auth_headers", lambda: {}), ): with self.assertRaises(cold_store.ColdStoreError) as ctx: - self.store.list_backups("supabase") - self.assertIn("supabase", str(ctx.exception)) + self.store.list_backups("d1") + self.assertIn("d1", str(ctx.exception)) self.assertEqual(calls["n"], 5) def test_drive_result_bound_trips(self): @@ -3868,7 +3842,7 @@ def test_drive_result_bound_trips(self): mock.patch.object(self.store, "_auth_headers", lambda: {}), ): with self.assertRaises(cold_store.ColdStoreError): - self.store.list_backups("supabase") + self.store.list_backups("d1") class TestListingBounds6602S3(S3TestBase): diff --git a/pkgs/cold-store-reaper/tests/test_nightly_backup.py b/pkgs/cold-store-reaper/tests/test_nightly_backup.py index 2f711a45da..4c79931e73 100644 --- a/pkgs/cold-store-reaper/tests/test_nightly_backup.py +++ b/pkgs/cold-store-reaper/tests/test_nightly_backup.py @@ -113,14 +113,6 @@ def test_all_steps_ok_exits_zero(self): self.assertIn("step prune-backups: ok", result.stdout) self.assertIn("step sync-manifest: ok", result.stdout) - def test_supabase_filing_is_retired_even_with_r2_credentials(self): - # The Supabase project was replaced by Turso; R2 credentials in - # the environment must not bring the nightly filing back. - result = self.run_script() - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("backup-supabase", self.calls()) - self.assertNotIn("backup-supabase", result.stdout + result.stderr) - def test_long_status_output_still_ok_and_truncated(self): # Regression: status printing >20 lines must not trip pipefail/SIGPIPE. # The verdict depends only on cold-store's own exit code; display is diff --git a/pkgs/fleet/crates/fleet-queue/src/backoff.rs b/pkgs/fleet/crates/fleet-queue/src/backoff.rs index c2325827fe..733fa0e8d7 100644 --- a/pkgs/fleet/crates/fleet-queue/src/backoff.rs +++ b/pkgs/fleet/crates/fleet-queue/src/backoff.rs @@ -2,10 +2,8 @@ //! error class (#6450 posture, enacted on Drew's 2026-11-06 ruling: //! "formalized client backoff on 57014", pass-2 proposal item 3). //! -//! One policy, used by both ends of the queue path so lanes stop -//! improvising their own retry shapes: -//! - the queue-broker's PostgREST caller (queue_broker::State), and -//! - the repo-queue client's broker caller (client::call). +//! One policy, used by the repo-queue client's broker caller +//! (client::call) so lanes stop improvising their own retry shapes. //! //! Retryable class: the PostgreSQL statement-timeout code `57014` //! ("canceling statement due to statement timeout") and PostgREST's diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index ba44cf191a..39d80529bd 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -13,7 +13,7 @@ //! role picks the broker's Unix socket when it answers; an absent //! or stale socket keeps the session-proxy route, and a failed //! UDS attempt falls back to it within the same call. -//! No Bitwarden fetch, no direct Supabase access. Exit 3 means the +//! No Bitwarden fetch, no direct database access. Exit 3 means the //! broker path itself is unavailable. //! //! Entry points: the fleet binary's queue domain and the standalone @@ -1190,10 +1190,6 @@ mod tests { // limit is below the matching count says so; an exhaustive // listing reports completeness; an unknown total is null, // never a fabricated zero. - assert_eq!(content_range_total("0-49/237"), Some(237)); - assert_eq!(content_range_total("*/0"), Some(0)); - assert_eq!(content_range_total("0-49/*"), None); - assert_eq!(content_range_total("garbage"), None); let rows = json!([{"id": 1}, {"id": 2}]); let limited = list_envelope(rows.clone(), Some(5), 0); assert_eq!(limited["total"], json!(5)); diff --git a/pkgs/fleet/crates/fleet-queue/src/client/support.rs b/pkgs/fleet/crates/fleet-queue/src/client/support.rs index 42bef78878..7eaed3677f 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/support.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/support.rs @@ -586,14 +586,6 @@ pub(crate) fn list_rows(resp: &Value) -> Result, String> { }) } -/// The total in a PostgREST `Content-Range` header (#10376): -/// `0-49/237` -> 237, `*/0` -> 0. A `*` total (no count was -/// requested) or an unparseable header yields None — unknown, -/// never a fabricated zero. -pub(crate) fn content_range_total(content_range: &str) -> Option { - content_range.rsplit('/').next()?.trim().parse::().ok() -} - /// The /list reply envelope (#10376; contract #6622 rule 3 — /// complete, bounded, or say so): alongside the rows, the total /// number of matching tasks when the backend knows it (null when diff --git a/pkgs/fleet/crates/fleet-queue/src/fallback.rs b/pkgs/fleet/crates/fleet-queue/src/fallback.rs index 323b6df4c4..625779055b 100644 --- a/pkgs/fleet/crates/fleet-queue/src/fallback.rs +++ b/pkgs/fleet/crates/fleet-queue/src/fallback.rs @@ -2,7 +2,7 @@ //! ordered 2026-11-06; tracking issue developing-today/code#6619's //! outage is the motivating incident). //! -//! When the queue backend (queue-broker → Supabase PostgREST) is +//! When the queue backend (queue-broker → Turso fleet-queue) is //! unreachable, the queue's workers starve: they cannot claim, and the //! fleet's work sits in GitHub issues doing nothing. Fallback mode //! moves the queue's coordination surface into the issues themselves, diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index e08ce2c233..ac54eca5a0 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -1,8 +1,6 @@ //! queue-broker — the repo-health queue as a resident laptop service -//! (code#5362). Server-side port of repo-queue.py's HTTP layer: the -//! Supabase service-role key lives only here, fetched from the -//! secrets broker; all queue semantics stay in the Postgres RPCs. -//! Sandbox clients reach it only through the session proxy. +//! (code#5362). Sandbox clients reach it only through the session +//! proxy. //! //! Protocol: POST / with a JSON args object; response is a //! JSON envelope {ok:true, ...} or {ok:false, exit, error} where exit @@ -17,86 +15,24 @@ //! or unix:// for the secrets broker's socket, #6218), //! QUEUE_BROKER_SECRETS_TOKEN_FILE (default ~/.config/secrets-broker/token). //! -//! Backend (#6741): QUEUE_BROKER_BACKEND=postgres (default; the -//! Supabase PostgREST path above) or =turso — the queue core on the -//! dedicated Turso DB `fleet-queue` (crate::turso_queue), selected by -//! QUEUE_BROKER_TURSO_URL / QUEUE_BROKER_TURSO_TOKEN_FILE. The -//! production default does not flip with the code; cutover is -//! doc/fleet/queue-turso-cutover.md. +//! Backend: the queue core on the dedicated Turso DB `fleet-queue` +//! (crate::turso_queue), at QUEUE_BROKER_TURSO_URL with the token +//! from QUEUE_BROKER_TURSO_TOKEN_FILE or the secrets broker. Turso is +//! the only backend: QUEUE_BROKER_BACKEND may be unset or `turso`; +//! any other value is a startup config error (exit 3). -use std::sync::{Arc, Mutex, RwLock}; -use std::time::{Duration, Instant}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; use fleet_secrets::{Resolver, SecretError, SecretSource, SecretValue}; use serde_json::{Value, json}; use tiny_http::{Header, Response, Server, StatusCode}; -const PILOT_REPO: &str = "developing-today/code"; - -/// #6450 posture (Drew ruling 2026-11-06): broker-side health cache -/// TTL — inside the recorded 10-15 s band. Simultaneous lane gate -/// calls collapse to one `repo_queue_health` view read per TTL -/// window instead of one read per lane. -const HEALTH_CACHE_TTL: Duration = Duration::from_secs(12); - -/// #6450 posture: enqueue pacing token bucket — a burst allowance, -/// then a sustained refill rate. A producer burst of N tasks now -/// spreads over ~(N - burst) / refill seconds against agent.tasks -/// instead of landing inside a single second while claims are in -/// flight (the 12:22Z burst that preceded the 12:23Z window). -/// Single enqueues are unaffected while the bucket holds tokens. -const ENQUEUE_BURST: f64 = 20.0; -const ENQUEUE_REFILL_PER_SEC: f64 = 20.0; - -#[derive(Clone)] -struct Creds { - key: String, - base: String, // project URL, no trailing slash -} - -/// One cached `/health` read: the rows of the `repo_queue_health` -/// view for one queue filter (the key), and when they were fetched. -struct HealthCacheEntry { - key: String, - at: Instant, - rows: Value, -} - -/// Token-bucket state for enqueue pacing (see ENQUEUE_BURST). -struct EnqueueGate { - tokens: f64, - last: Instant, -} - -impl EnqueueGate { - fn new() -> Self { - Self { - tokens: ENQUEUE_BURST, - last: Instant::now(), - } - } -} - struct State { secrets_url: String, secrets_token: String, - creds: RwLock>, agent: ureq::Agent, - health_cache: RwLock>, - enqueue_gate: Mutex, - failure_events_path: Option, - /// #6741: Some when QUEUE_BROKER_BACKEND=turso; dispatch routes - /// every verb except /validate + /healthz to the Turso backend. - turso: Option, -} - -struct BErr { - exit: i32, - msg: String, -} - -fn err4(msg: String) -> BErr { - BErr { exit: 4, msg } + turso: crate::turso_queue::TursoBackend, } /// The queue broker's secrets-by-name source: a direct HTTP call to @@ -239,306 +175,10 @@ fn default_secrets_url(explicit: Option) -> String { } } -impl State { - fn fetch_creds(&self) -> Result { - // Secrets resolve by name through the platform crate - // (fleet-secrets, design §1): the one-off HTTP exchange with - // the colocated secrets broker is a SecretSource, and the - // names flow through validate_name / SecretValue / the chain - // error shape like every other fleet consumer. - let resolver = Resolver::new(vec![Box::new(DirectSecrets { - url: self.secrets_url.clone(), - token: self.secrets_token.clone(), - agent: self.agent.clone(), - })]); - let get_secret = |name: &str| -> Result { - resolver - .resolve(name) - .map(|v| v.expose().to_string()) - .map_err(|e| BErr { - exit: 3, - msg: e.to_string(), - }) - }; - // Startup race: the secrets broker may still be doing its first - // vault load; retry 503s for up to ~60 s. - let mut last_err = None; - for _ in 0..20 { - match ( - get_secret("supabase.muse-dev2.service-role-key"), - get_secret("supabase.muse-dev2.project-url"), - ) { - (Ok(key), Ok(url)) => { - let creds = Creds { - key, - base: url.trim_end_matches('/').to_string(), - }; - *self.creds.write().unwrap() = Some(creds.clone()); - return Ok(creds); - } - (Err(e), _) | (_, Err(e)) => { - let retryable = e.msg.contains("503"); - last_err = Some(e); - if !retryable { - break; - } - std::thread::sleep(Duration::from_secs(3)); - } - } - } - Err(last_err.unwrap_or(BErr { - exit: 3, - msg: "credential fetch failed".into(), - })) - } - - fn creds(&self) -> Result { - if let Some(c) = self.creds.read().unwrap().clone() { - return Ok(c); - } - self.fetch_creds() - } - - /// One PostgREST request (a single credential-refresh cycle). - /// Returns (parsed body, content-range). The retry posture lives - /// in the `postgrest` wrapper below. - fn postgrest_once( - &self, - method: &str, - path: &str, - body: Option<&Value>, - count_exact: bool, - ) -> Result<(Value, Option), BErr> { - for attempt in 0..2 { - let creds = self.creds()?; - let url = format!("{}/rest/v1/{}", creds.base, path); - let bearer = format!("Bearer {}", creds.key); - let mut headers: Vec<(&str, &str)> = vec![ - ("apikey", &creds.key), - ("Authorization", &bearer), - ("Accept-Profile", "agent"), - ]; - if method != "GET" { - headers.push(("Content-Profile", "agent")); - headers.push(("Content-Type", "application/json")); - } - if count_exact { - headers.push(("Prefer", "count=exact")); - } - // ureq's builders are typestated (WithBody vs WithoutBody), - // so each arm applies the same header set itself. - let sent = match (method, body) { - ("GET", _) => { - let mut r = self.agent.get(&url); - for (k, v) in &headers { - r = r.header(*k, *v); - } - r.call() - } - (_, Some(b)) => { - let mut r = self.agent.post(&url); - for (k, v) in &headers { - r = r.header(*k, *v); - } - r.send_json(b.clone()) - } - (_, None) => { - let mut r = self.agent.post(&url); - for (k, v) in &headers { - r = r.header(*k, *v); - } - r.send("") - } - }; - let mut resp = sent.map_err(|e| err4(format!("PostgREST request failed: {e}")))?; - let status = resp.status().as_u16(); - let content_range = resp - .headers() - .get("content-range") - .and_then(|v| v.to_str().ok()) - .map(|s| s.to_string()); - let text = resp.body_mut().read_to_string().unwrap_or_default(); - if status == 401 && attempt == 0 { - // Key may have rotated: refetch from the secrets broker. - *self.creds.write().unwrap() = None; - continue; - } - if status >= 300 { - return Err(err4(format!( - "HTTP {status} from PostgREST: {}", - trim(text.trim(), 500) - ))); - } - let parsed = if text.trim().is_empty() { - Value::Null - } else { - serde_json::from_str(&text) - .map_err(|e| err4(format!("PostgREST returned non-JSON: {e}")))? - }; - return Ok((parsed, content_range)); - } - Err(err4( - "PostgREST request failed after credential refresh".into(), - )) - } - - /// PostgREST with the #6450 posture backoff (crate::backoff): - /// 57014 / PGRST002-class failures retry under the shared - /// policy. A final failure of that class is also the standing - /// capture's trigger: it is appended to the failure-events file - /// for the capture job to mine (arm (a) of the #6450 ruling). - fn postgrest( - &self, - method: &str, - path: &str, - body: Option<&Value>, - count_exact: bool, - ) -> Result<(Value, Option), BErr> { - let mut attempt: u32 = 0; - loop { - match self.postgrest_once(method, path, body, count_exact) { - Ok(v) => return Ok(v), - Err(e) => { - if !crate::backoff::is_retryable(&e.msg) { - return Err(e); - } - if attempt + 1 >= crate::backoff::MAX_ATTEMPTS { - self.record_failure_event(path, &e.msg, attempt + 1); - return Err(e); - } - let slept = crate::backoff::sleep_after_failure(attempt); - crate::log::info( - "queue-broker", - &format!( - "postgrest {path} 57014-class failure (attempt {}): {}; backing off {}ms", - attempt + 1, - trim(&e.msg, 160), - slept.as_millis() - ), - ); - attempt += 1; - } - } - } - } - - /// Append one failure-window record for the standing capture. - /// Best-effort: a logging failure never fails a request. - fn record_failure_event(&self, path: &str, msg: &str, attempts: u32) { - crate::log::info( - "queue-broker", - &format!( - "failure window: postgrest {path} exhausted backoff after {attempts} attempts: {}", - trim(msg, 200) - ), - ); - let Some(file) = &self.failure_events_path else { - return; - }; - let ts_epoch = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - let health_age_ms = self - .health_cache - .read() - .unwrap() - .as_ref() - .map(|e| e.at.elapsed().as_millis() as u64); - let line = json!({ - "ts_epoch": ts_epoch, - "path": path, - "attempts": attempts, - "error": trim(msg, 300), - "health_cache_age_ms": health_age_ms, - }); - if let Ok(mut f) = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(file) - { - use std::io::Write; - let _ = writeln!(f, "{line}"); - } - } - - /// The cached health rows for `key` when fresher than the TTL, - /// with their age in milliseconds. - fn health_cache_get(&self, key: &str) -> Option<(Value, u64)> { - let guard = self.health_cache.read().unwrap(); - let entry = guard.as_ref()?; - if entry.key != key { - return None; - } - let age = entry.at.elapsed(); - if age > HEALTH_CACHE_TTL { - return None; - } - Some((entry.rows.clone(), age.as_millis() as u64)) - } - - fn health_cache_put(&self, key: &str, rows: Value) { - *self.health_cache.write().unwrap() = Some(HealthCacheEntry { - key: key.to_string(), - at: Instant::now(), - rows, - }); - } - - /// #6450 posture: pace the enqueue RPC through the token bucket - /// (burst ENQUEUE_BURST, refilled at ENQUEUE_REFILL_PER_SEC). - fn pace_enqueue(&self) { - loop { - let wait = { - let mut g = self.enqueue_gate.lock().unwrap(); - let now = Instant::now(); - let elapsed = now.duration_since(g.last).as_secs_f64(); - g.tokens = (g.tokens + elapsed * ENQUEUE_REFILL_PER_SEC).min(ENQUEUE_BURST); - g.last = now; - if g.tokens >= 1.0 { - g.tokens -= 1.0; - return; - } - Duration::from_secs_f64((1.0 - g.tokens) / ENQUEUE_REFILL_PER_SEC) - }; - std::thread::sleep(wait.min(Duration::from_millis(100))); - } - } - - fn rpc(&self, fn_name: &str, args: Value) -> Result { - let (v, _) = self.postgrest("POST", &format!("rpc/{fn_name}"), Some(&args), false)?; - Ok(v) - } -} - fn trim(s: &str, n: usize) -> String { s.chars().take(n).collect() } -/// Percent-encode like Python urllib quote(s, safe). -fn quote(s: &str, safe: &str) -> String { - let mut out = String::new(); - for b in s.bytes() { - let c = b as char; - if c.is_ascii_alphanumeric() || "-._~".contains(c) || safe.contains(c) { - out.push(c); - } else { - out.push_str(&format!("%{b:02X}")); - } - } - out -} - -/// The `/list` limit, validated before it is interpolated into the -/// PostgREST path (#6419): an out-of-range value from any client is -/// rejected with the same usage error the client itself raises -/// (design #6448 Phase 3: reject, not clamp). Absent means the -/// existing default of 20. -fn list_limit(req: &Value) -> Result { - let raw = req.get("limit").and_then(|l| l.as_i64()); - crate::client::list_limit_or_default(raw) -} - /// One duration field of a request, validated before the RPC /// (#6420): the broker is the trust boundary for non-CLI callers, so /// an out-of-range value is rejected with the same usage error the @@ -595,11 +235,8 @@ fn delay_seconds(req: &Value) -> Result, String> { } /// The duration guard for one request path (#6420), run at the top -/// of `dispatch` BEFORE backend selection: the Turso backend -/// dispatches verbatim, so validating only inside the PostgREST -/// handlers would leave the trust boundary open on that backend -/// (Codex finding on PR #8425). The PostgREST handlers keep their -/// own checks as defense in depth. +/// of `dispatch`: the broker is the trust boundary for non-CLI +/// callers, and the Turso backend dispatches verbatim. fn validate_durations(path: &str, req: &Value) -> Result<(), String> { match path { "/claim" | "/claim-flow" => lease_seconds(req).map(|_| ()), @@ -642,47 +279,6 @@ fn fail(exit: i32, msg: impl Into) -> Value { json!({"ok": false, "exit": exit, "error": msg.into()}) } -fn record_execution(st: &State, req: &Value, row: &Value) -> Result, BErr> { - let Some(ex) = req.get("execution").filter(|e| e.is_object()) else { - return Ok(None); - }; - let ledger = st.rpc( - "record_repo_task_lane_execution", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_executed_lane": ex.get("lane"), - "p_fallback_reason": ex.get("fallback_reason"), - "p_session_id": ex.get("session_id"), - }), - )?; - let _ = row; - Ok(Some(ledger)) -} - -/// Verbs whose RPC takes the args object nearly verbatim. -fn simple_rpc(st: &State, fn_name: &str, args: Value) -> Value { - match st.rpc(fn_name, args) { - Ok(row) => ok(json!({"row": row})), - Err(e) => fail(e.exit, e.msg), - } -} - -fn verb_with_execution(st: &State, fn_name: &str, args: Value, req: &Value) -> Value { - let row = match st.rpc(fn_name, args) { - Ok(r) => r, - Err(e) => return fail(e.exit, e.msg), - }; - if row.is_null() { - return ok(json!({"row": Value::Null})); - } - match record_execution(st, req, &row) { - Ok(Some(ledger)) => ok(json!({"row": row, "lane_ledger": ledger})), - Ok(None) => ok(json!({"row": row})), - Err(e) => fail(e.exit, e.msg), - } -} - /// The GitHub token the dep rechecker authenticates with, /// resolved by name through the secrets broker like every other /// broker credential (#8276). @@ -950,437 +546,22 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value { if let Err(e) = validate_request_not_before(path, req) { return fail(2, e); } - if let Some(t) = &st.turso { - if path != "/validate" && path != "/healthz" { - let resp = crate::turso_queue::dispatch(t, path, req); - // #8568: the Turso backend answers /block before the - // Postgres match below, so the broker-side needs-drew - // raise hooks here too — same condition, same helper. - if path == "/block" { - maybe_raise_needs_drew(st, req, &resp); - } - return resp; - } - } match path { "/validate" => { let packet = req.get("packet").cloned().unwrap_or(Value::Null); let (errors, warnings) = crate::validate::validate_packet(&packet); ok(json!({"errors": errors, "warnings": warnings})) } - "/enqueue" => { - let packet = req.get("packet").cloned().unwrap_or(Value::Null); - let (errors, warnings) = crate::validate::validate_packet(&packet); - if !errors.is_empty() { - return json!({ - "ok": false, "exit": 2, - "error": format!("packet validation failed ({} error(s))", errors.len()), - "errors": errors, "warnings": warnings, - }); - } - let queue = req - .get("queue") - .and_then(|q| q.as_str()) - .unwrap_or("") - .to_string(); - let task = crate::validate::task_from_packet(&packet, &queue); - if req - .get("dry_run") - .and_then(|d| d.as_bool()) - .unwrap_or(false) - { - return ok(json!({"dry_run": true, "task": task, "warnings": warnings})); - } - let repo = packet - .get("payload") - .and_then(|p| p.get("repo")) - .and_then(|r| r.as_str()) - .map(|s| s.to_string()); - let rpc_name = match repo.as_deref() { - None | Some(PILOT_REPO) => "enqueue_repo_task", - _ => "enqueue_repo_task_fleet", - }; - let args = json!({ - "p_queue": task.get("queue"), - "p_title": task.get("title"), - "p_body": task.get("body"), - "p_payload": task.get("payload"), - "p_dedupe_key": task.get("dedupe_key"), - "p_priority": task.get("priority"), - "p_not_before": task.get("not_before"), - "p_max_attempts": task.get("max_attempts"), - }); - st.pace_enqueue(); - match st.rpc(rpc_name, args) { - Ok(row) if !row.is_null() => { - ok(json!({"row": row, "rpc": rpc_name, "warnings": warnings})) - } - Ok(_) => fail(5, format!("{rpc_name} returned no row")), - Err(e) => fail(e.exit, e.msg), - } - } - "/claim" => { - let lease = match lease_seconds(req) { - Ok(v) => v, - Err(e) => return fail(2, e), - }; - let mut args = json!({ - "p_worker": req.get("worker"), - "p_queue": req.get("queue"), - "p_lease_seconds": lease, - }); - if let Some(lane) = req.get("lane").filter(|l| !l.is_null()) { - args["p_lane_id"] = lane.clone(); - } - simple_rpc(st, "claim_repo_task", args) - } - "/claim-flow" => { - // #5757-A: claim + lane-assign + session-bind in one - // broker round trip. Each step is the corresponding - // single-verb RPC with the same arguments the three - // verbs pass. A claim-step failure — or an empty claim — - // returns that step's answer verbatim and later steps - // are not attempted (the three-verb flow's semantics, - // one trip). A LANE/BIND failure is different: the claim - // RPC has already COMMITTED, so it answers as a partial - // success (ok envelope + claimed row + - // `claim_flow_partial`), never as an error — a retryable - // error here (57014 / PGRST002) would make the client's - // call_result replay the WHOLE flow and claim a second - // task, leaking this one (Codex P1 on PR #8493). The - // caller finishes the failed step with the single-verb - // /lane or /bind call for this task id. The answer - // carries every step's row: - // `row` is the claimed task row (the shape /claim - // answers and the client's claim_output consumes); - // `lane_row` / `bind_row` are what /lane and /bind - // answer in the three-verb flow. - let lease = match lease_seconds(req) { - Ok(v) => v, - Err(e) => return fail(2, e), - }; - if let Err(e) = crate::client::claim_flow_precheck(req) { - return fail(2, e); - } - let mut args = json!({ - "p_worker": req.get("worker"), - "p_queue": req.get("queue"), - "p_lease_seconds": lease, - }); - if let Some(lane) = req.get("lane").filter(|l| !l.is_null()) { - args["p_lane_id"] = lane.clone(); - } - let row = match st.rpc("claim_repo_task", args) { - Ok(row) => row, - Err(e) => return fail(e.exit, e.msg), - }; - if row.is_null() { - return ok(json!({"row": row})); - } - let task_id = row.get("id").cloned().unwrap_or(Value::Null); - let lane_row = match st.rpc( - "assign_repo_task_lane", - json!({ - "p_task_id": task_id, - "p_worker": req.get("worker"), - "p_exclusion_reason": req.get("exclusion_reason"), - }), - ) { - Ok(r) => r, - Err(e) => { - return ok(json!({ - "row": row, - "claim_flow_partial": { - "step": "lane", - "exit": e.exit, - "error": e.msg, - }, - })); - } - }; - let bind_row = match st.rpc( - "bind_repo_task_lane_session", - json!({ - "p_task_id": task_id, - "p_worker": req.get("worker"), - "p_session_id": req.get("session_id"), - "p_launched_by": req.get("launched_by"), - }), - ) { - Ok(r) => r, - Err(e) => { - return ok(json!({ - "row": row, - "lane_row": lane_row, - "claim_flow_partial": { - "step": "bind", - "exit": e.exit, - "error": e.msg, - }, - })); - } - }; - ok(json!({"row": row, "lane_row": lane_row, "bind_row": bind_row})) - } - "/lane" => simple_rpc( - st, - "assign_repo_task_lane", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_exclusion_reason": req.get("exclusion_reason"), - }), - ), - "/bind" => simple_rpc( - st, - "bind_repo_task_lane_session", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_session_id": req.get("session_id"), - "p_launched_by": req.get("launched_by"), - }), - ), - "/heartbeat" => { - let extend = match extend_seconds(req) { - Ok(v) => v, - Err(e) => return fail(2, e), - }; - simple_rpc( - st, - "heartbeat_task", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_extend_seconds": extend, - "p_progress": req.get("progress"), - }), - ) - } - "/checkpoint" => simple_rpc( - st, - "checkpoint_task", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_stage": req.get("stage"), - "p_progress": req.get("progress").cloned().unwrap_or(json!({})), - }), - ), - "/park" => { - let delay = match delay_seconds(req) { - Ok(v) => v, - Err(e) => return fail(2, e), - }; - let mut args = json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_reason": req.get("reason"), - "p_progress": req.get("progress").cloned().unwrap_or(json!({})), - }); - if let Some(nb) = req.get("not_before").filter(|v| !v.is_null()) { - args["p_not_before"] = nb.clone(); - } else if let Some(d) = delay { - args["p_delay_seconds"] = json!(d); - } - if let Some(rc) = req.get("ready_condition").filter(|v| !v.is_null()) { - args["p_ready_condition"] = rc.clone(); + "/healthz" => ok(json!({"service": "queue-broker"})), + _ => { + let resp = crate::turso_queue::dispatch(&st.turso, path, req); + // #8568: the broker-side needs-drew raise for an + // escalated block (fire-and-forget). + if path == "/block" { + maybe_raise_needs_drew(st, req, &resp); } - verb_with_execution(st, "park_task", args, req) - } - "/block" => { - let resp = simple_rpc( - st, - "block_task", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_reason_class": req.get("reason_class"), - "p_blocker": req.get("blocker"), - "p_progress": req.get("progress").cloned().unwrap_or(json!({})), - }), - ); - // #8568: broker-side needs-drew raise, fire-and-forget - // (see maybe_raise_needs_drew). NOTE: this arm is the - // Postgres backend's route — dispatch() hands /block - // to the Turso backend before reaching here when - // QUEUE_BROKER_BACKEND=turso. - maybe_raise_needs_drew(st, req, &resp); resp } - "/cancel" => simple_rpc( - st, - "cancel_repo_task", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_reason": req.get("reason"), - }), - ), - "/fail" => verb_with_execution( - st, - "fail_repo_task", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_error": req.get("error"), - "p_reason_class": req.get("reason_class"), - }), - req, - ), - "/complete" => verb_with_execution( - st, - "complete_task", - json!({ - "p_task_id": req.get("task_id"), - "p_worker": req.get("worker"), - "p_result": req.get("result").cloned().unwrap_or(json!({})), - }), - req, - ), - "/list" => { - let queue = req.get("queue").and_then(|q| q.as_str()).unwrap_or(""); - let limit = match list_limit(req) { - Ok(limit) => limit, - Err(e) => return fail(2, e), - }; - // `rich` adds the claim/binding fields the on-laptop - // opencode claimant's poll.py needs (it reads through the - // broker since the binary-direct migration retired the - // Python helper it used to import). - let select = if req.get("rich").and_then(|r| r.as_bool()).unwrap_or(false) { - "id,queue,title,priority,status,dedupe_key,created_at,not_before,worker_id,lease_until,lane_id,attempts,max_attempts,progress,payload" - } else { - "id,queue,title,priority,status,dedupe_key,created_at,not_before" - }; - let offset = - crate::client::list_offset_or_default(req.get("offset").and_then(|o| o.as_i64())); - // #9420 parity with the Turso verb_list: omit the queue - // predicate when no queue is named (queue=eq. with an - // empty value matches nothing and breaks exact readback). - let queue_pred = if queue.is_empty() { - String::new() - } else { - format!("&queue=eq.{}", quote(queue, "")) - }; - let mut path = format!( - "tasks?select={select}{queue_pred}&order=priority.asc,created_at.asc,id.asc&limit={limit}&offset={offset}" - ); - // #7871: --task narrows to one task id, so a worker can - // verify a single recent completion from list output - // regardless of the done list's size or ordering. - if let Some(t) = req.get("task").and_then(|t| t.as_i64()) { - path += &format!("&id=eq.{t}"); - } - if let Some(s) = req.get("status").and_then(|s| s.as_str()) { - path += &format!("&status=eq.{}", quote(s, "")); - } - // #9420: dedupe_key narrows to the task carrying that key. - if let Some(d) = req.get("dedupe_key").and_then(|d| d.as_str()) { - path += &format!("&dedupe_key=eq.{}", quote(d, "")); - } - if let Some(nb) = req.get("not_before").and_then(|s| s.as_str()) { - path += &format!("&or=(not_before.is.null,not_before.lte.{})", quote(nb, ":")); - } - // #5444: --lane/--worker list filters, PostgREST side - // (the Turso verb_list applies the same filters). - if let Some(l) = req.get("lane").and_then(|s| s.as_str()) { - path += &format!("&lane_id=eq.{}", quote(l, "")); - } - if let Some(w) = req.get("worker").and_then(|s| s.as_str()) { - path += &format!("&worker_id=eq.{}", quote(w, "")); - } - // #10376: request the exact count so the reply can - // name its total — without count=exact the - // Content-Range total is `*` and a limited listing - // reads as complete. - match st.postgrest("GET", &path, None, true) { - Ok((rows, content_range)) => { - let total = content_range - .as_deref() - .and_then(crate::client::content_range_total); - ok(crate::client::list_envelope(rows, total, offset)) - } - Err(e) => fail(e.exit, e.msg), - } - } - "/health" => { - let creds = match st.creds() { - Ok(c) => c, - Err(e) => return fail(e.exit, e.msg), - }; - let netloc = creds - .base - .split("://") - .nth(1) - .unwrap_or(&creds.base) - .split('/') - .next() - .unwrap_or("") - .to_string(); - let mut path = "repo_queue_health?select=*".to_string(); - if let Some(q) = req.get("queue").and_then(|q| q.as_str()) { - path += &format!("&queue=eq.{}", quote(q, "")); - } - let cache_key = req - .get("queue") - .and_then(|q| q.as_str()) - .unwrap_or("*") - .to_string(); - if let Some((rows, age_ms)) = st.health_cache_get(&cache_key) { - return ok(json!({ - "project_netloc": netloc, - "project_source": "bitwarden", - "rows": rows, - "cache": {"hit": true, "age_ms": age_ms, "ttl_ms": HEALTH_CACHE_TTL.as_millis() as u64}, - })); - } - match st.postgrest("GET", &path, None, false) { - Ok((rows, _)) => { - st.health_cache_put(&cache_key, rows.clone()); - ok(json!({ - "project_netloc": netloc, - "project_source": "bitwarden", - "rows": rows, - "cache": {"hit": false, "ttl_ms": HEALTH_CACHE_TTL.as_millis() as u64}, - })) - } - Err(e) => fail(e.exit, e.msg), - } - } - "/signal-count" => { - let queue = req.get("queue").and_then(|q| q.as_str()).unwrap_or(""); - let path = format!( - "tasks?select=id,created_at&queue=eq.{}&status=eq.queued&order=created_at.asc&limit=1", - quote(queue, "") - ); - match st.postgrest("GET", &path, None, true) { - Ok((rows, content_range)) => { - let arr = rows.as_array().cloned().unwrap_or_default(); - let mut count = arr.len() as i64; - if let Some(cr) = content_range { - if let Some(total) = cr.rsplit('/').next() { - if let Ok(n) = total.parse::() { - count = n; - } - } - } - let oldest = arr - .first() - .and_then(|r| r.get("created_at")) - .cloned() - .unwrap_or(Value::Null); - ok(json!({"queued_count": count, "oldest_queued_at": oldest})) - } - Err(e) => fail(e.exit, e.msg), - } - } - "/stack-record" | "/stack-list" | "/stack-restack" => fail( - 2, - "merge-intent stack verbs require the turso queue backend (#8582)".to_string(), - ), - "/healthz" => ok(json!({"service": "queue-broker"})), - _ => json!({"ok": false, "exit": 2, "error": format!("unknown command {path}")}), } } @@ -1499,24 +680,21 @@ pub fn run() -> i32 { .timeout_global(Some(Duration::from_secs(90))) .build() .into(); - let failure_events_path = std::env::var("QUEUE_BROKER_FAILURE_EVENTS") - .map(std::path::PathBuf::from) - .unwrap_or_else(|_| { - std::path::PathBuf::from(format!( - "{home}/.local/state/queue-broker/failure-events.jsonl" - )) - }); - if let Some(dir) = failure_events_path.parent() { - let _ = std::fs::create_dir_all(dir); + // Turso is the only queue backend: QUEUE_BROKER_BACKEND unset + // (or empty) means turso; any other value is a config error. + if let Ok(v) = std::env::var("QUEUE_BROKER_BACKEND") { + let v = v.trim(); + if !v.is_empty() && !v.eq_ignore_ascii_case("turso") { + crate::log::info( + "queue-broker", + &format!( + "QUEUE_BROKER_BACKEND={v} is not supported; turso is the only queue backend" + ), + ); + return 3; + } } - - // #6741 backend selection: Postgres stays the default; the - // Turso backend is opt-in per broker process until the cutover - // runbook flips the unit env. - let turso = if std::env::var("QUEUE_BROKER_BACKEND") - .map(|v| v.eq_ignore_ascii_case("turso")) - .unwrap_or(false) - { + let turso = { let url = std::env::var("QUEUE_BROKER_TURSO_URL") .unwrap_or_else(|_| crate::turso_queue::DEFAULT_TURSO_URL.to_string()); let token = match std::env::var("QUEUE_BROKER_TURSO_TOKEN_FILE") { @@ -1572,19 +750,13 @@ pub fn run() -> i32 { "queue-broker", &format!("queue backend: turso ({})", backend.url()), ); - Some(backend) - } else { - None + backend }; let state = Arc::new(State { secrets_url, secrets_token, - creds: RwLock::new(None), agent, - health_cache: RwLock::new(None), - enqueue_gate: Mutex::new(EnqueueGate::new()), - failure_events_path: Some(failure_events_path), turso, }); @@ -1765,48 +937,6 @@ mod tests { ); } - #[test] - fn claim_flow_post_commit_failures_are_partial_not_errors_5757() { - // #5757-A Codex P1 oracle (PR #8493): in the PostgREST - // broker's /claim-flow handler, the lane and bind RPC - // failures answer with claim_flow_partial inside an ok - // envelope — never `return fail(...)`, whose retryable - // error text the client would replay into a second claim - // after the first claim already committed. - let src = include_str!("queue_broker.rs"); - let start = src - .find("\"/claim-flow\" => {") - .expect("claim-flow handler"); - let end = src[start..] - .find("\"/lane\" =>") - .expect("lane handler follows") - + start; - let flow = &src[start..end]; - assert_eq!( - flow.matches("\"claim_flow_partial\"").count(), - 2, - "lane and bind failures both carry claim_flow_partial" - ); - assert!( - flow.contains("\"step\": \"lane\""), - "lane partial names its step" - ); - assert!( - flow.contains("\"step\": \"bind\""), - "bind partial names its step" - ); - // The claim RPC's own `return fail(...)` is pre-commit and - // legitimate; the invariant binds everything from the lane - // RPC onward (post-commit). - let lane_at = flow - .find("assign_repo_task_lane") - .expect("lane RPC present"); - assert!( - !flow[lane_at..].contains("return fail(e.exit, e.msg)"), - "no post-claim step returns the raw retryable error" - ); - } - #[test] fn park_and_revive_not_before_are_gated_before_the_rpc() { // #6426: /park and /revive forwarded a raw not_before to the @@ -1949,23 +1079,6 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - #[test] - fn list_limit_rejects_out_of_range_before_the_postgrest_path() { - // #6419: the broker interpolated the limit unchecked, so a - // client that skipped validation (or a raw caller) could send - // 0, negatives, or an unbounded value straight to PostgREST. - for bad in [0, -1, 501, i64::MAX] { - let err = list_limit(&json!({"limit": bad})) - .err() - .expect("out-of-range limit must be rejected"); - assert!(err.contains("--limit"), "error names the flag: {err}"); - } - assert_eq!(list_limit(&json!({"limit": 1})), Ok(1)); - assert_eq!(list_limit(&json!({"limit": 500})), Ok(500)); - // Absent limit keeps the existing default of 20. - assert_eq!(list_limit(&json!({})), Ok(20)); - } - #[test] fn duration_fields_reject_out_of_range_before_the_rpc() { // #6420: a raw caller could send a born-expired lease, a @@ -2040,9 +1153,9 @@ mod tests { "error names the flag: {err}" ); } - // The dispatch-level guard covers both backends: it fires - // per path before backend selection (Codex finding on - // PR #8425), and leaves unrelated paths alone. + // The dispatch-level guard fires per path before the Turso + // dispatch (Codex finding on PR #8425), and leaves + // unrelated paths alone. assert!(validate_durations("/claim", &json!({"lease_seconds": 0})).is_err()); assert!(validate_durations("/heartbeat", &json!({"extend_seconds": -1})).is_err()); assert!(validate_durations("/park", &json!({"delay_seconds": 604_801})).is_err()); diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index f2aecdd7f4..ebdaab907e 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -1,21 +1,10 @@ //! queue-broker Turso backend — the queue core on libSQL (#6741). //! -//! The Postgres queue core (agent.tasks / leases / lanes / workers / -//! checkpoints / repo_task_lane_ledger / events in muse-dev2) was the -//! one piece of the 2026-11-04..06 migration (#5689/#5690 series) -//! deliberately kept on Postgres for transactional coupling. When -//! the muse-dev2 data plane went down on 2026-11-06 (#6619, Supabase -//! platform fault) the queue core had no live home; the GitHub -//! fallback mode (doc/fleet/queue-fallback-mode.md) carried the work. -//! This module is the dedicated-Turso replacement Drew ordered the -//! same evening: a dedicated database (`fleet-queue`, org dezren39, -//! group great-star-lord; rw token in BWS as -//! `turso.fleet-queue-rw-token`) behind the SAME broker protocol, so -//! no client changes: backend selection is the broker's config. -//! -//! Selection: `QUEUE_BROKER_BACKEND=turso` (default `postgres` — the -//! production default does NOT flip with this code; cutover is the -//! runbook in doc/fleet/queue-turso-cutover.md). URL: +//! The queue core (tasks / leases / lanes / workers / checkpoints / +//! repo_task_lane_ledger / events) on a dedicated Turso database +//! (`fleet-queue`, org dezren39, group great-star-lord; rw token in +//! BWS as `turso.fleet-queue-rw-token`) behind the broker protocol. +//! It is the queue broker's only backend. URL: //! `QUEUE_BROKER_TURSO_URL` (default the fleet-queue HTTPS URL). //! Token: `QUEUE_BROKER_TURSO_TOKEN_FILE`, else the secrets broker //! by the name above. @@ -39,8 +28,7 @@ //! stream's consumers get broker verbs here: /events-append, //! /events-seen (the event_seen ready-condition primitive), //! /events-count (observability + health), /events-prune (the -//! prune_events port). All of it exists only on this backend; the -//! Postgres dispatch is untouched. +//! prune_events port). //! //! Atomicity: libSQL is single-writer. A claim is ONE conditional //! UPDATE whose WHERE clause re-checks claimability (status in @@ -413,8 +401,7 @@ mod tests { // #9420 oracle: exact-task readback works on the Turso // verb_list — the task filter, a dedupe_key filter, and a // queue predicate that applies only when a queue is named (an - // unnamed queue must not degenerate into queue = ''). The - // PostgREST /list handler carries the same contract. + // unnamed queue must not degenerate into queue = ''). let src = &test_source(); let seg = seg8217(src, "fn verb_list(", "\nfn verb_health"); assert!( @@ -430,15 +417,6 @@ mod tests { seg.contains("if !queue.is_empty()"), "queue predicate is conditional on a named queue" ); - let broker = include_str!("queue_broker.rs"); - assert!( - broker.contains("dedupe_key=eq."), - "PostgREST /list applies the dedupe_key filter" - ); - assert!( - broker.contains("queue_pred"), - "PostgREST /list omits the queue predicate when unnamed" - ); } #[test] diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs index 2988c33413..7f8d8eb0e5 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs @@ -1366,8 +1366,7 @@ pub(crate) fn envelope_is_ok(v: &Value) -> bool { /// `claim_flow_partial` naming the failed step), never as an /// error envelope — a retryable error there would make the /// client's call_result replay the WHOLE flow and claim a -/// second task, leaking this one (Codex P1 on PR #8493; the -/// PostgREST broker in queue_broker.rs follows the same rule). +/// second task, leaking this one (Codex P1 on PR #8493). /// The caller finishes the failed step with the single-verb /// /lane or /bind call for this task id. The answer carries /// every step's row: `row` is the claimed task row (the shape diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs index 48102de828..4effa52db7 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs @@ -1008,9 +1008,9 @@ pub(crate) fn verb_outbox_metrics(t: &TursoBackend, _req: &Value) -> Value { Err(e) => terr(e), } } -/// The Turso backend's half of the broker dispatch: every verb the -/// Postgres path serves except /validate (purely local) and -/// /healthz (transport-level), which stay in queue_broker::dispatch. +/// The Turso backend's half of the broker dispatch: every verb +/// except /validate (purely local) and /healthz (transport-level), +/// which stay in queue_broker::dispatch. pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { match path { "/enqueue" => verb_enqueue(t, req), diff --git a/pkgs/fleet/crates/fleet-secrets/src/lib.rs b/pkgs/fleet/crates/fleet-secrets/src/lib.rs index 736b9ce45c..31b7f48a29 100644 --- a/pkgs/fleet/crates/fleet-secrets/src/lib.rs +++ b/pkgs/fleet/crates/fleet-secrets/src/lib.rs @@ -1104,7 +1104,7 @@ mod tests { assert!(validate_name(bad).is_err(), "name {bad:?} must be rejected"); } for good in [ - "supabase.service-role-key", + "turso.fleet-queue-rw-token", "openclaw.gateway-token", "a.b-c_d", ] { diff --git a/pkgs/fleet/fleet-fetch.py b/pkgs/fleet/fleet-fetch.py index 72e0d58c27..f2a2a95e32 100644 --- a/pkgs/fleet/fleet-fetch.py +++ b/pkgs/fleet/fleet-fetch.py @@ -16,14 +16,8 @@ name: turso.fleet-queue-rw-token). Failure of one repo never fails the others; exit is non-zero only if ALL repos fail. -History: snapshots/watermarks lived in Supabase muse-dev -(agent.repo_snapshots / agent.watermarks) until 2026-11-07, when the -#5693 ci re-home moved them to fleet-queue alongside the github-ci -Worker (which advances head_sha in the same table on push). The -snapshot_refresh event's sink (#5690, AGENT_EVENTS_SINK) had already -flipped to turso; the PG event leg is retired with this repoint — -the event now always lands in the fleet-queue events table. -Cutover: doc/fleet/agent-events-turso.md in developing-today/code. +Snapshots/watermarks and the snapshot_refresh event all live in the +fleet-queue Turso DB (doc/fleet/agent-events-turso.md). """ import json @@ -242,9 +236,8 @@ def fetch_repo(repo): def write_sql(statements): - """Kept name, new home (#5693): statements run against the - fleet-queue Turso DB (agent_repo_snapshots / agent_watermarks / - events), not Supabase.""" + """Statements run against the fleet-queue Turso DB + (agent_repo_snapshots / agent_watermarks / events).""" turso_pipeline(statements) @@ -304,7 +297,7 @@ def main(): except Exception as exc: results[repo] = {"ok": False, "error": str(exc)[:300]} - # Write each snapshot in its own supabase-exec call so one bad write + # Write each snapshot in its own pipeline call so one bad write # cannot sink the repos that fetched fine. write_errors = [] for repo, snap in snapshots.items(): diff --git a/pkgs/fleet/supabase-exec.py b/pkgs/fleet/supabase-exec.py deleted file mode 100644 index eb1d119873..0000000000 --- a/pkgs/fleet/supabase-exec.py +++ /dev/null @@ -1,116 +0,0 @@ -#!/usr/bin/env python3 -"""Run SQL against Drew's primary Supabase project via the Management API. - -Usage: supabase-exec.py [project-ref] - -The project ref defaults to the Bitwarden secret -`supabase.muse-dev2.project-ref` (the canonical pointer for muse-dev2, -the fleet's Supabase project since the 2026-10-30 cutover), so a -future project move is a Bitwarden change, not a code change. Pass the -ref explicitly to target another project (its scoped token must then be -used too — the canonical token is scoped to the canonical project). - -Auth: reads the Bitwarden Secrets Manager access token from -~/.config/bitwarden/access-token, fetches `supabase.muse-dev2.access-token-muse-cli` -(the sbp_ management token) from project "developing today", and uses it as -a Bearer token. No secret is ever printed. Output is the JSON result rows. -""" - -import json -import os -import subprocess -import sys -import urllib.request - -BWS = os.path.expanduser("~/tools/bin/bws") -TOKEN_FILE = os.path.expanduser("~/.config/bitwarden/access-token") -SECRET_KEY = "supabase.muse-dev2.access-token-muse-cli" -REF_KEY = "supabase.muse-dev2.project-ref" - - -def bws_env(): - env = dict(os.environ) - with open(TOKEN_FILE) as f: - env["BWS_ACCESS_TOKEN"] = f.read().strip() - return env - - -def get_secret(env, key): - out = subprocess.run( - [BWS, "secret", "list", "-o", "json"], - capture_output=True, - text=True, - env=env, - check=True, - ) - for s in json.loads(out.stdout): - if s.get("key") == key: - got = subprocess.run( - [BWS, "secret", "get", s["id"], "-o", "json"], - capture_output=True, - text=True, - env=env, - check=True, - ) - return json.loads(got.stdout)["value"] - raise SystemExit(f"secret {key} not found in Bitwarden") - - -def run_sql(token, ref, sql): - # curl, not urllib: urllib chunked reads through the sandbox egress - # proxy intermittently die with IncompleteRead (hit repeatedly - # 2026-10-20); curl handles the same responses reliably. - import tempfile - - with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: - json.dump({"query": sql}, f) - fname = f.name - try: - out = subprocess.run( - [ - "curl", - "-sS", - "-m", - "120", - "-A", - "Mozilla/5.0", - "-X", - "POST", - "-H", - f"Authorization: Bearer {token}", - "-H", - "Content-Type: application/json", - "--data", - f"@{fname}", - f"https://api.supabase.com/v1/projects/{ref}/database/query", - "-w", - "\n%{http_code}", - ], - capture_output=True, - text=True, - check=True, - ).stdout - body, _, code = out.rpartition("\n") - return int(code), body - finally: - os.unlink(fname) - - -def main(): - if len(sys.argv) < 2: - raise SystemExit(__doc__) - sql_file = sys.argv[1] - with open(sql_file) as f: - sql = f.read() - env = bws_env() - ref = sys.argv[2] if len(sys.argv) > 2 else get_secret(env, REF_KEY) - token = get_secret(env, SECRET_KEY) - status, text = run_sql(token, ref, sql) - print(f"HTTP {status}") - print(text) - if status >= 300: - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/pkgs/github-ci/worker/README.md b/pkgs/github-ci/worker/README.md index cae45ff2df..0323af90a6 100644 --- a/pkgs/github-ci/worker/README.md +++ b/pkgs/github-ci/worker/README.md @@ -1,15 +1,12 @@ # github-ci Worker -The GitHub webhook receiver (developing-today/code#5693), re-homed -off the Supabase Edge Function of the same name — the last Edge -Function on muse-dev2. Ported behavior-for-behavior from the Edge -Function (ACTIVE v8) so the two receivers can run side by side -during the dual-run diff period. +The GitHub webhook receiver (developing-today/code#5693). It writes +only to Turso; it is the sole receiver for every fleet repo. ## Shape -- `src/index.ts` — HMAC-SHA256 gate (Web Crypto, same semantics as - the Edge Function), routing, workflow_run ingest. The gate is +- `src/index.ts` — HMAC-SHA256 gate (Web Crypto), routing, + workflow_run ingest. The gate is unconditional (#6936): with `GITHUB_WEBHOOK_SECRET` unset or empty, every POST is rejected 503 "webhook secret not configured" before any write — the Worker fails closed, never open. @@ -74,9 +71,8 @@ npm test # vitest + @cloudflare/vitest-pool-workers npm run deploy # wrangler deploy (fleet Cloudflare account) ``` -Cutover state lives on #5693: deploy dark → replay smoke → one -repo-level dual-run webhook → (later, separately) org/App flip. -The Edge Function stays deployed as rollback until then. +The cutover from the earlier Postgres receiver is complete (#5693, +closeout below). ## Cutover closeout (2026-11-14, task 16806) @@ -94,16 +90,11 @@ The flip is complete and the Edge Function is retired: produced ~16k Turso events. No sender still reaches the old receiver; every fleet repo's webhook points at this Worker (verified per repo: code, opencode, openchamber, darwin-nix). -- **Edge Function retired.** `github-ci` (the last Edge Function - on muse-dev2, v9) was deleted via the Supabase Management API - on 2026-11-14; the project now has zero Edge Functions. The - Worker → Turso write path was verified live after the deletion - (new `ci_events` rows within a minute). Rollback, if ever - needed, is a redeploy of this Worker — its behavior is the - behavior-for-behavior port of the Edge Function. -- **The Postgres table stays.** `ci.events` remains read-only in - place for one retention window; dropping it is a separate, - separately-approved decision (not part of the cutover). +- **Old receiver retired.** The previous receiver was deleted on + 2026-11-14, and its database project has since been deleted too; + Turso is the only store. The Worker → Turso write path was + verified live after the deletion (new `ci_events` rows within a + minute). Rollback, if ever needed, is a redeploy of this Worker. ## Retention (90 days hot) diff --git a/pkgs/github-ci/worker/scripts/prune-ci-events.py b/pkgs/github-ci/worker/scripts/prune-ci-events.py index c171b5edb8..3c47bcdda9 100644 --- a/pkgs/github-ci/worker/scripts/prune-ci-events.py +++ b/pkgs/github-ci/worker/scripts/prune-ci-events.py @@ -1,11 +1,9 @@ #!/usr/bin/env python3 """Prune fleet-platform `ci_events` past the 90-day hot retention (#5693). -The ci.events ledger moved from Supabase Postgres to Turso -`fleet-platform.ci_events` (cutover completed 2026-11-14: dedupe diff -clean, Postgres write-silent since 2026-11-06, the Supabase Edge -Function receiver retired). The design's retention rule is 90 days -hot in Turso; this script is the prune that enforces it: +The ci events ledger lives in Turso `fleet-platform.ci_events`. The +design's retention rule is 90 days hot; this script is the prune that +enforces it: DELETE FROM ci_events WHERE received_at < datetime('now', '-90 days') diff --git a/pkgs/github-ci/worker/src/index.ts b/pkgs/github-ci/worker/src/index.ts index 6409701129..7c49292989 100644 --- a/pkgs/github-ci/worker/src/index.ts +++ b/pkgs/github-ci/worker/src/index.ts @@ -1,18 +1,17 @@ /** - * github-ci Worker (#5693) — the GitHub webhook receiver, re-homed - * off the Supabase Edge Function of the same name (ACTIVE v8). + * github-ci Worker (#5693) — the GitHub webhook receiver; all writes + * go to Turso. * * Gate: HMAC-SHA256 over the raw body, X-Hub-Signature-256 header, - * verified with Web Crypto against GITHUB_WEBHOOK_SECRET — the same - * semantics as the Edge Function (which ran verify_jwt=false; the - * HMAC is the gate). + * verified with Web Crypto against GITHUB_WEBHOOK_SECRET (the HMAC is + * the gate). * - * Behavior (parity with the Edge Function, minus Postgres): + * Behavior: * - workflow_run (any repo): INSERT OR IGNORE into Turso * fleet-platform ci_events ONLY, id unset (dedupe_key is the * identity), v4 ingest policy: completed runs only, conclusion * != skipped, raw payload kept only for failures. Fatal on - * failure (500 -> GitHub retries), as the EF's PG insert was. + * failure (500 -> GitHub retries). * - Fleet repos only: * - push: advance agent_repo_snapshots.head_sha in fleet-queue * (default-branch pushes only), stamp fetch_source='webhook', diff --git a/pkgs/github-ci/worker/wrangler.toml b/pkgs/github-ci/worker/wrangler.toml index 89734a5768..a337472f1d 100644 --- a/pkgs/github-ci/worker/wrangler.toml +++ b/pkgs/github-ci/worker/wrangler.toml @@ -1,7 +1,6 @@ -# github-ci Worker (#5693): the GitHub webhook receiver, re-homed off -# the Supabase Edge Function of the same name. Deployed to the fleet -# Cloudflare account. Dark until the #5693 cutover steps run: no -# webhook points here until a repo-level dual-run webhook is added. +# github-ci Worker (#5693): the GitHub webhook receiver, writing to +# Turso. Deployed to the fleet Cloudflare account; every fleet repo's +# webhook points here. # # Secrets (wrangler secret put; values never in this file): # GITHUB_WEBHOOK_SECRET HMAC gate; NEW value minted for this diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index cdc56bf277..cc6b79aa54 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -33,7 +33,7 @@ a second per-site failure TTL. The aggregator's three memo sites follow this contract: -- `src/supabase.ts` — `clientPromise` (`getSupabaseClient`), cleared +- `src/turso-stores.ts` — `cached` (`getTursoStoreClient`), cleared when an attempt resolves `null` or rejects (#3732). - `src/alerts.ts` — `storePromise` (`getAlertsStore`), cleared independently of the client layer when an attempt resolves `null` @@ -363,11 +363,12 @@ own alert path; one engine owns dedupe, delivery, escalation, and ack; every transition lands in a durable ledger. Drew's amendments to the #3450 design: delivery is Web Push (the #1254 design, doc `doc/2026-11-01T03-54-00Z_design_pwa_push_notifications.md`), and the -ledger lives in **Supabase muse-dev2**, schema `alerts` (`incidents` -with a partial unique index on `(source, incident_key)` for -non-closed rows, `incident_events`, `push_subscriptions`, -`notification_sends`) — reached through the same Management-API SQL -path as the fleet-feed collector's AA read (`src/supabase.ts`). +ledger lives in **Turso**, tables `alerts_incidents` (with a partial +unique index on `(source, incident_key)` for non-closed rows), +`alerts_incident_events`, `alerts_push_subscriptions` and +`alerts_notification_sends` — reached through the same Turso store +client as the fleet-feed collector's AA read (`src/turso-stores.ts`, +which translates the module's PostgreSQL-dialect `alerts.*` statements). - **PWA origin**: the aggregator is served through Tailscale Serve — `https://amd-6.raptor-pumpkinseed.ts.net` (443) → `127.0.0.1:4870`. @@ -534,7 +535,8 @@ The grammar lives as **per-app copies with one shared probe matrix** in field form; `""`, `"0x10"`, `"1e2"`, `" 12 "`, `"12abc"` are not measured. Embodiments: `src/aa.ts` `num()` (#2985), `src/saas-extract.ts` count patterns (#2997, #3000), -cloudflare-export and supabase-export gates (#2791, #2743), +the cloudflare-export gate (#2791; the supabase-export gate, #2743, +was retired with that exporter), meta-exporter's `parseSubscriptionQuota` (#2789 — drift found by the closing audit: the #6333 re-home restored the pre-#2789 bare coercion; restoration is filed as #7880). Closing audit: issue #3006. @@ -598,9 +600,9 @@ of silently showing canned data. `bun run dev` sets the switch for you. | `PM_AGG_ACTIONS_FILE` | `./actions.json` | Dashboard action store (#1152/#1154/#1156) — aggregator-local; created on first action | | `PM_AGG_REGISTRY_FILE` | `./registry.json` | Durable session identity registry (#906) — merged records persist across restarts | | `PM_AGG_ACTIVITY_FILE` | `~/.local/state/pm-aggregator/activity-ingestion.json` | Activity-ingestion store (#3321) — per-source checkpoints, dedupe seen sets, source status, and gap records for watchdog/Kaneo/GitHub writers | -| `PM_AGG_STORE_BACKEND` | `file` | Backing store for the four #6815 stores: `file` (local JSON, dev/test/rollback) or `supabase` (canonical in muse-dev2). Any other value refuses to start; see "Store backend" below | +| `PM_AGG_STORE_BACKEND` | `file` | Backing store for the four #6815 stores: `file` (local JSON, dev/test/rollback) or `turso` (canonical in Turso). Any other value refuses to start; see "Store backend" below | | `PM_AGG_STORE_WRITER` | `pm-aggregator.service` | Writer identity recorded on remote rows (`agg_store_documents.writer`), so the single writer of a store is visible in the data | -| `BWS_BIN` | first of `/run/current-system/sw/bin/bws`, `~/tools/bin/bws` | Bitwarden Secrets Manager binary used to resolve the muse-dev2 ref/token by NAME only | +| `BWS_BIN` | first of `/run/current-system/sw/bin/bws`, `~/tools/bin/bws` | Bitwarden Secrets Manager binary used to resolve the Turso store token by NAME only | | `BWS_ACCESS_TOKEN_FILE` | `~/.config/bws/access-token` | Machine-account access token file for `bws`; never logged, never rendered into the archive | Secrets are read from the environment only and are never committed or @@ -648,60 +650,58 @@ historical ranges) is documented in `ACTIVITY_SOURCE_COVERAGE` in with rows retained in the hot list; upstream webhook deliveries the projector never received and pre-hot-list history remain unsupported. -### Store backend: Supabase muse-dev2 (#6815) +### Store backend: Turso (#6815) Four stores that used to live only as laptop-local JSON under the -aggregator's state dir are canonical in Supabase muse-dev2. The +aggregator's state dir are canonical in Turso. The `PM_AGG_STORE_BACKEND` switch picks exactly one active backend: -| Store | `file` backend | `supabase` backend | -| ------------------ | -------------------------------------------------------- | ------------------------------------------------------------ | -| Dashboard actions | `actions.json` (`PM_AGG_ACTIONS_FILE`) | `public.agg_actions` (contract `20261105_0001`) | -| Activity ingestion | `activity-ingestion.json` (`PM_AGG_ACTIVITY_FILE`) | `public.agg_activity_ingestion` + `public.agg_activity_gaps` | -| Usage snapshots | `snapshots/usage-YYYY-MM.jsonl` (`PM_AGG_SNAPSHOTS_DIR`) | `public.agg_usage_snapshots` | -| AA last-good | `aa-last-good.json` (collector) | `public.agg_store_documents` key `aa-last-good` | +| Store | `file` backend | `turso` backend | +| ------------------ | -------------------------------------------------------- | ----------------------------------------------------- | +| Dashboard actions | `actions.json` (`PM_AGG_ACTIONS_FILE`) | `agg_actions` (contract `20261105_0001`) | +| Activity ingestion | `activity-ingestion.json` (`PM_AGG_ACTIVITY_FILE`) | `agg_activity_ingestion` + `agg_activity_gaps` | +| Usage snapshots | `snapshots/usage-YYYY-MM.jsonl` (`PM_AGG_SNAPSHOTS_DIR`) | `agg_usage_snapshots` | +| AA last-good | `aa-last-good.json` (collector) | `agg_store_documents` key `aa-last-good` | Rules the implementation holds to: - **One backend, no dual writes.** `parseStoreBackend()` accepts only - `file` (the default: dev, tests, and rollback) or `supabase`; any - other value refuses to start. In `supabase` mode a remote failure is + `file` (the default: dev, tests, and rollback) or `turso`; any + other value (including the retired `supabase`) refuses to start. In + `turso` mode a remote failure is fail-closed — the process reports the error and never silently falls back to the local file. - **One writer.** `pm-aggregator.service` is the only writer of the aggregator stores; the collector writes only its `aa-last-good` document and is recorded as writer `fleet-feed-collector` (`PM_AGG_STORE_WRITER`). Rows carry that identity. -- **Local files are a cache.** With `supabase` active, any remaining +- **Local files are a cache.** With `turso` active, any remaining local copy (`actions.json`, `activity-ingestion.json`, `snapshots/`, `aa-last-good.json`) is a rebuildable cache, not the source of truth: a fresh state dir boots empty and reconstructs from - muse-dev2 (covered by `test/store-remote-backends.test.ts`). + Turso (covered by `test/store-remote-backends.test.ts`). - **Schema is consumed, not redesigned.** `agg_actions` follows the #3142 contract in migration `20261105_0001`; the additive `20261116_0001_aggregator_remote_stores` adds the activity, snapshot - and document tables. + and document tables. Those PostgreSQL files are the contract; the + live Turso tables mirror them, and `src/turso-stores.ts` + (`storeStatement`) translates the statements in + `src/remote-stores.ts` to SQLite. -Cutover order (also the header of -`scripts/migrate-stores-to-supabase.ts`): - -1. Apply `shared-schema/migrations/20261105_0001_action_event_store`. -2. Apply `shared-schema/migrations/20261116_0001_aggregator_remote_stores`. -3. Run `bun run scripts/migrate-stores-to-supabase.ts` (idempotent; run - `--dry-run` first for counts). -4. Deploy with `PM_AGG_STORE_BACKEND=supabase` (rendered by - `install.sh` and set in the NixOS unit). -5. Re-run the import once after the switch: writes made between step 3 - and step 4 are then closed, and re-running is a no-op for rows - already present. +Deploy with `PM_AGG_STORE_BACKEND=turso` (rendered by `install.sh` and +set in the NixOS unit); the store token is resolved from Bitwarden by +name (`src/turso-stores.ts`). The Supabase project these stores first +lived in (muse-dev2) has been deleted and its one-off import script +removed; there is no `supabase` backend any more. Rollback is the reverse: set `PM_AGG_STORE_BACKEND=file` and restart; the file stores were never deleted. The tables are additive and the down migration refuses to drop a non-empty table. Backup / RPO (#1514, recorded on #6815): `pm-dashboard-backup.sh` -exports the five tables as JSON into `supabase/agg_*.json` in the daily -archive whenever the deployed backend is `supabase`, and records them as +exports the store tables (plus the alerts ledger and `orch_runs`) as JSON +into `turso/*.json` in the daily archive whenever the deployed backend is +`turso` (via `pm-aggregator-export-turso-stores`), and records them as conditionally-required manifest members. Without that export a restore would have no canonical store to read. @@ -882,10 +882,11 @@ Each tick: (`SnapshotStore.append` dedupes; change-tracking state in `quota-gatherer-state.json`). Setting `USAGE_SNAPSHOT_OUTBOX_PATH` reroutes records to the writers' outbox instead. -- appends one Supabase `agent.quota_records` row per pool entry to - muse-dev2 (source `opencode-quota`), so the readings land in - Supabase on the same tick as the dashboard file. Fail-soft: a sink - failure is logged and never fails the tick. +- appends one Turso `agent_quota_records` row per pool entry to + fleet-platform (source `opencode-quota`), so the readings land in + the quota ledger on the same tick as the dashboard file + (`TURSO_QUOTA_SINK=0` disables it). Fail-soft: a sink failure is + logged and never fails the tick. Fail-soft: a subcommand failure or unparseable output writes a heartbeat with the error, exits non-zero, and leaves the previous diff --git a/pm-stack/aggregator/install.sh b/pm-stack/aggregator/install.sh index 4a0717af9f..55e11fcdb6 100755 --- a/pm-stack/aggregator/install.sh +++ b/pm-stack/aggregator/install.sh @@ -185,9 +185,9 @@ if [ "$CHANGED" -eq 1 ]; then echo "PM_AGG_ROADMAP_ANNOTATIONS_FILE=${STATE_DIR}/roadmap-annotations.json" # #6815: the four stores that used to be laptop-local files # (actions, activity-ingestion, usage snapshots, aa-last-good) are - # canonical in Supabase muse-dev2; the local files remain a + # canonical in Turso (src/turso-stores.ts); the local files remain a # rebuildable cache. PM_AGG_STORE_BACKEND=file is the rollback. - echo "PM_AGG_STORE_BACKEND=supabase" + echo "PM_AGG_STORE_BACKEND=turso" echo "PM_AGG_STORE_WRITER=pm-aggregator.service" echo "BWS_BIN=/run/current-system/sw/bin/bws" echo "BWS_ACCESS_TOKEN_FILE=${HOME}/.config/bws/access-token" diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 93019c0770..9f3f38d6f7 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -23,9 +23,9 @@ // pass through: candidates are charge evidence only. // - the orchestration section (#899: tiers, dependencies, goal // measurements) — read since the #10504 reader flip from the -// latest public.orch_runs.document on Supabase muse-dev2 (the -// writer cutover's store), through the same Management API SQL -// route and Bitwarden token as the AA section; orchestration.json +// latest orch_runs.document in the Turso store (the writer +// cutover's store), through the same Turso store client +// (src/turso-stores.ts) as the AA section; orchestration.json // (still regenerated by the writer every pass) is the fallback on // any DB failure and the rollback source under // ORCHESTRATION_SOURCE=file. Embedded only after @@ -42,16 +42,15 @@ // `fleet gh`, with personal -> owner-specific App installation // rotation selected for each org. One failed board does not discard // the others; items retain their stable boardId in the feed. -// - the AA cost explorer data — Supabase `ainventory` (the AA -// import: v_rankings, v_threshold_metrics, +// - the AA cost explorer data — the Turso `ainventory_*` tables +// (the AA import: v_rankings, v_threshold_metrics, // measurement_events — both the AA Intelligence Index rows and the // Coding Agent Index rows, kept as separate benchmark families — // the Test_Runs data, and the price event log's v_current_prices), -// read through v_latest_import_batch via the Management API SQL endpoint. -// Token plumbing mirrors the Projects read: the Bitwarden secret -// named `supabase.muse-dev2.access-token-muse-cli` (the sbp_ management -// token), resolved by resolveBwsSecret and sent only to -// api.supabase.com. Any failure embeds the section in its absent +// read per import batch through the Turso store client +// (getTursoStoreClient, src/turso-stores.ts), whose token is +// resolved from Bitwarden and sent only to the Turso endpoint. +// Any failure embeds the section in its absent // form ({status:"absent", reason}) — the feed never fails over it. // Pool/catalog coverage is computed against the repo's own // .opencode/opencode.jsonc (provider catalog + model_routes @@ -71,7 +70,6 @@ // derived from; beside the charges-surfaced state by default), // CHARGE_CANDIDATES_PATH / CHARGES_SURFACED_STATE_PATH (#1057: the // producer's candidates file and the collector's surfaced-once state), -// SUPABASE_PROJECT_REF (else the canonical Bitwarden supabase.project-ref pointer), // AA_OPENCODE_CONFIG_PATH (default: the repo's .opencode/opencode.jsonc). import { execFile } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; @@ -83,7 +81,7 @@ import { dnsSectionFromRegister, dnsSectionFromRegisterJson, parseDnsRegister } import { disabledProvidersFromConfig, aaAbsent, - aaSectionFromSupabase, + aaSectionFromPayload, isAaSection, type AaRawPayload, } from "../src/aa.ts"; @@ -173,7 +171,7 @@ import { defaultHiddenDir, defaultQuotaViewPath, defaultUsageOutboxPath } from " import { mapServerSessions, poolBurn } from "../src/sources/opencode.ts"; import { getTursoStoreClient } from "../src/turso-stores.ts"; import { AaLastGoodStore } from "../src/aa-last-good.ts"; -import { createSupabaseDocumentRemote } from "../src/remote-stores.ts"; +import { createTursoDocumentRemote } from "../src/remote-stores.ts"; import { parseStoreBackend } from "../src/store-backend.ts"; import type { FreshnessInput } from "../src/freshness.ts"; @@ -467,7 +465,7 @@ const fleetGhProjectFetch: ProjectFetch = async (_input, init) => { return new Response(body, { status: 200, headers: { "content-type": "application/json" } }); }; -// --- AA cost explorer (Supabase ainventory) --------------------------------- +// --- AA cost explorer (Turso ainventory) ------------------------------------ // One SQL statement returns the whole section payload as a single // jsonb object (keys pre-renamed to the section's camelCase). The // Test_Runs data rides as raw rows; src/aa.ts maps them by @@ -480,23 +478,19 @@ const fleetGhProjectFetch: ProjectFetch = async (_input, init) => { /** * The last-good AA section store (code#3332): kept beside the feed so a - * transient Supabase failure degrades to the previous good payload + * transient Turso failure degrades to the previous good payload * instead of blanking the explorer. Keyed by the import batch and the * opencode config fingerprint — the section is rebuilt when either * changes and reused untouched while neither does. */ const aaLastGoodPath = join(dirname(outPath), "aa-last-good.json"); /** #6815: the AA last-good payload is a rebuildable cache, not a - * source of record. In supabase mode its canonical copy is - * public.agg_store_documents keyed "aa-last-good"; the local file is + * source of record. In turso mode its canonical copy is + * agg_store_documents keyed "aa-last-good"; the local file is * then neither read nor written. */ const aaLastGoodStore = new AaLastGoodStore( aaLastGoodPath, - parseStoreBackend() === "turso" - ? createSupabaseDocumentRemote(getTursoStoreClient) - : parseStoreBackend() === "supabase" - ? createSupabaseDocumentRemote() - : undefined, + parseStoreBackend() === "turso" ? createTursoDocumentRemote(getTursoStoreClient) : undefined, ); // #1116: last-good attention entries, carried across runs whose server // read fails (restart churn) so one bad read cannot zero the feed. @@ -505,7 +499,7 @@ const attentionLastGoodPath = join(dirname(outPath), "attention-last-good.json") const aaBatchDir = join(dirname(outPath), "aa-batches"); /** How many missing historical payloads one tick may build. The latest is * always fresh; history fills in over ticks so no single run storms the - * Management API (#3332). */ + * remote store (#3332). */ const AA_HISTORICAL_BUILDS_PER_TICK = 2; interface AaLastGood { @@ -620,8 +614,8 @@ async function fetchAaPayload(batch: string | null): Promise { * Build the AA feed section. Fail-soft like every other section: a * failed build degrades to the last good payload with a stale marker * (code#3332), or to the absent form when no good payload exists yet, - * so the dashboard explains the gap. The management token is only ever - * sent to api.supabase.com and is never logged or written to the feed. + * so the dashboard explains the gap. The store token is only ever + * sent to the Turso endpoint and is never logged or written to the feed. * * #3302: the index comes from ainventory.sources (complete); each batch * payload is cached under aa-batches/. The latest batch is refreshed @@ -651,7 +645,7 @@ async function collectAaSection(generatedAt: string): Promise { const cacheMeta = new Map(); const assemble = async (raw: AaRawPayload): Promise => { - const section = aaSectionFromSupabase(raw, configText, generatedAt, runtimeText); + const section = aaSectionFromPayload(raw, configText, generatedAt, runtimeText); if (!section) return null; const contentFingerprint = aaBatchFingerprint(raw); const cached = await writeAaBatchCache({ @@ -1222,7 +1216,7 @@ async function main(): Promise { markSection("coverage", "error", err); } - // --- AA cost explorer (Supabase ainventory) ------------------------------ + // --- AA cost explorer (Turso ainventory) --------------------------------- // Always attempted; the section carries its own failure (absent // form) so the dashboard can say why instead of showing stale data. const collectedAa = await collectAaSection(now.toISOString()); diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index 325988256b..00e5f196b0 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -103,9 +103,8 @@ // OPENCHAMBER_LIB_INSTALL_CMD (override for the lib checkout's // dependency install step, shell-split like QUOTA_SUBCOMMAND; // default is bun install at the checkout root, #8759), -// TURSO_QUOTA_SINK=0 (or the legacy SUPABASE_QUOTA_SINK=0) -// disables the Turso sink (default on; token resolved by name -// via the resolveBwsSecret plumbing: +// TURSO_QUOTA_SINK=0 disables the Turso sink (default on; token +// resolved by name via the resolveBwsSecret plumbing: // turso.fleet-platform-rw-token). import { execFile } from "node:child_process"; import { access, appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises"; @@ -378,7 +377,7 @@ async function runOpenDesignRenewal(tickAt: string): Promise { * alert episode dispatches a Web Push (class "incident", the * breakthrough class) to every stored subscription, with the same * sends-ledger bookkeeping the digest delivery uses. No alerts store - * (Supabase unavailable) = no delivery surface; the state-file alert + * (Turso store unavailable) = no delivery surface; the state-file alert * still stands and the outcome string records the skip. */ async function notifyMetaAuthPush(notice: { title: string; body: string }): Promise { @@ -785,7 +784,7 @@ function sqlString(v: string): string { * (source, id, ts) PK. */ async function writeTursoRecords(entries: QuotaCurrentEntry[], tickAt: string): Promise { - if (process.env.TURSO_QUOTA_SINK === "0" || process.env.SUPABASE_QUOTA_SINK === "0") return; + if (process.env.TURSO_QUOTA_SINK === "0") return; try { const token = await resolveBwsSecret(TURSO_TOKEN_NAME); if (!token) { diff --git a/pm-stack/aggregator/scripts/generate-digest.ts b/pm-stack/aggregator/scripts/generate-digest.ts index 55fc6d6bb9..4310c29873 100644 --- a/pm-stack/aggregator/scripts/generate-digest.ts +++ b/pm-stack/aggregator/scripts/generate-digest.ts @@ -115,7 +115,7 @@ async function main(): Promise { if (process.argv.includes("--no-deliver")) return; // Delivery: Web Push to every stored subscription, mirroring the // alert throat's send bookkeeping (gone subscriptions are noted, - // sends are logged under class "digest"). No store (Supabase + // sends are logged under class "digest"). No store (Turso store // unavailable) = no delivery surface; the archive still stands. const store = await getAlertsStore(); if (!store) { diff --git a/pm-stack/aggregator/scripts/migrate-stores-to-supabase.ts b/pm-stack/aggregator/scripts/migrate-stores-to-supabase.ts deleted file mode 100644 index 4b6148cb4d..0000000000 --- a/pm-stack/aggregator/scripts/migrate-stores-to-supabase.ts +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env bun -// Backfill the four aggregator stores that #6815 moved from laptop-local -// files to Supabase muse-dev2: -// -// actions.json -> public.agg_actions (20261105_0001) -// activity-ingestion.json -> public.agg_activity_ingestion + *_gaps -// snapshots/usage-*.jsonl -> public.agg_usage_snapshots -// aa-last-good.json -> public.agg_store_documents ("aa-last-good") -// -// The script is a read-only reader of the file stores and an idempotent -// writer of the remote ones: every remote write is an upsert on the same -// key the store itself uses (action id, source, gap id, snapshot key, -// document name), so running it twice appends/overwrites nothing new. -// -// Cutover order (see pm-stack/aggregator/README.md, "Store backend"): -// 1. apply shared-schema/migrations/20261105_0001_action_event_store -// 2. apply shared-schema/migrations/20261116_0001_aggregator_remote_stores -// 3. run this script (--dry-run first to see the counts) -// 4. set PM_AGG_STORE_BACKEND=supabase and deploy -// The file stores stay untouched, so the rollback target is intact. -// -// Usage: bun run scripts/migrate-stores-to-supabase.ts [--dry-run] [--help] -// Env: PM_AGG_STATE_DIR default ~/.local/state/pm-aggregator -// PM_AGG_SNAPSHOTS_DIR default /snapshots -// SUPABASE_PROJECT_REF / BWS secrets resolve as everywhere else -// (src/supabase.ts). -// Exit: 0 migrated (or dry run), 2 usage error, 1 remote/file failure. -import { homedir } from "node:os"; -import { join } from "node:path"; -import { ActionsStore } from "../src/actions.ts"; -import { IngestionStore } from "../src/activity.ts"; -import { AaLastGoodStore } from "../src/aa-last-good.ts"; -import { AA_LAST_GOOD_DOCUMENT } from "../src/store-backend.ts"; -import { SnapshotStore } from "../src/snapshots.ts"; -import { createSupabaseRemotes } from "../src/remote-stores.ts"; - -const USAGE = `Usage: bun run scripts/migrate-stores-to-supabase.ts [--dry-run] [--help] - -Reads the four file stores under the aggregator state dir and upserts -them into Supabase (muse-dev2). Idempotent; never deletes file state. - - --dry-run read and validate the files, print counts, write nothing - --help print this help - -Env: - PM_AGG_STATE_DIR default ~/.local/state/pm-aggregator - PM_AGG_SNAPSHOTS_DIR default /snapshots`; - -const KNOWN_FLAGS = new Set(["--dry-run", "--help"]); - -function usageError(message: string): never { - console.error(`migrate-stores-to-supabase: ${message}`); - console.error(USAGE); - process.exit(2); -} - -// Strict argument contract (#3352): every argv must be declared, and a -// malformed command line exits 2 before any file or network access. -const args = process.argv.slice(2); -let dryRun = false; -for (const arg of args) { - if (!KNOWN_FLAGS.has(arg)) usageError(`unknown argument ${JSON.stringify(arg)}`); - if (arg === "--help") { - console.log(USAGE); - process.exit(0); - } - if (arg === "--dry-run") dryRun = true; -} - -const stateDir = (process.env.PM_AGG_STATE_DIR ?? join(homedir(), ".local", "state", "pm-aggregator")).trim(); -if (stateDir === "") usageError("PM_AGG_STATE_DIR is set but empty"); -const snapshotsDir = (process.env.PM_AGG_SNAPSHOTS_DIR ?? join(stateDir, "snapshots")).trim(); -if (snapshotsDir === "") usageError("PM_AGG_SNAPSHOTS_DIR is set but empty"); - -const actionsFile = join(stateDir, "actions.json"); -const activityFile = join(stateDir, "activity-ingestion.json"); -const aaLastGoodFile = join(stateDir, "aa-last-good.json"); - -async function main(): Promise { - // File stores are only readers here; each one already validates its - // own shape and treats a missing file as an empty start. - const actionsStore = new ActionsStore(actionsFile); - await actionsStore.load(); - const actions = await actionsStore.all(); - - const activityStore = new IngestionStore(activityFile); - await activityStore.load(); - const activity = await activityStore.documentForExport(); - - const snapshots = await new SnapshotStore(snapshotsDir).readAll(); - const aaLastGood = await new AaLastGoodStore(aaLastGoodFile).read(); - - console.error( - `migrate-stores-to-supabase: read ${actions.length} action(s), ` + - `${Object.keys(activity.checkpoints).length} activity source(s), ${activity.gaps.length} gap(s), ` + - `${snapshots.length} usage snapshot(s), aa-last-good ${aaLastGood === null ? "absent" : "present"}`, - ); - - if (dryRun) { - console.error("migrate-stores-to-supabase: --dry-run, nothing written"); - return; - } - - const remotes = createSupabaseRemotes(undefined, "pm-aggregator-migrate"); - await remotes.actions.saveAll(actions); - await remotes.activity.save(activity); - const inserted = await remotes.usage.append(snapshots); - if (aaLastGood !== null) { - await remotes.aaLastGood.save(AA_LAST_GOOD_DOCUMENT, 1, aaLastGood); - } - console.error( - `migrate-stores-to-supabase: wrote actions=${actions.length}, ` + - `activitySources=${Object.keys(activity.checkpoints).length}, gaps=${activity.gaps.length}, ` + - `snapshotsInserted=${inserted}/${snapshots.length}, aaLastGood=${aaLastGood === null ? "skipped" : "written"}`, - ); -} - -try { - await main(); -} catch (err) { - console.error(`migrate-stores-to-supabase: failed (${err instanceof Error ? err.message : String(err)})`); - process.exit(1); -} diff --git a/pm-stack/aggregator/src/aa-last-good.ts b/pm-stack/aggregator/src/aa-last-good.ts index 9955ba756e..c15e201999 100644 --- a/pm-stack/aggregator/src/aa-last-good.ts +++ b/pm-stack/aggregator/src/aa-last-good.ts @@ -1,15 +1,15 @@ -// AA last-good store (code#3332, moved to Supabase in #6815). +// AA last-good store (code#3332, remote-capable since #6815; Turso-backed). // -// The collector keeps the last good AA section so a transient Supabase +// The collector keeps the last good AA section so a transient Turso // failure degrades to the previous payload instead of blanking the -// explorer. In file mode it is a JSON file beside the feed; in supabase -// mode its canonical copy is public.agg_store_documents keyed +// explorer. In file mode it is a JSON file beside the feed; in turso +// mode its canonical copy is agg_store_documents keyed // "aa-last-good" (the file is not read or written). import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import { AA_LAST_GOOD_DOCUMENT } from "./store-backend.ts"; -/** Minimal remote document contract; implemented over Supabase in +/** Minimal remote document contract; implemented over Turso in * remote-stores.ts and faked in tests. */ export interface DocumentRemote { load(store: string): Promise<{ version: number; document: unknown } | null>; diff --git a/pm-stack/aggregator/src/aa.ts b/pm-stack/aggregator/src/aa.ts index 971e9e1e99..8f257a2160 100644 --- a/pm-stack/aggregator/src/aa.ts +++ b/pm-stack/aggregator/src/aa.ts @@ -1,5 +1,5 @@ -// The AA cost explorer as data. The source of record is the Supabase -// `ainventory` schema (the AA import: v_rankings, +// The AA cost explorer as data. The source of record is the Turso +// `ainventory_*` tables (the AA import: v_rankings, // v_threshold_metrics, measurement_events (the canonical benchmark // store, code#4401), and the Test_Runs data in sheet_rows, read // through v_latest_import_batch where the store carries batch identity). The collector @@ -26,7 +26,7 @@ import { isIsoDate } from "./validate.ts"; import { antigravityPoolForModel, serviceIdFor } from "./quota-gather-map.ts"; // --- scalar coercion --------------------------------------------------------- -// The Supabase Management API serializes numeric columns as JSON +// The store's JSON sections can carry numeric columns as JSON // strings, so every number crosses a coercion gate here; anything // unparseable becomes null ("not measured"), never 0. // @@ -1056,7 +1056,7 @@ export function aaCatalogFromConfig( // --- section assembly + validation --------------------------------------------- -/** The collector's raw Supabase payload (one jsonb object; snake-case +/** The collector's raw store payload (one JSON object; snake-case * keys are renamed to the section's camelCase by the SQL itself). */ export interface AaRawPayload { batch?: unknown; @@ -1199,12 +1199,12 @@ function sheetRowsFromRaw(v: unknown): SheetRow[] { } /** - * Assemble the feed section from the Supabase payload + the repo's + * Assemble the feed section from the store payload + the repo's * opencode config text (null/unparseable = coverage omitted, stated in * the section by its absence). Returns null when the payload is not * recognizably the AA data — the collector degrades to the absent form. */ -export function aaSectionFromSupabase( +export function aaSectionFromPayload( raw: AaRawPayload, opencodeConfigText: string | null, generatedAt: string, diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 0680076d66..789602895b 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -1,7 +1,7 @@ // The alert throat (#3676; design #3450 as amended by Drew // 2026-11-01): every sentinel posts incidents to ONE intake; this // module owns dedupe, delivery, escalation, and ack state; every -// transition lands in the Supabase muse-dev2 `alerts` ledger +// transition lands in the Turso `alerts_*` ledger tables // (incidents / incident_events / push_subscriptions / // notification_sends). Delivery is Web Push per the #1254 design // (doc/2026-11-01T03-54-00Z_design_pwa_push_notifications.md): the @@ -23,7 +23,7 @@ import type { Config } from "./config.ts"; import { sendPush, type PushOutcome, type PushTarget } from "./push.ts"; import { getTursoStoreClient } from "./turso-stores.ts"; -import { getSupabaseClient, sqlInt, sqlJson, sqlStr, type SupabaseClient } from "./supabase.ts"; +import { sqlInt, sqlJson, sqlStr, type SqlClient } from "./sql-client.ts"; import { buildNotificationCandidates, classTestObjectRef, @@ -381,7 +381,7 @@ export function validateNewSubscription( }; } -// --- The store (Supabase `alerts` schema) ------------------------------------ +// --- The store (Turso `alerts_*` tables) ------------------------------------ interface PendingIncidentCursor { timestamp: string; @@ -396,7 +396,7 @@ export class AlertsStore { private readonly deliveryCursor: { last: PendingIncidentCursor | null } = { last: null }; private readonly escalationCursor: { last: PendingIncidentCursor | null } = { last: null }; - constructor(private readonly db: SupabaseClient) {} + constructor(private readonly db: SqlClient) {} private async pendingBatch( eligibility: string, @@ -786,7 +786,7 @@ export async function sendTestPush( * Lazy-init contract (success-only memoization): README "Lazy-initialization contract" (#3879). */ export function createAlertsStoreGetter( - getClient: typeof getSupabaseClient = getTursoStoreClient, + getClient: () => Promise = getTursoStoreClient, ): () => Promise { let storePromise: Promise | null = null; @@ -807,7 +807,7 @@ export function createAlertsStoreGetter( }; } -/** The shared store; null when the Supabase path is unavailable. */ +/** The shared store; null when the Turso store client is unavailable. */ export const getAlertsStore = createAlertsStoreGetter(); // --- The engine --------------------------------------------------------------- diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index c84b802d15..ba5ef91e1c 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -38,8 +38,8 @@ function parseAggregatorHosts(value: string | undefined): string[] { } export interface Config { - /** #6815: where the four Supabase-migrated stores live. "file" is the - * dev/test path and rollback target; "supabase" is the deployed + /** #6815: where the four remote-capable stores live. "file" is the + * dev/test path and rollback target; "turso" is the deployed * canonical backend. Exactly one is active — never both. */ storeBackend: StoreBackendKind; /** Default Source: "live" when PM_AGG_SOURCE=live; "fixtures" when @@ -123,9 +123,6 @@ export interface Config { /** Tracker of evaluated free services without automated quota cards (#1172). */ freeServicesTrackerFile: string; cloudflareExportFile: string; - /** The Supabase usage exporter's document (#1050): the gathered live read - * preferred over the quota view's Supabase prose when fresh. */ - supabaseExportFile: string; /** The provider quota registry; the hub's second dated-read source * (billing incidents) for the same fallback path. */ quotaRegistryFile: string; @@ -282,7 +279,6 @@ export function loadConfig(env: Record = process.env join(homedir(), "hatch-personal/workspace/ai-subscriptions/free-services-to-check.md"), ), cloudflareExportFile: s(env.PM_AGG_CLOUDFLARE_EXPORT, join(homedir(), "atlas/cloudflare-export/latest.json")), - supabaseExportFile: s(env.PM_AGG_SUPABASE_EXPORT, join(homedir(), "atlas/supabase-export/latest.json")), quotaRegistryFile: s( env.PM_AGG_QUOTA_REGISTRY, join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"), diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 1bcc468db7..3f36ef7c94 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -143,9 +143,9 @@ export interface FleetFeed { * Absent when the collector had no GitHub token or the census failed. */ coverage?: RepoCensus[]; /** AA cost explorer section: the ainventory (AA import) data read - * by the collector from Supabase, plus pool/catalog coverage computed + * by the collector from Turso, plus pool/catalog coverage computed * against the repo's opencode config. Present-but-absent - * ({status:"absent", reason}) when Supabase was unreachable — the + * ({status:"absent", reason}) when Turso was unreachable — the * section degrades, the feed never fails over it. */ aa?: AaFeedSection; /** Optional collector outcomes. Older feeds have no metadata and keep diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 6072392d3e..65cb2d24f3 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -880,8 +880,8 @@ export interface DnsSection { } // --------------------------------------------------------------------------- -// AA cost explorer: the Artificial Analysis import data (Supabase -// `ainventory`, latest import batch) as the collector embeds it in the +// AA cost explorer: the Artificial Analysis import data (Turso +// `ainventory_*`, latest import batch) as the collector embeds it in the // fleet feed. The figures are the import snapshot's — AA Intelligence // Index v4.3.2, Test_Runs snapshots of Sep–Oct 2026 — not a live AA pull; // the section's provenance says exactly which batch and files they are. @@ -1226,7 +1226,7 @@ export interface AaSection { staleReason?: string; } -/** The section's degraded form: the collector could not reach Supabase +/** The section's degraded form: the collector could not reach Turso * (or the payload failed its check) and no last good payload exists * to fall back to (code#3332) — the page renders the reason, and the * feed never fails over it. */ diff --git a/pm-stack/aggregator/src/orchestration-db.ts b/pm-stack/aggregator/src/orchestration-db.ts index f3fb4a8658..579344f426 100644 --- a/pm-stack/aggregator/src/orchestration-db.ts +++ b/pm-stack/aggregator/src/orchestration-db.ts @@ -1,8 +1,8 @@ // Orchestration reader flip (#10504, phase 1 of #3142): the fleet-feed // collector's orchestration section is read from the latest -// public.orch_runs.document on Supabase muse-dev2 — the writer cutover -// (task 14838, PR #10381) has written every hourly pass there since -// 2026-11-15 — and orchestration.json, which the writer still +// orch_runs.document in the Turso store — the writer cutover +// (task 14838, PR #10381) has written every hourly pass to the +// remote store since 2026-11-15 — and orchestration.json, which the writer still // regenerates every pass, becomes the export + rollback path only. // // Fallback contract (from #10504): on any DB read failure the reader @@ -13,9 +13,8 @@ // which points the reader back at the file and loses nothing. // // This module is the decision logic only: the collector injects its -// own Supabase query route (Management API SQL, the same one the AA -// section uses) and its file read, so the flip is unit-testable -// without a database. +// own Turso store query route (the same one the AA section uses) and +// its file read, so the flip is unit-testable without a database. /** The latest run's complete document, newest first. generated_at is * the document's own generatedAt (writer contract, ORCHESTRATION.md); diff --git a/pm-stack/aggregator/src/remote-stores.ts b/pm-stack/aggregator/src/remote-stores.ts index 5c6b207db0..a983d5d3cb 100644 --- a/pm-stack/aggregator/src/remote-stores.ts +++ b/pm-stack/aggregator/src/remote-stores.ts @@ -1,10 +1,12 @@ -// Supabase-backed implementations of the four remote store interfaces -// added in #6815. They speak the same Management API SQL client as the -// alerts ledger (src/supabase.ts) and write only the tables from +// Turso-backed implementations of the four remote store interfaces +// added in #6815. They speak the shared SqlClient contract +// (src/sql-client.ts), served by the Turso store client +// (src/turso-stores.ts), and write only the tables from // shared-schema/migrations/20261116_0001_aggregator_remote_stores.up.sql -// plus the pre-existing public.agg_actions contract (20261105_0001). +// plus the pre-existing agg_actions contract (20261105_0001). The SQL +// below is written once and translated to SQLite by storeStatement(). // -// The caller selects these only when PM_AGG_STORE_BACKEND=supabase. A +// The caller selects these only when PM_AGG_STORE_BACKEND=turso. A // missing client is an error here: silently writing a local canonical // copy would recreate exactly the laptop-only state #6815 removes. import { ACTION_STATES, type ActionsRemote, type DashAction } from "./actions.ts"; @@ -14,7 +16,8 @@ import type { SnapshotsRemote } from "./snapshots.ts"; import type { SnapshotRecord } from "./model.ts"; import { snapshotKey } from "./snapshots.ts"; import { storeWriterIdentity } from "./store-backend.ts"; -import { getSupabaseClient, sqlJson, sqlStr, type SupabaseClient } from "./supabase.ts"; +import { sqlJson, sqlStr, type SqlClient } from "./sql-client.ts"; +import { getTursoStoreClient } from "./turso-stores.ts"; export interface StoreRemotes { actions: ActionsRemote; @@ -23,7 +26,7 @@ export interface StoreRemotes { aaLastGood: DocumentRemote; } -type GetClient = () => Promise; +type GetClient = () => Promise; const WRITE_CHUNK = 200; @@ -33,12 +36,12 @@ function chunks(rows: readonly T[], size = WRITE_CHUNK): T[][] { return out; } -async function requireClient(getClient: GetClient): Promise { +async function requireClient(getClient: GetClient): Promise { const db = await getClient(); if (!db) { throw new Error( - "PM_AGG_STORE_BACKEND=supabase but the Supabase client is unavailable " + - "(management token or project ref missing); refusing to fall back to a local canonical copy", + "PM_AGG_STORE_BACKEND=turso but the Turso store client is unavailable " + + "(store token missing); refusing to fall back to a local canonical copy", ); } return db; @@ -133,7 +136,7 @@ export function actionFromRow(row: Record): DashAction { return action; } -export function createSupabaseActionsRemote(getClient: GetClient = getSupabaseClient): ActionsRemote { +export function createTursoActionsRemote(getClient: GetClient = getTursoStoreClient): ActionsRemote { return { async loadAll(): Promise { const db = await requireClient(getClient); @@ -167,7 +170,7 @@ export function createSupabaseActionsRemote(getClient: GetClient = getSupabaseCl // activity-ingestion.json -> public.agg_activity_ingestion + gaps // --------------------------------------------------------------------- -export function createSupabaseActivityRemote(getClient: GetClient = getSupabaseClient): ActivityRemote { +export function createTursoActivityRemote(getClient: GetClient = getTursoStoreClient): ActivityRemote { return { async load(): Promise { const db = await requireClient(getClient); @@ -282,7 +285,7 @@ export function snapshotRowValues(r: SnapshotRecord): string { ); } -export function createSupabaseSnapshotsRemote(getClient: GetClient = getSupabaseClient): SnapshotsRemote { +export function createTursoSnapshotsRemote(getClient: GetClient = getTursoStoreClient): SnapshotsRemote { return { async readAll(): Promise { const db = await requireClient(getClient); @@ -315,8 +318,8 @@ export function createSupabaseSnapshotsRemote(getClient: GetClient = getSupabase // aa-last-good.json -> public.agg_store_documents // --------------------------------------------------------------------- -export function createSupabaseDocumentRemote( - getClient: GetClient = getSupabaseClient, +export function createTursoDocumentRemote( + getClient: GetClient = getTursoStoreClient, writer: string = storeWriterIdentity(), ): DocumentRemote { return { @@ -342,14 +345,14 @@ export function createSupabaseDocumentRemote( }; } -export function createSupabaseRemotes( - getClient: GetClient = getSupabaseClient, +export function createTursoRemotes( + getClient: GetClient = getTursoStoreClient, writer: string = storeWriterIdentity(), ): StoreRemotes { return { - actions: createSupabaseActionsRemote(getClient), - activity: createSupabaseActivityRemote(getClient), - usage: createSupabaseSnapshotsRemote(getClient), - aaLastGood: createSupabaseDocumentRemote(getClient, writer), + actions: createTursoActionsRemote(getClient), + activity: createTursoActivityRemote(getClient), + usage: createTursoSnapshotsRemote(getClient), + aaLastGood: createTursoDocumentRemote(getClient, writer), }; } diff --git a/pm-stack/aggregator/src/saas-extract.ts b/pm-stack/aggregator/src/saas-extract.ts index 728372839f..cc435e75d6 100644 --- a/pm-stack/aggregator/src/saas-extract.ts +++ b/pm-stack/aggregator/src/saas-extract.ts @@ -25,7 +25,7 @@ import type { UsageMetric, } from "./model.ts"; import { sectionOf } from "./quota-extract.ts"; -import { isFiniteNumber, isNonEmptyString, isNonNegative, isRecord, parseIsoDate } from "./validate.ts"; +import { parseIsoDate } from "./validate.ts"; const DATE_RE = /\d{4}-\d{2}-\d{2}/g; @@ -622,8 +622,10 @@ const SERVICE_SPECS: ServiceSpec[] = [ metrics: supabaseMetrics, // supabaseMetrics returns fixed placeholders (no pattern extraction // from the section), so the service is intentionally uninstrumented - // for extraction-health purposes; live numbers arrive through the - // supabase-export overlay instead (Codex P2 on PR #3957). + // for extraction-health purposes (Codex P2 on PR #3957). The card is + // vendor data from the quota view's recorded prose only; nothing + // reads Supabase itself (the muse-dev2 project and its usage + // exporter are gone; every runtime store is on Turso). instrumented: false, shellNote: "Free plan (muse-dev); numerical quotas unknown in local records.", }, @@ -970,8 +972,8 @@ export function applyCloudflareExport( if (!cf) return services; const byId = new Map( // A negative measurement is a broken export, not live data: drop it - // here as applySupabaseExport does, so the metric keeps its prose or - // null fallback instead of stamping a negative used/percent. + // here, so the metric keeps its prose or null fallback instead of + // stamping a negative used/percent. doc.metrics .filter( (m) => m && typeof m.id === "string" && typeof m.used === "number" && Number.isFinite(m.used) && m.used >= 0, @@ -1026,126 +1028,6 @@ function cloudflareAlertsNote(alerts: CloudflareExportAlert[] | undefined): stri return parts.length ? `; ${parts.join("; ")}` : ""; } -// --- Supabase live export overlay (#1050) ----------------------------------- - -/** One metric row of a supabase-quota-export document. */ -export interface SupabaseExportMetric { - id: string; - label?: string; - /** null = the probe could not measure it this tick (a documented gap). */ - used: number | null; - limit?: number | null; - unit?: string; - source?: string; - detail?: string; - /** "approaching-paid-trigger" when used >= 80% of the Free limit. */ - flag?: string; -} - -/** The file-export document written by pm-stack/supabase-export. */ -export interface SupabaseExportDoc { - service?: string; - source?: string; - /** ok | partial (some scope gaps recorded) — measurements are present. */ - status?: string; - measuredAt?: string | null; - project?: string; - ref?: string; - metrics?: SupabaseExportMetric[]; - billing?: { plan?: string; billedUsd?: number; measured?: boolean; source?: string }; - scope?: { endpoint?: string; path?: string; status?: number; note?: string }[]; -} - -/** Freshness bound mirroring the #1151 tick: > 30 min means the producer is - * unreachable/stale and the card falls back to its recorded prose. */ -export const SUPABASE_EXPORT_STALE_MS = 30 * 60 * 1000; - -/** - * Prefer a fresh supabase-export document on the Supabase card (#1050). - * Matching metric ids take `used`, `limit`, `unit` and a measured-at/source - * note from the export; a metric the probe could not measure keeps today's - * null-but-recorded behaviour with the export's gap detail. `billedUsd` - * becomes the export's measured addon read instead of the hardcoded 0 — - * or unknown (null) when the accepted export carries no valid billing - * measurement, so a failed billing probe never renders as $0.00 billed. - * Missing, failed, unparseable or stale documents change nothing. - */ -export function applySupabaseExport( - services: SaasService[], - doc: SupabaseExportDoc | null, - nowMs: number = Date.now(), -): SaasService[] { - if (!doc || (doc.status !== "ok" && doc.status !== "partial")) return services; - // The freshness anchor must be a real calendar date, not merely a - // string Date.parse accepts (#2508, #5018): a non-string or impossible - // timestamp cannot pass the gate and corrupt the card. - if (typeof doc.measuredAt !== "string" || !doc.measuredAt || !Array.isArray(doc.metrics)) return services; - const measured = parseIsoDate(doc.measuredAt); - if (measured === null) return services; - const measuredMs = measured.getTime(); - const measuredAt = doc.measuredAt; - if (nowMs - measuredMs > SUPABASE_EXPORT_STALE_MS || measuredMs > nowMs + 5 * 60 * 1000) return services; - const supabase = services.find((s) => s.id === "supabase"); - if (!supabase) return services; - // Element-wise contract check (#2508): a metric needs a non-empty id, - // and a present used/limit must be finite and non-negative. A metric - // with a null used is a documented gap, not bad data. - const isLiveMetric = (m: unknown): m is SupabaseExportMetric => - isRecord(m) && - isNonEmptyString(m.id) && - (m.used == null || isNonNegative(m.used)) && - (m.limit == null || isNonNegative(m.limit)); - const byId = new Map(doc.metrics.filter(isLiveMetric).map((m) => [m.id, m])); - if (!byId.size) return services; - supabase.metrics = supabase.metrics.map((m) => { - const live = byId.get(m.id); - if (!live) return m; - const unit = live.unit === "gb" || live.unit === "pct" || live.unit === "count" ? live.unit : m.unit; - const used = isFiniteNumber(live.used) ? live.used : null; - const limit = isFiniteNumber(live.limit) ? live.limit : m.limit; - const parts: string[] = []; - if (used == null) { - parts.push(`Not measured this tick${live.detail ? ` — ${live.detail}` : ""}`); - } else { - parts.push(`Live via ${live.source ?? doc.source ?? "file-export/supabase"}, measured ${measuredAt}.`); - if (live.detail) parts.push(live.detail); - if (live.flag === "approaching-paid-trigger") { - parts.push( - "Approaching-paid trigger: at or above 80% of the Free-plan limit (Drew's $30/mo ceiling is the decision context).", - ); - } - } - return { - ...m, - used, - limit, - unit, - percent: used != null && limit != null && limit > 0 ? Math.round((used / limit) * 1000) / 10 : undefined, - note: capUnits(parts.join(" "), 600), - }; - }); - if (doc.billing && doc.billing.measured !== false && isNonNegative(doc.billing.billedUsd)) { - supabase.billedUsd = doc.billing.billedUsd; - } else { - // Codex P2 (PR #2369 re-review, 2026-10-29): an accepted export with no - // valid billing measurement must not keep the hardcoded 0 from - // extractSaasServices — the card is stamped fresh/api below, so $0.00 - // would read as a measured billed amount. Unknown (null) renders as - // no billed line at all. - supabase.billedUsd = null; - } - supabase.plan = doc.billing?.plan - ? `Free plan (${doc.project ?? "supabase"}); measured ${measuredAt}` - : supabase.plan; - supabase.measuredAt = measuredAt.slice(0, 10); - supabase.sourceClass = "api"; - const gapCount = (doc.scope ?? []).filter((s) => typeof s.status === "number" && s.status >= 400).length; - supabase.sourceNote = `Supabase usage collector (#1050): ${doc.source ?? "file-export/supabase"}, measured ${measuredAt}; ${ - gapCount ? `${gapCount} documented scope gap(s) — see the export's scope array` : "every probed endpoint answered" - }; limits from the Free-plan record.`; - return services; -} - // --- PAYG lines (§1.2) ------------------------------------------------------- /** One invoice cycle for the stewardship stale-estimate flag rule diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 47e0ce603a..57a13edb81 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -59,7 +59,7 @@ import { } from "./coverage.ts"; import { loadConfig } from "./config.ts"; import { getTursoStoreClient } from "./turso-stores.ts"; -import { createSupabaseRemotes } from "./remote-stores.ts"; +import { createTursoRemotes } from "./remote-stores.ts"; import { itemServiceLinks } from "./service-links.ts"; import { loadFeed } from "./feed.ts"; import { AA_PLAN_FACTS, sectionPoolIdsFromConfig } from "./aa.ts"; @@ -351,15 +351,10 @@ async function coverageSnapshot( return next; } // #6815: the four formerly laptop-local stores (actions, activity -// ingestion, usage snapshots, aa-last-good) move to muse-dev2 when -// PM_AGG_STORE_BACKEND=supabase. Exactly one backend is active: with +// ingestion, usage snapshots, aa-last-good) live in Turso when +// PM_AGG_STORE_BACKEND=turso. Exactly one backend is active: with // "file" (the default) no remote exists and no database call is made. -const storeRemotes = - cfg.storeBackend === "turso" - ? createSupabaseRemotes(getTursoStoreClient) - : cfg.storeBackend === "supabase" - ? createSupabaseRemotes() - : null; +const storeRemotes = cfg.storeBackend === "turso" ? createTursoRemotes(getTursoStoreClient) : null; const actionsStore = new ActionsStore(cfg.actionsFile, undefined, storeRemotes?.actions); const viewsStore = new ViewsStore(cfg.viewsFile); const eventsStore = new EventsStore(cfg.eventsFile); diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 0bc74a91fa..25feb83c80 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -57,7 +57,6 @@ import { summarizeDns } from "../dns.ts"; import { applyCloudflareExport, applyPaygSettlements, - applySupabaseExport, extractCharges, extractPaygLines, extractSaasServices, @@ -65,7 +64,7 @@ import { extractUninstrumentedServices, } from "../saas-extract.ts"; import { mergeChargeRows } from "../charges-collect.ts"; -import type { CloudflareExportDoc, SupabaseExportDoc } from "../saas-extract.ts"; +import type { CloudflareExportDoc } from "../saas-extract.ts"; import { poolItemToGhItem } from "../projects.ts"; import { createNeedsDrewSweeper, type NeedsDrewCensus } from "../needs-drew.ts"; import { INITIAL_STANDING_AUTO, sanitizeTierItemExtensions, withUserFallbacks } from "../tier-items.ts"; @@ -919,7 +918,7 @@ export function liveSource( // reissue an undated delivery id that dedupe would discard. seenActivityIds?: (source: string) => Promise | readonly string[]; /** #6815: usage-snapshot backend. Set only when - * PM_AGG_STORE_BACKEND=supabase; otherwise the local snapshot + * PM_AGG_STORE_BACKEND=turso; otherwise the local snapshot * directory is the store (the dev/test and rollback path). */ snapshotRemote?: SnapshotsRemote; }, @@ -1964,13 +1963,6 @@ export function liveSource( domainCount: feed.dns.entries.length, } : null; - // The Supabase export overlay applies to BOTH service sources: - // the collector's feed.saas cards are built with plain - // extractSaasServices, so without this the fresh export would be - // ignored exactly when the fleet collector is operating (#1050). - const supabaseExport = await readFile(cfg.supabaseExportFile, "utf8") - .then((text) => JSON.parse(text) as SupabaseExportDoc) - .catch(() => null); // Charges evidence + unmatched-charge flags (#3124): computed // once, before the branch. The feed's charge data is not a // byproduct of the saas section, so every return path below @@ -2013,7 +2005,7 @@ export function liveSource( .then((text) => JSON.parse(text) as CloudflareExportDoc) .catch(() => null); const partial = { - services: applySupabaseExport(applyCloudflareExport(feed.saas, cfExport), supabaseExport), + services: applyCloudflareExport(feed.saas, cfExport), uninstrumentedServices, // #1056: feed lines are built by the collector without // settlements — reconcile them against local history here, @@ -2055,7 +2047,7 @@ export function liveSource( // full-row equality would display it twice; automatic // evidence (the feed rows) takes precedence. const partial = { - services: applySupabaseExport(applyCloudflareExport(extractSaasServices(doc), cfExport), supabaseExport), + services: applyCloudflareExport(extractSaasServices(doc), cfExport), uninstrumentedServices, payg: extractPaygLines(doc, registryText, { settlements: Object.values(history).flat() }), charges: mergeChargeRows(feedCharges, extractCharges(doc, registryText)), @@ -2277,7 +2269,7 @@ export function liveSource( }, async aa(batch?: string | null): Promise { // AA cost explorer: the section rides the fleet feed, read from - // Supabase ainventory by the collector. Its absent form is a real + // Turso ainventory tables by the collector. Its absent form is a real // section (the page renders the reason); a missing section means // the collector has not embedded one yet. const feed = await getFeed(); diff --git a/pm-stack/aggregator/src/sql-client.ts b/pm-stack/aggregator/src/sql-client.ts new file mode 100644 index 0000000000..625c1a214b --- /dev/null +++ b/pm-stack/aggregator/src/sql-client.ts @@ -0,0 +1,27 @@ +// The SQL client contract shared by the remote stores (remote-stores.ts) +// and the alerts ledger (alerts.ts), plus the literal helpers they use to +// build statements. The only remote implementation is the Turso store +// client (turso-stores.ts), whose storeStatement() turns every literal +// produced here into a typed argument before it rewrites any syntax. + +/** Escape a string as a SQL string literal (standard-conforming strings: + * doubling the single quote is sufficient). */ +export function sqlStr(v: string): string { + return `'${v.replaceAll("'", "''")}'`; +} + +/** Escape a value as a jsonb literal. */ +export function sqlJson(v: unknown): string { + return `${sqlStr(JSON.stringify(v ?? null))}::jsonb`; +} + +/** Validate + render an integer for SQL interpolation. */ +export function sqlInt(v: number): string { + if (!Number.isFinite(v) || Math.floor(v) !== v) throw new Error(`not an integer: ${v}`); + return String(v); +} + +export interface SqlClient { + ref: string; + query>(sql: string): Promise; +} diff --git a/pm-stack/aggregator/src/store-backend.ts b/pm-stack/aggregator/src/store-backend.ts index d5bdb6606e..a370ac9553 100644 --- a/pm-stack/aggregator/src/store-backend.ts +++ b/pm-stack/aggregator/src/store-backend.ts @@ -1,29 +1,27 @@ -// Store backend selection for the four aggregator stores that became -// Supabase-backed in #6815 (actions, activity-ingestion, usage +// Store backend selection for the four aggregator stores that moved off +// laptop-local files in #6815 (actions, activity-ingestion, usage // snapshots, aa-last-good). // // `PM_AGG_STORE_BACKEND` is the single switch: // - "file" (default): the historical laptop-local files. This is the // dev/test path and the rollback target. -// - "supabase": the canonical muse-dev2 tables from +// - "turso": the canonical Turso tables from // shared-schema/migrations/20261116_0001_aggregator_remote_stores.up.sql -// (plus public.agg_actions from 20261105_0001). +// (plus agg_actions from 20261105_0001), via src/turso-stores.ts. // // Exactly one backend is active. The stores never dual-write: in -// supabase mode the local files are not read or written by the store +// turso mode the local files are not read or written by the store // classes, and in file mode no database call is made. An unavailable -// Supabase client in supabase mode is an error, never a silent fallback -// to a local canonical copy. -export type StoreBackendKind = "file" | "supabase" | "turso"; +// Turso client in turso mode is an error, never a silent fallback to a +// local canonical copy. Any other value (including the retired +// "supabase") fails startup loudly. +export type StoreBackendKind = "file" | "turso"; export function parseStoreBackend(env: Record = process.env): StoreBackendKind { const raw = (env.PM_AGG_STORE_BACKEND ?? "").trim(); if (raw === "" || raw === "file") return "file"; - if (raw === "supabase") return "supabase"; if (raw === "turso") return "turso"; - throw new Error( - `Invalid PM_AGG_STORE_BACKEND=${JSON.stringify(env.PM_AGG_STORE_BACKEND)}; expected "file", "supabase", or "turso"`, - ); + throw new Error(`Invalid PM_AGG_STORE_BACKEND=${JSON.stringify(env.PM_AGG_STORE_BACKEND)}; expected "file" or "turso"`); } /** Recorded on every remote write so the single writer is auditable. */ diff --git a/pm-stack/aggregator/src/supabase.ts b/pm-stack/aggregator/src/supabase.ts deleted file mode 100644 index b0226de4f8..0000000000 --- a/pm-stack/aggregator/src/supabase.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Supabase access for the aggregator — the same Management API path the -// fleet-feed collector uses (scripts/collect-fleet-feed.ts): SQL -// over the Management API query endpoint, authenticated with the -// Bitwarden secret named `supabase.muse-dev2.access-token-muse-cli` (the sbp_ -// management token), project ref from $SUPABASE_PROJECT_REF or the canonical -// Bitwarden `supabase.project-ref` pointer. -// The token is only ever sent to api.supabase.com; it is never logged. -import { resolveBwsSecret } from "./secrets.ts"; - -/** Escape a string as a SQL string literal (standard-conforming strings: - * doubling the single quote is sufficient). */ -export function sqlStr(v: string): string { - return `'${v.replaceAll("'", "''")}'`; -} - -/** Escape a value as a jsonb literal. */ -export function sqlJson(v: unknown): string { - return `${sqlStr(JSON.stringify(v ?? null))}::jsonb`; -} - -/** Validate + render an integer for SQL interpolation. */ -export function sqlInt(v: number): string { - if (!Number.isFinite(v) || Math.floor(v) !== v) throw new Error(`not an integer: ${v}`); - return String(v); -} - -export interface SupabaseClient { - ref: string; - query>(sql: string): Promise; -} - -/** Resolve the current project ref without pinning a project in source. */ -export async function resolveSupabaseProjectRef( - resolveSecret: typeof resolveBwsSecret = resolveBwsSecret, - env: Readonly> = process.env, -): Promise { - const override = env.SUPABASE_PROJECT_REF?.trim(); - if (override) return override; - // #6815: the canonical BWS entry is the environment-scoped - // `supabase.muse-dev2.project-ref`; the older unscoped pointer is kept - // as a first choice for deployments that still carry it. - const ref = (await resolveSecret("supabase.project-ref")) ?? (await resolveSecret("supabase.muse-dev2.project-ref")); - return ref?.trim() || null; -} - -async function supabaseQuery(token: string, ref: string, sql: string): Promise { - const res = await fetch(`https://api.supabase.com/v1/projects/${ref}/database/query`, { - method: "POST", - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - body: JSON.stringify({ query: sql }), - signal: AbortSignal.timeout(60_000), - }); - if (!res.ok) throw new Error(`Supabase query failed (HTTP ${res.status})`); - return res.json(); -} - -/** - * Create the shared Supabase client resolver. In-flight calls share one - * attempt and successful clients stay cached; a null result is fail-soft - * but not permanent, so a later call can recover. - * Lazy-init contract (success-only memoization): README "Lazy-initialization contract" (#3879). - */ -export function createSupabaseClientGetter( - resolveSecret: typeof resolveBwsSecret = resolveBwsSecret, -): () => Promise { - let clientPromise: Promise | null = null; - - return function getSupabaseClient(): Promise { - if (!clientPromise) { - const pending = (async () => { - const token = await resolveSecret("supabase.muse-dev2.access-token-muse-cli"); - if (!token) return null; - const ref = await resolveSupabaseProjectRef(resolveSecret); - if (!ref) return null; - return { - ref, - async query>(sql: string): Promise { - const out = await supabaseQuery(token, ref, sql); - return (Array.isArray(out) ? out : []) as T[]; - }, - }; - })().catch(() => null); - clientPromise = pending; - void pending.then((client) => { - if (client === null && clientPromise === pending) clientPromise = null; - }); - } - return clientPromise; - }; -} - -/** The shared Supabase client, fail-soft while its management token or project ref is unavailable. */ -export const getSupabaseClient = createSupabaseClientGetter(); diff --git a/pm-stack/aggregator/src/turso-stores.ts b/pm-stack/aggregator/src/turso-stores.ts index 36075d9284..4491fb0750 100644 --- a/pm-stack/aggregator/src/turso-stores.ts +++ b/pm-stack/aggregator/src/turso-stores.ts @@ -3,7 +3,7 @@ // not an arbitrary PostgreSQL query translator. Literals become typed args // BEFORE rewriting syntax, so user text/JSON can never be rewritten as SQL. import { resolveBwsSecret } from "./secrets.ts"; -import type { SupabaseClient } from "./supabase.ts"; +import type { SqlClient } from "./sql-client.ts"; import { DECISION_EVENTS_TURSO_URL, DECISION_EVENTS_TURSO_TOKEN_NAME } from "./decision-events-sync.ts"; export type StoreArg = { type: "text"; value: string }; @@ -95,7 +95,7 @@ export function decodeStoreRow(row: Record): Record Promise { - let cached: Promise | null = null; +export function createTursoStoreGetter(resolveSecret = resolveBwsSecret): () => Promise { + let cached: Promise | null = null; return () => { if (!cached) { const pending = (async () => { diff --git a/pm-stack/aggregator/test/aa-gate-5289.test.ts b/pm-stack/aggregator/test/aa-gate-5289.test.ts index f841d58880..acd5dd463e 100644 --- a/pm-stack/aggregator/test/aa-gate-5289.test.ts +++ b/pm-stack/aggregator/test/aa-gate-5289.test.ts @@ -51,7 +51,7 @@ describe("isAaSection snapshotDate validity (#5289)", () => { }); test("accepts collector-built test runs (testRunsFromSheetRows output)", () => { - // aaSectionFromSupabase builds its testRuns with + // aaSectionFromPayload builds its testRuns with // testRunsFromSheetRows: a real sheet date stays a date-only // string and an empty snapshot_date cell becomes null. const rows = [ diff --git a/pm-stack/aggregator/test/aa.test.ts b/pm-stack/aggregator/test/aa.test.ts index 3ae7c3160a..37ecb9a0f2 100644 --- a/pm-stack/aggregator/test/aa.test.ts +++ b/pm-stack/aggregator/test/aa.test.ts @@ -16,7 +16,7 @@ import { caiFamily, num, aaApplyPriceOverlay, - aaSectionFromSupabase, + aaSectionFromPayload, computeAaCoverage, effortRank, isAaSection, @@ -273,7 +273,7 @@ function rawPayload(): AaRawPayload { describe("payload assembly + section shape", () => { test("string numerics from the Management API are coerced; coverage computed when config parses", () => { - const section = aaSectionFromSupabase(rawPayload(), CONFIG_SNIPPET, "2026-10-26T18:05:00Z"); + const section = aaSectionFromPayload(rawPayload(), CONFIG_SNIPPET, "2026-10-26T18:05:00Z"); expect(section).not.toBeNull(); expect(section!.status).toBe("ok"); expect(section!.rankings[0].costTask).toBe(0.07); @@ -285,7 +285,7 @@ describe("payload assembly + section shape", () => { }); test("the same config read also builds the Model Explorer catalog", () => { - const section = aaSectionFromSupabase(rawPayload(), CONFIG_SNIPPET, "2026-10-26T18:05:00Z"); + const section = aaSectionFromPayload(rawPayload(), CONFIG_SNIPPET, "2026-10-26T18:05:00Z"); const catalog = section!.catalog; expect(catalog).toBeDefined(); const luna = catalog!.find((e) => e.id === "openai/gpt-6-luna")!; @@ -300,19 +300,19 @@ describe("payload assembly + section shape", () => { }); test("unparseable config omits the catalog with the coverage", () => { - const section = aaSectionFromSupabase(rawPayload(), "{ nope", "2026-10-26T18:05:00Z"); + const section = aaSectionFromPayload(rawPayload(), "{ nope", "2026-10-26T18:05:00Z"); expect(section?.catalog).toBeUndefined(); }); test("unparseable config omits coverage but keeps the section", () => { - const section = aaSectionFromSupabase(rawPayload(), "{ nope", "2026-10-26T18:05:00Z"); + const section = aaSectionFromPayload(rawPayload(), "{ nope", "2026-10-26T18:05:00Z"); expect(section?.status).toBe("ok"); expect(section?.coverage).toBeUndefined(); expect(isAaSection(section)).toBe(true); }); test("isAaSection accepts the absent form, rejects junk", () => { - expect(isAaSection(aaAbsent("Supabase unreachable", "2026-10-26T18:05:00Z"))).toBe(true); + expect(isAaSection(aaAbsent("Turso unreachable", "2026-10-26T18:05:00Z"))).toBe(true); expect(isAaSection(null)).toBe(false); expect(isAaSection({ status: "ok" })).toBe(false); expect(isAaSection({ status: "absent", reason: 42 })).toBe(false); @@ -320,9 +320,9 @@ describe("payload assembly + section shape", () => { }); test("isAaSection rejects the absent form with impossible generatedAt dates (#3441)", () => { - expect(isAaSection(aaAbsent("Supabase unreachable", "2026-10-26T18:05:00Z"))).toBe(true); + expect(isAaSection(aaAbsent("Turso unreachable", "2026-10-26T18:05:00Z"))).toBe(true); for (const generatedAt of ["2026-02-30T00:00:00Z", "2026-02-29T00:00:00Z", "2026-04-31T00:00:00Z"]) { - expect(isAaSection(aaAbsent("Supabase unreachable", generatedAt))).toBe(false); + expect(isAaSection(aaAbsent("Turso unreachable", generatedAt))).toBe(false); } }); @@ -619,7 +619,7 @@ describe("price overlay re-derivation (#8211)", () => { const raw = rawPayload(); raw.batch = batch; raw.prices = prices; - return aaSectionFromSupabase(raw, CONFIG_SNIPPET, "2026-10-26T18:05:00Z")!; + return aaSectionFromPayload(raw, CONFIG_SNIPPET, "2026-10-26T18:05:00Z")!; }; test("two cached batches with differing prices both report the refreshed overlay's rates", () => { @@ -736,8 +736,8 @@ describe("aa-explorer manifest + render", () => { test("null and absent sections render honest banners, no tables", () => { const missing = renderAa(null, PROV); expect(missing).toContain("has not reached the dashboard yet"); - const absent = renderAa(aaAbsent("Supabase query failed (HTTP 500)", "2026-10-26T18:05:00Z"), PROV); - expect(absent).toContain("Supabase query failed (HTTP 500)"); + const absent = renderAa(aaAbsent("Turso store query failed (HTTP 500)", "2026-10-26T18:05:00Z"), PROV); + expect(absent).toContain("Turso store query failed (HTTP 500)"); expect(absent).not.toContain("Rankings"); }); @@ -1004,7 +1004,7 @@ describe("prototype-key lookups in aa maps (#3056)", () => { cost: "1", wallSec: "60", }); - const section = aaSectionFromSupabase( + const section = aaSectionFromPayload( { ...rawPayload(), cai: [caiRow("constructor"), caiRow("__proto__"), caiRow("deepseek"), caiRow("acme")] }, null, "2026-10-26T18:05:00Z", diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index 62e1627562..75274cf84f 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -42,7 +42,7 @@ import { } from "../src/push.ts"; import { renderAlerts } from "../src/render.ts"; import type { Provenance } from "../src/model.ts"; -import { sqlInt, sqlJson, sqlStr, type SupabaseClient } from "../src/supabase.ts"; +import { sqlInt, sqlJson, sqlStr, type SqlClient } from "../src/sql-client.ts"; import { needsDrewIncidentKey } from "../src/needs-drew.ts"; import type { Config } from "../src/config.ts"; import type { NotificationHistoryEntry, NotificationSnapshot } from "../src/notifications.ts"; @@ -50,15 +50,15 @@ import type { NotificationHistoryEntry, NotificationSnapshot } from "../src/noti describe("getAlertsStore retry-after-null memoization", () => { test("retries a null client, shares the next in-flight attempt, and caches success", async () => { let clientCalls = 0; - let resolveFirst!: (value: SupabaseClient | null) => void; - const firstResult = new Promise((resolve) => { + let resolveFirst!: (value: SqlClient | null) => void; + const firstResult = new Promise((resolve) => { resolveFirst = resolve; }); - let resolveRetry!: (value: SupabaseClient | null) => void; - const retryResult = new Promise((resolve) => { + let resolveRetry!: (value: SqlClient | null) => void; + const retryResult = new Promise((resolve) => { resolveRetry = resolve; }); - const fakeClient: SupabaseClient = { + const fakeClient: SqlClient = { ref: "test-project", async query() { return [] as T[]; @@ -264,7 +264,7 @@ describe("stored subscription preference reads (#4978)", () => { }, ]; const queries: string[] = []; - const db: SupabaseClient = { + const db: SqlClient = { ref: "test", async query(sql: string): Promise { queries.push(sql); @@ -469,7 +469,7 @@ function alertTickStore( } function pendingIncidentStore(rows: Incident[]): AlertsStore { - const db: SupabaseClient = { + const db: SqlClient = { ref: "test", async query(sql: string): Promise { const orderColumn = /order by (first_seen_at|delivered_at)/i.exec(sql)?.[1] as @@ -1126,7 +1126,7 @@ describe("subscription class preservation (#7193 Codex)", () => { describe("closeOpenIncidentByKey — the needs-drew answer close (#8605)", () => { function storeWith(rows: Incident[]) { const calls: string[] = []; - const db: SupabaseClient = { + const db: SqlClient = { ref: "test", async query(sql: string): Promise { calls.push(sql); diff --git a/pm-stack/aggregator/test/attention-no-fixtures-1116.test.ts b/pm-stack/aggregator/test/attention-no-fixtures-1116.test.ts index 64025d4baf..23abd72acf 100644 --- a/pm-stack/aggregator/test/attention-no-fixtures-1116.test.ts +++ b/pm-stack/aggregator/test/attention-no-fixtures-1116.test.ts @@ -50,7 +50,6 @@ async function makeSource(opts: { PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile, PM_AGG_QUOTA_VIEW: join(dir, "no-quota-view.md"), - PM_AGG_SUPABASE_EXPORT: join(dir, "no-supabase-export.json"), PM_AGG_CLOUDFLARE_EXPORT: join(dir, "no-cloudflare-export.json"), PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), diff --git a/pm-stack/aggregator/test/charges-feed-gate.test.ts b/pm-stack/aggregator/test/charges-feed-gate.test.ts index 4d98af3fca..22013998ce 100644 --- a/pm-stack/aggregator/test/charges-feed-gate.test.ts +++ b/pm-stack/aggregator/test/charges-feed-gate.test.ts @@ -58,7 +58,6 @@ async function sourceWith(opts: { PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile, PM_AGG_QUOTA_VIEW: quotaViewFile, - PM_AGG_SUPABASE_EXPORT: join(dir, "no-supabase-export.json"), PM_AGG_CLOUDFLARE_EXPORT: join(dir, "no-cloudflare-export.json"), PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), diff --git a/pm-stack/aggregator/test/cloudflare-export.test.ts b/pm-stack/aggregator/test/cloudflare-export.test.ts index 0b10b2d6fb..b7cc9350de 100644 --- a/pm-stack/aggregator/test/cloudflare-export.test.ts +++ b/pm-stack/aggregator/test/cloudflare-export.test.ts @@ -56,7 +56,7 @@ describe("applyCloudflareExport", () => { expect(cf.sourceNote).toContain("invoice-only"); }); - test("a negative used value is refused, like the Supabase overlay", () => { + test("a negative used value is refused, not stamped as live data", () => { const doc = freshDoc(); doc.metrics = [ { id: "workers-requests", used: -500, unit: "count", source: "cloudflare-graphql-analytics" }, diff --git a/pm-stack/aggregator/test/feed-attention-filter-2427.test.ts b/pm-stack/aggregator/test/feed-attention-filter-2427.test.ts index c5f193862d..bdca52d02c 100644 --- a/pm-stack/aggregator/test/feed-attention-filter-2427.test.ts +++ b/pm-stack/aggregator/test/feed-attention-filter-2427.test.ts @@ -26,7 +26,6 @@ async function sourceWithAttention(attention: unknown[]): Promise): string { + return JSON.stringify({ + version: 1, + generatedAt: nowIso, + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + saas: extractSaasServices(VIEW), + snapshots: [record], + }); +} + +function snapshotRecord(nowIso: string) { + return { + ts: nowIso, + serviceId: "turso", + metricId: "rows-read", + value: 1154, + unit: "count", + source: "api", + observedBy: "fleet-feed-collector", + }; +} + +describe("live source usage(): fleet-feed snapshot history", () => { + test("usage reads feed history without writing to a read-only snapshot store", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-usage-readonly-")); + const feedFile = join(dir, "fleet-feed.json"); + const snapshotsDir = join(dir, "snapshots"); + const nowIso = new Date().toISOString(); + try { + await mkdir(snapshotsDir); + await chmod(snapshotsDir, 0o555); + await writeFile(feedFile, feedWith(nowIso, snapshotRecord(nowIso))); + const usage = await liveSource(liveConfig(dir, feedFile, snapshotsDir)).usage(); + expect(usage.services.some((service) => service.id === "turso")).toBe(true); + expect(await readdir(snapshotsDir)).toEqual([]); + } finally { + await chmod(snapshotsDir, 0o755).catch(() => {}); + await rm(dir, { recursive: true, force: true }); + } + }); + + test("background ingestion lands feed records idempotently", async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-usage-ingest-")); + const feedFile = join(dir, "fleet-feed.json"); + const snapshotsDir = join(dir, "snapshots"); + const nowIso = new Date().toISOString(); + const record = snapshotRecord(nowIso); + try { + await writeFile(feedFile, feedWith(nowIso, record)); + const source = liveSource(liveConfig(dir, feedFile, snapshotsDir)); + expect(await source.ingestSnapshots?.()).toBe(1); + expect(await source.ingestSnapshots?.()).toBe(0); + expect(await new SnapshotStore(snapshotsDir).byService()).toMatchObject({ turso: [record] }); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index 3a73650917..ba1f247abe 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -17,7 +17,7 @@ import { AlertsStore, type NotificationSendRow } from "../src/alerts.ts"; import { renderNotifications } from "../src/render.ts"; import { JsonlNotificationHistory } from "../src/notification-history.ts"; import type { Provenance } from "../src/model.ts"; -import type { SupabaseClient } from "../src/supabase.ts"; +import type { SqlClient } from "../src/sql-client.ts"; const TASK_NOW = Date.parse("2026-11-03T18:00:00Z"); @@ -411,7 +411,7 @@ describe("rollupNotificationSends", () => { describe("AlertsStore.listSends", () => { test("reads the notification_sends ledger", async () => { const rows = [send({})]; - const db: SupabaseClient = { + const db: SqlClient = { ref: "test", async query(sql: string): Promise { expect(sql).toContain("alerts.notification_sends"); diff --git a/pm-stack/aggregator/test/orchestration-db.test.ts b/pm-stack/aggregator/test/orchestration-db.test.ts index 8309b0b03e..613189b4e3 100644 --- a/pm-stack/aggregator/test/orchestration-db.test.ts +++ b/pm-stack/aggregator/test/orchestration-db.test.ts @@ -72,7 +72,7 @@ describe("resolveOrchestrationDocument", () => { const res = await resolveOrchestrationDocument({ source: "db", readDb: async () => { - throw new Error("Supabase query failed (HTTP 503)"); + throw new Error("Turso store query failed (HTTP 503)"); }, readFile: async () => fileDoc, validate, @@ -101,7 +101,7 @@ describe("resolveOrchestrationDocument", () => { const res = await resolveOrchestrationDocument({ source: "db", readDb: async () => { - throw new Error("no Supabase management token available (bws)"); + throw new Error("no Turso store token available (bws)"); }, readFile: async () => { throw enoent; @@ -110,7 +110,7 @@ describe("resolveOrchestrationDocument", () => { }); expect(res.document).toBeNull(); expect(res.source).toBeNull(); - expect(res.dbError).toContain("management token"); + expect(res.dbError).toContain("store token"); expect(res.fileMissing).toBe(true); }); diff --git a/pm-stack/aggregator/test/phase3-boundaries.test.ts b/pm-stack/aggregator/test/phase3-boundaries.test.ts index 8e9c8b6b8a..7f40e8dcbe 100644 --- a/pm-stack/aggregator/test/phase3-boundaries.test.ts +++ b/pm-stack/aggregator/test/phase3-boundaries.test.ts @@ -4,13 +4,10 @@ // boundary — retain (error entry), drop-and-count, or refuse — never a // throw, a fabricated row, or live out-of-range data. import { describe, expect, test } from "bun:test"; -import { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts"; import { entryFromFileExport, entryFromResult, entryFromTurso } from "../src/quota-gather-map.ts"; import { extractQuotaPools } from "../src/quota-extract.ts"; import { aggregateBillingUsage } from "../src/sources/github-billing.ts"; -const NOW = Date.parse("2026-10-29T15:00:00Z"); - function metaDoc(overrides: Record = {}) { return { service: "meta", @@ -129,74 +126,6 @@ describe("entryFromTurso (#2553)", () => { }); }); -const SUPABASE_VIEW = ` -## Summary (b) — subscriptions, infrastructure, account tooling - -| Service | Plan / price | Allowance sketch | Usage / status | Next date recorded | -|---|---|---|---|---| -| Supabase | Free plan (muse-dev) | DB + egress + storage | manual dashboard read needed | unknown | - -## Service details (b) - -### Supabase -- **Plan / price:** Free plan (muse-dev); numerical quotas unknown in local records. -- **Usage / dates:** Not measured — manual dashboard read needed. -- **Last checked:** 2026-10-28. -`; - -function supabaseDoc(overrides: Partial = {}): SupabaseExportDoc { - return { - service: "supabase", - source: "file-export/supabase", - status: "partial", - measuredAt: "2026-10-29T14:55:00Z", - project: "muse-dev", - metrics: [{ id: "egress", label: "Egress", used: 1.25, limit: 5, unit: "gb" }], - billing: { measured: true, billedUsd: 0 }, - ...overrides, - }; -} - -describe("applySupabaseExport (#2508)", () => { - test("a non-string measuredAt cannot pass the freshness gate", () => { - const services = extractSaasServices(SUPABASE_VIEW); - const out = applySupabaseExport(services, supabaseDoc({ measuredAt: [2026, 10, 29] as never }), NOW); - expect(out).toEqual(services); - }); - - test("an impossible measuredAt is rejected, not rolled over", () => { - const services = extractSaasServices(SUPABASE_VIEW); - const out = applySupabaseExport(services, supabaseDoc({ measuredAt: "2026-02-30T00:00:00Z" }), NOW); - expect(out).toEqual(services); - }); - - test("negative used/limit are dropped; valid siblings still apply", () => { - const services = extractSaasServices(SUPABASE_VIEW); - const out = applySupabaseExport( - services, - supabaseDoc({ - metrics: [ - { id: "egress", label: "Egress", used: 1.25, limit: 5, unit: "gb" }, - { id: "db-size", label: "DB", used: -1, limit: 0.5, unit: "gb" }, - { id: "storage", label: "Storage", used: 0.5, limit: -2, unit: "gb" }, - ], - }), - NOW, - ); - const supabase = out.find((s) => s.id === "supabase")!; - const egress = supabase.metrics.find((m) => m.id === "egress")!; - expect(egress.used).toBe(1.25); - const db = supabase.metrics.find((m) => m.id === "db-size")!; - expect(db.used).not.toBe(-1); - }); - - test("negative billedUsd is refused", () => { - const services = extractSaasServices(SUPABASE_VIEW); - const out = applySupabaseExport(services, supabaseDoc({ billing: { measured: true, billedUsd: -5 } }), NOW); - expect(out.find((s) => s.id === "supabase")!.billedUsd).toBeNull(); - }); -}); - const CLINE_VIEW = (measured: string, offset: string) => ` ### ClinePass diff --git a/pm-stack/aggregator/test/saas-extract-surrogate-7743.test.ts b/pm-stack/aggregator/test/saas-extract-surrogate-7743.test.ts index c4ad399cb3..74b728afbc 100644 --- a/pm-stack/aggregator/test/saas-extract-surrogate-7743.test.ts +++ b/pm-stack/aggregator/test/saas-extract-surrogate-7743.test.ts @@ -1,12 +1,12 @@ // #7743: saas-extract.ts capped six extracted text fields with raw slices -// (reads/conflicts 400, PAYG notes 300/220, usageNote 600, Supabase metric -// note 600) — an astral character straddling any cap was split, leaving a +// (reads/conflicts 400, PAYG notes 300/220, usageNote 600, and a +// since-removed export-overlay metric note 600) — an astral character straddling any cap was split, leaving a // lone high surrogate in the SaasService field that is serialized into the // feed/board JSON (the #3178 class; #7694/#7711 fixed the same defect for // neighbouring modules via capUnits, and #7741's audit of the remaining // slices missed this module). import { describe, expect, test } from "bun:test"; -import { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts"; +import { extractSaasServices } from "../src/saas-extract.ts"; const EMOJI = "\u{1F600}"; // 😀 — one astral character, two UTF-16 units const loneHighAtEnd = (s: string) => { @@ -82,44 +82,3 @@ describe("#7743 extractSaasServices caps are surrogate-pair-safe", () => { expect(roundTrips(note)).toBe(true); }); }); - -describe("#7743 applySupabaseExport metric note cap is surrogate-pair-safe", () => { - const VIEW = ` -## Summary (b) - -| Service | Plan / price | Allowance sketch | Usage / status | Next date recorded | -|---|---|---|---|---| -| Supabase | Free plan (muse-dev2) | DB + egress + storage | manual dashboard read needed | unknown | - -### Supabase -- **Plan / price:** Free plan (muse-dev2); numerical quotas unknown in local records. -- **Usage / dates:** Not measured — manual dashboard read needed. -- **Last checked:** 2026-10-28. -`; - const NOW = Date.parse("2026-10-29T15:00:00Z"); - // note = "Live via file-export/supabase, measured 2026-10-29T14:45:00.000Z. " (66) + detail - const run = (detail: string) => { - const doc = { - status: "ok", - measuredAt: "2026-10-29T14:45:00.000Z", - source: "file-export/supabase", - metrics: [{ id: "db-size", used: 1, limit: 10, unit: "gb", detail }], - } as unknown as SupabaseExportDoc; - const out = applySupabaseExport(extractSaasServices(VIEW), doc, NOW); - return out.find((s) => s.id === "supabase")!.metrics.find((m) => m.id === "db-size")!.note!; - }; - - test("metric note straddling the 600 cap is dropped whole", () => { - const note = run("a".repeat(533) + EMOJI + "zzzz"); - expect(note.length).toBe(599); - expect(loneHighAtEnd(note)).toBe(false); - expect(roundTrips(note)).toBe(true); - }); - - test("metric note pair ending exactly at the 600 cap stays intact (control)", () => { - const note = run("a".repeat(532) + EMOJI); - expect(note.length).toBe(600); - expect(note.endsWith(EMOJI)).toBe(true); - expect(roundTrips(note)).toBe(true); - }); -}); diff --git a/pm-stack/aggregator/test/saas-feed-gate.test.ts b/pm-stack/aggregator/test/saas-feed-gate.test.ts index fbd58ce02c..d7863c5709 100644 --- a/pm-stack/aggregator/test/saas-feed-gate.test.ts +++ b/pm-stack/aggregator/test/saas-feed-gate.test.ts @@ -61,7 +61,6 @@ async function sourceWith(saas: unknown, quotaView = VIEW) { PM_AGG_SOURCE: "live", PM_AGG_FEED_FILE: feedFile, PM_AGG_QUOTA_VIEW: quotaViewFile, - PM_AGG_SUPABASE_EXPORT: join(dir, "no-supabase-export.json"), PM_AGG_CLOUDFLARE_EXPORT: join(dir, "no-cloudflare-export.json"), PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), diff --git a/pm-stack/aggregator/test/store-remote-backends.test.ts b/pm-stack/aggregator/test/store-remote-backends.test.ts index e78babe3a8..bde2c69191 100644 --- a/pm-stack/aggregator/test/store-remote-backends.test.ts +++ b/pm-stack/aggregator/test/store-remote-backends.test.ts @@ -1,6 +1,6 @@ -// #6815: the four aggregator stores move to Supabase muse-dev2 behind +// #6815: the four aggregator stores move to a remote store (Turso) behind // PM_AGG_STORE_BACKEND. These tests pin the one-backend-at-a-time -// contract: in supabase mode the store reads/writes only its remote and +// contract: in turso mode the store reads/writes only its remote and // creates no local canonical file; in file mode no remote is touched. // // The fakes are the oracles: each implements the store's remote @@ -25,13 +25,13 @@ import { AA_LAST_GOOD_DOCUMENT, parseStoreBackend } from "../src/store-backend.t import { actionFromRow, actionRowValues, - createSupabaseActionsRemote, - createSupabaseDocumentRemote, - createSupabaseSnapshotsRemote, + createTursoActionsRemote, + createTursoDocumentRemote, + createTursoSnapshotsRemote, snapshotFromRow, snapshotRowValues, } from "../src/remote-stores.ts"; -import type { SupabaseClient } from "../src/supabase.ts"; +import type { SqlClient } from "../src/sql-client.ts"; const tmp = (label: string): string => mkdtempSync(join(tmpdir(), `agg-stores-${label}-`)); @@ -129,9 +129,15 @@ describe("PM_AGG_STORE_BACKEND parsing", () => { expect(parseStoreBackend({})).toBe("file"); expect(parseStoreBackend({ PM_AGG_STORE_BACKEND: " " })).toBe("file"); expect(parseStoreBackend({ PM_AGG_STORE_BACKEND: "file" })).toBe("file"); - expect(parseStoreBackend({ PM_AGG_STORE_BACKEND: "supabase" })).toBe("supabase"); + expect(parseStoreBackend({ PM_AGG_STORE_BACKEND: "turso" })).toBe("turso"); expect(() => parseStoreBackend({ PM_AGG_STORE_BACKEND: "postgres" })).toThrow(/PM_AGG_STORE_BACKEND/); - expect(() => parseStoreBackend({ PM_AGG_STORE_BACKEND: "SUPABASE" })).toThrow(/PM_AGG_STORE_BACKEND/); + expect(() => parseStoreBackend({ PM_AGG_STORE_BACKEND: "TURSO" })).toThrow(/PM_AGG_STORE_BACKEND/); + }); + + test("the retired supabase backend fails loudly, naming the valid values", () => { + expect(() => parseStoreBackend({ PM_AGG_STORE_BACKEND: "supabase" })).toThrow( + 'Invalid PM_AGG_STORE_BACKEND="supabase"; expected "file" or "turso"', + ); }); }); @@ -278,7 +284,7 @@ describe("empty local state dir boots from the remote (#6815 acceptance)", () => function recordingClient(responder: (sql: string) => unknown[] = () => []): { seen: string[]; - client: SupabaseClient; + client: SqlClient; } { const seen: string[] = []; return { @@ -293,7 +299,7 @@ function recordingClient(responder: (sql: string) => unknown[] = () => []): { }; } -describe("Supabase row mapping", () => { +describe("remote store row mapping", () => { test("action row -> DashAction -> row values preserves the #3142 contract", () => { const row = { id: "da-1", @@ -359,7 +365,7 @@ describe("Supabase row mapping", () => { test("actions remote orders inserts parent-first and upserts by id", async () => { const rec = recordingClient(() => []); - const remote = createSupabaseActionsRemote(async () => rec.client); + const remote = createTursoActionsRemote(async () => rec.client); const child: DashAction = { id: "da-child", clientToken: "ct-2-abcdefgh", @@ -389,22 +395,22 @@ describe("Supabase row mapping", () => { test("snapshots remote inserts with on-conflict-do-nothing and counts returned rows", async () => { const rec = recordingClient(() => [{ snapshot_key: "k" }]); - const remote = createSupabaseSnapshotsRemote(async () => rec.client); + const remote = createTursoSnapshotsRemote(async () => rec.client); expect(await remote.append([snapshot()])).toBe(1); expect(rec.seen[0]).toContain("on conflict (snapshot_key) do nothing returning snapshot_key"); }); test("document remote upserts the aa-last-good document with the writer recorded", async () => { const rec = recordingClient((sql) => (sql.startsWith("select") ? [{ version: 1, document: { batch: "b" } }] : [])); - const remote = createSupabaseDocumentRemote(async () => rec.client, "pm-aggregator-migrate"); + const remote = createTursoDocumentRemote(async () => rec.client, "pm-aggregator-migrate"); expect(await remote.load(AA_LAST_GOOD_DOCUMENT)).toEqual({ version: 1, document: { batch: "b" } }); await remote.save(AA_LAST_GOOD_DOCUMENT, 1, { batch: "b" }); expect(rec.seen[1]).toContain("on conflict (store) do update"); expect(rec.seen[1]).toContain("'pm-aggregator-migrate'"); }); - test("supabase mode without a client fails closed instead of using a local file", async () => { - const remote = createSupabaseActionsRemote(async () => null); + test("turso mode without a client fails closed instead of using a local file", async () => { + const remote = createTursoActionsRemote(async () => null); await expect(remote.loadAll()).rejects.toThrow(/refusing to fall back/); }); }); diff --git a/pm-stack/aggregator/test/supabase-export.test.ts b/pm-stack/aggregator/test/supabase-export.test.ts deleted file mode 100644 index a7c96bc015..0000000000 --- a/pm-stack/aggregator/test/supabase-export.test.ts +++ /dev/null @@ -1,423 +0,0 @@ -// Supabase live-export overlay (#1050 / queue task 2985): a fresh -// supabase-export document puts measured used/limit + the measured -// billed state on the Supabase card; a missing, failed or stale -// document reproduces the recorded prose exactly. -import { describe, expect, test } from "bun:test"; -import { chmod, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { loadConfig } from "../src/config.ts"; -import { applySupabaseExport, extractSaasServices, type SupabaseExportDoc } from "../src/saas-extract.ts"; -import { SnapshotStore } from "../src/snapshots.ts"; -import { liveSource } from "../src/sources/live.ts"; -import { createSupabaseClientGetter, resolveSupabaseProjectRef } from "../src/supabase.ts"; - -const VIEW = ` -## Summary (b) — subscriptions, infrastructure, account tooling - -| Service | Plan / price | Allowance sketch | Usage / status | Next date recorded | -|---|---|---|---|---| -| Supabase | Free plan (muse-dev2) | DB + egress + storage | manual dashboard read needed | unknown | - -## Service details (b) - -### Supabase -- **Plan / price:** Free plan (muse-dev2); numerical quotas unknown in local records. -- **Usage / dates:** Not measured — manual dashboard read needed. -- **Last checked:** 2026-10-28. -`; - -const NOW = Date.parse("2026-10-29T15:00:00Z"); - -describe("getSupabaseClient retry-after-null memoization", () => { - test("retries null, shares the next in-flight attempt, and caches success", async () => { - const previousProjectRef = process.env.SUPABASE_PROJECT_REF; - process.env.SUPABASE_PROJECT_REF = "test-project"; - let secretCalls = 0; - let resolveFirst!: (value: string | null) => void; - const firstResult = new Promise((resolve) => { - resolveFirst = resolve; - }); - let resolveRetry!: (value: string | null) => void; - const retryResult = new Promise((resolve) => { - resolveRetry = resolve; - }); - const getClient = createSupabaseClientGetter(async () => { - secretCalls += 1; - return secretCalls === 1 ? firstResult : retryResult; - }); - - try { - const initial = getClient(); - const concurrentInitial = getClient(); - expect(secretCalls).toBe(1); - resolveFirst(null); - expect(await Promise.all([initial, concurrentInitial])).toEqual([null, null]); - - const first = getClient(); - const second = getClient(); - expect(secretCalls).toBe(2); - resolveRetry("test-token"); - - const [client, concurrentClient] = await Promise.all([first, second]); - expect(client).not.toBeNull(); - expect(client).toBe(concurrentClient); - expect(client?.ref).toBe("test-project"); - expect(await getClient()).toBe(client); - expect(secretCalls).toBe(2); - } finally { - if (previousProjectRef === undefined) delete process.env.SUPABASE_PROJECT_REF; - else process.env.SUPABASE_PROJECT_REF = previousProjectRef; - } - }); - - test("resolves the project ref through the canonical Bitwarden pointer", async () => { - const requested: string[] = []; - const ref = await resolveSupabaseProjectRef(async (key) => { - requested.push(key); - return key === "supabase.project-ref" ? "configured-project" : null; - }, {}); - - expect(ref).toBe("configured-project"); - expect(requested).toEqual(["supabase.project-ref"]); - }); - - test("trims and prefers an explicit project-ref override", async () => { - const ref = await resolveSupabaseProjectRef( - async () => { - throw new Error("secret lookup should not run for an explicit override"); - }, - { SUPABASE_PROJECT_REF: " override-project " }, - ); - - expect(ref).toBe("override-project"); - }); - - test("does not fall back to a project literal when the canonical ref is unavailable", async () => { - const ref = await resolveSupabaseProjectRef(async () => null, {}); - expect(ref).toBeNull(); - }); -}); - -function freshDoc(overrides: Partial = {}): SupabaseExportDoc { - return { - service: "supabase", - source: "file-export/supabase", - status: "partial", - measuredAt: "2026-10-29T14:55:00Z", - project: "muse-dev2", - ref: "fixture-project-ref", - metrics: [ - { - id: "db-size", - label: "Database size", - used: 1.154, - limit: 0.5, - unit: "gb", - source: "management-api:/database/query pg_database_size", - flag: "approaching-paid-trigger", - }, - { - id: "egress", - label: "Egress (cycle)", - used: null, - limit: 5, - unit: "gb", - source: "none", - detail: "No Management API endpoint reports egress bytes.", - }, - { - id: "storage", - label: "File storage", - used: 0, - limit: 1, - unit: "gb", - source: "management-api:/storage/buckets", - detail: "0 buckets on the project", - }, - ], - billing: { plan: "free", billedUsd: 0, measured: true, source: "management-api:/billing/addons" }, - scope: [ - { endpoint: "projects", status: 200 }, - { endpoint: "organizations/:slug", status: 403, note: "scope gap" }, - { endpoint: "usage.egress", status: 404 }, - ], - ...overrides, - }; -} - -const supabaseCard = (services: ReturnType) => services.find((s) => s.id === "supabase")!; -const metricOf = (services: ReturnType, id: string) => - supabaseCard(services).metrics.find((m) => m.id === id)!; - -describe("applySupabaseExport", () => { - test("a fresh export supplies measured used + Free limits for db-size and storage", () => { - const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc(), NOW); - const db = metricOf(out, "db-size"); - expect(db.used).toBe(1.154); - expect(db.limit).toBe(0.5); - expect(db.unit).toBe("gb"); - expect(db.percent).toBe(230.8); - expect(db.note).toContain("measured 2026-10-29T14:55:00Z"); - expect(db.note).toContain("Approaching-paid trigger"); - const storage = metricOf(out, "storage"); - expect(storage.used).toBe(0); - expect(storage.limit).toBe(1); - expect(supabaseCard(out).sourceClass).toBe("api"); - expect(supabaseCard(out).measuredAt).toBe("2026-10-29"); - }); - - test("egress keeps a recorded limit but stays unmeasured, with the gap detail", () => { - const out = applySupabaseExport(extractSaasServices(VIEW), freshDoc(), NOW); - const egress = metricOf(out, "egress"); - expect(egress.used).toBeNull(); - expect(egress.limit).toBe(5); - expect(egress.percent).toBeUndefined(); - expect(egress.note).toContain("Not measured this tick"); - expect(egress.note).toContain("egress bytes"); - }); - - test("billed is the export's measured addon read, not the hardcoded 0", () => { - const out = applySupabaseExport( - extractSaasServices(VIEW), - freshDoc({ billing: { plan: "free", billedUsd: 25, measured: true } }), - NOW, - ); - expect(supabaseCard(out).billedUsd).toBe(25); - expect(supabaseCard(out).plan).toContain("measured 2026-10-29T14:55:00Z"); - }); - - test("an accepted export without a valid billing measurement clears billed to unknown", () => { - const noBilling = applySupabaseExport( - extractSaasServices(VIEW), - freshDoc({ billing: null as unknown as SupabaseExportDoc["billing"] }), - NOW, - ); - expect(supabaseCard(noBilling).billedUsd).toBeNull(); - expect(supabaseCard(noBilling).sourceClass).toBe("api"); // the rest of the overlay still applied - expect(metricOf(noBilling, "db-size").used).toBe(1.154); - const unmeasured = applySupabaseExport(extractSaasServices(VIEW), freshDoc({ billing: { plan: "free" } }), NOW); - expect(supabaseCard(unmeasured).billedUsd).toBeNull(); - }); - - test("negative billing is unknown without discarding valid metric measurements", () => { - const out = applySupabaseExport( - extractSaasServices(VIEW), - freshDoc({ billing: { plan: "free", billedUsd: -42.5, measured: true } }), - NOW, - ); - expect(supabaseCard(out).billedUsd).toBeNull(); - expect(supabaseCard(out).sourceClass).toBe("api"); - expect(metricOf(out, "db-size").used).toBe(1.154); - }); - - test("a non-string measuredAt is a no-op before Date.parse coercion", () => { - const base = extractSaasServices(VIEW); - const expected = structuredClone(base); - const out = applySupabaseExport(base, freshDoc({ measuredAt: ["2026-10-29T14:55:00Z"] as unknown as string }), NOW); - expect(out).toEqual(expected); - }); - - test("a negative used value leaves that metric at its recorded fallback", () => { - const base = extractSaasServices(VIEW); - const recordedDb = structuredClone(metricOf(base, "db-size")); - const out = applySupabaseExport( - base, - freshDoc({ - metrics: [ - { id: "db-size", used: -3.25, limit: 0.5 }, - { id: "storage", used: 0.25, limit: 1, unit: "gb" }, - ], - }), - NOW, - ); - expect(metricOf(out, "db-size")).toEqual(recordedDb); - expect(metricOf(out, "storage").used).toBe(0.25); - }); - - test("a negative limit leaves that metric at its recorded fallback", () => { - const base = extractSaasServices(VIEW); - const recordedDb = structuredClone(metricOf(base, "db-size")); - const out = applySupabaseExport(base, freshDoc({ metrics: [{ id: "db-size", used: 0.25, limit: -0.5 }] }), NOW); - expect(metricOf(out, "db-size")).toEqual(recordedDb); - }); - - test("an impossible or non-ISO measuredAt changes nothing — no Date.parse rollover (#5018)", () => { - // now is 2026-03-02T12:05Z: Date.parse rolls 2026-02-30 over to - // Mar 2 12:00, inside the freshness window; the real-calendar gate - // refuses it, and non-ISO stamps are refused the same way. - const now = Date.parse("2026-03-02T12:05:00Z"); - for (const bad of ["2026-02-30T12:00:00.000Z", "2026-04-31T12:00:00.000Z", "March 2, 2026 12:00 UTC"]) { - const base = extractSaasServices(VIEW); - const out = applySupabaseExport(base, freshDoc({ measuredAt: bad }), now); - expect(out).toEqual(base); - expect(supabaseCard(out).sourceClass).toBe("manual"); - } - }); - - test("a leap-date measuredAt still overlays (#5018)", () => { - const now = Date.parse("2024-02-29T12:05:00Z"); - const base = extractSaasServices(VIEW); - const out = applySupabaseExport(base, freshDoc({ measuredAt: "2024-02-29T12:00:00.000Z" }), now); - expect(metricOf(out, "db-size").used).toBe(1.154); - expect(supabaseCard(out).sourceClass).toBe("api"); - expect(supabaseCard(out).measuredAt).toBe("2024-02-29"); - }); - - test("a stale export falls back to exactly today's card", () => { - const base = extractSaasServices(VIEW); - const out = applySupabaseExport(base, freshDoc({ measuredAt: "2026-10-29T12:00:00Z" }), NOW); - expect(out).toEqual(base); - expect(supabaseCard(out).billedUsd).toBe(0); // today's constant - expect(metricOf(out, "db-size").used).toBeNull(); - }); - - test("missing, failed and unparseable documents change nothing", () => { - const base = extractSaasServices(VIEW); - expect(applySupabaseExport(base, null, NOW)).toEqual(base); - expect(applySupabaseExport(base, freshDoc({ status: "fetch-failed", metrics: undefined }), NOW)).toEqual(base); - expect(applySupabaseExport(base, freshDoc({ measuredAt: "not-a-date" }), NOW)).toEqual(base); - expect(applySupabaseExport(base, freshDoc({ metrics: [] }), NOW)).toEqual(base); - }); - - test("a document without a Supabase card in the view is a no-op", () => { - const out = applySupabaseExport(extractSaasServices("nothing here"), freshDoc(), NOW); - expect(out.find((s) => s.id === "supabase")!.metrics).toEqual([]); - }); -}); - -describe("live source usage(): the overlay reaches fleet-feed services too", () => { - test("feed.saas cards get the fresh export overlay, not just the quota-view fallback", async () => { - const dir = await mkdtemp(join(tmpdir(), "pm-supa-feed-")); - const nowIso = new Date().toISOString(); - const feedFile = join(dir, "fleet-feed.json"); - const exportFile = join(dir, "latest.json"); - await writeFile(exportFile, JSON.stringify(freshDoc({ measuredAt: nowIso }))); - await writeFile( - feedFile, - JSON.stringify({ - version: 1, - generatedAt: nowIso, - quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, - attention: [], - saas: extractSaasServices(VIEW), - }), - ); - const cfg = loadConfig({ - PM_AGG_SOURCE: "live", - PM_AGG_FEED_FILE: feedFile, - PM_AGG_SUPABASE_EXPORT: exportFile, - PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), - PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), - PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"), - PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), - PM_PROJECTOR_URL: "off", - KANEO_ADMIN_EMAIL: "", - KANEO_ADMIN_PASSWORD: "", - GRIST_API_KEY: "", - }); - const usage = await liveSource(cfg).usage(); - const db = metricOf(usage.services, "db-size"); - expect(db.used).toBe(1.154); - expect(db.limit).toBe(0.5); - expect(supabaseCard(usage.services).billedUsd).toBe(0); - }); - - test("usage reads feed history without writing to a read-only snapshot store", async () => { - const dir = await mkdtemp(join(tmpdir(), "pm-supa-readonly-")); - const feedFile = join(dir, "fleet-feed.json"); - const snapshotsDir = join(dir, "snapshots"); - const nowIso = new Date().toISOString(); - const record = { - ts: nowIso, - serviceId: "supabase", - metricId: "db-size", - value: 1.154, - unit: "gb", - source: "api", - observedBy: "fleet-feed-collector", - }; - try { - await mkdir(snapshotsDir); - await chmod(snapshotsDir, 0o555); - await writeFile( - feedFile, - JSON.stringify({ - version: 1, - generatedAt: nowIso, - quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, - attention: [], - saas: extractSaasServices(VIEW), - snapshots: [record], - }), - ); - const cfg = loadConfig({ - PM_AGG_SOURCE: "live", - PM_AGG_FEED_FILE: feedFile, - PM_AGG_SNAPSHOTS_DIR: snapshotsDir, - PM_AGG_SUPABASE_EXPORT: join(dir, "latest.json"), - PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), - PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), - PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), - PM_PROJECTOR_URL: "off", - KANEO_ADMIN_EMAIL: "", - KANEO_ADMIN_PASSWORD: "", - GRIST_API_KEY: "", - }); - const usage = await liveSource(cfg).usage(); - expect(usage.services.some((service) => service.id === "supabase")).toBe(true); - expect(await readdir(snapshotsDir)).toEqual([]); - } finally { - await chmod(snapshotsDir, 0o755).catch(() => {}); - await rm(dir, { recursive: true, force: true }); - } - }); - - test("background ingestion lands feed records idempotently", async () => { - const dir = await mkdtemp(join(tmpdir(), "pm-supa-ingest-")); - const feedFile = join(dir, "fleet-feed.json"); - const snapshotsDir = join(dir, "snapshots"); - const nowIso = new Date().toISOString(); - const record = { - ts: nowIso, - serviceId: "supabase", - metricId: "db-size", - value: 1.154, - unit: "gb", - source: "api", - observedBy: "fleet-feed-collector", - }; - try { - await writeFile( - feedFile, - JSON.stringify({ - version: 1, - generatedAt: nowIso, - quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, - attention: [], - saas: extractSaasServices(VIEW), - snapshots: [record], - }), - ); - const cfg = loadConfig({ - PM_AGG_SOURCE: "live", - PM_AGG_FEED_FILE: feedFile, - PM_AGG_SNAPSHOTS_DIR: snapshotsDir, - PM_AGG_SUPABASE_EXPORT: join(dir, "latest.json"), - PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), - PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), - PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), - PM_PROJECTOR_URL: "off", - KANEO_ADMIN_EMAIL: "", - KANEO_ADMIN_PASSWORD: "", - GRIST_API_KEY: "", - }); - const source = liveSource(cfg); - expect(await source.ingestSnapshots?.()).toBe(1); - expect(await source.ingestSnapshots?.()).toBe(0); - expect(await new SnapshotStore(snapshotsDir).byService()).toMatchObject({ supabase: [record] }); - } finally { - await rm(dir, { recursive: true, force: true }); - } - }); -}); diff --git a/pm-stack/aggregator/test/turso-stores.test.ts b/pm-stack/aggregator/test/turso-stores.test.ts index 913b71c582..ad6653db49 100644 --- a/pm-stack/aggregator/test/turso-stores.test.ts +++ b/pm-stack/aggregator/test/turso-stores.test.ts @@ -2,10 +2,10 @@ import { test, expect } from "bun:test"; import { Database } from "bun:sqlite"; import { storeStatement, decodeStoreRow, createTursoStoreClient } from "../src/turso-stores.ts"; import { - createSupabaseActionsRemote, - createSupabaseActivityRemote, - createSupabaseDocumentRemote, - createSupabaseSnapshotsRemote, + createTursoActionsRemote, + createTursoActivityRemote, + createTursoDocumentRemote, + createTursoSnapshotsRemote, } from "../src/remote-stores.ts"; import { AlertsStore } from "../src/alerts.ts"; @@ -37,8 +37,8 @@ test("activity arrays and document JSON round trip", async () => { create table agg_store_documents(store text primary key, version integer, document text, writer text, updated_at text);`); const c = localClient(db), get = async () => c; - const activity = createSupabaseActivityRemote(get); - const doc = createSupabaseDocumentRemote(get); + const activity = createTursoActivityRemote(get); + const doc = createTursoDocumentRemote(get); const value = { version: 1 as const, checkpoints: {}, @@ -111,7 +111,7 @@ test("snapshots preserve numeric and range JSON values and replay dedupes", asyn `create table agg_usage_snapshots(snapshot_key text primary key,ts text,service_id text,metric_id text,unit text,source text,value text,limit_value real,resets_at text,observed_by text)`, ); const c = localClient(db), - store = createSupabaseSnapshotsRemote(async () => c); + store = createTursoSnapshotsRemote(async () => c); const base = { ts: "2026-11-18T00:00:00.000Z", serviceId: "service", @@ -146,7 +146,7 @@ test("actions JSON and self references round trip with real FK constraints", asy const db = new Database(":memory:"); db.exec(`pragma foreign_keys=on; create table agg_actions(id text primary key,client_token text,kind text,verb text,object_ref text,target_ref text,session_id text,session_source text,payload text,author text,created_at text,state text,applied_at text,applied_by_run text,result_note text,supersedes_action_id text references agg_actions(id),duplicate_of_action_id text references agg_actions(id));`); - const store = createSupabaseActionsRemote(async () => localClient(db)); + const store = createTursoActionsRemote(async () => localClient(db)); const base = { id: "one", kind: "task", diff --git a/pm-stack/dispatch/install.sh b/pm-stack/dispatch/install.sh index 7805907339..774f5f5ea6 100755 --- a/pm-stack/dispatch/install.sh +++ b/pm-stack/dispatch/install.sh @@ -15,9 +15,7 @@ # - Queue access (#9028) needs NO secret in the rendered env: dispatch # talks to the fleet queue broker (QUEUE_BROKER_URL, rendered below # as a plain URL) with the broker token, which stays in its own -# file ~/.config/queue-broker/token. The Supabase service-role key -# is GONE from this deployment — the direct-PostgREST producer it -# fed wrote to the legacy store no lane reads. +# file ~/.config/queue-broker/token. # - NOT in sops: DISPATCH_API_TOKEN lives in ~/secrets/dispatch.env # (mode 600, laptop-only), which the unit also reads. Its by-name # vault home is Bitwarden `pm-dispatch.api-token` (issue #5555) — @@ -32,11 +30,7 @@ # 401s) until the vault and the clients are updated to match. # This script # ensures that file exists and carries a generated -# DISPATCH_API_TOKEN when one is absent. SUPABASE_URL / -# SUPABASE_SERVICE_ROLE_KEY lines left in that file are stale: the -# unit reads it AFTER the rendered file, so they would override the -# sops-managed values — this script warns about them below, and the -# operator copies should be deleted. +# DISPATCH_API_TOKEN when one is absent. # # Usage (on the laptop, from the repo checkout): bash install.sh set -euo pipefail @@ -72,9 +66,6 @@ if ! grep -q '^DISPATCH_API_TOKEN=' "$SECRETS_ENV"; then chmod 600 "$SECRETS_ENV" echo "generated a DISPATCH_API_TOKEN into $SECRETS_ENV (value not printed)" fi -if grep -q '^SUPABASE_URL=\|^SUPABASE_SERVICE_ROLE_KEY=' "$SECRETS_ENV"; then - echo "WARNING: $SECRETS_ENV still carries SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY lines — obsolete since #9028 (dispatch reads no Supabase config; the queue goes through the broker). Delete them from $SECRETS_ENV." >&2 -fi # --- Change detection + build marker ------------------------------------ DEPLOY_COMMIT="$(git -C "$SRC" rev-parse HEAD 2>/dev/null || true)" diff --git a/pm-stack/dispatch/src/config.ts b/pm-stack/dispatch/src/config.ts index efdfb480d1..de16901d72 100644 --- a/pm-stack/dispatch/src/config.ts +++ b/pm-stack/dispatch/src/config.ts @@ -3,8 +3,6 @@ // this process at all (#9028): dispatch talks to the fleet queue broker // with the broker token, which stays in its token file // (~/.config/queue-broker/token) and is read at client construction. -// The previous config required SUPABASE_URL and carried the Supabase -// service-role key — the direct-PostgREST producer that #9028 removed. import { homedir } from "node:os"; import { join } from "node:path"; diff --git a/pm-stack/dispatch/src/queue.ts b/pm-stack/dispatch/src/queue.ts index 5f0d8dd5fd..57374f7b7d 100644 --- a/pm-stack/dispatch/src/queue.ts +++ b/pm-stack/dispatch/src/queue.ts @@ -5,12 +5,7 @@ // laptop transport reads). The broker is backed by the live Turso // queue store and validates every packet on /enqueue. // -// This replaces the direct PostgREST producer this module used to be: -// pm-dispatch held the Supabase service-role key and wrote task rows -// (enqueue RPC + claim PATCH) straight into the legacy Supabase store, -// bypassing the packet validator and the broker, while the fleet's -// live queue moved to Turso — its writes landed where no lane claims. -// There is no service-role key in this process anymore, and no generic +// No database credential lives in this process and there is no generic // row PATCH: the broker's verbs are the whole surface — // enqueue -> POST /enqueue {packet, queue} (validated) // claimTask -> POST /claim-flow {task_id, worker, queue, session_id, diff --git a/pm-stack/dispatch/test/config.test.ts b/pm-stack/dispatch/test/config.test.ts index c2aaa41d37..5eda332523 100644 --- a/pm-stack/dispatch/test/config.test.ts +++ b/pm-stack/dispatch/test/config.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { APP_INSTALLED_REPOS, FLEET_REPOS, REPO_DIRS, REPO_QUEUES, loadConfig } from "../src/config.ts"; -/** loadConfig needs no fixture secrets (#9028: no Supabase config remains). */ +/** loadConfig needs no fixture secrets (#9028). */ const ENV = {}; describe("fleet config", () => { diff --git a/pm-stack/dispatch/test/dispatch_preexisting.test.ts b/pm-stack/dispatch/test/dispatch_preexisting.test.ts index b98c435580..a3fbd6f66f 100644 --- a/pm-stack/dispatch/test/dispatch_preexisting.test.ts +++ b/pm-stack/dispatch/test/dispatch_preexisting.test.ts @@ -6,8 +6,7 @@ // // The enqueue RPC dedupes on dedupe_key against ALL rows incl. terminal // ones and returns the old row as-is. These tests drive the server-level -// orchestration (enqueueDispatchTask) with a stubbed queue — no network, -// no Supabase. +// orchestration (enqueueDispatchTask) with a stubbed queue — no network. import { describe, expect, test } from "bun:test"; // src/server.ts loads config at import; the broker token file fixture keeps the queue unconfigured. // (#5120), so pin a fixture project before the dynamic import below. diff --git a/pm-stack/dispatch/test/server.test.ts b/pm-stack/dispatch/test/server.test.ts index e54308b16b..ce9a81aec4 100644 --- a/pm-stack/dispatch/test/server.test.ts +++ b/pm-stack/dispatch/test/server.test.ts @@ -106,7 +106,7 @@ describe("POST /v1/sessions directory scoping (issue #2903)", () => { }); test("OIDC + omitted directory passes validation (fails later at the unconfigured queue)", async () => { - // No SUPABASE_SERVICE_ROLE_KEY in test env, so a request that clears + // No broker token in test env, so a request that clears // validation reaches requireQueue() and maps to 502 — proving the // directory gate let it through. Any network beyond JWKS throws. const token = signOidc("developing-today/code"); diff --git a/pm-stack/external-comms/README.md b/pm-stack/external-comms/README.md index 92f0b1acae..3585a146e5 100644 --- a/pm-stack/external-comms/README.md +++ b/pm-stack/external-comms/README.md @@ -13,15 +13,15 @@ with its approval basis: (a) per-item approval, (b) surfaced-with-link ## Where things live -| Piece | Location | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Table | `agent_external_comms` in the Turso database **fleet-platform** (repointed 2026-11-07; before that `agent.external_comms` in Supabase project muse-dev2 — the 58 pre-repoint rows stay in Postgres until the finalize top-up) | -| Migration | `migration-0001-agent-external-comms.sql` (original Postgres DDL) + `migration-0002-agent-external-comms-turso.sql` (Turso DDL, executed 2026-11-07) | -| Writer CLI + pusher | `record-external-send` (this directory; deployed from the primary clone `~/git/code` on the laptop) | -| Outbox (spill) | `~/.local/state/external-comms/outbox.jsonl` on the laptop | -| Pusher health | `~/.local/state/external-comms/pusher-health.json` on the laptop | -| Pusher supervision | systemd **user** units `external-comms-pusher.service` / `.timer` (this directory; installed to `~/.config/systemd/user/`, timer every minute) | -| Backfill | `backfill-2026-11-05.jsonl` — the 68 sends enumerated by the 2026-11-05 audit, loaded once via `record-many` | +| Piece | Location | +| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| Table | `agent_external_comms` in the Turso database **fleet-platform** | +| Migration | `migration-0001-agent-external-comms.sql` (original Postgres DDL) + `migration-0002-agent-external-comms-turso.sql` (Turso DDL, executed 2026-11-07) | +| Writer CLI + pusher | `record-external-send` (this directory; deployed from the primary clone `~/git/code` on the laptop) | +| Outbox (spill) | `~/.local/state/external-comms/outbox.jsonl` on the laptop | +| Pusher health | `~/.local/state/external-comms/pusher-health.json` on the laptop | +| Pusher supervision | systemd **user** units `external-comms-pusher.service` / `.timer` (this directory; installed to `~/.config/systemd/user/`, timer every minute) | +| Backfill | `backfill-2026-11-05.jsonl` — the 68 sends enumerated by the 2026-11-05 audit, loaded once via `record-many` | ## Write pattern: database-first, spill to outbox, pusher drains diff --git a/pm-stack/external-comms/record-external-send b/pm-stack/external-comms/record-external-send index 3f380820ec..c5c37ce1c4 100755 --- a/pm-stack/external-comms/record-external-send +++ b/pm-stack/external-comms/record-external-send @@ -5,11 +5,7 @@ Implements Drew's ratified rule (2026-11-05): EXTERNAL COMMS ARE NEVER SILENT. Every send outside our own repos/channels under Drew's identity or a fleet identity is recorded at send time in the ledger table `agent_external_comms` in the Turso database fleet-platform -(repointed 2026-11-07 from `agent.external_comms` in Supabase -muse-dev2, whose data plane has been down since 2026-11-06, -code#6619; DDL: migration-0002-agent-external-comms-turso.sql. -The 58 rows recorded in Postgres before the repoint stay there -until the finalize pass tops this table up by id.) +(DDL: migration-0002-agent-external-comms-turso.sql). Write pattern (the pm-stack durability pattern, cf. aggregator events.ts): DATABASE-FIRST WITH SPILL TO OUTBOX. diff --git a/pm-stack/meta-exporter/meta-quota-export.test.mjs b/pm-stack/meta-exporter/meta-quota-export.test.mjs index 6cd7471440..810c2d4d4c 100644 --- a/pm-stack/meta-exporter/meta-quota-export.test.mjs +++ b/pm-stack/meta-exporter/meta-quota-export.test.mjs @@ -278,7 +278,7 @@ test("documents: page-not-ready is a distinct status/exit and recovery is record // so any symlinked invocation silently skipped main() and exited 0 — // the #2350 bug, restored by the #6333 re-home. The guard now resolves // symlinks on both sides (realpathSync, mirroring -// supabase-quota-export.mjs / cloudflare-quota-export.mjs). Oracle: a run +// cloudflare-quota-export.mjs). Oracle: a run // against an unreachable CDP port must produce the cdp-unavailable // failure document with exit 4, identically for direct and symlinked // invocation; a silent exit 0 is the counterexample. diff --git a/pm-stack/shared-schema/README.md b/pm-stack/shared-schema/README.md index 0eb3ffa94c..42e28f0167 100644 --- a/pm-stack/shared-schema/README.md +++ b/pm-stack/shared-schema/README.md @@ -1,9 +1,16 @@ # Shared schema v1: aggregator actions and outcomes -Status: the action/event contract and its #6815 add-on stores have been -applied to Supabase `muse-dev2` and are the canonical backing store when the -aggregator runs with `PM_AGG_STORE_BACKEND=supabase`; with the default -`file` backend the JSON files remain authoritative. +Status: the PostgreSQL DDL here is the original contract for the +action/event tables and the #6815 add-on stores. The live copies of these +tables are in Turso (the Supabase project they were first applied to has +been deleted; the Turso schema was created during the 2026-11-18 recovery, +see `doc/2026-11-18_supabase-turso-recovery.md`). They are the canonical +backing store when the aggregator runs with `PM_AGG_STORE_BACKEND=turso`; +with the default `file` backend the JSON files remain authoritative. The +aggregator reaches them only through `aggregator/src/turso-stores.ts`, which +translates the PostgreSQL-dialect statements in +`aggregator/src/remote-stores.ts` to SQLite (`public.` prefixes dropped, +`jsonb`/`timestamptz` casts removed). The target uses the `public` schema and the table-group names from [#1744](https://github.com/developing-today/code/issues/1744): @@ -76,8 +83,8 @@ Current events default to `{confidence: "unknown", asserted: false}` and `{identity: "pm-stack/aggregator"}`. Do not upgrade these to authenticated provenance without the separate #941 trust-hardening work. -RLS is enabled on both tables. The migration grants the Supabase -`service_role` the minimum table privileges needed by the current contracts: +RLS is enabled on both tables (PostgreSQL DDL only; Turso has no RLS). The +migration grants `service_role` the minimum table privileges needed by the current contracts: actions can be read/inserted/updated but not deleted; events can be read/inserted and pruned under the existing event-retention policy, but not updated. No client-facing RLS policy or production database write is part of @@ -103,14 +110,13 @@ migration drops its tables in reverse dependency order. The refusal is deliberate protection against an accidental data-loss rollback. Cutover and rollback are the aggregator's `PM_AGG_STORE_BACKEND` switch -(`file` default → `supabase`), documented in -[the aggregator README](../aggregator/README.md#store-backend-supabase-muse-dev2-6815). -Switching to `supabase` makes the tables the write path; the local JSON +(`file` default → `turso`), documented in +[the aggregator README](../aggregator/README.md#store-backend-turso-6815). +Switching to `turso` makes the tables the write path; the local JSON stores are preserved as a rebuildable cache and remain the rollback target. -The import script (`aggregator/scripts/migrate-stores-to-supabase.ts`) is -idempotent, and re-running it after the deploy closes writes made between the -import and the cutover. The migration test proves the paired DDL and rollback -on a disposable PostgreSQL 16 instance; it does not connect to Supabase. +The migration test proves the paired PostgreSQL DDL and rollback on a +disposable PostgreSQL 16 instance; it does not connect to any remote +database. This supplies reversible DDL for the #6815 slice. It does **not** finish the remaining `agg_*` / `shared_*` contracts, decide the projector's P1 location, @@ -129,5 +135,5 @@ migrations in order, proves key/foreign-key/check/idempotency behavior (including legacy-null compatibility and the #6815 store-table constraints), proves each down migration refuses non-empty tables, clears only its disposable fixtures, applies both down migrations in reverse, and verifies -the tables are gone. It does not connect to Supabase or the PM Compose +the tables are gone. It does not connect to Turso or the PM Compose database. diff --git a/pm-stack/shared-schema/test-migration.sh b/pm-stack/shared-schema/test-migration.sh index 6dc570c6eb..c585d664ca 100755 --- a/pm-stack/shared-schema/test-migration.sh +++ b/pm-stack/shared-schema/test-migration.sh @@ -46,7 +46,8 @@ psql_test() { docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d pm_actions_test "$@" } -# Supabase's service_role carries BYPASSRLS; model that so the test proves +# The migrations' service_role is a BYPASSRLS role (the hosted-Postgres +# convention the DDL was written for); model that so the test proves # the role can actually operate under the RLS model, not just hold grants. psql_test -c 'CREATE ROLE service_role BYPASSRLS LOGIN;' psql_test <"$up" @@ -82,8 +83,8 @@ if [[ $privileges != "true:true:true:false:true" ]]; then fi echo "ok - RLS and service_role privileges" -# The service_role must actually be able to operate under RLS (Supabase's -# service_role carries BYPASSRLS); a role that only holds grants but is +# The service_role must actually be able to operate under RLS (it is +# modelled as BYPASSRLS above); a role that only holds grants but is # blocked by RLS would pass the privilege probe above while being # unusable in production. svc_hash="$(printf '%064d' 7)" diff --git a/pm-stack/shared-schema/test-orchestration-migration.sh b/pm-stack/shared-schema/test-orchestration-migration.sh index bd93e20008..6870c5130b 100755 --- a/pm-stack/shared-schema/test-orchestration-migration.sh +++ b/pm-stack/shared-schema/test-orchestration-migration.sh @@ -44,7 +44,8 @@ psql_test() { docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d pm_orch_test "$@" } -# Supabase's service_role carries BYPASSRLS; model that so the test proves +# The migrations' service_role is a BYPASSRLS role (the hosted-Postgres +# convention the DDL was written for); model that so the test proves # the role can actually operate under the RLS model, not just hold grants. psql_test -c 'CREATE ROLE service_role BYPASSRLS LOGIN;' psql_test <"$up" @@ -88,8 +89,8 @@ if [[ $privileges != "true:true:true:false:false:true" ]]; then fi echo "ok - RLS enabled; run log is append-only for service_role; state table is replaceable" -# The service_role must actually be able to operate under RLS (Supabase's -# service_role carries BYPASSRLS): append a run and read state back. +# The service_role must actually be able to operate under RLS (it is +# modelled as BYPASSRLS above): append a run and read state back. docker exec -i "$container" psql -X -v ON_ERROR_STOP=1 -U service_role -d pm_orch_test -c "INSERT INTO public.orch_runs (run_id, generated_at, document_version, provenance, document, item_count) VALUES ('orch-2026-11-11T01:00:00Z', '2026-11-11T01:00:00Z', 1, diff --git a/pm-stack/supabase-export/README.md b/pm-stack/supabase-export/README.md deleted file mode 100644 index f15cf082bc..0000000000 --- a/pm-stack/supabase-export/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# supabase-export — Supabase usage producer (#1050) - -The Supabase half of the usage hub's file-export family (#1151 gatherer, -#1048 Cloudflare adapter shape). Runs on the laptop tick, probes the Supabase -Management API for the project named by Bitwarden `supabase.project-ref`, and -writes the document the aggregator prefers over `quota-view.md` prose on the -Supabase card. - -``` -~/atlas/supabase-export/latest.json atomic latest document -~/atlas/supabase-export/history.jsonl one line per tick, success or failure -``` - -## Document - -```json -{ - "service": "supabase", - "source": "file-export/supabase", - "status": "ok | partial", - "measuredAt": "2026-10-29T15:55:00Z", - "project": "", - "ref": "", - "metrics": [{ "id": "db-size", "used": 1.154, "limit": 0.5, "unit": "gb", "source": "management-api:/database/query pg_database_size", "flag": "approaching-paid-trigger" }], - "billing": { "plan": "free", "billedUsd": 0, "measured": true, "source": "management-api:/billing/addons (no selected paid addons)" }, - "scope": [{ "endpoint": "organizations/:slug", "status": 403, "note": "scope gap: …" }] -} -``` - -Failure documents carry `status` + `attemptedAt` + `detail` and **no** metrics -or billing — a failed tick can never look like a reading. Statuses: `no-token` -or `no-project-ref` (exit 3), `scope-denied` (4), `fetch-failed` (5), -`unparseable` (6). - -`status: "partial"` means at least one probed endpoint answered >= 400; the -`.scope` array records exactly which, so the card can state the gap instead of -guessing around it. - -## Metrics and limits - -| Metric | Source | Free limit | -| --------- | ----------------------------------------------------------------------- | ---------- | -| `db-size` | `POST /database/query` → `pg_database_size(current_database())` | 0.5 GB | -| `egress` | **no endpoint reports bytes** — gap recorded, request counts as context | 5 GB | -| `storage` | `GET /storage/buckets` (0 buckets on the current project → 0 GB) | 1 GB | - -Limits are the Supabase Free-plan allowances recorded on 2026-10-29 -(supabase.com/pricing); the API measures usage, it does not publish the numbers. -Any metric at >= 80% of its Free limit carries `flag: "approaching-paid-trigger"` -— the signal for Drew's standing $30/mo spend ceiling. - -## Scope probe (2026-10-29, the existing `supabase.*` management token) - -Recorded endpoint-by-endpoint in `.scope` on every run: - -| Endpoint | Status | -| ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| `GET /projects`, `GET /projects/:ref` | 200 | -| `POST /projects/:ref/database/query` | 201 | -| `GET /projects/:ref/analytics/endpoints/usage.api-counts` | 200 | -| `GET /projects/:ref/analytics/endpoints/usage.api-requests-count` | 200 | -| `GET /projects/:ref/billing/addons` | 200 (`selected_addons: []`) | -| `GET /projects/:ref/storage/buckets` | 200 | -| `GET /projects/:ref/health?services=db` | 200 | -| `GET /organizations/:slug` | **403** — token is project-scoped; org plan/billing reads need an org token (Drew's account action) | -| `GET /organizations/:slug/{billing,usage}` | 403 / 404 | -| `GET /projects/:ref/usage`, `…/database/size` | 404 — no such endpoint | -| egress bytes | no endpoint exists; only request counts | - -Creating a token or granting org consent is out of scope for the producer; the -gap is recorded, not worked around. - -## Token - -The project ref is resolved by **name** from Bitwarden Secrets Manager at -runtime (`supabase.project-ref`; `SUPABASE_PROJECT_REF` or `--project-ref` -overrides it). The management token is resolved by **name** from Bitwarden -(`supabase.muse-dev2.access-token-muse-cli`, override `SUPABASE_TOKEN_SECRET_NAME`; -`SUPABASE_MANAGEMENT_TOKEN` wins if set). The token value is sent only to -`api.supabase.com` and is never written to the document, a log line, a fixture, -or argv. - -## Run - -```bash -bun supabase-quota-export.mjs --out-dir ~/atlas/supabase-export -bun test # offline: the API is an injected fake fetch -``` - -Aggregator side: `saas-extract.ts` `applySupabaseExport` prefers a document -younger than 30 minutes (the #1151 tick); older or missing falls back to the -quota-view prose exactly as before. diff --git a/pm-stack/supabase-export/install-laptop.sh b/pm-stack/supabase-export/install-laptop.sh deleted file mode 100755 index 9080128b42..0000000000 --- a/pm-stack/supabase-export/install-laptop.sh +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env bash -# install-laptop.sh — install the Supabase usage exporter on the laptop -# (developing-today/code#1050). Copies the producer beside its output -# directory and enables the 15-minute timer beside the #1151 gatherer tick. -# The management token is resolved BY NAME from Bitwarden at runtime -# (SUPABASE_TOKEN_SECRET_NAME, default supabase.muse-dev2.access-token-muse-cli); -# this script never reads, prints, or stores its value. -set -euo pipefail -# Argument contract (#3352): this script takes no command-line -# arguments; anything given is a usage error before any work runs. -if [ "$#" -gt 0 ]; then - echo "install-laptop.sh: unexpected argument '$1'; usage: bash install-laptop.sh" >&2 - exit 2 -fi - -here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -target="${SUPABASE_EXPORT_DIR:-$HOME/atlas/supabase-export}" -units="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" - -mkdir -p "$target" "$units" -install -m 0644 "$here/supabase-quota-export.mjs" "$target/supabase-quota-export.mjs" -# Render the unit's paths from the selected install directory — copying it -# unchanged would leave the timer pointing at the default directory. -bash_bin="$(command -v bash || true)" -if [[ -z $bash_bin ]]; then - echo "install-laptop: bash not found on PATH" >&2 - exit 1 -fi -bun_bin="$(command -v bun || true)" -if [[ -z $bun_bin && -x $HOME/.bun/bin/bun ]]; then bun_bin="$HOME/.bun/bin/bun"; fi -if [[ -z $bun_bin ]]; then - echo "install-laptop: bun not found on PATH or at ~/.bun/bin/bun" >&2 - exit 1 -fi -sed -e "s|@EXPORT_DIR@|$target|g" -e "s|@BUN@|$bun_bin|g" -e "s|@BASH@|$bash_bin|g" "$here/supabase-quota-export.service" >"$units/supabase-quota-export.service" -chmod 0644 "$units/supabase-quota-export.service" -if grep -q '@EXPORT_DIR@\|@BUN@\|@BASH@' "$units/supabase-quota-export.service"; then - echo "install-laptop: service unit still contains an unrendered placeholder after rendering" >&2 - exit 1 -fi -install -m 0644 "$here/supabase-quota-export.timer" "$units/supabase-quota-export.timer" - -systemctl --user daemon-reload -systemctl --user enable --now supabase-quota-export.timer -systemctl --user list-timers supabase-quota-export.timer --no-pager -echo "supabase-export: installed to $target; first tick on the next quarter hour" diff --git a/pm-stack/supabase-export/supabase-quota-export.mjs b/pm-stack/supabase-export/supabase-quota-export.mjs deleted file mode 100755 index a9d8e103fd..0000000000 --- a/pm-stack/supabase-export/supabase-quota-export.mjs +++ /dev/null @@ -1,486 +0,0 @@ -#!/usr/bin/env node -/** - * supabase-quota-export — Supabase usage exporter (developing-today/code#1050, - * follow-up to triage task 2313). The Supabase half of the #1151 file-export - * family, in the #1048 Cloudflare adapter shape: a producer that runs on the - * laptop tick and writes the document the aggregator prefers over quota-view - * prose. - * - * Every run writes atomically to - * /latest.json (default ~/atlas/supabase-export/) - * and appends the same document to /history.jsonl. - * - * Success document (file-export format the #1151 gatherer ingests): - * { service: "supabase", source: "file-export/supabase", - * status: "ok" | "partial", - * measuredAt: , project: , ref: , - * metrics: [ { id: "db-size", used: 1.15, limit: 0.5, unit: "gb", - * source: "management-api:/database/query pg_database_size", - * flag?: "approaching-paid-trigger", detail? } ], - * billing: { plan: "free", billedUsd: 0, measured: true, source: ... }, - * scope: [ { endpoint, path, status, note? } ] } - * - * Failure documents carry status + attemptedAt + detail and NO metrics or - * billing values — a failed tick can never be mistaken for a reading: - * no-token the Bitwarden secret did not resolve. Exit 3. - * scope-denied GET /projects/:ref answered 401/403. Exit 4. - * fetch-failed network/other error. Exit 5. - * unparseable an endpoint answered a shape this parser does not know. - * Exit 6. - * - * The management token is resolved by NAME from Bitwarden Secrets Manager at - * runtime and sent only to api.supabase.com. Its value is never read into a - * document, log line, fixture, or argv. - * - * Scope probe (recorded endpoint-by-endpoint in the `.scope` array of every - * successful document; task #2985 re-ran it against the live token): - * GET /projects 200 (auth works) - * GET /projects/:ref 200 - * GET /projects/:ref/database/query 201 (db size SQL) - * GET /projects/:ref/analytics/endpoints/usage.api-counts 200 - * GET /projects/:ref/analytics/endpoints/usage.api-requests-count 200 - * GET /projects/:ref/billing/addons 200 (measured $0 addons) - * GET /projects/:ref/storage/buckets 200 - * GET /organizations/:slug 403 scope gap: org-scope - * GET /organizations/:slug/{billing,usage} 403/404 scope gap - * GET /projects/:ref/{usage,database/size} 404 no such endpoint - * egres bytes no endpoint exists (request counts only) — documented gap - */ -import { execFile } from "node:child_process"; -import fs from "node:fs"; -import { appendFile, mkdir, rename, writeFile } from "node:fs/promises"; -import { homedir } from "node:os"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; - -export const SOURCE = "file-export/supabase"; -export const DEFAULT_PROJECT_REF_SECRET_NAME = "supabase.project-ref"; -export const DEFAULT_SECRET_NAME = "supabase.muse-dev2.access-token-muse-cli"; -export const API_BASE = "https://api.supabase.com/v1"; - -/** Supabase Free-plan allowances (supabase.com/pricing, recorded 2026-10-29: - * 500 MB database, 1 GB file storage, 5 GB egress). There is no API read of - * the numbers themselves; the API measures usage against them. */ -export const FREE_LIMITS = { - "db-size": 0.5, - egress: 5, - storage: 1, -}; - -/** Metric ids at >= this share of their Free limit carry the paid trigger. */ -export const PAID_TRIGGER_RATIO = 0.8; - -const GB = (bytes) => Math.round((bytes / 1e9) * 1000) / 1000; - -export class ExportError extends Error { - constructor(status, exitCode, detail) { - super(detail); - this.status = status; - this.exitCode = exitCode; - } -} - -/** Parse a measurement as a non-negative integer without Number's string coercions. */ -function parseNonNegativeInteger(value) { - if (typeof value === "number") { - return Number.isInteger(value) && value >= 0 ? value : null; - } - if (typeof value !== "string" || !/^\d+$/.test(value)) return null; - const n = Number(value); - return Number.isInteger(n) && n >= 0 ? n : null; -} - -/** Non-secret shape check for the SQL row the db-size query returns. */ -export function parseDbSize(rows) { - const bytes = rows?.[0]?.bytes; - const n = parseNonNegativeInteger(bytes); - if (n === null) { - throw new ExportError("unparseable", 6, "database/query: pg_database_size row missing/invalid"); - } - return n; -} - -/** Total requests from usage.api-requests-count ({ result: [{ count }] }). */ -export function parseRequestCount(payload) { - const count = payload?.result?.[0]?.count; - return parseNonNegativeInteger(count); -} - -/** Measured $0 (or more) from billing/addons: selected addons priced fixed - * monthly amounts; usage-priced addons are unknown while none are selected. - * Fail-closed per addon (#2492): a selected addon whose price amount is - * missing, not a finite number, or negative is a shape this parser does - * not know — throw unparseable (run() turns that into billing: null for - * the tick) instead of silently counting the addon as $0 or letting a - * negative amount into a total that gets stamped measured. */ -export function billedFromAddons(payload) { - const selected = payload?.selected_addons; - if (!Array.isArray(selected)) { - throw new ExportError("unparseable", 6, "billing/addons: selected_addons missing"); - } - let usd = 0; - for (const addon of selected) { - const amount = addon?.price?.amount; - if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) { - throw new ExportError("unparseable", 6, "billing/addons: selected addon price amount missing/invalid"); - } - usd += amount; - } - return Math.round(usd * 100) / 100; -} - -export function metric(id, label, used, limit, unit, source, detail) { - const m = { id, label, used, limit, unit, source }; - if (detail) m.detail = detail; - if (used != null && limit != null && limit > 0 && used / limit >= PAID_TRIGGER_RATIO) { - m.flag = "approaching-paid-trigger"; - } - return m; -} - -/** Build the three tracked metrics from whatever the API answered. Missing - * reads stay null (never zero) and carry the reason in `detail`. */ -export function buildMetrics({ dbBytes, bucketCount, requestTotal }) { - const dbUsed = dbBytes == null ? null : GB(dbBytes); - const storageUsed = bucketCount === 0 ? 0 : null; // no buckets = no stored bytes (a non-empty bucket inventory exposes no byte sizes) - return [ - metric( - "db-size", - "Database size", - dbUsed, - FREE_LIMITS["db-size"], - "gb", - "management-api:/database/query pg_database_size", - dbBytes == null ? "SQL read unavailable this tick" : `${dbBytes} bytes`, - ), - metric( - "egress", - "Egress (cycle)", - null, - FREE_LIMITS.egress, - "gb", - "none", - `No Management API endpoint reports egress bytes (usage.egress / usage.unified-egress 404); ${ - requestTotal == null ? "request count also unavailable" : `${requestTotal} API requests observed (usage.api-requests-count)` - }.`, - ), - metric( - "storage", - "File storage", - storageUsed, - FREE_LIMITS.storage, - "gb", - "management-api:/storage/buckets", - bucketCount == null - ? "storage/buckets unavailable this tick" - : bucketCount === 0 - ? "0 buckets on the project — no stored objects" - : `${bucketCount} buckets; per-bucket byte sizes are not exposed by this endpoint`, - ), - ]; -} - -/** Probe a path and return { status, json? , text? } without throwing on HTTP. */ -async function probe(fetchImpl, token, path) { - const res = await fetchImpl(`${API_BASE}${path}`, { - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/json", - }, - }); - let body = null; - try { - body = await res.text(); - } catch { - body = null; - } - let json = null; - try { - json = body ? JSON.parse(body) : null; - } catch { - json = null; - } - return { status: res.status, json, body }; -} - -async function api(fetchImpl, token, path, init) { - const res = await fetchImpl(`${API_BASE}${path}`, { - ...init, - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/json", - ...(init?.headers ?? {}), - }, - }); - const text = await res.text(); - return { status: res.status, text }; -} - -export async function run({ token, ref, fetchImpl = fetch } = {}) { - if (!token) throw new ExportError("no-token", 3, "Bitwarden secret did not resolve"); - if (typeof ref !== "string" || !ref.trim()) { - throw new ExportError("no-project-ref", 3, `Bitwarden secret ${DEFAULT_PROJECT_REF_SECRET_NAME} did not resolve`); - } - ref = ref.trim(); - const call = (path, init) => api(fetchImpl, token, path, init); - - const project = await call(`/projects/${ref}`); - if (project.status === 401 || project.status === 403) { - throw new ExportError("scope-denied", 4, `GET /projects/${ref}: HTTP ${project.status}`); - } - if (project.status !== 200) { - throw new ExportError("fetch-failed", 5, `GET /projects/${ref}: HTTP ${project.status}`); - } - let projectBody; - try { - projectBody = JSON.parse(project.text); - } catch { - throw new ExportError("unparseable", 6, "GET /projects/:ref returned non-JSON"); - } - - const scope = [ - { endpoint: "projects", path: "/projects", status: project.status }, - { endpoint: "project", path: `/projects/${ref}`, status: project.status }, - ]; - - // Database size — the one real measure of the Free 500 MB wedge. - let dbBytes = null; - const size = await call(`/projects/${ref}/database/query`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ query: "select pg_database_size(current_database()) as bytes" }), - }); - scope.push({ endpoint: "db-size SQL", path: `/projects/${ref}/database/query`, status: size.status }); - if (size.status === 200 || size.status === 201) { - try { - dbBytes = parseDbSize(JSON.parse(size.text)); - } catch (err) { - scope.push({ endpoint: "db-size SQL", path: `/projects/${ref}/database/query`, status: size.status, note: err.message }); - } - } - - // File storage — bucket inventory (a project with no buckets stores nothing). - let bucketCount = null; - const buckets = await call(`/projects/${ref}/storage/buckets`); - scope.push({ endpoint: "storage/buckets", path: `/projects/${ref}/storage/buckets`, status: buckets.status }); - if (buckets.status === 200) { - try { - const parsed = JSON.parse(buckets.text); - if (Array.isArray(parsed)) bucketCount = parsed.length; - } catch { - /* leave null — the metric says so */ - } - } - - // Egress: there is no bytes endpoint. Record the gap precisely and keep the - // request count as context, then the available usage endpoints for the record. - const requests = await probe(fetchImpl, token, `/projects/${ref}/analytics/endpoints/usage.api-requests-count`); - scope.push({ - endpoint: "usage.api-requests-count", - path: `/projects/${ref}/analytics/endpoints/usage.api-requests-count`, - status: requests.status, - note: "request counts only — no egress bytes", - }); - const requestTotal = requests.status === 200 ? parseRequestCount(requests.json) : null; - for (const path of [ - `/projects/${ref}/analytics/endpoints/usage.egress`, - `/projects/${ref}/analytics/endpoints/usage.unified-egress`, - `/projects/${ref}/usage`, - `/projects/${ref}/database/size`, - ]) { - const r = await probe(fetchImpl, token, path); - scope.push({ endpoint: path.split("/").pop(), path, status: r.status, note: r.status === 404 ? "no such endpoint" : undefined }); - } - - // Billing: addons are the only readable $ state; the org-scope plan read is - // Forbidden with this token, which is recorded, not guessed around. - let billing = null; - const addons = await call(`/projects/${ref}/billing/addons`); - scope.push({ endpoint: "billing/addons", path: `/projects/${ref}/billing/addons`, status: addons.status }); - if (addons.status === 200) { - try { - const usd = billedFromAddons(JSON.parse(addons.text)); - billing = { - plan: "free", - billedUsd: usd, - measured: true, - source: "management-api:/billing/addons (no selected paid addons)", - }; - } catch { - billing = null; - } - } - const slug = projectBody?.organization_slug; - if (slug) { - const org = await probe(fetchImpl, token, `/organizations/${slug}`); - scope.push({ - endpoint: "organizations/:slug", - path: `/organizations/${slug}`, - status: org.status, - note: org.status === 403 ? "scope gap: token is project-scoped; plan/billing org reads need an org token (Drew's account action)" : undefined, - }); - } - - const metrics = buildMetrics({ dbBytes, bucketCount, requestTotal }); - const measured = metrics.some((m) => m.used != null); - if (!measured) { - throw new ExportError("unparseable", 6, "no metric could be measured this tick (scope: see probe)"); - } - const gaps = scope.filter((s) => s.status >= 400); - return { - service: "supabase", - source: SOURCE, - status: gaps.length ? "partial" : "ok", - measuredAt: new Date().toISOString(), - project: projectBody?.name ?? "unknown", - ref, - metrics, - billing, - scope, - }; -} - -export function failureDocument({ attemptedAt, status, detail }) { - return { - service: "supabase", - source: SOURCE, - status, - measuredAt: null, - attemptedAt, - detail, - }; -} - -export async function writeOutputs(outDir, doc) { - await mkdir(outDir, { recursive: true }); - const tmp = join(outDir, `.latest.json.tmp-${process.pid}`); - await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); - await rename(tmp, join(outDir, "latest.json")); - await appendFile(join(outDir, "history.jsonl"), `${JSON.stringify(doc)}\n`, "utf8"); -} - -/** Resolve a Bitwarden secret by NAME — its value stays in memory. */ -async function resolveBwsSecret(secretName, bwsBin = process.env.BWS_BIN ?? "bws", sourceEnv = process.env) { - const accessToken = sourceEnv.BWS_ACCESS_TOKEN; - const env = { ...sourceEnv, ...(accessToken ? { BWS_ACCESS_TOKEN: accessToken } : {}) }; - const runBws = (args) => - new Promise((resolve, reject) => { - execFile(bwsBin, args, { env, maxBuffer: 16 << 20, timeout: 30_000 }, (err, stdout) => - err ? reject(new Error("bws call failed")) : resolve(stdout), - ); - }); - try { - const list = JSON.parse(await runBws(["secret", "list"])); - const entry = Array.isArray(list) ? list.find((s) => s.key === secretName) : null; - if (!entry?.id) return null; - const got = JSON.parse(await runBws(["secret", "get", entry.id])); - return typeof got?.value === "string" && got.value.trim() ? got.value.trim() : null; - } catch { - return null; // never log why: the failure detail may carry the secret's neighbourhood - } -} - -/** Resolve the current Supabase project ref, preferring an explicit override. */ -export async function resolveProjectRef({ - secretName = process.env.SUPABASE_PROJECT_REF_SECRET_NAME ?? DEFAULT_PROJECT_REF_SECRET_NAME, - bwsBin = process.env.BWS_BIN ?? "bws", - env = process.env, -} = {}) { - const override = env.SUPABASE_PROJECT_REF?.trim(); - if (override) return override; - return resolveBwsSecret(secretName, bwsBin, env); -} - -/** Resolve the management token by its Bitwarden NAME — value stays in memory. */ -export async function resolveToken({ secretName = process.env.SUPABASE_TOKEN_SECRET_NAME ?? DEFAULT_SECRET_NAME, bwsBin = process.env.BWS_BIN ?? "bws" } = {}) { - if (process.env.SUPABASE_MANAGEMENT_TOKEN) return process.env.SUPABASE_MANAGEMENT_TOKEN; - return resolveBwsSecret(secretName, bwsBin); -} - -/** Strict single-pass argv parsing (#3469). Every value-taking flag must be - * followed by a value token that is not itself a flag: a flag token (or - * nothing) where a value belongs is a usage error naming the flag, raised - * before any directory is created, any token is resolved, or any API call - * is made. The parse is single-pass — each value token is consumed once — - * so a flag token can never double as both a value and a flag. Unknown - * flags and bare positionals are usage errors too: silently ignoring them - * is what used to redirect output into a directory named after a flag. - * Throws ExportError("usage", 2); main() turns it into stderr + exit 2. - * The project-ref flag is returned unresolved: main() applies the env - * fallback and resolveProjectRef()'s secret-based resolution to it, in - * that order, exactly as the old opt() flow did. */ -const VALUE_FLAGS = new Set(["--out-dir", "--project-ref"]); - -function usageError(message) { - throw new ExportError("usage", 2, message); -} - -export function parseArgs(argv) { - const values = {}; - for (let i = 0; i < argv.length; i++) { - const token = argv[i]; - if (!VALUE_FLAGS.has(token)) { - if (token.startsWith("--")) usageError(`unknown flag ${JSON.stringify(token)}`); - else usageError(`unexpected argument ${JSON.stringify(token)} (this exporter takes only --flag value pairs)`); - } - const value = argv[i + 1]; - if (typeof value !== "string" || value === "" || value.startsWith("--")) { - usageError( - `${token} requires a value that is not another flag (got ${value === undefined ? "nothing" : JSON.stringify(value)})`, - ); - } - values[token] = value; - i++; // consume the value: no token is read twice - } - return { - outDir: values["--out-dir"] ?? join(homedir(), "atlas", "supabase-export"), - refOverride: values["--project-ref"], - }; -} - -async function main() { - let options; - try { - options = parseArgs(process.argv.slice(2)); - } catch (error) { - if (error instanceof ExportError && error.status === "usage") { - console.error(`supabase-quota-export: ${error.message}; refusing to run, no output written`); - process.exit(2); - } - throw error; - } - const outDir = options.outDir; - const refOverride = options.refOverride ?? process.env.SUPABASE_PROJECT_REF; - try { - const token = await resolveToken(); - const ref = refOverride?.trim() || await resolveProjectRef(); - const doc = await run({ token, ref }); - await writeOutputs(outDir, doc); - const flags = doc.metrics.filter((m) => m.flag).map((m) => m.id); - console.log( - JSON.stringify({ status: doc.status, measuredAt: doc.measuredAt, metrics: doc.metrics.map((m) => m.id), triggers: flags, outDir }), - ); - } catch (e) { - const err = e instanceof ExportError ? e : new ExportError("fetch-failed", 5, `unexpected: ${e.message ?? String(e)}`); - const doc = failureDocument({ attemptedAt: new Date().toISOString(), status: err.status, detail: err.message }); - try { - await writeOutputs(outDir, doc); - } catch (writeErr) { - console.error(`supabase-quota-export: could not write outputs: ${writeErr.message}`); - } - console.error(`supabase-quota-export: ${err.status}: ${err.message}`); - process.exit(err.exitCode); - } -} - -const isMain = (() => { - try { - if (!process.argv[1]) return false; - return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); - } catch { - return false; - } -})(); -if (isMain) { - await main(); -} diff --git a/pm-stack/supabase-export/supabase-quota-export.service b/pm-stack/supabase-export/supabase-quota-export.service deleted file mode 100644 index 8685a90527..0000000000 --- a/pm-stack/supabase-export/supabase-quota-export.service +++ /dev/null @@ -1,18 +0,0 @@ -[Unit] -Description=Supabase usage exporter — code#1050 -After=network-online.target - -[Service] -Type=oneshot -TimeoutStartSec=120 -# Start through bash so the laptop auth hook loads: systemd user units get -# BASH_ENV from the manager environment (home/common/default.nix -# sessionVariables -> agent-shell-env env.sh), and a non-interactive bash -# sources $BASH_ENV before running the command — that hook is what puts -# BWS_ACCESS_TOKEN in the environment for the producer's Bitwarden token -# resolution. Starting bun directly skipped the hook and every tick failed -# no-token. The placeholders in ExecStart are rendered by -# install-laptop.sh from the selected installation directory and the -# laptop's bash/bun found on PATH at install time (this NixOS laptop has -# no /bin/bash, so a hardcoded shell path would not even start). -ExecStart=@BASH@ -c "exec @BUN@ @EXPORT_DIR@/supabase-quota-export.mjs --out-dir @EXPORT_DIR@" diff --git a/pm-stack/supabase-export/supabase-quota-export.test.mjs b/pm-stack/supabase-export/supabase-quota-export.test.mjs deleted file mode 100644 index 8bb2093ef5..0000000000 --- a/pm-stack/supabase-export/supabase-quota-export.test.mjs +++ /dev/null @@ -1,304 +0,0 @@ -// Offline tests for pm-stack/supabase-export (#1050 / queue task 2985). -// No network, no Bitwarden: the Supabase API is an injected fake fetch. -import { describe, expect, test } from "bun:test"; -import { - DEFAULT_PROJECT_REF_SECRET_NAME, - ExportError, - FREE_LIMITS, - PAID_TRIGGER_RATIO, - billedFromAddons, - buildMetrics, - failureDocument, - parseArgs, - parseDbSize, - parseRequestCount, - resolveProjectRef, - run, -} from "./supabase-quota-export.mjs"; - -const REF = "fixture-project-ref"; - -function response(status, body) { - return { - status, - text: async () => (typeof body === "string" ? body : JSON.stringify(body)), - }; -} - -/** Fake Management API response for an isolated fixture project. */ -function fakeFetch({ dbBytes = 1_153_939_123, bucketCount = 0, addonsStatus = 200, addons = [] } = {}) { - const calls = []; - const impl = async (url, init) => { - calls.push({ url, method: init?.method ?? "GET", authorization: init?.headers?.Authorization }); - // The real Management API refuses unauthenticated calls; the fake does - // too, so a probe that forgets the bearer token cannot pass silently. - if (init?.headers?.Authorization !== "Bearer sbp_fake") return response(401, { message: "Unauthorized" }); - const path = url.replace("https://api.supabase.com/v1", ""); - if (path === `/projects/${REF}`) { - return response(200, { - ref: REF, - name: "fixture-project", - organization_slug: "crwkmndylaagtbprrljn", - status: "ACTIVE_HEALTHY", - }); - } - if (path === `/projects/${REF}/database/query`) return response(dbBytes == null ? 500 : 201, [{ bytes: dbBytes }]); - if (path === `/projects/${REF}/storage/buckets`) return response(200, Array.from({ length: bucketCount }, (_, i) => ({ id: `b${i}` }))); - if (path === `/projects/${REF}/analytics/endpoints/usage.api-requests-count`) return response(200, { result: [{ count: 185893 }] }); - if (path === `/projects/${REF}/billing/addons`) return response(addonsStatus, { selected_addons: addons, available_addons: [] }); - if (path === `/organizations/crwkmndylaagtbprrljn`) return response(403, { message: "Forbidden" }); - return response(404, { message: `Cannot GET ${path}` }); - }; - return { impl, calls }; -} - -describe("supabase-quota-export", () => { - test("measures db size against the Free limit and flags the paid trigger", async () => { - const { impl } = fakeFetch(); - const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); - expect(doc.service).toBe("supabase"); - expect(doc.source).toBe("file-export/supabase"); - const db = doc.metrics.find((m) => m.id === "db-size"); - expect(db.used).toBeCloseTo(1.154, 2); - expect(db.limit).toBe(FREE_LIMITS["db-size"]); - expect(db.used / db.limit).toBeGreaterThanOrEqual(PAID_TRIGGER_RATIO); - expect(db.flag).toBe("approaching-paid-trigger"); - expect(db.source).toContain("pg_database_size"); - }); - - test("every Management API call, probes included, carries the bearer token", async () => { - const { impl, calls } = fakeFetch(); - await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); - expect(calls.length).toBeGreaterThan(5); - expect(calls.every((c) => c.authorization === "Bearer sbp_fake")).toBe(true); - }); - - test("records the egress scope gap without inventing a value", async () => { - const { impl } = fakeFetch(); - const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); - const egress = doc.metrics.find((m) => m.id === "egress"); - expect(egress.used).toBeNull(); - expect(egress.limit).toBe(FREE_LIMITS.egress); - expect(egress.detail).toContain("185893"); - expect(egress.flag).toBeUndefined(); - const egressProbe = doc.scope.find((s) => s.path.endsWith("usage.egress")); - expect(egressProbe.status).toBe(404); - const orgProbe = doc.scope.find((s) => s.endpoint === "organizations/:slug"); - expect(orgProbe.status).toBe(403); - expect(orgProbe.note).toContain("scope gap"); - }); - - test("storage is zero when the project has no buckets, and billing is a measured addon read", async () => { - const { impl } = fakeFetch({ bucketCount: 0 }); - const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); - const storage = doc.metrics.find((m) => m.id === "storage"); - expect(storage.used).toBe(0); - expect(storage.limit).toBe(FREE_LIMITS.storage); - expect(doc.billing).toMatchObject({ plan: "free", billedUsd: 0, measured: true }); - expect(doc.status).toBe("partial"); // 403/404 probes were recorded - }); - - test("an unreadable db size leaves used null rather than zero", async () => { - const { impl } = fakeFetch({ dbBytes: null }); - const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); - const db = doc.metrics.find((m) => m.id === "db-size"); - expect(db.used).toBeNull(); - expect(db.flag).toBeUndefined(); - }); - - test("a token the API refuses is a scope-denied failure with no values", async () => { - const impl = async () => response(401, { message: "Unauthorized" }); - const err = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }).catch((e) => e); - expect(err).toBeInstanceOf(ExportError); - expect(err.status).toBe("scope-denied"); - expect(err.exitCode).toBe(4); - }); - - test("a missing token is a no-token failure", async () => { - const err = await run({ token: null, ref: REF }).catch((e) => e); - expect(err.status).toBe("no-token"); - }); - - test("project ref uses the canonical Bitwarden key and honors the environment override", async () => { - expect(DEFAULT_PROJECT_REF_SECRET_NAME).toBe("supabase.project-ref"); - expect(await resolveProjectRef({ env: { SUPABASE_PROJECT_REF: "from-env" } })).toBe("from-env"); - expect(await resolveProjectRef({ secretName: "fixture.project-ref", bwsBin: "missing-bws" })).toBeNull(); - }); - - test("a missing project ref fails explicitly", async () => { - const err = await run({ token: "sbp_fake", fetchImpl: async () => response(200, {}) }).catch((e) => e); - expect(err).toBeInstanceOf(ExportError); - expect(err.status).toBe("no-project-ref"); - expect(err.exitCode).toBe(3); - }); - - test("failure documents carry no metric or billing values", () => { - const doc = failureDocument({ attemptedAt: "2026-10-29T10:00:00Z", status: "fetch-failed", detail: "HTTP 502" }); - expect(doc.metrics).toBeUndefined(); - expect(doc.billing).toBeUndefined(); - expect(doc.measuredAt).toBeNull(); - }); - - test("parsers reject shape drift", () => { - expect(() => parseDbSize([{ bytes: "nope" }])).toThrow(ExportError); - for (const bytes of ["", " ", "0x10", "1e3", "1.5", 1.5, -1, "-1"]) { - expect(() => parseDbSize([{ bytes }])).toThrow(ExportError); - } - expect(parseDbSize([{ bytes: "0012" }])).toBe(12); - expect(parseDbSize([{ bytes: 12 }])).toBe(12); - expect(parseRequestCount({ result: [{ count: "12" }] })).toBe(12); - for (const count of ["", " ", "0x10", "1e3", "1.5", 1.5, -1, "-1"]) { - expect(parseRequestCount({ result: [{ count }] })).toBeNull(); - } - expect(parseRequestCount({ result: [{ count: 12 }] })).toBe(12); - expect(parseRequestCount({ result: [] })).toBeNull(); - expect(() => billedFromAddons({})).toThrow(ExportError); - expect(billedFromAddons({ selected_addons: [{ price: { amount: 25 } }] })).toBe(25); - }); - - test("billedFromAddons fails closed on unpriced or negative selected addons (#2492)", () => { - expect(() => billedFromAddons({ selected_addons: [{}] })).toThrow(ExportError); - expect(() => billedFromAddons({ selected_addons: [{ price: {} }] })).toThrow(ExportError); - expect(() => billedFromAddons({ selected_addons: [{ price: { amount: null } }] })).toThrow(ExportError); - expect(() => billedFromAddons({ selected_addons: [{ price: { amount: "25" } }] })).toThrow(ExportError); - expect(() => billedFromAddons({ selected_addons: [{ price: { amount: -25 } }] })).toThrow(ExportError); - expect(() => billedFromAddons({ selected_addons: [{ price: { amount: 25 } }, { price: {} }] })).toThrow(ExportError); - expect(billedFromAddons({ selected_addons: [] })).toBe(0); - expect(billedFromAddons({ selected_addons: [{ price: { amount: 0 } }] })).toBe(0); - expect(billedFromAddons({ selected_addons: [{ price: { amount: 25 } }, { price: { amount: 5 } }] })).toBe(30); - }); - - test("a drifted addon yields billing null while metrics still publish (#2492)", async () => { - const { impl } = fakeFetch({ addons: [{ price: { amount: 25 } }, { name: "unpriced-addon" }] }); - const doc = await run({ token: "sbp_fake", ref: REF, fetchImpl: impl }); - expect(doc.billing).toBeNull(); - expect(doc.metrics.find((m) => m.id === "db-size").used).toBeCloseTo(1.154, 2); - }); - - test("buildMetrics never emits a paid trigger for an unmeasured metric", () => { - const metrics = buildMetrics({ dbBytes: null, bucketCount: null, requestTotal: null }); - expect(metrics.every((m) => m.flag === undefined)).toBe(true); - }); -}); - -describe("parseArgs strict argv (#3469)", () => { - // Strict argv validation (#3469): a value flag followed by another - // flag (or by nothing) is a usage error naming the flag, raised before - // any directory creation, token resolution, or API call; no token is - // consumed twice. - function expectUsage(argv, flag) { - let error = null; - try { - parseArgs(argv); - } catch (e) { - error = e; - } - expect(error).toBeInstanceOf(ExportError); - expect(error.status).toBe("usage"); - expect(error.exitCode).toBe(2); - expect(error.message).toContain(flag); - } - - test("parseArgs: the control invocation parses, project-ref override (#3469)", () => { - expect(parseArgs(["--out-dir", "out", "--project-ref", "proberef"])).toEqual({ - outDir: "out", - refOverride: "proberef", - }); - const def = parseArgs([]); - expect(def.outDir).toMatch(/supabase-export$/); - expect(def.refOverride).toBeUndefined(); - }); - - test("parseArgs: flag-as-value is a usage error naming the flag (#3469)", () => { - // The exact probe from the issue: --project-ref must not double as - // the out-dir value and the ref flag. - expectUsage(["--out-dir", "--project-ref", "proberef"], "--out-dir"); - expectUsage(["--project-ref", "--out-dir", "out"], "--project-ref"); - }); - - test("parseArgs: a trailing flag with no value is a usage error, not a silent fallback (#3469)", () => { - expectUsage(["--out-dir"], "--out-dir"); - expectUsage(["--out-dir", "out", "--project-ref"], "--project-ref"); - }); - - test("parseArgs: no token is consumed twice (#3469)", () => { - // Old opt() returned "--project-ref" as the out-dir while the API - // call still used proberef. Now the single-pass parse refuses - // outright instead of splitting the token stream two ways. - expectUsage(["--out-dir", "--project-ref", "proberef"], "--out-dir"); - }); - - test("parseArgs: unknown flags and bare positionals are usage errors (#3469)", () => { - expectUsage(["--bogus", "x"], "--bogus"); - expectUsage(["--out-dir=out"], "--out-dir=out"); - expectUsage(["out"], "out"); - }); -}); - -describe("parseArgs property-based (#3469, Codex P1 on PR #9009)", () => { - // Oracle: the declared argv grammar — a stream is zero or more - // (value-flag, value) pairs; a value is a non-empty token not - // starting with "--"; a repeated flag's last occurrence wins. - // Streams are generated from that grammar (valid) or by injecting - // exactly one grammar violation (malformed), so the expected - // outcome is known by construction, independent of the parser - // under test. Deterministic seeded RNG: failures reproduce exactly. - function mulberry32(seed) { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) | 0; - let t = Math.imul(a ^ (a >>> 15), 1 | a); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; - } - function expectUsage(argv, flag) { - let error = null; - try { - parseArgs(argv); - } catch (e) { - error = e; - } - expect(error).toBeInstanceOf(ExportError); - expect(error.status).toBe("usage"); - expect(error.exitCode).toBe(2); - expect(error.message).toContain(flag); - } - const FLAGS = ["--out-dir", "--project-ref"]; - const VALUES = ["out", "a/b", "x", "-single", "proberef", "19222"]; - - test("generated valid streams parse, last value wins, no token consumed twice", () => { - const rand = mulberry32(0x3469e); - const defaults = parseArgs([]); - for (let iter = 0; iter < 250; iter++) { - const pairs = []; - const n = Math.floor(rand() * 5); - for (let k = 0; k < n; k++) { - pairs.push([FLAGS[Math.floor(rand() * FLAGS.length)], VALUES[Math.floor(rand() * VALUES.length)]]); - } - const argv = pairs.flat(); - const parsed = parseArgs(argv); - const last = (flag) => pairs.filter(([f]) => f === flag).at(-1)?.[1]; - expect(parsed.outDir).toBe(last("--out-dir") ?? defaults.outDir); - expect(parsed.refOverride).toBe(last("--project-ref")); - for (const v of [parsed.outDir, parsed.refOverride]) if (v !== undefined) expect(String(v).startsWith("--")).toBe(false); - } - }); - - test("generated malformed streams are usage errors naming the offending flag", () => { - const rand = mulberry32(0x3469f); - for (let iter = 0; iter < 250; iter++) { - const kind = Math.floor(rand() * 3); - const flag = FLAGS[Math.floor(rand() * FLAGS.length)]; - if (kind === 0) { - const other = FLAGS[Math.floor(rand() * FLAGS.length)]; - expectUsage([flag, other, "x"], flag); - } else if (kind === 1) { - expectUsage(["--out-dir", "out", flag], flag); - } else { - const bogus = "--bogus-" + Math.floor(rand() * 1000); - expectUsage(["--out-dir", "out", bogus, "x"], bogus); - } - } - }); -}); diff --git a/pm-stack/supabase-export/supabase-quota-export.timer b/pm-stack/supabase-export/supabase-quota-export.timer deleted file mode 100644 index 9afe2a6034..0000000000 --- a/pm-stack/supabase-export/supabase-quota-export.timer +++ /dev/null @@ -1,11 +0,0 @@ -[Unit] -Description=Run the Supabase usage exporter every 15 minutes — code#1050 (gatherer tick, #1151) - -[Timer] -OnCalendar=*:0/15 -RandomizedDelaySec=20 -Persistent=true -Unit=supabase-quota-export.service - -[Install] -WantedBy=timers.target diff --git a/pm-stack/systemd/pm-dispatch.service b/pm-stack/systemd/pm-dispatch.service index 24a983a3e8..0ce9fb58f4 100644 --- a/pm-stack/systemd/pm-dispatch.service +++ b/pm-stack/systemd/pm-dispatch.service @@ -18,8 +18,7 @@ EnvironmentFile=%h/pm-stack/dispatch/.env # Operator secrets that are NOT in the sops file (mode 600, laptop-only): # DISPATCH_API_TOKEN only. Optional-file syntax so a missing file # degrades to bearer-auth-off, not a crash loop. This file is read -# AFTER the rendered file, so it wins on any collision. SUPABASE_* -# lines are obsolete since #9028 (install.sh warns; delete them). +# AFTER the rendered file, so it wins on any collision. EnvironmentFile=-%h/secrets/dispatch.env Restart=on-failure RestartSec=5