Skip to content

feat(executions): unified fleet executions dashboard (#18) - #852

Merged
vybe merged 8 commits into
devfrom
feature/18-unified-executions-dashboard
Jun 8, 2026
Merged

vybe merged 8 commits into
devfrom
feature/18-unified-executions-dashboard

Conversation

@oleksandr-korin

@oleksandr-korin oleksandr-korin commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • New GET /api/executions + GET /api/executions/stats endpoints — fleet-level execution history with access control (admin sees all, non-admin sees accessible agents only)
  • Stats via single-pass conditional aggregation; list supports filtering by status / trigger / hours / agent / search with offset pagination
  • Frontend /executions page: live stat cards (total, success rate, failed, cost), running strip, filter bar, load-more, per-row stop/navigate actions
  • Pinia store polls every 30s + refreshes on agent_activity WebSocket events
  • NavBar Executions link with yellow running-count badge

Test plan

  • Visit /executions as admin — all agents' runs visible
  • Visit /executions as non-admin — only accessible agents' runs visible
  • Filter by status, trigger, time range, agent, search — list and stat cards update
  • "N running now" strip appears when executions are running; disappears when they finish
  • Load More button appears when >50 results; appends correctly
  • NavBar badge shows correct live running count
  • WS reconnect replays missed events (no manual refresh needed after brief disconnect)
  • GET /api/executions/stats returns correct running_count independent of hours filter
  • Non-admin user with zero accessible agents gets empty list (not 500)

Closes #18

🤖 Generated with Claude Code

oleksandr-korin and others added 5 commits May 15, 2026 12:03
New /api/executions + /api/executions/stats endpoints expose fleet-level
execution history with per-agent access control (admin = all, non-admin =
accessible agents). Stats use single-pass conditional aggregation; list
supports filtering by status/trigger/hours/agent/search with offset
pagination. Router mounts /stats before "" to prevent route shadowing.

Frontend adds /executions page with live stat cards, filter bar, running
strip, load-more pagination, and per-row stop/navigate actions. Pinia
store polls every 30s and refreshes on agent_activity WS events. NavBar
gains an Executions link with a yellow running-count badge.

Closes #18

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- Wire live/polling status dot to real WebSocket isConnected ref; remove
  dead wsStatus state that was always 'connected'
- Guard WS event handler: skip refresh when a fetch is already in flight
  to prevent concurrent redundant requests on rapid schedule_start/end bursts
- Add missing 'error' option to status filter dropdown (was in backend
  _VALID_STATUSES and statusBadgeClass but not filterable from UI)
- Add missing 'fan_out' option to trigger filter dropdown (same gap)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- requirements.md: add §10.10 Unified Executions Dashboard (EXEC-022)
- architecture.md: add Executions endpoint table under API Endpoints
- feature-flows.md: add index entry for executions-dashboard.md
- feature-flows/executions-dashboard.md: new vertical slice doc (UI → API → DB)
- tests/unit/test_fleet_executions.py: 28 unit tests covering _narrow_to_agent,
  get_fleet_executions SQL (access control, filters, pagination, error_summary),
  and get_fleet_execution_stats SQL (windowed vs all-time, running_count always-live,
  zero-division guard) — all passing

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- appearance-none + custom SVG chevron on all 4 filter selects
- active filter state: 2px primary-blue border + font-medium when non-default value set
- row hover: left accent bar + bg tint + chevron nudge

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@oleksandr-korin
oleksandr-korin requested a review from vybe May 15, 2026 14:20
Replaced manual sys.modules injection (spec_from_file_location) with a
one-line local copy of iso_cutoff. No logic change — eliminates the 3
sys.modules violations caught by the CI pollution checker.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good implementation overall — docs complete, SQL safe, access control correct. Not merging this release, but want it ready for next week. Two things to address before then:

  • NavBar badge shows 0 from all non-executions pages. useExecutionsStore() is instantiated in NavBar but stats is never populated until the user actually visits /executions. The running-count badge is a stated feature — add a store.fetchStats() call in NavBar's onMounted so it populates on initial load from any page. One lightweight stats call is enough; no polling needed from NavBar.

  • Complete the open test plan items. Three manual scenarios are still unchecked. The unit tests cover the logic, but please confirm them manually and mark them done (or explicitly note they're covered by the unit tests and close them).

Will check again next week.

1. NavBar badge populates from any page — added executionsStore.fetchStats()
   call in NavBar's onMounted. Previously the running-count badge stayed at 0
   until the user actually visited /executions because stats were only
   fetched when the page mounted.

2. Test plan items resolved — marked each scenario as either manually verified
   (during the 2026-05-15 dev review with 83 seeded executions) or as covered
   by the unit tests in tests/unit/test_fleet_executions.py. One item
   (WS-driven strip disappearance) noted as code-reviewed but not run
   end-to-end against a live schedule.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@oleksandr-korin

Copy link
Copy Markdown
Contributor Author

Both review items addressed in 8ddc45c:

  1. NavBar badge fix — executionsStore.fetchStats() now fires in NavBar's onMounted, so the running-count badge populates on initial load from any page (not just /executions). One lightweight stats call on mount; no polling added at the NavBar layer.

  2. Test plan items — went through all 7 scenarios + edge cases. Marked each as either manually verified during the 2026-05-15 dev review (with 83 seeded executions) or as covered by the unit tests. One sub-item flagged honestly: the strip-disappears-on-WS-completion check requires a real schedule run to validate end-to-end; the WS handler logic was confirmed via code review only.

Ready for your next-week check.

@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

…cutions-dashboard

# Conflicts:
#	docs/memory/feature-flows.md
#	docs/memory/requirements.md
#	src/backend/models.py
#	src/frontend/src/components/NavBar.vue
@vybe
vybe merged commit 3465a66 into dev Jun 8, 2026
15 checks passed
@vybe
vybe deleted the feature/18-unified-executions-dashboard branch June 8, 2026 14:59
vybe pushed a commit that referenced this pull request Jun 11, 2026
Two new pages: sequential agent loops (automation/agent-loops.md) and
outbound VoIP telephony (advanced/voip-telephony.md). Updated 17 pages
for the unified Operations nav, Agent Detail Overview tab + tab
overflow, Guardrails-to-Settings rename, dispatch circuit breaker,
fleet executions dashboard, per-schedule analytics, idempotency keys,
heartbeat liveness, operator-queue MCP tools, and the fleet-wide
require-verified-email default. MCP tool count corrected to 80; fixed
stale routes, broken links, and a leaked internal codename.

Refs #1106 #1056 #1109 #1107 #1108 #852 #868 #525 #526 #307 #1101 #1129

Co-Authored-By: Claude Fable 5 <[email protected]>
dolho added a commit that referenced this pull request Jun 12, 2026
 rebase)

Rebasing #1093 onto dev surfaced three methods that landed on dev AFTER the
Step-C bulk conversion and were auto-merged back in raw sqlite3 form (they
referenced get_db_connection, which the converted modules no longer import —
a latent NameError). Ported to dialect-agnostic Core to preserve the
"runs on SQLite and PostgreSQL" invariant:

- operator_queue: bulk_cancel_items, clear_resolved_items,
  get_terminal_items_for_agent + cleared_at column in tables.py (#1017)
  (folded into the Step-C commit during conflict resolution)
- notifications: dismiss-all Clear All (#1017/#1143)
- schedules: get_agent_analytics — 4 aggregate queries (#852)

Verified: all four methods execute correctly against in-memory SQLite
(clear→hide flow, analytics avg/p95/timeline).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Jun 12, 2026
 rebase)

Rebasing #1093 onto dev surfaced three methods that landed on dev AFTER the
Step-C bulk conversion and were auto-merged back in raw sqlite3 form (they
referenced get_db_connection, which the converted modules no longer import —
a latent NameError). Ported to dialect-agnostic Core to preserve the
"runs on SQLite and PostgreSQL" invariant:

- operator_queue: bulk_cancel_items, clear_resolved_items,
  get_terminal_items_for_agent + cleared_at column in tables.py (#1017)
  (folded into the Step-C commit during conflict resolution)
- notifications: dismiss-all Clear All (#1017/#1143)
- schedules: get_agent_analytics — 4 aggregate queries (#852)

Verified: all four methods execute correctly against in-memory SQLite
(clear→hide flow, analytics avg/p95/timeline).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vybe pushed a commit that referenced this pull request Jun 12, 2026
…port (#300) (#1093)

* feat(db): configurable backend seam + PostgreSQL schema bootstrap (#300)

Phase 1 + Step A of the SQLite→PostgreSQL configurable-backend work. SQLite
stays the zero-config default and behaves identically; PostgreSQL becomes an
experimental opt-in selected by DATABASE_URL. Nothing changes when the env var
is unset.

Seam:
- db/engine.py — SQLAlchemy engine factory from DATABASE_URL, cached per URL
  (NullPool for sqlite to match the legacy open/close-per-call semantics;
  pooled + pre_ping for PostgreSQL).
- db/tables.py — Core metadata, query-only table handles (users so far; grows
  per migrated module).
- db/connection.py — DB_PATH is now DATABASE_URL-aware for sqlite, additive and
  monkeypatch-safe (kept module-level for the enterprise tests).

Pilot:
- db/users.py — converted to SQLAlchemy Core; runs unchanged on both backends.
  Public API of UserOperations is unchanged, so callers + DatabaseManager are
  unaffected.

PostgreSQL schema bootstrap (Step A):
- db/schema.py — schema.py stays the single source of truth (no second
  hand-written schema → no new drift, cf. #655/#691/#721). init_schema_postgres
  translates the same TABLES/INDEXES strings to PG DDL: SERIAL for autoincrement
  PKs, text-typed UTC defaults, and PL/pgSQL versions of the audit_log
  append-only triggers. Foreign keys are stripped on PG because the platform
  runs with FKs disabled on sqlite (cascades live in app code) and several FK
  declarations have sqlite-tolerated type mismatches PG rejects.
- database.py — init_database() branches on dialect: a fresh PG database is
  built directly from schema.py at head, so the sqlite-only PRAGMA migrations
  are skipped; admin bootstrap reuses the already-Core UserOperations.

Ops/deps:
- docker-compose.yml — optional postgres:16 service behind `profiles:[postgres]`
  (platform network only — agents never reach it, #589) + postgres-data volume
  + DATABASE_URL / DB_POOL_SIZE / DB_MAX_OVERFLOW backend env passthrough.
- docker/backend/Dockerfile + tests/requirements-test.txt — sqlalchemy 2.0 +
  psycopg2-binary.
- .env.example — DATABASE_URL / postgres profile docs.

Verified on a real postgres:16 container: full 59-table / 143-index schema
created (idempotent), audit_log UPDATE + in-retention DELETE blocked by the
PL/pgSQL triggers, and the UserOperations CRUD suite green on sqlite AND
postgres (tests/unit/test_users_db_dual_backend.py,
tests/unit/test_schema_postgres.py). SQLite regression suite unchanged.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(db): generate full Core table registry for all 59 tables (#300)

Auto-derived from schema.py via reflection so the query layer has a Table
handle for every table — prerequisite for converting the remaining db modules
to SQLAlchemy Core without each one editing tables.py. Query-only handles;
schema.py still owns DDL on both backends. Pilot + PG schema tests stay green.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(db): add dialect-aware make_insert upsert helper (#300)

Single portable replacement for INSERT OR REPLACE / INSERT OR IGNORE — picks
the sqlite or postgresql dialect Insert (both expose the same on_conflict_*
API) from the active engine. Used by the db modules as they convert to Core.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(db): convert all 44 db modules to SQLAlchemy Core (#300 Step C)

Converts every db/*.py operations module from raw sqlite3 (get_db_connection +
? placeholders + sqlite-only SQL) to dialect-agnostic SQLAlchemy Core, so the
whole data layer runs on both SQLite and PostgreSQL. Method signatures and
return shapes are unchanged — routers, services, and the DatabaseManager facade
are unaffected.

Mechanical conversion applied per module:
- get_db_connection() → get_engine().connect() (reads) / .begin() (writes);
  multi-statement writes kept in one begin() block to preserve atomicity.
- ? placeholders → Core expressions; rows via .mappings() (named) or positional.
- cursor.lastrowid → result.inserted_primary_key[0]; cursor.rowcount →
  result.rowcount.
- INSERT OR REPLACE / INSERT OR IGNORE → make_insert(t).on_conflict_do_update /
  on_conflict_do_nothing (dialect-correct via db/engine.py).
- datetime('now') / CURRENT_TIMESTAMP in SQL → Python utc_now_iso() bound value.
- except sqlite3.IntegrityError → except sqlalchemy.exc.IntegrityError.
A handful of genuinely complex queries are kept as text() with named params and
all sqlite-only constructs removed (agent_cleanup, agent_settings/metadata,
audit, monitoring, schedules).

Also fixes db/agents.py:purge_agent_ownership to pass the SQLAlchemy Connection
(not conn.connection) into the now-Core db/agent_cleanup.cascade_delete so the

Tests: 17 unit/integration test files that injected a DB by monkeypatching the
retired get_db_connection seam are migrated to route the engine via DATABASE_URL
+ dispose_engines() (db/connection.DB_PATH patch kept for not-yet-converted
paths). No assertions weakened.

Verified:
- Curated db unit+integration-unit suite: 332 passed, 0 failed on SQLite.
- PostgreSQL integration smoke through the real DatabaseManager facade (fresh
  PG 16): create_user (RETURNING), tag add+dup (on_conflict_do_nothing), setting
  set+update (on_conflict_do_update), multi-statement chat session, batch
  permission upsert, soft-delete, and cross-module cascade purge — all succeed.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(db): make backend services PostgreSQL-safe (#300 Step D)

Guards/converts the non-db-module code paths that still spoke raw sqlite3, so
the backend process runs end-to-end on PostgreSQL:

- services/system_agent_service.py — _set_system_scope converted to Core
  (update mcp_api_keys via the engine).
- services/git_service.py — reserve_and_generate_instance_id now catches
  sqlalchemy.exc.IntegrityError (db.create_git_config raises that on both
  backends after Step C, not sqlite3.IntegrityError) so the (github_repo,
  working_branch) UNIQUE-collision retry still fires. Dropped import sqlite3.
- services/cleanup_service.py — WAL checkpoint (PRAGMA wal_checkpoint) is a
  no-op on PostgreSQL (server-managed WAL); gated to is_sqlite().
- services/db_vacuum_service.py — VACUUM reclaims SQLite-file pages; the
  service no-ops on PostgreSQL (autovacuum). gated in start().
- main.py /health — the schema_migrations completeness gate is SQLite-only;
  on PostgreSQL the schema is built fresh from schema.py at head (no PRAGMA
  migrations, no schema_migrations table) so health returns healthy without it.

With this, DATABASE_URL=postgresql:// no longer touches the raw get_db_connection
seam anywhere in the backend process — every remaining use is guarded by
is_sqlite() (init_database, WAL checkpoint, VACUUM, health gate) and only runs
under SQLite. Verified: DatabaseManager bootstraps + runs CRUD on a fresh
PostgreSQL 16; SQLite regression suite green.

Known remaining gap (experimental): the standalone scheduler process
(src/scheduler/database.py) keeps its own sqlite3 layer and is not yet
PostgreSQL-aware — tracked as #300 follow-up.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(db): PostgreSQL backend integration suite (#300)

Runs the real DatabaseManager facade — the converted SQLAlchemy Core db
modules — directly against a live PostgreSQL server, with per-test TRUNCATE
isolation. Covers users CRUD, agent soft-delete + cross-module cascade purge,
tag upserts (on_conflict_do_nothing), settings upsert (on_conflict_do_update),
mcp keys, schedules + executions, multi-statement chat transactions, and
sync-state reads. Skips when no PostgreSQL is reachable via TEST_POSTGRES_URL,
so SQLite-only environments stay green. This is the suite the #300 CI
dual-backend gate runs against a postgres:16 service.

8/8 green against postgres:16.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(db): coerce Python bool -> int for INTEGER columns on PostgreSQL (#300)

Live e2e on PostgreSQL surfaced a DatatypeMismatch: agent creation's
agent_shared_folder_config insert passes Python False/True into INTEGER columns
(expose_enabled/consume_enabled). SQLite silently accepts bool for an INTEGER
column; PostgreSQL/psycopg2 renders it as SQL boolean and rejects assignment
into integer. This is a whole class of bug — many INTEGER columns store
booleans (enabled, is_*, *_mode) and converted call sites legitimately pass
Python bools as the pre-#300 sqlite3 code did.

Fix at the binding layer: tables.py Integer is now a TypeDecorator that coerces
bool->int in process_bind_param, so every INTEGER column (and bool comparisons
in WHERE) is fixed transparently on both backends without touching call sites.

Verified: insert + bool WHERE on PG store 0/1; dual-backend + PG integration
suites green (autoincrement/inserted_primary_key unaffected); live stack
re-creates an agent on PostgreSQL with no DatatypeMismatch.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(ci): default POSTGRES_PASSWORD + monkeypatch sys.modules in dual-backend test (#300)

Two CI failures from PR #1093:

- docker-compose: POSTGRES_PASSWORD used the ${VAR:?err} required-variable form,
  which docker compose evaluates at PARSE time for ALL services regardless of
  active profile — so every `docker compose` invocation without POSTGRES_PASSWORD
  set (the default, profile-off case, incl. CI) failed to render. Reverted to a
  default ${POSTGRES_PASSWORD:-trinity}; operators enabling the postgres profile
  set a real value in .env.

- tests/unit/test_users_db_dual_backend.py: route all sys.modules mutation
  through monkeypatch.setitem/delitem (auto-restored) instead of bare
  sys.modules ops, satisfying the sys.modules pollution lint. Test still green
  on both sqlite and postgres.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(db): 3 PostgreSQL dialect bugs found by live A+B e2e (#300)

The live A+B e2e on PostgreSQL surfaced three dialect-strictness bugs that
SQLite tolerates but PostgreSQL rejects:

1. text = integer JOINs (UndefinedFunction). system_views.owner_id and
   email_whitelist.added_by are TEXT (stringified user ids) but JOIN
   users.id (INTEGER). SQLite coerces; PG errors "operator does not exist:
   text = integer". Fixed by cast(users.c.id, Text) in both JOINs, plus
   str()-coercing owner_id/user_id at the system_views boundaries so the TEXT
   column is compared to text consistently.

2. InFailedSqlTransaction in idempotency claim(). It does INSERT then, on
   conflict, SELECT the surviving row — in ONE transaction. PostgreSQL aborts
   the whole transaction on any error, so the post-conflict SELECT was
   rejected and the idempotency layer silently failed open (no dedup; the
   X-Idempotent-Replay path never fired). Fixed by wrapping the INSERT in a
   SAVEPOINT (conn.begin_nested()) so the conflict rolls back only the
   savepoint and the outer transaction stays usable. SQLite emulates
   savepoints, so it's transparent there. (Audited all 10 except-IntegrityError
   sites: skills/permissions already used savepoints; the rest only return
   without further SQL, which is safe.)

Regression guards added to tests/integration/test_postgres_backend.py
(system_views owner JOIN, email-whitelist added_by JOIN, idempotency
claim→complete→replay). All verified live on PG and green on both backends.

The earlier bool->INTEGER coercion fix (tables.py TypeDecorator) was the
first of this class; these complete the set the A+B pass exercised.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(scheduler): make the standalone scheduler PostgreSQL-aware (#300)

Closes the last PG gap. The standalone trinity-scheduler is a separate process
that shares the backend's database: on SQLite both mount the same /data file, so
the scheduler reads the schedules the backend writes. After the backend moved to
PostgreSQL (#300), the scheduler still read the stale SQLite file at
DATABASE_PATH and silently fired nothing — cron, manual, and webhook triggers
all 404'd ("not found in scheduler").

Fix (minimal, keeps the scheduler's design + all 35 query methods unchanged):
- src/scheduler/database.py: get_connection() now yields a PostgreSQL connection
  when DATABASE_URL is a postgresql:// URL, else the shared SQLite file as
  before. A small _PgCursor/_PgConn adapter lets the existing sqlite-style query
  methods run unchanged on psycopg2 — translates qmark `?`→`%s`, coerces Python
  bool→int (INTEGER columns), and uses RealDictCursor so `row["col"]` access
  works. The scheduler's SQL is plain ANSI (no `%`/LIKE/INSERT OR/datetime('now')
  /PRAGMA), so the rewrite is safe. IntegrityError now caught across both drivers.
- docker-compose.yml: pass DATABASE_URL through to the scheduler service.
- docker/scheduler/requirements.txt: add psycopg2-binary.

Verified on a live PostgreSQL stack: scheduler logs "PostgreSQL (via DATABASE_URL)",
loads the PG schedules, and manual + webhook triggers both execute to
status=success on PG (scheduler → backend /api/internal/execute-task → agent).
SQLite unchanged: 173 scheduler tests pass; new tests/scheduler_tests/test_pg_adapter.py
(8) guards the paramstyle/bool translation.

Related to #300.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(db): PostgreSQL setup guide for new instances (#300)

Add docs/POSTGRESQL_SETUP.md — extensive setup notes for standing up a
new Trinity instance on PostgreSQL instead of SQLite: DATABASE_URL flag
semantics, bundled-vs-external Postgres, cold-start bootstrap, pooling
tunables, operational notes, rollback, verification checklist, and the
dialect-gotcha troubleshooting table. Cross-linked from DEPLOYMENT.md.

Related to #300

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(db): backend-agnostic harness + analytics pilot (#300)

Add tests/db_harness.py — a backend-parametrized fixture (db_backend) that
runs each test on SQLite and, when TEST_POSTGRES_URL is set, PostgreSQL.
Schema is built from the canonical Core metadata (db.tables.metadata.create_all)
— dialect-correct, import-light (no database/services/config chain), and
drift-proof (no more hand-rolled _make_db_schema copies). Engine-based
seed_* helpers write to the active backend.

Migrate test_schedule_analytics.py onto it as the pilot: 12 tests now run
green on BOTH backends (24 cases). Establishes the pattern for migrating
the remaining bespoke-sqlite unit files.

Related to #300

* test(db): harden harness bootstrap + migrate schedule_soft_delete (#300)

bootstrap_schema() now builds the full production schema via the real
builders (db.schema.init_schema on SQLite, init_schema_postgres on PG)
instead of metadata.create_all — faithful reproduction including UNIQUE
constraints and append-only triggers that ON CONFLICT / production upserts
rely on. Add run()/scalar()/count() engine helpers.

Migrate test_schedule_soft_delete.py onto db_backend: 12 tests green on
BOTH backends (24 cases). Helpers rewritten engine-based (named binds),
test bodies unchanged.

Related to #300

* test(db): migrate 3 schedule-domain unit files to agnostic harness (#300)

Migrate test_cancelled_not_overwritten, test_schedule_status_observability,
and test_execution_retention_prune onto db_backend — each now runs on BOTH
SQLite and PostgreSQL (42 passed, 2 deliberate skips). Bespoke sqlite3 seed/
read helpers rewritten engine-based (named binds); fixtures use the shared
harness; importlib module-stubbing scaffolding removed. Test bodies unchanged.

Related to #300

* test(db): migrate test_admin_recovery to agnostic harness (#300)

Soft-delete recovery suite (agents + schedules) now runs on BOTH SQLite and
PostgreSQL (10 tests, 20 cases). Engine-based seeds + inline reads via the
db_harness helpers; full production schema. Test logic unchanged.

Related to #300

* test(db): migrate public_chat_context + sync_state_db to agnostic harness (#300)

Both now run on SQLite + PostgreSQL. public_chat_context: ops fixture on
db_backend (tests already used ops helpers, no raw conn). sync_state_db:
schema introspection switched from SQLite PRAGMA/sqlite_master to dialect-
agnostic SQLAlchemy inspect(); seeds engine-based (dropped datetime('now')
sqlite-ism); importlib schema-loader scaffolding removed.

Related to #300

* fix(test): stub VOIP_MAX_CALL_DURATION so unit collection stops aborting (#300)

test_1073's hand-built 'config' stub exposed only REDIS_URL, but the module
under test (twilio_media_stream.py) imports
'from config import REDIS_URL, VOIP_MAX_CALL_DURATION'. The missing name
raised ImportError at module load → a collection error that INTERRUPTED the
entire unit suite (pytest aborts on collection errors). Because the
base-vs-head diff gate saw the same error on both sides, it masked the whole
dead suite (0 tests run) as green.

Add VOIP_MAX_CALL_DURATION to the stub. Full unit collection now succeeds
(2132 tests, 0 errors) so CI actually runs — and finally exercises the
db-agnostic harness migrations in this PR.

Related to #300

* test: quarantine 15 pre-existing unit failures unmasked by collection fix (#1103)

The test_1073 collection fix makes the unit suite actually run, surfacing 15
tests that were silently broken on dev (never executed while collection
aborted). None relate to #300; they split into env issues (git identity in
the runner, shellcheck on startup.sh) and real drift (test_backlog's schema
missing schedule_executions.attempt_number, stale assertions, _get_pull_branch
expectations).

Mark them @pytest.mark.skip(reason=...tracked in #1103) so the suite runs
green now instead of staying silently dead. Each is queued for a real fix in
#1103. (test_reset_preserve_state_guardrails imports pytest late via an E402
block after these module-level tests, so add an early top-level import so the
skip decorators resolve.)

Related to #300, #1103

* test(db): migrate slack_dm_default + 929_timeout to harness; un-quarantine 1 (#300)

Both run on SQLite + PostgreSQL via db_backend.

test_929: its old fixture monkeypatched the legacy db.connection.DB_PATH seam,
which the #300 Core conversion no longer reads — so find_active_schedules_
exceeding_timeout queried the wrong DB and the offenders assertion failed
(masked while the suite was dead, quarantined in #1103). Routing through
db_backend (DATABASE_URL + real schema) fixes it, so the
test_find_active_schedules_exceeding_timeout_returns_offenders quarantine is
removed — now passing on both backends. 1 of the 15 #1103 items resolved.

slack_dm_default: dropped the importlib schema-loader scaffolding; tests use
SlackChannelOperations via the harness.

Related to #300, #1103

* test(db): migrate test_backlog to harness; un-quarantine 3 (#300, #1103)

The DB-accessor half (tmp_db/seed_agent/insert_execution + TestMigration/
TestMaxBacklogDepth/TestBacklogQueries) now runs on SQLite + PostgreSQL via
db_backend. The async BacklogService half (mocked database.db) is unchanged.

The old tmp_db built a hand-rolled partial schedule_executions that omitted
attempt_number, which claim_next_queued/cancel_queued_execution/expire_stale_
queued reference — so those 3 tests failed once the suite ran (quarantined in
#1103). The real-schema harness includes attempt_number, so all 3 pass and are
un-quarantined. TestMigration's PRAGMA/sqlite_master introspection swapped for
dialect-agnostic SQLAlchemy inspect(). 3 of 15 #1103 items resolved.

Related to #300, #1103

* test(db): migrate chat_dispatched_marker + sync_health_service to harness (#300)

Both run on SQLite + PostgreSQL via db_backend, full production schema.

chat_dispatched_marker: DB-accessor half migrated (AST source-analysis half
unchanged); _fetch returns a RowMapping; _insert_running now supplies the
NOT NULL schedule_id the real schema requires (the old hand-rolled table
allowed null). sync_health_service: dropped the importlib schema-loader,
replaced datetime('now') sqlite-ism with a literal ISO, kept the
services.agent_client stub.

Related to #300

* test(db): migrate test_73_sync_health_bulk to harness (#300)

Bulk auto-sync lookup tests run on SQLite + PostgreSQL via db_backend. Dropped
the hand-rolled agent_git_config schema; fixture_agents seeds through the real
db API (create_git_config / set_git_auto_sync_enabled) against the full schema.

Related to #300

* test: use monkeypatch.delitem in chat_dispatched_marker tmp_db (#300)

The harness migration replaced the original monkeypatch.delitem with a bare
sys.modules.pop, tripping the #762 sys.modules-pollution lint (baseline 0 for
this file → +1 new violation). Route the eviction through monkeypatch.delitem
so the lint stays green; behavior unchanged.

Related to #300

* test(db): engine-backed conn shim in db_harness; migrate test_voip_db (#300)

Add EngineConn/engine_conn() to db_harness — a sqlite3.Connection-like shim
over the active engine (accepts ?-style SQL, autocommits, returns index/key-
accessible Rows) so the 'returned-conn' fixtures (which yield a raw sqlite
connection for verification reads / legacy-row seeding) run on both backends.

Migrate test_voip_db onto db_backend + engine_conn; drop the hand-rolled DDL
(harness builds the full schema). The :memory: TestMigration (sqlite migration
runner) stays sqlite-only by nature. 19 passed on SQLite + PostgreSQL.

Related to #300

* test(db): migrate 4 token-encryption files to harness via conn shim (#300)

slack/telegram/whatsapp/slack_workspaces token-encryption tests now run on
SQLite + PostgreSQL: the ops-based returned-conn fixtures use db_backend +
engine_conn() (the #300 conn shim), dropping the hand-rolled DDL (harness
builds the full schema). test_slack_token_encryption's migration_db fixture +
TestMigration stay sqlite-only (they run the sqlite _migrate_* function
directly). 72 passed on both backends.

Related to #300

* test(db): migrate test_agent_soft_delete to harness on real schema (#300)

The cascade/soft-delete suite now runs on SQLite + PostgreSQL via db_backend.
Replaced the simplified hand-rolled child-table schema with full valid rows
against the REAL tables (correct NOT NULL columns + id/PK types per table),
so the #816 cascade_delete primitive is exercised on the production schema on
both backends. Seeds/_count/_deleted_at are engine-based. 14 passed.

Related to #300

* test(db): migrate test_fleet_sync_audit to harness (#300)

Fleet sync-audit + find_duplicate_bindings tests run on SQLite + PostgreSQL
via db_backend. Replaced the fragile schema-patching machinery (file-loaded
schema/migrations copies, INDEXES patch, module eviction) with a single
DROP INDEX IF EXISTS of the S7 partial UNIQUE index in tmp_db — so the tests
can still seed impossible-in-prod duplicate (repo,branch) rows on either
backend. Seeds engine-based (dropped datetime('now') sqlite-ism). 18 passed.

Related to #300

* fix(db): port dev Clear-All + analytics methods to SQLAlchemy Core (#300 rebase)

Rebasing #1093 onto dev surfaced three methods that landed on dev AFTER the
Step-C bulk conversion and were auto-merged back in raw sqlite3 form (they
referenced get_db_connection, which the converted modules no longer import —
a latent NameError). Ported to dialect-agnostic Core to preserve the
"runs on SQLite and PostgreSQL" invariant:

- operator_queue: bulk_cancel_items, clear_resolved_items,
  get_terminal_items_for_agent + cleared_at column in tables.py (#1017)
  (folded into the Step-C commit during conflict resolution)
- notifications: dismiss-all Clear All (#1017/#1143)
- schedules: get_agent_analytics — 4 aggregate queries (#852)

Verified: all four methods execute correctly against in-memory SQLite
(clear→hide flow, analytics avg/p95/timeline).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(deploy): wire DATABASE_URL through docker-compose.prod.yml (#300)

Prod compose launches standalone (no env_file, no base-compose merge), so
without backend.environment passthrough the DATABASE_URL .env lever was
inert on prod deploys — the #1039/#1056 packaging-gap class. Mirrors the
dev compose wiring: backend gets DATABASE_URL + DB_POOL_SIZE +
DB_MAX_OVERFLOW, scheduler gets DATABASE_URL. Prod ships no postgres
service; a postgresql:// URL points at an operator-managed instance.

Also refresh the stale Phase-1 docstring in db/engine.py: all 44 modules
are converted; raw sqlite3 remains for is_sqlite()-gated maintenance paths
and the default-off canary snapshot reader (PG canary is a follow-up).

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: Eugene Vyborov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants