diff --git a/doc/backups/README.md b/doc/backups/README.md new file mode 100644 index 0000000000..c628d695d2 --- /dev/null +++ b/doc/backups/README.md @@ -0,0 +1,5 @@ +# Reports + +Dated outputs of work done in this repo: summaries, audits, analyses, backup ledgers. A report records what happened at a time; it is not maintained afterwards (corrections get a new dated report, or a note in the original). + +If a report becomes standing reference material, it graduates to `library/` — reports are the inbox, the library is the shelf. diff --git a/doc/backups/backup-process-2026-10-21.md b/doc/backups/backup-process-2026-10-21.md new file mode 100644 index 0000000000..7c76429b6d --- /dev/null +++ b/doc/backups/backup-process-2026-10-21.md @@ -0,0 +1,22 @@ +# Backup process + ledger — 2026-10-21 + +## The process + +Backups here are layered, by what the thing is: + +1. **Source-of-truth text** (memory, docs, scripts, plans) → git: `dezren39/hatch` (public-safe) and `dezren39/hatch-personal` (everything private, including "not secret but private-guidance" material). Commits are the change record; the push is the backup completing. +2. **Secrets** → Bitwarden Secrets Manager, by name; repos and docs reference names and locations only. Files that are themselves secrets get uploaded as secret values (file-level) — audited 2026-10-21. +3. **Bulky/opaque data** (session transcripts, tarballs) → Google Drive folders `Muse Backups` and `Muse Avatar Backup`, each with a manifest (date, source, sha256, restore instructions). Git is the wrong tool for these (see the chunk-drawer research in the library build notes). +4. **Databases** → native dumps stored in the private repo when tiny (a SQLite dump is text and diffs beautifully) plus independent exports for anything that matters. +5. **The nix store / toolchains** → reproducible from docs + the snapshot tarball (`~/tools/nix-snapshot.sh`); binaries that are NOT reproducible that way are listed in `library/toolchains/binary-backup.md`. + +Rule of thumb: every backup run leaves a record a future agent can verify — a commit, a manifest with hashes, or an entry in this ledger. + +## Ledger (most recent first) + +- 2026-10-21 — Private DB backup (SQLite dump, verified by restore into a scratch DB) filed in hatch-personal. Details intentionally private-only. +- 2026-10-21 — Secret-file → Bitwarden coverage audit + upload (see private records). +- 2026-10-21 — Small-files/scripts sweep into hatch `archive/` + hatch-personal `junk/` with hash manifests. +- 2026-10-21 — Session logs: `session-logs-2026-10-21.tar.zst` (~/agents, 1.1 GB → 103 MiB) + manifest → Drive `Muse Backups`; MD5-verified after upload. +- 2026-10-18 — Avatar backup to Drive `Muse Avatar Backup` (12 files, sizes verified; restore test passed; daily job `avatar-backup-daily` continues it). +- Ongoing — memory/personality/instructions sync to hatch-personal with normal work (private). diff --git a/doc/backups/binary-backup.md b/doc/backups/binary-backup.md new file mode 100644 index 0000000000..d2b321e095 --- /dev/null +++ b/doc/backups/binary-backup.md @@ -0,0 +1,55 @@ +# Binary backup manifest + +Generated 2026-10-21. Drew's rule (2026-10-21): the toolchain **backup set includes the binaries themselves**, not just docs and secrets — including the Bitwarden CLI (`bws`) in addition to the Bitwarden secrets it guards. + +Most entries in `~/tools/bin` are symlinks/dispatcher stubs that resolve reproducibly from nix/omnibin — those are covered by the setup-cycle docs and do not need byte-level backup. The standalone real files below are the ones to copy as-is. + +| file | bytes | sha256 (first 16) | note | +|---|---|---|---| +| ~/tools/bin/age-keygen | 266 | 6b060af7d8c038e8 | | +| ~/tools/bin/bws | 12359704 | e6982cfac1094d9b | Bitwarden Secrets Manager CLI | +| ~/tools/bin/cargo | 256 | a100950361d070f0 | | +| ~/tools/bin/codedb | 4427904 | af44d5f02a6c9a28 | | +| ~/tools/bin/cowsay | 258 | b7740b9809c9e427 | | +| ~/tools/bin/crane | 256 | be91577b8a1ac8e4 | | +| ~/tools/bin/deno | 254 | 4c7ada24e696fbdc | | +| ~/tools/bin/docker | 258 | e3681a0254f0d1b0 | | +| ~/tools/bin/fff | 252 | 3e167cda916b4f64 | | +| ~/tools/bin/fff-mcp | 13355488 | 20917f2c3e35612d | | +| ~/tools/bin/figlet | 258 | fe9c3942d930a249 | | +| ~/tools/bin/fish | 254 | 3d3b597485d150b3 | | +| ~/tools/bin/getfacl | 260 | c0968976ce93d357 | | +| ~/tools/bin/git | 252 | 049121e426d9b97b | | +| ~/tools/bin/go | 250 | 2c122df9bf24305a | | +| ~/tools/bin/gofmt | 256 | 9d8bfd8a1df15613 | | +| ~/tools/bin/hello | 256 | fe940ebd1ed3d9c5 | | +| ~/tools/bin/just | 254 | e4361fbe2890472f | | +| ~/tools/bin/nix-instantiate | 276 | 6e57018a7f535e4c | | +| ~/tools/bin/nix-store | 264 | dd65b1979f6c21f5 | | +| ~/tools/bin/oci | 252 | 380c4e135c86215f | | +| ~/tools/bin/or | 250 | 4b85ec244ca08ff3 | | +| ~/tools/bin/pg_dump | 260 | 37f2bbf8e11f0c9c | | +| ~/tools/bin/prettier | 262 | c9b4365c02c6f163 | | +| ~/tools/bin/profile | 260 | 78ff579ea1239248 | | +| ~/tools/bin/ruff | 254 | c3faa7cc358d6ef5 | | +| ~/tools/bin/rustc | 256 | 08c36859e3a9f1c6 | | +| ~/tools/bin/rustfmt | 260 | a4c0e7a9f12e7977 | | +| ~/tools/bin/rustup | 258 | e0753235a8cd1e4a | | +| ~/tools/bin/screen | 258 | f1f614f1cef5fe46 | | +| ~/tools/bin/shellcheck | 266 | 7a232ee2cc8806c4 | | +| ~/tools/bin/shfmt | 256 | e6d81acf6578b9d5 | | +| ~/tools/bin/skopeo | 258 | 1c0c1faae31fd5aa | | +| ~/tools/bin/sops | 254 | e87db8469016699d | | +| ~/tools/bin/supabase | 262 | 91af8ed5796cbf3e | | +| ~/tools/bin/taplo | 256 | 9c5fa27d54713afc | | +| ~/tools/bin/timeline | 262 | 193bbde90014c5a9 | | +| ~/tools/bin/turso | 256 | 24ad55d62ff4cff2 | | +| ~/tools/bin/uv | 250 | 060a1679f1359bbc | | +| ~/tools/bin/xxd | 252 | 96ccfd733eff6a9b | | + +Toolchains installed as trees (back up the tree or reinstall via its doc): Go (~/tools/go), Rust (~/tools/cargo + ~/tools/rustup), wrangler (~/tools/wrangler), nix (persistent store — see nix.md, snapshot via ~/tools/nix-snapshot.sh). +Chromium + Playwright: install targets only, optional/headless — see chromium-playwright.md. Tailscale CLI: keep installed — see tailscale.md. + +## Turso CLI provenance (resolved 2026-10-21) + +The turso binary originally 'just existed' because it was a dispatcher/omnibin stub (Nix build of turso-cli 1.0.30), auto-created on first invocation — never a deliberate install. It has since been replaced with the official install (`get.tur.so/install.sh`, archived in `archive/install-scripts/`): real binary at `~/.turso/turso` (**v1.0.34**), `~/tools/bin/turso` now symlinks to it, existing `~/.config/turso/settings.json` worked unchanged (auth whoami = dezren39). Sandbox gotchas for any reinstall: the official script needs `TAR_OPTIONS=--no-same-owner` (sandbox denies chown, same quirk class as the Nix installer), it performs NO checksum verification, and it always installs 'latest' with no pinning — a reinstall silently upgrades. diff --git a/doc/backups/muse-backup-SKILL.md b/doc/backups/muse-backup-SKILL.md new file mode 100644 index 0000000000..790d9229c6 --- /dev/null +++ b/doc/backups/muse-backup-SKILL.md @@ -0,0 +1,27 @@ +# muse-backup + +Status: tentative, first draft 2026-10-21. + +## Purpose + +Back up Muse's durable state — memory and avatar — so it can be restored after a sandbox loss or an accidental edit, and keep the locations/rules in one place. + +## What lives where + +- **Memory (source of truth):** `dezren39/hatch-personal` (private git repo). On disk it is `~/hatch-personal/`, symlinked back to `~/MEMORY.md`, `~/memory/`, `~/USER.md`, etc. Backup = commit + push the private repo (surgical staging — memory files only when that is the task). The full symlink restore map is in `hatch-personal/library/inventory/symlink-map.md`. +- **Avatar:** source image + generated renders under `~/workspace/avatars/`, tracked in the public repo `dezren39/hatch`. Drew wants the backup to clearly include the avatar *and its animations*, with liked animations restorable if an accidental source-image edit produces renders he dislikes — i.e. keep prior render sets, don't just overwrite them; a new source image gets a new render set alongside the old. +- **Too big for git:** session transcripts (`~/agents/`, ~1 GB) and similar bulk go as tarballs to the dedicated Google Drive **"Muse Backups"** folder, never into either git repo. +- **Secrets are never part of a backup.** They live in Bitwarden; backups reference names only. Credential files are SECRET-SKIP (paths + sizes in the private inventory classification) — never copied into a backup set. + +## Procedure + +1. `git -C ~/hatch-personal status` — review carefully; stage only the intended memory/personal files; commit; push. Never sweep unrelated dirty files into a backup commit. +2. Avatar: confirm the current source image and all render/animation files for it are present under `~/workspace/avatars/` and tracked in `dezren39/hatch`; if renders were regenerated, keep the previous set until Drew confirms the new one. +3. Bulk (only when asked): tar the target (e.g. `~/agents/`) with a dated name, upload to Drive "Muse Backups", record name + size + date in the private repo. +4. Report what was backed up, where, and the commit SHA / Drive file name. State explicitly what was skipped and why. + +## Pitfalls + +- `/home/hatch` itself is a git repo distinct from `~/hatch-personal` — commit memory with `git -C ~/hatch-personal`, not from home. +- `~/workspace/goals` is a symlink into hatch-personal — files there are private-repo files even though the path looks public-workspace. +- Deletion inside read-only (555) directories fails even as root; `chmod u+w` first, or keep backups as single tarballs instead of live trees. diff --git a/doc/backups/muse-backup.md b/doc/backups/muse-backup.md new file mode 100644 index 0000000000..790d9229c6 --- /dev/null +++ b/doc/backups/muse-backup.md @@ -0,0 +1,27 @@ +# muse-backup + +Status: tentative, first draft 2026-10-21. + +## Purpose + +Back up Muse's durable state — memory and avatar — so it can be restored after a sandbox loss or an accidental edit, and keep the locations/rules in one place. + +## What lives where + +- **Memory (source of truth):** `dezren39/hatch-personal` (private git repo). On disk it is `~/hatch-personal/`, symlinked back to `~/MEMORY.md`, `~/memory/`, `~/USER.md`, etc. Backup = commit + push the private repo (surgical staging — memory files only when that is the task). The full symlink restore map is in `hatch-personal/library/inventory/symlink-map.md`. +- **Avatar:** source image + generated renders under `~/workspace/avatars/`, tracked in the public repo `dezren39/hatch`. Drew wants the backup to clearly include the avatar *and its animations*, with liked animations restorable if an accidental source-image edit produces renders he dislikes — i.e. keep prior render sets, don't just overwrite them; a new source image gets a new render set alongside the old. +- **Too big for git:** session transcripts (`~/agents/`, ~1 GB) and similar bulk go as tarballs to the dedicated Google Drive **"Muse Backups"** folder, never into either git repo. +- **Secrets are never part of a backup.** They live in Bitwarden; backups reference names only. Credential files are SECRET-SKIP (paths + sizes in the private inventory classification) — never copied into a backup set. + +## Procedure + +1. `git -C ~/hatch-personal status` — review carefully; stage only the intended memory/personal files; commit; push. Never sweep unrelated dirty files into a backup commit. +2. Avatar: confirm the current source image and all render/animation files for it are present under `~/workspace/avatars/` and tracked in `dezren39/hatch`; if renders were regenerated, keep the previous set until Drew confirms the new one. +3. Bulk (only when asked): tar the target (e.g. `~/agents/`) with a dated name, upload to Drive "Muse Backups", record name + size + date in the private repo. +4. Report what was backed up, where, and the commit SHA / Drive file name. State explicitly what was skipped and why. + +## Pitfalls + +- `/home/hatch` itself is a git repo distinct from `~/hatch-personal` — commit memory with `git -C ~/hatch-personal`, not from home. +- `~/workspace/goals` is a symlink into hatch-personal — files there are private-repo files even though the path looks public-workspace. +- Deletion inside read-only (555) directories fails even as root; `chmod u+w` first, or keep backups as single tarballs instead of live trees. diff --git a/pkgs/agent-backup/README.md b/pkgs/agent-backup/README.md new file mode 100644 index 0000000000..7fda98bb85 --- /dev/null +++ b/pkgs/agent-backup/README.md @@ -0,0 +1,142 @@ +# runtime-db-export + +Periodic export of the Muse runtime records DB into the Turso DB +`muse-mirror` (`agent_mirror_*` tables). Built 2026-10-29, approved by +Drew 2026-10-28. Runs as an agent cron job `runtime-db-export` every 6 hours +(America/Chicago) — it must be an agent job because scripts cannot reach the +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. + +## Files + +- `JOB-BODY.md` — the exact cron job body (self-contained: every query, + loader spec, watermark rule). The stored cron body is character-identical + to this file (verified by diff against the cron projection). +- `load_rows.py` — the landing loader (spec JSON on stdin; upserts, history + archiving, epoch→date/hour conversion pinned to UTC; drops `_`-prefixed + columns). Writes to Turso via `turso_client.py`. +- `turso_client.py` — the Turso transport (libsql HTTP pipeline) + the + SQLite DDL for all 28 landing tables (created on first use; the 20 + migration-copied tables already exist). Token by BWS name only + (`turso.muse-mirror-rw-token`), resolved via `fleet secrets get` with an + automatic direct-BWS fallback when the broker's cached value is rejected. + Also provides the staging mode: `RDE_TURSO_URL=file:/path.db` runs the + identical SQL path against a local SQLite file. +- `load_from_output.py` / `page_load.py` — feed saved oversized muse.db + outputs into the loader without rows passing through agent generation; + page_load prints the next keyset cursor. +- `run_sql.py` — raw SQL files → Turso muse-mirror (prunes, reconciliation + counts). Translates the PG dialect the job body uses (`agent.mirror_*` + names, `now()`, `DATE 'YYYY-MM-DD'`) to SQLite/libsql. +- `set_state.py` — records a unit's outcome in BOTH `state.json` and + `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 + inline merge; kept for reference). + +## Landing tables (28, all in Turso `muse-mirror` as `agent_mirror_*`) + +Mirrors: mirror_scheduler_jobs (162), mirror_scheduler_job_runs, +mirror_agent_agents, mirror_goals_goals (49), mirror_goals_updates, +mirror_scheduler_job_definitions (metadata only), mirror_agent_sessions +(source empty), mirror_sessions (derived per-session summaries). +History: mirror_history_{scheduler_jobs, agent_agents, goals_goals, +goals_updates, agent_sessions}. Rollups: mirror_token_usage_daily, +mirror_token_usage_hourly, mirror_session_activity_hourly. +Stats: mirror_message_token_stats_daily, mirror_session_stats_daily, +mirror_run_stats_daily, mirror_histograms_daily, mirror_concurrency_hourly, +mirror_distincts_daily, mirror_top_daily, mirror_tool_stats_daily, +mirror_compaction_stats_daily, mirror_subagent_stats_daily, +mirror_conversation_stats_daily. State: mirror_export_state. +(Counts as of the inaugural backfill are in the build report; they grow +every run.) + +## Design decisions and adaptations + +- **History granularity = run cadence.** mirror_history_* rows are written + when a mutable row's payload_hash changes between runs; changes made and + reverted between two runs collapse into one step. job_runs has NO history + (immutable-ish; status transitions are refreshed in place by M2 REFRESH). +- **agent.agents lands a REDUCED payload.** spawn_metadata_json averages + ~29KB/row (max 2.4MB — beyond muse.db's 64KB row cap) and + last_assistant_message ~4KB; the payload carries all scalar/identity + columns, the extracted scheduler_cron_job_id / worker phase, and the BYTE + LENGTHS of the four big text columns. Full-text export of agents is + impossible through muse.db. +- **scheduler.job_definitions is metadata-only** (task_text byte length + + md5): bodies are job prompts; length+hash detect changes. Source table + was empty at build anyway. +- **job_runs payload excludes** the raw device_read_state_json / + pending_terminal_result_json / onboarding_tour_body / + worker_approval_wait_json contents (NULL or approval blobs at build); + the approval blob's byte length is kept. +- **agent.sessions is EMPTY at source**, so mirror_agent_sessions is empty + and per-session summaries are DERIVED from agent.agents + (mirror_sessions): session key = coalesce(root_session_id, session_id), + with chat_id via chat.chats on the root agent's session_id. +- **Percentiles are nearest-rank** (row_number + rank + greatest(1, ceil(p*n))) — the muse.db vocabulary has no percentile_cont. + The "median" is the single middle rank ((n+1)/2 integer division): for + even n it is the lower-middle value, not the average of two middles. +- **Histogram bucket edges are fixed** (listed in JOB-BODY S4; do not + change). Zero-count buckets are skipped at load, so a recompute cannot + remove a bucket that dropped to zero (documented caveat). +- **Concurrency is an exact event-sweep** (single-pass peaks + carry-in + form; per-bucket correlated subqueries blow the 3s statement limit). + Runs with finished_at set but started_at NULL (never started) contribute + NO end event. Hour spine = hours with token usage (runs variant adds + run-scheduled hours). Run-concurrency is only meaningful inside the + job_runs retention window (~7 days at build); earlier hours read 0. +- **Rollups are upsert-only**: a recompute overwrites values for keys that + still exist but cannot retract a key that vanished from the source + grouping (e.g. an agent re-attributed to another job). Windows (last 4 + days daily, last 2 hours hourly) bound the staleness. +- **M3 mirror is append-only**: agents deleted at source are not pruned + (at final build check the mirror held 12,726 rows vs 12,680 live source + rows — source-side churn during the scan). M1/M4 snapshot tables DO + prune (with history archiving). +- **S8 tool stats**: runtime.tool_calls / tool_outputs were EMPTY at + build; the unit is landed-empty and its error rule (output error_text + NOT NULL OR status outside ('success','completed','ok')) is PROVISIONAL + until real data exists to validate against. +- **Anchors are UTC epochs**: first token day_epoch = 20724 (2026-09-28), + first hour_epoch = 497390. (An early build note used 20728 as the first + day — that was a wrong anchor, caught and repaired by a gap backfill; + coverage now spans 2026-09-28 onward for every daily unit.) +- **Pad technique**: short-row aggregate pages return inline from muse.db + and would have to be retyped; appending a 600-char `_pad` literal forces + the runtime to save the page to a file, and the loader drops `_` columns. + Page data then never passes through agent generation. + +## Operations + +- Inspect health: `agent_mirror_export_state` in muse-mirror + (`turso db shell muse-mirror`) or `state.json` (last_status / last_error + per unit; failures are isolated per unit and named in the run's report + line). +- Manual run: `cron.run runtime-db-export`. Cadence changes need Drew. +- Steady-state cost (measured on the inaugural run, 2026-10-29): + 50,772,671 input tokens / 199,890 output across the run's 6-agent tree + (worker root + live worker + 4 subagents), 3,067s wall. Usage rows post + only at run completion. NOTE: subagents do NOT inherit the + scheduler_cron_job_id spawn-metadata key, so the per-job rollup (R1/R2) + attributes only the root agents' ~25.6M input to this job — the true + all-in cost is the tree sum above. This is NOT a cheap job: at 6h + cadence it projects to ~200M input tokens/day. If that burn is + unwanted, levers are: longer cadence, narrower recompute windows, or a + leaner run agent (fewer inline pages in context). Cadence changes need + Drew. diff --git a/pkgs/agent-backup/bws-backup-secrets.sh b/pkgs/agent-backup/bws-backup-secrets.sh new file mode 100755 index 0000000000..caefcf3fae --- /dev/null +++ b/pkgs/agent-backup/bws-backup-secrets.sh @@ -0,0 +1,78 @@ +#!/bin/bash +# Back up on-disk secrets into Bitwarden Secrets Manager ("developing today"). +# +# bws has NO stdin/file input for values: `bws secret create KEY - PROJECT` +# stores the literal string "-". Values therefore go through $(cat file) — +# the literal command text (what the exec harness keeps in environ) contains +# only the file path, never the value. The value appears only transiently in +# the bws child process's argv while it runs. +# +# Gotchas (hit 2026-10-07): +# - `bws secret get -o json` returns an OBJECT for one id but the shape +# has varied; always normalize with: jq 'if type=="array" then .[0].value else .value end' +# - `jq -r` appends a trailing newline to the value; use `jq -j` when hashing +# for comparison, or every verification fails. +# - Values starting with `-` (e.g. "-----BEGIN OPENSSH PRIVATE KEY-----") +# are parsed as flags: put options FIRST, then `--`, then positionals: +# `bws secret create --note ... -o none -- KEY VALUE PROJECT`. +# (Without `--`, clap errors and ECHOES THE VALUE in the error message.) +# +# Verification compares sha256 of the round-tripped value against the file +# (trailing newline stripped, since $(...) strips it) — values are never printed. +set -u +source ~/tools/bws-env.sh >/dev/null 2>&1 + +PROJECT=d370cd10-3d67-4b34-b61a-b4dc00753f97 +DATE=$(date -u +%F) + +declare -A SECRETS=( + [nix-cache.upload-secret]="$HOME/.config/nix-cache/upload-secret" + [nix-cache.signing-key]="$HOME/.config/nix-cache/signing.sec" + [cachix.cachix-dhall]="$HOME/.config/cachix/cachix.dhall" + [github-cli.hosts-yml]="$HOME/.config/gh/hosts.yml" + [ssh.id-ed25519]="$HOME/.ssh/id_ed25519" +) +declare -A NOTES=( + [nix-cache.upload-secret]="Source: ~/.config/nix-cache/upload-secret. Backed up $DATE. Same value is set as Cloudflare Worker secret UPLOAD_SECRET (nix-cache worker)." + [nix-cache.signing-key]="Source: ~/.config/nix-cache/signing.sec (nix store signing private key). Backed up $DATE." + [cachix.cachix-dhall]="Source: ~/.config/cachix/cachix.dhall (contains Cachix auth token). Backed up $DATE." + [github-cli.hosts-yml]="Source: ~/.config/gh/hosts.yml (gh CLI OAuth tokens). Backed up $DATE." + [ssh.id-ed25519]="Source: ~/.ssh/id_ed25519 (SSH private key). Backed up $DATE." +) + +strip_nl() { perl -0777 -pe 's/\n\z//'; } +bw_value() { # $1 = secret id -> prints value on stdout, no trailing newline + bws secret get "$1" -o json 2>/dev/null \ + | jq -j 'if type=="array" then .[0].value else .value end' +} + +fail=0 +for key in "${!SECRETS[@]}"; do + file="${SECRETS[$key]}" + [ -f "$file" ] || { echo "SKIP $key: $file missing"; fail=1; continue; } + id=$(bws secret list 2>/dev/null | jq -r --arg k "$key" '.[] | select(.key==$k) | .id' | head -1) + want=$(strip_nl < "$file" | sha256sum | cut -d' ' -f1) + if [ -n "$id" ]; then + got=$(bw_value "$id" | sha256sum | cut -d' ' -f1) + if [ "$got" = "$want" ]; then + echo "OK $key (already correct)" + continue + else + echo "REWRITE $key (existing value wrong, id $id)" + bws secret delete "$id" -o none 2>/dev/null + fi + fi + # shellcheck disable=SC2046 + id=$(bws secret create --note "${NOTES[$key]}" -o json -- \ + "$key" "$(cat "$file")" "$PROJECT" 2>/dev/null | jq -r '.id') + if [ -z "$id" ] || [ "$id" = "null" ]; then + echo "FAIL $key: create error"; fail=1; continue + fi + got=$(bw_value "$id" | sha256sum | cut -d' ' -f1) + if [ "$got" = "$want" ]; then + echo "OK $key (created, verified)" + else + echo "FAIL $key (round-trip mismatch)"; fail=1 + fi +done +echo "---"; echo "fail=$fail" diff --git a/pkgs/agent-backup/load_from_output.py b/pkgs/agent-backup/load_from_output.py new file mode 100644 index 0000000000..97de44ed72 --- /dev/null +++ b/pkgs/agent-backup/load_from_output.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Feed a saved muse.db tool-output file into load_rows.py without the rows +passing through agent generation. + +Usage: load_from_output.py +The tool output is the JSON the runtime saved for an oversized muse.db +result; rows are extracted from result.rows (or rows). The spec file is a +load_rows.py spec WITHOUT "rows" (rows are injected from the output file). +Prints load_rows.py's result; exit code propagates. +""" +import json +import subprocess +import sys +import os + +LOADER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "load_rows.py") + + +def extract_rows(path): + with open(path) as f: + data = json.load(f) + if isinstance(data, dict): + for key in ("result", "output", "data"): + inner = data.get(key) + if isinstance(inner, dict) and "rows" in inner: + return inner["rows"] + if "rows" in data: + return data["rows"] + # the saved file may be the raw exec envelope: search one level down + for v in data.values(): + if isinstance(v, dict) and "rows" in v: + return v["rows"] + if isinstance(v, str): + try: + inner = json.loads(v) + except Exception: + continue + if isinstance(inner, dict) and "rows" in inner: + return inner["rows"] + if isinstance(inner, dict): + r = inner.get("result") + if isinstance(r, dict) and "rows" in r: + return r["rows"] + raise SystemExit(f"no rows found in {path}") + + +def main(): + out_file, spec_file = sys.argv[1], sys.argv[2] + rows = extract_rows(out_file) + with open(spec_file) as f: + spec = json.load(f) + spec["rows"] = rows + p = subprocess.run([sys.executable, LOADER], input=json.dumps(spec), + text=True) + sys.exit(p.returncode) + + +if __name__ == "__main__": + main() diff --git a/pkgs/agent-backup/load_rows.py b/pkgs/agent-backup/load_rows.py new file mode 100644 index 0000000000..30e335e09c --- /dev/null +++ b/pkgs/agent-backup/load_rows.py @@ -0,0 +1,169 @@ +#!/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. + +Spec (JSON on stdin) — unchanged from the PG loader: +{ + "table": "agent.mirror_scheduler_jobs", // landing table (spec + // name; physically lands in agent_mirror_* in Turso) + "conflict": ["job_id"], // PK columns + "jsonb_cols": ["payload"], // columns stored as JSON text + "hash_payload": true, // add payload_hash=md5 of the + // stored JSON text + exported_at + "history_table": "agent.mirror_history_scheduler_jobs" | null, + "mode": "update" | "nothing", // ON CONFLICT behavior (default "update") + "epoch_day": {"day_epoch": "day"}, // rename col, emit UTC date text + "epoch_hour": {"hour_epoch": "hour"}, // rename col, emit UTC timestamp text + "no_exported_at": true, // export_state only + "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). + +Shapes match the rows the 2026-11-06 Turso migration copy already holds: +dates as YYYY-MM-DD text, timestamps as ISO-8601 UTC text, JSON columns as +JSON text, booleans as 1/0. payload_hash is md5 of the JSON text stored +(the PG loader's history path hashed PG's canonical jsonb text instead; +key order and separators coincide for muse.db-built payloads, but the +first post-repoint run may still record a one-time history version-step +for rows whose texts differ — hashes are self-consistent from then on). + +Exit 0 on success (prints "loaded N rows into "), 1 on failure. +A failed call changes nothing else. Transport details (token by name, +pipeline, staging mode): see turso_client.py. +""" +import hashlib +import json +import sys +from datetime import datetime, timedelta, timezone + +sys.path.insert(0, __file__.rsplit("/", 1)[0]) +import turso_client + + +def iso_now(): + return datetime.now(timezone.utc).isoformat() + + +def epoch_text(v, mult): + if v is None or isinstance(v, str): + return v + base = datetime(1970, 1, 1, tzinfo=timezone.utc) + if mult == 86400: + return (base + timedelta(days=int(v))).strftime("%Y-%m-%d") + return (base + timedelta(hours=int(v))).isoformat() + + +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 = spec["table"] + table = turso_client.physical_name(table_spec) + if not rows: + print(f"loaded 0 rows into {table_spec} (empty page)") + return + conflict = spec.get("conflict") or [] + jsonb_cols = set(spec.get("jsonb_cols") or []) + hash_payload = bool(spec.get("hash_payload")) + mode = spec.get("mode", "update") + hist = spec.get("history_table") + if hist and not hash_payload: + raise SystemExit("history_table requires hash_payload") + hist_phys = turso_client.physical_name(hist) if hist else None + + 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 = [epoch_maps[c][0] if c in epoch_maps else c for c in rows[0].keys()] + src_for = {dst: src for src, (dst, _m) in epoch_maps.items()} + + now = iso_now() + prepared = [] + for r in rows: + vals = {} + for c in cols: + if c in src_for: + src = src_for[c] + vals[c] = epoch_text(r.get(src), epoch_maps[src][1]) + else: + v = r.get(c) + if c in jsonb_cols and v is not None: + v = v if isinstance(v, str) else json.dumps(v) + vals[c] = v + prepared.append(vals) + + extra = [] + if hash_payload: + extra = ["payload_hash", "exported_at"] + elif spec.get("no_exported_at"): + extra = [] + elif "exported_at" not in cols: + extra = ["exported_at"] + for vals in prepared: + if hash_payload: + p = vals.get("payload") + text = p if isinstance(p, str) else json.dumps(p) + vals["payload_hash"] = hashlib.md5(text.encode()).hexdigest() + if extra and "exported_at" in extra: + vals["exported_at"] = now + all_cols = cols + extra + + stmts = [] + stmts += turso_client.ensure_tables_sql([table] + ([hist_phys] if hist_phys else [])) + collist = ", ".join(all_cols) + ph = ", ".join("?" for _ in all_cols) + if hist_phys: + # stage the page in a temp table for the history archive step + # (SQLite upserts cannot source from SELECT, so the upsert + # itself below is VALUES-based; the archive is a plain + # INSERT..SELECT and can read the staged page) + stmts.append((f"CREATE TEMP TABLE rde_incoming ({collist})", [])) + stmts.append(("DELETE FROM rde_incoming", [])) + for vals in prepared: + stmts.append((f"INSERT INTO rde_incoming ({collist}) VALUES ({ph})", + [vals.get(c) for c in all_cols])) + on = " AND ".join(f"m.{k} = i.{k}" for k in conflict) + stmts.append(( + f"INSERT INTO {hist_phys} ({', '.join(conflict)}, payload, payload_hash, valid_from, valid_to) " + f"SELECT {', '.join('m.' + k for k in conflict)}, m.payload, m.payload_hash, m.exported_at, ? " + f"FROM {table} m JOIN rde_incoming i ON {on} " + f"WHERE m.payload_hash <> i.payload_hash", [now])) + values_sql = ", ".join(f"({ph})" for _ in prepared) + values_args = [] + for vals in prepared: + values_args += [vals.get(c) for c in all_cols] + insert = f"INSERT INTO {table} ({collist}) VALUES {values_sql}" + if hist_phys: + set_cols = [c for c in all_cols if c not in conflict] + sets = ", ".join(f"{c} = excluded.{c}" for c in set_cols) + insert += (f" ON CONFLICT ({', '.join(conflict)}) DO UPDATE SET {sets}" + f" WHERE {table}.payload_hash <> excluded.payload_hash") + elif mode == "nothing": + insert += " ON CONFLICT DO NOTHING" + else: + set_cols = [c for c in all_cols if c not in conflict] + if set_cols: + sets = ", ".join(f"{c} = excluded.{c}" for c in set_cols) + insert += f" ON CONFLICT ({', '.join(conflict)}) DO UPDATE SET {sets}" + else: + insert += " ON CONFLICT DO NOTHING" + stmts.append((insert, values_args)) + if hist_phys: + stmts.append(("DROP TABLE IF EXISTS rde_incoming", [])) + + turso_client.client().execute(stmts) + print(f"loaded {len(prepared)} rows into {table_spec}") + + +if __name__ == "__main__": + main() diff --git a/pkgs/agent-backup/load_rows_pg.py b/pkgs/agent-backup/load_rows_pg.py new file mode 100644 index 0000000000..3cfa5f35b9 --- /dev/null +++ b/pkgs/agent-backup/load_rows_pg.py @@ -0,0 +1,220 @@ +#!/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/merge_s5.py b/pkgs/agent-backup/merge_s5.py new file mode 100644 index 0000000000..2c1a50c7b6 --- /dev/null +++ b/pkgs/agent-backup/merge_s5.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Merge S5 runs+sessions saved-output pages and load mirror_concurrency_hourly. +Usage: merge_s5.py runs= [runs=...] sessions= [...] +Missing side for an hour = 0. Loads via load_rows.py in 200-row chunks.""" +import json, subprocess, sys, os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from load_from_output import extract_rows + +runs, sessions = {}, {} +for arg in sys.argv[1:]: + kind, path = arg.split("=", 1) + target = runs if kind == "runs" else sessions + col = "max_concurrent_runs" if kind == "runs" else "max_concurrent_sessions" + for r in extract_rows(path): + target[int(r["hour_epoch"])] = int(r[col]) +hours = sorted(set(runs) | set(sessions)) +rows = [{"hour_epoch": h, "max_concurrent_runs": runs.get(h, 0), + "max_concurrent_sessions": sessions.get(h, 0)} for h in hours] +spec = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "spec_s5.json"))) +total = 0 +for i in range(0, len(rows), 200): + spec["rows"] = rows[i:i + 200] + p = subprocess.run([sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "load_rows.py")], + input=json.dumps(spec), text=True, capture_output=True) + if p.returncode != 0: + print(p.stdout, p.stderr); sys.exit(1) + total += len(spec["rows"]) +print(f"merged+loaded {total} concurrency rows over {len(hours)} hours") diff --git a/pkgs/agent-backup/page_load.py b/pkgs/agent-backup/page_load.py new file mode 100644 index 0000000000..60e998a62d --- /dev/null +++ b/pkgs/agent-backup/page_load.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Load one saved muse.db page via load_from_output.py and print the cursor +for the next page: {"count": n, "last": {key: value, ...}}. +Usage: page_load.py +""" +import json +import subprocess +import sys +import os + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +from load_from_output import extract_rows + + +def main(): + out_file, spec_file, keys = sys.argv[1], sys.argv[2], sys.argv[3].split(",") + rows = extract_rows(out_file) + p = subprocess.run([sys.executable, os.path.join(HERE, "load_from_output.py"), + out_file, spec_file]) + if p.returncode != 0: + sys.exit(p.returncode) + last = {k: rows[-1].get(k) for k in keys} if rows else {} + print(json.dumps({"count": len(rows), "last": last})) + + +if __name__ == "__main__": + main() diff --git a/pkgs/agent-backup/progress/load_and_log.py b/pkgs/agent-backup/progress/load_and_log.py new file mode 100644 index 0000000000..8262f11fdf --- /dev/null +++ b/pkgs/agent-backup/progress/load_and_log.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import json, shutil, subprocess, sys, os +HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +src, page = sys.argv[1], sys.argv[2] +size = sys.argv[3] if len(sys.argv) > 3 else "100" +keep = os.path.join(HERE, "progress", "cur_page.json") +shutil.copyfile(src, keep) +p = subprocess.run([sys.executable, os.path.join(HERE, "page_load.py"), keep, "spec_m3.json", "updated_at,agent_id"], cwd=HERE, capture_output=True, text=True) +sys.stdout.write(p.stdout); sys.stderr.write(p.stderr) +if p.returncode != 0: + sys.exit(p.returncode) +d = json.loads(p.stdout.strip().splitlines()[-1]) +last = d["last"] +line = f"page {page} rows={d['count']} cursor=({last.get('updated_at')},{last.get('agent_id')}) size={size}\n" +with open(os.path.join(HERE, "progress", "m3.log"), "a") as f: + f.write(line) +print("logged:", line.strip()) diff --git a/pkgs/agent-backup/prune_m1.sql b/pkgs/agent-backup/prune_m1.sql new file mode 100644 index 0000000000..2f1954b987 --- /dev/null +++ b/pkgs/agent-backup/prune_m1.sql @@ -0,0 +1,4 @@ +INSERT INTO agent.mirror_history_scheduler_jobs (job_id, payload, payload_hash, valid_from, valid_to) +SELECT job_id, payload, payload_hash, exported_at, now() FROM agent.mirror_scheduler_jobs WHERE job_id NOT IN ('account-campaign-nudge', 'action-outbox-processor', 'agent-queue-worker', 'agentfs-llmwiki-fri-am', 'agentfs-llmwiki-sat-pm', 'agentfs-llmwiki-thu-pm', 'agentic-feature-tour', 'airthings-alerts', 'amazon-business-10pct-reminder', 'archer-slack-review', 'aster-explorer-recheck', 'atlas-local-backup-daily', 'avatar-backup-daily', 'boot-init-todo-check', 'chatgpt-export-watch', 'chatgpt-student-cancel-cleanup', 'chatgpt-student-cancel-final-week', 'chatgpt-student-cancel-last-month', 'check-laptop-oc-385-386-ci-fix', 'check-laptop-oc-385-386-finish', 'check-opencode-385-386-adaptation', 'coding-plan-watch-daily', 'cold-store-eviction-scan', 'cold-store-nightly-backup', 'cold-store-restore-drill', 'commandcode-fix-watch', 'crunchyroll-response-watch', 'daily-gmail-summary', 'daily-token-usage-checkin', 'dashboard-backup-daily', 'deterministic-doctor', 'dfi-filing-status-watch', 'dns-spending-review-reminder', 'duns-arrival-check', 'feed-pulse-00', 'feed-pulse-01', 'feed-pulse-02', 'feed-pulse-03', 'feed-pulse-04', 'feed-pulse-05', 'feed-pulse-06', 'feed-pulse-07', 'feed-pulse-08', 'feed-pulse-09', 'feed-pulse-10', 'feed-pulse-11', 'feed-pulse-12', 'feed-pulse-13', 'feed-pulse-14', 'feed-pulse-15', 'feed-pulse-16', 'feed-pulse-17', 'feed-pulse-18', 'feed-pulse-19', 'feed-pulse-20', 'feed-pulse-21', 'feed-pulse-22', 'feed-pulse-23', 'fleet-watchdog', 'git-hygiene-sweep', 'github-project-token-renewal', 'globalping-watch', 'go-plan-expiry-watch', 'hardware-roundup-weekly', 'hatch-untracked-review', 'heartbeat', 'home-projects-weekly', 'id-horizons-resurface', 'id-train-watch', 'id-wave2-watch', 'id-wave3-watch', 'issue-sweep-devtoday-code', 'issue-sweep-devtoday-openchamber', 'issue-sweep-devtoday-opencode', 'issue-sweep-dezren-nix', 'issue-sweep-rotating', 'jules-daily-top-issue', 'jules-daily-top-issue-code', 'jules-review', 'labcluster-fri-am', 'labcluster-sat-pm', 'labcluster-thu-pm', 'late-night-shift-priorities', 'llc-filing-stripe-link-morning-retry', 'marketplace-deal-hunt-sweep', 'memory-curation-review', 'meta-burn-switchback', 'metapay-charge-watch', 'morning-day-start-readout', 'multi-provider-build-watch', 'multi-provider-build-watch-3', 'multi-provider-build-watch-4', 'multi-provider-build-watch-5', 'multi-provider-code-pr-watch', 'multi-provider-lock-watch', 'multi-provider-lock2-watch', 'multi-provider-oc-fix-watch', 'multi-provider-oc-test-watch', 'multi-provider-oc-test-watch-2', 'multi-provider-pr-watch', 'multi-provider-pr-watch-2', 'multi-provider-session-watch', 'multi-provider-ssh-recovery-watch', 'new-issue-creator', 'new-issue-creator-b', 'new-issue-creator-code-a', 'new-issue-creator-code-b', 'new-issue-creator-nix', 'new-issue-creator-openchamber', 'new-issue-creator-opencode', 'nix-mcpx-15min-check', 'nixpkgs-update-amd', 'oci-followup-3-cpcoe-29381', 'oci-followup-4-cpcoe-29381', 'oci-followup-5-cpcoe-29381', 'oci-followup-6-cpcoe-29381', 'oci-followup-cpcoe-29381', 'oci-followup-monday-cpcoe-29381', 'oci-followup-retry-cpcoe-29381', 'offpeak-gate-verify-2026-10-28', 'openchamber-babysitter', 'openchamber-dispatcher', 'orchestration-pass', 'outside-schedulers-cleanup', 'pet-care-weekly-watch', 'plaid-nudge-am', 'plaid-nudge-pm', 'plaid-nudge-start', 'pool-composition-review', 'pool-intelligence', 'pool-meta-reviewer', 'pool-quota-steward', 'porkbun-account-nudge', 'pr-diff-review', 'pr-diff-review-b', 'profile-image', 'program-tending', 'queue-pilot-interim-check', 'repo-design-architect', 'repo-design-architect-code', 'repo-fleet-monitor', 'repo-queue-worker-shift', 'repo-queue-worker-shift-b', 'repo-queue-worker-shift-c', 'repo-queue-worker-shift-d', 'repo-queue-worker-shift-nix', 'repo-queue-worker-shift-nix-b', 'repo-queue-worker-shift-openchamber', 'repo-queue-worker-shift-openchamber-b', 'repo-queue-worker-shift-opencode', 'repo-queue-worker-shift-opencode-b', 'roadmap-sync-grist-md', 'sandbox-boot-init', 'sandbox-state-backup-daily', 'stale-pr-warden', 'stewardship-cycle', 'supabase-muse-dev-backup', 'supabase-turso-coord-mirror', 'turso-cloudflare-idea-engine', 'unusual-charge-watch', 'verx-q3-valuation', 'weekly-token-usage-review'); +DELETE FROM agent.mirror_scheduler_jobs WHERE job_id NOT IN ('account-campaign-nudge', 'action-outbox-processor', 'agent-queue-worker', 'agentfs-llmwiki-fri-am', 'agentfs-llmwiki-sat-pm', 'agentfs-llmwiki-thu-pm', 'agentic-feature-tour', 'airthings-alerts', 'amazon-business-10pct-reminder', 'archer-slack-review', 'aster-explorer-recheck', 'atlas-local-backup-daily', 'avatar-backup-daily', 'boot-init-todo-check', 'chatgpt-export-watch', 'chatgpt-student-cancel-cleanup', 'chatgpt-student-cancel-final-week', 'chatgpt-student-cancel-last-month', 'check-laptop-oc-385-386-ci-fix', 'check-laptop-oc-385-386-finish', 'check-opencode-385-386-adaptation', 'coding-plan-watch-daily', 'cold-store-eviction-scan', 'cold-store-nightly-backup', 'cold-store-restore-drill', 'commandcode-fix-watch', 'crunchyroll-response-watch', 'daily-gmail-summary', 'daily-token-usage-checkin', 'dashboard-backup-daily', 'deterministic-doctor', 'dfi-filing-status-watch', 'dns-spending-review-reminder', 'duns-arrival-check', 'feed-pulse-00', 'feed-pulse-01', 'feed-pulse-02', 'feed-pulse-03', 'feed-pulse-04', 'feed-pulse-05', 'feed-pulse-06', 'feed-pulse-07', 'feed-pulse-08', 'feed-pulse-09', 'feed-pulse-10', 'feed-pulse-11', 'feed-pulse-12', 'feed-pulse-13', 'feed-pulse-14', 'feed-pulse-15', 'feed-pulse-16', 'feed-pulse-17', 'feed-pulse-18', 'feed-pulse-19', 'feed-pulse-20', 'feed-pulse-21', 'feed-pulse-22', 'feed-pulse-23', 'fleet-watchdog', 'git-hygiene-sweep', 'github-project-token-renewal', 'globalping-watch', 'go-plan-expiry-watch', 'hardware-roundup-weekly', 'hatch-untracked-review', 'heartbeat', 'home-projects-weekly', 'id-horizons-resurface', 'id-train-watch', 'id-wave2-watch', 'id-wave3-watch', 'issue-sweep-devtoday-code', 'issue-sweep-devtoday-openchamber', 'issue-sweep-devtoday-opencode', 'issue-sweep-dezren-nix', 'issue-sweep-rotating', 'jules-daily-top-issue', 'jules-daily-top-issue-code', 'jules-review', 'labcluster-fri-am', 'labcluster-sat-pm', 'labcluster-thu-pm', 'late-night-shift-priorities', 'llc-filing-stripe-link-morning-retry', 'marketplace-deal-hunt-sweep', 'memory-curation-review', 'meta-burn-switchback', 'metapay-charge-watch', 'morning-day-start-readout', 'multi-provider-build-watch', 'multi-provider-build-watch-3', 'multi-provider-build-watch-4', 'multi-provider-build-watch-5', 'multi-provider-code-pr-watch', 'multi-provider-lock-watch', 'multi-provider-lock2-watch', 'multi-provider-oc-fix-watch', 'multi-provider-oc-test-watch', 'multi-provider-oc-test-watch-2', 'multi-provider-pr-watch', 'multi-provider-pr-watch-2', 'multi-provider-session-watch', 'multi-provider-ssh-recovery-watch', 'new-issue-creator', 'new-issue-creator-b', 'new-issue-creator-code-a', 'new-issue-creator-code-b', 'new-issue-creator-nix', 'new-issue-creator-openchamber', 'new-issue-creator-opencode', 'nix-mcpx-15min-check', 'nixpkgs-update-amd', 'oci-followup-3-cpcoe-29381', 'oci-followup-4-cpcoe-29381', 'oci-followup-5-cpcoe-29381', 'oci-followup-6-cpcoe-29381', 'oci-followup-cpcoe-29381', 'oci-followup-monday-cpcoe-29381', 'oci-followup-retry-cpcoe-29381', 'offpeak-gate-verify-2026-10-28', 'openchamber-babysitter', 'openchamber-dispatcher', 'orchestration-pass', 'outside-schedulers-cleanup', 'pet-care-weekly-watch', 'plaid-nudge-am', 'plaid-nudge-pm', 'plaid-nudge-start', 'pool-composition-review', 'pool-intelligence', 'pool-meta-reviewer', 'pool-quota-steward', 'porkbun-account-nudge', 'pr-diff-review', 'pr-diff-review-b', 'profile-image', 'program-tending', 'queue-pilot-interim-check', 'repo-design-architect', 'repo-design-architect-code', 'repo-fleet-monitor', 'repo-queue-worker-shift', 'repo-queue-worker-shift-b', 'repo-queue-worker-shift-c', 'repo-queue-worker-shift-d', 'repo-queue-worker-shift-nix', 'repo-queue-worker-shift-nix-b', 'repo-queue-worker-shift-openchamber', 'repo-queue-worker-shift-openchamber-b', 'repo-queue-worker-shift-opencode', 'repo-queue-worker-shift-opencode-b', 'roadmap-sync-grist-md', 'sandbox-boot-init', 'sandbox-state-backup-daily', 'stale-pr-warden', 'stewardship-cycle', 'supabase-muse-dev-backup', 'supabase-turso-coord-mirror', 'turso-cloudflare-idea-engine', 'unusual-charge-watch', 'verx-q3-valuation', 'weekly-token-usage-review'); +SELECT (SELECT count(*) FROM agent.mirror_scheduler_jobs) AS mirror_jobs, (SELECT count(*) FROM agent.mirror_history_scheduler_jobs) AS history_jobs; diff --git a/pkgs/agent-backup/prune_m4.sql b/pkgs/agent-backup/prune_m4.sql new file mode 100644 index 0000000000..5dd1e94238 --- /dev/null +++ b/pkgs/agent-backup/prune_m4.sql @@ -0,0 +1,6 @@ +INSERT INTO agent.mirror_history_goals_goals (goal_id, payload, payload_hash, valid_from, valid_to) +SELECT goal_id, payload, payload_hash, exported_at, now() FROM agent.mirror_goals_goals WHERE goal_id NOT IN ('goal_007d149459cc', 'goal_1a2cd00bd7d2', 'goal_31893eee8dfc', 'goal_32db44dec735', 'goal_35a11f521fc6', 'goal_3bb0f282c6a8', 'goal_3ee9c125444e', 'goal_423efbe1c4ec', 'goal_469c8af99c27', 'goal_49a7f35a16de', 'goal_4bd599c9ab26', 'goal_4ff7896f6699', 'goal_50580cc2b543', 'goal_5470d7fe3d17', 'goal_55d3136785c6', 'goal_57ce3e73ff19', 'goal_5ef002df045e', 'goal_63cc1f5f3fe1', 'goal_653ffcb56124', 'goal_6b0e383b212d', 'goal_6cd35969c6af', 'goal_6f3a55c433a2', 'goal_6f48d745f802', 'goal_796c3ad7aad2', 'goal_852587d25700', 'goal_86b7469e123e', 'goal_8c75ed164542', 'goal_8d41e3184cb1', 'goal_926c48c007ce', 'goal_943002484d08', 'goal_a243772844c3', 'goal_a2d5596827e1', 'goal_a496fd4beeb5', 'goal_b647ff5c92f5', 'goal_ba17a5777c21', 'goal_c3150d672042', 'goal_c64976ab9c0d', 'goal_d7ac1b4a49da', 'goal_dfa91a7c232a', 'goal_e0cf263d64e3', 'goal_e2e8b09c5af5', 'goal_e32f74415598', 'goal_e877a932b054', 'goal_e9cc628bc6dd', 'goal_efe8ee9a0570', 'goal_f09e57b77fe8', 'goal_f4d050ec82f4', 'goal_fbdde57a43cd', 'goal_fe27e03b921a'); +DELETE FROM agent.mirror_goals_goals WHERE goal_id NOT IN ('goal_007d149459cc', 'goal_1a2cd00bd7d2', 'goal_31893eee8dfc', 'goal_32db44dec735', 'goal_35a11f521fc6', 'goal_3bb0f282c6a8', 'goal_3ee9c125444e', 'goal_423efbe1c4ec', 'goal_469c8af99c27', 'goal_49a7f35a16de', 'goal_4bd599c9ab26', 'goal_4ff7896f6699', 'goal_50580cc2b543', 'goal_5470d7fe3d17', 'goal_55d3136785c6', 'goal_57ce3e73ff19', 'goal_5ef002df045e', 'goal_63cc1f5f3fe1', 'goal_653ffcb56124', 'goal_6b0e383b212d', 'goal_6cd35969c6af', 'goal_6f3a55c433a2', 'goal_6f48d745f802', 'goal_796c3ad7aad2', 'goal_852587d25700', 'goal_86b7469e123e', 'goal_8c75ed164542', 'goal_8d41e3184cb1', 'goal_926c48c007ce', 'goal_943002484d08', 'goal_a243772844c3', 'goal_a2d5596827e1', 'goal_a496fd4beeb5', 'goal_b647ff5c92f5', 'goal_ba17a5777c21', 'goal_c3150d672042', 'goal_c64976ab9c0d', 'goal_d7ac1b4a49da', 'goal_dfa91a7c232a', 'goal_e0cf263d64e3', 'goal_e2e8b09c5af5', 'goal_e32f74415598', 'goal_e877a932b054', 'goal_e9cc628bc6dd', 'goal_efe8ee9a0570', 'goal_f09e57b77fe8', 'goal_f4d050ec82f4', 'goal_fbdde57a43cd', 'goal_fe27e03b921a'); +SELECT (SELECT count(*) FROM agent.mirror_goals_goals) AS goals, (SELECT count(*) FROM agent.mirror_history_goals_goals) AS goals_hist, +(SELECT count(*) FROM agent.mirror_scheduler_jobs) AS jobs, (SELECT count(*) FROM agent.mirror_goals_updates) AS goal_updates_so_far, +(SELECT count(*) FROM agent.mirror_export_state) AS state_rows; diff --git a/pkgs/agent-backup/run_sql.py b/pkgs/agent-backup/run_sql.py new file mode 100755 index 0000000000..2eb4cc917e --- /dev/null +++ b/pkgs/agent-backup/run_sql.py @@ -0,0 +1,71 @@ +#!/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). +Usage: run_sql.py + +The job's SQL files are written in the old PG dialect; this runner +translates exactly the constructs they use: + agent.mirror_* / agent.mirror_history_* -> agent_mirror_* names + now() -> current UTC ISO timestamp + DATE 'YYYY-MM-DD' -> 'YYYY-MM-DD' +Statements run one by one over the libsql pipeline (see +turso_client.py); SELECT results print as JSON lines so callers can +read reconciliation counts from stdout. +""" +import json +import re +import sys +from datetime import datetime, timezone + +sys.path.insert(0, __file__.rsplit("/", 1)[0]) +import turso_client + + +def translate(sql): + now = datetime.now(timezone.utc).isoformat() + sql = re.sub(r"\bagent\.(mirror(?:_history)?_[a-z0-9_]+)", r"agent_\1", sql) + sql = re.sub(r"\bnow\(\)", f"'{now}'", sql) + sql = re.sub(r"(?i)\bDATE\s+('[^']+')", r"\1", sql) + return sql + + +def split_statements(sql): + out, buf = [], "" + for line in sql.splitlines(): + if line.strip().startswith("--"): + continue + buf += line + "\n" + if line.rstrip().endswith(";"): + stmt = buf.strip().rstrip(";").strip() + if stmt: + out.append(stmt) + buf = "" + tail = buf.strip() + if tail: + out.append(tail) + return out + + +def main(): + if len(sys.argv) < 2: + raise SystemExit(__doc__) + with open(sys.argv[1]) as f: + sql = translate(f.read()) + stmts = split_statements(sql) + # make sure any landing tables the SQL touches exist (history tables + # and shells were not part of the migration copy) + names = sorted(set(re.findall(r"agent_mirror_[a-z0-9_]+", sql))) + client = turso_client.client() + pre = turso_client.ensure_tables_sql(names) + if pre: + client.execute(pre) + for stmt in stmts: + results = client.execute([(stmt, [])]) + for res in results: + for row in res.get("rows", []): + print(json.dumps(row, default=str)) + print(f"run_sql: {len(stmts)} statement(s) ok") + + +if __name__ == "__main__": + main() diff --git a/pkgs/agent-backup/run_sql_pg.py b/pkgs/agent-backup/run_sql_pg.py new file mode 100755 index 0000000000..bc24d34bfe --- /dev/null +++ b/pkgs/agent-backup/run_sql_pg.py @@ -0,0 +1,40 @@ +#!/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 new file mode 100644 index 0000000000..5adde0bf58 --- /dev/null +++ b/pkgs/agent-backup/schema.sql @@ -0,0 +1,152 @@ +-- 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 new file mode 100644 index 0000000000..d30673f687 --- /dev/null +++ b/pkgs/agent-backup/schema2.sql @@ -0,0 +1,140 @@ +-- 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/set_state.py b/pkgs/agent-backup/set_state.py new file mode 100644 index 0000000000..0982eb2c4b --- /dev/null +++ b/pkgs/agent-backup/set_state.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Record a unit's outcome in state.json AND agent.mirror_export_state. +Usage: set_state.py [error_text] +""" +import json +import os +import subprocess +import sys +from datetime import datetime, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +STATE = os.path.join(HERE, "state.json") +LOADER = os.path.join(HERE, "load_rows.py") + + +def main(): + table, watermark, count, status = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] + error = sys.argv[5] if len(sys.argv) > 5 else None + now = datetime.now(timezone.utc).isoformat() + if os.path.exists(STATE): + with open(STATE) as f: + state = json.load(f) + else: + state = {"tables": {}} + state["tables"][table] = {"watermark": watermark, "last_run_at": now, + "last_row_count": count, "last_status": status, + "last_error": error} + with open(STATE, "w") as f: + json.dump(state, f, indent=1) + spec = {"table": "agent.mirror_export_state", "conflict": ["table_name"], + "mode": "update", "no_exported_at": True, + "rows": [{"table_name": table, "watermark": watermark, + "last_run_at": now, "last_row_count": count, + "last_status": status, "last_error": error}]} + p = subprocess.run([sys.executable, LOADER], input=json.dumps(spec), text=True) + sys.exit(p.returncode) + + +if __name__ == "__main__": + main() diff --git a/pkgs/agent-backup/spec_m1.json b/pkgs/agent-backup/spec_m1.json new file mode 100644 index 0000000000..9e7a45e159 --- /dev/null +++ b/pkgs/agent-backup/spec_m1.json @@ -0,0 +1,3 @@ +{"table": "agent.mirror_scheduler_jobs", "conflict": ["job_id"], + "jsonb_cols": ["payload"], "hash_payload": true, + "history_table": "agent.mirror_history_scheduler_jobs", "mode": "update"} diff --git a/pkgs/agent-backup/spec_m2.json b/pkgs/agent-backup/spec_m2.json new file mode 100644 index 0000000000..b05e9d35cc --- /dev/null +++ b/pkgs/agent-backup/spec_m2.json @@ -0,0 +1,2 @@ +{"table": "agent.mirror_scheduler_job_runs", "conflict": ["run_id"], + "jsonb_cols": ["payload"], "mode": "update"} diff --git a/pkgs/agent-backup/spec_m3.json b/pkgs/agent-backup/spec_m3.json new file mode 100644 index 0000000000..850fe456b0 --- /dev/null +++ b/pkgs/agent-backup/spec_m3.json @@ -0,0 +1,3 @@ +{"table": "agent.mirror_agent_agents", "conflict": ["agent_id"], + "jsonb_cols": ["payload"], "hash_payload": true, + "history_table": "agent.mirror_history_agent_agents", "mode": "update"} diff --git a/pkgs/agent-backup/spec_m4.json b/pkgs/agent-backup/spec_m4.json new file mode 100644 index 0000000000..c6268dcfc0 --- /dev/null +++ b/pkgs/agent-backup/spec_m4.json @@ -0,0 +1,3 @@ +{"table": "agent.mirror_goals_goals", "conflict": ["goal_id"], + "jsonb_cols": ["payload"], "hash_payload": true, + "history_table": "agent.mirror_history_goals_goals", "mode": "update"} diff --git a/pkgs/agent-backup/spec_m5.json b/pkgs/agent-backup/spec_m5.json new file mode 100644 index 0000000000..c32312faac --- /dev/null +++ b/pkgs/agent-backup/spec_m5.json @@ -0,0 +1,3 @@ +{"table": "agent.mirror_goals_updates", "conflict": ["update_id"], + "jsonb_cols": ["payload"], "hash_payload": true, + "history_table": "agent.mirror_history_goals_updates", "mode": "update"} diff --git a/pkgs/agent-backup/spec_m8.json b/pkgs/agent-backup/spec_m8.json new file mode 100644 index 0000000000..df73da865c --- /dev/null +++ b/pkgs/agent-backup/spec_m8.json @@ -0,0 +1,2 @@ +{"table": "agent.mirror_sessions", "conflict": ["session_id"], + "jsonb_cols": ["payload"], "mode": "update"} diff --git a/pkgs/agent-backup/spec_r1.json b/pkgs/agent-backup/spec_r1.json new file mode 100644 index 0000000000..0e794379dc --- /dev/null +++ b/pkgs/agent-backup/spec_r1.json @@ -0,0 +1 @@ +{"table": "agent.mirror_token_usage_daily", "conflict": ["day", "dimension", "key"], "epoch_day": {"day_epoch": "day"}} diff --git a/pkgs/agent-backup/spec_r2.json b/pkgs/agent-backup/spec_r2.json new file mode 100644 index 0000000000..49b241b884 --- /dev/null +++ b/pkgs/agent-backup/spec_r2.json @@ -0,0 +1 @@ +{"table": "agent.mirror_token_usage_hourly", "conflict": ["hour", "dimension", "key"], "epoch_hour": {"hour_epoch": "hour"}} diff --git a/pkgs/agent-backup/spec_s5.json b/pkgs/agent-backup/spec_s5.json new file mode 100644 index 0000000000..2ab4aef36f --- /dev/null +++ b/pkgs/agent-backup/spec_s5.json @@ -0,0 +1 @@ +{"table": "agent.mirror_concurrency_hourly", "conflict": ["hour"], "epoch_hour": {"hour_epoch": "hour"}} diff --git a/pkgs/agent-backup/turso_client.py b/pkgs/agent-backup/turso_client.py new file mode 100644 index 0000000000..2f2f0a1389 --- /dev/null +++ b/pkgs/agent-backup/turso_client.py @@ -0,0 +1,400 @@ +#!/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). + +Target access: +- HTTP pipeline (libsql /v2/pipeline) at the fleet-mirror host. The + sandbox reaches it through the AMBIENT proxy environment (urllib's + default opener honors it); do not override proxy settings. +- Token by NAME only: `turso.fleet-mirror-rw-token`, resolved via + `fleet secrets get` (laptop broker first). If the DB rejects that + value ("auth role not found" — the broker served a stale cached + value after the BWS secret was rotated 2026-11-06; defect recorded + on #5691), fall back to a direct BWS read of the same secret and + retry once. The token value is never printed or written to a file. + +Staging mode: RDE_TURSO_URL=file:/path/to.db runs the identical SQL +generation path against a local SQLite file, no token involved. +RDE_PRINT_SQL=1 prints the generated statements instead of executing. +""" +import base64 +import json +import os +import sqlite3 +import subprocess +import sys +import urllib.error +import urllib.request + +DB_HTTP_URL = "https://fleet-mirror-dezren39.aws-us-east-1.turso.io/v2/pipeline" +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 +# 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 = { + "agent_mirror_export_state": """CREATE TABLE IF NOT EXISTS agent_mirror_export_state ( + table_name TEXT PRIMARY KEY, watermark TEXT, last_run_at TEXT, + last_row_count INTEGER, last_status TEXT, last_error TEXT)""", + "agent_mirror_scheduler_jobs": """CREATE TABLE IF NOT EXISTS agent_mirror_scheduler_jobs ( + job_id TEXT PRIMARY KEY, + is_heartbeat INTEGER, source_path TEXT, schedule_kind TEXT, enabled INTEGER, + schedule_expr TEXT, timezone TEXT, last_status TEXT, + consecutive_failures INTEGER, next_run_at_utc INTEGER, + last_run_at_utc INTEGER, last_success_at_utc INTEGER, + payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + exported_at TEXT NOT NULL)""", + "agent_mirror_history_scheduler_jobs": """CREATE TABLE IF NOT EXISTS agent_mirror_history_scheduler_jobs ( + job_id TEXT NOT NULL, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + valid_from TEXT, valid_to TEXT NOT NULL)""", + "agent_mirror_scheduler_job_runs": """CREATE TABLE IF NOT EXISTS agent_mirror_scheduler_job_runs ( + run_id TEXT PRIMARY KEY, + job_id TEXT, job_definition_id INTEGER, + scheduled_for_utc INTEGER, started_at_utc INTEGER, finished_at_utc INTEGER, + status TEXT, attempt INTEGER, worker_phase TEXT, + worker_agent_id TEXT, worker_history_agent_id TEXT, + payload TEXT NOT NULL, exported_at TEXT NOT NULL)""", + "agent_mirror_agent_agents": """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 INTEGER, agent_type TEXT, + created_at INTEGER, updated_at INTEGER, + scheduler_cron_job_id TEXT, scheduler_cron_worker_phase TEXT, + payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + exported_at TEXT NOT NULL)""", + "agent_mirror_history_agent_agents": """CREATE TABLE IF NOT EXISTS agent_mirror_history_agent_agents ( + agent_id TEXT NOT NULL, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + valid_from TEXT, valid_to TEXT NOT NULL)""", + "agent_mirror_goals_goals": """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 TEXT NOT NULL, payload_hash TEXT NOT NULL, + exported_at TEXT NOT NULL)""", + "agent_mirror_history_goals_goals": """CREATE TABLE IF NOT EXISTS agent_mirror_history_goals_goals ( + goal_id TEXT NOT NULL, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + valid_from TEXT, valid_to TEXT NOT NULL)""", + "agent_mirror_goals_updates": """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 TEXT NOT NULL, payload_hash TEXT NOT NULL, + exported_at TEXT NOT NULL)""", + "agent_mirror_history_goals_updates": """CREATE TABLE IF NOT EXISTS agent_mirror_history_goals_updates ( + update_id TEXT NOT NULL, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + valid_from TEXT, valid_to TEXT NOT NULL)""", + "agent_mirror_scheduler_job_definitions": """CREATE TABLE IF NOT EXISTS agent_mirror_scheduler_job_definitions ( + job_definition_id INTEGER PRIMARY KEY, + job_id TEXT, version INTEGER, prompt_template_id INTEGER, + created_at TEXT, retired_at TEXT, + task_text_bytes INTEGER, task_text_md5 TEXT, + payload TEXT NOT NULL, exported_at TEXT NOT NULL)""", + "agent_mirror_token_usage_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_token_usage_daily ( + day TEXT NOT NULL, dimension TEXT NOT NULL, key TEXT NOT NULL, + input_tokens INTEGER, output_tokens INTEGER, messages INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, dimension, key))""", + "agent_mirror_token_usage_hourly": """CREATE TABLE IF NOT EXISTS agent_mirror_token_usage_hourly ( + hour TEXT NOT NULL, dimension TEXT NOT NULL, key TEXT NOT NULL, + input_tokens INTEGER, output_tokens INTEGER, messages INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (hour, dimension, key))""", + "agent_mirror_session_activity_hourly": """CREATE TABLE IF NOT EXISTS agent_mirror_session_activity_hourly ( + hour TEXT PRIMARY KEY, + active_sessions INTEGER, new_sessions INTEGER, messages INTEGER, + input_tokens INTEGER, output_tokens INTEGER, + exported_at TEXT NOT NULL)""", + "agent_mirror_session_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_session_stats_daily ( + day TEXT NOT NULL, grain TEXT NOT NULL, key TEXT NOT NULL, + sessions_active INTEGER, sessions_started INTEGER, + msgs_min INTEGER, msgs_max INTEGER, msgs_avg REAL, + msgs_p50 INTEGER, msgs_p90 INTEGER, msgs_p95 INTEGER, msgs_p99 INTEGER, + toks_min INTEGER, toks_max INTEGER, toks_avg REAL, + toks_p50 INTEGER, toks_p90 INTEGER, toks_p95 INTEGER, toks_p99 INTEGER, + dur_min_s INTEGER, dur_max_s INTEGER, dur_avg_s REAL, + dur_p50_s INTEGER, dur_p90_s INTEGER, dur_p95_s INTEGER, dur_p99_s INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, grain, key))""", + "agent_mirror_sessions": """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 INTEGER, agent_count INTEGER, + created_at_epoch INTEGER, updated_at_epoch INTEGER, + message_count INTEGER, input_tokens INTEGER, output_tokens INTEGER, + payload TEXT NOT NULL, exported_at TEXT NOT NULL, chat_id TEXT)""", + "agent_mirror_agent_sessions": """CREATE TABLE IF NOT EXISTS agent_mirror_agent_sessions ( + session_id TEXT PRIMARY KEY, + root_request_id TEXT, created_at TEXT, updated_at TEXT, archived_at TEXT, + payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + exported_at TEXT NOT NULL)""", + "agent_mirror_history_agent_sessions": """CREATE TABLE IF NOT EXISTS agent_mirror_history_agent_sessions ( + session_id TEXT NOT NULL, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, + valid_from TEXT, valid_to TEXT NOT NULL)""", + "agent_mirror_message_token_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_message_token_stats_daily ( + day TEXT NOT NULL, grain TEXT NOT NULL, key TEXT NOT NULL, + messages INTEGER, + in_min INTEGER, in_max INTEGER, in_avg REAL, + in_p50 INTEGER, in_p90 INTEGER, in_p95 INTEGER, in_p99 INTEGER, + out_min INTEGER, out_max INTEGER, out_avg REAL, + out_p50 INTEGER, out_p90 INTEGER, out_p95 INTEGER, out_p99 INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, grain, key))""", + "agent_mirror_run_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_run_stats_daily ( + day TEXT NOT NULL, job_id TEXT NOT NULL, + runs INTEGER, succeeded INTEGER, failed INTEGER, timeout INTEGER, + cancelled INTEGER, other INTEGER, finished_runs INTEGER, + dur_min_s INTEGER, dur_max_s INTEGER, dur_avg_s REAL, + dur_p50_s INTEGER, dur_p90_s INTEGER, dur_p95_s INTEGER, dur_p99_s INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, job_id))""", + "agent_mirror_histograms_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_histograms_daily ( + day TEXT NOT NULL, grain TEXT NOT NULL, key TEXT NOT NULL, + metric TEXT NOT NULL, bucket_lo INTEGER NOT NULL, bucket_hi INTEGER, + count INTEGER, exported_at TEXT NOT NULL, + PRIMARY KEY (day, grain, key, metric, bucket_lo))""", + "agent_mirror_concurrency_hourly": """CREATE TABLE IF NOT EXISTS agent_mirror_concurrency_hourly ( + hour TEXT PRIMARY KEY, + max_concurrent_runs INTEGER, max_concurrent_sessions INTEGER, + exported_at TEXT NOT NULL)""", + "agent_mirror_distincts_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_distincts_daily ( + day TEXT NOT NULL, grain TEXT NOT NULL, key TEXT NOT NULL, + models_used INTEGER, sessions_active INTEGER, agents_active INTEGER, + chats_active INTEGER, tools_used INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, grain, key))""", + "agent_mirror_top_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_top_daily ( + day TEXT NOT NULL, kind TEXT NOT NULL, rank INTEGER NOT NULL, + ref TEXT, label TEXT, tokens INTEGER, messages INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, kind, rank))""", + "agent_mirror_tool_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_tool_stats_daily ( + day TEXT NOT NULL, tool_name TEXT NOT NULL, server_name TEXT NOT NULL, + calls INTEGER, errors INTEGER, + dur_avg_s REAL, dur_p95_s REAL, dur_max_s REAL, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, tool_name, server_name))""", + "agent_mirror_compaction_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_compaction_stats_daily ( + day TEXT NOT NULL, grain TEXT NOT NULL, key TEXT NOT NULL, + compactions INTEGER, + tokens_before_avg REAL, tokens_before_p95 INTEGER, + tokens_after_avg REAL, tokens_after_p95 INTEGER, + saved_avg REAL, exported_at TEXT NOT NULL, + PRIMARY KEY (day, grain, key))""", + "agent_mirror_subagent_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_subagent_stats_daily ( + day TEXT PRIMARY KEY, + spawns INTEGER, parents INTEGER, + children_avg REAL, children_max INTEGER, + children_p50 INTEGER, children_p90 INTEGER, children_p95 INTEGER, + children_p99 INTEGER, exported_at TEXT NOT NULL)""", + "agent_mirror_conversation_stats_daily": """CREATE TABLE IF NOT EXISTS agent_mirror_conversation_stats_daily ( + day TEXT NOT NULL, chat_id TEXT NOT NULL, + sessions INTEGER, messages INTEGER, + input_tokens INTEGER, output_tokens INTEGER, + first_activity_epoch INTEGER, last_activity_epoch INTEGER, + sess_msgs_p50 INTEGER, sess_msgs_p90 INTEGER, + sess_toks_p50 INTEGER, sess_toks_p90 INTEGER, + exported_at TEXT NOT NULL, + PRIMARY KEY (day, chat_id))""", +} + +INDEXES = [ + "CREATE INDEX IF NOT EXISTS agent_mirror_history_scheduler_jobs_key_idx ON agent_mirror_history_scheduler_jobs (job_id, valid_to)", + "CREATE INDEX IF NOT EXISTS agent_mirror_history_agent_agents_key_idx ON agent_mirror_history_agent_agents (agent_id, valid_to)", + "CREATE INDEX IF NOT EXISTS agent_mirror_history_goals_goals_key_idx ON agent_mirror_history_goals_goals (goal_id, valid_to)", + "CREATE INDEX IF NOT EXISTS agent_mirror_history_goals_updates_key_idx ON agent_mirror_history_goals_updates (update_id, valid_to)", + "CREATE INDEX IF NOT EXISTS agent_mirror_history_agent_sessions_key_idx ON agent_mirror_history_agent_sessions (session_id, valid_to)", + "CREATE INDEX IF NOT EXISTS agent_mirror_scheduler_job_runs_job_idx ON agent_mirror_scheduler_job_runs (job_id, scheduled_for_utc)", +] + + +def physical_name(spec_table): + """agent.mirror_scheduler_jobs -> agent_mirror_scheduler_jobs""" + return spec_table.replace(".", "_") + + +def ensure_tables_sql(physical_names): + out = [] + for name in physical_names: + ddl = DDL.get(name) + if ddl: + out.append((ddl, [])) + for idx in INDEXES: + if any(n in idx for n in physical_names): + out.append((idx, [])) + return out + + +def _last_line(text): + lines = [l for l in text.strip().splitlines() if l.strip()] + return lines[-1].strip() if lines else "" + + +def token_from_fleet(): + out = subprocess.run([FLEET, "secrets", "get", TOKEN_NAME], + capture_output=True, text=True, timeout=60) + if out.returncode != 0: + raise RuntimeError(f"fleet secrets get failed rc={out.returncode}") + return _last_line(out.stdout) + + +def token_from_bws(): + env = dict(os.environ) + helper = os.path.expanduser("~/tools/bws-env.sh") + script = ( + f"source {helper} >/dev/null 2>&1; " + "SID=$(bws secret list 2>/dev/null | jq -r " + f"'.[] | select(.key==\"{TOKEN_NAME}\") | .id'); " + "bws secret get \"$SID\" | jq -r .value" + ) + out = subprocess.run(["bash", "-c", script], capture_output=True, + text=True, timeout=60, env=env) + if out.returncode != 0: + raise RuntimeError(f"bws fallback failed rc={out.returncode}") + return _last_line(out.stdout) + + +def _typed(value): + if value is None: + return {"type": "null"} + if isinstance(value, bool): + return {"type": "integer", "value": str(1 if value else 0)} + if isinstance(value, int): + return {"type": "integer", "value": str(value)} + if isinstance(value, float): + return {"type": "float", "value": value} + if isinstance(value, (bytes, bytearray)): + return {"type": "blob", "base64": base64.b64encode(bytes(value)).decode()} + return {"type": "text", "value": str(value)} + + +def _plain(value): + if isinstance(value, bool): + return 1 if value else 0 + return value + + +class AuthError(RuntimeError): + pass + + +class Turso: + """Executes batches of (sql, [python values]) against fleet-mirror. + + A batch runs as one pipeline request sequence; statements in a batch + share a session (temp tables work inside a batch).""" + + def __init__(self): + self.url = os.environ.get("RDE_TURSO_URL", "") + self.file_mode = self.url.startswith("file:") + self.print_only = os.environ.get("RDE_PRINT_SQL") == "1" + self._token = None + self._token_source = None + self._conn = None + if self.file_mode: + self._conn = sqlite3.connect(self.url[5:]) + if self.print_only: + self.file_mode = False + + # -- remote ------------------------------------------------------ + def _pipeline(self, statements): + reqs = [{"type": "execute", "stmt": {"sql": sql, "args": [_typed(v) for v in args]}} + for sql, args in statements] + reqs.append({"type": "close"}) + body = json.dumps({"requests": reqs}).encode() + r = urllib.request.Request( + DB_HTTP_URL, data=body, + headers={"Authorization": f"Bearer {self._token}", + "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(r, timeout=180) as resp: + data = json.load(resp) + except urllib.error.HTTPError as e: + detail = e.read().decode()[:300] + if e.code in (401, 404) and "auth" in detail: + raise AuthError(f"HTTP {e.code}: {detail}") + raise RuntimeError(f"pipeline HTTP {e.code}: {detail}") + results = [] + for item in data.get("results", []): + if item.get("type") == "error": + raise RuntimeError(f"pipeline error: {item['error'].get('message')}") + res = item.get("response", {}).get("result") + if res is not None: + results.append(res) + return results + + def _get_token(self, source): + if source == "fleet": + return token_from_fleet() + return token_from_bws() + + # -- local file -------------------------------------------------- + def _file_exec(self, statements): + results = [] + cur = self._conn.cursor() + for sql, args in statements: + cur.execute(sql, [_plain(v) for v in args]) + if cur.description: + cols = [d[0] for d in cur.description] + rows = [{c: v for c, v in zip(cols, row)} for row in cur.fetchall()] + results.append({"cols": cols, "rows": rows}) + else: + results.append({"rows_affected": cur.rowcount}) + self._conn.commit() + return results + + # -- public ------------------------------------------------------ + def execute(self, statements): + """statements: list of (sql, args). Returns per-statement result + dicts (remote results normalized to {cols, rows} like file mode).""" + if self.print_only: + for sql, args in statements: + print("SQL>", sql, "ARGS>", json.dumps([str(a)[:60] for a in args])) + return [] + if self.file_mode: + return self._file_exec(statements) + # chunk into pipeline calls of at most 100 statements + out = [] + for i in range(0, len(statements), 100): + chunk = statements[i:i + 100] + if self._token is None: + self._token_source = "fleet" + self._token = self._get_token("fleet") + try: + raw = self._pipeline(chunk) + except AuthError: + if self._token_source == "bws": + raise + # broker value rejected: rotate to the direct BWS read + self._token_source = "bws" + self._token = self._get_token("bws") + raw = self._pipeline(chunk) + for res in raw: + cols = [c.get("name") for c in res.get("cols", [])] + rows = [] + for row in res.get("rows", []): + rows.append({c: (cell.get("value") if isinstance(cell, dict) else cell) + for c, cell in zip(cols, row)}) + out.append({"cols": cols, "rows": rows, + "rows_affected": res.get("affected_row_count")}) + return out + + def note_token_source(self): + return self._token_source + + +_CLIENT = None + + +def client(): + global _CLIENT + if _CLIENT is None: + _CLIENT = Turso() + return _CLIENT